apex-code 0.2.1 → 0.4.0

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.
Files changed (119) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/client/transcript.d.ts.map +1 -1
  3. package/dist/client/transcript.js +1 -1
  4. package/dist/client/transcript.js.map +1 -1
  5. package/dist/core/agent-session-services.d.ts.map +1 -1
  6. package/dist/core/agent-session-services.js +2 -1
  7. package/dist/core/agent-session-services.js.map +1 -1
  8. package/dist/core/delegation/runtime.d.ts.map +1 -1
  9. package/dist/core/delegation/runtime.js +2 -2
  10. package/dist/core/delegation/runtime.js.map +1 -1
  11. package/dist/core/durable-state/daemon.d.ts.map +1 -1
  12. package/dist/core/durable-state/daemon.js +1 -1
  13. package/dist/core/durable-state/daemon.js.map +1 -1
  14. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  15. package/dist/core/export-html/tool-renderer.js +3 -0
  16. package/dist/core/export-html/tool-renderer.js.map +1 -1
  17. package/dist/core/extensions/types.d.ts +8 -1
  18. package/dist/core/extensions/types.d.ts.map +1 -1
  19. package/dist/core/extensions/types.js.map +1 -1
  20. package/dist/core/keybindings.d.ts +2 -2
  21. package/dist/core/keybindings.d.ts.map +1 -1
  22. package/dist/core/keybindings.js +1 -1
  23. package/dist/core/keybindings.js.map +1 -1
  24. package/dist/core/mcp/mcp-tool.d.ts.map +1 -1
  25. package/dist/core/mcp/mcp-tool.js +2 -4
  26. package/dist/core/mcp/mcp-tool.js.map +1 -1
  27. package/dist/core/mcp/oauth/authorize.d.ts.map +1 -1
  28. package/dist/core/mcp/oauth/authorize.js +7 -2
  29. package/dist/core/mcp/oauth/authorize.js.map +1 -1
  30. package/dist/core/mcp/runtime.d.ts +2 -2
  31. package/dist/core/mcp/runtime.d.ts.map +1 -1
  32. package/dist/core/mcp/runtime.js +8 -3
  33. package/dist/core/mcp/runtime.js.map +1 -1
  34. package/dist/core/permissions/store.d.ts +7 -2
  35. package/dist/core/permissions/store.d.ts.map +1 -1
  36. package/dist/core/permissions/store.js +6 -1
  37. package/dist/core/permissions/store.js.map +1 -1
  38. package/dist/core/project-resources.d.ts +12 -0
  39. package/dist/core/project-resources.d.ts.map +1 -1
  40. package/dist/core/project-resources.js +19 -0
  41. package/dist/core/project-resources.js.map +1 -1
  42. package/dist/core/provider-composer.d.ts.map +1 -1
  43. package/dist/core/provider-composer.js +10 -1
  44. package/dist/core/provider-composer.js.map +1 -1
  45. package/dist/core/resource-loader.d.ts +6 -0
  46. package/dist/core/resource-loader.d.ts.map +1 -1
  47. package/dist/core/resource-loader.js +9 -3
  48. package/dist/core/resource-loader.js.map +1 -1
  49. package/dist/core/sdk.d.ts +1 -1
  50. package/dist/core/sdk.d.ts.map +1 -1
  51. package/dist/core/sdk.js +3 -3
  52. package/dist/core/sdk.js.map +1 -1
  53. package/dist/core/settings-manager.d.ts +16 -3
  54. package/dist/core/settings-manager.d.ts.map +1 -1
  55. package/dist/core/settings-manager.js +38 -15
  56. package/dist/core/settings-manager.js.map +1 -1
  57. package/dist/core/tools/bash.d.ts +9 -0
  58. package/dist/core/tools/bash.d.ts.map +1 -1
  59. package/dist/core/tools/bash.js +29 -16
  60. package/dist/core/tools/bash.js.map +1 -1
  61. package/dist/core/tools/edit.d.ts.map +1 -1
  62. package/dist/core/tools/edit.js +50 -10
  63. package/dist/core/tools/edit.js.map +1 -1
  64. package/dist/core/tools/path-utils.d.ts +9 -0
  65. package/dist/core/tools/path-utils.d.ts.map +1 -1
  66. package/dist/core/tools/path-utils.js +235 -10
  67. package/dist/core/tools/path-utils.js.map +1 -1
  68. package/dist/core/tools/write.d.ts.map +1 -1
  69. package/dist/core/tools/write.js +3 -3
  70. package/dist/core/tools/write.js.map +1 -1
  71. package/dist/core/workspace/state.d.ts.map +1 -1
  72. package/dist/core/workspace/state.js +1 -1
  73. package/dist/core/workspace/state.js.map +1 -1
  74. package/dist/main.d.ts.map +1 -1
  75. package/dist/main.js +3 -1
  76. package/dist/main.js.map +1 -1
  77. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  78. package/dist/modes/interactive/components/diff.js +2 -2
  79. package/dist/modes/interactive/components/diff.js.map +1 -1
  80. package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -1
  81. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  82. package/dist/modes/interactive/components/keybinding-hints.js +3 -2
  83. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  84. package/dist/modes/interactive/components/model-row.d.ts +84 -0
  85. package/dist/modes/interactive/components/model-row.d.ts.map +1 -0
  86. package/dist/modes/interactive/components/model-row.js +206 -0
  87. package/dist/modes/interactive/components/model-row.js.map +1 -0
  88. package/dist/modes/interactive/components/model-selector.d.ts +39 -4
  89. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  90. package/dist/modes/interactive/components/model-selector.js +158 -27
  91. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  92. package/dist/modes/interactive/components/tool-execution.d.ts +2 -0
  93. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  94. package/dist/modes/interactive/components/tool-execution.js +8 -0
  95. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  96. package/dist/modes/interactive/interactive-mode.d.ts +53 -1
  97. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  98. package/dist/modes/interactive/interactive-mode.js +100 -27
  99. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  100. package/dist/modes/interactive/theme/theme.d.ts +16 -0
  101. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  102. package/dist/modes/interactive/theme/theme.js +19 -1
  103. package/dist/modes/interactive/theme/theme.js.map +1 -1
  104. package/dist/tsconfig.json +3 -0
  105. package/dist/utils/clipboard-image.d.ts.map +1 -1
  106. package/dist/utils/clipboard-image.js +1 -1
  107. package/dist/utils/clipboard-image.js.map +1 -1
  108. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  109. package/dist/utils/syntax-highlight.js +22 -22
  110. package/dist/utils/syntax-highlight.js.map +1 -1
  111. package/docs/models.md +1 -1
  112. package/examples/extensions/gondolin/package-lock.json +3 -3
  113. package/examples/extensions/minimal-mode.ts +6 -6
  114. package/examples/extensions/sandbox/package-lock.json +4 -4
  115. package/examples/extensions/sandbox/package.json +1 -1
  116. package/examples/sdk/10-settings.ts +2 -2
  117. package/examples/sdk/README.md +1 -1
  118. package/npm-shrinkwrap.json +19 -34
  119. package/package.json +6 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Apex Code changelog
2
2
 
