@bastani/atomic 0.9.25 → 0.9.26-alpha.2

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 (186) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/builtin/intercom/package.json +2 -2
  3. package/dist/builtin/mcp/OAUTH.md +1 -1
  4. package/dist/builtin/mcp/native-client-licenses/NOTICE +2 -2
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/package.json +3 -3
  7. package/dist/builtin/web-access/package.json +2 -2
  8. package/dist/builtin/workflows/CHANGELOG.md +6 -0
  9. package/dist/builtin/workflows/package.json +2 -2
  10. package/dist/builtin/workflows/src/extension/index.bundle.mjs +17 -0
  11. package/dist/builtin/workflows/src/index.js +15 -0
  12. package/dist/cli/args.js +1 -1
  13. package/dist/cli/args.js.map +1 -1
  14. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  15. package/dist/core/agent-session-extension-bindings.js +4 -0
  16. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  17. package/dist/core/agent-session-methods.d.ts +5 -1
  18. package/dist/core/agent-session-methods.d.ts.map +1 -1
  19. package/dist/core/agent-session-methods.js.map +1 -1
  20. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  21. package/dist/core/agent-session-prompt.js +1 -0
  22. package/dist/core/agent-session-prompt.js.map +1 -1
  23. package/dist/core/agent-session-state.d.ts +14 -2
  24. package/dist/core/agent-session-state.d.ts.map +1 -1
  25. package/dist/core/agent-session-state.js +31 -6
  26. package/dist/core/agent-session-state.js.map +1 -1
  27. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  28. package/dist/core/agent-session-tool-registry.js +5 -1
  29. package/dist/core/agent-session-tool-registry.js.map +1 -1
  30. package/dist/core/agent-session.d.ts +1 -0
  31. package/dist/core/agent-session.d.ts.map +1 -1
  32. package/dist/core/agent-session.js +2 -2
  33. package/dist/core/agent-session.js.map +1 -1
  34. package/dist/core/extensions/api-types.d.ts +2 -1
  35. package/dist/core/extensions/api-types.d.ts.map +1 -1
  36. package/dist/core/extensions/api-types.js.map +1 -1
  37. package/dist/core/extensions/index.d.ts +1 -1
  38. package/dist/core/extensions/index.d.ts.map +1 -1
  39. package/dist/core/extensions/index.js.map +1 -1
  40. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  41. package/dist/core/extensions/loader-api.js +7 -0
  42. package/dist/core/extensions/loader-api.js.map +1 -1
  43. package/dist/core/extensions/provider-types.d.ts +2 -0
  44. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  45. package/dist/core/extensions/provider-types.js.map +1 -1
  46. package/dist/core/messages.d.ts.map +1 -1
  47. package/dist/core/messages.js +4 -3
  48. package/dist/core/messages.js.map +1 -1
  49. package/dist/core/model-registry.d.ts +2 -1
  50. package/dist/core/model-registry.d.ts.map +1 -1
  51. package/dist/core/model-registry.js +3 -0
  52. package/dist/core/model-registry.js.map +1 -1
  53. package/dist/core/model-runtime-streaming.d.ts +2 -1
  54. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  55. package/dist/core/model-runtime-streaming.js +4 -1
  56. package/dist/core/model-runtime-streaming.js.map +1 -1
  57. package/dist/core/model-runtime.d.ts +2 -0
  58. package/dist/core/model-runtime.d.ts.map +1 -1
  59. package/dist/core/model-runtime.js +69 -5
  60. package/dist/core/model-runtime.js.map +1 -1
  61. package/dist/core/oauth-login.d.ts +1 -0
  62. package/dist/core/oauth-login.d.ts.map +1 -1
  63. package/dist/core/oauth-login.js.map +1 -1
  64. package/dist/core/oauth-provider-metadata.d.ts.map +1 -1
  65. package/dist/core/oauth-provider-metadata.js +5 -17
  66. package/dist/core/oauth-provider-metadata.js.map +1 -1
  67. package/dist/core/provider-alias.d.ts +8 -0
  68. package/dist/core/provider-alias.d.ts.map +1 -0
  69. package/dist/core/provider-alias.js +119 -0
  70. package/dist/core/provider-alias.js.map +1 -0
  71. package/dist/core/provider-composer-internal.d.ts +1 -0
  72. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  73. package/dist/core/provider-composer-internal.js.map +1 -1
  74. package/dist/core/provider-composer.d.ts.map +1 -1
  75. package/dist/core/provider-composer.js +9 -0
  76. package/dist/core/provider-composer.js.map +1 -1
  77. package/dist/core/sdk.js +2 -1
  78. package/dist/core/sdk.js.map +1 -1
  79. package/dist/core/settings-manager-resource-accessors.d.ts +3 -3
  80. package/dist/core/settings-manager-resource-accessors.d.ts.map +1 -1
  81. package/dist/core/settings-manager-resource-accessors.js +2 -1
  82. package/dist/core/settings-manager-resource-accessors.js.map +1 -1
  83. package/dist/core/settings-manager.d.ts +1 -1
  84. package/dist/core/settings-manager.d.ts.map +1 -1
  85. package/dist/core/settings-manager.js.map +1 -1
  86. package/dist/core/settings-types.d.ts +2 -1
  87. package/dist/core/settings-types.d.ts.map +1 -1
  88. package/dist/core/settings-types.js.map +1 -1
  89. package/dist/core/system-prompt.js +1 -1
  90. package/dist/core/system-prompt.js.map +1 -1
  91. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  92. package/dist/extensions/codemode/execute.js +133 -31
  93. package/dist/extensions/codemode/execute.js.map +1 -1
  94. package/dist/extensions/codemode/tool.d.ts +2 -1
  95. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  96. package/dist/extensions/codemode/tool.js +25 -4
  97. package/dist/extensions/codemode/tool.js.map +1 -1
  98. package/dist/extensions/mcp/cli.js +2 -2
  99. package/dist/extensions/mcp/cli.js.map +1 -1
  100. package/dist/extensions/mcp/client/oauth/flow.d.ts +6 -0
  101. package/dist/extensions/mcp/client/oauth/flow.d.ts.map +1 -1
  102. package/dist/extensions/mcp/client/oauth/flow.js +23 -5
  103. package/dist/extensions/mcp/client/oauth/flow.js.map +1 -1
  104. package/dist/extensions/mcp/client/oauth/index.d.ts +1 -1
  105. package/dist/extensions/mcp/client/oauth/index.d.ts.map +1 -1
  106. package/dist/extensions/mcp/client/oauth/index.js +1 -1
  107. package/dist/extensions/mcp/client/oauth/index.js.map +1 -1
  108. package/dist/extensions/mcp/index.d.ts.map +1 -1
  109. package/dist/extensions/mcp/index.js +22 -12
  110. package/dist/extensions/mcp/index.js.map +1 -1
  111. package/dist/extensions/mcp/oauth.d.ts +12 -7
  112. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  113. package/dist/extensions/mcp/oauth.js +58 -24
  114. package/dist/extensions/mcp/oauth.js.map +1 -1
  115. package/dist/extensions/mcp/runtime.js +1 -1
  116. package/dist/extensions/mcp/runtime.js.map +1 -1
  117. package/dist/index-extensions.d.ts +1 -1
  118. package/dist/index-extensions.d.ts.map +1 -1
  119. package/dist/index-extensions.js.map +1 -1
  120. package/dist/index.d.ts +1 -1
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js.map +1 -1
  123. package/dist/main-session-options.d.ts.map +1 -1
  124. package/dist/main-session-options.js +6 -0
  125. package/dist/main-session-options.js.map +1 -1
  126. package/dist/main.js +1 -1
  127. package/dist/main.js.map +1 -1
  128. package/dist/modes/interactive/components/atomic-banner.d.ts +2 -0
  129. package/dist/modes/interactive/components/atomic-banner.d.ts.map +1 -1
  130. package/dist/modes/interactive/components/atomic-banner.js +9 -1
  131. package/dist/modes/interactive/components/atomic-banner.js.map +1 -1
  132. package/dist/modes/interactive/components/oauth-selector.d.ts +2 -0
  133. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  134. package/dist/modes/interactive/components/oauth-selector.js +9 -4
  135. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  136. package/dist/modes/interactive/components/settings-selector-handlers.js +1 -1
  137. package/dist/modes/interactive/components/settings-selector-handlers.js.map +1 -1
  138. package/dist/modes/interactive/components/settings-selector-items.js +3 -3
  139. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  140. package/dist/modes/interactive/components/settings-selector-types.d.ts +3 -3
  141. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  143. package/dist/modes/interactive/components/startup-identity.js +2 -2
  144. package/dist/modes/interactive/components/startup-identity.js.map +1 -1
  145. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  146. package/dist/modes/interactive/components/user-message.js +3 -4
  147. package/dist/modes/interactive/components/user-message.js.map +1 -1
  148. package/dist/modes/interactive/interactive-auth-login.js +14 -5
  149. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  150. package/dist/modes/interactive/interactive-auth-routing.js +38 -17
  151. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  152. package/dist/modes/interactive/interactive-mode-surface.d.ts +6 -4
  153. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  154. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  155. package/dist/modes/interactive/interactive-resource-rendering.js +1 -1
  156. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  157. package/dist/modes/interactive/interactive-selectors.js +2 -2
  158. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  159. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  160. package/dist/modes/interactive/interactive-startup.js +12 -4
  161. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  162. package/dist/modes/interactive/login-provider-options.d.ts +2 -1
  163. package/dist/modes/interactive/login-provider-options.d.ts.map +1 -1
  164. package/dist/modes/interactive/login-provider-options.js +11 -6
  165. package/dist/modes/interactive/login-provider-options.js.map +1 -1
  166. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
  167. package/dist/modes/interactive/theme/system-theme.js +10 -4
  168. package/dist/modes/interactive/theme/system-theme.js.map +1 -1
  169. package/docs/codemode.md +214 -0
  170. package/docs/custom-provider/oauth.md +2 -0
  171. package/docs/custom-provider/registration.md +32 -0
  172. package/docs/custom-provider.md +1 -0
  173. package/docs/docs.json +1 -0
  174. package/docs/extensions/api-reference.md +2 -0
  175. package/docs/getting-started/authentication.md +2 -2
  176. package/docs/guides.md +1 -1
  177. package/docs/mcp-servers.md +2 -0
  178. package/docs/providers.md +5 -3
  179. package/docs/reference/cli.md +1 -1
  180. package/docs/settings.md +1 -1
  181. package/docs/terminal-setup.md +2 -0
  182. package/docs/tools.md +1 -3
  183. package/docs/usage.md +1 -1
  184. package/examples/extensions/provider-accounts.ts +11 -0
  185. package/npm-shrinkwrap.json +68 -73
  186. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,CAAU,CAAC;AA4DvH,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AACxD,gGAAgG;AAChG,MAAM,UAAU,iCAAiC,CAAC,KAA+B;IAChF,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,aAAa,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,oBAAoB,CAAC,CAAC;QACjE,YAAY,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE;QAC/C,cAAc,EAAE,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAC/F;QACD,gBAAgB,EAAE,CAAC,GAA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AC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CACvC,QAAuC,EACvC,OAA6B;IAE7B,MAAM,KAAK,GAAkC,EAAE,CAAC;IAChD,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t\taddGuideline(\n\t\t\t[\n\t\t\t\t\"**Execution history**: Leave a mineable record of how each task was executed and what the user prefers, and mine those records to calibrate later work. The records only accumulate value if every task writes them. If the user, a context file, or `APPEND_SYSTEM.md` asks you not to record some or all of these records, skip those records.\",\n\t\t\t\t\" - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.\",\n\t\t\t\t\" - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.\",\n\t\t\t\t\" - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.\",\n\t\t\t\t\" - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work. Missing, sparse, or mostly inline workflow history is not evidence that the user prefers inline work: records exist only for tasks that wrote them, and past inline runs may reflect an earlier default rather than a choice. Without a recorded or stated preference that covers the situation, judge the task's shape yourself and choose a workflow when it would help, then let comparable records and the user's preferences refine that call.\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \\`cua-driver skills install\\` or \\`clawhub install @cua/driver\\`, and do not link or copy a skill into \\`~/.agents/skills/cua-driver\\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers, because its text snapshots cost far fewer tokens than screenshot-driven CUA: websites and web apps in Chrome/Chromium, Mobile Safari in the iOS Simulator or on a connected iPhone/iPad (\\`agent-browser -p ios\\`, macOS with Xcode and Appium), Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify and other apps exposing a CDP port, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, native iOS apps in the iOS Simulator, Android emulators, OS dialogs and permission prompts, desktop Safari and other non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- Also skip \\`cua-driver skills update\\` and any skill installation into other agent directories such as \\`~/.claude/skills\\`; updating the executable is separate from installing or updating a skill.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,CAAU,CAAC;AA4DvH,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AACxD,gGAAgG;AAChG,MAAM,UAAU,iCAAiC,CAAC,KAA+B;IAChF,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,aAAa,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,oBAAoB,CAAC,CAAC;QACjE,YAAY,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE;QAC/C,cAAc,EAAE,MAAM,CAAC,WAAW,CACjC,M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AC,EAAE,CAAC;AACpE,CAAC;AAED,oGAAoG;AACpG,MAAM,UAAU,iBAAiB,CAAC,KAA+B;IAChE,OAAO,oBAAoB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,sBAAsB,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC;AACjG,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CACvC,QAAuC,EACvC,OAA6B;IAE7B,MAAM,KAAK,GAAkC,EAAE,CAAC;IAChD,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t\taddGuideline(\n\t\t\t[\n\t\t\t\t\"**Execution history**: Leave a mineable record of how each task was executed and what the user prefers, and mine those records to calibrate later work. The records only accumulate value if every task writes them. If the user, a context file, or `APPEND_SYSTEM.md` asks you not to record some or all of these records, skip those records.\",\n\t\t\t\t\" - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.\",\n\t\t\t\t\" - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.\",\n\t\t\t\t\" - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.\",\n\t\t\t\t\" - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work. Missing, sparse, or mostly inline workflow history is not evidence that the user prefers inline work: records exist only for tasks that wrote them, and past inline runs may reflect an earlier default rather than a choice. Without a recorded or stated preference that covers the situation, judge the task's shape yourself and choose a workflow when it would help, then let comparable records and the user's preferences refine that call.\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \\`cua-driver skills install\\` or \\`clawhub install @cua/driver\\`, and do not link or copy a skill into \\`~/.agents/skills/cua-driver\\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers, because its text snapshots cost far fewer tokens than screenshot-driven CUA: websites and web apps in Chrome/Chromium, Mobile Safari in the iOS Simulator or on a connected iPhone/iPad (\\`agent-browser -p ios\\`, macOS with Xcode and Appium), Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify and other apps exposing a CDP port, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, native iOS apps in the iOS Simulator, Android emulators, OS dialogs and permission prompts, desktop Safari and other non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- Also skip \\`cua-driver skills update\\` and any skill installation into other agent directories such as \\`~/.claude/skills\\`; updating the executable is separate from installing or updating a skill.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAkE,MAAM,gBAAgB,CAAC;AAC/G,OAAO,KAAK,EAAa,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAWhF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAEnF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,OAAO,EAGN,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAGxB,MAAM,WAAW,CAAC;AAEnB,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAsB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E,eAAe,CAAC,mBAAmB,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,EAC5E,GAAG,EAAE,oBAAoB,GAAG,SAAS,EACrC,OAAO,GAAE,mBAAwB,GAC/B,OAAO,CAAC,eAAe,CAAC,mBAAmB,CAAC,CAAC,CAgI/C"}
@@ -6,7 +6,7 @@ import { CodemodeSandbox, loadQuickJSWasm, parseCodemodeSource, renderToolSample
6
6
  import { getCodemodeWorkerUrl, getQuickJSWasmPath } from "../../config.js";
7
7
  import { combineUsage } from "../../core/usage-totals.js";
8
8
  import { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from "../tool-search/tool.js";
9
- import { CODEMODE_STORE_ENTRY_TYPE, getCodemodeCallableTools, toCodemodeDeclaration, } from "./tool.js";
9
+ import { CODEMODE_DOCS_PATH, CODEMODE_STORE_ENTRY_TYPE, getCodemodeCallableTools, toCodemodeDeclaration, } from "./tool.js";
10
10
  export function readCodemodeStore(branch) {
11
11
  const store = new Map();
12
12
  for (const entry of branch) {
@@ -49,11 +49,86 @@ export function toCodemodeModelInfo(model) {
49
49
  cost: model.cost,
50
50
  };
51
51
  }
52
+ const MODEL_TYPES = ["chat", "image", "classifier"];
52
53
  function modelType(value) {
53
54
  if (value === "chat" || value === "image" || value === "classifier")
54
55
  return value;
55
56
  throw new Error('Model type must be "chat", "image", or "classifier"');
56
57
  }
58
+ function withArticle(word) {
59
+ return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
60
+ }
61
+ function isRecord(value) {
62
+ return typeof value === "object" && value !== null && !Array.isArray(value);
63
+ }
64
+ function describeValue(value) {
65
+ if (value === undefined || value === null)
66
+ return String(value);
67
+ if (Array.isArray(value))
68
+ return value.length === 0 ? "an empty array" : "an array";
69
+ if (typeof value === "object") {
70
+ const keys = Object.keys(value);
71
+ if (keys.length === 0)
72
+ return "{}";
73
+ return `{ ${keys.slice(0, 6).join(", ")}${keys.length > 6 ? ", ..." : ""} }`;
74
+ }
75
+ return typeof value === "string" ? "a string" : `a ${typeof value}`;
76
+ }
77
+ const CLASSIFIER_CONTEXT_SHAPE = '{ state: { ... }, questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';
78
+ function checkClassifierContext(context) {
79
+ const fail = (problem) => new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`);
80
+ if (!isRecord(context))
81
+ throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
82
+ if (!isRecord(context.state))
83
+ throw fail(`context.state must be an object, got ${describeValue(context.state)}`);
84
+ const { questions } = context;
85
+ if (!isRecord(questions) || Object.keys(questions).length === 0)
86
+ throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);
87
+ const isStrings = (values) => values.length > 0 && values.every((value) => typeof value === "string");
88
+ for (const [questionId, question] of Object.entries(questions)) {
89
+ const at = `context.questions.${questionId}`;
90
+ if (!isRecord(question))
91
+ throw fail(`${at} must be a question object, got ${describeValue(question)}`);
92
+ if (typeof question.instructions !== "string")
93
+ throw fail(`${at}.instructions must be a string`);
94
+ const { criteria } = question;
95
+ if (question.type === "choice") {
96
+ if (!isRecord(criteria) || !isStrings(Object.values(criteria)))
97
+ throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`);
98
+ }
99
+ else if (question.type === "score") {
100
+ if (!Array.isArray(criteria) || !isStrings(criteria))
101
+ throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`);
102
+ }
103
+ else if (question.type === "bool") {
104
+ if (!isRecord(criteria) || typeof criteria.true !== "string" || typeof criteria.false !== "string")
105
+ throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`);
106
+ }
107
+ else {
108
+ throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(question.type)}`);
109
+ }
110
+ }
111
+ return context;
112
+ }
113
+ function checkImagesContext(context) {
114
+ const fail = (problem) => new Error(`models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${CODEMODE_DOCS_PATH}.`);
115
+ if (!isRecord(context))
116
+ throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
117
+ const { input } = context;
118
+ if (!Array.isArray(input) || input.length === 0)
119
+ throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);
120
+ input.forEach((block, index) => {
121
+ if (isRecord(block) && block.type === "text" && typeof block.text === "string")
122
+ return;
123
+ if (isRecord(block) &&
124
+ block.type === "image" &&
125
+ typeof block.data === "string" &&
126
+ typeof block.mimeType === "string")
127
+ return;
128
+ throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);
129
+ });
130
+ return context;
131
+ }
57
132
  function provider(value) {
58
133
  if (value === undefined || value === null)
59
134
  return undefined;
@@ -148,10 +223,48 @@ function discoveryGlobals(tools, samples, options) {
148
223
  },
149
224
  ];
150
225
  }
151
- function modelGlobals(ctx, id, calls, publish, addUsage) {
226
+ function modelGlobals(ctx, id, calls, publish, addUsage, addGeneratedImages) {
152
227
  const models = ctx.modelRegistry;
153
228
  const limit = createLimiter(4);
154
229
  let count = 0;
230
+ const runModelCall = async (name, type, [ref, context], checkContext, run) => {
231
+ const listHint = `List the ${type} models you can use with models.getAvailableOfType("${type}").`;
232
+ if (!isRecord(ref) || typeof ref.provider !== "string" || typeof ref.id !== "string") {
233
+ const undefinedHint = ref === undefined || ref === null
234
+ ? " models.getModelOfType() returns undefined for an unknown provider or id."
235
+ : "";
236
+ throw new Error(`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(ref)}.${undefinedHint} ${listHint}`);
237
+ }
238
+ const { provider: providerId, id: modelId } = ref;
239
+ const model = models.getModelOfType(type, providerId, modelId);
240
+ if (!model) {
241
+ const actualType = MODEL_TYPES.find((other) => other !== type && models.getModelOfType(other, providerId, modelId) !== undefined);
242
+ throw new Error(actualType
243
+ ? `"${providerId}/${modelId}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`
244
+ : `Unknown ${type} model "${providerId}/${modelId}". ${listHint}`);
245
+ }
246
+ const checked = checkContext(context);
247
+ const record = {
248
+ id: `${id}/${name}/${++count}`,
249
+ name,
250
+ args: `${model.provider}/${model.id}`,
251
+ status: "running",
252
+ };
253
+ calls.push(record);
254
+ publish();
255
+ const start = performance.now();
256
+ const result = await limit(() => run(model, checked));
257
+ record.durationMs = performance.now() - start;
258
+ record.status = result.stopReason === "stop" ? "ok" : result.stopReason === "aborted" ? "cancelled" : "error";
259
+ if (result.errorMessage)
260
+ record.error = result.errorMessage.slice(0, 500);
261
+ if (result.usage) {
262
+ record.cost = result.usage.cost.total;
263
+ addUsage(result.usage);
264
+ }
265
+ publish();
266
+ return result;
267
+ };
155
268
  return [
156
269
  {
157
270
  name: "models.getModelsOfType",
@@ -175,7 +288,7 @@ function modelGlobals(ctx, id, calls, publish, addUsage) {
175
288
  execute: (args) => {
176
289
  const [type, source, modelId] = args;
177
290
  if (typeof source !== "string" || typeof modelId !== "string")
178
- throw new Error("models.getModelOfType() expects type, provider, and id");
291
+ throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${args.map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);
179
292
  const model = models.getModelOfType(modelType(type), source, modelId);
180
293
  return model ? toCodemodeModelInfo(model) : undefined;
181
294
  },
@@ -183,35 +296,16 @@ function modelGlobals(ctx, id, calls, publish, addUsage) {
183
296
  {
184
297
  name: "models.classify",
185
298
  spread: true,
186
- execute: async (args, { signal }) => {
187
- const [ref, context] = args;
188
- if (!ref || typeof ref.provider !== "string" || typeof ref.id !== "string")
189
- throw new Error("models.classify() expects a catalog model reference");
190
- const model = models.getModelOfType("classifier", ref.provider, ref.id);
191
- if (!model)
192
- throw new Error(`Unknown classifier model ${ref.provider}/${ref.id}`);
193
- const record = {
194
- id: `${id}/models.classify/${++count}`,
195
- name: "models.classify",
196
- args: `${model.provider}/${model.id}`,
197
- status: "running",
198
- };
199
- calls.push(record);
200
- publish();
201
- const start = performance.now();
202
- const result = await limit(() => models.classify(model, context, { signal }));
203
- record.durationMs = performance.now() - start;
204
- record.status =
205
- result.stopReason === "stop" ? "ok" : result.stopReason === "aborted" ? "cancelled" : "error";
206
- if (result.errorMessage)
207
- record.error = result.errorMessage.slice(0, 500);
208
- if (result.usage) {
209
- record.cost = result.usage.cost.total;
210
- addUsage(result.usage);
211
- }
212
- publish();
299
+ execute: (args, { signal }) => runModelCall("models.classify", "classifier", args, checkClassifierContext, (model, context) => models.classify(model, context, { signal })),
300
+ },
301
+ {
302
+ name: "models.generateImages",
303
+ spread: true,
304
+ execute: (args, { signal }) => runModelCall("models.generateImages", "image", args, checkImagesContext, async (model, context) => {
305
+ const result = await models.generateImages(model, context, { signal });
306
+ addGeneratedImages(result.output.filter((block) => block.type === "image").length);
213
307
  return result;
214
- },
308
+ }),
215
309
  },
216
310
  ];
217
311
  }
@@ -220,6 +314,7 @@ export async function executeCodemode(id, input, signal, update, ctx, options =
220
314
  const { code, options: source } = parseCodemodeSource(input.code);
221
315
  const calls = [];
222
316
  let usage;
317
+ let generatedImages = 0;
223
318
  const snapshot = () => ({ calls: calls.map((call) => ({ ...call })) });
224
319
  const publish = () => update?.({ content: [], details: snapshot() });
225
320
  const callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];
@@ -260,6 +355,8 @@ export async function executeCodemode(id, input, signal, update, ctx, options =
260
355
  ...(options.models && ctx
261
356
  ? modelGlobals(ctx, id, calls, publish, (extra) => {
262
357
  usage = usage ? combineUsage(usage, extra) : extra;
358
+ }, (count) => {
359
+ generatedImages += count;
263
360
  })
264
361
  : []),
265
362
  ],
@@ -296,6 +393,11 @@ export async function executeCodemode(id, input, signal, update, ctx, options =
296
393
  type: "text",
297
394
  text: `Script error:\n${result.error.stack ?? result.error.message}\n\nTool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(", ") || "none"}`,
298
395
  });
396
+ if (generatedImages > 0 && !content.some((block) => block.type === "image"))
397
+ content.push({
398
+ type: "text",
399
+ text: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? "" : "s"} that the script did not show. Show each image block of result.output with image(block).`,
400
+ });
299
401
  const text = content
300
402
  .filter((block) => block.type === "text")
301
403
  .map((block) => block.text)
@@ -1 +1 @@
1
- {"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAEN,eAAe,EAEf,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAI3E,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACzG,OAAO,EACN,yBAAyB,EAKzB,wBAAwB,EACxB,qBAAqB,GACrB,MAAM,WAAW,CAAC;AAEnB,MAAM,UAAU,iBAAiB,CAAC,MAA+B;IAChE,MAAM,KAAK,GAAG,IAAI,GAAG,EAAmB,CAAC;IACzC,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC5B,IACC,KAAK,CAAC,IAAI,KAAK,QAAQ;YACvB,KAAK,CAAC,UAAU,KAAK,yBAAyB;YAC9C,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;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AAG,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,MAAM,GAAG,IAAI,CAAC;QAC3B,OAAO,GAAG;YACT;gBACC,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,oDAAoD,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,+BAA+B,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,MAAM,EAAE;aACtL;YACD,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,OAAO,CAAC;SACpD,CAAC;IACH,CAAC;IACD,OAAO;QACN,OAAO,EAAE;YACR;gBACC,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,eAAe,eAAe,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,qBAAqB;aAC5I;YACD,GAAG,OAAO;SACV;QACD,OAAO;QACP,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3B,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;KACvC,CAAC;AACH,CAAC","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AnyModel, ClassifierContext, ImageContent, ModelType, TextContent, Usage } from \"@bastani/pi-ai\";\nimport type { AgentTool, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerUrl, getQuickJSWasmPath } from \"../../config.js\";\nimport type { ExtensionToolContext } from \"../../core/extensions/context-types.ts\";\nimport type { ToolNamespace } from \"../../core/extensions/tool-types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.js\";\nimport {\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeNestedCall,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.js\";\n\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (\n\t\t\tentry.type !== \"custom\" ||\n\t\t\tentry.customType !== CODEMODE_STORE_ENTRY_TYPE ||\n\t\t\ttypeof entry.data !== \"object\" ||\n\t\t\tentry.data === null\n\t\t)\n\t\t\tcontinue;\n\t\tconst data = entry.data as { set?: Record<string, unknown>; delete?: string[] };\n\t\tif (\n\t\t\t!data.set ||\n\t\t\ttypeof data.set !== \"object\" ||\n\t\t\t!Array.isArray(data.delete) ||\n\t\t\t!data.delete.every((key) => typeof key === \"string\")\n\t\t)\n\t\t\tcontinue;\n\t\tfor (const key of data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn result.content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n/** Explicit public catalog fields. Provider configuration and credential-bearing URLs never cross into the VM. */\nexport function toCodemodeModelInfo(model: AnyModel): Record<string, unknown> {\n\treturn {\n\t\ttype: model.type,\n\t\tprovider: model.provider,\n\t\tid: model.id,\n\t\tname: model.name,\n\t\tapi: model.api,\n\t\tinput: model.input,\n\t\t...(\"reasoning\" in model ? { reasoning: model.reasoning } : {}),\n\t\t...(\"contextWindow\" in model ? { contextWindow: model.contextWindow } : {}),\n\t\t...(\"maxTokens\" in model ? { maxTokens: model.maxTokens } : {}),\n\t\tcost: model.cost,\n\t};\n}\nfunction modelType(value: unknown): ModelType {\n\tif (value === \"chat\" || value === \"image\" || value === \"classifier\") return value;\n\tthrow new Error('Model type must be \"chat\", \"image\", or \"classifier\"');\n}\nfunction provider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value === \"string\") return value;\n\tthrow new Error(\"provider must be a string\");\n}\nfunction preview(args: unknown): string {\n\ttry {\n\t\treturn (JSON.stringify(args) ?? \"\").slice(0, 200);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\nfunction createLimiter(limit: number) {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async <T>(run: () => Promise<T>): Promise<T> => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\nfunction discoveryGlobals(\n\ttools: readonly AgentTool[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, config] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = config?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0)\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\tif (config?.namespace !== undefined && typeof config.namespace !== \"string\")\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\tconst docs = tools.flatMap((tool) => {\n\t\t\t\t\tconst namespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\treturn config?.namespace && namespace?.name !== config.namespace\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: [createToolSearchDocument(tool, namespace)];\n\t\t\t\t});\n\t\t\t\treturn new Bm25Ranker().rank(query, docs, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find((tool) => tool.name === name || toCodemodeIdentifier(tool.name) === name);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (toolNamespace?.name !== name) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\nfunction modelGlobals(\n\tctx: ExtensionToolContext,\n\tid: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n): CodemodeTool[] {\n\tconst models = ctx.modelRegistry;\n\tconst limit = createLimiter(4);\n\tlet count = 0;\n\treturn [\n\t\t{\n\t\t\tname: \"models.getModelsOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn models.getModelsOfType(modelType(type), provider(source)).map(toCodemodeModelInfo);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getAvailableOfType\",\n\t\t\tspread: true,\n\t\t\texecute: async (args, { signal }) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn (await models.getAvailableOfType(modelType(type), provider(source), { signal })).map(\n\t\t\t\t\ttoCodemodeModelInfo,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getModelOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source, modelId] = args as unknown[];\n\t\t\t\tif (typeof source !== \"string\" || typeof modelId !== \"string\")\n\t\t\t\t\tthrow new Error(\"models.getModelOfType() expects type, provider, and id\");\n\t\t\t\tconst model = models.getModelOfType(modelType(type), source, modelId);\n\t\t\t\treturn model ? toCodemodeModelInfo(model) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.classify\",\n\t\t\tspread: true,\n\t\t\texecute: async (args, { signal }) => {\n\t\t\t\tconst [ref, context] = args as [{ provider?: string; id?: string } | null, unknown];\n\t\t\t\tif (!ref || typeof ref.provider !== \"string\" || typeof ref.id !== \"string\")\n\t\t\t\t\tthrow new Error(\"models.classify() expects a catalog model reference\");\n\t\t\t\tconst model = models.getModelOfType(\"classifier\", ref.provider, ref.id);\n\t\t\t\tif (!model) throw new Error(`Unknown classifier model ${ref.provider}/${ref.id}`);\n\t\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\t\tid: `${id}/models.classify/${++count}`,\n\t\t\t\t\tname: \"models.classify\",\n\t\t\t\t\targs: `${model.provider}/${model.id}`,\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t};\n\t\t\t\tcalls.push(record);\n\t\t\t\tpublish();\n\t\t\t\tconst start = performance.now();\n\t\t\t\tconst result = await limit(() => models.classify(model, context as ClassifierContext, { signal }));\n\t\t\t\trecord.durationMs = performance.now() - start;\n\t\t\t\trecord.status =\n\t\t\t\t\tresult.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\t\t\tif (result.errorMessage) record.error = result.errorMessage.slice(0, 500);\n\t\t\t\tif (result.usage) {\n\t\t\t\t\trecord.cost = result.usage.cost.total;\n\t\t\t\t\taddUsage(result.usage);\n\t\t\t\t}\n\t\t\t\tpublish();\n\t\t\t\treturn result;\n\t\t\t},\n\t\t},\n\t];\n}\n\nexport async function executeCodemode(\n\tid: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tupdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst start = performance.now();\n\tconst { code, options: source } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\tlet usage: Usage | undefined;\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => update?.({ content: [], details: snapshot() });\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: callable.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: samples.get(tool.name),\n\t\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\t\tid: `${id}/?`,\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\targs: preview(args),\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t};\n\t\t\t\tcalls.push(record);\n\t\t\t\tpublish();\n\t\t\t\tconst started = performance.now();\n\t\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\t\trecord.id = outcome.toolCall.id;\n\t\t\t\trecord.durationMs = performance.now() - started;\n\t\t\t\trecord.status = outcome.isError ? (callSignal.aborted ? \"cancelled\" : \"error\") : \"ok\";\n\t\t\t\tconst text = textOf(outcome.result);\n\t\t\t\tif (outcome.isError) record.error = (text || `Tool ${tool.name} failed`).slice(0, 500);\n\t\t\t\tpublish();\n\t\t\t\tif (tool.outputSchema && outcome.result.structuredContent !== undefined)\n\t\t\t\t\treturn outcome.result.structuredContent;\n\t\t\t\tif (outcome.isError) throw new Error(text || `Tool ${tool.name} failed`);\n\t\t\t\treturn text;\n\t\t\t},\n\t\t})),\n\t\tglobals: [\n\t\t\t...discoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? modelGlobals(ctx, id, calls, publish, (extra) => {\n\t\t\t\t\t\tusage = usage ? combineUsage(usage, extra) : extra;\n\t\t\t\t\t})\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: source.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: 256 * 1024 * 1024,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerUrl(),\n\t});\n\tlet result: CodemodeResult;\n\ttry {\n\t\tresult = await sandbox.execute(code, {\n\t\t\tsignal,\n\t\t\tstore: ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {},\n\t\t});\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\tfor (const call of calls) if (call.status === \"running\") call.status = \"cancelled\";\n\tlet content: (TextContent | ImageContent)[] = [...result.output];\n\tif (result.ok) {\n\t\tif (Object.keys(result.storeWrites.set).length || result.storeWrites.delete.length)\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, result.storeWrites);\n\t\tif (result.value !== undefined)\n\t\t\tcontent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\ttypeof result.value === \"string\" ? result.value : (JSON.stringify(result.value) ?? String(result.value)),\n\t\t\t});\n\t} else\n\t\tcontent.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Script error:\\n${result.error.stack ?? result.error.message}\\n\\nTool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \") || \"none\"}`,\n\t\t});\n\tconst text = content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tconst budget = (source.maxOutputTokens ?? 10_000) * 4;\n\tconst details = snapshot();\n\tif (text.length > budget) {\n\t\tconst path = join(tmpdir(), `atomic-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\t\tlet notice: string;\n\t\ttry {\n\t\t\tawait writeFile(path, text);\n\t\t\tdetails.fullOutputPath = path;\n\t\t\tnotice = `Full output: ${path}`;\n\t\t} catch (error) {\n\t\t\tnotice = `Could not save full output: ${error instanceof Error ? error.message : String(error)}`;\n\t\t}\n\t\tconst head = Math.floor(budget / 2);\n\t\tconst tail = budget - head;\n\t\tcontent = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Warning: truncated output (original token count: ${Math.ceil(text.length / 4)})\\n${text.slice(0, head)}\\n... output truncated ...\\n${tail ? text.slice(-tail) : \"\"}\\n${notice}`,\n\t\t\t},\n\t\t\t...content.filter((block) => block.type === \"image\"),\n\t\t];\n\t}\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${((performance.now() - start) / 1000).toFixed(1)} seconds\\nOutput:\\n`,\n\t\t\t},\n\t\t\t...content,\n\t\t],\n\t\tdetails,\n\t\t...(usage ? { usage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n"]}
1
+ {"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/codemode/execute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAYjC,OAAO,EAEN,eAAe,EAEf,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAI3E,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACzG,OAAO,EACN,kBAAkB,EAClB,yBAAyB,EAKzB,wBAAwB,EACxB,qBAAqB,GACrB,MAAM,WAAW,CAAC;AAEnB,MAAM,UAAU,iBAAiB,CAAC,MAA+B;IAChE,MAAM,KAAK,GAAG,IAAI,GAAG,EAAmB,CAAC;IACzC,KAAK,MAAM,K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CAAC,CAAC,CAAC,qBAAqB;aAC5I;YACD,GAAG,OAAO;SACV;QACD,OAAO;QACP,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3B,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;KACvC,CAAC;AACH,CAAC","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type {\n\tAnyModel,\n\tClassifierContext,\n\tImageContent,\n\tImagesContext,\n\tModelType,\n\tModelTypeMap,\n\tTextContent,\n\tUsage,\n} from \"@bastani/pi-ai\";\nimport type { AgentTool, AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\tloadQuickJSWasm,\n\tparseCodemodeSource,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode\";\nimport { getCodemodeWorkerUrl, getQuickJSWasmPath } from \"../../config.js\";\nimport type { ExtensionToolContext } from \"../../core/extensions/context-types.ts\";\nimport type { ToolNamespace } from \"../../core/extensions/tool-types.ts\";\nimport type { SessionEntry } from \"../../core/session-manager.ts\";\nimport { combineUsage } from \"../../core/usage-totals.ts\";\nimport { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from \"../tool-search/tool.js\";\nimport {\n\tCODEMODE_DOCS_PATH,\n\tCODEMODE_STORE_ENTRY_TYPE,\n\ttype CodemodeNestedCall,\n\ttype CodemodeToolDetails,\n\ttype CodemodeToolInput,\n\ttype CodemodeToolOptions,\n\tgetCodemodeCallableTools,\n\ttoCodemodeDeclaration,\n} from \"./tool.js\";\n\nexport function readCodemodeStore(branch: readonly SessionEntry[]): Record<string, unknown> {\n\tconst store = new Map<string, unknown>();\n\tfor (const entry of branch) {\n\t\tif (\n\t\t\tentry.type !== \"custom\" ||\n\t\t\tentry.customType !== CODEMODE_STORE_ENTRY_TYPE ||\n\t\t\ttypeof entry.data !== \"object\" ||\n\t\t\tentry.data === null\n\t\t)\n\t\t\tcontinue;\n\t\tconst data = entry.data as { set?: Record<string, unknown>; delete?: string[] };\n\t\tif (\n\t\t\t!data.set ||\n\t\t\ttypeof data.set !== \"object\" ||\n\t\t\t!Array.isArray(data.delete) ||\n\t\t\t!data.delete.every((key) => typeof key === \"string\")\n\t\t)\n\t\t\tcontinue;\n\t\tfor (const key of data.delete) store.delete(key);\n\t\tfor (const [key, value] of Object.entries(data.set)) store.set(key, value);\n\t}\n\treturn Object.fromEntries(store);\n}\nfunction textOf(result: AgentToolResult<unknown>): string {\n\treturn result.content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n/** Explicit public catalog fields. Provider configuration and credential-bearing URLs never cross into the VM. */\nexport function toCodemodeModelInfo(model: AnyModel): Record<string, unknown> {\n\treturn {\n\t\ttype: model.type,\n\t\tprovider: model.provider,\n\t\tid: model.id,\n\t\tname: model.name,\n\t\tapi: model.api,\n\t\tinput: model.input,\n\t\t...(\"reasoning\" in model ? { reasoning: model.reasoning } : {}),\n\t\t...(\"contextWindow\" in model ? { contextWindow: model.contextWindow } : {}),\n\t\t...(\"maxTokens\" in model ? { maxTokens: model.maxTokens } : {}),\n\t\tcost: model.cost,\n\t};\n}\nconst MODEL_TYPES = [\"chat\", \"image\", \"classifier\"] as const;\nfunction modelType(value: unknown): ModelType {\n\tif (value === \"chat\" || value === \"image\" || value === \"classifier\") return value;\n\tthrow new Error('Model type must be \"chat\", \"image\", or \"classifier\"');\n}\nfunction withArticle(word: string): string {\n\treturn `${/^[aeiou]/.test(word) ? \"an\" : \"a\"} ${word}`;\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction describeValue(value: unknown): string {\n\tif (value === undefined || value === null) return String(value);\n\tif (Array.isArray(value)) return value.length === 0 ? \"an empty array\" : \"an array\";\n\tif (typeof value === \"object\") {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{ ${keys.slice(0, 6).join(\", \")}${keys.length > 6 ? \", ...\" : \"\"} }`;\n\t}\n\treturn typeof value === \"string\" ? \"a string\" : `a ${typeof value}`;\n}\nconst CLASSIFIER_CONTEXT_SHAPE =\n\t'{ state: { ... }, questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';\nfunction checkClassifierContext(context: unknown): ClassifierContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See \"Classify\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tif (!isRecord(context.state)) throw fail(`context.state must be an object, got ${describeValue(context.state)}`);\n\tconst { questions } = context;\n\tif (!isRecord(questions) || Object.keys(questions).length === 0)\n\t\tthrow fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);\n\tconst isStrings = (values: unknown[]) => values.length > 0 && values.every((value) => typeof value === \"string\");\n\tfor (const [questionId, question] of Object.entries(questions)) {\n\t\tconst at = `context.questions.${questionId}`;\n\t\tif (!isRecord(question)) throw fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\tif (typeof question.instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tconst { criteria } = question;\n\t\tif (question.type === \"choice\") {\n\t\t\tif (!isRecord(criteria) || !isStrings(Object.values(criteria)))\n\t\t\t\tthrow fail(`${at} is a \"choice\" question, so criteria must map each label to its meaning`);\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (!Array.isArray(criteria) || !isStrings(criteria))\n\t\t\t\tthrow fail(`${at} is a \"score\" question, so criteria must list the levels as strings, lowest first`);\n\t\t} else if (question.type === \"bool\") {\n\t\t\tif (!isRecord(criteria) || typeof criteria.true !== \"string\" || typeof criteria.false !== \"string\")\n\t\t\t\tthrow fail(`${at} is a \"bool\" question, so criteria must be { true: string, false: string }`);\n\t\t} else {\n\t\t\tthrow fail(`${at}.type must be \"choice\", \"score\", or \"bool\", got ${JSON.stringify(question.type)}`);\n\t\t}\n\t}\n\treturn context as unknown as ClassifierContext;\n}\nfunction checkImagesContext(context: unknown): ImagesContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.generateImages() ${problem}. Expected context: { input: [{ type: \"text\", text: <prompt> }, ...optional { type: \"image\", data: <base64>, mimeType } references] }. See \"Generate images\" in ${CODEMODE_DOCS_PATH}.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tconst { input } = context;\n\tif (!Array.isArray(input) || input.length === 0)\n\t\tthrow fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);\n\tinput.forEach((block: unknown, index) => {\n\t\tif (isRecord(block) && block.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (\n\t\t\tisRecord(block) &&\n\t\t\tblock.type === \"image\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t)\n\t\t\treturn;\n\t\tthrow fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);\n\t});\n\treturn context as unknown as ImagesContext;\n}\nfunction provider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value === \"string\") return value;\n\tthrow new Error(\"provider must be a string\");\n}\nfunction preview(args: unknown): string {\n\ttry {\n\t\treturn (JSON.stringify(args) ?? \"\").slice(0, 200);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\ninterface ModelCallResult {\n\tstopReason: \"stop\" | \"error\" | \"aborted\";\n\terrorMessage?: string;\n\tusage?: Usage;\n}\nfunction createLimiter(limit: number) {\n\tlet active = 0;\n\tconst waiting: (() => void)[] = [];\n\treturn async <T>(run: () => Promise<T>): Promise<T> => {\n\t\tif (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));\n\t\tactive++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} finally {\n\t\t\tactive--;\n\t\t\twaiting.shift()?.();\n\t\t}\n\t};\n}\nfunction discoveryGlobals(\n\ttools: readonly AgentTool[],\n\tsamples: ReadonlyMap<string, string>,\n\toptions: CodemodeToolOptions,\n): CodemodeTool[] {\n\tconst entry = (name: string) => ({ name: toCodemodeIdentifier(name), description: samples.get(name) ?? \"\" });\n\treturn [\n\t\t{\n\t\t\tname: \"searchTools\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [query, config] = args as [unknown, { limit?: unknown; namespace?: unknown } | undefined];\n\t\t\t\tif (typeof query !== \"string\") throw new Error(\"searchTools() expects a query string\");\n\t\t\t\tconst limit = config?.limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\t\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0)\n\t\t\t\t\tthrow new Error(\"searchTools() limit must be a positive integer\");\n\t\t\t\tif (config?.namespace !== undefined && typeof config.namespace !== \"string\")\n\t\t\t\t\tthrow new Error(\"searchTools() namespace must be a string\");\n\t\t\t\tconst docs = tools.flatMap((tool) => {\n\t\t\t\t\tconst namespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\treturn config?.namespace && namespace?.name !== config.namespace\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: [createToolSearchDocument(tool, namespace)];\n\t\t\t\t});\n\t\t\t\treturn new Bm25Ranker().rank(query, docs, limit).map((match) => entry(match.name));\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeTool\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeTool() expects a tool name\");\n\t\t\t\tconst tool = tools.find((tool) => tool.name === name || toCodemodeIdentifier(tool.name) === name);\n\t\t\t\treturn tool ? samples.get(tool.name) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"describeNamespace\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [name] = args as unknown[];\n\t\t\t\tif (typeof name !== \"string\") throw new Error(\"describeNamespace() expects a namespace name\");\n\t\t\t\tlet namespace: ToolNamespace | undefined;\n\t\t\t\tconst names: string[] = [];\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tconst toolNamespace = options.getToolNamespace?.(tool.name);\n\t\t\t\t\tif (toolNamespace?.name !== name) continue;\n\t\t\t\t\tnamespace ??= toolNamespace;\n\t\t\t\t\tnames.push(toCodemodeIdentifier(tool.name));\n\t\t\t\t}\n\t\t\t\tif (!namespace) return undefined;\n\t\t\t\treturn {\n\t\t\t\t\tname,\n\t\t\t\t\t...(namespace.description ? { description: namespace.description } : {}),\n\t\t\t\t\t...(namespace.instructions ? { instructions: namespace.instructions } : {}),\n\t\t\t\t\ttools: names,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\nfunction modelGlobals(\n\tctx: ExtensionToolContext,\n\tid: string,\n\tcalls: CodemodeNestedCall[],\n\tpublish: () => void,\n\taddUsage: (usage: Usage) => void,\n\taddGeneratedImages: (count: number) => void,\n): CodemodeTool[] {\n\tconst models = ctx.modelRegistry;\n\tconst limit = createLimiter(4);\n\tlet count = 0;\n\tconst runModelCall = async <TType extends \"classifier\" | \"image\", TContext, TResult extends ModelCallResult>(\n\t\tname: string,\n\t\ttype: TType,\n\t\t[ref, context]: unknown[],\n\t\tcheckContext: (context: unknown) => TContext,\n\t\trun: (model: ModelTypeMap[TType], context: TContext) => Promise<TResult>,\n\t): Promise<TResult> => {\n\t\tconst listHint = `List the ${type} models you can use with models.getAvailableOfType(\"${type}\").`;\n\t\tif (!isRecord(ref) || typeof ref.provider !== \"string\" || typeof ref.id !== \"string\") {\n\t\t\tconst undefinedHint =\n\t\t\t\tref === undefined || ref === null\n\t\t\t\t\t? \" models.getModelOfType() returns undefined for an unknown provider or id.\"\n\t\t\t\t\t: \"\";\n\t\t\tthrow new Error(\n\t\t\t\t`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(ref)}.${undefinedHint} ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst { provider: providerId, id: modelId } = ref;\n\t\tconst model = models.getModelOfType(type, providerId, modelId);\n\t\tif (!model) {\n\t\t\tconst actualType = MODEL_TYPES.find(\n\t\t\t\t(other) => other !== type && models.getModelOfType(other, providerId, modelId) !== undefined,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\tactualType\n\t\t\t\t\t? `\"${providerId}/${modelId}\" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`\n\t\t\t\t\t: `Unknown ${type} model \"${providerId}/${modelId}\". ${listHint}`,\n\t\t\t);\n\t\t}\n\t\tconst checked = checkContext(context);\n\t\tconst record: CodemodeNestedCall = {\n\t\t\tid: `${id}/${name}/${++count}`,\n\t\t\tname,\n\t\t\targs: `${model.provider}/${model.id}`,\n\t\t\tstatus: \"running\",\n\t\t};\n\t\tcalls.push(record);\n\t\tpublish();\n\t\tconst start = performance.now();\n\t\tconst result = await limit(() => run(model, checked));\n\t\trecord.durationMs = performance.now() - start;\n\t\trecord.status = result.stopReason === \"stop\" ? \"ok\" : result.stopReason === \"aborted\" ? \"cancelled\" : \"error\";\n\t\tif (result.errorMessage) record.error = result.errorMessage.slice(0, 500);\n\t\tif (result.usage) {\n\t\t\trecord.cost = result.usage.cost.total;\n\t\t\taddUsage(result.usage);\n\t\t}\n\t\tpublish();\n\t\treturn result;\n\t};\n\treturn [\n\t\t{\n\t\t\tname: \"models.getModelsOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn models.getModelsOfType(modelType(type), provider(source)).map(toCodemodeModelInfo);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getAvailableOfType\",\n\t\t\tspread: true,\n\t\t\texecute: async (args, { signal }) => {\n\t\t\t\tconst [type, source] = args as unknown[];\n\t\t\t\treturn (await models.getAvailableOfType(modelType(type), provider(source), { signal })).map(\n\t\t\t\t\ttoCodemodeModelInfo,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.getModelOfType\",\n\t\t\tspread: true,\n\t\t\texecute: (args) => {\n\t\t\t\tconst [type, source, modelId] = args as unknown[];\n\t\t\t\tif (typeof source !== \"string\" || typeof modelId !== \"string\")\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`models.getModelOfType(type, provider, id) expects three strings, got (${(args as unknown[]).map(describeValue).join(\", \")}). The provider and the id are separate arguments, for example models.getModelOfType(\"classifier\", \"typesafe\", \"jev-latest\").`,\n\t\t\t\t\t);\n\t\t\t\tconst model = models.getModelOfType(modelType(type), source, modelId);\n\t\t\t\treturn model ? toCodemodeModelInfo(model) : undefined;\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"models.classify\",\n\t\t\tspread: true,\n\t\t\texecute: (args, { signal }) =>\n\t\t\t\trunModelCall(\"models.classify\", \"classifier\", args as unknown[], checkClassifierContext, (model, context) =>\n\t\t\t\t\tmodels.classify(model, context, { signal }),\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"models.generateImages\",\n\t\t\tspread: true,\n\t\t\texecute: (args, { signal }) =>\n\t\t\t\trunModelCall(\n\t\t\t\t\t\"models.generateImages\",\n\t\t\t\t\t\"image\",\n\t\t\t\t\targs as unknown[],\n\t\t\t\t\tcheckImagesContext,\n\t\t\t\t\tasync (model, context) => {\n\t\t\t\t\t\tconst result = await models.generateImages(model, context, { signal });\n\t\t\t\t\t\taddGeneratedImages(result.output.filter((block) => block.type === \"image\").length);\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t];\n}\n\nexport async function executeCodemode(\n\tid: string,\n\tinput: CodemodeToolInput,\n\tsignal: AbortSignal | undefined,\n\tupdate: ((result: AgentToolResult<CodemodeToolDetails>) => void) | undefined,\n\tctx: ExtensionToolContext | undefined,\n\toptions: CodemodeToolOptions = {},\n): Promise<AgentToolResult<CodemodeToolDetails>> {\n\tconst start = performance.now();\n\tconst { code, options: source } = parseCodemodeSource(input.code);\n\tconst calls: CodemodeNestedCall[] = [];\n\tlet usage: Usage | undefined;\n\tlet generatedImages = 0;\n\tconst snapshot = (): CodemodeToolDetails => ({ calls: calls.map((call) => ({ ...call })) });\n\tconst publish = () => update?.({ content: [], details: snapshot() });\n\tconst callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];\n\tconst samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool))]));\n\tconst sandbox = new CodemodeSandbox({\n\t\ttools: callable.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\tdescription: samples.get(tool.name),\n\t\t\texecute: async (args, { signal: callSignal }) => {\n\t\t\t\tconst record: CodemodeNestedCall = {\n\t\t\t\t\tid: `${id}/?`,\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\targs: preview(args),\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t};\n\t\t\t\tcalls.push(record);\n\t\t\t\tpublish();\n\t\t\t\tconst started = performance.now();\n\t\t\t\tif (!ctx) throw new Error(\"Tool calls need a session\");\n\t\t\t\tconst outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });\n\t\t\t\trecord.id = outcome.toolCall.id;\n\t\t\t\trecord.durationMs = performance.now() - started;\n\t\t\t\trecord.status = outcome.isError ? (callSignal.aborted ? \"cancelled\" : \"error\") : \"ok\";\n\t\t\t\tconst text = textOf(outcome.result);\n\t\t\t\tif (outcome.isError) record.error = (text || `Tool ${tool.name} failed`).slice(0, 500);\n\t\t\t\tpublish();\n\t\t\t\tif (tool.outputSchema && outcome.result.structuredContent !== undefined)\n\t\t\t\t\treturn outcome.result.structuredContent;\n\t\t\t\tif (outcome.isError) throw new Error(text || `Tool ${tool.name} failed`);\n\t\t\t\treturn text;\n\t\t\t},\n\t\t})),\n\t\tglobals: [\n\t\t\t...discoveryGlobals(callable, samples, options),\n\t\t\t...(options.models && ctx\n\t\t\t\t? modelGlobals(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tcalls,\n\t\t\t\t\t\tpublish,\n\t\t\t\t\t\t(extra) => {\n\t\t\t\t\t\t\tusage = usage ? combineUsage(usage, extra) : extra;\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(count) => {\n\t\t\t\t\t\t\tgeneratedImages += count;\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t: []),\n\t\t],\n\t\ttimeoutMs: source.timeoutMs ?? Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: 256 * 1024 * 1024,\n\t\twasm: loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: getCodemodeWorkerUrl(),\n\t});\n\tlet result: CodemodeResult;\n\ttry {\n\t\tresult = await sandbox.execute(code, {\n\t\t\tsignal,\n\t\t\tstore: ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {},\n\t\t});\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n\tfor (const call of calls) if (call.status === \"running\") call.status = \"cancelled\";\n\tlet content: (TextContent | ImageContent)[] = [...result.output];\n\tif (result.ok) {\n\t\tif (Object.keys(result.storeWrites.set).length || result.storeWrites.delete.length)\n\t\t\toptions.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, result.storeWrites);\n\t\tif (result.value !== undefined)\n\t\t\tcontent.push({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\ttypeof result.value === \"string\" ? result.value : (JSON.stringify(result.value) ?? String(result.value)),\n\t\t\t});\n\t} else\n\t\tcontent.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Script error:\\n${result.error.stack ?? result.error.message}\\n\\nTool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \") || \"none\"}`,\n\t\t});\n\tif (generatedImages > 0 && !content.some((block) => block.type === \"image\"))\n\t\tcontent.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? \"\" : \"s\"} that the script did not show. Show each image block of result.output with image(block).`,\n\t\t});\n\tconst text = content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tconst budget = (source.maxOutputTokens ?? 10_000) * 4;\n\tconst details = snapshot();\n\tif (text.length > budget) {\n\t\tconst path = join(tmpdir(), `atomic-codemode-${randomBytes(8).toString(\"hex\")}.txt`);\n\t\tlet notice: string;\n\t\ttry {\n\t\t\tawait writeFile(path, text);\n\t\t\tdetails.fullOutputPath = path;\n\t\t\tnotice = `Full output: ${path}`;\n\t\t} catch (error) {\n\t\t\tnotice = `Could not save full output: ${error instanceof Error ? error.message : String(error)}`;\n\t\t}\n\t\tconst head = Math.floor(budget / 2);\n\t\tconst tail = budget - head;\n\t\tcontent = [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Warning: truncated output (original token count: ${Math.ceil(text.length / 4)})\\n${text.slice(0, head)}\\n... output truncated ...\\n${tail ? text.slice(-tail) : \"\"}\\n${notice}`,\n\t\t\t},\n\t\t\t...content.filter((block) => block.type === \"image\"),\n\t\t];\n\t}\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${((performance.now() - start) / 1000).toFixed(1)} seconds\\nOutput:\\n`,\n\t\t\t},\n\t\t\t...content,\n\t\t],\n\t\tdetails,\n\t\t...(usage ? { usage } : {}),\n\t\t...(result.ok ? {} : { isError: true }),\n\t};\n}\n"]}
@@ -5,13 +5,14 @@ import type { ToolDefinition, ToolInfo, ToolNamespace } from "../../core/extensi
5
5
  import type { ModelRegistry } from "../../core/model-registry.ts";
6
6
  import type { CodemodeMode } from "../../core/settings-manager.ts";
7
7
  export declare const CODEMODE_TOOL_NAME = "codemode";
8
+ export declare const CODEMODE_DOCS_PATH: string;
8
9
  export declare const CODEMODE_STORE_ENTRY_TYPE = "codemode-store";
9
10
  export declare const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
10
11
  export interface CodemodeStoreEntryData {
11
12
  set: Record<string, unknown>;
12
13
  delete: string[];
13
14
  }
14
- export type CodemodeModelRuntime = Pick<ModelRegistry, "getModelsOfType" | "getAvailableOfType" | "getModelOfType" | "classify">;
15
+ export type CodemodeModelRuntime = Pick<ModelRegistry, "getModelsOfType" | "getAvailableOfType" | "getModelOfType" | "classify" | "generateImages">;
15
16
  export interface CodemodeToolOptions {
16
17
  getToolNamespace?: (name: string) => ToolNamespace | undefined;
17
18
  models?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,KAAK,EAAsB,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAGpF,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAe,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC3G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAInE,eAAO,MAAM,kBAAkB,aAAa,CAAC;AAC7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