apex-code 0.0.1-alpha.7 → 0.0.1-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/CHANGELOG.md +146 -0
  2. package/README.md +5 -0
  3. package/dist/cli/args.d.ts +3 -1
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +15 -0
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/concurrent-session.d.ts +3 -0
  8. package/dist/cli/concurrent-session.d.ts.map +1 -0
  9. package/dist/cli/concurrent-session.js +13 -0
  10. package/dist/cli/concurrent-session.js.map +1 -0
  11. package/dist/cli.d.ts.map +1 -1
  12. package/dist/cli.js +1 -2
  13. package/dist/cli.js.map +1 -1
  14. package/dist/core/agent-session-services.d.ts.map +1 -1
  15. package/dist/core/agent-session-services.js +20 -0
  16. package/dist/core/agent-session-services.js.map +1 -1
  17. package/dist/core/agent-session.d.ts +15 -2
  18. package/dist/core/agent-session.d.ts.map +1 -1
  19. package/dist/core/agent-session.js +9 -6
  20. package/dist/core/agent-session.js.map +1 -1
  21. package/dist/core/auth-storage.d.ts +4 -1
  22. package/dist/core/auth-storage.d.ts.map +1 -1
  23. package/dist/core/auth-storage.js +6 -2
  24. package/dist/core/auth-storage.js.map +1 -1
  25. package/dist/core/bash-executor.d.ts.map +1 -1
  26. package/dist/core/bash-executor.js +10 -9
  27. package/dist/core/bash-executor.js.map +1 -1
  28. package/dist/core/experimental.d.ts +4 -0
  29. package/dist/core/experimental.d.ts.map +1 -1
  30. package/dist/core/experimental.js +4 -0
  31. package/dist/core/experimental.js.map +1 -1
  32. package/dist/core/extensions/types.d.ts +4 -0
  33. package/dist/core/extensions/types.d.ts.map +1 -1
  34. package/dist/core/extensions/types.js.map +1 -1
  35. package/dist/core/http-dispatcher.d.ts +1 -2
  36. package/dist/core/http-dispatcher.d.ts.map +1 -1
  37. package/dist/core/http-dispatcher.js +2 -17
  38. package/dist/core/http-dispatcher.js.map +1 -1
  39. package/dist/core/http-idle-timeout.d.ts +12 -0
  40. package/dist/core/http-idle-timeout.d.ts.map +1 -0
  41. package/dist/core/http-idle-timeout.js +27 -0
  42. package/dist/core/http-idle-timeout.js.map +1 -0
  43. package/dist/core/keybindings.d.ts +24 -0
  44. package/dist/core/keybindings.d.ts.map +1 -1
  45. package/dist/core/lsp/client.d.ts +2 -0
  46. package/dist/core/lsp/client.d.ts.map +1 -1
  47. package/dist/core/lsp/client.js +27 -2
  48. package/dist/core/lsp/client.js.map +1 -1
  49. package/dist/core/model-config.d.ts +5 -0
  50. package/dist/core/model-config.d.ts.map +1 -1
  51. package/dist/core/model-config.js +1 -0
  52. package/dist/core/model-config.js.map +1 -1
  53. package/dist/core/sandbox/child-entry.d.ts.map +1 -1
  54. package/dist/core/sandbox/child-entry.js +8 -1
  55. package/dist/core/sandbox/child-entry.js.map +1 -1
  56. package/dist/core/sandbox/cli-launch.d.ts +3 -0
  57. package/dist/core/sandbox/cli-launch.d.ts.map +1 -1
  58. package/dist/core/sandbox/cli-launch.js +25 -4
  59. package/dist/core/sandbox/cli-launch.js.map +1 -1
  60. package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -1
  61. package/dist/core/sandbox/cli-supervisor.js +53 -13
  62. package/dist/core/sandbox/cli-supervisor.js.map +1 -1
  63. package/dist/core/sandbox/linux-backend.d.ts.map +1 -1
  64. package/dist/core/sandbox/linux-backend.js +15 -0
  65. package/dist/core/sandbox/linux-backend.js.map +1 -1
  66. package/dist/core/sandbox/macos-backend.d.ts.map +1 -1
  67. package/dist/core/sandbox/macos-backend.js +24 -1
  68. package/dist/core/sandbox/macos-backend.js.map +1 -1
  69. package/dist/core/sandbox/rpc/credential-client.d.ts +20 -0
  70. package/dist/core/sandbox/rpc/credential-client.d.ts.map +1 -0
  71. package/dist/core/sandbox/rpc/credential-client.js +170 -0
  72. package/dist/core/sandbox/rpc/credential-client.js.map +1 -0
  73. package/dist/core/sandbox/rpc/credential-proxy.d.ts +44 -0
  74. package/dist/core/sandbox/rpc/credential-proxy.d.ts.map +1 -0
  75. package/dist/core/sandbox/rpc/credential-proxy.js +381 -0
  76. package/dist/core/sandbox/rpc/credential-proxy.js.map +1 -0
  77. package/dist/core/sandbox/supervisor.d.ts +11 -0
  78. package/dist/core/sandbox/supervisor.d.ts.map +1 -1
  79. package/dist/core/sandbox/supervisor.js.map +1 -1
  80. package/dist/core/sandbox/terminal-size.d.ts +40 -0
  81. package/dist/core/sandbox/terminal-size.d.ts.map +1 -0
  82. package/dist/core/sandbox/terminal-size.js +105 -0
  83. package/dist/core/sandbox/terminal-size.js.map +1 -0
  84. package/dist/core/sdk.d.ts +6 -3
  85. package/dist/core/sdk.d.ts.map +1 -1
  86. package/dist/core/sdk.js +16 -4
  87. package/dist/core/sdk.js.map +1 -1
  88. package/dist/core/session-lease.d.ts +31 -0
  89. package/dist/core/session-lease.d.ts.map +1 -0
  90. package/dist/core/session-lease.js +138 -0
  91. package/dist/core/session-lease.js.map +1 -0
  92. package/dist/core/session-manager.d.ts +5 -0
  93. package/dist/core/session-manager.d.ts.map +1 -1
  94. package/dist/core/session-manager.js +3 -3
  95. package/dist/core/session-manager.js.map +1 -1
  96. package/dist/core/settings-manager.d.ts +26 -0
  97. package/dist/core/settings-manager.d.ts.map +1 -1
  98. package/dist/core/settings-manager.js +42 -3
  99. package/dist/core/settings-manager.js.map +1 -1
  100. package/dist/core/slash-commands.d.ts.map +1 -1
  101. package/dist/core/slash-commands.js +2 -0
  102. package/dist/core/slash-commands.js.map +1 -1
  103. package/dist/core/system-prompt.d.ts +2 -2
  104. package/dist/core/system-prompt.d.ts.map +1 -1
  105. package/dist/core/system-prompt.js +47 -62
  106. package/dist/core/system-prompt.js.map +1 -1
  107. package/dist/core/tools/bash.d.ts.map +1 -1
  108. package/dist/core/tools/bash.js +2 -0
  109. package/dist/core/tools/bash.js.map +1 -1
  110. package/dist/core/tools/delegate.d.ts.map +1 -1
  111. package/dist/core/tools/delegate.js +24 -0
  112. package/dist/core/tools/delegate.js.map +1 -1
  113. package/dist/core/tools/edit.d.ts.map +1 -1
  114. package/dist/core/tools/edit.js +2 -0
  115. package/dist/core/tools/edit.js.map +1 -1
  116. package/dist/core/tools/find.d.ts.map +1 -1
  117. package/dist/core/tools/find.js +1 -1
  118. package/dist/core/tools/find.js.map +1 -1
  119. package/dist/core/tools/grep.d.ts +2 -0
  120. package/dist/core/tools/grep.d.ts.map +1 -1
  121. package/dist/core/tools/grep.js +35 -10
  122. package/dist/core/tools/grep.js.map +1 -1
  123. package/dist/core/tools/ls.d.ts +2 -0
  124. package/dist/core/tools/ls.d.ts.map +1 -1
  125. package/dist/core/tools/ls.js +5 -1
  126. package/dist/core/tools/ls.js.map +1 -1
  127. package/dist/core/tools/read.d.ts.map +1 -1
  128. package/dist/core/tools/read.js +2 -0
  129. package/dist/core/tools/read.js.map +1 -1
  130. package/dist/core/tools/web-search-exa.d.ts +33 -0
  131. package/dist/core/tools/web-search-exa.d.ts.map +1 -0
  132. package/dist/core/tools/web-search-exa.js +128 -0
  133. package/dist/core/tools/web-search-exa.js.map +1 -0
  134. package/dist/core/tools/write.d.ts.map +1 -1
  135. package/dist/core/tools/write.js +2 -0
  136. package/dist/core/tools/write.js.map +1 -1
  137. package/dist/core/web-search-provider.d.ts +64 -0
  138. package/dist/core/web-search-provider.d.ts.map +1 -0
  139. package/dist/core/web-search-provider.js +149 -0
  140. package/dist/core/web-search-provider.js.map +1 -0
  141. package/dist/index.d.ts +1 -1
  142. package/dist/index.d.ts.map +1 -1
  143. package/dist/index.js.map +1 -1
  144. package/dist/main.d.ts +1 -0
  145. package/dist/main.d.ts.map +1 -1
  146. package/dist/main.js +20 -1
  147. package/dist/main.js.map +1 -1
  148. package/dist/modes/interactive/components/custom-editor.d.ts +23 -0
  149. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  150. package/dist/modes/interactive/components/custom-editor.js +105 -2
  151. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  152. package/dist/modes/interactive/components/dynamic-border.d.ts +7 -1
  153. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  154. package/dist/modes/interactive/components/dynamic-border.js +11 -2
  155. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  156. package/dist/modes/interactive/components/extension-selector.d.ts +4 -0
  157. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  158. package/dist/modes/interactive/components/extension-selector.js +24 -6
  159. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  160. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  161. package/dist/modes/interactive/components/first-time-setup.js +6 -3
  162. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  163. package/dist/modes/interactive/components/first-use-hints.d.ts +8 -0
  164. package/dist/modes/interactive/components/first-use-hints.d.ts.map +1 -0
  165. package/dist/modes/interactive/components/first-use-hints.js +22 -0
  166. package/dist/modes/interactive/components/first-use-hints.js.map +1 -0
  167. package/dist/modes/interactive/components/footer.d.ts +12 -0
  168. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/footer.js +128 -9
  170. package/dist/modes/interactive/components/footer.js.map +1 -1
  171. package/dist/modes/interactive/components/index.d.ts +1 -0
  172. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/index.js +1 -0
  174. package/dist/modes/interactive/components/index.js.map +1 -1
  175. package/dist/modes/interactive/components/model-selector.d.ts +2 -0
  176. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/model-selector.js +20 -5
  178. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  179. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  180. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  181. package/dist/modes/interactive/components/settings-selector.js +10 -0
  182. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  183. package/dist/modes/interactive/components/splash-header.d.ts +29 -4
  184. package/dist/modes/interactive/components/splash-header.d.ts.map +1 -1
  185. package/dist/modes/interactive/components/splash-header.js +58 -23
  186. package/dist/modes/interactive/components/splash-header.js.map +1 -1
  187. package/dist/modes/interactive/components/tool-execution.d.ts +14 -0
  188. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  189. package/dist/modes/interactive/components/tool-execution.js +113 -35
  190. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  191. package/dist/modes/interactive/components/tool-panel.d.ts +30 -0
  192. package/dist/modes/interactive/components/tool-panel.d.ts.map +1 -0
  193. package/dist/modes/interactive/components/tool-panel.js +130 -0
  194. package/dist/modes/interactive/components/tool-panel.js.map +1 -0
  195. package/dist/modes/interactive/interactive-mode.d.ts +44 -9
  196. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  197. package/dist/modes/interactive/interactive-mode.js +282 -70
  198. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  199. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  200. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  201. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  202. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  203. package/dist/modes/interactive/theme/apex.json +62 -63
  204. package/dist/modes/interactive/theme/dark.json +2 -0
  205. package/dist/modes/interactive/theme/light.json +2 -0
  206. package/dist/modes/interactive/theme/theme-controller.d.ts +10 -2
  207. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  208. package/dist/modes/interactive/theme/theme-controller.js +25 -11
  209. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  210. package/dist/modes/interactive/theme/theme-schema.json +9 -1
  211. package/dist/modes/interactive/theme/theme.d.ts +14 -3
  212. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  213. package/dist/modes/interactive/theme/theme.js +55 -6
  214. package/dist/modes/interactive/theme/theme.js.map +1 -1
  215. package/dist/modes/json-event.d.ts +4 -1
  216. package/dist/modes/json-event.d.ts.map +1 -1
  217. package/dist/modes/json-event.js +5 -2
  218. package/dist/modes/json-event.js.map +1 -1
  219. package/dist/server/create-harness.d.ts.map +1 -1
  220. package/dist/server/create-harness.js +2 -0
  221. package/dist/server/create-harness.js.map +1 -1
  222. package/dist/themes/apex-logo.d.ts +36 -16
  223. package/dist/themes/apex-logo.d.ts.map +1 -1
  224. package/dist/themes/apex-logo.js +32 -28
  225. package/dist/themes/apex-logo.js.map +1 -1
  226. package/dist/utils/tools-manager.d.ts +10 -1
  227. package/dist/utils/tools-manager.d.ts.map +1 -1
  228. package/dist/utils/tools-manager.js +15 -20
  229. package/dist/utils/tools-manager.js.map +1 -1
  230. package/docs/compaction.md +3 -3
  231. package/docs/custom-provider.md +1 -1
  232. package/docs/environment-variables.md +1 -0
  233. package/docs/extensions.md +4 -0
  234. package/docs/json.md +6 -4
  235. package/docs/keybindings.md +8 -2
  236. package/docs/rpc.md +15 -4
  237. package/docs/sdk.md +9 -0
  238. package/docs/settings.md +63 -0
  239. package/docs/terminal-setup.md +23 -2
  240. package/docs/themes.md +24 -3
  241. package/docs/tui.md +2 -2
  242. package/docs/usage.md +3 -2
  243. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  244. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  245. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  246. package/examples/extensions/gondolin/package-lock.json +2 -2
  247. package/examples/extensions/gondolin/package.json +1 -1
  248. package/examples/extensions/sandbox/package-lock.json +2 -2
  249. package/examples/extensions/sandbox/package.json +1 -1
  250. package/examples/extensions/subagent/README.md +2 -0
  251. package/examples/extensions/subagent/agents.ts +40 -9
  252. package/examples/extensions/subagent/index.ts +21 -3
  253. package/examples/extensions/with-deps/package-lock.json +2 -2
  254. package/examples/extensions/with-deps/package.json +1 -1
  255. package/npm-shrinkwrap.json +27 -78
  256. package/package.json +6 -6
