@earendil-works/pi-coding-agent 0.99.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/dist/bundle/chunks/anthropic-messages-UID2PALB.js +6 -0
  3. package/dist/bundle/chunks/anthropic.js +2 -2
  4. package/dist/bundle/chunks/{azure-openai-responses-EN5WOBET.js → azure-openai-responses-AFMVM6NP.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  6. package/dist/bundle/chunks/{chunk-AXPY26X7.js → chunk-2KTBZM5G.js} +14 -28
  7. package/dist/bundle/chunks/{chunk-LRS5S6EK.js → chunk-2VNGUWBO.js} +2 -2
  8. package/dist/bundle/chunks/chunk-33XOIQ5N.js +1204 -0
  9. package/dist/bundle/chunks/{chunk-W2DOMZSC.js → chunk-3LH3ZQKY.js} +1 -1
  10. package/dist/bundle/chunks/chunk-4KU537KD.js +2 -0
  11. package/dist/bundle/chunks/chunk-6D7LHLKG.js +2 -0
  12. package/dist/bundle/chunks/chunk-7FH3BDRG.js +82 -0
  13. package/dist/bundle/chunks/{chunk-LLMKQWZS.js → chunk-IBCPYVFK.js} +7 -9
  14. package/dist/bundle/chunks/chunk-KDN6RCEQ.js +4 -0
  15. package/dist/bundle/chunks/chunk-LD2P6SFZ.js +2 -0
  16. package/dist/bundle/chunks/{chunk-PEHWOV5U.js → chunk-LTXEMVMA.js} +18 -78
  17. package/dist/bundle/chunks/{chunk-J4CWPC4N.js → chunk-OSKPX3Z5.js} +1 -1
  18. package/dist/bundle/chunks/chunk-PRD6WYBT.js +16 -0
  19. package/dist/bundle/chunks/chunk-VIV3CWXG.js +2 -0
  20. package/dist/bundle/chunks/{cli-AZXNGIZH.js → cli-QOMC26IJ.js} +8 -6
  21. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-XJQQYGGU.js → cloudflare-workers-ai-system-one-NPQN263E.js} +1 -1
  22. package/dist/bundle/chunks/codemode-worker.js +67 -8
  23. package/dist/bundle/chunks/execute-GVRSEGHL.js +367 -0
  24. package/dist/bundle/chunks/github-copilot.js +1 -1
  25. package/dist/bundle/chunks/{google-generative-ai-CQAKKJTA.js → google-generative-ai-APTPZOQL.js} +1 -1
  26. package/dist/bundle/chunks/{google-vertex-AE36YXJU.js → google-vertex-MXCOSOY3.js} +1 -1
  27. package/dist/bundle/chunks/{llama-cpp-classify-PJJYKPLD.js → llama-cpp-classify-XT44PI3C.js} +1 -1
  28. package/dist/bundle/chunks/{mistral-conversations-KEYTXJM7.js → mistral-conversations-DKVFNQL6.js} +1 -1
  29. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  30. package/dist/bundle/chunks/{openai-codex-responses-JQTCOVEG.js → openai-codex-responses-GK67DQQJ.js} +1 -1
  31. package/dist/bundle/chunks/openai-codex.js +1 -1
  32. package/dist/bundle/chunks/{openai-completions-XW2Q5HVC.js → openai-completions-JXDDPZ23.js} +1 -1
  33. package/dist/bundle/chunks/{openai-responses-6AXWFL75.js → openai-responses-CQDDLDQF.js} +1 -1
  34. package/dist/bundle/chunks/{openrouter-images-TPQ4V6OR.js → openrouter-images-ZVXWCSIM.js} +1 -1
  35. package/dist/bundle/chunks/openrouter.js +1 -1
  36. package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +2 -0
  37. package/dist/bundle/chunks/radius.js +1 -1
  38. package/dist/bundle/chunks/runtime-2SO2JDWM.js +2 -0
  39. package/dist/bundle/chunks/{typesafe-system-one-E7A4HNJI.js → typesafe-system-one-A4CZTQWZ.js} +1 -1
  40. package/dist/bundle/chunks/virtual-modules-6ZMK7GDO.js +2 -0
  41. package/dist/bundle/cli-runtime.js +1 -1
  42. package/dist/bundle/index.js +1 -1
  43. package/dist/bundle/rpc-entry.js +1 -1
  44. package/dist/cli/args.js +2 -2
  45. package/dist/cli/args.js.map +1 -1
  46. package/dist/config.d.ts +5 -8
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +16 -13
  49. package/dist/config.js.map +1 -1
  50. package/dist/core/agent-session.d.ts +15 -1
  51. package/dist/core/agent-session.d.ts.map +1 -1
  52. package/dist/core/agent-session.js +51 -10
  53. package/dist/core/agent-session.js.map +1 -1
  54. package/dist/core/extensions/loader.d.ts.map +1 -1
  55. package/dist/core/extensions/loader.js +13 -1
  56. package/dist/core/extensions/loader.js.map +1 -1
  57. package/dist/core/extensions/types.d.ts +6 -1
  58. package/dist/core/extensions/types.d.ts.map +1 -1
  59. package/dist/core/extensions/types.js.map +1 -1
  60. package/dist/core/mcp-servers.d.ts +34 -7
  61. package/dist/core/mcp-servers.d.ts.map +1 -1
  62. package/dist/core/mcp-servers.js +52 -11
  63. package/dist/core/mcp-servers.js.map +1 -1
  64. package/dist/core/model-registry.d.ts +3 -1
  65. package/dist/core/model-registry.d.ts.map +1 -1
  66. package/dist/core/model-registry.js +4 -0
  67. package/dist/core/model-registry.js.map +1 -1
  68. package/dist/core/model-runtime.d.ts +6 -0
  69. package/dist/core/model-runtime.d.ts.map +1 -1
  70. package/dist/core/model-runtime.js +22 -18
  71. package/dist/core/model-runtime.js.map +1 -1
  72. package/dist/core/radius.d.ts +2 -0
  73. package/dist/core/radius.d.ts.map +1 -1
  74. package/dist/core/radius.js +2 -0
  75. package/dist/core/radius.js.map +1 -1
  76. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  77. package/dist/core/remote-catalog-provider.js +4 -9
  78. package/dist/core/remote-catalog-provider.js.map +1 -1
  79. package/dist/core/sdk.d.ts.map +1 -1
  80. package/dist/core/sdk.js +1 -0
  81. package/dist/core/sdk.js.map +1 -1
  82. package/dist/core/settings-manager.d.ts +7 -5
  83. package/dist/core/settings-manager.d.ts.map +1 -1
  84. package/dist/core/settings-manager.js +3 -2
  85. package/dist/core/settings-manager.js.map +1 -1
  86. package/dist/core/system-prompt.js +1 -1
  87. package/dist/core/system-prompt.js.map +1 -1
  88. package/dist/core/tools/bash.d.ts.map +1 -1
  89. package/dist/core/tools/bash.js +3 -5
  90. package/dist/core/tools/bash.js.map +1 -1
  91. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  92. package/dist/core/tools/renderers/bash.js +11 -31
  93. package/dist/core/tools/renderers/bash.js.map +1 -1
  94. package/dist/core/virtual-models.d.ts +2 -0
  95. package/dist/core/virtual-models.d.ts.map +1 -1
  96. package/dist/core/virtual-models.js +19 -12
  97. package/dist/core/virtual-models.js.map +1 -1
  98. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  99. package/dist/extensions/codemode/execute.js +197 -51
  100. package/dist/extensions/codemode/execute.js.map +1 -1
  101. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  102. package/dist/extensions/codemode/renderer.js +43 -25
  103. package/dist/extensions/codemode/renderer.js.map +1 -1
  104. package/dist/extensions/codemode/tool.d.ts +12 -11
  105. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  106. package/dist/extensions/codemode/tool.js +73 -129
  107. package/dist/extensions/codemode/tool.js.map +1 -1
  108. package/dist/extensions/codemode/worker.d.ts +1 -1
  109. package/dist/extensions/codemode/worker.js +1 -1
  110. package/dist/extensions/codemode/worker.js.map +1 -1
  111. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  112. package/dist/extensions/mcp/cli.js +20 -5
  113. package/dist/extensions/mcp/cli.js.map +1 -1
  114. package/dist/extensions/mcp/config.d.ts +4 -2
  115. package/dist/extensions/mcp/config.d.ts.map +1 -1
  116. package/dist/extensions/mcp/config.js +14 -2
  117. package/dist/extensions/mcp/config.js.map +1 -1
  118. package/dist/extensions/mcp/index.d.ts +32 -8
  119. package/dist/extensions/mcp/index.d.ts.map +1 -1
  120. package/dist/extensions/mcp/index.js +220 -56
  121. package/dist/extensions/mcp/index.js.map +1 -1
  122. package/dist/extensions/mcp/oauth.d.ts +10 -7
  123. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  124. package/dist/extensions/mcp/oauth.js +56 -31
  125. package/dist/extensions/mcp/oauth.js.map +1 -1
  126. package/dist/extensions/mcp/runtime.d.ts +2 -0
  127. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  128. package/dist/extensions/mcp/runtime.js +16 -9
  129. package/dist/extensions/mcp/runtime.js.map +1 -1
  130. package/dist/extensions/mcp/tools.d.ts +5 -4
  131. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  132. package/dist/extensions/mcp/tools.js +33 -15
  133. package/dist/extensions/mcp/tools.js.map +1 -1
  134. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  135. package/dist/extensions/mcp/ui.js +4 -2
  136. package/dist/extensions/mcp/ui.js.map +1 -1
  137. package/dist/extensions/tool-search/tool.d.ts +5 -4
  138. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  139. package/dist/extensions/tool-search/tool.js +7 -28
  140. package/dist/extensions/tool-search/tool.js.map +1 -1
  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.map +1 -1
  145. package/dist/main.js +6 -0
  146. package/dist/main.js.map +1 -1
  147. package/dist/modes/interactive/components/oauth-selector.d.ts +8 -2
  148. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/oauth-selector.js +24 -21
  150. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  151. package/dist/modes/interactive/components/pi-logo-animation.d.ts +68 -0
  152. package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +1 -0
  153. package/dist/modes/interactive/components/pi-logo-animation.js +1086 -0
  154. package/dist/modes/interactive/components/pi-logo-animation.js.map +1 -0
  155. package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +7 -0
  156. package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +1 -0
  157. package/dist/modes/interactive/components/pi-logo-animation.lazy.js +12 -0
  158. package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +1 -0
  159. package/dist/modes/interactive/components/pi-logo.d.ts +7 -0
  160. package/dist/modes/interactive/components/pi-logo.d.ts.map +1 -1
  161. package/dist/modes/interactive/components/pi-logo.js +13 -1
  162. package/dist/modes/interactive/components/pi-logo.js.map +1 -1
  163. package/dist/modes/interactive/components/radius-login-selector.d.ts +15 -0
  164. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -0
  165. package/dist/modes/interactive/components/radius-login-selector.js +85 -0
  166. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -0
  167. package/dist/modes/interactive/components/settings-selector.d.ts +3 -3
  168. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/settings-selector.js +5 -5
  170. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  171. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  172. package/dist/modes/interactive/components/user-message.js +5 -4
  173. package/dist/modes/interactive/components/user-message.js.map +1 -1
  174. package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
  175. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  176. package/dist/modes/interactive/components/visual-truncate.js +39 -6
  177. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  178. package/dist/modes/interactive/interactive-mode.d.ts +10 -0
  179. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  180. package/dist/modes/interactive/interactive-mode.js +153 -40
  181. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  182. package/dist/modes/interactive/theme/system-theme.d.ts +2 -1
  183. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
  184. package/dist/modes/interactive/theme/system-theme.js +16 -5
  185. package/dist/modes/interactive/theme/system-theme.js.map +1 -1
  186. package/docs/cli.md +8 -18
  187. package/docs/codemode.md +207 -0
  188. package/docs/docs.json +5 -1
  189. package/docs/environment-variables.md +2 -2
  190. package/docs/extensions.md +3 -3
  191. package/docs/index.md +1 -1
  192. package/docs/mcp.md +142 -82
  193. package/docs/models.md +22 -1
  194. package/docs/providers.md +18 -6
  195. package/docs/sdk.md +2 -2
  196. package/docs/settings.md +5 -3
  197. package/docs/usage.md +1 -1
  198. package/examples/extensions/built-in-tool-renderer.ts +16 -40
  199. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  200. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  201. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  202. package/examples/extensions/gondolin/package-lock.json +2 -2
  203. package/examples/extensions/gondolin/package.json +1 -1
  204. package/examples/extensions/minimal-mode.ts +24 -96
  205. package/examples/extensions/sandbox/package-lock.json +2 -2
  206. package/examples/extensions/sandbox/package.json +1 -1
  207. package/examples/extensions/with-deps/package-lock.json +2 -2
  208. package/examples/extensions/with-deps/package.json +1 -1
  209. package/examples/sdk/14-codemode-mcp.ts +2 -2
  210. package/npm-shrinkwrap.json +25 -30
  211. package/package.json +10 -10
  212. package/dist/bundle/chunks/anthropic-messages-A6EXUBG6.js +0 -6
  213. package/dist/bundle/chunks/chunk-GOPCREV2.js +0 -4
  214. package/dist/bundle/chunks/chunk-GUORCHFS.js +0 -1435
  215. package/dist/bundle/chunks/chunk-HSPCVFST.js +0 -2
  216. package/dist/bundle/chunks/chunk-IMTXZUO7.js +0 -82
  217. package/dist/bundle/chunks/chunk-SLDA2X2H.js +0 -2
  218. package/dist/bundle/chunks/chunk-XNGRGP62.js +0 -2
  219. package/dist/bundle/chunks/execute-7XXPZAWW.js +0 -308
  220. package/dist/bundle/chunks/runtime-G5WJPRBM.js +0 -2
  221. package/dist/bundle/chunks/virtual-modules-CSWRO37N.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AAEn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EAAE,gCAAgC,CAAC,UAAU;IAC7D,cAAc,EAAE,SAAS;CACzB,CAAC;AAEF,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB;IAEzB,OAAO,yBAAyB,CAAC,GAAG,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,MAAM,UAAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS, createShellRenderers } from \"./renderers/bash.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n/** Output limit of `structuredContent.output`, which programmatic callers such as codemode scripts receive. */\nconst STRUCTURED_OUTPUT_MAX_BYTES = 1024 * 1024;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.\n * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.\n */\nconst bashOutputSchema = Type.Object({\n\toutput: Type.String({\n\t\tdescription:\n\t\t\t\"Combined stdout and stderr, up to 1 MiB. Longer output keeps its first and last 512 KiB around an omission marker.\",\n\t}),\n\ttruncated: Type.Boolean({ description: \"Whether `output` omits part of the command output\" }),\n\tfull_output_path: Type.Optional(Type.String({ description: \"Temp file with the full output, when truncated\" })),\n\texit_code: Type.Number(),\n\twall_time_seconds: Type.Number(),\n});\n\nexport type BashToolOutput = Static<typeof bashOutputSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\treturn { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst startedAt = performance.now();\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode === null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, \"Command terminated without an exit code\"));\n\t\t\t\t}\n\t\t\t\tconst wallTimeSeconds = Math.round((performance.now() - startedAt) / 100) / 10;\n\t\t\t\tconst fullOutput = await output.readFullOutput(STRUCTURED_OUTPUT_MAX_BYTES);\n\t\t\t\tconst structuredContent: BashToolOutput = {\n\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t...(fullOutput.truncated && snapshot.fullOutputPath\n\t\t\t\t\t\t? { full_output_path: snapshot.fullOutputPath }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\twall_time_seconds: wallTimeSeconds,\n\t\t\t\t};\n\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: appendStatus(outputText, `Command exited with code ${exitCode}`) }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t\tstructuredContent,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details, structuredContent };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\t...createShellRenderers(config.prompt),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EAEf,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACpF,OA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ACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS, createShellRenderers } from \"./renderers/bash.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n/** Output limit of `structuredContent.output`, which programmatic callers such as codemode scripts receive. */\nconst STRUCTURED_OUTPUT_MAX_BYTES = 1024 * 1024;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.\n * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.\n */\nconst bashOutputSchema = Type.Object({\n\toutput: Type.String({ description: \"Combined stdout and stderr, possibly truncated\" }),\n\ttruncated: Type.Boolean(),\n\tfull_output_path: Type.Optional(Type.String({ description: \"Full output, when truncated\" })),\n\texit_code: Type.Number(),\n\twall_time_seconds: Type.Number(),\n});\n\nexport type BashToolOutput = Static<typeof bashOutputSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\treturn { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst startedAt = performance.now();\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode === null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, \"Command terminated without an exit code\"));\n\t\t\t\t}\n\t\t\t\tconst wallTimeSeconds = Math.round((performance.now() - startedAt) / 100) / 10;\n\t\t\t\tconst fullOutput = await output.readFullOutput(STRUCTURED_OUTPUT_MAX_BYTES);\n\t\t\t\tconst structuredContent: BashToolOutput = {\n\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t...(fullOutput.truncated && snapshot.fullOutputPath\n\t\t\t\t\t\t? { full_output_path: snapshot.fullOutputPath }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\twall_time_seconds: wallTimeSeconds,\n\t\t\t\t};\n\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: appendStatus(outputText, `Command exited with code ${exitCode}`) }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t\tstructuredContent,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details, structuredContent };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\t...createShellRenderers(config.prompt),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/renderers/bash.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,2BAA2B,CAAC;AAMzF,eAAO,MAAM,uBAAuB,MAAM,CAAC;AA+G3C,uGAAuG;AACvG,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,YAAY,GAAG,cAAc,CAAC,CAsClH"}
