feat(identity): add browser setup and user accounts

This commit is contained in:
sam committed 2026-10-16 02:41:24 +11:00
1 parent cf3455ef2e
commit aa012a7c6e
91 files changed
+6823 -636

No files matched your search

-2
View File
@@ -27,8 +27,6 @@ func run() int {
flag.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory (only [services.*] targets and [web] are read)")
flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory")
flag.StringVar(&options.Listen, "listen", "", "dashboard HTTP listen address (defaults to [web].listen, else 127.0.0.1:8484)")
flag.StringVar(&options.Token, "token", "", "dashboard token; required for a non-loopback listener")
flag.StringVar(&options.TokenFile, "token-file", "", "file holding the dashboard token, minted on first use")
flag.StringVar(&options.OidcIssuer, "oidc-issuer", "", "identity provider issuer URL; requests must then carry a token it signed")
flag.StringVar(&options.OidcAudience, "oidc-audience", "", "audience (resource identifier) this dashboard accepts tokens for; required with -oidc-issuer")
flag.StringVar(&options.OidcClientID, "oidc-client-id", "", "provider client id for browser sign-in; omitted means no sign-in flow")
+3 -4
View File
@@ -55,10 +55,9 @@ as a host binary. Pull it from GHCR: `ghcr.io/samcharles93/archie-agent`.
./archied -config ~/.config/archie/config.toml
```
Dashboard reachability comes from `[web].listen` (default
`127.0.0.1:8484`, which needs no dashboard token). For a non-loopback
bind pass `-listen` with `-token` or `-token-file` to mint and persist
one.
Open `[web].listen` (default `127.0.0.1:8484`) to configure the organisation,
workspace and first administrator account. Remote access requires an HTTPS
reverse proxy. Complete setup before exposing the dashboard publicly.
4. For a persistent, 24/7 deployment instead of a foreground run, follow the
systemd user-unit runbook:
+2 -2
View File
@@ -69,8 +69,8 @@ default). Start it after the Gateway and the State Store:
archie-ui -config ~/.config/archie/config.toml
```
A non-loopback `[web].listen` requires a dashboard token (`-token`, or
`-token-file` to mint and persist one); a loopback bind needs none.
Open the dashboard to configure the organisation, workspace and first administrator account.
Use HTTPS through a reverse proxy for remote access, and complete setup before exposing it publicly.
`archied` runs no dashboard listener at all, so webhook capture
(`POST /webhooks/capture/{source}`) is received by archie-ui and the
binding-dispatch loop in `archied` consumes what arrives from the shared
+6 -8
View File
@@ -50,28 +50,26 @@ each service waits for the peers it needs.
The dashboard is served by the standalone UI Service, not by `archied`. It reads the same `config.toml`, dials
the Gateway and State Store targets already in it, and binds `[web].listen`.
A non-loopback bind requires a dashboard token (`-token`, or `-token-file` to
mint and persist one);
Open the dashboard to configure the organisation, workspace and first administrator account.
Complete setup before exposing it publicly; remote access requires an HTTPS reverse proxy.
**Auth note:** `archie-ui` authenticates to the Gateway, State Store and
harness with its `[tls]` certificate (`archie-ui.pem`) from `config.toml`.
For supervision, `GET /healthz` on `[web].listen` is the process's liveness
probe (token-free by design); the authenticated readiness surface lives at
the dashboard's health endpoint behind the token. A watchdog can curl
the dashboard's health endpoint behind account authentication. A watchdog can curl
`/healthz` without credentials.
`install.sh` writes `archie-ui.service`. The dashboard token comes from
`-token-file` (there is no environment variable for it).
`install.sh` writes `archie-ui.service`. Browser accounts are configured through the dashboard.
`After=` orders the start, it does not wait for the store to bind. The UI
process closes that gap itself: its event pump retries priming with backoff
until the State Store answers, so the activity feed goes live once the store
is up rather than staying history-only until the next restart.
For a non-loopback bind, override the installed unit's `ExecStart` with
`-token-file %h/.local/share/archie/web-token` (or `-token`) in a drop-in rather
than editing the installer's copy in place.
For remote access, configure a TLS reverse proxy and the instance public URL in
Settings → Authentication. Enrol passkeys from Your account on HTTPS or localhost.
---
+239
View File
@@ -0,0 +1,239 @@
# User authorization boundaries
Archie separates authentication (which person or service is calling) from
permission to act on a resource. This inventory follows the [OWASP
Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
and [Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html),
including its guidance on attributes and relationships. It describes concrete
enforcement points and their regression tests; it is not a compliance certification.
## Transport and authority
The browser uses HTTP/JSON and SSE to the UI service. The UI service calls
State Store, Gateway, Messaging and Harness through their gRPC contracts.
Only the State Store opens the task/control-plane/account database; Gateway
owns conversation storage. Browser HTTP handlers never open either database.
Instance service credentials are administrative authority. They are not user
sessions and must never reach a browser, model, or agent container. A service
forwarding a principal preserves attribution and tenant scope; forwarding alone
does not mean every internal RPC evaluates Cedar. Most internal RPCs trust the
authenticated service and enforce their own resource scope. The public HTTP
boundary evaluates Cedar before invoking them. Task credentials have a separate,
explicit RPC allowlist and cannot call account or identity administration.
Local service listeners are trusted process boundaries. Loopback is not a
substitute for authentication on a remotely reachable listener. OIDC credentials,
local browser sessions, personal API tokens, service credentials, and task grants
must remain distinct.
## Policy and relationship model
`internal/domain/access` defines actions, resources, principals and memberships.
`internal/infrastructure/access` assembles Cedar entities and evaluates the
instance → organization → workspace → object chain. A forbid wins; each applicable
level must permit the operation. Missing or invalid policy chains fail closed.
The default policies grant actions through scoped roles. Policies can also
restrict a named identity, workspace environment, owner, state, source address,
signature, run or step. HTTP task decisions now include the stored initiating identity and task state; binding decisions include the stored binding state. The HTTP source address is the actual connection peer, not an unverified forwarded header. Membership and resource attributes must come from stored
records or authenticated context, never a request's assertion about itself.
Cedar permission is not ownership of another person's private data. Conversation
history, passkeys, recovery codes and personal tokens are bound to the person.
An organization or instance admin role does not override those relationships.
Account creation uses `manage_members` policy rather than a hard-coded admin
role. Authenticating through OIDC does not automatically grant membership, link
accounts by unverified email, or create an administrator.
## Enforcement inventory
| Location | Enforcement | Regression evidence |
| --- | --- | --- |
| Browser credential gate: `webui/auth.go`, `accounts.go` | Account session or verified provider identity; shared dashboard token is not a person when accounts are enabled. No API data before authentication. | `TestAccountBoundary`, `TestAccountSessionFailureIsClosed` |
| Browser policy gate: `webui/authorize.go` | Resolve principal from stored identity; evaluate action against stored org/workspace and resource kind before handler. Missing chain refuses. | `TestHTTPPolicyCannotBeBypassed`, `TestAuthorizeRefusesWithoutAChain`, `TestAuthorizeRecord`, `TestTaskAuthorizationUsesStoredAttributes`, `TestAuthorizeCreateIn` |
| Instance-only HTTP surfaces: `webui/instance_only.go`, server route registration | Hide instance-owned configuration and diagnostics from another org; policy still applies first. | `TestInstanceOnlyHidesTheInstanceFromOtherOrgs`, `TestInstanceAdminOrgs` |
| First setup: `webui/accounts.go`, `postgres/accounts.go` | Initial organization, workspace, instance URL, admin identity and password commit together. Transaction lock closes bootstrap after first account; later requests require `manage_members`. | Disposable PostgreSQL smoke verification for bootstrap race and rollback; account policy tests below |
| Account creation: `webui/accounts.go`, `staterpc/accounts.go`, `postgres/accounts.go` | Cedar `manage_members` at HTTP and RPC; target org is authenticated context. New local accounts cannot request owner role. | `TestAccountManagementUsesPolicy`, `TestAccountBoundary` |
| Local passwords and sessions: `identity/password.go`, `postgres/accounts.go` | Argon2id, independent salts, length/common-password checks, generic login refusal, account throttling, session hashes and expiry, revocation on logout/password change/suspension. | `TestPasswordVerification`, `TestAccountBoundary`; disposable PostgreSQL session verification |
| Transport and CSRF: `webui/accounts.go`, `api_tasks.go` | Password/account mutations require HTTPS or localhost development, JSON, custom CSRF header and same-origin requests. Forwarded headers require explicit trusted-proxy configuration. | `TestAuthenticationTransport`, existing mutation security tests |
| Personal account routes: `webui/accounts.go` | Active signed-in person; principal supplied by server. Password change verifies current password. Sensitive authenticator changes require recent sign-in. No caller-supplied target identity. | `TestAccountBoundary` |
| Recovery: `postgres/account_security.go`, `webui/accounts.go` | Fresh authenticated owner generates a hashed, one-use recovery secret. Redemption replaces password and revokes all sessions atomically. No email-existence disclosure. | Disposable PostgreSQL recovery verification |
| Passkeys: `postgres/passkeys.go`, `webui/passkeys.go` | Configured RP origin, browser-bound one-use expiring challenge, verified credential signature and user verification. Enrollment/management belong to caller. Credential counters persist under a row lock. | Disposable browser virtual-authenticator verification; task-grant denial tests |
| OIDC: `infrastructure/oidc`, `archieui/account_oidc.go`, `webui/auth.go` | Discovery and signed ID token with issuer/client audience/expiry, PKCE, state and nonce. Verified subject resolves to active identity. Browser-local session cannot outlive provider token, and provider credential remains checked. | `TestBrowserFlowVerifiesIDToken`, `TestProviderOutageIsUnavailableThenRecovers`, subject-claim tests; no external provider acceptance implied |
| OIDC settings: `webui/accounts.go`, `postgres/authentication.go` | Instance ownership plus policy; recent sign-in for changes. Public URL cannot change while enrolled passkeys would be orphaned. | `TestAccountBoundary`, `TestAuthenticationSettingsRejectUntrustedOrigins` |
| Org membership/workspaces/agent assignment: `webui/api_orgs.go`, `staterpc/orgs.go`, `postgres/orgs.go` | Own org or instance-owner relationship, allowed role vocabulary, membership escalation/last-owner guards, tenant-scoped SQL. | `TestOrgRPCsActInTheCallersOrg`, `TestSetMembershipRefusesUnknownRole`, org HTTP tests |
| Personal API tokens: `webui/api_personal_tokens.go`, `staterpc/personal_tokens.go`, `postgres/personal_tokens.go` | Token owner comes from principal; store only token hash; revoke only caller's binding. | `TestPersonalTokensWithoutPerson`, `TestPersonalTokenOwner` |
| gRPC caller attribution: `rpcidentity/identity.go` | Authenticated service may forward a principal; State Store resolves memberships/org itself. Task grant metadata is stripped. | `TestCallerAttribution` |
| Agent/task gRPC: `staterpc/task_grants.go` | Durable task-scoped grant, explicit allowed RPC and target task, no definition-pin replacement, no account RPCs. | `TestTaskCredentialsCannotManageAccounts`, `TestTaskCredentialCannotReplaceItsPin`, `TestRecordUsageAuthority`, `TestWorkerPresenceAuthority` |
| Chat HTTP: `webui/api_chat.go` | Server stamps sender and person thread; lists/read/turns/cancel/persona verify session ownership. Browser cannot submit another sender identity. | `TestWebChatOwnership`, `TestWebChatSenderCannotBeSuppliedByBrowser`; HTTP deny matrix |
| Chat history, slash commands and model session tools: `gateway/session_store_postgres.go` | Store filters `Get`, `List`, `GetByChannel`; shared read/write guards check person ownership as well as org. A saved session cannot change its conversation source to claim another person's history. Service curation runs without a person principal. | `TestSessionVisibility`; PostgreSQL smoke for history isolation |
| Chat questions/approvals: `webui/api_chat_ask.go` | Waiting question is bound to the initiating person, in addition to its unguessable ID. | `TestChatQuestionBelongsToInitiatingPerson` |
| Chat downloads: `webui/api_chat_files.go` | Offered file token expires and is bound to the initiating person; requests cannot supply a filesystem path. | `TestChatFileDownload` |
| Per-person memory: `archiegateway/chat_identity.go`, gateway memory tools, `sessioncurator` | Verified web sender identity scopes reads/writes. Curator refuses unidentified or mixed participants instead of guessing a person. | Gateway memory and session-curator tests |
| Workflow/task actions: `webui/api_tasks.go`, `domain/taskactions`, `staterpc` | Policy and stored workspace before action; domain transition, authority and durable dispatch guards remain in force. | HTTP deny matrix, task action/domain tests, task grant tests |
| Incoming webhooks: `forge/webhook`, `captureintake`, access delivery engine | Verify HMAC before parsing; derive source/org from stored source; evaluate source delivery policies and egress rules. No browser-user credential is inferred. | Webhook/capture tests, `TestAuthorizeDelivery` |
| Control-plane configuration, secrets, harness and extensions | Browser policy and instance-only restrictions where registered; service contracts carry principal/org; task grants cannot invoke administrative RPCs. | HTTP deny matrix, `TestAdministrationRoutes`, `TestChannelReloadRoute`, `TestConfineHarnessOrg` |
| Live HTTP/SSE and diagnostics | Authenticated policy gate applies before stream creation; org-scoped event reads; instance logs require administrative visibility. | HTTP deny matrix, instance-only tests, `TestServiceLogsRequireInstanceCredential` |
| Background schedules, dispatch, curation | Service/agent authority, not an implicit browser user. Task-scoped grants and org scopes remain distinct from initiating human attribution. | Existing dispatch, grant, memory and org-scope tests |
The policy HTTP matrix enumerates each registered protected route. It checks
both anonymous refusal and refusal by an explicit Cedar forbid, using the real
handler stack. Separate tests exercise allowed requests and personal ownership;
a denied-request matrix alone is not proof that a workflow works end to end.
## Public and personal routes
Public protocol entry points are `GET /api/auth/status`, `POST /api/auth/setup`,
`POST /api/auth/login`, `POST /api/auth/logout`, `POST /api/auth/recover`,
`POST /api/auth/passkey/begin`, `POST /api/auth/passkey/finish`,
`GET /oauth2/login`, `GET /oauth2/callback`, health probes and signed webhook
intake. Each has its own protocol checks. Static embedded app assets are public;
they do not contain user data. `/health/detailed` remains protected.
Personal routes under `/api/account/` require an active signed-in person and
server-derived ownership: password change, recovery-secret generation, passkey
begin/finish/list/delete. They do not require an organization administrator role.
`POST /api/accounts` and `/api/authentication` are administrative policy routes.
## HTTP route inventory
The following routes are covered by `TestHTTPPolicyCannotBeBypassed` in
`internal/webui/authorization_surfaces_test.go`. `authorize.go` maps each to its
action/resource; the handler may impose a stricter record or instance boundary.
| Method | Route example |
| --- | --- |
| DELETE | `/api/access/policies` |
| DELETE | `/api/bindings/7` |
| DELETE | `/api/event-types/7` |
| DELETE | `/api/extensions/sample` |
| DELETE | `/api/mappings/7` |
| DELETE | `/api/orgs/7/members/sample` |
| DELETE | `/api/sources/sample` |
| DELETE | `/api/tokens/7` |
| GET | `/api/access/policies` |
| GET | `/api/alerts` |
| GET | `/api/authentication` |
| GET | `/api/bindings` |
| GET | `/api/bindings/7` |
| GET | `/api/bindings/7/dispatches` |
| GET | `/api/capabilities` |
| GET | `/api/captures` |
| GET | `/api/captures/7/dispatches` |
| GET | `/api/channels` |
| GET | `/api/chat/file/sample` |
| GET | `/api/chat/sessions` |
| GET | `/api/chat/sessions/7/messages` |
| GET | `/api/chat/sessions/7/turns` |
| GET | `/api/chat/update` |
| GET | `/api/config` |
| GET | `/api/control-plane/apply-status` |
| GET | `/api/control-plane/audit` |
| GET | `/api/control-plane/catalog` |
| GET | `/api/control-plane/resources/sample` |
| GET | `/api/control-plane/resources/sample/history` |
| GET | `/api/curators` |
| GET | `/api/event-types` |
| GET | `/api/extensions` |
| GET | `/api/extensions/catalogue` |
| GET | `/api/harness/bindings` |
| GET | `/api/harness/terminal` |
| GET | `/api/identities` |
| GET | `/api/logs` |
| GET | `/api/mappings` |
| GET | `/api/mappings/7` |
| GET | `/api/orgs` |
| GET | `/api/orgs/7` |
| GET | `/api/orgs/7/members` |
| GET | `/api/orgs/7/workspaces` |
| GET | `/api/secret-engines` |
| GET | `/api/services` |
| GET | `/api/setup` |
| GET | `/api/skills` |
| GET | `/api/sources` |
| GET | `/api/stream` |
| GET | `/api/summary` |
| GET | `/api/task-meta` |
| GET | `/api/tasks` |
| GET | `/api/tasks/7` |
| GET | `/api/tasks/7/attempts` |
| GET | `/api/tasks/7/changes` |
| GET | `/api/tasks/7/debug` |
| GET | `/api/tasks/7/dispatches` |
| GET | `/api/tasks/7/logs` |
| GET | `/api/tasks/7/logs/download` |
| GET | `/api/tasks/7/sandbox` |
| GET | `/api/tokens` |
| GET | `/api/version` |
| GET | `/api/workflows` |
| PATCH | `/api/bindings/7` |
| PATCH | `/api/mappings/7` |
| POST | `/api/accounts` |
| POST | `/api/alerts/7/dismiss` |
| POST | `/api/bindings` |
| POST | `/api/bindings/7/approve` |
| POST | `/api/bindings/7/pause` |
| POST | `/api/bindings/7/resume` |
| POST | `/api/channels/7/reload` |
| POST | `/api/chat/answer` |
| POST | `/api/chat/cancel` |
| POST | `/api/chat/message` |
| POST | `/api/chat/persona` |
| POST | `/api/chat/stream` |
| POST | `/api/chat/update/defer` |
| POST | `/api/chat/update/install` |
| POST | `/api/control-plane/resources/sample/commands/sample` |
| POST | `/api/event-types` |
| POST | `/api/extensions` |
| POST | `/api/extensions/catalogue/sample/install` |
| POST | `/api/extensions/sample/accept` |
| POST | `/api/extensions/sample/approve-update` |
| POST | `/api/extensions/sample/rollback` |
| POST | `/api/extensions/sample/update` |
| POST | `/api/identities` |
| POST | `/api/identities/7/sample` |
| POST | `/api/mappings` |
| POST | `/api/mappings/preview` |
| POST | `/api/orgs` |
| POST | `/api/orgs/7/members` |
| POST | `/api/orgs/7/workspaces` |
| POST | `/api/secret-references/check` |
| POST | `/api/sources` |
| POST | `/api/sources/sample/approve-unsigned` |
| POST | `/api/sources/sample/secret` |
| POST | `/api/sources/sample/signing` |
| POST | `/api/tasks/7/action` |
| POST | `/api/tokens` |
| POST | `/api/work-requests` |
| PUT | `/api/access/policies` |
| PUT | `/api/authentication` |
| PUT | `/api/event-types/7` |
| PUT | `/api/extensions/sample/enabled` |
| PUT | `/api/extensions/sample/update-policy` |
| PUT | `/api/orgs/7/agents/sample` |
| PUT | `/api/orgs/7/members/sample` |
| PUT | `/api/sources/sample/delivery-header` |
| PUT | `/api/sources/sample/name` |
| PUT | `/api/workflows/7/enabled` |
## Verification limits
A synthetic browser authenticator verifies protocol behavior, not a physical
security key or every operating system. An OIDC unit test is not acceptance
against a deployed provider. Disposable PostgreSQL smoke checks verify real SQL
without putting database-dependent tests in the fast unit suite.
Existing anonymous conversations are retained but are not silently assigned to
a new person. Existing service credentials remain privileged; this inventory
does not claim that all internal gRPC methods have independent Cedar gates.
When changing a user-facing operation, update its inventory entry and its
allow/deny behavior cases. Include another user in the same organization, a
caller in another organization, a missing principal, unavailable policy storage,
and the applicable owner/workspace/instance restrictions.
Bootstrap is unauthenticated until the first administrator is created. Complete
setup before exposing a new installation to untrusted users. Last-active-owner
protection for identity suspension/retirement is tracked separately as
`archie-core-d7avc`; membership-policy guards are not that lifecycle guard.
+10 -2
View File
@@ -19,11 +19,13 @@ require (
github.com/emirpasic/gods v1.18.1 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/fxamacker/cbor/v2 v2.9.4 // indirect
github.com/go-git/gcfg/v2 v2.0.2 // indirect
github.com/go-jose/go-jose/v4 v4.1.5 // indirect
github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/go-webauthn/x v0.3.1 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/go-tpm v0.9.8 // indirect
github.com/hashicorp/yamux v0.1.2 // indirect
@@ -41,6 +43,7 @@ require (
github.com/nats-io/nkeys v0.4.16 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/oklog/run v1.2.0 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pjbgf/sha1cd v0.7.0 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/segmentio/asm v1.2.1 // indirect
@@ -48,6 +51,8 @@ require (
github.com/sergi/go-diff v1.4.0 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/sirupsen/logrus v1.10.2 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
@@ -57,7 +62,6 @@ require (
go.opentelemetry.io/otel/trace v1.47.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/exp v0.0.0-20261013213113-2ab7f3cbc5fb // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/text v0.43.0 // indirect
@@ -75,7 +79,10 @@ require (
github.com/docker/sandbox-kit-spec/v3 v3.0.0-m.8
github.com/go-git/go-billy/v6 v6.0.0-beta.1
github.com/go-git/go-git/v6 v6.0.0-beta.1
github.com/go-jose/go-jose/v4 v4.1.5
github.com/go-telegram/bot v1.27.0
github.com/go-webauthn/webauthn v0.18.2
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/jsonschema-go v0.4.3
github.com/google/uuid v1.6.0
github.com/hashicorp/go-hclog v1.6.3
@@ -93,6 +100,7 @@ require (
go.lsp.dev/jsonrpc2 v1.0.1
go.lsp.dev/protocol v1.0.1
go.lsp.dev/uri v1.0.1
golang.org/x/crypto v0.58.0
golang.org/x/mod v0.42.0
golang.org/x/net v0.61.0
golang.org/x/oauth2 v0.37.0
+18
View File
@@ -53,6 +53,8 @@ github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo=
github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=
@@ -74,6 +76,12 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-telegram/bot v1.27.0 h1:PG9yBDzM8O26oUerE9SZwWlHon4RpH8WcNslZ7CEZmE=
github.com/go-telegram/bot v1.27.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-webauthn/webauthn v0.18.2 h1:0BeftmEHU7i3Dv0VFwBtidy/ba37Vcdjvqst9EYu8Sk=
github.com/go-webauthn/webauthn v0.18.2/go.mod h1:hEXaOuLxvZ3zG9miZe3ehlyeVso9AtklXG+kTn36k+A=
github.com/go-webauthn/x v0.3.1 h1:1ff37z3XfmTTomkhlURgGizLIDyOvPgTt2t9nlzKLRo=
github.com/go-webauthn/x v0.3.1/go.mod h1:ZInxAynYXfBPvvm5gzKZ7geBlL23K71xASMgohHl/Rg=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
@@ -82,6 +90,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -151,6 +161,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pjbgf/sha1cd v0.7.0 h1:ZRNPKHj+gfkLBf0KJv/p1Hmz+7bqCT5o311YX0nq+DA=
github.com/pjbgf/sha1cd v0.7.0/go.mod h1:pKR5Li+qTCo+ebqITZfwPlJGoCFCvSO00qxjbNtTUFQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
@@ -181,6 +193,10 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
go.lsp.dev/jsonrpc2 v1.0.1 h1:JZAchpm6RcOuwEOnZ7kF3kA1EpEjdJZ/6rMSfOF3+F4=
@@ -205,6 +221,8 @@ go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
+3 -6
View File
@@ -7,17 +7,14 @@ import (
// carriesPersonIdentity reports whether a platform's SenderID names a person.
//
// Telegram and email carry a native per-person sender id (a Telegram numeric
// user id, an SMTP from address). The dashboard ("web") has one bearer token,
// not users. Treating a shared token as an identity
// would give it the same standing as a real user, which the read path's
// isolation guarantee depends on never happening.
// Web sender IDs are supplied by the authenticated UI service.
// Telegram and email carry native person identifiers.
//
// An unknown platform fails closed, so a channel added later gets global and
// agent scopes only until someone decides deliberately that it carries people.
func carriesPersonIdentity(platform string) bool {
switch platform {
case "telegram", "email":
case "telegram", "email", "web":
return true
default:
return false
+91
View File
@@ -0,0 +1,91 @@
package archieui
import (
"context"
"sync"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/infrastructure/oidc"
)
// accountOIDC reloads browser-managed provider settings without restarting UI.
// The provider retains its discovery and signing-key cache until settings change.
type accountOIDC struct {
fallbackFlow identity.LoginFlow
fallbackProvider *oidc.Provider
settings identity.AuthenticationSettingsStore
subjects identity.SubjectResolver
fallback identity.AuthenticationSettings
mu sync.Mutex
current identity.AuthenticationSettings
provider *oidc.Provider
}
func (a *accountOIDC) flow(ctx context.Context) (identity.LoginFlow, *oidc.Verifier, error) {
settings, err := a.settings.AuthenticationSettings(ctx)
if err != nil {
return nil, nil, err
}
if settings.PublicURL == "" {
settings = a.fallback
if a.fallbackFlow != nil {
return a.fallbackFlow, oidc.NewVerifierForAudience(a.fallbackProvider, a.fallback.OIDCClientID), nil
}
}
if settings.OIDCIssuer == "" {
return nil, nil, identity.ErrNoCredential
}
a.mu.Lock()
defer a.mu.Unlock()
if a.provider == nil || a.current != settings {
provider, err := oidc.NewProvider(oidc.Config{Issuer: settings.OIDCIssuer, Audience: settings.OIDCAudience})
if err != nil {
return nil, nil, err
}
a.provider, a.current = provider, settings
}
flow, err := oidc.NewFlow(a.provider, settings.OIDCClientID, "", settings.PublicURL+"/oauth2/callback")
return flow, oidc.NewVerifierForAudience(a.provider, settings.OIDCClientID), err
}
func (a *accountOIDC) AuthenticateBrowser(ctx context.Context, credential string) (identity.Identity, error) {
_, verifier, err := a.flow(ctx)
if err != nil {
return identity.Identity{}, err
}
value, _, err := identity.Authenticate(ctx, a.subjects, verifier, credential)
return value, err
}
func (a *accountOIDC) AuthCodeURL(ctx context.Context, state string) (string, string, error) {
flow, _, err := a.flow(ctx)
if err != nil {
return "", "", err
}
return flow.AuthCodeURL(ctx, state)
}
func (a *accountOIDC) Exchange(ctx context.Context, code, verifier string) (identity.ProviderSession, error) {
flow, _, err := a.flow(ctx)
if err != nil {
return identity.ProviderSession{}, err
}
return flow.Exchange(ctx, code, verifier)
}
func (a *accountOIDC) Authenticate(ctx context.Context, credential string) (identity.Identity, error) {
if subject, ok := identity.PersonalTokenSubject(credential); ok {
return identity.Resolve(ctx, a.subjects, identity.Credential{Subject: subject})
}
if _, _, err := a.flow(ctx); err != nil {
return identity.Identity{}, err
}
a.mu.Lock()
provider := a.provider
if provider == nil {
provider = a.fallbackProvider
}
a.mu.Unlock()
value, _, err := identity.Authenticate(ctx, a.subjects, oidc.NewVerifier(provider), credential)
return value, err
}
-21
View File
@@ -1,8 +1,6 @@
package archieui
import (
"context"
"log/slog"
"os"
"strings"
@@ -20,25 +18,6 @@ func signInProvider(opts Options) (*oidc.Provider, error) {
return oidc.NewProvider(oidc.Config{Issuer: opts.OidcIssuer, Audience: opts.OidcAudience})
}
// dashboardAuthenticator builds the credential check, or nil when no provider
// is configured.
func dashboardAuthenticator(provider *oidc.Provider, opts Options, subjects identity.SubjectResolver, log *slog.Logger) func(context.Context, string) (identity.Identity, error) {
if provider == nil {
return nil
}
verifier := oidc.NewVerifier(provider)
log.Info("dashboard authenticates provider credentials", "issuer", opts.OidcIssuer, "audience", opts.OidcAudience)
return func(ctx context.Context, credential string) (identity.Identity, error) {
// A personal token is bound in the State Store, not issued by the
// provider, so it resolves without the provider's verifier.
if subject, ok := identity.PersonalTokenSubject(credential); ok {
return identity.Resolve(ctx, subjects, identity.Credential{Subject: subject})
}
value, _, err := identity.Authenticate(ctx, subjects, verifier, credential)
return value, err
}
}
// dashboardLoginFlow builds the browser sign-in flow, or nil when not
// configured. The client secret is read from the named env var.
func dashboardLoginFlow(provider *oidc.Provider, opts Options) (identity.LoginFlow, error) {
+6 -2
View File
@@ -38,7 +38,8 @@ type deps struct {
Identities identity.Repository
// Authenticate resolves a presented credential to the identity that may
// act. Nil when no provider is configured, which keeps the shared token.
Authenticate func(context.Context, string) (identity.Identity, error)
Authenticate func(context.Context, string) (identity.Identity, error)
AuthenticateBrowser func(context.Context, string) (identity.Identity, error)
// Login drives the browser sign-in flow, or nil when no provider is
// configured for it.
Login identity.LoginFlow
@@ -56,8 +57,8 @@ func compose(ctx context.Context, d deps) *webui.Server {
srv := &webui.Server{
Store: d.Store,
Log: d.Log,
Token: d.Options.Token,
Authenticate: d.Authenticate,
AuthenticateBrowser: d.AuthenticateBrowser,
Login: d.Login,
TrustForwardedHeaders: d.Options.trustForwardedHeaders(),
Health: d.Health,
@@ -134,6 +135,9 @@ func compose(ctx context.Context, d deps) *webui.Server {
// wireOrgSurface attaches the dashboard's org surface when the state client
// carries it.
func wireOrgSurface(srv *webui.Server, store storecontract.TaskStore) {
if accounts, ok := store.(identity.Accounts); ok {
srv.Accounts = accounts
}
if orgs, ok := store.(org.API); ok {
srv.Orgs = orgs
}
+2 -25
View File
@@ -34,11 +34,6 @@ func Resolve(o Options, log *slog.Logger) (Options, error) {
return Options{}, err
}
o.identity = id
token, err := resolveToken(o)
if err != nil {
return Options{}, err
}
o.Token = token
if err := o.validate(); err != nil {
return Options{}, err
}
@@ -146,20 +141,7 @@ func withDefaults(o Options) Options {
return o
}
// resolveToken returns the dashboard token, minting and persisting one when
// the operator named a token file and gave no token directly. Naming the file
// is how a non-loopback listener opts in to a generated token instead of
// being refused.
func resolveToken(o Options) (string, error) {
if o.Token != "" || o.TokenFile == "" {
return o.Token, nil
}
return webui.LoadOrCreateToken(o.TokenFile)
}
// Unlike the daemon, which mints a token silently, this process refuses to
// start -- an operator who exposed the dashboard by accident learns about it
// here rather than from the log.
// Browser access is gated by accounts; service endpoints must still be configured.
func (o Options) validate() error {
if o.Gateway.Target == "" {
return fmt.Errorf("gateway target is required (-gateway-target or [services.gateway].target)")
@@ -167,12 +149,7 @@ func (o Options) validate() error {
if o.State.Target == "" {
return fmt.Errorf("state store target is required (-state-target or [services.state].target)")
}
if !webui.IsLoopback(o.Listen) && o.Token == "" {
return fmt.Errorf(
"ui listen address %q is non-loopback; a reachable dashboard requires a token (-token) or a token file to mint one (-token-file) (deployments/README.md, running the dashboard)",
o.Listen,
)
}
return nil
}
+2 -9
View File
@@ -37,15 +37,8 @@ type Options struct {
// Listen is the dashboard HTTP bind address.
Listen string
// Token gates browser access. Empty is permitted only for a loopback
// listener; see Options.validate.
Token string
// TokenFile is where the dashboard token is persisted, minted on first
// use. It is the explicit opt-in to a non-loopback listener: without it
// a reachable bind must be given a token.
TokenFile string
// OidcIssuer and OidcAudience configure the identity provider. Both empty
// keeps the shared token; an issuer without an audience is refused.
// OidcIssuer and OidcAudience configure the identity provider. Local accounts remain available;
// an issuer without an audience is refused.
OidcIssuer string
OidcAudience string
// OidcClientID and OidcClientSecretEnv register the browser sign-in; the
+18 -19
View File
@@ -10,11 +10,13 @@ import (
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/app/servicekit"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/presence"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
@@ -73,25 +75,27 @@ func Run(ctx context.Context, options Options) error {
if err != nil {
return err
}
authenticate := dashboardAuthenticator(provider, opts, tasks, log)
login, err := dashboardLoginFlow(provider, opts)
if err != nil {
return err
}
runtimeOIDC := &accountOIDC{settings: tasks, subjects: tasks, fallbackFlow: login, fallbackProvider: provider, fallback: identity.AuthenticationSettings{PublicURL: strings.TrimSuffix(opts.OidcRedirectURL, "/oauth2/callback"), OIDCIssuer: opts.OidcIssuer, OIDCAudience: opts.OidcAudience, OIDCClientID: opts.OidcClientID}}
srv := compose(ctx, deps{
Options: opts,
Log: log,
Store: tasks,
Chat: chat,
Updates: controlplanerpc.UpdateService(controlplanerpc.NewRPCClient(tasks.ControlPlane()), filepath.Join(configuration.DefaultWorkDir(), "ui-update-deferrals.json")),
Health: newReadinessRegistry(opts, tasks, chat, chain, provider),
ControlPlane: tasks.ControlPlane(),
Identities: tasks,
Authenticate: authenticate,
Login: login,
Access: chain,
Principals: tasks,
Denials: tasks,
Options: opts,
Log: log,
Store: tasks,
Chat: chat,
Updates: controlplanerpc.UpdateService(controlplanerpc.NewRPCClient(tasks.ControlPlane()), filepath.Join(configuration.DefaultWorkDir(), "ui-update-deferrals.json")),
Health: newReadinessRegistry(opts, tasks, chat, chain, provider),
ControlPlane: tasks.ControlPlane(),
Identities: tasks,
Authenticate: runtimeOIDC.Authenticate,
AuthenticateBrowser: runtimeOIDC.AuthenticateBrowser,
Login: runtimeOIDC,
Access: chain,
Principals: tasks,
Denials: tasks,
})
stopLogs, err := wireServiceLogs(opts, srv, tasks, chat, feed)
if err != nil {
@@ -118,11 +122,6 @@ func Run(ctx context.Context, options Options) error {
"gateway", opts.Gateway.Target,
"state", opts.State.Target,
}
// Name the file holding the token, never the token itself: this line
// reaches the journal and any log an operator pastes.
if opts.TokenFile != "" {
attrs = append(attrs, "token_file", opts.TokenFile)
}
log.Info("archie-ui running", attrs...)
return serve(ctx, listener, srv.Handler(), opts)
}
+3
View File
@@ -403,6 +403,9 @@ func (b *server) callers() rpcidentity.Callers {
// no tenant boundary yet -- degrades the access RPCs rather than failing the
// boot, the same pattern the other optional surfaces use.
func (b *server) accessDeps(deps *staterpc.Deps) {
if accounts, ok := b.st.(identity.Accounts); ok {
deps.Accounts = accounts
}
if ps, ok := b.st.(access.PrincipalSource); ok {
deps.Principals = ps
}
File diff suppressed because it is too large. Load diff
@@ -35,6 +35,22 @@ const (
StateStoreService_RevokeTaskGrant_FullMethodName = "/state.v1.StateStoreService/RevokeTaskGrant"
StateStoreService_ResolveTaskGrant_FullMethodName = "/state.v1.StateStoreService/ResolveTaskGrant"
StateStoreService_ListIdentities_FullMethodName = "/state.v1.StateStoreService/ListIdentities"
StateStoreService_GetAuthenticationSettings_FullMethodName = "/state.v1.StateStoreService/GetAuthenticationSettings"
StateStoreService_SaveAuthenticationSettings_FullMethodName = "/state.v1.StateStoreService/SaveAuthenticationSettings"
StateStoreService_BeginPasskey_FullMethodName = "/state.v1.StateStoreService/BeginPasskey"
StateStoreService_FinishPasskey_FullMethodName = "/state.v1.StateStoreService/FinishPasskey"
StateStoreService_ListPasskeys_FullMethodName = "/state.v1.StateStoreService/ListPasskeys"
StateStoreService_DeletePasskey_FullMethodName = "/state.v1.StateStoreService/DeletePasskey"
StateStoreService_OpenAccountSession_FullMethodName = "/state.v1.StateStoreService/OpenAccountSession"
StateStoreService_RequireFreshAccountSession_FullMethodName = "/state.v1.StateStoreService/RequireFreshAccountSession"
StateStoreService_CreateAccountRecovery_FullMethodName = "/state.v1.StateStoreService/CreateAccountRecovery"
StateStoreService_RecoverAccount_FullMethodName = "/state.v1.StateStoreService/RecoverAccount"
StateStoreService_AccountSetup_FullMethodName = "/state.v1.StateStoreService/AccountSetup"
StateStoreService_RegisterAccount_FullMethodName = "/state.v1.StateStoreService/RegisterAccount"
StateStoreService_SignInAccount_FullMethodName = "/state.v1.StateStoreService/SignInAccount"
StateStoreService_ResolveAccountSession_FullMethodName = "/state.v1.StateStoreService/ResolveAccountSession"
StateStoreService_SignOutAccount_FullMethodName = "/state.v1.StateStoreService/SignOutAccount"
StateStoreService_ChangeAccountPassword_FullMethodName = "/state.v1.StateStoreService/ChangeAccountPassword"
StateStoreService_GetIdentity_FullMethodName = "/state.v1.StateStoreService/GetIdentity"
StateStoreService_CreateIdentity_FullMethodName = "/state.v1.StateStoreService/CreateIdentity"
StateStoreService_RenameIdentity_FullMethodName = "/state.v1.StateStoreService/RenameIdentity"
@@ -202,6 +218,22 @@ type StateStoreServiceClient interface {
ResolveTaskGrant(ctx context.Context, in *ResolveTaskGrantRequest, opts ...grpc.CallOption) (*ResolveTaskGrantResponse, error)
// Identity domain. Task-scoped grants cannot call these administrative RPCs.
ListIdentities(ctx context.Context, in *ListIdentitiesRequest, opts ...grpc.CallOption) (*ListIdentitiesResponse, error)
GetAuthenticationSettings(ctx context.Context, in *GetAuthenticationSettingsRequest, opts ...grpc.CallOption) (*GetAuthenticationSettingsResponse, error)
SaveAuthenticationSettings(ctx context.Context, in *SaveAuthenticationSettingsRequest, opts ...grpc.CallOption) (*SaveAuthenticationSettingsResponse, error)
BeginPasskey(ctx context.Context, in *BeginPasskeyRequest, opts ...grpc.CallOption) (*BeginPasskeyResponse, error)
FinishPasskey(ctx context.Context, in *FinishPasskeyRequest, opts ...grpc.CallOption) (*FinishPasskeyResponse, error)
ListPasskeys(ctx context.Context, in *ListPasskeysRequest, opts ...grpc.CallOption) (*ListPasskeysResponse, error)
DeletePasskey(ctx context.Context, in *DeletePasskeyRequest, opts ...grpc.CallOption) (*DeletePasskeyResponse, error)
OpenAccountSession(ctx context.Context, in *OpenAccountSessionRequest, opts ...grpc.CallOption) (*OpenAccountSessionResponse, error)
RequireFreshAccountSession(ctx context.Context, in *RequireFreshAccountSessionRequest, opts ...grpc.CallOption) (*RequireFreshAccountSessionResponse, error)
CreateAccountRecovery(ctx context.Context, in *CreateAccountRecoveryRequest, opts ...grpc.CallOption) (*CreateAccountRecoveryResponse, error)
RecoverAccount(ctx context.Context, in *RecoverAccountRequest, opts ...grpc.CallOption) (*RecoverAccountResponse, error)
AccountSetup(ctx context.Context, in *AccountSetupRequest, opts ...grpc.CallOption) (*AccountSetupResponse, error)
RegisterAccount(ctx context.Context, in *RegisterAccountRequest, opts ...grpc.CallOption) (*RegisterAccountResponse, error)
SignInAccount(ctx context.Context, in *SignInAccountRequest, opts ...grpc.CallOption) (*SignInAccountResponse, error)
ResolveAccountSession(ctx context.Context, in *ResolveAccountSessionRequest, opts ...grpc.CallOption) (*ResolveAccountSessionResponse, error)
SignOutAccount(ctx context.Context, in *SignOutAccountRequest, opts ...grpc.CallOption) (*SignOutAccountResponse, error)
ChangeAccountPassword(ctx context.Context, in *ChangeAccountPasswordRequest, opts ...grpc.CallOption) (*ChangeAccountPasswordResponse, error)
GetIdentity(ctx context.Context, in *GetIdentityRequest, opts ...grpc.CallOption) (*GetIdentityResponse, error)
CreateIdentity(ctx context.Context, in *CreateIdentityRequest, opts ...grpc.CallOption) (*CreateIdentityResponse, error)
RenameIdentity(ctx context.Context, in *RenameIdentityRequest, opts ...grpc.CallOption) (*RenameIdentityResponse, error)
@@ -601,6 +633,166 @@ func (c *stateStoreServiceClient) ListIdentities(ctx context.Context, in *ListId
return out, nil
}
func (c *stateStoreServiceClient) GetAuthenticationSettings(ctx context.Context, in *GetAuthenticationSettingsRequest, opts ...grpc.CallOption) (*GetAuthenticationSettingsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetAuthenticationSettingsResponse)
err := c.cc.Invoke(ctx, StateStoreService_GetAuthenticationSettings_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) SaveAuthenticationSettings(ctx context.Context, in *SaveAuthenticationSettingsRequest, opts ...grpc.CallOption) (*SaveAuthenticationSettingsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SaveAuthenticationSettingsResponse)
err := c.cc.Invoke(ctx, StateStoreService_SaveAuthenticationSettings_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) BeginPasskey(ctx context.Context, in *BeginPasskeyRequest, opts ...grpc.CallOption) (*BeginPasskeyResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(BeginPasskeyResponse)
err := c.cc.Invoke(ctx, StateStoreService_BeginPasskey_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) FinishPasskey(ctx context.Context, in *FinishPasskeyRequest, opts ...grpc.CallOption) (*FinishPasskeyResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(FinishPasskeyResponse)
err := c.cc.Invoke(ctx, StateStoreService_FinishPasskey_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ListPasskeys(ctx context.Context, in *ListPasskeysRequest, opts ...grpc.CallOption) (*ListPasskeysResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListPasskeysResponse)
err := c.cc.Invoke(ctx, StateStoreService_ListPasskeys_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) DeletePasskey(ctx context.Context, in *DeletePasskeyRequest, opts ...grpc.CallOption) (*DeletePasskeyResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DeletePasskeyResponse)
err := c.cc.Invoke(ctx, StateStoreService_DeletePasskey_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) OpenAccountSession(ctx context.Context, in *OpenAccountSessionRequest, opts ...grpc.CallOption) (*OpenAccountSessionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(OpenAccountSessionResponse)
err := c.cc.Invoke(ctx, StateStoreService_OpenAccountSession_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) RequireFreshAccountSession(ctx context.Context, in *RequireFreshAccountSessionRequest, opts ...grpc.CallOption) (*RequireFreshAccountSessionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RequireFreshAccountSessionResponse)
err := c.cc.Invoke(ctx, StateStoreService_RequireFreshAccountSession_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) CreateAccountRecovery(ctx context.Context, in *CreateAccountRecoveryRequest, opts ...grpc.CallOption) (*CreateAccountRecoveryResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CreateAccountRecoveryResponse)
err := c.cc.Invoke(ctx, StateStoreService_CreateAccountRecovery_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) RecoverAccount(ctx context.Context, in *RecoverAccountRequest, opts ...grpc.CallOption) (*RecoverAccountResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RecoverAccountResponse)
err := c.cc.Invoke(ctx, StateStoreService_RecoverAccount_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) AccountSetup(ctx context.Context, in *AccountSetupRequest, opts ...grpc.CallOption) (*AccountSetupResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AccountSetupResponse)
err := c.cc.Invoke(ctx, StateStoreService_AccountSetup_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) RegisterAccount(ctx context.Context, in *RegisterAccountRequest, opts ...grpc.CallOption) (*RegisterAccountResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RegisterAccountResponse)
err := c.cc.Invoke(ctx, StateStoreService_RegisterAccount_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) SignInAccount(ctx context.Context, in *SignInAccountRequest, opts ...grpc.CallOption) (*SignInAccountResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SignInAccountResponse)
err := c.cc.Invoke(ctx, StateStoreService_SignInAccount_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ResolveAccountSession(ctx context.Context, in *ResolveAccountSessionRequest, opts ...grpc.CallOption) (*ResolveAccountSessionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ResolveAccountSessionResponse)
err := c.cc.Invoke(ctx, StateStoreService_ResolveAccountSession_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) SignOutAccount(ctx context.Context, in *SignOutAccountRequest, opts ...grpc.CallOption) (*SignOutAccountResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SignOutAccountResponse)
err := c.cc.Invoke(ctx, StateStoreService_SignOutAccount_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ChangeAccountPassword(ctx context.Context, in *ChangeAccountPasswordRequest, opts ...grpc.CallOption) (*ChangeAccountPasswordResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ChangeAccountPasswordResponse)
err := c.cc.Invoke(ctx, StateStoreService_ChangeAccountPassword_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) GetIdentity(ctx context.Context, in *GetIdentityRequest, opts ...grpc.CallOption) (*GetIdentityResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetIdentityResponse)
@@ -1900,6 +2092,22 @@ type StateStoreServiceServer interface {
ResolveTaskGrant(context.Context, *ResolveTaskGrantRequest) (*ResolveTaskGrantResponse, error)
// Identity domain. Task-scoped grants cannot call these administrative RPCs.
ListIdentities(context.Context, *ListIdentitiesRequest) (*ListIdentitiesResponse, error)
GetAuthenticationSettings(context.Context, *GetAuthenticationSettingsRequest) (*GetAuthenticationSettingsResponse, error)
SaveAuthenticationSettings(context.Context, *SaveAuthenticationSettingsRequest) (*SaveAuthenticationSettingsResponse, error)
BeginPasskey(context.Context, *BeginPasskeyRequest) (*BeginPasskeyResponse, error)
FinishPasskey(context.Context, *FinishPasskeyRequest) (*FinishPasskeyResponse, error)
ListPasskeys(context.Context, *ListPasskeysRequest) (*ListPasskeysResponse, error)
DeletePasskey(context.Context, *DeletePasskeyRequest) (*DeletePasskeyResponse, error)
OpenAccountSession(context.Context, *OpenAccountSessionRequest) (*OpenAccountSessionResponse, error)
RequireFreshAccountSession(context.Context, *RequireFreshAccountSessionRequest) (*RequireFreshAccountSessionResponse, error)
CreateAccountRecovery(context.Context, *CreateAccountRecoveryRequest) (*CreateAccountRecoveryResponse, error)
RecoverAccount(context.Context, *RecoverAccountRequest) (*RecoverAccountResponse, error)
AccountSetup(context.Context, *AccountSetupRequest) (*AccountSetupResponse, error)
RegisterAccount(context.Context, *RegisterAccountRequest) (*RegisterAccountResponse, error)
SignInAccount(context.Context, *SignInAccountRequest) (*SignInAccountResponse, error)
ResolveAccountSession(context.Context, *ResolveAccountSessionRequest) (*ResolveAccountSessionResponse, error)
SignOutAccount(context.Context, *SignOutAccountRequest) (*SignOutAccountResponse, error)
ChangeAccountPassword(context.Context, *ChangeAccountPasswordRequest) (*ChangeAccountPasswordResponse, error)
GetIdentity(context.Context, *GetIdentityRequest) (*GetIdentityResponse, error)
CreateIdentity(context.Context, *CreateIdentityRequest) (*CreateIdentityResponse, error)
RenameIdentity(context.Context, *RenameIdentityRequest) (*RenameIdentityResponse, error)
@@ -2187,6 +2395,54 @@ func (UnimplementedStateStoreServiceServer) ResolveTaskGrant(context.Context, *R
func (UnimplementedStateStoreServiceServer) ListIdentities(context.Context, *ListIdentitiesRequest) (*ListIdentitiesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListIdentities not implemented")
}
func (UnimplementedStateStoreServiceServer) GetAuthenticationSettings(context.Context, *GetAuthenticationSettingsRequest) (*GetAuthenticationSettingsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetAuthenticationSettings not implemented")
}
func (UnimplementedStateStoreServiceServer) SaveAuthenticationSettings(context.Context, *SaveAuthenticationSettingsRequest) (*SaveAuthenticationSettingsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SaveAuthenticationSettings not implemented")
}
func (UnimplementedStateStoreServiceServer) BeginPasskey(context.Context, *BeginPasskeyRequest) (*BeginPasskeyResponse, error) {
return nil, status.Error(codes.Unimplemented, "method BeginPasskey not implemented")
}
func (UnimplementedStateStoreServiceServer) FinishPasskey(context.Context, *FinishPasskeyRequest) (*FinishPasskeyResponse, error) {
return nil, status.Error(codes.Unimplemented, "method FinishPasskey not implemented")
}
func (UnimplementedStateStoreServiceServer) ListPasskeys(context.Context, *ListPasskeysRequest) (*ListPasskeysResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListPasskeys not implemented")
}
func (UnimplementedStateStoreServiceServer) DeletePasskey(context.Context, *DeletePasskeyRequest) (*DeletePasskeyResponse, error) {
return nil, status.Error(codes.Unimplemented, "method DeletePasskey not implemented")
}
func (UnimplementedStateStoreServiceServer) OpenAccountSession(context.Context, *OpenAccountSessionRequest) (*OpenAccountSessionResponse, error) {
return nil, status.Error(codes.Unimplemented, "method OpenAccountSession not implemented")
}
func (UnimplementedStateStoreServiceServer) RequireFreshAccountSession(context.Context, *RequireFreshAccountSessionRequest) (*RequireFreshAccountSessionResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RequireFreshAccountSession not implemented")
}
func (UnimplementedStateStoreServiceServer) CreateAccountRecovery(context.Context, *CreateAccountRecoveryRequest) (*CreateAccountRecoveryResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CreateAccountRecovery not implemented")
}
func (UnimplementedStateStoreServiceServer) RecoverAccount(context.Context, *RecoverAccountRequest) (*RecoverAccountResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RecoverAccount not implemented")
}
func (UnimplementedStateStoreServiceServer) AccountSetup(context.Context, *AccountSetupRequest) (*AccountSetupResponse, error) {
return nil, status.Error(codes.Unimplemented, "method AccountSetup not implemented")
}
func (UnimplementedStateStoreServiceServer) RegisterAccount(context.Context, *RegisterAccountRequest) (*RegisterAccountResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RegisterAccount not implemented")
}
func (UnimplementedStateStoreServiceServer) SignInAccount(context.Context, *SignInAccountRequest) (*SignInAccountResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SignInAccount not implemented")
}
func (UnimplementedStateStoreServiceServer) ResolveAccountSession(context.Context, *ResolveAccountSessionRequest) (*ResolveAccountSessionResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ResolveAccountSession not implemented")
}
func (UnimplementedStateStoreServiceServer) SignOutAccount(context.Context, *SignOutAccountRequest) (*SignOutAccountResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SignOutAccount not implemented")
}
func (UnimplementedStateStoreServiceServer) ChangeAccountPassword(context.Context, *ChangeAccountPasswordRequest) (*ChangeAccountPasswordResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ChangeAccountPassword not implemented")
}
func (UnimplementedStateStoreServiceServer) GetIdentity(context.Context, *GetIdentityRequest) (*GetIdentityResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetIdentity not implemented")
}
@@ -2865,6 +3121,294 @@ func _StateStoreService_ListIdentities_Handler(srv interface{}, ctx context.Cont
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_GetAuthenticationSettings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetAuthenticationSettingsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).GetAuthenticationSettings(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_GetAuthenticationSettings_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).GetAuthenticationSettings(ctx, req.(*GetAuthenticationSettingsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SaveAuthenticationSettings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SaveAuthenticationSettingsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SaveAuthenticationSettings(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SaveAuthenticationSettings_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SaveAuthenticationSettings(ctx, req.(*SaveAuthenticationSettingsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_BeginPasskey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BeginPasskeyRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).BeginPasskey(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_BeginPasskey_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).BeginPasskey(ctx, req.(*BeginPasskeyRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_FinishPasskey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FinishPasskeyRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).FinishPasskey(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_FinishPasskey_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).FinishPasskey(ctx, req.(*FinishPasskeyRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ListPasskeys_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListPasskeysRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ListPasskeys(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ListPasskeys_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ListPasskeys(ctx, req.(*ListPasskeysRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_DeletePasskey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeletePasskeyRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).DeletePasskey(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_DeletePasskey_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).DeletePasskey(ctx, req.(*DeletePasskeyRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_OpenAccountSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(OpenAccountSessionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).OpenAccountSession(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_OpenAccountSession_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).OpenAccountSession(ctx, req.(*OpenAccountSessionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RequireFreshAccountSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequireFreshAccountSessionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RequireFreshAccountSession(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RequireFreshAccountSession_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RequireFreshAccountSession(ctx, req.(*RequireFreshAccountSessionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_CreateAccountRecovery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateAccountRecoveryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).CreateAccountRecovery(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_CreateAccountRecovery_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).CreateAccountRecovery(ctx, req.(*CreateAccountRecoveryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RecoverAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RecoverAccountRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RecoverAccount(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RecoverAccount_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RecoverAccount(ctx, req.(*RecoverAccountRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_AccountSetup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AccountSetupRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).AccountSetup(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_AccountSetup_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).AccountSetup(ctx, req.(*AccountSetupRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RegisterAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RegisterAccountRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RegisterAccount(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RegisterAccount_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RegisterAccount(ctx, req.(*RegisterAccountRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SignInAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SignInAccountRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SignInAccount(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SignInAccount_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SignInAccount(ctx, req.(*SignInAccountRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ResolveAccountSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ResolveAccountSessionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ResolveAccountSession(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ResolveAccountSession_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ResolveAccountSession(ctx, req.(*ResolveAccountSessionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SignOutAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SignOutAccountRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SignOutAccount(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SignOutAccount_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SignOutAccount(ctx, req.(*SignOutAccountRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ChangeAccountPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ChangeAccountPasswordRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ChangeAccountPassword(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ChangeAccountPassword_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ChangeAccountPassword(ctx, req.(*ChangeAccountPasswordRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_GetIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetIdentityRequest)
if err := dec(in); err != nil {
@@ -5129,6 +5673,70 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "ListIdentities",
Handler: _StateStoreService_ListIdentities_Handler,
},
{
MethodName: "GetAuthenticationSettings",
Handler: _StateStoreService_GetAuthenticationSettings_Handler,
},
{
MethodName: "SaveAuthenticationSettings",
Handler: _StateStoreService_SaveAuthenticationSettings_Handler,
},
{
MethodName: "BeginPasskey",
Handler: _StateStoreService_BeginPasskey_Handler,
},
{
MethodName: "FinishPasskey",
Handler: _StateStoreService_FinishPasskey_Handler,
},
{
MethodName: "ListPasskeys",
Handler: _StateStoreService_ListPasskeys_Handler,
},
{
MethodName: "DeletePasskey",
Handler: _StateStoreService_DeletePasskey_Handler,
},
{
MethodName: "OpenAccountSession",
Handler: _StateStoreService_OpenAccountSession_Handler,
},
{
MethodName: "RequireFreshAccountSession",
Handler: _StateStoreService_RequireFreshAccountSession_Handler,
},
{
MethodName: "CreateAccountRecovery",
Handler: _StateStoreService_CreateAccountRecovery_Handler,
},
{
MethodName: "RecoverAccount",
Handler: _StateStoreService_RecoverAccount_Handler,
},
{
MethodName: "AccountSetup",
Handler: _StateStoreService_AccountSetup_Handler,
},
{
MethodName: "RegisterAccount",
Handler: _StateStoreService_RegisterAccount_Handler,
},
{
MethodName: "SignInAccount",
Handler: _StateStoreService_SignInAccount_Handler,
},
{
MethodName: "ResolveAccountSession",
Handler: _StateStoreService_ResolveAccountSession_Handler,
},
{
MethodName: "SignOutAccount",
Handler: _StateStoreService_SignOutAccount_Handler,
},
{
MethodName: "ChangeAccountPassword",
Handler: _StateStoreService_ChangeAccountPassword_Handler,
},
{
MethodName: "GetIdentity",
Handler: _StateStoreService_GetIdentity_Handler,
+59
View File
@@ -0,0 +1,59 @@
package identity
import (
"context"
"errors"
"net/mail"
"strings"
"time"
)
var ErrSetupComplete = errors.New("administrator has already been set up")
const AccountSessionLifetime = 7 * 24 * time.Hour
type AccountRegistration struct {
PublicURL string `json:"public_url"`
WorkspaceName string `json:"workspace_name"`
OrganisationName string `json:"organisation_name"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
Role string `json:"role"`
}
func (r *AccountRegistration) Validate() error {
r.Email = strings.ToLower(strings.TrimSpace(r.Email))
address, err := mail.ParseAddress(r.Email)
r.DisplayName = strings.TrimSpace(r.DisplayName)
if err != nil || address.Address != r.Email || len(r.Email) > 254 || r.DisplayName == "" || len(r.DisplayName) > 200 {
return ErrInvalid
}
return nil
}
type AccountSession struct {
Identity Identity
Token string
Expires time.Time
}
// Accounts is served by the State Store. Account creation after bootstrap is
// administrative; password changes always address the caller's own identity.
type Accounts interface {
AccountSetupRequired(context.Context) (bool, error)
RegisterAccount(context.Context, AccountRegistration, bool) (Identity, error)
SignInAccount(context.Context, string, string) (AccountSession, error)
ResolveAccountSession(context.Context, string) (Identity, error)
SignOutAccount(context.Context, string) error
ChangeAccountPassword(context.Context, string, string) error
}
// AccountSecurity guards authenticator changes with recent authentication and
// provides a one-use recovery secret without relying on outbound email.
type AccountSecurity interface {
OpenAccountSession(context.Context, time.Time) (AccountSession, error)
RequireFreshAccountSession(context.Context, string) error
CreateAccountRecovery(context.Context) (string, error)
RecoverAccount(context.Context, string, string, string) error
}
@@ -0,0 +1,68 @@
package identity
import (
"context"
"net/url"
"strings"
)
type AuthenticationSettings struct {
PublicURL string `json:"public_url"`
OIDCIssuer string `json:"oidc_issuer"`
OIDCAudience string `json:"oidc_audience"`
OIDCClientID string `json:"oidc_client_id"`
}
func (s AuthenticationSettings) Validate() error {
if !validInstanceOrigin(s.PublicURL) {
return ErrInvalid
}
if s.OIDCIssuer == "" {
if s.OIDCClientID != "" || s.OIDCAudience != "" {
return ErrInvalid
}
return nil
}
if !validProviderIssuer(s.OIDCIssuer) || strings.TrimSpace(s.OIDCClientID) == "" || strings.TrimSpace(s.OIDCAudience) == "" {
return ErrInvalid
}
return nil
}
func validInstanceOrigin(raw string) bool {
u, err := url.Parse(raw)
if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return false
}
return (u.Path == "" || u.Path == "/") && (u.Scheme == "https" || u.Scheme == "http")
}
func validProviderIssuer(raw string) bool {
u, err := url.Parse(raw)
if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return false
}
return u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "localhost")
}
type AuthenticationSettingsStore interface {
AuthenticationSettings(context.Context) (AuthenticationSettings, error)
SaveAuthenticationSettings(context.Context, AuthenticationSettings) error
}
type Passkey struct {
ID string `json:"id"`
Name string `json:"name"`
}
type PasskeyCeremony struct {
Token string
Options []byte
}
type Passkeys interface {
BeginPasskey(context.Context, bool) (PasskeyCeremony, error)
FinishPasskey(context.Context, string, []byte, bool, string) (AccountSession, error)
ListPasskeys(context.Context) ([]Passkey, error)
DeletePasskey(context.Context, string) error
}
@@ -0,0 +1,27 @@
package identity
import "testing"
func TestAuthenticationSettingsRejectUntrustedOrigins(t *testing.T) {
for _, tc := range []struct {
name, url, issuer, client, audience string
want bool
}{
{name: "public TLS", url: "https://archie.example", want: true},
{name: "localhost", url: "http://localhost:8484", want: true},
{name: "userinfo is not an origin", url: "https://user:password@archie.example", want: false},
{name: "URL path cannot change the RP origin", url: "https://archie.example/subpath", want: false},
{name: "query is not an origin", url: "https://archie.example?token=1", want: false},
{name: "complete provider", url: "https://archie.example", issuer: "https://identity.example", client: "archie", audience: "archie", want: true},
{name: "remote insecure provider", url: "https://archie.example", issuer: "http://identity.example", client: "archie", audience: "archie", want: false},
{name: "issuer without client", url: "https://archie.example", issuer: "https://identity.example", audience: "archie", want: false},
{name: "audience without provider", url: "https://archie.example", audience: "archie", want: false},
} {
t.Run(tc.name, func(t *testing.T) {
err := (AuthenticationSettings{PublicURL: tc.url, OIDCIssuer: tc.issuer, OIDCClientID: tc.client, OIDCAudience: tc.audience}).Validate()
if (err == nil) != tc.want {
t.Fatalf("validation err=%v, allowed=%v", err, tc.want)
}
})
}
}
@@ -0,0 +1,359 @@
package identity
// Known common passwords at or above the minimum length, from the NCSC
// list in SecLists. Shorter entries are rejected by the length rule.
// Source: https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/100k-most-used-passwords-NCSC.txt
//
// MIT License
//
// Copyright (c) 2018 Daniel Miessler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
const commonPasswords = `
$hex[687474703a2f2f616473]
$hex[687474703a2f2f777777]
000000000000000
00000000000000000000
010203040506070809
102030405060708090
111111111111111
11111111111111111111
111111prof_root2.sql.txt:,
111111prof_root3.sql.txt:,
111222333444555
1122334455667788
112233445566778899
11223344556677889900
1213141516171819
122333444455555
123123123123123
123451234512345
1234567812345678
1234567887654321
12345678900987654321
123456789012345
1234567890123456
12345678901234567890
1234567890987654321
1234567890qwert
1234567890qwerty
1234567890qwertyuiop
123456789101112
123456789123456
1234567891234567
123456789123456789
12345678987654321
123456789987654
1234567899876543
123456789987654321
123456789qwerty
123456789qwertyuio
123456789qwertyuiop
123456789zxcvbnm
12345678qwertyui
123456prof_root2.sql.txt:,
123456prof_root3.sql.txt:,
12345qwertasdfg
1234qwerasdfzxcv
1324354657687980
1q2w3e4r5t6y7u8
1q2w3e4r5t6y7u8i
1q2w3e4r5t6y7u8i9o
1q2w3e4r5t6y7u8i9o0p
1qa2ws3ed4rf5tg
1qaz2wsx3edc4rfv
1qaz2wsx3edc4rfv5tgb
1qazxsw23edcvfr4
30secondstomars
5.254.105.20:test
5.254.105.20:test1
555555555555555
6666666666empulgara
79621601378.kirill
827ccb0eea8a706c4c
9121318barssuki
987654321123456789
???????????????
@elit-centr.com.ua
aaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaa
abuse_123456_abuse
aleksandr.ustinov.2012
aleksej.shorin.86
alena_plotnikova_1995
aliya.mutallapova
andrey.shalanov
andreyka.gorshkov.98
andreyka.zhilin.1981
anna.savickaya.1986
antsiferova1973
antusenok_zhekonya
apalkova.tatiana
aqwleeb_6e0pk59
arina-sharapova-80
arividerchi_shatalov
armyach-aleksandra
arsik-di-noxcho95
asdfghjkl:&#39:
asdfghjkl;'
asdfghjklzxcvbnm
asil.dovlatov.1982
avengedsevenfold
azefirov.inno1987.r
bad_boys_adience
bakuman.manga.drawing
beloved_a_devil
blackangel09021
blckd_sa_unpaidfee_oct06
californication
ceckbrcerfkbxyjcnm2
cod12qw75rqyi59n
constance626boilard1987
cristianoronaldo
d1bd6bc58c1d74df41a957489c9942f5
d41d8cd98f00b204e980
damira.shagabutdinova
default_password
demon1q2w3e4r5t
denis_nazarenko
dimulya.vasilenko
dmitrij.mironov2014
doomsayer.2.7mords.v
doomsayer.2.7mords.vv
dovbeshkosushova.1972
drm199019902323
e10adc3949ba59abbe56
eremei_vasechkin
etravelmoleoptin
evgenii-shenderovich
familiyafamiliya
fiammalex1@hotmail.it
fjodorova-natashenka
friendofarriane
friendofearning$1
friendofeveryemailyouproc
friendofthenext18peoplew
friendofyoucanmake$200-
gadjieva.gulmira
galatasaray1905
galina-davidyuk
galinka_korneeva
gayassfagpastebinleaks
goderdzikarxjxv
golovizina_elena
guldaniya.galina
gygypyfyyyposhy
hallucinationse
hd764nw5d7e1vb1
hermina617berno1990f6i
holidaysecure123
holidaysecure123$
htt//members.cumfiesta.com/
hugo854lataille1988
ignatova_1978_09
ijfrnhf7yhcy54bhy0cd
inactive1996aug
ivankaterinchenko
jafjkshf7y6w34rjd
john!20130605at1753
julia_eduardovna
juliadronina1996
kamazist.tsobenko
kartoffelpuffer
kikugalanetroot
kinyabuzova.eleonora
kirienko_svetlana
kirik26trimyasov
kirill.kirillov.2013
korostelev_3333
kotovichvalentina
ksyusha.kulagina.91
kudryavcevavalya
kurmangazieva_gulmira
kuznecovviktorr
lady.procenko71
len_rin_kagamine_02
lexaafanasiev84
lhbjkjubz2957704
lightpower12345
linkedinlinkedin
linkedinpassword
listopad.iuliia
macegorova.mariya
maitland571ka1994
maks.abramov.99.99
maksim.bychkov.1986
maksimilian_nasirov
malhotra493ozzy1991282151
manchesterunited
mandds1mg6bv8re
maria-demidchik
mariagoncharenko
marina.shapovalo
marina.ushakovaznuv
marina_stryazhkova
marinadeduxinaa
marinaorlova1991
marinochka.zhelannaya
masloboinikova1987
maximova_elena77
migrationsandeep
migrationschool
mihail_alekseevskiy406
mihailpezhemskii
milankasanakoeva
mirellabroersma1987570
miss-evgeniya-93
miss.marina.nikolaeva.2013
mknaxhxeh8yp3tf
morozovavalya28
mozellbranou81e
mutalim.gusenov
mychemicalromance
narashchivaiunoghti
nastyaanciferova
natalya.dmitrieva.1978
nati.beridze.92
never_desponding
neworleans12345
nikolay_thebest
oksanaorgadykova
olesya.kolchina
olga.kazakova_85
olga.ponomarenko.2012
olga.rumyanceva.1985
olgha.pietrova.1979
password1234567
password12345678
password123456789
passwordpassword
pletnevakaterina
polniypizdec0211
polniypizdec1102
polniypizdec110211
professionaltools
prosto_chelkynchik
q1w2e3r4t5y6u7i8
q1w2e3r4t5y6u7i8o9
q1w2e3r4t5y6u7i8o9p0
qazwsxedcrfvtgb
qwertasdfgzxcvb
qwerty123456789
qwerty1234567890
qwertyuiop12345
qwertyuiop123456
qwertyuiop123456789
qwertyuiop1234567890
qwertyuiopasdfg
qwertyuiopasdfghjkl
qwertyuiopasdfghjkl151515
qwertyuiopasdfghjklzxcvbnm
r6a50de3ujwtog4
rachelle289ariyoshi5251987
rashaun966krager1993
raymonde336schwegel7331987
regawf7ss1dm7rn
rendakova_sveta
riwr2hky4w3tjgg
rkamkin.karoli1988mp
romanova.natalya.96
rtertuy77ijyhu7i
sataieva.elinka
sdf7asdf6asdg8df
sdf7asdf6asdg8df1
sergeevna_10.10.91
sergey-personal
sergey.lushnikoff
sergey.melnik-1996
sergio-emperior
shakmakovataisiya1992
shaquillesecx10
sharmaine005foskett6071988
shea019bernabei1992
sheba417yorck1986vxm7
shukurova-ismigu
siiifonjiknalivai
silakova.nadezhda.2012
simonova_lyudmila_73
simonovskiy1970
sirazhdinov.shamil
slava_kulbidyuk
sofya.kulikova.87
soloveibormalei
somanypickles27
sorokina-999-01
spiridonmarkin1982
spring938burston0001990
srcuqq1_2j1h3rbf
stalker_lemurrr
stas.gorodissky
stas_the_best.ru
stefangreil1983
stepanov_georgij
sulamifcherenchikova1979
svetik_kryuchkov
svetlana-mironova-13
tagesgruppe2010
thisismypassword
travelmoleoptin
vadyusha.isaev.83
valentina.victoria
valya-valya-1982
valya.klimenko.87
valya.korobeynik
valya.kryuchkova.1990
valya.lantux.83
varfolomeeva0990
varida.alibaeva
veralipatnikova
victor_evdokimov
victor_sakhalin1990-20
victoria-berkat-energo
victoria-dyatlova
victoria392eliezrie1992frp
victoria_shkurco
vika.krivonos.1995
vkovshut_annab1988fg
vks1zz9v_7ceu69
vladcherktecktonik
volfram.kozlov123633
volfram.kozlov173902
volgograd.orlovka
volkova.elena.13
volkova.ksyusha.89
volodina.elena66
volodya-ivanov-63
volokitina.olga
voroshilova.liliya
worldofwarcraft
wwwksenechkawww
yegbpltw2012lol
yfdbufnjh10305070
yulia-dubrovina
yushinazena2009
zabloczkaya2012
zabolotneva_ira
zabolotnova31337
zarina_sabirova
zarinaismailova
zxcvbnm123456789
zxcvbnmasdfghjkl
пїѕпїѕпїѕпїѕпїѕпїѕ@mail.ru
`
+47
View File
@@ -0,0 +1,47 @@
package identity
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"unicode/utf8"
"golang.org/x/crypto/argon2"
)
// HashPassword uses the OWASP Argon2id minimum with a fresh salt.
func HashPassword(password string) (string, error) {
if utf8.RuneCountInString(password) < 15 || len(password) > 1024 {
return "", fmt.Errorf("%w: password must have at least 15 characters and at most 1024 bytes", ErrInvalid)
}
if strings.Contains(commonPasswords, "\n"+strings.ToLower(password)+"\n") {
return "", fmt.Errorf("%w: choose a password that is not commonly used", ErrInvalid)
}
var salt [16]byte
if _, err := rand.Read(salt[:]); err != nil {
return "", err
}
key := argon2.IDKey([]byte(password), salt[:], 2, 19*1024, 1, 32)
return "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
}
// VerifyPassword accepts only parameters this application produces, bounding
// the work even if a stored hash is corrupted.
func VerifyPassword(password, hash string) bool {
parts := strings.Split(hash, "$")
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" || parts[3] != "m=19456,t=2,p=1" || len(password) > 1024 {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) != 16 {
return false
}
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(expected) != 32 {
return false
}
key := argon2.IDKey([]byte(password), salt, 2, 19*1024, 1, 32)
return subtle.ConstantTimeCompare(key, expected) == 1
}
+40
View File
@@ -0,0 +1,40 @@
package identity
import (
"strings"
"testing"
)
func TestPasswordVerification(t *testing.T) {
hash, err := HashPassword("a sufficiently long password")
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, password, hash string
want bool
}{
{"correct", "a sufficiently long password", hash, true},
{"wrong", "a different long password", hash, false},
{"malformed", "a sufficiently long password", "bad", false},
{"unbounded parameters", "password", "$argon2id$v=19$m=999999999,t=2,p=1$c2FsdA$aGFzaA", false},
} {
t.Run(tc.name, func(t *testing.T) {
if got := VerifyPassword(tc.password, tc.hash); got != tc.want {
t.Fatalf("verification = %v, want %v", got, tc.want)
}
})
}
for _, password := range []string{"short", strings.Repeat("a", 1025), "123456789012345", "passwordpassword"} {
if _, err := HashPassword(password); err == nil {
t.Fatal("accepted invalid password length")
}
}
second, err := HashPassword("a sufficiently long password")
if err != nil {
t.Fatal(err)
}
if hash == second {
t.Fatal("password hashes reuse salts")
}
}
+8 -3
View File
@@ -26,6 +26,10 @@ type DashboardPage struct {
var dashboardPages = []DashboardPage{
{Path: "/", Label: "Dashboard", Description: "Running work, work needing attention, token spend."},
{Path: "/tasks", Label: "Tasks", Description: "Picked-up issues and their status."},
{Path: "/account", Label: "Your account", Description: "Password, recovery code and passkeys."},
{Path: "/org", Label: "Organisation", Description: "Members, local accounts and organization roles."},
{Path: "/settings/authentication", Label: "Authentication", Description: "Instance URL and OIDC sign-in."},
{Path: "/settings/playbooks", Label: "Playbooks", Description: "Edit event-driven automation rules."},
{Path: "/workflows", Label: "Workflows", Description: "Workflows and run history."},
{Path: "/settings/skills", Label: "Skills", Description: "Skills Archie can activate."},
{Path: "/settings/curators", Label: "Curators", Description: "Scheduled memory and capture curation."},
@@ -60,7 +64,8 @@ func DashboardPages() []DashboardPage {
// PageIndexResult is what page_index returns: the full list of dashboard pages
// and what each one shows, so the agent can answer where to go.
type PageIndexResult struct {
Pages []DashboardPage `json:"pages"`
Pages []DashboardPage `json:"pages"`
ProductGuide string `json:"product_guide"`
}
// pageIndexTool returns the tool that lists every dashboard page. It is only
@@ -70,10 +75,10 @@ func pageIndexTool() (tools.ToolEntry, bool) {
entry := tools.ToolEntry{
Name: "page_index",
Toolset: "dashboard",
Description: "List every dashboard page and, in one line, what it shows. Use it to tell the operator where to go for something rather than guessing.",
Description: "List every dashboard page, what it shows, and built-in guidance for creating workflows and using Archie. Use it to tell the operator where to go for something rather than guessing.",
Classification: tools.ClassIdempotent,
Handler: func(_ context.Context, _ map[string]any) (any, error) {
return PageIndexResult{Pages: DashboardPages()}, nil
return PageIndexResult{Pages: DashboardPages(), ProductGuide: productGuide}, nil
},
}
return entry, true
+18 -13
View File
@@ -10,6 +10,9 @@ import (
//go:embed templates/archie.md.tpl
var archiePromptTpl string
//go:embed templates/product-guide.md
var productGuide string
// ToolSummary is the capability metadata for one registered tool, as it is
// advertised to the model.
type ToolSummary struct {
@@ -66,7 +69,8 @@ type SystemPromptConfig struct {
// calling methods during rendering.
type promptData struct {
SystemPromptConfig
Date string
Date string
ProductGuide string
}
// escapeXML replaces the three bytes that would otherwise be read as markup
@@ -95,18 +99,19 @@ func BuildSystemPrompt(cfg SystemPromptConfig) string {
}
}
data := promptData{
Soul: cfg.Soul,
Tools: tools,
Channel: cfg.Channel,
Model: cfg.Model,
SessionID: cfg.SessionID,
Page: cfg.Page,
Now: cfg.Now,
Date: cfg.Now.Format("2006-01-02"),
Workspace: cfg.Workspace,
Repos: cfg.Repos,
Operator: cfg.Operator,
Memory: cfg.Memory,
Soul: cfg.Soul,
Tools: tools,
Channel: cfg.Channel,
Model: cfg.Model,
SessionID: cfg.SessionID,
Page: cfg.Page,
Now: cfg.Now,
Date: cfg.Now.Format("2006-01-02"),
Workspace: cfg.Workspace,
Repos: cfg.Repos,
Operator: cfg.Operator,
Memory: cfg.Memory,
ProductGuide: productGuide,
}
var buf strings.Builder
if err := archiePromptTemplate.Execute(&buf, data); err != nil {
+29 -2
View File
@@ -13,6 +13,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
@@ -40,6 +41,9 @@ func (s *postgresSessionStore) Close() error {
// ── Sessions ────────────────────────────────────────────────────────────────
func (s *postgresSessionStore) Save(ctx context.Context, sc SessionContext) error {
if !sessionVisible(ctx, sc) {
return ErrSessionNotFound
}
q := postgresdb.New(s.pool)
saved, err := q.SaveSession(ctx, postgresdb.SaveSessionParams{
SessionID: sc.SessionID,
@@ -73,6 +77,9 @@ func (s *postgresSessionStore) Get(ctx context.Context, sessionID string) (*Sess
return nil, fmt.Errorf("sessionstore: get: %w", err)
}
sc := sessionFromRow(row)
if !sessionVisible(ctx, sc) {
return nil, nil
}
return &sc, nil
}
@@ -84,7 +91,7 @@ func (s *postgresSessionStore) GetByChannel(ctx context.Context, platform, chann
if err != nil {
return nil, fmt.Errorf("sessionstore: get by channel: %w", err)
}
return sessionsFromRows(rows), nil
return visibleSessions(ctx, sessionsFromRows(rows)), nil
}
func (s *postgresSessionStore) Delete(ctx context.Context, sessionID string) error {
@@ -133,7 +140,7 @@ func (s *postgresSessionStore) List(ctx context.Context) ([]SessionContext, erro
if err != nil {
return nil, fmt.Errorf("sessionstore: list: %w", err)
}
return sessionsFromRows(rows), nil
return visibleSessions(ctx, sessionsFromRows(rows)), nil
}
func sessionFromRow(row postgresdb.Session) SessionContext {
@@ -846,6 +853,15 @@ func (s *postgresSessionStore) mayRead(ctx context.Context, sessionID string) er
} else if err != nil {
return fmt.Errorf("sessionstore: session org: %w", err)
}
if _, ok := access.PrincipalFromContext(ctx); ok {
session, err := s.Get(ctx, sessionID)
if err != nil {
return err
}
if session == nil {
return ErrSessionNotFound
}
}
if owner != callerOrg(ctx) {
return ErrSessionNotFound
}
@@ -861,3 +877,14 @@ func (s *postgresSessionStore) mayWrite(ctx context.Context, sessionID string) e
}
return s.mayRead(ctx, sessionID)
}
// Service-owned curation has no person principal. Signed-in callers only
// see their own web conversations, including through tools and slash commands.
func sessionVisible(ctx context.Context, session SessionContext) bool {
p, ok := access.PrincipalFromContext(ctx)
return !ok || (session.Source.Platform == "web" && session.Source.ThreadID == string(p.IdentityID))
}
func visibleSessions(ctx context.Context, sessions []SessionContext) []SessionContext {
return slices.DeleteFunc(sessions, func(session SessionContext) bool { return !sessionVisible(ctx, session) })
}
@@ -0,0 +1,34 @@
package gateway
import (
"testing"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
func TestSessionVisibility(t *testing.T) {
for _, tc := range []struct {
name string
service bool
platform, owner string
want bool
}{
{"own history", false, "web", "alice", true},
{"another user in the same org", false, "web", "bob", false},
{"anonymous history is not assigned to a person", false, "web", "", false},
{"other channel history", false, "telegram", "alice", false},
{"curator service", true, "web", "bob", true},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := t.Context()
if !tc.service {
ctx = access.WithPrincipal(ctx, access.Principal{IdentityID: "alice"})
}
session := SessionContext{Source: messaging.SessionSource{Platform: tc.platform, ThreadID: tc.owner}}
if got := sessionVisible(ctx, session); got != tc.want {
t.Fatalf("visible=%v want=%v", got, tc.want)
}
})
}
}
+5 -1
View File
@@ -16,7 +16,7 @@ The `<soul>` block above, when present, supplies identity and communication styl
</instruction_precedence>
<core_rules>
1. Never claim a capability beyond the tools listed below, and never assert that a file, memory, action, result or specific system detail (a file path, subsystem name, count or config value) exists, succeeded, or is accurate unless you checked it with a tool this turn -- a detail from earlier in the conversation, from memory, or from your own training data is unconfirmed, however specific or familiar it sounds. If you are unsure whether you can do something, say so plainly rather than guessing, and do not wait for the user to challenge you before correcting an unchecked claim.
1. Never claim a capability beyond the tools listed below, and never assert that a file, memory, action, result or specific system detail (a file path, subsystem name, count or config value) exists, succeeded, or is accurate unless it is supplied in the runtime metadata or built-in product guide, or you checked it with a tool this turn -- a detail from earlier in the conversation, from memory, or from your own training data is unconfirmed, however specific or familiar it sounds. If you are unsure whether you can do something, say so plainly rather than guessing, and do not wait for the user to challenge you before correcting an unchecked claim.
2. The tools listed below are the complete set available to you. You have no others. Do not offer to run commands, read files, install software or reach the network unless a listed tool actually does it.
3. When you cannot do something, say what you cannot do and what you can do instead, in one or two sentences. Do not offer a numbered menu of questions.
4. Prefer acting with a tool over asking the user for information a tool could retrieve.
@@ -25,6 +25,10 @@ The `<soul>` block above, when present, supplies identity and communication styl
7. Never ask to be given shell access, credentials, a connection or a path into a system. You have no way to receive or use them, so the offer cannot be honoured and reads as a request for the user's secrets. Say what a listed tool can do instead.
</core_rules>
<product_guide purpose="product_reference" trust="data">
{{xml .ProductGuide}}
</product_guide>
<communication>
- Replies are delivered over a chat channel: lead with the answer, keep it short, and skip preamble.
- Brevity means not padding an answer; it does not mean being cold. A short reply can still be warm, and a clipped transactional one reads as rude.
@@ -0,0 +1,18 @@
Archie is event-driven automation: events start workflows, workflows run agent/tool steps, and results can require human review. A repository is optional. Use this built-in guide for product questions; the public GitHub repository is not a required source and may be private. Source-code details still require a file/tool lookup in an authorized workspace. Never invent a checkout or assume public repository access.
Accounts and organization:
- First visit creates the organization, first workspace, instance URL, and first admin account. Organization members are managed at /org. Local accounts and OIDC identities are distinct; an identity must have membership before it can act.
- Your account (/account) manages passwords, one-use recovery codes and passkeys. Passkeys need the configured HTTPS domain or localhost and a supported browser. Instance admins configure OIDC at /settings/authentication. Never request passwords, tokens or recovery codes in chat.
Creating a workflow:
1. Open /workflows and choose New workflow. The new definition is an unsaved draft with an id and empty steps.
2. Use YAML to edit its id, or the canvas to add and select steps. Select Starts when on the canvas to open Workflow settings. Set Runs as to an existing active agent identity. Works on selects Repository, If given, or None.
3. Read an existing workflow and the served step/settings catalog before constructing YAML. A repository planning workflow normally prepares the repository, then uses agent.run with read_only: true and a mission asking it to inspect the code and return a plan. Keep forge writes, commits, implementation steps and automatic implementation handoffs out of a planning-only workflow. The shipped feasibility workflow also closes issues or hands off after approval: it is not a planning-only template unchanged.
4. Save the definition. Test runs the draft once with forge writes/pushes skipped; commands and tools still run, so a test is not a side-effect-free simulation. Run starts the saved version. History, Performance and Runs show revisions and execution evidence.
5. Manual workflows need no automatic trigger. Bind an event creates an event binding from a captured example and maps payload fields to declared inputs. Existing bindings can be paused or removed. Playbooks are edited at /settings/playbooks; workflow calls/handoffs are edited in the workflow that invokes them. Built-in issue-label routes are marked Built-in; they cannot be removed in the event-binding editor. Disable the workflow to prevent automatic execution.
Other product operations:
- /tasks lists work and opens task details. Available actions depend on task state and permissions; read the served action vocabulary rather than guessing an action.
- /events covers captured events, event types, field mappings and bindings. A source, mapping and binding are different records. Removing a binding does not remove its source or mapping.
- /settings/status reports service health/configuration. For a status request, use the available status/health tool; a page listing does not check service health.
- Settings and workflow changes must go through the available control-plane tools or the dashboard. Navigation tools only open pages; they do not click controls or save changes. If no listed tool can perform a requested operation, explain the concrete UI steps without claiming to have changed anything.
+21 -7
View File
@@ -17,7 +17,6 @@ import (
// the code exchange, PKCE and token verification are the libraries'.
type Flow struct {
provider *Provider
verifier *Verifier
clientID string
clientSecret string
redirectURL string
@@ -34,7 +33,7 @@ func NewFlow(provider *Provider, clientID, clientSecret, redirectURL string) (*F
return nil, fmt.Errorf("oidc: redirect URL is required for the browser flow")
}
return &Flow{
provider: provider, verifier: NewVerifier(provider),
provider: provider,
clientID: clientID, clientSecret: clientSecret, redirectURL: redirectURL,
}, nil
}
@@ -65,15 +64,15 @@ func (f *Flow) AuthCodeURL(ctx context.Context, state string) (string, string, e
codeVerifier := oauth2.GenerateVerifier()
url := config.AuthCodeURL(state,
oauth2.S256ChallengeOption(codeVerifier),
oauth2.SetAuthURLParam("nonce", oauth2.S256ChallengeFromVerifier(codeVerifier)),
oauth2.SetAuthURLParam("audience", f.provider.audience),
)
return url, codeVerifier, nil
}
// Exchange completes the flow: it trades the code for the provider's tokens and
// verifies the access token through the same Verifier a presented token goes
// through. There is no second verification path here, so a token obtained by the
// browser cannot be accepted on terms a presented token would be refused on.
// verifies the ID token against the browser client and binds its nonce to the
// PKCE verifier. Access tokens are not proof of a browser login.
func (f *Flow) Exchange(ctx context.Context, code, codeVerifier string) (identity.ProviderSession, error) {
config, err := f.oauth(ctx)
if err != nil {
@@ -83,7 +82,22 @@ func (f *Flow) Exchange(ctx context.Context, code, codeVerifier string) (identit
if err != nil {
return identity.ProviderSession{}, fmt.Errorf("oidc: exchange code: %w", err)
}
credential, err := f.verifier.Verify(ctx, token.AccessToken)
rawIDToken, ok := token.Extra("id_token").(string)
if !ok || rawIDToken == "" {
return identity.ProviderSession{}, fmt.Errorf("oidc: provider returned no ID token")
}
discovered, err := f.provider.get(ctx)
if err != nil {
return identity.ProviderSession{}, err
}
verified, err := discovered.Verifier(&gooidc.Config{ClientID: f.clientID}).Verify(ctx, rawIDToken)
if err != nil {
return identity.ProviderSession{}, fmt.Errorf("oidc: verify ID token: %w", err)
}
if verified.Nonce != oauth2.S256ChallengeFromVerifier(codeVerifier) {
return identity.ProviderSession{}, fmt.Errorf("oidc: ID token nonce mismatch")
}
credential, err := NewVerifierForAudience(f.provider, f.clientID).Verify(ctx, rawIDToken)
if err != nil {
return identity.ProviderSession{}, err
}
@@ -91,5 +105,5 @@ func (f *Flow) Exchange(ctx context.Context, code, codeVerifier string) (identit
if credential.Expires.Before(expires) || expires.IsZero() {
expires = credential.Expires
}
return identity.ProviderSession{Credential: credential, Token: token.AccessToken, Expires: expires}, nil
return identity.ProviderSession{Credential: credential, Token: rawIDToken, Expires: expires}, nil
}
+88
View File
@@ -0,0 +1,88 @@
package oidc
import (
"crypto/rand"
"crypto/rsa"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/oauth2"
)
func TestBrowserFlowVerifiesIDToken(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, nonce, audience string
omit, expired bool
want bool
}{
{name: "verified ID token", nonce: oauth2.S256ChallengeFromVerifier("verifier"), audience: "browser-client", want: true},
{name: "nonce mismatch", nonce: "different", audience: "browser-client"},
{name: "wrong audience", nonce: oauth2.S256ChallengeFromVerifier("verifier"), audience: "other-client"},
{name: "missing ID token", omit: true},
{name: "expired ID token", nonce: oauth2.S256ChallengeFromVerifier("verifier"), audience: "browser-client", expired: true},
} {
t.Run(tc.name, func(t *testing.T) {
var provider *httptest.Server
provider = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/.well-known/openid-configuration":
_ = json.NewEncoder(w).Encode(map[string]any{"issuer": provider.URL, "authorization_endpoint": provider.URL + "/auth", "token_endpoint": provider.URL + "/token", "jwks_uri": provider.URL + "/keys", "id_token_signing_alg_values_supported": []string{"RS256"}})
case "/keys":
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []jose.JSONWebKey{{Key: &key.PublicKey, KeyID: "test", Algorithm: "RS256", Use: "sig"}}})
case "/token":
if err := r.ParseForm(); err != nil {
t.Error(err)
return
}
if r.Form.Get("code_verifier") != "verifier" {
t.Error("token exchange omitted PKCE verifier")
}
expires := time.Now().Add(time.Hour).Unix()
if tc.expired {
expires = time.Now().Add(-time.Hour).Unix()
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"iss": provider.URL, "aud": tc.audience, "sub": "alice", "nonce": tc.nonce, "iat": time.Now().Unix(), "exp": expires, "email": "alice@example.com", "email_verified": true})
token.Header["kid"] = "test"
raw, signErr := token.SignedString(key)
if signErr != nil {
t.Error(signErr)
return
}
body := map[string]any{"access_token": "opaque-access-token", "token_type": "Bearer", "expires_in": 3600}
if !tc.omit {
body["id_token"] = raw
}
_ = json.NewEncoder(w).Encode(body)
default:
http.NotFound(w, r)
}
}))
defer provider.Close()
configured, err := NewProvider(Config{Issuer: provider.URL, Audience: "resource-audience"})
if err != nil {
t.Fatal(err)
}
flow, err := NewFlow(configured, "browser-client", "", "https://archie.example/oauth2/callback")
if err != nil {
t.Fatal(err)
}
result, err := flow.Exchange(t.Context(), "code", "verifier")
if (err == nil) != tc.want {
t.Fatalf("accepted=%v want=%v err=%v", err == nil, tc.want, err)
}
if tc.want && (result.Credential.Subject.Subject != "alice" || result.Credential.Email != "alice@example.com" || result.Token == "opaque-access-token") {
t.Fatalf("unverified/wrong token became browser identity: %+v", result.Credential)
}
})
}
}
+12 -1
View File
@@ -73,6 +73,7 @@ func (p *Provider) Check(ctx context.Context) error {
// Verifier validates tokens against the provider's published signing keys.
type Verifier struct {
provider *Provider
audience string
}
// NewVerifier returns a verifier for provider's tokens.
@@ -91,7 +92,11 @@ func (v *Verifier) Verify(ctx context.Context, rawToken string) (identity.Creden
if err != nil {
return identity.Credential{}, err
}
verifier := discovered.Verifier(&gooidc.Config{ClientID: v.provider.audience})
audience := v.audience
if audience == "" {
audience = v.provider.audience
}
verifier := discovered.Verifier(&gooidc.Config{ClientID: audience})
token, err := verifier.Verify(ctx, strings.TrimSpace(rawToken))
if err != nil {
return identity.Credential{}, fmt.Errorf("oidc: verify: %w", err)
@@ -146,3 +151,9 @@ func scopesFor(scope string, scopes []string) []string {
}
return strings.Fields(scope)
}
// NewVerifierForAudience shares discovery and signing-key caches while checking
// the browser client's audience instead of a resource-server audience.
func NewVerifierForAudience(provider *Provider, audience string) *Verifier {
return &Verifier{provider: provider, audience: audience}
}
@@ -0,0 +1,97 @@
package postgres
import (
"context"
"crypto/rand"
"errors"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func (s *Store) OpenAccountSession(ctx context.Context, expires time.Time) (identity.AccountSession, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
row, err := s.queries().GetIdentity(ctx, string(p.IdentityID))
if err != nil {
return identity.AccountSession{}, err
}
value := identityFromRow(row)
if value.Kind != identity.KindUser || !value.CanAct() {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
result := identity.AccountSession{Identity: value, Token: rand.Text(), Expires: time.Now().UTC().Add(identity.AccountSessionLifetime)}
if expires.IsZero() || !expires.After(time.Now()) {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if expires.Before(result.Expires) {
result.Expires = expires
}
_, err = s.pool.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(result.Token), string(p.IdentityID), result.Expires)
return result, err
}
func (s *Store) RequireFreshAccountSession(ctx context.Context, token string) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.ErrCredentialRejected
}
var fresh bool
err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM account_sessions WHERE token_hash=$1 AND identity_id=$2 AND expires_at>now() AND issued_at>now()-interval '10 minutes')`, sessionHash(token), string(p.IdentityID)).Scan(&fresh)
if err != nil {
return err
}
if !fresh {
return identity.ErrCredentialRejected
}
return nil
}
func (s *Store) CreateAccountRecovery(ctx context.Context) (string, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return "", identity.ErrCredentialRejected
}
code := rand.Text() + rand.Text()
result, err := s.pool.Exec(ctx, `UPDATE accounts SET recovery_hash=$2 WHERE identity_id=$1`, string(p.IdentityID), sessionHash(code))
if err != nil {
return "", err
}
if result.RowsAffected() != 1 {
return "", identity.ErrNotFound
}
return code, nil
}
func (s *Store) RecoverAccount(ctx context.Context, email, code, password string) error {
if len(code) < 52 || len(code) > 128 {
return identity.ErrCredentialRejected
}
hash, err := identity.HashPassword(password)
if err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
var id string
err = tx.QueryRow(ctx, `UPDATE accounts a SET password_hash=$3,recovery_hash=NULL,failed_attempts=0,locked_until=NULL FROM identities i WHERE a.identity_id=i.id AND i.lifecycle='active' AND a.email=$1 AND a.recovery_hash=$2 RETURNING a.identity_id`, strings.ToLower(strings.TrimSpace(email)), sessionHash(code), hash).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return identity.ErrCredentialRejected
}
if err != nil {
return err
}
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, id); err != nil {
return err
}
return tx.Commit(ctx)
}
@@ -0,0 +1,286 @@
package postgres
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
func (s *Store) AccountSetupRequired(ctx context.Context) (bool, error) {
var required bool
err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT 1 FROM accounts)`).Scan(&required)
return required, err
}
func (s *Store) RegisterAccount(ctx context.Context, r identity.AccountRegistration, bootstrap bool) (identity.Identity, error) {
role, orgID, err := accountRegistrationScope(ctx, &r, bootstrap)
if err != nil {
return identity.Identity{}, err
}
hash, err := identity.HashPassword(r.Password)
if err != nil {
return identity.Identity{}, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
// Every registration shares this lock so only one transaction can bootstrap.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(484726231)`); err != nil {
return identity.Identity{}, err
}
var anyAccounts bool
if err = tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM accounts)`).Scan(&anyAccounts); err != nil {
return identity.Identity{}, err
}
if bootstrap && anyAccounts {
return identity.Identity{}, identity.ErrSetupComplete
}
if !bootstrap && !anyAccounts {
return identity.Identity{}, identity.ErrCredentialRejected
}
value, err := writeAccount(ctx, tx, r, bootstrap, orgID, role, hash)
if err != nil {
return identity.Identity{}, err
}
if err = tx.Commit(ctx); err != nil {
return identity.Identity{}, err
}
return value, nil
}
func writeAccount(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, bootstrap bool, orgID org.OrgID, role org.Role, hash string) (identity.Identity, error) {
id := identity.IdentityID(rand.Text())
if bootstrap {
id = identity.OperatorID()
}
value, err := identity.New(id, identity.KindUser, r.DisplayName)
if err != nil {
return identity.Identity{}, err
}
now := time.Now().UTC()
value.CreatedAt, value.UpdatedAt = now, now
if bootstrap {
if err := setupAccountOrganisation(ctx, tx, r, orgID, now); err != nil {
return identity.Identity{}, err
}
}
_, err = tx.Exec(ctx, `INSERT INTO identities (id,kind,display_name,lifecycle,version,created_at,updated_at) VALUES ($1,'user',$2,'active',1,$3,$3)
ON CONFLICT (id) DO UPDATE SET display_name=EXCLUDED.display_name, lifecycle='active',version=identities.version+1,updated_at=EXCLUDED.updated_at`, string(id), r.DisplayName, now)
if err != nil {
return identity.Identity{}, err
}
_, err = tx.Exec(ctx, `INSERT INTO accounts (identity_id,email,password_hash) VALUES ($1,$2,$3)`, string(id), r.Email, hash)
if err != nil {
var pgerr *pgconn.PgError
if errors.As(err, &pgerr) && pgerr.Code == "23505" {
return identity.Identity{}, identity.ErrConflict
}
return identity.Identity{}, err
}
_, err = tx.Exec(ctx, `INSERT INTO memberships (identity_id,org_id,role) VALUES ($1,$2,$3) ON CONFLICT (identity_id,org_id,(COALESCE(workspace_id,''))) DO UPDATE SET role=EXCLUDED.role`, string(id), string(orgID), string(role))
if err != nil {
return identity.Identity{}, err
}
actor := id
if p, ok := access.PrincipalFromContext(ctx); ok {
actor = p.IdentityID
}
err = insertIdentityEvent(ctx, postgresdb.New(tx), id, identity.Event{Type: "create", To: identity.LifecycleActive, DisplayName: r.DisplayName}, identity.Audit{ActorID: actor, Source: "accounts", RequestID: "account:" + rand.Text()}, now)
if err != nil {
return identity.Identity{}, err
}
return value, nil
}
func sessionHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func (s *Store) SignInAccount(ctx context.Context, email, password string) (identity.AccountSession, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return identity.AccountSession{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
var id, hash string
var attempts int
var locked *time.Time
err = tx.QueryRow(ctx, `SELECT identity_id,password_hash,failed_attempts,locked_until FROM accounts WHERE email=$1 FOR UPDATE`, strings.ToLower(strings.TrimSpace(email))).Scan(&id, &hash, &attempts, &locked)
if errors.Is(err, pgx.ErrNoRows) {
// An unknown email still pays the password hashing cost.
_, hashErr := identity.HashPassword("unknown account dummy password")
if hashErr != nil {
return identity.AccountSession{}, hashErr
}
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if err != nil {
return identity.AccountSession{}, err
}
valid := identity.VerifyPassword(password, hash)
if locked != nil && time.Now().Before(*locked) {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if !valid {
return identity.AccountSession{}, recordFailedAccountLogin(ctx, tx, id, attempts, locked)
}
row, err := postgresdb.New(tx).GetIdentity(ctx, id)
if err != nil {
return identity.AccountSession{}, err
}
value := identityFromRow(row)
if !value.CanAct() {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
token := rand.Text()
expires := time.Now().UTC().Add(identity.AccountSessionLifetime)
if _, err = tx.Exec(ctx, `UPDATE accounts SET failed_attempts=0,locked_until=NULL WHERE identity_id=$1`, id); err != nil {
return identity.AccountSession{}, err
}
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE expires_at<=now()`); err != nil {
return identity.AccountSession{}, err
}
if _, err = tx.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(token), id, expires); err != nil {
return identity.AccountSession{}, err
}
if err = tx.Commit(ctx); err != nil {
return identity.AccountSession{}, err
}
return identity.AccountSession{Identity: value, Token: token, Expires: expires}, nil
}
func (s *Store) ResolveAccountSession(ctx context.Context, token string) (identity.Identity, error) {
if len(token) < 26 || len(token) > 128 {
return identity.Identity{}, identity.ErrCredentialRejected
}
var id string
err := s.pool.QueryRow(ctx, `SELECT s.identity_id FROM account_sessions s JOIN identities i ON i.id=s.identity_id WHERE s.token_hash=$1 AND s.expires_at>now() AND i.lifecycle='active'`, sessionHash(token)).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrCredentialRejected
}
if err != nil {
return identity.Identity{}, err
}
row, err := s.queries().GetIdentity(ctx, id)
return identityFromRow(row), err
}
func (s *Store) SignOutAccount(ctx context.Context, token string) error {
_, err := s.pool.Exec(ctx, `DELETE FROM account_sessions WHERE token_hash=$1`, sessionHash(token))
return err
}
func (s *Store) ChangeAccountPassword(ctx context.Context, current, next string) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.ErrCredentialRejected
}
hash, err := identity.HashPassword(next)
if err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
var old string
err = tx.QueryRow(ctx, `SELECT password_hash FROM accounts WHERE identity_id=$1 FOR UPDATE`, string(p.IdentityID)).Scan(&old)
if errors.Is(err, pgx.ErrNoRows) {
return identity.ErrCredentialRejected
}
if err != nil {
return err
}
if !identity.VerifyPassword(current, old) {
return identity.ErrCredentialRejected
}
if _, err = tx.Exec(ctx, `UPDATE accounts SET password_hash=$2,failed_attempts=0,locked_until=NULL WHERE identity_id=$1`, string(p.IdentityID), hash); err != nil {
return err
}
if _, err = tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(p.IdentityID)); err != nil {
return err
}
return tx.Commit(ctx)
}
func accountRegistrationScope(ctx context.Context, r *identity.AccountRegistration, bootstrap bool) (org.Role, org.OrgID, error) {
if err := r.Validate(); err != nil {
return "", "", err
}
role := org.Role(r.Role)
orgID := org.OrgFromContext(ctx)
if bootstrap {
if err := validateAccountSetup(r); err != nil {
return "", "", err
}
return org.RoleOwner, org.DefaultOrgID, nil
}
p, ok := access.PrincipalFromContext(ctx)
if !ok || p.Org != orgID {
return "", "", identity.ErrCredentialRejected
}
if role != org.RoleAdmin && role != org.RoleDeveloper && role != org.RoleViewer {
return "", "", identity.ErrInvalid
}
return role, orgID, nil
}
func recordFailedAccountLogin(ctx context.Context, tx pgx.Tx, id string, attempts int, locked *time.Time) error {
if locked != nil {
attempts = 0
}
if _, err := tx.Exec(ctx, `UPDATE accounts SET failed_attempts=$2,locked_until=CASE WHEN $2>=5 THEN now()+interval '15 minutes' ELSE NULL END WHERE identity_id=$1`, id, attempts+1); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return err
}
return identity.ErrCredentialRejected
}
func setupAccountOrganisation(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, orgID org.OrgID, now time.Time) error {
_, err := tx.Exec(ctx, `UPDATE orgs SET name=$1, updated_at=$2 WHERE id=$3`, r.OrganisationName, now, string(orgID))
if err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE workspaces SET name=$1,updated_at=$2 WHERE org_id=$3 AND id=$4`, r.WorkspaceName, now, string(orgID), string(org.DefaultWorkspaceID)); err != nil {
return err
}
if _, err := tx.Exec(ctx, `INSERT INTO authentication_settings (public_url) VALUES ($1)`, r.PublicURL); err != nil {
return err
}
return nil
}
func validateAccountSetup(r *identity.AccountRegistration) error {
r.OrganisationName = strings.TrimSpace(r.OrganisationName)
r.WorkspaceName = strings.TrimSpace(r.WorkspaceName)
r.PublicURL = strings.TrimRight(r.PublicURL, "/")
if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 {
return identity.ErrInvalid
}
if r.OrganisationName == "" || len(r.OrganisationName) > 200 {
return fmt.Errorf("%w: organisation name is required", identity.ErrInvalid)
}
return (identity.AuthenticationSettings{PublicURL: r.PublicURL}).Validate()
}
@@ -0,0 +1,41 @@
package postgres
import (
"context"
"errors"
"strings"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func (s *Store) AuthenticationSettings(ctx context.Context) (identity.AuthenticationSettings, error) {
var value identity.AuthenticationSettings
err := s.pool.QueryRow(ctx, `SELECT public_url,oidc_issuer,oidc_audience,oidc_client_id FROM authentication_settings WHERE singleton`).Scan(&value.PublicURL, &value.OIDCIssuer, &value.OIDCAudience, &value.OIDCClientID)
if errors.Is(err, pgx.ErrNoRows) {
return value, nil
}
return value, err
}
func (s *Store) SaveAuthenticationSettings(ctx context.Context, value identity.AuthenticationSettings) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok || !p.InstanceAdmin() {
return identity.ErrCredentialRejected
}
value.PublicURL = strings.TrimRight(value.PublicURL, "/")
if err := value.Validate(); err != nil {
return err
}
// The relying-party origin cannot silently change and orphan enrolled keys.
command, err := s.pool.Exec(ctx, `UPDATE authentication_settings SET public_url=$1,oidc_issuer=$2,oidc_audience=$3,oidc_client_id=$4 WHERE singleton AND (public_url=$1 OR NOT EXISTS (SELECT 1 FROM passkeys))`, value.PublicURL, value.OIDCIssuer, value.OIDCAudience, value.OIDCClientID)
if err != nil {
return err
}
if command.RowsAffected() != 1 {
return identity.ErrInvalid
}
return nil
}
@@ -185,6 +185,11 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
if n != 1 {
return identity.Identity{}, identity.ErrConflict
}
if next.Lifecycle != identity.LifecycleActive {
if _, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id)); err != nil {
return identity.Identity{}, err
}
}
if command.Type == identity.CommandRename {
if err := q.InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{
Alias: next.DisplayName, IdentityID: string(id),
@@ -0,0 +1,49 @@
-- +goose Up
CREATE TABLE accounts (
identity_id text PRIMARY KEY REFERENCES identities(id),
email text NOT NULL UNIQUE CHECK (email = lower(email)),
password_hash text NOT NULL,
recovery_hash text,
failed_attempts integer NOT NULL DEFAULT 0,
locked_until timestamptz
);
CREATE TABLE account_sessions (
token_hash text PRIMARY KEY,
identity_id text NOT NULL REFERENCES identities(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
issued_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX account_sessions_identity ON account_sessions(identity_id);
CREATE INDEX account_sessions_expiry ON account_sessions(expires_at);
CREATE TABLE authentication_settings (
singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
public_url text NOT NULL,
oidc_issuer text NOT NULL DEFAULT '',
oidc_audience text NOT NULL DEFAULT '',
oidc_client_id text NOT NULL DEFAULT ''
);
CREATE TABLE passkeys (
credential_id text PRIMARY KEY,
identity_id text NOT NULL REFERENCES identities(id),
name text NOT NULL,
credential jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX passkeys_identity ON passkeys(identity_id);
CREATE TABLE passkey_ceremonies (
token_hash text PRIMARY KEY,
identity_id text NOT NULL,
registration boolean NOT NULL,
session_data jsonb NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE INDEX passkey_ceremonies_expiry ON passkey_ceremonies(expires_at);
-- +goose Down
DROP TABLE passkey_ceremonies;
DROP TABLE passkeys;
DROP TABLE authentication_settings;
DROP TABLE account_sessions;
DROP TABLE accounts;
@@ -0,0 +1,264 @@
package postgres
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"net"
"net/url"
"strings"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
type passkeyUser struct {
value identity.Identity
credentials []webauthn.Credential
}
func (u passkeyUser) WebAuthnID() []byte { return []byte(u.value.ID) }
func (u passkeyUser) WebAuthnName() string { return u.value.DisplayName }
func (u passkeyUser) WebAuthnDisplayName() string { return u.value.DisplayName }
func (u passkeyUser) WebAuthnCredentials() []webauthn.Credential { return u.credentials }
func (s *Store) webAuthn(ctx context.Context) (*webauthn.WebAuthn, error) {
settings, err := s.AuthenticationSettings(ctx)
if err != nil {
return nil, err
}
u, err := url.Parse(settings.PublicURL)
secure := err == nil && (u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "localhost"))
if !secure || u.Hostname() == "" || net.ParseIP(u.Hostname()) != nil {
return nil, identity.ErrInvalid
}
return webauthn.New(&webauthn.Config{RPDisplayName: "Archie", RPID: u.Hostname(), RPOrigins: []string{strings.TrimRight(settings.PublicURL, "/")}, AuthenticatorSelection: protocol.AuthenticatorSelection{UserVerification: protocol.VerificationRequired, ResidentKey: protocol.ResidentKeyRequirementRequired}})
}
func loadPasskeyUser(ctx context.Context, q *postgresdb.Queries, db interface {
Query(context.Context, string, ...any) (pgx.Rows, error)
}, id string,
) (passkeyUser, error) {
row, err := q.GetIdentity(ctx, id)
if err != nil {
return passkeyUser{}, err
}
user := passkeyUser{value: identityFromRow(row)}
if user.value.Kind != identity.KindUser || !user.value.CanAct() {
return passkeyUser{}, identity.ErrCredentialRejected
}
rows, err := db.Query(ctx, `SELECT credential FROM passkeys WHERE identity_id=$1`, id)
if err != nil {
return passkeyUser{}, err
}
defer rows.Close()
for rows.Next() {
var data []byte
if err = rows.Scan(&data); err != nil {
return passkeyUser{}, err
}
var credential webauthn.Credential
if err = json.Unmarshal(data, &credential); err != nil {
return passkeyUser{}, err
}
user.credentials = append(user.credentials, credential)
}
return user, rows.Err()
}
func (s *Store) BeginPasskey(ctx context.Context, registration bool) (identity.PasskeyCeremony, error) {
wa, err := s.webAuthn(ctx)
if err != nil {
return identity.PasskeyCeremony{}, err
}
var options any
var session *webauthn.SessionData
var owner string
if registration {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.PasskeyCeremony{}, identity.ErrCredentialRejected
}
owner = string(p.IdentityID)
user, loadErr := loadPasskeyUser(ctx, s.queries(), s.pool, owner)
if loadErr != nil {
return identity.PasskeyCeremony{}, loadErr
}
options, session, err = wa.BeginRegistration(user)
} else {
options, session, err = wa.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))
}
if err != nil {
return identity.PasskeyCeremony{}, err
}
data, err := json.Marshal(session)
if err != nil {
return identity.PasskeyCeremony{}, err
}
encoded, err := json.Marshal(options)
if err != nil {
return identity.PasskeyCeremony{}, err
}
token := rand.Text()
if _, err = s.pool.Exec(ctx, `DELETE FROM passkey_ceremonies WHERE expires_at<=now()`); err != nil {
return identity.PasskeyCeremony{}, err
}
_, err = s.pool.Exec(ctx, `INSERT INTO passkey_ceremonies (token_hash,identity_id,registration,session_data,expires_at) VALUES ($1,$2,$3,$4,now()+interval '5 minutes')`, sessionHash(token), owner, registration, data)
return identity.PasskeyCeremony{Token: token, Options: encoded}, err
}
func (s *Store) FinishPasskey(ctx context.Context, token string, response []byte, registration bool, name string) (identity.AccountSession, error) {
wa, err := s.webAuthn(ctx)
if err != nil {
return identity.AccountSession{}, err
}
var owner string
var data []byte
// Consume before verification: failed and successful attempts are single-use.
err = s.pool.QueryRow(ctx, `DELETE FROM passkey_ceremonies WHERE token_hash=$1 AND registration=$2 AND expires_at>now() RETURNING identity_id,session_data`, sessionHash(token), registration).Scan(&owner, &data)
if errors.Is(err, pgx.ErrNoRows) {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
if err != nil {
return identity.AccountSession{}, err
}
var session webauthn.SessionData
if err = json.Unmarshal(data, &session); err != nil {
return identity.AccountSession{}, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return identity.AccountSession{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
credential, user, err := verifyPasskey(ctx, tx, wa, owner, session, response, registration)
if err != nil || credential == nil || credential.Authenticator.CloneWarning {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
owner = string(user.value.ID)
if err := persistPasskey(ctx, tx, credential, owner, name, registration); err != nil {
return identity.AccountSession{}, err
}
result := identity.AccountSession{Identity: user.value}
if !registration {
result.Token = rand.Text()
result.Expires = time.Now().UTC().Add(identity.AccountSessionLifetime)
_, err = tx.Exec(ctx, `INSERT INTO account_sessions (token_hash,identity_id,expires_at) VALUES ($1,$2,$3)`, sessionHash(result.Token), owner, result.Expires)
if err != nil {
return identity.AccountSession{}, err
}
}
if err = tx.Commit(ctx); err != nil {
return identity.AccountSession{}, err
}
return result, nil
}
func (s *Store) ListPasskeys(ctx context.Context) ([]identity.Passkey, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return nil, identity.ErrCredentialRejected
}
rows, err := s.pool.Query(ctx, `SELECT credential_id,name FROM passkeys WHERE identity_id=$1 ORDER BY created_at`, string(p.IdentityID))
if err != nil {
return nil, err
}
defer rows.Close()
out := []identity.Passkey{}
for rows.Next() {
var value identity.Passkey
if err = rows.Scan(&value.ID, &value.Name); err != nil {
return nil, err
}
out = append(out, value)
}
return out, rows.Err()
}
func (s *Store) DeletePasskey(ctx context.Context, id string) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return identity.ErrCredentialRejected
}
result, err := s.pool.Exec(ctx, `DELETE FROM passkeys WHERE credential_id=$1 AND identity_id=$2`, id, string(p.IdentityID))
if err != nil {
return err
}
if result.RowsAffected() != 1 {
return identity.ErrNotFound
}
return nil
}
func verifyPasskey(ctx context.Context, tx pgx.Tx, wa *webauthn.WebAuthn, owner string, session webauthn.SessionData, response []byte, registration bool) (*webauthn.Credential, passkeyUser, error) {
if registration {
return verifyPasskeyRegistration(ctx, tx, wa, owner, session, response)
}
var user passkeyUser
parsed, err := protocol.ParseCredentialRequestResponseBytes(response)
if err != nil {
return nil, user, identity.ErrCredentialRejected
}
credential, err := wa.ValidateDiscoverableLogin(func(rawID, userHandle []byte) (webauthn.User, error) {
if err = tx.QueryRow(ctx, `SELECT identity_id FROM passkeys WHERE credential_id=$1 FOR UPDATE`, base64.RawURLEncoding.EncodeToString(rawID)).Scan(&owner); err != nil {
return nil, identity.ErrCredentialRejected
}
if owner != string(userHandle) {
return nil, identity.ErrCredentialRejected
}
user, err = loadPasskeyUser(ctx, postgresdb.New(tx), tx, owner)
return user, err
}, session, parsed)
return credential, user, err
}
func verifyPasskeyRegistration(ctx context.Context, tx pgx.Tx, wa *webauthn.WebAuthn, owner string, session webauthn.SessionData, response []byte) (*webauthn.Credential, passkeyUser, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok || string(p.IdentityID) != owner {
return nil, passkeyUser{}, identity.ErrCredentialRejected
}
user, err := loadPasskeyUser(ctx, postgresdb.New(tx), tx, owner)
if err != nil {
return nil, user, err
}
parsed, err := protocol.ParseCredentialCreationResponseBytes(response)
if err != nil {
return nil, user, identity.ErrCredentialRejected
}
credential, err := wa.CreateCredential(user, session, parsed)
return credential, user, err
}
func persistPasskey(ctx context.Context, tx pgx.Tx, credential *webauthn.Credential, owner, name string, registration bool) error {
encoded, err := json.Marshal(credential)
if err != nil {
return err
}
credentialID := base64.RawURLEncoding.EncodeToString(credential.ID)
if registration {
name = strings.TrimSpace(name)
if name == "" {
name = "Passkey"
}
if len(name) > 200 {
return identity.ErrInvalid
}
_, err = tx.Exec(ctx, `INSERT INTO passkeys (credential_id,identity_id,name,credential) VALUES ($1,$2,$3,$4)`, credentialID, owner, name, encoded)
} else {
_, err = tx.Exec(ctx, `UPDATE passkeys SET credential=$2 WHERE credential_id=$1`, credentialID, encoded)
}
if err != nil {
return err
}
return nil
}
@@ -558,6 +558,11 @@ ON CONFLICT (session_id) DO UPDATE SET
created_at = EXCLUDED.created_at,
last_active_at = EXCLUDED.last_active_at
WHERE sessions.org_id = EXCLUDED.org_id
AND (
(sessions.platform = '' AND sessions.bot_user = '' AND sessions.channel_id = '' AND sessions.thread_id = '')
OR (sessions.platform = EXCLUDED.platform AND sessions.bot_user = EXCLUDED.bot_user
AND sessions.channel_id = EXCLUDED.channel_id AND sessions.thread_id = EXCLUDED.thread_id)
)
`
type SaveSessionParams struct {
@@ -577,8 +582,9 @@ type SaveSessionParams struct {
// Gateway conversation queries: sessions, messages, turns, full-text search.
// These back internal/gateway's PostgreSQL SessionStore.
// ── Sessions ────────────────────────────────────────────────────────────────
// Updates only a session the writing org owns: another org's session of the
// same id is left untouched and the zero row count refuses the write.
// A saved session keeps its organization and conversation identity. Empty
// placeholder rows may be completed; an existing conversation cannot be claimed
// by overwriting its source with another person's thread.
func (q *Queries) SaveSession(ctx context.Context, arg SaveSessionParams) (int64, error) {
result, err := q.db.Exec(ctx, saveSession,
arg.SessionID,
@@ -44,6 +44,22 @@ type AccessPolicyVersion struct {
UpdatedAt time.Time
}
type Account struct {
IdentityID string
Email string
PasswordHash string
RecoveryHash pgtype.Text
FailedAttempts int32
LockedUntil pgtype.Timestamptz
}
type AccountSession struct {
TokenHash string
IdentityID string
ExpiresAt time.Time
IssuedAt time.Time
}
type Alert struct {
ID int64
OrgID string
@@ -89,6 +105,14 @@ type ApplyStatus struct {
ReportedAt time.Time
}
type AuthenticationSetting struct {
Singleton bool
PublicUrl string
OidcIssuer string
OidcAudience string
OidcClientID string
}
type Binding struct {
ID string
Name string
@@ -344,6 +368,22 @@ type OrgUpgrade struct {
CompletedAt time.Time
}
type Passkey struct {
CredentialID string
IdentityID string
Name string
Credential []byte
CreatedAt time.Time
}
type PasskeyCeremony struct {
TokenHash string
IdentityID string
Registration bool
SessionData []byte
ExpiresAt time.Time
}
type PlaybookDispatch struct {
PlaybookID string
PlaybookVersion string
@@ -4,8 +4,9 @@
-- ── Sessions ────────────────────────────────────────────────────────────────
-- name: SaveSession :execrows
-- Updates only a session the writing org owns: another org's session of the
-- same id is left untouched and the zero row count refuses the write.
-- A saved session keeps its organization and conversation identity. Empty
-- placeholder rows may be completed; an existing conversation cannot be claimed
-- by overwriting its source with another person's thread.
INSERT INTO sessions (session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
@@ -19,7 +20,12 @@ ON CONFLICT (session_id) DO UPDATE SET
branch_name = EXCLUDED.branch_name,
created_at = EXCLUDED.created_at,
last_active_at = EXCLUDED.last_active_at
WHERE sessions.org_id = EXCLUDED.org_id;
WHERE sessions.org_id = EXCLUDED.org_id
AND (
(sessions.platform = '' AND sessions.bot_user = '' AND sessions.channel_id = '' AND sessions.thread_id = '')
OR (sessions.platform = EXCLUDED.platform AND sessions.bot_user = EXCLUDED.bot_user
AND sessions.channel_id = EXCLUDED.channel_id AND sessions.thread_id = EXCLUDED.thread_id)
);
-- name: ClaimSession :exec
-- A write to a session no row names yet makes the writing org its owner.
@@ -0,0 +1,86 @@
package staterpc
import (
"context"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func (s *server) accountSecurity() (identity.AccountSecurity, error) {
store, ok := s.deps.Accounts.(identity.AccountSecurity)
if !ok {
return nil, status.Error(codes.Unavailable, "account security unavailable")
}
return store, nil
}
func (s *server) OpenAccountSession(ctx context.Context, r *pb.OpenAccountSessionRequest) (*pb.OpenAccountSessionResponse, error) {
store, err := s.accountSecurity()
if err != nil {
return nil, err
}
value, err := store.OpenAccountSession(ctx, timeValue(r.ExpiresAt))
if err != nil {
return nil, accountStatus(err)
}
return &pb.OpenAccountSessionResponse{Identity: identityProto(value.Identity), Token: value.Token, ExpiresAt: timestamp(value.Expires)}, nil
}
func (s *server) RequireFreshAccountSession(ctx context.Context, r *pb.RequireFreshAccountSessionRequest) (*pb.RequireFreshAccountSessionResponse, error) {
store, err := s.accountSecurity()
if err != nil {
return nil, err
}
return &pb.RequireFreshAccountSessionResponse{}, accountStatus(store.RequireFreshAccountSession(ctx, r.Token))
}
func (s *server) CreateAccountRecovery(ctx context.Context, _ *pb.CreateAccountRecoveryRequest) (*pb.CreateAccountRecoveryResponse, error) {
store, err := s.accountSecurity()
if err != nil {
return nil, err
}
code, err := store.CreateAccountRecovery(ctx)
if err != nil {
return nil, accountStatus(err)
}
return &pb.CreateAccountRecoveryResponse{Code: code}, nil
}
func (s *server) RecoverAccount(ctx context.Context, r *pb.RecoverAccountRequest) (*pb.RecoverAccountResponse, error) {
store, err := s.accountSecurity()
if err != nil {
return nil, err
}
return &pb.RecoverAccountResponse{}, accountStatus(store.RecoverAccount(ctx, r.Email, r.Code, r.Password))
}
func (c *Client) OpenAccountSession(ctx context.Context, expires time.Time) (identity.AccountSession, error) {
r, err := c.client.OpenAccountSession(ctx, &pb.OpenAccountSessionRequest{ExpiresAt: timestamp(expires)})
if err != nil {
return identity.AccountSession{}, accountClientError(err)
}
return identity.AccountSession{Identity: identityValue(r.Identity), Token: r.Token, Expires: timeValue(r.ExpiresAt)}, nil
}
func (c *Client) RequireFreshAccountSession(ctx context.Context, token string) error {
_, err := c.client.RequireFreshAccountSession(ctx, &pb.RequireFreshAccountSessionRequest{Token: token})
return accountClientError(err)
}
func (c *Client) CreateAccountRecovery(ctx context.Context) (string, error) {
r, err := c.client.CreateAccountRecovery(ctx, &pb.CreateAccountRecoveryRequest{})
if err != nil {
return "", accountClientError(err)
}
return r.Code, nil
}
func (c *Client) RecoverAccount(ctx context.Context, email, code, password string) error {
_, err := c.client.RecoverAccount(ctx, &pb.RecoverAccountRequest{Email: email, Code: code, Password: password})
return accountClientError(err)
}
@@ -0,0 +1,170 @@
package staterpc
import (
"context"
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
)
func accountStatus(err error) error {
if err == nil {
return nil
}
switch {
case errors.Is(err, identity.ErrSetupComplete):
return status.Error(codes.AlreadyExists, identity.ErrSetupComplete.Error())
case errors.Is(err, identity.ErrCredentialRejected):
return status.Error(codes.Unauthenticated, "credentials not accepted")
default:
return identityStatus(err)
}
}
func accountClientError(err error) error {
switch status.Code(err) {
case codes.AlreadyExists:
return identity.ErrSetupComplete
case codes.Unauthenticated:
return identity.ErrCredentialRejected
default:
return identityClientError(err)
}
}
func (s *server) accountStore() (identity.Accounts, error) {
if s.deps.Accounts == nil {
return nil, status.Error(codes.Unavailable, "accounts unavailable")
}
return s.deps.Accounts, nil
}
func (s *server) AccountSetup(ctx context.Context, _ *pb.AccountSetupRequest) (*pb.AccountSetupResponse, error) {
store, err := s.accountStore()
if err != nil {
return nil, err
}
required, err := store.AccountSetupRequired(ctx)
return &pb.AccountSetupResponse{Required: required}, accountStatus(err)
}
func (s *server) RegisterAccount(ctx context.Context, r *pb.RegisterAccountRequest) (*pb.RegisterAccountResponse, error) {
store, err := s.accountStore()
if err != nil {
return nil, err
}
if !r.Bootstrap {
if err := s.authorizeAccountManagement(ctx); err != nil {
return nil, err
}
}
value, err := store.RegisterAccount(ctx, identity.AccountRegistration{Email: r.Email, DisplayName: r.DisplayName, Password: r.Password, Role: r.Role, OrganisationName: r.OrganisationName, WorkspaceName: r.WorkspaceName, PublicURL: r.PublicUrl}, r.Bootstrap)
if err != nil {
return nil, accountStatus(err)
}
return &pb.RegisterAccountResponse{Identity: identityProto(value)}, nil
}
func (s *server) SignInAccount(ctx context.Context, r *pb.SignInAccountRequest) (*pb.SignInAccountResponse, error) {
store, err := s.accountStore()
if err != nil {
return nil, err
}
value, err := store.SignInAccount(ctx, r.Email, r.Password)
if err != nil {
return nil, accountStatus(err)
}
return &pb.SignInAccountResponse{Identity: identityProto(value.Identity), Token: value.Token, ExpiresAt: timestamp(value.Expires)}, nil
}
func (s *server) ResolveAccountSession(ctx context.Context, r *pb.ResolveAccountSessionRequest) (*pb.ResolveAccountSessionResponse, error) {
store, err := s.accountStore()
if err != nil {
return nil, err
}
value, err := store.ResolveAccountSession(ctx, r.Token)
if err != nil {
return nil, accountStatus(err)
}
return &pb.ResolveAccountSessionResponse{Identity: identityProto(value)}, nil
}
func (s *server) SignOutAccount(ctx context.Context, r *pb.SignOutAccountRequest) (*pb.SignOutAccountResponse, error) {
store, err := s.accountStore()
if err != nil {
return nil, err
}
return &pb.SignOutAccountResponse{}, accountStatus(store.SignOutAccount(ctx, r.Token))
}
func (s *server) ChangeAccountPassword(ctx context.Context, r *pb.ChangeAccountPasswordRequest) (*pb.ChangeAccountPasswordResponse, error) {
store, err := s.accountStore()
if err != nil {
return nil, err
}
return &pb.ChangeAccountPasswordResponse{}, accountStatus(store.ChangeAccountPassword(ctx, r.CurrentPassword, r.NewPassword))
}
func (c *Client) AccountSetupRequired(ctx context.Context) (bool, error) {
r, err := c.client.AccountSetup(ctx, &pb.AccountSetupRequest{})
return r.GetRequired(), accountClientError(err)
}
func (c *Client) RegisterAccount(ctx context.Context, r identity.AccountRegistration, bootstrap bool) (identity.Identity, error) {
out, err := c.client.RegisterAccount(ctx, &pb.RegisterAccountRequest{Email: r.Email, DisplayName: r.DisplayName, Password: r.Password, Role: r.Role, Bootstrap: bootstrap, OrganisationName: r.OrganisationName, WorkspaceName: r.WorkspaceName, PublicUrl: r.PublicURL})
if err != nil {
return identity.Identity{}, accountClientError(err)
}
return identityValue(out.Identity), nil
}
func (c *Client) SignInAccount(ctx context.Context, email, password string) (identity.AccountSession, error) {
r, err := c.client.SignInAccount(ctx, &pb.SignInAccountRequest{Email: email, Password: password})
if err != nil {
return identity.AccountSession{}, accountClientError(err)
}
return identity.AccountSession{Identity: identityValue(r.Identity), Token: r.Token, Expires: timeValue(r.ExpiresAt)}, nil
}
func (c *Client) ResolveAccountSession(ctx context.Context, token string) (identity.Identity, error) {
r, err := c.client.ResolveAccountSession(ctx, &pb.ResolveAccountSessionRequest{Token: token})
if err != nil {
return identity.Identity{}, accountClientError(err)
}
return identityValue(r.Identity), nil
}
func (c *Client) SignOutAccount(ctx context.Context, token string) error {
_, err := c.client.SignOutAccount(ctx, &pb.SignOutAccountRequest{Token: token})
return accountClientError(err)
}
func (c *Client) ChangeAccountPassword(ctx context.Context, current, next string) error {
_, err := c.client.ChangeAccountPassword(ctx, &pb.ChangeAccountPasswordRequest{CurrentPassword: current, NewPassword: next})
return accountClientError(err)
}
func (s *server) authorizeAccountManagement(ctx context.Context) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return status.Error(codes.PermissionDenied, "account management requires a principal")
}
if s.deps.Policies == nil {
return status.Error(codes.Unavailable, "access policies unavailable")
}
policies, err := s.deps.Policies.ListPolicies(access.WithoutPrincipal(ctx))
if err != nil {
return status.Error(codes.Unavailable, "access policies unavailable")
}
decision := infraaccess.New(policies).Authorize(p, access.ActionManageMembers, access.Resource{Kind: access.KindMember, Org: p.Org}, access.Context{})
if !decision.Allowed {
return status.Error(codes.PermissionDenied, "account management refused")
}
return nil
}
@@ -0,0 +1,88 @@
package staterpc
import (
"context"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
type accountPolicyStore struct {
access.PolicyStore
policies []access.Policy
}
func (s accountPolicyStore) ListPolicies(context.Context) ([]access.Policy, error) {
return s.policies, nil
}
type accountRegistrationStore struct{ identity.Accounts }
func (accountRegistrationStore) RegisterAccount(context.Context, identity.AccountRegistration, bool) (identity.Identity, error) {
return identity.Identity{ID: "created"}, nil
}
func TestAccountManagementUsesPolicy(t *testing.T) {
for _, tc := range []struct {
name string
role org.Role
extra string
anonymous bool
want codes.Code
}{
{name: "administrator relationship permits", role: org.RoleAdmin, want: codes.OK},
{name: "developer has no grant", role: org.RoleDeveloper, want: codes.PermissionDenied},
{name: "explicit identity policy permits without admin role", role: org.RoleDeveloper, extra: `permit(principal == Archie::Identity::"alice", action == Archie::Action::"manage_members", resource);`, want: codes.OK},
{name: "explicit forbid wins over admin role", role: org.RoleAdmin, extra: `forbid(principal,action == Archie::Action::"manage_members",resource);`, want: codes.PermissionDenied},
{name: "unauthenticated service has no user grant", anonymous: true, want: codes.PermissionDenied},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := t.Context()
if !tc.anonymous {
ctx = access.WithPrincipal(ctx, access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: tc.role}}})
}
policies := access.ShippedOrgPolicies("acme")
if tc.extra != "" {
policies = append(policies, access.Policy{ID: "custom-members", Level: access.LevelOrg, OrgID: "acme", Text: tc.extra})
}
srv := &server{deps: Deps{Accounts: accountRegistrationStore{}, Policies: accountPolicyStore{policies: policies}}}
_, err := srv.RegisterAccount(ctx, &pb.RegisterAccountRequest{Email: "new@example.com", Role: "viewer"})
if got := status.Code(err); got != tc.want {
t.Fatalf("code=%s want=%s err=%v", got, tc.want, err)
}
})
}
}
func TestTaskCredentialsCannotManageAccounts(t *testing.T) {
for _, method := range []string{
pb.StateStoreService_AccountSetup_FullMethodName,
pb.StateStoreService_RegisterAccount_FullMethodName,
pb.StateStoreService_SignInAccount_FullMethodName,
pb.StateStoreService_ResolveAccountSession_FullMethodName,
pb.StateStoreService_SignOutAccount_FullMethodName,
pb.StateStoreService_ChangeAccountPassword_FullMethodName,
pb.StateStoreService_GetAuthenticationSettings_FullMethodName,
pb.StateStoreService_SaveAuthenticationSettings_FullMethodName,
pb.StateStoreService_BeginPasskey_FullMethodName,
pb.StateStoreService_FinishPasskey_FullMethodName,
pb.StateStoreService_ListPasskeys_FullMethodName,
pb.StateStoreService_DeletePasskey_FullMethodName,
pb.StateStoreService_OpenAccountSession_FullMethodName,
pb.StateStoreService_RequireFreshAccountSession_FullMethodName,
pb.StateStoreService_CreateAccountRecovery_FullMethodName,
pb.StateStoreService_RecoverAccount_FullMethodName,
} {
t.Run(method, func(t *testing.T) {
if authorizesTaskScopedCall(method, nil, 7) {
t.Fatal("task credential authorizes account operation")
}
})
}
}
@@ -0,0 +1,141 @@
package staterpc
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func authenticationProto(v identity.AuthenticationSettings) *pb.AuthenticationSettings {
return &pb.AuthenticationSettings{PublicUrl: v.PublicURL, OidcIssuer: v.OIDCIssuer, OidcAudience: v.OIDCAudience, OidcClientId: v.OIDCClientID}
}
func authenticationValue(v *pb.AuthenticationSettings) identity.AuthenticationSettings {
return identity.AuthenticationSettings{PublicURL: v.GetPublicUrl(), OIDCIssuer: v.GetOidcIssuer(), OIDCAudience: v.GetOidcAudience(), OIDCClientID: v.GetOidcClientId()}
}
func (s *server) GetAuthenticationSettings(ctx context.Context, _ *pb.GetAuthenticationSettingsRequest) (*pb.GetAuthenticationSettingsResponse, error) {
store, ok := s.deps.Accounts.(identity.AuthenticationSettingsStore)
if !ok {
return nil, status.Error(codes.Unavailable, "authentication settings unavailable")
}
value, err := store.AuthenticationSettings(ctx)
if err != nil {
return nil, accountStatus(err)
}
return &pb.GetAuthenticationSettingsResponse{Settings: authenticationProto(value)}, nil
}
func (s *server) SaveAuthenticationSettings(ctx context.Context, r *pb.SaveAuthenticationSettingsRequest) (*pb.SaveAuthenticationSettingsResponse, error) {
store, ok := s.deps.Accounts.(identity.AuthenticationSettingsStore)
if !ok {
return nil, status.Error(codes.Unavailable, "authentication settings unavailable")
}
return &pb.SaveAuthenticationSettingsResponse{}, accountStatus(store.SaveAuthenticationSettings(ctx, authenticationValue(r.Settings)))
}
func (c *Client) AuthenticationSettings(ctx context.Context) (identity.AuthenticationSettings, error) {
r, err := c.client.GetAuthenticationSettings(ctx, &pb.GetAuthenticationSettingsRequest{})
if err != nil {
return identity.AuthenticationSettings{}, accountClientError(err)
}
return authenticationValue(r.Settings), nil
}
func (c *Client) SaveAuthenticationSettings(ctx context.Context, v identity.AuthenticationSettings) error {
_, err := c.client.SaveAuthenticationSettings(ctx, &pb.SaveAuthenticationSettingsRequest{Settings: authenticationProto(v)})
return accountClientError(err)
}
func (s *server) passkeyStore() (identity.Passkeys, error) {
v, ok := s.deps.Accounts.(identity.Passkeys)
if !ok {
return nil, status.Error(codes.Unavailable, "passkeys unavailable")
}
return v, nil
}
func (s *server) BeginPasskey(ctx context.Context, r *pb.BeginPasskeyRequest) (*pb.BeginPasskeyResponse, error) {
store, err := s.passkeyStore()
if err != nil {
return nil, err
}
value, err := store.BeginPasskey(ctx, r.Registration)
if err != nil {
return nil, accountStatus(err)
}
return &pb.BeginPasskeyResponse{Token: value.Token, Options: value.Options}, nil
}
func (s *server) FinishPasskey(ctx context.Context, r *pb.FinishPasskeyRequest) (*pb.FinishPasskeyResponse, error) {
store, err := s.passkeyStore()
if err != nil {
return nil, err
}
value, err := store.FinishPasskey(ctx, r.Token, r.Credential, r.Registration, r.Name)
if err != nil {
return nil, accountStatus(err)
}
return &pb.FinishPasskeyResponse{Identity: identityProto(value.Identity), Token: value.Token, ExpiresAt: timestamp(value.Expires)}, nil
}
func (s *server) ListPasskeys(ctx context.Context, _ *pb.ListPasskeysRequest) (*pb.ListPasskeysResponse, error) {
store, err := s.passkeyStore()
if err != nil {
return nil, err
}
values, err := store.ListPasskeys(ctx)
if err != nil {
return nil, accountStatus(err)
}
out := &pb.ListPasskeysResponse{}
for _, value := range values {
out.Passkeys = append(out.Passkeys, &pb.Passkey{Id: value.ID, Name: value.Name})
}
return out, nil
}
func (s *server) DeletePasskey(ctx context.Context, r *pb.DeletePasskeyRequest) (*pb.DeletePasskeyResponse, error) {
store, err := s.passkeyStore()
if err != nil {
return nil, err
}
return &pb.DeletePasskeyResponse{}, accountStatus(store.DeletePasskey(ctx, r.Id))
}
func (c *Client) BeginPasskey(ctx context.Context, registration bool) (identity.PasskeyCeremony, error) {
r, err := c.client.BeginPasskey(ctx, &pb.BeginPasskeyRequest{Registration: registration})
if err != nil {
return identity.PasskeyCeremony{}, accountClientError(err)
}
return identity.PasskeyCeremony{Token: r.Token, Options: r.Options}, nil
}
func (c *Client) FinishPasskey(ctx context.Context, token string, credential []byte, registration bool, name string) (identity.AccountSession, error) {
r, err := c.client.FinishPasskey(ctx, &pb.FinishPasskeyRequest{Token: token, Credential: credential, Registration: registration, Name: name})
if err != nil {
return identity.AccountSession{}, accountClientError(err)
}
return identity.AccountSession{Identity: identityValue(r.Identity), Token: r.Token, Expires: timeValue(r.ExpiresAt)}, nil
}
func (c *Client) ListPasskeys(ctx context.Context) ([]identity.Passkey, error) {
r, err := c.client.ListPasskeys(ctx, &pb.ListPasskeysRequest{})
if err != nil {
return nil, accountClientError(err)
}
out := []identity.Passkey{}
for _, v := range r.Passkeys {
out = append(out, identity.Passkey{ID: v.Id, Name: v.Name})
}
return out, nil
}
func (c *Client) DeletePasskey(ctx context.Context, id string) error {
_, err := c.client.DeletePasskey(ctx, &pb.DeletePasskeyRequest{Id: id})
return accountClientError(err)
}
@@ -69,6 +69,7 @@ const taskLogChunkBytes = 256 << 10
type Deps struct {
ControlPlane controlpb.ControlPlaneServiceServer
Identities identity.Repository
Accounts identity.Accounts
// SubjectBindings fronts the subject-binding surface, which only the
// authenticating path needs. Unset means this process cannot resolve a
// verified subject, and the RPCs answer Unavailable rather than pretending.
+417
View File
@@ -0,0 +1,417 @@
package webui
import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/ratelimit"
)
const accountCookie = "archie_session"
func (s *Server) registerAccountRoutes(public, protected *http.ServeMux) {
if s.Accounts == nil {
return
}
s.accountRateLimit = ratelimit.New(time.Minute, 20)
public.HandleFunc("GET /api/auth/status", s.handleAccountStatus)
public.HandleFunc("POST /api/auth/setup", s.handleAccountSetup)
public.HandleFunc("POST /api/auth/login", s.handleAccountLogin)
public.HandleFunc("POST /api/auth/logout", s.handleAccountLogout)
public.HandleFunc("POST /api/auth/recover", s.handleAccountRecover)
protected.HandleFunc("POST /api/accounts", s.handleAccountCreate)
personal := http.NewServeMux()
personal.HandleFunc("POST /api/account/password", s.handleAccountPassword)
personal.HandleFunc("POST /api/account/recovery", s.handleAccountRecovery)
public.Handle("/api/account/", s.requireAccount(s.authorizeAccountSelf(personal)))
protected.HandleFunc("GET /api/authentication", s.handleAuthenticationSettings)
protected.HandleFunc("PUT /api/authentication", s.handleAuthenticationSettings)
s.registerPasskeyRoutes(public, personal)
}
func (s *Server) accountIdentity(r *http.Request) (identity.Identity, error) {
if c, err := r.Cookie(accountCookie); err == nil {
value, err := s.Accounts.ResolveAccountSession(r.Context(), c.Value)
if err != nil {
return identity.Identity{}, err
}
if err := s.verifyAccountProvider(r, value); err != nil {
return identity.Identity{}, err
}
return value, nil
}
if s.Authenticate != nil && strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
return s.Authenticate(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
}
if cookie, err := r.Cookie(providerTokenCookie); err == nil {
return s.authenticateBrowser(r.Context(), cookie.Value)
}
return identity.Identity{}, identity.ErrNoCredential
}
func (s *Server) requireAccount(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
value, err := s.accountIdentity(r)
if err != nil || value.Kind != identity.KindUser || !value.CanAct() {
if err == nil {
err = identity.ErrCredentialRejected
}
s.writeAccountError(w, err)
return
}
h.ServeHTTP(w, r.WithContext(WithActingIdentity(r.Context(), value)))
})
}
func (s *Server) handleAccountStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
required, err := s.Accounts.AccountSetupRequired(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
var user *identity.Identity
value, err := s.accountIdentity(r)
if err == nil && value.Kind == identity.KindUser && value.CanAct() {
user = &value
} else if err != nil && !errors.Is(err, identity.ErrNoCredential) && !errors.Is(err, identity.ErrCredentialRejected) && !errors.Is(err, identity.ErrIdentityInactive) && !errors.Is(err, identity.ErrSubjectUnbound) {
s.writeAccountError(w, err)
return
}
oidcEnabled := s.Login != nil
publicURL := ""
if store, ok := s.authenticationSettings(); ok {
settings, settingsErr := store.AuthenticationSettings(r.Context())
if settingsErr != nil {
s.writeAccountError(w, settingsErr)
return
}
publicURL = settings.PublicURL
if settings.PublicURL != "" {
oidcEnabled = settings.OIDCIssuer != ""
}
}
writeJSON(w, map[string]any{"setup_required": required, "user": user, "oidc": oidcEnabled, "public_url": publicURL})
}
func decodeAccountRequest(w http.ResponseWriter, r *http.Request, value any) bool {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(value); err != nil {
http.Error(w, "invalid account request", http.StatusBadRequest)
return false
}
return true
}
func (s *Server) handleAccountSetup(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var request identity.AccountRegistration
if !decodeAccountRequest(w, r, &request) {
return
}
if _, err := s.Accounts.RegisterAccount(r.Context(), request, true); err != nil {
s.writeAccountError(w, err)
return
}
s.signInAccount(w, r, request.Email, request.Password)
}
func (s *Server) handleAccountLogin(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var request struct {
Email string `json:"email"`
Password string `json:"password"`
}
if !decodeAccountRequest(w, r, &request) {
return
}
s.signInAccount(w, r, request.Email, request.Password)
}
func (s *Server) signInAccount(w http.ResponseWriter, r *http.Request, email, password string) {
value, err := s.Accounts.SignInAccount(r.Context(), email, password)
if err != nil {
s.logf("account sign-in refused", "peer", r.RemoteAddr)
s.writeAccountError(w, err)
return
}
if s.Log != nil {
s.Log.Info("account signed in", "identity", value.Identity.ID)
}
s.clearProviderCookie(w)
s.setAccountCookie(w, r, value)
writeJSON(w, map[string]any{"user": value.Identity})
}
func (s *Server) setAccountCookie(w http.ResponseWriter, r *http.Request, value identity.AccountSession) {
scheme, _ := s.expectedOrigin(r)
http.SetCookie(w, &http.Cookie{Name: accountCookie, Value: value.Token, Path: "/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, Expires: value.Expires, MaxAge: int(time.Until(value.Expires).Seconds())})
w.Header().Set("Cache-Control", "no-store")
}
func (s *Server) handleAccountLogout(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
if c, err := r.Cookie(accountCookie); err == nil {
if err = s.Accounts.SignOutAccount(r.Context(), c.Value); err != nil {
s.writeAccountError(w, err)
return
}
}
for _, name := range []string{accountCookie, providerTokenCookie} {
http.SetCookie(w, &http.Cookie{Name: name, Path: "/", HttpOnly: true, MaxAge: -1, SameSite: http.SameSiteStrictMode})
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
if !s.requireFreshAccount(w, r) {
return
}
var request identity.AccountRegistration
if !decodeAccountRequest(w, r, &request) {
return
}
value, err := s.Accounts.RegisterAccount(r.Context(), request, false)
if err != nil {
s.writeAccountError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]any{"user": value})
}
func (s *Server) handleAccountPassword(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var request struct {
Current string `json:"current_password"`
New string `json:"new_password"`
}
if !decodeAccountRequest(w, r, &request) {
return
}
if err := s.Accounts.ChangeAccountPassword(r.Context(), request.Current, request.New); err != nil {
s.writeAccountError(w, err)
return
}
http.SetCookie(w, &http.Cookie{Name: accountCookie, Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode})
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) writeAccountError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, identity.ErrNoCredential), errors.Is(err, identity.ErrCredentialRejected), errors.Is(err, identity.ErrIdentityInactive), errors.Is(err, identity.ErrSubjectUnbound):
http.Error(w, "Sign-in required or credentials not accepted.", http.StatusUnauthorized)
case errors.Is(err, identity.ErrSetupComplete):
http.Error(w, identity.ErrSetupComplete.Error(), http.StatusConflict)
case errors.Is(err, identity.ErrNotFound):
http.Error(w, "Record not found.", http.StatusNotFound)
case errors.Is(err, identity.ErrConflict):
http.Error(w, "An account already uses that email.", http.StatusConflict)
case errors.Is(err, identity.ErrInvalid):
http.Error(w, "Enter a name, valid email, organisation name for setup, and an uncommon password of at least 15 characters (at most 1024 bytes).", http.StatusBadRequest)
default:
s.logf("account operation failed", "err", err)
http.Error(w, "Account service unavailable.", http.StatusServiceUnavailable)
}
}
func (s *Server) authenticationSettings() (identity.AuthenticationSettingsStore, bool) {
value, ok := s.Accounts.(identity.AuthenticationSettingsStore)
return value, ok
}
func (s *Server) handleAuthenticationSettings(w http.ResponseWriter, r *http.Request) {
if !instanceOwner(r) {
http.Error(w, "instance administrator required", http.StatusForbidden)
return
}
store, ok := s.authenticationSettings()
if !ok {
http.Error(w, "authentication settings unavailable", http.StatusServiceUnavailable)
return
}
if r.Method == http.MethodGet {
value, err := store.AuthenticationSettings(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
writeJSON(w, value)
return
}
if !s.requireFreshAccount(w, r) {
return
}
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var value identity.AuthenticationSettings
if !decodeAccountRequest(w, r, &value) {
return
}
if err := store.SaveAuthenticationSettings(r.Context(), value); err != nil {
if errors.Is(err, identity.ErrInvalid) {
http.Error(w, "Use a valid instance origin and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.", http.StatusBadRequest)
return
}
s.writeAccountError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) authorizeAccountSelf(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
acting, ok := ActingIdentity(r.Context())
if !ok || acting.Kind != identity.KindUser || !acting.CanAct() {
http.Error(w, "sign-in required", http.StatusUnauthorized)
return
}
principal, err := s.requestPrincipal(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
h.ServeHTTP(w, r.WithContext(org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)))
})
}
func (s *Server) requireFreshAccount(w http.ResponseWriter, r *http.Request) bool {
store, ok := s.Accounts.(identity.AccountSecurity)
if !ok {
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
return false
}
cookie, err := r.Cookie(accountCookie)
if err == nil {
err = store.RequireFreshAccountSession(r.Context(), cookie.Value)
}
if err != nil {
http.Error(w, "Sign in again before changing account security.", http.StatusForbidden)
return false
}
return true
}
func (s *Server) handleAccountRecovery(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.requireFreshAccount(w, r) {
return
}
store, ok := s.Accounts.(identity.AccountSecurity)
if !ok {
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
return
}
code, err := store.CreateAccountRecovery(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, map[string]string{"code": code})
}
func (s *Server) handleAccountRecover(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
store, ok := s.Accounts.(identity.AccountSecurity)
if !ok {
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
return
}
var request struct {
Email string `json:"email"`
Code string `json:"code"`
Password string `json:"password"`
}
if !decodeAccountRequest(w, r, &request) {
return
}
if err := store.RecoverAccount(r.Context(), request.Email, request.Code, request.Password); err != nil {
s.writeAccountError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) clearProviderCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{Name: providerTokenCookie, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
}
func (s *Server) authorizeAuthenticationMutation(w http.ResponseWriter, r *http.Request) bool {
if !s.authorizeTaskMutation(w, r) {
return false
}
scheme, host := s.expectedOrigin(r)
hostname := host
if name, _, err := net.SplitHostPort(host); err == nil {
hostname = name
}
local := strings.EqualFold(hostname, "localhost") || (net.ParseIP(hostname) != nil && net.ParseIP(hostname).IsLoopback())
if scheme != "https" && !local {
http.Error(w, "Account credentials require HTTPS. Use a TLS proxy, or localhost for development.", http.StatusForbidden)
return false
}
if strings.HasPrefix(r.URL.Path, "/api/auth/") && s.accountRateLimit != nil {
peer, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
peer = r.RemoteAddr
}
s.accountRateLimit.EvictStale()
if !s.accountRateLimit.Allow("authentication", peer) {
w.Header().Set("Retry-After", "60")
http.Error(w, "Too many sign-in attempts. Try again shortly.", http.StatusTooManyRequests)
return false
}
}
return true
}
func (s *Server) verifyAccountProvider(r *http.Request, value identity.Identity) error {
cookie, err := r.Cookie(providerTokenCookie)
if errors.Is(err, http.ErrNoCookie) {
return nil
}
if err != nil {
return err
}
providerValue, err := s.authenticateBrowser(r.Context(), cookie.Value)
if err != nil {
return err
}
if providerValue.ID != value.ID {
return identity.ErrCredentialRejected
}
return nil
}
func (s *Server) authenticateBrowser(ctx context.Context, credential string) (identity.Identity, error) {
verify := s.AuthenticateBrowser
if verify == nil {
verify = s.Authenticate
}
if verify == nil {
return identity.Identity{}, identity.ErrCredentialRejected
}
return verify(ctx, credential)
}
+138
View File
@@ -0,0 +1,138 @@
package webui
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
)
type accountBoundaryStore struct {
identity.Accounts
identity.AccountSecurity
fresh bool
}
func (accountBoundaryStore) AccountSetupRequired(context.Context) (bool, error) { return false, nil }
func (accountBoundaryStore) ResolveAccountSession(_ context.Context, token string) (identity.Identity, error) {
if token != "valid" {
return identity.Identity{}, identity.ErrCredentialRejected
}
return identity.Identity{ID: "alice", Kind: identity.KindUser, DisplayName: "Alice", Lifecycle: identity.LifecycleActive}, nil
}
func (accountBoundaryStore) SignInAccount(_ context.Context, email, password string) (identity.AccountSession, error) {
if email != "alice@example.com" || password != "a sufficiently long password" {
return identity.AccountSession{}, identity.ErrCredentialRejected
}
return identity.AccountSession{Identity: identity.Identity{ID: "alice", Kind: identity.KindUser, Lifecycle: identity.LifecycleActive}, Token: "new-session", Expires: time.Now().Add(time.Hour)}, nil
}
func (s accountBoundaryStore) RequireFreshAccountSession(context.Context, string) error {
if !s.fresh {
return identity.ErrCredentialRejected
}
return nil
}
func (accountBoundaryStore) CreateAccountRecovery(context.Context) (string, error) {
return "one-use-recovery-code", nil
}
func TestAccountBoundary(t *testing.T) {
principal := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleViewer}}}
for _, tc := range []struct {
name, method, path, body, cookie, csrf string
fresh bool
want int
}{
{name: "shared token cannot authenticate", method: "GET", path: "/api/summary", cookie: "legacy", want: 401},
{name: "API reads reach authentication", method: "GET", path: "/api/chat/sessions", want: 401},
{name: "valid cookie reaches protected API", method: "GET", path: "/api/chat/sessions", cookie: "valid", want: 501},
{name: "login requires CSRF", method: "POST", path: "/api/auth/login", body: `{"email":"alice@example.com","password":"a sufficiently long password"}`, want: 403},
{name: "incorrect credentials use generic refusal", method: "POST", path: "/api/auth/login", csrf: "1", body: `{"email":"unknown@example.com","password":"wrong"}`, want: 401},
{name: "successful login", method: "POST", path: "/api/auth/login", csrf: "1", body: `{"email":"alice@example.com","password":"a sufficiently long password"}`, want: 200},
{name: "anonymous cannot manage personal security", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, want: 401},
{name: "viewer manages own security after recent sign in", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 200},
{name: "stale session cannot replace recovery", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, cookie: "valid", want: 403},
{name: "viewer cannot create accounts", method: "POST", path: "/api/accounts", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 403},
{name: "viewer cannot edit instance authentication", method: "PUT", path: "/api/authentication", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 403},
} {
t.Run(tc.name, func(t *testing.T) {
srv := &Server{Accounts: accountBoundaryStore{fresh: tc.fresh}, Access: infraaccess.New(access.ShippedOrgPolicies("acme")), Principals: principalOf(principal)}
req := httptest.NewRequestWithContext(t.Context(), tc.method, "https://archie.example"+tc.path, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", tc.csrf)
if tc.cookie != "" {
req.AddCookie(&http.Cookie{Name: accountCookie, Value: tc.cookie})
}
recorder := httptest.NewRecorder()
srv.Handler().ServeHTTP(recorder, req)
if recorder.Code != tc.want {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.want, recorder.Body.String())
}
if tc.name == "successful login" {
var found bool
for _, cookie := range recorder.Result().Cookies() {
if cookie.Name == accountCookie {
found = true
if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode || cookie.Value != "new-session" {
t.Fatalf("unsafe session cookie: %+v", cookie)
}
}
}
if !found {
t.Fatal("login did not set a session")
}
}
})
}
}
func TestAuthenticationTransport(t *testing.T) {
for _, tc := range []struct {
name, url, origin, csrf string
want bool
}{
{"TLS", "https://archie.example/api/auth/login", "https://archie.example", "1", true},
{"localhost development", "http://localhost:8484/api/auth/login", "http://localhost:8484", "1", true},
{"network cleartext", "http://archie.example/api/auth/login", "http://archie.example", "1", false},
{"cross origin", "https://archie.example/api/auth/login", "https://attacker.example", "1", false},
{"missing CSRF", "https://archie.example/api/auth/login", "https://archie.example", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(), "POST", tc.url, strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", tc.csrf)
req.Header.Set("Origin", tc.origin)
if got := (&Server{}).authorizeAuthenticationMutation(httptest.NewRecorder(), req); got != tc.want {
t.Fatalf("allowed=%v want=%v", got, tc.want)
}
})
}
}
func TestAccountSessionFailureIsClosed(t *testing.T) {
srv := &Server{Accounts: unavailableAccounts{}}
req := httptest.NewRequestWithContext(t.Context(), "GET", "https://archie.example/api/auth/status", nil)
rec := httptest.NewRecorder()
srv.handleAccountStatus(rec, req)
if rec.Code != 503 {
t.Fatalf("account outage status=%d, want 503", rec.Code)
}
}
type unavailableAccounts struct{ identity.Accounts }
func (unavailableAccounts) AccountSetupRequired(context.Context) (bool, error) {
return false, errors.New("store unavailable")
}
+23 -8
View File
@@ -163,7 +163,7 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
out := make([]messaging.SessionContext, 0, len(snapshot.Sessions))
active := make(map[string]string)
for _, session := range snapshot.Sessions {
if session.Source.Platform == "web" {
if s.ownsChatSession(r.Context(), session) {
out = append(out, session)
if name, ok := snapshot.ActivePersonas[session.SessionID]; ok {
active[session.SessionID] = name
@@ -200,7 +200,7 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || session.Source.Platform != "web" {
if !found || !s.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -231,7 +231,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || session.Source.Platform != "web" {
if !found || !s.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -290,7 +290,8 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mess
return messaging.Inbound{
Message: messaging.Message{
SourceID: req.SourceID,
ConversationID: messaging.ConversationID{ChannelID: req.ChannelID},
ConversationID: messaging.ConversationID{ChannelID: req.ChannelID, ThreadID: chatUser(r.Context())},
SenderID: chatUser(r.Context()),
Sender: "web",
Role: messaging.RoleUser,
Text: req.Text,
@@ -345,6 +346,7 @@ type chatStreamSink struct {
showToolCalls bool
// files hands out downloads for the local files a turn sends.
files *chatFiles
owner string
}
func (s chatStreamSink) Delta(text string) {
@@ -394,7 +396,7 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) {
if name == "" {
name = filepath.Base(att.Path)
}
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 [" + name + "](" + chatFileURL(s.files.offer(att.Path, att.FileName)) + ")"})
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 [" + name + "](" + chatFileURL(s.files.offerFor(att.Path, att.FileName, s.owner)) + ")"})
}
}
@@ -442,7 +444,7 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
return
}
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles}
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles, owner: chatUser(r.Context())}
for event := range events {
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
switch event.Kind {
@@ -480,7 +482,7 @@ func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || session.Source.Platform != "web" {
if !found || !s.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -514,7 +516,7 @@ func (s *Server) handleChatPersona(w http.ResponseWriter, r *http.Request) {
if session, found, err := chat.Contract.GetSession(r.Context(), req.SessionID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else if !found || session.Source.Platform != "web" {
} else if !found || !s.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -641,3 +643,16 @@ func newChatSourceID() string {
}
return "web-" + id.String()
}
// The server supplies the person thread; browser-supplied conversation IDs
// cannot select another person's history.
func chatUser(ctx context.Context) string {
if value, ok := ActingIdentity(ctx); ok {
return string(value.ID)
}
return ""
}
func (s *Server) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
return session.Source.Platform == "web" && session.Source.ThreadID == chatUser(ctx)
}
+9 -4
View File
@@ -31,9 +31,10 @@ type chatAskChoice struct {
type chatAsks struct {
mu sync.Mutex
waiting map[string]chan string
owners map[string]string
}
func (a *chatAsks) open() (string, chan string) {
func (a *chatAsks) open(owner string) (string, chan string) {
var b [12]byte
_, _ = rand.Read(b[:])
id := hex.EncodeToString(b[:])
@@ -41,8 +42,10 @@ func (a *chatAsks) open() (string, chan string) {
a.mu.Lock()
if a.waiting == nil {
a.waiting = make(map[string]chan string)
a.owners = make(map[string]string)
}
a.waiting[id] = ch
a.owners[id] = owner
a.mu.Unlock()
return id, ch
}
@@ -50,12 +53,14 @@ func (a *chatAsks) open() (string, chan string) {
func (a *chatAsks) close(id string) {
a.mu.Lock()
delete(a.waiting, id)
delete(a.owners, id)
a.mu.Unlock()
}
func (a *chatAsks) answer(id, answer string) bool {
func (a *chatAsks) answer(id, answer, owner string) bool {
a.mu.Lock()
ch, ok := a.waiting[id]
ok = ok && a.owners[id] == owner
a.mu.Unlock()
if ok {
select {
@@ -74,7 +79,7 @@ type dashboardAsker struct {
}
func (d dashboardAsker) ask(ctx context.Context, q chatAsk) (string, error) {
id, ch := d.asks.open()
id, ch := d.asks.open(chatUser(ctx))
defer d.asks.close(id)
q.ID = id
d.write(chatStreamEvent{Type: "ask", Ask: &q})
@@ -152,7 +157,7 @@ func (s *Server) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if !s.chatAsks.answer(req.ID, req.Answer) {
if !s.chatAsks.answer(req.ID, req.Answer, chatUser(r.Context())) {
http.Error(w, "that question is no longer waiting", http.StatusNotFound)
return
}
+6 -3
View File
@@ -26,6 +26,7 @@ type chatFiles struct {
type chatFile struct {
path string
name string
owner string
expires time.Time
}
@@ -37,7 +38,9 @@ func (c *chatFiles) clock() time.Time {
}
// offer registers path and returns the token that downloads it.
func (c *chatFiles) offer(path, name string) string {
func (c *chatFiles) offer(path, name string) string { return c.offerFor(path, name, "") }
func (c *chatFiles) offerFor(path, name, owner string) string {
var b [16]byte
_, _ = rand.Read(b[:])
token := hex.EncodeToString(b[:])
@@ -55,7 +58,7 @@ func (c *chatFiles) offer(path, name string) string {
delete(c.files, t)
}
}
c.files[token] = chatFile{path: path, name: name, expires: now.Add(chatFileTTL)}
c.files[token] = chatFile{path: path, name: name, owner: owner, expires: now.Add(chatFileTTL)}
return token
}
@@ -71,7 +74,7 @@ func (c *chatFiles) lookup(token string) (chatFile, bool) {
func (s *Server) handleChatFile(w http.ResponseWriter, r *http.Request) {
f, ok := s.chatFiles.lookup(r.PathValue("token"))
if !ok {
if !ok || f.owner != chatUser(r.Context()) {
http.Error(w, "that file is no longer available", http.StatusNotFound)
return
}
+12 -1
View File
@@ -7,6 +7,8 @@ import (
"path/filepath"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
// TestChatFileDownload: only a file a turn offered is served, and only until
@@ -20,9 +22,11 @@ func TestChatFileDownload(t *testing.T) {
srv := &Server{}
srv.chatFiles.now = func() time.Time { return now }
token := srv.chatFiles.offer(path, "")
private := srv.chatFiles.offerFor(path, "", "alice")
tests := []struct {
name string
user string
token string
after time.Duration
want int
@@ -30,12 +34,19 @@ func TestChatFileDownload(t *testing.T) {
{name: "an offered file is served", token: token, want: http.StatusOK},
{name: "a token nobody was given is refused", token: "0123456789abcdef0123456789abcdef", want: http.StatusNotFound},
{name: "a path is not a token", token: "..%2f..%2fetc%2fpasswd", want: http.StatusNotFound},
{name: "owner downloads private file", user: "alice", token: private, want: http.StatusOK},
{name: "another person cannot download", user: "bob", token: private, want: http.StatusNotFound},
{name: "unidentified caller cannot download private file", token: private, want: http.StatusNotFound},
{name: "an expired token is refused", token: token, after: chatFileTTL + time.Second, want: http.StatusNotFound},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv.chatFiles.now = func() time.Time { return now.Add(tt.after) }
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/chat/file/x", nil)
ctx := t.Context()
if tt.user != "" {
ctx = WithActingIdentity(ctx, identity.Identity{ID: identity.IdentityID(tt.user)})
}
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/chat/file/x", nil)
req.SetPathValue("token", tt.token)
rec := httptest.NewRecorder()
srv.handleChatFile(rec, req)
+16 -3
View File
@@ -220,7 +220,7 @@ func (s *Server) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if s.Subjects == nil || s.Identities == nil || s.Issuer == "" {
if s.Subjects == nil || s.Identities == nil || s.memberIssuer(r) == "" {
http.Error(w, "adding a person needs a configured identity provider", http.StatusServiceUnavailable)
return
}
@@ -281,9 +281,9 @@ func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (reques
http.Error(w, "give either a subject or an email", http.StatusBadRequest)
return request, bound, name, false
case subject != "":
bound, name = identity.Subject{Issuer: s.Issuer, Subject: subject}, cmp.Or(name, subject)
bound, name = identity.Subject{Issuer: s.memberIssuer(r), Subject: subject}, cmp.Or(name, subject)
default:
bound, name = identity.EmailSubject(s.Issuer, email), cmp.Or(name, email)
bound, name = identity.EmailSubject(s.memberIssuer(r), email), cmp.Or(name, email)
}
if err := org.Role(request.Role).Validate(); err != nil {
writeOrgError(w, err)
@@ -405,3 +405,16 @@ func writeOrgError(w http.ResponseWriter, err error) {
writeControlPlaneError(w, err)
}
}
func (s *Server) memberIssuer(r *http.Request) string {
if store, ok := s.authenticationSettings(); ok {
value, err := store.AuthenticationSettings(r.Context())
if err != nil {
return ""
}
if value.PublicURL != "" {
return value.OIDCIssuer
}
}
return s.Issuer
}
+19 -1
View File
@@ -15,6 +15,7 @@ import (
"path/filepath"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
@@ -105,6 +106,9 @@ func LoadOrCreateToken(path string) (string, error) {
// token when an identity provider is configured, else the shared token. A
// ?t= token is moved into a cookie and the request redirected.
func (s *Server) requireToken(h http.Handler) http.Handler {
if s.Accounts != nil {
return s.requireAccount(h)
}
if s.Authenticate != nil {
return s.requireIdentity(h)
}
@@ -244,12 +248,26 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
s.refuseUnidentified(w, r, err)
return
}
if _, err := s.Authenticate(r.Context(), session.Token); err != nil {
value, err := s.authenticateBrowser(r.Context(), session.Token)
if err != nil {
s.refuseUnidentified(w, r, err)
return
}
clearFlowCookie(w, r, loginStateCookie)
clearFlowCookie(w, r, loginVerifierCookie)
if security, ok := s.Accounts.(identity.AccountSecurity); ok {
principal, resolveErr := s.Principals.PrincipalFor(r.Context(), value.ID)
if resolveErr != nil {
s.writeAccountError(w, resolveErr)
return
}
local, openErr := security.OpenAccountSession(access.WithPrincipal(r.Context(), principal), session.Expires)
if openErr != nil {
s.writeAccountError(w, openErr)
return
}
s.setAccountCookie(w, r, local)
}
http.SetCookie(w, &http.Cookie{
Name: providerTokenCookie, Value: session.Token, Path: "/",
HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil,
@@ -0,0 +1,162 @@
package webui
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
)
type authorizationTasks struct{ storecontract.TaskStore }
func (authorizationTasks) TaskByID(context.Context, int64) (*task.Task, error) {
return &task.Task{ID: 7}, nil
}
// These are the policy-governed HTTP surfaces. Protocol entry points and
// private account resources have separate credential/ownership behavior tests.
func TestHTTPPolicyCannotBeBypassed(t *testing.T) {
routes := []struct{ method, path string }{
{"DELETE", "/api/access/policies"},
{"DELETE", "/api/bindings/7"},
{"DELETE", "/api/event-types/7"},
{"DELETE", "/api/extensions/sample"},
{"DELETE", "/api/mappings/7"},
{"DELETE", "/api/orgs/7/members/sample"},
{"DELETE", "/api/sources/sample"},
{"DELETE", "/api/tokens/7"},
{"GET", "/api/access/policies"},
{"GET", "/api/alerts"},
{"GET", "/api/authentication"},
{"GET", "/api/bindings"},
{"GET", "/api/bindings/7"},
{"GET", "/api/bindings/7/dispatches"},
{"GET", "/api/capabilities"},
{"GET", "/api/captures"},
{"GET", "/api/captures/7/dispatches"},
{"GET", "/api/channels"},
{"GET", "/api/chat/file/sample"},
{"GET", "/api/chat/sessions"},
{"GET", "/api/chat/sessions/7/messages"},
{"GET", "/api/chat/sessions/7/turns"},
{"GET", "/api/chat/update"},
{"GET", "/api/config"},
{"GET", "/api/control-plane/apply-status"},
{"GET", "/api/control-plane/audit"},
{"GET", "/api/control-plane/catalog"},
{"GET", "/api/control-plane/resources/sample"},
{"GET", "/api/control-plane/resources/sample/history"},
{"GET", "/api/curators"},
{"GET", "/api/event-types"},
{"GET", "/api/extensions"},
{"GET", "/api/extensions/catalogue"},
{"GET", "/api/harness/bindings"},
{"GET", "/api/harness/terminal"},
{"GET", "/api/identities"},
{"GET", "/api/logs"},
{"GET", "/api/mappings"},
{"GET", "/api/mappings/7"},
{"GET", "/api/orgs"},
{"GET", "/api/orgs/7"},
{"GET", "/api/orgs/7/members"},
{"GET", "/api/orgs/7/workspaces"},
{"GET", "/api/secret-engines"},
{"GET", "/api/services"},
{"GET", "/api/setup"},
{"GET", "/api/skills"},
{"GET", "/api/sources"},
{"GET", "/api/stream"},
{"GET", "/api/summary"},
{"GET", "/api/task-meta"},
{"GET", "/api/tasks"},
{"GET", "/api/tasks/7"},
{"GET", "/api/tasks/7/attempts"},
{"GET", "/api/tasks/7/changes"},
{"GET", "/api/tasks/7/debug"},
{"GET", "/api/tasks/7/dispatches"},
{"GET", "/api/tasks/7/logs"},
{"GET", "/api/tasks/7/logs/download"},
{"GET", "/api/tasks/7/sandbox"},
{"GET", "/api/tokens"},
{"GET", "/api/version"},
{"GET", "/api/workflows"},
{"PATCH", "/api/bindings/7"},
{"PATCH", "/api/mappings/7"},
{"POST", "/api/accounts"},
{"POST", "/api/alerts/7/dismiss"},
{"POST", "/api/bindings"},
{"POST", "/api/bindings/7/approve"},
{"POST", "/api/bindings/7/pause"},
{"POST", "/api/bindings/7/resume"},
{"POST", "/api/channels/7/reload"},
{"POST", "/api/chat/answer"},
{"POST", "/api/chat/cancel"},
{"POST", "/api/chat/message"},
{"POST", "/api/chat/persona"},
{"POST", "/api/chat/stream"},
{"POST", "/api/chat/update/defer"},
{"POST", "/api/chat/update/install"},
{"POST", "/api/control-plane/resources/sample/commands/sample"},
{"POST", "/api/event-types"},
{"POST", "/api/extensions"},
{"POST", "/api/extensions/catalogue/sample/install"},
{"POST", "/api/extensions/sample/accept"},
{"POST", "/api/extensions/sample/approve-update"},
{"POST", "/api/extensions/sample/rollback"},
{"POST", "/api/extensions/sample/update"},
{"POST", "/api/identities"},
{"POST", "/api/identities/7/sample"},
{"POST", "/api/mappings"},
{"POST", "/api/mappings/preview"},
{"POST", "/api/orgs"},
{"POST", "/api/orgs/7/members"},
{"POST", "/api/orgs/7/workspaces"},
{"POST", "/api/secret-references/check"},
{"POST", "/api/sources"},
{"POST", "/api/sources/sample/approve-unsigned"},
{"POST", "/api/sources/sample/secret"},
{"POST", "/api/sources/sample/signing"},
{"POST", "/api/tasks/7/action"},
{"POST", "/api/tokens"},
{"POST", "/api/work-requests"},
{"PUT", "/api/access/policies"},
{"PUT", "/api/authentication"},
{"PUT", "/api/event-types/7"},
{"PUT", "/api/extensions/sample/enabled"},
{"PUT", "/api/extensions/sample/update-policy"},
{"PUT", "/api/orgs/7/agents/sample"},
{"PUT", "/api/orgs/7/members/sample"},
{"PUT", "/api/sources/sample/delivery-header"},
{"PUT", "/api/sources/sample/name"},
{"PUT", "/api/workflows/7/enabled"},
}
principal := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleAdmin}}}
policy := access.Policy{ID: "deny-all", Level: access.LevelInstance, Text: `forbid(principal,action,resource);`}
for _, route := range routes {
t.Run(route.method+" "+route.path, func(t *testing.T) {
for _, signedIn := range []bool{false, true} {
srv := &Server{Store: authorizationTasks{}, Accounts: accountBoundaryStore{}, Access: infraaccess.New(append(access.ShippedOrgPolicies("acme"), policy)), Principals: principalOf(principal)}
req := httptest.NewRequestWithContext(t.Context(), route.method, "https://archie.example"+route.path, strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", "1")
want := http.StatusUnauthorized
if signedIn {
req.AddCookie(&http.Cookie{Name: accountCookie, Value: "valid"})
want = http.StatusForbidden
}
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != want {
t.Fatalf("signedIn=%v status=%d want=%d body=%s", signedIn, rec.Code, want, rec.Body.String())
}
}
})
}
}
+46 -31
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"strconv"
"strings"
@@ -41,15 +42,15 @@ func (s *Server) authorize(h http.Handler) http.Handler {
// The record's org is not loaded here: org-filtered lookups keep a
// record of another org from ever being fetched, and this request's
// record (when it has an ID) belongs to the caller's org. The
// workspace is the record's, not the route's, so it is read.
workspace, err := s.recordWorkspace(ctx, kind, id)
// workspace, owner and state are read from the record, never the body.
resource, err := s.recordResource(ctx, kind, id)
if err != nil {
s.logf("record workspace unavailable", "kind", kind, "id", id, "err", err)
http.Error(w, "record unavailable", http.StatusServiceUnavailable)
return
}
resource := access.Resource{Kind: kind, ID: id, Org: principal.Org, Workspace: workspace}
decision := s.Access.Authorize(principal, action, resource, access.Context{})
peer, _, _ := net.SplitHostPort(r.RemoteAddr)
decision := s.Access.Authorize(principal, action, resource, access.Context{Addr: peer})
if !decision.Allowed {
if errors.Is(decision.Err, access.ErrChainUnavailable) {
// Nothing was evaluated: the chain has not loaded. This is an
@@ -91,27 +92,26 @@ func (s *Server) authorizeCreateIn(w http.ResponseWriter, r *http.Request, kind
return false
}
// recordWorkspace returns the workspace of the record a request names, so
// workspace policies and per-workspace roles decide for it. A request naming
// no record, or one the caller's org does not hold, has none: the handler's
// own lookup answers not found.
func (s *Server) recordWorkspace(ctx context.Context, kind access.ResourceKind, id string) (org.WorkspaceID, error) {
// recordResource reads policy attributes from the stored record, never the body.
func (s *Server) recordResource(ctx context.Context, kind access.ResourceKind, id string) (access.Resource, error) {
resource := access.Resource{Kind: kind, ID: id, Org: org.OrgFromContext(ctx)}
if id == "" {
return "", nil
return resource, nil
}
var err error
switch kind {
case access.KindSource:
return s.sourceWorkspace(ctx, id)
case access.KindBinding:
return s.bindingWorkspace(ctx, id)
case access.KindMapping:
return s.mappingWorkspace(ctx, id)
case access.KindEventType:
return s.eventTypeWorkspace(ctx, id)
case access.KindTask:
return s.taskWorkspace(ctx, id)
return s.taskResource(ctx, resource)
case access.KindBinding:
return s.bindingResource(ctx, resource)
case access.KindSource:
resource.Workspace, err = s.sourceWorkspace(ctx, id)
case access.KindMapping:
resource.Workspace, err = s.mappingWorkspace(ctx, id)
case access.KindEventType:
resource.Workspace, err = s.eventTypeWorkspace(ctx, id)
}
return "", nil
return resource, err
}
func (s *Server) sourceWorkspace(ctx context.Context, path string) (org.WorkspaceID, error) {
@@ -125,15 +125,16 @@ func (s *Server) sourceWorkspace(ctx context.Context, path string) (org.Workspac
return src.WorkspaceID, nil
}
func (s *Server) bindingWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
func (s *Server) bindingResource(ctx context.Context, resource access.Resource) (access.Resource, error) {
if s.Bindings == nil {
return "", nil
return resource, nil
}
b, err := s.Bindings.GetBinding(ctx, id)
b, err := s.Bindings.GetBinding(ctx, resource.ID)
if b == nil || err != nil {
return "", ignoreNotFound(err, storecontract.ErrBindingNotFound)
return resource, ignoreNotFound(err, storecontract.ErrBindingNotFound)
}
return b.WorkspaceID, nil
resource.Workspace, resource.State = b.WorkspaceID, string(b.Status)
return resource, nil
}
func (s *Server) mappingWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
@@ -163,16 +164,17 @@ func (s *Server) eventTypeWorkspace(ctx context.Context, id string) (org.Workspa
return "", nil
}
func (s *Server) taskWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
taskID, ok := numericID(id)
if s.Store == nil || !ok {
return "", nil
func (s *Server) taskResource(ctx context.Context, resource access.Resource) (access.Resource, error) {
taskID, ok := numericID(resource.ID)
if !ok {
return resource, nil
}
t, err := s.Store.TaskByID(ctx, taskID)
if t == nil || err != nil {
return "", err
return resource, err
}
return t.Workspace, nil
resource.Workspace, resource.Owner, resource.State = t.Workspace, identity.IdentityID(t.Identity), t.Status
return resource, nil
}
// numericID parses a task route's ID; any other segment names no task.
@@ -285,6 +287,9 @@ func actionOf(method string) access.Action {
// routeOverride returns the action, kind and record key a specific route
// shape carries, or ok=false when the method-and-kind fallback applies.
func routeOverride(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if a, kind, ok := accountRoute(path); ok {
return a, kind, "", true
}
if command, ok := bindingCommand(action, path); ok {
return command, access.KindBinding, segmentValue(path, 2), true
}
@@ -427,3 +432,13 @@ func matchPrefix(path, prefix string) bool {
func matchSegment(path, prefix, suffix string) bool {
return strings.HasPrefix(path, prefix) && strings.HasSuffix(path, suffix)
}
func accountRoute(path string) (access.Action, access.ResourceKind, bool) {
switch path {
case "/api/accounts":
return access.ActionManageMembers, access.KindMember, true
case "/api/authentication":
return access.ActionManageIdentities, access.KindIdentity, true
}
return "", "", false
}
+33
View File
@@ -12,6 +12,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
)
@@ -350,3 +351,35 @@ func TestAuthorizeCreateIn(t *testing.T) {
})
}
}
type taskAttributesStore struct {
storecontract.TaskStore
owner, status string
}
func (s taskAttributesStore) TaskByID(context.Context, int64) (*task.Task, error) {
return &task.Task{ID: 7, Identity: s.owner, Status: s.status, Workspace: "default"}, nil
}
func TestTaskAuthorizationUsesStoredAttributes(t *testing.T) {
policy := access.Policy{ID: "owned-queued", Level: access.LevelObject, OrgID: "acme", ObjectKind: access.KindTask, ObjectID: "7", Text: `permit(principal,action,resource) when {resource.owner == "alice" && resource.state == "queued"};`}
p := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleDeveloper}}}
for _, tc := range []struct {
name, owner, state string
want int
}{
{"owned queued task", "alice", "queued", 200},
{"other owner", "bob", "queued", 403},
{"different state", "alice", "running", 403},
} {
t.Run(tc.name, func(t *testing.T) {
srv := &Server{Store: taskAttributesStore{owner: tc.owner, status: tc.state}, Access: infraaccess.New(append(access.ShippedOrgPolicies("acme"), policy)), Principals: principalOf(p)}
req := httptest.NewRequestWithContext(WithActingIdentity(t.Context(), identity.Identity{ID: "alice"}), "PUT", "https://archie.example/api/tasks/7", strings.NewReader(`{"owner":"alice","state":"queued"}`))
rec := httptest.NewRecorder()
srv.authorize(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})).ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tc.want, rec.Body.String())
}
})
}
}
+97
View File
@@ -0,0 +1,97 @@
package webui
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
type ownedChat struct{ messaging.ChatContract }
func (ownedChat) Snapshot(context.Context) (messaging.ChatSnapshot, error) {
return messaging.ChatSnapshot{CancellationAvailable: true, PersonasAvailable: true}, nil
}
func (ownedChat) GetSession(context.Context, string) (messaging.SessionContext, bool, error) {
return messaging.SessionContext{SessionID: "private", Source: messaging.SessionSource{Platform: "web", ThreadID: "alice"}}, true, nil
}
func (ownedChat) RecentMessages(context.Context, string, int) ([]messaging.Message, error) {
return []messaging.Message{}, nil
}
func (ownedChat) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) {
return []messaging.TurnRecord{}, nil
}
func (ownedChat) Cancel(context.Context, string) (messaging.ChatCancellation, error) {
return messaging.ChatCancellation{Cancelled: true}, nil
}
func (ownedChat) SetPersona(context.Context, string, string) (bool, error) { return true, nil }
func TestWebChatOwnership(t *testing.T) {
for _, route := range []struct {
name, body string
handler func(*Server, http.ResponseWriter, *http.Request)
}{
{"messages", "", (*Server).handleChatMessages},
{"turns", "", (*Server).handleChatTurns},
{"cancel", `{"session_id":"private"}`, (*Server).handleChatCancel},
{"persona", `{"session_id":"private","name":"archie"}`, (*Server).handleChatPersona},
} {
for _, user := range []string{"alice", "bob"} {
t.Run(route.name+"/"+user, func(t *testing.T) {
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: identity.IdentityID(user)})
req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/test", strings.NewReader(route.body))
req.SetPathValue("id", "private")
rec := httptest.NewRecorder()
srv := &Server{Chat: &ChatService{Contract: ownedChat{}}}
route.handler(srv, rec, req)
want := 200
if user != "alice" {
want = 404
}
if rec.Code != want {
t.Fatalf("status=%d want=%d body=%s", rec.Code, want, rec.Body.String())
}
})
}
}
}
func TestWebChatSenderCannotBeSuppliedByBrowser(t *testing.T) {
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: "alice"})
req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/message", strings.NewReader(`{"channel_id":"browser-channel","text":"hello","sender_id":"bob","thread_id":"bob"}`))
value, ok := (&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
if !ok {
t.Fatal("message refused")
}
if value.Message.SenderID != "alice" || value.Message.ConversationID.ThreadID != "alice" {
t.Fatalf("browser selected sender: %+v", value.Message)
}
}
func TestChatQuestionBelongsToInitiatingPerson(t *testing.T) {
var asks chatAsks
id, answers := asks.open("alice")
defer asks.close(id)
if asks.answer(id, "approve", "bob") {
t.Fatal("another person answered the question")
}
select {
case <-answers:
t.Fatal("unauthorized answer delivered")
default:
}
if !asks.answer(id, "approve", "alice") {
t.Fatal("owner could not answer")
}
if answer := <-answers; answer != "approve" {
t.Fatalf("answer=%s", answer)
}
}
+117
View File
@@ -0,0 +1,117 @@
package webui
import (
"encoding/json"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func (s *Server) registerPasskeyRoutes(public, protected *http.ServeMux) {
public.HandleFunc("POST /api/auth/passkey/begin", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyBegin(w, r, false) })
public.HandleFunc("POST /api/auth/passkey/finish", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyFinish(w, r, false) })
protected.HandleFunc("POST /api/account/passkeys/begin", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyBegin(w, r, true) })
protected.HandleFunc("POST /api/account/passkeys/finish", func(w http.ResponseWriter, r *http.Request) { s.handlePasskeyFinish(w, r, true) })
protected.HandleFunc("GET /api/account/passkeys", s.handlePasskeyList)
protected.HandleFunc("DELETE /api/account/passkeys/{id}", s.handlePasskeyDelete)
}
func passkeyCookie(registration bool) string {
if registration {
return "archie_passkey_registration"
}
return "archie_passkey_login"
}
func (s *Server) handlePasskeyBegin(w http.ResponseWriter, r *http.Request, registration bool) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
if registration && !s.requireFreshAccount(w, r) {
return
}
store, ok := s.Accounts.(identity.Passkeys)
if !ok {
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
return
}
value, err := store.BeginPasskey(r.Context(), registration)
if err != nil {
s.writeAccountError(w, err)
return
}
scheme, _ := s.expectedOrigin(r)
http.SetCookie(w, &http.Cookie{Name: passkeyCookie(registration), Value: value.Token, Path: "/api/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, MaxAge: 300})
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, json.RawMessage(value.Options))
}
func (s *Server) handlePasskeyFinish(w http.ResponseWriter, r *http.Request, registration bool) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
if registration && !s.requireFreshAccount(w, r) {
return
}
store, ok := s.Accounts.(identity.Passkeys)
if !ok {
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
return
}
cookie, err := r.Cookie(passkeyCookie(registration))
if err != nil {
http.Error(w, "passkey request expired", http.StatusUnauthorized)
return
}
http.SetCookie(w, &http.Cookie{Name: passkeyCookie(registration), Path: "/api/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
var request struct {
Credential json.RawMessage `json:"credential"`
Name string `json:"name"`
}
if !decodeAccountRequest(w, r, &request) {
return
}
value, err := store.FinishPasskey(r.Context(), cookie.Value, request.Credential, registration, request.Name)
if err != nil {
s.writeAccountError(w, err)
return
}
if !registration {
s.clearProviderCookie(w)
s.setAccountCookie(w, r, value)
}
writeJSON(w, map[string]any{"user": value.Identity})
}
func (s *Server) handlePasskeyList(w http.ResponseWriter, r *http.Request) {
store, ok := s.Accounts.(identity.Passkeys)
if !ok {
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
return
}
values, err := store.ListPasskeys(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
writeJSON(w, map[string]any{"passkeys": values})
}
func (s *Server) handlePasskeyDelete(w http.ResponseWriter, r *http.Request) {
if !s.requireFreshAccount(w, r) {
return
}
if !s.authorizeAuthenticationMutation(w, r) {
return
}
store, ok := s.Accounts.(identity.Passkeys)
if !ok {
http.Error(w, "passkeys unavailable", http.StatusServiceUnavailable)
return
}
if err := store.DeletePasskey(r.Context(), r.PathValue("id")); err != nil {
s.writeAccountError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
+15 -2
View File
@@ -22,11 +22,15 @@ import (
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/captureintake"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/ratelimit"
"github.com/samcharles93/archie-core/internal/secret"
"github.com/samcharles93/archie-core/ui"
)
type Server struct {
Accounts identity.Accounts
accountRateLimit *ratelimit.Limiter
// chatAsks holds the chat questions waiting for the operator's answer.
chatAsks chatAsks
// chatFiles holds the downloads for files chat turns sent.
@@ -123,7 +127,8 @@ type Server struct {
// Authenticate resolves a presented credential to an identity. Non-nil
// replaces the shared token.
Authenticate func(context.Context, string) (identity.Identity, error)
Authenticate func(context.Context, string) (identity.Identity, error)
AuthenticateBrowser func(context.Context, string) (identity.Identity, error)
// PersonalTokens manages the signed-in person's API tokens. Nil answers
// Unavailable.
@@ -398,6 +403,7 @@ func (s *Server) Handler() http.Handler {
mux.Handle("GET /", s.assets())
top := http.NewServeMux()
s.registerAccountRoutes(top, mux)
top.HandleFunc("GET /healthz", s.handleHealthz)
top.HandleFunc("GET /health", s.handleHealth)
// The sign-in routes sit on the bypass mux because they are how a caller
@@ -415,7 +421,14 @@ func (s *Server) Handler() http.Handler {
}
// The chain runs after the credential check and before any handler: the
// principal exists only once the credential resolved
top.Handle("/", s.requireToken(s.authorize(mux)))
authenticated := s.requireToken(s.authorize(mux))
top.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.Accounts != nil && r.Method == http.MethodGet && !strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != healthDetailedRoute {
s.assets().ServeHTTP(w, r)
return
}
authenticated.ServeHTTP(w, r)
}))
return top
}
+72
View File
@@ -44,6 +44,22 @@ service StateStoreService {
rpc ResolveTaskGrant(ResolveTaskGrantRequest) returns (ResolveTaskGrantResponse);
// Identity domain. Task-scoped grants cannot call these administrative RPCs.
rpc ListIdentities(ListIdentitiesRequest) returns (ListIdentitiesResponse);
rpc GetAuthenticationSettings(GetAuthenticationSettingsRequest) returns (GetAuthenticationSettingsResponse);
rpc SaveAuthenticationSettings(SaveAuthenticationSettingsRequest) returns (SaveAuthenticationSettingsResponse);
rpc BeginPasskey(BeginPasskeyRequest) returns (BeginPasskeyResponse);
rpc FinishPasskey(FinishPasskeyRequest) returns (FinishPasskeyResponse);
rpc ListPasskeys(ListPasskeysRequest) returns (ListPasskeysResponse);
rpc DeletePasskey(DeletePasskeyRequest) returns (DeletePasskeyResponse);
rpc OpenAccountSession(OpenAccountSessionRequest) returns (OpenAccountSessionResponse);
rpc RequireFreshAccountSession(RequireFreshAccountSessionRequest) returns (RequireFreshAccountSessionResponse);
rpc CreateAccountRecovery(CreateAccountRecoveryRequest) returns (CreateAccountRecoveryResponse);
rpc RecoverAccount(RecoverAccountRequest) returns (RecoverAccountResponse);
rpc AccountSetup(AccountSetupRequest) returns (AccountSetupResponse);
rpc RegisterAccount(RegisterAccountRequest) returns (RegisterAccountResponse);
rpc SignInAccount(SignInAccountRequest) returns (SignInAccountResponse);
rpc ResolveAccountSession(ResolveAccountSessionRequest) returns (ResolveAccountSessionResponse);
rpc SignOutAccount(SignOutAccountRequest) returns (SignOutAccountResponse);
rpc ChangeAccountPassword(ChangeAccountPasswordRequest) returns (ChangeAccountPasswordResponse);
rpc GetIdentity(GetIdentityRequest) returns (GetIdentityResponse);
rpc CreateIdentity(CreateIdentityRequest) returns (CreateIdentityResponse);
rpc RenameIdentity(RenameIdentityRequest) returns (RenameIdentityResponse);
@@ -1720,3 +1736,59 @@ message RecordAlertAttemptRequest {
string error = 4;
}
message RecordAlertAttemptResponse {}
message AccountSetupRequest {}
message AccountSetupResponse { bool required = 1; }
message RegisterAccountRequest {
string email = 1;
string display_name = 2;
string password = 3;
string role = 4;
bool bootstrap = 5;
string organisation_name = 6;
string workspace_name = 7;
string public_url = 8;
}
message RegisterAccountResponse { Identity identity = 1; }
message SignInAccountRequest { string email = 1; string password = 2; }
message SignInAccountResponse {
Identity identity = 1;
string token = 2;
google.protobuf.Timestamp expires_at = 3;
}
message ResolveAccountSessionRequest { string token = 1; }
message ResolveAccountSessionResponse { Identity identity = 1; }
message SignOutAccountRequest { string token = 1; }
message SignOutAccountResponse {}
message ChangeAccountPasswordRequest { string current_password = 1; string new_password = 2; }
message ChangeAccountPasswordResponse {}
message AuthenticationSettings {
string public_url = 1;
string oidc_issuer = 2;
string oidc_audience = 3;
string oidc_client_id = 4;
}
message GetAuthenticationSettingsRequest {}
message GetAuthenticationSettingsResponse { AuthenticationSettings settings = 1; }
message SaveAuthenticationSettingsRequest { AuthenticationSettings settings = 1; }
message SaveAuthenticationSettingsResponse {}
message BeginPasskeyRequest { bool registration = 1; }
message BeginPasskeyResponse { string token = 1; bytes options = 2; }
message FinishPasskeyRequest { string token = 1; bytes credential = 2; bool registration = 3; string name = 4; }
message FinishPasskeyResponse { Identity identity = 1; string token = 2; google.protobuf.Timestamp expires_at = 3; }
message Passkey { string id = 1; string name = 2; }
message ListPasskeysRequest {}
message ListPasskeysResponse { repeated Passkey passkeys = 1; }
message DeletePasskeyRequest { string id = 1; }
message DeletePasskeyResponse {}
message OpenAccountSessionRequest { google.protobuf.Timestamp expires_at = 1; }
message OpenAccountSessionResponse { Identity identity = 1; string token = 2; google.protobuf.Timestamp expires_at = 3; }
message RequireFreshAccountSessionRequest { string token = 1; }
message RequireFreshAccountSessionResponse {}
message CreateAccountRecoveryRequest {}
message CreateAccountRecoveryResponse { string code = 1; }
message RecoverAccountRequest { string email = 1; string code = 2; string password = 3; }
message RecoverAccountResponse {}
+1
View File
@@ -0,0 +1 @@
import{A as e,Ct as t,D as n,Jt as r,O as i,_ as a,b as o,ht as s,kn as c,lt as l,nr as u,s as d,t as f,v as p,x as m,xt as h,yn as g}from"./PageHeader.js";import{W as _,h as v,n as y}from"./api.js";import{C as b,S as x,w as S,x as C}from"./index.js";var w={class:`max-w-2xl space-y-6`},T={class:`text-sm`},E={key:0,class:`rounded-lg border border-border bg-card p-4 text-sm`},D={key:1,role:`alert`,class:`text-sm text-danger`},O={class:`rounded-lg border border-border bg-card p-5`},k={class:`mt-4 divide-y divide-border`},A={class:`min-w-0 flex-1 truncate`},j={key:1,class:`mt-3 text-sm text-muted-foreground`},M={class:`rounded-lg border border-border bg-card p-5 space-y-3`},N={key:0,class:`break-all rounded border border-border p-3 font-mono text-sm`,role:`status`},P={class:`rounded-lg border border-border bg-card p-5`},F={class:`block space-y-1 text-sm`,for:`current-password`},I={class:`block space-y-1 text-sm`,for:`new-password`},L=e({__name:`AccountPage`,setup(e){let L=g(``),R=()=>J(async()=>{L.value=(await y.recoveryCode()).code}),z=x(),B=g([]),V=g(``),H=g(!1),U=g(``),W=g(``),G=g(``),K=a(()=>C(z.status?.public_url??``));async function q(){try{B.value=(await y.passkeys()).passkeys}catch(e){V.value=String(e.message||e)}}l(q);async function J(e){H.value=!0,V.value=``;try{await e()}catch(e){V.value=String(e.message||e)}finally{H.value=!1}}let Y=()=>J(async()=>{await b(!0,U.value),U.value=``,await q()}),X=e=>J(async()=>{await y.deletePasskey(e),await q()}),Z=()=>J(async()=>{await y.changePassword(W.value,G.value),W.value=G.value=``,window.location.assign(`/`)});return(e,a)=>{let l=t(`RouterLink`);return s(),m(`div`,w,[i(f,{title:`Your account`}),p(`p`,T,u(c(z).status?.user?.display_name),1),e.$route.query.welcome?(s(),m(`p`,E,[a[5]||=n(`Your organisation and admin account are ready. Add a passkey below, `,-1),i(l,{class:`underline`,to:`/org`},{default:r(()=>[...a[3]||=[n(`add accounts`,-1)]]),_:1}),a[6]||=n(`, or `,-1),i(l,{class:`underline`,to:`/settings/authentication`},{default:r(()=>[...a[4]||=[n(`configure OIDC`,-1)]]),_:1}),a[7]||=n(`.`,-1)])):o(``,!0),V.value?(s(),m(`p`,D,[n(u(V.value)+` `,1),a[8]||=p(`a`,{class:`underline`,href:`/?reauth=1`},`Sign in again`,-1)])):o(``,!0),p(`section`,O,[a[14]||=p(`h2`,{class:`font-medium`},`Passkeys`,-1),a[15]||=p(`p`,{class:`mt-1 text-sm text-muted-foreground`},`Sign in with your device or security key.`,-1),p(`ul`,k,[(s(!0),m(d,null,h(B.value,e=>(s(),m(`li`,{key:e.id,class:`flex items-center gap-3 py-2 text-sm`},[p(`span`,A,u(e.name),1),i(c(v),{variant:`ghost`,size:`sm`,disabled:H.value,onClick:t=>X(e.id)},{default:r(()=>[...a[9]||=[n(`Remove`,-1)]]),_:1},8,[`disabled`,`onClick`])]))),128))]),K.value?(s(),m(`form`,{key:0,class:`mt-3 flex flex-wrap gap-2`,onSubmit:_(Y,[`prevent`])},[i(c(S),{modelValue:U.value,"onUpdate:modelValue":a[0]||=e=>U.value=e,"aria-label":`Passkey name`,placeholder:`Passkey name (optional)`,maxlength:`200`,class:`min-w-40 flex-1`},null,8,[`modelValue`]),i(c(v),{type:`submit`,disabled:H.value},{default:r(()=>[...a[10]||=[n(`Add passkey`,-1)]]),_:1},8,[`disabled`])],32)):(s(),m(`p`,j,[a[12]||=n(`Open Archie at its configured HTTPS domain, or localhost, in a browser that supports passkeys. The instance URL is managed in `,-1),i(l,{class:`underline`,to:`/settings/authentication`},{default:r(()=>[...a[11]||=[n(`Authentication settings`,-1)]]),_:1}),a[13]||=n(`.`,-1)]))]),p(`section`,M,[a[17]||=p(`h2`,{class:`font-medium`},`Recovery code`,-1),a[18]||=p(`p`,{class:`text-sm text-muted-foreground`},`Save this once-only code somewhere safe. It resets your password if you lose access. Generating a new code replaces the previous one.`,-1),i(c(v),{disabled:H.value,onClick:R},{default:r(()=>[...a[16]||=[n(`Generate recovery code`,-1)]]),_:1},8,[`disabled`]),L.value?(s(),m(`p`,N,u(L.value),1)):o(``,!0)]),p(`section`,P,[a[23]||=p(`h2`,{class:`font-medium`},`Change password`,-1),p(`form`,{class:`mt-4 max-w-sm space-y-3`,onSubmit:_(Z,[`prevent`])},[p(`label`,F,[a[19]||=n(`Current password`,-1),i(c(S),{id:`current-password`,modelValue:W.value,"onUpdate:modelValue":a[1]||=e=>W.value=e,type:`password`,autocomplete:`current-password`,required:``},null,8,[`modelValue`])]),p(`label`,I,[a[20]||=n(`New password`,-1),i(c(S),{id:`new-password`,modelValue:G.value,"onUpdate:modelValue":a[2]||=e=>G.value=e,type:`password`,autocomplete:`new-password`,required:``,minlength:`15`,maxlength:`1024`},null,8,[`modelValue`])]),a[22]||=p(`p`,{class:`text-xs text-muted-foreground`},`Changing your password signs out all your sessions.`,-1),i(c(v),{type:`submit`,disabled:H.value},{default:r(()=>[...a[21]||=[n(`Change password`,-1)]]),_:1},8,[`disabled`])],32)])])}}});export{L as default};
+1 -1
View File
@@ -1 +1 @@
import{b as e,d as t,o as n,s as r,t as i}from"./CardAccordion.js";import{A as a,D as o,Jt as s,O as c,_ as l,b as u,ht as d,kn as f,lt as p,nr as m,t as h,v as g,x as _,yn as v}from"./PageHeader.js";import{X as y,o as b}from"./alert.js";import{y as x}from"./index.js";var S={key:0,class:`mb-4 text-sm text-destructive`,role:`alert`},C={key:1,class:`text-sm text-fg-muted`},w=`agent-profiles`,T=a({__name:`AgentProfilesPage`,setup(a){let T=t();p(T.load);let E=l(()=>T.drafts[w]?.value),D=v(``),O=v(``),k=l(()=>T.changesFor(w).length>0),A=l(()=>Object.entries(E.value??{}));function j(){if(k.value)return;let e=D.value.trim();if(!e||E.value?.[e])return;let t=T.drafts[w];t&&(t.value||={},t.value[e]={image:``,kit:``,adapter:``,tools:[]},D.value=``,O.value=String(Object.keys(t.value).indexOf(e)))}function M(e,t){e.tools=String(t).split(`,`).map(e=>e.trim()).filter(Boolean)}return(t,a)=>(d(),_(`div`,null,[c(h,{title:`Agent profiles`},{default:s(()=>[c(n,{kinds:[w]},null,8,[`kinds`])]),_:1}),c(r,{kind:w,class:`mb-4`}),f(T).catalogError||f(T).pageErrorFor(w)?(d(),_(`p`,S,m(f(T).catalogError||f(T).pageErrorFor(w)),1)):u(``,!0),g(`form`,{class:`mb-4 flex gap-2`,onSubmit:y(j,[`prevent`])},[c(f(e),{modelValue:D.value,"onUpdate:modelValue":a[0]||=e=>D.value=e,"aria-label":`Profile name`,placeholder:`Profile name`,class:`max-w-xs`,disabled:k.value},null,8,[`modelValue`,`disabled`]),c(f(b),{type:`submit`,disabled:k.value||!D.value.trim()||!!E.value?.[D.value.trim()]},{default:s(()=>[...a[3]||=[o(`Add profile`,-1)]]),_:1},8,[`disabled`])],32),Object.keys(E.value??{}).length?u(``,!0):(d(),_(`p`,C,`No agent profiles.`)),c(i,{open:O.value,"onUpdate:open":a[1]||=e=>O.value=e,items:A.value,title:([e])=>e,"remove-label":`Remove`,mono:``,onRemove:a[2]||=e=>delete E.value[A.value[e][0]]},{default:s(({item:[t,n]})=>[c(f(x),{label:`Image`,for:`${t}-image`},{default:s(()=>[c(f(e),{id:`${t}-image`,modelValue:n.image,"onUpdate:modelValue":e=>n.image=e,placeholder:`Container image`},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),c(f(x),{label:`Kit`,for:`${t}-kit`,hint:`Pinned digest. Used only when Image is empty.`},{default:s(()=>[c(f(e),{id:`${t}-kit`,modelValue:n.kit,"onUpdate:modelValue":e=>n.kit=e,placeholder:`registry/kit@sha256:…`},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),c(f(x),{label:`Adapter`,for:`${t}-adapter`},{default:s(()=>[c(f(e),{id:`${t}-adapter`,modelValue:n.adapter,"onUpdate:modelValue":e=>n.adapter=e},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),c(f(x),{label:`Tools`,for:`${t}-tools`,hint:`Comma-separated tool names.`},{default:s(()=>[c(f(e),{id:`${t}-tools`,"model-value":(n.tools??[]).join(`, `),"onUpdate:modelValue":e=>M(n,e)},null,8,[`id`,`model-value`,`onUpdate:modelValue`])]),_:2},1032,[`for`])]),_:1},8,[`open`,`items`,`title`])]))}});export{T as default};
import{d as e,o as t,s as n,t as r}from"./CardAccordion.js";import{A as i,D as a,Jt as o,O as s,_ as c,b as l,ht as u,kn as d,lt as f,nr as p,t as m,v as h,x as g,yn as _}from"./PageHeader.js";import{W as v,h as y}from"./api.js";import{w as b,y as x}from"./index.js";var S={key:0,class:`mb-4 text-sm text-destructive`,role:`alert`},C={key:1,class:`text-sm text-fg-muted`},w=`agent-profiles`,T=i({__name:`AgentProfilesPage`,setup(i){let T=e();f(T.load);let E=c(()=>T.drafts[w]?.value),D=_(``),O=_(``),k=c(()=>T.changesFor(w).length>0),A=c(()=>Object.entries(E.value??{}));function j(){if(k.value)return;let e=D.value.trim();if(!e||E.value?.[e])return;let t=T.drafts[w];t&&(t.value||={},t.value[e]={image:``,kit:``,adapter:``,tools:[]},D.value=``,O.value=String(Object.keys(t.value).indexOf(e)))}function M(e,t){e.tools=String(t).split(`,`).map(e=>e.trim()).filter(Boolean)}return(e,i)=>(u(),g(`div`,null,[s(m,{title:`Agent profiles`},{default:o(()=>[s(t,{kinds:[w]},null,8,[`kinds`])]),_:1}),s(n,{kind:w,class:`mb-4`}),d(T).catalogError||d(T).pageErrorFor(w)?(u(),g(`p`,S,p(d(T).catalogError||d(T).pageErrorFor(w)),1)):l(``,!0),h(`form`,{class:`mb-4 flex gap-2`,onSubmit:v(j,[`prevent`])},[s(d(b),{modelValue:D.value,"onUpdate:modelValue":i[0]||=e=>D.value=e,"aria-label":`Profile name`,placeholder:`Profile name`,class:`max-w-xs`,disabled:k.value},null,8,[`modelValue`,`disabled`]),s(d(y),{type:`submit`,disabled:k.value||!D.value.trim()||!!E.value?.[D.value.trim()]},{default:o(()=>[...i[3]||=[a(`Add profile`,-1)]]),_:1},8,[`disabled`])],32),Object.keys(E.value??{}).length?l(``,!0):(u(),g(`p`,C,`No agent profiles.`)),s(r,{open:O.value,"onUpdate:open":i[1]||=e=>O.value=e,items:A.value,title:([e])=>e,"remove-label":`Remove`,mono:``,onRemove:i[2]||=e=>delete E.value[A.value[e][0]]},{default:o(({item:[e,t]})=>[s(d(x),{label:`Image`,for:`${e}-image`},{default:o(()=>[s(d(b),{id:`${e}-image`,modelValue:t.image,"onUpdate:modelValue":e=>t.image=e,placeholder:`Container image`},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),s(d(x),{label:`Kit`,for:`${e}-kit`,hint:`Pinned digest. Used only when Image is empty.`},{default:o(()=>[s(d(b),{id:`${e}-kit`,modelValue:t.kit,"onUpdate:modelValue":e=>t.kit=e,placeholder:`registry/kit@sha256:…`},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),s(d(x),{label:`Adapter`,for:`${e}-adapter`},{default:o(()=>[s(d(b),{id:`${e}-adapter`,modelValue:t.adapter,"onUpdate:modelValue":e=>t.adapter=e},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),s(d(x),{label:`Tools`,for:`${e}-tools`,hint:`Comma-separated tool names.`},{default:o(()=>[s(d(b),{id:`${e}-tools`,"model-value":(t.tools??[]).join(`, `),"onUpdate:modelValue":e=>M(t,e)},null,8,[`id`,`model-value`,`onUpdate:modelValue`])]),_:2},1032,[`for`])]),_:1},8,[`open`,`items`,`title`])]))}});export{T as default};
+1
View File
@@ -0,0 +1 @@
import{A as e,Ct as t,D as n,Jt as r,O as i,b as a,ht as o,kn as s,lt as c,nr as l,t as u,v as d,x as f,yn as p}from"./PageHeader.js";import{W as m,h,n as g}from"./api.js";import{w as _}from"./index.js";var v={class:`max-w-2xl`},y={key:0,class:`mb-4 text-sm text-danger`,role:`alert`},b={class:`space-y-3 rounded-lg border border-border bg-card p-5`},x={for:`instance-url`,class:`block space-y-1 text-sm`},S={class:`space-y-3 rounded-lg border border-border bg-card p-5`},C={for:`oidc-issuer`,class:`block space-y-1 text-sm`},w={for:`oidc-client`,class:`block space-y-1 text-sm`},T={for:`oidc-audience`,class:`block space-y-1 text-sm`},E={class:`break-all text-xs text-muted-foreground`},D={class:`text-xs text-muted-foreground`},O={key:0,role:`status`,class:`text-sm`},k=e({__name:`AuthenticationPage`,setup(e){let k=p({public_url:``,oidc_issuer:``,oidc_audience:``,oidc_client_id:``}),A=p(!1),j=p(``),M=p(!1),N=p(!1);c(async()=>{try{k.value=await g.authentication(),A.value=!0}catch(e){j.value=String(e.message||e)}});async function P(){M.value=!0,j.value=``,N.value=!1;try{await g.saveAuthentication(k.value),N.value=!0}catch(e){j.value=String(e.message||e)}finally{M.value=!1}}return(e,c)=>{let p=t(`RouterLink`);return o(),f(`div`,v,[i(u,{title:`Authentication`}),j.value?(o(),f(`p`,y,[n(l(j.value)+` `,1),c[4]||=d(`a`,{class:`underline`,href:`/?reauth=1`},`Sign in again`,-1)])):a(``,!0),A.value?(o(),f(`form`,{key:1,class:`space-y-6`,onSubmit:m(P,[`prevent`])},[d(`section`,b,[c[6]||=d(`h2`,{class:`font-medium`},`Instance URL`,-1),d(`label`,x,[c[5]||=n(`Public address`,-1),i(s(_),{id:`instance-url`,modelValue:k.value.public_url,"onUpdate:modelValue":c[0]||=e=>k.value.public_url=e,type:`url`,required:``},null,8,[`modelValue`])]),c[7]||=d(`p`,{class:`text-xs text-muted-foreground`},`Passkeys require HTTPS and a domain name, or localhost. Once passkeys are enrolled, their domain is fixed.`,-1)]),d(`section`,S,[c[14]||=d(`h2`,{class:`font-medium`},`OpenID Connect`,-1),c[15]||=d(`p`,{class:`text-sm text-muted-foreground`},`Register a public client with authorization code flow and PKCE. Local accounts remain available.`,-1),d(`label`,C,[c[8]||=n(`Issuer URL`,-1),i(s(_),{id:`oidc-issuer`,modelValue:k.value.oidc_issuer,"onUpdate:modelValue":c[1]||=e=>k.value.oidc_issuer=e,type:`url`,placeholder:`https://identity.example.com`},null,8,[`modelValue`])]),d(`label`,w,[c[9]||=n(`Client ID`,-1),i(s(_),{id:`oidc-client`,modelValue:k.value.oidc_client_id,"onUpdate:modelValue":c[2]||=e=>k.value.oidc_client_id=e},null,8,[`modelValue`])]),d(`label`,T,[c[10]||=n(`Access token audience`,-1),i(s(_),{id:`oidc-audience`,modelValue:k.value.oidc_audience,"onUpdate:modelValue":c[3]||=e=>k.value.oidc_audience=e},null,8,[`modelValue`])]),d(`p`,E,`Redirect URI: `+l(k.value.public_url.replace(/\/$/,``))+`/oauth2/callback`,1),d(`p`,D,[c[12]||=n(`Add permitted people by their verified email or provider subject in `,-1),i(p,{class:`underline`,to:`/org`},{default:r(()=>[...c[11]||=[n(`Organisation members`,-1)]]),_:1}),c[13]||=n(`. Clear the OIDC fields to disable provider sign-in.`,-1)])]),N.value?(o(),f(`p`,O,`Authentication settings saved.`)):a(``,!0),i(s(h),{type:`submit`,disabled:M.value},{default:r(()=>[...c[16]||=[n(`Save`,-1)]]),_:1},8,[`disabled`])],32)):a(``,!0)])}}});export{k as default};
+2 -2
View File
@@ -1,3 +1,3 @@
import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Cn as s,Ct as c,D as l,Dn as u,Dt as d,E as f,En as p,Et as m,F as h,Ft as g,G as _,Gt as v,H as y,Ht as b,I as x,It as S,J as C,Jt as w,K as T,Kt as E,L as ee,Lt as te,M as D,Mn as ne,Mt as re,N as ie,Nn as ae,Nt as oe,O,On as se,Ot as ce,P as le,Pt as ue,Q as de,Qn as fe,Qt as pe,R as me,Rt as he,S as ge,Sn as _e,St as k,T as ve,Tn as ye,Tt as be,U as xe,Ut as A,V as Se,Vt as Ce,W as we,Wt as j,X as Te,Xt as Ee,Y as De,Yt as Oe,Z as ke,Zt as Ae,_ as M,_n as je,_t as Me,a as Ne,an as Pe,at as Fe,b as Ie,bn as Le,bt as Re,c as ze,cn as Be,ct as Ve,d as He,dn as N,dt as Ue,en as We,er as Ge,et as Ke,f as qe,fn as Je,ft as Ye,g as Xe,gn as Ze,gt as Qe,h as $e,hn as et,ht as P,i as tt,in as nt,it as rt,j as it,jt as at,k as ot,kn as F,kt as st,l as ct,ln as lt,lt as ut,m as dt,mn as ft,mt as pt,n as mt,nn as ht,nr as gt,nt as I,o as _t,on as vt,ot as yt,p as bt,pn as xt,pt as St,q as Ct,qt as wt,r as Tt,rn as Et,rr as Dt,rt as Ot,s as kt,sn as At,st as jt,tn as Mt,tr as Nt,tt as L,u as Pt,un as Ft,ut as It,v as Lt,vn as Rt,vt as zt,w as Bt,wn as Vt,wt as Ht,x as Ut,xn as Wt,xt as Gt,y as R,yn as z,yt as Kt,z as qt,zt as Jt}from"./PageHeader.js";import{A as Yt,B as Xt,C as Zt,D as Qt,E as $t,F as en,G as tn,H as nn,I as rn,J as an,K as on,L as sn,M as cn,N as ln,O as un,P as dn,R as fn,T as pn,U as mn,V as hn,W as gn,X as _n,Y as vn,b as yn,d as bn,f as xn,g as Sn,i as Cn,j as wn,k as Tn,m as B,n as En,o as Dn,q as On,r as kn,t as An,v as jn,w as Mn,x as Nn,z as Pn}from"./alert.js";var Fn=Object.defineProperty,In=((e,t)=>{let n={};for(var r in e)Fn(n,r,{get:e[r],enumerable:!0});return t||Fn(n,Symbol.toStringTag,{value:`Module`}),n})({BaseTransition:()=>mt,BaseTransitionPropsValidators:()=>Tt,Comment:()=>tt,DeprecationTypes:()=>null,EffectScope:()=>t,ErrorCodes:()=>Ne,ErrorTypeStrings:()=>_t,Fragment:()=>kt,KeepAlive:()=>ze,ReactiveEffect:()=>We,Static:()=>ct,Suspense:()=>Pt,Teleport:()=>He,Text:()=>qe,TrackOpTypes:()=>Mt,Transition:()=>Qt,TransitionGroup:()=>un,TriggerOpTypes:()=>ht,VueElement:()=>Tn,assertNumber:()=>bt,callWithAsyncErrorHandling:()=>dt,callWithErrorHandling:()=>$e,camelize:()=>ne,capitalize:()=>ae,cloneVNode:()=>Xe,compatUtils:()=>null,compile:()=>Ln,computed:()=>M,createApp:()=>Yt,createBlock:()=>R,createCommentVNode:()=>Ie,createElementBlock:()=>Ut,createElementVNode:()=>Lt,createHydrationRenderer:()=>ge,createPropsRestProxy:()=>o,createRenderer:()=>Bt,createSSRApp:()=>wn,createSlots:()=>ve,createStaticVNode:()=>f,createTextVNode:()=>l,createVNode:()=>O,customRef:()=>Et,defineAsyncComponent:()=>ot,defineComponent:()=>n,defineCustomElement:()=>cn,defineEmits:()=>it,defineExpose:()=>D,defineModel:()=>ie,defineOptions:()=>le,defineProps:()=>h,defineSSRCustomElement:()=>ln,defineSlots:()=>x,devtools:()=>ee,effect:()=>nt,effectScope:()=>Pe,getCurrentInstance:()=>me,getCurrentScope:()=>vt,getCurrentWatcher:()=>At,getTransitionRawChildren:()=>qt,guardReactiveProps:()=>i,h:()=>Se,handleError:()=>y,hasInjectionContext:()=>xe,hydrate:()=>dn,hydrateOnIdle:()=>we,hydrateOnInteraction:()=>_,hydrateOnMediaQuery:()=>T,hydrateOnVisible:()=>Ct,initCustomFormatter:()=>C,initDirectivesForSSR:()=>en,inject:()=>De,isMemoSame:()=>Te,isProxy:()=>Be,isReactive:()=>lt,isReadonly:()=>Ft,isRef:()=>N,isRuntimeOnly:()=>ke,isShallow:()=>Je,isVNode:()=>de,markRaw:()=>xt,mergeDefaults:()=>e,mergeModels:()=>Ke,mergeProps:()=>L,nextTick:()=>I,nodeOps:()=>rn,normalizeClass:()=>fe,normalizeProps:()=>Ge,normalizeStyle:()=>Nt,onActivated:()=>Ot,onBeforeMount:()=>rt,onBeforeUnmount:()=>Fe,onBeforeUpdate:()=>yt,onDeactivated:()=>jt,onErrorCaptured:()=>Ve,onMounted:()=>ut,onRenderTracked:()=>It,onRenderTriggered:()=>Ue,onScopeDispose:()=>ft,onServerPrefetch:()=>Ye,onUnmounted:()=>St,onUpdated:()=>pt,onWatcherCleanup:()=>et,openBlock:()=>P,patchProp:()=>sn,popScopeId:()=>Qe,provide:()=>Me,proxyRefs:()=>Ze,pushScopeId:()=>zt,queuePostFlushCb:()=>Kt,reactive:()=>je,readonly:()=>Rt,ref:()=>z,registerRuntimeCompiler:()=>Re,render:()=>fn,renderList:()=>Gt,renderSlot:()=>k,resolveComponent:()=>c,resolveDirective:()=>Ht,resolveDynamicComponent:()=>be,resolveFilter:()=>null,resolveTransitionHooks:()=>m,setBlockTracking:()=>d,setDevtoolsHook:()=>ce,setTransitionHooks:()=>st,shallowReactive:()=>Le,shallowReadonly:()=>Wt,shallowRef:()=>_e,ssrContextKey:()=>r,ssrUtils:()=>at,stop:()=>s,toDisplayString:()=>gt,toHandlerKey:()=>Dt,toHandlers:()=>re,toRaw:()=>Vt,toRef:()=>ye,toRefs:()=>p,toValue:()=>u,transformVNodeArgs:()=>oe,triggerRef:()=>se,unref:()=>F,useAttrs:()=>ue,useCssModule:()=>Pn,useCssVars:()=>Xt,useHost:()=>hn,useId:()=>g,useModel:()=>S,useSSRContext:()=>te,useShadowRoot:()=>nn,useSlots:()=>he,useTemplateRef:()=>Jt,useTransitionState:()=>a,vModelCheckbox:()=>mn,vModelDynamic:()=>gn,vModelRadio:()=>tn,vModelSelect:()=>on,vModelText:()=>On,vShow:()=>an,version:()=>Ce,warn:()=>b,watch:()=>A,watchEffect:()=>j,watchPostEffect:()=>v,watchSyncEffect:()=>E,withAsyncContext:()=>wt,witLine truncated
import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Cn as s,Ct as c,D as l,Dn as u,Dt as d,E as f,En as p,Et as m,F as h,Ft as g,G as _,Gt as v,H as y,Ht as b,I as x,It as S,J as C,Jt as w,K as T,Kt as E,L as ee,Lt as te,M as D,Mn as ne,Mt as re,N as ie,Nn as ae,Nt as oe,O,On as se,Ot as ce,P as le,Pt as ue,Q as de,Qn as fe,Qt as pe,R as me,Rt as he,S as ge,Sn as _e,St as k,T as ve,Tn as ye,Tt as be,U as xe,Ut as A,V as Se,Vt as Ce,W as we,Wt as j,X as Te,Xt as Ee,Y as De,Yt as Oe,Z as ke,Zt as Ae,_ as M,_n as je,_t as Me,a as Ne,an as Pe,at as Fe,b as Ie,bn as Le,bt as Re,c as ze,cn as Be,ct as Ve,d as He,dn as Ue,dt as We,en as Ge,er as Ke,et as qe,f as Je,fn as Ye,ft as Xe,g as Ze,gn as Qe,gt as $e,h as et,hn as tt,ht as N,i as nt,in as rt,it,j as at,jt as ot,k as st,kn as P,kt as ct,l as lt,ln as ut,lt as dt,m as ft,mn as pt,mt,n as ht,nn as gt,nr as _t,nt as F,o as vt,on as yt,ot as bt,p as xt,pn as St,pt as Ct,q as wt,qt as Tt,r as Et,rn as Dt,rr as Ot,rt as kt,s as At,sn as jt,st as Mt,tn as Nt,tr as Pt,tt as I,u as Ft,un as It,ut as Lt,v as Rt,vn as zt,vt as Bt,w as Vt,wn as Ht,wt as Ut,x as Wt,xn as Gt,xt as Kt,y as L,yn as R,yt as qt,z as Jt,zt as Yt}from"./PageHeader.js";import{A as Xt,B as Zt,C as Qt,D as $t,E as en,F as tn,H as nn,I as rn,L as an,M as on,N as sn,O as cn,P as ln,R as un,S as dn,T as fn,U as pn,V as mn,W as hn,_ as z,a as gn,f as _n,g as vn,h as yn,i as bn,j as xn,k as Sn,n as Cn,s as wn,w as Tn,x as En,y as Dn,z as On}from"./api.js";import{n as kn}from"./pinia.js";import{a as An,i as jn,n as Mn,o as Nn,r as Pn,t as Fn}from"./alert.js";var In=Object.defineProperty,Ln=((e,t)=>{let n={};for(var r in e)In(n,r,{get:e[r],enumerable:!0});return t||In(n,Symbol.toStringTag,{value:`Module`}),n})({BaseTransition:()=>ht,BaseTransitionPropsValidators:()=>Et,Comment:()=>nt,DeprecationTypes:()=>null,EffectScope:()=>t,ErrorCodes:()=>Ne,ErrorTypeStrings:()=>vt,Fragment:()=>At,KeepAlive:()=>ze,ReactiveEffect:()=>Ge,Static:()=>lt,Suspense:()=>Ft,Teleport:()=>He,Text:()=>Je,TrackOpTypes:()=>Nt,Transition:()=>En,TransitionGroup:()=>dn,TriggerOpTypes:()=>gt,VueElement:()=>Qt,assertNumber:()=>xt,callWithAsyncErrorHandling:()=>ft,callWithErrorHandling:()=>et,camelize:()=>ne,capitalize:()=>ae,cloneVNode:()=>Ze,compatUtils:()=>null,compile:()=>Rn,computed:()=>M,createApp:()=>Tn,createBlock:()=>L,createCommentVNode:()=>Ie,createElementBlock:()=>Wt,createElementVNode:()=>Rt,createHydrationRenderer:()=>ge,createPropsRestProxy:()=>o,createRenderer:()=>Vt,createSSRApp:()=>fn,createSlots:()=>ve,createStaticVNode:()=>f,createTextVNode:()=>l,createVNode:()=>O,customRef:()=>Dt,defineAsyncComponent:()=>st,defineComponent:()=>n,defineCustomElement:()=>en,defineEmits:()=>at,defineExpose:()=>D,defineModel:()=>ie,defineOptions:()=>le,defineProps:()=>h,defineSSRCustomElement:()=>$t,defineSlots:()=>x,devtools:()=>ee,effect:()=>rt,effectScope:()=>Pe,getCurrentInstance:()=>me,getCurrentScope:()=>yt,getCurrentWatcher:()=>jt,getTransitionRawChildren:()=>Jt,guardReactiveProps:()=>i,h:()=>Se,handleError:()=>y,hasInjectionContext:()=>xe,hydrate:()=>cn,hydrateOnIdle:()=>we,hydrateOnInteraction:()=>_,hydrateOnMediaQuery:()=>T,hydrateOnVisible:()=>wt,initCustomFormatter:()=>C,initDirectivesForSSR:()=>Sn,inject:()=>De,isMemoSame:()=>Te,isProxy:()=>Be,isReactive:()=>ut,isReadonly:()=>It,isRef:()=>Ue,isRuntimeOnly:()=>ke,isShallow:()=>Ye,isVNode:()=>de,markRaw:()=>St,mergeDefaults:()=>e,mergeModels:()=>qe,mergeProps:()=>I,nextTick:()=>F,nodeOps:()=>Xt,normalizeClass:()=>fe,normalizeProps:()=>Ke,normalizeStyle:()=>Pt,onActivated:()=>kt,onBeforeMount:()=>it,onBeforeUnmount:()=>Fe,onBeforeUpdate:()=>bt,onDeactivated:()=>Mt,onErrorCaptured:()=>Ve,onMounted:()=>dt,onRenderTracked:()=>Lt,onRenderTriggered:()=>We,onScopeDispose:()=>pt,onServerPrefetch:()=>Xe,onUnmounted:()=>Ct,onUpdated:()=>mt,onWatcherCleanup:()=>tt,openBlock:()=>N,patchProp:()=>xn,popScopeId:()=>$e,provide:()=>Me,proxyRefs:()=>Qe,pushScopeId:()=>Bt,queuePostFlushCb:()=>qt,reactive:()=>je,readonly:()=>zt,ref:()=>R,registerRuntimeCompiler:()=>Re,render:()=>on,renderList:()=>Kt,renderSlot:()=>k,resolveComponent:()=>c,resolveDirective:()=>Ut,resolveDynamicComponent:()=>be,resolveFilter:()=>null,resolveTransitionHooks:()=>m,setBlockTracking:()=>d,setDevtoolsHook:()=>ce,setTransitionHooks:()=>ct,shallowReactive:()=>Le,shallowReadonly:()=>Gt,shallowRef:()=>_e,ssrContextKey:()=>r,ssrUtils:()=>ot,stop:()=>s,toDisplayString:()=>_t,toHandlerKey:()=>Ot,toHandlers:()=>re,toRaw:()=>Ht,toRef:()=>ye,toRefs:()=>p,toValue:()=>u,transformVNodeArgs:()=>oe,triggerRef:()=>se,unref:()=>P,useAttrs:()=>ue,useCssModule:()=>sn,useCssVars:()=>ln,useHost:()=>tn,useId:()=>g,useModel:()=>S,useSSRContext:()=>te,useShadowRoot:()=>rn,useSlots:()=>he,useTemplateRef:()=>Yt,useTransitionState:()=>a,vModelCheckbox:()=>an,vModelDynamic:()=>un,vModelRadio:()=>On,vModelSelect:()=>Zt,vModelText:()=>mn,vShow:()=>nn,version:()=>Ce,warn:()=>b,watch:()=>A,watchEffect:()=>j,watchPostEffect:()=>v,watchSyncEffeLine truncated
`)].join(`
`))}return()=>i.value||r.value||o.value?Se(t.default({present:o.value})[0],{ref:e=>{let t=U(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),[$i,ea]=Er(`CollapsibleRoot`),ta=n({__name:`CollapsibleRoot`,props:{defaultOpen:{type:Boolean,required:!1,default:!1},open:{type:Boolean,required:!1,default:void 0},disabled:{type:Boolean,required:!1},unmountOnHide:{type:Boolean,required:!1,default:!0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:open`],setup(e,{expose:t,emit:n}){let r=e,i=di(r,`open`,n,{defaultValue:r.defaultOpen,passive:r.open===void 0}),{disabled:a,unmountOnHide:o}=p(r);return ea({contentId:``,disabled:a,open:i,unmountOnHide:o,onOpenToggle:()=>{a.value||(i.value=!i.value)}}),t({open:i}),W(),(t,n)=>(P(),R(F(B),{as:e.as,"as-child":r.asChild,"data-state":F(i)?`open`:`closed`,"data-disabled":F(a)?``:void 0},{default:w(()=>[k(t.$slots,`default`,{open:F(i)})]),_:3},8,[`as`,`as-child`,`data-state`,`data-disabled`]))}}),na=n({inheritAttrs:!1,__name:`CollapsibleContent`,props:{forceMount:{type:Boolean,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`contentFound`],setup(e,{emit:t}){let n=e,r=t,i=$i();i.contentId||=qi(void 0,`reka-collapsible-content`);let a=z(),{forwardRef:o,currentElement:s}=W(),c=z(0),l=z(0),u=M(()=>i.open.value),d=z(u.value),f=z();A(()=>[u.value,a.value?.present],async()=>{await I();let e=s.value;if(!e)return;f.value=f.value||{transitionDuration:e.style.transitionDuration,animationName:e.style.animationName},e.style.transitionDuration=`0s`,e.style.animationName=`none`;let t=e.getBoundingClientRect();l.value=t.height,c.value=t.width,d.value||(e.style.transitionDuration=f.value.transitionDuration,e.style.animationName=f.value.animationName)},{immediate:!0});let p=M(()=>d.value&&i.open.value);return ut(()=>{requestAnimationFrame(()=>{d.value=!1})}),Zr(s,`beforematch`,e=>{requestAnimationFrame(()=>{i.onOpenToggle(),r(`contentFound`)})}),(t,r)=>(P(),R(F(Qi),{ref_key:`presentRef`,ref:a,present:e.forceMount||F(i).open.value,"force-mount":!0},{default:w(({present:r})=>[O(F(B),L(t.$attrs,{id:F(i).contentId,ref:F(o),"as-child":n.asChild,as:e.as,hidden:r?void 0:F(i).unmountOnHide.value?``:`until-found`,"data-state":p.value?void 0:F(i).open.value?`open`:`closed`,"data-disabled":F(i).disabled?.value?``:void 0,style:{"--reka-collapsible-content-height":`${l.value}px`,"--reka-collapsible-content-width":`${c.value}px`}}),{default:w(()=>[!F(i).unmountOnHide.value||r?k(t.$slots,`default`,{},void 0,void 0,0):Ie(`v-if`,!0)]),_:2},1040,[`id`,`as-child`,`as`,`hidden`,`data-state`,`data-disabled`,`style`])]),_:3},8,[`present`]))}}),ra=n({__name:`CollapsibleTrigger`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;W();let n=$i();return(r,i)=>(P(),R(F(B),{type:e.as===`button`?`button`:void 0,as:e.as,"as-child":t.asChild,"aria-controls":F(n).contentId,"aria-expanded":F(n).open.value,"data-state":F(n).open.value?`open`:`closed`,"data-disabled":F(n).disabled?.value?``:void 0,disabled:F(n).disabled?.value,onClick:F(n).onOpenToggle},{default:w(()=>[k(r.$slots,`default`)]),_:3},8,[`type`,`as`,`as-child`,`aria-controls`,`aria-expanded`,`data-state`,`data-disabled`,`disabled`,`onClick`]))}});function ia({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function aa({type:e,defaultValue:t,modelValue:n}){return e||ia({type:e,defaultValue:t,modelValue:n})}function oa({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function sa(e,t){let n=M(()=>aa(e)),r=di(e,`modelValue`,t,{defaultValue:oa(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=Tr(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(kr(t,e)){let n=t.findIndex(t=>Tr(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:M(()=>n.value===`single`)}}var[ca,la]=Er(`AccordionRoot`),ua=n({__name:`AccordionRoot`,props:{collapsible:{type:Boolean,required:!1,default:!1},disabled:{type:Boolean,required:!1,default:!1},dir:{type:String,required:!1},orientation:{type:String,required:!1,default:`vertical`},unmountOnHide:{type:Boolean,required:!1,default:!0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},type:{type:String,required:!1},modelValue:{type:null,required:!1},defaultValue:{type:null,required:!1}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,{dir:i,disabled:a,unmountOnHide:o}=p(n),s=ki(i),{modelValue:c,changeModelValue:l,isSingle:u}=sa(n,r),{forwardRef:d,currentElement:f}=W();return la({disabled:a,direction:s,orientation:n.orientation,parentElement:f,isSingle:u,collapsible:n.collapsible,modelValue:c,changeModelValue:l,unmountOnHide:o}),(t,n)=>(P(),R(F(B),{ref:F(d),"as-child":e.asChild,as:e.as},{default:w(()=>[k(t.$sl Line truncated
`))}return()=>i.value||r.value||o.value?Se(t.default({present:o.value})[0],{ref:e=>{let t=H(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),[_i,vi]=Gn(`CollapsibleRoot`),yi=n({__name:`CollapsibleRoot`,props:{defaultOpen:{type:Boolean,required:!1,default:!1},open:{type:Boolean,required:!1,default:void 0},disabled:{type:Boolean,required:!1},unmountOnHide:{type:Boolean,required:!1,default:!0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:open`],setup(e,{expose:t,emit:n}){let r=e,i=kr(r,`open`,n,{defaultValue:r.defaultOpen,passive:r.open===void 0}),{disabled:a,unmountOnHide:o}=p(r);return vi({contentId:``,disabled:a,open:i,unmountOnHide:o,onOpenToggle:()=>{a.value||(i.value=!i.value)}}),t({open:i}),W(),(t,n)=>(N(),L(P(z),{as:e.as,"as-child":r.asChild,"data-state":P(i)?`open`:`closed`,"data-disabled":P(a)?``:void 0},{default:w(()=>[k(t.$slots,`default`,{open:P(i)})]),_:3},8,[`as`,`as-child`,`data-state`,`data-disabled`]))}}),bi=n({inheritAttrs:!1,__name:`CollapsibleContent`,props:{forceMount:{type:Boolean,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`contentFound`],setup(e,{emit:t}){let n=e,r=t,i=_i();i.contentId||=di(void 0,`reka-collapsible-content`);let a=R(),{forwardRef:o,currentElement:s}=W(),c=R(0),l=R(0),u=M(()=>i.open.value),d=R(u.value),f=R();A(()=>[u.value,a.value?.present],async()=>{await F();let e=s.value;if(!e)return;f.value=f.value||{transitionDuration:e.style.transitionDuration,animationName:e.style.animationName},e.style.transitionDuration=`0s`,e.style.animationName=`none`;let t=e.getBoundingClientRect();l.value=t.height,c.value=t.width,d.value||(e.style.transitionDuration=f.value.transitionDuration,e.style.animationName=f.value.animationName)},{immediate:!0});let p=M(()=>d.value&&i.open.value);return dt(()=>{requestAnimationFrame(()=>{d.value=!1})}),U(s,`beforematch`,e=>{requestAnimationFrame(()=>{i.onOpenToggle(),r(`contentFound`)})}),(t,r)=>(N(),L(P(gi),{ref_key:`presentRef`,ref:a,present:e.forceMount||P(i).open.value,"force-mount":!0},{default:w(({present:r})=>[O(P(z),I(t.$attrs,{id:P(i).contentId,ref:P(o),"as-child":n.asChild,as:e.as,hidden:r?void 0:P(i).unmountOnHide.value?``:`until-found`,"data-state":p.value?void 0:P(i).open.value?`open`:`closed`,"data-disabled":P(i).disabled?.value?``:void 0,style:{"--reka-collapsible-content-height":`${l.value}px`,"--reka-collapsible-content-width":`${c.value}px`}}),{default:w(()=>[!P(i).unmountOnHide.value||r?k(t.$slots,`default`,{},void 0,void 0,0):Ie(`v-if`,!0)]),_:2},1040,[`id`,`as-child`,`as`,`hidden`,`data-state`,`data-disabled`,`style`])]),_:3},8,[`present`]))}}),xi=n({__name:`CollapsibleTrigger`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;W();let n=_i();return(r,i)=>(N(),L(P(z),{type:e.as===`button`?`button`:void 0,as:e.as,"as-child":t.asChild,"aria-controls":P(n).contentId,"aria-expanded":P(n).open.value,"data-state":P(n).open.value?`open`:`closed`,"data-disabled":P(n).disabled?.value?``:void 0,disabled:P(n).disabled?.value,onClick:P(n).onOpenToggle},{default:w(()=>[k(r.$slots,`default`)]),_:3},8,[`type`,`as`,`as-child`,`aria-controls`,`aria-expanded`,`data-state`,`data-disabled`,`disabled`,`onClick`]))}});function Si({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Ci({type:e,defaultValue:t,modelValue:n}){return e||Si({type:e,defaultValue:t,modelValue:n})}function wi({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function Ti(e,t){let n=M(()=>Ci(e)),r=kr(e,`modelValue`,t,{defaultValue:wi(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=Wn(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Jn(t,e)){let n=t.findIndex(t=>Wn(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:M(()=>n.value===`single`)}}var[Ei,Di]=Gn(`AccordionRoot`),Oi=n({__name:`AccordionRoot`,props:{collapsible:{type:Boolean,required:!1,default:!1},disabled:{type:Boolean,required:!1,default:!1},dir:{type:String,required:!1},orientation:{type:String,required:!1,default:`vertical`},unmountOnHide:{type:Boolean,required:!1,default:!0},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},type:{type:String,required:!1},modelValue:{type:null,required:!1},defaultValue:{type:null,required:!1}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,{dir:i,disabled:a,unmountOnHide:o}=p(n),s=qr(i),{modelValue:c,changeModelValue:l,isSingle:u}=Ti(n,r),{forwardRef:d,currentElement:f}=W();return Di({disabled:a,direction:s,orientation:n.orientation,parentElement:f,isSingle:u,collapsible:n.collapsible,modelValue:c,changeModelValue:l,unmountOnHide:o}),(t,n)=>(N(),L(P(z),{ref:P(d),"as-child":e.asChild,as:e.as},{default:w(()=>[k(t.$slo Line truncated
+1 -1
View File
@@ -1 +1 @@
import{b as e,d as t,o as n,s as r,t as i}from"./CardAccordion.js";import{A as a,D as o,Jt as s,O as c,_ as l,b as u,ht as d,kn as f,lt as p,nr as m,t as h,x as g,yn as _}from"./PageHeader.js";import{o as v}from"./alert.js";import{v as y,y as b}from"./index.js";var x={key:0,class:`mb-4 text-sm text-destructive`,role:`alert`},S={key:1,class:`text-sm text-fg-muted`},C=`credential-bindings`,w=a({__name:`CredentialBindingsPage`,setup(a){let w=t();p(w.load);let T=l(()=>w.drafts[C]?.value),E=_(``),D=l(()=>w.changesFor(C).length>0);function O(){if(D.value)return;let e=w.drafts[C];e&&(e.value||=[],e.value.push({service:``,org:``,secret:{engine:``,key:``}}),E.value=String(e.value.length-1))}return(t,a)=>(d(),g(`div`,null,[c(h,{title:`Credential bindings`},{default:s(()=>[c(n,{kinds:[C]},null,8,[`kinds`]),c(f(v),{disabled:D.value,onClick:O},{default:s(()=>[...a[2]||=[o(`Add binding`,-1)]]),_:1},8,[`disabled`])]),_:1}),c(r,{kind:C,class:`mb-4`}),f(w).catalogError||f(w).pageErrorFor(C)?(d(),g(`p`,x,m(f(w).catalogError||f(w).pageErrorFor(C)),1)):u(``,!0),T.value?.length?u(``,!0):(d(),g(`p`,S,`No credential bindings.`)),c(i,{open:E.value,"onUpdate:open":a[0]||=e=>E.value=e,items:T.value??[],title:e=>e.service||`New binding`,"remove-label":`Remove`,mono:``,onRemove:a[1]||=e=>T.value.splice(e,1)},{default:s(({item:t,index:n})=>[c(f(b),{label:`Service`,for:`binding-${n}-service`},{default:s(()=>[c(f(e),{id:`binding-${n}-service`,modelValue:t.service,"onUpdate:modelValue":e=>t.service=e},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),c(f(b),{label:`Organisation`,for:`binding-${n}-org`,hint:`Empty uses the default organisation.`},{default:s(()=>[c(f(e),{id:`binding-${n}-org`,modelValue:t.org,"onUpdate:modelValue":e=>t.org=e},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),c(f(b),{label:`Secret`},{default:s(()=>[c(y,{modelValue:t.secret,"onUpdate:modelValue":e=>t.secret=e,"id-prefix":`binding-${n}-secret`},null,8,[`modelValue`,`onUpdate:modelValue`,`id-prefix`])]),_:2},1024)]),_:1},8,[`open`,`items`,`title`])]))}});export{w as default};
import{d as e,o as t,s as n,t as r}from"./CardAccordion.js";import{A as i,D as a,Jt as o,O as s,_ as c,b as l,ht as u,kn as d,lt as f,nr as p,t as m,x as h,yn as g}from"./PageHeader.js";import{h as _}from"./api.js";import{v,w as y,y as b}from"./index.js";var x={key:0,class:`mb-4 text-sm text-destructive`,role:`alert`},S={key:1,class:`text-sm text-fg-muted`},C=`credential-bindings`,w=i({__name:`CredentialBindingsPage`,setup(i){let w=e();f(w.load);let T=c(()=>w.drafts[C]?.value),E=g(``),D=c(()=>w.changesFor(C).length>0);function O(){if(D.value)return;let e=w.drafts[C];e&&(e.value||=[],e.value.push({service:``,org:``,secret:{engine:``,key:``}}),E.value=String(e.value.length-1))}return(e,i)=>(u(),h(`div`,null,[s(m,{title:`Credential bindings`},{default:o(()=>[s(t,{kinds:[C]},null,8,[`kinds`]),s(d(_),{disabled:D.value,onClick:O},{default:o(()=>[...i[2]||=[a(`Add binding`,-1)]]),_:1},8,[`disabled`])]),_:1}),s(n,{kind:C,class:`mb-4`}),d(w).catalogError||d(w).pageErrorFor(C)?(u(),h(`p`,x,p(d(w).catalogError||d(w).pageErrorFor(C)),1)):l(``,!0),T.value?.length?l(``,!0):(u(),h(`p`,S,`No credential bindings.`)),s(r,{open:E.value,"onUpdate:open":i[0]||=e=>E.value=e,items:T.value??[],title:e=>e.service||`New binding`,"remove-label":`Remove`,mono:``,onRemove:i[1]||=e=>T.value.splice(e,1)},{default:o(({item:e,index:t})=>[s(d(b),{label:`Service`,for:`binding-${t}-service`},{default:o(()=>[s(d(y),{id:`binding-${t}-service`,modelValue:e.service,"onUpdate:modelValue":t=>e.service=t},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),s(d(b),{label:`Organisation`,for:`binding-${t}-org`,hint:`Empty uses the default organisation.`},{default:o(()=>[s(d(y),{id:`binding-${t}-org`,modelValue:e.org,"onUpdate:modelValue":t=>e.org=t},null,8,[`id`,`modelValue`,`onUpdate:modelValue`])]),_:2},1032,[`for`]),s(d(b),{label:`Secret`},{default:o(()=>[s(v,{modelValue:e.secret,"onUpdate:modelValue":t=>e.secret=t,"id-prefix":`binding-${t}-secret`},null,8,[`modelValue`,`onUpdate:modelValue`,`id-prefix`])]),_:2},1024)]),_:1},8,[`open`,`items`,`title`])]))}});export{w as default};
+1 -1
View File
@@ -1 +1 @@
import{A as e,D as t,Jt as n,O as r,at as i,b as a,ht as o,kn as s,lt as c,nr as l,s as u,t as d,v as f,x as p,xt as m,y as h,yn as g}from"./PageHeader.js";import{_,i as v,n as y,o as b,r as x,t as S,v as C}from"./alert.js";import{_ as w,a as T,c as E,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as L,s as R,t as z,u as B}from"./index.js";function V(e,t=Date.now()){if(!e.captured)return`unconfigured`;if(!e.expires_at)return`ready`;let n=Date.parse(e.expires_at);return Number.isNaN(n)?`ready`:n<=t?`expired`:n-t<=18e5?`expiring`:`ready`}function H(e,t,n=80,r=24){let i=t.protocol===`https:`?`wss:`:`ws:`,a=new URLSearchParams({profile:e,cols:String(n),rows:String(r)}).toString();return`${i}//${t.host}/api/harness/terminal?${a}`}var U={class:`flex h-full min-h-0 flex-col gap-2`},W={key:0,class:`text-sm text-muted-foreground`,role:`status`},G=e({__name:`SetupTerminal`,props:{profile:{}},setup(e){let n=e,r=g(null),s=g(`connecting`),l=null,d=null,m=null,h=null;function _(){try{m?.fit()}catch{}}return c(()=>{let e=r.value;if(!e)return;l=new P({convertEol:!0,cursorBlink:!0,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`,cursor:`#e6edf3`,selectionBackground:`#264f78`}}),m=new z,l.loadAddon(m),l.open(e),_(),l.focus();let t=new WebSocket(H(n.profile,window.location,l?.cols??80,l?.rows??24));d=t,t.binaryType=`arraybuffer`,t.onopen=()=>{s.value=`open`},t.onmessage=e=>{l&&(typeof e.data==`string`?l.write(e.data):l.write(new Uint8Array(e.data)))},t.onerror=()=>{s.value=`failed`},t.onclose=()=>{s.value=`closed`},l.onData(e=>{t.readyState===WebSocket.OPEN&&t.send(e)}),h=new ResizeObserver(_),h.observe(e)}),i(()=>{h?.disconnect(),h=null,d?.close(),d=null,l?.dispose(),l=null,m=null}),(e,n)=>(o(),p(`div`,U,[s.value===`open`?a(``,!0):(o(),p(`p`,W,[s.value===`connecting`?(o(),p(u,{key:0},[t(`Connecting…`)],64)):s.value===`closed`?(o(),p(u,{key:1},[t(`The terminal session ended.`)],64)):(o(),p(u,{key:2},[t(`Could not open the setup terminal.`)],64))])),f(`div`,{ref_key:`host`,ref:r,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),K={key:0,class:`mb-4 text-sm text-danger`,role:`alert`},q={key:1,class:`space-y-2`},J={class:`flex flex-col gap-1 text-sm`},Y=e({__name:`HarnessPage`,setup(e){let i=g(null),P=g(!0),z=g(null),H=g(!1),U=g(``),W=g(!1),Y={ready:{label:`Ready`,variant:`ok`},expiring:{label:`Expiring soon`,variant:`warn`},expired:{label:`Expired`,variant:`danger`},unconfigured:{label:`Not set up`,variant:`idle`}};c(X);async function X(){P.value=!0,z.value=null,H.value=!1;try{let e=await C.harnessBindings();i.value={terminal:e.terminal,bindings:e.bindings??[],profiles:e.profiles??[]},U.value=i.value.profiles[0]??``}catch(e){let t=e instanceof _?e.status:void 0;t===501||t===503?H.value=!0:z.value=e instanceof Error?e.message:String(e),i.value=null}finally{P.value=!1}}function Z(){i.value?.terminal&&U.value&&(W.value=!0)}function Q(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function $(e){return e.scopes?.length?e.scopes.join(`, `):`—`}return(e,c)=>(o(),p(`div`,null,[r(d,{title:`Harness`}),z.value?(o(),p(`p`,K,l(z.value),1)):a(``,!0),P.value?(o(),p(`div`,q,[r(s(L),{class:`h-24 w-full`}),r(s(L),{class:`h-40 w-full`})])):H.value?(o(),h(s(w),{key:2},{default:n(()=>[r(s(A),null,{default:n(()=>[r(s(N),null,{default:n(()=>[...c[1]||=[t(`Harness bindings are not configured`,-1)]]),_:1}),r(s(k),null,{default:n(()=>[...c[2]||=[t(`Credential bindings and OAuth tokens unavailable.`,-1)]]),_:1})]),_:1})]),_:1})):i.value?(o(),p(u,{key:3},[i.value.terminal?(o(),h(s(I),{key:1,class:`mb-4`},{default:n(()=>[r(s(O),{class:`flex flex-wrap items-end gap-3`},{default:n(()=>[f(`label`,J,[c[6]||=f(`span`,{class:`text-muted-foreground`},`Profile`,-1),r(s(T),{size:`sm`,modelValue:U.value,"onUpdate:modelValue":c[0]||=e=>U.value=e,class:`min-w-48`,disabled:!i.value.profiles.length},{default:n(()=>[i.value.profiles.length?a(``,!0):(o(),h(s(j),{key:0,value:``},{default:n(()=>[...c[5]||=[t(`No profiles configured`,-1)]]),_:1})),(o(!0),p(u,null,m(i.value.profiles,e=>(o(),h(s(j),{key:e,value:e},{default:n(()=>[t(l(e),1)]),_:2},1032,[`value`]))),128))]),_:1},8,[`modelValue`,`disabled`])]),r(s(b),{disabled:!U.value,onClick:Z},{default:n(()=>[...c[7]||=[t(`Open setup terminal`,-1)]]),_:1},8,[`disabled`])]),_:1})]),_:1})):(o(),h(s(x),{key:0,class:`mb-4`},{default:n(()=>[r(s(S),null,{default:n(()=>[...c[3]||=[t(`Setup terminal unavailable`,-1)]]),_:1}),r(s(y),null,{default:n(()=>[...c[4]||=[t(`Start the daemon with a container runtime and a harness token to log in to a CLI from here. Bindings are still listed below.`,-1)]]),_:1})]),_:1})),W.value&&U.value?(o(),h(s(I),{key:2,class:`mb-4`},{default:n(()=>[r(s(O),{class:`h-96`},{default:n(()=>[r(G,{profile:U.value},null,8,[`profile`])]),_:1})]),_:1})):a(``,!0),r(s(I),null,{default:n(()=>[r(s(O),null,{default:n(()=>[r(s(D)Line truncated
import{A as e,D as t,Jt as n,O as r,at as i,b as a,ht as o,kn as s,lt as c,nr as l,s as u,t as d,v as f,x as p,xt as m,y as h,yn as g}from"./PageHeader.js";import{h as _,n as v,t as y}from"./api.js";import{i as b,n as x,r as S,t as C}from"./alert.js";import{_ as w,a as T,c as E,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as L,s as R,t as z,u as B}from"./index.js";function V(e,t=Date.now()){if(!e.captured)return`unconfigured`;if(!e.expires_at)return`ready`;let n=Date.parse(e.expires_at);return Number.isNaN(n)?`ready`:n<=t?`expired`:n-t<=18e5?`expiring`:`ready`}function H(e,t,n=80,r=24){let i=t.protocol===`https:`?`wss:`:`ws:`,a=new URLSearchParams({profile:e,cols:String(n),rows:String(r)}).toString();return`${i}//${t.host}/api/harness/terminal?${a}`}var U={class:`flex h-full min-h-0 flex-col gap-2`},W={key:0,class:`text-sm text-muted-foreground`,role:`status`},G=e({__name:`SetupTerminal`,props:{profile:{}},setup(e){let n=e,r=g(null),s=g(`connecting`),l=null,d=null,m=null,h=null;function _(){try{m?.fit()}catch{}}return c(()=>{let e=r.value;if(!e)return;l=new P({convertEol:!0,cursorBlink:!0,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`,cursor:`#e6edf3`,selectionBackground:`#264f78`}}),m=new z,l.loadAddon(m),l.open(e),_(),l.focus();let t=new WebSocket(H(n.profile,window.location,l?.cols??80,l?.rows??24));d=t,t.binaryType=`arraybuffer`,t.onopen=()=>{s.value=`open`},t.onmessage=e=>{l&&(typeof e.data==`string`?l.write(e.data):l.write(new Uint8Array(e.data)))},t.onerror=()=>{s.value=`failed`},t.onclose=()=>{s.value=`closed`},l.onData(e=>{t.readyState===WebSocket.OPEN&&t.send(e)}),h=new ResizeObserver(_),h.observe(e)}),i(()=>{h?.disconnect(),h=null,d?.close(),d=null,l?.dispose(),l=null,m=null}),(e,n)=>(o(),p(`div`,U,[s.value===`open`?a(``,!0):(o(),p(`p`,W,[s.value===`connecting`?(o(),p(u,{key:0},[t(`Connecting…`)],64)):s.value===`closed`?(o(),p(u,{key:1},[t(`The terminal session ended.`)],64)):(o(),p(u,{key:2},[t(`Could not open the setup terminal.`)],64))])),f(`div`,{ref_key:`host`,ref:r,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),K={key:0,class:`mb-4 text-sm text-danger`,role:`alert`},q={key:1,class:`space-y-2`},J={class:`flex flex-col gap-1 text-sm`},Y=e({__name:`HarnessPage`,setup(e){let i=g(null),P=g(!0),z=g(null),H=g(!1),U=g(``),W=g(!1),Y={ready:{label:`Ready`,variant:`ok`},expiring:{label:`Expiring soon`,variant:`warn`},expired:{label:`Expired`,variant:`danger`},unconfigured:{label:`Not set up`,variant:`idle`}};c(X);async function X(){P.value=!0,z.value=null,H.value=!1;try{let e=await v.harnessBindings();i.value={terminal:e.terminal,bindings:e.bindings??[],profiles:e.profiles??[]},U.value=i.value.profiles[0]??``}catch(e){let t=e instanceof y?e.status:void 0;t===501||t===503?H.value=!0:z.value=e instanceof Error?e.message:String(e),i.value=null}finally{P.value=!1}}function Z(){i.value?.terminal&&U.value&&(W.value=!0)}function Q(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function $(e){return e.scopes?.length?e.scopes.join(`, `):`—`}return(e,c)=>(o(),p(`div`,null,[r(d,{title:`Harness`}),z.value?(o(),p(`p`,K,l(z.value),1)):a(``,!0),P.value?(o(),p(`div`,q,[r(s(L),{class:`h-24 w-full`}),r(s(L),{class:`h-40 w-full`})])):H.value?(o(),h(s(w),{key:2},{default:n(()=>[r(s(A),null,{default:n(()=>[r(s(N),null,{default:n(()=>[...c[1]||=[t(`Harness bindings are not configured`,-1)]]),_:1}),r(s(k),null,{default:n(()=>[...c[2]||=[t(`Credential bindings and OAuth tokens unavailable.`,-1)]]),_:1})]),_:1})]),_:1})):i.value?(o(),p(u,{key:3},[i.value.terminal?(o(),h(s(I),{key:1,class:`mb-4`},{default:n(()=>[r(s(O),{class:`flex flex-wrap items-end gap-3`},{default:n(()=>[f(`label`,J,[c[6]||=f(`span`,{class:`text-muted-foreground`},`Profile`,-1),r(s(T),{size:`sm`,modelValue:U.value,"onUpdate:modelValue":c[0]||=e=>U.value=e,class:`min-w-48`,disabled:!i.value.profiles.length},{default:n(()=>[i.value.profiles.length?a(``,!0):(o(),h(s(j),{key:0,value:``},{default:n(()=>[...c[5]||=[t(`No profiles configured`,-1)]]),_:1})),(o(!0),p(u,null,m(i.value.profiles,e=>(o(),h(s(j),{key:e,value:e},{default:n(()=>[t(l(e),1)]),_:2},1032,[`value`]))),128))]),_:1},8,[`modelValue`,`disabled`])]),r(s(_),{disabled:!U.value,onClick:Z},{default:n(()=>[...c[7]||=[t(`Open setup terminal`,-1)]]),_:1},8,[`disabled`])]),_:1})]),_:1})):(o(),h(s(S),{key:0,class:`mb-4`},{default:n(()=>[r(s(C),null,{default:n(()=>[...c[3]||=[t(`Setup terminal unavailable`,-1)]]),_:1}),r(s(x),null,{default:n(()=>[...c[4]||=[t(`Start the daemon with a container runtime and a harness token to log in to a CLI from here. Bindings are still listed below.`,-1)]]),_:1})]),_:1})),W.value&&U.value?(o(),h(s(I),{key:2,class:`mb-4`},{default:n(()=>[r(s(O),{class:`h-96`},{default:n(()=>[r(G,{profile:U.value},null,8,[`profile`])]),_:1})]),_:1})):a(``,!0),r(s(I),null,{default:n(()=>[r(s(O),Line truncated
+1 -1
View File
@@ -1 +1 @@
import{b as e,d as t,o as n,s as r,t as i}from"./CardAccordion.js";import{A as a,D as o,Jt as s,O as c,_ as l,b as u,ht as d,kn as f,lt as p,nr as m,t as h,v as g,x as _,yn as v}from"./PageHeader.js";import{X as y,o as b}from"./alert.js";import{b as x}from"./index.js";var S={key:0,class:`mb-4 text-sm text-destructive`,role:`alert`},C={key:1,class:`text-sm text-fg-muted`},w=`eda-playbooks`,T=a({__name:`PlaybooksPage`,setup(a){let T=t();p(T.load);let E=l(()=>T.drafts[w]?.value),D=v(``),O=v(``),k=l(()=>T.changesFor(w).length>0);function A(){if(k.value)return;let e=D.value.trim();if(!e||E.value?.playbooks.some(t=>t.id===e))return;let t=T.drafts[w];t&&(t.value||={playbooks:[]},t.value.playbooks.push({id:e,yaml:``}),D.value=``,O.value=String(t.value.playbooks.length-1))}return(t,a)=>(d(),_(`div`,null,[c(h,{title:`Playbooks`},{default:s(()=>[c(n,{kinds:[w]},null,8,[`kinds`])]),_:1}),c(r,{kind:w,class:`mb-4`}),f(T).catalogError||f(T).pageErrorFor(w)?(d(),_(`p`,S,m(f(T).catalogError||f(T).pageErrorFor(w)),1)):u(``,!0),g(`form`,{class:`mb-4 flex gap-2`,onSubmit:y(A,[`prevent`])},[c(f(e),{modelValue:D.value,"onUpdate:modelValue":a[0]||=e=>D.value=e,"aria-label":`Playbook ID`,placeholder:`Playbook ID`,class:`max-w-xs`,disabled:k.value},null,8,[`modelValue`,`disabled`]),c(f(b),{type:`submit`,disabled:k.value||!D.value.trim()||E.value?.playbooks.some(e=>e.id===D.value.trim())},{default:s(()=>[...a[3]||=[o(`Add playbook`,-1)]]),_:1},8,[`disabled`])],32),E.value?.playbooks.length?u(``,!0):(d(),_(`p`,C,`No playbooks installed.`)),c(i,{open:O.value,"onUpdate:open":a[1]||=e=>O.value=e,items:E.value?.playbooks??[],title:e=>e.id,"remove-label":`Remove`,mono:``,onRemove:a[2]||=e=>E.value.playbooks.splice(e,1)},{default:s(({item:e,index:t})=>[c(f(x),{id:`playbook-${t}`,modelValue:e.yaml,"onUpdate:modelValue":t=>e.yaml=t,"aria-label":`${e.id} YAML`,class:`mb-3 min-h-64 font-mono`,spellcheck:`false`},null,8,[`id`,`modelValue`,`onUpdate:modelValue`,`aria-label`])]),_:1},8,[`open`,`items`,`title`])]))}});export{T as default};
import{d as e,o as t,s as n,t as r}from"./CardAccordion.js";import{A as i,D as a,Jt as o,O as s,_ as c,b as l,ht as u,kn as d,lt as f,nr as p,t as m,v as h,x as g,yn as _}from"./PageHeader.js";import{W as v,h as y}from"./api.js";import{b,w as x}from"./index.js";var S={key:0,class:`mb-4 text-sm text-destructive`,role:`alert`},C={key:1,class:`text-sm text-fg-muted`},w=`eda-playbooks`,T=i({__name:`PlaybooksPage`,setup(i){let T=e();f(T.load);let E=c(()=>T.drafts[w]?.value),D=_(``),O=_(``),k=c(()=>T.changesFor(w).length>0);function A(){if(k.value)return;let e=D.value.trim();if(!e||E.value?.playbooks.some(t=>t.id===e))return;let t=T.drafts[w];t&&(t.value||={playbooks:[]},t.value.playbooks.push({id:e,yaml:``}),D.value=``,O.value=String(t.value.playbooks.length-1))}return(e,i)=>(u(),g(`div`,null,[s(m,{title:`Playbooks`},{default:o(()=>[s(t,{kinds:[w]},null,8,[`kinds`])]),_:1}),s(n,{kind:w,class:`mb-4`}),d(T).catalogError||d(T).pageErrorFor(w)?(u(),g(`p`,S,p(d(T).catalogError||d(T).pageErrorFor(w)),1)):l(``,!0),h(`form`,{class:`mb-4 flex gap-2`,onSubmit:v(A,[`prevent`])},[s(d(x),{modelValue:D.value,"onUpdate:modelValue":i[0]||=e=>D.value=e,"aria-label":`Playbook ID`,placeholder:`Playbook ID`,class:`max-w-xs`,disabled:k.value},null,8,[`modelValue`,`disabled`]),s(d(y),{type:`submit`,disabled:k.value||!D.value.trim()||E.value?.playbooks.some(e=>e.id===D.value.trim())},{default:o(()=>[...i[3]||=[a(`Add playbook`,-1)]]),_:1},8,[`disabled`])],32),E.value?.playbooks.length?l(``,!0):(u(),g(`p`,C,`No playbooks installed.`)),s(r,{open:O.value,"onUpdate:open":i[1]||=e=>O.value=e,items:E.value?.playbooks??[],title:e=>e.id,"remove-label":`Remove`,mono:``,onRemove:i[2]||=e=>E.value.playbooks.splice(e,1)},{default:o(({item:e,index:t})=>[s(d(b),{id:`playbook-${t}`,modelValue:e.yaml,"onUpdate:modelValue":t=>e.yaml=t,"aria-label":`${e.id} YAML`,class:`mb-3 min-h-64 font-mono`,spellcheck:`false`},null,8,[`id`,`modelValue`,`onUpdate:modelValue`,`aria-label`])]),_:1},8,[`open`,`items`,`title`])]))}});export{T as default};
+1 -3
View File
@@ -1,3 +1 @@
import{$n as e,A as t,An as n,Bn as r,Bt as i,Dn as a,En as o,Et as s,Fn as c,Gn as l,Hn as u,In as d,Jn as f,Jt as p,Kn as m,Ln as h,Mn as g,Nn as _,O as v,Pn as y,Qn as b,R as x,Rn as ee,S as te,Sn as S,St as C,U as w,Un as ne,Ut as T,V as E,Vn as re,Wn as D,Wt as O,Xn as k,Y as ie,Yn as A,Zn as j,_ as M,_n as ae,dn as oe,g as se,ht as N,i as P,ir as ce,jn as le,kn as F,kt as ue,l as de,lt as fe,m as pe,mn as me,mt as he,n as ge,nt as _e,on as ve,ot as ye,pt as be,qn as xe,r as Se,rn as Ce,s as we,tt as Te,w as Ee,wn as De,x as Oe,xn as ke,y as Ae,yn as je,yt as Me,z as Ne,zn as I}from"./PageHeader.js";var Pe=void 0,Fe=typeof window<`u`&&window.trustedTypes;if(Fe)try{Pe=Fe.createPolicy(`vue`,{createHTML:e=>e})}catch{}var Ie=Pe?e=>Pe.createHTML(e):e=>e,Le=`http://www.w3.org/2000/svg`,Re=`http://www.w3.org/1998/Math/MathML`,L=typeof document<`u`?document:null,ze=L&&L.createElement(`template`),Be={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?L.createElementNS(Le,e):t===`mathml`?L.createElementNS(Re,e):n?L.createElement(e,{is:n}):L.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>L.createTextNode(e),createComment:e=>L.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>L.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),i!==a&&(i=i.nextSibling););else{ze.innerHTML=Ie(r===`svg`?`<svg>${e}</svg>`:r===`mathml`?`<math>${e}</math>`:e);let i=ze.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},R=`transition`,Ve=`animation`,He=Symbol(`_vtc`),Ue={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},We=y({},Se,Ue),Ge=(e=>(e.displayName=`Transition`,e.props=We,e))((e,{slots:t})=>E(ge,Je(e),t)),Ke=(e,t=[])=>{I(e)?e.forEach(e=>e(...t)):e&&e(...t)},qe=e=>e?I(e)?e.some(e=>e.length>1):e.length>1:!1;function Je(e){let t={};for(let n in e)n in Ue||(t[n]=e[n]);if(e.css===!1)return t;let{name:n=`v`,type:r,duration:i,enterFromClass:a=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:c=a,appearActiveClass:l=o,appearToClass:u=s,leaveFromClass:d=`${n}-leave-from`,leaveActiveClass:f=`${n}-leave-active`,leaveToClass:p=`${n}-leave-to`}=e,m=Ye(i),h=m&&m[0],g=m&&m[1],{onBeforeEnter:_,onEnter:v,onEnterCancelled:b,onLeave:x,onLeaveCancelled:ee,onBeforeAppear:te=_,onAppear:S=v,onAppearCancelled:C=b}=t,w=(e,t,n,r)=>{e._enterCancelled=r,B(e,t?u:s),B(e,t?l:o),n&&n()},ne=(e,t)=>{e._isLeaving=!1,B(e,d),B(e,p),B(e,f),t&&t()},T=e=>(t,n)=>{let i=e?S:v,o=()=>w(t,e,n);Ke(i,[t,o]),Ze(()=>{B(t,e?c:a),z(t,e?u:s),qe(i)||$e(t,r,h,o)})};return y(t,{onBeforeEnter(e){Ke(_,[e]),z(e,a),z(e,o)},onBeforeAppear(e){Ke(te,[e]),z(e,c),z(e,l)},onEnter:T(!1),onAppear:T(!0),onLeave(e,t){e._isLeaving=!0;let n=()=>ne(e,t);z(e,d),e._enterCancelled?(z(e,f),rt(e)):(rt(e),z(e,f)),Ze(()=>{e._isLeaving&&(B(e,d),z(e,p),qe(x)||$e(e,r,g,n))}),Ke(x,[e,n])},onEnterCancelled(e){w(e,!1,void 0,!0),Ke(b,[e])},onAppearCancelled(e){w(e,!0,void 0,!0),Ke(C,[e])},onLeaveCancelled(e){ne(e),Ke(ee,[e])}})}function Ye(e){if(e==null)return null;if(u(e))return[Xe(e.enter),Xe(e.leave)];{let t=Xe(e);return[t,t]}}function Xe(e){return ce(e)}function z(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.add(t)),(e[He]||(e[He]=new Set)).add(t)}function B(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.remove(t));let n=e[He];n&&(n.delete(t),n.size||(e[He]=void 0))}function Ze(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}var Qe=0;function $e(e,t,n,r){let i=e._endId=++Qe,a=()=>{i===e._endId&&r()};if(n!=null)return setTimeout(a,n);let{type:o,timeout:s,propCount:c}=et(e,t);if(!o)return r();let l=o+`end`,u=0,d=()=>{e.removeEventListener(l,f),a()},f=t=>{t.target===e&&++u>=c&&d()};setTimeout(()=>{u<c&&d()},s+1),e.addEventListener(l,f)}function et(e,t){let n=window.getComputedStyle(e),r=e=>(n[e]||``).split(`, `),i=r(`${R}Delay`),a=r(`${R}Duration`),o=tt(i,a),s=r(`${Ve}Delay`),c=r(`${Ve}Duration`),l=tt(s,c),u=null,d=0,f=0;t===R?o>0&&(u=R,d=o,f=a.length):t===Ve?l>0&&(u=Ve,d=l,f=c.length):(d=Math.max(o,l),u=d>0?o>l?R:Ve:null,f=u?u===R?a.length:c.length:0);let p=u===R&&/\b(?:transform|all)(?:,|$)/.test(r(`${R}Property`).toString());return{type:u,timeout:d,propCount:f,hasTransform:p}}function tt(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max(...t.map((t,nLine truncated
`))),e[U]=H(i);let a=r||i.props&&i.props.type===`number`;V(e,t?`change`:`input`,t=>{t.target.composing||e[U](sn(e.value,n,a))}),(n||a)&&V(e,`change`,()=>{e.value=sn(e.value,n,a)}),t||(V(e,`compositionstart`,rn),V(e,`compositionend`,an),V(e,`change`,an))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[on];delete e[on],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[U](sn(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[U]=H(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?j(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},ln={deep:!0,created(e,t,n){e[U]=H(n),V(e,`change`,()=>{let t=e._modelValue,n=hn(e),r=e.checked,i=e[U];if(I(t)){let e=k(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(l(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(gn(e,r))})},mounted:un,beforeUpdate(e,t,n){e[U]=H(n),un(e,t,n)}};function un(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(I(t))i=k(t,r.props.value)>-1;else if(l(t))i=t.has(r.props.value);else{if(t===n)return;i=A(t,gn(e,!0))}e.checked!==i&&(e.checked=i)}var dn={created(e,{value:t},n){e.checked=A(t,n.props.value),e[U]=H(n),V(e,`change`,()=>{e[U](hn(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[U]=H(r),t!==n&&(e.checked=A(t,r.props.value))}},fn={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,V(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?j(hn(e)):hn(e)),r=e.multiple,i=r?l(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?I(i)?t.slice():t:i];try{e[U](i)}finally{_e(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[U]=H(r)},mounted(e,{value:t}){mn(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[U]=H(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!pn(t,n[1],n[0]))&&mn(e,t)}};function pn(e,t,n){if(!n||I(e))return A(e,t);if(l(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function mn(e,t){let n=e.multiple,r=I(t);if(!n||r||l(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=hn(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):k(t,o)>-1}else a.selected=t.has(o)}else if(A(hn(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function hn(e){return`_value`in e?e._value:e.value}function gn(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var _n={created(e,t,n){yn(e,t,n,null,`created`)},mounted(e,t,n){yn(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){yn(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){yn(e,t,n,r,`updated`)}};function vn(e,t){switch(e){case`SELECT`:return fn;case`TEXTAREA`:return cn;default:switch(t){case`checkbox`:return ln;case`radio`:return dn;default:return cn}}}function yn(e,t,n,r,i){let a=vn(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function bn(){cn.getSSRProps=({value:e})=>({value:e}),dn.getSSRProps=({value:e},t)=>{if(t.props&&A(t.props.value,e))return{checked:!0}},ln.getSSRProps=({value:e},t)=>{if(I(e)){if(t.props&&k(e,t.props.value)>-1)return{checked:!0}}else if(l(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},_n.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=vn(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var xn=[`ctrl`,`shift`,`alt`,`meta`],Sn={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>xn.some(n=>e[`${n}Key`]&&!t.includes(n))},Cn=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=Sn[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},wn={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Tn=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=d(n.key);if(t.some(e=>e===r||wn[e]===r))return e(n)}))},En=y({patchProp:It},Be),Dn,On=!1;function kn(){return Dn||=Ee(En)}function An(){return Dn=On?Dn:te(En),On=!0,Dn}var jn=((...e)=>{kn().render(...e)}),Mn=((...e)=>{An().hydrate(...e)}),Nn=((...e)=>{let t=kn().createApp(...e),{mount:n}=t;return t.mount=e=>{let i=In(e);if(!i)return;let a=t._component;!r(a)&&!a.render&&!a.template&&(a.template=i.innerHTML),i.nodeType===1&&(i.textContent=``);let o=n(i,!1,Fn(i));return i instanceof Element&&(i.removeAttribute(`v-cloak`),i.setAttribute(`data-v-app`,``)),o},t}),Pn=((...e)=>{let t=An().createApp(...e),{mount: Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Ei;function Di(e){Ei=e}var Oi=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function ki(e){let t=e instanceof Oi?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ai(e,t){let n=await fetch(e,t);if(Ei?.(n.status===401),!n.ok)throw new Oi(await Ti(n),n.status);return n}async function $(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=wi,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Ai(e,s);return a?await c.json():void 0}var ji={secretEngines:()=>$(`/api/secret-engines`),checkSecret:e=>$(`/api/secret-references/check`,{method:`POST`,body:e}),health:()=>$(`/health/detailed`),services:()=>$(`/api/services`),policies:()=>$(`/api/access/policies`),putPolicy:e=>$(`/api/access/policies`,{method:`PUT`,body:e}),deletePolicy:e=>$(`/api/access/policies`,{method:`DELETE`,body:e,parse:!1}),orgs:()=>$(`/api/orgs`),orgCreate:e=>$(`/api/orgs`,{method:`POST`,body:e}),org:e=>$(`/api/orgs/${encodeURIComponent(e)}`),orgWorkspaces:e=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`),createOrgWorkspace:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`,{method:`POST`,body:t}),orgMembers:e=>$(`/api/orgs/${encodeURIComponent(e)}/members`),addOrgMember:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/members`,{method:`POST`,body:t}),setOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:`PUT`,body:n}),removeOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`+Q({workspace:n}),{method:`DELETE`,parse:!1}),assignOrgAgent:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}`,{method:`PUT`}),alerts:()=>$(`/api/alerts`),dismissAlert:e=>$(`/api/alerts/${e}/dismiss`,{method:`POST`,parse:!1}),identities:()=>$(`/api/identities`),identityCreate:e=>$(`/api/identities`,{method:`POST`,body:e}),identityCommand:(e,t,n)=>$(`/api/identities/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`POST`,body:n}),summary:()=>$(`/api/summary`),tasks:()=>$(`/api/tasks`),taskPage:async e=>{let t=await Ai(`/api/tasks`+Q(e),{headers:{Accept:`application/json`},signal:AbortSignal.timeout(wi)});return{tasks:await t.json(),next:t.headers.get(`X-Next-Cursor`)}},taskMeta:()=>$(`/api/task-meta`),task:e=>$(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>$(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/changes`+Q(t)),taskDebug:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/debug`+Q(t)),taskAction:(e,t,n)=>$(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t,...n}}),setup:()=>$(`/api/setup`),capabilities:()=>$(`/api/capabilities`),workflows:()=>$(`/api/workflows`),workflowEnabled:(e,t)=>$(`/api/workflows/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:{enabled:t},parse:!1}),workRequest:e=>$(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>$(`/api/skills`),channels:()=>$(`/api/channels`),curators:()=>$(`/api/curators`),channelReload:e=>$(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>$(`/api/config`),logs:e=>$(`/api/logs`+Q(e)),taskLogs:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/logs`+Q(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>$(`/api/version`),updateSnapshot:()=>$(`/api/chat/update`),updateDefer:e=>$(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),updateInstall:e=>$(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>$(`/api/captures`+Q({limit:e})),eventTypes:e=>$(`/api/event-types`+Q({workspace:e})),eventTypeCreate:e=>$(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>$(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>$(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:e=>$(`/api/mappings`+Q({workspace:e})),mappingCreate:e=>$(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>$(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>$(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>$(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:e=>$(`/api/bindings`+Q({workspace:e})),dispatches:(e,t)=>$(`/api/${e}/${encodeURIComponent(t)}/dispatches`),bindingCreate:e=>$(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>$(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>$(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELLine truncated
import{A as e,Jt as t,Qn as n,St as r,V as i,Y as a,ht as o,kn as s,tt as c,x as l,y as u}from"./PageHeader.js";import{_ as d,b as f,f as p,g as m}from"./api.js";var h={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`},g=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim();function _(e){return e!=null}function v(e,t={}){let n=t.attributeNames??{},r=e=>n[e]??e,i=e.size??e.width??h.width,a=e.size??e.height??h.height,o=e.aliases?.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>`lucide-${e}`)??[],s=[...e.name?[`lucide-${e.name}`]:[],...o],c=t.className?.split(` `).filter(Boolean)??[],l=t.includeDefaultClasses===!1?g(...c):g(`lucide`,...s,...c),u=t.absoluteStrokeWidth?Number(t.strokeWidth??h[`stroke-width`])*Number(e.size??e.width??h.width)/Number(t.size??t.width??h.width):t.strokeWidth??h[`stroke-width`];return[`svg`,{...Object.entries(h).reduce((e,[t,n])=>(e[r(t)]=n,e),{}),...`color`in t&&t.color&&{[r(`stroke`)]:t.color},...`size`in t&&_(t.size)&&{[r(`width`)]:t.size,[r(`height`)]:t.size},...`width`in t&&_(t.width)&&{[r(`width`)]:t.width},...`height`in t&&_(t.height)&&{[r(`height`)]:t.height},[r(`stroke-width`)]:u,...l&&{[r(`class`)]:l},[r(`viewBox`)]:`0 0 ${i} ${a}`,...t.hasA11yProp===!1?{[r(`aria-hidden`)]:`true`}:{},...`attributes`in t&&t.attributes},e.node.map(e=>{let[n,i,a]=e,o=t.nonScalingStroke?{[r(`vector-effect`)]:`non-scaling-stroke`,...i}:i;return a?[n,o,a]:[n,o]})]}var y=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},b=e=>e===``,x=e=>e?.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),S=Symbol(`lucide-icons`);function C(){return a(S,{})}var w=({name:e,iconNode:t,"icon-node":n,icon:r={name:e&&x(e),node:t??n??[],size:24,aliases:[]},absoluteStrokeWidth:a,"absolute-stroke-width":o,nonScalingStroke:s,"non-scaling-stroke":c,strokeWidth:l,"stroke-width":u,size:d,width:f=d,height:p=d,color:m,...h},{slots:g})=>{let{size:_,color:S,strokeWidth:w=2,absoluteStrokeWidth:T=!1,nonScalingStroke:E=!1,class:D=``}=C(),O=b(a)||b(o)||a===!0||o===!0||T===!0,k=b(s)||b(c)||s===!0||c===!0||E===!0;delete h.class;let A=g.default?.(),[,j,M=[]]=v(r,{color:m??S,width:f??d??_,height:p??d??_,strokeWidth:l??u??w,absoluteStrokeWidth:O,nonScalingStroke:k,className:D,hasA11yProp:A!=null&&A.length>0||y(h),attributes:h});return i(`svg`,j,[...M.map(([e,t])=>i(e,t)),...A??[]])};function T(e,t=[]){let n=typeof e==`string`?{name:e,node:t}:e;return(e,{slots:t})=>i(w,{...e,icon:n},t.default?{default:t.default}:void 0)}var E=T({name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]}),D=e({__name:`Badge`,props:{asChild:{type:Boolean},as:{},variant:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let n=e,i=p(n,`class`);return(a,l)=>(o(),u(s(d),c({"data-slot":`badge`,"data-variant":e.variant,class:s(m)(s(O)({variant:e.variant}),n.class)},s(i)),{default:t(()=>[r(a.$slots,`default`)]),_:3},16,[`data-variant`,`class`]))}}),O=f(`h-5 gap-1 rounded-sm border border-transparent px-2 py-0.5 text-xs font-medium transition-all has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&>svg]:size-3! group/badge inline-flex w-fit shrink-0 items-center justify-center overflow-hidden whitespace-nowrap focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none`,{variants:{variant:{default:`bg-primary text-primary-foreground [a]:hover:bg-primary/80`,secondary:`bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80`,destructive:`bg-destructive/10 [a]:hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-destructive dark:bg-destructive/20`,outline:`border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground`,ghost:`hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50`,link:`text-primary underline-offset-4 hover:underline`,ok:`bg-ok-soft text-ok`,warn:`bg-warn-soft text-warn`,danger:`bg-danger-soft text-danger`,info:`bg-info-soft text-info`,idle:`bg-idle-soft text-idle`}},defaultVariants:{variant:`default`}}),k=e({__name:`Alert`,props:{class:{type:[Boolean,null,String,Object,Array]},variant:{}},setup(e){let t=e;return(i,a)=>(o(),l(`div`,{"data-slot":`alert`,class:n(s(m)(s(M)({variant:e.variant}),t.class)),role:`alert`},[r(i.$slots,`default`)],2))}}),A=e({__name:`AlertDescription`,props:{class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e;return(e,i)=>(o(),l(`div`,{"data-slot":`alert-description`,class:n(s(m)(`text-muted-foreground text-sm text-balance md:text-pretty [&_p:not(:last-child)]:mb-4 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground`,t.class))},[r(e.$slots,`default`)],2))}}),j=e({__name:`AlertTitle`,props:{class:{type:[Boolean,null,String,ObjecLine truncated
+3
View File
@@ -0,0 +1,3 @@
import{$n as e,A as t,An as n,Bn as r,Bt as i,Dn as a,En as o,Et as s,Fn as c,Gn as l,Hn as u,In as d,Jn as f,Jt as p,Kn as m,Ln as h,Mn as g,Nn as _,O as ee,Pn as v,Qn as y,R as b,Rn as te,S as ne,Sn as x,St as S,U as re,Un as ie,Ut as C,V as ae,Vn as oe,Wn as w,Wt as T,Xn as E,Y as se,Yn as D,Zn as O,_ as k,_n as ce,dn as le,g as ue,ht as A,i as j,ir as de,jn as fe,kn as M,kt as pe,l as me,lt as N,m as he,mn as ge,mt as _e,n as ve,nt as ye,on as be,ot as xe,pt as Se,qn as P,r as Ce,rn as we,s as Te,tt as Ee,w as De,wn as Oe,xn as ke,y as Ae,yn as je,yt as Me,z as Ne,zn as F}from"./PageHeader.js";var Pe=void 0,Fe=typeof window<`u`&&window.trustedTypes;if(Fe)try{Pe=Fe.createPolicy(`vue`,{createHTML:e=>e})}catch{}var Ie=Pe?e=>Pe.createHTML(e):e=>e,Le=`http://www.w3.org/2000/svg`,Re=`http://www.w3.org/1998/Math/MathML`,I=typeof document<`u`?document:null,ze=I&&I.createElement(`template`),Be={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?I.createElementNS(Le,e):t===`mathml`?I.createElementNS(Re,e):n?I.createElement(e,{is:n}):I.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>I.createTextNode(e),createComment:e=>I.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>I.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),i!==a&&(i=i.nextSibling););else{ze.innerHTML=Ie(r===`svg`?`<svg>${e}</svg>`:r===`mathml`?`<math>${e}</math>`:e);let i=ze.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},L=`transition`,Ve=`animation`,He=Symbol(`_vtc`),Ue={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},We=v({},Ce,Ue),Ge=(e=>(e.displayName=`Transition`,e.props=We,e))((e,{slots:t})=>ae(ve,qe(e),t)),R=(e,t=[])=>{F(e)?e.forEach(e=>e(...t)):e&&e(...t)},Ke=e=>e?F(e)?e.some(e=>e.length>1):e.length>1:!1;function qe(e){let t={};for(let n in e)n in Ue||(t[n]=e[n]);if(e.css===!1)return t;let{name:n=`v`,type:r,duration:i,enterFromClass:a=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:c=a,appearActiveClass:l=o,appearToClass:u=s,leaveFromClass:d=`${n}-leave-from`,leaveActiveClass:f=`${n}-leave-active`,leaveToClass:p=`${n}-leave-to`}=e,m=Je(i),h=m&&m[0],g=m&&m[1],{onBeforeEnter:_,onEnter:ee,onEnterCancelled:y,onLeave:b,onLeaveCancelled:te,onBeforeAppear:ne=_,onAppear:x=ee,onAppearCancelled:S=y}=t,re=(e,t,n,r)=>{e._enterCancelled=r,B(e,t?u:s),B(e,t?l:o),n&&n()},ie=(e,t)=>{e._isLeaving=!1,B(e,d),B(e,p),B(e,f),t&&t()},C=e=>(t,n)=>{let i=e?x:ee,o=()=>re(t,e,n);R(i,[t,o]),Xe(()=>{B(t,e?c:a),z(t,e?u:s),Ke(i)||Qe(t,r,h,o)})};return v(t,{onBeforeEnter(e){R(_,[e]),z(e,a),z(e,o)},onBeforeAppear(e){R(ne,[e]),z(e,c),z(e,l)},onEnter:C(!1),onAppear:C(!0),onLeave(e,t){e._isLeaving=!0;let n=()=>ie(e,t);z(e,d),e._enterCancelled?(z(e,f),nt(e)):(nt(e),z(e,f)),Xe(()=>{e._isLeaving&&(B(e,d),z(e,p),Ke(b)||Qe(e,r,g,n))}),R(b,[e,n])},onEnterCancelled(e){re(e,!1,void 0,!0),R(y,[e])},onAppearCancelled(e){re(e,!0,void 0,!0),R(S,[e])},onLeaveCancelled(e){ie(e),R(te,[e])}})}function Je(e){if(e==null)return null;if(u(e))return[Ye(e.enter),Ye(e.leave)];{let t=Ye(e);return[t,t]}}function Ye(e){return de(e)}function z(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.add(t)),(e[He]||(e[He]=new Set)).add(t)}function B(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.remove(t));let n=e[He];n&&(n.delete(t),n.size||(e[He]=void 0))}function Xe(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}var Ze=0;function Qe(e,t,n,r){let i=e._endId=++Ze,a=()=>{i===e._endId&&r()};if(n!=null)return setTimeout(a,n);let{type:o,timeout:s,propCount:c}=$e(e,t);if(!o)return r();let l=o+`end`,u=0,d=()=>{e.removeEventListener(l,f),a()},f=t=>{t.target===e&&++u>=c&&d()};setTimeout(()=>{u<c&&d()},s+1),e.addEventListener(l,f)}function $e(e,t){let n=window.getComputedStyle(e),r=e=>(n[e]||``).split(`, `),i=r(`${L}Delay`),a=r(`${L}Duration`),o=et(i,a),s=r(`${Ve}Delay`),c=r(`${Ve}Duration`),l=et(s,c),u=null,d=0,f=0;t===L?o>0&&(u=L,d=o,f=a.length):t===Ve?l>0&&(u=Ve,d=l,f=c.length):(d=Math.max(o,l),u=d>0?o>l?L:Ve:null,f=u?u===L?a.length:c.length:0);let p=u===L&&/\b(?:transform|all)(?:,|$)/.test(r(`${L}Property`).toString());return{type:u,timeout:d,propCount:f,hasTransform:p}}function et(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max(...t.map((t,n)=>tt(tLine truncated
`))),e[U]=H(i);let a=r||i.props&&i.props.type===`number`;V(e,t?`change`:`input`,t=>{t.target.composing||e[U](on(e.value,n,a))}),(n||a)&&V(e,`change`,()=>{e.value=on(e.value,n,a)}),t||(V(e,`compositionstart`,nn),V(e,`compositionend`,rn),V(e,`change`,rn))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[an];delete e[an],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[U](on(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[U]=H(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?O(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},cn={deep:!0,created(e,t,n){e[U]=H(n),V(e,`change`,()=>{let t=e._modelValue,n=mn(e),r=e.checked,i=e[U];if(F(t)){let e=E(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(l(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(hn(e,r))})},mounted:ln,beforeUpdate(e,t,n){e[U]=H(n),ln(e,t,n)}};function ln(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(F(t))i=E(t,r.props.value)>-1;else if(l(t))i=t.has(r.props.value);else{if(t===n)return;i=D(t,hn(e,!0))}e.checked!==i&&(e.checked=i)}var un={created(e,{value:t},n){e.checked=D(t,n.props.value),e[U]=H(n),V(e,`change`,()=>{e[U](mn(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[U]=H(r),t!==n&&(e.checked=D(t,r.props.value))}},dn={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,V(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?O(mn(e)):mn(e)),r=e.multiple,i=r?l(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?F(i)?t.slice():t:i];try{e[U](i)}finally{ye(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[U]=H(r)},mounted(e,{value:t}){pn(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[U]=H(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!fn(t,n[1],n[0]))&&pn(e,t)}};function fn(e,t,n){if(!n||F(e))return D(e,t);if(l(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function pn(e,t){let n=e.multiple,r=F(t);if(!n||r||l(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=mn(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):E(t,o)>-1}else a.selected=t.has(o)}else if(D(mn(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function mn(e){return`_value`in e?e._value:e.value}function hn(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var gn={created(e,t,n){vn(e,t,n,null,`created`)},mounted(e,t,n){vn(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){vn(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){vn(e,t,n,r,`updated`)}};function _n(e,t){switch(e){case`SELECT`:return dn;case`TEXTAREA`:return sn;default:switch(t){case`checkbox`:return cn;case`radio`:return un;default:return sn}}}function vn(e,t,n,r,i){let a=_n(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function yn(){sn.getSSRProps=({value:e})=>({value:e}),un.getSSRProps=({value:e},t)=>{if(t.props&&D(t.props.value,e))return{checked:!0}},cn.getSSRProps=({value:e},t)=>{if(F(e)){if(t.props&&E(e,t.props.value)>-1)return{checked:!0}}else if(l(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},gn.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=_n(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var bn=[`ctrl`,`shift`,`alt`,`meta`],xn={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>bn.some(n=>e[`${n}Key`]&&!t.includes(n))},Sn=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=xn[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Cn={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},wn=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=d(n.key);if(t.some(e=>e===r||Cn[e]===r))return e(n)}))},Tn=v({patchProp:Ft},Be),En,Dn=!1;function On(){return En||=De(Tn)}function kn(){return En=Dn?En:ne(Tn),Dn=!0,En}var An=((...e)=>{On().render(...e)}),jn=((...e)=>{kn().hydrate(...e)}),Mn=((...e)=>{let t=On().createApp(...e),{mount:n}=t;return t.mount=e=>{let i=Fn(e);if(!i)return;let a=t._component;!r(a)&&!a.render&&!a.template&&(a.template=i.innerHTML),i.nodeType===1&&(i.textContent=``);let o=n(i,!1,Pn(i));return i instanceof Element&&(i.removeAttribute(`v-cloak`),i.setAttribute(`data-v-app`,``)),o},t}),Nn=((...e)=>{let t=kn().createApp(...e),{mount: Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var $i;function ea(e){$i=e}var ta=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function na(e){let t=e instanceof ta?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function ra(e,t){let n=await fetch(e,t);if($i?.(n.status===401),!n.ok)throw new ta(await Qi(n),n.status);return n}async function $(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Zi,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await ra(e,s);return a?await c.json():void 0}var ia={recoveryCode:()=>$(`/api/account/recovery`,{method:`POST`,body:{}}),recoverAccount:(e,t,n)=>$(`/api/auth/recover`,{method:`POST`,body:{email:e,code:t,password:n},parse:!1}),authStatus:()=>$(`/api/auth/status`),setupAccount:e=>$(`/api/auth/setup`,{method:`POST`,body:e}),signIn:(e,t)=>$(`/api/auth/login`,{method:`POST`,body:{email:e,password:t}}),signOut:()=>$(`/api/auth/logout`,{method:`POST`,body:{},parse:!1}),createAccount:e=>$(`/api/accounts`,{method:`POST`,body:e}),changePassword:(e,t)=>$(`/api/account/password`,{method:`POST`,body:{current_password:e,new_password:t},parse:!1}),authentication:()=>$(`/api/authentication`),saveAuthentication:e=>$(`/api/authentication`,{method:`PUT`,body:e,parse:!1}),passkeys:()=>$(`/api/account/passkeys`),deletePasskey:e=>$(`/api/account/passkeys/${encodeURIComponent(e)}`,{method:`DELETE`,body:{},parse:!1}),beginPasskey:e=>$(e?`/api/account/passkeys/begin`:`/api/auth/passkey/begin`,{method:`POST`,body:{}}),finishPasskey:(e,t,n)=>$(e?`/api/account/passkeys/finish`:`/api/auth/passkey/finish`,{method:`POST`,body:{credential:t,name:n}}),secretEngines:()=>$(`/api/secret-engines`),checkSecret:e=>$(`/api/secret-references/check`,{method:`POST`,body:e}),health:()=>$(`/health/detailed`),services:()=>$(`/api/services`),policies:()=>$(`/api/access/policies`),putPolicy:e=>$(`/api/access/policies`,{method:`PUT`,body:e}),deletePolicy:e=>$(`/api/access/policies`,{method:`DELETE`,body:e,parse:!1}),orgs:()=>$(`/api/orgs`),orgCreate:e=>$(`/api/orgs`,{method:`POST`,body:e}),org:e=>$(`/api/orgs/${encodeURIComponent(e)}`),orgWorkspaces:e=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`),createOrgWorkspace:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/workspaces`,{method:`POST`,body:t}),orgMembers:e=>$(`/api/orgs/${encodeURIComponent(e)}/members`),addOrgMember:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/members`,{method:`POST`,body:t}),setOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:`PUT`,body:n}),removeOrgMember:(e,t,n)=>$(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`+Q({workspace:n}),{method:`DELETE`,parse:!1}),assignOrgAgent:(e,t)=>$(`/api/orgs/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}`,{method:`PUT`}),alerts:()=>$(`/api/alerts`),dismissAlert:e=>$(`/api/alerts/${e}/dismiss`,{method:`POST`,parse:!1}),identities:()=>$(`/api/identities`),identityCreate:e=>$(`/api/identities`,{method:`POST`,body:e}),identityCommand:(e,t,n)=>$(`/api/identities/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`POST`,body:n}),summary:()=>$(`/api/summary`),tasks:()=>$(`/api/tasks`),taskPage:async e=>{let t=await ra(`/api/tasks`+Q(e),{headers:{Accept:`application/json`},signal:AbortSignal.timeout(Zi)});return{tasks:await t.json(),next:t.headers.get(`X-Next-Cursor`)}},taskMeta:()=>$(`/api/task-meta`),task:e=>$(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>$(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/changes`+Q(t)),taskDebug:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/debug`+Q(t)),taskAction:(e,t,n)=>$(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t,...n}}),setup:()=>$(`/api/setup`),capabilities:()=>$(`/api/capabilities`),workflows:()=>$(`/api/workflows`),workflowEnabled:(e,t)=>$(`/api/workflows/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:{enabled:t},parse:!1}),workRequest:e=>$(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>$(`/api/skills`),channels:()=>$(`/api/channels`),curators:()=>$(`/api/curators`),channelReload:e=>$(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>$(`/api/config`),logs:e=>$(`/api/logs`+Q(e)),taskLogs:(e,t)=>$(`/api/tasks/${encodeURIComponent(e)}/logs`+Q(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>$(`/api/version`),updateSnapshot:()=>$(`/api/chat/update`),updateDefer:e=>$(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),updateInstall:e=>$(`/api/chat/update/install`,{method:`POST`,body:{snaps Line truncated
+1 -1
View File
@@ -1 +1 @@
.xterm{cursor:text;-webkit-user-select:none;user-select:none;position:relative}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{z-index:5;position:absolute;top:0}.xterm .xterm-helper-textarea{opacity:0;z-index:-5;white-space:nowrap;resize:none;border:0;width:0;height:0;margin:0;padding:0;position:absolute;top:0;left:-9999em;overflow:hidden}.xterm .composition-view{color:#fff;white-space:nowrap;z-index:1;background:#000;display:none;position:absolute}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{cursor:default;background-color:#000;position:absolute;inset:0;overflow-y:scroll}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;top:0;left:0}.xterm-char-measure-element{visibility:hidden;line-height:normal;display:inline-block;position:absolute;top:0;left:-9999em}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{z-index:10;color:#0000;pointer-events:none;position:absolute;inset:0}.xterm .xterm-accessibility-tree:not(.debug) ::selection{color:#0000}.xterm .xterm-accessibility-tree{-webkit-user-select:text;user-select:text;white-space:pre;font-family:monospace}.xterm .xterm-accessibility-tree>div{transform-origin:0;width:fit-content}.xterm .live-region{width:1px;height:1px;position:absolute;left:-9999px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{-webkit-text-decoration:underline double;text-decoration:underline double}.xterm-underline-3{-webkit-text-decoration:underline wavy;text-decoration:underline wavy}.xterm-underline-4{-webkit-text-decoration:underline dotted;text-decoration:underline dotted}.xterm-underline-5{-webkit-text-decoration:underline dashed;text-decoration:underline dashed}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:underline overline}.xterm-overline.xterm-underline-2{-webkit-text-decoration:overline double underline;text-decoration:overline double underline}.xterm-overline.xterm-underline-3{-webkit-text-decoration:overline wavy underline;text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{-webkit-text-decoration:overline dotted underline;text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{-webkit-text-decoration:overline dashed underline;text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;pointer-events:none;position:absolute;top:0;right:0}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;z-index:11;background:0 0;transition:opacity .1s linear}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{display:none;position:absolute}.xterm .xterm-scrollable-element>.shadow.top{width:100%;height:3px;box-shadow:var(--vscode-scrollbar-shadow,#000) 0 6px 6px -6px inset;display:block;top:0;left:3px}.xterm .xterm-scrollable-element>.shadow.left{width:3px;height:100%;box-shadow:var(--vscode-scrollbar-shadow,#000) 6px 0 6px -6px inset;display:block;top:3px;left:0}.xterm .xterm-scrollable-element>.shadow.top-left-corner{width:3px;height:3px;display:block;top:0;left:0}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow,#000) 6px 0 6px -6px inset}.vue-flow{z-index:0;direction:ltr;width:100%;height:100%;position:relative;overflow:hidden}.vue-flow__container{width:100%;height:100%;position:absolute;top:0;left:0}.vue-flow__pane{z-index:1}.vue-flow__pane.draggable{cursor:grab}.vue-flow__pane.selection{cursor:pointer}.vue-flow__pane.dragging{cursor:grabbing}.vue-flow__transformationpane{transform-origin:0 0;z-index:2;pointer-events:none}.vue-flow__viewport{z-index:4;overflow:clip}.vue-flow__selection{z-index:6}.vue-flow__edge-labels{pointer-events:none;-webkit-user-select:none;user-select:none;width:100%;height:100%;position:absolute}.vue-flow__nodesselection-rect:focus,.vue-flow__nodesselection-rect:focus-visible{outline:none}.vue-flow .vue-flow__edges{pointer-events:none;overflow:visible}.vue-flow__edge-path,.vue-flow__connection-path{stroke:#b1b1b7;stroke-width:1px;fill:none}.vue-flow__edge{pointer-events:visibleStroke;cursor:pointer}.vue-flow__edge.animated path{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__edge.animated path.vue-flow__edge-interaction{stroke-dasharLine truncated
.xterm{cursor:text;-webkit-user-select:none;user-select:none;position:relative}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{z-index:5;position:absolute;top:0}.xterm .xterm-helper-textarea{opacity:0;z-index:-5;white-space:nowrap;resize:none;border:0;width:0;height:0;margin:0;padding:0;position:absolute;top:0;left:-9999em;overflow:hidden}.xterm .composition-view{color:#fff;white-space:nowrap;z-index:1;background:#000;display:none;position:absolute}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{cursor:default;background-color:#000;position:absolute;inset:0;overflow-y:scroll}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;top:0;left:0}.xterm-char-measure-element{visibility:hidden;line-height:normal;display:inline-block;position:absolute;top:0;left:-9999em}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{z-index:10;color:#0000;pointer-events:none;position:absolute;inset:0}.xterm .xterm-accessibility-tree:not(.debug) ::selection{color:#0000}.xterm .xterm-accessibility-tree{-webkit-user-select:text;user-select:text;white-space:pre;font-family:monospace}.xterm .xterm-accessibility-tree>div{transform-origin:0;width:fit-content}.xterm .live-region{width:1px;height:1px;position:absolute;left:-9999px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{-webkit-text-decoration:underline double;text-decoration:underline double}.xterm-underline-3{-webkit-text-decoration:underline wavy;text-decoration:underline wavy}.xterm-underline-4{-webkit-text-decoration:underline dotted;text-decoration:underline dotted}.xterm-underline-5{-webkit-text-decoration:underline dashed;text-decoration:underline dashed}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:underline overline}.xterm-overline.xterm-underline-2{-webkit-text-decoration:overline double underline;text-decoration:overline double underline}.xterm-overline.xterm-underline-3{-webkit-text-decoration:overline wavy underline;text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{-webkit-text-decoration:overline dotted underline;text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{-webkit-text-decoration:overline dashed underline;text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;pointer-events:none;position:absolute;top:0;right:0}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;z-index:11;background:0 0;transition:opacity .1s linear}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{display:none;position:absolute}.xterm .xterm-scrollable-element>.shadow.top{width:100%;height:3px;box-shadow:var(--vscode-scrollbar-shadow,#000) 0 6px 6px -6px inset;display:block;top:0;left:3px}.xterm .xterm-scrollable-element>.shadow.left{width:3px;height:100%;box-shadow:var(--vscode-scrollbar-shadow,#000) 6px 0 6px -6px inset;display:block;top:3px;left:0}.xterm .xterm-scrollable-element>.shadow.top-left-corner{width:3px;height:3px;display:block;top:0;left:0}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow,#000) 6px 0 6px -6px inset}.vue-flow{z-index:0;direction:ltr;width:100%;height:100%;position:relative;overflow:hidden}.vue-flow__container{width:100%;height:100%;position:absolute;top:0;left:0}.vue-flow__pane{z-index:1}.vue-flow__pane.draggable{cursor:grab}.vue-flow__pane.selection{cursor:pointer}.vue-flow__pane.dragging{cursor:grabbing}.vue-flow__transformationpane{transform-origin:0 0;z-index:2;pointer-events:none}.vue-flow__viewport{z-index:4;overflow:clip}.vue-flow__selection{z-index:6}.vue-flow__edge-labels{pointer-events:none;-webkit-user-select:none;user-select:none;width:100%;height:100%;position:absolute}.vue-flow__nodesselection-rect:focus,.vue-flow__nodesselection-rect:focus-visible{outline:none}.vue-flow .vue-flow__edges{pointer-events:none;overflow:visible}.vue-flow__edge-path,.vue-flow__connection-path{stroke:#b1b1b7;stroke-width:1px;fill:none}.vue-flow__edge{pointer-events:visibleStroke;cursor:pointer}.vue-flow__edge.animated path{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__edge.animated path.vue-flow__edge-interaction{stroke-dasharLine truncated
+80 -80
View File
@@ -1,79 +1,79 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentProfilesPage.js","assets/CardAccordion.js","assets/PageHeader.js","assets/alert.js","assets/CredentialBindingsPage.js","assets/PlaybooksPage.js","assets/HarnessPage.js","assets/NotFoundPage.js"])))=>i.map(i=>d[i]);
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as ee,Z as T,_ as E,_t as D,a as te,at as ne,b as O,c as re,ct as ie,d as ae,dt as oe,et as se,f as ce,ft as le,g as ue,gt as de,h as fe,ht as pe,i as me,it as he,j as ge,k as _e,l as ve,lt as ye,m as be,mt as xe,n as Se,nt as Ce,o as we,ot as Te,p as Ee,pt as De,q as Oe,r as ke,rt as Ae,s as je,st as Me,t as Ne,tt as Pe,u as Fe,ut as Ie,v as Le,vt as Re,w as ze,x as Be,y as Ve,z as He}from"./CardAccordion.js";import{$ as Ue,A as k,B as We,C as Ge,Ct as Ke,D as A,Dn as qe,En as Je,Ft as Ye,It as Xe,Jt as j,Kt as Ze,Mt as Qe,O as M,Pt as $e,Qn as N,R as et,Rt as tt,Sn as nt,St as P,Tn as rt,Tt as it,Ut as F,V as at,Wt as ot,X as st,Xt as ct,Y as lt,Zt as ut,_ as I,_n as dt,_t as ft,an as pt,at as mt,b as L,bn as ht,d as gt,dn as _t,er as vt,et as yt,ht as R,it as bt,kn as z,lt as xt,mn as St,nr as B,nt as Ct,on as wt,pn as Tt,pt as Et,rn as Dt,s as V,t as Ot,tr as kt,tt as H,v as U,vn as At,wn as jt,x as W,xt as G,y as K,yn as q,zt as Mt}from"./PageHeader.js";import{A as Nt,D as Pt,E as Ft,J as It,K as Lt,S as Rt,T as zt,X as Bt,Y as Vt,_ as Ht,a as Ut,c as Wt,d as Gt,f as Kt,h as qt,i as Jt,l as Yt,m as Xt,n as Zt,o as J,p as Qt,q as $t,r as en,s as tn,t as nn,u as rn,v as Y,w as X,y as an}from"./alert.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var on=Ft({name:`arrow-down`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]}),sn=Ft({name:`arrow-left`,size:24,node:[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]}),cn=Ft({name:`arrow-up-down`,size:24,node:[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]}),ln=Ft({name:`arrow-up-right`,size:24,node:[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]}),un=Ft({name:`arrow-up`,size:24,node:[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]}),dn=Ft({name:`bell`,size:24,node:[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]}),fn=Ft({name:`book-open`,size:24,node:[[`path`,{d:`M12 5v16`,key:`1f6ucr`}],[`path`,{d:`M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z`,key:`1fyvmf`}]]}),pn=Ft({name:`bot`,size:24,node:[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]}),mn=Ft({name:`braces`,size:24,node:[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]],aliases:[`curly-braces`]}),hn=Ft({name:`calendar-clock`,size:24,node:[[`path`,{d:`M16 14v2.2l1.6 1`,key:`fo4ql5`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`path`,{d:`M21 7.338V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h2.338`,key:`7hb8p4`}],[`path`,{d:`M3 9h5.859`,key:`numkqi`}],[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`circle`,{cx:`16`,cy:`16`,r:`6`,key:`qoo3c4`}]]}),gn=Ft({name:`check`,size:24,node:[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]}),_n=Ft({name:`chevron-right`,size:24,node:[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]}),vn=Ft({name:`circle-alert`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]],aliases:[`alert-circle`]}),yn=Ft({name:`circle-check`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16 9-5.5 5.5L8 12`,key:`xofnsj`}]],aliases:[`check-circle-2`]}),bn=Ft({name:`circle-dot`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]}),xn=Ft({name:`circle-question-mark`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3- Line truncated
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AccountPage.js","assets/PageHeader.js","assets/api.js","assets/AuthenticationPage.js","assets/AgentProfilesPage.js","assets/CardAccordion.js","assets/pinia.js","assets/alert.js","assets/CredentialBindingsPage.js","assets/PlaybooksPage.js","assets/HarnessPage.js","assets/NotFoundPage.js"])))=>i.map(i=>d[i]);
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as ee,_ as E,a as D,at as te,b as ne,c as re,ct as ie,d as O,dt as ae,et as oe,f as se,ft as ce,g as le,h as ue,i as de,it as fe,j as pe,k as me,l as he,lt as ge,m as _e,mt as ve,n as ye,nt as be,o as xe,ot as Se,p as Ce,pt as we,q as Te,r as Ee,rt as De,s as Oe,st as ke,t as Ae,tt as je,u as Me,ut as Ne,v as Pe,w as Fe,x as Ie,y as Le,z as Re}from"./CardAccordion.js";import{$ as ze,A as k,B as Be,C as Ve,Ct as He,D as A,Dn as Ue,En as We,Ft as Ge,It as Ke,Jt as j,Kt as qe,Mt as Je,O as M,Pt as Ye,Qn as N,R as Xe,Rt as Ze,Sn as Qe,St as P,Tn as $e,Tt as et,Ut as F,V as tt,Wt as nt,X as rt,Xt as it,Y as at,Zt as ot,_ as I,_n as st,_t as ct,an as lt,at as ut,b as L,bn as dt,d as ft,dn as pt,er as mt,et as ht,ht as R,it as gt,kn as z,lt as _t,mn as vt,nr as B,nt as yt,on as bt,pn as xt,pt as St,rn as Ct,s as V,t as wt,tr as Tt,tt as H,v as U,vn as Et,wn as Dt,x as W,xt as G,y as K,yn as q,zt as Ot}from"./PageHeader.js";import{B as kt,H as At,U as jt,V as Mt,W as Nt,_ as Pt,b as Ft,c as It,d as Lt,f as Rt,g as J,h as Y,l as zt,m as Bt,n as X,o as Vt,p as Ht,r as Ut,t as Wt,u as Gt,v as Kt,w as qt,x as Jt}from"./api.js";import{n as Yt,r as Xt,t as Zt}from"./pinia.js";import{a as Qt,i as $t,n as en,o as tn,r as nn,t as rn}from"./alert.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function an(e,t,n){let r=e.findIndex(e=>ve(e,t)),i=e.findIndex(e=>ve(e,n));if(r===-1||i===-1)return[];let[a,o]=[r,i].sort((e,t)=>e-t);return e.slice(a,o+1)}function on(e,t=-1/0,n=1/0){return Math.min(n,Math.max(t,e))}function sn(e,t){let n=e,r=t.toString(),i=r.indexOf(`.`),a=i>=0?r.length-i:0;if(a>0){let e=10**a;n=Math.round(n*e)/e}return n}function cn(e,t,n,r){t=Number(t),n=Number(n);let i=(e-(Number.isNaN(t)?0:t))%r,a=sn(Math.abs(i)*2>=r?e+Math.sign(i)*(r-Math.abs(i)):e-i,r);return Number.isNaN(t)?!Number.isNaN(n)&&a>n&&(a=Math.floor(sn(n/r,r))*r):a<t?a=t:!Number.isNaN(n)&&a>n&&(a=t+Math.floor(sn((n-t)/r,r))*r),a=sn(a,r),a}var ln=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Bopomofo}]/u,un=/android/i;function dn(){return typeof navigator<`u`&&un.test(navigator.userAgent)}function fn(e){let t=q(!1),n=q(!0),r=q(!1),i=I(()=>t.value&&n.value);function a(){t.value=!0,n.value=!0,r.value=!1}function o(e){e.data&&(ln.test(e.data)?(n.value=!0,r.value=!0):dn()&&!r.value&&(n.value=!1))}function s(n){yt(()=>{t.value=!1,e?.(n)})}return{isComposing:t,shouldDeferInput:i,handleCompositionStart:a,handleCompositionUpdate:o,handleCompositionEnd:s}}function pn(e){let t=I(()=>z(e)),n=I(()=>new Intl.Collator(`en`,{usage:`search`,...t.value}));return{startsWith:(e,t)=>t.length===0||(e=e.normalize(`NFC`),t=t.normalize(`NFC`),n.value.compare(e.slice(0,t.length),t)===0),endsWith:(e,t)=>t.length===0||(e=e.normalize(`NFC`),t=t.normalize(`NFC`),n.value.compare(e.slice(-t.length),t)===0),contains:(e,t)=>{if(t.length===0)return!0;if(e=e.normalize(`NFC`),t=t.normalize(`NFC`),t.length>e.length)return!1;let r=n.value.compare;if(e.includes(t))return!0;let i=t.length;for(let n=0;n+i<=e.length;n++)if(r(t,e.slice(n,n+i))===0)return!0;return!1}}}function mn(e){return I(()=>!Ue(e)||!!w(e)?.closest(`form`))}function hn(){let e=Xe()?.vnode?.scopeId;return e?{[e]:``}:{}}function gn(e,t){let n=Se(!1,300);ke(()=>{n.value=!1});let r=q(null),i=je();function a(){r.value=null,n.value=!1}function o(e,t){if(!t)return;let i=e.currentTarget,a={x:e.clientX,y:e.clientY},o=vn(a,_n(a,i.getBoundingClientRect()),1),s=yn(t.getBoundingClientRect()),c=xn([...o,...s]);r.value=c,n.value=!0}return nt(n=>{if(e.value&&t.value){let r=e.value,i=t.value,a=e=>o(e,i),s=e=>o(e,r);r.addEventListener(`pointerleave`,a),i.addEventListener(`pointerleave`,s),n(()=>{r.removeEventListener(`pointerleave`,a),i.removeEventListener(`pointerleave`,s)})}}),nt(n=>{if(r.value){let o=n=>{if(!r.value||!(n.target instanceof Element))return;let o=n.target,s={x:n.clientX,y:n.clientY},c=e.value?.contains(o)||t.value?.contains(o),l=!bn(s,r.value),u=!!o.closest(`[data-grace-area-trigger]`);c?a():(l||u)&&(a(),i.trigger())},s=e.value?.ownerDocument;s?.addEventListener(`pointermove`,o),n(()=>s?.removeEventListener(`pointermove`,o))}}),{isPointerInTransit:n,onPointerExit:i.on}}function _n(e,t){lLine truncated
`);d=n.pop()||``;for(let e of n){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(Er.value=n.session_id),n.type===`delta`&&(o+=n.text,jr.value=jr.value?{...jr.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],jr.value=jr.value?{...jr.value,tools:a}:null),n.type===`ask`&&n.ask&&(clearTimeout(l),jr.value=jr.value?{...jr.value,ask:n.ask}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);Dr.value=[...Dr.value,{from:`assistant`,text:o,tool_calls:a}],jr.value=null,kr.value=`Ready`,await Kr()}catch(e){let t=e;t.name===`AbortError`&&!c?(jr.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},kr.value=`Stopped`):(jr.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?yr(r):void 0,isRetry:i},kr.value=`Error. Retry available.`)}finally{clearTimeout(l),Cr=null,Wr=null,Ar.value=!1}}function ai(){kr.value=`Stopping…`,Er.value&&Y.chatCancel(Er.value).catch(()=>{}),Gr()}function oi(){xt(()=>{Kr().catch(e=>{kr.value=e.message||`Chat unavailable`})}),Et(()=>{Gr()})}async function si(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));await ii({textOverride:`🎤 Voice message`,voice:{data:btoa(n),mime_type:e.type||`audio/webm`}})}var ci=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],li=k({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return X(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(R(),W(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full border border-border-strong bg-secondary text-primary shadow-[var(--shadow-md)] transition-transform duration-[140ms] hover:-translate-y-px focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":z(xr),onClick:i[0]||=e=>n(`toggle`)},[U(`span`,{"aria-hidden":`true`,class:N(r(!e.open))},[M(z(In),{size:22})],2),U(`span`,{"aria-hidden":`true`,class:N(r(e.open))},[M(z(lr),{size:22})],2)],8,ci))}});function ui(e,t,n){let r=e.findIndex(e=>De(e,t)),i=e.findIndex(e=>De(e,n));if(r===-1||i===-1)return[];let[a,o]=[r,i].sort((e,t)=>e-t);return e.slice(a,o+1)}function di(e,t=-1/0,n=1/0){return Math.min(n,Math.max(t,e))}function fi(e,t){let n=e,r=t.toString(),i=r.indexOf(`.`),a=i>=0?r.length-i:0;if(a>0){let e=10**a;n=Math.round(n*e)/e}return n}function pi(e,t,n,r){t=Number(t),n=Number(n);let i=(e-(Number.isNaN(t)?0:t))%r,a=fi(Math.abs(i)*2>=r?e+Math.sign(i)*(r-Math.abs(i)):e-i,r);return Number.isNaN(t)?!Number.isNaN(n)&&a>n&&(a=Math.floor(fi(n/r,r))*r):a<t?a=t:!Number.isNaN(n)&&a>n&&(a=t+Math.floor(fi((n-t)/r,r))*r),a=fi(a,r),a}var mi=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Bopomofo}]/u,hi=/android/i;function gi(){return typeof navigator<`u`&&hi.test(navigator.userAgent)}function _i(e){let t=q(!1),n=q(!0),r=q(!1),i=I(()=>t.value&&n.value);function a(){t.value=!0,n.value=!0,r.value=!1}function o(e){e.data&&(mi.test(e.data)?(n.value=!0,r.value=!0):gi()&&!r.value&&(n.value=!1))}function s(n){Ct(()=>{t.value=!1,e?.(n)})}return{isComposing:t,shouldDeferInput:i,handleCompositionStart:a,handleCompositionUpdate:o,handleCompositionEnd:s}}function vi(e){let t=I(()=>z(e)),n=I(()=>new Intl.Collator(`en`,{usage:`search`,...t.value}));return{startsWith:(e,t)=>t.length===0||(e=e.normalize(`NFC`),t=t.normalize(`NFC`),n.value.compare(e.slice(0,t.length),t)===0),endsWith:(e,t)=>t.length===0||(e=e.normalize(`NFC`),t=t.normalize(`NFC`),n.value.compare(e.slice(-t.length),t)===0),contains:(e,t)=>{if(t.length===0)return!0;if(e=e.normalize(`NFC`),t=t.normalize(`NFC`),t.length>e.length)return!1;let r=n.value.compare;if(e.includes(t))return!0;let i=t.length;for(let n=0;n+i<=e.length;n++)if(r(t,e.slice(n,n+i))===0)return!0;return!1}}}function yi(e){return I(()=>!qe(e)||!!ee(e)?.closest(`form`))}function bi(){let e=et()?.vnode?.scopeId;return e?{[e]:``}:{}}function xi(e,t){let n=ne(!1,300);Te(()=>{n.value=!1});let r=q(null),i=se();function a(){r.value=null,n.value=!1}function o(e,t){if(!t)return;let i=e.currentTarget,a={x:e.clientX,y:e.clientY},o=Ci(a,Si(a,i.getBoundingClientRect()),1),s=wi(t.getBoundingClientRect()),c=Ei([...o,...s]);r.value=c,n.value=!0}return ot(n=>{if(e.value&&t.value){let r=e.value,i=t.value,a=e=>o(e,i),s=e=>o(e,r);r.addEventListener(`pointerleave`,a),i.addEventListener(`pointerleave`,s),n(()=>{r.removeEventListener(`pointerleave`,a),i.removeEventListener(`pointerleave`,s)})}}),ot(n=>{if(r.value){let o=n=>{if(!r.value||!(n.target instanceof Element))return;let o=n.target,s={x:n.clientX,y:n Line truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:nd(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>nd(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=id(c),u=e+1<n.length?id(n[e+1]):null;if(l&&u&&ad(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=id(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>nd(e)),rows:r.map(e=>e.map(e=>nd(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:nd(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1])}else c.startsWith(`>`)?(o(),s(),t.push({kind:`blockquote`,inline:nd(c.replace(/^>\s?/,``))})):r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function id(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function ad(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var od={class:`[overflow-wrap:anywhere]`},sd={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},cd={class:`font-mono text-[0.85em]`},ld={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},ud={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},dd={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},fd={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},pd={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},md={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},hd={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},gd={key:8,class:`mb-2.5 last:mb-0`},_d=k({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=I(()=>rd(t.text));return(e,t)=>(R(),W(`div`,od,[(R(!0),W(V,null,G(n.value,(e,t)=>(R(),W(V,{key:t},[e.kind===`pre`?(R(),W(`pre`,sd,[U(`code`,cd,B(e.code),1)])):e.kind===`table`?(R(),W(`table`,ld,[U(`thead`,null,[U(`tr`,null,[(R(!0),W(V,null,G(e.head,(e,t)=>(R(),W(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[M(ed,{inline:e},null,8,[`inline`])]))),128))])]),U(`tbody`,null,[(R(!0),W(V,null,G(e.rows,(e,t)=>(R(),W(`tr`,{key:t},[(R(!0),W(V,null,G(e,(e,t)=>(R(),W(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[M(ed,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(R(),W(`blockquote`,ud,[M(ed,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(R(),W(`h1`,dd,[M(ed,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(R(),W(`h2`,fd,[M(ed,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(R(),W(`h3`,pd,[M(ed,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(R(),W(`ul`,md,[(R(!0),W(V,null,G(e.items,(e,t)=>(R(),W(`li`,{key:t},[M(ed,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(R(),W(`ol`,hd,[(R(!0),W(V,null,G(e.items,(e,t)=>(R(),W(`li`,{key:t},[M(ed,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(R(),W(`p`,gd,[M(ed,{inline:e.inline},null,8,[`inline`])])):L(``,!0)],64))),128))]))}}),vd={class:`truncate`},yd=k({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=Ke(`RouterLink`);return R(),K(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-md border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[M(z(ln),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),U(`span`,vd,B(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),bd={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},xd={class:`font-semibold text-foreground`},Sd={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},Cd=k({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=I(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=I(()=>t.tool.parameters||t.tool.Parameters||``),i=I(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=I(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(R(),K(yd,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(R(),W(`div`,bd,[M(z(cr),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),U(`span`,xd,B(n.value),1),r.value?(R(),W(`code`,Sd,B(r.value),1)):L(``,!0),U(`span`,{class:N(z(X)(`text-fg-muted`,i.value&&`text-danger`))},B(a.value),3)]))}}),wd={key:0,class:`mb-2 grid gap-0.5 text-xs`},Td={key:1,class:`mb-2 flex flex-wrap gap-1.5`},Ed={key:3,class:`whitespace-pre-wrap`},Dd=k({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},media:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(R(),W(`div`,{class:N([`flex`,e.assistant?`justify-start`:`justify-end`])},[U(`div`,{class:N(z(X)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(R(),W(`div`,wd,[(R(!0),W(V,null,G(e.tools,(t,n)=>(R(),K(Cd,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):L(``,!0),e.media.length?(R(),W(`div`,Td,[(R(!0),W(V,null,G(e.media,(e,t)=>(R(),K(qu,{key:t,attachment:e},null,8,[`attachment`]))),128))])):L(``,!0),e.assistant?(R(),K(_d,{key:2,text:e.text},null,8,[`text`])):(R(),W(`div`,Ed,B(e.text),1)),P(t.$slots,`default`)],2)],2))}}),Od={class:`text-sm`},kd={class:`font-medium`},Ad={key:0,class:`mt-1 text-fg-muted`},jd={key:1,class:`mt-2 flex flex-wrap gap-2`},Md=k({__name:`ChatChooLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>Og?`${n.slice(0,Og).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}function Ag(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function jg(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`under 1 s`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function Mg(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function Ng(e){return typeof e==`string`?e:``}function Pg(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=jg(t.duration_ms),i=[r,e&&`ran for ${e}`].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.skipped?`Skipped stage: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[i,Ng(t.error),Ng(t.when)].filter(Boolean).join(` · `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[Ng(t.previous_stage)&&`after ${Ng(t.previous_stage)}`,Ng(t.previous_reason)].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=Mg(t.iterations),i=Mg(t.tokens),a=Number(t.cached_tokens)||0,o=Mg((Number(t.prompt_tokens)||0)-a),s=Mg(t.completion_tokens),c=Mg(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,Ng(t.model)].filter(Boolean);return{title:`Agent ${Ng(t.status)||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}if(e.kind===`remediation_round`){let e=Number(t.of),n=Ng(t.author);return{title:`Remediation ${Ng(t.round)}${e>0?` of ${e}`:``}`,detail:[n&&`answers ${n}'s review`,t.review_id?`#${Ng(t.review_id)}`:``].filter(Boolean).join(` `)}}if(e.kind===`review_approved`){let e=Ng(t.pr_number);return{title:`Pull request approved`,detail:[Ng(t.author),e&&`#${e}`].filter(Boolean).join(` · `)}}if(e.kind===`step_retried`)return{title:`Attempt ${Ng(t.attempt)} of ${Ng(t.of)} failed: ${e.stage||`step`}`,detail:Ng(t.error),tone:`warn`};if(e.kind===`config_captured`)return{title:`Configuration captured`,detail:`The effective task-runtime configuration for this run.`};if(e.kind===`binding_started`){let e=Ng(t.source),n=Ng(t.capture_id),r=[{label:`binding ${Ng(t.binding_name)||Ng(t.binding_id)}`,to:`/events?tab=bindings`},...n?[{label:`captured event`,to:`/events?tab=inspector&capture=${encodeURIComponent(n)}`}]:[]];return t.unsigned===!0?{title:`Started by an unsigned event`,detail:e?`source ${e}`:``,tone:`warn`,links:r}:{title:`Started by an event`,detail:e?`source ${e}`:``,links:r}}if(e.kind===`changes_captured`){let e=t.totals??{},n=Number(e.files);return{title:`Change capture recorded`,detail:[Number.isFinite(n)&&n>0?`${n} file${n===1?``:`s`} changed`:``,t.captured_after?`captured after ${Ng(t.captured_after)}`:``].filter(Boolean).join(` · `)}}return{title:Ag(e.kind||e.type),detail:e.detail||``}}var Fg=[`title`],Ig=k({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=vg(),a=I(()=>i.taskIDFor(n.event)),o=I(()=>kg(n.event));function s(){a.value>0&&r(`open`,a.value)}let c=I(()=>n.event.at?Zh(n.event.at):`—`);return(e,t)=>(R(),K(z(Tg),{class:N(a.value>0?`cursor-pointer`:``),role:a.value>0?`link`:void 0,tabindex:a.value>0?0:void 0,title:a.value>0?`Open task details`:void 0,onClick:s,onKeydown:[Vt(Bt(s,[`prevent`]),[`enter`]),Vt(Bt(s,[`prevent`]),[`space`])]},{default:j(()=>[M(z(Z),{class:`font-medium`},{default:j(()=>[A(B(z(Pg)({...n.event,at:void 0,detail:void 0}).title),1)]),_:1}),M(z(Z),{class:`font-mono`},{default:j(()=>[A(B(a.value>0?`#${a.value}`:`—`),1)]),_:1}),M(z(Z),{class:`w-[55%] max-w-0`},{default:j(()=>[U(`span`,{class:`block truncate`,title:o.value.truncated?o.value.full:void 0},B(o.value.text),9,Fg)]),_:1}),M(z(Z),null,{default:j(()=>[A(B(c.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),Lg=[{value:`all`,label:`All`},{value:`tasks`,label:`Tasks`},{value:`system`,label:`System`}];function Rg(e){return(Number(e?.task_id)||0)>0}function zg(e,t){return t===`tasks`?Rg(e):t!==`system`||!Rg(e)}function Bg(e,t){return e.filter(e=>zg(e,t))}function Vg(e,t){return e>0?``:t===`all`?`Waiting for activity`:t===`tasks`?`No task events yet`:`No system events yet`}function Hg(e,t){return`${e}:${t??0}`}function Ug(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=Hg(kg(n).text,r),a=t[t.length-1];a&&a.key===i?(a.count+=1,a.events.push(n)):t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var Wg={key:0,class:`font-normal text-fg-subtle`},Gg={role:`region`,"aria-label":`Activity`,"aria-live":`polite`},Kg={class:`max-h-[28rem] oveLine truncated
`,1)[0]??``;return t.length>80?`${t.slice(0,79)}…`:t}var uv=k({__name:`Collapsible`,props:{defaultOpen:{type:Boolean},open:{type:Boolean},disabled:{type:Boolean},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{}},emits:[`update:open`],setup(e,{emit:t}){let n=He(e,t);return(e,t)=>(R(),K(z(o),H({"data-slot":`collapsible`},z(n)),{default:j(t=>[P(e.$slots,`default`,vt(We(t)))]),_:3},16))}}),dv=k({__name:`CollapsibleContent`,props:{forceMount:{type:Boolean},asChild:{type:Boolean},as:{}},setup(e){let t=e;return(e,n)=>(R(),K(z(g),H({"data-slot":`collapsible-content`},t),{default:j(()=>[P(e.$slots,`default`)]),_:3},16))}}),fv=k({__name:`CollapsibleTrigger`,props:{asChild:{type:Boolean},as:{}},setup(e){let t=e;return(e,n)=>(R(),K(z(m),H({"data-slot":`collapsible-trigger`},t),{default:j(()=>[P(e.$slots,`default`)]),_:3},16))}});function pv(e){return(e?.merged||0)+(e?.completed||0)}function mv(e){return Object.entries(e?.inputs??{}).map(([e,t])=>({name:e,type:t.type,required:t.required===!0})).sort((e,t)=>e.name.localeCompare(t.name))}function hv(e,t){return e.filter(e=>e.required&&!(t[e.name]??``).trim()).map(e=>e.name)}function gv(e,t){switch(t){case`number`:{let t=e.trim();return t!==``&&!Number.isNaN(Number(t))?Number(t):e}case`bool`:return e===`true`||e!==`false`&&e;case`string`:return e;default:try{return JSON.parse(e)}catch{return e}}}function _v(e,t){let n={};for(let r of e){let e=t[r.name];e!==void 0&&e!==``&&(n[r.name]=gv(e,r.type))}return n}var vv=[`onKeydown`],yv={key:0,class:`text-sm text-danger`,role:`alert`},bv={key:1,class:`grid gap-1.5`},xv=[`for`],Sv={key:0,class:`font-normal text-fg-subtle`},Cv=[`id`],wv=[`value`],Tv={key:0,class:`text-xs text-fg-subtle`},Ev={key:2,class:`grid gap-1.5`},Dv=[`id`],Ov={class:`block truncate font-mono text-[13px] font-medium`},kv={class:`block text-xs text-fg-subtle`},Av={key:0,class:`text-xs text-fg-subtle`},jv={key:3,class:`grid gap-3`},Mv=[`for`],Nv={class:`font-mono`},Pv={key:0,class:`text-fg-subtle`},Fv={class:`text-xs text-fg-subtle`},Iv={class:`grid gap-1.5`},Lv=[`for`],Rv={class:`grid gap-1.5`},zv=[`for`],Bv={class:`font-mono`},Vv={key:4,class:`text-sm text-danger`,role:`alert`},Hv={class:`flex items-center gap-2 border-t border-border pt-4`},Uv={class:`mr-auto text-xs text-fg-subtle`},Wv=k({__name:`NewTaskForm`,props:{workflow:{},draft:{},initialWorkflow:{},initialInstructions:{}},emits:[`started`,`cancel`],setup(e,{emit:t}){let n=e,r=t,i=Ye(),a=q([]),o=q([]),s=q([]),c=q(``);xt(async()=>{try{let[e,t]=await Promise.all([Y.workflows(),Y.tasks()]);a.value=(e?.definitions??[]).filter(e=>e.enabled),o.value=e?.workflows??[],s.value=[...new Set((t??[]).filter(e=>e.owner&&e.repo).map(e=>`${e.owner}/${e.repo}`))].slice(0,5)}catch(e){c.value=String(e.message||e)}});let l=cv();l.watchIdentities();let u=I(()=>l.identities.filter(e=>e.kind!==`system`&&e.lifecycle===`active`)),d=q(``),f=q(n.workflow??n.initialWorkflow??``),p=q(n.initialInstructions??``),m=q(lv(p.value)),h=q(``),g=q({});ot(()=>{!f.value&&a.value[0]&&(f.value=a.value[0].id),!h.value&&u.value[0]&&(h.value=u.value[0].id)});let _=I(()=>a.value.find(e=>e.id===f.value)),v=I(()=>mv(_.value)),y=I(()=>hv(v.value,g.value)),b=I(()=>_.value?.repository??`required`),x=I(()=>b.value!==`optional`&&b.value!==`none`),S=e=>o.value.find(t=>t.workflow===e),C=I(()=>u.value.find(e=>e.id===h.value)?.display_name??`nobody`),w=q(!1),ee=q(``),T=I(()=>!!((d.value.trim()||!x.value)&&f.value&&m.value.trim()&&p.value.trim()&&h.value)&&y.value.length===0);async function E(){if(T.value&&!w.value){w.value=!0,ee.value=``;try{let e=await Y.workRequest({identity:h.value,repository:b.value===`none`?``:d.value.trim(),workflow:f.value,title:m.value.trim(),instructions:p.value,inputs:_v(v.value,g.value),...n.draft?{draft:n.draft}:{}});r(`started`,e.task_id)}catch(e){ee.value=String(e.message||e)}finally{w.value=!1}}}return(e,t)=>(R(),W(`form`,{class:`grid gap-5`,onSubmit:Bt(E,[`prevent`]),onKeydown:[Vt(Bt(E,[`meta`,`prevent`]),[`enter`]),Vt(Bt(E,[`ctrl`,`prevent`]),[`enter`])]},[c.value?(R(),W(`p`,yv,B(c.value),1)):L(``,!0),b.value===`none`?L(``,!0):(R(),W(`div`,bv,[U(`label`,{for:`${z(i)}-repo`,class:`text-[13px] font-medium`},[t[6]||=A(`Repository`,-1),x.value?L(``,!0):(R(),W(`span`,Sv,` (optional)`))],8,xv),M(z(O),{id:`${z(i)}-repo`,modelValue:d.value,"onUpdate:modelValue":t[0]||=e=>d.value=e,class:`font-mono`,placeholder:`owner/repository`,list:`${z(i)}-repos`,required:x.value},null,8,[`id`,`modelValue`,`list`,`required`]),U(`datalist`,{id:`${z(i)}-repos`},[(R(!0),W(V,null,G(s.value,e=>(R(),W(`option`,{key:e,value:e},null,8,wv))),128))],8,Cv),s.value.length?(R(),W(`p`,Tv,[t[7]||=A(`Recent: `,-1),(R(!0),W(V,null,G(s.value,e=>(R(),K(z(J),{key:e,type:`button`,variant:`link`,size:`xs`,class:`h-auto px-1 font-mono text-fg-subtle`,onClick:t=>d.value=e},{default:j(()=>[A(B(e),1)]),_:2},1032,[`onClick`]))),128))])):L(``,!0)])),n.workflow?L(``,!0):(R(),W(`div`,Ev,[U(`span`,{id:`${z(i)}-wf`,class:`text-[13px] font-medium`},`Workflow`,8,Dv),M( Line truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function cy(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function ly(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function uy(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function dy(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var fy=q([]),py=q([]),my=q(!0),hy=q(null),gy=q(null),_y=q(!1),vy=q(null);async function yy(){try{let e=await Y.eventTypes(oy().workspace);my.value=e.enabled!==!1,fy.value=e.event_types||[],py.value=e.proposals||[],hy.value=null}catch(e){hy.value=e.message||String(e)}}function by(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function xy(e){vy.value=null,gy.value=e}function Sy(e){let t=Ay.value.find(t=>String(t.id)===e.sample_id);xy({mode:`proposal`,id:null,source:e.source,name:``,rule:by(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function Cy(e=``){xy({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function wy(e){xy({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:by(e.rule),headersText:``,body:``,exampleHeaders:{}})}function Ty(){gy.value=null}async function Ey(){let e=gy.value;if(e){_y.value=!0;try{if(e.mode===`edit`&&e.id)await Y.eventTypeUpdate(e.id,{name:e.name,rule:dy(e.rule)});else{let t=e.mode===`paste`?sy(e.headersText):e.exampleHeaders;await Y.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:dy(e.rule),example:{headers:t,body:e.body}})}gy.value=null,await yy()}catch(e){vy.value=e.message||String(e)}finally{_y.value=!1}}}var Dy=q(null);async function Oy(){let e=Dy.value;if(Dy.value=null,e)try{await Y.eventTypeDelete(e.id),await yy()}catch(e){hy.value=e.message||String(e)}}var ky=100,Ay=q([]),jy=q(!0),My=q(null),Ny=q(!0),Py=q(null);async function Fy(){try{let e=await Y.captures(ky);jy.value=e.enabled!==!1,Ay.value=e.captures||[],My.value=null}catch(e){My.value=e.message||String(e)}finally{Ny.value=!1}}function Iy(e){let t=Ay.value.find(t=>t.id===e);return t&&(Py.value=t),!!t}function Ly(){Ay.value.length&&(Py.value=Ay.value[0])}function Ry(){Le(`captures`,()=>{Fy(),yy()})}var zy=k({__name:`Tabs`,props:{defaultValue:{},orientation:{},dir:{},activationMode:{},modelValue:{},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=Kt(n,`class`),a=He(i,r);return(e,t)=>(R(),K(z(wc),H({"data-slot":`tabs`,"data-orientation":z(a).orientation||`horizontal`},z(a),{class:z(X)(`gap-2 group/tabs flex data-horizontal:flex-col`,n.class)}),{default:j(t=>[P(e.$slots,`default`,vt(We(t)))]),_:3},16,[`data-orientation`,`class`]))}}),By=k({__name:`TabsContent`,props:{value:{},forceMount:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=Kt(t,`class`);return(e,r)=>(R(),K(z(Dc),H({"data-slot":`tabs-content`,class:z(X)(`text-sm flex-1 outline-none`,t.class)},z(n)),{default:j(()=>[P(e.$slots,`default`)]),_:3},16,[`class`]))}}),Vy=k({__name:`TabsList`,props:{loop:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]},variant:{default:`default`}},setup(e){let t=e,n=Kt(t,`class`,`variant`);return(r,i)=>(R(),K(z(Oc),H({"data-slot":`tabs-list`,"data-variant":e.variant},z(n),{class:z(X)(z(Uy)({variant:e.variant}),t.class)}),{default:j(()=>[P(r.$slots,`default`)]),_:3},16,[`data-variant`,`class`]))}}),Hy=k({__name:`TabsTrigger`,props:{value:{},disabled:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,r=Kt(t,`class`),i=n(r);return(e,n)=>(R(),K(z(kc),H({"data-slot":`tabs-trigger`,class:z(X)(`gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg:not([class*=size-])]:size-4 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointerLine truncated
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(zc.value=n.session_id),n.type===`delta`&&(o+=n.text,Wc.value=Wc.value?{...Wc.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],Wc.value=Wc.value?{...Wc.value,tools:a}:null),n.type===`ask`&&n.ask&&(clearTimeout(l),Wc.value=Wc.value?{...Wc.value,ask:n.ask}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);Bc.value=[...Bc.value,{from:`assistant`,text:o,tool_calls:a}],Wc.value=null,Hc.value=`Ready`,await al()}catch(e){let t=e;t.name===`AbortError`&&!c?(Wc.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},Hc.value=`Stopped`):(Wc.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Mc(r):void 0,isRetry:i},Hc.value=`Error. Retry available.`)}finally{clearTimeout(l),Ic=null,rl=null,Uc.value=!1}}function vl(){Hc.value=`Stopping…`,zc.value&&X.chatCancel(zc.value).catch(()=>{}),il()}function yl(){_t(()=>{al().catch(e=>{Hc.value=e.message||`Chat unavailable`})}),St(()=>{il()})}async function bl(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));await _l({textOverride:`🎤 Voice message`,voice:{data:btoa(n),mime_type:e.type||`audio/webm`}})}var xl=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Sl=k({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return J(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(R(),W(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full border border-border-strong bg-secondary text-primary shadow-[var(--shadow-md)] transition-transform duration-[140ms] hover:-translate-y-px focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":z(Pc),onClick:i[0]||=e=>n(`toggle`)},[U(`span`,{"aria-hidden":`true`,class:N(r(!e.open))},[M(z(Ys),{size:22})],2),U(`span`,{"aria-hidden":`true`,class:N(r(e.open))},[M(z(Sc),{size:22})],2)],8,xl))}}),Cl=k({__name:`Select`,props:{open:{type:Boolean},defaultOpen:{type:Boolean},defaultValue:{},modelValue:{},nullableValue:{},by:{type:[String,Function]},dir:{},multiple:{type:Boolean},autocomplete:{},disabled:{type:Boolean},name:{},required:{type:Boolean}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let r=n(e,t);return(e,t)=>(R(),K(z(Ra),H({"data-slot":`select`},z(r)),{default:j(t=>[P(e.$slots,`default`,mt(Be(t)))]),_:3},16))}}),wl=k({inheritAttrs:!1,__name:`SelectContent`,props:{forceMount:{type:Boolean},position:{default:`item-aligned`},bodyLock:{type:Boolean},loop:{type:Boolean},memoDependencies:{},side:{},sideOffset:{},sideFlip:{type:Boolean},align:{default:`center`},alignOffset:{},alignFlip:{type:Boolean},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},hideShiftedArrow:{type:Boolean},sticky:{},hideWhenDetached:{type:Boolean},positionStrategy:{},updatePositionStrategy:{},disableUpdateOnLayoutShift:{type:Boolean},prioritizePosition:{type:Boolean},reference:{},dir:{},asChild:{type:Boolean},as:{},disableOutsidePointerEvents:{type:Boolean},class:{type:[Boolean,null,String,Object,Array]}},emits:[`closeAutoFocus`,`escapeKeyDown`,`pointerDownOutside`],setup(e,{emit:t}){let r=e,i=t,a=Rt(r,`class`),o=n(a,i);return(t,n)=>(R(),K(z(ao),null,{default:j(()=>[M(z(Xa),H({"data-slot":`select-content`,"data-align-trigger":e.position===`item-aligned`},{...t.$attrs,...z(o)},{class:z(J)(`bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 min-w-36 rounded-lg shadow-md ring-1 duration-100 data-[side=inline-start]:slide-in-from-right-2 data-[side=inline-end]:slide-in-from-left-2 cn-menu-translucent relative z-50 max-h-(--reka-select-content-available-height) origin-(--reka-select-content-transform-origin) overflow-x-hidden overflow-y-auto data-[align-trigger=true]:animate-none`,e.position===`popper`&&`data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1`,r.class)}),{default:j(()=>[M(z(kl)),M(z(fo),{"data-position":e.position,class:N(z(J)(`data-[position=popper]:h-(--reka-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--reka-select-trigger-width)`))},{default:j(()=>[P(t.$slots,`default`)]),_:3 Line truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:xd(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>xd(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=Cd(c),u=e+1<n.length?Cd(n[e+1]):null;if(l&&u&&wd(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=Cd(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>xd(e)),rows:r.map(e=>e.map(e=>xd(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:xd(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1])}else c.startsWith(`>`)?(o(),s(),t.push({kind:`blockquote`,inline:xd(c.replace(/^>\s?/,``))})):r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function Cd(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function wd(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var Td={class:`[overflow-wrap:anywhere]`},Ed={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},Dd={class:`font-mono text-[0.85em]`},Od={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},kd={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},Ad={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},jd={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},Md={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},Nd={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},Pd={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},Fd={key:8,class:`mb-2.5 last:mb-0`},Id=k({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=I(()=>Sd(t.text));return(e,t)=>(R(),W(`div`,Td,[(R(!0),W(V,null,G(n.value,(e,t)=>(R(),W(V,{key:t},[e.kind===`pre`?(R(),W(`pre`,Ed,[U(`code`,Dd,B(e.code),1)])):e.kind===`table`?(R(),W(`table`,Od,[U(`thead`,null,[U(`tr`,null,[(R(!0),W(V,null,G(e.head,(e,t)=>(R(),W(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[M(yd,{inline:e},null,8,[`inline`])]))),128))])]),U(`tbody`,null,[(R(!0),W(V,null,G(e.rows,(e,t)=>(R(),W(`tr`,{key:t},[(R(!0),W(V,null,G(e,(e,t)=>(R(),W(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[M(yd,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(R(),W(`blockquote`,kd,[M(yd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(R(),W(`h1`,Ad,[M(yd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(R(),W(`h2`,jd,[M(yd,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(R(),W(`h3`,Md,[M(yd,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(R(),W(`ul`,Nd,[(R(!0),W(V,null,G(e.items,(e,t)=>(R(),W(`li`,{key:t},[M(yd,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(R(),W(`ol`,Pd,[(R(!0),W(V,null,G(e.items,(e,t)=>(R(),W(`li`,{key:t},[M(yd,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(R(),W(`p`,Fd,[M(yd,{inline:e.inline},null,8,[`inline`])])):L(``,!0)],64))),128))]))}}),Ld={class:`truncate`},Rd=k({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=He(`RouterLink`);return R(),K(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-md border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[M(z(Ss),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),U(`span`,Ld,B(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),zd={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},Bd={class:`font-semibold text-foreground`},Vd={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},Hd=k({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=I(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=I(()=>t.tool.parameters||t.tool.Parameters||``),i=I(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=I(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(R(),K(Rd,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(R(),W(`div`,zd,[M(z(xc),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),U(`span`,Bd,B(n.value),1),r.value?(R(),W(`code`,Vd,B(r.value),1)):L(``,!0),U(`span`,{class:N(z(J)(`text-fg-muted`,i.value&&`text-danger`))},B(a.value),3)]))}}),Ud={key:0,class:`mb-2 grid gap-0.5 text-xs`},Wd={key:1,class:`mb-2 flex flex-wrap gap-1.5`},Gd={key:3,class:`whitespace-pre-wrap`},Kd=k({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},media:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(R(),W(`div`,{class:N([`flex`,e.assistant?`justify-start`:`justify-end`])},[U(`div`,{class:N(z(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(R(),W(`div`,Ud,[(R(!0),W(V,null,G(e.tools,(t,n)=>(R(),K(Hd,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):L(``,!0),e.media.length?(R(),W(`div`,Wd,[(R(!0),W(V,null,G(e.media,(e,t)=>(R(),K(fd,{key:t,attachment:e},null,8,[`attachment`]))),128))])):L(``,!0),e.assistant?(R(),K(Id,{key:2,text:e.text},null,8,[`text`])):(R(),W(`div`,Gd,B(e.text),1)),P(t.$slots,`default`)],2)],2))}}),qd={class:`text-sm`},Jd={class:`font-medium`},Yd={key:0,class:`mt-1 text-fg-muted`},Xd={key:1,class:`mt-2 flex flex-wrap gap-2`},Zd=k({__name:`ChatChooLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>$g?`${n.slice(0,$g).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}function t_(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function n_(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`under 1 s`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function r_(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function i_(e){return typeof e==`string`?e:``}function a_(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=n_(t.duration_ms),i=[r,e&&`ran for ${e}`].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.skipped?`Skipped stage: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[i,i_(t.error),i_(t.when)].filter(Boolean).join(` · `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[i_(t.previous_stage)&&`after ${i_(t.previous_stage)}`,i_(t.previous_reason)].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=r_(t.iterations),i=r_(t.tokens),a=Number(t.cached_tokens)||0,o=r_((Number(t.prompt_tokens)||0)-a),s=r_(t.completion_tokens),c=r_(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,i_(t.model)].filter(Boolean);return{title:`Agent ${i_(t.status)||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}if(e.kind===`remediation_round`){let e=Number(t.of),n=i_(t.author);return{title:`Remediation ${i_(t.round)}${e>0?` of ${e}`:``}`,detail:[n&&`answers ${n}'s review`,t.review_id?`#${i_(t.review_id)}`:``].filter(Boolean).join(` `)}}if(e.kind===`review_approved`){let e=i_(t.pr_number);return{title:`Pull request approved`,detail:[i_(t.author),e&&`#${e}`].filter(Boolean).join(` · `)}}if(e.kind===`step_retried`)return{title:`Attempt ${i_(t.attempt)} of ${i_(t.of)} failed: ${e.stage||`step`}`,detail:i_(t.error),tone:`warn`};if(e.kind===`config_captured`)return{title:`Configuration captured`,detail:`The effective task-runtime configuration for this run.`};if(e.kind===`binding_started`){let e=i_(t.source),n=i_(t.capture_id),r=[{label:`binding ${i_(t.binding_name)||i_(t.binding_id)}`,to:`/events?tab=bindings`},...n?[{label:`captured event`,to:`/events?tab=inspector&capture=${encodeURIComponent(n)}`}]:[]];return t.unsigned===!0?{title:`Started by an unsigned event`,detail:e?`source ${e}`:``,tone:`warn`,links:r}:{title:`Started by an event`,detail:e?`source ${e}`:``,links:r}}if(e.kind===`changes_captured`){let e=t.totals??{},n=Number(e.files);return{title:`Change capture recorded`,detail:[Number.isFinite(n)&&n>0?`${n} file${n===1?``:`s`} changed`:``,t.captured_after?`captured after ${i_(t.captured_after)}`:``].filter(Boolean).join(` · `)}}return{title:t_(e.kind||e.type),detail:e.detail||``}}var o_=[`title`],s_=k({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=Ug(),a=I(()=>i.taskIDFor(n.event)),o=I(()=>e_(n.event));function s(){a.value>0&&r(`open`,a.value)}let c=I(()=>n.event.at?Sg(n.event.at):`—`);return(e,t)=>(R(),K(z(Xg),{class:N(a.value>0?`cursor-pointer`:``),role:a.value>0?`link`:void 0,tabindex:a.value>0?0:void 0,title:a.value>0?`Open task details`:void 0,onClick:s,onKeydown:[jt(Nt(s,[`prevent`]),[`enter`]),jt(Nt(s,[`prevent`]),[`space`])]},{default:j(()=>[M(z(Q),{class:`font-medium`},{default:j(()=>[A(B(z(a_)({...n.event,at:void 0,detail:void 0}).title),1)]),_:1}),M(z(Q),{class:`font-mono`},{default:j(()=>[A(B(a.value>0?`#${a.value}`:`—`),1)]),_:1}),M(z(Q),{class:`w-[55%] max-w-0`},{default:j(()=>[U(`span`,{class:`block truncate`,title:o.value.truncated?o.value.full:void 0},B(o.value.text),9,o_)]),_:1}),M(z(Q),null,{default:j(()=>[A(B(c.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),c_=[{value:`all`,label:`All`},{value:`tasks`,label:`Tasks`},{value:`system`,label:`System`}];function l_(e){return(Number(e?.task_id)||0)>0}function u_(e,t){return t===`tasks`?l_(e):t!==`system`||!l_(e)}function d_(e,t){return e.filter(e=>u_(e,t))}function f_(e,t){return e>0?``:t===`all`?`Waiting for activity`:t===`tasks`?`No task events yet`:`No system events yet`}function p_(e,t){return`${e}:${t??0}`}function m_(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=p_(e_(n).text,r),a=t[t.length-1];a&&a.key===i?(a.count+=1,a.events.push(n)):t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var h_={key:0,class:`font-normal text-fg-subtle`},g_={role:`region`,"aria-label":`Activity`,"aria-live":`polite`},__={class:`max-h-[28rem] oveLine truncated
`,1)[0]??``;return t.length>80?`${t.slice(0,79)}…`:t}var Fv=k({__name:`Collapsible`,props:{defaultOpen:{type:Boolean},open:{type:Boolean},disabled:{type:Boolean},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{}},emits:[`update:open`],setup(e,{emit:t}){let r=n(e,t);return(e,t)=>(R(),K(z(l),H({"data-slot":`collapsible`},z(r)),{default:j(t=>[P(e.$slots,`default`,mt(Be(t)))]),_:3},16))}}),Iv=k({__name:`CollapsibleContent`,props:{forceMount:{type:Boolean},asChild:{type:Boolean},as:{}},setup(e){let t=e;return(e,n)=>(R(),K(z(o),H({"data-slot":`collapsible-content`},t),{default:j(()=>[P(e.$slots,`default`)]),_:3},16))}}),Lv=k({__name:`CollapsibleTrigger`,props:{asChild:{type:Boolean},as:{}},setup(e){let t=e;return(e,n)=>(R(),K(z(g),H({"data-slot":`collapsible-trigger`},t),{default:j(()=>[P(e.$slots,`default`)]),_:3},16))}});function Rv(e){return(e?.merged||0)+(e?.completed||0)}function zv(e){return Object.entries(e?.inputs??{}).map(([e,t])=>({name:e,type:t.type,required:t.required===!0})).sort((e,t)=>e.name.localeCompare(t.name))}function Bv(e,t){return e.filter(e=>e.required&&!(t[e.name]??``).trim()).map(e=>e.name)}function Vv(e,t){switch(t){case`number`:{let t=e.trim();return t!==``&&!Number.isNaN(Number(t))?Number(t):e}case`bool`:return e===`true`||e!==`false`&&e;case`string`:return e;default:try{return JSON.parse(e)}catch{return e}}}function Hv(e,t){let n={};for(let r of e){let e=t[r.name];e!==void 0&&e!==``&&(n[r.name]=Vv(e,r.type))}return n}var Uv=[`onKeydown`],Wv={key:0,class:`text-sm text-danger`,role:`alert`},Gv={key:1,class:`grid gap-1.5`},Kv=[`for`],qv={key:0,class:`font-normal text-fg-subtle`},Jv=[`id`],Yv=[`value`],Xv={key:0,class:`text-xs text-fg-subtle`},Zv={key:2,class:`grid gap-1.5`},Qv=[`id`],$v={class:`block truncate font-mono text-[13px] font-medium`},ey={class:`block text-xs text-fg-subtle`},ty={key:0,class:`text-xs text-fg-subtle`},ny={key:3,class:`grid gap-3`},ry=[`for`],iy={class:`font-mono`},ay={key:0,class:`text-fg-subtle`},oy={class:`text-xs text-fg-subtle`},sy={class:`grid gap-1.5`},cy=[`for`],ly={class:`grid gap-1.5`},uy=[`for`],dy={class:`font-mono`},fy={key:4,class:`text-sm text-danger`,role:`alert`},py={class:`flex items-center gap-2 border-t border-border pt-4`},my={class:`mr-auto text-xs text-fg-subtle`},hy=k({__name:`NewTaskForm`,props:{workflow:{},draft:{},initialWorkflow:{},initialInstructions:{}},emits:[`started`,`cancel`],setup(e,{emit:t}){let n=e,r=t,i=Ge(),a=q([]),o=q([]),s=q([]),c=q(``);_t(async()=>{try{let[e,t]=await Promise.all([X.workflows(),X.tasks()]);a.value=(e?.definitions??[]).filter(e=>e.enabled),o.value=e?.workflows??[],s.value=[...new Set((t??[]).filter(e=>e.owner&&e.repo).map(e=>`${e.owner}/${e.repo}`))].slice(0,5)}catch(e){c.value=String(e.message||e)}});let l=Nv();l.watchIdentities();let u=I(()=>l.identities.filter(e=>e.kind!==`system`&&e.lifecycle===`active`)),d=q(``),f=q(n.workflow??n.initialWorkflow??``),p=q(n.initialInstructions??``),m=q(Pv(p.value)),h=q(``),g=q({});nt(()=>{!f.value&&a.value[0]&&(f.value=a.value[0].id),!h.value&&u.value[0]&&(h.value=u.value[0].id)});let _=I(()=>a.value.find(e=>e.id===f.value)),v=I(()=>zv(_.value)),y=I(()=>Bv(v.value,g.value)),b=I(()=>_.value?.repository??`required`),x=I(()=>b.value!==`optional`&&b.value!==`none`),S=e=>o.value.find(t=>t.workflow===e),C=I(()=>u.value.find(e=>e.id===h.value)?.display_name??`nobody`),w=q(!1),T=q(``),ee=I(()=>!!((d.value.trim()||!x.value)&&f.value&&m.value.trim()&&p.value.trim()&&h.value)&&y.value.length===0);async function E(){if(ee.value&&!w.value){w.value=!0,T.value=``;try{let e=await X.workRequest({identity:h.value,repository:b.value===`none`?``:d.value.trim(),workflow:f.value,title:m.value.trim(),instructions:p.value,inputs:Hv(v.value,g.value),...n.draft?{draft:n.draft}:{}});r(`started`,e.task_id)}catch(e){T.value=String(e.message||e)}finally{w.value=!1}}}return(e,t)=>(R(),W(`form`,{class:`grid gap-5`,onSubmit:Nt(E,[`prevent`]),onKeydown:[jt(Nt(E,[`meta`,`prevent`]),[`enter`]),jt(Nt(E,[`ctrl`,`prevent`]),[`enter`])]},[c.value?(R(),W(`p`,Wv,B(c.value),1)):L(``,!0),b.value===`none`?L(``,!0):(R(),W(`div`,Gv,[U(`label`,{for:`${z(i)}-repo`,class:`text-[13px] font-medium`},[t[6]||=A(`Repository`,-1),x.value?L(``,!0):(R(),W(`span`,qv,` (optional)`))],8,Kv),M(z(Z),{id:`${z(i)}-repo`,modelValue:d.value,"onUpdate:modelValue":t[0]||=e=>d.value=e,class:`font-mono`,placeholder:`owner/repository`,list:`${z(i)}-repos`,required:x.value},null,8,[`id`,`modelValue`,`list`,`required`]),U(`datalist`,{id:`${z(i)}-repos`},[(R(!0),W(V,null,G(s.value,e=>(R(),W(`option`,{key:e,value:e},null,8,Yv))),128))],8,Jv),s.value.length?(R(),W(`p`,Xv,[t[7]||=A(`Recent: `,-1),(R(!0),W(V,null,G(s.value,e=>(R(),K(z(Y),{key:e,type:`button`,variant:`link`,size:`xs`,class:`h-auto px-1 font-mono text-fg-subtle`,onClick:t=>d.value=e},{default:j(()=>[A(B(e),1)]),_:2},1032,[`onClick`]))),128))])):L(``,!0)])),n.workflow?L(``,!0):(R(),W(`div`,Zv,[U(`span`,{id:`${z(i)}-wf`,class:`text-[13px] font-medium`},`Workflow`,8,Qv),M(z( Line truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function Ny(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function Py(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function Fy(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function Iy(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var Ly=q([]),Ry=q([]),zy=q(!0),By=q(null),Vy=q(null),Hy=q(!1),Uy=q(null);async function Wy(){try{let e=await X.eventTypes(jy().workspace);zy.value=e.enabled!==!1,Ly.value=e.event_types||[],Ry.value=e.proposals||[],By.value=null}catch(e){By.value=e.message||String(e)}}function Gy(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function Ky(e){Uy.value=null,Vy.value=e}function qy(e){let t=tb.value.find(t=>String(t.id)===e.sample_id);Ky({mode:`proposal`,id:null,source:e.source,name:``,rule:Gy(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function Jy(e=``){Ky({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function Yy(e){Ky({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:Gy(e.rule),headersText:``,body:``,exampleHeaders:{}})}function Xy(){Vy.value=null}async function Zy(){let e=Vy.value;if(e){Hy.value=!0;try{if(e.mode===`edit`&&e.id)await X.eventTypeUpdate(e.id,{name:e.name,rule:Iy(e.rule)});else{let t=e.mode===`paste`?My(e.headersText):e.exampleHeaders;await X.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:Iy(e.rule),example:{headers:t,body:e.body}})}Vy.value=null,await Wy()}catch(e){Uy.value=e.message||String(e)}finally{Hy.value=!1}}}var Qy=q(null);async function $y(){let e=Qy.value;if(Qy.value=null,e)try{await X.eventTypeDelete(e.id),await Wy()}catch(e){By.value=e.message||String(e)}}var eb=100,tb=q([]),nb=q(!0),rb=q(null),ib=q(!0),ab=q(null);async function ob(){try{let e=await X.captures(eb);nb.value=e.enabled!==!1,tb.value=e.captures||[],rb.value=null}catch(e){rb.value=e.message||String(e)}finally{ib.value=!1}}function sb(e){let t=tb.value.find(t=>t.id===e);return t&&(ab.value=t),!!t}function cb(){tb.value.length&&(ab.value=tb.value[0])}function lb(){Pe(`captures`,()=>{ob(),Wy()})}var ub=k({__name:`Tabs`,props:{defaultValue:{},orientation:{},dir:{},activationMode:{},modelValue:{},unmountOnHide:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},emits:[`update:modelValue`],setup(e,{emit:t}){let r=e,i=t,a=Rt(r,`class`),o=n(a,i);return(e,t)=>(R(),K(z(yo),H({"data-slot":`tabs`,"data-orientation":z(o).orientation||`horizontal`},z(o),{class:z(J)(`gap-2 group/tabs flex data-horizontal:flex-col`,r.class)}),{default:j(t=>[P(e.$slots,`default`,mt(Be(t)))]),_:3},16,[`data-orientation`,`class`]))}}),db=k({__name:`TabsContent`,props:{value:{},forceMount:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=Rt(t,`class`);return(e,r)=>(R(),K(z(So),H({"data-slot":`tabs-content`,class:z(J)(`text-sm flex-1 outline-none`,t.class)},z(n)),{default:j(()=>[P(e.$slots,`default`)]),_:3},16,[`class`]))}}),fb=k({__name:`TabsList`,props:{loop:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]},variant:{default:`default`}},setup(e){let t=e,n=Rt(t,`class`,`variant`);return(r,i)=>(R(),K(z(Co),H({"data-slot":`tabs-list`,"data-variant":e.variant},z(n),{class:z(J)(z(mb)({variant:e.variant}),t.class)}),{default:j(()=>[P(r.$slots,`default`)]),_:3},16,[`data-variant`,`class`]))}}),pb=k({__name:`TabsTrigger`,props:{value:{},disabled:{type:Boolean},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=Rt(t,`class`),r=S(n);return(e,n)=>(R(),K(z(wo),H({"data-slot":`tabs-trigger`,class:z(J)(`gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg:not([class*=size-])]:size-4 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-Line truncated
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var mM=eM(`CharSizeService`),hM=eM(`CoreBrowserService`),gM=eM(`MouseService`),_M=eM(`RenderService`),vM=eM(`SelectionService`),yM=eM(`CharacterJoinerService`),bM=eM(`ThemeService`),xM=eM(`LinkProviderService`),SM=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?OM.isErrorNoTelemetry(e)?new OM(e.message+`
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var BM=EM(`CharSizeService`),VM=EM(`CoreBrowserService`),HM=EM(`MouseService`),UM=EM(`RenderService`),WM=EM(`SelectionService`),GM=EM(`CharacterJoinerService`),KM=EM(`ThemeService`),qM=EM(`LinkProviderService`),JM=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?eN.isErrorNoTelemetry(e)?new eN(e.message+`
`+e.stack):Error(e.message+`
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function CM(e){TM(e)||SM.onUnexpectedError(e)}var wM=`Canceled`;function TM(e){return e instanceof EM||e instanceof Error&&e.name===wM&&e.message===wM}var EM=class extends Error{constructor(){super(wM),this.name=this.message}};function DM(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var OM=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},kM=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function AM(e,t=0){return e[e.length-(1+t)]}var jM;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(jM||={});var MM=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||jM.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};MM.empty=new MM(e=>{});function NM(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var PM;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(PM||={});var FM=null;function IM(e){return FM?.trackDisposable(e),e}function LM(e){FM?.markAsDisposed(e)}function RM(e,t){FM?.setParent(e,t)}function zM(e){return FM?.markAsSingleton(e),e}function BM(e){if(PM.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function VM(...e){return HM(()=>BM(e))}function HM(e){let t=IM({dispose:NM(()=>{LM(t),e()})});return t}var UM=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,IM(this)}dispose(){this._isDisposed||(LM(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{BM(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return RM(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),RM(e,null))}};UM.DISABLE_DISPOSED_WARNING=!1;var WM=UM,GM=class{constructor(){this._store=new WM,IM(this),RM(this._store,this)}dispose(){LM(thi Line truncated
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function YM(e){ZM(e)||JM.onUnexpectedError(e)}var XM=`Canceled`;function ZM(e){return e instanceof QM||e instanceof Error&&e.name===XM&&e.message===XM}var QM=class extends Error{constructor(){super(XM),this.name=this.message}};function $M(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var eN=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},tN=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function nN(e,t=0){return e[e.length-(1+t)]}var rN;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(rN||={});var iN=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||rN.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};iN.empty=new iN(e=>{});function aN(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var oN;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(oN||={});var sN=null;function cN(e){return sN?.trackDisposable(e),e}function lN(e){sN?.markAsDisposed(e)}function uN(e,t){sN?.setParent(e,t)}function dN(e){return sN?.markAsSingleton(e),e}function fN(e){if(oN.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function pN(...e){return mN(()=>fN(e))}function mN(e){let t=cN({dispose:aN(()=>{lN(t),e()})});return t}var hN=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,cN(this)}dispose(){this._isDisposed||(lN(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{fN(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return uN(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),uN(e,null))}};hN.DISABLE_DISPOSED_WARNING=!1;var gN=hN,_N=class{constructor(){this._store=new gN,cN(this),uN(this._store,this)}dispose(){lN(thi Line truncated
`).slice(2).join(`
`))}},oN=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},sN=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},cN=0,lN=class{constructor(e){this.value=e,this.id=cN++}},uN=2,Q=class{constructor(e){this._size=0,this._options=e,this._leakageMon=nN>0||this._options?.leakWarningThreshold?new iN(e?.onListenerError??CM,this._options?.leakWarningThreshold??nN):void 0,this._perfMon=this._options?._profName?new tN(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new sN(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||CM)(n),GM.None}if(this._disposed)return GM.None;t&&(e=e.bind(t));let r=new lN(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=aN.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof lN?(this._deliveryQueue??=new dN,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=HM(()=>{i?.(),this._removeListener(r)});return n instanceof WM?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*uN<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||CM;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof lN)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},dN=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},fN=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Q,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Q,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};fN.INSTANCE=new fN;var pN=fN;function mN(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}pN.INSTANCE.onDidChangeZoomLevel;function hN(e){return pN.INSTANCE.getZoomFactor(e)}pN.INSTANCE.onDidChangeFullscreen;var gN=typeof navigator==`object`?navigator.userAgent:``,_N=gN.indexOf(`Firefox`)>=0,vN=gN.indexOf(`AppleWebKit`)>=0,yN=gN.indexOf(`Chrome`)>=0,bN=!yN&&gN.indexOf(`Safari`)>=0;gN.indexOf(`Electron/`),gN.indexOf(`Android`);var xN=!1;if(typeof qM.matchMedia==`function`){let e=qM.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=qM.matchMedia(`(display-mode: fullscreen)`);xN=e.matches,mN(qM,e,({matches:e})=>{xN&&t.matches||(xN=e)})}f Line truncated
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};_F=Oj([kj(2,nM),kj(3,hM),kj(4,rM),kj(5,bM),kj(6,cM),kj(7,_M)],_F);var vF=class extends GM{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(HM(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderLine truncated
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var wF;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(wF||={});var TF;(e=>e.ST=`${$.ESC}\\`)(TF||={});var EF=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};EF=Oj([kj(2,nM),kj(3,cM),kj(4,iM),kj(5,_M)],EF);var DF=0,OF=0,kF=0,AF=0,jF={css:`#00000000`,rgba:0},MF;(e=>{function t(e,t,n,r){return r===void 0?`#${LF(e)}${LF(t)}${LF(n)}`:`#${LF(e)}${LF(t)}${LF(n)}${LF(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(MF||={});var NF;(e=>{function t(e,t){if(AF=(t.rgba&255)/255,AF===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return DF=a+Math.round((n-a)*AF),OF=o+Math.round((r-o)*AF),kF=s+Math.round((i-s)*AF),{css:MF.toCss(DF,OF,kF),rgba:MF.toRgba(DF,OF,kF)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=IF.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return MF.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[DF,OF,kF]=IF.toChannels(t),{css:MF.toCss(DF,OF,kF),rgba:t}}e.opaque=i;function a(e,t){return AF=Math.round(t*255),[DF,OF,kF]=IF.toChannels(e.rgba),{css:MF.toCss(DF,OF,kF,AF),rgba:MF.toRgba(DF,OF,kF,AF)}}e.opacity=a;function o(e,t){return AF=e.rgba&255,a(e,AF*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.r Line truncated
`))}},MN=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},NN=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},PN=0,FN=class{constructor(e){this.value=e,this.id=PN++}},IN=2,LN=class{constructor(e){this._size=0,this._options=e,this._leakageMon=ON>0||this._options?.leakWarningThreshold?new AN(e?.onListenerError??YM,this._options?.leakWarningThreshold??ON):void 0,this._perfMon=this._options?._profName?new DN(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new NN(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||YM)(n),_N.None}if(this._disposed)return _N.None;t&&(e=e.bind(t));let r=new FN(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=jN.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof FN?(this._deliveryQueue??=new RN,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=mN(()=>{i?.(),this._removeListener(r)});return n instanceof gN?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*IN<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||YM;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof FN)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},RN=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},zN=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new LN,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new LN,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};zN.INSTANCE=new zN;var BN=zN;function VN(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}BN.INSTANCE.onDidChangeZoomLevel;function HN(e){return BN.INSTANCE.getZoomFactor(e)}BN.INSTANCE.onDidChangeFullscreen;var UN=typeof navigator==`object`?navigator.userAgent:``,WN=UN.indexOf(`Firefox`)>=0,GN=UN.indexOf(`AppleWebKit`)>=0,KN=UN.indexOf(`Chrome`)>=0,qN=!KN&&UN.indexOf(`Safari`)>=0;UN.indexOf(`Electron/`),UN.indexOf(`Android`);var JN=!1;if(typeof yN.matchMedia==`function`){let e=yN.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=yN.matchMedia(`(display-mode: fullscreen)`);JN=e.matches,VN(yN,e,({matches:e})=>{JN&&t.matches||(JN=e)} Line truncated
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};WF=eM([tM(2,OM),tM(3,VM),tM(4,kM),tM(5,KM),tM(6,PM),tM(7,UM)],WF);var GF=class extends _N{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(mN(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderLine truncated
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var ZF;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(ZF||={});var QF;(e=>e.ST=`${$.ESC}\\`)(QF||={});var $F=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};$F=eM([tM(2,OM),tM(3,PM),tM(4,AM),tM(5,UM)],$F);var eI=0,tI=0,nI=0,rI=0,iI={css:`#00000000`,rgba:0},aI;(e=>{function t(e,t,n,r){return r===void 0?`#${uI(e)}${uI(t)}${uI(n)}`:`#${uI(e)}${uI(t)}${uI(n)}${uI(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(aI||={});var oI;(e=>{function t(e,t){if(rI=(t.rgba&255)/255,rI===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return eI=a+Math.round((n-a)*rI),tI=o+Math.round((r-o)*rI),nI=s+Math.round((i-s)*rI),{css:aI.toCss(eI,tI,nI),rgba:aI.toRgba(eI,tI,nI)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=lI.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return aI.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[eI,tI,nI]=lI.toChannels(t),{css:aI.toCss(eI,tI,nI),rgba:t}}e.opaque=i;function a(e,t){return rI=Math.round(t*255),[eI,tI,nI]=lI.toChannels(e.rgba),{css:aI.toCss(eI,tI,nI,rI),rgba:aI.toRgba(eI,tI,nI,rI)}}e.opacity=a;function o(e,t){return rI=e.rgba&255,a(e,rI*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.r Line truncated
`:`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),OI&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=ZI(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=fI(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-QI),QI),t/=QI,t/Math.abs(t)+Math.round(t*($I-1)))}shouldForceSelection(e){return wI?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),eL)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(wI&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._active Line truncated
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(DP(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(HM(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<ez+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===ez+1&&(this._liveRegion.textContent+=Nj.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let Line truncated
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return jj.get()},set promptLabel(e){jj.set(e)},get tooMuchOutput(){return Nj.get()},set tooMuchOutput(e){Nj.set(e)}}}_verifyIntegers(...e){for(pz of e)if(pz===1/0||isNaN(pz)||pz%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(pz of e)if(pz&&(pz===1/0||isNaN(pz)||pz%1!=0||pz<0))throw Error(`This API only accepts positive integers`)}},hz=2,gz=1,_z=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(hz,Math.floor(u/e.css.cell.width)),rows:Math.max(gz,Math.floor(l/e.css.cell.height))}}},vz={class:`flex h-[32rem] min-h-0 flex-col gap-2`},yz={key:0,class:`text-sm text-muted-foreground`,role:`status`},bz=k({__name:`SandboxView`,props:{taskId:{},attempt:{}},setup(e){let t=e,n=q(null),r=q(`connecting`),i=null,a=null,o=null,s=null;function c(){try{o?.fit()}catch{}}return xt(()=>{let e=n.value;if(!e)return;i=new mz({convertEol:!0,disableStdin:!0,cursorBlink:!1,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`}}),o=new _z,i.loadAddon(o),i.open(e),c();let l=window.location.protocol===`https:`?`wss:`:`ws:`,u=new URLSearchParams({attempt:String(t.attempt)}),d=new WebSocket(`${l}//${window.location.host}/api/tasks/${encodeURIComponent(t.taskId)}/sandbox?${u}`);a=d,d.binaryType=`arraybuffer`,d.onopen=()=>{r.value=`open`},d.onmessage=e=>{i&&(typeof e.data==`string`&&(r.value=`failed`),i.write(typeof e.data==`string`?e.data:new Uint8Array(e.data)))},d.onerror=()=>{r.value=`failed`},d.onclose=()=>{r.value!==`failed`&&(r.value=`closed`)},s=new ResizeObserver(c),s.observe(e)}),mt(()=>{s?.disconnect(),s=null,a?.close(),a=null,i?.dispose(),i=null,o=null}),(e,t)=>(R(),W(`div`,vz,[r.value===`open`?L(``,!0):(R(),W(`p`,yz,[r.value===`connecting`?(R(),W(V,{key:0},[A(`Connecting…`)],64)):r.value===`closed`?(R(),W(V,{key:1},[A(`The sandbox view ended.`)],64)):(R(),W(V,{key:2},[A(`The sandbox view is unavailable.`)],64))])),U(`div`,{ref_key:`host`,ref:n,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),xz={class:`flex flex-wrap items-center gap-3 border-b border-border pb-3`},Sz={class:`inline-flex items-center gap-2`},Cz={class:`inline-flex items-center gap-2`},wz=`__all__`,Tz=k({__name:`TaskLogFilters`,props:{filters:{},stages:{}},emits:[`filter`],setup(e,{emit:t}){let n=e,r=t,i=I(()=>FC.map(e=>({value:e.value||wz,label:e.label}))),a=I(()=>n.filters.level||wz),o=I(()=>n.filters.stage||wz);function s(e){r(`filter`,{...n.filters,...e})}function c(e){s({level:String(e)===wz?``:String(e)})}function l(e){s({stage:String(e)===wz?``:String(e)})}return(t,n)=>(R(),W(`div`,xz,[U(`div`,Sz,[M(z(rl),{"model-value":a.value,"aria-label":`Filter log entries by level`,"onUpdate:modelValue":c},{default:j(()=>[M(z(ul),{size:`sm`},{default:j(()=>[M(z(dl))]),_:1}),M(z(il),null,{default:j(()=>[M(z(al),null,{default:j(()=>[(R(!0),W(V,null,G(i.value,e=>(R(),K(z(sl),{key:e.value,value:e.value},{default:j(()=>[A(B(e.label),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])]),U(`div`,Cz,[M(z(rl),{"model-value":o.value,"aria-label":`Filter log entries by stage`,"onUpdate:modelValue":l},{default:j(()=>[M(z(ul),{size:`sm`},{default:j(()=>[M(z(dl))]),_:1}),M(z(il),null,{default:j(()=>[M(z(al),null,{default:j(()=>[M(z(sl),{value:wz},{default:j(()=>[...n[0]||=[A(`All stages`,-1)]]),_:1}),(R(!0),W(V,null,G(e.stages,e=>(R(),K(z(sl),{key:e,value:e},{default:j(()=>[A(B(e),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])])]))}}),Ez={class:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`},Dz={key:2,class:`flex flex-col items-start gap-2 py-3`},Oz={key:0,class:`mt-2 Line truncated
`)}};GW.defaultYaml={explicit:!1,version:`1.2`},GW.defaultTags={"!!":`tag:yaml.org,2002:`};function KW(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function qW(e){let t=new Set;return RW(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function JW(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function YW(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=qW(e);let a=JW(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(AW(t.node)||MW(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function XW(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=XW(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=XW(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=XW(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=XW(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function ZW(e,t,n){if(Array.isArray(e))return e.map((e,t)=>ZW(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!PW(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var QW=class{constructor(e){Object.defineProperty(this,TW,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!DW(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=ZW(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?XW(i,{"":o},``,o):o}},$W=class extends QW{constructor(e){super(yW),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],RW(e,{Node:(e,t)=>{(EW(t)||PW(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(ZW(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=eG(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(KW(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function eG(e,t,n){if(EW(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(MW(t)){let r=0;for(let i of t.items){let t=eG(e,i,n);t>r&&(r=t)}return r}if(kW(t)){let r=eG(e,t.key,n),i=eG(e,t.value,n);return Math.max(r,i)}return 1}var tG=e=>!e||typeof e!=`function`&&typeof e!=`object`,nG=class extends QW{constructor(e){super(CW),this.value=e}toJSON(e,t){return t?.keep?this.value:ZW(this.value,e,t)}toString(){return String(this.value)}};nG.BLOCK_FOLDED=`BLOCK_FOLDED`,nG.BLOCK_LITERAL=`BLOCK_LITERAL`,nG.PLAIN=`PLAIN`,nG.QUOTE_DOUBLE=`QUOTE_DOUBLE`,nG.QUOTE_SINGLE=`QUOTE_SINGLE`;var rG=`tag:yaml.org,2002:`;function iG(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function aG(e,t,n){if(DW(e)&&(e=e.contents),NW(e))return e;if(kW(e)){let t=n.schema[xW].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new $W(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=rG+t.slice(2));let l=iG(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new nG(e);return c&&(c.node=t),t Line truncated
`)?uG(n,t):n.includes(`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),tL&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=wL(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=zI(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-TL),TL),t/=TL,t/Math.abs(t)+Math.round(t*(EL-1)))}shouldForceSelection(e){return ZI?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),DL)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(ZI&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._active Line truncated
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(eF(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(mN(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Dz+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Dz+1&&(this._liveRegion.textContent+=aM.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let Line truncated
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return rM.get()},set promptLabel(e){rM.set(e)},get tooMuchOutput(){return aM.get()},set tooMuchOutput(e){aM.set(e)}}}_verifyIntegers(...e){for(Bz of e)if(Bz===1/0||isNaN(Bz)||Bz%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(Bz of e)if(Bz&&(Bz===1/0||isNaN(Bz)||Bz%1!=0||Bz<0))throw Error(`This API only accepts positive integers`)}},Hz=2,Uz=1,Wz=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(Hz,Math.floor(u/e.css.cell.width)),rows:Math.max(Uz,Math.floor(l/e.css.cell.height))}}},Gz={class:`flex h-[32rem] min-h-0 flex-col gap-2`},Kz={key:0,class:`text-sm text-muted-foreground`,role:`status`},qz=k({__name:`SandboxView`,props:{taskId:{},attempt:{}},setup(e){let t=e,n=q(null),r=q(`connecting`),i=null,a=null,o=null,s=null;function c(){try{o?.fit()}catch{}}return _t(()=>{let e=n.value;if(!e)return;i=new Vz({convertEol:!0,disableStdin:!0,cursorBlink:!1,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`}}),o=new Wz,i.loadAddon(o),i.open(e),c();let l=window.location.protocol===`https:`?`wss:`:`ws:`,u=new URLSearchParams({attempt:String(t.attempt)}),d=new WebSocket(`${l}//${window.location.host}/api/tasks/${encodeURIComponent(t.taskId)}/sandbox?${u}`);a=d,d.binaryType=`arraybuffer`,d.onopen=()=>{r.value=`open`},d.onmessage=e=>{i&&(typeof e.data==`string`&&(r.value=`failed`),i.write(typeof e.data==`string`?e.data:new Uint8Array(e.data)))},d.onerror=()=>{r.value=`failed`},d.onclose=()=>{r.value!==`failed`&&(r.value=`closed`)},s=new ResizeObserver(c),s.observe(e)}),ut(()=>{s?.disconnect(),s=null,a?.close(),a=null,i?.dispose(),i=null,o=null}),(e,t)=>(R(),W(`div`,Gz,[r.value===`open`?L(``,!0):(R(),W(`p`,Kz,[r.value===`connecting`?(R(),W(V,{key:0},[A(`Connecting…`)],64)):r.value===`closed`?(R(),W(V,{key:1},[A(`The sandbox view ended.`)],64)):(R(),W(V,{key:2},[A(`The sandbox view is unavailable.`)],64))])),U(`div`,{ref_key:`host`,ref:n,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),Jz={class:`flex flex-wrap items-center gap-3 border-b border-border pb-3`},Yz={class:`inline-flex items-center gap-2`},Xz={class:`inline-flex items-center gap-2`},Zz=`__all__`,Qz=k({__name:`TaskLogFilters`,props:{filters:{},stages:{}},emits:[`filter`],setup(e,{emit:t}){let n=e,r=t,i=I(()=>ow.map(e=>({value:e.value||Zz,label:e.label}))),a=I(()=>n.filters.level||Zz),o=I(()=>n.filters.stage||Zz);function s(e){r(`filter`,{...n.filters,...e})}function c(e){s({level:String(e)===Zz?``:String(e)})}function l(e){s({stage:String(e)===Zz?``:String(e)})}return(t,n)=>(R(),W(`div`,Jz,[U(`div`,Yz,[M(z(Cl),{"model-value":a.value,"aria-label":`Filter log entries by level`,"onUpdate:modelValue":c},{default:j(()=>[M(z(Al),{size:`sm`},{default:j(()=>[M(z(jl))]),_:1}),M(z(wl),null,{default:j(()=>[M(z(Tl),null,{default:j(()=>[(R(!0),W(V,null,G(i.value,e=>(R(),K(z(Dl),{key:e.value,value:e.value},{default:j(()=>[A(B(e.label),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])]),U(`div`,Xz,[M(z(Cl),{"model-value":o.value,"aria-label":`Filter log entries by stage`,"onUpdate:modelValue":l},{default:j(()=>[M(z(Al),{size:`sm`},{default:j(()=>[M(z(jl))]),_:1}),M(z(wl),null,{default:j(()=>[M(z(Tl),null,{default:j(()=>[M(z(Dl),{value:Zz},{default:j(()=>[...n[0]||=[A(`All stages`,-1)]]),_:1}),(R(!0),W(V,null,G(e.stages,e=>(R(),K(z(Dl),{key:e,value:e},{default:j(()=>[A(B(e),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`model-value`])])]))}}),$z={class:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`},eB={key:2,class:`flex flex-col items-start gap-2 py-3`},tB={key:0,class:`mt-2 Line truncated
`)}};vG.defaultYaml={explicit:!1,version:`1.2`},vG.defaultTags={"!!":`tag:yaml.org,2002:`};function yG(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function bG(e){let t=new Set;return dG(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function xG(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function SG(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=bG(e);let a=xG(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(rG(t.node)||aG(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function CG(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=CG(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=CG(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=CG(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=CG(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function wG(e,t,n){if(Array.isArray(e))return e.map((e,t)=>wG(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!sG(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var TG=class{constructor(e){Object.defineProperty(this,QW,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!eG(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=wG(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?CG(i,{"":o},``,o):o}},EG=class extends TG{constructor(e){super(KW),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],dG(e,{Node:(e,t)=>{($W(t)||sG(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(wG(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=DG(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(yG(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function DG(e,t,n){if($W(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(aG(t)){let r=0;for(let i of t.items){let t=DG(e,i,n);t>r&&(r=t)}return r}if(nG(t)){let r=DG(e,t.key,n),i=DG(e,t.value,n);return Math.max(r,i)}return 1}var OG=e=>!e||typeof e!=`function`&&typeof e!=`object`,kG=class extends TG{constructor(e){super(XW),this.value=e}toJSON(e,t){return t?.keep?this.value:wG(this.value,e,t)}toString(){return String(this.value)}};kG.BLOCK_FOLDED=`BLOCK_FOLDED`,kG.BLOCK_LITERAL=`BLOCK_LITERAL`,kG.PLAIN=`PLAIN`,kG.QUOTE_DOUBLE=`QUOTE_DOUBLE`,kG.QUOTE_SINGLE=`QUOTE_SINGLE`;var AG=`tag:yaml.org,2002:`;function jG(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function MG(e,t,n){if(eG(e)&&(e=e.contents),oG(e))return e;if(nG(e)){let t=n.schema[JW].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new EG(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=AG+t.slice(2));let l=jG(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new kG(e);return c&&(c.node=t),t Line truncated
`)?LG(n,t):n.includes(`
`)?`
`+uG(n,t):(e.endsWith(` `)?``:` `)+n,fG=`flow`,pG=`block`,mG=`quoted`;function hG(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=gG(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
`)n===`block`&&(h=gG(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
`+LG(n,t):(e.endsWith(` `)?``:` `)+n,zG=`flow`,BG=`block`,VG=`quoted`;function HG(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=UG(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
`)n===`block`&&(h=UG(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
`&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
`&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function gG(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
`);r=t,i=t+1,a=e[i]}return r}var _G=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),vG=e=>/^(%|---|\.\.\.)/m.test(e);function yG(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function bG(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(vG(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
`&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function UG(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
`);r=t,i=t+1,a=e[i]}return r}var WG=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),GG=e=>/^(%|---|\.\.\.)/m.test(e);function KG(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function qG(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(GG(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
`;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
`,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:hG(o,a,mG,_G(t,!1))}function xG(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
`)||/[ \t]\n|\n[ \t]/.test(e))return bG(e,t);let n=t.indent||(vG(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:hG(r,n,fG,_G(t,!1))}function SG(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=bG;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?xG:i&&!t?bG:n?xG:bG}return r(e,t)}var CG;try{CG=RegExp(`(^|(?<!
`,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:HG(o,a,VG,WG(t,!1))}function JG(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
`)||/[ \t]\n|\n[ \t]/.test(e))return qG(e,t);let n=t.indent||(GG(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:HG(r,n,zG,WG(t,!1))}function YG(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=qG;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?JG:i&&!t?qG:n?JG:qG}return r(e,t)}var XG;try{XG=RegExp(`(^|(?<!
))
+(?!
|$)`,`g`)}catch{CG=/\n+(?!\n|$)/g}function wG({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return SG(n,r);let l=r.indent||(r.forceBlockIndent||vG(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===nG.BLOCK_FOLDED?!1:t===nG.BLOCK_LITERAL||!yG(n,c,l.length);if(!n)return u?`|
|$)`,`g`)}catch{XG=/\n+(?!\n|$)/g}function ZG({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return YG(n,r);let l=r.indent||(r.forceBlockIndent||GG(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===kG.BLOCK_FOLDED?!1:t===kG.BLOCK_LITERAL||!KG(n,c,l.length);if(!n)return u?`|
`:`>
`;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
`&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
`);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
`&&(p=p.slice(0,-1)),p.replace(CG,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
`&&(p=p.slice(0,-1)),p.replace(XG,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
`)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let y=(h?l?`2`:`1`:``)+d;if(e&&(y+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=_G(r,!0);o!==`folded`&&t!==nG.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=hG(`${v}${e}${p}`,l,pG,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function TG(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
`)||u&&/[[\]{},]/.test(a))return SG(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
`)?SG(a,t):wG(e,t,n,r);if(!s&&!u&&i!==nG.PLAIN&&a.includes(`
`))return wG(e,t,n,r);if(vG(a)){if(c===``)return t.forceBlockIndent=!0,wG(e,t,n,r);if(s&&c===l)return SG(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return SG(a,t)}return s?d:hG(d,c,fG,_G(t,!1))}function EG(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==nG.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=nG.QUOTE_DOUBLE);let c=e=>{switch(e){case nG.BLOCK_FOLDED:case nG.BLOCK_LITERAL:return i||a?SG(o.value,t):wG(o,t,n,r);case nG.QUOTE_DOUBLE:return bG(o.value,t);case nG.QUOTE_SINGLE:return xG(o.value,t);case nG.PLAIN:return TG(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function DG(e,t){let n=Object.assign({blockQuote:!0,commentString:lG,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function OG(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(AW(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function kG(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(AW(e)||MW(e))&&e.anchor;a&&KW(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function AG(e,t,n,r){if(kW(e))return e.toString(t,n,r);if(EW(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=NW(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=OG(t.doc.schema.tags,a);let o=kG(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):AW(a)?EG(a,t,n,r):a.toString(t,n,r);return o?AW(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function jG({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=NW(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(MW(e)||!NW(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||MW(e)||(AW(e)?e.type===nG.BLOCK_FOLDED||e.type===nG.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=AG(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=dG(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=dG(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=dG(g,n.indent,l(f))));let _,v,y;NW(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&AW(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&jW(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=AG(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
`:``,v){let e=l(v);S+=`\n${uG(e,n.indent)}`}x===``&&!n.inFlow?S===`
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=WG(r,!0);o!==`folded`&&t!==kG.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=HG(`${v}${e}${p}`,l,BG,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function QG(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
`)||u&&/[[\]{},]/.test(a))return YG(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
`)?YG(a,t):ZG(e,t,n,r);if(!s&&!u&&i!==kG.PLAIN&&a.includes(`
`))return ZG(e,t,n,r);if(GG(a)){if(c===``)return t.forceBlockIndent=!0,ZG(e,t,n,r);if(s&&c===l)return YG(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return YG(a,t)}return s?d:HG(d,c,zG,WG(t,!1))}function $G(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==kG.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=kG.QUOTE_DOUBLE);let c=e=>{switch(e){case kG.BLOCK_FOLDED:case kG.BLOCK_LITERAL:return i||a?YG(o.value,t):ZG(o,t,n,r);case kG.QUOTE_DOUBLE:return qG(o.value,t);case kG.QUOTE_SINGLE:return JG(o.value,t);case kG.PLAIN:return QG(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function eK(e,t){let n=Object.assign({blockQuote:!0,commentString:IG,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function tK(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(rG(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function nK(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(rG(e)||aG(e))&&e.anchor;a&&yG(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function rK(e,t,n,r){if(nG(e))return e.toString(t,n,r);if($W(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=oG(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=tK(t.doc.schema.tags,a);let o=nK(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):rG(a)?$G(a,t,n,r):a.toString(t,n,r);return o?rG(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function iK({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=oG(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(aG(e)||!oG(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||aG(e)||(rG(e)?e.type===kG.BLOCK_FOLDED||e.type===kG.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=rK(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=RG(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=RG(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=RG(g,n.indent,l(f))));let _,v,y;oG(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&rG(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&iG(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=rK(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
`:``,v){let e=l(v);S+=`\n${LG(e,n.indent)}`}x===``&&!n.inFlow?S===`
`&&y&&(S=`
`):S+=`\n${n.indent}`}else if(!p&&MW(t)){let e=x[0],r=x.indexOf(`
`):S+=`\n${n.indent}`}else if(!p&&aG(t)){let e=x[0],r=x.indexOf(`
`),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=x.indexOf(` `);e===`&`&&n!==-1&&n<r&&x[n+1]===`!`&&(n=x.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(S=`\n${n.indent}`)}}else(x===``||x[0]===`
`)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=dG(g,n.indent,l(y)):h&&i&&i(),g}function MG(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var NG=`<<`,PG={identify:e=>e===NG||typeof e==`symbol`&&e.description===NG,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new nG(Symbol(NG)),{addToJSMap:IG}),stringify:()=>NG},FG=(e,t)=>(PG.identify(t)||AW(t)&&(!t.type||t.type===nG.PLAIN)&&PG.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===PG.tag&&e.default);function IG(e,t,n){let r=RG(e,n);if(jW(r))for(let n of r.items)LG(e,t,n);else if(Array.isArray(r))for(let n of r)LG(e,t,n);else LG(e,t,r)}function LG(e,t,n){let r=RG(e,n);if(!OW(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function RG(e,t){return e&&EW(t)?t.resolve(e.doc,e):t}function zG(e,t,{key:n,value:r}){if(NW(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(FG(e,n))IG(e,t,r);else{let i=ZW(n,``,e);if(t instanceof Map)t.set(i,ZW(r,i,e));else if(t instanceof Set)t.add(i);else{let a=BG(n,i,e),o=ZW(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function BG(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(NW(e)&&n?.doc){let t=DG(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),MG(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function VG(e,t,n){return new HG(aG(e,void 0,n),aG(t,void 0,n))}var HG=class e{constructor(e,t=null){Object.defineProperty(this,TW,{value:SW}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return NW(n)&&(n=n.clone(t)),NW(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return zG(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?jG(this,e,t,n):JSON.stringify(this)}};function UG(e,t,n){return(t.inFlow??e.flow?GG:WG)(e,t,n)}function WG({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(NW(i))!d&&i.spaceBefore&&f.push(``),KG(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(kW(i)){let e=NW(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),KG(n,f,e.commentBefore,d))}d=!1;let s=AG(i,u,()=>o=null,()=>d=!0);o&&(s+=dG(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
`)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=RG(g,n.indent,l(y)):h&&i&&i(),g}function aK(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var oK=`<<`,sK={identify:e=>e===oK||typeof e==`symbol`&&e.description===oK,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new kG(Symbol(oK)),{addToJSMap:lK}),stringify:()=>oK},cK=(e,t)=>(sK.identify(t)||rG(t)&&(!t.type||t.type===kG.PLAIN)&&sK.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===sK.tag&&e.default);function lK(e,t,n){let r=dK(e,n);if(iG(r))for(let n of r.items)uK(e,t,n);else if(Array.isArray(r))for(let n of r)uK(e,t,n);else uK(e,t,r)}function uK(e,t,n){let r=dK(e,n);if(!tG(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function dK(e,t){return e&&$W(t)?t.resolve(e.doc,e):t}function fK(e,t,{key:n,value:r}){if(oG(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(cK(e,n))lK(e,t,r);else{let i=wG(n,``,e);if(t instanceof Map)t.set(i,wG(r,i,e));else if(t instanceof Set)t.add(i);else{let a=pK(n,i,e),o=wG(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function pK(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(oG(e)&&n?.doc){let t=eK(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),aK(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function mK(e,t,n){return new hK(MG(e,void 0,n),MG(t,void 0,n))}var hK=class e{constructor(e,t=null){Object.defineProperty(this,QW,{value:YW}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return oG(n)&&(n=n.clone(t)),oG(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return fK(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?iK(this,e,t,n):JSON.stringify(this)}};function gK(e,t,n){return(t.inFlow??e.flow?vK:_K)(e,t,n)}function _K({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(oG(i))!d&&i.spaceBefore&&f.push(``),yK(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(nG(i)){let e=oG(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),yK(n,f,e.commentBefore,d))}d=!1;let s=rK(i,u,()=>o=null,()=>d=!0);o&&(s+=RG(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
`}}return e?(p+=`
`+uG(l(e),c),s&&s()):d&&o&&o(),p}function GG({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(NW(i))i.spaceBefore&&d.push(``),KG(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(kW(i)){let e=NW(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),KG(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=NW(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=AG(i,c,()=>a=null);l||=d.length>u||o.includes(`
`),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=dG(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
`;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function KG({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=uG(t(r),e);n.push(i.trimStart())}}function qG(e,t){let n=AW(t)?t.value:t;for(let r of e)if(kW(r)&&(r.key===t||r.key===n||AW(r.key)&&r.key.value===n))return r}var JG=class extends cG{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(xW,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(VG(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=kW(e)?e:!e||typeof e!=`object`||!(`key`in e)?new HG(e,e?.value):new HG(e.key,e.value);let r=qG(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);AW(r.value)&&tG(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=qG(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=qG(this.items,e)?.value;return(!t&&AW(n)?n.value:n)??void 0}has(e){return!!qG(this.items,e)}set(e,t){this.add(new HG(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)zG(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!kW(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),UG(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},YG={collection:`map`,default:!0,nodeClass:JG,tag:`tag:yaml.org,2002:map`,resolve(e,t){return OW(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>JG.from(e,t,n)},XG=class extends cG{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(wW,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=ZG(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=ZG(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&AW(r)?r.value:r}has(e){let t=ZG(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=ZG(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];AW(r)&&tG(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(ZW(e,String(r++),t));return n}toString(e,t,n){return e?UG(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(aG(a,void 0,n))}}return i}};function ZG(e){let t=AW(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var QG={collection:`seq`,default:!0,nodeClass:XG,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return jW(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>XG.from(e,t,n)},$G={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),EG(e,t,n,r)}},eK={identify:e=>e==null,createNode:()=>new nG(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new nG(null),stringify:({source:e},t)=>typeof e==`string`&&eK.test.test(e)?e:t.options.nullStr},tK={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new nG(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&tK.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function nK({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var rK={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:nK},iK={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),string Line truncated
`:` `)}return EG({comment:e,type:t,value:s},r,i,a)}};function vK(e,t){if(jW(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!kW(r)){if(OW(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new HG(new nG(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=kW(r)?r:new HG(r)}}else t(`Expected a sequence for this tag`);return e}function yK(e,t,n){let{replacer:r}=n,i=new XG(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(VG(o,s,n))}return i}var bK={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:vK,createNode:yK},xK=class e extends XG{constructor(){super(),this.add=JG.prototype.add.bind(this),this.delete=JG.prototype.delete.bind(this),this.get=JG.prototype.get.bind(this),this.has=JG.prototype.has.bind(this),this.set=JG.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(kW(e)?(r=ZW(e.key,``,t),i=ZW(e.value,r,t)):r=ZW(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=yK(e,t,n),i=new this;return i.items=r.items,i}};xK.tag=`tag:yaml.org,2002:omap`;var SK={collection:`seq`,identify:e=>e instanceof Map,nodeClass:xK,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=vK(e,t),r=[];for(let{key:e}of n.items)AW(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new xK,n)},createNode:(e,t,n)=>xK.from(e,t,n)};function CK({value:e,source:t},n){return t&&(e?wK:TK).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var wK={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new nG(!0),stringify:CK},TK={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new nG(!1),stringify:CK},EK={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:nK},DK={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():nK(e)}},OK={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new nG(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:nK},kK=e=>typeof e==`bigint`||Number.isInteger(e);function AK(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function jK(e,t,n){let{value:r}=e;if(kK(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return nK(e)}var MK={identify:kK,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>AK(e,2,2,n),stringify:e=>jK(e,2,`0b`)},NK={identify:kK,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>AK(e,1,8,n),stringify:e=>jK(e,8,`0`)},PK={identify:kK,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>AK(e,0,10,n),stringify:nK},FK={identify:kK,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>AK(e,2,16,n),stringify:e=>jK(e,16,`0x`)},IK=class e extends JG{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=kW(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new HG(e.key,null):new HG(e,null),qG(this.items,t.key)||this.items.push(t)}get(e,t){let n=qG(this.items,e);return!t&&kW(n)?AW(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=qG(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new HG(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return s Line truncated
`)?(n.push(`...`),n.push(uG(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(uG(a(t),``)))}return n.join(`
`+LG(l(e),c),s&&s()):d&&o&&o(),p}function vK({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(oG(i))i.spaceBefore&&d.push(``),yK(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(nG(i)){let e=oG(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),yK(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=oG(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=rK(i,c,()=>a=null);l||=d.length>u||o.includes(`
`),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=RG(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
`;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function yK({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=LG(t(r),e);n.push(i.trimStart())}}function bK(e,t){let n=rG(t)?t.value:t;for(let r of e)if(nG(r)&&(r.key===t||r.key===n||rG(r.key)&&r.key.value===n))return r}var xK=class extends FG{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(JW,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(mK(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=nG(e)?e:!e||typeof e!=`object`||!(`key`in e)?new hK(e,e?.value):new hK(e.key,e.value);let r=bK(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);rG(r.value)&&OG(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=bK(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=bK(this.items,e)?.value;return(!t&&rG(n)?n.value:n)??void 0}has(e){return!!bK(this.items,e)}set(e,t){this.add(new hK(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)fK(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!nG(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),gK(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},SK={collection:`map`,default:!0,nodeClass:xK,tag:`tag:yaml.org,2002:map`,resolve(e,t){return tG(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>xK.from(e,t,n)},CK=class extends FG{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(ZW,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=wK(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=wK(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&rG(r)?r.value:r}has(e){let t=wK(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=wK(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];rG(r)&&OG(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(wG(e,String(r++),t));return n}toString(e,t,n){return e?gK(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(MG(a,void 0,n))}}return i}};function wK(e){let t=rG(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var TK={collection:`seq`,default:!0,nodeClass:CK,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return iG(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>CK.from(e,t,n)},EK={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),$G(e,t,n,r)}},DK={identify:e=>e==null,createNode:()=>new kG(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new kG(null),stringify:({source:e},t)=>typeof e==`string`&&DK.test.test(e)?e:t.options.nullStr},OK={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new kG(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&OK.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function kK({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var AK={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:kK},jK={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),string Line truncated
`:` `)}return $G({comment:e,type:t,value:s},r,i,a)}};function GK(e,t){if(iG(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!nG(r)){if(tG(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new hK(new kG(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=nG(r)?r:new hK(r)}}else t(`Expected a sequence for this tag`);return e}function KK(e,t,n){let{replacer:r}=n,i=new CK(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(mK(o,s,n))}return i}var qK={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:GK,createNode:KK},JK=class e extends CK{constructor(){super(),this.add=xK.prototype.add.bind(this),this.delete=xK.prototype.delete.bind(this),this.get=xK.prototype.get.bind(this),this.has=xK.prototype.has.bind(this),this.set=xK.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(nG(e)?(r=wG(e.key,``,t),i=wG(e.value,r,t)):r=wG(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=KK(e,t,n),i=new this;return i.items=r.items,i}};JK.tag=`tag:yaml.org,2002:omap`;var YK={collection:`seq`,identify:e=>e instanceof Map,nodeClass:JK,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=GK(e,t),r=[];for(let{key:e}of n.items)rG(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new JK,n)},createNode:(e,t,n)=>JK.from(e,t,n)};function XK({value:e,source:t},n){return t&&(e?ZK:QK).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var ZK={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new kG(!0),stringify:XK},QK={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new kG(!1),stringify:XK},$K={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:kK},eq={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():kK(e)}},tq={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new kG(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:kK},nq=e=>typeof e==`bigint`||Number.isInteger(e);function rq(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function iq(e,t,n){let{value:r}=e;if(nq(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return kK(e)}var aq={identify:nq,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>rq(e,2,2,n),stringify:e=>iq(e,2,`0b`)},oq={identify:nq,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>rq(e,1,8,n),stringify:e=>iq(e,8,`0`)},sq={identify:nq,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>rq(e,0,10,n),stringify:kK},cq={identify:nq,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>rq(e,2,16,n),stringify:e=>iq(e,16,`0x`)},lq=class e extends xK{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=nG(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new hK(e.key,null):new hK(e,null),bK(this.items,t.key)||this.items.push(t)}get(e,t){let n=bK(this.items,e);return!t&&nG(n)?rG(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=bK(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new hK(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return s Line truncated
`)?(n.push(`...`),n.push(LG(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(LG(a(t),``)))}return n.join(`
`)+`
`}var ZK=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,TW,{value:bW});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new GW({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[TW]:{value:bW}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=NW(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){QK(this.contents)&&this.contents.add(e)}addIn(e,t){QK(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=qW(this);e.anchor=!t||n.has(t)?JW(t||`a`,n):t}return new $W(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=YW(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=aG(e,l,p);return o&&MW(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new HG(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return QK(this.contents)?this.contents.delete(e):!1}deleteIn(e){return sG(e)?this.contents!=null&&(this.contents=null,!0):QK(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return MW(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return sG(e)?!t&&AW(this.contents)?this.contents.value:this.contents:MW(this.contents)?this.contents.getIn(e,t):void 0}has(e){return MW(this.contents)?this.contents.has(e):!1}hasIn(e){return sG(e)?this.contents!==void 0:MW(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=oG(this.schema,[e],t):QK(this.contents)&&this.contents.set(e,t)}setIn(e,t){sG(e)?this.contents=t:this.contents==null?this.contents=oG(this.schema,Array.from(e),t):QK(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new GW({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new GW({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new YK(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=ZW(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?XW(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return XK(this,e)}};function QK(e){if(MW(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var $K=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},eq=class extends $K{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},tq=class extends $K{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},nq=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function rq(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}function iq(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(iq(t.key)||iq(t.value))return!0}return!1;default:return!0}}function aq(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&iq(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function oq(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||AW(e)&&AW(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var sq=`All mapping items must start at the same column`;function cq({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??JG)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=rq(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,sq)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||iq(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,sq);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&aq(r.indent,u,i),n.atKey=!1,oq(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=rq(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&aq(r.indent,f,i),s=c.range[2];let l=new HG(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let e=new HG(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function lq({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??XG)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=rq(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&aq(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function uq(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var dq=`Block collections are not allowed within flow collections`,fq=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function pq({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?JG:XG))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=rq(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
`+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&iq(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];kW(t)&&(t=t.value??t.key),t.comment?t.comment+=`
`+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],fq(m)&&i(r.range,`BLOCK_IN_FLOW`,dq)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);fq(f)&&i(g.range,`BLOCK_IN_FLOW`,dq),n.atKey=!1;let _=rq(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?fq(m)&&i(v.range,`BLOCK_IN_FLOW`,dq):_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let y=new HG(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;oq(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new JG(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=uq(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
`+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function mq(e,t,n,r,i,a){let o=n.type===`block-map`?cq(e,t,n,r,a):n.type===`block-seq`?lq(e,t,n,r,a):pq(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function hq(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===JG.tagName&&s===`map`||o===XG.tagName&&s===`seq`)return mq(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),mq(e,t,n,i,o)}let l=mq(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=NW(u)?u:new nG(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function gq(e,t,n){let r=t.offset,i=_q(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?nG.BLOCK_FOLDED:nG.BLOCK_LITERAL,o=t.source?vq(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
`}var wq=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,QW,{value:qW});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new vG({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[QW]:{value:qW}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=oG(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){Tq(this.contents)&&this.contents.add(e)}addIn(e,t){Tq(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=bG(this);e.anchor=!t||n.has(t)?xG(t||`a`,n):t}return new EG(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=SG(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=MG(e,l,p);return o&&aG(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new hK(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return Tq(this.contents)?this.contents.delete(e):!1}deleteIn(e){return PG(e)?this.contents!=null&&(this.contents=null,!0):Tq(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return aG(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return PG(e)?!t&&rG(this.contents)?this.contents.value:this.contents:aG(this.contents)?this.contents.getIn(e,t):void 0}has(e){return aG(this.contents)?this.contents.has(e):!1}hasIn(e){return PG(e)?this.contents!==void 0:aG(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=NG(this.schema,[e],t):Tq(this.contents)&&this.contents.set(e,t)}setIn(e,t){PG(e)?this.contents=t:this.contents==null?this.contents=NG(this.schema,Array.from(e),t):Tq(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new vG({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new vG({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Sq(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=wG(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?CG(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return Cq(this,e)}};function Tq(e){if(aG(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var Eq=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},Dq=class extends Eq{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},Oq=class extends Eq{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},kq=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function Aq(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}function jq(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(jq(t.key)||jq(t.value))return!0}return!1;default:return!0}}function Mq(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&jq(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function Nq(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||rG(e)&&rG(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var Pq=`All mapping items must start at the same column`;function Fq({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??xK)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=Aq(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,Pq)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||jq(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,Pq);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&Mq(r.indent,u,i),n.atKey=!1,Nq(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=Aq(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&Mq(r.indent,f,i),s=c.range[2];let l=new hK(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let e=new hK(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function Iq({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??CK)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=Aq(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&Mq(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function Lq(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var Rq=`Block collections are not allowed within flow collections`,zq=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function Bq({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?xK:CK))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=Aq(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
`+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&jq(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];nG(t)&&(t=t.value??t.key),t.comment?t.comment+=`
`+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],zq(m)&&i(r.range,`BLOCK_IN_FLOW`,Rq)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);zq(f)&&i(g.range,`BLOCK_IN_FLOW`,Rq),n.atKey=!1;let _=Aq(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?zq(m)&&i(v.range,`BLOCK_IN_FLOW`,Rq):_.comment&&(g.comment?g.comment+=`
`+_.comment:g.comment=_.comment);let y=new hK(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;Nq(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new xK(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=Lq(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
`+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function Vq(e,t,n,r,i,a){let o=n.type===`block-map`?Fq(e,t,n,r,a):n.type===`block-seq`?Iq(e,t,n,r,a):Bq(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function Hq(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===xK.tagName&&s===`map`||o===CK.tagName&&s===`seq`)return Vq(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),Vq(e,t,n,i,o)}let l=Vq(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=oG(u)?u:new kG(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Uq(e,t,n){let r=t.offset,i=Wq(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?kG.BLOCK_FOLDED:kG.BLOCK_LITERAL,o=t.source?Gq(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
`.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
`;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===nG.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
`;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===kG.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
`):t.length>c||r[0]===` `?(f===` `?f=`
`:!p&&f===`
`&&(f=`
@@ -86,59 +86,59 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
`+o[e][0].slice(c);d[d.length-1]!==`
`&&(d+=`
`);break;default:d+=`
`}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function _q({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function vq(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function yq(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=nG.PLAIN,c=bq(a,l);break;case`single-quoted-scalar`:s=nG.QUOTE_SINGLE,c=xq(a,l);break;case`double-quoted-scalar`:s=nG.QUOTE_DOUBLE,c=Cq(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=uq(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function bq(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),Sq(e)}function xq(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),Sq(e.slice(1,-1)).replace(/''/g,`'`)}function Sq(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
`}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function Wq({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Gq(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function Oee(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=kG.PLAIN,c=Kq(a,l);break;case`single-quoted-scalar`:s=kG.QUOTE_SINGLE,c=qq(a,l);break;case`double-quoted-scalar`:s=kG.QUOTE_DOUBLE,c=Yq(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Lq(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Kq(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),Jq(e)}function qq(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),Jq(e.slice(1,-1)).replace(/''/g,`'`)}function Jq(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
`?a+=o:o=`
`:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function Cq(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
`:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function Yq(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
`){if(i===`
`){let{fold:t,offset:i}=wq(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=Dee[i];if(a)n+=a;else if(i===`
`){let{fold:t,offset:i}=Xq(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=Zq[i];if(a)n+=a;else if(i===`
`)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
`)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=Tq(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
`)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=Qq(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
`&&(a!==`\r`||e[r+2]!==`
`)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function wq(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
`)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function Xq(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
`||r===`\r`)&&(r!==`\r`||e[t+2]===`
`);)r===`
`&&(n+=`
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var Dee={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
`,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function Tq(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function Eq(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?gq(e,t,r):yq(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[CW]:c?Dq(e.schema,i,c,n,r):t.type===`scalar`?Oq(e,i,t,r):e.schema[CW];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=AW(a)?a:new nG(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new nG(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Dq(e,t,n,r,i){if(n===`!`)return e[CW];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[CW])}function Oq({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[CW];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[CW];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function kq(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var Aq={composeNode:jq,composeEmptyNode:Mq};function jq(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=Nq(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=Eq(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=hq(Aq,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=Mq(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!AW(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Mq(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=Eq(e,{type:`scalar`,offset:kq(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Nq({options:e},{offset:t,source:n,end:r},i){let a=new $W(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=uq(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function Pq(e,t,{offset:n,start:r,value:i,end:a},o){let s=new ZK(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=rq(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?jq(c,i,l,o):Mq(c,l.end,r,null,l,o);let u=s.contents.range[2],d=uq(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function Fq(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function Iq(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var Zq={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
`,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function Qq(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function $q(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Uq(e,t,r):Oee(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[XW]:c?eJ(e.schema,i,c,n,r):t.type===`scalar`?tJ(e,i,t,r):e.schema[XW];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=rG(a)?a:new kG(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new kG(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function eJ(e,t,n,r,i){if(n===`!`)return e[XW];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[XW])}function tJ({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[XW];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[XW];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function nJ(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var rJ={composeNode:iJ,composeEmptyNode:aJ};function iJ(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=oJ(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=$q(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=Hq(rJ,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=aJ(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!rG(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function aJ(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=$q(e,{type:`scalar`,offset:nJ(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function oJ({options:e},{offset:t,source:n,end:r},i){let a=new EG(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=Lq(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function sJ(e,t,{offset:n,start:r,value:i,end:a},o){let s=new wq(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=Aq(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?iJ(c,i,l,o):aJ(c,l.end,r,null,l,o);let u=s.contents.range[2],d=Lq(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function cJ(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function lJ(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
`:`
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var Lq=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=Fq(e);r?this.warnings.push(new tq(i,t,n)):this.errors.push(new eq(i,t,n))},this.directives=new GW({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=Iq(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(MW(i)&&!i.flow&&i.items.length>0){let e=i.items[0];kW(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Iq(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=Fq(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=Pq(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new eq(Fq(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new eq(Fq(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=uq(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new eq(Fq(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new ZK(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},Rq=Symbol(`break visit`),zq=Symbol(`skip children`),Bq=Symbol(`remove item`);function Vq(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Hq(Object.freeze([]),e,t)}Vq.BREAK=Rq,Vq.SKIP=zq,Vq.REMOVE=Bq,Vq.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Vq.parentCollection=(e,t)=>{let n=Vq.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function Hq(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=Hq(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===Rq)return Rq;else r===Bq&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function Uq(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var uJ=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=cJ(e);r?this.warnings.push(new Oq(i,t,n)):this.errors.push(new Dq(i,t,n))},this.directives=new vG({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=lJ(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(aG(i)&&!i.flow&&i.items.length>0){let e=i.items[0];nG(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:lJ(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=cJ(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=sJ(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Dq(cJ(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new Dq(cJ(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=Lq(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Dq(cJ(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new wq(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},dJ=Symbol(`break visit`),fJ=Symbol(`skip children`),pJ=Symbol(`remove item`);function mJ(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),hJ(Object.freeze([]),e,t)}mJ.BREAK=dJ,mJ.SKIP=fJ,mJ.REMOVE=pJ,mJ.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},mJ.parentCollection=(e,t)=>{let n=mJ.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function hJ(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=hJ(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===dJ)return dJ;else r===pJ&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function gJ(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
`:case`\r
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function Wq(e){switch(e){case void 0:case` `:case`
`:case`\r`:case` `:return!0;default:return!1}}var Gq=new Set(`0123456789ABCDEFabcdef`),Kq=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),qq=new Set(`,[]{}`),Jq=new Set(` ,[]{}
\r `),Yq=e=>!e||Jq.has(e),Xq=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function _J(e){switch(e){case void 0:case` `:case`
`:case`\r`:case` `:return!0;default:return!1}}var vJ=new Set(`0123456789ABCDEFabcdef`),yJ=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),bJ=new Set(`,[]{}`),xJ=new Set(` ,[]{}
\r `),SJ=e=>!e||xJ.has(e),CJ=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
`||t===`\r`&&this.buffer[e+1]===`
`}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
`||!t&&!this.atEnd)return e+n+1}return t===`
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&Wq(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&Wq(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Wq(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&Wq(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(Yq),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&Wq(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(Yq),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||Wq(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&_J(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&_J(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!_J(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&_J(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(SJ),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&_J(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(SJ),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||_J(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
`,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
`,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>Wq(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
`,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>_J(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
`:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
`)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
`,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
`;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
`&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(Wq(r)||e&&qq.has(r))break;t=n}else if(Wq(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
`&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(_J(r)||e&&bJ.has(r))break;t=n}else if(_J(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
`?(n+=1,r=`
`,i=this.buffer[n+1]):t=n),i===`#`||e&&qq.has(i))break;if(r===`
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&qq.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(Yq),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(Wq(n)||t&&qq.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!Wq(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Kq.has(t))t=this.buffer[++e];else if(t===`%`&&Gq.has(this.buffer[e+1])&&Gq.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
`,i=this.buffer[n+1]):t=n),i===`#`||e&&bJ.has(i))break;if(r===`
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&bJ.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(SJ),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(_J(n)||t&&bJ.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!_J(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(yJ.has(t))t=this.buffer[++e];else if(t===`%`&&vJ.has(this.buffer[e+1])&&vJ.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},Zq=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function Qq(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function $q(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function eJ(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function tJ(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function nJ(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function rJ(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function iJ(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!Qq(t.start,`explicit-key-ind`)&&!Qq(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,eJ(t.value)?t.value.end?rJ(t.value.end,t.sep):t.value.end=t.sep:rJ(t.start,t.sep),delete t.sep)}var aJ=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new Xq,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Uq(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&iJ(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&$q(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.in Line truncated
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},wJ=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function TJ(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function EJ(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function DJ(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function OJ(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function kJ(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function AJ(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function jJ(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!TJ(t.start,`explicit-key-ind`)&&!TJ(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,DJ(t.value)?t.value.end?AJ(t.value.end,t.sep):t.value.end=t.sep:AJ(t.start,t.sep),delete t.sep)}var MJ=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new CJ,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=gJ(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&jJ(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&EJ(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.in Line truncated
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){rJ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(Qq(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=nJ(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Qq(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(eJ(t.key)&&!Qq(t.sep,`newline`)){let e=nJ(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Qq(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!Qq(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){rJ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||Qq(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.ite Line truncated
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){AJ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(TJ(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=kJ(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(TJ(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(DJ(t.key)&&!TJ(t.sep,`newline`)){let e=kJ(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):TJ(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!TJ(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){AJ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||TJ(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.ite Line truncated
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=nJ(tJ(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=nJ(tJ(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function oJ(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Zq||null,prettyErrors:t}}function sJ(e,t={}){let{lineCounter:n,prettyErrors:r}=oJ(t),i=new aJ(n?.addNewLine),a=new Lq(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new eq(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(nq(e,n)),o.warnings.forEach(nq(e,n))),o}function cJ(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=sJ(e,n);if(!i)return null;if(i.warnings.forEach(e=>MG(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function lJ(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return DW(e)&&!r?e.toString(n):new ZK(e,r,n).toString(n)}var uJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e),dJ=e=>uJ(e)?Object.entries(e).map(([e,t])=>[e,Array.isArray(t)?t:[]]):[];function fJ(e){if(uJ(e)){if(uJ(e.parallel))return{kind:`parallel`,base:[`parallel`],branches:dJ(e.parallel)};if(uJ(e.switch))return{kind:`switch`,base:[`switch`,`cases`],on:typeof e.switch.on==`string`?e.switch.on:``,branches:dJ(e.switch.cases)}}}function pJ(e){return e.slice(2).includes(`parallel`)}function mJ(e,t){let n=sJ(e).getIn(t,!0);if(OW(n))return n.toJSON()}function hJ(e,t,n){let r=sJ(e);return r.setIn(t,r.createNode(EJ(n))),r.toString()}function gJ(e,t,n){let r=sJ(e),i=t.slice(0,-1),a=pJ(i);if(a&&![`agent.run`,`workflow.call`].includes(n))throw Error(`Branches allow only read-only agents and workflow calls.`);let o=r.getIn(i,!0);if(jW(o)||(r.setIn(i,r.createNode([])),o=r.getIn(i,!0)),!jW(o))return{source:e,path:[]};let s=Math.min(Math.max(Number(t.at(-1))+1,0),o.items.length),c=n===`parallel`?{parallel:{"branch-1":[],"branch-2":[]}}:n===`switch`?{switch:{on:``,cases:{true:[],default:[]}}}:{type:n,...a&&n===`agent.run`?{settings:{read_only:!0}}:{}};return o.items.splice(s,0,r.createNode(c)),{source:r.toString(),path:[...i,s]}}function _J(e,t){if(t===`switch`){if(!e||e.includes(`/`))throw Error(`A case is the value it matches, without a slash.`)}else if(!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(e))throw Error(`Use a lowercase branch name with letters, digits, dots or dashes.`)}function vJ(e,t){let n=e.getIn(t,!0),r=fJ(OW(n)?n.toJSON():void 0),i=r?e.getIn([...t,...r.base],!0):void 0;if(!r||!OW(i))throw Error(`This step has no branches.`);return{kind:r.kind,branches:i}}function yJ(e,t,n){let r=sJ(e),{kind:i,branches:a}=vJ(r,t);if(_J(n,i),a.has(n))throw Error(`Branch ${n} already exists.`);return a.set(n,r.createNode([])),r.toString()}function bJ(e,t,n,r){let i=sJ(e),{kind:a,branches:o}=vJ(i,t);if(_J(r,a),n!==r&&o.has(r))throw Error(`Branch ${r} already exists.`);let s=o.items.find(e=>AW(e.key)&&e.key.value===n);if(!s||!AW(s.key))throw Error(`Branch ${n} does not exist.`);return s.key.value=r,i.toString()}function xJ(e,t,n){let r=sJ(e),{kind:i,branches:a}=vJ(r,t);if(i===`parallel`&&a.items.length<=2)throw Error(`Parallel needs at least two branches.`);if(a.items.length<=1)throw Error(`A switch needs at least one case.`);return Line truncated
`).find(e=>e.trim())?.trim()}}function BJ(e,t){let n=JSON.stringify(e??{})+` `+(typeof t==`string`?`{{ ${t.replace(/^!/,``)} }}`:``);return[...new Set([...n.matchAll(IJ)].map(e=>e[1]))]}function VJ(e){let t=sJ(e).toJS(),n=LJ(t)&&Array.isArray(t.steps)?t.steps:[],r=[],i=[],a=new Map,o=[],s=new Set,c=`start`;r.push({id:c,type:`step`,position:{x:0,y:0},data:{kind:`start`,key:`start`,title:`Starts when`,type:``,detail:``}});let l=[c],u=1,d=new Map,f=e=>{let t=d.get(e)??0;return d.set(e,t+1),t},p=(e,t,n,i,s,c,l,u)=>{let d=LJ(e)?e:{},p=fJ(d),m=p?.kind??(typeof d.type==`string`?d.type:``),h=LJ(d.settings)?d.settings:{},g=typeof d.id==`string`?d.id:``,_=`step-${t}`,v=s?`${s}/${g||m}`:g||m;r.push({id:_,type:`step`,position:{x:n,y:i},data:{kind:`step`,key:g||t,title:g||FJ(m),type:m,role:kJ(m),step:l?.length===2?String(Number(l[1])+1).padStart(2,`0`):void 0,detail:p?.on?`on ${p.on.replace(/^steps\./,``)}`:RJ(m,h),summary:zJ(h),when:typeof d.when==`string`?d.when:void 0,retry:LJ(d.retry)&&typeof d.retry.attempts==`number`?d.retry.attempts:void 0,continues:d.on_failure===`continue`,branch:s,lane:u,path:l,stage:v,occurrence:f(v),...c?{resume:c}:{}}}),g&&a.set(g,_);let y=p?.on?`{{ ${p.on} }}`:``;for(let e of BJ([d.settings,y],d.when))o.push({from:e,to:_});return _},m=(e,t,n)=>{e.forEach((r,a)=>i.push({id:`flow-${r}-${t}`,source:r,target:t,kind:`flow`,...s.has(r)?{otherwise:!0}:{},insertAfter:a===e.length-1?n:void 0}))};for(let[e,t]of n.entries()){let n=fJ(t);if(n){let{kind:i,base:a,branches:o}=n,c=p(t,String(e+1),0,u*MJ,void 0,void 0,[`steps`,e]);m(l,c,[`steps`,e-1]),u++;let d=LJ(t)&&typeof t.id==`string`?t.id:i,f=i===`switch`&&!o.some(([e])=>e==="default"),h=o.length+ +!!f,g=[],_=0;o.forEach(([t,n],o)=>{let s=(o-(h-1)/2)*NJ,l=[c],f=[`steps`,e,...a,t];n.forEach((n,r)=>{let a=p(n,`${e+1}-${t}-${r+1}`,s,(u+r)*MJ,t,d,[...f,r],i);m(l,a,[...f,r-1]),l=[a]}),_=Math.max(_,n.length);let v=`add-${e}-${t}`;r.push({id:v,type:`add`,position:{x:s+104,y:(u+n.length)*MJ},data:{kind:`step`,key:v,title:``,type:``,detail:``,branch:t,lane:i,insertAfter:[...f,n.length-1]}}),m(l,v),g.push(v)});let v=(Math.max(_,1)+1)*MJ-24;o.forEach(([t],n)=>{let a=(n-(h-1)/2)*NJ;r.push({id:`lane-${e}-${t}`,type:`lane`,position:{x:a-12,y:u*MJ-40},style:{width:`264px`,height:`${v}px`},zIndex:-1,data:{kind:`step`,key:t,title:t,type:``,detail:``,lane:i}})}),f&&(g.push(c),s.add(c)),l=g,u+=Math.max(_,1)+1;continue}let i=p(t,String(e+1),0,u*MJ,void 0,void 0,[`steps`,e]);m(l,i,[`steps`,e-1]),l=[i],u++}r.push({id:`add-end`,type:`add`,position:{x:104,y:u*MJ-24},data:{kind:`step`,key:`add`,title:``,type:``,detail:``,insertAfter:[`steps`,n.length-1]}}),m(l,`add-end`);for(let{from:e,to:t}of o){let n=a.get(e);n&&(i.some(e=>e.kind===`flow`&&e.source===n&&e.target===t)||i.push({id:`data-${n}-${t}`,source:n,target:t,kind:`data`,label:e,offset:24+14*i.filter(e=>e.kind===`data`).length,sourceHandle:`data-out`,targetHandle:`data-in`}))}return{nodes:r,edges:i}}var HJ={agent:pn,command:tr,repo:kn,gate:Zn,forge:Ln,human:ir,review:En,workflow:sr},UJ={agent:`Agents`,command:`Commands`,repo:`Repository`,gate:`Checks`,forge:`Issues and PRs`,human:`People`,review:`Review`,workflow:`Flow`};function WJ(e){return e===`parallel`?kn:e===`switch`?$n:HJ[e.split(`.`)[0]]??sr}function GJ(e){return Object.keys(UJ).map(t=>({title:UJ[t],icon:HJ[t],types:e.filter(e=>e.split(`.`)[0]===t)})).filter(e=>e.types.length)}var KJ=k({__name:`WorkflowPicker`,props:{value:{},workflows:{},label:{}},emits:[`pick`],setup(e,{emit:t}){let n=t;return(t,r)=>(R(),K(z(rl),{"model-value":e.value||void 0,"onUpdate:modelValue":r[0]||=e=>n(`pick`,String(e))},{default:j(()=>[M(z(ul),{"aria-label":e.label},{default:j(()=>[M(z(dl),{placeholder:`Choose workflow`})]),_:1},8,[`aria-label`]),M(z(il),null,{default:j(()=>[e.value&&!e.workflows.some(t=>t.id===e.value)?(R(),K(z(sl),{key:0,value:e.value,disabled:``},{default:j(()=>[A(B(e.value)+` (unavailable)`,1)]),_:1},8,[`value`])):L(``,!0),(R(!0),W(V,null,G(e.workflows,e=>(R(),K(z(sl),{key:e.id,value:e.id},{default:j(()=>[A(B(e.id),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1},8,[`model-value`]))}});function qJ(e){return e.ok?`Valid`:e.line?`Line ${e.line}: ${e.message}`:e.message}function JJ(e,t=[]){let n=sJ(e),r=n.errors[0];if(r)return{ok:!1,message:cY(r.message),line:r.linePos?.[0]?.line};let i=n.toJS();if(!lY(i))return{ok:!1,message:`A workflow is a mapping with an id and steps.`};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,message:`workflow id is required`};let o=i.steps;if(o==null||o===``)return{ok:!1,message:`workflow ${a} has no steps`};if(!Array.isArray(o))return{ok:!1,message:`workflow ${a}: steps must be a list`};if(!o.length)return{ok:!1,message:`workflow ${a} has no steps`};let s=new Map(t.map(e=>[e.name,e])),c=typeof i.repository==`string`&&i.repository.trim()?i.repository.trim():`required`,l=[],u=new Set;for(let[e,t]of o.entries()){let n=`workflow ${a} step ${e+1}`,r=fJ(t);if(r){if(r.kind===`switch`&&!r.on)return{ok:!1,message:`${n}: switch.on Line truncated
`).map((e,t)=>({number:t+1,text:e,tokens:iY(e)}))}var nY=/^(\s*)(-\s+)?/,rY=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function iY(e){let{code:t,comment:n}=aY(e),r=oY(t);return n&&r.push({text:n,kind:`comment`}),r}function aY(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(t)r===t&&(t=``);else if(r===`"`||r===`'`)t=r;else if(r===`#`&&(n===0||/\s/.test(e[n-1]??``)))return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:``}}function oY(e){if(!e)return[];let t=[],n=nY.exec(e);n?.[1]&&t.push({text:n[1],kind:`plain`}),n?.[2]&&t.push({text:n[2],kind:`punct`});let r=e.slice(n?.[0].length??0);if(!r)return t;let i=rY.exec(r);return i?(t.push({text:i[1]??``,kind:`key`}),t.push({text:i[2]??`:`,kind:`punct`}),i[3]&&t.push({text:i[3],kind:`plain`}),[...t,...sY(i[4]??``)]):[...t,...sY(r)]}function sY(e){if(!e)return[];let t=/^("[^"]*"?|'[^']*'?)([\s\S]*)$/.exec(e);if(!t)return[{text:e,kind:`plain`}];let n=[{text:t[1]??``,kind:`string`}];return t[2]&&n.push({text:t[2],kind:`plain`}),n}function cY(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function lY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uY(e){return typeof e==`string`&&e.trim()!==``}var dY={class:`flex h-full w-[24rem] flex-col border-l border-border bg-card shadow-xl`},fY={class:`flex items-center gap-2.5 border-b border-border px-4 py-3`},pY={class:`flex size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-primary`},mY={class:`min-w-0 flex-1`},hY={class:`truncate font-mono text-[11px] text-fg-subtle`},gY={class:`flex-1 space-y-5 overflow-y-auto px-4 py-4`},_Y={key:0,class:`rounded-md bg-danger/10 px-2.5 py-1.5 text-xs text-danger`,role:`alert`},vY={key:1,class:`space-y-3`},yY={key:0,class:`block space-y-1.5`},bY={id:`switch-on`},xY=[`value`],SY={class:`text-xs font-medium text-muted-foreground`},CY={class:`flex items-center gap-2`},wY={key:1,role:`alert`,class:`text-xs text-danger`},TY={key:2,class:`space-y-1.5`},EY=[`title`],DY={key:4,class:`flex flex-wrap items-center gap-1 pt-0.5`},OY={key:3,class:`divide-y divide-border rounded-md border border-border`},kY=[`title`],AY={key:0,class:`space-y-3`},jY={class:`text-[13px]`},MY={key:0,class:`text-danger`},NY={class:`ml-2 text-xs text-fg-subtle`},PY={key:1,class:`space-y-3`},FY={class:`text-[13px]`},IY={class:`ml-2 text-xs text-fg-subtle`},LY=[`title`],RY={key:0,class:`text-xs text-danger`},zY={class:`space-y-2`},BY={class:`divide-y divide-border rounded-md border border-border`},VY={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},HY={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},UY={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},WY={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},GY={class:`flex items-center border-t border-border px-4 py-2.5`},KY=k({__name:`StepEditor`,props:{yaml:{},path:{},vocabulary:{},workflows:{},modelAliases:{}},emits:[`update:yaml`,`close`,`remove`],setup(e,{emit:t}){let n=e,r=t,i=I(()=>mJ(n.yaml,n.path)??{}),a=I(()=>fJ(i.value)),o=I(()=>a.value?.kind??(typeof i.value.type==`string`?i.value.type:``)),s=I(()=>a.value?.branches.map(([e])=>e)??[]),c=I(()=>o.value===`parallel`?2:1);function l(e){r(`update:yaml`,hJ(n.yaml,n.path,{...i.value,switch:{...i.value.switch,on:e}}))}let u=q(``),d=q(``);function f(e,t,i=``){try{let a=e===`add`?yJ(n.yaml,n.path,t):e===`rename`?bJ(n.yaml,n.path,t,i):xJ(n.yaml,n.path,t);r(`update:yaml`,a),u.value=``,d.value=``}catch(e){d.value=String(e.message)}}let p=I(()=>n.vocabulary.find(e=>e.name===o.value)),m=I(()=>typeof i.value.settings==`object`&&i.value.settings!==null?i.value.settings:{}),h=I(()=>TJ(n.yaml,n.path)),g=I(()=>p.value?.settings&&i.value.settings?$J(i.value.settings,p.value.settings,`settings`):``),_=[`mission`,`workflow`,`message`,`body`,`plan`,`then`,`status`,`detail`,`run`,`rules`],v=/mission|body|detail|plan|rules/;function y(e,t){return[`workflow.call`,`workflow.handoff`].includes(o.value)&&e===`workflow`||o.value===`human.approve`&&e===`then`?`workflow`:o.value===`agent.run`&&e===`model`?`select`:t.type===`string`?t.enum?`select`:v.test(e)?`text`:`line`:t.type===`boolean`?`boolean`:t.type===`integer`||t.type===`number`?`number`:t.type===`array`&&t.items?.type===`string`?`lines`:`yaml`}let b=I(()=>{let e=Object.entries(p.value?.settings?.properties??{}).filter(([e])=>o.value!==`workflow.call`||![`inputs`,`outputs`].includes(e)).map(([e,t])=>({key:e,schema:t,kind:y(e,t),options:o.value===`agent.run`&&e===`model`?n.modelAliases:t.enum??[]})),t=e.filter(e=>_.includes(e.key)&&e.kind!==`boolean`).sort((e,t)=>_.indexOf(e.key)-_.indexOf(t.key))[0],r=e.filter(e=>e!==t);return{lead:t,compact:r.filter(e=>[`workflow`,`select`,`line`,`number`,`boolean`].includes(e.kind)),long:r.filter(e=>[`text`,`lines`,`yaml`].includes(e.kind))}});function x(e){let{id:t,type:i,...a}=e;r(`update:yaml`,hJ(n.yaml,n.path,{id:t,type:i,...a}))}function S(e,t){x({...i.value,[e]:t})}function C(e){S(`retry`,{...i.value.retry,...e})}function w(e,t){let n={...m.value,[e]:t};o.value===`workflow.call`&&e===`wait`&&t!==!0&&delete n.outputs,x({...i.value,settings:n})}function ee(e,t){let n={...m.value,[e]:t};o.value===`workflow.call`&&t!==m.value[e]&&(delete n.inputs,delete n.outputs),x({...i.value,settings:n})}let T=I(()=>n.workflows.find(e=>e.id===m.value.workflow)),E=I(()=>Object.entries(DJ(T.value?.yaml??``,`inputs`)??{})),D=I(()=>Object.entries(DJ(T.value?.yaml??``,`outputs`)??{})),te=I(()=>Object.entries(DJ(n.yaml,`inputs`)??{})),ne=I(()=>Object.entries(DJ(n.yaml,`outputs`)??{})),re=I(()=>m.value.inputs??{}),ie=I(()=>m.value.outputs??{}),ae=e=>typeof e==`string`&&e.startsWith(`inputs.`),oe=e=>re.value[e]===void 0?``:String(re.value[e]);function se(e,t,n){w(`inputs`,{...re.value,[e]:t===``?void 0:ae(t)?t:gv(t,n??`string`)})}let ce=q(null);function le(e,t){let n=ce.value??b.value.lead?.key;if(!n)return;let r=typeof m.value[n]==`string`?m.value[n]:``,i=`{{ steps.${e}.${t} }}`;w(n,r?`${r.trimEnd()} ${i}`:i)}let ue=q({});function de(e,t){try{w(e,t.trim()?cJ(t):void 0),ue.value={...ue.value,[e]:``}}catch(t){ue.val Line truncated
`)[0]}}}let fe=e=>e===void 0?``:lJ(e).trimEnd(),pe=(e,t)=>t.title??e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase()),me=e=>typeof m.value[e]==`string`?m.value[e]:``;return(t,n)=>(R(),W(`aside`,dY,[U(`header`,fY,[U(`span`,pY,[(R(),K(it(z(WJ)(o.value)),{class:`size-4`}))]),U(`div`,mY,[M(z(O),{"model-value":i.value.id??``,class:`h-7 truncate border-transparent px-1 font-medium shadow-none hover:border-input dark:bg-transparent`,placeholder:z(FJ)(o.value),"aria-label":`Step id`,"onUpdate:modelValue":n[0]||=e=>S(`id`,String(e))},null,8,[`model-value`,`placeholder`]),U(`div`,hY,B(o.value),1)]),M(z(J),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Close`,onClick:n[1]||=e=>r(`close`)},{default:j(()=>[M(z(lr))]),_:1})]),U(`div`,gY,[g.value?(R(),W(`p`,_Y,B(g.value),1)):L(``,!0),a.value?(R(),W(`section`,vY,[o.value===`switch`?(R(),W(`label`,yY,[n[18]||=U(`span`,{class:`text-xs font-medium text-muted-foreground`,title:`The value whose case runs; a case named default runs when none matches`},`Switch on`,-1),M(z(O),{"model-value":a.value.on,class:`font-mono`,placeholder:`steps.assess.result.fit`,list:`switch-on`,onChange:n[2]||=e=>l(e.target.value.trim())},null,8,[`model-value`]),U(`datalist`,bY,[(R(!0),W(V,null,G(h.value,e=>(R(),W(`option`,{key:e,value:`steps.${e}.result.`},null,8,xY))),128))])])):L(``,!0),U(`div`,SY,B(o.value===`switch`?`Cases`:`Branches`),1),(R(!0),W(V,null,G(s.value,e=>(R(),W(`div`,{key:e,class:`flex items-center gap-2`},[M(z(O),{"model-value":e,class:N(o.value===`switch`&&`font-mono`),"aria-label":`${o.value===`switch`?`Case`:`Branch`} ${e}`,onChange:t=>f(`rename`,e,t.target.value.trim())},null,8,[`model-value`,`class`,`aria-label`,`onChange`]),M(z(J),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Remove ${e}`,disabled:s.value.length<=c.value,onClick:t=>f(`delete`,e)},{default:j(()=>[M(z(xe))]),_:1},8,[`aria-label`,`disabled`,`onClick`])]))),128)),U(`div`,CY,[M(z(O),{modelValue:u.value,"onUpdate:modelValue":n[3]||=e=>u.value=e,"aria-label":o.value===`switch`?`New case value`:`New branch name`,placeholder:o.value===`switch`?`Value, or default`:`Branch name`,onKeydown:n[4]||=Vt(Bt(e=>f(`add`,u.value.trim()),[`prevent`]),[`enter`])},null,8,[`modelValue`,`aria-label`,`placeholder`]),M(z(J),{type:`button`,size:`icon-sm`,variant:`outline`,"aria-label":o.value===`switch`?`Add case`:`Add branch`,disabled:!u.value.trim(),onClick:n[5]||=e=>f(`add`,u.value.trim())},{default:j(()=>[M(z(Wn))]),_:1},8,[`aria-label`,`disabled`])]),d.value?(R(),W(`p`,wY,B(d.value),1)):L(``,!0)])):L(``,!0),b.value.lead?(R(),W(`section`,TY,[U(`div`,{class:`flex items-center gap-1 text-xs font-medium text-muted-foreground`,title:b.value.lead.schema.description},[A(B(pe(b.value.lead.key,b.value.lead.schema))+` `,1),b.value.lead.schema.description?(R(),K(z(xn),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,EY),b.value.lead.kind===`workflow`?(R(),K(KJ,{key:0,value:me(b.value.lead.key),workflows:e.workflows,label:pe(b.value.lead.key,b.value.lead.schema),onPick:n[6]||=e=>ee(b.value.lead.key,e)},null,8,[`value`,`workflows`,`label`])):b.value.lead.kind===`select`?(R(),K(z(iv),{key:1,size:`sm`,class:`w-full`,"model-value":me(b.value.lead.key),"onUpdate:modelValue":n[7]||=e=>w(b.value.lead.key,String(e)||void 0)},{default:j(()=>[M(z(av),{value:``},{default:j(()=>[...n[19]||=[A(`Default`,-1)]]),_:1}),(R(!0),W(V,null,G(b.value.lead.options,e=>(R(),K(z(av),{key:e,value:e},{default:j(()=>[A(B(e),1)]),_:2},1032,[`value`]))),128))]),_:1},8,[`model-value`])):b.value.lead.kind===`text`?(R(),K(z(Ol),{key:2,"model-value":me(b.value.lead.key),class:`min-h-40 text-[13px] leading-relaxed`,onFocus:n[8]||=e=>ce.value=b.value.lead.key,"onUpdate:modelValue":n[9]||=e=>w(b.value.lead.key,String(e))},null,8,[`model-value`])):(R(),K(z(O),{key:3,"model-value":me(b.value.lead.key),onFocus:n[10]||=e=>ce.value=b.value.lead.key,"onUpdate:modelValue":n[11]||=e=>w(b.value.lead.key,String(e))},null,8,[`model-value`])),h.value.length&&b.value.lead.kind!==`select`?(R(),W(`div`,DY,[n[20]||=U(`span`,{class:`text-[11px] text-fg-subtle`},`Insert`,-1),(R(!0),W(V,null,G(h.value,e=>(R(),W(V,{key:e},[M(z(J),{type:`button`,variant:`outline`,size:`xs`,class:`font-mono`,onClick:t=>le(e,`summary`)},{default:j(()=>[A(B(e),1)]),_:2},1032,[`onClick`]),M(z(J),{type:`button`,variant:`outline`,size:`xs`,class:`font-mono`,onClick:t=>le(e,`result`)},{default:j(()=>[A(B(e)+`.result`,1)]),_:2},1032,[`onClick`])],64))),128))])):L(``,!0)])):L(``,!0),b.value.compact.length?(R(),W(`section`,OY,[(R(!0),W(V,null,G(b.value.compact,t=>(R(),W(`div`,{key:t.key,class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},[U(`span`,{class:`flex flex-1 items-center gap-1 text-[13px]`,title:t.schema.description},[A(B(pe(t.key,t.schema))+` `,1),t.schema.description?(R(),K(z(xn),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,kY),t.kind===`workflow`?(R(),K(KJ,{key:0,class:`max-w-48`,value:me(t.key),workflows:e.workflows,label:pe(t.key,t.schema),onPick:e=>ee(t.key,e)},null,8,[`vLine truncated
`):``,class:`min-h-16 font-mono text-xs`,placeholder:`One per line`,"onUpdate:modelValue":t=>w(e.key,String(t).split(`
`).filter(Boolean))},null,8,[`model-value`,`onUpdate:modelValue`])):(R(),W(V,{key:2},[M(z(Ol),{"model-value":fe(m.value[e.key]),class:`min-h-24 font-mono text-xs`,placeholder:`YAML`,onChange:t=>de(e.key,t.target.value)},null,8,[`model-value`,`onChange`]),ue.value[e.key]?(R(),W(`span`,RY,B(ue.value[e.key]),1)):L(``,!0)],64))]))),128)),U(`section`,zY,[n[37]||=U(`div`,{class:`text-xs font-medium text-muted-foreground`},`Flow`,-1),U(`div`,BY,[U(`label`,VY,[n[31]||=U(`span`,{class:`flex-1 text-[13px]`},`Run only when`,-1),M(z(O),{class:`h-7 w-48 font-mono text-xs`,placeholder:`always`,"model-value":i.value.when??``,"onUpdate:modelValue":n[12]||=e=>S(`when`,String(e))},null,8,[`model-value`])]),U(`label`,HY,[n[34]||=U(`span`,{class:`flex-1 text-[13px]`},`If it fails`,-1),M(z(iv),{size:`sm`,"model-value":i.value.on_failure??``,"onUpdate:modelValue":n[13]||=e=>S(`on_failure`,String(e)||void 0)},{default:j(()=>[M(z(av),{value:``},{default:j(()=>[...n[32]||=[A(`Park the task`,-1)]]),_:1}),M(z(av),{value:`continue`},{default:j(()=>[...n[33]||=[A(`Continue`,-1)]]),_:1})]),_:1},8,[`model-value`])]),U(`label`,UY,[n[35]||=U(`span`,{class:`flex-1 text-[13px]`},`Attempts`,-1),M(z(O),{type:`number`,min:`1`,max:`10`,placeholder:`1`,class:`h-7 w-20 text-right text-[13px]`,"model-value":i.value.retry?.attempts??``,"onUpdate:modelValue":n[14]||=e=>C({attempts:String(e)===``?void 0:Number(String(e))})},null,8,[`model-value`])]),U(`label`,WY,[n[36]||=U(`span`,{class:`flex-1 text-[13px]`},`Retry backoff`,-1),M(z(Jm),{"model-value":i.value.retry?.backoff??``,units:[`s`,`m`,`h`],"onUpdate:modelValue":n[15]||=e=>C({backoff:e||void 0})},null,8,[`model-value`])])])])]),U(`footer`,GY,[M(z(J),{type:`button`,variant:`ghost`,size:`sm`,class:`text-danger`,onClick:n[16]||=e=>r(`remove`)},{default:j(()=>[M(z(xe)),n[38]||=A(`Delete step`,-1)]),_:1}),M(z(J),{type:`button`,size:`sm`,class:`ml-auto`,onClick:n[17]||=e=>r(`close`)},{default:j(()=>[...n[39]||=[A(`Done`,-1)]]),_:1})])]))}}),qY=`repository_path`;function JY(e,t,n){let r=[];for(let[n,i]of e){let e=t[n];e?.from===`path`&&e.path.trim()&&r.push({name:n,path:e.path.trim(),type:i.type??`string`,required:i.required===!0})}return n.trim()&&r.push({name:qY,path:n.trim(),type:`string`,required:!0}),r}function YY(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e==`boolean`?`bool`:typeof e==`object`?`object`:typeof e}function XY(e,t,n){let r=[];for(let[i,a]of e){let e=t[i],o=a.type??`string`;if(!(e&&(e.from===`path`?e.path.trim():e.value!==``))){a.required&&r.push(`${i} is required`);continue}if(e.from===`path`){let e=n?.failures?.find(e=>e.field_name===i);e&&r.push(`${i}: ${e.reason}`);continue}let s=YY(Qy(e.value,o));o!==`any`&&s!==o&&r.push(`${i} is ${o}, but ${JSON.stringify(e.value)} is not`)}return n?.failures?.some(e=>e.field_name===`repository_path`)&&r.push(`the repository path does not resolve`),r}function ZY(e,t){let n={};for(let[r,i]of e){let e=t[r];e?.from===`path`&&e.path.trim()?n[r]={param:r}:e?.from===`value`&&e.value!==``&&(n[r]={value:Qy(e.value,i.type??`string`)})}return n}function QY(e,t){let n=e=>t.find(t=>t.name===e)?.path??``,r={};for(let[t,i]of Object.entries(e.inputs??{}))r[t]=i.param?{from:`path`,path:n(i.param),value:``}:{from:`value`,path:``,value:typeof i.value==`string`?i.value:JSON.stringify(i.value)};return{rows:r,repositoryPath:n(e.repo_param)}}function $Y(e,t=``){return Array.isArray(e)?e.slice(0,3).flatMap((e,n)=>{let r=`${t}[${n}]`;return[r,...$Y(e,r)]}):e&&typeof e==`object`?Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return[r,...$Y(n,r)]}):[]}function eX(e){try{return e?.body?JSON.parse(e.body):null}catch{return null}}function tX(e){try{let t=JSON.parse(e.headers??`{}`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t)]))}catch{return{}}}function nX(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>80?`${t.slice(0,80)}…`:t}var rX={class:`flex h-full flex-col`},iX={class:`flex items-center gap-2 border-b border-border px-4 py-3`},aX={class:`min-w-0 flex-1 truncate text-sm font-medium`},oX={key:0,class:`flex flex-1 items-center justify-center`},sX={class:`space-y-1.5`},cX={key:1,class:`space-y-1.5`},lX=[`title`],uX={class:`space-y-1.5`},dX={id:`bind-paths`},fX=[`value`],pX={class:`divide-y divide-border rounded-md border border-border`},mX={class:`flex items-center gap-1.5 text-xs`},hX={class:`font-mono`},gX={class:`text-fg-subtle`},_X={key:0,class:`text-danger`,title:`Required`},vX={key:2,class:`text-xs text-danger`},yX=[`title`],bX={key:0,class:`space-y-1 px-3 py-2`},xX={key:0,class:`text-xs text-danger`},SX={key:1,class:`truncate font-mono text-xs text-success`},CX={key:1,class:`px-3 py-2 text-xs text-fg-subtle`},wX={class:`space-y-2`},TX={key:0,role:`alert`,class:`text-xs text-danger`},EX={key:1,class:`text-xs text-fg-subtle`},DX={class:`flex gap-2`},OX=`__new__`,kX=k({__name:`BindEvent`,props:{yaml:{},binding:{}},emits:[`back`,`saved`],setup(e,{emit:t}){let n=e,r=t,i= Line truncated
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=kJ(OJ(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=kJ(OJ(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function NJ(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new wJ||null,prettyErrors:t}}function PJ(e,t={}){let{lineCounter:n,prettyErrors:r}=NJ(t),i=new MJ(n?.addNewLine),a=new uJ(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new Dq(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(kq(e,n)),o.warnings.forEach(kq(e,n))),o}function FJ(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=PJ(e,n);if(!i)return null;if(i.warnings.forEach(e=>aK(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function IJ(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return eG(e)&&!r?e.toString(n):new wq(e,r,n).toString(n)}var LJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e),RJ=e=>LJ(e)?Object.entries(e).map(([e,t])=>[e,Array.isArray(t)?t:[]]):[];function zJ(e){if(LJ(e)){if(LJ(e.parallel))return{kind:`parallel`,base:[`parallel`],branches:RJ(e.parallel)};if(LJ(e.switch))return{kind:`switch`,base:[`switch`,`cases`],on:typeof e.switch.on==`string`?e.switch.on:``,branches:RJ(e.switch.cases)}}}function BJ(e){return e.slice(2).includes(`parallel`)}function VJ(e,t){let n=PJ(e).getIn(t,!0);if(tG(n))return n.toJSON()}function HJ(e,t,n){let r=PJ(e);return r.setIn(t,r.createNode($J(n))),r.toString()}function UJ(e,t,n){let r=PJ(e),i=t.slice(0,-1),a=BJ(i);if(a&&![`agent.run`,`workflow.call`].includes(n))throw Error(`Branches allow only read-only agents and workflow calls.`);let o=r.getIn(i,!0);if(iG(o)||(r.setIn(i,r.createNode([])),o=r.getIn(i,!0)),!iG(o))return{source:e,path:[]};let s=Math.min(Math.max(Number(t.at(-1))+1,0),o.items.length),c=n===`parallel`?{parallel:{"branch-1":[],"branch-2":[]}}:n===`switch`?{switch:{on:``,cases:{true:[],default:[]}}}:{type:n,...a&&n===`agent.run`?{settings:{read_only:!0}}:{}};return o.items.splice(s,0,r.createNode(c)),{source:r.toString(),path:[...i,s]}}function WJ(e,t){if(t===`switch`){if(!e||e.includes(`/`))throw Error(`A case is the value it matches, without a slash.`)}else if(!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(e))throw Error(`Use a lowercase branch name with letters, digits, dots or dashes.`)}function GJ(e,t){let n=e.getIn(t,!0),r=zJ(tG(n)?n.toJSON():void 0),i=r?e.getIn([...t,...r.base],!0):void 0;if(!r||!tG(i))throw Error(`This step has no branches.`);return{kind:r.kind,branches:i}}function KJ(e,t,n){let r=PJ(e),{kind:i,branches:a}=GJ(r,t);if(WJ(n,i),a.has(n))throw Error(`Branch ${n} already exists.`);return a.set(n,r.createNode([])),r.toString()}function qJ(e,t,n,r){let i=PJ(e),{kind:a,branches:o}=GJ(i,t);if(WJ(r,a),n!==r&&o.has(r))throw Error(`Branch ${r} already exists.`);let s=o.items.find(e=>rG(e.key)&&e.key.value===n);if(!s||!rG(s.key))throw Error(`Branch ${n} does not exist.`);return s.key.value=r,i.toString()}function JJ(e,t,n){let r=PJ(e),{kind:i,branches:a}=GJ(r,t);if(i===`parallel`&&a.items.length<=2)throw Error(`Parallel needs at least two branches.`);if(a.items.length<=1)throw Error(`A switch needs at least one case.`);return Line truncated
`).find(e=>e.trim())?.trim()}}function pY(e,t){let n=JSON.stringify(e??{})+` `+(typeof t==`string`?`{{ ${t.replace(/^!/,``)} }}`:``);return[...new Set([...n.matchAll(lY)].map(e=>e[1]))]}function mY(e){let t=PJ(e).toJS(),n=uY(t)&&Array.isArray(t.steps)?t.steps:[],r=[],i=[],a=new Map,o=[],s=new Set,c=`start`;r.push({id:c,type:`step`,position:{x:0,y:0},data:{kind:`start`,key:`start`,title:`Starts when`,type:``,detail:``}});let l=[c],u=1,d=new Map,f=e=>{let t=d.get(e)??0;return d.set(e,t+1),t},p=(e,t,n,i,s,c,l,u)=>{let d=uY(e)?e:{},p=zJ(d),m=p?.kind??(typeof d.type==`string`?d.type:``),h=uY(d.settings)?d.settings:{},g=typeof d.id==`string`?d.id:``,_=`step-${t}`,v=s?`${s}/${g||m}`:g||m;r.push({id:_,type:`step`,position:{x:n,y:i},data:{kind:`step`,key:g||t,title:g||cY(m),type:m,role:nY(m),step:l?.length===2?String(Number(l[1])+1).padStart(2,`0`):void 0,detail:p?.on?`on ${p.on.replace(/^steps\./,``)}`:dY(m,h),summary:fY(h),when:typeof d.when==`string`?d.when:void 0,retry:uY(d.retry)&&typeof d.retry.attempts==`number`?d.retry.attempts:void 0,continues:d.on_failure===`continue`,branch:s,lane:u,path:l,stage:v,occurrence:f(v),...c?{resume:c}:{}}}),g&&a.set(g,_);let y=p?.on?`{{ ${p.on} }}`:``;for(let e of pY([d.settings,y],d.when))o.push({from:e,to:_});return _},m=(e,t,n)=>{e.forEach((r,a)=>i.push({id:`flow-${r}-${t}`,source:r,target:t,kind:`flow`,...s.has(r)?{otherwise:!0}:{},insertAfter:a===e.length-1?n:void 0}))};for(let[e,t]of n.entries()){let n=zJ(t);if(n){let{kind:i,base:a,branches:o}=n,c=p(t,String(e+1),0,u*aY,void 0,void 0,[`steps`,e]);m(l,c,[`steps`,e-1]),u++;let d=uY(t)&&typeof t.id==`string`?t.id:i,f=i===`switch`&&!o.some(([e])=>e==="default"),h=o.length+ +!!f,g=[],_=0;o.forEach(([t,n],o)=>{let s=(o-(h-1)/2)*oY,l=[c],f=[`steps`,e,...a,t];n.forEach((n,r)=>{let a=p(n,`${e+1}-${t}-${r+1}`,s,(u+r)*aY,t,d,[...f,r],i);m(l,a,[...f,r-1]),l=[a]}),_=Math.max(_,n.length);let v=`add-${e}-${t}`;r.push({id:v,type:`add`,position:{x:s+104,y:(u+n.length)*aY},data:{kind:`step`,key:v,title:``,type:``,detail:``,branch:t,lane:i,insertAfter:[...f,n.length-1]}}),m(l,v),g.push(v)});let v=(Math.max(_,1)+1)*aY-24;o.forEach(([t],n)=>{let a=(n-(h-1)/2)*oY;r.push({id:`lane-${e}-${t}`,type:`lane`,position:{x:a-12,y:u*aY-40},style:{width:`264px`,height:`${v}px`},zIndex:-1,data:{kind:`step`,key:t,title:t,type:``,detail:``,lane:i}})}),f&&(g.push(c),s.add(c)),l=g,u+=Math.max(_,1)+1;continue}let i=p(t,String(e+1),0,u*aY,void 0,void 0,[`steps`,e]);m(l,i,[`steps`,e-1]),l=[i],u++}r.push({id:`add-end`,type:`add`,position:{x:104,y:u*aY-24},data:{kind:`step`,key:`add`,title:``,type:``,detail:``,insertAfter:[`steps`,n.length-1]}}),m(l,`add-end`);for(let{from:e,to:t}of o){let n=a.get(e);n&&(i.some(e=>e.kind===`flow`&&e.source===n&&e.target===t)||i.push({id:`data-${n}-${t}`,source:n,target:t,kind:`data`,label:e,offset:24+14*i.filter(e=>e.kind===`data`).length,sourceHandle:`data-out`,targetHandle:`data-in`}))}return{nodes:r,edges:i}}var hY={agent:Es,command:mc,repo:Hs,gate:uc,forge:Xs,human:_c,review:zs,workflow:bc},gY={agent:`Agents`,command:`Commands`,repo:`Repository`,gate:`Checks`,forge:`Issues and PRs`,human:`People`,review:`Review`,workflow:`Flow`};function _Y(e){return e===`parallel`?Hs:e===`switch`?fc:hY[e.split(`.`)[0]]??bc}function vY(e){return Object.keys(gY).map(t=>({title:gY[t],icon:hY[t],types:e.filter(e=>e.split(`.`)[0]===t)})).filter(e=>e.types.length)}var yY=k({__name:`WorkflowPicker`,props:{value:{},workflows:{},label:{}},emits:[`pick`],setup(e,{emit:t}){let n=t;return(t,r)=>(R(),K(z(Cl),{"model-value":e.value||void 0,"onUpdate:modelValue":r[0]||=e=>n(`pick`,String(e))},{default:j(()=>[M(z(Al),{"aria-label":e.label},{default:j(()=>[M(z(jl),{placeholder:`Choose workflow`})]),_:1},8,[`aria-label`]),M(z(wl),null,{default:j(()=>[e.value&&!e.workflows.some(t=>t.id===e.value)?(R(),K(z(Dl),{key:0,value:e.value,disabled:``},{default:j(()=>[A(B(e.value)+` (unavailable)`,1)]),_:1},8,[`value`])):L(``,!0),(R(!0),W(V,null,G(e.workflows,e=>(R(),K(z(Dl),{key:e.id,value:e.id},{default:j(()=>[A(B(e.id),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1},8,[`model-value`]))}});function bY(e){return e.ok?`Valid`:e.line?`Line ${e.line}: ${e.message}`:e.message}function xY(e,t=[]){let n=PJ(e),r=n.errors[0];if(r)return{ok:!1,message:FY(r.message),line:r.linePos?.[0]?.line};let i=n.toJS();if(!IY(i))return{ok:!1,message:`A workflow is a mapping with an id and steps.`};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,message:`workflow id is required`};let o=i.steps;if(o==null||o===``)return{ok:!1,message:`workflow ${a} has no steps`};if(!Array.isArray(o))return{ok:!1,message:`workflow ${a}: steps must be a list`};if(!o.length)return{ok:!1,message:`workflow ${a} has no steps`};let s=new Map(t.map(e=>[e.name,e])),c=typeof i.repository==`string`&&i.repository.trim()?i.repository.trim():`required`,l=[],u=new Set;for(let[e,t]of o.entries()){let n=`workflow ${a} step ${e+1}`,r=zJ(t);if(r){if(r.kind===`switch`&&!r.on)return{ok:!1,message:`${n}: switch.on Line truncated
`).map((e,t)=>({number:t+1,text:e,tokens:jY(e)}))}var kY=/^(\s*)(-\s+)?/,AY=/^([^:#\s][^:#]*?)(:)(\s*)(.*)$/;function jY(e){let{code:t,comment:n}=MY(e),r=NY(t);return n&&r.push({text:n,kind:`comment`}),r}function MY(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(t)r===t&&(t=``);else if(r===`"`||r===`'`)t=r;else if(r===`#`&&(n===0||/\s/.test(e[n-1]??``)))return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:``}}function NY(e){if(!e)return[];let t=[],n=kY.exec(e);n?.[1]&&t.push({text:n[1],kind:`plain`}),n?.[2]&&t.push({text:n[2],kind:`punct`});let r=e.slice(n?.[0].length??0);if(!r)return t;let i=AY.exec(r);return i?(t.push({text:i[1]??``,kind:`key`}),t.push({text:i[2]??`:`,kind:`punct`}),i[3]&&t.push({text:i[3],kind:`plain`}),[...t,...PY(i[4]??``)]):[...t,...PY(r)]}function PY(e){if(!e)return[];let t=/^("[^"]*"?|'[^']*'?)([\s\S]*)$/.exec(e);if(!t)return[{text:e,kind:`plain`}];let n=[{text:t[1]??``,kind:`string`}];return t[2]&&n.push({text:t[2],kind:`plain`}),n}function FY(e){return e.split(`
`)[0]?.trim()||`invalid YAML`}function IY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function LY(e){return typeof e==`string`&&e.trim()!==``}var RY={class:`flex h-full w-[24rem] flex-col border-l border-border bg-card shadow-xl`},zY={class:`flex items-center gap-2.5 border-b border-border px-4 py-3`},BY={class:`flex size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-primary`},VY={class:`min-w-0 flex-1`},HY={class:`truncate font-mono text-[11px] text-fg-subtle`},UY={class:`flex-1 space-y-5 overflow-y-auto px-4 py-4`},WY={key:0,class:`rounded-md bg-danger/10 px-2.5 py-1.5 text-xs text-danger`,role:`alert`},GY={key:1,class:`space-y-3`},KY={key:0,class:`block space-y-1.5`},qY={id:`switch-on`},JY=[`value`],YY={class:`text-xs font-medium text-muted-foreground`},XY={class:`flex items-center gap-2`},ZY={key:1,role:`alert`,class:`text-xs text-danger`},QY={key:2,class:`space-y-1.5`},$Y=[`title`],eX={key:4,class:`flex flex-wrap items-center gap-1 pt-0.5`},tX={key:3,class:`divide-y divide-border rounded-md border border-border`},nX=[`title`],rX={key:0,class:`space-y-3`},iX={class:`text-[13px]`},aX={key:0,class:`text-danger`},oX={class:`ml-2 text-xs text-fg-subtle`},sX={key:1,class:`space-y-3`},cX={class:`text-[13px]`},lX={class:`ml-2 text-xs text-fg-subtle`},uX=[`title`],dX={key:0,class:`text-xs text-danger`},fX={class:`space-y-2`},pX={class:`divide-y divide-border rounded-md border border-border`},mX={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},hX={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},gX={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},_X={class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},vX={class:`flex items-center border-t border-border px-4 py-2.5`},yX=k({__name:`StepEditor`,props:{yaml:{},path:{},vocabulary:{},workflows:{},modelAliases:{}},emits:[`update:yaml`,`close`,`remove`],setup(e,{emit:t}){let n=e,i=t,a=I(()=>VJ(n.yaml,n.path)??{}),o=I(()=>zJ(a.value)),s=I(()=>o.value?.kind??(typeof a.value.type==`string`?a.value.type:``)),c=I(()=>o.value?.branches.map(([e])=>e)??[]),l=I(()=>s.value===`parallel`?2:1);function u(e){i(`update:yaml`,HJ(n.yaml,n.path,{...a.value,switch:{...a.value.switch,on:e}}))}let d=q(``),f=q(``);function p(e,t,r=``){try{let a=e===`add`?KJ(n.yaml,n.path,t):e===`rename`?qJ(n.yaml,n.path,t,r):JJ(n.yaml,n.path,t);i(`update:yaml`,a),d.value=``,f.value=``}catch(e){f.value=String(e.message)}}let m=I(()=>n.vocabulary.find(e=>e.name===s.value)),h=I(()=>typeof a.value.settings==`object`&&a.value.settings!==null?a.value.settings:{}),g=I(()=>QJ(n.yaml,n.path)),_=I(()=>m.value?.settings&&a.value.settings?EY(a.value.settings,m.value.settings,`settings`):``),v=[`mission`,`workflow`,`message`,`body`,`plan`,`then`,`status`,`detail`,`run`,`rules`],y=/mission|body|detail|plan|rules/;function b(e,t){return[`workflow.call`,`workflow.handoff`].includes(s.value)&&e===`workflow`||s.value===`human.approve`&&e===`then`?`workflow`:s.value===`agent.run`&&e===`model`?`select`:t.type===`string`?t.enum?`select`:y.test(e)?`text`:`line`:t.type===`boolean`?`boolean`:t.type===`integer`||t.type===`number`?`number`:t.type===`array`&&t.items?.type===`string`?`lines`:`yaml`}let x=I(()=>{let e=Object.entries(m.value?.settings?.properties??{}).filter(([e])=>s.value!==`workflow.call`||![`inputs`,`outputs`].includes(e)).map(([e,t])=>({key:e,schema:t,kind:b(e,t),options:s.value===`agent.run`&&e===`model`?n.modelAliases:t.enum??[]})),t=e.filter(e=>v.includes(e.key)&&e.kind!==`boolean`).sort((e,t)=>v.indexOf(e.key)-v.indexOf(t.key))[0],r=e.filter(e=>e!==t);return{lead:t,compact:r.filter(e=>[`workflow`,`select`,`line`,`number`,`boolean`].includes(e.kind)),long:r.filter(e=>[`text`,`lines`,`yaml`].includes(e.kind))}});function S(e){let{id:t,type:r,...a}=e;i(`update:yaml`,HJ(n.yaml,n.path,{id:t,type:r,...a}))}function C(e,t){S({...a.value,[e]:t})}function w(e){C(`retry`,{...a.value.retry,...e})}function T(e,t){let n={...h.value,[e]:t};s.value===`workflow.call`&&e===`wait`&&t!==!0&&delete n.outputs,S({...a.value,settings:n})}function ee(e,t){let n={...h.value,[e]:t};s.value===`workflow.call`&&t!==h.value[e]&&(delete n.inputs,delete n.outputs),S({...a.value,settings:n})}let E=I(()=>n.workflows.find(e=>e.id===h.value.workflow)),D=I(()=>Object.entries(eY(E.value?.yaml??``,`inputs`)??{})),te=I(()=>Object.entries(eY(E.value?.yaml??``,`outputs`)??{})),ne=I(()=>Object.entries(eY(n.yaml,`inputs`)??{})),re=I(()=>Object.entries(eY(n.yaml,`outputs`)??{})),ie=I(()=>h.value.inputs??{}),O=I(()=>h.value.outputs??{}),ae=e=>typeof e==`string`&&e.startsWith(`inputs.`),oe=e=>ie.value[e]===void 0?``:String(ie.value[e]);function se(e,t,n){T(`inputs`,{...ie.value,[e]:t===``?void 0:ae(t)?t:Vv(t,n??`string`)})}let ce=q(null);function le(e,t){let n=ce.value??x.value.lead?.key;if(!n)return;let r=typeof h.value[n]==`string`?h.value[n]:``,i=`{{ steps.${e}.${t} }}`;T(n,r?`${r.trimEnd()} ${i}`:i)}let ue=q({});function de(e,t){try{T(e,t.trim()?FJ(t):void 0),ue.value={...ue.value,[e]:``}}catch(t){ue.val Line truncated
`)[0]}}}let fe=e=>e===void 0?``:IJ(e).trimEnd(),pe=(e,t)=>t.title??e.replaceAll(`_`,` `).replace(/^./,e=>e.toUpperCase()),me=e=>typeof h.value[e]==`string`?h.value[e]:``;return(t,n)=>(R(),W(`aside`,RY,[U(`header`,zY,[U(`span`,BY,[(R(),K(et(z(_Y)(s.value)),{class:`size-4`}))]),U(`div`,VY,[M(z(Z),{"model-value":a.value.id??``,class:`h-7 truncate border-transparent px-1 font-medium shadow-none hover:border-input dark:bg-transparent`,placeholder:z(cY)(s.value),"aria-label":`Step id`,"onUpdate:modelValue":n[0]||=e=>C(`id`,String(e))},null,8,[`model-value`,`placeholder`]),U(`div`,HY,B(s.value),1)]),M(z(Y),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Close`,onClick:n[1]||=e=>i(`close`)},{default:j(()=>[M(z(Sc))]),_:1})]),U(`div`,UY,[_.value?(R(),W(`p`,WY,B(_.value),1)):L(``,!0),o.value?(R(),W(`section`,GY,[s.value===`switch`?(R(),W(`label`,KY,[n[18]||=U(`span`,{class:`text-xs font-medium text-muted-foreground`,title:`The value whose case runs; a case named default runs when none matches`},`Switch on`,-1),M(z(Z),{"model-value":o.value.on,class:`font-mono`,placeholder:`steps.assess.result.fit`,list:`switch-on`,onChange:n[2]||=e=>u(e.target.value.trim())},null,8,[`model-value`]),U(`datalist`,qY,[(R(!0),W(V,null,G(g.value,e=>(R(),W(`option`,{key:e,value:`steps.${e}.result.`},null,8,JY))),128))])])):L(``,!0),U(`div`,YY,B(s.value===`switch`?`Cases`:`Branches`),1),(R(!0),W(V,null,G(c.value,e=>(R(),W(`div`,{key:e,class:`flex items-center gap-2`},[M(z(Z),{"model-value":e,class:N(s.value===`switch`&&`font-mono`),"aria-label":`${s.value===`switch`?`Case`:`Branch`} ${e}`,onChange:t=>p(`rename`,e,t.target.value.trim())},null,8,[`model-value`,`class`,`aria-label`,`onChange`]),M(z(Y),{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":`Remove ${e}`,disabled:c.value.length<=l.value,onClick:t=>p(`delete`,e)},{default:j(()=>[M(z(r))]),_:1},8,[`aria-label`,`disabled`,`onClick`])]))),128)),U(`div`,XY,[M(z(Z),{modelValue:d.value,"onUpdate:modelValue":n[3]||=e=>d.value=e,"aria-label":s.value===`switch`?`New case value`:`New branch name`,placeholder:s.value===`switch`?`Value, or default`:`Branch name`,onKeydown:n[4]||=jt(Nt(e=>p(`add`,d.value.trim()),[`prevent`]),[`enter`])},null,8,[`modelValue`,`aria-label`,`placeholder`]),M(z(Y),{type:`button`,size:`icon-sm`,variant:`outline`,"aria-label":s.value===`switch`?`Add case`:`Add branch`,disabled:!d.value.trim(),onClick:n[5]||=e=>p(`add`,d.value.trim())},{default:j(()=>[M(z(rc))]),_:1},8,[`aria-label`,`disabled`])]),f.value?(R(),W(`p`,ZY,B(f.value),1)):L(``,!0)])):L(``,!0),x.value.lead?(R(),W(`section`,QY,[U(`div`,{class:`flex items-center gap-1 text-xs font-medium text-muted-foreground`,title:x.value.lead.schema.description},[A(B(pe(x.value.lead.key,x.value.lead.schema))+` `,1),x.value.lead.schema.description?(R(),K(z(Ps),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,$Y),x.value.lead.kind===`workflow`?(R(),K(yY,{key:0,value:me(x.value.lead.key),workflows:e.workflows,label:pe(x.value.lead.key,x.value.lead.schema),onPick:n[6]||=e=>ee(x.value.lead.key,e)},null,8,[`value`,`workflows`,`label`])):x.value.lead.kind===`select`?(R(),K(z(kv),{key:1,size:`sm`,class:`w-full`,"model-value":me(x.value.lead.key),"onUpdate:modelValue":n[7]||=e=>T(x.value.lead.key,String(e)||void 0)},{default:j(()=>[M(z(Av),{value:``},{default:j(()=>[...n[19]||=[A(`Default`,-1)]]),_:1}),(R(!0),W(V,null,G(x.value.lead.options,e=>(R(),K(z(Av),{key:e,value:e},{default:j(()=>[A(B(e),1)]),_:2},1032,[`value`]))),128))]),_:1},8,[`model-value`])):x.value.lead.kind===`text`?(R(),K(z(Jl),{key:2,"model-value":me(x.value.lead.key),class:`min-h-40 text-[13px] leading-relaxed`,onFocus:n[8]||=e=>ce.value=x.value.lead.key,"onUpdate:modelValue":n[9]||=e=>T(x.value.lead.key,String(e))},null,8,[`model-value`])):(R(),K(z(Z),{key:3,"model-value":me(x.value.lead.key),onFocus:n[10]||=e=>ce.value=x.value.lead.key,"onUpdate:modelValue":n[11]||=e=>T(x.value.lead.key,String(e))},null,8,[`model-value`])),g.value.length&&x.value.lead.kind!==`select`?(R(),W(`div`,eX,[n[20]||=U(`span`,{class:`text-[11px] text-fg-subtle`},`Insert`,-1),(R(!0),W(V,null,G(g.value,e=>(R(),W(V,{key:e},[M(z(Y),{type:`button`,variant:`outline`,size:`xs`,class:`font-mono`,onClick:t=>le(e,`summary`)},{default:j(()=>[A(B(e),1)]),_:2},1032,[`onClick`]),M(z(Y),{type:`button`,variant:`outline`,size:`xs`,class:`font-mono`,onClick:t=>le(e,`result`)},{default:j(()=>[A(B(e)+`.result`,1)]),_:2},1032,[`onClick`])],64))),128))])):L(``,!0)])):L(``,!0),x.value.compact.length?(R(),W(`section`,tX,[(R(!0),W(V,null,G(x.value.compact,t=>(R(),W(`div`,{key:t.key,class:`flex min-h-10 items-center gap-3 px-3 py-1.5`},[U(`span`,{class:`flex flex-1 items-center gap-1 text-[13px]`,title:t.schema.description},[A(B(pe(t.key,t.schema))+` `,1),t.schema.description?(R(),K(z(Ps),{key:0,class:`size-3 text-fg-subtle`})):L(``,!0)],8,nX),t.kind===`workflow`?(R(),K(yY,{key:0,class:`max-w-48`,value:me(t.key),workflows:e.workflows,label:pe(t.key,t.schema),onPick:e=>ee(t.key,e)},null,8,[`vaLine truncated
`):``,class:`min-h-16 font-mono text-xs`,placeholder:`One per line`,"onUpdate:modelValue":t=>T(e.key,String(t).split(`
`).filter(Boolean))},null,8,[`model-value`,`onUpdate:modelValue`])):(R(),W(V,{key:2},[M(z(Jl),{"model-value":fe(h.value[e.key]),class:`min-h-24 font-mono text-xs`,placeholder:`YAML`,onChange:t=>de(e.key,t.target.value)},null,8,[`model-value`,`onChange`]),ue.value[e.key]?(R(),W(`span`,dX,B(ue.value[e.key]),1)):L(``,!0)],64))]))),128)),U(`section`,fX,[n[37]||=U(`div`,{class:`text-xs font-medium text-muted-foreground`},`Flow`,-1),U(`div`,pX,[U(`label`,mX,[n[31]||=U(`span`,{class:`flex-1 text-[13px]`},`Run only when`,-1),M(z(Z),{class:`h-7 w-48 font-mono text-xs`,placeholder:`always`,"model-value":a.value.when??``,"onUpdate:modelValue":n[12]||=e=>C(`when`,String(e))},null,8,[`model-value`])]),U(`label`,hX,[n[34]||=U(`span`,{class:`flex-1 text-[13px]`},`If it fails`,-1),M(z(kv),{size:`sm`,"model-value":a.value.on_failure??``,"onUpdate:modelValue":n[13]||=e=>C(`on_failure`,String(e)||void 0)},{default:j(()=>[M(z(Av),{value:``},{default:j(()=>[...n[32]||=[A(`Park the task`,-1)]]),_:1}),M(z(Av),{value:`continue`},{default:j(()=>[...n[33]||=[A(`Continue`,-1)]]),_:1})]),_:1},8,[`model-value`])]),U(`label`,gX,[n[35]||=U(`span`,{class:`flex-1 text-[13px]`},`Attempts`,-1),M(z(Z),{type:`number`,min:`1`,max:`10`,placeholder:`1`,class:`h-7 w-20 text-right text-[13px]`,"model-value":a.value.retry?.attempts??``,"onUpdate:modelValue":n[14]||=e=>w({attempts:String(e)===``?void 0:Number(String(e))})},null,8,[`model-value`])]),U(`label`,_X,[n[36]||=U(`span`,{class:`flex-1 text-[13px]`},`Retry backoff`,-1),M(z(ph),{"model-value":a.value.retry?.backoff??``,units:[`s`,`m`,`h`],"onUpdate:modelValue":n[15]||=e=>w({backoff:e||void 0})},null,8,[`model-value`])])])])]),U(`footer`,vX,[M(z(Y),{type:`button`,variant:`ghost`,size:`sm`,class:`text-danger`,onClick:n[16]||=e=>i(`remove`)},{default:j(()=>[M(z(r)),n[38]||=A(`Delete step`,-1)]),_:1}),M(z(Y),{type:`button`,size:`sm`,class:`ml-auto`,onClick:n[17]||=e=>i(`close`)},{default:j(()=>[...n[39]||=[A(`Done`,-1)]]),_:1})])]))}}),bX=`repository_path`;function xX(e,t,n){let r=[];for(let[n,i]of e){let e=t[n];e?.from===`path`&&e.path.trim()&&r.push({name:n,path:e.path.trim(),type:i.type??`string`,required:i.required===!0})}return n.trim()&&r.push({name:bX,path:n.trim(),type:`string`,required:!0}),r}function SX(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e==`boolean`?`bool`:typeof e==`object`?`object`:typeof e}function CX(e,t,n){let r=[];for(let[i,a]of e){let e=t[i],o=a.type??`string`;if(!(e&&(e.from===`path`?e.path.trim():e.value!==``))){a.required&&r.push(`${i} is required`);continue}if(e.from===`path`){let e=n?.failures?.find(e=>e.field_name===i);e&&r.push(`${i}: ${e.reason}`);continue}let s=SX(Cb(e.value,o));o!==`any`&&s!==o&&r.push(`${i} is ${o}, but ${JSON.stringify(e.value)} is not`)}return n?.failures?.some(e=>e.field_name===`repository_path`)&&r.push(`the repository path does not resolve`),r}function wX(e,t){let n={};for(let[r,i]of e){let e=t[r];e?.from===`path`&&e.path.trim()?n[r]={param:r}:e?.from===`value`&&e.value!==``&&(n[r]={value:Cb(e.value,i.type??`string`)})}return n}function TX(e,t){let n=e=>t.find(t=>t.name===e)?.path??``,r={};for(let[t,i]of Object.entries(e.inputs??{}))r[t]=i.param?{from:`path`,path:n(i.param),value:``}:{from:`value`,path:``,value:typeof i.value==`string`?i.value:JSON.stringify(i.value)};return{rows:r,repositoryPath:n(e.repo_param)}}function EX(e,t=``){return Array.isArray(e)?e.slice(0,3).flatMap((e,n)=>{let r=`${t}[${n}]`;return[r,...EX(e,r)]}):e&&typeof e==`object`?Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return[r,...EX(n,r)]}):[]}function DX(e){try{return e?.body?JSON.parse(e.body):null}catch{return null}}function OX(e){try{let t=JSON.parse(e.headers??`{}`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t)]))}catch{return{}}}function kX(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>80?`${t.slice(0,80)}…`:t}var AX={class:`flex h-full flex-col`},jX={class:`flex items-center gap-2 border-b border-border px-4 py-3`},MX={class:`min-w-0 flex-1 truncate text-sm font-medium`},NX={key:0,class:`flex flex-1 items-center justify-center`},PX={class:`space-y-1.5`},FX={key:1,class:`space-y-1.5`},IX=[`title`],LX={class:`space-y-1.5`},RX={id:`bind-paths`},zX=[`value`],BX={class:`divide-y divide-border rounded-md border border-border`},VX={class:`flex items-center gap-1.5 text-xs`},HX={class:`font-mono`},UX={class:`text-fg-subtle`},WX={key:0,class:`text-danger`,title:`Required`},GX={key:2,class:`text-xs text-danger`},KX=[`title`],qX={key:0,class:`space-y-1 px-3 py-2`},JX={key:0,class:`text-xs text-danger`},YX={key:1,class:`truncate font-mono text-xs text-success`},XX={key:1,class:`px-3 py-2 text-xs text-fg-subtle`},ZX={class:`space-y-2`},QX={key:0,role:`alert`,class:`text-xs text-danger`},$X={key:1,class:`text-xs text-fg-subtle`},eZ={class:`flex flex-wrap gap-2`},tZ=`__new__`,nZ=k({__name:`BindEvent`,props:{yaml:{},binding:{}},emits:[`back`,`saved`],setup(e,{emit:t}){let n Line truncated
`).replace(`
`,`
+`).split(`
`).map(e=>e.trim().toLowerCase());if(i.length===1)return e.toLowerCase()===t.toLowerCase();r||n.add(e.toLowerCase());let a=i.every((e,t)=>n.has(e)&&Array.from(n.values())[t]===i[t]);return r&&n.delete(e.toLowerCase()),a}function k4(e,t){return n=>{if(!n.code&&!n.key)return!1;let r=A4(n.code,e);return Array.isArray(e)?e.some(e=>O4(n[r],e,t,n.type===`keyup`)):O4(n[r],e,t,n.type===`keyup`)}}function A4(e,t){return t.includes(e)?`code`:`key`}function j4(e,t){let n=I(()=>qe(t?.target)??T4),r=nt(qe(e)===!0),i=!1,a=new Set,o=c(qe(e));F(()=>qe(e),(e,t)=>{typeof t==`boolean`&&typeof e!=`boolean`&&s(),o=c(e)},{immediate:!0}),CZ([`blur`,`contextmenu`],s),TZ((...e)=>o(...e),e=>{let n=qe(t?.actInsideInputWithModifier)??!0,a=qe(t?.preventDefault)??!1;if(i=D4(e),(!i||i&&!n)&&E4(e))return;let o=e.composedPath?.call(e)?.[0]||e.target,s=o?.nodeName===`BUTTON`||o?.nodeName===`A`;!a&&(i||!s)&&e.preventDefault(),r.value=!0},{eventName:`keydown`,target:n}),TZ((...e)=>o(...e),e=>{let n=qe(t?.actInsideInputWithModifier)??!0;if(r.value){if((!i||i&&!n)&&E4(e))return;i=!1,r.value=!1}},{eventName:`keyup`,target:n});function s(){i=!1,a.clear(),r.value=qe(e)===!0}function c(e){return e===null?(s(),()=>!1):typeof e==`boolean`?(s(),r.value=e,()=>!1):Array.isArray(e)||typeof e==`string`?k4(e,a):e}return r}var M4=`vue-flow__node-desc`,N4=`vue-flow__edge-desc`,P4=`vue-flow__aria-live`,F4=[`Enter`,` `,`Escape`],I4={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};function L4(e){return{...e.computedPosition||{x:0,y:0},width:e.dimensions.width||0,height:e.dimensions.height||0}}function R4(e,t){let n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)}function z4(e){return{width:e.offsetWidth,height:e.offsetHeight}}function B4(e,t=0,n=1){return Math.min(Math.max(e,t),n)}function V4(e,t){return{x:B4(e.x,t[0][0],t[1][0]),y:B4(e.y,t[0][1],t[1][1])}}function H4(e){let t=e.getRootNode();return`elementFromPoint`in t?t:window.document}function U4(e){return e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e}function W4(e){return e&&typeof e==`object`&&`id`in e&&`position`in e&&!U4(e)}function G4(e){return W4(e)&&`computedPosition`in e}function K4(e){return!Number.isNaN(e)&&Number.isFinite(e)}function q4(e){return K4(e.width)&&K4(e.height)&&K4(e.x)&&K4(e.y)}function J4(e,t,n){let r={id:e.id.toString(),type:e.type??`default`,dimensions:Tt({width:0,height:0}),computedPosition:Tt({z:0,...e.position}),handleBounds:{source:[],target:[]},draggable:void 0,selectable:void 0,connectable:void 0,focusable:void 0,selected:!1,dragging:!1,resizing:!1,initialized:!1,isParent:!1,position:{x:0,y:0},data:d6(e.data)?e.data:{},events:Tt(d6(e.events)?e.events:{})};return Object.assign(t??r,e,{id:e.id.toString(),parentNode:n})}function Y4(e,t,n){let r={id:e.id.toString(),type:e.type??t?.type??`default`,source:e.source.toString(),target:e.target.toString(),sourceHandle:e.sourceHandle?.toString(),targetHandle:e.targetHandle?.toString(),updatable:e.updatable??n?.updatable,selectable:e.selectable??n?.selectable,focusable:e.focusable??n?.focusable,data:d6(e.data)?e.data:{},events:Tt(d6(e.events)?e.events:{}),label:e.label??``,interactionWidth:e.interactionWidth??n?.interactionWidth,...n??{}};return Object.assign(t??r,e,{id:e.id.toString()})}function X4(e,t,n,r){let i=typeof e==`string`?e:e.id,a=new Set,o=r===`source`?`target`:`source`;for(let e of n)e[o]===i&&a.add(e[r]);return t.filter(e=>a.has(e.id))}function Z4(...e){if(e.length===3){let[t,n,r]=e;return X4(t,n,r,`target`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>U4(e)&&e.source===r).map(e=>n.find(t=>W4(t)&&t.id===e.target))}function Q4(...e){if(e.length===3){let[t,n,r]=e;return X4(t,n,r,`source`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>U4(e)&&e.target===r).map(e=>n.find(t=>W4(t)&&t.id===e.source))}function $4({source:e,sourceHandle:t,target:n,targetHandle:r}){return`vueflow__edge-${e}${t??``}-${n}${r??``}`}function e3(e,t){return t.some(t=>U4(t)&&t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle))}function t3({x:e,y:t},{x:n,y:r,zoom:i}){return{x:e*i+n,y:t*i+r}}function n3({x:e,y:t},{x:n,y:r,zoom:i},a=!1,o=[1,1]){let s={x:(e-n)/i,y:(t-r)/i};return a?J3(s,o):s}function r3(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}}function i3({x:e,y:t,width:n,height:r}){return{x:e,y:t,x2:e+n,y2:t+r}}function a3({x:e,y:t,x2:n,y2:r}){return{x:e,y:t,width:n-e,height:r-t}}function o3(e){let t={x:1/0,y:1/0,x2:-1/0,y2:-1/0};for(let n=0;n<e.length;n++){let r=e[n];t=r3(t,i3({...r.computedPosition,...r.dimensions}))}return a3(t)}function s3(e,t,n={x:0,y:0,zoom:1},r=!1,i=!1){let a={...n3(t,n),width:t.width/n.zoom,height:t.height/n.zoom},o=[];for(let t of e){let{dimensions:e,selectable:n=!0,hidden:s= Line truncated
`).map(e=>e.trim().toLowerCase());if(i.length===1)return e.toLowerCase()===t.toLowerCase();r||n.add(e.toLowerCase());let a=i.every((e,t)=>n.has(e)&&Array.from(n.values())[t]===i[t]);return r&&n.delete(e.toLowerCase()),a}function i3(e,t){return n=>{if(!n.code&&!n.key)return!1;let r=a3(n.code,e);return Array.isArray(e)?e.some(e=>r3(n[r],e,t,n.type===`keyup`)):r3(n[r],e,t,n.type===`keyup`)}}function a3(e,t){return t.includes(e)?`code`:`key`}function o3(e,t){let n=I(()=>Ue(t?.target)??e3),r=Qe(Ue(e)===!0),i=!1,a=new Set,o=c(Ue(e));F(()=>Ue(e),(e,t)=>{typeof t==`boolean`&&typeof e!=`boolean`&&s(),o=c(e)},{immediate:!0}),QZ([`blur`,`contextmenu`],s),eQ((...e)=>o(...e),e=>{let n=Ue(t?.actInsideInputWithModifier)??!0,a=Ue(t?.preventDefault)??!1;if(i=n3(e),(!i||i&&!n)&&t3(e))return;let o=e.composedPath?.call(e)?.[0]||e.target,s=o?.nodeName===`BUTTON`||o?.nodeName===`A`;!a&&(i||!s)&&e.preventDefault(),r.value=!0},{eventName:`keydown`,target:n}),eQ((...e)=>o(...e),e=>{let n=Ue(t?.actInsideInputWithModifier)??!0;if(r.value){if((!i||i&&!n)&&t3(e))return;i=!1,r.value=!1}},{eventName:`keyup`,target:n});function s(){i=!1,a.clear(),r.value=Ue(e)===!0}function c(e){return e===null?(s(),()=>!1):typeof e==`boolean`?(s(),r.value=e,()=>!1):Array.isArray(e)||typeof e==`string`?i3(e,a):e}return r}var s3=`vue-flow__node-desc`,c3=`vue-flow__edge-desc`,l3=`vue-flow__aria-live`,u3=[`Enter`,` `,`Escape`],d3={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};function f3(e){return{...e.computedPosition||{x:0,y:0},width:e.dimensions.width||0,height:e.dimensions.height||0}}function p3(e,t){let n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)}function m3(e){return{width:e.offsetWidth,height:e.offsetHeight}}function h3(e,t=0,n=1){return Math.min(Math.max(e,t),n)}function g3(e,t){return{x:h3(e.x,t[0][0],t[1][0]),y:h3(e.y,t[0][1],t[1][1])}}function _3(e){let t=e.getRootNode();return`elementFromPoint`in t?t:window.document}function v3(e){return e&&typeof e==`object`&&`id`in e&&`source`in e&&`target`in e}function y3(e){return e&&typeof e==`object`&&`id`in e&&`position`in e&&!v3(e)}function b3(e){return y3(e)&&`computedPosition`in e}function x3(e){return!Number.isNaN(e)&&Number.isFinite(e)}function S3(e){return x3(e.width)&&x3(e.height)&&x3(e.x)&&x3(e.y)}function C3(e,t,n){let r={id:e.id.toString(),type:e.type??`default`,dimensions:xt({width:0,height:0}),computedPosition:xt({z:0,...e.position}),handleBounds:{source:[],target:[]},draggable:void 0,selectable:void 0,connectable:void 0,focusable:void 0,selected:!1,dragging:!1,resizing:!1,initialized:!1,isParent:!1,position:{x:0,y:0},data:B6(e.data)?e.data:{},events:xt(B6(e.events)?e.events:{})};return Object.assign(t??r,e,{id:e.id.toString(),parentNode:n})}function w3(e,t,n){let r={id:e.id.toString(),type:e.type??t?.type??`default`,source:e.source.toString(),target:e.target.toString(),sourceHandle:e.sourceHandle?.toString(),targetHandle:e.targetHandle?.toString(),updatable:e.updatable??n?.updatable,selectable:e.selectable??n?.selectable,focusable:e.focusable??n?.focusable,data:B6(e.data)?e.data:{},events:xt(B6(e.events)?e.events:{}),label:e.label??``,interactionWidth:e.interactionWidth??n?.interactionWidth,...n??{}};return Object.assign(t??r,e,{id:e.id.toString()})}function T3(e,t,n,r){let i=typeof e==`string`?e:e.id,a=new Set,o=r===`source`?`target`:`source`;for(let e of n)e[o]===i&&a.add(e[r]);return t.filter(e=>a.has(e.id))}function E3(...e){if(e.length===3){let[t,n,r]=e;return T3(t,n,r,`target`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>v3(e)&&e.source===r).map(e=>n.find(t=>y3(t)&&t.id===e.target))}function D3(...e){if(e.length===3){let[t,n,r]=e;return T3(t,n,r,`source`)}let[t,n]=e,r=typeof t==`string`?t:t.id;return n.filter(e=>v3(e)&&e.target===r).map(e=>n.find(t=>y3(t)&&t.id===e.source))}function O3({source:e,sourceHandle:t,target:n,targetHandle:r}){return`vueflow__edge-${e}${t??``}-${n}${r??``}`}function k3(e,t){return t.some(t=>v3(t)&&t.source===e.source&&t.target===e.target&&(t.sourceHandle===e.sourceHandle||!t.sourceHandle&&!e.sourceHandle)&&(t.targetHandle===e.targetHandle||!t.targetHandle&&!e.targetHandle))}function A3({x:e,y:t},{x:n,y:r,zoom:i}){return{x:e*i+n,y:t*i+r}}function j3({x:e,y:t},{x:n,y:r,zoom:i},a=!1,o=[1,1]){let s={x:(e-n)/i,y:(t-r)/i};return a?C6(s,o):s}function M3(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}}function N3({x:e,y:t,width:n,height:r}){return{x:e,y:t,x2:e+n,y2:t+r}}function P3({x:e,y:t,x2:n,y2:r}){return{x:e,y:t,width:n-e,height:r-t}}function F3(e){let t={x:1/0,y:1/0,x2:-1/0,y2:-1/0};for(let n=0;n<e.length;n++){let r=e[n];t=M3(t,N3({...r.computedPosition,...r.dimensions}))}return P3(t)}function I3(e,t,n={x:0,y:0,zoom:1},r=!1,i=!1){let a={...j3(t,n),width:t.width/n.zoom,height:t.height/n.zoom},o=[];for(let t of e){let{dimensions:e,selectable:n=!0,hidden:s= Line truncated
Node: ${e}`,NODE_NOT_FOUND:e=>`Node not found
Node: ${e}`,NODE_MISSING_PARENT:(e,t)=>`Node is missing a parent
Node: ${e}
@@ -158,6 +158,6 @@ Edge: ${e}
Source: ${t}
Target: ${n}`,EDGE_ORPHANED:e=>`Edge was orphaned (suddenly missing source or target) and has been removed
Edge: ${e}`,EDGE_NOT_FOUND:e=>`Edge not found
Edge: ${e}`,USEVUEFLOW_OPTIONS:()=>`The options parameter is deprecated and will be removed in the next major version. Please use the id parameter instead`},H3=class extends Error{constructor(e,...t){super(V3[e]?.call(V3,...t)),this.name=`VueFlowError`,this.code=e,this.args=t}};function U3(e){return`clientX`in e}function W3(e){return`sourceEvent`in e}function G3(e,t){let n=U3(e),r,i;return n?(r=e.clientX,i=e.clientY):`touches`in e&&e.touches.length>0?(r=e.touches[0].clientX,i=e.touches[0].clientY):`changedTouches`in e&&e.changedTouches.length>0?(r=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(r=0,i=0),{x:r-(t?.left??0),y:i-(t?.top??0)}}var K3=()=>typeof navigator<`u`&&(navigator==null?void 0:navigator.userAgent)?.indexOf(`Mac`)>=0;function q3(e){return{width:e.dimensions?.width??e.width??0,height:e.dimensions?.height??e.height??0}}function J3(e,t=[1,1]){return{x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}}var Y3=()=>!0;function X3(e){e?.classList.remove(`valid`,`connecting`,`vue-flow__handle-valid`,`vue-flow__handle-connecting`)}function Z3(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())R4(i,L4(e))>0&&r.push(e);return r}var Q3=250;function $3(e,t,n,r){let i=[],a=1/0,o=Z3(e,n,t+Q3);for(let n of o){let o=[...n.handleBounds?.source??[],...n.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=I3(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l<a?(i=[{...s,x:o,y:c}],a=l):l===a&&i.push({...s,x:o,y:c}))}}if(!i.length)return null;if(i.length>1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function e6(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=Y3},u,d,f,p){let m=a===`target`,h=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:g,y:_}=G3(e),v=o.elementFromPoint(g,_),y=v?.classList.contains(`${s}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){let e=t6(void 0,y),t=y.getAttribute(`data-nodeid`),a=y.getAttribute(`data-handleid`),o=y.classList.contains(`connectable`),s=y.classList.contains(`connectableend`);if(!t||!e)return b;let c={source:m?t:r,sourceHandle:m?a:i,target:m?r:t,targetHandle:m?i:a};b.connection=c,b.isValid=o&&s&&(n===b4.Strict?m&&e===`source`||!m&&e===`target`:t!==r||a!==i)&&l(c,{nodes:d,edges:u,sourceNode:f(c.source),targetNode:f(c.target)}),b.toHandle=i6(t,e,a,p,n,!0)}return b}function t6(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function n6(e,t){let n=null;return t?n=`valid`:e&&!t&&(n=`invalid`),n}function r6(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}function i6(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===b4.Strict?o.handleBounds?.[t]:[...o.handleBounds?.source??[],...o.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...I3(o,c,c.position,!0)}:c}var a6={[_4.Left]:_4.Right,[_4.Right]:_4.Left,[_4.Top]:_4.Bottom,[_4.Bottom]:_4.Top},o6=[`production`,`prod`];function s6(e,...t){c6()&&console.warn(`[Vue Flow]: ${e}`,...t)}function c6(){return!o6.includes(`production`)}function l6(e,t,n,r,i){let a=t.querySelectorAll(`.vue-flow__handle.${e}`);return a?.length?Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...z4(t)}}):null}function u6(e,t,n,r,i,a=!1,o){i.value=!1,e.selected?(a||e.selected&&t)&&(r([e]),Ct(()=>{o.blur()})):n([e])}function d6(e){return z(e)!==void 0}function f6(e,t,n,r){if(!e||!e.source||!e.target)return n(new H3(B3.EDGE_INVALID,e?.id??`[ID UNKNOWN]`)),!1;let i;return i=U4(e)?e:{...e,id:$4(e)},i=Y4(i,void 0,r),!e3(i,t)&&i}function p6(e,t,n,r,i){if(!t.source||!t.target)return i(new H3(B3.EDGE_INVALID,e.id)),!1;if(!n)return i(new H3(B3.EDGE_NOT_FOUND,e.id)),!1;let{id:a,...o}=e;return{...o,id:r?$4(t):a,source:t.source,target:t.target,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle}}function m6(e,t,n){let r={},i=[];for(let a=0;a<e.length;++a){let o=e[a];if(!W4(o)){n(new H3(B3.NODE_INVALID,o?.id));continue}let s=J4(o,t(o.id),o.parentNode);o.parentNode&&(r[o.parentNode]=!0),i[a]=s}for(let e of i){let a=t(e.parentNode)||i.find(t=>t.id===e.parentNode);e.parentNode&&!a&&n(new H3(B3.NODE_MISSING_PARENT,e.id,e.parentNode)),(e.parentNode||r[e.id])&&(r[e.id]&&(e.isParent=!0),a&&(a.isParent=!0))}return i}function h6(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function g6(e,t,n){e.clear();for(let t of n){let{source:n,target:r,sourceHandle:i=null,targetHandle:a=null}=t,o={edgeId:t.id,source:n,target:r,sourceHandle:i,targetHandle:a},s=`${n}-${i}--${r}-${a}`;h6(`source`,o,`${r}-${a}--Line truncated
Edge: ${e}`,USEVUEFLOW_OPTIONS:()=>`The options parameter is deprecated and will be removed in the next major version. Please use the id parameter instead`},_6=class extends Error{constructor(e,...t){super(g6[e]?.call(g6,...t)),this.name=`VueFlowError`,this.code=e,this.args=t}};function v6(e){return`clientX`in e}function y6(e){return`sourceEvent`in e}function b6(e,t){let n=v6(e),r,i;return n?(r=e.clientX,i=e.clientY):`touches`in e&&e.touches.length>0?(r=e.touches[0].clientX,i=e.touches[0].clientY):`changedTouches`in e&&e.changedTouches.length>0?(r=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(r=0,i=0),{x:r-(t?.left??0),y:i-(t?.top??0)}}var x6=()=>typeof navigator<`u`&&(navigator==null?void 0:navigator.userAgent)?.indexOf(`Mac`)>=0;function S6(e){return{width:e.dimensions?.width??e.width??0,height:e.dimensions?.height??e.height??0}}function C6(e,t=[1,1]){return{x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}}var w6=()=>!0;function T6(e){e?.classList.remove(`valid`,`connecting`,`vue-flow__handle-valid`,`vue-flow__handle-connecting`)}function E6(e,t,n){let r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(let e of t.values())p3(i,f3(e))>0&&r.push(e);return r}var D6=250;function O6(e,t,n,r){let i=[],a=1/0,o=E6(e,n,t+D6);for(let n of o){let o=[...n.handleBounds?.source??[],...n.handleBounds?.target??[]];for(let s of o){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;let{x:o,y:c}=d6(n,s,s.position,!0),l=Math.sqrt((o-e.x)**2+(c-e.y)**2);l>t||(l<a?(i=[{...s,x:o,y:c}],a=l):l===a&&i.push({...s,x:o,y:c}))}}if(!i.length)return null;if(i.length>1){let e=r.type===`source`?`target`:`source`;return i.find(t=>t.type===e)??i[0]}return i[0]}function k6(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:o,lib:s,flowId:c,isValidConnection:l=w6},u,d,f,p){let m=a===`target`,h=t?o.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:g,y:_}=b6(e),v=o.elementFromPoint(g,_),y=v?.classList.contains(`${s}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){let e=A6(void 0,y),t=y.getAttribute(`data-nodeid`),a=y.getAttribute(`data-handleid`),o=y.classList.contains(`connectable`),s=y.classList.contains(`connectableend`);if(!t||!e)return b;let c={source:m?t:r,sourceHandle:m?a:i,target:m?r:t,targetHandle:m?i:a};b.connection=c,b.isValid=o&&s&&(n===Y4.Strict?m&&e===`source`||!m&&e===`target`:t!==r||a!==i)&&l(c,{nodes:d,edges:u,sourceNode:f(c.source),targetNode:f(c.target)}),b.toHandle=N6(t,e,a,p,n,!0)}return b}function A6(e,t){return e||(t?.classList.contains(`target`)?`target`:t?.classList.contains(`source`)?`source`:null)}function j6(e,t){let n=null;return t?n=`valid`:e&&!t&&(n=`invalid`),n}function M6(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}function N6(e,t,n,r,i,a=!1){let o=r.get(e);if(!o)return null;let s=i===Y4.Strict?o.handleBounds?.[t]:[...o.handleBounds?.source??[],...o.handleBounds?.target??[]],c=(n?s?.find(e=>e.id===n):s?.[0])??null;return c&&a?{...c,...d6(o,c,c.position,!0)}:c}var P6={[K4.Left]:K4.Right,[K4.Right]:K4.Left,[K4.Top]:K4.Bottom,[K4.Bottom]:K4.Top},F6=[`production`,`prod`];function I6(e,...t){L6()&&console.warn(`[Vue Flow]: ${e}`,...t)}function L6(){return!F6.includes(`production`)}function R6(e,t,n,r,i){let a=t.querySelectorAll(`.vue-flow__handle.${e}`);return a?.length?Array.from(a).map(t=>{let a=t.getBoundingClientRect();return{id:t.getAttribute(`data-handleid`),type:e,nodeId:i,position:t.getAttribute(`data-handlepos`),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...m3(t)}}):null}function z6(e,t,n,r,i,a=!1,o){i.value=!1,e.selected?(a||e.selected&&t)&&(r([e]),yt(()=>{o.blur()})):n([e])}function B6(e){return z(e)!==void 0}function V6(e,t,n,r){if(!e||!e.source||!e.target)return n(new _6(h6.EDGE_INVALID,e?.id??`[ID UNKNOWN]`)),!1;let i;return i=v3(e)?e:{...e,id:O3(e)},i=w3(i,void 0,r),!k3(i,t)&&i}function H6(e,t,n,r,i){if(!t.source||!t.target)return i(new _6(h6.EDGE_INVALID,e.id)),!1;if(!n)return i(new _6(h6.EDGE_NOT_FOUND,e.id)),!1;let{id:a,...o}=e;return{...o,id:r?O3(t):a,source:t.source,target:t.target,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle}}function U6(e,t,n){let r={},i=[];for(let a=0;a<e.length;++a){let o=e[a];if(!y3(o)){n(new _6(h6.NODE_INVALID,o?.id));continue}let s=C3(o,t(o.id),o.parentNode);o.parentNode&&(r[o.parentNode]=!0),i[a]=s}for(let e of i){let a=t(e.parentNode)||i.find(t=>t.id===e.parentNode);e.parentNode&&!a&&n(new _6(h6.NODE_MISSING_PARENT,e.id,e.parentNode)),(e.parentNode||r[e.id])&&(r[e.id]&&(e.isParent=!0),a&&(a.isParent=!0))}return i}function W6(e,t,n,r,i,a){let o=i,s=r.get(o)||new Map;r.set(o,s.set(n,t)),o=`${i}-${e}`;let c=r.get(o)||new Map;if(r.set(o,c.set(n,t)),a){o=`${i}-${e}-${a}`;let s=r.get(o)||new Map;r.set(o,s.set(n,t))}}function G6(e,t,n){e.clear();for(let t of n){let{source:n,target:r,sourceHandle:i=null,targetHandle:a=null}=t,o={edgeId:t.id,source:n,target:r,sourceHandle:i,targetHandle:a},s=`${n}-${i}--${r}-${a}`;W6(`source`,o,`${r}-${a}--Line truncated
`),r=t.split(`
`),i=Array.from({length:n.length+1},()=>Array(r.length+1).fill(0));for(let e=n.length-1;e>=0;e--)for(let t=r.length-1;t>=0;t--)i[e][t]=n[e]===r[t]?i[e+1][t+1]+1:Math.max(i[e+1][t],i[e][t+1]);let a=[],o=0,s=0;for(;o<n.length&&s<r.length;)n[o]===r[s]?(a.push({kind:`same`,text:n[o++]}),s++):i[o+1][s]>=i[o][s+1]?a.push({kind:`del`,text:n[o++]}):a.push({kind:`add`,text:r[s++]});for(;o<n.length;)a.push({kind:`del`,text:n[o++]});for(;s<r.length;)a.push({kind:`add`,text:r[s++]});return a}function N7(e){let t=sJ(e).toJS(),n=new Map;for(let r of VJ(e).nodes){let{kind:e,path:i,stage:a,occurrence:o}=r.data;if(r.type!==`step`||e!==`step`||!i||a===void 0)continue;let s=t;for(let e of i)s=s?.[e];n.set(`${a}#${o??0}`,{node:r.id,signature:JSON.stringify(s??null)})}return n}function P7(e,t,n){let r=N7(e),i=N7(t),a={};for(let[e,t]of r){let r=i.get(e);r?r.signature!==t.signature&&(a[t.node]=`changed`):a[t.node]=n}return a}var F7={class:`grid h-[calc(100dvh-17rem)] min-h-[26rem] grid-cols-[18rem_1fr] gap-3`},I7={class:`min-h-0 divide-y divide-border overflow-y-auto rounded-lg border border-border`,"aria-label":`Revisions`},L7=[`aria-current`,`onClick`],R7={class:`flex items-center gap-2 text-sm`},z7={class:`font-mono text-xs text-fg-subtle`},B7=[`title`],V7={key:0,class:`px-3 py-2 text-sm text-muted-foreground`},H7={key:0,class:`flex min-h-0 flex-col gap-2`},U7={class:`flex items-center gap-2`},W7={class:`text-xs text-muted-foreground`},G7={key:0,class:`rounded-lg border border-border p-4 text-sm text-muted-foreground`},K7={key:1,class:`min-h-0 flex-1 overflow-auto rounded-lg border border-border py-2 font-mono text-[13px] leading-6`},q7={class:`inline-block w-4 select-none text-fg-subtle`},J7={key:2,class:`grid min-h-0 flex-1 grid-cols-2 gap-3`},Y7={class:`flex min-h-0 flex-col gap-1`},X7={class:`text-xs font-medium text-muted-foreground`},Z7={class:`min-h-0 flex-1`},Q7={class:`flex min-h-0 flex-col gap-1`},$7={class:`min-h-0 flex-1`},e9=k({__name:`WorkflowHistory`,props:yt({revisions:{},current:{},error:{}},{selected:{default:0},selectedModifiers:{},mode:{default:`yaml`},modeModifiers:{}}),emits:yt([`restore`],[`update:selected`,`update:mode`]),setup(e,{emit:t}){let n=e,r=t,i=Xe(e,`selected`),a=Xe(e,`mode`);F(()=>n.revisions,e=>{e.some(e=>e.version===i.value)||(i.value=(e.find(e=>e.yaml!==n.current)??e[0])?.version??0)},{immediate:!0});let o=I(()=>n.revisions.find(e=>e.version===i.value)),s=I(()=>o.value?.yaml??null),c=I(()=>s.value===null?[]:M7(s.value,n.current)),l=I(()=>s.value!==null&&s.value===n.current),u=I(()=>s.value===null?{}:P7(s.value,n.current,`removed`)),d=I(()=>s.value===null?{}:P7(n.current,s.value,`added`)),f={added:`default`,edited:`secondary`,removed:`destructive`};return(t,n)=>(R(),W(`div`,F7,[U(`ol`,I7,[(R(!0),W(V,null,G(e.revisions,e=>(R(),W(`li`,{key:e.version},[U(`button`,{type:`button`,class:N([`block w-full px-3 py-2 text-left hover:bg-secondary`,e.version===i.value&&`bg-secondary`]),"aria-current":e.version===i.value,onClick:t=>i.value=e.version},[U(`span`,R7,[U(`span`,z7,`v`+B(e.version),1),M(z(Jt),{variant:f[e.change]},{default:j(()=>[A(B(e.change),1)]),_:2},1032,[`variant`])]),U(`span`,{class:`mt-0.5 block truncate text-xs text-muted-foreground`,title:e.at},B(e.actor||`unknown`)+` · `+B(e.source||`unknown`)+` · `+B(z(Zh)(e.at)),9,B7)],10,L7)]))),128)),e.revisions.length?L(``,!0):(R(),W(`li`,V7,B(e.error||`No recorded changes`),1))]),o.value?(R(),W(`div`,H7,[U(`div`,U7,[M(z(zy),{modelValue:a.value,"onUpdate:modelValue":n[0]||=e=>a.value=e},{default:j(()=>[M(z(Vy),null,{default:j(()=>[M(z(Hy),{value:`yaml`},{default:j(()=>[...n[2]||=[A(`YAML`,-1)]]),_:1}),M(z(Hy),{value:`canvas`},{default:j(()=>[...n[3]||=[A(`Canvas`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`]),U(`span`,W7,B(l.value?`Same as the current definition`:`Compared with the current definition`),1),M(z(J),{type:`button`,size:`sm`,variant:`outline`,class:`ml-auto`,disabled:s.value===null||l.value,title:s.value===null?`Workflow removed`:void 0,onClick:n[1]||=e=>r(`restore`,s.value)},{default:j(()=>[M(z(qn),{"data-icon":`inline-start`}),n[4]||=A(` Restore this version`,-1)]),_:1},8,[`disabled`,`title`])]),s.value===null?(R(),W(`p`,G7,`Workflow removed in this revision.`)):a.value===`yaml`?(R(),W(`pre`,K7,[U(`code`,null,[(R(!0),W(V,null,G(c.value,(e,t)=>(R(),W(`span`,{key:t,class:N([`block min-h-6 px-3 whitespace-pre-wrap`,{"bg-ok/10":e.kind===`add`,"bg-danger/10 text-danger":e.kind===`del`}])},[U(`span`,q7,B(e.kind===`add`?`+`:e.kind===`del`?`-`:``),1),A(B(e.text),1)],2))),128))])])):(R(),W(`div`,J7,[U(`div`,Y7,[U(`span`,X7,`v`+B(o.value.version),1),U(`div`,Z7,[M(O7,{yaml:s.value,marks:u.value},null,8,[`yaml`,`marks`])])]),U(`div`,Q7,[n[5]||=U(`span`,{class:`text-xs font-medium text-muted-foreground`},`Current`,-1),U(`div`,$7,[M(O7,{yaml:e.current,marks:d.value},null,8,[`yaml`,`marks`])])])]))])):L(``,!0)]))}}),t9=`workflow-definitions`;function n9(e){let t=ae(),n=q([]),r=q(``);async function i(){try{n.value=await t.history(t9),r.value=``} Line truncated
`),i=Array.from({length:n.length+1},()=>Array(r.length+1).fill(0));for(let e=n.length-1;e>=0;e--)for(let t=r.length-1;t>=0;t--)i[e][t]=n[e]===r[t]?i[e+1][t+1]+1:Math.max(i[e+1][t],i[e][t+1]);let a=[],o=0,s=0;for(;o<n.length&&s<r.length;)n[o]===r[s]?(a.push({kind:`same`,text:n[o++]}),s++):i[o+1][s]>=i[o][s+1]?a.push({kind:`del`,text:n[o++]}):a.push({kind:`add`,text:r[s++]});for(;o<n.length;)a.push({kind:`del`,text:n[o++]});for(;s<r.length;)a.push({kind:`add`,text:r[s++]});return a}function c9(e){let t=PJ(e).toJS(),n=new Map;for(let r of mY(e).nodes){let{kind:e,path:i,stage:a,occurrence:o}=r.data;if(r.type!==`step`||e!==`step`||!i||a===void 0)continue;let s=t;for(let e of i)s=s?.[e];n.set(`${a}#${o??0}`,{node:r.id,signature:JSON.stringify(s??null)})}return n}function l9(e,t,n){let r=c9(e),i=c9(t),a={};for(let[e,t]of r){let r=i.get(e);r?r.signature!==t.signature&&(a[t.node]=`changed`):a[t.node]=n}return a}var u9={class:`grid h-[calc(100dvh-17rem)] min-h-[26rem] grid-cols-[18rem_1fr] gap-3`},d9={class:`min-h-0 divide-y divide-border overflow-y-auto rounded-lg border border-border`,"aria-label":`Revisions`},f9=[`aria-current`,`onClick`],p9={class:`flex items-center gap-2 text-sm`},m9={class:`font-mono text-xs text-fg-subtle`},h9=[`title`],g9={key:0,class:`px-3 py-2 text-sm text-muted-foreground`},_9={key:0,class:`flex min-h-0 flex-col gap-2`},v9={class:`flex items-center gap-2`},y9={class:`text-xs text-muted-foreground`},b9={key:0,class:`rounded-lg border border-border p-4 text-sm text-muted-foreground`},x9={key:1,class:`min-h-0 flex-1 overflow-auto rounded-lg border border-border py-2 font-mono text-[13px] leading-6`},S9={class:`inline-block w-4 select-none text-fg-subtle`},C9={key:2,class:`grid min-h-0 flex-1 grid-cols-2 gap-3`},w9={class:`flex min-h-0 flex-col gap-1`},T9={class:`text-xs font-medium text-muted-foreground`},E9={class:`min-h-0 flex-1`},D9={class:`flex min-h-0 flex-col gap-1`},O9={class:`min-h-0 flex-1`},k9=k({__name:`WorkflowHistory`,props:ht({revisions:{},current:{},error:{}},{selected:{default:0},selectedModifiers:{},mode:{default:`yaml`},modeModifiers:{}}),emits:ht([`restore`],[`update:selected`,`update:mode`]),setup(e,{emit:t}){let n=e,r=t,i=Ke(e,`selected`),a=Ke(e,`mode`);F(()=>n.revisions,e=>{e.some(e=>e.version===i.value)||(i.value=(e.find(e=>e.yaml!==n.current)??e[0])?.version??0)},{immediate:!0});let o=I(()=>n.revisions.find(e=>e.version===i.value)),s=I(()=>o.value?.yaml??null),c=I(()=>s.value===null?[]:s9(s.value,n.current)),l=I(()=>s.value!==null&&s.value===n.current),u=I(()=>s.value===null?{}:l9(s.value,n.current,`removed`)),d=I(()=>s.value===null?{}:l9(n.current,s.value,`added`)),f={added:`default`,edited:`secondary`,removed:`destructive`};return(t,n)=>(R(),W(`div`,u9,[U(`ol`,d9,[(R(!0),W(V,null,G(e.revisions,e=>(R(),W(`li`,{key:e.version},[U(`button`,{type:`button`,class:N([`block w-full px-3 py-2 text-left hover:bg-secondary`,e.version===i.value&&`bg-secondary`]),"aria-current":e.version===i.value,onClick:t=>i.value=e.version},[U(`span`,p9,[U(`span`,m9,`v`+B(e.version),1),M(z($t),{variant:f[e.change]},{default:j(()=>[A(B(e.change),1)]),_:2},1032,[`variant`])]),U(`span`,{class:`mt-0.5 block truncate text-xs text-muted-foreground`,title:e.at},B(e.actor||`unknown`)+` · `+B(e.source||`unknown`)+` · `+B(z(Sg)(e.at)),9,h9)],10,f9)]))),128)),e.revisions.length?L(``,!0):(R(),W(`li`,g9,B(e.error||`No recorded changes`),1))]),o.value?(R(),W(`div`,_9,[U(`div`,v9,[M(z(ub),{modelValue:a.value,"onUpdate:modelValue":n[0]||=e=>a.value=e},{default:j(()=>[M(z(fb),null,{default:j(()=>[M(z(pb),{value:`yaml`},{default:j(()=>[...n[2]||=[A(`YAML`,-1)]]),_:1}),M(z(pb),{value:`canvas`},{default:j(()=>[...n[3]||=[A(`Canvas`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`]),U(`span`,y9,B(l.value?`Same as the current definition`:`Compared with the current definition`),1),M(z(Y),{type:`button`,size:`sm`,variant:`outline`,class:`ml-auto`,disabled:s.value===null||l.value,title:s.value===null?`Workflow removed`:void 0,onClick:n[1]||=e=>r(`restore`,s.value)},{default:j(()=>[M(z(oc),{"data-icon":`inline-start`}),n[4]||=A(` Restore this version`,-1)]),_:1},8,[`disabled`,`title`])]),s.value===null?(R(),W(`p`,b9,`Workflow removed in this revision.`)):a.value===`yaml`?(R(),W(`pre`,x9,[U(`code`,null,[(R(!0),W(V,null,G(c.value,(e,t)=>(R(),W(`span`,{key:t,class:N([`block min-h-6 px-3 whitespace-pre-wrap`,{"bg-ok/10":e.kind===`add`,"bg-danger/10 text-danger":e.kind===`del`}])},[U(`span`,S9,B(e.kind===`add`?`+`:e.kind===`del`?`-`:``),1),A(B(e.text),1)],2))),128))])])):(R(),W(`div`,C9,[U(`div`,w9,[U(`span`,T9,`v`+B(o.value.version),1),U(`div`,E9,[M(r9,{yaml:s.value,marks:u.value},null,8,[`yaml`,`marks`])])]),U(`div`,D9,[n[5]||=U(`span`,{class:`text-xs font-medium text-muted-foreground`},`Current`,-1),U(`div`,O9,[M(r9,{yaml:e.current,marks:d.value},null,8,[`yaml`,`marks`])])])]))])):L(``,!0)]))}}),A9=`workflow-definitions`;function j9(e){let t=O(),n=q([]),r=q(``);async function i(){try{n.value=await t.history(A9),r.value=``}c Line truncated
+1
View File
@@ -0,0 +1 @@
import{En as e,Tn as t,U as n,Ut as r,Y as i,_ as a,_n as o,an as s,dn as c,ln as l,mn as u,nt as d,on as f,pn as p,wn as m,yn as h}from"./PageHeader.js";var g=typeof window<`u`,_,v=e=>_=e,y=Symbol();function b(e){return e&&typeof e==`object`&&Object.prototype.toString.call(e)===`[object Object]`&&typeof e.toJSON!=`function`}var x=typeof window==`object`&&window.window===window?window:typeof self==`object`&&self.self===self?self:typeof global==`object`&&global.global===global?global:typeof globalThis==`object`?globalThis:{HTMLElement:null};function S(e,{autoBom:t=!1}={}){return t&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([``,e],{type:e.type}):e}function C(e,t,n){let r=new XMLHttpRequest;r.open(`GET`,e),r.responseType=`blob`,r.onload=function(){O(r.response,t,n)},r.onerror=function(){console.error(`could not download file`)},r.send()}function w(e){let t=new XMLHttpRequest;t.open(`HEAD`,e,!1);try{t.send()}catch{}return t.status>=200&&t.status<=299}function T(e){try{e.dispatchEvent(new MouseEvent(`click`))}catch{let t=new MouseEvent(`click`,{bubbles:!0,cancelable:!0,view:window,detail:0,screenX:80,screenY:20,clientX:80,clientY:20,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,button:0,relatedTarget:null});e.dispatchEvent(t)}}var E=typeof navigator==`object`?navigator:{userAgent:``},D=/Macintosh/.test(E.userAgent)&&/AppleWebKit/.test(E.userAgent)&&!/Safari/.test(E.userAgent),O=g?typeof HTMLAnchorElement<`u`&&`download`in HTMLAnchorElement.prototype&&!D?k:`msSaveOrOpenBlob`in E?A:j:()=>{};function k(e,t=`download`,n){let r=document.createElement(`a`);r.download=t,r.rel=`noopener`,typeof e==`string`?(r.href=e,r.origin===location.origin?T(r):w(r.href)?C(e,t,n):(r.target=`_blank`,T(r))):(r.href=URL.createObjectURL(e),setTimeout(function(){URL.revokeObjectURL(r.href)},4e4),setTimeout(function(){T(r)},0))}function A(e,t=`download`,n){if(typeof e==`string`){if(w(e))C(e,t,n);else{let t=document.createElement(`a`);t.href=e,t.target=`_blank`,setTimeout(function(){T(t)})}}else navigator.msSaveOrOpenBlob(S(e,n),t)}function j(e,t,n,r){if(r||=open(``,`_blank`),r&&(r.document.title=r.document.body.innerText=`downloading...`),typeof e==`string`)return C(e,t,n);let i=e.type===`application/octet-stream`,a=/constructor/i.test(String(x.HTMLElement))||`safari`in x,o=/CriOS\/[\d]+/.test(navigator.userAgent);if((o||i&&a||D)&&typeof FileReader<`u`){let t=new FileReader;t.onloadend=function(){let e=t.result;if(typeof e!=`string`)throw r=null,Error(`Wrong reader.result type`);e=o?e:e.replace(/^data:[^;]*;/,`data:attachment/file;`),r?r.location.href=e:location.assign(e),r=null},t.readAsDataURL(e)}else{let t=URL.createObjectURL(e);r?r.location.assign(t):location.href=t,r=null,setTimeout(function(){URL.revokeObjectURL(t)},4e4)}}var{assign:M}=Object;function N(){let e=s(!0),t=e.run(()=>h({})),n=[],r=[],i=p({install(e){v(i),i._a=e,e.provide(y,i),e.config.globalProperties.$pinia=i,r.forEach(e=>n.push(e)),r=[]},use(e){return this._a?n.push(e):r.push(e),this},_p:n,_a:null,_e:e,_s:new Map,state:t});return i}var P=()=>{};function F(e,t,n,r=P){e.add(t);let i=()=>{e.delete(t)&&r()};return!n&&f()&&u(i),i}function I(e,...t){e.forEach(e=>{e(...t)})}var L=e=>e(),R=Symbol(),z=Symbol();function B(e,t){e instanceof Map&&t instanceof Map?t.forEach((t,n)=>e.set(n,t)):e instanceof Set&&t instanceof Set&&t.forEach(e.add,e);for(let n in t){if(!Object.hasOwn(t,n))continue;let r=t[n],i=e[n];e[n]=b(i)&&b(r)&&Object.hasOwn(e,n)&&!c(r)&&!l(r)?B(i,r):r}return e}var V=Symbol();function H(e){return!e||typeof e!=`object`||!Object.hasOwn(e,V)}var{assign:U}=Object;function W(e){return!!(c(e)&&e.effect)}function G(t,n,r,i){let{state:o,actions:s,getters:c}=n,l=r.state.value[t],u;function d(){return l||(r.state.value[t]=o?o():{}),U(e(r.state.value[t]),s,Object.keys(c||{}).reduce((e,n)=>(e[n]=p(a(()=>{v(r);let e=r._s.get(t);return c[n].call(e,e)})),e),{}))}return u=K(t,d,n,r,i,!0),u}function K(e,t,n={},i,a,u){let f,p=U({actions:{}},n),h={deep:!0},g,_,y=new Set,b=new Set,x,S=i.state.value[e];!u&&!S&&(i.state.value[e]={});let C;function w(t){let n;g=_=!1,typeof t==`function`?(t(i.state.value[e]),n={type:`patch function`,storeId:e,events:x}):(B(i.state.value[e],t),n={type:`patch object`,payload:t,storeId:e,events:x});let r=C=Symbol();d().then(()=>{C===r&&(g=!0)}),_=!0,I(y,n,i.state.value[e])}let T=u?function(){let{state:e}=n,t=e?e():{};this.$patch(e=>{U(e,t)})}:P;function E(){f.stop(),y.clear(),b.clear(),i._s.delete(e)}let D=(t,n=``)=>{if(R in t)return t[z]=n,t;let r=function(){v(i);let n=Array.from(arguments),a=new Set,o=new Set;function s(e){a.add(e)}function c(e){o.add(e)}I(b,{args:n,name:r[z],store:k,after:s,onError:c});let l;try{l=t.apply(this&&this.$id===e?this:k,n)}catch(e){throw I(o,e),e}return l instanceof Promise?l.then(e=>(I(a,e),e)).catch(e=>(I(o,e),Promise.reject(e))):(I(a,l),l)};return r[R]=!0,r[z]=n,r},O={_p:i,$id:e,$onAction:F.bind(null,b),$patch:w,$reset:T,$subscribe(t,n={}){if(y.has(t))return P;let a=FLine truncated
+2
View File
@@ -34,6 +34,8 @@
</script>
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="modulepreload" crossorigin href="/assets/PageHeader.js">
<link rel="modulepreload" crossorigin href="/assets/api.js">
<link rel="modulepreload" crossorigin href="/assets/pinia.js">
<link rel="modulepreload" crossorigin href="/assets/alert.js">
<link rel="modulepreload" crossorigin href="/assets/CardAccordion.js">
<link rel="stylesheet" crossorigin href="/assets/index.css">
+13 -3
View File
@@ -1,5 +1,8 @@
<script setup lang="ts">
import { computed, onMounted } from "vue";
import { computed, onMounted, watch } from "vue";
import AccountEntry from "@/accounts/AccountEntry.vue";
import { useAccountsStore } from "@/accounts/accounts";
import ChatLauncher from "@/chat/ChatLauncher.vue";
import Topbar from "@/components/topbar/Topbar.vue";
@@ -9,10 +12,15 @@ import { hiddenPaths } from "@/lib/nav";
import { loadTaskMeta } from "@/lib/task-meta";
import { useSessionStore } from "@/stores/session";
const reauthenticate=new URLSearchParams(window.location.search).has("reauth");
const accounts=useAccountsStore();
const session = useSessionStore();
const hidden = computed(() => hiddenPaths(session.sections));
onMounted(() => {
onMounted(() => {void accounts.load();});
watch(() => accounts.status?.user, (user) => {
if (!user || reauthenticate) return;
session.initialize();
// Asked for once, after the shell is up: the nav paints immediately and
// loses the entries this process cannot back a moment later, rather than
// holding the page behind a request. A failed read hides nothing.
@@ -29,7 +37,9 @@ onMounted(() => {
</script>
<template>
<TooltipProvider :delay-duration="350">
<div v-if="!accounts.status" class="mx-auto max-w-md p-8" role="status"><p>{{accounts.error||'Connecting to Archie…'}}</p><button v-if="accounts.error" class="mt-3 underline" @click="accounts.load">Retry</button></div>
<AccountEntry v-else-if="!accounts.status.user || accounts.status.setup_required || reauthenticate" />
<TooltipProvider v-else :delay-duration="350">
<!--
One contained, rounded surface floating on the canvas `body` carries:
framing the workspace gives the panels an edge to sit against, and lets
+57
View File
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { api } from "@/lib/api";
import { passkeysAvailable, useAccountsStore, usePasskey } from "./accounts";
const accounts=useAccountsStore();
const step=ref(1);const recovery=ref(false);const recoveryCode=ref("");
const organisation=ref("");const workspace=ref("Default");const publicURL=ref(window.location.origin);
const name=ref("");const email=ref("");const password=ref("");const busy=ref(false);const error=ref("");
const setup=computed(()=>accounts.status?.setup_required===true);
const passkey=computed(()=>passkeysAvailable(accounts.status?.public_url??""));
async function submit(){
if(setup.value&&step.value===1&&!recovery.value){step.value=2;return}
busy.value=true;error.value="";
try{
if(recovery.value){await api.recoverAccount(email.value,recoveryCode.value,password.value);recovery.value=false;password.value="";error.value="Password changed. Sign in with your new password.";return}
if(setup.value)await api.setupAccount({organisation_name:organisation.value,workspace_name:workspace.value,public_url:publicURL.value.replace(/\/$/,""),display_name:name.value,email:email.value,password:password.value});
else await api.signIn(email.value,password.value);
password.value="";
window.location.assign(setup.value?"/account?welcome=1":new URLSearchParams(window.location.search).has("reauth")?"/account":"/");
}catch(cause){error.value=String((cause as Error).message||cause);await accounts.load()}
finally{busy.value=false}
}
async function signInPasskey(){busy.value=true;error.value="";try{await usePasskey(false);window.location.assign("/")}catch(cause){error.value=String((cause as Error).message||cause)}finally{busy.value=false}}
</script>
<template>
<main class="mx-auto flex min-h-[90dvh] max-w-md flex-col justify-center px-5 py-10">
<div class="rounded-xl border border-border bg-card p-6 shadow-sm">
<p class="mb-2 text-xs font-medium tracking-widest text-muted-foreground">ARCHIE</p>
<h1 class="text-2xl font-medium">{{setup?(step===1?'Set up your organisation':'Create your admin account'):recovery?'Recover your account':'Sign in'}}</h1>
<p class="mt-2 text-sm text-muted-foreground">{{setup?(step===1?'Start with the organisation and workspace this installation will serve.':'This first account administers the installation. You can add people and configure OIDC after setup.'):'Use your account to open your workspace.'}}</p>
<form class="mt-6 space-y-4" @submit.prevent="submit">
<template v-if="setup&&step===1">
<label class="block space-y-1.5 text-sm" for="organisation">Organisation name<Input id="organisation" v-model="organisation" autocomplete="organization" required maxlength="200" /></label>
<label class="block space-y-1.5 text-sm" for="workspace">First workspace<Input id="workspace" v-model="workspace" required maxlength="200" /></label>
<label class="block space-y-1.5 text-sm" for="public-url">Instance URL<Input id="public-url" v-model="publicURL" type="url" required autocomplete="url" /></label>
<p class="text-xs text-muted-foreground">Use the address people will visit. Passkeys require HTTPS and a domain name, or localhost for development.</p>
</template>
<template v-else>
<label v-if="setup" class="block space-y-1.5 text-sm" for="account-name">Your name<Input id="account-name" v-model="name" autocomplete="name" required maxlength="200" /></label>
<label class="block space-y-1.5 text-sm" for="account-email">Email<Input id="account-email" v-model="email" type="email" autocomplete="username" :spellcheck="false" required /></label>
<label v-if="recovery" class="block space-y-1.5 text-sm" for="recovery-code">Recovery code<Input id="recovery-code" v-model="recoveryCode" autocomplete="off" required /></label>
<label class="block space-y-1.5 text-sm" for="account-password">{{recovery?"New password":"Password"}}<Input id="account-password" v-model="password" type="password" :autocomplete="setup||recovery?'new-password':'current-password'" :minlength="setup||recovery?15:undefined" maxlength="1024" required /></label>
<p v-if="setup" class="text-xs text-muted-foreground">At least 15 characters. You can add a passkey after creating your account.</p>
</template>
<p v-if="error" role="alert" class="text-sm text-danger">{{error}}</p>
<div class="flex gap-2"><Button v-if="setup&&step===2" type="button" variant="outline" :disabled="busy" @click="step=1">Back</Button><Button type="submit" class="flex-1" :disabled="busy">{{busy?'Please wait…':setup?(step===1?'Continue':'Create organisation and admin'):recovery?'Reset password':'Sign in'}}</Button></div>
</form>
<div v-if="!setup&&!recovery" class="mt-4 flex flex-col gap-2">
<Button v-if="passkey" variant="outline" :disabled="busy" @click="signInPasskey">Sign in with a passkey</Button>
<Button v-if="accounts.status?.oidc" variant="outline" as-child><a href="/oauth2/login">Sign in with OIDC</a></Button>
</div>
<Button v-if="!setup" variant="link" class="mt-3" :disabled="busy" @click="recovery=!recovery;error=''">{{recovery?'Back to sign in':'Use a recovery code'}}</Button>
</div>
</main>
</template>
+48
View File
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { api } from "@/lib/api";
import { passkeysAvailable,useAccountsStore,usePasskey } from "./accounts";
const recovery=ref("");
const makeRecovery=()=>run(async()=>{recovery.value=(await api.recoveryCode()).code});
const accounts=useAccountsStore();const keys=ref<{id:string;name:string}[]>([]);const error=ref("");const busy=ref(false);const keyName=ref("");const current=ref("");const next=ref("");
const eligible=computed(()=>passkeysAvailable(accounts.status?.public_url??""));
async function load(){try{keys.value=(await api.passkeys()).passkeys}catch(cause){error.value=String((cause as Error).message||cause)}}
onMounted(load);
async function run(action:()=>Promise<unknown>){busy.value=true;error.value="";try{await action()}catch(cause){error.value=String((cause as Error).message||cause)}finally{busy.value=false}}
const enroll=()=>run(async()=>{await usePasskey(true,keyName.value);keyName.value="";await load()});
const remove=(id:string)=>run(async()=>{await api.deletePasskey(id);await load()});
const change=()=>run(async()=>{await api.changePassword(current.value,next.value);current.value=next.value="";window.location.assign("/")});
</script>
<template>
<div class="max-w-2xl space-y-6">
<PageHeader title="Your account" />
<p class="text-sm">{{accounts.status?.user?.display_name}}</p>
<p v-if="$route.query.welcome" class="rounded-lg border border-border bg-card p-4 text-sm">Your organisation and admin account are ready. Add a passkey below, <RouterLink class="underline" to="/org">add accounts</RouterLink>, or <RouterLink class="underline" to="/settings/authentication">configure OIDC</RouterLink>.</p>
<p v-if="error" role="alert" class="text-sm text-danger">{{error}} <a class="underline" href="/?reauth=1">Sign in again</a></p>
<section class="rounded-lg border border-border bg-card p-5">
<h2 class="font-medium">Passkeys</h2>
<p class="mt-1 text-sm text-muted-foreground">Sign in with your device or security key.</p>
<ul class="mt-4 divide-y divide-border"><li v-for="key in keys" :key="key.id" class="flex items-center gap-3 py-2 text-sm"><span class="min-w-0 flex-1 truncate">{{key.name}}</span><Button variant="ghost" size="sm" :disabled="busy" @click="remove(key.id)">Remove</Button></li></ul>
<form v-if="eligible" class="mt-3 flex flex-wrap gap-2" @submit.prevent="enroll"><Input v-model="keyName" aria-label="Passkey name" placeholder="Passkey name (optional)" maxlength="200" class="min-w-40 flex-1"/><Button type="submit" :disabled="busy">Add passkey</Button></form>
<p v-else class="mt-3 text-sm text-muted-foreground">Open Archie at its configured HTTPS domain, or localhost, in a browser that supports passkeys. The instance URL is managed in <RouterLink class="underline" to="/settings/authentication">Authentication settings</RouterLink>.</p>
</section>
<section class="rounded-lg border border-border bg-card p-5 space-y-3">
<h2 class="font-medium">Recovery code</h2>
<p class="text-sm text-muted-foreground">Save this once-only code somewhere safe. It resets your password if you lose access. Generating a new code replaces the previous one.</p>
<Button :disabled="busy" @click="makeRecovery">Generate recovery code</Button>
<p v-if="recovery" class="break-all rounded border border-border p-3 font-mono text-sm" role="status">{{recovery}}</p>
</section>
<section class="rounded-lg border border-border bg-card p-5">
<h2 class="font-medium">Change password</h2>
<form class="mt-4 max-w-sm space-y-3" @submit.prevent="change">
<label class="block space-y-1 text-sm" for="current-password">Current password<Input id="current-password" v-model="current" type="password" autocomplete="current-password" required /></label>
<label class="block space-y-1 text-sm" for="new-password">New password<Input id="new-password" v-model="next" type="password" autocomplete="new-password" required minlength="15" maxlength="1024" /></label>
<p class="text-xs text-muted-foreground">Changing your password signs out all your sessions.</p>
<Button type="submit" :disabled="busy">Change password</Button>
</form>
</section>
</div>
</template>
+34
View File
@@ -0,0 +1,34 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { api } from "@/lib/api";
interface Settings {public_url:string;oidc_issuer:string;oidc_audience:string;oidc_client_id:string}
const value=ref<Settings>({public_url:"",oidc_issuer:"",oidc_audience:"",oidc_client_id:""});const loaded=ref(false);const error=ref("");const busy=ref(false);const saved=ref(false);
onMounted(async()=>{try{value.value=await api.authentication<Settings>();loaded.value=true}catch(cause){error.value=String((cause as Error).message||cause)}});
async function save(){busy.value=true;error.value="";saved.value=false;try{await api.saveAuthentication(value.value);saved.value=true}catch(cause){error.value=String((cause as Error).message||cause)}finally{busy.value=false}}
</script>
<template>
<div class="max-w-2xl"><PageHeader title="Authentication"/>
<p v-if="error" class="mb-4 text-sm text-danger" role="alert">{{error}} <a class="underline" href="/?reauth=1">Sign in again</a></p>
<form v-if="loaded" class="space-y-6" @submit.prevent="save">
<section class="space-y-3 rounded-lg border border-border bg-card p-5">
<h2 class="font-medium">Instance URL</h2>
<label for="instance-url" class="block space-y-1 text-sm">Public address<Input id="instance-url" v-model="value.public_url" type="url" required /></label>
<p class="text-xs text-muted-foreground">Passkeys require HTTPS and a domain name, or localhost. Once passkeys are enrolled, their domain is fixed.</p>
</section>
<section class="space-y-3 rounded-lg border border-border bg-card p-5">
<h2 class="font-medium">OpenID Connect</h2>
<p class="text-sm text-muted-foreground">Register a public client with authorization code flow and PKCE. Local accounts remain available.</p>
<label for="oidc-issuer" class="block space-y-1 text-sm">Issuer URL<Input id="oidc-issuer" v-model="value.oidc_issuer" type="url" placeholder="https://identity.example.com" /></label>
<label for="oidc-client" class="block space-y-1 text-sm">Client ID<Input id="oidc-client" v-model="value.oidc_client_id" /></label>
<label for="oidc-audience" class="block space-y-1 text-sm">Access token audience<Input id="oidc-audience" v-model="value.oidc_audience" /></label>
<p class="break-all text-xs text-muted-foreground">Redirect URI: {{value.public_url.replace(/\/$/,'')}}/oauth2/callback</p>
<p class="text-xs text-muted-foreground">Add permitted people by their verified email or provider subject in <RouterLink class="underline" to="/org">Organisation members</RouterLink>. Clear the OIDC fields to disable provider sign-in.</p>
</section>
<p v-if="saved" role="status" class="text-sm">Authentication settings saved.</p>
<Button type="submit" :disabled="busy">Save</Button>
</form>
</div>
</template>
+23
View File
@@ -0,0 +1,23 @@
<script setup lang="ts">
import { ref } from "vue";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { api } from "@/lib/api";
const emit=defineEmits<{created:[]}>();
const name=ref("");const email=ref("");const password=ref("");const role=ref("viewer");const busy=ref(false);const error=ref("");
async function create(){busy.value=true;error.value="";try{await api.createAccount({display_name:name.value,email:email.value,password:password.value,role:role.value});name.value=email.value=password.value="";emit("created")}catch(cause){error.value=String((cause as Error).message||cause)}finally{busy.value=false}}
</script>
<template>
<section class="mt-6 max-w-md rounded-lg border border-border bg-card p-5">
<h2 class="text-sm font-medium">Create a local account</h2>
<form class="mt-4 space-y-3" @submit.prevent="create">
<label for="new-account-name" class="block space-y-1 text-sm">Name<Input id="new-account-name" v-model="name" required maxlength="200" autocomplete="off" /></label>
<label for="new-account-email" class="block space-y-1 text-sm">Email<Input id="new-account-email" v-model="email" type="email" required autocomplete="off" :spellcheck="false" /></label>
<label for="new-account-password" class="block space-y-1 text-sm">Initial password<Input id="new-account-password" v-model="password" type="password" required minlength="15" maxlength="1024" autocomplete="new-password" /></label>
<label for="new-account-role" class="block space-y-1 text-sm">Role<NativeSelect id="new-account-role" v-model="role"><NativeSelectOption value="viewer">Viewer</NativeSelectOption><NativeSelectOption value="developer">Developer</NativeSelectOption><NativeSelectOption value="admin">Admin</NativeSelectOption></NativeSelect></label>
<p v-if="error" role="alert" class="text-sm text-danger">{{error}} <a class="underline" href="/?reauth=1">Sign in again</a></p>
<Button type="submit" :disabled="busy">Create account</Button>
</form>
</section>
</template>
+41
View File
@@ -0,0 +1,41 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import { api } from "@/lib/api";
export interface AccountUser {id:string;display_name:string;kind:string}
interface AuthStatus {setup_required:boolean;user:AccountUser|null;oidc:boolean;public_url:string}
export const useAccountsStore=defineStore("accounts",()=>{
const status=ref<AuthStatus|null>(null);
const error=ref("");
async function load():Promise<void>{try{status.value=await api.authStatus<AuthStatus>();error.value=""}catch(cause){error.value=String((cause as Error).message||cause)}}
async function signOut():Promise<void>{await api.signOut();window.location.assign("/")}
return {status,error,load,signOut};
});
export function passkeysAvailable(publicURL:string):boolean{
if (!window.isSecureContext || !window.PublicKeyCredential) return false;
try{const url=new URL(publicURL);return url.origin===window.location.origin && (url.protocol==="https:"||url.hostname==="localhost")}catch{return false}
}
// WebAuthn JSON conversion is native in current browsers. These conversions
// preserve support for browsers that implement credentials but not JSON helpers.
function decode(value:string):ArrayBuffer{
const bytes=Uint8Array.from(atob(value.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0));return bytes.buffer;
}
function encode(value:ArrayBuffer|null):string|null{
if(value===null)return null;
return btoa(String.fromCharCode(...new Uint8Array(value))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");
}
export async function usePasskey(registration:boolean,name=""):Promise<void>{
const options=await api.beginPasskey<{publicKey:Record<string,unknown>}>(registration);
const key=options.publicKey;
key.challenge=decode(key.challenge as string);
if(registration){const user=key.user as Record<string,unknown>;user.id=decode(user.id as string)}
for(const list of ["excludeCredentials","allowCredentials"]){for(const entry of (key[list] as {id:string|ArrayBuffer}[]|undefined)??[]){entry.id=decode(entry.id as string)}}
const credential=(registration?await navigator.credentials.create({publicKey:key as unknown as PublicKeyCredentialCreationOptions}):await navigator.credentials.get({publicKey:key as unknown as PublicKeyCredentialRequestOptions})) as PublicKeyCredential|null;
if(!credential)throw new Error("No passkey was selected.");
const response=credential.response;
const common={clientDataJSON:encode(response.clientDataJSON)};
const data=response instanceof AuthenticatorAttestationResponse?{...common,attestationObject:encode(response.attestationObject),transports:response.getTransports()}:{...common,authenticatorData:encode((response as AuthenticatorAssertionResponse).authenticatorData),signature:encode((response as AuthenticatorAssertionResponse).signature),userHandle:encode((response as AuthenticatorAssertionResponse).userHandle)};
await api.finishPasskey(registration,{id:credential.id,rawId:encode(credential.rawId),type:credential.type,response:data,clientExtensionResults:credential.getClientExtensionResults(),authenticatorAttachment:credential.authenticatorAttachment},name);
}
+7 -2
View File
@@ -1,4 +1,6 @@
<script setup lang="ts">
import { useAccountsStore } from "@/accounts/accounts";
const accounts=useAccountsStore();
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
DropdownMenu,
@@ -17,18 +19,21 @@ import {
aria-label="Operator menu"
>
<Avatar class="size-7">
<AvatarFallback class="text-xs">A</AvatarFallback>
<AvatarFallback class="text-xs">{{accounts.status?.user?.display_name.slice(0,1).toUpperCase()}}</AvatarFallback>
</Avatar>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-48">
<DropdownMenuLabel class="text-muted-foreground text-xs font-normal">Signed in locally</DropdownMenuLabel>
<DropdownMenuLabel class="text-muted-foreground text-xs font-normal">{{accounts.status?.user?.display_name}}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem as-child><RouterLink to="/account">Your account</RouterLink></DropdownMenuItem>
<DropdownMenuItem as-child>
<RouterLink to="/settings/appearance" class="w-full cursor-pointer">Appearance</RouterLink>
</DropdownMenuItem>
<DropdownMenuItem as-child>
<RouterLink to="/logs" class="w-full cursor-pointer">Logs</RouterLink>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem @select="accounts.signOut">Sign out</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</template>
+14
View File
@@ -138,6 +138,20 @@ async function request<T = unknown>(
}
export const api = {
recoveryCode: () => request<{code:string}>("/api/account/recovery",{method:"POST",body:{}}),
recoverAccount: (email:string,code:string,password:string) => request<void>("/api/auth/recover",{method:"POST",body:{email,code,password},parse:false}),
authStatus: <T = unknown>() => request<T>("/api/auth/status"),
setupAccount: (body: unknown) => request("/api/auth/setup", {method:"POST",body}),
signIn: (email: string,password: string) => request("/api/auth/login",{method:"POST",body:{email,password}}),
signOut: () => request<void>("/api/auth/logout",{method:"POST",body:{},parse:false}),
createAccount: (body: unknown) => request("/api/accounts",{method:"POST",body}),
changePassword: (current_password: string,new_password: string) => request<void>("/api/account/password",{method:"POST",body:{current_password,new_password},parse:false}),
authentication: <T = unknown>() => request<T>("/api/authentication"),
saveAuthentication: (body: unknown) => request<void>("/api/authentication",{method:"PUT",body,parse:false}),
passkeys: () => request<{passkeys:{id:string;name:string}[]}>("/api/account/passkeys"),
deletePasskey: (id:string) => request<void>(`/api/account/passkeys/${encodeURIComponent(id)}`,{method:"DELETE",body:{},parse:false}),
beginPasskey: <T = unknown>(registration:boolean) => request<T>(registration?"/api/account/passkeys/begin":"/api/auth/passkey/begin",{method:"POST",body:{}}),
finishPasskey: (registration:boolean,credential:unknown,name:string) => request(registration?"/api/account/passkeys/finish":"/api/auth/passkey/finish",{method:"POST",body:{credential,name}}),
secretEngines: <T = unknown>() => request<T>("/api/secret-engines"),
checkSecret: (ref: { engine: string; key: string }) => request<{ resolved: boolean; process: string }>("/api/secret-references/check", { method: "POST", body: ref }),
health: <T = unknown>() => request<T>("/health/detailed"),
+1 -1
View File
@@ -82,7 +82,7 @@ const settings: NavSpec = {
"/settings/status",
],
},
{ paths: ["/settings/appearance", "/settings/history"] },
{ paths: ["/settings/authentication", "/settings/appearance", "/settings/history"] },
],
};
+2 -2
View File
@@ -5,7 +5,7 @@ import App from "./App.vue";
import { registerArchieWebMcpTools } from "./lib/archie-webmcp";
import router from "./router";
import { useAppearanceStore } from "./stores/appearance";
import { useSessionStore } from "./stores/session";
// One stylesheet: the design tokens, and the element defaults that have no
// component to live in (the canvas, the focus floor, the motion preference).
// Everything else is Tailwind on the component that owns it.
@@ -16,7 +16,7 @@ const pinia = createPinia();
app.use(pinia).use(router);
useAppearanceStore(pinia).initialize();
useSessionStore(pinia).initialize();
app.mount("#app");
// Published after the shell paints: an in-page agent's tools are not worth
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import CreateAccount from "@/accounts/CreateAccount.vue";
import { Card, CardContent } from "@/components/ui/card";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref } from "vue";
@@ -185,6 +186,7 @@ const remove = (member: Member) =>
</CardContent>
</Card>
<CreateAccount v-if="org?.id===identities.homeOrg" @created="load" />
<section class="mt-8 grid gap-6 lg:grid-cols-2" aria-label="Add people">
<div>
<h2 class="mb-3 text-sm font-medium">Add an identity</h2>
+2
View File
@@ -42,6 +42,8 @@ import WorkflowsPage from "@/workflows/WorkflowsPage.vue";
// route with no section is served in every composition
// navPath the navigation entry this route keeps current
const routes = [
{path:"/account",name:"account",component:()=>import("@/accounts/AccountPage.vue"),meta:{label:"Your account"}},
{path:"/settings/authentication",name:"authentication",component:()=>import("@/accounts/AuthenticationPage.vue"),meta:{label:"Authentication",settings:true,navPath:"/settings"}},
{
path: "/",
name: "dashboard",
+14 -1
View File
@@ -4,6 +4,7 @@ import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select"
import { computed, onMounted, ref, watch } from "vue";
import { ArrowLeft, Braces, Type } from "@lucide/vue";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
@@ -56,6 +57,7 @@ const rows = ref<Record<string, InputRow>>({});
const repositoryPath = ref("");
const preview = ref<Preview | null>(null);
const saving = ref(false);
const confirmRemove=ref(false);
const creatingSource = ref(false);
const revealed = ref<Source | null>(null);
const error = ref("");
@@ -221,6 +223,13 @@ async function transition(command: (id: string) => Promise<unknown>, next: strin
error.value = err instanceof Error ? err.message : String(err);
}
}
async function removeBinding():Promise<void>{
if(!props.binding)return;
saving.value=true;error.value="";
try{await api.bindingDelete(props.binding.id);emit("saved")}
catch(cause){error.value=cause instanceof Error?cause.message:String(cause)}
finally{saving.value=false}
}
const approve = () => transition(api.bindingApprove, "armed");
const pause = () => transition(api.bindingPause, "paused");
const resume = () => transition(api.bindingResume, "pending_approval");
@@ -228,6 +237,9 @@ const resume = () => transition(api.bindingResume, "pending_approval");
<template>
<div class="flex h-full flex-col">
<AlertDialog v-model:open="confirmRemove">
<AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Remove event binding?</AlertDialogTitle><AlertDialogDescription>This event will stop starting this workflow. The event source and mapping are kept.</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction @click="removeBinding">Remove binding</AlertDialogAction></AlertDialogFooter></AlertDialogContent>
</AlertDialog>
<header class="flex items-center gap-2 border-b border-border px-4 py-3">
<Button type="button" variant="ghost" size="icon-sm" aria-label="Back to settings" @click="emit('back')"><ArrowLeft /></Button>
<div class="min-w-0 flex-1 truncate text-sm font-medium">{{ binding ? binding.name : "Bind an event" }}</div>
@@ -321,11 +333,12 @@ const resume = () => transition(api.bindingResume, "pending_approval");
<div class="space-y-2">
<p v-if="error" role="alert" class="text-xs text-danger">{{ error }}</p>
<p v-else-if="blockers.length" class="text-xs text-fg-subtle">Cannot save: {{ blockers[0] }}</p>
<div class="flex gap-2">
<div class="flex flex-wrap gap-2">
<Button type="submit" size="sm" :disabled="saving || !!blockers.length"><Spinner v-if="saving" />Save binding</Button>
<Button v-if="binding && status === 'pending_approval'" type="button" size="sm" variant="outline" @click="approve">Approve</Button>
<Button v-if="binding && status === 'armed'" type="button" size="sm" variant="outline" @click="pause">Pause</Button>
<Button v-if="binding && status === 'paused'" type="button" size="sm" variant="outline" @click="resume">Resume</Button>
<Button v-if="binding" type="button" size="sm" variant="destructive" :disabled="saving" @click="confirmRemove=true">Remove binding</Button>
</div>
</div>
</form>
+1 -1
View File
@@ -120,7 +120,7 @@ function place(store?: VueFlowStore): void {
const reached = graph.value.nodes.find((node) => props.marks?.[node.id]) ?? graph.value.nodes.filter((node) => node.data.run).at(-1);
const below = reached && 24 + (reached.position.y + 180) * ZOOM > height;
const y = below ? height / 3 - reached.position.y * ZOOM : 24;
void flow.setViewport({ x: width / 2 - NODE_WIDTH / 2, y, zoom: ZOOM }, { duration: animate ? 300 : 0 });
void flow.setViewport({ x: width / 2 - NODE_WIDTH * ZOOM / 2, y, zoom: ZOOM }, { duration: animate ? 300 : 0 });
}
watch(() => graph.value.nodes.filter((node) => node.data.run).length, () => place());
+4 -4
View File
@@ -242,8 +242,8 @@ function syncScroll(event: Event): void {
<template>
<form class="space-y-4" @submit.prevent="saveDraft">
<Tabs v-model="view" class="space-y-1.5">
<div class="flex items-center gap-2">
<TabsList>
<div class="flex flex-wrap items-center gap-2">
<TabsList class="max-w-full justify-start overflow-x-auto">
<TabsTrigger value="canvas">Canvas</TabsTrigger>
<TabsTrigger value="yaml">YAML</TabsTrigger>
<TabsTrigger v-if="stored !== undefined" value="history">History</TabsTrigger>
@@ -318,7 +318,7 @@ function syncScroll(event: Event): void {
enter-active-class="transition duration-200"
leave-active-class="transition duration-150"
>
<div v-if="settingsOpen" class="absolute inset-y-0 right-0 overflow-hidden rounded-r-lg">
<div v-if="settingsOpen" class="absolute inset-y-0 right-0 max-w-full overflow-hidden rounded-r-lg">
<WorkflowSettings v-model:yaml="yaml" :triggers="triggers" @close="settingsOpen = false" @bound="reloadTriggers" />
</div>
</Transition>
@@ -328,7 +328,7 @@ function syncScroll(event: Event): void {
enter-active-class="transition duration-200"
leave-active-class="transition duration-150"
>
<div v-if="selectedStep" class="absolute inset-y-0 right-0 flex flex-col overflow-hidden rounded-r-lg border-l border-border bg-card shadow-xl">
<div v-if="selectedStep" class="absolute inset-y-0 right-0 flex max-w-full flex-col overflow-hidden rounded-r-lg border-l border-border bg-card shadow-xl">
<template v-if="selectedNode?.run && watchedRun">
<div class="flex items-center gap-2 border-b border-border px-3 py-2">
<Tabs v-model="stepTab"><TabsList><TabsTrigger value="run">Run</TabsTrigger><TabsTrigger value="definition">Definition</TabsTrigger></TabsList></Tabs>
+6 -2
View File
@@ -84,7 +84,7 @@ function setNeeds(next: { captures?: boolean; gate_retries?: number }): void {
</script>
<template>
<aside class="flex h-full w-[24rem] flex-col border-l border-border bg-card shadow-xl">
<aside class="flex h-full w-[24rem] max-w-full flex-col border-l border-border bg-card shadow-xl">
<BindEvent v-if="binding !== undefined" :yaml="yaml" :binding="binding" @back="binding = undefined" @saved="bound" />
<template v-else>
<header class="flex items-center gap-2 border-b border-border px-4 py-3">
@@ -206,8 +206,12 @@ function setNeeds(next: { captures?: boolean; gate_retries?: number }): void {
<Badge v-if="trigger.binding.status !== 'armed'" :variant="statusKind(trigger.binding.status)">{{ statusLabel(trigger.binding.status) }}</Badge>
<span v-if="trigger.detail" class="ml-auto truncate text-xs text-fg-subtle">{{ trigger.detail }}</span>
</button>
<div v-else class="flex items-center gap-2 px-3 py-2">
<RouterLink v-else-if="trigger.kind==='workflow' || trigger.kind==='playbook'" :to="trigger.kind==='workflow'?{path:'/workflows',query:{workflow:trigger.label}}:{path:'/settings/playbooks'}" class="flex items-center gap-2 px-3 py-2 hover:bg-secondary">
<span class="truncate">{{trigger.label}}</span><span class="ml-auto truncate text-xs text-fg-subtle">{{trigger.detail}}</span>
</RouterLink>
<div v-else class="flex items-center gap-2 px-3 py-2" title="Built-in issue routing. Disable this workflow to stop it running automatically.">
<span class="truncate">{{ trigger.label }}</span>
<Badge v-if="trigger.kind==='issue'" variant="outline" class="ml-auto">Built-in</Badge>
<span v-if="trigger.detail" class="ml-auto truncate text-xs text-fg-subtle">{{ trigger.detail }}</span>
</div>
</li>
+3 -3
View File
@@ -193,8 +193,8 @@ const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total :
<p v-if="error" class="mb-4 text-sm text-danger" role="alert">Cannot reach archied: {{ error }}</p>
<div class="grid items-start gap-6 lg:grid-cols-[24rem_minmax(0,1fr)]">
<ul class="flex flex-col gap-0.5" aria-label="Workflows">
<li v-for="row in rows" :key="row.id">
<ul class="flex gap-1 overflow-x-auto pb-2 lg:flex-col lg:gap-0.5 lg:overflow-visible lg:pb-0" aria-label="Workflows">
<li v-for="row in rows" :key="row.id" class="min-w-36 shrink-0 lg:min-w-0">
<button
type="button"
:aria-current="row.id === selected ? 'true' : undefined"
@@ -227,7 +227,7 @@ const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total :
</EmptyHeader>
</Empty>
</section>
<section v-else class="min-w-0 rounded-lg border border-border bg-card px-5 py-4" aria-label="Workflow">
<section v-else class="min-w-0 rounded-lg border border-border bg-card px-3 py-4 sm:px-5" aria-label="Workflow">
<header class="mb-2 flex flex-wrap items-center gap-2">
<h2 class="font-mono text-[15px] font-medium">{{ selected }}</h2>
<Badge v-if="provenance" variant="outline">{{ provenance }}</Badge>