package/dist/cli.js CHANGED
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync } from "node:fs";
3
2
  import { homedir } from "node:os";
4
3
  import { dirname, join } from "node:path";
5
4
  /** The public CLI either supervises a sandbox child or starts an ordinary runtime. */
@@ -47,7 +46,7 @@ async function run() {
47
46
  environment: process.env,
48
47
  workspace: process.cwd(),
49
48
  allowedHosts,
50
- authPath: existsSync(authPath) ? authPath : undefined,
49
+ authPath,
51
50
  readOnlyPaths: [getPackageDir(), dirname(getPackageDir())],
52
51
  toolBinaries,
53
52
  skillPaths,
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,sFAAsF;AACtF,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACN,sBAAsB,EACtB,qBAAqB,EACrB,6BAA6B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,KAAK,UAAU,GAAG,GAAkB;IACnC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACnC,oFAAoF;IACpF,sEAAsE;IACtE,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IACpD,MAAM,SAAS,GAAG,cAAc,IAAI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,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CACxG;gBACD,GAAG,IAAI;aACP;YACD,WAAW,EAAE,OAAO,CAAC,GAAG;YACxB,SAAS,EAAE,OAAO,CAAC,GAAG,EAAE;YACxB,YAAY;YACZ,QAAQ,EAAE,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;YACrD,aAAa,EAAE,CAAC,aAAa,EAAE,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;YAC1D,YAAY;YACZ,UAAU;SACV,CAAC,CAAC;QACH,OAAO;IACR,CAAC;IAED,OAAO,CAAC,KAAK,GAAG,QAAQ,CAAC;IACzB,kBAAkB,CAAC,wBAAwB,EAAE,MAAM,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,WAAW,CAAC;IACnC,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAA+B,CAAC;IAC/D,uBAAuB,EAAE,CAAC;IAC1B,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACjB;AAED,MAAM,GAAG,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n/** The public CLI either supervises a sandbox child or starts an ordinary runtime. */\nimport { fileURLToPath } from \"node:url\";\nimport { APP_NAME, getAgentDir, getPackageDir } from \"./config.ts\";\nimport { setApexEnvironment } from \"./core/environment.ts\";\nimport { configureHttpDispatcher } from \"./core/http-dispatcher.ts\";\nimport {\n\trequiresSandboxedChild,\n\tresolveHostSkillPaths,\n\tresolveSupervisorAllowedHosts,\n} from \"./core/sandbox/cli-launch.ts\";\nimport { launchSandboxedCli } from \"./core/sandbox/cli-supervisor.ts\";\nimport { prepareHostToolBinaries } from \"./utils/tools-manager.ts\";\n\nasync function run(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\t// Validate session IDs before entering the sandbox. Invalid metadata must fail fast\n\t// without starting a child process or touching network/sandbox setup.\n\tconst sessionIdIndex = args.indexOf(\"--session-id\");\n\tconst sessionId = sessionIdIndex >= 0 ? args[sessionIdIndex + 1] : undefined;\n\tif (sessionId !== undefined && !/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(sessionId)) {\n\t\tconsole.error(\n\t\t\t\"Error: Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t\tprocess.exitCode = 1;\n\t\treturn;\n\t}\n\tif (requiresSandboxedChild(args)) {\n\t\tconst allowedHosts = resolveSupervisorAllowedHosts(process.cwd(), getAgentDir());\n\t\tconst authPath = join(getAgentDir(), \"auth.json\");\n\t\t// Resolve fd and rg out here, where the host home and the network are both still\n\t\t// reachable. The child's own PATH still names host directories the sandbox has\n\t\t// replaced, so without this projection it finds nothing and cannot download either.\n\t\t// Silent because this runs ahead of every mode, including --print and --mode rpc,\n\t\t// whose stdout carries machine-readable output; the child still reports a genuinely\n\t\t// missing tool through its own startup path.\n\t\tconst toolBinaries = await prepareHostToolBinaries(true);\n\t\t// Resolved here, where the host home is still reachable -- exactly like the\n\t\t// tool binaries above and unlike anything sourced from project files, which\n\t\t// ADR 0016 forbids as supervisor input before trust is established.\n\t\tconst { paths: skillPaths, refusals: skillPathRefusals } = resolveHostSkillPaths(\n\t\t\tgetAgentDir(),\n\t\t\tprocess.env.HOME || homedir(),\n\t\t);\n\t\tfor (const refusal of skillPathRefusals) {\n\t\t\tprocess.stderr.write(`Warning: not mounting skill directory ${refusal.path}: ${refusal.reason}\\n`);\n\t\t}\n\n\t\tprocess.exitCode = await launchSandboxedCli({\n\t\t\tcommand: process.execPath,\n\t\t\targs: [\n\t\t\t\tfileURLToPath(\n\t\t\t\t\tnew URL(`./core/sandbox/child-entry${import.meta.url.endsWith(\".ts\") ? \".ts\" : \".js\"}`, import.meta.url),\n\t\t\t\t),\n\t\t\t\t...args,\n\t\t\t],\n\t\t\tenvironment: process.env,\n\t\t\tworkspace: process.cwd(),\n\t\t\tallowedHosts,\n\t\t\tauthPath: existsSync(authPath) ? authPath : undefined,\n\t\t\treadOnlyPaths: [getPackageDir(), dirname(getPackageDir())],\n\t\t\ttoolBinaries,\n\t\t\tskillPaths,\n\t\t});\n\t\treturn;\n\t}\n\n\tprocess.title = APP_NAME;\n\tsetApexEnvironment(\"APEX_CODE_CODING_AGENT\", \"true\");\n\tprocess.env.AI_AGENT = \"apex-code\";\n\tprocess.emitWarning = (() => {}) as typeof process.emitWarning;\n\tconfigureHttpDispatcher();\n\tconst { main } = await import(\"./main.ts\");\n\tawait main(args);\n}\n\nawait run();\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,sFAAsF;AACtF,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACN,sBAAsB,EACtB,qBAAqB,EACrB,6BAA6B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,KAAK,UAAU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OAAO,CAAC,MAAM,IAAI,CAAC,CAAC;QACpG,CAAC;QAED,OAAO,CAAC,QAAQ,GAAG,MAAM,kBAAkB,CAAC;YAC3C,OAAO,EAAE,OAAO,CAAC,QAAQ;YACzB,IAAI,EAAE;gBACL,aAAa,CACZ,IAAI,GAAG,CAAC,6BAA6B,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CACxG;gBACD,GAAG,IAAI;aACP;YACD,WAAW,EAAE,OAAO,CAAC,GAAG;YACxB,SAAS,EAAE,OAAO,CAAC,GAAG,EAAE;YACxB,YAAY;YACZ,QAAQ;YACR,aAAa,EAAE,CAAC,aAAa,EAAE,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;YAC1D,YAAY;YACZ,UAAU;SACV,CAAC,CAAC;QACH,OAAO;IACR,CAAC;IAED,OAAO,CAAC,KAAK,GAAG,QAAQ,CAAC;IACzB,kBAAkB,CAAC,wBAAwB,EAAE,MAAM,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,WAAW,CAAC;IACnC,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAA+B,CAAC;IAC/D,uBAAuB,EAAE,CAAC;IAC1B,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACjB;AAED,MAAM,GAAG,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n/** The public CLI either supervises a sandbox child or starts an ordinary runtime. */\nimport { fileURLToPath } from \"node:url\";\nimport { APP_NAME, getAgentDir, getPackageDir } from \"./config.ts\";\nimport { setApexEnvironment } from \"./core/environment.ts\";\nimport { configureHttpDispatcher } from \"./core/http-dispatcher.ts\";\nimport {\n\trequiresSandboxedChild,\n\tresolveHostSkillPaths,\n\tresolveSupervisorAllowedHosts,\n} from \"./core/sandbox/cli-launch.ts\";\nimport { launchSandboxedCli } from \"./core/sandbox/cli-supervisor.ts\";\nimport { prepareHostToolBinaries } from \"./utils/tools-manager.ts\";\n\nasync function run(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\t// Validate session IDs before entering the sandbox. Invalid metadata must fail fast\n\t// without starting a child process or touching network/sandbox setup.\n\tconst sessionIdIndex = args.indexOf(\"--session-id\");\n\tconst sessionId = sessionIdIndex >= 0 ? args[sessionIdIndex + 1] : undefined;\n\tif (sessionId !== undefined && !/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(sessionId)) {\n\t\tconsole.error(\n\t\t\t\"Error: Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t\tprocess.exitCode = 1;\n\t\treturn;\n\t}\n\tif (requiresSandboxedChild(args)) {\n\t\tconst allowedHosts = resolveSupervisorAllowedHosts(process.cwd(), getAgentDir());\n\t\tconst authPath = join(getAgentDir(), \"auth.json\");\n\t\t// Resolve fd and rg out here, where the host home and the network are both still\n\t\t// reachable. The child's own PATH still names host directories the sandbox has\n\t\t// replaced, so without this projection it finds nothing and cannot download either.\n\t\t// Silent because this runs ahead of every mode, including --print and --mode rpc,\n\t\t// whose stdout carries machine-readable output; the child still reports a genuinely\n\t\t// missing tool through its own startup path.\n\t\tconst toolBinaries = await prepareHostToolBinaries(true);\n\t\t// Resolved here, where the host home is still reachable -- exactly like the\n\t\t// tool binaries above and unlike anything sourced from project files, which\n\t\t// ADR 0016 forbids as supervisor input before trust is established.\n\t\tconst { paths: skillPaths, refusals: skillPathRefusals } = resolveHostSkillPaths(\n\t\t\tgetAgentDir(),\n\t\t\tprocess.env.HOME || homedir(),\n\t\t);\n\t\tfor (const refusal of skillPathRefusals) {\n\t\t\tprocess.stderr.write(`Warning: not mounting skill directory ${refusal.path}: ${refusal.reason}\\n`);\n\t\t}\n\n\t\tprocess.exitCode = await launchSandboxedCli({\n\t\t\tcommand: process.execPath,\n\t\t\targs: [\n\t\t\t\tfileURLToPath(\n\t\t\t\t\tnew URL(`./core/sandbox/child-entry${import.meta.url.endsWith(\".ts\") ? \".ts\" : \".js\"}`, import.meta.url),\n\t\t\t\t),\n\t\t\t\t...args,\n\t\t\t],\n\t\t\tenvironment: process.env,\n\t\t\tworkspace: process.cwd(),\n\t\t\tallowedHosts,\n\t\t\tauthPath,\n\t\t\treadOnlyPaths: [getPackageDir(), dirname(getPackageDir())],\n\t\t\ttoolBinaries,\n\t\t\tskillPaths,\n\t\t});\n\t\treturn;\n\t}\n\n\tprocess.title = APP_NAME;\n\tsetApexEnvironment(\"APEX_CODE_CODING_AGENT\", \"true\");\n\tprocess.env.AI_AGENT = \"apex-code\";\n\tprocess.emitWarning = (() => {}) as typeof process.emitWarning;\n\tconfigureHttpDispatcher();\n\tconst { main } = await import(\"./main.ts\");\n\tawait main(args);\n}\n\nawait run();\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,uB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CAAC,GAAG,CAAC,CAAC;QAAC,aAAa,CAAC,EAAE,aAAa,CAAA;KAAE,CAAC,CAAC;IAC3E,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,YAAY,CAAC,EAAE,yBAAyB,CAAC,cAAc,CAAC,CAAC;IACzD,OAAO,CAAC,EAAE,yBAAyB,CAAC,SAAS,CAAC,CAAC;IAC/C,WAAW,CAAC,EAAE,cAAc,EAAE,CAAC;IAC/B,cAAc,CAAC,EAAE,IAAI,CAAC,qBAAqB,EAAE,aAAa,CAAC,CAAC;CAC5D;AAED;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,YAAY,CAAC;IAC3B,eAAe,EAAE,eAAe,CAAC;IACjC,cAAc,EAAE,cAAc,CAAC;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB;;;;OAIG;IACH,cAAc,EAAE,cAAc,CAAC;IAC/B,8FAA8F;IAC9F,aAAa,EAAE,OAAO,CAAC;IACvB;;;;;OAKG;IACH,SAAS,EAAE,cAAc,CAAC;IAC1B,WAAW,EAAE,6BAA6B,EAAE,CAAC;IAC7C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAkDD;;;;GAIG;AACH,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,iCAAiC,GACxC,OAAO,CAAC,oBAAoB,CAAC,CAuJ/B;AAED;;;;;;GAMG;AACH,wBAAsB,8BAA8B,CACnD,OAAO,EAAE,qCAAqC,GAC5C,OAAO,CAAC,wBAAwB,CAAC,CAyCnC","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 {\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\";\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}\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\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\tdiagnosticsOperations,\n\t\tlspOperations,\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,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAEN,KAAK,4BAA4B,EACjC,KAAK,cAAc,EACnB,KAAK,2BAA2B,EAChC,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,KAAK,yBAAyB,EAAE,KAAK,wBAAwB,EAAsB,MAAM,UAAU,CAAC;AAC7G,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAQxD;;;;;;GAMG;AACH,MAAM,WAAW,6BAA6B;IAC7C,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC;IACnC,OAAO,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,iCAAiC;IACjD,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CA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AIG;IACH,cAAc,EAAE,cAAc,CAAC;IAC/B,8FAA8F;IAC9F,aAAa,EAAE,OAAO,CAAC;IACvB;;;;;OAKG;IACH,SAAS,EAAE,cAAc,CAAC;IAC1B,WAAW,EAAE,6BAA6B,EAAE,CAAC;IAC7C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAkDD;;;;GAIG;AACH,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,iCAAiC,GACxC,OAAO,CAAC,oBAAoB,CAAC,CA8J/B;AAED;;;;;;GAMG;AACH,wBAAsB,8BAA8B,CACnD,OAAO,EAAE,qCAAqC,GAC5C,OAAO,CAAC,wBAAwB,CAAC,CAqDnC","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 {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { createSandboxCredentialStore } from \"./sandbox/rpc/credential-client.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}\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\t// Inside a sandboxed session the supervisor advertises a credential write channel\n\t// (spec: 2026-08-22-supervisor-mediated-credential-writes). Reads are unchanged --\n\t// still the read-only projection of the host credential file -- while writes and\n\t// deletes travel the supervisor-owned socket instead of failing on the read-only\n\t// mount. Outside a sandbox this resolves to undefined and the default store applies.\n\tconst sandboxCredentialStore = createSandboxCredentialStore();\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\tcredentials: sandboxCredentialStore,\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\tdiagnosticsOperations,\n\t\tlspOperations,\n\t\twebSearchOperations,\n\t});\n}\n"]}
@@ -7,9 +7,11 @@ import { resolveLspRegistry } from "./lsp/registry.js";
7
7
  import { LspStatusStore } from "./lsp/status.js";
