@draht/coding-agent 2026.10.4 → 2026.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +32 -6
- package/dist/bundle/chunks/anthropic.js +1 -1
- package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-2VAF4XJI.js} +1 -1
- package/dist/bundle/chunks/chunk-6APPDDHH.js +65 -0
- package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-JFDPOIUH.js} +1 -1
- package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-KU5HAKZL.js} +1 -1
- package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-MIUVNYYW.js} +292 -153
- package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-NHTOADU6.js} +2 -2
- package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-OWGSPJPZ.js} +4 -4
- package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
- package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
- package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-TJ3AW62W.js} +1 -1
- package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-U7Y4VNNI.js} +1 -1
- package/dist/bundle/chunks/execute-ZWB4PIQQ.js +18 -0
- package/dist/bundle/chunks/google-antigravity.js +1 -1
- package/dist/bundle/chunks/google-gemini-cli.js +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/runtime-363BOYEO.js +3 -0
- package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-PXJK4L7Y.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-GEOZJXFQ.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-BEJ4ZJ3D.js +2 -0
- package/dist/bundle/chunks/xai.js +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +3 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/core/builtins/duet.d.ts +5 -2
- package/dist/core/builtins/duet.d.ts.map +1 -1
- package/dist/core/builtins/duet.js +65 -27
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/builtins/index.d.ts.map +1 -1
- package/dist/core/builtins/index.js +2 -0
- package/dist/core/builtins/index.js.map +1 -1
- package/dist/core/builtins/polyphase.d.ts +15 -0
- package/dist/core/builtins/polyphase.d.ts.map +1 -0
- package/dist/core/builtins/polyphase.js +196 -0
- package/dist/core/builtins/polyphase.js.map +1 -0
- package/dist/core/builtins/subagent.d.ts +44 -34
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +827 -560
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/types.d.ts +17 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +30 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +24 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-resolver.js +4 -4
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +4 -1
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/polyphase/approval.d.ts +35 -0
- package/dist/core/polyphase/approval.d.ts.map +1 -0
- package/dist/core/polyphase/approval.js +184 -0
- package/dist/core/polyphase/approval.js.map +1 -0
- package/dist/core/polyphase/child-events.d.ts +107 -0
- package/dist/core/polyphase/child-events.d.ts.map +1 -0
- package/dist/core/polyphase/child-events.js +862 -0
- package/dist/core/polyphase/child-events.js.map +1 -0
- package/dist/core/polyphase/child-process.d.ts +65 -0
- package/dist/core/polyphase/child-process.d.ts.map +1 -0
- package/dist/core/polyphase/child-process.js +361 -0
- package/dist/core/polyphase/child-process.js.map +1 -0
- package/dist/core/polyphase/commands.d.ts +44 -0
- package/dist/core/polyphase/commands.d.ts.map +1 -0
- package/dist/core/polyphase/commands.js +244 -0
- package/dist/core/polyphase/commands.js.map +1 -0
- package/dist/core/polyphase/details.d.ts +40 -0
- package/dist/core/polyphase/details.d.ts.map +1 -0
- package/dist/core/polyphase/details.js +538 -0
- package/dist/core/polyphase/details.js.map +1 -0
- package/dist/core/polyphase/emitter.d.ts +20 -0
- package/dist/core/polyphase/emitter.d.ts.map +1 -0
- package/dist/core/polyphase/emitter.js +90 -0
- package/dist/core/polyphase/emitter.js.map +1 -0
- package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
- package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
- package/dist/core/polyphase/jsonl-reader.js +161 -0
- package/dist/core/polyphase/jsonl-reader.js.map +1 -0
- package/dist/core/polyphase/keyword.d.ts +27 -0
- package/dist/core/polyphase/keyword.d.ts.map +1 -0
- package/dist/core/polyphase/keyword.js +97 -0
- package/dist/core/polyphase/keyword.js.map +1 -0
- package/dist/core/polyphase/limiter.d.ts +38 -0
- package/dist/core/polyphase/limiter.d.ts.map +1 -0
- package/dist/core/polyphase/limiter.js +129 -0
- package/dist/core/polyphase/limiter.js.map +1 -0
- package/dist/core/polyphase/model-selection.d.ts +35 -0
- package/dist/core/polyphase/model-selection.d.ts.map +1 -0
- package/dist/core/polyphase/model-selection.js +72 -0
- package/dist/core/polyphase/model-selection.js.map +1 -0
- package/dist/core/polyphase/render/format.d.ts +52 -0
- package/dist/core/polyphase/render/format.d.ts.map +1 -0
- package/dist/core/polyphase/render/format.js +169 -0
- package/dist/core/polyphase/render/format.js.map +1 -0
- package/dist/core/polyphase/render/renderers.d.ts +63 -0
- package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
- package/dist/core/polyphase/render/renderers.js +277 -0
- package/dist/core/polyphase/render/renderers.js.map +1 -0
- package/dist/core/polyphase/render/run-block.d.ts +45 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
- package/dist/core/polyphase/render/run-block.js +843 -0
- package/dist/core/polyphase/render/run-block.js.map +1 -0
- package/dist/core/polyphase/render/snapshot.d.ts +106 -0
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
- package/dist/core/polyphase/render/snapshot.js +292 -0
- package/dist/core/polyphase/render/snapshot.js.map +1 -0
- package/dist/core/polyphase/result-text.d.ts +41 -0
- package/dist/core/polyphase/result-text.d.ts.map +1 -0
- package/dist/core/polyphase/result-text.js +326 -0
- package/dist/core/polyphase/result-text.js.map +1 -0
- package/dist/core/polyphase/session.d.ts +33 -0
- package/dist/core/polyphase/session.d.ts.map +1 -0
- package/dist/core/polyphase/session.js +106 -0
- package/dist/core/polyphase/session.js.map +1 -0
- package/dist/core/polyphase/settings.d.ts +18 -0
- package/dist/core/polyphase/settings.d.ts.map +1 -0
- package/dist/core/polyphase/settings.js +93 -0
- package/dist/core/polyphase/settings.js.map +1 -0
- package/dist/core/polyphase/store.d.ts +197 -0
- package/dist/core/polyphase/store.d.ts.map +1 -0
- package/dist/core/polyphase/store.js +558 -0
- package/dist/core/polyphase/store.js.map +1 -0
- package/dist/core/polyphase/types.d.ts +371 -0
- package/dist/core/polyphase/types.d.ts.map +1 -0
- package/dist/core/polyphase/types.js +36 -0
- package/dist/core/polyphase/types.js.map +1 -0
- package/dist/core/polyphase/ui/controller.d.ts +28 -0
- package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
- package/dist/core/polyphase/ui/controller.js +150 -0
- package/dist/core/polyphase/ui/controller.js.map +1 -0
- package/dist/core/polyphase/ui/dock.d.ts +27 -0
- package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
- package/dist/core/polyphase/ui/dock.js +121 -0
- package/dist/core/polyphase/ui/dock.js.map +1 -0
- package/dist/core/polyphase/ui/inspector.d.ts +117 -0
- package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
- package/dist/core/polyphase/ui/inspector.js +1016 -0
- package/dist/core/polyphase/ui/inspector.js.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.js +210 -0
- package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
- package/dist/core/polyphase/update-pump.d.ts +18 -0
- package/dist/core/polyphase/update-pump.d.ts.map +1 -0
- package/dist/core/polyphase/update-pump.js +132 -0
- package/dist/core/polyphase/update-pump.js.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.js +187 -0
- package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
- package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
- package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/guidance.js +119 -0
- package/dist/core/polyphase/workflow/guidance.js.map +1 -0
- package/dist/core/polyphase/workflow/launch.d.ts +41 -0
- package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/launch.js +173 -0
- package/dist/core/polyphase/workflow/launch.js.map +1 -0
- package/dist/core/polyphase/workflow/meta.d.ts +43 -0
- package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/meta.js +529 -0
- package/dist/core/polyphase/workflow/meta.js.map +1 -0
- package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
- package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/prelude.js +93 -0
- package/dist/core/polyphase/workflow/prelude.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
- package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.js +217 -0
- package/dist/core/polyphase/workflow/runtime.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
- package/dist/core/polyphase/workflow/saved.d.ts +55 -0
- package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/saved.js +299 -0
- package/dist/core/polyphase/workflow/saved.js.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.js +66 -0
- package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
- package/dist/core/polyphase/workflow/tool.d.ts +24 -0
- package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/tool.js +139 -0
- package/dist/core/polyphase/workflow/tool.js.map +1 -0
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +27 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/socket-server/permission-relay.js +4 -0
- package/dist/core/socket-server/permission-relay.js.map +1 -1
- package/dist/core/trust-manager.d.ts +3 -2
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +5 -2
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/experimental/micro/runtime.js +1 -1
- package/dist/experimental/micro/runtime.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +18 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +11 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +9 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/prompts/commands/orchestrate.md +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +7 -1
- package/dist/utils/shell.js.map +1 -1
- package/docs/docs.json +4 -0
- package/docs/duet.md +3 -3
- package/docs/environment-variables.md +11 -0
- package/docs/json.md +7 -0
- package/docs/keybindings.md +20 -0
- package/docs/polyphase.md +391 -0
- package/docs/rpc-commands.md +9 -9
- package/docs/settings.md +12 -0
- package/docs/virtual-models.md +3 -3
- package/examples/extensions/preset.ts +3 -3
- package/examples/extensions/subagent/README.md +1 -1
- package/examples/extensions/subagent/agents/planner.md +1 -1
- package/examples/extensions/subagent/agents/reviewer.md +1 -1
- package/examples/extensions/subagent/agents/scout.md +1 -1
- package/examples/extensions/subagent/agents/worker.md +1 -1
- package/examples/extensions/summarize.ts +3 -3
- package/examples/sdk/02-custom-model.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/package.json +10 -10
- package/prompts/commands/orchestrate.md +1 -1
- package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
- package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
- package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permission-relay.js","sourceRoot":"","sources":["../../../src/core/socket-server/permission-relay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAaH,OAAO,EACN,mBAAmB,GAMnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAuCjD;;;;;;;G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IAAI,KAAK,CAAC,MAAM,IAAI,aAAa,CAAC;AAC1D,CAAC;AAED;;;;;;GAMG;AACH,SAAS,OAAO,CAAC,KAAa;IAC7B,IAAI,KAAK,CAAC,MAAM,IAAI,aAAa;QAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IACpE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAChE,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["/**\n * permission-relay — the session's implementation of the {@link PermissionRelay} port.\n *\n * This is the piece that makes an ask raised by the agent reach a phone, and an answer from that\n * phone reach the agent. Everything it does is one of five things:\n *\n * raise build the frame, register it, fan it out, hand back a promise\n * answer first VALID answer wins, exactly once, and everybody is told\n * withdraw some other surface decided; the remote copies come down, saying WHAT it decided\n * replay a client that arrived late is shown what is still unanswered\n * expire nobody answered in time; fail closed, attributed to the system\n *\n * THE ORDER AFTER A WINNING ANSWER IS LOAD-BEARING, and it cost four adversarial rounds:\n *\n * settle → resolve the raise() promise → broadcast `permission_resolved` → append the JSONL record\n *\n * The decorator that owns the caller's promise aborts the LOSING surfaces as part of resolving, and\n * it does so only after it has marked itself settled. Aborting before resolving is a real defect\n * with a real transcript consequence: interactive mode honours an abort by resolving its selector\n * to `undefined`, which its confirm wrapper maps to `false` — a FABRICATED local denial that would\n * overwrite the remote approval that just won, and be recorded as a human's refusal.\n *\n * NOTHING HERE FABRICATES A DECISION. An answer's meaning is read off the offered option's own\n * `decision`; an option nobody offered is silence and consumes nothing; an ask that expires or is\n * cancelled is attributed to `system`, never to a surface that did not act. AND NOTHING HERE\n * GUESSES ONE EITHER: `withdraw` is told what happened by the surface that settled the ask, because\n * when it guessed `cancelled` it wrote that word over an approval whose command had already run.\n */\n\nimport type { PermissionAskDetail } from \"../extensions/types.js\";\nimport type {\n\tPermissionRelay,\n\tRelayAnswer,\n\tRelayAsk,\n\tRelayDecider,\n\tRelayEnded,\n\tRelayOutcome,\n} from \"../permission-relay/types.js\";\nimport type { PermissionResolution } from \"../session-manager.js\";\nimport type { PermissionDelivery } from \"./permission-delivery.js\";\nimport {\n\tCANCELLED_BY_SYSTEM,\n\ttype PermissionEnding,\n\ttype PermissionEntry,\n\ttype PermissionRegistry,\n\ttype RegisteredOption,\n\ttype TerminalDecision,\n} from \"./permission-registry.js\";\nimport { boundedSafeText } from \"./safe-text.js\";\nimport type { PermissionOption, PermissionRequestMessage, PermissionResolvedMessage } from \"./types.js\";\n\n/**\n * The socket server, as this module uses it.\n *\n * Structural on purpose: `SocketServer` satisfies it without this module importing the class, so\n * the relay can be driven by a hand-written double in a unit test and there is no import cycle\n * between the server and the thing it hands answers to.\n */\nexport interface PermissionSocketServer {\n\treadonly permissionCapableClientCount: number;\n\tbroadcastPermissionRequest(message: PermissionRequestMessage): string[];\n\tsendPermissionRequest(clientId: string, message: PermissionRequestMessage): void;\n\tbroadcastPermissionResolved(message: PermissionResolvedMessage): void;\n\tsendErrorToClient(clientId: string, message: string, code?: string): void;\n}\n\n/** The session's own JSONL writer, as this module uses it. `SessionManager` satisfies it. */\nexport interface PermissionRecorder {\n\tappendPermissionResolution(resolution: PermissionResolution): string;\n}\n\n/**\n * What was asked, in exactly the terms an audit row needs.\n *\n * Two things can produce one: a still-pending {@link PermissionEntry}, and an ask this relay\n * REFUSED to raise at all (see {@link SocketPermissionRelayOptions} and `unraised` below). Both are\n * real endings of a real ask and both deserve a row, so the writer takes this rather than an entry.\n */\ninterface ResolutionSubject {\n\treadonly requestId: string;\n\treadonly detail: PermissionAskDetail | undefined;\n\t/** The offered set, in the order it was offered. Empty when nothing was ever offered. */\n\treadonly offeredOptionIds: readonly string[];\n\treadonly requestedAt: string;\n\treadonly deadline: string | null;\n}\n\n/**\n * How many refused-at-raise asks are remembered so their ending can still be recorded truthfully.\n *\n * An entry lives only until the decorator settles that ask and withdraws it, which it does for\n * every ask it settles — so in practice the map holds the handful currently in flight. The cap is\n * the backstop for the one path that settles WITHOUT withdrawing: a local surface whose promise\n * REJECTS, which resolves the caller by rejection and never reaches `settle`.\n */\nconst MAX_UNRAISED = 64;\n\n/**\n * Grapheme budgets, one per wire field.\n *\n * Each is EXACTLY the bound `packages/geist-protocol/src/wire.ts` re-asserts for that field. They\n * are not a second policy: the mirrored schema counts grapheme clusters, `boundedSafeText` bounds\n * grapheme clusters AND UTF-8 bytes, and a frame constructed here therefore cannot be refused by\n * the bridge for its length — a refusal there drops the renderer's connection with close 1008,\n * which is the phone-killing failure the whole capability gate exists to prevent.\n */\nconst FIELD_BUDGET = {\n\ttoolName: 128,\n\tcwd: 1024,\n\ttitle: 200,\n\tmessage: 4000,\n\tcommand: 4000,\n\tpath: 1024,\n\toperation: 128,\n\tlabel: 200,\n} as const;\n\n/** Hard cap on every plain-string id on the wire, in UTF-16 code units. */\nconst MAX_ID_LENGTH = 128;\n\n/** Most options a `permission_request` may carry. */\nconst MAX_OPTIONS = 16;\n\n/** Errors a client gets back when its answer is refused. Codes, so a renderer can switch on them. */\nconst ERROR_UNKNOWN_REQUEST = \"PERMISSION_UNKNOWN_REQUEST\";\nconst ERROR_INVALID_OPTION = \"PERMISSION_INVALID_OPTION\";\nconst ERROR_ALREADY_RESOLVED = \"PERMISSION_ALREADY_RESOLVED\";\n\nexport interface SocketPermissionRelayOptions {\n\tregistry: PermissionRegistry;\n\tdelivery: PermissionDelivery<PermissionEntry>;\n\t/** Read live: the server is replaced when the session is, and stopped before it is. */\n\tserver: () => PermissionSocketServer | null;\n\t/** Read live: the session's own JSONL writer, or null once the session is gone. */\n\trecorder: () => PermissionRecorder | null;\n\t/** The session id the registry is scoped to. */\n\tsessionId: string;\n\t/** The session's resolved working directory, for asks that carry no tool detail of their own. */\n\tcwd: string;\n\t/** Reports non-fatal problems. Defaults to stderr. */\n\tonWarning?: (message: string) => void;\n}\n\n/** The port, plus the four hooks the socket server drives it through. */\nexport interface SocketPermissionRelay extends PermissionRelay {\n\t/** A client answered. Validates, settles at most once, echoes, records. */\n\thandleResponse(message: { requestId: string; optionId: string }, clientId: string): void;\n\t/** A client attached: show it everything still unanswered, exactly once. */\n\treplayTo(clientId: string): void;\n\t/** A client's connection ended: drop its delivery record so a reconnect is shown everything. */\n\tforgetClient(clientId: string): void;\n\t/** The session is going away. Every pending ask ends fail-closed and is recorded as cancelled. */\n\tcancelAll(): void;\n}\n\nexport function createSocketPermissionRelay(options: SocketPermissionRelayOptions): SocketPermissionRelay {\n\tconst { registry, delivery, sessionId } = options;\n\tconst warn = options.onWarning ?? ((message: string) => console.error(message));\n\n\t/**\n\t * Asks this relay REFUSED to raise, kept until their real ending is known.\n\t *\n\t * A refusal is not a decision. `raise` hands back `undefined` for a bound it could not honour —\n\t * `too_many_pending` at 33 concurrent asks, a frame too large, a socket already gone — and in a\n\t * headless session with a phone attached that `undefined` became the decorator's fail-closed\n\t * `false`, which the permission gate reports to the model as \"User denied approval\": a resource\n\t * failure wearing a human's refusal. Nothing was written down, so the record could not\n\t * contradict it either.\n\t *\n\t * Remembering the ask is what makes the two distinguishable AFTERWARDS, where it matters. The\n\t * decorator withdraws every ask it settles, refused ones included, and it states what actually\n\t * happened — so a bound that nobody could answer is recorded as `cancelled` by `system`, and a\n\t * local human who answered the same ask anyway is recorded as having done exactly that.\n\t */\n\tconst unraised = new Map<string, RelayAsk>();\n\n\t/**\n\t * Remember a refused ask and tell the caller the relay is spent.\n\t *\n\t * `reason` is warned about when it is given, and withheld for the ROUTINE refusal — a socket\n\t * that is already gone, which happens on every session replacement and stop. This module's\n\t * warnings default to `console.error`, and a session running under a TUI that owns the terminal\n\t * gets its screen corrupted by an expected teardown message.\n\t */\n\tconst refuse = (ask: RelayAsk, reason?: string): Promise<undefined> => {\n\t\tif (reason !== undefined) warn(`Permission ask not relayed: ${reason}`);\n\t\tunraised.set(ask.requestId, ask);\n\t\twhile (unraised.size > MAX_UNRAISED) {\n\t\t\tconst oldest = unraised.keys().next();\n\t\t\tif (oldest.done === true) break;\n\t\t\tunraised.delete(oldest.value);\n\t\t}\n\t\treturn Promise.resolve(undefined);\n\t};\n\n\tconst subjectOf = (entry: PermissionEntry): ResolutionSubject => ({\n\t\trequestId: entry.requestId,\n\t\tdetail: entry.detail,\n\t\tofferedOptionIds: entry.options.map((option) => option.id),\n\t\trequestedAt: entry.requestedAt,\n\t\tdeadline: entry.frame.deadline,\n\t});\n\n\tconst subjectOfAsk = (ask: RelayAsk): ResolutionSubject => ({\n\t\trequestId: ask.requestId,\n\t\tdetail: ask.detail,\n\t\tofferedOptionIds: ask.options.map((option) => option.id),\n\t\trequestedAt: ask.requestedAt,\n\t\tdeadline: ask.deadline,\n\t});\n\n\t/**\n\t * Announce and record one terminal state.\n\t *\n\t * Called for every ending there is — approved, denied, cancelled, expired — because a record\n\t * that only covers approvals is not an audit trail, it is a highlight reel.\n\t */\n\tconst finish = (\n\t\tentry: PermissionEntry,\n\t\tdecision: TerminalDecision,\n\t\tchosenOptionId: string | null,\n\t\tdecidedBy: RelayDecider,\n\t): void => {\n\t\tdelivery.forgetRequest(entry.requestId);\n\t\tconst resolved: PermissionResolvedMessage = {\n\t\t\ttype: \"permission_resolved\",\n\t\t\trequestId: entry.requestId,\n\t\t\tdecision,\n\t\t\tchosenOptionId,\n\t\t\tsurface: decidedBy.surface,\n\t\t\tclientId: decidedBy.clientId,\n\t\t};\n\t\ttry {\n\t\t\toptions.server()?.broadcastPermissionResolved(resolved);\n\t\t} catch (error) {\n\t\t\twarn(`Permission relay could not announce a resolution: ${describe(error)}`);\n\t\t}\n\t\tappendResolution(subjectOf(entry), decision, chosenOptionId, decidedBy);\n\t};\n\n\t/**\n\t * Record the ending of an ask that was never raised. NOTHING is announced.\n\t *\n\t * No surface was ever shown this ask, so there is no remote copy to take down and a\n\t * `permission_resolved` naming it would be a resolution to a request no client has seen.\n\t * Returns silently for any id that was not refused, which is the ordinary case — the decorator\n\t * withdraws every ask it settles and almost all of them were raised normally.\n\t */\n\tconst finishUnraised = (\n\t\trequestId: string,\n\t\tdecision: TerminalDecision,\n\t\tchosenOptionId: string | null,\n\t\tdecidedBy: RelayDecider,\n\t): void => {\n\t\tconst ask = unraised.get(requestId);\n\t\tif (ask === undefined) return;\n\t\tunraised.delete(requestId);\n\t\tappendResolution(subjectOfAsk(ask), decision, chosenOptionId, decidedBy);\n\t};\n\n\t/**\n\t * Write the session's own record of how a TOOL permission ended.\n\t *\n\t * Scoped to tool permissions deliberately. `PermissionResolutionEntry` is a record ABOUT A TOOL\n\t * CALL — it requires a `toolCallId`, a `toolName` and a cwd — and an extension's plain\n\t * `confirm`/`select`/`input` has none of those. Synthesizing them so that every relayed dialog\n\t * produced a row would put invented tool facts into the one artifact that is supposed to be\n\t * evidence. The dialog is still relayed, still answerable and still echoed to every surface;\n\t * it simply is not written down as a tool permission, because it is not one.\n\t */\n\tconst appendResolution = (\n\t\tsubject: ResolutionSubject,\n\t\tdecision: TerminalDecision,\n\t\tchosenOptionId: string | null,\n\t\tdecidedBy: RelayDecider,\n\t): void => {\n\t\tconst detail = subject.detail;\n\t\tif (detail === undefined || detail.kind !== \"tool_permission\") return;\n\t\tconst recorder = options.recorder();\n\t\tif (recorder === null) return;\n\t\ttry {\n\t\t\trecorder.appendPermissionResolution({\n\t\t\t\trequestId: subject.requestId,\n\t\t\t\t// The FULL id, not the wire's copy: the wire caps ids at 128 code units because a\n\t\t\t\t// renderer's schema does, and this record's job is to name the tool call the\n\t\t\t\t// transcript reports, which nothing here may abbreviate.\n\t\t\t\ttoolCallId: detail.toolCallId,\n\t\t\t\ttoolName: detail.toolName,\n\t\t\t\tcwd: detail.cwd,\n\t\t\t\tdetail: { command: detail.command, path: detail.path, operation: detail.operation },\n\t\t\t\tofferedOptionIds: [...subject.offeredOptionIds],\n\t\t\t\tdecision,\n\t\t\t\tchosenOptionId,\n\t\t\t\tdecidedBy,\n\t\t\t\trequestedAt: subject.requestedAt,\n\t\t\t\tdeadline: subject.deadline,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\t// A session that cannot be written to must not take the answer down with it: the human\n\t\t\t// decided, the agent has its answer, and losing the audit row is the lesser failure.\n\t\t\twarn(`Permission relay could not record a resolution: ${describe(error)}`);\n\t\t}\n\t};\n\n\t/**\n\t * Tell the raiser its ask is OVER — not merely that this relay is spent.\n\t *\n\t * The difference is a fail-OPEN defect. `resolve(undefined)` means \"the relay gave up\", and a\n\t * decorator with a live local surface correctly keeps waiting on it. For an EXPIRY that reading\n\t * is catastrophic: the relay has already broadcast `expired` and appended the audit row, and the\n\t * local dialog was still on screen — a human tapping Approve after that ran the command the\n\t * durable record says was refused. {@link RelayEnded} is the value that takes the ask down\n\t * everywhere, and the ending it carries is the one the registry already tombstoned.\n\t */\n\tconst endAsk = (entry: PermissionEntry, ending: PermissionEnding): void => {\n\t\tconst ended: RelayEnded = {\n\t\t\trequestId: entry.requestId,\n\t\t\t// The two words the wire can carry for an ask nobody answered. `approved`/`denied`\n\t\t\t// cannot reach here: this path exists precisely because nobody decided.\n\t\t\tended: ending.decision === \"expired\" ? \"expired\" : \"cancelled\",\n\t\t\tdecidedBy: ending.decidedBy,\n\t\t};\n\t\tentry.resolve(ended);\n\t};\n\n\tregistry.onExpired((entry, ending) => {\n\t\t// Fail closed, attributed to nobody — and the ask comes down on EVERY surface, including\n\t\t// the local one this relay cannot see. `ending` is the registry's own value, not a second\n\t\t// literal saying the same thing; see PermissionEnding.\n\t\tendAsk(entry, ending);\n\t\tfinish(entry, ending.decision, null, ending.decidedBy);\n\t});\n\n\tconst relay: SocketPermissionRelay = {\n\t\treadWriteClientCount(): number {\n\t\t\t// Live, never cached: clients attach and detach while a session is running, and this\n\t\t\t// number is what `hasUI()` becomes for a headless session. Reporting a stale 1 here is\n\t\t\t// how \"no UI available to request approval\" turns into a fabricated \"User denied\n\t\t\t// approval\" in the transcript.\n\t\t\treturn options.server()?.permissionCapableClientCount ?? 0;\n\t\t},\n\n\t\traise(ask: RelayAsk): Promise<RelayAnswer | RelayEnded | undefined> {\n\t\t\tif (options.server() === null) {\n\t\t\t\t// The socket this relay belonged to is gone — the session was replaced or stopped.\n\t\t\t\t// Registering an ask nobody can be sent and nobody can answer would park the caller\n\t\t\t\t// on it until the clock ran out; saying \"spent\" immediately lets the local surface,\n\t\t\t\t// or the raising method's own fail-closed default, end it now.\n\t\t\t\treturn refuse(ask);\n\t\t\t}\n\t\t\tconst built = buildRequestFrame(ask, options.cwd, registry.expiryMs);\n\t\t\tif (built === undefined) {\n\t\t\t\t// The ask cannot be represented on the wire without changing what is being offered.\n\t\t\t\t// Offering a REPAIRED vocabulary would be worse than offering none: a surface\n\t\t\t\t// showing only the options that happened to fit — an \"Approve\" with its \"Deny\"\n\t\t\t\t// silently dropped — is a trap. Nothing is sent, so the local surface decides, or\n\t\t\t\t// the raising method's own fail-closed default does.\n\t\t\t\treturn refuse(ask, \"the ask cannot be represented on the wire without changing what is offered\");\n\t\t\t}\n\n\t\t\tlet resolveAsk!: (answer: RelayAnswer | RelayEnded | undefined) => void;\n\t\t\tconst answered = new Promise<RelayAnswer | RelayEnded | undefined>((resolve) => {\n\t\t\t\tresolveAsk = resolve;\n\t\t\t});\n\n\t\t\t// REGISTERED BEFORE THE FIRST WRITE. A client can answer before the fan-out loop has\n\t\t\t// finished, and an answer naming an id the registry has never seen is refused as\n\t\t\t// unknown — which would refuse the first correct answer to a real ask.\n\t\t\tconst inserted = registry.insert({\n\t\t\t\trequestId: ask.requestId,\n\t\t\t\tmethod: ask.method,\n\t\t\t\toptions: built.options,\n\t\t\t\tdetail: ask.detail,\n\t\t\t\tframe: built.frame,\n\t\t\t\trequestedAt: built.frame.requestedAt,\n\t\t\t\tresolve: resolveAsk,\n\t\t\t});\n\t\t\tif (!inserted.ok) {\n\t\t\t\t// A BOUND, not a decision. Remembered so the ending the decorator settles on is\n\t\t\t\t// still written down and can be told apart from a human's refusal.\n\t\t\t\treturn refuse(ask, inserted.message);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst reached = options.server()?.broadcastPermissionRequest(built.frame) ?? [];\n\t\t\t\tfor (const clientId of reached) delivery.markDelivered(clientId, ask.requestId);\n\t\t\t} catch (error) {\n\t\t\t\t// A write failure is not an answer. The ask stays pending: a client that reconnects\n\t\t\t\t// is replayed it, and the registry's clock still ends it if nobody ever does.\n\t\t\t\twarn(`Permission ask could not be broadcast: ${describe(error)}`);\n\t\t\t}\n\n\t\t\treturn answered;\n\t\t},\n\n\t\twithdraw(requestId: string, decidedBy: RelayDecider, outcome: RelayOutcome): void {\n\t\t\t// WHAT HAPPENED comes from the caller, which has just settled the ask and holds the\n\t\t\t// value. This used to hardcode `cancelled`, and an approved bash call whose command had\n\t\t\t// already run was written into the JSONL — and broadcast to the attached phone — as\n\t\t\t// `{decision: \"cancelled\", chosenOptionId: null}`. Nothing here reconstructs an outcome.\n\t\t\tconst decision = terminalDecisionFor(outcome);\n\t\t\tconst chosenOptionId =\n\t\t\t\toutcome.kind === \"approved\" || outcome.kind === \"denied\" ? outcome.chosenOptionId : null;\n\n\t\t\t// The decorator withdraws EVERY ask it settles, including the ones a remote answer just\n\t\t\t// settled here. `withdraw` returns undefined for an ask that is already over, and that\n\t\t\t// silence is what stops a second broadcast and a second audit row.\n\t\t\tconst entry = registry.withdraw(requestId, decidedBy, decision);\n\t\t\tif (entry === undefined) {\n\t\t\t\t// Either the ask is already over — the ordinary, silent case — or it was never\n\t\t\t\t// raised because a bound refused it. Only the second writes anything.\n\t\t\t\tfinishUnraised(requestId, decision, chosenOptionId, decidedBy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// The caller already has its answer from the surface that won; this only releases the\n\t\t\t// arm this relay was holding.\n\t\t\tentry.resolve(undefined);\n\t\t\tfinish(entry, decision, chosenOptionId, decidedBy);\n\t\t},\n\n\t\thandleResponse(message: { requestId: string; optionId: string }, clientId: string): void {\n\t\t\tconst decidedBy: RelayDecider = { surface: \"attach\", clientId };\n\t\t\tconst result = registry.settle(sessionId, message.requestId, message.optionId, decidedBy);\n\n\t\t\tif (result.status === \"refused\") {\n\t\t\t\t// The entry is untouched and still answerable — by this client, by another surface,\n\t\t\t\t// or by nobody at all. Saying so beats silence: a phone must be able to tell\n\t\t\t\t// \"answered\" from \"this draht never asked\".\n\t\t\t\toptions\n\t\t\t\t\t.server()\n\t\t\t\t\t?.sendErrorToClient(\n\t\t\t\t\t\tclientId,\n\t\t\t\t\t\tresult.message,\n\t\t\t\t\t\tresult.reason === \"invalid_option\" ? ERROR_INVALID_OPTION : ERROR_UNKNOWN_REQUEST,\n\t\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.status === \"already_resolved\") {\n\t\t\t\t// A client that answered and then dropped its connection comes back to a definite\n\t\t\t\t// account of what happened, rather than to a bare unknown-id refusal that reads\n\t\t\t\t// exactly like a lost answer.\n\t\t\t\toptions.server()?.sendErrorToClient(clientId, result.message, ERROR_ALREADY_RESOLVED);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// settle → resolve → (the decorator aborts the losing surfaces) → broadcast → record.\n\t\t\tresult.entry.resolve(result.answer);\n\t\t\tfinish(result.entry, result.decision, result.chosenOptionId, decidedBy);\n\t\t},\n\n\t\treplayTo(clientId: string): void {\n\t\t\tconst server = options.server();\n\t\t\tif (server === null) return;\n\t\t\tfor (const entry of delivery.pendingFor(clientId)) {\n\t\t\t\ttry {\n\t\t\t\t\t// Targeted, not broadcast: every other client has already been shown this one.\n\t\t\t\t\t// The server drops it silently if this client is read-only or never declared\n\t\t\t\t\t// the capability, which is the correct outcome for both.\n\t\t\t\t\tserver.sendPermissionRequest(clientId, entry.frame);\n\t\t\t\t\tdelivery.markDelivered(clientId, entry.requestId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\twarn(`Permission ask could not be replayed to ${clientId}: ${describe(error)}`);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tforgetClient(clientId: string): void {\n\t\t\tdelivery.forgetClient(clientId);\n\t\t},\n\n\t\tcancelAll(): void {\n\t\t\tconst ending = CANCELLED_BY_SYSTEM;\n\t\t\tfor (const entry of registry.cancelAll(ending.decidedBy)) {\n\t\t\t\t// Same reasoning as expiry: the session is going away, so the ask is OVER and the\n\t\t\t\t// local dialog must come down with it. A `undefined` here leaves a live Approve\n\t\t\t\t// button on an ask this very loop has already recorded as cancelled.\n\t\t\t\tendAsk(entry, ending);\n\t\t\t\tfinish(entry, ending.decision, null, ending.decidedBy);\n\t\t\t}\n\t\t\tdelivery.clear();\n\t\t\t// `unraised` is deliberately NOT cleared. Those asks were never broadcast, so there is\n\t\t\t// nothing of theirs on any client to sweep — and they may still be parked on a LIVE\n\t\t\t// local surface. The session's own recorder outlives this teardown (the bind hands over\n\t\t\t// `session.sessionManager`, which does not go null), so a human who answers one of them\n\t\t\t// a moment later still gets that answer written into the session it belongs to. The map\n\t\t\t// is bounded and dies with this relay object.\n\t\t},\n\t};\n\n\treturn relay;\n}\n\n/**\n * The wire's word for an outcome. All four map exactly — the gap is closed.\n *\n * GAP CLOSED (geist/0.4). `RelayOutcome` has always carried an honest `answered` kind; what was\n * missing was a neutral member on the wire, so this function flattened `answered` onto `cancelled`.\n * That understated: it said an ask came down UNANSWERED about an ask a human had answered and whose\n * tool call had already RUN. The mirror-image falsehood lived in the registry's `decisionFor`,\n * which said `approved` — a grant nobody made — for the remote half of the very same case.\n *\n * The containment argument that let both survive Phase 34 — \"no audit row is written for a `select`\n * or `input`, because `appendResolution` gates on a `tool_permission` detail and those never carry\n * one\" — IS FALSE. Nothing stops an extension attaching such a detail to a `select`, and a probe\n * did; at that point the false word was written into the durable session JSONL, not merely\n * broadcast. See ROADMAP.md, \"Owner: whoever next opens the wire\".\n *\n * `answered` now exists on `TerminalDecision` (`permission-registry.ts`), on\n * `PermissionResolvedMessage.decision` (`socket-server/types.ts`), on\n * `PermissionResolutionEntry.decision` (`core/session-manager.ts`) and on\n * `PermissionResolvedFrameSchema.decision` (`packages/geist-protocol/src/wire.ts`, mirrored through\n * `MIRRORED_FRAMES` and frozen in the `geist-0.4` conformance corpus).\n *\n * IT GRANTS NOTHING. It is neutral, not permissive: any consumer branching on this value must treat\n * `answered` the way it treats `denied`, and only `approved` as permission. What was chosen travels\n * as `chosenOptionId`.\n */\nfunction terminalDecisionFor(outcome: RelayOutcome): TerminalDecision {\n\tswitch (outcome.kind) {\n\t\tcase \"approved\":\n\t\t\treturn \"approved\";\n\t\tcase \"denied\":\n\t\t\treturn \"denied\";\n\t\tcase \"answered\":\n\t\t\treturn \"answered\";\n\t\tcase \"cancelled\":\n\t\t\treturn \"cancelled\";\n\t}\n}\n\n/** What was put on the wire, and the offered set exactly as it was offered. */\ninterface BuiltRequest {\n\treadonly frame: PermissionRequestMessage;\n\treadonly options: readonly RegisteredOption[];\n}\n\n/**\n * Build the `permission_request` frame — the ONE place the wire text is constructed.\n *\n * Every free-text field goes through `boundedSafeText`, which neutralizes control, bidi and\n * invisible code points ONE FOR ONE (never deleting: dropping a control character welds `rm -r` +\n * `f /` into `rm -rf /`) and bounds the result in grapheme clusters AND UTF-8 bytes, preserving the\n * decisive TAIL. `truncated` is the OR of every field's own verdict, so a surface can say that a\n * decision is being made on an abbreviated string.\n *\n * THAT OR STARTS FROM THE PRODUCER'S VERDICT, NOT FROM `false`. The text arriving in `detail` was\n * already neutralized-and-bounded at construction, at a budget EIGHT TIMES TIGHTER than the wire's\n * (512 graphemes against `command`'s 4000) — so a 5000-character command reaches this function\n * already ~530 characters long, every `bound` call below leaves it untouched, and an OR that began\n * at `false` reported `truncated: false` about a string the human was shown 4,572 characters short\n * of. Re-bounding here can only ever discover elisions THIS function performs; the producer's is\n * unrecoverable from the value, so it is carried on the detail and read back below.\n *\n * Returns `undefined` when the ask cannot be carried WITHOUT CHANGING WHAT IS OFFERED — an option\n * id the wire cannot hold, or more options than it can carry. Repairing that would mean offering a\n * different vocabulary than the caller authorised.\n */\nfunction buildRequestFrame(ask: RelayAsk, sessionCwd: string, registryExpiryMs: number): BuiltRequest | undefined {\n\tif (!isWireId(ask.requestId)) return undefined;\n\tif (ask.options.length > MAX_OPTIONS) return undefined;\n\n\tconst detail: PermissionAskDetail | undefined =\n\t\task.detail !== undefined && ask.detail.kind === \"tool_permission\" ? ask.detail : undefined;\n\n\t// Seeded, not initialised to `false`: see the note above. A detail that never elided says\n\t// nothing, and a detail from a producer that does not carry the flag at all leaves this `false`\n\t// exactly as before — so this is additive, never a source of a fabricated `true`.\n\tlet truncated = detail?.truncated === true;\n\tconst bound = (raw: string, budget: number): string => {\n\t\tconst result = boundedSafeText(raw, budget);\n\t\ttruncated = truncated || result.truncated;\n\t\treturn result.value;\n\t};\n\n\tconst options: RegisteredOption[] = [];\n\tconst wireOptions: PermissionOption[] = [];\n\tfor (const option of ask.options) {\n\t\tif (!isWireId(option.id)) return undefined;\n\t\toptions.push({ id: option.id, label: option.label, decision: option.decision });\n\t\t// `decision` rides in `detail.options` and in the registry, not here: the socket wire's\n\t\t// `PermissionOption` is `{id, label}` and the mirrored schema would strip anything else,\n\t\t// so adding it would produce a field a renderer can never rely on.\n\t\twireOptions.push({ id: option.id, label: bound(option.label, FIELD_BUDGET.label) });\n\t}\n\n\t// An ask that gates no tool call still has to fill the frame's required identity fields. It is\n\t// labelled for what it IS — a UI dialog raised by the session — rather than dressed up as a\n\t// tool call that does not exist, and its id is its own request id so nothing joins it to a\n\t// tool call in the transcript.\n\tconst toolCallId = clampId(detail?.toolCallId ?? ask.requestId);\n\tif (toolCallId.clamped) truncated = true;\n\tconst toolName = bound(detail?.toolName ?? `ui:${ask.method}`, FIELD_BUDGET.toolName);\n\tconst cwd = bound(detail?.cwd ?? sessionCwd, FIELD_BUDGET.cwd);\n\n\tconst frame: PermissionRequestMessage = {\n\t\ttype: \"permission_request\",\n\t\trequestId: ask.requestId,\n\t\tmethod: ask.method,\n\t\ttoolCallId: toolCallId.value,\n\t\ttoolName,\n\t\tcwd,\n\t\ttitle: bound(ask.title, FIELD_BUDGET.title),\n\t\tmessage: bound(ask.message ?? \"\", FIELD_BUDGET.message),\n\t\ttruncated: false,\n\t\toptions: wireOptions,\n\t\trequestedAt: ask.requestedAt,\n\t\tdeadline: advisoryDeadline(ask.deadline, registryExpiryMs),\n\t};\n\tif (detail?.command !== undefined) frame.command = bound(detail.command, FIELD_BUDGET.command);\n\tif (detail?.path !== undefined) frame.path = bound(detail.path, FIELD_BUDGET.path);\n\tif (detail?.operation !== undefined) frame.operation = bound(detail.operation, FIELD_BUDGET.operation);\n\t// Set last: every `bound` call above contributes to it, on top of the producer's own verdict.\n\tframe.truncated = truncated;\n\n\treturn { frame, options };\n}\n\n/**\n * The instant a surface may draw a countdown to — ADVISORY, and enforced by nobody remote.\n *\n * The earlier of the two clocks that really exist: the registry's own fail-closed timer, which is\n * armed for every ask, and the caller's declared timeout, which the decorator arms when it holds\n * the only arm and which interactive mode counts down itself. Showing the earlier of them is the\n * only honest countdown — showing the later one would tick past the moment the ask actually stopped\n * being answerable.\n *\n * NOTHING MAY DENY AN ASK BECAUSE THIS INSTANT PASSED. A client-side auto-deny would be a second\n * clock and a new denial path, and it would deny in the name of a human who simply had not looked\n * at their phone yet. Real expiry binds solely to the registry.\n */\nfunction advisoryDeadline(declared: string | null, registryExpiryMs: number): string | null {\n\tconst registryDeadline = new Date(Date.now() + registryExpiryMs).toISOString();\n\tif (declared === null) return registryDeadline;\n\tconst declaredAt = Date.parse(declared);\n\tif (!Number.isFinite(declaredAt)) return registryDeadline;\n\treturn declaredAt < Date.parse(registryDeadline) ? declared : registryDeadline;\n}\n\n/** Whether a plain (non-`safeText`) wire id fits its schema: non-empty, at most 128 code units. */\nfunction isWireId(value: string): boolean {\n\treturn value.length > 0 && value.length <= MAX_ID_LENGTH;\n}\n\n/**\n * Fit an id the wire caps at 128 code units.\n *\n * Only ever applied to `toolCallId`, which is a JOIN KEY for rendering and not something a client\n * echoes back; the audit record keeps the full value. An option id is never clamped — a clamped id\n * would come back not matching the set it was offered from.\n */\nfunction clampId(value: string): { value: string; clamped: boolean } {\n\tif (value.length <= MAX_ID_LENGTH) return { value, clamped: false };\n\treturn { value: value.slice(0, MAX_ID_LENGTH), clamped: true };\n}\n\nfunction describe(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"permission-relay.js","sourceRoot":"","sources":["../../../src/core/socket-server/permission-relay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAaH,OAAO,EACN,mBAAmB,GAMnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAuCjD;;;;;;;GAOG;AACH,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB;;;;;;;;GAQG;AACH,MAAM,YAAY,GAAG;IACpB,QAAQ,EAAE,GAAG;IACb,GAAG,EAAE,IAAI;IACT,KAAK,EAAE,GAAG;IACV,OAAO,EAAE,IAAI;IACb,OAAO,EAAE,IAAI;IACb,IAAI,EAAE,IAAI;IACV,SAAS,EAAE,GAAG;IACd,KAAK,EAAE,GAAG;CACD,CAAC;AAEX,2EAA2E;AAC3E,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B,qDAAqD;AACrD,MAAM,WAAW,GAAG,EAAE,CAAC;AAEvB,qGAAqG;AACrG,MAAM,qBAAqB,GAAG,4BAA4B,CAAC;AAC3D,MAAM,oBAAoB,GAAG,2BAA2B,CAAC;AACzD,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AA6B7D,MAAM,UAAU,2BAA2B,CAAC,OAAqC;IAChF,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAClD,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,IAAI,CAAC,CAAC,OAAe,EAAE,EAAE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B,CAAC,QAAuB,EAAE,gBAAwB;IAC1E,MAAM,gBAAgB,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,gBAAgB,CAAC,CAAC,WAAW,EAAE,CAAC;IAC/E,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,gBAAgB,CAAC;IAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC;QAAE,OAAO,gBAAgB,CAAC;IAC1D,OAAO,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC;AAChF,CAAC;AAED,mGAAmG;AACnG,SAAS,QAAQ,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,aAAa,CAAC;AAC1D,CAAC;AAED;;;;;;GAMG;AACH,SAAS,OAAO,CAAC,KAAa;IAC7B,IAAI,KAAK,CAAC,MAAM,IAAI,aAAa;QAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IACpE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAChE,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["/**\n * permission-relay — the session's implementation of the {@link PermissionRelay} port.\n *\n * This is the piece that makes an ask raised by the agent reach a phone, and an answer from that\n * phone reach the agent. Everything it does is one of five things:\n *\n * raise build the frame, register it, fan it out, hand back a promise\n * answer first VALID answer wins, exactly once, and everybody is told\n * withdraw some other surface decided; the remote copies come down, saying WHAT it decided\n * replay a client that arrived late is shown what is still unanswered\n * expire nobody answered in time; fail closed, attributed to the system\n *\n * THE ORDER AFTER A WINNING ANSWER IS LOAD-BEARING, and it cost four adversarial rounds:\n *\n * settle → resolve the raise() promise → broadcast `permission_resolved` → append the JSONL record\n *\n * The decorator that owns the caller's promise aborts the LOSING surfaces as part of resolving, and\n * it does so only after it has marked itself settled. Aborting before resolving is a real defect\n * with a real transcript consequence: interactive mode honours an abort by resolving its selector\n * to `undefined`, which its confirm wrapper maps to `false` — a FABRICATED local denial that would\n * overwrite the remote approval that just won, and be recorded as a human's refusal.\n *\n * NOTHING HERE FABRICATES A DECISION. An answer's meaning is read off the offered option's own\n * `decision`; an option nobody offered is silence and consumes nothing; an ask that expires or is\n * cancelled is attributed to `system`, never to a surface that did not act. AND NOTHING HERE\n * GUESSES ONE EITHER: `withdraw` is told what happened by the surface that settled the ask, because\n * when it guessed `cancelled` it wrote that word over an approval whose command had already run.\n */\n\nimport type { PermissionAskDetail } from \"../extensions/types.js\";\nimport type {\n\tPermissionRelay,\n\tRelayAnswer,\n\tRelayAsk,\n\tRelayDecider,\n\tRelayEnded,\n\tRelayOutcome,\n} from \"../permission-relay/types.js\";\nimport type { PermissionResolution } from \"../session-manager.js\";\nimport type { PermissionDelivery } from \"./permission-delivery.js\";\nimport {\n\tCANCELLED_BY_SYSTEM,\n\ttype PermissionEnding,\n\ttype PermissionEntry,\n\ttype PermissionRegistry,\n\ttype RegisteredOption,\n\ttype TerminalDecision,\n} from \"./permission-registry.js\";\nimport { boundedSafeText } from \"./safe-text.js\";\nimport type { PermissionOption, PermissionRequestMessage, PermissionResolvedMessage } from \"./types.js\";\n\n/**\n * The socket server, as this module uses it.\n *\n * Structural on purpose: `SocketServer` satisfies it without this module importing the class, so\n * the relay can be driven by a hand-written double in a unit test and there is no import cycle\n * between the server and the thing it hands answers to.\n */\nexport interface PermissionSocketServer {\n\treadonly permissionCapableClientCount: number;\n\tbroadcastPermissionRequest(message: PermissionRequestMessage): string[];\n\tsendPermissionRequest(clientId: string, message: PermissionRequestMessage): void;\n\tbroadcastPermissionResolved(message: PermissionResolvedMessage): void;\n\tsendErrorToClient(clientId: string, message: string, code?: string): void;\n}\n\n/** The session's own JSONL writer, as this module uses it. `SessionManager` satisfies it. */\nexport interface PermissionRecorder {\n\tappendPermissionResolution(resolution: PermissionResolution): string;\n}\n\n/**\n * What was asked, in exactly the terms an audit row needs.\n *\n * Two things can produce one: a still-pending {@link PermissionEntry}, and an ask this relay\n * REFUSED to raise at all (see {@link SocketPermissionRelayOptions} and `unraised` below). Both are\n * real endings of a real ask and both deserve a row, so the writer takes this rather than an entry.\n */\ninterface ResolutionSubject {\n\treadonly requestId: string;\n\treadonly detail: PermissionAskDetail | undefined;\n\t/** The offered set, in the order it was offered. Empty when nothing was ever offered. */\n\treadonly offeredOptionIds: readonly string[];\n\treadonly requestedAt: string;\n\treadonly deadline: string | null;\n}\n\n/**\n * How many refused-at-raise asks are remembered so their ending can still be recorded truthfully.\n *\n * An entry lives only until the decorator settles that ask and withdraws it, which it does for\n * every ask it settles — so in practice the map holds the handful currently in flight. The cap is\n * the backstop for the one path that settles WITHOUT withdrawing: a local surface whose promise\n * REJECTS, which resolves the caller by rejection and never reaches `settle`.\n */\nconst MAX_UNRAISED = 64;\n\n/**\n * Grapheme budgets, one per wire field.\n *\n * Each is EXACTLY the bound `packages/geist-protocol/src/wire.ts` re-asserts for that field. They\n * are not a second policy: the mirrored schema counts grapheme clusters, `boundedSafeText` bounds\n * grapheme clusters AND UTF-8 bytes, and a frame constructed here therefore cannot be refused by\n * the bridge for its length — a refusal there drops the renderer's connection with close 1008,\n * which is the phone-killing failure the whole capability gate exists to prevent.\n */\nconst FIELD_BUDGET = {\n\ttoolName: 128,\n\tcwd: 1024,\n\ttitle: 200,\n\tmessage: 4000,\n\tcommand: 4000,\n\tpath: 1024,\n\toperation: 128,\n\tlabel: 200,\n} as const;\n\n/** Hard cap on every plain-string id on the wire, in UTF-16 code units. */\nconst MAX_ID_LENGTH = 128;\n\n/** Most options a `permission_request` may carry. */\nconst MAX_OPTIONS = 16;\n\n/** Errors a client gets back when its answer is refused. Codes, so a renderer can switch on them. */\nconst ERROR_UNKNOWN_REQUEST = \"PERMISSION_UNKNOWN_REQUEST\";\nconst ERROR_INVALID_OPTION = \"PERMISSION_INVALID_OPTION\";\nconst ERROR_ALREADY_RESOLVED = \"PERMISSION_ALREADY_RESOLVED\";\n\nexport interface SocketPermissionRelayOptions {\n\tregistry: PermissionRegistry;\n\tdelivery: PermissionDelivery<PermissionEntry>;\n\t/** Read live: the server is replaced when the session is, and stopped before it is. */\n\tserver: () => PermissionSocketServer | null;\n\t/** Read live: the session's own JSONL writer, or null once the session is gone. */\n\trecorder: () => PermissionRecorder | null;\n\t/** The session id the registry is scoped to. */\n\tsessionId: string;\n\t/** The session's resolved working directory, for asks that carry no tool detail of their own. */\n\tcwd: string;\n\t/** Reports non-fatal problems. Defaults to stderr. */\n\tonWarning?: (message: string) => void;\n}\n\n/** The port, plus the four hooks the socket server drives it through. */\nexport interface SocketPermissionRelay extends PermissionRelay {\n\t/** A client answered. Validates, settles at most once, echoes, records. */\n\thandleResponse(message: { requestId: string; optionId: string }, clientId: string): void;\n\t/** A client attached: show it everything still unanswered, exactly once. */\n\treplayTo(clientId: string): void;\n\t/** A client's connection ended: drop its delivery record so a reconnect is shown everything. */\n\tforgetClient(clientId: string): void;\n\t/** The session is going away. Every pending ask ends fail-closed and is recorded as cancelled. */\n\tcancelAll(): void;\n}\n\nexport function createSocketPermissionRelay(options: SocketPermissionRelayOptions): SocketPermissionRelay {\n\tconst { registry, delivery, sessionId } = options;\n\tconst warn = options.onWarning ?? ((message: string) => console.error(message));\n\n\t/**\n\t * Asks this relay REFUSED to raise, kept until their real ending is known.\n\t *\n\t * A refusal is not a decision. `raise` hands back `undefined` for a bound it could not honour —\n\t * `too_many_pending` at 33 concurrent asks, a frame too large, a socket already gone — and in a\n\t * headless session with a phone attached that `undefined` became the decorator's fail-closed\n\t * `false`, which the permission gate reports to the model as \"User denied approval\": a resource\n\t * failure wearing a human's refusal. Nothing was written down, so the record could not\n\t * contradict it either.\n\t *\n\t * Remembering the ask is what makes the two distinguishable AFTERWARDS, where it matters. The\n\t * decorator withdraws every ask it settles, refused ones included, and it states what actually\n\t * happened — so a bound that nobody could answer is recorded as `cancelled` by `system`, and a\n\t * local human who answered the same ask anyway is recorded as having done exactly that.\n\t */\n\tconst unraised = new Map<string, RelayAsk>();\n\n\t/**\n\t * Remember a refused ask and tell the caller the relay is spent.\n\t *\n\t * `reason` is warned about when it is given, and withheld for the ROUTINE refusal — a socket\n\t * that is already gone, which happens on every session replacement and stop. This module's\n\t * warnings default to `console.error`, and a session running under a TUI that owns the terminal\n\t * gets its screen corrupted by an expected teardown message.\n\t */\n\tconst refuse = (ask: RelayAsk, reason?: string): Promise<undefined> => {\n\t\tif (reason !== undefined) warn(`Permission ask not relayed: ${reason}`);\n\t\tunraised.set(ask.requestId, ask);\n\t\twhile (unraised.size > MAX_UNRAISED) {\n\t\t\tconst oldest = unraised.keys().next();\n\t\t\tif (oldest.done === true) break;\n\t\t\tunraised.delete(oldest.value);\n\t\t}\n\t\treturn Promise.resolve(undefined);\n\t};\n\n\tconst subjectOf = (entry: PermissionEntry): ResolutionSubject => ({\n\t\trequestId: entry.requestId,\n\t\tdetail: entry.detail,\n\t\tofferedOptionIds: entry.options.map((option) => option.id),\n\t\trequestedAt: entry.requestedAt,\n\t\tdeadline: entry.frame.deadline,\n\t});\n\n\tconst subjectOfAsk = (ask: RelayAsk): ResolutionSubject => ({\n\t\trequestId: ask.requestId,\n\t\tdetail: ask.detail,\n\t\tofferedOptionIds: ask.options.map((option) => option.id),\n\t\trequestedAt: ask.requestedAt,\n\t\tdeadline: ask.deadline,\n\t});\n\n\t/**\n\t * Announce and record one terminal state.\n\t *\n\t * Called for every ending there is — approved, denied, cancelled, expired — because a record\n\t * that only covers approvals is not an audit trail, it is a highlight reel.\n\t */\n\tconst finish = (\n\t\tentry: PermissionEntry,\n\t\tdecision: TerminalDecision,\n\t\tchosenOptionId: string | null,\n\t\tdecidedBy: RelayDecider,\n\t): void => {\n\t\tdelivery.forgetRequest(entry.requestId);\n\t\tconst resolved: PermissionResolvedMessage = {\n\t\t\ttype: \"permission_resolved\",\n\t\t\trequestId: entry.requestId,\n\t\t\tdecision,\n\t\t\tchosenOptionId,\n\t\t\tsurface: decidedBy.surface,\n\t\t\tclientId: decidedBy.clientId,\n\t\t};\n\t\ttry {\n\t\t\toptions.server()?.broadcastPermissionResolved(resolved);\n\t\t} catch (error) {\n\t\t\twarn(`Permission relay could not announce a resolution: ${describe(error)}`);\n\t\t}\n\t\tappendResolution(subjectOf(entry), decision, chosenOptionId, decidedBy);\n\t};\n\n\t/**\n\t * Record the ending of an ask that was never raised. NOTHING is announced.\n\t *\n\t * No surface was ever shown this ask, so there is no remote copy to take down and a\n\t * `permission_resolved` naming it would be a resolution to a request no client has seen.\n\t * Returns silently for any id that was not refused, which is the ordinary case — the decorator\n\t * withdraws every ask it settles and almost all of them were raised normally.\n\t */\n\tconst finishUnraised = (\n\t\trequestId: string,\n\t\tdecision: TerminalDecision,\n\t\tchosenOptionId: string | null,\n\t\tdecidedBy: RelayDecider,\n\t): void => {\n\t\tconst ask = unraised.get(requestId);\n\t\tif (ask === undefined) return;\n\t\tunraised.delete(requestId);\n\t\tappendResolution(subjectOfAsk(ask), decision, chosenOptionId, decidedBy);\n\t};\n\n\t/**\n\t * Write the session's own record of how a TOOL permission ended.\n\t *\n\t * Scoped to tool permissions deliberately. `PermissionResolutionEntry` is a record ABOUT A TOOL\n\t * CALL — it requires a `toolCallId`, a `toolName` and a cwd — and an extension's plain\n\t * `confirm`/`select`/`input` has none of those. Synthesizing them so that every relayed dialog\n\t * produced a row would put invented tool facts into the one artifact that is supposed to be\n\t * evidence. The dialog is still relayed, still answerable and still echoed to every surface;\n\t * it simply is not written down as a tool permission, because it is not one.\n\t */\n\tconst appendResolution = (\n\t\tsubject: ResolutionSubject,\n\t\tdecision: TerminalDecision,\n\t\tchosenOptionId: string | null,\n\t\tdecidedBy: RelayDecider,\n\t): void => {\n\t\tconst detail = subject.detail;\n\t\tif (detail === undefined || detail.kind !== \"tool_permission\") return;\n\t\tconst recorder = options.recorder();\n\t\tif (recorder === null) return;\n\t\ttry {\n\t\t\trecorder.appendPermissionResolution({\n\t\t\t\trequestId: subject.requestId,\n\t\t\t\t// The FULL id, not the wire's copy: the wire caps ids at 128 code units because a\n\t\t\t\t// renderer's schema does, and this record's job is to name the tool call the\n\t\t\t\t// transcript reports, which nothing here may abbreviate.\n\t\t\t\ttoolCallId: detail.toolCallId,\n\t\t\t\ttoolName: detail.toolName,\n\t\t\t\tcwd: detail.cwd,\n\t\t\t\tdetail: { command: detail.command, path: detail.path, operation: detail.operation },\n\t\t\t\tofferedOptionIds: [...subject.offeredOptionIds],\n\t\t\t\tdecision,\n\t\t\t\tchosenOptionId,\n\t\t\t\tdecidedBy,\n\t\t\t\trequestedAt: subject.requestedAt,\n\t\t\t\tdeadline: subject.deadline,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\t// A session that cannot be written to must not take the answer down with it: the human\n\t\t\t// decided, the agent has its answer, and losing the audit row is the lesser failure.\n\t\t\twarn(`Permission relay could not record a resolution: ${describe(error)}`);\n\t\t}\n\t};\n\n\t/**\n\t * Tell the raiser its ask is OVER — not merely that this relay is spent.\n\t *\n\t * The difference is a fail-OPEN defect. `resolve(undefined)` means \"the relay gave up\", and a\n\t * decorator with a live local surface correctly keeps waiting on it. For an EXPIRY that reading\n\t * is catastrophic: the relay has already broadcast `expired` and appended the audit row, and the\n\t * local dialog was still on screen — a human tapping Approve after that ran the command the\n\t * durable record says was refused. {@link RelayEnded} is the value that takes the ask down\n\t * everywhere, and the ending it carries is the one the registry already tombstoned.\n\t */\n\tconst endAsk = (entry: PermissionEntry, ending: PermissionEnding): void => {\n\t\tconst ended: RelayEnded = {\n\t\t\trequestId: entry.requestId,\n\t\t\t// The two words the wire can carry for an ask nobody answered. `approved`/`denied`\n\t\t\t// cannot reach here: this path exists precisely because nobody decided.\n\t\t\tended: ending.decision === \"expired\" ? \"expired\" : \"cancelled\",\n\t\t\tdecidedBy: ending.decidedBy,\n\t\t};\n\t\tentry.resolve(ended);\n\t};\n\n\tregistry.onExpired((entry, ending) => {\n\t\t// Fail closed, attributed to nobody — and the ask comes down on EVERY surface, including\n\t\t// the local one this relay cannot see. `ending` is the registry's own value, not a second\n\t\t// literal saying the same thing; see PermissionEnding.\n\t\tendAsk(entry, ending);\n\t\tfinish(entry, ending.decision, null, ending.decidedBy);\n\t});\n\n\tconst relay: SocketPermissionRelay = {\n\t\treadWriteClientCount(): number {\n\t\t\t// Live, never cached: clients attach and detach while a session is running, and this\n\t\t\t// number is what `hasUI()` becomes for a headless session. Reporting a stale 1 here is\n\t\t\t// how \"no UI available to request approval\" turns into a fabricated \"User denied\n\t\t\t// approval\" in the transcript.\n\t\t\treturn options.server()?.permissionCapableClientCount ?? 0;\n\t\t},\n\n\t\traise(ask: RelayAsk): Promise<RelayAnswer | RelayEnded | undefined> {\n\t\t\tif (options.server() === null) {\n\t\t\t\t// The socket this relay belonged to is gone — the session was replaced or stopped.\n\t\t\t\t// Registering an ask nobody can be sent and nobody can answer would park the caller\n\t\t\t\t// on it until the clock ran out; saying \"spent\" immediately lets the local surface,\n\t\t\t\t// or the raising method's own fail-closed default, end it now.\n\t\t\t\treturn refuse(ask);\n\t\t\t}\n\t\t\tconst built = buildRequestFrame(ask, options.cwd, registry.expiryMs);\n\t\t\tif (built === undefined) {\n\t\t\t\t// The ask cannot be represented on the wire without changing what is being offered.\n\t\t\t\t// Offering a REPAIRED vocabulary would be worse than offering none: a surface\n\t\t\t\t// showing only the options that happened to fit — an \"Approve\" with its \"Deny\"\n\t\t\t\t// silently dropped — is a trap. Nothing is sent, so the local surface decides, or\n\t\t\t\t// the raising method's own fail-closed default does.\n\t\t\t\treturn refuse(ask, \"the ask cannot be represented on the wire without changing what is offered\");\n\t\t\t}\n\n\t\t\tlet resolveAsk!: (answer: RelayAnswer | RelayEnded | undefined) => void;\n\t\t\tconst answered = new Promise<RelayAnswer | RelayEnded | undefined>((resolve) => {\n\t\t\t\tresolveAsk = resolve;\n\t\t\t});\n\n\t\t\t// REGISTERED BEFORE THE FIRST WRITE. A client can answer before the fan-out loop has\n\t\t\t// finished, and an answer naming an id the registry has never seen is refused as\n\t\t\t// unknown — which would refuse the first correct answer to a real ask.\n\t\t\tconst inserted = registry.insert({\n\t\t\t\trequestId: ask.requestId,\n\t\t\t\tmethod: ask.method,\n\t\t\t\toptions: built.options,\n\t\t\t\tdetail: ask.detail,\n\t\t\t\tframe: built.frame,\n\t\t\t\trequestedAt: built.frame.requestedAt,\n\t\t\t\tresolve: resolveAsk,\n\t\t\t});\n\t\t\tif (!inserted.ok) {\n\t\t\t\t// A BOUND, not a decision. Remembered so the ending the decorator settles on is\n\t\t\t\t// still written down and can be told apart from a human's refusal.\n\t\t\t\treturn refuse(ask, inserted.message);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst reached = options.server()?.broadcastPermissionRequest(built.frame) ?? [];\n\t\t\t\tfor (const clientId of reached) delivery.markDelivered(clientId, ask.requestId);\n\t\t\t} catch (error) {\n\t\t\t\t// A write failure is not an answer. The ask stays pending: a client that reconnects\n\t\t\t\t// is replayed it, and the registry's clock still ends it if nobody ever does.\n\t\t\t\twarn(`Permission ask could not be broadcast: ${describe(error)}`);\n\t\t\t}\n\n\t\t\treturn answered;\n\t\t},\n\n\t\twithdraw(requestId: string, decidedBy: RelayDecider, outcome: RelayOutcome): void {\n\t\t\t// WHAT HAPPENED comes from the caller, which has just settled the ask and holds the\n\t\t\t// value. This used to hardcode `cancelled`, and an approved bash call whose command had\n\t\t\t// already run was written into the JSONL — and broadcast to the attached phone — as\n\t\t\t// `{decision: \"cancelled\", chosenOptionId: null}`. Nothing here reconstructs an outcome.\n\t\t\tconst decision = terminalDecisionFor(outcome);\n\t\t\tconst chosenOptionId =\n\t\t\t\toutcome.kind === \"approved\" || outcome.kind === \"denied\" ? outcome.chosenOptionId : null;\n\n\t\t\t// The decorator withdraws EVERY ask it settles, including the ones a remote answer just\n\t\t\t// settled here. `withdraw` returns undefined for an ask that is already over, and that\n\t\t\t// silence is what stops a second broadcast and a second audit row.\n\t\t\tconst entry = registry.withdraw(requestId, decidedBy, decision);\n\t\t\tif (entry === undefined) {\n\t\t\t\t// Either the ask is already over — the ordinary, silent case — or it was never\n\t\t\t\t// raised because a bound refused it. Only the second writes anything.\n\t\t\t\tfinishUnraised(requestId, decision, chosenOptionId, decidedBy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// The caller already has its answer from the surface that won; this only releases the\n\t\t\t// arm this relay was holding.\n\t\t\tentry.resolve(undefined);\n\t\t\tfinish(entry, decision, chosenOptionId, decidedBy);\n\t\t},\n\n\t\thandleResponse(message: { requestId: string; optionId: string }, clientId: string): void {\n\t\t\tconst decidedBy: RelayDecider = { surface: \"attach\", clientId };\n\t\t\tconst result = registry.settle(sessionId, message.requestId, message.optionId, decidedBy);\n\n\t\t\tif (result.status === \"refused\") {\n\t\t\t\t// The entry is untouched and still answerable — by this client, by another surface,\n\t\t\t\t// or by nobody at all. Saying so beats silence: a phone must be able to tell\n\t\t\t\t// \"answered\" from \"this draht never asked\".\n\t\t\t\toptions\n\t\t\t\t\t.server()\n\t\t\t\t\t?.sendErrorToClient(\n\t\t\t\t\t\tclientId,\n\t\t\t\t\t\tresult.message,\n\t\t\t\t\t\tresult.reason === \"invalid_option\" ? ERROR_INVALID_OPTION : ERROR_UNKNOWN_REQUEST,\n\t\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.status === \"already_resolved\") {\n\t\t\t\t// A client that answered and then dropped its connection comes back to a definite\n\t\t\t\t// account of what happened, rather than to a bare unknown-id refusal that reads\n\t\t\t\t// exactly like a lost answer.\n\t\t\t\toptions.server()?.sendErrorToClient(clientId, result.message, ERROR_ALREADY_RESOLVED);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// settle → resolve → (the decorator aborts the losing surfaces) → broadcast → record.\n\t\t\tresult.entry.resolve(result.answer);\n\t\t\tfinish(result.entry, result.decision, result.chosenOptionId, decidedBy);\n\t\t},\n\n\t\treplayTo(clientId: string): void {\n\t\t\tconst server = options.server();\n\t\t\tif (server === null) return;\n\t\t\tfor (const entry of delivery.pendingFor(clientId)) {\n\t\t\t\ttry {\n\t\t\t\t\t// Targeted, not broadcast: every other client has already been shown this one.\n\t\t\t\t\t// The server drops it silently if this client is read-only or never declared\n\t\t\t\t\t// the capability, which is the correct outcome for both.\n\t\t\t\t\tserver.sendPermissionRequest(clientId, entry.frame);\n\t\t\t\t\tdelivery.markDelivered(clientId, entry.requestId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\twarn(`Permission ask could not be replayed to ${clientId}: ${describe(error)}`);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tforgetClient(clientId: string): void {\n\t\t\tdelivery.forgetClient(clientId);\n\t\t},\n\n\t\tcancelAll(): void {\n\t\t\tconst ending = CANCELLED_BY_SYSTEM;\n\t\t\tfor (const entry of registry.cancelAll(ending.decidedBy)) {\n\t\t\t\t// Same reasoning as expiry: the session is going away, so the ask is OVER and the\n\t\t\t\t// local dialog must come down with it. A `undefined` here leaves a live Approve\n\t\t\t\t// button on an ask this very loop has already recorded as cancelled.\n\t\t\t\tendAsk(entry, ending);\n\t\t\t\tfinish(entry, ending.decision, null, ending.decidedBy);\n\t\t\t}\n\t\t\tdelivery.clear();\n\t\t\t// `unraised` is deliberately NOT cleared. Those asks were never broadcast, so there is\n\t\t\t// nothing of theirs on any client to sweep — and they may still be parked on a LIVE\n\t\t\t// local surface. The session's own recorder outlives this teardown (the bind hands over\n\t\t\t// `session.sessionManager`, which does not go null), so a human who answers one of them\n\t\t\t// a moment later still gets that answer written into the session it belongs to. The map\n\t\t\t// is bounded and dies with this relay object.\n\t\t},\n\t};\n\n\treturn relay;\n}\n\n/**\n * The wire's word for an outcome. All four map exactly — the gap is closed.\n *\n * GAP CLOSED (geist/0.4). `RelayOutcome` has always carried an honest `answered` kind; what was\n * missing was a neutral member on the wire, so this function flattened `answered` onto `cancelled`.\n * That understated: it said an ask came down UNANSWERED about an ask a human had answered and whose\n * tool call had already RUN. The mirror-image falsehood lived in the registry's `decisionFor`,\n * which said `approved` — a grant nobody made — for the remote half of the very same case.\n *\n * The containment argument that let both survive Phase 34 — \"no audit row is written for a `select`\n * or `input`, because `appendResolution` gates on a `tool_permission` detail and those never carry\n * one\" — IS FALSE. Nothing stops an extension attaching such a detail to a `select`, and a probe\n * did; at that point the false word was written into the durable session JSONL, not merely\n * broadcast. See ROADMAP.md, \"Owner: whoever next opens the wire\".\n *\n * `answered` now exists on `TerminalDecision` (`permission-registry.ts`), on\n * `PermissionResolvedMessage.decision` (`socket-server/types.ts`), on\n * `PermissionResolutionEntry.decision` (`core/session-manager.ts`) and on\n * `PermissionResolvedFrameSchema.decision` (`packages/geist-protocol/src/wire.ts`, mirrored through\n * `MIRRORED_FRAMES` and frozen in the `geist-0.4` conformance corpus).\n *\n * IT GRANTS NOTHING. It is neutral, not permissive: any consumer branching on this value must treat\n * `answered` the way it treats `denied`, and only `approved` as permission. What was chosen travels\n * as `chosenOptionId`.\n */\nfunction terminalDecisionFor(outcome: RelayOutcome): TerminalDecision {\n\tswitch (outcome.kind) {\n\t\tcase \"approved\":\n\t\t\treturn \"approved\";\n\t\tcase \"denied\":\n\t\t\treturn \"denied\";\n\t\tcase \"answered\":\n\t\t\treturn \"answered\";\n\t\tcase \"cancelled\":\n\t\t\treturn \"cancelled\";\n\t}\n}\n\n/** What was put on the wire, and the offered set exactly as it was offered. */\ninterface BuiltRequest {\n\treadonly frame: PermissionRequestMessage;\n\treadonly options: readonly RegisteredOption[];\n}\n\n/**\n * Build the `permission_request` frame — the ONE place the wire text is constructed.\n *\n * Every free-text field goes through `boundedSafeText`, which neutralizes control, bidi and\n * invisible code points ONE FOR ONE (never deleting: dropping a control character welds `rm -r` +\n * `f /` into `rm -rf /`) and bounds the result in grapheme clusters AND UTF-8 bytes, preserving the\n * decisive TAIL. `truncated` is the OR of every field's own verdict, so a surface can say that a\n * decision is being made on an abbreviated string.\n *\n * THAT OR STARTS FROM THE PRODUCER'S VERDICT, NOT FROM `false`. The text arriving in `detail` was\n * already neutralized-and-bounded at construction, at a budget EIGHT TIMES TIGHTER than the wire's\n * (512 graphemes against `command`'s 4000) — so a 5000-character command reaches this function\n * already ~530 characters long, every `bound` call below leaves it untouched, and an OR that began\n * at `false` reported `truncated: false` about a string the human was shown 4,572 characters short\n * of. Re-bounding here can only ever discover elisions THIS function performs; the producer's is\n * unrecoverable from the value, so it is carried on the detail and read back below.\n *\n * Returns `undefined` when the ask cannot be carried WITHOUT CHANGING WHAT IS OFFERED — an option\n * id the wire cannot hold, or more options than it can carry. Repairing that would mean offering a\n * different vocabulary than the caller authorised.\n */\nfunction buildRequestFrame(ask: RelayAsk, sessionCwd: string, registryExpiryMs: number): BuiltRequest | undefined {\n\tif (!isWireId(ask.requestId)) return undefined;\n\tif (ask.options.length > MAX_OPTIONS) return undefined;\n\n\tconst detail: PermissionAskDetail | undefined =\n\t\task.detail !== undefined && ask.detail.kind === \"tool_permission\" ? ask.detail : undefined;\n\n\t// Seeded, not initialised to `false`: see the note above. A detail that never elided says\n\t// nothing, and a detail from a producer that does not carry the flag at all leaves this `false`\n\t// exactly as before — so this is additive, never a source of a fabricated `true`.\n\tlet truncated = detail?.truncated === true;\n\tconst bound = (raw: string, budget: number): string => {\n\t\tconst result = boundedSafeText(raw, budget);\n\t\ttruncated = truncated || result.truncated;\n\t\treturn result.value;\n\t};\n\n\tconst options: RegisteredOption[] = [];\n\tconst wireOptions: PermissionOption[] = [];\n\tfor (const option of ask.options) {\n\t\tif (!isWireId(option.id)) return undefined;\n\t\toptions.push({ id: option.id, label: option.label, decision: option.decision });\n\t\t// `decision` rides in `detail.options` and in the registry, not here: the socket wire's\n\t\t// `PermissionOption` is `{id, label}` and the mirrored schema would strip anything else,\n\t\t// so adding it would produce a field a renderer can never rely on.\n\t\twireOptions.push({ id: option.id, label: bound(option.label, FIELD_BUDGET.label) });\n\t}\n\n\t// An ask that gates no tool call still has to fill the frame's required identity fields. It is\n\t// labelled for what it IS — a UI dialog raised by the session — rather than dressed up as a\n\t// tool call that does not exist, and its id is its own request id so nothing joins it to a\n\t// tool call in the transcript.\n\tconst toolCallId = clampId(detail?.toolCallId ?? ask.requestId);\n\tif (toolCallId.clamped) truncated = true;\n\tconst toolName = bound(detail?.toolName ?? `ui:${ask.method}`, FIELD_BUDGET.toolName);\n\tconst cwd = bound(detail?.cwd ?? sessionCwd, FIELD_BUDGET.cwd);\n\n\tconst frame: PermissionRequestMessage = {\n\t\ttype: \"permission_request\",\n\t\trequestId: ask.requestId,\n\t\tmethod: ask.method,\n\t\ttoolCallId: toolCallId.value,\n\t\ttoolName,\n\t\tcwd,\n\t\ttitle: bound(ask.title, FIELD_BUDGET.title),\n\t\tmessage: bound(ask.message ?? \"\", FIELD_BUDGET.message),\n\t\ttruncated: false,\n\t\toptions: wireOptions,\n\t\trequestedAt: ask.requestedAt,\n\t\tdeadline: advisoryDeadline(ask.deadline, registryExpiryMs),\n\t};\n\tif (detail?.command !== undefined) frame.command = bound(detail.command, FIELD_BUDGET.command);\n\tif (detail?.path !== undefined) frame.path = bound(detail.path, FIELD_BUDGET.path);\n\tif (detail?.operation !== undefined) frame.operation = bound(detail.operation, FIELD_BUDGET.operation);\n\t// `detail.summary` (a workflow approval's description rows) is deliberately NOT copied onto this\n\t// frame: `PermissionRequestMessage`/`PermissionRequestFrameSchema` (packages/geist-protocol/src/\n\t// wire.ts) have no field for it. It reaches the TUI and an RPC client (same object, by\n\t// reference) but not an attached or geist client. See `PermissionAskDetail.summary`'s doc.\n\t// Set last: every `bound` call above contributes to it, on top of the producer's own verdict.\n\tframe.truncated = truncated;\n\n\treturn { frame, options };\n}\n\n/**\n * The instant a surface may draw a countdown to — ADVISORY, and enforced by nobody remote.\n *\n * The earlier of the two clocks that really exist: the registry's own fail-closed timer, which is\n * armed for every ask, and the caller's declared timeout, which the decorator arms when it holds\n * the only arm and which interactive mode counts down itself. Showing the earlier of them is the\n * only honest countdown — showing the later one would tick past the moment the ask actually stopped\n * being answerable.\n *\n * NOTHING MAY DENY AN ASK BECAUSE THIS INSTANT PASSED. A client-side auto-deny would be a second\n * clock and a new denial path, and it would deny in the name of a human who simply had not looked\n * at their phone yet. Real expiry binds solely to the registry.\n */\nfunction advisoryDeadline(declared: string | null, registryExpiryMs: number): string | null {\n\tconst registryDeadline = new Date(Date.now() + registryExpiryMs).toISOString();\n\tif (declared === null) return registryDeadline;\n\tconst declaredAt = Date.parse(declared);\n\tif (!Number.isFinite(declaredAt)) return registryDeadline;\n\treturn declaredAt < Date.parse(registryDeadline) ? declared : registryDeadline;\n}\n\n/** Whether a plain (non-`safeText`) wire id fits its schema: non-empty, at most 128 code units. */\nfunction isWireId(value: string): boolean {\n\treturn value.length > 0 && value.length <= MAX_ID_LENGTH;\n}\n\n/**\n * Fit an id the wire caps at 128 code units.\n *\n * Only ever applied to `toolCallId`, which is a JOIN KEY for rendering and not something a client\n * echoes back; the audit record keeps the full value. An option id is never clamped — a clamped id\n * would come back not matching the set it was offered from.\n */\nfunction clampId(value: string): { value: string; clamped: boolean } {\n\tif (value.length <= MAX_ID_LENGTH) return { value, clamped: false };\n\treturn { value: value.slice(0, MAX_ID_LENGTH), clamped: true };\n}\n\nfunction describe(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"]}
|
|
@@ -20,8 +20,9 @@ export declare function getProjectTrustOptions(cwd: string, options?: {
|
|
|
20
20
|
/**
|
|
21
21
|
* Returns true when cwd has project-local resources that must be gated by
|
|
22
22
|
* project trust: trust-requiring entries under the cwd's config dir, or an
|
|
23
|
-
* ancestor-loaded resource (.agents/skills, <config dir>/agents
|
|
24
|
-
* of its ancestors, or when the real cwd
|
|
23
|
+
* ancestor-loaded resource (.agents/skills, <config dir>/agents, <config
|
|
24
|
+
* dir>/workflows) in cwd or one of its ancestors, or when the real cwd
|
|
25
|
+
* cannot be determined.
|
|
25
26
|
* Returns false when no such project resources exist. The user/global
|
|
26
27
|
* ~/.agents/skills directory is always treated as a trusted user resource and
|
|
27
28
|
* is ignored here, even when cwd is $HOME.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trust-manager.d.ts","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAcA,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,IAAI,CAAC;AAElD,MAAM,WAAW,sBAAsB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,oBAAoB,CAAC;CAC/B;AAED,MAAM,WAAW,kBAAkB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,kBAAkB,EAAE,CAAC;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;
|
|
1
|
+
{"version":3,"file":"trust-manager.d.ts","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAcA,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,IAAI,CAAC;AAElD,MAAM,WAAW,sBAAsB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,oBAAoB,CAAC;CAC/B;AAED,MAAM,WAAW,kBAAkB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,kBAAkB,EAAE,CAAC;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAoDD,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIzE;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,kBAAkB,EAAE,CA8BpH;AAkFD;;;;;;;;;GASG;AACH,wBAAgB,iCAAiC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CActE;AA6BD,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,SAAS,CAAS;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAE3B;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB,CAErC;IAED,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,sBAAsB,GAAG,IAAI,CAKnD;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,GAAG,IAAI,CAErD;IAED,OAAO,CAAC,SAAS,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAa7C;CACD"}
|
|
@@ -20,6 +20,8 @@ const TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [
|
|
|
20
20
|
const TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES = [
|
|
21
21
|
join(".agents", "skills"),
|
|
22
22
|
join(CONFIG_DIR_NAME, "agents"),
|
|
23
|
+
// Saved workflows spawn agents and are loaded from ancestors like .draht/agents.
|
|
24
|
+
join(CONFIG_DIR_NAME, "workflows"),
|
|
23
25
|
];
|
|
24
26
|
// The key is the spelling resolved through the filesystem; the settings/extensions/skills loaders
|
|
25
27
|
// still read `<lexical cwd>/<config dir>`. A `..` that crossed a symlink makes those two different
|
|
@@ -158,8 +160,9 @@ function withTrustFileLock(path, fn) {
|
|
|
158
160
|
/**
|
|
159
161
|
* Returns true when cwd has project-local resources that must be gated by
|
|
160
162
|
* project trust: trust-requiring entries under the cwd's config dir, or an
|
|
161
|
-
* ancestor-loaded resource (.agents/skills, <config dir>/agents
|
|
162
|
-
* of its ancestors, or when the real cwd
|
|
163
|
+
* ancestor-loaded resource (.agents/skills, <config dir>/agents, <config
|
|
164
|
+
* dir>/workflows) in cwd or one of its ancestors, or when the real cwd
|
|
165
|
+
* cannot be determined.
|
|
163
166
|
* Returns false when no such project resources exist. The user/global
|
|
164
167
|
* ~/.agents/skills directory is always treated as a trusted user resource and
|
|
165
168
|
* is ignored here, even when cwd is $HOME.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trust-manager.js","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EACN,WAAW,EACX,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,YAAY,GACZ,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAuB5C,MAAM,wCAAwC,GAAG;IAChD,eAAe;IACf,UAAU;IACV,iBAAiB;IACjB,YAAY;IACZ,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,WAAW;IACX,kBAAkB;CACT,CAAC;AAEX,+FAA+F;AAC/F,MAAM,0CAA0C,GAAG;IAClD,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC;IACzB,IAAI,CAAC,eAAe,EAAE,QAAQ,CAAC;CACtB,CAAC;AAEX,kGAAkG;AAClG,mGAAmG;AACnG,kGAAkG;AAClG,uFAAuF;AACv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AAI,CAAC;IAC7C,CAAC;IAED,QAAQ,CAAC,GAAW;QACnB,OAAO,iBAAiB,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE;YAC7C,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC3C,OAAO,qBAAqB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,GAAG,CAAC,GAAW,EAAE,QAA8B;QAC9C,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,CAAC,SAA+B;QACtC,iBAAiB,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE;YACtC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC3C,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,SAAS,EAAE,CAAC;gBAC5C,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;gBAC/B,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;oBACvB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;gBAClB,CAAC;qBAAM,CAAC;oBACP,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport {\n\trealHomeDir,\n\trealPathStrict,\n\tresolveRealPrefix,\n\tspellRealPrefix,\n\ttrustKeyPath,\n} from \"../utils/canonical-path.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { stripBom } from \"../utils/text.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record<string, boolean | null | undefined>;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"mcp.json\",\n\t\"permissions.yml\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\n// Loaded from cwd *and every ancestor*, so the gate has to walk the whole chain, not just cwd.\nconst TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES = [\n\tjoin(\".agents\", \"skills\"),\n\tjoin(CONFIG_DIR_NAME, \"agents\"),\n] as const;\n\n// The key is the spelling resolved through the filesystem; the settings/extensions/skills loaders\n// still read `<lexical cwd>/<config dir>`. A `..` that crossed a symlink makes those two different\n// directories, so a decision recorded about the key would authorize project config the user never\n// judged. A plain symlinked cwd is not this: it and its key are one directory on disk.\nfunction trustKeyEscapesProjectConfigDir(cwd: string): boolean {\n\tconst lexicalCwd = resolvePath(cwd);\n\treturn hasProjectConfigResources(lexicalCwd) && realPathStrict(lexicalCwd) !== realPathStrict(cwd);\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tconst prefix = resolveRealPrefix(cwd);\n\t// A stored refusal always binds; a stored trust binds only when the key names the directory whose project config loads. An unresolved suffix is spelled lexically, and a `..` across a symlink resolves away from it: either way the key is not that directory.\n\tconst trustBinds = !prefix.failed && !trustKeyEscapesProjectConfigDir(cwd);\n\tlet currentDir = spellRealPrefix(prefix);\n\twhile (true) {\n\t\tconst value = data[currentDir];\n\t\tif (value === false || (value === true && trustBinds)) {\n\t\t\treturn { path: currentDir, decision: value };\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = trustKeyPath(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = trustKeyPath(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripBom(readFileSync(path, \"utf-8\")));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock<T>(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under the cwd's config dir, or an\n * ancestor-loaded resource (.agents/skills, <config dir>/agents) in cwd or one\n * of its ancestors, or when the real cwd cannot be determined.\n * Returns false when no such project resources exist. The user/global\n * ~/.agents/skills directory is always treated as a trusted user resource and\n * is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\tconst realCwd = realPathStrict(cwd);\n\tif (realCwd === undefined) {\n\t\treturn true;\n\t}\n\tconst realHome = realHomeDir();\n\tconst userAgentsSkillsDir = realHome === undefined ? undefined : join(realHome, \".agents\", \"skills\");\n\tif (hasProjectResourcesAtOrAbove(realCwd, userAgentsSkillsDir)) {\n\t\treturn true;\n\t}\n\t// The ancestor loaders walk `realCwd` now, but the loaders that read the cwd's OWN\n\t// config dir still spell it `resolvePath(config.cwd)`, which collapses `..` lexically.\n\tconst lexicalCwd = resolvePath(cwd);\n\treturn lexicalCwd !== realCwd && hasProjectConfigResources(lexicalCwd);\n}\n\nfunction hasProjectConfigResources(dir: string): boolean {\n\tconst configDir = join(dir, CONFIG_DIR_NAME);\n\treturn TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)));\n}\n\nfunction hasProjectResourcesAtOrAbove(startDir: string, userAgentsSkillsDir: string | undefined): boolean {\n\tif (hasProjectConfigResources(startDir)) {\n\t\treturn true;\n\t}\n\n\tlet currentDir = startDir;\n\twhile (true) {\n\t\tfor (const entry of TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES) {\n\t\t\tconst resourceDir = join(currentDir, entry);\n\t\t\tif (resourceDir !== userAgentsSkillsDir && existsSync(resourceDir)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = trustKeyPath(path);\n\t\t\t\tif (decision === null) {\n\t\t\t\t\tdelete data[key];\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"trust-manager.js","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EACN,WAAW,EACX,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,YAAY,GACZ,MAAM,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AI,QAAQ,KAAK,IAAI,EAAE,CAAC;oBACvB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;gBAClB,CAAC;qBAAM,CAAC;oBACP,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport {\n\trealHomeDir,\n\trealPathStrict,\n\tresolveRealPrefix,\n\tspellRealPrefix,\n\ttrustKeyPath,\n} from \"../utils/canonical-path.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { stripBom } from \"../utils/text.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record<string, boolean | null | undefined>;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"mcp.json\",\n\t\"permissions.yml\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\n// Loaded from cwd *and every ancestor*, so the gate has to walk the whole chain, not just cwd.\nconst TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES = [\n\tjoin(\".agents\", \"skills\"),\n\tjoin(CONFIG_DIR_NAME, \"agents\"),\n\t// Saved workflows spawn agents and are loaded from ancestors like .draht/agents.\n\tjoin(CONFIG_DIR_NAME, \"workflows\"),\n] as const;\n\n// The key is the spelling resolved through the filesystem; the settings/extensions/skills loaders\n// still read `<lexical cwd>/<config dir>`. A `..` that crossed a symlink makes those two different\n// directories, so a decision recorded about the key would authorize project config the user never\n// judged. A plain symlinked cwd is not this: it and its key are one directory on disk.\nfunction trustKeyEscapesProjectConfigDir(cwd: string): boolean {\n\tconst lexicalCwd = resolvePath(cwd);\n\treturn hasProjectConfigResources(lexicalCwd) && realPathStrict(lexicalCwd) !== realPathStrict(cwd);\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tconst prefix = resolveRealPrefix(cwd);\n\t// A stored refusal always binds; a stored trust binds only when the key names the directory whose project config loads. An unresolved suffix is spelled lexically, and a `..` across a symlink resolves away from it: either way the key is not that directory.\n\tconst trustBinds = !prefix.failed && !trustKeyEscapesProjectConfigDir(cwd);\n\tlet currentDir = spellRealPrefix(prefix);\n\twhile (true) {\n\t\tconst value = data[currentDir];\n\t\tif (value === false || (value === true && trustBinds)) {\n\t\t\treturn { path: currentDir, decision: value };\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = trustKeyPath(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = trustKeyPath(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripBom(readFileSync(path, \"utf-8\")));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock<T>(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under the cwd's config dir, or an\n * ancestor-loaded resource (.agents/skills, <config dir>/agents, <config\n * dir>/workflows) in cwd or one of its ancestors, or when the real cwd\n * cannot be determined.\n * Returns false when no such project resources exist. The user/global\n * ~/.agents/skills directory is always treated as a trusted user resource and\n * is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\tconst realCwd = realPathStrict(cwd);\n\tif (realCwd === undefined) {\n\t\treturn true;\n\t}\n\tconst realHome = realHomeDir();\n\tconst userAgentsSkillsDir = realHome === undefined ? undefined : join(realHome, \".agents\", \"skills\");\n\tif (hasProjectResourcesAtOrAbove(realCwd, userAgentsSkillsDir)) {\n\t\treturn true;\n\t}\n\t// The ancestor loaders walk `realCwd` now, but the loaders that read the cwd's OWN\n\t// config dir still spell it `resolvePath(config.cwd)`, which collapses `..` lexically.\n\tconst lexicalCwd = resolvePath(cwd);\n\treturn lexicalCwd !== realCwd && hasProjectConfigResources(lexicalCwd);\n}\n\nfunction hasProjectConfigResources(dir: string): boolean {\n\tconst configDir = join(dir, CONFIG_DIR_NAME);\n\treturn TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)));\n}\n\nfunction hasProjectResourcesAtOrAbove(startDir: string, userAgentsSkillsDir: string | undefined): boolean {\n\tif (hasProjectConfigResources(startDir)) {\n\t\treturn true;\n\t}\n\n\tlet currentDir = startDir;\n\twhile (true) {\n\t\tfor (const entry of TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES) {\n\t\t\tconst resourceDir = join(currentDir, entry);\n\t\t\tif (resourceDir !== userAgentsSkillsDir && existsSync(resourceDir)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = trustKeyPath(path);\n\t\t\t\tif (decision === null) {\n\t\t\t\t\tdelete data[key];\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]}
|
|
@@ -11,7 +11,7 @@ import { refreshModelCatalogs } from "../../modes/interactive/model-catalog-refr
|
|
|
11
11
|
import { createPicoModels, readModelsView } from "./models.js";
|
|
12
12
|
import { selectSession } from "./sessions.js";
|
|
13
13
|
import { createMicroTools } from "./tools.js";
|
|
14
|
-
const DEFAULT_MODEL = { provider: "openai-codex", modelId: "gpt-
|
|
14
|
+
const DEFAULT_MODEL = { provider: "openai-codex", modelId: "gpt-6.1-sol" };
|
|
15
15
|
const SYSTEM_PROMPT = [
|
|
16
16
|
"You are an expert coding assistant working in a terminal.",
|
|
17
17
|
"Use read to inspect files, bash to run commands, edit for precise changes, and write for new files or complete rewrites.",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/experimental/micro/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,aAAa,EAIb,OAAO,EACP,YAAY,EACZ,KAAK,EAEL,cAAc,GAGd,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAIN,kBAAkB,EAClB,0BAA0B,GAG1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAA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UUID } from \"node:crypto\";\nimport {\n\tapplyEnvelope,\n\ttype ConversationView,\n\ttype Entry,\n\ttype Envelope,\n\tHarness,\n\tJsonlStorage,\n\tkinds,\n\ttype ModelRef,\n\tsystemSections,\n\ttype ViewEvent,\n\ttype Watch,\n} from \"@draht/agent-core/experimental/pico3\";\nimport { NodeExecutionEnv } from \"@draht/agent-core/node\";\nimport {\n\ttype AssistantMessage,\n\ttype AuthEvent,\n\ttype AuthPrompt,\n\tclampThinkingLevel,\n\tgetSupportedThinkingLevels,\n\ttype ModelThinkingLevel,\n\ttype Usage,\n} from \"@draht/ai\";\nimport { BACKGROUND_CONTEXT } from \"@draht/chord/context\";\nimport { APP_NAME } from \"../../config.ts\";\nimport { findInitialModel } from \"../../core/model-resolver.ts\";\nimport { ModelRuntime } from \"../../core/model-runtime.ts\";\nimport { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { refreshModelCatalogs } from \"../../modes/interactive/model-catalog-refresh.ts\";\nimport type {\n\tAuthPromptRequest,\n\tMicroController,\n\tMicroNotice,\n\tMicroUsageView,\n\tMicroView,\n\tMicroViewSource,\n} from \"./api.ts\";\nimport { createPicoModels, readModelsView } from \"./models.ts\";\nimport { selectSession } from \"./sessions.ts\";\nimport { createMicroTools } from \"./tools.ts\";\n\nconst DEFAULT_MODEL = { provider: \"openai-codex\", modelId: \"gpt-5.6-sol\" } as const;\n\nconst SYSTEM_PROMPT = [\n\t\"You are an expert coding assistant working in a terminal.\",\n\t\"Use read to inspect files, bash to run commands, edit for precise changes, and write for new files or complete rewrites.\",\n\t\"Keep answers concise and technical.\",\n].join(\"\\n\");\n\nexport interface OpenMicroOptions {\n\tcwd?: string;\n\tcontinueSession?: boolean;\n}\n\nexport interface OpenMicroResult {\n\tview: MicroViewSource;\n\tcontroller: MicroController;\n\tclose(): Promise<void>;\n}\n\nexport async function openMicro(options: OpenMicroOptions = {}): Promise<OpenMicroResult> {\n\tconst location = await selectSession(options.cwd ?? process.cwd(), options.continueSession ?? false);\n\tlet storage: JsonlStorage | undefined;\n\tlet executionEnv: NodeExecutionEnv | undefined;\n\ttry {\n\t\tconst modelRuntime = await ModelRuntime.create();\n\t\tconst settings = SettingsManager.create(location.cwd);\n\t\tconst env = new NodeExecutionEnv({ cwd: location.cwd });\n\t\texecutionEnv = env;\n\t\tconst microTools = createMicroTools(env);\n\t\tconst picoModels = createPicoModels(modelRuntime, microTools.modelMetadata);\n\t\tconst selectedTools = microTools.declarations.map((tool) => tool.name);\n\t\tconst preferredModel = modelRuntime.getModel(DEFAULT_MODEL.provider, DEFAULT_MODEL.modelId);\n\t\tconst initial = location.created\n\t\t\t? preferredModel\n\t\t\t\t? { model: preferredModel, thinkingLevel: \"medium\" as const, fallbackMessage: undefined }\n\t\t\t\t: await findInitialModel({ scopedModels: [], isContinuing: false, modelRuntime })\n\t\t\t: undefined;\n\t\tconst compaction = initial?.model ? settings.getCompactionSettings(initial.model) : undefined;\n\t\tconst threshold =\n\t\t\tinitial?.model && compaction?.enabled\n\t\t\t\t? Math.max(0, initial.model.contextWindow - compaction.reserveTokens)\n\t\t\t\t: 0;\n\n\t\tstorage = await JsonlStorage.open(location.path);\n\t\tconst pendingReports: unknown[] = [];\n\t\tlet report: (error: unknown) => void = (error) => pendingReports.push(error);\n\t\tconst harness = await Harness.open(\n\t\t\tstorage,\n\t\t\t{\n\t\t\t\tmodels: picoModels,\n\t\t\t\ttools: microTools.declarations,\n\t\t\t\troot: {\n\t\t\t\t\trewindable: {\n\t\t\t\t\t\tselectedTools,\n\t\t\t\t\t\tthreshold,\n\t\t\t\t\t\tkeepRecent: compaction?.keepRecentTokens ?? 20_000,\n\t\t\t\t\t\t...(initial?.model\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tmodel: { provider: initial.model.provider, modelId: initial.model.id },\n\t\t\t\t\t\t\t\t\tthinkingLevel: initial.thinkingLevel,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tonReport: (error) => report(error),\n\t\t\t},\n\t\t\tBACKGROUND_CONTEXT,\n\t\t);\n\t\tconst root = await harness.root(BACKGROUND_CONTEXT);\n\t\tconst config = await root.config.get(BACKGROUND_CONTEXT);\n\t\tif (JSON.stringify(config.selectedTools) !== JSON.stringify(selectedTools)) {\n\t\t\tawait root.config.set({ selectedTools }, BACKGROUND_CONTEXT);\n\t\t}\n\n\t\tconst namespace = harness.namespace(\"micro.system\", {});\n\t\tharness.hooks(namespace, kinds.generation, {\n\t\t\tsystemInstructions: ({ sections }) => {\n\t\t\t\tsections.set(systemSections.identity, SYSTEM_PROMPT);\n\t\t\t\tsections.set(systemSections.environment, { cwd: location.cwd });\n\t\t\t},\n\t\t});\n\n\t\tlet watch: Watch = await root.watch(BACKGROUND_CONTEXT);\n\t\tlet cumulativeUsage = await readUsageAccumulator(harness, root.id);\n\t\tlet state: MicroView = {\n\t\t\tsession: { id: location.id, path: location.path, cwd: location.cwd },\n\t\t\tconversation: structuredClone(watch.view),\n\t\t\tmodels: readModelsView(modelRuntime, false),\n\t\t\tusage: usageView(cumulativeUsage, watch.view, modelRuntime),\n\t\t\tnotices: [],\n\t\t};\n\t\tconst listeners = new Set<() => void>();\n\t\tlet nextNoticeId = 1;\n\t\tlet closed = false;\n\t\tconst modelRefreshControllers = new Set<AbortController>();\n\t\tlet loginController: AbortController | undefined;\n\t\tlet pendingAuth:\n\t\t\t| {\n\t\t\t\t\tid: string;\n\t\t\t\t\tresolve(answer: string): void;\n\t\t\t\t\treject(error: Error): void;\n\t\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t\tonAbort(): void;\n\t\t\t }\n\t\t\t| undefined;\n\n\t\tconst publish = (): void => {\n\t\t\tfor (const listener of listeners) listener();\n\t\t};\n\t\tconst update = (patch: Partial<MicroView>): void => {\n\t\t\tstate = { ...state, ...patch };\n\t\t\tpublish();\n\t\t};\n\t\tconst notice = (level: MicroNotice[\"level\"], message: string): void => {\n\t\t\tconst notices = [...state.notices, { id: nextNoticeId++, level, message }].slice(-50);\n\t\t\tupdate({ notices });\n\t\t};\n\t\tconst fail = (error: unknown): void => {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (error instanceof Error && error.name === \"Faulted\") update({ fatal: message });\n\t\t\tnotice(\"error\", message);\n\t\t};\n\t\tconst foldEvent = (event: ViewEvent, previousCompaction: ConversationView[\"compaction\"]): void => {\n\t\t\tif (event.type === \"entry.added\") accumulateUsage(cumulativeUsage, event.entry);\n\t\t\telse if (event.type === \"warning\") notice(\"warning\", event.message);\n\t\t\telse if (event.type === \"generation.failed\") {\n\t\t\t\tnotice(event.reason === \"overflow\" ? \"info\" : \"error\", event.detail);\n\t\t\t} else if (event.type === \"compaction.failed\") notice(\"error\", `Compaction failed: ${event.detail}`);\n\t\t\telse if (event.type === \"compaction.finished\" && previousCompaction?.reason === \"threshold\") {\n\t\t\t\tnotice(\"info\", \"Automatic compaction completed.\");\n\t\t\t}\n\t\t};\n\n\t\tconst envelopes: Envelope[] = [];\n\t\tlet drainScheduled = false;\n\t\tlet restartingWatch = false;\n\t\tconst restartWatch = async (): Promise<void> => {\n\t\t\tif (closed || restartingWatch) return;\n\t\t\trestartingWatch = true;\n\t\t\twatch.stop();\n\t\t\tenvelopes.length = 0;\n\t\t\ttry {\n\t\t\t\twatch = await root.watch(BACKGROUND_CONTEXT);\n\t\t\t\tcumulativeUsage = await readUsageAccumulator(harness, root.id);\n\t\t\t\tstate = {\n\t\t\t\t\t...state,\n\t\t\t\t\tconversation: structuredClone(watch.view),\n\t\t\t\t\tusage: usageView(cumulativeUsage, watch.view, modelRuntime),\n\t\t\t\t};\n\t\t\t\tattachWatch();\n\t\t\t\tpublish();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t} finally {\n\t\t\t\trestartingWatch = false;\n\t\t\t}\n\t\t};\n\t\tconst drain = (): void => {\n\t\t\tdrainScheduled = false;\n\t\t\twhile (!closed && envelopes.length > 0) {\n\t\t\t\tconst envelope = envelopes.shift();\n\t\t\t\tif (!envelope) break;\n\t\t\t\ttry {\n\t\t\t\t\tconst previousCompaction = state.conversation.compaction;\n\t\t\t\t\tconst conversation = applyEnvelope(state.conversation, envelope);\n\t\t\t\t\tstate = { ...state, conversation };\n\t\t\t\t\tfor (const event of envelope.events) foldEvent(event, previousCompaction);\n\t\t\t\t\tstate = { ...state, usage: usageView(cumulativeUsage, conversation, modelRuntime) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfail(error);\n\t\t\t\t\tvoid restartWatch();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tpublish();\n\t\t};\n\t\tfunction attachWatch(): void {\n\t\t\twatch.start((envelope) => {\n\t\t\t\tenvelopes.push(envelope);\n\t\t\t\tif (drainScheduled) return;\n\t\t\t\tdrainScheduled = true;\n\t\t\t\tqueueMicrotask(drain);\n\t\t\t});\n\t\t}\n\t\tattachWatch();\n\t\treport = (error) => {\n\t\t\tfail(error);\n\t\t\tif (watch.closed) void restartWatch();\n\t\t};\n\t\tfor (const error of pendingReports) report(error);\n\n\t\tconst command = async (operation: () => Promise<void>): Promise<void> => {\n\t\t\tif (state.fatal || closed) return;\n\t\t\ttry {\n\t\t\t\tawait operation();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t}\n\t\t};\n\t\tconst refreshModels = async (): Promise<void> => {\n\t\t\tawait command(async () => {\n\t\t\t\tupdate({ models: readModelsView(modelRuntime, true) });\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tmodelRefreshControllers.add(controller);\n\t\t\t\tconst timeout = setTimeout(() => controller.abort(), 15_000);\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await refreshModelCatalogs(modelRuntime, controller.signal);\n\t\t\t\t\tif (result.errors.size > 0) {\n\t\t\t\t\t\tnotice(\"warning\", `Could not refresh: ${[...result.errors.keys()].join(\", \")}`);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tmodelRefreshControllers.delete(controller);\n\t\t\t\t\tupdate({ models: readModelsView(modelRuntime, false) });\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t\tconst clearPendingAuth = (error: Error): void => {\n\t\t\tconst pending = pendingAuth;\n\t\t\tpendingAuth = undefined;\n\t\t\tif (!pending) return;\n\t\t\tpending.signal?.removeEventListener(\"abort\", pending.onAbort);\n\t\t\tpending.reject(error);\n\t\t};\n\t\tconst askAuth = (request: AuthPromptRequest, signal?: AbortSignal): Promise<string> => {\n\t\t\tif (signal?.aborted) return Promise.reject(new Error(\"Login cancelled\"));\n\t\t\tclearPendingAuth(new Error(\"Login prompt replaced\"));\n\t\t\treturn new Promise<string>((resolve, reject) => {\n\t\t\t\tconst id = randomUUID();\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\tif (pendingAuth?.id !== id) return;\n\t\t\t\t\tpendingAuth = undefined;\n\t\t\t\t\tupdate({ auth: state.auth ? { ...state.auth, prompt: undefined } : undefined });\n\t\t\t\t\treject(new Error(\"Login cancelled\"));\n\t\t\t\t};\n\t\t\t\tpendingAuth = { id, resolve, reject, signal, onAbort };\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tif (state.auth) update({ auth: { ...state.auth, prompt: { id, request } } });\n\t\t\t});\n\t\t};\n\t\tconst addAuthNotice = (authEvent: AuthEvent): void => {\n\t\t\tif (!state.auth) return;\n\t\t\tupdate({ auth: { ...state.auth, notices: [...state.auth.notices, structuredClone(authEvent)] } });\n\t\t};\n\n\t\tconst controller: MicroController = {\n\t\t\tprompt: (text) =>\n\t\t\t\tcommand(async () => void (await root.send({ content: text, whenBusy: \"reject\" }, BACKGROUND_CONTEXT))),\n\t\t\tsteer: (text) =>\n\t\t\t\tcommand(async () => void (await root.send({ content: text, whenBusy: \"steer\" }, BACKGROUND_CONTEXT))),\n\t\t\tfollowUp: (text) =>\n\t\t\t\tcommand(async () => void (await root.send({ content: text, whenBusy: \"followUp\" }, BACKGROUND_CONTEXT))),\n\t\t\tcompact: (instructions) => command(async () => void (await root.collapse(instructions, BACKGROUND_CONTEXT))),\n\t\t\tabort: () =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst compactionTask = state.conversation.compaction?.taskId;\n\t\t\t\t\tawait root.abort(BACKGROUND_CONTEXT);\n\t\t\t\t\tif (compactionTask !== undefined) await harness.abortTask(compactionTask, BACKGROUND_CONTEXT);\n\t\t\t\t}),\n\t\t\tcycleThinking: () =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst ref = modelRef(state.conversation.config.model);\n\t\t\t\t\tif (!ref) throw new Error(\"No model selected\");\n\t\t\t\t\tconst model = modelRuntime.getModel(ref.provider, ref.modelId);\n\t\t\t\t\tif (!model) throw new Error(\"Current model is unavailable\");\n\t\t\t\t\tif (!model.reasoning) throw new Error(\"Current model does not support thinking\");\n\t\t\t\t\tconst levels = getSupportedThinkingLevels(model);\n\t\t\t\t\tconst current = String(state.conversation.config.thinkingLevel ?? \"off\");\n\t\t\t\t\tconst index = levels.indexOf(current as ModelThinkingLevel);\n\t\t\t\t\tconst level = levels[(index + 1) % levels.length] ?? \"off\";\n\t\t\t\t\tawait root.config.set({ thinkingLevel: level }, BACKGROUND_CONTEXT);\n\t\t\t\t}),\n\t\t\tsetModel: (ref) =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst model = modelRuntime.getModel(ref.provider, ref.modelId);\n\t\t\t\t\tif (!model) throw new Error(`Unknown model: ${ref.provider}/${ref.modelId}`);\n\t\t\t\t\tconst compact = settings.getCompactionSettings(model);\n\t\t\t\t\tconst currentThinking = String(state.conversation.config.thinkingLevel ?? \"off\") as ModelThinkingLevel;\n\t\t\t\t\tawait root.config.set(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmodel: ref,\n\t\t\t\t\t\t\tthinkingLevel: clampThinkingLevel(model, currentThinking),\n\t\t\t\t\t\t\tthreshold: compact.enabled ? Math.max(0, model.contextWindow - compact.reserveTokens) : 0,\n\t\t\t\t\t\t\tkeepRecent: compact.keepRecentTokens,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tBACKGROUND_CONTEXT,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\trefreshModels,\n\t\t\tlogin: (providerId, authType) =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tif (loginController) throw new Error(\"A login is already running\");\n\t\t\t\t\tconst account = state.models.accounts.find(\n\t\t\t\t\t\t(candidate) => candidate.id === providerId && candidate.authType === authType,\n\t\t\t\t\t);\n\t\t\t\t\tif (!account) throw new Error(`Unknown login method: ${providerId}/${authType}`);\n\t\t\t\t\tif (!account.interactive)\n\t\t\t\t\t\tthrow new Error(`${account.methodName ?? \"Authentication\"} is configured outside ${APP_NAME}`);\n\t\t\t\t\tloginController = new AbortController();\n\t\t\t\t\tupdate({\n\t\t\t\t\t\tauth: { providerId, providerName: account.name, authType, notices: [] },\n\t\t\t\t\t});\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait modelRuntime.login(\n\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\tauthType,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsignal: loginController.signal,\n\t\t\t\t\t\t\t\tprompt: ({ signal, ...request }: AuthPrompt) => askAuth(request, signal),\n\t\t\t\t\t\t\t\tnotify: addAuthNotice,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ getDeviceId: () => settings.getOrCreateDeviceId() },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tnotice(\"info\", `Logged in to ${account.name}.`);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tclearPendingAuth(new Error(\"Login finished\"));\n\t\t\t\t\t\tloginController = undefined;\n\t\t\t\t\t\tupdate({ auth: undefined, models: readModelsView(modelRuntime, false) });\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\treplyAuth: (requestId, answer) =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst pending = pendingAuth;\n\t\t\t\t\tif (!pending || pending.id !== requestId) return;\n\t\t\t\t\tpendingAuth = undefined;\n\t\t\t\t\tpending.signal?.removeEventListener(\"abort\", pending.onAbort);\n\t\t\t\t\tupdate({ auth: state.auth ? { ...state.auth, prompt: undefined } : undefined });\n\t\t\t\t\tif (answer === null) pending.reject(new Error(\"Login cancelled\"));\n\t\t\t\t\telse pending.resolve(answer);\n\t\t\t\t}),\n\t\t\tcancelLogin: () =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tloginController?.abort(new Error(\"Login cancelled\"));\n\t\t\t\t\tclearPendingAuth(new Error(\"Login cancelled\"));\n\t\t\t\t\tupdate({ auth: undefined });\n\t\t\t\t}),\n\t\t};\n\n\t\tconst configuredModel = modelRef(state.conversation.config.model);\n\t\tif (configuredModel && !modelRuntime.getModel(configuredModel.provider, configuredModel.modelId)) {\n\t\t\tnotice(\"warning\", `Saved model is unavailable: ${configuredModel.provider}/${configuredModel.modelId}`);\n\t\t}\n\t\tharness.resume();\n\n\t\treturn {\n\t\t\tview: {\n\t\t\t\tcurrent: () => state,\n\t\t\t\tsubscribe: (listener) => {\n\t\t\t\t\tlisteners.add(listener);\n\t\t\t\t\treturn () => listeners.delete(listener);\n\t\t\t\t},\n\t\t\t},\n\t\t\tcontroller,\n\t\t\tasync close() {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tfor (const controller of modelRefreshControllers) controller.abort(new Error(\"Micro closed\"));\n\t\t\t\tloginController?.abort(new Error(\"Micro closed\"));\n\t\t\t\tclearPendingAuth(new Error(\"Micro closed\"));\n\t\t\t\twatch.stop();\n\t\t\t\tawait harness.close(BACKGROUND_CONTEXT).catch(() => {});\n\t\t\t\tawait env.cleanup(BACKGROUND_CONTEXT).catch(() => {});\n\t\t\t\tawait location.release().catch(() => {});\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tawait storage?.close(BACKGROUND_CONTEXT).catch(() => {});\n\t\tawait executionEnv?.cleanup(BACKGROUND_CONTEXT).catch(() => {});\n\t\tawait location.release().catch(() => {});\n\t\tthrow error;\n\t}\n}\n\ninterface UsageAccumulator {\n\tseen: Set<number>;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalCost: number;\n\tlastAssistantId: number;\n\tlastCacheHitRate?: number;\n}\n\nasync function readUsageAccumulator(harness: Harness, conversationId: number): Promise<UsageAccumulator> {\n\tconst accumulator: UsageAccumulator = {\n\t\tseen: new Set(),\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalCost: 0,\n\t\tlastAssistantId: 0,\n\t};\n\tlet before: number | undefined;\n\tfor (;;) {\n\t\tconst page = await harness.entries(\n\t\t\t{ conversationId, limit: 256, ...(before === undefined ? {} : { before }) },\n\t\t\tBACKGROUND_CONTEXT,\n\t\t);\n\t\tfor (const entry of page) accumulateUsage(accumulator, entry);\n\t\tif (page.length < 256) break;\n\t\tbefore = page.at(-1)?.id;\n\t}\n\treturn accumulator;\n}\n\nfunction accumulateUsage(accumulator: UsageAccumulator, entry: Entry): void {\n\tif (accumulator.seen.has(entry.id)) return;\n\taccumulator.seen.add(entry.id);\n\tconst assistant = assistantMessage(entry);\n\tconst usage = assistant?.usage ?? usageRecord(entry);\n\tif (usage) {\n\t\taccumulator.input += usage.input;\n\t\taccumulator.output += usage.output;\n\t\taccumulator.cacheRead += usage.cacheRead;\n\t\taccumulator.cacheWrite += usage.cacheWrite;\n\t\taccumulator.totalCost += usage.cost.total;\n\t}\n\tif (\n\t\tassistant &&\n\t\tassistant.stopReason !== \"aborted\" &&\n\t\tassistant.stopReason !== \"error\" &&\n\t\tentry.id > accumulator.lastAssistantId\n\t) {\n\t\taccumulator.lastAssistantId = entry.id;\n\t\tconst promptTokens = assistant.usage.input + assistant.usage.cacheRead + assistant.usage.cacheWrite;\n\t\taccumulator.lastCacheHitRate = promptTokens > 0 ? (assistant.usage.cacheRead / promptTokens) * 100 : undefined;\n\t}\n}\n\nfunction usageView(\n\tcumulative: UsageAccumulator,\n\tconversation: ConversationView,\n\tmodelRuntime: ModelRuntime,\n): MicroUsageView {\n\tconst ref = modelRef(conversation.config.model);\n\tconst contextWindow = ref ? (modelRuntime.getModel(ref.provider, ref.modelId)?.contextWindow ?? 0) : 0;\n\tconst newestSummary = conversation.entries\n\t\t.filter((entry) => entry.kind === \"pi.summary\")\n\t\t.map((entry) => entry.id)\n\t\t.at(-1);\n\tconst contextAssistant = [...conversation.entries].reverse().find((entry) => {\n\t\tconst assistant = assistantMessage(entry);\n\t\treturn (\n\t\t\tassistant !== undefined &&\n\t\t\tassistant.stopReason !== \"aborted\" &&\n\t\t\tassistant.stopReason !== \"error\" &&\n\t\t\t(newestSummary === undefined || entry.id > newestSummary)\n\t\t);\n\t});\n\tconst contextUsage = contextAssistant ? assistantMessage(contextAssistant)?.usage : undefined;\n\tconst contextTokens = contextUsage ? contextTokenCount(contextUsage) : null;\n\tconst contextPercent = contextTokens === null || contextWindow <= 0 ? null : (contextTokens / contextWindow) * 100;\n\treturn {\n\t\tinput: cumulative.input,\n\t\toutput: cumulative.output,\n\t\tcacheRead: cumulative.cacheRead,\n\t\tcacheWrite: cumulative.cacheWrite,\n\t\ttotalCost: cumulative.totalCost,\n\t\t...(cumulative.lastCacheHitRate === undefined ? {} : { lastCacheHitRate: cumulative.lastCacheHitRate }),\n\t\tcontextTokens,\n\t\tcontextWindow,\n\t\tcontextPercent,\n\t};\n}\n\nfunction assistantMessage(entry: Entry): AssistantMessage | undefined {\n\tconst message = entry.model?.find((candidate) => candidate.role === \"assistant\");\n\tif (message) return message as unknown as AssistantMessage;\n\tif (entry.kind !== \"pi.assistant\" || !entry.data?.display) return undefined;\n\treturn entry.data.display as unknown as AssistantMessage;\n}\n\nfunction usageRecord(entry: Entry): Usage | undefined {\n\tif (!entry.data?.usage) return undefined;\n\treturn entry.data.usage as unknown as Usage;\n}\n\nfunction contextTokenCount(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\nfunction modelRef(value: unknown): ModelRef | undefined {\n\tif (typeof value !== \"object\" || value === null) return undefined;\n\tconst candidate = value as { provider?: unknown; modelId?: unknown };\n\treturn typeof candidate.provider === \"string\" && typeof candidate.modelId === \"string\"\n\t\t? { provider: candidate.provider, modelId: candidate.modelId }\n\t\t: undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/experimental/micro/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,aAAa,EAIb,OAAO,EACP,YAAY,EACZ,KAAK,EAEL,cAAc,GAGd,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAIN,kBAAkB,EAClB,0BAA0B,GAG1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kDAAkD,CAAC;AASxF,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,aAAa,GAAG,EAAE,QAAQ,EAAE,cAAc,EAAE,OAAO,EAAE,aAAa,EAAW,CAAC;AAEpF,MAAM,aAAa,GAAG;IACrB,2DAA2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,CAAC,IAAI,EAAE,OAAO;QAAE,OAAO,SAAS,CAAC;IAC5E,OAAO,KAAK,CAAC,IAAI,CAAC,OAAsC,CAAC;AAC1D,CAAC;AAED,SAAS,WAAW,CAAC,KAAY;IAChC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK;QAAE,OAAO,SAAS,CAAC;IACzC,OAAO,KAAK,CAAC,IAAI,CAAC,KAAyB,CAAC;AAC7C,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAY;IACtC,OAAO,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC;AAC7F,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAClE,MAAM,SAAS,GAAG,KAAkD,CAAC;IACrE,OAAO,OAAO,SAAS,CAAC,QAAQ,KAAK,QAAQ,IAAI,OAAO,SAAS,CAAC,OAAO,KAAK,QAAQ;QACrF,CAAC,CAAC,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE;QAC9D,CAAC,CAAC,SAAS,CAAC;AACd,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\tapplyEnvelope,\n\ttype ConversationView,\n\ttype Entry,\n\ttype Envelope,\n\tHarness,\n\tJsonlStorage,\n\tkinds,\n\ttype ModelRef,\n\tsystemSections,\n\ttype ViewEvent,\n\ttype Watch,\n} from \"@draht/agent-core/experimental/pico3\";\nimport { NodeExecutionEnv } from \"@draht/agent-core/node\";\nimport {\n\ttype AssistantMessage,\n\ttype AuthEvent,\n\ttype AuthPrompt,\n\tclampThinkingLevel,\n\tgetSupportedThinkingLevels,\n\ttype ModelThinkingLevel,\n\ttype Usage,\n} from \"@draht/ai\";\nimport { BACKGROUND_CONTEXT } from \"@draht/chord/context\";\nimport { APP_NAME } from \"../../config.ts\";\nimport { findInitialModel } from \"../../core/model-resolver.ts\";\nimport { ModelRuntime } from \"../../core/model-runtime.ts\";\nimport { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { refreshModelCatalogs } from \"../../modes/interactive/model-catalog-refresh.ts\";\nimport type {\n\tAuthPromptRequest,\n\tMicroController,\n\tMicroNotice,\n\tMicroUsageView,\n\tMicroView,\n\tMicroViewSource,\n} from \"./api.ts\";\nimport { createPicoModels, readModelsView } from \"./models.ts\";\nimport { selectSession } from \"./sessions.ts\";\nimport { createMicroTools } from \"./tools.ts\";\n\nconst DEFAULT_MODEL = { provider: \"openai-codex\", modelId: \"gpt-6.1-sol\" } as const;\n\nconst SYSTEM_PROMPT = [\n\t\"You are an expert coding assistant working in a terminal.\",\n\t\"Use read to inspect files, bash to run commands, edit for precise changes, and write for new files or complete rewrites.\",\n\t\"Keep answers concise and technical.\",\n].join(\"\\n\");\n\nexport interface OpenMicroOptions {\n\tcwd?: string;\n\tcontinueSession?: boolean;\n}\n\nexport interface OpenMicroResult {\n\tview: MicroViewSource;\n\tcontroller: MicroController;\n\tclose(): Promise<void>;\n}\n\nexport async function openMicro(options: OpenMicroOptions = {}): Promise<OpenMicroResult> {\n\tconst location = await selectSession(options.cwd ?? process.cwd(), options.continueSession ?? false);\n\tlet storage: JsonlStorage | undefined;\n\tlet executionEnv: NodeExecutionEnv | undefined;\n\ttry {\n\t\tconst modelRuntime = await ModelRuntime.create();\n\t\tconst settings = SettingsManager.create(location.cwd);\n\t\tconst env = new NodeExecutionEnv({ cwd: location.cwd });\n\t\texecutionEnv = env;\n\t\tconst microTools = createMicroTools(env);\n\t\tconst picoModels = createPicoModels(modelRuntime, microTools.modelMetadata);\n\t\tconst selectedTools = microTools.declarations.map((tool) => tool.name);\n\t\tconst preferredModel = modelRuntime.getModel(DEFAULT_MODEL.provider, DEFAULT_MODEL.modelId);\n\t\tconst initial = location.created\n\t\t\t? preferredModel\n\t\t\t\t? { model: preferredModel, thinkingLevel: \"medium\" as const, fallbackMessage: undefined }\n\t\t\t\t: await findInitialModel({ scopedModels: [], isContinuing: false, modelRuntime })\n\t\t\t: undefined;\n\t\tconst compaction = initial?.model ? settings.getCompactionSettings(initial.model) : undefined;\n\t\tconst threshold =\n\t\t\tinitial?.model && compaction?.enabled\n\t\t\t\t? Math.max(0, initial.model.contextWindow - compaction.reserveTokens)\n\t\t\t\t: 0;\n\n\t\tstorage = await JsonlStorage.open(location.path);\n\t\tconst pendingReports: unknown[] = [];\n\t\tlet report: (error: unknown) => void = (error) => pendingReports.push(error);\n\t\tconst harness = await Harness.open(\n\t\t\tstorage,\n\t\t\t{\n\t\t\t\tmodels: picoModels,\n\t\t\t\ttools: microTools.declarations,\n\t\t\t\troot: {\n\t\t\t\t\trewindable: {\n\t\t\t\t\t\tselectedTools,\n\t\t\t\t\t\tthreshold,\n\t\t\t\t\t\tkeepRecent: compaction?.keepRecentTokens ?? 20_000,\n\t\t\t\t\t\t...(initial?.model\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tmodel: { provider: initial.model.provider, modelId: initial.model.id },\n\t\t\t\t\t\t\t\t\tthinkingLevel: initial.thinkingLevel,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tonReport: (error) => report(error),\n\t\t\t},\n\t\t\tBACKGROUND_CONTEXT,\n\t\t);\n\t\tconst root = await harness.root(BACKGROUND_CONTEXT);\n\t\tconst config = await root.config.get(BACKGROUND_CONTEXT);\n\t\tif (JSON.stringify(config.selectedTools) !== JSON.stringify(selectedTools)) {\n\t\t\tawait root.config.set({ selectedTools }, BACKGROUND_CONTEXT);\n\t\t}\n\n\t\tconst namespace = harness.namespace(\"micro.system\", {});\n\t\tharness.hooks(namespace, kinds.generation, {\n\t\t\tsystemInstructions: ({ sections }) => {\n\t\t\t\tsections.set(systemSections.identity, SYSTEM_PROMPT);\n\t\t\t\tsections.set(systemSections.environment, { cwd: location.cwd });\n\t\t\t},\n\t\t});\n\n\t\tlet watch: Watch = await root.watch(BACKGROUND_CONTEXT);\n\t\tlet cumulativeUsage = await readUsageAccumulator(harness, root.id);\n\t\tlet state: MicroView = {\n\t\t\tsession: { id: location.id, path: location.path, cwd: location.cwd },\n\t\t\tconversation: structuredClone(watch.view),\n\t\t\tmodels: readModelsView(modelRuntime, false),\n\t\t\tusage: usageView(cumulativeUsage, watch.view, modelRuntime),\n\t\t\tnotices: [],\n\t\t};\n\t\tconst listeners = new Set<() => void>();\n\t\tlet nextNoticeId = 1;\n\t\tlet closed = false;\n\t\tconst modelRefreshControllers = new Set<AbortController>();\n\t\tlet loginController: AbortController | undefined;\n\t\tlet pendingAuth:\n\t\t\t| {\n\t\t\t\t\tid: string;\n\t\t\t\t\tresolve(answer: string): void;\n\t\t\t\t\treject(error: Error): void;\n\t\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t\tonAbort(): void;\n\t\t\t }\n\t\t\t| undefined;\n\n\t\tconst publish = (): void => {\n\t\t\tfor (const listener of listeners) listener();\n\t\t};\n\t\tconst update = (patch: Partial<MicroView>): void => {\n\t\t\tstate = { ...state, ...patch };\n\t\t\tpublish();\n\t\t};\n\t\tconst notice = (level: MicroNotice[\"level\"], message: string): void => {\n\t\t\tconst notices = [...state.notices, { id: nextNoticeId++, level, message }].slice(-50);\n\t\t\tupdate({ notices });\n\t\t};\n\t\tconst fail = (error: unknown): void => {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (error instanceof Error && error.name === \"Faulted\") update({ fatal: message });\n\t\t\tnotice(\"error\", message);\n\t\t};\n\t\tconst foldEvent = (event: ViewEvent, previousCompaction: ConversationView[\"compaction\"]): void => {\n\t\t\tif (event.type === \"entry.added\") accumulateUsage(cumulativeUsage, event.entry);\n\t\t\telse if (event.type === \"warning\") notice(\"warning\", event.message);\n\t\t\telse if (event.type === \"generation.failed\") {\n\t\t\t\tnotice(event.reason === \"overflow\" ? \"info\" : \"error\", event.detail);\n\t\t\t} else if (event.type === \"compaction.failed\") notice(\"error\", `Compaction failed: ${event.detail}`);\n\t\t\telse if (event.type === \"compaction.finished\" && previousCompaction?.reason === \"threshold\") {\n\t\t\t\tnotice(\"info\", \"Automatic compaction completed.\");\n\t\t\t}\n\t\t};\n\n\t\tconst envelopes: Envelope[] = [];\n\t\tlet drainScheduled = false;\n\t\tlet restartingWatch = false;\n\t\tconst restartWatch = async (): Promise<void> => {\n\t\t\tif (closed || restartingWatch) return;\n\t\t\trestartingWatch = true;\n\t\t\twatch.stop();\n\t\t\tenvelopes.length = 0;\n\t\t\ttry {\n\t\t\t\twatch = await root.watch(BACKGROUND_CONTEXT);\n\t\t\t\tcumulativeUsage = await readUsageAccumulator(harness, root.id);\n\t\t\t\tstate = {\n\t\t\t\t\t...state,\n\t\t\t\t\tconversation: structuredClone(watch.view),\n\t\t\t\t\tusage: usageView(cumulativeUsage, watch.view, modelRuntime),\n\t\t\t\t};\n\t\t\t\tattachWatch();\n\t\t\t\tpublish();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t} finally {\n\t\t\t\trestartingWatch = false;\n\t\t\t}\n\t\t};\n\t\tconst drain = (): void => {\n\t\t\tdrainScheduled = false;\n\t\t\twhile (!closed && envelopes.length > 0) {\n\t\t\t\tconst envelope = envelopes.shift();\n\t\t\t\tif (!envelope) break;\n\t\t\t\ttry {\n\t\t\t\t\tconst previousCompaction = state.conversation.compaction;\n\t\t\t\t\tconst conversation = applyEnvelope(state.conversation, envelope);\n\t\t\t\t\tstate = { ...state, conversation };\n\t\t\t\t\tfor (const event of envelope.events) foldEvent(event, previousCompaction);\n\t\t\t\t\tstate = { ...state, usage: usageView(cumulativeUsage, conversation, modelRuntime) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfail(error);\n\t\t\t\t\tvoid restartWatch();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tpublish();\n\t\t};\n\t\tfunction attachWatch(): void {\n\t\t\twatch.start((envelope) => {\n\t\t\t\tenvelopes.push(envelope);\n\t\t\t\tif (drainScheduled) return;\n\t\t\t\tdrainScheduled = true;\n\t\t\t\tqueueMicrotask(drain);\n\t\t\t});\n\t\t}\n\t\tattachWatch();\n\t\treport = (error) => {\n\t\t\tfail(error);\n\t\t\tif (watch.closed) void restartWatch();\n\t\t};\n\t\tfor (const error of pendingReports) report(error);\n\n\t\tconst command = async (operation: () => Promise<void>): Promise<void> => {\n\t\t\tif (state.fatal || closed) return;\n\t\t\ttry {\n\t\t\t\tawait operation();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t}\n\t\t};\n\t\tconst refreshModels = async (): Promise<void> => {\n\t\t\tawait command(async () => {\n\t\t\t\tupdate({ models: readModelsView(modelRuntime, true) });\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tmodelRefreshControllers.add(controller);\n\t\t\t\tconst timeout = setTimeout(() => controller.abort(), 15_000);\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await refreshModelCatalogs(modelRuntime, controller.signal);\n\t\t\t\t\tif (result.errors.size > 0) {\n\t\t\t\t\t\tnotice(\"warning\", `Could not refresh: ${[...result.errors.keys()].join(\", \")}`);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tmodelRefreshControllers.delete(controller);\n\t\t\t\t\tupdate({ models: readModelsView(modelRuntime, false) });\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t\tconst clearPendingAuth = (error: Error): void => {\n\t\t\tconst pending = pendingAuth;\n\t\t\tpendingAuth = undefined;\n\t\t\tif (!pending) return;\n\t\t\tpending.signal?.removeEventListener(\"abort\", pending.onAbort);\n\t\t\tpending.reject(error);\n\t\t};\n\t\tconst askAuth = (request: AuthPromptRequest, signal?: AbortSignal): Promise<string> => {\n\t\t\tif (signal?.aborted) return Promise.reject(new Error(\"Login cancelled\"));\n\t\t\tclearPendingAuth(new Error(\"Login prompt replaced\"));\n\t\t\treturn new Promise<string>((resolve, reject) => {\n\t\t\t\tconst id = randomUUID();\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\tif (pendingAuth?.id !== id) return;\n\t\t\t\t\tpendingAuth = undefined;\n\t\t\t\t\tupdate({ auth: state.auth ? { ...state.auth, prompt: undefined } : undefined });\n\t\t\t\t\treject(new Error(\"Login cancelled\"));\n\t\t\t\t};\n\t\t\t\tpendingAuth = { id, resolve, reject, signal, onAbort };\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tif (state.auth) update({ auth: { ...state.auth, prompt: { id, request } } });\n\t\t\t});\n\t\t};\n\t\tconst addAuthNotice = (authEvent: AuthEvent): void => {\n\t\t\tif (!state.auth) return;\n\t\t\tupdate({ auth: { ...state.auth, notices: [...state.auth.notices, structuredClone(authEvent)] } });\n\t\t};\n\n\t\tconst controller: MicroController = {\n\t\t\tprompt: (text) =>\n\t\t\t\tcommand(async () => void (await root.send({ content: text, whenBusy: \"reject\" }, BACKGROUND_CONTEXT))),\n\t\t\tsteer: (text) =>\n\t\t\t\tcommand(async () => void (await root.send({ content: text, whenBusy: \"steer\" }, BACKGROUND_CONTEXT))),\n\t\t\tfollowUp: (text) =>\n\t\t\t\tcommand(async () => void (await root.send({ content: text, whenBusy: \"followUp\" }, BACKGROUND_CONTEXT))),\n\t\t\tcompact: (instructions) => command(async () => void (await root.collapse(instructions, BACKGROUND_CONTEXT))),\n\t\t\tabort: () =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst compactionTask = state.conversation.compaction?.taskId;\n\t\t\t\t\tawait root.abort(BACKGROUND_CONTEXT);\n\t\t\t\t\tif (compactionTask !== undefined) await harness.abortTask(compactionTask, BACKGROUND_CONTEXT);\n\t\t\t\t}),\n\t\t\tcycleThinking: () =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst ref = modelRef(state.conversation.config.model);\n\t\t\t\t\tif (!ref) throw new Error(\"No model selected\");\n\t\t\t\t\tconst model = modelRuntime.getModel(ref.provider, ref.modelId);\n\t\t\t\t\tif (!model) throw new Error(\"Current model is unavailable\");\n\t\t\t\t\tif (!model.reasoning) throw new Error(\"Current model does not support thinking\");\n\t\t\t\t\tconst levels = getSupportedThinkingLevels(model);\n\t\t\t\t\tconst current = String(state.conversation.config.thinkingLevel ?? \"off\");\n\t\t\t\t\tconst index = levels.indexOf(current as ModelThinkingLevel);\n\t\t\t\t\tconst level = levels[(index + 1) % levels.length] ?? \"off\";\n\t\t\t\t\tawait root.config.set({ thinkingLevel: level }, BACKGROUND_CONTEXT);\n\t\t\t\t}),\n\t\t\tsetModel: (ref) =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst model = modelRuntime.getModel(ref.provider, ref.modelId);\n\t\t\t\t\tif (!model) throw new Error(`Unknown model: ${ref.provider}/${ref.modelId}`);\n\t\t\t\t\tconst compact = settings.getCompactionSettings(model);\n\t\t\t\t\tconst currentThinking = String(state.conversation.config.thinkingLevel ?? \"off\") as ModelThinkingLevel;\n\t\t\t\t\tawait root.config.set(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmodel: ref,\n\t\t\t\t\t\t\tthinkingLevel: clampThinkingLevel(model, currentThinking),\n\t\t\t\t\t\t\tthreshold: compact.enabled ? Math.max(0, model.contextWindow - compact.reserveTokens) : 0,\n\t\t\t\t\t\t\tkeepRecent: compact.keepRecentTokens,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tBACKGROUND_CONTEXT,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\trefreshModels,\n\t\t\tlogin: (providerId, authType) =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tif (loginController) throw new Error(\"A login is already running\");\n\t\t\t\t\tconst account = state.models.accounts.find(\n\t\t\t\t\t\t(candidate) => candidate.id === providerId && candidate.authType === authType,\n\t\t\t\t\t);\n\t\t\t\t\tif (!account) throw new Error(`Unknown login method: ${providerId}/${authType}`);\n\t\t\t\t\tif (!account.interactive)\n\t\t\t\t\t\tthrow new Error(`${account.methodName ?? \"Authentication\"} is configured outside ${APP_NAME}`);\n\t\t\t\t\tloginController = new AbortController();\n\t\t\t\t\tupdate({\n\t\t\t\t\t\tauth: { providerId, providerName: account.name, authType, notices: [] },\n\t\t\t\t\t});\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait modelRuntime.login(\n\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\tauthType,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsignal: loginController.signal,\n\t\t\t\t\t\t\t\tprompt: ({ signal, ...request }: AuthPrompt) => askAuth(request, signal),\n\t\t\t\t\t\t\t\tnotify: addAuthNotice,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ getDeviceId: () => settings.getOrCreateDeviceId() },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tnotice(\"info\", `Logged in to ${account.name}.`);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tclearPendingAuth(new Error(\"Login finished\"));\n\t\t\t\t\t\tloginController = undefined;\n\t\t\t\t\t\tupdate({ auth: undefined, models: readModelsView(modelRuntime, false) });\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\treplyAuth: (requestId, answer) =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tconst pending = pendingAuth;\n\t\t\t\t\tif (!pending || pending.id !== requestId) return;\n\t\t\t\t\tpendingAuth = undefined;\n\t\t\t\t\tpending.signal?.removeEventListener(\"abort\", pending.onAbort);\n\t\t\t\t\tupdate({ auth: state.auth ? { ...state.auth, prompt: undefined } : undefined });\n\t\t\t\t\tif (answer === null) pending.reject(new Error(\"Login cancelled\"));\n\t\t\t\t\telse pending.resolve(answer);\n\t\t\t\t}),\n\t\t\tcancelLogin: () =>\n\t\t\t\tcommand(async () => {\n\t\t\t\t\tloginController?.abort(new Error(\"Login cancelled\"));\n\t\t\t\t\tclearPendingAuth(new Error(\"Login cancelled\"));\n\t\t\t\t\tupdate({ auth: undefined });\n\t\t\t\t}),\n\t\t};\n\n\t\tconst configuredModel = modelRef(state.conversation.config.model);\n\t\tif (configuredModel && !modelRuntime.getModel(configuredModel.provider, configuredModel.modelId)) {\n\t\t\tnotice(\"warning\", `Saved model is unavailable: ${configuredModel.provider}/${configuredModel.modelId}`);\n\t\t}\n\t\tharness.resume();\n\n\t\treturn {\n\t\t\tview: {\n\t\t\t\tcurrent: () => state,\n\t\t\t\tsubscribe: (listener) => {\n\t\t\t\t\tlisteners.add(listener);\n\t\t\t\t\treturn () => listeners.delete(listener);\n\t\t\t\t},\n\t\t\t},\n\t\t\tcontroller,\n\t\t\tasync close() {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tfor (const controller of modelRefreshControllers) controller.abort(new Error(\"Micro closed\"));\n\t\t\t\tloginController?.abort(new Error(\"Micro closed\"));\n\t\t\t\tclearPendingAuth(new Error(\"Micro closed\"));\n\t\t\t\twatch.stop();\n\t\t\t\tawait harness.close(BACKGROUND_CONTEXT).catch(() => {});\n\t\t\t\tawait env.cleanup(BACKGROUND_CONTEXT).catch(() => {});\n\t\t\t\tawait location.release().catch(() => {});\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tawait storage?.close(BACKGROUND_CONTEXT).catch(() => {});\n\t\tawait executionEnv?.cleanup(BACKGROUND_CONTEXT).catch(() => {});\n\t\tawait location.release().catch(() => {});\n\t\tthrow error;\n\t}\n}\n\ninterface UsageAccumulator {\n\tseen: Set<number>;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalCost: number;\n\tlastAssistantId: number;\n\tlastCacheHitRate?: number;\n}\n\nasync function readUsageAccumulator(harness: Harness, conversationId: number): Promise<UsageAccumulator> {\n\tconst accumulator: UsageAccumulator = {\n\t\tseen: new Set(),\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalCost: 0,\n\t\tlastAssistantId: 0,\n\t};\n\tlet before: number | undefined;\n\tfor (;;) {\n\t\tconst page = await harness.entries(\n\t\t\t{ conversationId, limit: 256, ...(before === undefined ? {} : { before }) },\n\t\t\tBACKGROUND_CONTEXT,\n\t\t);\n\t\tfor (const entry of page) accumulateUsage(accumulator, entry);\n\t\tif (page.length < 256) break;\n\t\tbefore = page.at(-1)?.id;\n\t}\n\treturn accumulator;\n}\n\nfunction accumulateUsage(accumulator: UsageAccumulator, entry: Entry): void {\n\tif (accumulator.seen.has(entry.id)) return;\n\taccumulator.seen.add(entry.id);\n\tconst assistant = assistantMessage(entry);\n\tconst usage = assistant?.usage ?? usageRecord(entry);\n\tif (usage) {\n\t\taccumulator.input += usage.input;\n\t\taccumulator.output += usage.output;\n\t\taccumulator.cacheRead += usage.cacheRead;\n\t\taccumulator.cacheWrite += usage.cacheWrite;\n\t\taccumulator.totalCost += usage.cost.total;\n\t}\n\tif (\n\t\tassistant &&\n\t\tassistant.stopReason !== \"aborted\" &&\n\t\tassistant.stopReason !== \"error\" &&\n\t\tentry.id > accumulator.lastAssistantId\n\t) {\n\t\taccumulator.lastAssistantId = entry.id;\n\t\tconst promptTokens = assistant.usage.input + assistant.usage.cacheRead + assistant.usage.cacheWrite;\n\t\taccumulator.lastCacheHitRate = promptTokens > 0 ? (assistant.usage.cacheRead / promptTokens) * 100 : undefined;\n\t}\n}\n\nfunction usageView(\n\tcumulative: UsageAccumulator,\n\tconversation: ConversationView,\n\tmodelRuntime: ModelRuntime,\n): MicroUsageView {\n\tconst ref = modelRef(conversation.config.model);\n\tconst contextWindow = ref ? (modelRuntime.getModel(ref.provider, ref.modelId)?.contextWindow ?? 0) : 0;\n\tconst newestSummary = conversation.entries\n\t\t.filter((entry) => entry.kind === \"pi.summary\")\n\t\t.map((entry) => entry.id)\n\t\t.at(-1);\n\tconst contextAssistant = [...conversation.entries].reverse().find((entry) => {\n\t\tconst assistant = assistantMessage(entry);\n\t\treturn (\n\t\t\tassistant !== undefined &&\n\t\t\tassistant.stopReason !== \"aborted\" &&\n\t\t\tassistant.stopReason !== \"error\" &&\n\t\t\t(newestSummary === undefined || entry.id > newestSummary)\n\t\t);\n\t});\n\tconst contextUsage = contextAssistant ? assistantMessage(contextAssistant)?.usage : undefined;\n\tconst contextTokens = contextUsage ? contextTokenCount(contextUsage) : null;\n\tconst contextPercent = contextTokens === null || contextWindow <= 0 ? null : (contextTokens / contextWindow) * 100;\n\treturn {\n\t\tinput: cumulative.input,\n\t\toutput: cumulative.output,\n\t\tcacheRead: cumulative.cacheRead,\n\t\tcacheWrite: cumulative.cacheWrite,\n\t\ttotalCost: cumulative.totalCost,\n\t\t...(cumulative.lastCacheHitRate === undefined ? {} : { lastCacheHitRate: cumulative.lastCacheHitRate }),\n\t\tcontextTokens,\n\t\tcontextWindow,\n\t\tcontextPercent,\n\t};\n}\n\nfunction assistantMessage(entry: Entry): AssistantMessage | undefined {\n\tconst message = entry.model?.find((candidate) => candidate.role === \"assistant\");\n\tif (message) return message as unknown as AssistantMessage;\n\tif (entry.kind !== \"pi.assistant\" || !entry.data?.display) return undefined;\n\treturn entry.data.display as unknown as AssistantMessage;\n}\n\nfunction usageRecord(entry: Entry): Usage | undefined {\n\tif (!entry.data?.usage) return undefined;\n\treturn entry.data.usage as unknown as Usage;\n}\n\nfunction contextTokenCount(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\nfunction modelRef(value: unknown): ModelRef | undefined {\n\tif (typeof value !== \"object\" || value === null) return undefined;\n\tconst candidate = value as { provider?: unknown; modelId?: unknown };\n\treturn typeof candidate.provider === \"string\" && typeof candidate.modelId === \"string\"\n\t\t? { provider: candidate.provider, modelId: candidate.modelId }\n\t\t: undefined;\n}\n"]}
|
|
@@ -7,6 +7,13 @@ export interface KeyTextFormatOptions {
|
|
|
7
7
|
}
|
|
8
8
|
export declare function formatKeyText(key: string, options?: KeyTextFormatOptions): string;
|
|
9
9
|
export declare function keyText(keybinding: Keybinding): string;
|
|
10
|
+
/** Formats several keybindings' keys as one group, e.g. "↑↓" for a combined select-up/select-down
|
|
11
|
+
* hint whose keys are still each bound to a single directional key, or "up/down"-style `/`-joined
|
|
12
|
+
* key names otherwise. Each keybinding still resolves through the configured bindings, so a
|
|
13
|
+
* rebinding away from the defaults is reflected here exactly as it is in `keyText`, never hidden
|
|
14
|
+
* behind a hardcoded glyph. */
|
|
15
|
+
export declare function combinedKeyText(keybindings: readonly Keybinding[]): string;
|
|
16
|
+
export declare function combinedKeyHint(keybindings: readonly Keybinding[], description: string): string;
|
|
10
17
|
export declare function keyDisplayText(keybinding: Keybinding): string;
|
|
11
18
|
export declare function keyHint(keybinding: Keybinding, description: string): string;
|
|
12
19
|
export declare function rawKeyHint(key: string, description: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keybinding-hints.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/keybinding-hints.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAkB,KAAK,UAAU,EAAc,MAAM,YAAY,CAAC;AAGzE,MAAM,WAAW,oBAAoB;IACpC,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAOD,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,MAAM,CAUrF;AAOD,wBAAgB,OAAO,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAEtD;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAE7D;AAED,wBAAgB,OAAO,CAAC,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAE3E;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAEnE"}
|
|
1
|
+
{"version":3,"file":"keybinding-hints.d.ts","sourceRoot":"","s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