3
+ ## [Unreleased]
4
+
5
+ ## [0.4.0] - 2026-09-21
6
+
7
+ ### Changed
8
+
9
+ - **Project trust is now a required argument on the three loaders that read a checkout's own configuration.** `FilePermissionRuleStore`, `SettingsManager.create`, `SettingsManager.fromStorage`, and `createMcpRuntime` treated a missing `projectTrusted` as trusted, so a forgotten argument and a deliberate grant were the same value at the call site and in review. Omitting it is now a compile error for a TypeScript caller and a thrown `TypeError` for a JavaScript one, which is the break: an SDK caller constructing any of them directly must pass the decision. `SettingsManager.inMemory` is unchanged, because its storage holds only what the caller wrote into it and there is no untrusted source to gate. Making the argument required is what found the rest of this entry. See ADR 0034.
10
+
11
+ ### Fixed
12
+
13
+ - **`apex-code mcp auth` read the project's `.mcp.json` by a path the classifier does not resolve.** It composed the path itself rather than going through the project resource registry, so a `piConfig.configDir` override would have pointed the command at one file while the trust classifier checked another. It now resolves through the registry like every other reader of a gated resource. The command is deliberately not trust-gated: naming one server to authorize is the user's decision, and a one-shot command has no session trust state to consult. The guard that was supposed to catch this shape could not see it, because it matched the filename as a string and the two offending sites reached it through a constant; it now checks the identifiers too, and was proved by reintroducing the old line and watching it get named.
14
+
15
+ - **`edit` and `write` could destroy a file they failed to replace.** Both truncated the authorized target and then wrote into it, so the window between the two held a file with none of the old content and not yet all of the new. A crash, a full disk, or a kill in that window left the only copy gone. They now write a sibling and rename it over the target, which is what the session store has always done, so the name refers to the complete old file until it refers to the complete new one. The destination's mode is carried across, so publishing no longer resets permissions. The device-and-inode identity check that makes the authorized target the written target is unchanged, and a new-file write still proves the name was absent before it publishes. One consequence is worth stating: a rename installs a file this process created, so a target owned by someone else and merely writable by you changes owner. On Windows, where a rename onto a destination another handle holds open is refused and an ordinary read handle is enough, the write falls back to the previous in-place path rather than failing, so a file open in an editor still writes. That write is not crash-safe, which is the honest cost of the platform refusing the atomic one.
16
+
17
+ - **A `bash` command with no `timeout` ran unbounded.** A process waiting on input nothing will send, or a network call with no timeout of its own, held the tool call open for the life of the session, and nothing in the loop could tell that apart from slow. Calls now default to one hour, a value derived from this repository's own recorded suite runs rather than from taste, and the message when it fires names both ways forward: a larger explicit `timeout`, or the background shell. A background launch is still unbounded, because it is the escape hatch. See ADR 0035.
18
+
19
+ - **A cloned repository's `AGENTS.md` reached the system prompt with no trust decision.** Repository instruction files are wrapped as `<project_instructions>` and handed to the model as instructions, so a checkout supplying one is steering the agent, which is the thing the trust prompt exists to ask about. They were loaded before any decision and were not among the resources whose presence raises one. A test asserted the old behavior, which is how it survived review. An untrusted checkout's `AGENTS.md`, `AGENTS.override.md`, `AGENTS.MD`, `CLAUDE.md`, and `CLAUDE.MD` are now withheld, along with any ancestor directory's, while the agent directory's own still loads because it is yours and not the project's. This is not prompt-injection defense and does not claim to be; it puts the highest-value injection surface in the product behind the same decision every other project-controlled surface is behind. The cost is a first-run change: a repository whose only project file is an `AGENTS.md` now asks once, where it used to start silently, and most repositories have one.
20
+
21
+ - **A project could choose where its own session transcripts were written, before you trusted it.** Startup builds a settings manager before the trust store exists, and that manager read the merged global-and-project settings, so a cloned repository shipping `.apex-code/settings.json` with `sessionDir` set had that path honored with no trust decision anywhere in the sequence. A transcript carries everything the session saw, so choosing where one lands is an exfiltration primitive that needs no cooperation from the model: point it somewhere the repository reads or commits and the contents follow. `sessionDir` is now a global setting, like `defaultProjectTrust`, and a project's value is ignored whether or not you trust the project. Your own `sessionDir`, the `--session-dir` flag, and `~` expansion are unchanged. This is a behavior change for anyone who set it per project, and the reason it is a removal rather than a repair is that there is no point in startup where honoring a project's value would be both safe and possible.
22
+
23
+ - **Custom `openai-responses` models now default to strict tool schemas.** `supportsStrictMode` defaults to `true` for that API when omitted, with an explicit `false` opting out; other APIs are unchanged.
24
+ - **The bash schema's `kill: false` branch is harmless.** Responses-compatible calls carrying the flag no longer fail schema validation or alter command behavior.
25
+ - **Empty MCP calls now explain how to load their schema.** The local error points to the schema-loading guidance instead of failing without actionable context.
26
+
27
+ ## [0.3.0] - 2026-09-18
28
+
29
+ ### Changed
30
+
31
+ - **The model step of `/model` now names models and prices them, and dials reasoning effort in place.** The two-step flow is unchanged: you still pick a provider, then a model. What changed is the second step. A row led with the raw model id and repeated the display name on a single line under the list, which spent the widest part of the row on the string you already typed to get there and the line under it on the one piece of information that was never in question. The row now leads with the model's name and carries its id, provider, and `default`/`current` badges in a right-aligned cluster that sheds the cheapest context first as the terminal narrows, so the active marker outlives the id, which the row's name already implies. Under the list, the repeated name is replaced by input, cached-input, and output prices per million tokens, which is what you actually weigh when two models are otherwise interchangeable. Reasoning models carry a square gauge for thinking effort that left and right adjust on the highlighted row, so choosing a model and the effort to run it at is one decision rather than a model switch followed by a trip through `/thinking`. Effort is handed to the session only when it was moved; leaving it alone keeps whatever the model switch would have applied on its own. Left and right still belong to the search field's cursor until up or down moves you into the list. The gauge is placed once per rendered page rather than per row, so the squares hold one column while you arrow down, and it gives up its label and then itself as the terminal narrows, in that order. The provider step is untouched.
32
+
33
+ - **`ctrl+o` now cycles three readings of the transcript instead of toggling two.** Tool output expansion and edit-diff visibility were separate concerns with only one control between them, so the diff of every edit was always on screen whether or not you were reading it, and the only lever moved tool output. The key now walks `overview`, `details`, `all`. At `overview` a diff reduces to its `+N -M` counts and tool output stays a counted preview, which is the quiet read for scrolling back through a long session. `details` is the default and renders exactly what the previous default rendered, so an upgrade changes nothing until the key is pressed and the new rung exists in both directions rather than only one. `all` expands tool output as the old toggle did. The three rungs derive from one `ChatDetail` value rather than from independently settable booleans, because only three of the eight combinations are coherent and the order between them is the whole point.
34
+
35
+ - **Thinking blocks stay a persisted preference, and the top rung borrows them.** `all` shows thinking even when the setting hides it, and cycling back down restores the setting. The override is never written to settings, so `ctrl+o` cannot silently rewrite a durable preference, and the dedicated toggle still persists as it always did. The extension-facing `setToolsExpanded(false)` lands on `details` rather than `overview`, because an extension asking to collapse tool output has not asked to hide diffs.
36
+
3
37
  ## [0.2.1] - 2026-09-16
4
38
 
5
39
  ### Fixed