8
8
  import { ModelRuntime } from "./model-runtime.js";
9
9
  import { DefaultResourceLoader, } from "./resource-loader.js";
10
+ import { createSandboxCredentialStore } from "./sandbox/rpc/credential-client.js";
10
11
  import { createAgentSession } from "./sdk.js";
11
12
  import { SettingsManager } from "./settings-manager.js";
12
13
  import { SqliteUsagePerformanceStore } from "./usage-performance-store.js";
14
+ import { createDeferredWebSearchOperations, resolveWebSearchOperations } from "./web-search-provider.js";
13
15
  /** Filename of the shared durable-state database within an agent directory (roadmap Phase 8). */
14
16
  const DURABLE_STATE_DATABASE_FILENAME = "state.sqlite";
15
17
  function applyExtensionFlagValues(resourceLoader, extensionFlagValues) {
@@ -78,9 +80,16 @@ export async function createAgentSessionServices(options) {
78
80
  const otlpExportConfig = otlpEndpoint
79
81
  ? { endpoint: otlpEndpoint, headers: settingsManager.getObservabilitySettings().otlpHeaders }
80
82
  : undefined;
83
+ // Inside a sandboxed session the supervisor advertises a credential write channel
84
+ // (spec: 2026-08-22-supervisor-mediated-credential-writes). Reads are unchanged --
85
+ // still the read-only projection of the host credential file -- while writes and
86
+ // deletes travel the supervisor-owned socket instead of failing on the read-only
87
+ // mount. Outside a sandbox this resolves to undefined and the default store applies.
88
+ const sandboxCredentialStore = createSandboxCredentialStore();
81
89
  const modelRuntime = options.modelRuntime ??
82
90
  (await ModelRuntime.create({
83
91
  authPath: process.env.APEX_CODE_AUTH_PATH ?? (options.agentDir ? join(agentDir, "auth.json") : getAuthPath()),
92
+ credentials: sandboxCredentialStore,
84
93
  modelsPath: join(agentDir, "models.json"),
85
94
  signal: options.modelRuntimeSignal,
86
95
  usagePerformanceStore,
@@ -227,6 +236,16 @@ export async function createAgentSessionFromServices(options) {
227
236
  },
228
237
  }
229
238
  : undefined;
239
+ // Read per call rather than captured here. The tool registry is built once at
240
+ // session construction, so a key saved from the settings panel mid-session would
241
+ // otherwise not take effect until restart.
242
+ // Two different questions. Whether a credential resolves *now* decides whether the
243
+ // tool is active, because activation happens once at construction. Resolution then
244
+ // stays deferred so a key changed mid-session is picked up without a restart.
245
+ const settingsManager = options.services.settingsManager;
246
+ const webSearchOperations = resolveWebSearchOperations(settingsManager.getWebSearchSettings())
247
+ ? createDeferredWebSearchOperations(() => settingsManager.getWebSearchSettings())
248
+ : undefined;
230
249
  return createAgentSession({
231
250
  cwd: options.services.cwd,
232
251
  agentDir: options.services.agentDir,
@@ -245,6 +264,7 @@ export async function createAgentSessionFromServices(options) {
245
264
  permissionGate: options.permissionGate,
246
265
  diagnosticsOperations,
247
266
  lspOperations,
267
+ webSearchOperations,
248
268
  });
249
269
  }
250
270
  //# sourceMappingURL=agent-session-services.js.map
@@ -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;AAElD,OAAO,EACN,qBAAqB,GAIr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,EAAE,MAAM,CAAC,CAAC;YAAA,CACzD;SACD;QACF,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,qBAAqB;QACrB,aAAa;KACb,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 {\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\";\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}\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\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\tdiagnosticsOperations,\n\t\tlspOperations,\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;AAG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Q,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,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 {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { createSandboxCredentialStore } from \"./sandbox/rpc/credential-client.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}\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\t// Inside a sandboxed session the supervisor advertises a credential write channel\n\t// (spec: 2026-08-22-supervisor-mediated-credential-writes). Reads are unchanged --\n\t// still the read-only projection of the host credential file -- while writes and\n\t// deletes travel the supervisor-owned socket instead of failing on the read-only\n\t// mount. Outside a sandbox this resolves to undefined and the default store applies.\n\tconst sandboxCredentialStore = createSandboxCredentialStore();\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\tcredentials: sandboxCredentialStore,\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\tdiagnosticsOperations,\n\t\tlspOperations,\n\t\twebSearchOperations,\n\t});\n}\n"]}
@@ -30,6 +30,7 @@ import { type BashOperations } from "./tools/bash.ts";
30
30
  import type { EvidenceSink } from "./tools/contract.ts";
31
31
  import type { DiagnosticsOperations } from "./tools/diagnostics.ts";
32
32
  import type { LspOperations } from "./tools/lsp.ts";
33
+ import type { WebSearchOperations } from "./tools/web-search.ts";
33
34
  /** Parsed skill block from a user message */
34
35
  export interface ParsedSkillBlock {
35
36
  name: string;
@@ -171,6 +172,12 @@ export interface AgentSessionConfig {
171
172
  * `baseToolsOverride` is set.
172
173
  */
173
174
  lspOperations?: LspOperations;
175
+ /**
176
+ * Optional `web_search` backend. Absent leaves the tool on its unconfigured
177
+ * operations, which throw a model-readable "not configured" error rather than
178
+ * returning zero results. Ignored when `baseToolsOverride` is set.
179
+ */
180
+ webSearchOperations?: WebSearchOperations;
174
181
  }
175
182
  export interface ExtensionBindings {
176
183
  uiContext?: ExtensionUIContext;
@@ -182,7 +189,7 @@ export interface ExtensionBindings {
182
189
  }
183
190
  /** Options for AgentSession.prompt() */
184
191
  export interface PromptOptions {
185
- /** Whether to expand file-based prompt templates (default: true) */
192
+ /** Whether to dispatch extension commands and expand skill commands and prompt templates (default: true) */
186
193
  expandPromptTemplates?: boolean;
187
194
  /** Image attachments */
188
195
  images?: ImageContent[];
@@ -259,6 +266,7 @@ export declare class AgentSession {
259
266
  private _evidenceSink?;
260
267
  private _diagnosticsOperations?;
261
268
  private _lspOperations?;
269
+ private _webSearchOperations?;
262
270
  private _extensionUIContext?;
263
271
  private _extensionMode;
264
272
  private _extensionCommandContextActions?;
@@ -470,9 +478,11 @@ export declare class AgentSession {
470
478
  *
471
479
  * @param content User message content (string or content array)
472
480
  * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
481
+ * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.
473
482
  */
474
483
  sendUserMessage(content: string | (TextContent | ImageContent)[], options?: {
475
484
  deliverAs?: "steer" | "followUp";
485
+ expandPromptTemplates?: boolean;
476
486
  }): Promise<void>;
477
487
  /**
478
488
  * Clear all queued messages and return them.
@@ -695,9 +705,12 @@ export declare class AgentSession {
695
705
  /**
696
706
  * Export session to HTML.
697
707
  * @param outputPath Optional output path (defaults to session directory)
708
+ * @param options Optional export presentation settings
698
709
  * @returns Path to exported file
699
710
  */
700
- exportToHtml(outputPath?: string): Promise<string>;
711
+ exportToHtml(outputPath?: string, options?: {
712
+ themeName?: string;
713
+ }): Promise<string>;
701
714
  /**
702
715
  * Export the current session branch to a JSONL file.
703
716
  * Writes the session header followed by all entries on the current branch path.