1
+ {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/renderers/bash.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,2BAA2B,CAAC;AAMzF,eAAO,MAAM,uBAAuB,MAAM,CAAC;AAyF3C,uGAAuG;AACvG,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,YAAY,GAAG,cAAc,CAAC,CAqClH"}
@@ -5,20 +5,14 @@
5
5
  * load the execution path or its typebox parameter schema. `bash.ts` spreads these into the shell
6
6
  * tool definition, so the tool's public shape is unchanged.
7
7
  */
8
- import { Container, Text, truncateToWidth } from "@earendil-works/pi-tui";
8
+ import { Container, Spacer, Text } from "@earendil-works/pi-tui";
9
9
  import { keyHint } from "../../../modes/interactive/components/keybinding-hints.js";
10
- import { truncateToVisualLines } from "../../../modes/interactive/components/visual-truncate.js";
10
+ import { VisualLinePreview } from "../../../modes/interactive/components/visual-truncate.js";
11
11
  import { theme } from "../../../modes/interactive/theme/theme.js";
12
12
  import { getTextOutput, invalidArgText, str } from "../render-utils.js";
13
13
  import { DEFAULT_MAX_BYTES, formatSize } from "../truncate.js";
14
14
  const BASH_PREVIEW_LINES = 5;
15
15
  export const BASH_UPDATE_THROTTLE_MS = 100;
16
- class BashResultRenderComponent extends Container {
17
- state = {
18
- cachedWidth: undefined,
19
- cachedLines: undefined,
20
- };
21
- }
22
16
  function formatDuration(ms) {
23
17
  const seconds = ms / 1000;
24
18
  if (seconds < 60)
@@ -38,7 +32,6 @@ function formatShellCall(args, prompt) {
38
32
  return theme.fg("toolTitle", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;
39
33
  }
40
34
  function rebuildBashResultRenderComponent(component, result, options, showImages, startedAt, endedAt) {
41
- const state = component.state;
42
35
  component.clear();
43
36
  let output = getTextOutput(result, showImages).trim();
44
37
  const truncation = result.details?.truncation;
@@ -58,27 +51,14 @@ function rebuildBashResultRenderComponent(component, result, options, showImages
58
51
  component.addChild(new Text(`\n${styledOutput}`, 0, 0));
59
52
  }
60
53
  else {
61
- component.addChild({
62
- render: (width) => {
63
- // Cache the complete output: this renders on every frame for every bash result in the transcript.
64
- if (state.cachedLines === undefined || state.cachedWidth !== width) {
65
- const preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);
66
- const hintLines = [];
67
- if (preview.skippedCount > 0) {
68
- const hint = theme.fg("muted", `... (${preview.skippedCount} earlier lines,`) +
69
- ` ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
70
- hintLines.push(truncateToWidth(hint, width, "..."));
71
- }
72
- state.cachedLines = ["", ...hintLines, ...preview.visualLines];
73
- state.cachedWidth = width;
74
- }
75
- return state.cachedLines;
76
- },
77
- invalidate: () => {
78
- state.cachedWidth = undefined;
79
- state.cachedLines = undefined;
80
- },
81
- });
54
+ component.addChild(new Spacer(1));
55
+ component.addChild(new VisualLinePreview({
56
+ text: styledOutput,
57
+ maxVisualLines: BASH_PREVIEW_LINES,
58
+ keep: "end",
59
+ formatHint: (hidden) => theme.fg("muted", `... (${hidden} earlier lines,`) +
60
+ ` ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`,
61
+ }));
82
62
  }
83
63
  }
84
64
  if (truncation?.truncated || fullOutputPath) {
@@ -127,7 +107,7 @@ export function createShellRenderers(prompt) {
127
107
  state.interval = undefined;
128
108
  }
129
109
  }
130
- const component = context.lastComponent ?? new BashResultRenderComponent();
110
+ const component = context.lastComponent ?? new Container();
131
111
  rebuildBashResultRenderComponent(component, result, options, context.showImages, state.startedAt, state.endedAt);
132
112
  component.invalidate();
133
113
  return component;
@@ -1 +1 @@
1
- {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../../src/core/tools/renderers/bash.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,2DAA2D,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,0DAA0D,CAAC;AACjG,OAAO,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAGlE,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE/D,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAK3C,MAAM,yBAA0B,SAAQ,SAAS;IAChD,KAAK,GAA0B;QAC9B,WAAW,EAAE,SAAS;QACtB,WAAW,EAAE,SAAS;KACtB,CAAC;CACF;AACD,SAAS,cAAc,CAAC,EAAU;IACjC,MAAM,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC;IAC1B,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IAElD,MAAM,YAAY,GAAG,IAAI,C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AAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,IAA0D,EAAE,MAAM,CAAC,CAAC,CAAC;YAClG,OAAO,IAAI,CAAC;QACb,CAAC;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO;YAC5C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;YAC5B,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,CAAC,SAAS,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;gBAC3E,KAAK,CAAC,QAAQ,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,IAAI,CAAC,CAAC;YAChE,CAAC;YACD,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;gBAC3C,KAAK,CAAC,OAAO,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC;gBAC7B,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;oBACpB,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;oBAC9B,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;gBAC5B,CAAC;YACF,CAAC;YACD,MAAM,SAAS,GACb,OAAO,CAAC,aAAuD,IAAI,IAAI,yBAAyB,EAAE,CAAC;YACrG,gCAAgC,CAC/B,SAAS,EACT,MAAa,EACb,OAAO,EACP,OAAO,CAAC,UAAU,EAClB,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,OAAO,CACb,CAAC;YACF,SAAS,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Presentation for the shell tools.\n *\n * Renderers live apart from the implementation so a process that only displays tool output does not\n * load the execution path or its typebox parameter schema. `bash.ts` spreads these into the shell\n * tool definition, so the tool's public shape is unchanged.\n */\n\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { keyHint } from \"../../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../../extensions/types.ts\";\nimport type { BashToolDetails } from \"../bash.ts\";\nimport { getTextOutput, invalidArgText, str } from \"../render-utils.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize } from \"../truncate.ts\";\n\nconst BASH_PREVIEW_LINES = 5;\nexport const BASH_UPDATE_THROTTLE_MS = 100;\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n};\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t};\n}\nfunction formatDuration(ms: number): string {\n\tconst seconds = ms / 1000;\n\tif (seconds < 60) return `${seconds.toFixed(1)}s`;\n\n\tconst totalSeconds = Math.floor(seconds);\n\tconst minutes = Math.floor(totalSeconds / 60);\n\tconst remainder = totalSeconds % 60;\n\tif (minutes < 60) return `${minutes}m ${remainder}s`;\n\n\treturn `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;\n}\nfunction formatShellCall(args: { command?: string; timeout?: number } | undefined, prompt: string): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;\n}\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\t// Cache the complete output: this renders on every frame for every bash result in the transcript.\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tconst hintLines: string[] = [];\n\t\t\t\t\t\tif (preview.skippedCount > 0) {\n\t\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${preview.skippedCount} earlier lines,`) +\n\t\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\t\thintLines.push(truncateToWidth(hint, width, \"...\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.cachedLines = [\"\", ...hintLines, ...preview.visualLines];\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\treturn state.cachedLines;\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\n/** Shell renderers are shared by bash and powershell, which differ only in the prompt they display. */\nexport function createShellRenderers(prompt: string): Pick<ToolDefinition<any, any>, \"renderCall\" | \"renderResult\"> {\n\treturn {\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args as { command?: string; timeout?: number } | undefined, prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../../src/core/tools/renderers/bash.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,2DAA2D,CAAC;AACpF,OAAO,EAAE,iBAAiB,EAAE,MAAM,0DAA0D,CAAC;AAC7F,OAAO,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAGlE,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE/D,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAC3C,SAAS,cAAc,CAAC,EAAU;IACjC,MAAM,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC;IAC1B,IAAI,OAAO,GAAG,EAAE;QA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,SAAS,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;gBAC3C,KAAK,CAAC,OAAO,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC;gBAC7B,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;oBACpB,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;oBAC9B,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;gBAC5B,CAAC;YACF,CAAC;YACD,MAAM,SAAS,GAAI,OAAO,CAAC,aAAuC,IAAI,IAAI,SAAS,EAAE,CAAC;YACtF,gCAAgC,CAC/B,SAAS,EACT,MAAa,EACb,OAAO,EACP,OAAO,CAAC,UAAU,EAClB,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,OAAO,CACb,CAAC;YACF,SAAS,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Presentation for the shell tools.\n *\n * Renderers live apart from the implementation so a process that only displays tool output does not\n * load the execution path or its typebox parameter schema. `bash.ts` spreads these into the shell\n * tool definition, so the tool's public shape is unchanged.\n */\n\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { keyHint } from \"../../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../../extensions/types.ts\";\nimport type { BashToolDetails } from \"../bash.ts\";\nimport { getTextOutput, invalidArgText, str } from \"../render-utils.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize } from \"../truncate.ts\";\n\nconst BASH_PREVIEW_LINES = 5;\nexport const BASH_UPDATE_THROTTLE_MS = 100;\nfunction formatDuration(ms: number): string {\n\tconst seconds = ms / 1000;\n\tif (seconds < 60) return `${seconds.toFixed(1)}s`;\n\n\tconst totalSeconds = Math.floor(seconds);\n\tconst minutes = Math.floor(totalSeconds / 60);\n\tconst remainder = totalSeconds % 60;\n\tif (minutes < 60) return `${minutes}m ${remainder}s`;\n\n\treturn `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;\n}\nfunction formatShellCall(args: { command?: string; timeout?: number } | undefined, prompt: string): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;\n}\nfunction rebuildBashResultRenderComponent(\n\tcomponent: Container,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(\n\t\t\t\tnew VisualLinePreview({\n\t\t\t\t\ttext: styledOutput,\n\t\t\t\t\tmaxVisualLines: BASH_PREVIEW_LINES,\n\t\t\t\t\tkeep: \"end\",\n\t\t\t\t\tformatHint: (hidden) =>\n\t\t\t\t\t\ttheme.fg(\"muted\", `... (${hidden} earlier lines,`) +\n\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\n/** Shell renderers are shared by bash and powershell, which differ only in the prompt they display. */\nexport function createShellRenderers(prompt: string): Pick<ToolDefinition<any, any>, \"renderCall\" | \"renderResult\"> {\n\treturn {\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args as { command?: string; timeout?: number } | undefined, prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}
@@ -97,6 +97,8 @@ export declare function findLatestResponse(messages: readonly AgentMessage[]): A
97
97
  * `model_change`, because responses name the physical models it routed to. Otherwise the latest
98
98
  * physical response wins, as in sessions without virtual models. A virtual model that is no longer
99
99
  * registered does not hold, so the selection falls back to the physical model that answered last.
100
+ *
101
+ * Only the last `model_change` can hold, so this looks up at most one model in the catalog.
100
102
  */
101
103
  export declare function getBranchSelection(branch: readonly SessionEntry[], getModel: (provider: string, modelId: string) => Model<Api> | undefined): {
102
104
  provider: string;
@@ -1 +1 @@
1
- {"version":3,"file":"virtual-models.d.ts","sourceRoot":"","sources":["../../src/core/virtual-models.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAEN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAIrB,KAAK,OAAO,EACZ,KAAK,KAAK,EACV,KAAK,kBAAkB,EACvB,KAAK,QAA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U,CAAC,MAAM,CAAC,CAAC,CAAC;CAC5F;AAED,gHAAgH;AAChH,wBAAgB,cAAc,CAAC,KAAK,EAAE;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAE9D;AAED,4HAA4H;AAC5H,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,gBAAgB,GAAG,SAAS,CAQlG;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,SAAS,YAAY,EAAE,EAC/B,QAAQ,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,GACrE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAcnD;AAaD,uEAAuE;AACvE,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAQhH;AAED,kDAAkD;AAClD,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,IAAI,CAAC,sBAAsB,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAiBhG;AASD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAChC,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,QAAQ,GAAG,SAAS,EAC9B,aAAa,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,GAClC,QAAQ,CAiCV"}
@@ -23,24 +23,31 @@ export function findLatestResponse(messages) {
23
23
  * `model_change`, because responses name the physical models it routed to. Otherwise the latest
24
24
  * physical response wins, as in sessions without virtual models. A virtual model that is no longer
25
25
  * registered does not hold, so the selection falls back to the physical model that answered last.
26
+ *
27
+ * Only the last `model_change` can hold, so this looks up at most one model in the catalog.
26
28
  */
27
29
  export function getBranchSelection(branch, getModel) {
28
- const isVirtual = (provider, modelId) => {
29
- const model = getModel(provider, modelId);
30
- return model !== undefined && isVirtualModel(model);
31
- };
32
- let selection;
33
- for (const entry of branch) {
30
+ for (let i = branch.length - 1; i >= 0; i--) {
31
+ const entry = branch[i];
34
32
  if (entry.type === "model_change") {
35
- selection = { provider: entry.provider, modelId: entry.modelId };
33
+ return { provider: entry.provider, modelId: entry.modelId };
36
34
  }
37
- else if (entry.type === "message" && entry.message.role === "assistant" && !isVirtualModel(entry.message)) {
38
- if (!selection || !isVirtual(selection.provider, selection.modelId)) {
39
- selection = { provider: entry.message.provider, modelId: entry.message.model };
40
- }
35
+ if (entry.type === "message" && entry.message.role === "assistant" && !isVirtualModel(entry.message)) {
36
+ const response = { provider: entry.message.provider, modelId: entry.message.model };
37
+ const change = findLastModelChange(branch, i);
38
+ const model = change && getModel(change.provider, change.modelId);
39
+ return change && model && isVirtualModel(model) ? change : response;
41
40
  }
42
41
  }
43
- return selection;
42
+ return undefined;
43
+ }
44
+ function findLastModelChange(branch, before) {
45
+ for (let i = before - 1; i >= 0; i--) {
46
+ const entry = branch[i];
47
+ if (entry.type === "model_change")
48
+ return { provider: entry.provider, modelId: entry.modelId };
49
+ }
50
+ return undefined;
44
51
  }
45
52
  /** Latest router state a session branch stores for a virtual model. */
46
53
  export function getVirtualModelState(branch, provider, modelId) {
@@ -1 +1 @@
1
- {"version":3,"file":"virtual-models.js","sourceRoot":"","sources":["../../src/core/virtual-models.ts"],"names":[],"mappings":"AAYA,OAAO,EAKN,WAAW,EACX,UAAU,GAMV,MAAM,uBAAuB,CAAC;AAG/B,mFAAmF;AACnF,MAAM,CAAC,MAAM,iBAAiB,GAAG,YAAY,CAAC;AAE9C,wEAAwE;AACxE,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;AASlE,MAAM,eAAe,GAAkC,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;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YACf,CAAC,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC,GAAG,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;QACjG,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CACnC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;QACzF,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CACzC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KAC/F,CAAC;AACH,CAAC","sourcesContent":["/**\n * Virtual models are catalog entries that route each request to a physical model.\n *\n * The selection (`model_change`, `agent.state.model`, `ctx.model`) may name a virtual model.\n * Everything below the routing step only sees physical models: providers stream them and\n * assistant messages record them. A virtual model never reaches a provider.\n *\n * Virtual models belong to a provider id but are not provider models. `ModelRuntime` keeps them\n * separately and adds them to the provider's catalog with `withVirtualModels()`, so any provider,\n * including one with physical models, can list several virtual models.\n */\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AnyModel,\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\tisModelType,\n\tlazyStream,\n\ttype Message,\n\ttype Model,\n\ttype ModelThinkingLevel,\n\ttype Provider,\n\ttype ThinkingLevelMap,\n} from \"@earendil-works/pi-ai\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\n/** API id of virtual catalog entries. Requests for it fail unless routed first. */\nexport const VIRTUAL_MODEL_API = \"pi-virtual\";\n\n/** Custom entry type that stores router state on the session branch. */\nexport const VIRTUAL_MODEL_STATE_ENTRY = \"pi.virtual-model-state\";\n\n/** Data of a `pi.virtual-model-state` custom entry. */\nexport interface VirtualModelStateData<TState = unknown> {\n\tprovider: string;\n\tmodelId: string;\n\tstate: TState;\n}\n\nconst THINKING_LEVELS: readonly ModelThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\n/**\n * Why a request is being routed.\n * - `user`: first request after a message the user wrote (prompt, steering, or follow-up)\n * - `continuation`: any other request in the agent loop, e.g. after tool results or extension messages\n * - `retry`: automatic retry after a failed request, including after compaction for a context overflow\n * - `direct`: a request outside the agent loop, e.g. a compaction summary or an extension call\n */\nexport type ModelRouteReason = \"user\" | \"continuation\" | \"retry\" | \"direct\";\n\nexport interface ModelRouteRequest<TState = unknown> {\n\t/** The selected virtual model. */\n\tmodel: Model<Api>;\n\t/** The selected thinking level. Its meaning is up to the router. */\n\tthinkingLevel: ModelThinkingLevel;\n\treason: ModelRouteReason;\n\t/** Physical model and thinking level of the latest successful response in `messages`. */\n\tprevious?: { model: Model<Api>; thinkingLevel?: ModelThinkingLevel };\n\t/**\n\t * For `retry`: the failed request, which `messages` no longer contains. `message` carries its\n\t * `stopReason` and `errorMessage`. Absent when the router itself failed.\n\t */\n\tfailed?: { model: Model<Api>; thinkingLevel?: ModelThinkingLevel; message: AssistantMessage };\n\t/** Router state last returned on this session branch. Undefined before the first state and for `direct` requests. */\n\tstate?: TState;\n\t/** Conversation for this request, including system messages. */\n\tmessages: readonly Message[];\n\tsignal?: AbortSignal;\n}\n\n/** Physical model and thinking level for one request. */\nexport interface ModelRoute<TState = unknown> {\n\tmodel: Model<Api>;\n\tthinkingLevel: ModelThinkingLevel;\n\t/**\n\t * New router state, stored on the session branch unless it is `request.state` itself. Return\n\t * `request.state` or undefined to keep the current state. Must be JSON-serializable. Ignored for\n\t * `direct` requests.\n\t */\n\tstate?: TState;\n}\n\nexport interface VirtualModelDefinition<TState = unknown> {\n\t/** Provider the virtual model is listed under. May be a provider with physical models. */\n\tprovider: string;\n\t/** Model id. Must not be the id of a physical model of `provider`. */\n\tid: string;\n\tname: string;\n\t/** Thinking levels offered for selection. Defaults to `[\"off\"]`. */\n\tthinkingLevels?: readonly ModelThinkingLevel[];\n\t/**\n\t * Limits shown before the first response. Afterwards, Pi uses the limits of the physical model\n\t * that answered. Unset limits are unknown (0).\n\t */\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n\t/** Input types accepted for selection. Defaults to text and images; routed models without image support get placeholders. */\n\tinput?: (\"text\" | \"image\")[];\n\t/** Pick the physical model, which must have credentials, and thinking level for one request. */\n\troute(request: ModelRouteRequest<TState>): ModelRoute<TState> | Promise<ModelRoute<TState>>;\n}\n\n/** Whether a model or message names a virtual model. Failed routing leaves the virtual model on its message. */\nexport function isVirtualModel(model: { api: string }): boolean {\n\treturn model.api === VIRTUAL_MODEL_API;\n}\n\n/** Latest successful response. Its model is physical: failed or aborted requests, including failed routing, are skipped. */\nexport function findLatestResponse(messages: readonly AgentMessage[]): AssistantMessage | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"assistant\" && message.stopReason !== \"error\" && message.stopReason !== \"aborted\") {\n\t\t\treturn message;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * The model selection a session branch records. A virtual `model_change` holds until the next\n * `model_change`, because responses name the physical models it routed to. Otherwise the latest\n * physical response wins, as in sessions without virtual models. A virtual model that is no longer\n * registered does not hold, so the selection falls back to the physical model that answered last.\n */\nexport function getBranchSelection(\n\tbranch: readonly SessionEntry[],\n\tgetModel: (provider: string, modelId: string) => Model<Api> | undefined,\n): { provider: string; modelId: string } | undefined {\n\tconst isVirtual = (provider: string, modelId: string) => {\n\t\tconst model = getModel(provider, modelId);\n\t\treturn model !== undefined && isVirtualModel(model);\n\t};\n\tlet selection: { provider: string; modelId: string } | undefined;\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"model_change\") {\n\t\t\tselection = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\" && !isVirtualModel(entry.message)) {\n\t\t\tif (!selection || !isVirtual(selection.provider, selection.modelId)) {\n\t\t\t\tselection = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t\t}\n\t\t}\n\t}\n\treturn selection;\n}\n\n/** Latest router state a session branch stores for a virtual model. */\nexport function getVirtualModelState(branch: readonly SessionEntry[], provider: string, modelId: string): unknown {\n\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type !== \"custom\" || entry.customType !== VIRTUAL_MODEL_STATE_ENTRY) continue;\n\t\tconst data = entry.data as VirtualModelStateData | undefined;\n\t\tif (data?.provider === provider && data.modelId === modelId) return data.state;\n\t}\n\treturn undefined;\n}\n\n/** Build the catalog entry of a virtual model. */\nexport function createVirtualModel(definition: Omit<VirtualModelDefinition, \"route\">): Model<Api> {\n\tconst levels = definition.thinkingLevels ?? [\"off\"];\n\tconst thinkingLevelMap: ThinkingLevelMap = {};\n\tfor (const level of THINKING_LEVELS) thinkingLevelMap[level] = levels.includes(level) ? level : null;\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\tapi: VIRTUAL_MODEL_API,\n\t\tprovider: definition.provider,\n\t\tbaseUrl: \"\",\n\t\treasoning: levels.some((level) => level !== \"off\"),\n\t\tthinkingLevelMap,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 0,\n\t\tmaxTokens: definition.maxTokens ?? 0,\n\t};\n}\n\n/** Stream for a virtual model that was not routed, e.g. `stream()` with API-specific options. */\nfunction unroutedStream(model: Model<Api>): AssistantMessageEventStream {\n\treturn lazyStream(model, async () => {\n\t\tthrow new Error(`Virtual model ${model.provider}/${model.id} must be routed before streaming`);\n\t});\n}\n\n/**\n * Add virtual models to a provider's catalog. Without a provider, the result is a keyless provider\n * that only lists the virtual models. A virtual model hides a physical chat model with the same id,\n * which a catalog refresh can add after registration. Availability follows the provider's auth.\n */\nexport function withVirtualModels(\n\tproviderId: string,\n\tprovider: Provider | undefined,\n\tvirtualModels: readonly Model<Api>[],\n): Provider {\n\tif (!provider) {\n\t\treturn {\n\t\t\tid: providerId,\n\t\t\tname: providerId,\n\t\t\tauth: { apiKey: { name: \"Virtual model\", resolve: async () => ({ auth: {}, source: \"virtual\" }) } },\n\t\t\tgetModels: () => virtualModels,\n\t\t\tstream: unroutedStream,\n\t\t\tstreamSimple: unroutedStream,\n\t\t};\n\t}\n\tconst ids = new Set(virtualModels.map((model) => model.id));\n\tconst physical = <TModel extends AnyModel>(models: readonly TModel[]) =>\n\t\tmodels.filter((model) => !isVirtualModel(model) && !(isModelType(model, \"chat\") && ids.has(model.id)));\n\tconst virtual = <TModel extends AnyModel>(models: readonly TModel[]) =>\n\t\tmodels.filter((model) => isVirtualModel(model));\n\tconst { filterModels, filterAllModels } = provider;\n\treturn {\n\t\t...provider,\n\t\tgetModels: () => [...physical(provider.getModels()), ...virtualModels],\n\t\tgetAllModels: () => [...physical(provider.getAllModels?.() ?? provider.getModels()), ...virtualModels],\n\t\tfilterModels: (models, credential) => {\n\t\t\tconst real = physical(models);\n\t\t\treturn [...(filterModels?.(real, credential) ?? real), ...virtual(models)];\n\t\t},\n\t\tfilterAllModels:\n\t\t\tfilterAllModels &&\n\t\t\t((models, credential) => [...filterAllModels(physical(models), credential), ...virtual(models)]),\n\t\tstream: (model, context, options) =>\n\t\t\tisVirtualModel(model) ? unroutedStream(model) : provider.stream(model, context, options),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tisVirtualModel(model) ? unroutedStream(model) : provider.streamSimple(model, context, options),\n\t};\n}\n"]}
1
+ {"version":3,"file":"virtual-models.js","sourceRoot":"","sources":["../../src/core/virtual-models.ts"],"names":[],"mappings":"AAYA,OAA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C,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KAC/F,CAAC;AACH,CAAC","sourcesContent":["/**\n * Virtual models are catalog entries that route each request to a physical model.\n *\n * The selection (`model_change`, `agent.state.model`, `ctx.model`) may name a virtual model.\n * Everything below the routing step only sees physical models: providers stream them and\n * assistant messages record them. A virtual model never reaches a provider.\n *\n * Virtual models belong to a provider id but are not provider models. `ModelRuntime` keeps them\n * separately and adds them to the provider's catalog with `withVirtualModels()`, so any provider,\n * including one with physical models, can list several virtual models.\n */\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AnyModel,\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\tisModelType,\n\tlazyStream,\n\ttype Message,\n\ttype Model,\n\ttype ModelThinkingLevel,\n\ttype Provider,\n\ttype ThinkingLevelMap,\n} from \"@earendil-works/pi-ai\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\n/** API id of virtual catalog entries. Requests for it fail unless routed first. */\nexport const VIRTUAL_MODEL_API = \"pi-virtual\";\n\n/** Custom entry type that stores router state on the session branch. */\nexport const VIRTUAL_MODEL_STATE_ENTRY = \"pi.virtual-model-state\";\n\n/** Data of a `pi.virtual-model-state` custom entry. */\nexport interface VirtualModelStateData<TState = unknown> {\n\tprovider: string;\n\tmodelId: string;\n\tstate: TState;\n}\n\nconst THINKING_LEVELS: readonly ModelThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\n/**\n * Why a request is being routed.\n * - `user`: first request after a message the user wrote (prompt, steering, or follow-up)\n * - `continuation`: any other request in the agent loop, e.g. after tool results or extension messages\n * - `retry`: automatic retry after a failed request, including after compaction for a context overflow\n * - `direct`: a request outside the agent loop, e.g. a compaction summary or an extension call\n */\nexport type ModelRouteReason = \"user\" | \"continuation\" | \"retry\" | \"direct\";\n\nexport interface ModelRouteRequest<TState = unknown> {\n\t/** The selected virtual model. */\n\tmodel: Model<Api>;\n\t/** The selected thinking level. Its meaning is up to the router. */\n\tthinkingLevel: ModelThinkingLevel;\n\treason: ModelRouteReason;\n\t/** Physical model and thinking level of the latest successful response in `messages`. */\n\tprevious?: { model: Model<Api>; thinkingLevel?: ModelThinkingLevel };\n\t/**\n\t * For `retry`: the failed request, which `messages` no longer contains. `message` carries its\n\t * `stopReason` and `errorMessage`. Absent when the router itself failed.\n\t */\n\tfailed?: { model: Model<Api>; thinkingLevel?: ModelThinkingLevel; message: AssistantMessage };\n\t/** Router state last returned on this session branch. Undefined before the first state and for `direct` requests. */\n\tstate?: TState;\n\t/** Conversation for this request, including system messages. */\n\tmessages: readonly Message[];\n\tsignal?: AbortSignal;\n}\n\n/** Physical model and thinking level for one request. */\nexport interface ModelRoute<TState = unknown> {\n\tmodel: Model<Api>;\n\tthinkingLevel: ModelThinkingLevel;\n\t/**\n\t * New router state, stored on the session branch unless it is `request.state` itself. Return\n\t * `request.state` or undefined to keep the current state. Must be JSON-serializable. Ignored for\n\t * `direct` requests.\n\t */\n\tstate?: TState;\n}\n\nexport interface VirtualModelDefinition<TState = unknown> {\n\t/** Provider the virtual model is listed under. May be a provider with physical models. */\n\tprovider: string;\n\t/** Model id. Must not be the id of a physical model of `provider`. */\n\tid: string;\n\tname: string;\n\t/** Thinking levels offered for selection. Defaults to `[\"off\"]`. */\n\tthinkingLevels?: readonly ModelThinkingLevel[];\n\t/**\n\t * Limits shown before the first response. Afterwards, Pi uses the limits of the physical model\n\t * that answered. Unset limits are unknown (0).\n\t */\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n\t/** Input types accepted for selection. Defaults to text and images; routed models without image support get placeholders. */\n\tinput?: (\"text\" | \"image\")[];\n\t/** Pick the physical model, which must have credentials, and thinking level for one request. */\n\troute(request: ModelRouteRequest<TState>): ModelRoute<TState> | Promise<ModelRoute<TState>>;\n}\n\n/** Whether a model or message names a virtual model. Failed routing leaves the virtual model on its message. */\nexport function isVirtualModel(model: { api: string }): boolean {\n\treturn model.api === VIRTUAL_MODEL_API;\n}\n\n/** Latest successful response. Its model is physical: failed or aborted requests, including failed routing, are skipped. */\nexport function findLatestResponse(messages: readonly AgentMessage[]): AssistantMessage | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"assistant\" && message.stopReason !== \"error\" && message.stopReason !== \"aborted\") {\n\t\t\treturn message;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * The model selection a session branch records. A virtual `model_change` holds until the next\n * `model_change`, because responses name the physical models it routed to. Otherwise the latest\n * physical response wins, as in sessions without virtual models. A virtual model that is no longer\n * registered does not hold, so the selection falls back to the physical model that answered last.\n *\n * Only the last `model_change` can hold, so this looks up at most one model in the catalog.\n */\nexport function getBranchSelection(\n\tbranch: readonly SessionEntry[],\n\tgetModel: (provider: string, modelId: string) => Model<Api> | undefined,\n): { provider: string; modelId: string } | undefined {\n\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type === \"model_change\") {\n\t\t\treturn { provider: entry.provider, modelId: entry.modelId };\n\t\t}\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\" && !isVirtualModel(entry.message)) {\n\t\t\tconst response = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t\tconst change = findLastModelChange(branch, i);\n\t\t\tconst model = change && getModel(change.provider, change.modelId);\n\t\t\treturn change && model && isVirtualModel(model) ? change : response;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction findLastModelChange(\n\tbranch: readonly SessionEntry[],\n\tbefore: number,\n): { provider: string; modelId: string } | undefined {\n\tfor (let i = before - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type === \"model_change\") return { provider: entry.provider, modelId: entry.modelId };\n\t}\n\treturn undefined;\n}\n\n/** Latest router state a session branch stores for a virtual model. */\nexport function getVirtualModelState(branch: readonly SessionEntry[], provider: string, modelId: string): unknown {\n\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\tconst entry = branch[i];\n\t\tif (entry.type !== \"custom\" || entry.customType !== VIRTUAL_MODEL_STATE_ENTRY) continue;\n\t\tconst data = entry.data as VirtualModelStateData | undefined;\n\t\tif (data?.provider === provider && data.modelId === modelId) return data.state;\n\t}\n\treturn undefined;\n}\n\n/** Build the catalog entry of a virtual model. */\nexport function createVirtualModel(definition: Omit<VirtualModelDefinition, \"route\">): Model<Api> {\n\tconst levels = definition.thinkingLevels ?? [\"off\"];\n\tconst thinkingLevelMap: ThinkingLevelMap = {};\n\tfor (const level of THINKING_LEVELS) thinkingLevelMap[level] = levels.includes(level) ? level : null;\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\tapi: VIRTUAL_MODEL_API,\n\t\tprovider: definition.provider,\n\t\tbaseUrl: \"\",\n\t\treasoning: levels.some((level) => level !== \"off\"),\n\t\tthinkingLevelMap,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 0,\n\t\tmaxTokens: definition.maxTokens ?? 0,\n\t};\n}\n\n/** Stream for a virtual model that was not routed, e.g. `stream()` with API-specific options. */\nfunction unroutedStream(model: Model<Api>): AssistantMessageEventStream {\n\treturn lazyStream(model, async () => {\n\t\tthrow new Error(`Virtual model ${model.provider}/${model.id} must be routed before streaming`);\n\t});\n}\n\n/**\n * Add virtual models to a provider's catalog. Without a provider, the result is a keyless provider\n * that only lists the virtual models. A virtual model hides a physical chat model with the same id,\n * which a catalog refresh can add after registration. Availability follows the provider's auth.\n */\nexport function withVirtualModels(\n\tproviderId: string,\n\tprovider: Provider | undefined,\n\tvirtualModels: readonly Model<Api>[],\n): Provider {\n\tif (!provider) {\n\t\treturn {\n\t\t\tid: providerId,\n\t\t\tname: providerId,\n\t\t\tauth: { apiKey: { name: \"Virtual model\", resolve: async () => ({ auth: {}, source: \"virtual\" }) } },\n\t\t\tgetModels: () => virtualModels,\n\t\t\tstream: unroutedStream,\n\t\t\tstreamSimple: unroutedStream,\n\t\t};\n\t}\n\tconst ids = new Set(virtualModels.map((model) => model.id));\n\tconst physical = <TModel extends AnyModel>(models: readonly TModel[]) =>\n\t\tmodels.filter((model) => !isVirtualModel(model) && !(isModelType(model, \"chat\") && ids.has(model.id)));\n\tconst virtual = <TModel extends AnyModel>(models: readonly TModel[]) =>\n\t\tmodels.filter((model) => isVirtualModel(model));\n\tconst { filterModels, filterAllModels } = provider;\n\treturn {\n\t\t...provider,\n\t\tgetModels: () => [...physical(provider.getModels()), ...virtualModels],\n\t\tgetAllModels: () => [...physical(provider.getAllModels?.() ?? provider.getModels()), ...virtualModels],\n\t\tfilterModels: (models, credential) => {\n\t\t\tconst real = physical(models);\n\t\t\treturn [...(filterModels?.(real, credential) ?? real), ...virtual(models)];\n\t\t},\n\t\tfilterAllModels:\n\t\t\tfilterAllModels &&\n\t\t\t((models, credential) => [...filterAllModels(physical(models), credential), ...virtual(models)]),\n\t\tstream: (model, context, options) =>\n\t\t\tisVirtualModel(model) ? unroutedStream(model) : provider.stream(model, context, options),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tisVirtualModel(model) ? unroutedStream(model) : provider.streamSimple(model, context, options),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH,OAAO,KAAK,EAAmC,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAYtG,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,OAAO,EAKN,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAIx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