@@ -1 +1 @@
1
- {"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/client/transcript.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,eAAe,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAElH,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAC;IACnC,QAAQ,CAAC,aAAa,EAAE,WAAW,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC5D,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,eAAe,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtD;AAoBD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,eAAe,GAAG,eAAe,CAOhF;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,eAAe,GAAG,eAAe,CAG1G;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,kBAAkB,GAAG,eAAe,CAiC7G;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,eAAe,GAAG,SAAS,cAAc,EAAE,CAiBlF","sourcesContent":["import type { JsonValue, SessionSnapshot, TranscriptItem, TranscriptProgress } from \"@earendil-works/pi-protocol\";\n\nexport interface TranscriptState {\n\treadonly snapshot: SessionSnapshot;\n\treadonly progressItems: ReadonlyMap<string, TranscriptItem>;\n\treadonly progressOrder: readonly string[];\n\treadonly toolCallBuffers: ReadonlyMap<string, string>;\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"string\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) return value.every(isJsonValue);\n\tif (typeof value !== \"object\" || Object.getPrototypeOf(value) !== Object.prototype) return false;\n\treturn Object.values(value).every(isJsonValue);\n}\n\nfunction parsePartialToolInput(value: string): JsonValue {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\tif (isJsonValue(parsed)) return parsed;\n\t} catch {\n\t\t// Tool arguments are incomplete while streaming. Preserve their raw prefix until they form valid JSON.\n\t}\n\treturn value;\n}\n\nexport function createTranscriptState(snapshot: SessionSnapshot): TranscriptState {\n\treturn {\n\t\tsnapshot: structuredClone(snapshot),\n\t\tprogressItems: new Map(),\n\t\tprogressOrder: [],\n\t\ttoolCallBuffers: new Map(),\n\t};\n}\n\nexport function applyTranscriptSnapshot(state: TranscriptState, snapshot: SessionSnapshot): TranscriptState {\n\tif (state.snapshot.id === snapshot.id && snapshot.revision < state.snapshot.revision) return state;\n\treturn createTranscriptState(snapshot);\n}\n\nexport function applyTranscriptProgress(state: TranscriptState, progress: TranscriptProgress): TranscriptState {\n\tif (progress.type === \"item_started\" || progress.type === \"item_updated\") {\n\t\treturn setProgressItem(state, progress.item);\n\t}\n\tif (progress.type === \"item_finished\") {\n\t\tconst toolCallBuffers = new Map(state.toolCallBuffers);\n\t\tfor (const key of toolCallBuffers.keys()) {\n\t\t\tif (key.startsWith(`${progress.item.id}:`)) toolCallBuffers.delete(key);\n\t\t}\n\t\treturn setProgressItem({ ...state, toolCallBuffers }, progress.item);\n\t}\n\n\tconst item =\n\t\tstate.progressItems.get(progress.messageId) ??\n\t\tstate.snapshot.transcript.find(({ id }) => id === progress.messageId);\n\tif (!item || item.role !== \"assistant\") return state;\n\tlet toolCallBuffers = state.toolCallBuffers;\n\tconst content = item.content.map((part, index) => {\n\t\tif (index !== progress.contentIndex) return structuredClone(part);\n\t\tif (progress.kind === \"text\" && part.type === \"text\") return { ...part, text: part.text + progress.delta };\n\t\tif (progress.kind === \"thinking\" && part.type === \"thinking\") {\n\t\t\treturn { ...part, thinking: part.thinking + progress.delta };\n\t\t}\n\t\tif (progress.kind === \"toolCall\" && part.type === \"toolCall\") {\n\t\t\tconst key = `${progress.messageId}:${progress.contentIndex}`;\n\t\t\tconst existing = state.toolCallBuffers.get(key) ?? (typeof part.input === \"string\" ? part.input : \"\");\n\t\t\tconst buffer = existing + progress.delta;\n\t\t\ttoolCallBuffers = new Map(state.toolCallBuffers).set(key, buffer);\n\t\t\treturn { ...part, input: parsePartialToolInput(buffer) };\n\t\t}\n\t\treturn structuredClone(part);\n\t});\n\treturn setProgressItem({ ...state, toolCallBuffers }, { ...item, content });\n}\n\nexport function selectTranscript(state: TranscriptState): readonly TranscriptItem[] {\n\tconst transcript = state.snapshot.transcript.map((item) => state.progressItems.get(item.id) ?? item);\n\tconst ids = new Set(transcript.map((item) => item.id));\n\tfor (const id of state.progressOrder) {\n\t\tif (ids.has(id)) continue;\n\t\tconst item = state.progressItems.get(id);\n\t\tif (item) {\n\t\t\ttranscript.push(item);\n\t\t\tids.add(id);\n\t\t}\n\t}\n\tfor (const item of state.snapshot.queuedSteer) {\n\t\tif (ids.has(item.id)) continue;\n\t\ttranscript.push(item);\n\t\tids.add(item.id);\n\t}\n\treturn transcript;\n}\n\nfunction setProgressItem(state: TranscriptState, item: TranscriptItem): TranscriptState {\n\tconst progressItems = new Map(state.progressItems);\n\tconst progressOrder = progressItems.has(item.id) ? state.progressOrder : [...state.progressOrder, item.id];\n\tprogressItems.set(item.id, structuredClone(item));\n\treturn { ...state, progressItems, progressOrder };\n}\n"]}
1
+ {"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/client/transcript.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,eAAe,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAElH,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAC;IACnC,QAAQ,CAAC,aAAa,EAAE,WAAW,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC5D,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,eAAe,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtD;AAoBD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,eAAe,GAAG,eAAe,CAOhF;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,eAAe,GAAG,eAAe,CAG1G;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,kBAAkB,GAAG,eAAe,CAiC7G;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,eAAe,GAAG,SAAS,cAAc,EAAE,CAiBlF","sourcesContent":["import type { JsonValue, SessionSnapshot, TranscriptItem, TranscriptProgress } from \"@earendil-works/pi-protocol\";\n\nexport interface TranscriptState {\n\treadonly snapshot: SessionSnapshot;\n\treadonly progressItems: ReadonlyMap<string, TranscriptItem>;\n\treadonly progressOrder: readonly string[];\n\treadonly toolCallBuffers: ReadonlyMap<string, string>;\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"string\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) return value.every(isJsonValue);\n\tif (typeof value !== \"object\" || Object.getPrototypeOf(value) !== Object.prototype) return false;\n\treturn Object.values(value).every(isJsonValue);\n}\n\nfunction parsePartialToolInput(value: string): JsonValue {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\tif (isJsonValue(parsed)) return parsed;\n\t} catch {\n\t\t// Tool arguments are incomplete while streaming. Preserve their raw prefix until they form valid JSON.\n\t}\n\treturn value;\n}\n\nexport function createTranscriptState(snapshot: SessionSnapshot): TranscriptState {\n\treturn {\n\t\tsnapshot: structuredClone(snapshot),\n\t\tprogressItems: new Map(),\n\t\tprogressOrder: [],\n\t\ttoolCallBuffers: new Map(),\n\t};\n}\n\nexport function applyTranscriptSnapshot(state: TranscriptState, snapshot: SessionSnapshot): TranscriptState {\n\tif (state.snapshot.id === snapshot.id && snapshot.revision < state.snapshot.revision) return state;\n\treturn createTranscriptState(snapshot);\n}\n\nexport function applyTranscriptProgress(state: TranscriptState, progress: TranscriptProgress): TranscriptState {\n\tif (progress.type === \"item_started\" || progress.type === \"item_updated\") {\n\t\treturn setProgressItem(state, progress.item);\n\t}\n\tif (progress.type === \"item_finished\") {\n\t\tconst toolCallBuffers = new Map(state.toolCallBuffers);\n\t\tfor (const key of toolCallBuffers.keys()) {\n\t\t\tif (key.startsWith(`${progress.item.id}:`)) toolCallBuffers.delete(key);\n\t\t}\n\t\treturn setProgressItem({ ...state, toolCallBuffers }, progress.item);\n\t}\n\n\tconst item =\n\t\tstate.progressItems.get(progress.messageId) ??\n\t\tstate.snapshot.transcript.find(({ id }) => id === progress.messageId);\n\tif (item?.role !== \"assistant\") return state;\n\tlet toolCallBuffers = state.toolCallBuffers;\n\tconst content = item.content.map((part, index) => {\n\t\tif (index !== progress.contentIndex) return structuredClone(part);\n\t\tif (progress.kind === \"text\" && part.type === \"text\") return { ...part, text: part.text + progress.delta };\n\t\tif (progress.kind === \"thinking\" && part.type === \"thinking\") {\n\t\t\treturn { ...part, thinking: part.thinking + progress.delta };\n\t\t}\n\t\tif (progress.kind === \"toolCall\" && part.type === \"toolCall\") {\n\t\t\tconst key = `${progress.messageId}:${progress.contentIndex}`;\n\t\t\tconst existing = state.toolCallBuffers.get(key) ?? (typeof part.input === \"string\" ? part.input : \"\");\n\t\t\tconst buffer = existing + progress.delta;\n\t\t\ttoolCallBuffers = new Map(state.toolCallBuffers).set(key, buffer);\n\t\t\treturn { ...part, input: parsePartialToolInput(buffer) };\n\t\t}\n\t\treturn structuredClone(part);\n\t});\n\treturn setProgressItem({ ...state, toolCallBuffers }, { ...item, content });\n}\n\nexport function selectTranscript(state: TranscriptState): readonly TranscriptItem[] {\n\tconst transcript = state.snapshot.transcript.map((item) => state.progressItems.get(item.id) ?? item);\n\tconst ids = new Set(transcript.map((item) => item.id));\n\tfor (const id of state.progressOrder) {\n\t\tif (ids.has(id)) continue;\n\t\tconst item = state.progressItems.get(id);\n\t\tif (item) {\n\t\t\ttranscript.push(item);\n\t\t\tids.add(id);\n\t\t}\n\t}\n\tfor (const item of state.snapshot.queuedSteer) {\n\t\tif (ids.has(item.id)) continue;\n\t\ttranscript.push(item);\n\t\tids.add(item.id);\n\t}\n\treturn transcript;\n}\n\nfunction setProgressItem(state: TranscriptState, item: TranscriptItem): TranscriptState {\n\tconst progressItems = new Map(state.progressItems);\n\tconst progressOrder = progressItems.has(item.id) ? state.progressOrder : [...state.progressOrder, item.id];\n\tprogressItems.set(item.id, structuredClone(item));\n\treturn { ...state, progressItems, progressOrder };\n}\n"]}
@@ -47,7 +47,7 @@ export function applyTranscriptProgress(state, progress) {
47
47
  }
48
48
  const item = state.progressItems.get(progress.messageId) ??
49
49
  state.snapshot.transcript.find(({ id }) => id === progress.messageId);
50
- if (!item || item.role !== "assistant")
50
+ if (item?.role !== "assistant")
51
51
  return state;
52
52
  let toolCallBuffers = state.toolCallBuffers;
53
53
  const content = item.content.map((part, index) => {
@@ -1 +1 @@
1
- {"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/client/transcript.ts"],"names":[],"mappings":"AASA,SAAS,WAAW,CAAC,KAAc,EAAsB;IACxD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3F,IAAI,OAAO,KAAK,KAAK,QAAQ;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EAAE,CAAC,CAAC;IAC3G,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC;IAClD,OAAO,EAAE,GAAG,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;AAAA,CAClD","sourcesContent":["import type { JsonValue, SessionSnapshot, TranscriptItem, TranscriptProgress } from \"@earendil-works/pi-protocol\";\n\nexport interface TranscriptState {\n\treadonly snapshot: SessionSnapshot;\n\treadonly progressItems: ReadonlyMap<string, TranscriptItem>;\n\treadonly progressOrder: readonly string[];\n\treadonly toolCallBuffers: ReadonlyMap<string, string>;\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"string\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) return value.every(isJsonValue);\n\tif (typeof value !== \"object\" || Object.getPrototypeOf(value) !== Object.prototype) return false;\n\treturn Object.values(value).every(isJsonValue);\n}\n\nfunction parsePartialToolInput(value: string): JsonValue {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\tif (isJsonValue(parsed)) return parsed;\n\t} catch {\n\t\t// Tool arguments are incomplete while streaming. Preserve their raw prefix until they form valid JSON.\n\t}\n\treturn value;\n}\n\nexport function createTranscriptState(snapshot: SessionSnapshot): TranscriptState {\n\treturn {\n\t\tsnapshot: structuredClone(snapshot),\n\t\tprogressItems: new Map(),\n\t\tprogressOrder: [],\n\t\ttoolCallBuffers: new Map(),\n\t};\n}\n\nexport function applyTranscriptSnapshot(state: TranscriptState, snapshot: SessionSnapshot): TranscriptState {\n\tif (state.snapshot.id === snapshot.id && snapshot.revision < state.snapshot.revision) return state;\n\treturn createTranscriptState(snapshot);\n}\n\nexport function applyTranscriptProgress(state: TranscriptState, progress: TranscriptProgress): TranscriptState {\n\tif (progress.type === \"item_started\" || progress.type === \"item_updated\") {\n\t\treturn setProgressItem(state, progress.item);\n\t}\n\tif (progress.type === \"item_finished\") {\n\t\tconst toolCallBuffers = new Map(state.toolCallBuffers);\n\t\tfor (const key of toolCallBuffers.keys()) {\n\t\t\tif (key.startsWith(`${progress.item.id}:`)) toolCallBuffers.delete(key);\n\t\t}\n\t\treturn setProgressItem({ ...state, toolCallBuffers }, progress.item);\n\t}\n\n\tconst item =\n\t\tstate.progressItems.get(progress.messageId) ??\n\t\tstate.snapshot.transcript.find(({ id }) => id === progress.messageId);\n\tif (!item || item.role !== \"assistant\") return state;\n\tlet toolCallBuffers = state.toolCallBuffers;\n\tconst content = item.content.map((part, index) => {\n\t\tif (index !== progress.contentIndex) return structuredClone(part);\n\t\tif (progress.kind === \"text\" && part.type === \"text\") return { ...part, text: part.text + progress.delta };\n\t\tif (progress.kind === \"thinking\" && part.type === \"thinking\") {\n\t\t\treturn { ...part, thinking: part.thinking + progress.delta };\n\t\t}\n\t\tif (progress.kind === \"toolCall\" && part.type === \"toolCall\") {\n\t\t\tconst key = `${progress.messageId}:${progress.contentIndex}`;\n\t\t\tconst existing = state.toolCallBuffers.get(key) ?? (typeof part.input === \"string\" ? part.input : \"\");\n\t\t\tconst buffer = existing + progress.delta;\n\t\t\ttoolCallBuffers = new Map(state.toolCallBuffers).set(key, buffer);\n\t\t\treturn { ...part, input: parsePartialToolInput(buffer) };\n\t\t}\n\t\treturn structuredClone(part);\n\t});\n\treturn setProgressItem({ ...state, toolCallBuffers }, { ...item, content });\n}\n\nexport function selectTranscript(state: TranscriptState): readonly TranscriptItem[] {\n\tconst transcript = state.snapshot.transcript.map((item) => state.progressItems.get(item.id) ?? item);\n\tconst ids = new Set(transcript.map((item) => item.id));\n\tfor (const id of state.progressOrder) {\n\t\tif (ids.has(id)) continue;\n\t\tconst item = state.progressItems.get(id);\n\t\tif (item) {\n\t\t\ttranscript.push(item);\n\t\t\tids.add(id);\n\t\t}\n\t}\n\tfor (const item of state.snapshot.queuedSteer) {\n\t\tif (ids.has(item.id)) continue;\n\t\ttranscript.push(item);\n\t\tids.add(item.id);\n\t}\n\treturn transcript;\n}\n\nfunction setProgressItem(state: TranscriptState, item: TranscriptItem): TranscriptState {\n\tconst progressItems = new Map(state.progressItems);\n\tconst progressOrder = progressItems.has(item.id) ? state.progressOrder : [...state.progressOrder, item.id];\n\tprogressItems.set(item.id, structuredClone(item));\n\treturn { ...state, progressItems, progressOrder };\n}\n"]}
1
+ {"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/client/transcript.ts"],"names":[],"mappings":"AASA,SAAS,WAAW,CAAC,KAAc,EAAsB;IACxD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3F,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC7D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAC1D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,MAAM,CAAC,SAAS;QAAE,OAAO,KAAK,CAAC;IACjG,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;AAAA,CAC/C;AAED,SAAS,qBAAqB,CAAC,KAAa,EAAa;IACxD,IAAI,CAAC;QACJ,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC1C,IAAI,WAAW,CAAC,MAAM,CAAC;YAAE,OAAO,MAAM,CAAC;IACxC,CAAC;IAAC,MAAM,CAAC;QACR,uGAAuG;IACxG,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb;AAED,MAAM,UAAU,qBAAqB,CAAC,QAAyB,EAAmB;IACjF,OAAO;QACN,QAAQ,EAAE,eAAe,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AAE,CAAC;YAAE,SAAS;QAC/B,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,UAAU,CAAC;AAAA,CAClB;AAED,SAAS,eAAe,CAAC,KAAsB,EAAE,IAAoB,EAAmB;IACvF,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACnD,MAAM,aAAa,GAAG,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;IAC3G,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC;IAClD,OAAO,EAAE,GAAG,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;AAAA,CAClD","sourcesContent":["import type { JsonValue, SessionSnapshot, TranscriptItem, TranscriptProgress } from \"@earendil-works/pi-protocol\";\n\nexport interface TranscriptState {\n\treadonly snapshot: SessionSnapshot;\n\treadonly progressItems: ReadonlyMap<string, TranscriptItem>;\n\treadonly progressOrder: readonly string[];\n\treadonly toolCallBuffers: ReadonlyMap<string, string>;\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"string\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) return value.every(isJsonValue);\n\tif (typeof value !== \"object\" || Object.getPrototypeOf(value) !== Object.prototype) return false;\n\treturn Object.values(value).every(isJsonValue);\n}\n\nfunction parsePartialToolInput(value: string): JsonValue {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\tif (isJsonValue(parsed)) return parsed;\n\t} catch {\n\t\t// Tool arguments are incomplete while streaming. Preserve their raw prefix until they form valid JSON.\n\t}\n\treturn value;\n}\n\nexport function createTranscriptState(snapshot: SessionSnapshot): TranscriptState {\n\treturn {\n\t\tsnapshot: structuredClone(snapshot),\n\t\tprogressItems: new Map(),\n\t\tprogressOrder: [],\n\t\ttoolCallBuffers: new Map(),\n\t};\n}\n\nexport function applyTranscriptSnapshot(state: TranscriptState, snapshot: SessionSnapshot): TranscriptState {\n\tif (state.snapshot.id === snapshot.id && snapshot.revision < state.snapshot.revision) return state;\n\treturn createTranscriptState(snapshot);\n}\n\nexport function applyTranscriptProgress(state: TranscriptState, progress: TranscriptProgress): TranscriptState {\n\tif (progress.type === \"item_started\" || progress.type === \"item_updated\") {\n\t\treturn setProgressItem(state, progress.item);\n\t}\n\tif (progress.type === \"item_finished\") {\n\t\tconst toolCallBuffers = new Map(state.toolCallBuffers);\n\t\tfor (const key of toolCallBuffers.keys()) {\n\t\t\tif (key.startsWith(`${progress.item.id}:`)) toolCallBuffers.delete(key);\n\t\t}\n\t\treturn setProgressItem({ ...state, toolCallBuffers }, progress.item);\n\t}\n\n\tconst item =\n\t\tstate.progressItems.get(progress.messageId) ??\n\t\tstate.snapshot.transcript.find(({ id }) => id === progress.messageId);\n\tif (item?.role !== \"assistant\") return state;\n\tlet toolCallBuffers = state.toolCallBuffers;\n\tconst content = item.content.map((part, index) => {\n\t\tif (index !== progress.contentIndex) return structuredClone(part);\n\t\tif (progress.kind === \"text\" && part.type === \"text\") return { ...part, text: part.text + progress.delta };\n\t\tif (progress.kind === \"thinking\" && part.type === \"thinking\") {\n\t\t\treturn { ...part, thinking: part.thinking + progress.delta };\n\t\t}\n\t\tif (progress.kind === \"toolCall\" && part.type === \"toolCall\") {\n\t\t\tconst key = `${progress.messageId}:${progress.contentIndex}`;\n\t\t\tconst existing = state.toolCallBuffers.get(key) ?? (typeof part.input === \"string\" ? part.input : \"\");\n\t\t\tconst buffer = existing + progress.delta;\n\t\t\ttoolCallBuffers = new Map(state.toolCallBuffers).set(key, buffer);\n\t\t\treturn { ...part, input: parsePartialToolInput(buffer) };\n\t\t}\n\t\treturn structuredClone(part);\n\t});\n\treturn setProgressItem({ ...state, toolCallBuffers }, { ...item, content });\n}\n\nexport function selectTranscript(state: TranscriptState): readonly TranscriptItem[] {\n\tconst transcript = state.snapshot.transcript.map((item) => state.progressItems.get(item.id) ?? item);\n\tconst ids = new Set(transcript.map((item) => item.id));\n\tfor (const id of state.progressOrder) {\n\t\tif (ids.has(id)) continue;\n\t\tconst item = state.progressItems.get(id);\n\t\tif (item) {\n\t\t\ttranscript.push(item);\n\t\t\tids.add(id);\n\t\t}\n\t}\n\tfor (const item of state.snapshot.queuedSteer) {\n\t\tif (ids.has(item.id)) continue;\n\t\ttranscript.push(item);\n\t\tids.add(item.id);\n\t}\n\treturn transcript;\n}\n\nfunction setProgressItem(state: TranscriptState, item: TranscriptItem): TranscriptState {\n\tconst progressItems = new Map(state.progressItems);\n\tconst progressOrder = progressItems.has(item.id) ? state.progressOrder : [...state.progressOrder, item.id];\n\tprogressItems.set(item.id, structuredClone(item));\n\treturn { ...state, progressItems, progressOrder };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-services.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,u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el } from \"apex-code-agent-core\";\nimport { getAgentDir, getAuthPath } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { LspDiagnostics } from \"./lsp/diagnostics.ts\";\nimport { LspPool } from \"./lsp/pool.ts\";\nimport { resolveLspRegistry } from \"./lsp/registry.ts\";\nimport { LspStatusStore } from \"./lsp/status.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport type { PermissionGateOptions } from \"./permissions/gate.ts\";\nimport type { PermissionResponder } from \"./permissions/responder.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { LspOperations } from \"./tools/lsp.ts\";\nimport { SqliteUsagePerformanceStore } from \"./usage-performance-store.ts\";\nimport { createDeferredWebSearchOperations, resolveWebSearchOperations } from \"./web-search-provider.ts\";\n\n/** Filename of the shared durable-state database within an agent directory (roadmap Phase 8). */\nconst DURABLE_STATE_DATABASE_FILENAME = \"state.sqlite\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\t/**\n\t * Session id to stamp on every usage-performance sample this runtime records.\n\t * Only observed when `modelRuntime` is not already provided — a caller-supplied\n\t * runtime owns its own store, if any.\n\t */\n\tsessionId?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\tmodelRuntimeSignal?: AbortSignal;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n\tpermissionGate?: Omit<PermissionGateOptions, \"getContract\">;\n\t/** Optional headless permission bridge (ACP, spec 2026-08-31-acp-adapter.md). */\n\tpermissionResponderFactory?: () => PermissionResponder | undefined;\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tlspPool: LspPool;\n\t/**\n\t * Wraps `lspPool` for `DiagnosticsOperations.afterMutation` (LSP.4). Structurally\n\t * compatible with `core/tools/diagnostics.ts`'s `DiagnosticsOperations` -- callers\n\t * pass this value directly, never importing `core/lsp/*` themselves.\n\t */\n\tlspDiagnostics: LspDiagnostics;\n\t/** True when at least one LSP server resolved -- gates registering the `lsp` tool (LSP.5). */\n\tlspConfigured: boolean;\n\t/**\n\t * Chronological, bounded record of every server-root state transition observed by\n\t * `lspPool` for this services lifetime (LSP.2). Inspectable structured state -- not\n\t * wired to any user-facing surface by this plan (see `docs/plans/2026-08-18-lsp.md`,\n\t * Task LSP.2: this is not a `/doctor` task).\n\t */\n\tlspStatus: LspStatusStore;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n\tclose(): Promise<void>;\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\n\t// A ledger failure must never block session creation or a turn — open it\n\t// best-effort and degrade to a diagnostic, never a thrown error.\n\tlet usagePerformanceStore: SqliteUsagePerformanceStore | undefined;\n\tif (!options.modelRuntime) {\n\t\ttry {\n\t\t\tusagePerformanceStore = new SqliteUsagePerformanceStore(\n\t\t\t\tjoin(agentDir, DURABLE_STATE_DATABASE_FILENAME),\n\t\t\t\toptions.sessionId,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({ type: \"warning\", message: `Usage/cost recording unavailable: ${message}` });\n\t\t}\n\t}\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst otlpEndpoint = settingsManager.getObservabilitySettings().otlpEndpoint;\n\tconst otlpExportConfig = otlpEndpoint\n\t\t? { endpoint: otlpEndpoint, headers: settingsManager.getObservabilitySettings().otlpHeaders }\n\t\t: undefined;\n\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: process.env.APEX_CODE_AUTH_PATH ?? (options.agentDir ? join(agentDir, \"auth.json\") : getAuthPath()),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t\tusagePerformanceStore,\n\t\t\totlpExportConfig,\n\t\t}));\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tfor (const { provider, extensionPath } of extensionsResult.runtime.pendingNativeProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerNativeProvider(provider);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingNativeProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\t// `lspStatus` is constructed unconditionally (and outside the try) so it always\n\t// records real state transitions the pool experiences below, including the\n\t// eager-start failure the catch block handles -- not just a snapshot taken at one\n\t// fixed point in time.\n\tconst lspStatus = new LspStatusStore();\n\tlet lspPool: LspPool | undefined;\n\tlet registry: ReturnType<typeof resolveLspRegistry> | undefined;\n\tlet lspConfigured = false;\n\ttry {\n\t\tregistry = resolveLspRegistry(settingsManager.getLspSettings(), { workspace: cwd });\n\t\tlspPool = new LspPool(registry, {\n\t\t\tonStatusChange: (status) =>\n\t\t\t\tlspStatus.record({\n\t\t\t\t\tserverId: status.serverId,\n\t\t\t\t\troot: status.root,\n\t\t\t\t\tstate: status.state,\n\t\t\t\t\tattempt: status.attempts,\n\t\t\t\t\t...(status.reason === undefined ? {} : { reason: status.reason }),\n\t\t\t\t}),\n\t\t});\n\t\tlspConfigured = registry.servers.length > 0;\n\t\t// Per the spec's \"Resolved configuration, ownership, and lifecycle\": any\n\t\t// configured entry that cannot resolve, spawn, or initialize its cwd-root\n\t\t// process within its timeout is a startup misconfiguration -- fail fast here,\n\t\t// following core/permissions/startup.ts's precedent, rather than let a broken\n\t\t// server surface only when a tool call needs it mid-run.\n\t\tif (lspConfigured) await lspPool.start();\n\t} catch (error) {\n\t\t// Name the failing binary(ies), not just the raw client/registry error: the\n\t\t// registry itself already does this for a resolution failure (missing/\n\t\t// un-spawnable binary names the command and lookup path), but a `pool.start()`\n\t\t// rejection surfaces only the first client's bare error (e.g. \"initialize timed\n\t\t// out\"), with no server id attached. `registry.servers` (resolved commands) and\n\t\t// `lspPool.status()` (which entries actually failed) are both in scope here, so\n\t\t// build the richer message without changing `LspPoolStatus`'s shape or the\n\t\t// pool's own error-propagation wire format.\n\t\tconst commandById = new Map(registry?.servers.map((server) => [server.id, server.command]) ?? []);\n\t\tconst failedEntries = (lspPool?.status() ?? []).filter(\n\t\t\t(status) => status.state === \"degraded\" || status.state === \"disabled\",\n\t\t);\n\t\tconst message =\n\t\t\tfailedEntries.length > 0\n\t\t\t\t? failedEntries\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(status) =>\n\t\t\t\t\t\t\t\t`${status.serverId} (${commandById.get(status.serverId) ?? \"?\"}) at ${status.root}: ${status.reason ?? \"unknown error\"}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(\"; \")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: String(error);\n\t\tdiagnostics.push({ type: \"error\", message: `LSP startup failed: ${message}` });\n\t\t// A pool that got partway through eager start may already have spawned and\n\t\t// initialized sibling servers successfully; discarding it without disposing\n\t\t// would orphan those child processes rather than tearing them down cleanly.\n\t\tawait lspPool?.dispose().catch(() => {});\n\t\tlspConfigured = false;\n\t\tlspPool = new LspPool({ workspace: cwd, servers: [], platform: process.platform });\n\t}\n\tconst lspDiagnostics = new LspDiagnostics(lspPool);\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tlspPool,\n\t\tlspDiagnostics,\n\t\tlspConfigured,\n\t\tlspStatus,\n\t\tdiagnostics,\n\t\tclose: async () => {\n\t\t\t// Diagnostics first: it still needs live LSP clients to send didClose\n\t\t\t// during its own teardown, so it must not outlive the pool it wraps.\n\t\t\tawait lspDiagnostics.dispose();\n\t\t\tawait lspPool.dispose();\n\t\t\tif (!options.modelRuntime) modelRuntime.close();\n\t\t},\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\tconst { lspPool, lspDiagnostics, lspConfigured } = options.services;\n\t// Both gated on `lspConfigured` (at least one server resolved), not per-path:\n\t// the spec's \"no diagnostics injection or result change whatsoever when `lsp` is\n\t// unconfigured\" is a session-level guarantee. A session with servers configured\n\t// for *some* languages still injects diagnosticsOperations -- a mutated path with\n\t// no matching server correctly resolves to the explicit `unavailable` outcome via\n\t// `LspDiagnostics.afterMutation`'s own per-path `pool.acquire`, it is simply never\n\t// asked at all when the session has no servers whatsoever. `lspDiagnostics`\n\t// already matches `DiagnosticsOperations` structurally, so it is passed directly\n\t// rather than wrapped.\n\tconst diagnosticsOperations = lspConfigured ? lspDiagnostics : undefined;\n\tconst lspOperations: LspOperations | undefined = lspConfigured\n\t\t? {\n\t\t\t\trequest: async (absolutePath, method, params, signal) => {\n\t\t\t\t\tconst connection = await lspPool.acquire(absolutePath);\n\t\t\t\t\tif (!connection) return undefined;\n\t\t\t\t\treturn connection.client.request(method, params, signal);\n\t\t\t\t},\n\t\t\t}\n\t\t: undefined;\n\n\t// Read per call rather than captured here. The tool registry is built once at\n\t// session construction, so a key saved from the settings panel mid-session would\n\t// otherwise not take effect until restart.\n\t// Two different questions. Whether a credential resolves *now* decides whether the\n\t// tool is active, because activation happens once at construction. Resolution then\n\t// stays deferred so a key changed mid-session is picked up without a restart.\n\tconst settingsManager = options.services.settingsManager;\n\tconst webSearchOperations = resolveWebSearchOperations(settingsManager.getWebSearchSettings())\n\t\t? createDeferredWebSearchOperations(() => settingsManager.getWebSearchSettings())\n\t\t: undefined;\n\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tpermissionGate: options.permissionGate,\n\t\tpermissionResponderFactory: options.permissionResponderFactory,\n\t\tdiagnosticsOperations,\n\t\tlspOperations,\n\t\twebSearchOperations,\n\t});\n}\n"]}
1
+ {"version":3,"file":"agent-session-services.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAA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,CAAC,CAsDnC","sourcesContent":["import { join } from \"node:path\";\nimport type { Model } from \"@earendil-works/pi-ai\";\nimport type { ThinkingLevel } from \"apex-code-agent-core\";\nimport { getAgentDir, getAuthPath } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { LspDiagnostics } from \"./lsp/diagnostics.ts\";\nimport { LspPool } from \"./lsp/pool.ts\";\nimport { resolveLspRegistry } from \"./lsp/registry.ts\";\nimport { LspStatusStore } from \"./lsp/status.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport type { PermissionGateOptions } from \"./permissions/gate.ts\";\nimport type { PermissionResponder } from \"./permissions/responder.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { LspOperations } from \"./tools/lsp.ts\";\nimport { SqliteUsagePerformanceStore } from \"./usage-performance-store.ts\";\nimport { createDeferredWebSearchOperations, resolveWebSearchOperations } from \"./web-search-provider.ts\";\n\n/** Filename of the shared durable-state database within an agent directory (roadmap Phase 8). */\nconst DURABLE_STATE_DATABASE_FILENAME = \"state.sqlite\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\t/**\n\t * Session id to stamp on every usage-performance sample this runtime records.\n\t * Only observed when `modelRuntime` is not already provided — a caller-supplied\n\t * runtime owns its own store, if any.\n\t */\n\tsessionId?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\tmodelRuntimeSignal?: AbortSignal;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n\tpermissionGate?: Omit<PermissionGateOptions, \"getContract\">;\n\t/** Optional headless permission bridge (ACP, spec 2026-08-31-acp-adapter.md). */\n\tpermissionResponderFactory?: () => PermissionResponder | undefined;\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tlspPool: LspPool;\n\t/**\n\t * Wraps `lspPool` for `DiagnosticsOperations.afterMutation` (LSP.4). Structurally\n\t * compatible with `core/tools/diagnostics.ts`'s `DiagnosticsOperations` -- callers\n\t * pass this value directly, never importing `core/lsp/*` themselves.\n\t */\n\tlspDiagnostics: LspDiagnostics;\n\t/** True when at least one LSP server resolved -- gates registering the `lsp` tool (LSP.5). */\n\tlspConfigured: boolean;\n\t/**\n\t * Chronological, bounded record of every server-root state transition observed by\n\t * `lspPool` for this services lifetime (LSP.2). Inspectable structured state -- not\n\t * wired to any user-facing surface by this plan (see `docs/plans/2026-08-18-lsp.md`,\n\t * Task LSP.2: this is not a `/doctor` task).\n\t */\n\tlspStatus: LspStatusStore;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n\tclose(): Promise<void>;\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\n\t// A ledger failure must never block session creation or a turn — open it\n\t// best-effort and degrade to a diagnostic, never a thrown error.\n\tlet usagePerformanceStore: SqliteUsagePerformanceStore | undefined;\n\tif (!options.modelRuntime) {\n\t\ttry {\n\t\t\tusagePerformanceStore = new SqliteUsagePerformanceStore(\n\t\t\t\tjoin(agentDir, DURABLE_STATE_DATABASE_FILENAME),\n\t\t\t\toptions.sessionId,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({ type: \"warning\", message: `Usage/cost recording unavailable: ${message}` });\n\t\t}\n\t}\n\n\t// No caller-supplied manager means nobody resolved trust, so this one cannot claim it.\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tconst otlpEndpoint = settingsManager.getObservabilitySettings().otlpEndpoint;\n\tconst otlpExportConfig = otlpEndpoint\n\t\t? { endpoint: otlpEndpoint, headers: settingsManager.getObservabilitySettings().otlpHeaders }\n\t\t: undefined;\n\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: process.env.APEX_CODE_AUTH_PATH ?? (options.agentDir ? join(agentDir, \"auth.json\") : getAuthPath()),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t\tusagePerformanceStore,\n\t\t\totlpExportConfig,\n\t\t}));\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tfor (const { provider, extensionPath } of extensionsResult.runtime.pendingNativeProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerNativeProvider(provider);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingNativeProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\t// `lspStatus` is constructed unconditionally (and outside the try) so it always\n\t// records real state transitions the pool experiences below, including the\n\t// eager-start failure the catch block handles -- not just a snapshot taken at one\n\t// fixed point in time.\n\tconst lspStatus = new LspStatusStore();\n\tlet lspPool: LspPool | undefined;\n\tlet registry: ReturnType<typeof resolveLspRegistry> | undefined;\n\tlet lspConfigured = false;\n\ttry {\n\t\tregistry = resolveLspRegistry(settingsManager.getLspSettings(), { workspace: cwd });\n\t\tlspPool = new LspPool(registry, {\n\t\t\tonStatusChange: (status) =>\n\t\t\t\tlspStatus.record({\n\t\t\t\t\tserverId: status.serverId,\n\t\t\t\t\troot: status.root,\n\t\t\t\t\tstate: status.state,\n\t\t\t\t\tattempt: status.attempts,\n\t\t\t\t\t...(status.reason === undefined ? {} : { reason: status.reason }),\n\t\t\t\t}),\n\t\t});\n\t\tlspConfigured = registry.servers.length > 0;\n\t\t// Per the spec's \"Resolved configuration, ownership, and lifecycle\": any\n\t\t// configured entry that cannot resolve, spawn, or initialize its cwd-root\n\t\t// process within its timeout is a startup misconfiguration -- fail fast here,\n\t\t// following core/permissions/startup.ts's precedent, rather than let a broken\n\t\t// server surface only when a tool call needs it mid-run.\n\t\tif (lspConfigured) await lspPool.start();\n\t} catch (error) {\n\t\t// Name the failing binary(ies), not just the raw client/registry error: the\n\t\t// registry itself already does this for a resolution failure (missing/\n\t\t// un-spawnable binary names the command and lookup path), but a `pool.start()`\n\t\t// rejection surfaces only the first client's bare error (e.g. \"initialize timed\n\t\t// out\"), with no server id attached. `registry.servers` (resolved commands) and\n\t\t// `lspPool.status()` (which entries actually failed) are both in scope here, so\n\t\t// build the richer message without changing `LspPoolStatus`'s shape or the\n\t\t// pool's own error-propagation wire format.\n\t\tconst commandById = new Map(registry?.servers.map((server) => [server.id, server.command]) ?? []);\n\t\tconst failedEntries = (lspPool?.status() ?? []).filter(\n\t\t\t(status) => status.state === \"degraded\" || status.state === \"disabled\",\n\t\t);\n\t\tconst message =\n\t\t\tfailedEntries.length > 0\n\t\t\t\t? failedEntries\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(status) =>\n\t\t\t\t\t\t\t\t`${status.serverId} (${commandById.get(status.serverId) ?? \"?\"}) at ${status.root}: ${status.reason ?? \"unknown error\"}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(\"; \")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: String(error);\n\t\tdiagnostics.push({ type: \"error\", message: `LSP startup failed: ${message}` });\n\t\t// A pool that got partway through eager start may already have spawned and\n\t\t// initialized sibling servers successfully; discarding it without disposing\n\t\t// would orphan those child processes rather than tearing them down cleanly.\n\t\tawait lspPool?.dispose().catch(() => {});\n\t\tlspConfigured = false;\n\t\tlspPool = new LspPool({ workspace: cwd, servers: [], platform: process.platform });\n\t}\n\tconst lspDiagnostics = new LspDiagnostics(lspPool);\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tlspPool,\n\t\tlspDiagnostics,\n\t\tlspConfigured,\n\t\tlspStatus,\n\t\tdiagnostics,\n\t\tclose: async () => {\n\t\t\t// Diagnostics first: it still needs live LSP clients to send didClose\n\t\t\t// during its own teardown, so it must not outlive the pool it wraps.\n\t\t\tawait lspDiagnostics.dispose();\n\t\t\tawait lspPool.dispose();\n\t\t\tif (!options.modelRuntime) modelRuntime.close();\n\t\t},\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\tconst { lspPool, lspDiagnostics, lspConfigured } = options.services;\n\t// Both gated on `lspConfigured` (at least one server resolved), not per-path:\n\t// the spec's \"no diagnostics injection or result change whatsoever when `lsp` is\n\t// unconfigured\" is a session-level guarantee. A session with servers configured\n\t// for *some* languages still injects diagnosticsOperations -- a mutated path with\n\t// no matching server correctly resolves to the explicit `unavailable` outcome via\n\t// `LspDiagnostics.afterMutation`'s own per-path `pool.acquire`, it is simply never\n\t// asked at all when the session has no servers whatsoever. `lspDiagnostics`\n\t// already matches `DiagnosticsOperations` structurally, so it is passed directly\n\t// rather than wrapped.\n\tconst diagnosticsOperations = lspConfigured ? lspDiagnostics : undefined;\n\tconst lspOperations: LspOperations | undefined = lspConfigured\n\t\t? {\n\t\t\t\trequest: async (absolutePath, method, params, signal) => {\n\t\t\t\t\tconst connection = await lspPool.acquire(absolutePath);\n\t\t\t\t\tif (!connection) return undefined;\n\t\t\t\t\treturn connection.client.request(method, params, signal);\n\t\t\t\t},\n\t\t\t}\n\t\t: undefined;\n\n\t// Read per call rather than captured here. The tool registry is built once at\n\t// session construction, so a key saved from the settings panel mid-session would\n\t// otherwise not take effect until restart.\n\t// Two different questions. Whether a credential resolves *now* decides whether the\n\t// tool is active, because activation happens once at construction. Resolution then\n\t// stays deferred so a key changed mid-session is picked up without a restart.\n\tconst settingsManager = options.services.settingsManager;\n\tconst webSearchOperations = resolveWebSearchOperations(settingsManager.getWebSearchSettings())\n\t\t? createDeferredWebSearchOperations(() => settingsManager.getWebSearchSettings())\n\t\t: undefined;\n\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tpermissionGate: options.permissionGate,\n\t\tpermissionResponderFactory: options.permissionResponderFactory,\n\t\tdiagnosticsOperations,\n\t\tlspOperations,\n\t\twebSearchOperations,\n\t});\n}\n"]}
@@ -74,7 +74,8 @@ export async function createAgentSessionServices(options) {
74
74
  diagnostics.push({ type: "warning", message: `Usage/cost recording unavailable: ${message}` });
75
75
  }
76
76
  }
77
- const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);
77
+ // No caller-supplied manager means nobody resolved trust, so this one cannot claim it.
78
+ const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir, { projectTrusted: false });
78
79
  const otlpEndpoint = settingsManager.getObservabilitySettings().otlpEndpoint;
79
80
  const otlpExportConfig = otlpEndpoint
80
81
  ? { endpoint: otlpEndpoint, headers: settingsManager.getObservabilitySettings().otlpHeaders }
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,OAAO,EACN,qBAAqB,GAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAiE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE7G,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,iCAAiC,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AAEzG,iGAAiG;AACjG,MAAM,+BAA+B,GAAG,cAAc,CAAC;AA4FvD,SAAS,wBAAwB,CAChC,cAA8B,EAC9B,mBAA8D,EAC5B;IAClC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC1B,OAAO,EAAE,CAAC;IACX,CAAC;IAED,MAAM,WAAW,GAAoC,EAAE,CAAC;IACxD,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IACxD,MAAM,eAAe,GAAG,IAAI,GAAG,EAA0C,CAAC;IAC1E,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QAAQ,CAAC,QAAQ;QACnC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY;QAC3C,eAAe,EAAE,OAAO,CAAC,QAAQ,CAAC,eAAe;QACjD,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,cAAc;QAC/C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,qBAAqB;QACrB,aAAa;QACb,mBAAmB;KACnB,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { join } from \"node:path\";\nimport type { Model } from \"@earendil-works/pi-ai\";\nimport type { ThinkingLevel } from \"apex-code-agent-core\";\nimport { getAgentDir, getAuthPath } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { LspDiagnostics } from \"./lsp/diagnostics.ts\";\nimport { LspPool } from \"./lsp/pool.ts\";\nimport { resolveLspRegistry } from \"./lsp/registry.ts\";\nimport { LspStatusStore } from \"./lsp/status.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport type { PermissionGateOptions } from \"./permissions/gate.ts\";\nimport type { PermissionResponder } from \"./permissions/responder.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { LspOperations } from \"./tools/lsp.ts\";\nimport { SqliteUsagePerformanceStore } from \"./usage-performance-store.ts\";\nimport { createDeferredWebSearchOperations, resolveWebSearchOperations } from \"./web-search-provider.ts\";\n\n/** Filename of the shared durable-state database within an agent directory (roadmap Phase 8). */\nconst DURABLE_STATE_DATABASE_FILENAME = \"state.sqlite\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\t/**\n\t * Session id to stamp on every usage-performance sample this runtime records.\n\t * Only observed when `modelRuntime` is not already provided — a caller-supplied\n\t * runtime owns its own store, if any.\n\t */\n\tsessionId?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\tmodelRuntimeSignal?: AbortSignal;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n\tpermissionGate?: Omit<PermissionGateOptions, \"getContract\">;\n\t/** Optional headless permission bridge (ACP, spec 2026-08-31-acp-adapter.md). */\n\tpermissionResponderFactory?: () => PermissionResponder | undefined;\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tlspPool: LspPool;\n\t/**\n\t * Wraps `lspPool` for `DiagnosticsOperations.afterMutation` (LSP.4). Structurally\n\t * compatible with `core/tools/diagnostics.ts`'s `DiagnosticsOperations` -- callers\n\t * pass this value directly, never importing `core/lsp/*` themselves.\n\t */\n\tlspDiagnostics: LspDiagnostics;\n\t/** True when at least one LSP server resolved -- gates registering the `lsp` tool (LSP.5). */\n\tlspConfigured: boolean;\n\t/**\n\t * Chronological, bounded record of every server-root state transition observed by\n\t * `lspPool` for this services lifetime (LSP.2). Inspectable structured state -- not\n\t * wired to any user-facing surface by this plan (see `docs/plans/2026-08-18-lsp.md`,\n\t * Task LSP.2: this is not a `/doctor` task).\n\t */\n\tlspStatus: LspStatusStore;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n\tclose(): Promise<void>;\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\n\t// A ledger failure must never block session creation or a turn — open it\n\t// best-effort and degrade to a diagnostic, never a thrown error.\n\tlet usagePerformanceStore: SqliteUsagePerformanceStore | undefined;\n\tif (!options.modelRuntime) {\n\t\ttry {\n\t\t\tusagePerformanceStore = new SqliteUsagePerformanceStore(\n\t\t\t\tjoin(agentDir, DURABLE_STATE_DATABASE_FILENAME),\n\t\t\t\toptions.sessionId,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({ type: \"warning\", message: `Usage/cost recording unavailable: ${message}` });\n\t\t}\n\t}\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst otlpEndpoint = settingsManager.getObservabilitySettings().otlpEndpoint;\n\tconst otlpExportConfig = otlpEndpoint\n\t\t? { endpoint: otlpEndpoint, headers: settingsManager.getObservabilitySettings().otlpHeaders }\n\t\t: undefined;\n\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: process.env.APEX_CODE_AUTH_PATH ?? (options.agentDir ? join(agentDir, \"auth.json\") : getAuthPath()),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t\tusagePerformanceStore,\n\t\t\totlpExportConfig,\n\t\t}));\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tfor (const { provider, extensionPath } of extensionsResult.runtime.pendingNativeProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerNativeProvider(provider);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingNativeProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\t// `lspStatus` is constructed unconditionally (and outside the try) so it always\n\t// records real state transitions the pool experiences below, including the\n\t// eager-start failure the catch block handles -- not just a snapshot taken at one\n\t// fixed point in time.\n\tconst lspStatus = new LspStatusStore();\n\tlet lspPool: LspPool | undefined;\n\tlet registry: ReturnType<typeof resolveLspRegistry> | undefined;\n\tlet lspConfigured = false;\n\ttry {\n\t\tregistry = resolveLspRegistry(settingsManager.getLspSettings(), { workspace: cwd });\n\t\tlspPool = new LspPool(registry, {\n\t\t\tonStatusChange: (status) =>\n\t\t\t\tlspStatus.record({\n\t\t\t\t\tserverId: status.serverId,\n\t\t\t\t\troot: status.root,\n\t\t\t\t\tstate: status.state,\n\t\t\t\t\tattempt: status.attempts,\n\t\t\t\t\t...(status.reason === undefined ? {} : { reason: status.reason }),\n\t\t\t\t}),\n\t\t});\n\t\tlspConfigured = registry.servers.length > 0;\n\t\t// Per the spec's \"Resolved configuration, ownership, and lifecycle\": any\n\t\t// configured entry that cannot resolve, spawn, or initialize its cwd-root\n\t\t// process within its timeout is a startup misconfiguration -- fail fast here,\n\t\t// following core/permissions/startup.ts's precedent, rather than let a broken\n\t\t// server surface only when a tool call needs it mid-run.\n\t\tif (lspConfigured) await lspPool.start();\n\t} catch (error) {\n\t\t// Name the failing binary(ies), not just the raw client/registry error: the\n\t\t// registry itself already does this for a resolution failure (missing/\n\t\t// un-spawnable binary names the command and lookup path), but a `pool.start()`\n\t\t// rejection surfaces only the first client's bare error (e.g. \"initialize timed\n\t\t// out\"), with no server id attached. `registry.servers` (resolved commands) and\n\t\t// `lspPool.status()` (which entries actually failed) are both in scope here, so\n\t\t// build the richer message without changing `LspPoolStatus`'s shape or the\n\t\t// pool's own error-propagation wire format.\n\t\tconst commandById = new Map(registry?.servers.map((server) => [server.id, server.command]) ?? []);\n\t\tconst failedEntries = (lspPool?.status() ?? []).filter(\n\t\t\t(status) => status.state === \"degraded\" || status.state === \"disabled\",\n\t\t);\n\t\tconst message =\n\t\t\tfailedEntries.length > 0\n\t\t\t\t? failedEntries\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(status) =>\n\t\t\t\t\t\t\t\t`${status.serverId} (${commandById.get(status.serverId) ?? \"?\"}) at ${status.root}: ${status.reason ?? \"unknown error\"}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(\"; \")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: String(error);\n\t\tdiagnostics.push({ type: \"error\", message: `LSP startup failed: ${message}` });\n\t\t// A pool that got partway through eager start may already have spawned and\n\t\t// initialized sibling servers successfully; discarding it without disposing\n\t\t// would orphan those child processes rather than tearing them down cleanly.\n\t\tawait lspPool?.dispose().catch(() => {});\n\t\tlspConfigured = false;\n\t\tlspPool = new LspPool({ workspace: cwd, servers: [], platform: process.platform });\n\t}\n\tconst lspDiagnostics = new LspDiagnostics(lspPool);\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tlspPool,\n\t\tlspDiagnostics,\n\t\tlspConfigured,\n\t\tlspStatus,\n\t\tdiagnostics,\n\t\tclose: async () => {\n\t\t\t// Diagnostics first: it still needs live LSP clients to send didClose\n\t\t\t// during its own teardown, so it must not outlive the pool it wraps.\n\t\t\tawait lspDiagnostics.dispose();\n\t\t\tawait lspPool.dispose();\n\t\t\tif (!options.modelRuntime) modelRuntime.close();\n\t\t},\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\tconst { lspPool, lspDiagnostics, lspConfigured } = options.services;\n\t// Both gated on `lspConfigured` (at least one server resolved), not per-path:\n\t// the spec's \"no diagnostics injection or result change whatsoever when `lsp` is\n\t// unconfigured\" is a session-level guarantee. A session with servers configured\n\t// for *some* languages still injects diagnosticsOperations -- a mutated path with\n\t// no matching server correctly resolves to the explicit `unavailable` outcome via\n\t// `LspDiagnostics.afterMutation`'s own per-path `pool.acquire`, it is simply never\n\t// asked at all when the session has no servers whatsoever. `lspDiagnostics`\n\t// already matches `DiagnosticsOperations` structurally, so it is passed directly\n\t// rather than wrapped.\n\tconst diagnosticsOperations = lspConfigured ? lspDiagnostics : undefined;\n\tconst lspOperations: LspOperations | undefined = lspConfigured\n\t\t? {\n\t\t\t\trequest: async (absolutePath, method, params, signal) => {\n\t\t\t\t\tconst connection = await lspPool.acquire(absolutePath);\n\t\t\t\t\tif (!connection) return undefined;\n\t\t\t\t\treturn connection.client.request(method, params, signal);\n\t\t\t\t},\n\t\t\t}\n\t\t: undefined;\n\n\t// Read per call rather than captured here. The tool registry is built once at\n\t// session construction, so a key saved from the settings panel mid-session would\n\t// otherwise not take effect until restart.\n\t// Two different questions. Whether a credential resolves *now* decides whether the\n\t// tool is active, because activation happens once at construction. Resolution then\n\t// stays deferred so a key changed mid-session is picked up without a restart.\n\tconst settingsManager = options.services.settingsManager;\n\tconst webSearchOperations = resolveWebSearchOperations(settingsManager.getWebSearchSettings())\n\t\t? createDeferredWebSearchOperations(() => settingsManager.getWebSearchSettings())\n\t\t: undefined;\n\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tpermissionGate: options.permissionGate,\n\t\tpermissionResponderFactory: options.permissionResponderFactory,\n\t\tdiagnosticsOperations,\n\t\tlspOperations,\n\t\twebSearchOperations,\n\t});\n}\n"]}
1
+ {"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,OAAO,EACN,qBAAqB,GAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAiE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE7G,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,iCAAiC,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AAEzG,iGAAiG;AACjG,MAAM,+BAA+B,GAAG,cAAc,CAAC;AA4FvD,SAAS,wBAAwB,CAChC,cAA8B,EAC9B,mBAA8D,EAC5B;IAClC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC1B,OAAO,E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QAC7F,CAAC,CAAC,iCAAiC,CAAC,GAAG,EAAE,CAAC,eAAe,CAAC,oBAAoB,EAAE,CAAC;QACjF,CAAC,CAAC,SAAS,CAAC;IAEb,OAAO,kBAAkB,CAAC;QACzB,GAAG,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG;QACzB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,QAAQ;QACnC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY;QAC3C,eAAe,EAAE,OAAO,CAAC,QAAQ,CAAC,eAAe;QACjD,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,cAAc;QAC/C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,qBAAqB;QACrB,aAAa;QACb,mBAAmB;KACnB,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { join } from \"node:path\";\nimport type { Model } from \"@earendil-works/pi-ai\";\nimport type { ThinkingLevel } from \"apex-code-agent-core\";\nimport { getAgentDir, getAuthPath } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { LspDiagnostics } from \"./lsp/diagnostics.ts\";\nimport { LspPool } from \"./lsp/pool.ts\";\nimport { resolveLspRegistry } from \"./lsp/registry.ts\";\nimport { LspStatusStore } from \"./lsp/status.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport type { PermissionGateOptions } from \"./permissions/gate.ts\";\nimport type { PermissionResponder } from \"./permissions/responder.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { LspOperations } from \"./tools/lsp.ts\";\nimport { SqliteUsagePerformanceStore } from \"./usage-performance-store.ts\";\nimport { createDeferredWebSearchOperations, resolveWebSearchOperations } from \"./web-search-provider.ts\";\n\n/** Filename of the shared durable-state database within an agent directory (roadmap Phase 8). */\nconst DURABLE_STATE_DATABASE_FILENAME = \"state.sqlite\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\t/**\n\t * Session id to stamp on every usage-performance sample this runtime records.\n\t * Only observed when `modelRuntime` is not already provided — a caller-supplied\n\t * runtime owns its own store, if any.\n\t */\n\tsessionId?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\tmodelRuntimeSignal?: AbortSignal;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n\tpermissionGate?: Omit<PermissionGateOptions, \"getContract\">;\n\t/** Optional headless permission bridge (ACP, spec 2026-08-31-acp-adapter.md). */\n\tpermissionResponderFactory?: () => PermissionResponder | undefined;\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tlspPool: LspPool;\n\t/**\n\t * Wraps `lspPool` for `DiagnosticsOperations.afterMutation` (LSP.4). Structurally\n\t * compatible with `core/tools/diagnostics.ts`'s `DiagnosticsOperations` -- callers\n\t * pass this value directly, never importing `core/lsp/*` themselves.\n\t */\n\tlspDiagnostics: LspDiagnostics;\n\t/** True when at least one LSP server resolved -- gates registering the `lsp` tool (LSP.5). */\n\tlspConfigured: boolean;\n\t/**\n\t * Chronological, bounded record of every server-root state transition observed by\n\t * `lspPool` for this services lifetime (LSP.2). Inspectable structured state -- not\n\t * wired to any user-facing surface by this plan (see `docs/plans/2026-08-18-lsp.md`,\n\t * Task LSP.2: this is not a `/doctor` task).\n\t */\n\tlspStatus: LspStatusStore;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n\tclose(): Promise<void>;\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\n\t// A ledger failure must never block session creation or a turn — open it\n\t// best-effort and degrade to a diagnostic, never a thrown error.\n\tlet usagePerformanceStore: SqliteUsagePerformanceStore | undefined;\n\tif (!options.modelRuntime) {\n\t\ttry {\n\t\t\tusagePerformanceStore = new SqliteUsagePerformanceStore(\n\t\t\t\tjoin(agentDir, DURABLE_STATE_DATABASE_FILENAME),\n\t\t\t\toptions.sessionId,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({ type: \"warning\", message: `Usage/cost recording unavailable: ${message}` });\n\t\t}\n\t}\n\n\t// No caller-supplied manager means nobody resolved trust, so this one cannot claim it.\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tconst otlpEndpoint = settingsManager.getObservabilitySettings().otlpEndpoint;\n\tconst otlpExportConfig = otlpEndpoint\n\t\t? { endpoint: otlpEndpoint, headers: settingsManager.getObservabilitySettings().otlpHeaders }\n\t\t: undefined;\n\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: process.env.APEX_CODE_AUTH_PATH ?? (options.agentDir ? join(agentDir, \"auth.json\") : getAuthPath()),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t\tusagePerformanceStore,\n\t\t\totlpExportConfig,\n\t\t}));\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tfor (const { provider, extensionPath } of extensionsResult.runtime.pendingNativeProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerNativeProvider(provider);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingNativeProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\t// `lspStatus` is constructed unconditionally (and outside the try) so it always\n\t// records real state transitions the pool experiences below, including the\n\t// eager-start failure the catch block handles -- not just a snapshot taken at one\n\t// fixed point in time.\n\tconst lspStatus = new LspStatusStore();\n\tlet lspPool: LspPool | undefined;\n\tlet registry: ReturnType<typeof resolveLspRegistry> | undefined;\n\tlet lspConfigured = false;\n\ttry {\n\t\tregistry = resolveLspRegistry(settingsManager.getLspSettings(), { workspace: cwd });\n\t\tlspPool = new LspPool(registry, {\n\t\t\tonStatusChange: (status) =>\n\t\t\t\tlspStatus.record({\n\t\t\t\t\tserverId: status.serverId,\n\t\t\t\t\troot: status.root,\n\t\t\t\t\tstate: status.state,\n\t\t\t\t\tattempt: status.attempts,\n\t\t\t\t\t...(status.reason === undefined ? {} : { reason: status.reason }),\n\t\t\t\t}),\n\t\t});\n\t\tlspConfigured = registry.servers.length > 0;\n\t\t// Per the spec's \"Resolved configuration, ownership, and lifecycle\": any\n\t\t// configured entry that cannot resolve, spawn, or initialize its cwd-root\n\t\t// process within its timeout is a startup misconfiguration -- fail fast here,\n\t\t// following core/permissions/startup.ts's precedent, rather than let a broken\n\t\t// server surface only when a tool call needs it mid-run.\n\t\tif (lspConfigured) await lspPool.start();\n\t} catch (error) {\n\t\t// Name the failing binary(ies), not just the raw client/registry error: the\n\t\t// registry itself already does this for a resolution failure (missing/\n\t\t// un-spawnable binary names the command and lookup path), but a `pool.start()`\n\t\t// rejection surfaces only the first client's bare error (e.g. \"initialize timed\n\t\t// out\"), with no server id attached. `registry.servers` (resolved commands) and\n\t\t// `lspPool.status()` (which entries actually failed) are both in scope here, so\n\t\t// build the richer message without changing `LspPoolStatus`'s shape or the\n\t\t// pool's own error-propagation wire format.\n\t\tconst commandById = new Map(registry?.servers.map((server) => [server.id, server.command]) ?? []);\n\t\tconst failedEntries = (lspPool?.status() ?? []).filter(\n\t\t\t(status) => status.state === \"degraded\" || status.state === \"disabled\",\n\t\t);\n\t\tconst message =\n\t\t\tfailedEntries.length > 0\n\t\t\t\t? failedEntries\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(status) =>\n\t\t\t\t\t\t\t\t`${status.serverId} (${commandById.get(status.serverId) ?? \"?\"}) at ${status.root}: ${status.reason ?? \"unknown error\"}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(\"; \")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: String(error);\n\t\tdiagnostics.push({ type: \"error\", message: `LSP startup failed: ${message}` });\n\t\t// A pool that got partway through eager start may already have spawned and\n\t\t// initialized sibling servers successfully; discarding it without disposing\n\t\t// would orphan those child processes rather than tearing them down cleanly.\n\t\tawait lspPool?.dispose().catch(() => {});\n\t\tlspConfigured = false;\n\t\tlspPool = new LspPool({ workspace: cwd, servers: [], platform: process.platform });\n\t}\n\tconst lspDiagnostics = new LspDiagnostics(lspPool);\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tlspPool,\n\t\tlspDiagnostics,\n\t\tlspConfigured,\n\t\tlspStatus,\n\t\tdiagnostics,\n\t\tclose: async () => {\n\t\t\t// Diagnostics first: it still needs live LSP clients to send didClose\n\t\t\t// during its own teardown, so it must not outlive the pool it wraps.\n\t\t\tawait lspDiagnostics.dispose();\n\t\t\tawait lspPool.dispose();\n\t\t\tif (!options.modelRuntime) modelRuntime.close();\n\t\t},\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\tconst { lspPool, lspDiagnostics, lspConfigured } = options.services;\n\t// Both gated on `lspConfigured` (at least one server resolved), not per-path:\n\t// the spec's \"no diagnostics injection or result change whatsoever when `lsp` is\n\t// unconfigured\" is a session-level guarantee. A session with servers configured\n\t// for *some* languages still injects diagnosticsOperations -- a mutated path with\n\t// no matching server correctly resolves to the explicit `unavailable` outcome via\n\t// `LspDiagnostics.afterMutation`'s own per-path `pool.acquire`, it is simply never\n\t// asked at all when the session has no servers whatsoever. `lspDiagnostics`\n\t// already matches `DiagnosticsOperations` structurally, so it is passed directly\n\t// rather than wrapped.\n\tconst diagnosticsOperations = lspConfigured ? lspDiagnostics : undefined;\n\tconst lspOperations: LspOperations | undefined = lspConfigured\n\t\t? {\n\t\t\t\trequest: async (absolutePath, method, params, signal) => {\n\t\t\t\t\tconst connection = await lspPool.acquire(absolutePath);\n\t\t\t\t\tif (!connection) return undefined;\n\t\t\t\t\treturn connection.client.request(method, params, signal);\n\t\t\t\t},\n\t\t\t}\n\t\t: undefined;\n\n\t// Read per call rather than captured here. The tool registry is built once at\n\t// session construction, so a key saved from the settings panel mid-session would\n\t// otherwise not take effect until restart.\n\t// Two different questions. Whether a credential resolves *now* decides whether the\n\t// tool is active, because activation happens once at construction. Resolution then\n\t// stays deferred so a key changed mid-session is picked up without a restart.\n\tconst settingsManager = options.services.settingsManager;\n\tconst webSearchOperations = resolveWebSearchOperations(settingsManager.getWebSearchSettings())\n\t\t? createDeferredWebSearchOperations(() => settingsManager.getWebSearchSettings())\n\t\t: undefined;\n\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tpermissionGate: options.permissionGate,\n\t\tpermissionResponderFactory: options.permissionResponderFactory,\n\t\tdiagnosticsOperations,\n\t\tlspOperations,\n\t\twebSearchOperations,\n\t});\n}\n"]}