zidane 8.2.3 → 8.2.5

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 (166) hide show
  1. package/dist/{acp-oYRjlh71.js → acp-BIInKhVI.js} +6 -6
  2. package/dist/{acp-oYRjlh71.js.map → acp-BIInKhVI.js.map} +1 -1
  3. package/dist/acp-cli.js +4 -4
  4. package/dist/acp.d.ts +2 -2
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-CBQglXtH.js → agent-CmhCOmyO.js} +10 -5
  7. package/dist/{agent-CBQglXtH.js.map → agent-CmhCOmyO.js.map} +1 -1
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/chat/pure.d.ts +4 -4
  11. package/dist/chat/pure.js +7 -7
  12. package/dist/chat.d.ts +3 -3
  13. package/dist/chat.js +16 -16
  14. package/dist/{cli-shared-E5m_pI8A.js → cli-shared-GOehTeqk.js} +2 -2
  15. package/dist/{cli-shared-E5m_pI8A.js.map → cli-shared-GOehTeqk.js.map} +1 -1
  16. package/dist/{client-core-EEEX_u6D.d.ts → client-core-Dz8hELs4.d.ts} +15 -5
  17. package/dist/client-core-Dz8hELs4.d.ts.map +1 -0
  18. package/dist/codemode-worker.js +1 -1
  19. package/dist/codemode.js +1 -1
  20. package/dist/{connection-loop-CpgfUmuw.d.ts → connection-loop-dm_TN-QD.d.ts} +3 -3
  21. package/dist/{connection-loop-CpgfUmuw.d.ts.map → connection-loop-dm_TN-QD.d.ts.map} +1 -1
  22. package/dist/contexts/daytona.d.ts +1 -1
  23. package/dist/contexts/e2b.d.ts +1 -1
  24. package/dist/{credentials-B9DfBJP9.js → credentials-DxOQmset.js} +2 -2
  25. package/dist/{credentials-B9DfBJP9.js.map → credentials-DxOQmset.js.map} +1 -1
  26. package/dist/daemon-cli.js +2 -2
  27. package/dist/{dispatcher-Bv9-c6I2.js → dispatcher-D_9_QFO3.js} +22 -18
  28. package/dist/dispatcher-D_9_QFO3.js.map +1 -0
  29. package/dist/{engine-XmoPPB6U.js → engine-BsWBWgTB.js} +6 -6
  30. package/dist/{engine-XmoPPB6U.js.map → engine-BsWBWgTB.js.map} +1 -1
  31. package/dist/{eval-CfQlBR81.js → eval-CIHIF_Ns.js} +3 -3
  32. package/dist/{eval-CfQlBR81.js.map → eval-CIHIF_Ns.js.map} +1 -1
  33. package/dist/eval.d.ts +1 -1
  34. package/dist/eval.js +1 -1
  35. package/dist/{executor-BhthPE1q.js → executor-BSesPPcU.js} +3 -3
  36. package/dist/{executor-BhthPE1q.js.map → executor-BSesPPcU.js.map} +1 -1
  37. package/dist/{extensions-BgBwogRW.js → extensions-BJof-2mi.js} +3 -3
  38. package/dist/{extensions-BgBwogRW.js.map → extensions-BJof-2mi.js.map} +1 -1
  39. package/dist/extensions.d.ts +1 -1
  40. package/dist/extensions.js +1 -1
  41. package/dist/{fold-rules-DSypi36k.d.ts → fold-rules-CMpWNPqk.d.ts} +2 -2
  42. package/dist/{fold-rules-DSypi36k.d.ts.map → fold-rules-CMpWNPqk.d.ts.map} +1 -1
  43. package/dist/{headless-R4pbpTkm.js → headless-Bs9Lb4vs.js} +4 -4
  44. package/dist/{headless-R4pbpTkm.js.map → headless-Bs9Lb4vs.js.map} +1 -1
  45. package/dist/headless.d.ts +1 -1
  46. package/dist/headless.js +1 -1
  47. package/dist/history-worker.js +1 -1
  48. package/dist/{host-scoped-settings-C-Nmb6vr.js → host-scoped-settings-DxxI_yRo.js} +2 -2
  49. package/dist/{host-scoped-settings-C-Nmb6vr.js.map → host-scoped-settings-DxxI_yRo.js.map} +1 -1
  50. package/dist/{host-signals-BFudPyCT.js → host-signals-CUKPZZxC.js} +5 -5
  51. package/dist/{host-signals-BFudPyCT.js.map → host-signals-CUKPZZxC.js.map} +1 -1
  52. package/dist/{index-DyQyDLX1.d.ts → index-4mDRyTGJ.d.ts} +1722 -1691
  53. package/dist/index-4mDRyTGJ.d.ts.map +1 -0
  54. package/dist/{index-CDS7YdUC.d.ts → index-Dlmu8HnG.d.ts} +5 -5
  55. package/dist/{index-CDS7YdUC.d.ts.map → index-Dlmu8HnG.d.ts.map} +1 -1
  56. package/dist/{index-AqRZ3gEz.d.ts → index-QsAN9yjZ.d.ts} +3 -3
  57. package/dist/{index-AqRZ3gEz.d.ts.map → index-QsAN9yjZ.d.ts.map} +1 -1
  58. package/dist/index.d.ts +3 -3
  59. package/dist/index.js +8 -8
  60. package/dist/ipc/remote.d.ts +5 -5
  61. package/dist/ipc/remote.js +3 -3
  62. package/dist/ipc.d.ts +5 -5
  63. package/dist/ipc.js +9 -9
  64. package/dist/{links-rFaWqS2Y.js → links-Bto-5dVu.js} +10 -10
  65. package/dist/{links-rFaWqS2Y.js.map → links-Bto-5dVu.js.map} +1 -1
  66. package/dist/{mcp-allowlist-CLXweyxk.js → mcp-allowlist-BbnTBKNN.js} +2 -2
  67. package/dist/{mcp-allowlist-CLXweyxk.js.map → mcp-allowlist-BbnTBKNN.js.map} +1 -1
  68. package/dist/mcp.d.ts +1 -1
  69. package/dist/{oauth-7_48zR7n.js → oauth-BwPiX0hL.js} +66 -32
  70. package/dist/oauth-BwPiX0hL.js.map +1 -0
  71. package/dist/output/stream-json.d.ts +1 -1
  72. package/dist/output/terminal.d.ts +1 -1
  73. package/dist/plugins.d.ts +1 -1
  74. package/dist/{prelude-HzY_JEGq.js → prelude-qjPUkw4f.js} +26 -2
  75. package/dist/prelude-qjPUkw4f.js.map +1 -0
  76. package/dist/{presets-DXeHsd24.js → presets-C4hkykN-.js} +2 -2
  77. package/dist/{presets-DXeHsd24.js.map → presets-C4hkykN-.js.map} +1 -1
  78. package/dist/presets.d.ts +1 -1
  79. package/dist/presets.js +1 -1
  80. package/dist/{protocol-BIv1Yuvl.js → protocol-Do_i6Ras.js} +3 -1
  81. package/dist/protocol-Do_i6Ras.js.map +1 -0
  82. package/dist/providers/anthropic.d.ts +1 -1
  83. package/dist/providers/arcee.d.ts +1 -1
  84. package/dist/providers/baseten.d.ts +1 -1
  85. package/dist/providers/cerebras.d.ts +1 -1
  86. package/dist/providers/google.d.ts +1 -1
  87. package/dist/providers/local.d.ts +1 -1
  88. package/dist/providers/neuralwatt.d.ts +1 -1
  89. package/dist/providers/openai-compat.d.ts +1 -1
  90. package/dist/providers/openai.d.ts +1 -1
  91. package/dist/providers/openrouter.d.ts +1 -1
  92. package/dist/providers/xai.d.ts +1 -1
  93. package/dist/providers.d.ts +1 -1
  94. package/dist/{registry-eourRLY2.js → registry-DxPP_tAt.js} +3 -3
  95. package/dist/{registry-eourRLY2.js.map → registry-DxPP_tAt.js.map} +1 -1
  96. package/dist/{remote-hosts-DY2J07ut.js → remote-hosts-DcCh7fqp.js} +4 -4
  97. package/dist/{remote-hosts-DY2J07ut.js.map → remote-hosts-DcCh7fqp.js.map} +1 -1
  98. package/dist/restate.d.ts +1 -1
  99. package/dist/{secret-shapes-BjW4l6U0.js → secret-shapes-HvaYVzwc.js} +10 -2
  100. package/dist/secret-shapes-HvaYVzwc.js.map +1 -0
  101. package/dist/session/sqlite.d.ts +1 -1
  102. package/dist/{session-7TUHs42_.js → session-CCsKXID6.js} +6 -2
  103. package/dist/session-CCsKXID6.js.map +1 -0
  104. package/dist/{session-factory-CMwIXE-7.js → session-factory-Ct7J9CK1.js} +6 -6
  105. package/dist/{session-factory-CMwIXE-7.js.map → session-factory-Ct7J9CK1.js.map} +1 -1
  106. package/dist/session.d.ts +2 -2
  107. package/dist/session.js +1 -1
  108. package/dist/{settings-keys-CPdmkTz7.js → settings-keys-CnrJgT1T.js} +4 -4
  109. package/dist/{settings-keys-CPdmkTz7.js.map → settings-keys-CnrJgT1T.js.map} +1 -1
  110. package/dist/{shell-path-B8b3EOtK.js → shell-path-rJDa0OMv.js} +4 -4
  111. package/dist/{shell-path-B8b3EOtK.js.map → shell-path-rJDa0OMv.js.map} +1 -1
  112. package/dist/skills.d.ts +1 -1
  113. package/dist/{spaces-CyjMh5Zf.js → spaces-C_x2bvEl.js} +14 -4
  114. package/dist/spaces-C_x2bvEl.js.map +1 -0
  115. package/dist/{store-L01W0gGI.js → store-BpkWIaSH.js} +10 -30
  116. package/dist/store-BpkWIaSH.js.map +1 -0
  117. package/dist/{todo-edits-BERpCRPj.js → todo-edits-DKoxu7Ss.js} +3 -3
  118. package/dist/{todo-edits-BERpCRPj.js.map → todo-edits-DKoxu7Ss.js.map} +1 -1
  119. package/dist/tools/fetch-url.d.ts +1 -1
  120. package/dist/tools/web-search.d.ts +1 -1
  121. package/dist/{tools-pZVFIJ_K.js → tools-FHEIKGkh.js} +2 -2
  122. package/dist/{tools-pZVFIJ_K.js.map → tools-FHEIKGkh.js.map} +1 -1
  123. package/dist/tools.d.ts +1 -1
  124. package/dist/tools.js +2 -2
  125. package/dist/{transcript-anchors-jHrg-r-H.js → transcript-anchors-BcFLh3ZA.js} +10 -10
  126. package/dist/{transcript-anchors-jHrg-r-H.js.map → transcript-anchors-BcFLh3ZA.js.map} +1 -1
  127. package/dist/{transcript-cache-DXdgVuoy.js → transcript-cache-CdHKtx9y.js} +4 -4
  128. package/dist/{transcript-cache-DXdgVuoy.js.map → transcript-cache-CdHKtx9y.js.map} +1 -1
  129. package/dist/{transcript-reconcile-CPdrNbbR.js → transcript-reconcile-D_SWw6dX.js} +11 -3
  130. package/dist/transcript-reconcile-D_SWw6dX.js.map +1 -0
  131. package/dist/tui.d.ts +7 -7
  132. package/dist/tui.js +24 -23
  133. package/dist/tui.js.map +1 -1
  134. package/dist/{turn-operations-DuGtKuc_.d.ts → turn-operations-Dbk3xPKu.d.ts} +11 -3
  135. package/dist/{turn-operations-DuGtKuc_.d.ts.map → turn-operations-Dbk3xPKu.d.ts.map} +1 -1
  136. package/dist/{types-C0PJmBaO.d.ts → types-CMXR7A0b.d.ts} +2 -2
  137. package/dist/{types-C0PJmBaO.d.ts.map → types-CMXR7A0b.d.ts.map} +1 -1
  138. package/dist/types-CzmghX7C.js.map +1 -1
  139. package/dist/types.d.ts +2 -2
  140. package/dist/{url-D8KZ7Edw.js → url-D4vG7lzO.js} +2 -2
  141. package/dist/{url-D8KZ7Edw.js.map → url-D4vG7lzO.js.map} +1 -1
  142. package/dist/{version-bd3DQJkc.js → version-DOvIuU8M.js} +2 -2
  143. package/dist/{version-bd3DQJkc.js.map → version-DOvIuU8M.js.map} +1 -1
  144. package/dist/{workspace-exec-stream-CyfYgqAh.js → workspace-exec-stream-Bzxczzu2.js} +5 -5
  145. package/dist/{workspace-exec-stream-CyfYgqAh.js.map → workspace-exec-stream-Bzxczzu2.js.map} +1 -1
  146. package/dist/{write-file-QYrcDdl3.js → write-file-ChtRPdEL.js} +3 -3
  147. package/dist/{write-file-QYrcDdl3.js.map → write-file-ChtRPdEL.js.map} +1 -1
  148. package/dist/{ws-CURQ2igk.js → ws-CrD-4Mx6.js} +6 -6
  149. package/dist/{ws-CURQ2igk.js.map → ws-CrD-4Mx6.js.map} +1 -1
  150. package/dist/{ws-client-BVljYbdb.js → ws-client-Dond8vT3.js} +4 -4
  151. package/dist/{ws-client-BVljYbdb.js.map → ws-client-Dond8vT3.js.map} +1 -1
  152. package/docs/CODEMODE.md +6 -0
  153. package/docs/IPC.md +2 -0
  154. package/docs/ONBOARDING.md +1 -1
  155. package/package.json +1 -1
  156. package/dist/client-core-EEEX_u6D.d.ts.map +0 -1
  157. package/dist/dispatcher-Bv9-c6I2.js.map +0 -1
  158. package/dist/index-DyQyDLX1.d.ts.map +0 -1
  159. package/dist/oauth-7_48zR7n.js.map +0 -1
  160. package/dist/prelude-HzY_JEGq.js.map +0 -1
  161. package/dist/protocol-BIv1Yuvl.js.map +0 -1
  162. package/dist/secret-shapes-BjW4l6U0.js.map +0 -1
  163. package/dist/session-7TUHs42_.js.map +0 -1
  164. package/dist/spaces-CyjMh5Zf.js.map +0 -1
  165. package/dist/store-L01W0gGI.js.map +0 -1
  166. package/dist/transcript-reconcile-CPdrNbbR.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { QT as ToolDef } from "../index-DyQyDLX1.js";
1
+ import { $T as ToolDef } from "../index-4mDRyTGJ.js";
2
2
  //#region src/tools/fetch-url.d.ts
3
3
  /**
4
4
  * Tells whether an IP address is in a range the SSRF guard refuses: loopback, private, link-local, multicast and similar. Anything that is not an IP literal is refused too.
@@ -1,4 +1,4 @@
1
- import { QT as ToolDef } from "../index-DyQyDLX1.js";
1
+ import { $T as ToolDef } from "../index-4mDRyTGJ.js";
2
2
  //#region src/tools/web-search.d.ts
3
3
  /**
4
4
  * The `web_search` tool. Searches the web through the configured backend and returns titles, URLs and snippets.
@@ -6,7 +6,7 @@ import { c as pathArgError } from "./wait-task-BZiNOAcc.js";
6
6
  import { c as imageSizeFromBase64, s as shrinkImageBase64 } from "./skills-use-CssTEaIj.js";
7
7
  import { toolPrompts } from "./tools/prompts.js";
8
8
  import { n as isToolFailure, t as ToolFailure } from "./failure-_rDKdaLk.js";
9
- import { a as readFileAsBase64, i as imageMediaTypeFor } from "./write-file-QYrcDdl3.js";
9
+ import { a as readFileAsBase64, i as imageMediaTypeFor } from "./write-file-ChtRPdEL.js";
10
10
  import { t as IMAGE_ASPECT_RATIOS } from "./types-JzccL5GE.js";
11
11
  import { Buffer } from "node:buffer";
12
12
  import { isAbsolute, relative, resolve } from "node:path";
@@ -861,4 +861,4 @@ function createInteractionTool(options) {
861
861
  //#endregion
862
862
  export { createGenerateImageTool as a, DEFAULT_IMAGE_DIR as i, grep as n, glob as r, createInteractionTool as t };
863
863
 
864
- //# sourceMappingURL=tools-pZVFIJ_K.js.map
864
+ //# sourceMappingURL=tools-FHEIKGkh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tools-pZVFIJ_K.js","names":[],"sources":["../src/tools/generate-image.ts","../src/tools/glob.ts","../src/tools/grep.ts","../src/tools/interaction.ts"],"sourcesContent":["/**\n * `generate_image`: text to image (or image to image) with any image model\n * of the providers the run can reach (`Provider.images`).\n *\n * The tool saves full-size files into the workspace, writes a `<file>.json`\n * record next to each one (prompt, provider, model, date, cost) so an asset's origin\n * stays on disk, and returns the paths plus a preview capped at\n * {@link PREVIEW_EDGE} px. The preview is what the model sees and what the\n * transcript shows; the file keeps the full resolution.\n *\n * The description lists up to {@link LISTED_MODELS} models so the model can\n * pick one without a round trip; `list: true` returns all of them.\n */\n\nimport type { ImageAspectRatio, ImageData, ImageModelInfo, ProviderImageResponse, ProviderImages } from '../providers/images'\nimport type { ToolResultContent } from '../types'\nimport type { ToolContext, ToolDef } from './types'\nimport { Buffer } from 'node:buffer'\nimport { randomBytes } from 'node:crypto'\nimport { isAbsolute, relative, resolve } from 'node:path'\nimport { errorMessage, isAbortLikeError } from '../errors'\nimport { imageSizeFromBase64 } from '../media/image-size'\nimport { shrinkImageBase64 } from '../media/png-downscale'\nimport { IMAGE_ASPECT_RATIOS, MAX_IMAGES_PER_REQUEST } from '../providers/images'\nimport { imageMediaTypeFor, readFileAsBase64 } from './binary-read'\nimport { ToolFailure } from './failure'\nimport { reconcileImageMediaType } from './media-sniff'\nimport { toolPrompts } from './prompts'\nimport { pathArgError } from './validation'\n\n/** Longest edge of the preview returned to the model, in px. */\nexport const PREVIEW_EDGE = 768\n\n/** Models named in the tool description; the rest are behind `list: true`. */\nexport const LISTED_MODELS = 15\n\n/** Folder for images saved without a `path`. */\nexport const DEFAULT_IMAGE_DIR = 'generated-images'\n\n/** Most reference images one call takes. */\nconst MAX_REFERENCES = 8\n\n/** Largest reference image, in bytes. Image APIs cap uploads near this size. */\nconst MAX_REFERENCE_BYTES = 20 * 1024 * 1024\n\n/** A provider the tool can generate with. */\nexport interface ImageModelSource {\n /** Provider name as the `model` argument spells it: `<provider>/<model id>`. */\n provider: string\n /** Display name of the provider, for the model list. */\n label?: string\n /** The provider's image endpoint. */\n images: ProviderImages\n}\n\n/** Options for {@link createGenerateImageTool}. */\nexport interface GenerateImageToolOptions {\n /**\n * Providers to generate with. Omitted: the run's providers that have an\n * available image endpoint (`ToolContext.providers`, else `provider`).\n */\n sources?: readonly ImageModelSource[]\n /** Model used when a call names none, as `<provider>/<model id>`. Default: the first source's default model. */\n defaultModel?: string\n}\n\n/** One model of one source. */\ninterface ModelEntry {\n source: ImageModelSource\n model: ImageModelInfo\n /** `<provider>/<model id>`. */\n ref: string\n}\n\nfunction entriesOf(sources: readonly ImageModelSource[]): ModelEntry[] {\n return sources.flatMap(source => source.images.models.map(model => ({ source, model, ref: `${source.provider}/${model.id}` })))\n}\n\nfunction sourcesFromContext(ctx: ToolContext): ImageModelSource[] {\n const providers = ctx.providers?.length ? ctx.providers : [ctx.provider]\n return providers.flatMap((provider) => {\n const images = provider.images\n return images && images.availability().available ? [{ provider: provider.name, images }] : []\n })\n}\n\n/** The entry `ref` names: an exact `<provider>/<id>`, else a model id only one source serves. */\nfunction findEntry(entries: readonly ModelEntry[], ref: string): ModelEntry | undefined {\n const exact = entries.find(e => e.ref === ref)\n if (exact)\n return exact\n const byId = entries.filter(e => e.model.id === ref)\n return byId.length === 1 ? byId[0] : undefined\n}\n\nfunction defaultEntry(entries: readonly ModelEntry[], sources: readonly ImageModelSource[], configured: string | undefined): ModelEntry | undefined {\n const picked = configured ? findEntry(entries, configured) : undefined\n if (picked)\n return picked\n const first = sources[0]\n return first ? findEntry(entries, `${first.provider}/${first.images.defaultModel}`) ?? entries[0] : undefined\n}\n\n/** One line per model: `provider/id · name · [ref] [alpha]`, `(default)` on the default one. */\nfunction modelLine(entry: ModelEntry, isDefault: boolean): string {\n const parts = [entry.ref]\n if (entry.model.name && entry.model.name !== entry.model.id)\n parts.push(entry.model.name)\n const flags = [\n ...(entry.model.input.includes('image') ? ['[ref]'] : []),\n ...(entry.model.transparency ? ['[alpha]'] : []),\n ...(isDefault ? ['(default)'] : []),\n ]\n return `- ${parts.join(' · ')}${flags.length ? ` ${flags.join(' ')}` : ''}`\n}\n\nfunction describeModels(entries: readonly ModelEntry[], def: ModelEntry | undefined): string {\n if (entries.length === 0)\n return 'Call with `list: true` to see the image models of the connected providers.'\n // The default first, then in source order.\n const ordered = def ? [def, ...entries.filter(e => e !== def)] : [...entries]\n const shown = ordered.slice(0, LISTED_MODELS)\n const lines = [\n 'Models (`model` argument; [ref]: takes reference images, [alpha]: transparent background):',\n ...shown.map(e => modelLine(e, e === def)),\n ]\n if (ordered.length > shown.length)\n lines.push(`Call with \\`list: true\\` for all ${ordered.length} models.`)\n return lines.join('\\n')\n}\n\nconst EXTENSION_BY_TYPE: Readonly<Record<string, string>> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n}\n\n/** A file-name stem from the first words of the prompt: `snowy-pine-forest-texture`. */\nfunction slugOf(prompt: string): string {\n const slug = prompt.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim().split(' ').slice(0, 6).join('-')\n return slug || 'image'\n}\n\n/**\n * `YYYYMMDD-HHMMSS-xxxx` of `now`; the random tail keeps two calls with the\n * same prompt in the same second (parallel tool calls) from overwriting each other.\n */\nfunction timeStamp(now: Date): string {\n const pad = (n: number) => String(n).padStart(2, '0')\n const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`\n const time = [now.getHours(), now.getMinutes(), now.getSeconds()].map(pad).join('')\n return `${date}-${time}-${randomBytes(2).toString('hex')}`\n}\n\n/** The record next to an image: the image's full name plus `.json`, so it never lands on a project file like `package.json`. */\nfunction recordPathOf(file: string): string {\n return `${file}.json`\n}\n\n/** `path` without an image extension, or the default stem when absent. */\nfunction stemOf(path: string | undefined, prompt: string, now: Date): string {\n if (!path)\n return `${DEFAULT_IMAGE_DIR}/${slugOf(prompt)}-${timeStamp(now)}`\n return imageMediaTypeFor(path) ? path.slice(0, path.lastIndexOf('.')) : path\n}\n\n/** The workspace-relative `path`, or a failure when it leaves the working directory. */\nfunction confinedPath(ctx: ToolContext, path: string, field: string): string {\n const err = pathArgError(path, field)\n if (err)\n throw new ToolFailure(`generate_image error: ${err}`)\n const cwd = ctx.handle.cwd\n const rel = relative(cwd, resolve(cwd, path))\n if (rel === '' || rel.startsWith('..') || isAbsolute(rel))\n throw new ToolFailure(`generate_image error: \\`${field}\\` must be a file inside the working directory (${cwd}), got \"${path}\".`)\n return rel\n}\n\nasync function readReference(ctx: ToolContext, path: string): Promise<ImageData> {\n const rel = confinedPath(ctx, path, 'references')\n const extMedia = imageMediaTypeFor(rel)\n if (!extMedia)\n throw new ToolFailure(`generate_image error: reference \"${path}\" is not a PNG, JPEG, WebP or GIF file.`)\n const size = await ctx.execution.fileSize?.(ctx.handle, rel) ?? null\n if (size !== null && size > MAX_REFERENCE_BYTES)\n throw new ToolFailure(`generate_image error: reference \"${path}\" is ${size} bytes; the limit is ${MAX_REFERENCE_BYTES}.`)\n try {\n const { base64 } = await readFileAsBase64(ctx.execution, ctx.handle, rel)\n return { data: base64, mediaType: reconcileImageMediaType(extMedia, base64) }\n }\n catch (err) {\n throw new ToolFailure(`generate_image error: cannot read reference \"${path}\": ${errorMessage(err)}`)\n }\n}\n\nfunction listText(entries: readonly ModelEntry[], def: ModelEntry | undefined): string {\n if (entries.length === 0)\n return 'No image models are available. Connect a provider with image generation (OpenRouter, OpenAI with a platform key, Google Gemini or xAI) in the provider settings.'\n const ordered = def ? [def, ...entries.filter(e => e !== def)] : entries\n return [`${entries.length} image model${entries.length === 1 ? '' : 's'}:`, ...ordered.map(e => modelLine(e, e === def))].join('\\n')\n}\n\nfunction formatCost(usd: number): string {\n return usd < 0.01 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`\n}\n\n/**\n * Build the `generate_image` tool.\n *\n * @param options - Providers to generate with and the default model.\n */\nexport function createGenerateImageTool(options: GenerateImageToolOptions = {}): ToolDef {\n const fixedSources = options.sources\n const fixedEntries = fixedSources ? entriesOf(fixedSources) : []\n const fixedDefault = fixedSources ? defaultEntry(fixedEntries, fixedSources, options.defaultModel) : undefined\n\n return {\n spec: {\n name: 'generate_image',\n description: `${toolPrompts.generate_image}\\n\\n${describeModels(fixedEntries, fixedDefault)}`,\n inputSchema: {\n type: 'object',\n properties: {\n prompt: {\n type: 'string',\n description: 'What to draw: subject, style, colors, lighting, framing. For an edit, what to change.',\n },\n model: {\n type: 'string',\n description: 'Image model as `<provider>/<model id>` from the list. Omit to use the default.',\n },\n path: {\n type: 'string',\n description: `Where to save, relative to the working directory, for example \\`assets/textures/snow.png\\`. The extension follows the format the model returns. Several images get \\`-1\\`, \\`-2\\` suffixes. Omit to save under \\`${DEFAULT_IMAGE_DIR}/\\`.`,\n },\n aspect_ratio: {\n type: 'string',\n enum: [...IMAGE_ASPECT_RATIOS],\n description: 'Shape of the image. Omit to let the model choose (usually square).',\n },\n n: {\n type: 'number',\n description: `How many variations to generate, 1 to ${MAX_IMAGES_PER_REQUEST}. Default 1. Each one costs.`,\n },\n references: {\n type: 'array',\n items: { type: 'string' },\n description: `Workspace image paths to edit or to match the style of, up to ${MAX_REFERENCES}. Only for models marked [ref].`,\n },\n transparent: {\n type: 'boolean',\n description: 'Ask for a transparent background (sprites, icons). Only for models marked [alpha].',\n },\n list: {\n type: 'boolean',\n description: 'List every available image model and generate nothing.',\n },\n },\n },\n },\n async execute(input, ctx): Promise<string | ToolResultContent[]> {\n const sources = fixedSources ?? sourcesFromContext(ctx)\n const entries = fixedSources ? fixedEntries : entriesOf(sources)\n const def = fixedSources ? fixedDefault : defaultEntry(entries, sources, options.defaultModel)\n\n if (input.list === true)\n return listText(entries, def)\n\n const prompt = typeof input.prompt === 'string' ? input.prompt.trim() : ''\n if (!prompt)\n throw new ToolFailure('generate_image error: `prompt` is required.')\n if (entries.length === 0)\n throw new ToolFailure(`generate_image error: ${listText(entries, def)}`)\n\n const requested = typeof input.model === 'string' && input.model.trim() ? input.model.trim() : undefined\n const entry = requested ? findEntry(entries, requested) : def\n if (!entry) {\n throw new ToolFailure(`generate_image error: unknown model \"${requested}\". Use \\`<provider>/<model id>\\`:\\n${listText(entries, def)}`)\n }\n\n const aspectRatio = typeof input.aspect_ratio === 'string' ? input.aspect_ratio as ImageAspectRatio : undefined\n if (aspectRatio && !IMAGE_ASPECT_RATIOS.includes(aspectRatio))\n throw new ToolFailure(`generate_image error: \\`aspect_ratio\\` must be one of ${IMAGE_ASPECT_RATIOS.join(', ')}.`)\n const count = typeof input.n === 'number' && Number.isFinite(input.n) ? Math.floor(input.n) : 1\n if (count < 1 || count > MAX_IMAGES_PER_REQUEST)\n throw new ToolFailure(`generate_image error: \\`n\\` must be from 1 to ${MAX_IMAGES_PER_REQUEST}.`)\n const transparent = input.transparent === true\n if (transparent && !entry.model.transparency) {\n const capable = entries.filter(e => e.model.transparency).map(e => e.ref)\n throw new ToolFailure(`generate_image error: ${entry.ref} cannot make a transparent background.${capable.length ? ` Models that can: ${capable.join(', ')}.` : ''}`)\n }\n\n const referencePaths = Array.isArray(input.references) ? input.references.filter((p): p is string => typeof p === 'string' && p.trim() !== '') : []\n if (referencePaths.length > 0 && !entry.model.input.includes('image'))\n throw new ToolFailure(`generate_image error: ${entry.ref} does not take reference images. Pick a model marked [ref].`)\n if (referencePaths.length > MAX_REFERENCES)\n throw new ToolFailure(`generate_image error: at most ${MAX_REFERENCES} references per call.`)\n\n const now = new Date()\n const pathArg = typeof input.path === 'string' && input.path.trim() ? input.path.trim() : undefined\n const stem = stemOf(pathArg ? confinedPath(ctx, pathArg, 'path') : undefined, prompt, now)\n const references = await Promise.all(referencePaths.map(p => readReference(ctx, p)))\n\n const started = Date.now()\n let response: ProviderImageResponse\n try {\n response = await entry.source.images.generate({\n model: entry.model.id,\n prompt,\n ...(references.length ? { references } : {}),\n ...(aspectRatio ? { aspectRatio } : {}),\n count,\n ...(transparent ? { transparent } : {}),\n }, ctx.signal)\n }\n catch (err) {\n if (isAbortLikeError(err) || ctx.signal.aborted)\n throw err\n throw new ToolFailure(`generate_image error (${entry.ref}): ${errorMessage(err)}`)\n }\n const seconds = (Date.now() - started) / 1000\n\n const images = response.images.slice(0, count)\n const saved: string[] = []\n for (const [i, image] of images.entries()) {\n const ext = EXTENSION_BY_TYPE[image.mediaType] ?? 'png'\n const file = `${stem}${images.length > 1 ? `-${i + 1}` : ''}.${ext}`\n const record = {\n prompt,\n provider: entry.source.provider,\n model: response.model || entry.model.id,\n ...(aspectRatio ? { aspectRatio } : {}),\n ...(transparent ? { transparent } : {}),\n ...(referencePaths.length ? { references: referencePaths } : {}),\n ...(response.costUsd !== undefined ? { costUsd: response.costUsd / images.length } : {}),\n createdAt: now.toISOString(),\n }\n try {\n await ctx.execution.writeFile(ctx.handle, file, Buffer.from(image.data, 'base64'))\n await ctx.execution.writeFile(ctx.handle, recordPathOf(file), `${JSON.stringify(record, null, 2)}\\n`)\n }\n catch (err) {\n throw new ToolFailure(`generate_image error: the image was generated but saving ${file} failed: ${errorMessage(err)}`)\n }\n saved.push(file)\n }\n\n const sizes = images.map((image) => {\n const size = imageSizeFromBase64(image.data)\n return size ? `${size.width}x${size.height}` : image.mediaType\n })\n const lines = [\n `Generated ${images.length} image${images.length === 1 ? '' : 's'} with ${entry.ref} in ${seconds.toFixed(1)} s.`,\n ...saved.map((file, i) => `Saved: ${file} (${sizes[i]})`),\n `Records: ${saved.map(recordPathOf).join(', ')}`,\n ...(response.costUsd !== undefined ? [`Cost: ${formatCost(response.costUsd)}`] : []),\n ...(response.text ? [`Model note: ${response.text}`] : []),\n ]\n const previews: ToolResultContent[] = images.map((image) => {\n const shrunk = shrinkImageBase64(image.data, image.mediaType, PREVIEW_EDGE)\n return { type: 'image', mediaType: shrunk?.mediaType ?? image.mediaType, data: shrunk?.data ?? image.data }\n })\n return [{ type: 'text', text: lines.join('\\n') }, ...previews]\n },\n }\n}\n","import type { ListFileMetadata, ListFilesEntry } from '../contexts'\nimport type { ToolContext, ToolDef } from './types'\nimport { errorMessage, isAbortLikeError } from '../errors'\nimport { ToolFailure } from './failure'\nimport { toolPrompts } from './prompts'\n\n/** Default cap on returned matches. A `limit` argument overrides it. */\nconst DEFAULT_LIMIT = 1000\n\n/** Backstop so a pathological walk can never hang the agent's turn. */\nconst GLOB_TIMEOUT_MS = 20_000\n\nfunction entryPath(entry: ListFilesEntry): string {\n return typeof entry === 'string' ? entry : entry.path\n}\n\nfunction entryMetadata(entry: ListFilesEntry): ListFileMetadata | undefined {\n return typeof entry === 'string' ? undefined : entry\n}\n\nfunction renderEntry(entry: ListFilesEntry, wantMetadata: boolean): string {\n const path = entryPath(entry)\n const meta = entryMetadata(entry)\n if (!wantMetadata || typeof meta?.size !== 'number' || typeof meta.mtimeMs !== 'number')\n return path\n return `${path}\\t${meta.size}\\t${new Date(meta.mtimeMs).toISOString()}`\n}\n\n/**\n * The `glob` tool. Lists files in the execution context that match a glob pattern.\n *\n * Delegates matching to {@link ExecutionContext.listFiles} with `{ glob:\n * true }`. This keeps filesystem semantics inside the execution context\n * (process / docker / sandbox) instead of reaching around it from the tool.\n *\n * Results are capped at 1000 entries by default to keep model input bounded.\n * The cap applies after the directory filter, so dirs don't consume the\n * file budget.\n *\n * Patterns are deliberately NOT confined to the workspace: like\n * `read_file`, `../`-prefixed patterns may match outside the cwd — the\n * execution context is the sandbox boundary, not this tool.\n *\n * By default, contexts that can cheaply provide metadata return\n * `<path>\\t<size>\\t<mtime>` rows. Contexts without cheap metadata support return\n * paths only. Pass `metadata: false` to request plain newline-separated paths.\n */\nexport const glob: ToolDef = {\n // Filesystem listing only — safe to fan out alongside other reads.\n isConcurrencySafe: true,\n spec: {\n name: 'glob',\n description: toolPrompts.glob,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern (e.g. \"src/**/*.ts\", \"*.md\", \"test/**/fixtures/*\").',\n },\n limit: {\n type: 'number',\n description: `Maximum number of matches to return. Default: ${DEFAULT_LIMIT}.`,\n },\n metadata: {\n type: 'boolean',\n description: 'Append size (bytes) and mtime (ISO) per row, tab-separated. Default: true. In-process only; non-process execution contexts always return paths.',\n },\n gitignore: {\n type: 'boolean',\n description: 'Skip files git ignores (.gitignore, .git/info/exclude, global excludes). Default: true. Set false to include ignored files like node_modules. Honored where git is available; a no-op otherwise.',\n },\n },\n required: ['pattern'],\n },\n },\n async execute({ pattern, limit, metadata, gitignore }, ctx: ToolContext) {\n const pat = pattern as string\n const max = typeof limit === 'number' && limit > 0 ? limit : DEFAULT_LIMIT\n const wantMetadata = metadata !== false\n\n try {\n if (ctx.execution.capabilities.glob !== true)\n throw new Error(`The active execution context (${ctx.execution.type}) does not support glob matching.`)\n\n // Backstop: a pathological walk must never hang the turn. Abort the\n // listing and return a steer after GLOB_TIMEOUT_MS — raced so the tool\n // settles on time even if a streaming matcher is slow to yield control.\n // The controller is also linked to the caller's signal.\n const controller = new AbortController()\n const onAbort = () => controller.abort()\n ctx.signal.addEventListener('abort', onAbort, { once: true })\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => {\n controller.abort()\n resolve('timeout')\n }, GLOB_TIMEOUT_MS)\n })\n try {\n const outcome = await Promise.race([\n ctx.execution.listFiles(ctx.handle, pat, {\n glob: true,\n limit: max,\n metadata: wantMetadata,\n gitignore: gitignore as boolean | undefined,\n signal: controller.signal,\n }),\n timeout,\n ])\n if (outcome === 'timeout')\n return `Glob timed out after ${GLOB_TIMEOUT_MS}ms: narrow the pattern (anchor a literal prefix like \\`src/**\\`) or scope it to a subdirectory.`\n if (outcome.length === 0)\n return '(no matches)'\n return outcome.map(entry => renderEntry(entry, wantMetadata)).join('\\n')\n }\n finally {\n clearTimeout(timer)\n ctx.signal.removeEventListener('abort', onAbort)\n }\n }\n catch (err) {\n if (isAbortLikeError(err))\n throw err\n throw new ToolFailure(`Glob error: ${errorMessage(err)}`)\n }\n },\n}\n","import type { ToolContext, ToolDef } from './types'\nimport { Buffer } from 'node:buffer'\nimport { GIT_LS_FILES_COMMAND, parseGitLsFiles } from '../contexts/git-ls-files'\nimport { errorMessage, isAbortLikeError } from '../errors'\nimport { isToolFailure, ToolFailure } from './failure'\nimport { toolPrompts } from './prompts'\nimport { shellQuote } from './shell-quote'\n\n/** Default cap on output lines (`head_limit`). */\nconst DEFAULT_HEAD_LIMIT = 250\n\n/**\n * Per-line byte cap. ripgrep reports a match as the whole matching LINE, so a\n * minified / single-line file (one line = the entire file) would otherwise be\n * returned in full. Clip each line so a single line can't dump unbounded bytes\n * into the model context.\n */\nconst MAX_LINE_BYTES = 2000\n\n/**\n * OOM guard for the no-ripgrep fallback: it reads each candidate WHOLE\n * into memory (the execution interface has no streaming read), so one\n * multi-GB artifact would take the process down. Enforced twice — the\n * `find` walk excludes oversized files via the portable `-size`\n * predicate (POSIX `c` suffix, GNU + BSD), and the read loop probes\n * process-local sizes to cover the single-file fast path that bypasses\n * the walk. A documented divergence from the ripgrep path, which\n * streams and searches such files fine.\n */\nconst FALLBACK_MAX_FILE_BYTES = 16 * 1024 * 1024\n\n/** Total output byte cap, mirroring read_file's `DEFAULT_BYTE_CAP`. */\nconst OUTPUT_BYTE_CAP = 262_144\n\nconst DEFAULT_OUTPUT_MODE: OutputMode = 'files_with_matches'\n\ntype OutputMode = 'content' | 'files_with_matches' | 'count'\n\ninterface GrepInput {\n 'pattern': string\n 'patterns'?: string[]\n 'exclude'?: string\n 'fixed_strings'?: boolean\n '-w'?: boolean\n 'path'?: string\n 'paths'?: string[]\n 'glob'?: string\n 'type'?: string\n 'output_mode'?: OutputMode\n '-i'?: boolean\n '-n'?: boolean\n '-A'?: number\n '-B'?: number\n '-C'?: number\n 'multiline'?: boolean\n 'head_limit'?: number\n 'offset'?: number\n 'gitignore'?: boolean\n}\n\n/**\n * The `grep` tool. Searches file contents for regular expressions, using ripgrep when it is available and a JavaScript fallback otherwise.\n *\n * Wraps ripgrep (`rg`) when available; when it's not, falls back to a\n * regex search that enumerates files via the execution context's shell\n * (`find` over `exec`) and reads them via `ctx.execution.readFile`. Both\n * legs go through the {@link ToolContext.execution} seam, so the search\n * runs wherever the context's files actually live — in-process, a\n * container, or a remote sandbox — without the tool ever touching the host\n * filesystem directly.\n *\n * The tool surface mirrors Claude Code's `Grep` so models authored against the\n * Anthropic tool surface need no relearning. Output modes:\n * - `files_with_matches` (default) — newline-separated paths.\n * - `content` — `path:line:match` (line numbers on by default).\n * - `count` — `path:N` per matching file.\n *\n * Results are capped via `head_limit` (default 250) to keep model input\n * bounded; `offset` lets the caller page through. Pagination operates on\n * OUTPUT LINES, not match groups — in content mode, context lines and `--`\n * separators consume the budget too (documented in the schema).\n *\n * A line cap is not enough on its own: ripgrep is line-oriented, so a minified\n * / single-line file collapses to ONE match line that is the entire file, and\n * `head_limit` would happily return megabytes — enough to blow the model's\n * context window. Output is therefore ALSO byte-bounded: each line is clipped\n * to `MAX_LINE_BYTES` and the total to `OUTPUT_BYTE_CAP`, mirroring the byte\n * discipline `read_file` already enforces.\n *\n * `path` is deliberately NOT confined to the workspace: like `read_file`,\n * absolute paths and `../` traversal are allowed — the execution context is\n * the sandbox boundary, not this tool.\n */\n\nexport const grep: ToolDef = {\n // Searches files without touching them — concurrency-safe.\n isConcurrencySafe: true,\n spec: {\n name: 'grep',\n description: toolPrompts.grep,\n inputSchema: {\n type: 'object',\n properties: {\n 'pattern': { type: 'string', description: 'Regex (PCRE-flavored via ripgrep, JS regex via fallback).' },\n 'patterns': { type: 'array', items: { type: 'string' }, description: 'More regexes; a line matches if it matches `pattern` OR any of these (like `rg -e a -e b`).' },\n 'exclude': { type: 'string', description: 'Drop output lines matching this regex (applied to the whole output line, like piping through `grep -v`).' },\n 'fixed_strings': { type: 'boolean', description: 'Treat patterns as literal strings, not regexes (`-F`).' },\n '-w': { type: 'boolean', description: 'Match whole words only.' },\n 'path': { type: 'string', description: 'File or directory to search. Default: \".\". May be absolute or outside the workspace (no confinement; consistent with read_file).' },\n 'paths': { type: 'array', items: { type: 'string' }, description: 'Several files or directories to search in one call (combined with `path` when both are set).' },\n 'glob': { type: 'string', description: 'Restrict to files matching this glob, e.g. \"**/*.ts\".' },\n 'type': { type: 'string', description: 'rg file type filter, e.g. \"ts\", \"py\", \"rust\". Ignored by the fallback.' },\n 'output_mode': { type: 'string', enum: ['content', 'files_with_matches', 'count'], description: 'Default: \"files_with_matches\".' },\n '-i': { type: 'boolean', description: 'Case-insensitive match.' },\n '-n': { type: 'boolean', description: 'Show line numbers (content mode). Default: true.' },\n '-A': { type: 'integer', description: 'Lines of trailing context (content mode).' },\n '-B': { type: 'integer', description: 'Lines of leading context (content mode).' },\n '-C': { type: 'integer', description: 'Lines of surrounding context (content mode). Overridden by -A/-B if set.' },\n 'multiline': { type: 'boolean', description: 'Allow patterns to match across line boundaries.' },\n 'gitignore': { type: 'boolean', description: 'Skip files git ignores (.gitignore, .git/info/exclude, global excludes). Default: true. Set false to also search ignored files like node_modules.' },\n 'head_limit': { type: 'integer', description: `Cap output lines. Default: 250. Set 0 for unlimited lines. In content mode, context lines (-A/-B/-C) and \"--\" separators count toward the cap, so the number of matches shown may be lower. Output is independently byte-bounded: each line is clipped to ${MAX_LINE_BYTES} bytes and the total to ${OUTPUT_BYTE_CAP} bytes, so long (e.g. minified) lines never overflow the context window.` },\n 'offset': { type: 'integer', description: 'Skip first N output lines. Default: 0.' },\n },\n required: ['pattern'],\n },\n },\n async execute(rawInput, ctx: ToolContext) {\n const input = rawInput as unknown as GrepInput\n const invalid = validateInput(input)\n if (invalid)\n throw new ToolFailure(`grep error: ${invalid}`)\n\n try {\n if (await isRipgrepAvailable(ctx))\n return await runViaRipgrep(input, ctx)\n return await runFallback(input, ctx)\n }\n catch (err) {\n // grep must never leak a raw exception to the model. An abort is the\n // sole exception we re-throw — the loop renders its canonical\n // interrupt/cascade marker; everything else (a broken `exec`, an\n // unreadable tree, a remote transport error) becomes a `grep error:`.\n if (isAbortLikeError(err) || isToolFailure(err))\n throw err\n throw new ToolFailure(`grep error: ${errorMessage(err)}`)\n }\n },\n}\n\n// ---------------------------------------------------------------------------\n// ripgrep path\n// ---------------------------------------------------------------------------\n\n/**\n * Probe ripgrep availability **per call**. The probe is intentionally not\n * cached: caching at module scope would leak across execution contexts (an\n * orchestrator running an in-process agent and a docker agent in the same\n * Node process must be able to differ on whether `rg` exists), and caching\n * per handle adds bookkeeping for negligible savings — `rg --version` is\n * ~5 ms, and grep is invoked at most a few times per turn.\n */\nasync function isRipgrepAvailable(ctx: ToolContext): Promise<boolean> {\n const result = await ctx.execution.exec(ctx.handle, 'rg --version', { signal: ctx.signal })\n return result.exitCode === 0\n}\n\n/**\n * Every regex the call matches on: `pattern` plus non-empty `patterns`. An\n * empty `pattern` next to non-empty `patterns` is dropped: it would match\n * every line.\n */\nfunction allPatterns(input: GrepInput): string[] {\n const extra = Array.isArray(input.patterns) ? input.patterns.filter(p => typeof p === 'string' && p.length > 0) : []\n if (input.pattern === '' && extra.length > 0)\n return extra\n return [input.pattern, ...extra]\n}\n\n/** Search roots: `path` and `paths` combined, defaulting to `.`. */\nfunction searchRoots(input: GrepInput): string[] {\n const roots = [\n ...(typeof input.path === 'string' && input.path.length > 0 ? [input.path] : []),\n ...(Array.isArray(input.paths) ? input.paths.filter(p => typeof p === 'string' && p.length > 0) : []),\n ]\n return roots.length > 0 ? [...new Set(roots)] : ['.']\n}\n\nfunction validateInput(input: GrepInput): string | undefined {\n if (typeof input.pattern !== 'string')\n return '`pattern` must be a string.'\n if (input.patterns !== undefined && (!Array.isArray(input.patterns) || input.patterns.some(p => typeof p !== 'string')))\n return '`patterns` must be an array of strings.'\n if (input.paths !== undefined && (!Array.isArray(input.paths) || input.paths.some(p => typeof p !== 'string')))\n return '`paths` must be an array of strings.'\n if (input.exclude !== undefined) {\n if (typeof input.exclude !== 'string')\n return '`exclude` must be a string.'\n try {\n void new RegExp(input.exclude)\n }\n catch (err) {\n return `invalid exclude regex: ${errorMessage(err)}`\n }\n }\n return undefined\n}\n\nasync function runViaRipgrep(input: GrepInput, ctx: ToolContext): Promise<string> {\n const args = ['rg']\n const mode = (input.output_mode ?? DEFAULT_OUTPUT_MODE) as OutputMode\n\n if (mode === 'files_with_matches')\n args.push('--files-with-matches')\n else if (mode === 'count')\n args.push('--count')\n else\n args.push((input['-n'] ?? true) ? '--line-number' : '--no-line-number')\n\n if (input['-i'])\n args.push('-i')\n if (input.fixed_strings)\n args.push('--fixed-strings')\n if (input['-w'])\n args.push('--word-regexp')\n\n if (mode === 'content') {\n if (typeof input['-A'] === 'number')\n args.push('-A', String(input['-A']))\n if (typeof input['-B'] === 'number')\n args.push('-B', String(input['-B']))\n if (typeof input['-C'] === 'number' && typeof input['-A'] !== 'number' && typeof input['-B'] !== 'number')\n args.push('-C', String(input['-C']))\n }\n\n if (input.multiline)\n args.push('--multiline', '--multiline-dotall')\n\n // ripgrep respects .gitignore by default; only disable it on explicit opt-out.\n if (input.gitignore === false)\n args.push('--no-ignore')\n\n if (input.glob)\n args.push('--glob', input.glob)\n\n if (input.type)\n args.push('--type', input.type)\n\n // `-e` per pattern (OR semantics); `-e` also keeps a leading-dash pattern\n // from parsing as a flag.\n for (const pattern of allPatterns(input))\n args.push('-e', pattern)\n\n // Always pass a path — rg reads from stdin when invoked from a non-TTY child\n // process without a path argument, which hangs forever waiting for input.\n args.push('--', ...searchRoots(input))\n\n const command = args.map(shellQuote).join(' ')\n const result = await ctx.execution.exec(ctx.handle, command, { signal: ctx.signal })\n\n // ripgrep exits 1 when there are no matches — that's not an error here.\n if (result.exitCode !== 0 && result.exitCode !== 1) {\n throw new ToolFailure(`grep error: ${result.stderr.trim() || `rg exited with code ${result.exitCode}`}`)\n }\n\n return formatPaginated(result.stdout, input)\n}\n\n// ---------------------------------------------------------------------------\n// Fallback path (context-routed `find` enumeration + readFile + JS regex)\n// ---------------------------------------------------------------------------\n\nasync function runFallback(input: GrepInput, ctx: ToolContext): Promise<string> {\n const mode = (input.output_mode ?? DEFAULT_OUTPUT_MODE) as OutputMode\n const flags = `${input['-i'] ? 'i' : ''}${input.multiline ? 's' : ''}${mode !== 'content' ? '' : 'g'}`\n\n let regex: RegExp\n try {\n regex = new RegExp(fallbackSource(input), flags || undefined)\n }\n catch (err) {\n throw new ToolFailure(`grep error: invalid regex: ${errorMessage(err)}`)\n }\n\n const multilineRegex = input.multiline ? new RegExp(regex.source, `${flags.replace(/g/, '')}g`) : undefined\n const files: string[] = []\n for (const root of searchRoots(input)) {\n for (const file of await enumerateFiles(input, root, ctx)) {\n if (!files.includes(file))\n files.push(file)\n }\n }\n const showLineNumbers = input['-n'] ?? true\n const before = (input['-B'] ?? input['-C'] ?? 0)\n const after = (input['-A'] ?? input['-C'] ?? 0)\n\n // Second layer of the fallback's OOM guard, scoped to the single-file\n // fast path ONLY: walk-enumerated files are already size-filtered by\n // the find predicate, and probing each of them would cost one exec per\n // file on exec-probed contexts (docker/sandbox) — N extra round-trips\n // for zero added protection. The fast path bypasses the walk, so it is\n // the one entry that needs the probe. (Contexts without the capability\n // proceed unguarded: same accepted residual as whole-read-guard.ts.)\n const viaSingleFileFastPath = files.length === 1 && searchRoots(input).includes(files[0] as string)\n if (viaSingleFileFastPath) {\n const size = await ctx.execution.fileSize?.(ctx.handle, files[0] as string) ?? null\n if (size !== null && size > FALLBACK_MAX_FILE_BYTES)\n return '(no matches)'\n }\n\n const lines: string[] = []\n for (const path of files) {\n let content: string\n try {\n content = await ctx.execution.readFile(ctx.handle, path)\n }\n catch (err) {\n // Skip unreadable / binary / vanished files — but let an abort\n // propagate (a remote readFile may reject with AbortError on cancel).\n if (isAbortLikeError(err))\n throw err\n continue\n }\n if (multilineRegex) {\n // Multiline mode: scan the whole buffer with /g semantics.\n const allMatches = [...content.matchAll(multilineRegex)]\n if (allMatches.length === 0)\n continue\n if (mode === 'files_with_matches') {\n lines.push(path)\n continue\n }\n if (mode === 'count') {\n lines.push(`${path}:${allMatches.length}`)\n continue\n }\n // content mode — emit each match's surrounding line context. Line\n // numbers advance incrementally (matches arrive in index order) instead\n // of re-splitting the prefix per match (which costs O(matches x size)).\n let lineNo = 1\n let scannedTo = 0\n for (const m of allMatches) {\n const lineStart = content.lastIndexOf('\\n', m.index! - 1) + 1\n const lineEnd = content.indexOf('\\n', m.index!)\n const snippet = content.slice(lineStart, lineEnd === -1 ? undefined : lineEnd)\n for (let nl = content.indexOf('\\n', scannedTo); nl !== -1 && nl < m.index!; nl = content.indexOf('\\n', nl + 1))\n lineNo++\n scannedTo = m.index!\n lines.push(formatContentLine(path, lineNo, snippet, showLineNumbers))\n }\n continue\n }\n\n const fileLines = content.split('\\n')\n const matched: number[] = []\n for (let i = 0; i < fileLines.length; i++) {\n regex.lastIndex = 0\n if (regex.test(fileLines[i]))\n matched.push(i)\n }\n if (matched.length === 0)\n continue\n\n if (mode === 'files_with_matches') {\n lines.push(path)\n continue\n }\n if (mode === 'count') {\n lines.push(`${path}:${matched.length}`)\n continue\n }\n\n const includeLineNos = new Set<number>()\n for (const m of matched) {\n for (let i = Math.max(0, m - before); i <= Math.min(fileLines.length - 1, m + after); i++)\n includeLineNos.add(i)\n }\n const sorted = [...includeLineNos].sort((a, b) => a - b)\n let prev = -2\n for (const lineNo of sorted) {\n if (lineNo > prev + 1 && lines.length > 0)\n lines.push('--')\n const snippet = fileLines[lineNo]\n lines.push(formatContentLine(path, lineNo + 1, snippet, showLineNumbers))\n prev = lineNo\n }\n }\n\n return formatPaginated(lines.join('\\n'), input)\n}\n\nfunction formatContentLine(path: string, lineNo: number, snippet: string, showLineNumbers: boolean): string {\n return showLineNumbers ? `${path}:${lineNo}:${snippet}` : `${path}:${snippet}`\n}\n\n/**\n * JS regex source for the fallback: patterns OR'ed together, escaped under\n * `fixed_strings`, wrapped in word boundaries under `-w`.\n */\nfunction fallbackSource(input: GrepInput): string {\n const parts = allPatterns(input).map(p => input.fixed_strings ? p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') : p)\n const joined = parts.length === 1 ? parts[0] : parts.map(p => `(?:${p})`).join('|')\n return input['-w'] ? `\\\\b(?:${joined})\\\\b` : joined\n}\n\nasync function enumerateFiles(input: GrepInput, root: string, ctx: ToolContext): Promise<string[]> {\n // Single-file fast path: if the root names a file, search just it. Routed\n // through `exec` so the check runs inside the context, not on the host.\n if (root !== '.' && !root.includes('*') && !root.includes('?')) {\n const probe = await ctx.execution.exec(ctx.handle, `test -f ${shellQuote(root)} && echo file || echo dir`, { signal: ctx.signal })\n if (probe.stdout.trim() === 'file')\n return [root]\n }\n\n // Enumerate through the execution context's shell so the listing comes from\n // wherever the context's files live — never the host filesystem. `find` is\n // the same primitive the `glob` tool's portable path uses.\n const result = await ctx.execution.exec(ctx.handle, buildFindCommand(root, input.glob), { signal: ctx.signal })\n\n // A non-zero exit with NO output is a real failure (find unavailable, bad\n // root) — surface it like ripgrep would for a bad path. A non-zero exit WITH\n // output is a partial walk (e.g. an unreadable subdir): keep what we got.\n // `find` writes diagnostics to\n // stderr, so stdout stays a clean newline-separated path list either way.\n if (result.exitCode !== 0 && !result.stdout.trim())\n throw new Error(result.stderr.trim() || `find exited with code ${result.exitCode}`)\n\n const files = result.stdout\n .split('\\n')\n .map(line => line.replace(/^\\.\\//, ''))\n .filter(line => line.length > 0)\n .sort()\n\n // `find` honors no ignore rules, so the no-`rg` fallback would otherwise\n // walk `node_modules` etc. — inconsistent with the ripgrep path. Restrict to\n // git's non-ignored set by default; `gitignore: false` keeps everything.\n if (input.gitignore === false)\n return files\n return filterByGitignore(files, root, ctx)\n}\n\n/**\n * Best-effort intersection of `files` with `git ls-files` (non-ignored set).\n * Returns `files` unchanged when git is unavailable, the dir isn't a repo, or\n * `root` escapes the repo (absolute / `..`) — the filter can only fail open.\n */\nasync function filterByGitignore(files: string[], root: string, ctx: ToolContext): Promise<string[]> {\n if (files.length === 0)\n return files\n if (root !== '.' && (root.startsWith('/') || root.split('/').includes('..')))\n return files\n try {\n const res = await ctx.execution.exec(ctx.handle, GIT_LS_FILES_COMMAND, { signal: ctx.signal })\n if (res.exitCode !== 0)\n return files\n const allowed = new Set(parseGitLsFiles(res.stdout))\n if (allowed.size === 0)\n return files\n return files.filter(file => allowed.has(file))\n }\n catch {\n return files\n }\n}\n\n/**\n * Build a `find` command listing files under `root`, optionally filtered by\n * `glob`. Mirrors `glob`'s shell fallback:\n * - a bare basename, or one behind a leading recursive-wildcard segment,\n * with no inner slash → `-name` (matches at any depth, including the top\n * level — preserving the recursive-glob semantics).\n * - anything with a slash → `-path` against the full relative path. `find`'s\n * `*` spans `/`, so the single- and double-star forms collapse to the\n * same matcher; close enough for the no-`rg` fallback.\n */\nfunction buildFindCommand(root: string, glob?: string): string {\n const findRoot = normalizeFindRoot(root)\n const base = shellQuote(findRoot)\n const sizeGuard = `! -size +${FALLBACK_MAX_FILE_BYTES}c`\n if (!glob)\n return `find ${base} -type f ${sizeGuard}`\n const anyDepth = glob.match(/^(?:\\*\\*\\/)?([^/]+)$/)\n if (anyDepth)\n return `find ${base} -type f ${sizeGuard} -name ${shellQuote(anyDepth[1])}`\n const normRoot = findRoot.replace(/\\/$/, '')\n const pathPattern = root === '.' ? `./${glob}` : `${normRoot}/${glob}`\n return `find ${base} -type f ${sizeGuard} -path ${shellQuote(pathPattern)}`\n}\n\nfunction normalizeFindRoot(root: string): string {\n // POSIX `find` parses a leading-dash first operand as an expression/option.\n // Prefix relative paths like `-fixtures` so they remain path operands.\n return root.startsWith('-') ? `./${root}` : root\n}\n\nfunction formatPaginated(text: string, input: GrepInput): string {\n const headLimit = typeof input.head_limit === 'number' && input.head_limit >= 0\n ? input.head_limit\n : DEFAULT_HEAD_LIMIT\n const offset = typeof input.offset === 'number' && input.offset > 0\n ? Math.floor(input.offset)\n : 0\n\n if (!text.trim())\n return '(no matches)'\n\n const lines = applyExclude(text.split('\\n').filter(l => l.length > 0), input.exclude)\n if (lines.length === 0)\n return '(no matches after exclude)'\n const total = lines.length\n\n const sliced = headLimit === 0\n ? lines.slice(offset)\n : lines.slice(offset, offset + headLimit)\n\n if (sliced.length === 0)\n return '(no matches in this slice)'\n\n // Byte budget. `head_limit` caps the LINE count, but a single line can be\n // arbitrarily large (a minified / one-line file is one match line = the whole\n // file), so a line cap alone leaves byte output unbounded and can overflow the\n // model context. Clip each line, then stop once the total crosses the cap.\n const capped: string[] = []\n let bytesUsed = 0\n let byteCut = false\n for (const line of sliced) {\n const clipped = clipLine(line)\n const lineBytes = Buffer.byteLength(clipped) + 1 // +1 for the rejoining '\\n'\n if (bytesUsed + lineBytes > OUTPUT_BYTE_CAP && capped.length > 0) {\n byteCut = true\n break\n }\n capped.push(clipped)\n bytesUsed += lineBytes\n }\n\n const shown = capped.length\n const truncatedHead = offset > 0\n // Lines withheld by the line-count window, independent of the byte cut.\n const lineCutTail = headLimit > 0 && offset + headLimit < total\n\n // Markers say \"lines\", not \"matches\" — in content mode the pagination\n // unit includes context lines and `--` separators.\n let out = capped.join('\\n')\n if (truncatedHead)\n out = `…(${offset} earlier lines skipped)…\\n${out}`\n if (byteCut)\n out = `${out}\\n…(output truncated at ${OUTPUT_BYTE_CAP} bytes after ${shown} of ${total - offset} matching lines; narrow the pattern or page with offset=${offset + shown})`\n else if (lineCutTail)\n out = `${out}\\n…(${total - offset - headLimit} more lines; re-run with offset=${offset + headLimit} or larger head_limit)`\n return out\n}\n\n/**\n * Drop output lines matching `exclude` (validated upfront). Context-group\n * `--` separators are kept only between surviving lines, never doubled or at\n * the edges.\n */\nfunction applyExclude(lines: string[], exclude: string | undefined): string[] {\n if (!exclude)\n return lines\n const re = new RegExp(exclude)\n const kept: string[] = []\n for (const line of lines) {\n if (line === '--') {\n if (kept.length > 0 && kept[kept.length - 1] !== '--')\n kept.push(line)\n continue\n }\n if (!re.test(line))\n kept.push(line)\n }\n while (kept.length > 0 && kept[kept.length - 1] === '--')\n kept.pop()\n return kept\n}\n\n/**\n * Clip one output line to `MAX_LINE_BYTES` at a UTF-8-safe boundary, appending\n * a marker that reports how many bytes were withheld. Lines within budget pass\n * through untouched.\n */\nfunction clipLine(line: string): string {\n if (Buffer.byteLength(line) <= MAX_LINE_BYTES)\n return line\n let cut = Math.min(line.length, MAX_LINE_BYTES)\n while (cut > 0 && Buffer.byteLength(line.slice(0, cut)) > MAX_LINE_BYTES)\n cut--\n const omitted = Buffer.byteLength(line) - Buffer.byteLength(line.slice(0, cut))\n return `${line.slice(0, cut)}… [line clipped, ${omitted} more bytes]`\n}\n","/**\n * Interaction tool — lets the agent request structured input from the outside world.\n *\n * Not included in any preset by default. Add it explicitly:\n *\n * import { createInteractionTool } from 'zidane'\n *\n * const askUser = createInteractionTool({\n * schema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] },\n * onRequest: async (payload) => {\n * const answer = await promptUser(payload.question)\n * return { answer }\n * },\n * })\n *\n * const preset = definePreset({ name: 'interactive', tools: { ...basicTools, ask_user: askUser } })\n */\n\nimport type { ToolContext, ToolDef } from './types'\nimport { toolPrompts } from './prompts'\n\nfunction abortReason(signal: AbortSignal): string {\n return typeof signal.reason === 'string' && signal.reason.length > 0\n ? signal.reason\n : 'Interaction aborted'\n}\n\n/** Options for {@link createInteractionTool}. */\nexport interface InteractionToolOptions {\n /** JSON Schema for the request payload the model sends */\n schema: Record<string, unknown>\n /** Tool name (default: 'interaction') */\n name?: string\n /** Tool description shown to the model */\n description?: string\n /** Called when the model invokes this tool. Receives the validated payload and tool context, returns data for the model. */\n onRequest: (payload: Record<string, unknown>, ctx: ToolContext) => Promise<Record<string, unknown> | string>\n}\n\n/**\n * Create an interaction tool that lets the agent request structured input.\n *\n * The model calls this tool with a payload matching the schema.\n * `onRequest` is called with the payload and should return the response\n * (string or object) that gets sent back to the model as the tool result.\n * @param options - Payload schema, optional name and description, and the `onRequest` handler.\n * @example\n * ```ts\n * import { createInteractionTool } from 'zidane/tools'\n *\n * const askUser = createInteractionTool({\n * name: 'ask_user',\n * schema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] },\n * onRequest: async payload => `Answer to: ${String(payload.question)}`,\n * })\n * ```\n */\nexport function createInteractionTool(options: InteractionToolOptions): ToolDef {\n const name = options.name ?? 'interaction'\n const description = options.description ?? toolPrompts.interaction\n\n return {\n spec: {\n name,\n description,\n inputSchema: options.schema,\n },\n async execute(input, ctx) {\n // Race the host resolver against the run's abort signal. `onRequest`\n // settles only on external (human/system) action, so without this an\n // `agent.abort()` / `agent.destroy()` — every teardown/cancel path —\n // would leave the tool body (and the run) hanging on a promise that can\n // never settle. On abort we reject so the loop unwinds cleanly.\n const { signal } = ctx\n if (signal?.aborted)\n throw new Error(abortReason(signal))\n\n let onAbort: (() => void) | undefined\n const abortPromise = signal\n ? new Promise<never>((_, reject) => {\n onAbort = () => reject(new Error(abortReason(signal)))\n signal.addEventListener('abort', onAbort, { once: true })\n })\n : undefined\n\n try {\n const result = abortPromise\n ? await Promise.race([options.onRequest(input, ctx), abortPromise])\n : await options.onRequest(input, ctx)\n return typeof result === 'string' ? result : JSON.stringify(result)\n }\n finally {\n if (signal && onAbort)\n signal.removeEventListener('abort', onAbort)\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;;AAGjC,MAAM,iBAAiB;;AAGvB,MAAM,sBAAsB;AA+B5B,SAAS,UAAU,SAAoD;CACrE,OAAO,QAAQ,SAAQ,WAAU,OAAO,OAAO,OAAO,KAAI,WAAU;EAAE;EAAQ;EAAO,KAAK,GAAG,OAAO,SAAS,GAAG,MAAM;CAAK,EAAE,CAAC;AAChI;AAEA,SAAS,mBAAmB,KAAsC;CAEhE,QADkB,IAAI,WAAW,SAAS,IAAI,YAAY,CAAC,IAAI,QAAQ,EAAA,CACtD,SAAS,aAAa;EACrC,MAAM,SAAS,SAAS;EACxB,OAAO,UAAU,OAAO,aAAa,CAAC,CAAC,YAAY,CAAC;GAAE,UAAU,SAAS;GAAM;EAAO,CAAC,IAAI,CAAC;CAC9F,CAAC;AACH;;AAGA,SAAS,UAAU,SAAgC,KAAqC;CACtF,MAAM,QAAQ,QAAQ,MAAK,MAAK,EAAE,QAAQ,GAAG;CAC7C,IAAI,OACF,OAAO;CACT,MAAM,OAAO,QAAQ,QAAO,MAAK,EAAE,MAAM,OAAO,GAAG;CACnD,OAAO,KAAK,WAAW,IAAI,KAAK,KAAK,KAAA;AACvC;AAEA,SAAS,aAAa,SAAgC,SAAsC,YAAwD;CAClJ,MAAM,SAAS,aAAa,UAAU,SAAS,UAAU,IAAI,KAAA;CAC7D,IAAI,Q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,UAAU,SACZ,OAAO,oBAAoB,SAAS,OAAO;GAC/C;EACF;CACF;AACF"}
1
+ {"version":3,"file":"tools-FHEIKGkh.js","names":[],"sources":["../src/tools/generate-image.ts","../src/tools/glob.ts","../src/tools/grep.ts","../src/tools/interaction.ts"],"sourcesContent":["/**\n * `generate_image`: text to image (or image to image) with any image model\n * of the providers the run can reach (`Provider.images`).\n *\n * The tool saves full-size files into the workspace, writes a `<file>.json`\n * record next to each one (prompt, provider, model, date, cost) so an asset's origin\n * stays on disk, and returns the paths plus a preview capped at\n * {@link PREVIEW_EDGE} px. The preview is what the model sees and what the\n * transcript shows; the file keeps the full resolution.\n *\n * The description lists up to {@link LISTED_MODELS} models so the model can\n * pick one without a round trip; `list: true` returns all of them.\n */\n\nimport type { ImageAspectRatio, ImageData, ImageModelInfo, ProviderImageResponse, ProviderImages } from '../providers/images'\nimport type { ToolResultContent } from '../types'\nimport type { ToolContext, ToolDef } from './types'\nimport { Buffer } from 'node:buffer'\nimport { randomBytes } from 'node:crypto'\nimport { isAbsolute, relative, resolve } from 'node:path'\nimport { errorMessage, isAbortLikeError } from '../errors'\nimport { imageSizeFromBase64 } from '../media/image-size'\nimport { shrinkImageBase64 } from '../media/png-downscale'\nimport { IMAGE_ASPECT_RATIOS, MAX_IMAGES_PER_REQUEST } from '../providers/images'\nimport { imageMediaTypeFor, readFileAsBase64 } from './binary-read'\nimport { ToolFailure } from './failure'\nimport { reconcileImageMediaType } from './media-sniff'\nimport { toolPrompts } from './prompts'\nimport { pathArgError } from './validation'\n\n/** Longest edge of the preview returned to the model, in px. */\nexport const PREVIEW_EDGE = 768\n\n/** Models named in the tool description; the rest are behind `list: true`. */\nexport const LISTED_MODELS = 15\n\n/** Folder for images saved without a `path`. */\nexport const DEFAULT_IMAGE_DIR = 'generated-images'\n\n/** Most reference images one call takes. */\nconst MAX_REFERENCES = 8\n\n/** Largest reference image, in bytes. Image APIs cap uploads near this size. */\nconst MAX_REFERENCE_BYTES = 20 * 1024 * 1024\n\n/** A provider the tool can generate with. */\nexport interface ImageModelSource {\n /** Provider name as the `model` argument spells it: `<provider>/<model id>`. */\n provider: string\n /** Display name of the provider, for the model list. */\n label?: string\n /** The provider's image endpoint. */\n images: ProviderImages\n}\n\n/** Options for {@link createGenerateImageTool}. */\nexport interface GenerateImageToolOptions {\n /**\n * Providers to generate with. Omitted: the run's providers that have an\n * available image endpoint (`ToolContext.providers`, else `provider`).\n */\n sources?: readonly ImageModelSource[]\n /** Model used when a call names none, as `<provider>/<model id>`. Default: the first source's default model. */\n defaultModel?: string\n}\n\n/** One model of one source. */\ninterface ModelEntry {\n source: ImageModelSource\n model: ImageModelInfo\n /** `<provider>/<model id>`. */\n ref: string\n}\n\nfunction entriesOf(sources: readonly ImageModelSource[]): ModelEntry[] {\n return sources.flatMap(source => source.images.models.map(model => ({ source, model, ref: `${source.provider}/${model.id}` })))\n}\n\nfunction sourcesFromContext(ctx: ToolContext): ImageModelSource[] {\n const providers = ctx.providers?.length ? ctx.providers : [ctx.provider]\n return providers.flatMap((provider) => {\n const images = provider.images\n return images && images.availability().available ? [{ provider: provider.name, images }] : []\n })\n}\n\n/** The entry `ref` names: an exact `<provider>/<id>`, else a model id only one source serves. */\nfunction findEntry(entries: readonly ModelEntry[], ref: string): ModelEntry | undefined {\n const exact = entries.find(e => e.ref === ref)\n if (exact)\n return exact\n const byId = entries.filter(e => e.model.id === ref)\n return byId.length === 1 ? byId[0] : undefined\n}\n\nfunction defaultEntry(entries: readonly ModelEntry[], sources: readonly ImageModelSource[], configured: string | undefined): ModelEntry | undefined {\n const picked = configured ? findEntry(entries, configured) : undefined\n if (picked)\n return picked\n const first = sources[0]\n return first ? findEntry(entries, `${first.provider}/${first.images.defaultModel}`) ?? entries[0] : undefined\n}\n\n/** One line per model: `provider/id · name · [ref] [alpha]`, `(default)` on the default one. */\nfunction modelLine(entry: ModelEntry, isDefault: boolean): string {\n const parts = [entry.ref]\n if (entry.model.name && entry.model.name !== entry.model.id)\n parts.push(entry.model.name)\n const flags = [\n ...(entry.model.input.includes('image') ? ['[ref]'] : []),\n ...(entry.model.transparency ? ['[alpha]'] : []),\n ...(isDefault ? ['(default)'] : []),\n ]\n return `- ${parts.join(' · ')}${flags.length ? ` ${flags.join(' ')}` : ''}`\n}\n\nfunction describeModels(entries: readonly ModelEntry[], def: ModelEntry | undefined): string {\n if (entries.length === 0)\n return 'Call with `list: true` to see the image models of the connected providers.'\n // The default first, then in source order.\n const ordered = def ? [def, ...entries.filter(e => e !== def)] : [...entries]\n const shown = ordered.slice(0, LISTED_MODELS)\n const lines = [\n 'Models (`model` argument; [ref]: takes reference images, [alpha]: transparent background):',\n ...shown.map(e => modelLine(e, e === def)),\n ]\n if (ordered.length > shown.length)\n lines.push(`Call with \\`list: true\\` for all ${ordered.length} models.`)\n return lines.join('\\n')\n}\n\nconst EXTENSION_BY_TYPE: Readonly<Record<string, string>> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n}\n\n/** A file-name stem from the first words of the prompt: `snowy-pine-forest-texture`. */\nfunction slugOf(prompt: string): string {\n const slug = prompt.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim().split(' ').slice(0, 6).join('-')\n return slug || 'image'\n}\n\n/**\n * `YYYYMMDD-HHMMSS-xxxx` of `now`; the random tail keeps two calls with the\n * same prompt in the same second (parallel tool calls) from overwriting each other.\n */\nfunction timeStamp(now: Date): string {\n const pad = (n: number) => String(n).padStart(2, '0')\n const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`\n const time = [now.getHours(), now.getMinutes(), now.getSeconds()].map(pad).join('')\n return `${date}-${time}-${randomBytes(2).toString('hex')}`\n}\n\n/** The record next to an image: the image's full name plus `.json`, so it never lands on a project file like `package.json`. */\nfunction recordPathOf(file: string): string {\n return `${file}.json`\n}\n\n/** `path` without an image extension, or the default stem when absent. */\nfunction stemOf(path: string | undefined, prompt: string, now: Date): string {\n if (!path)\n return `${DEFAULT_IMAGE_DIR}/${slugOf(prompt)}-${timeStamp(now)}`\n return imageMediaTypeFor(path) ? path.slice(0, path.lastIndexOf('.')) : path\n}\n\n/** The workspace-relative `path`, or a failure when it leaves the working directory. */\nfunction confinedPath(ctx: ToolContext, path: string, field: string): string {\n const err = pathArgError(path, field)\n if (err)\n throw new ToolFailure(`generate_image error: ${err}`)\n const cwd = ctx.handle.cwd\n const rel = relative(cwd, resolve(cwd, path))\n if (rel === '' || rel.startsWith('..') || isAbsolute(rel))\n throw new ToolFailure(`generate_image error: \\`${field}\\` must be a file inside the working directory (${cwd}), got \"${path}\".`)\n return rel\n}\n\nasync function readReference(ctx: ToolContext, path: string): Promise<ImageData> {\n const rel = confinedPath(ctx, path, 'references')\n const extMedia = imageMediaTypeFor(rel)\n if (!extMedia)\n throw new ToolFailure(`generate_image error: reference \"${path}\" is not a PNG, JPEG, WebP or GIF file.`)\n const size = await ctx.execution.fileSize?.(ctx.handle, rel) ?? null\n if (size !== null && size > MAX_REFERENCE_BYTES)\n throw new ToolFailure(`generate_image error: reference \"${path}\" is ${size} bytes; the limit is ${MAX_REFERENCE_BYTES}.`)\n try {\n const { base64 } = await readFileAsBase64(ctx.execution, ctx.handle, rel)\n return { data: base64, mediaType: reconcileImageMediaType(extMedia, base64) }\n }\n catch (err) {\n throw new ToolFailure(`generate_image error: cannot read reference \"${path}\": ${errorMessage(err)}`)\n }\n}\n\nfunction listText(entries: readonly ModelEntry[], def: ModelEntry | undefined): string {\n if (entries.length === 0)\n return 'No image models are available. Connect a provider with image generation (OpenRouter, OpenAI with a platform key, Google Gemini or xAI) in the provider settings.'\n const ordered = def ? [def, ...entries.filter(e => e !== def)] : entries\n return [`${entries.length} image model${entries.length === 1 ? '' : 's'}:`, ...ordered.map(e => modelLine(e, e === def))].join('\\n')\n}\n\nfunction formatCost(usd: number): string {\n return usd < 0.01 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`\n}\n\n/**\n * Build the `generate_image` tool.\n *\n * @param options - Providers to generate with and the default model.\n */\nexport function createGenerateImageTool(options: GenerateImageToolOptions = {}): ToolDef {\n const fixedSources = options.sources\n const fixedEntries = fixedSources ? entriesOf(fixedSources) : []\n const fixedDefault = fixedSources ? defaultEntry(fixedEntries, fixedSources, options.defaultModel) : undefined\n\n return {\n spec: {\n name: 'generate_image',\n description: `${toolPrompts.generate_image}\\n\\n${describeModels(fixedEntries, fixedDefault)}`,\n inputSchema: {\n type: 'object',\n properties: {\n prompt: {\n type: 'string',\n description: 'What to draw: subject, style, colors, lighting, framing. For an edit, what to change.',\n },\n model: {\n type: 'string',\n description: 'Image model as `<provider>/<model id>` from the list. Omit to use the default.',\n },\n path: {\n type: 'string',\n description: `Where to save, relative to the working directory, for example \\`assets/textures/snow.png\\`. The extension follows the format the model returns. Several images get \\`-1\\`, \\`-2\\` suffixes. Omit to save under \\`${DEFAULT_IMAGE_DIR}/\\`.`,\n },\n aspect_ratio: {\n type: 'string',\n enum: [...IMAGE_ASPECT_RATIOS],\n description: 'Shape of the image. Omit to let the model choose (usually square).',\n },\n n: {\n type: 'number',\n description: `How many variations to generate, 1 to ${MAX_IMAGES_PER_REQUEST}. Default 1. Each one costs.`,\n },\n references: {\n type: 'array',\n items: { type: 'string' },\n description: `Workspace image paths to edit or to match the style of, up to ${MAX_REFERENCES}. Only for models marked [ref].`,\n },\n transparent: {\n type: 'boolean',\n description: 'Ask for a transparent background (sprites, icons). Only for models marked [alpha].',\n },\n list: {\n type: 'boolean',\n description: 'List every available image model and generate nothing.',\n },\n },\n },\n },\n async execute(input, ctx): Promise<string | ToolResultContent[]> {\n const sources = fixedSources ?? sourcesFromContext(ctx)\n const entries = fixedSources ? fixedEntries : entriesOf(sources)\n const def = fixedSources ? fixedDefault : defaultEntry(entries, sources, options.defaultModel)\n\n if (input.list === true)\n return listText(entries, def)\n\n const prompt = typeof input.prompt === 'string' ? input.prompt.trim() : ''\n if (!prompt)\n throw new ToolFailure('generate_image error: `prompt` is required.')\n if (entries.length === 0)\n throw new ToolFailure(`generate_image error: ${listText(entries, def)}`)\n\n const requested = typeof input.model === 'string' && input.model.trim() ? input.model.trim() : undefined\n const entry = requested ? findEntry(entries, requested) : def\n if (!entry) {\n throw new ToolFailure(`generate_image error: unknown model \"${requested}\". Use \\`<provider>/<model id>\\`:\\n${listText(entries, def)}`)\n }\n\n const aspectRatio = typeof input.aspect_ratio === 'string' ? input.aspect_ratio as ImageAspectRatio : undefined\n if (aspectRatio && !IMAGE_ASPECT_RATIOS.includes(aspectRatio))\n throw new ToolFailure(`generate_image error: \\`aspect_ratio\\` must be one of ${IMAGE_ASPECT_RATIOS.join(', ')}.`)\n const count = typeof input.n === 'number' && Number.isFinite(input.n) ? Math.floor(input.n) : 1\n if (count < 1 || count > MAX_IMAGES_PER_REQUEST)\n throw new ToolFailure(`generate_image error: \\`n\\` must be from 1 to ${MAX_IMAGES_PER_REQUEST}.`)\n const transparent = input.transparent === true\n if (transparent && !entry.model.transparency) {\n const capable = entries.filter(e => e.model.transparency).map(e => e.ref)\n throw new ToolFailure(`generate_image error: ${entry.ref} cannot make a transparent background.${capable.length ? ` Models that can: ${capable.join(', ')}.` : ''}`)\n }\n\n const referencePaths = Array.isArray(input.references) ? input.references.filter((p): p is string => typeof p === 'string' && p.trim() !== '') : []\n if (referencePaths.length > 0 && !entry.model.input.includes('image'))\n throw new ToolFailure(`generate_image error: ${entry.ref} does not take reference images. Pick a model marked [ref].`)\n if (referencePaths.length > MAX_REFERENCES)\n throw new ToolFailure(`generate_image error: at most ${MAX_REFERENCES} references per call.`)\n\n const now = new Date()\n const pathArg = typeof input.path === 'string' && input.path.trim() ? input.path.trim() : undefined\n const stem = stemOf(pathArg ? confinedPath(ctx, pathArg, 'path') : undefined, prompt, now)\n const references = await Promise.all(referencePaths.map(p => readReference(ctx, p)))\n\n const started = Date.now()\n let response: ProviderImageResponse\n try {\n response = await entry.source.images.generate({\n model: entry.model.id,\n prompt,\n ...(references.length ? { references } : {}),\n ...(aspectRatio ? { aspectRatio } : {}),\n count,\n ...(transparent ? { transparent } : {}),\n }, ctx.signal)\n }\n catch (err) {\n if (isAbortLikeError(err) || ctx.signal.aborted)\n throw err\n throw new ToolFailure(`generate_image error (${entry.ref}): ${errorMessage(err)}`)\n }\n const seconds = (Date.now() - started) / 1000\n\n const images = response.images.slice(0, count)\n const saved: string[] = []\n for (const [i, image] of images.entries()) {\n const ext = EXTENSION_BY_TYPE[image.mediaType] ?? 'png'\n const file = `${stem}${images.length > 1 ? `-${i + 1}` : ''}.${ext}`\n const record = {\n prompt,\n provider: entry.source.provider,\n model: response.model || entry.model.id,\n ...(aspectRatio ? { aspectRatio } : {}),\n ...(transparent ? { transparent } : {}),\n ...(referencePaths.length ? { references: referencePaths } : {}),\n ...(response.costUsd !== undefined ? { costUsd: response.costUsd / images.length } : {}),\n createdAt: now.toISOString(),\n }\n try {\n await ctx.execution.writeFile(ctx.handle, file, Buffer.from(image.data, 'base64'))\n await ctx.execution.writeFile(ctx.handle, recordPathOf(file), `${JSON.stringify(record, null, 2)}\\n`)\n }\n catch (err) {\n throw new ToolFailure(`generate_image error: the image was generated but saving ${file} failed: ${errorMessage(err)}`)\n }\n saved.push(file)\n }\n\n const sizes = images.map((image) => {\n const size = imageSizeFromBase64(image.data)\n return size ? `${size.width}x${size.height}` : image.mediaType\n })\n const lines = [\n `Generated ${images.length} image${images.length === 1 ? '' : 's'} with ${entry.ref} in ${seconds.toFixed(1)} s.`,\n ...saved.map((file, i) => `Saved: ${file} (${sizes[i]})`),\n `Records: ${saved.map(recordPathOf).join(', ')}`,\n ...(response.costUsd !== undefined ? [`Cost: ${formatCost(response.costUsd)}`] : []),\n ...(response.text ? [`Model note: ${response.text}`] : []),\n ]\n const previews: ToolResultContent[] = images.map((image) => {\n const shrunk = shrinkImageBase64(image.data, image.mediaType, PREVIEW_EDGE)\n return { type: 'image', mediaType: shrunk?.mediaType ?? image.mediaType, data: shrunk?.data ?? image.data }\n })\n return [{ type: 'text', text: lines.join('\\n') }, ...previews]\n },\n }\n}\n","import type { ListFileMetadata, ListFilesEntry } from '../contexts'\nimport type { ToolContext, ToolDef } from './types'\nimport { errorMessage, isAbortLikeError } from '../errors'\nimport { ToolFailure } from './failure'\nimport { toolPrompts } from './prompts'\n\n/** Default cap on returned matches. A `limit` argument overrides it. */\nconst DEFAULT_LIMIT = 1000\n\n/** Backstop so a pathological walk can never hang the agent's turn. */\nconst GLOB_TIMEOUT_MS = 20_000\n\nfunction entryPath(entry: ListFilesEntry): string {\n return typeof entry === 'string' ? entry : entry.path\n}\n\nfunction entryMetadata(entry: ListFilesEntry): ListFileMetadata | undefined {\n return typeof entry === 'string' ? undefined : entry\n}\n\nfunction renderEntry(entry: ListFilesEntry, wantMetadata: boolean): string {\n const path = entryPath(entry)\n const meta = entryMetadata(entry)\n if (!wantMetadata || typeof meta?.size !== 'number' || typeof meta.mtimeMs !== 'number')\n return path\n return `${path}\\t${meta.size}\\t${new Date(meta.mtimeMs).toISOString()}`\n}\n\n/**\n * The `glob` tool. Lists files in the execution context that match a glob pattern.\n *\n * Delegates matching to {@link ExecutionContext.listFiles} with `{ glob:\n * true }`. This keeps filesystem semantics inside the execution context\n * (process / docker / sandbox) instead of reaching around it from the tool.\n *\n * Results are capped at 1000 entries by default to keep model input bounded.\n * The cap applies after the directory filter, so dirs don't consume the\n * file budget.\n *\n * Patterns are deliberately NOT confined to the workspace: like\n * `read_file`, `../`-prefixed patterns may match outside the cwd — the\n * execution context is the sandbox boundary, not this tool.\n *\n * By default, contexts that can cheaply provide metadata return\n * `<path>\\t<size>\\t<mtime>` rows. Contexts without cheap metadata support return\n * paths only. Pass `metadata: false` to request plain newline-separated paths.\n */\nexport const glob: ToolDef = {\n // Filesystem listing only — safe to fan out alongside other reads.\n isConcurrencySafe: true,\n spec: {\n name: 'glob',\n description: toolPrompts.glob,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern (e.g. \"src/**/*.ts\", \"*.md\", \"test/**/fixtures/*\").',\n },\n limit: {\n type: 'number',\n description: `Maximum number of matches to return. Default: ${DEFAULT_LIMIT}.`,\n },\n metadata: {\n type: 'boolean',\n description: 'Append size (bytes) and mtime (ISO) per row, tab-separated. Default: true. In-process only; non-process execution contexts always return paths.',\n },\n gitignore: {\n type: 'boolean',\n description: 'Skip files git ignores (.gitignore, .git/info/exclude, global excludes). Default: true. Set false to include ignored files like node_modules. Honored where git is available; a no-op otherwise.',\n },\n },\n required: ['pattern'],\n },\n },\n async execute({ pattern, limit, metadata, gitignore }, ctx: ToolContext) {\n const pat = pattern as string\n const max = typeof limit === 'number' && limit > 0 ? limit : DEFAULT_LIMIT\n const wantMetadata = metadata !== false\n\n try {\n if (ctx.execution.capabilities.glob !== true)\n throw new Error(`The active execution context (${ctx.execution.type}) does not support glob matching.`)\n\n // Backstop: a pathological walk must never hang the turn. Abort the\n // listing and return a steer after GLOB_TIMEOUT_MS — raced so the tool\n // settles on time even if a streaming matcher is slow to yield control.\n // The controller is also linked to the caller's signal.\n const controller = new AbortController()\n const onAbort = () => controller.abort()\n ctx.signal.addEventListener('abort', onAbort, { once: true })\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => {\n controller.abort()\n resolve('timeout')\n }, GLOB_TIMEOUT_MS)\n })\n try {\n const outcome = await Promise.race([\n ctx.execution.listFiles(ctx.handle, pat, {\n glob: true,\n limit: max,\n metadata: wantMetadata,\n gitignore: gitignore as boolean | undefined,\n signal: controller.signal,\n }),\n timeout,\n ])\n if (outcome === 'timeout')\n return `Glob timed out after ${GLOB_TIMEOUT_MS}ms: narrow the pattern (anchor a literal prefix like \\`src/**\\`) or scope it to a subdirectory.`\n if (outcome.length === 0)\n return '(no matches)'\n return outcome.map(entry => renderEntry(entry, wantMetadata)).join('\\n')\n }\n finally {\n clearTimeout(timer)\n ctx.signal.removeEventListener('abort', onAbort)\n }\n }\n catch (err) {\n if (isAbortLikeError(err))\n throw err\n throw new ToolFailure(`Glob error: ${errorMessage(err)}`)\n }\n },\n}\n","import type { ToolContext, ToolDef } from './types'\nimport { Buffer } from 'node:buffer'\nimport { GIT_LS_FILES_COMMAND, parseGitLsFiles } from '../contexts/git-ls-files'\nimport { errorMessage, isAbortLikeError } from '../errors'\nimport { isToolFailure, ToolFailure } from './failure'\nimport { toolPrompts } from './prompts'\nimport { shellQuote } from './shell-quote'\n\n/** Default cap on output lines (`head_limit`). */\nconst DEFAULT_HEAD_LIMIT = 250\n\n/**\n * Per-line byte cap. ripgrep reports a match as the whole matching LINE, so a\n * minified / single-line file (one line = the entire file) would otherwise be\n * returned in full. Clip each line so a single line can't dump unbounded bytes\n * into the model context.\n */\nconst MAX_LINE_BYTES = 2000\n\n/**\n * OOM guard for the no-ripgrep fallback: it reads each candidate WHOLE\n * into memory (the execution interface has no streaming read), so one\n * multi-GB artifact would take the process down. Enforced twice — the\n * `find` walk excludes oversized files via the portable `-size`\n * predicate (POSIX `c` suffix, GNU + BSD), and the read loop probes\n * process-local sizes to cover the single-file fast path that bypasses\n * the walk. A documented divergence from the ripgrep path, which\n * streams and searches such files fine.\n */\nconst FALLBACK_MAX_FILE_BYTES = 16 * 1024 * 1024\n\n/** Total output byte cap, mirroring read_file's `DEFAULT_BYTE_CAP`. */\nconst OUTPUT_BYTE_CAP = 262_144\n\nconst DEFAULT_OUTPUT_MODE: OutputMode = 'files_with_matches'\n\ntype OutputMode = 'content' | 'files_with_matches' | 'count'\n\ninterface GrepInput {\n 'pattern': string\n 'patterns'?: string[]\n 'exclude'?: string\n 'fixed_strings'?: boolean\n '-w'?: boolean\n 'path'?: string\n 'paths'?: string[]\n 'glob'?: string\n 'type'?: string\n 'output_mode'?: OutputMode\n '-i'?: boolean\n '-n'?: boolean\n '-A'?: number\n '-B'?: number\n '-C'?: number\n 'multiline'?: boolean\n 'head_limit'?: number\n 'offset'?: number\n 'gitignore'?: boolean\n}\n\n/**\n * The `grep` tool. Searches file contents for regular expressions, using ripgrep when it is available and a JavaScript fallback otherwise.\n *\n * Wraps ripgrep (`rg`) when available; when it's not, falls back to a\n * regex search that enumerates files via the execution context's shell\n * (`find` over `exec`) and reads them via `ctx.execution.readFile`. Both\n * legs go through the {@link ToolContext.execution} seam, so the search\n * runs wherever the context's files actually live — in-process, a\n * container, or a remote sandbox — without the tool ever touching the host\n * filesystem directly.\n *\n * The tool surface mirrors Claude Code's `Grep` so models authored against the\n * Anthropic tool surface need no relearning. Output modes:\n * - `files_with_matches` (default) — newline-separated paths.\n * - `content` — `path:line:match` (line numbers on by default).\n * - `count` — `path:N` per matching file.\n *\n * Results are capped via `head_limit` (default 250) to keep model input\n * bounded; `offset` lets the caller page through. Pagination operates on\n * OUTPUT LINES, not match groups — in content mode, context lines and `--`\n * separators consume the budget too (documented in the schema).\n *\n * A line cap is not enough on its own: ripgrep is line-oriented, so a minified\n * / single-line file collapses to ONE match line that is the entire file, and\n * `head_limit` would happily return megabytes — enough to blow the model's\n * context window. Output is therefore ALSO byte-bounded: each line is clipped\n * to `MAX_LINE_BYTES` and the total to `OUTPUT_BYTE_CAP`, mirroring the byte\n * discipline `read_file` already enforces.\n *\n * `path` is deliberately NOT confined to the workspace: like `read_file`,\n * absolute paths and `../` traversal are allowed — the execution context is\n * the sandbox boundary, not this tool.\n */\n\nexport const grep: ToolDef = {\n // Searches files without touching them — concurrency-safe.\n isConcurrencySafe: true,\n spec: {\n name: 'grep',\n description: toolPrompts.grep,\n inputSchema: {\n type: 'object',\n properties: {\n 'pattern': { type: 'string', description: 'Regex (PCRE-flavored via ripgrep, JS regex via fallback).' },\n 'patterns': { type: 'array', items: { type: 'string' }, description: 'More regexes; a line matches if it matches `pattern` OR any of these (like `rg -e a -e b`).' },\n 'exclude': { type: 'string', description: 'Drop output lines matching this regex (applied to the whole output line, like piping through `grep -v`).' },\n 'fixed_strings': { type: 'boolean', description: 'Treat patterns as literal strings, not regexes (`-F`).' },\n '-w': { type: 'boolean', description: 'Match whole words only.' },\n 'path': { type: 'string', description: 'File or directory to search. Default: \".\". May be absolute or outside the workspace (no confinement; consistent with read_file).' },\n 'paths': { type: 'array', items: { type: 'string' }, description: 'Several files or directories to search in one call (combined with `path` when both are set).' },\n 'glob': { type: 'string', description: 'Restrict to files matching this glob, e.g. \"**/*.ts\".' },\n 'type': { type: 'string', description: 'rg file type filter, e.g. \"ts\", \"py\", \"rust\". Ignored by the fallback.' },\n 'output_mode': { type: 'string', enum: ['content', 'files_with_matches', 'count'], description: 'Default: \"files_with_matches\".' },\n '-i': { type: 'boolean', description: 'Case-insensitive match.' },\n '-n': { type: 'boolean', description: 'Show line numbers (content mode). Default: true.' },\n '-A': { type: 'integer', description: 'Lines of trailing context (content mode).' },\n '-B': { type: 'integer', description: 'Lines of leading context (content mode).' },\n '-C': { type: 'integer', description: 'Lines of surrounding context (content mode). Overridden by -A/-B if set.' },\n 'multiline': { type: 'boolean', description: 'Allow patterns to match across line boundaries.' },\n 'gitignore': { type: 'boolean', description: 'Skip files git ignores (.gitignore, .git/info/exclude, global excludes). Default: true. Set false to also search ignored files like node_modules.' },\n 'head_limit': { type: 'integer', description: `Cap output lines. Default: 250. Set 0 for unlimited lines. In content mode, context lines (-A/-B/-C) and \"--\" separators count toward the cap, so the number of matches shown may be lower. Output is independently byte-bounded: each line is clipped to ${MAX_LINE_BYTES} bytes and the total to ${OUTPUT_BYTE_CAP} bytes, so long (e.g. minified) lines never overflow the context window.` },\n 'offset': { type: 'integer', description: 'Skip first N output lines. Default: 0.' },\n },\n required: ['pattern'],\n },\n },\n async execute(rawInput, ctx: ToolContext) {\n const input = rawInput as unknown as GrepInput\n const invalid = validateInput(input)\n if (invalid)\n throw new ToolFailure(`grep error: ${invalid}`)\n\n try {\n if (await isRipgrepAvailable(ctx))\n return await runViaRipgrep(input, ctx)\n return await runFallback(input, ctx)\n }\n catch (err) {\n // grep must never leak a raw exception to the model. An abort is the\n // sole exception we re-throw — the loop renders its canonical\n // interrupt/cascade marker; everything else (a broken `exec`, an\n // unreadable tree, a remote transport error) becomes a `grep error:`.\n if (isAbortLikeError(err) || isToolFailure(err))\n throw err\n throw new ToolFailure(`grep error: ${errorMessage(err)}`)\n }\n },\n}\n\n// ---------------------------------------------------------------------------\n// ripgrep path\n// ---------------------------------------------------------------------------\n\n/**\n * Probe ripgrep availability **per call**. The probe is intentionally not\n * cached: caching at module scope would leak across execution contexts (an\n * orchestrator running an in-process agent and a docker agent in the same\n * Node process must be able to differ on whether `rg` exists), and caching\n * per handle adds bookkeeping for negligible savings — `rg --version` is\n * ~5 ms, and grep is invoked at most a few times per turn.\n */\nasync function isRipgrepAvailable(ctx: ToolContext): Promise<boolean> {\n const result = await ctx.execution.exec(ctx.handle, 'rg --version', { signal: ctx.signal })\n return result.exitCode === 0\n}\n\n/**\n * Every regex the call matches on: `pattern` plus non-empty `patterns`. An\n * empty `pattern` next to non-empty `patterns` is dropped: it would match\n * every line.\n */\nfunction allPatterns(input: GrepInput): string[] {\n const extra = Array.isArray(input.patterns) ? input.patterns.filter(p => typeof p === 'string' && p.length > 0) : []\n if (input.pattern === '' && extra.length > 0)\n return extra\n return [input.pattern, ...extra]\n}\n\n/** Search roots: `path` and `paths` combined, defaulting to `.`. */\nfunction searchRoots(input: GrepInput): string[] {\n const roots = [\n ...(typeof input.path === 'string' && input.path.length > 0 ? [input.path] : []),\n ...(Array.isArray(input.paths) ? input.paths.filter(p => typeof p === 'string' && p.length > 0) : []),\n ]\n return roots.length > 0 ? [...new Set(roots)] : ['.']\n}\n\nfunction validateInput(input: GrepInput): string | undefined {\n if (typeof input.pattern !== 'string')\n return '`pattern` must be a string.'\n if (input.patterns !== undefined && (!Array.isArray(input.patterns) || input.patterns.some(p => typeof p !== 'string')))\n return '`patterns` must be an array of strings.'\n if (input.paths !== undefined && (!Array.isArray(input.paths) || input.paths.some(p => typeof p !== 'string')))\n return '`paths` must be an array of strings.'\n if (input.exclude !== undefined) {\n if (typeof input.exclude !== 'string')\n return '`exclude` must be a string.'\n try {\n void new RegExp(input.exclude)\n }\n catch (err) {\n return `invalid exclude regex: ${errorMessage(err)}`\n }\n }\n return undefined\n}\n\nasync function runViaRipgrep(input: GrepInput, ctx: ToolContext): Promise<string> {\n const args = ['rg']\n const mode = (input.output_mode ?? DEFAULT_OUTPUT_MODE) as OutputMode\n\n if (mode === 'files_with_matches')\n args.push('--files-with-matches')\n else if (mode === 'count')\n args.push('--count')\n else\n args.push((input['-n'] ?? true) ? '--line-number' : '--no-line-number')\n\n if (input['-i'])\n args.push('-i')\n if (input.fixed_strings)\n args.push('--fixed-strings')\n if (input['-w'])\n args.push('--word-regexp')\n\n if (mode === 'content') {\n if (typeof input['-A'] === 'number')\n args.push('-A', String(input['-A']))\n if (typeof input['-B'] === 'number')\n args.push('-B', String(input['-B']))\n if (typeof input['-C'] === 'number' && typeof input['-A'] !== 'number' && typeof input['-B'] !== 'number')\n args.push('-C', String(input['-C']))\n }\n\n if (input.multiline)\n args.push('--multiline', '--multiline-dotall')\n\n // ripgrep respects .gitignore by default; only disable it on explicit opt-out.\n if (input.gitignore === false)\n args.push('--no-ignore')\n\n if (input.glob)\n args.push('--glob', input.glob)\n\n if (input.type)\n args.push('--type', input.type)\n\n // `-e` per pattern (OR semantics); `-e` also keeps a leading-dash pattern\n // from parsing as a flag.\n for (const pattern of allPatterns(input))\n args.push('-e', pattern)\n\n // Always pass a path — rg reads from stdin when invoked from a non-TTY child\n // process without a path argument, which hangs forever waiting for input.\n args.push('--', ...searchRoots(input))\n\n const command = args.map(shellQuote).join(' ')\n const result = await ctx.execution.exec(ctx.handle, command, { signal: ctx.signal })\n\n // ripgrep exits 1 when there are no matches — that's not an error here.\n if (result.exitCode !== 0 && result.exitCode !== 1) {\n throw new ToolFailure(`grep error: ${result.stderr.trim() || `rg exited with code ${result.exitCode}`}`)\n }\n\n return formatPaginated(result.stdout, input)\n}\n\n// ---------------------------------------------------------------------------\n// Fallback path (context-routed `find` enumeration + readFile + JS regex)\n// ---------------------------------------------------------------------------\n\nasync function runFallback(input: GrepInput, ctx: ToolContext): Promise<string> {\n const mode = (input.output_mode ?? DEFAULT_OUTPUT_MODE) as OutputMode\n const flags = `${input['-i'] ? 'i' : ''}${input.multiline ? 's' : ''}${mode !== 'content' ? '' : 'g'}`\n\n let regex: RegExp\n try {\n regex = new RegExp(fallbackSource(input), flags || undefined)\n }\n catch (err) {\n throw new ToolFailure(`grep error: invalid regex: ${errorMessage(err)}`)\n }\n\n const multilineRegex = input.multiline ? new RegExp(regex.source, `${flags.replace(/g/, '')}g`) : undefined\n const files: string[] = []\n for (const root of searchRoots(input)) {\n for (const file of await enumerateFiles(input, root, ctx)) {\n if (!files.includes(file))\n files.push(file)\n }\n }\n const showLineNumbers = input['-n'] ?? true\n const before = (input['-B'] ?? input['-C'] ?? 0)\n const after = (input['-A'] ?? input['-C'] ?? 0)\n\n // Second layer of the fallback's OOM guard, scoped to the single-file\n // fast path ONLY: walk-enumerated files are already size-filtered by\n // the find predicate, and probing each of them would cost one exec per\n // file on exec-probed contexts (docker/sandbox) — N extra round-trips\n // for zero added protection. The fast path bypasses the walk, so it is\n // the one entry that needs the probe. (Contexts without the capability\n // proceed unguarded: same accepted residual as whole-read-guard.ts.)\n const viaSingleFileFastPath = files.length === 1 && searchRoots(input).includes(files[0] as string)\n if (viaSingleFileFastPath) {\n const size = await ctx.execution.fileSize?.(ctx.handle, files[0] as string) ?? null\n if (size !== null && size > FALLBACK_MAX_FILE_BYTES)\n return '(no matches)'\n }\n\n const lines: string[] = []\n for (const path of files) {\n let content: string\n try {\n content = await ctx.execution.readFile(ctx.handle, path)\n }\n catch (err) {\n // Skip unreadable / binary / vanished files — but let an abort\n // propagate (a remote readFile may reject with AbortError on cancel).\n if (isAbortLikeError(err))\n throw err\n continue\n }\n if (multilineRegex) {\n // Multiline mode: scan the whole buffer with /g semantics.\n const allMatches = [...content.matchAll(multilineRegex)]\n if (allMatches.length === 0)\n continue\n if (mode === 'files_with_matches') {\n lines.push(path)\n continue\n }\n if (mode === 'count') {\n lines.push(`${path}:${allMatches.length}`)\n continue\n }\n // content mode — emit each match's surrounding line context. Line\n // numbers advance incrementally (matches arrive in index order) instead\n // of re-splitting the prefix per match (which costs O(matches x size)).\n let lineNo = 1\n let scannedTo = 0\n for (const m of allMatches) {\n const lineStart = content.lastIndexOf('\\n', m.index! - 1) + 1\n const lineEnd = content.indexOf('\\n', m.index!)\n const snippet = content.slice(lineStart, lineEnd === -1 ? undefined : lineEnd)\n for (let nl = content.indexOf('\\n', scannedTo); nl !== -1 && nl < m.index!; nl = content.indexOf('\\n', nl + 1))\n lineNo++\n scannedTo = m.index!\n lines.push(formatContentLine(path, lineNo, snippet, showLineNumbers))\n }\n continue\n }\n\n const fileLines = content.split('\\n')\n const matched: number[] = []\n for (let i = 0; i < fileLines.length; i++) {\n regex.lastIndex = 0\n if (regex.test(fileLines[i]))\n matched.push(i)\n }\n if (matched.length === 0)\n continue\n\n if (mode === 'files_with_matches') {\n lines.push(path)\n continue\n }\n if (mode === 'count') {\n lines.push(`${path}:${matched.length}`)\n continue\n }\n\n const includeLineNos = new Set<number>()\n for (const m of matched) {\n for (let i = Math.max(0, m - before); i <= Math.min(fileLines.length - 1, m + after); i++)\n includeLineNos.add(i)\n }\n const sorted = [...includeLineNos].sort((a, b) => a - b)\n let prev = -2\n for (const lineNo of sorted) {\n if (lineNo > prev + 1 && lines.length > 0)\n lines.push('--')\n const snippet = fileLines[lineNo]\n lines.push(formatContentLine(path, lineNo + 1, snippet, showLineNumbers))\n prev = lineNo\n }\n }\n\n return formatPaginated(lines.join('\\n'), input)\n}\n\nfunction formatContentLine(path: string, lineNo: number, snippet: string, showLineNumbers: boolean): string {\n return showLineNumbers ? `${path}:${lineNo}:${snippet}` : `${path}:${snippet}`\n}\n\n/**\n * JS regex source for the fallback: patterns OR'ed together, escaped under\n * `fixed_strings`, wrapped in word boundaries under `-w`.\n */\nfunction fallbackSource(input: GrepInput): string {\n const parts = allPatterns(input).map(p => input.fixed_strings ? p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') : p)\n const joined = parts.length === 1 ? parts[0] : parts.map(p => `(?:${p})`).join('|')\n return input['-w'] ? `\\\\b(?:${joined})\\\\b` : joined\n}\n\nasync function enumerateFiles(input: GrepInput, root: string, ctx: ToolContext): Promise<string[]> {\n // Single-file fast path: if the root names a file, search just it. Routed\n // through `exec` so the check runs inside the context, not on the host.\n if (root !== '.' && !root.includes('*') && !root.includes('?')) {\n const probe = await ctx.execution.exec(ctx.handle, `test -f ${shellQuote(root)} && echo file || echo dir`, { signal: ctx.signal })\n if (probe.stdout.trim() === 'file')\n return [root]\n }\n\n // Enumerate through the execution context's shell so the listing comes from\n // wherever the context's files live — never the host filesystem. `find` is\n // the same primitive the `glob` tool's portable path uses.\n const result = await ctx.execution.exec(ctx.handle, buildFindCommand(root, input.glob), { signal: ctx.signal })\n\n // A non-zero exit with NO output is a real failure (find unavailable, bad\n // root) — surface it like ripgrep would for a bad path. A non-zero exit WITH\n // output is a partial walk (e.g. an unreadable subdir): keep what we got.\n // `find` writes diagnostics to\n // stderr, so stdout stays a clean newline-separated path list either way.\n if (result.exitCode !== 0 && !result.stdout.trim())\n throw new Error(result.stderr.trim() || `find exited with code ${result.exitCode}`)\n\n const files = result.stdout\n .split('\\n')\n .map(line => line.replace(/^\\.\\//, ''))\n .filter(line => line.length > 0)\n .sort()\n\n // `find` honors no ignore rules, so the no-`rg` fallback would otherwise\n // walk `node_modules` etc. — inconsistent with the ripgrep path. Restrict to\n // git's non-ignored set by default; `gitignore: false` keeps everything.\n if (input.gitignore === false)\n return files\n return filterByGitignore(files, root, ctx)\n}\n\n/**\n * Best-effort intersection of `files` with `git ls-files` (non-ignored set).\n * Returns `files` unchanged when git is unavailable, the dir isn't a repo, or\n * `root` escapes the repo (absolute / `..`) — the filter can only fail open.\n */\nasync function filterByGitignore(files: string[], root: string, ctx: ToolContext): Promise<string[]> {\n if (files.length === 0)\n return files\n if (root !== '.' && (root.startsWith('/') || root.split('/').includes('..')))\n return files\n try {\n const res = await ctx.execution.exec(ctx.handle, GIT_LS_FILES_COMMAND, { signal: ctx.signal })\n if (res.exitCode !== 0)\n return files\n const allowed = new Set(parseGitLsFiles(res.stdout))\n if (allowed.size === 0)\n return files\n return files.filter(file => allowed.has(file))\n }\n catch {\n return files\n }\n}\n\n/**\n * Build a `find` command listing files under `root`, optionally filtered by\n * `glob`. Mirrors `glob`'s shell fallback:\n * - a bare basename, or one behind a leading recursive-wildcard segment,\n * with no inner slash → `-name` (matches at any depth, including the top\n * level — preserving the recursive-glob semantics).\n * - anything with a slash → `-path` against the full relative path. `find`'s\n * `*` spans `/`, so the single- and double-star forms collapse to the\n * same matcher; close enough for the no-`rg` fallback.\n */\nfunction buildFindCommand(root: string, glob?: string): string {\n const findRoot = normalizeFindRoot(root)\n const base = shellQuote(findRoot)\n const sizeGuard = `! -size +${FALLBACK_MAX_FILE_BYTES}c`\n if (!glob)\n return `find ${base} -type f ${sizeGuard}`\n const anyDepth = glob.match(/^(?:\\*\\*\\/)?([^/]+)$/)\n if (anyDepth)\n return `find ${base} -type f ${sizeGuard} -name ${shellQuote(anyDepth[1])}`\n const normRoot = findRoot.replace(/\\/$/, '')\n const pathPattern = root === '.' ? `./${glob}` : `${normRoot}/${glob}`\n return `find ${base} -type f ${sizeGuard} -path ${shellQuote(pathPattern)}`\n}\n\nfunction normalizeFindRoot(root: string): string {\n // POSIX `find` parses a leading-dash first operand as an expression/option.\n // Prefix relative paths like `-fixtures` so they remain path operands.\n return root.startsWith('-') ? `./${root}` : root\n}\n\nfunction formatPaginated(text: string, input: GrepInput): string {\n const headLimit = typeof input.head_limit === 'number' && input.head_limit >= 0\n ? input.head_limit\n : DEFAULT_HEAD_LIMIT\n const offset = typeof input.offset === 'number' && input.offset > 0\n ? Math.floor(input.offset)\n : 0\n\n if (!text.trim())\n return '(no matches)'\n\n const lines = applyExclude(text.split('\\n').filter(l => l.length > 0), input.exclude)\n if (lines.length === 0)\n return '(no matches after exclude)'\n const total = lines.length\n\n const sliced = headLimit === 0\n ? lines.slice(offset)\n : lines.slice(offset, offset + headLimit)\n\n if (sliced.length === 0)\n return '(no matches in this slice)'\n\n // Byte budget. `head_limit` caps the LINE count, but a single line can be\n // arbitrarily large (a minified / one-line file is one match line = the whole\n // file), so a line cap alone leaves byte output unbounded and can overflow the\n // model context. Clip each line, then stop once the total crosses the cap.\n const capped: string[] = []\n let bytesUsed = 0\n let byteCut = false\n for (const line of sliced) {\n const clipped = clipLine(line)\n const lineBytes = Buffer.byteLength(clipped) + 1 // +1 for the rejoining '\\n'\n if (bytesUsed + lineBytes > OUTPUT_BYTE_CAP && capped.length > 0) {\n byteCut = true\n break\n }\n capped.push(clipped)\n bytesUsed += lineBytes\n }\n\n const shown = capped.length\n const truncatedHead = offset > 0\n // Lines withheld by the line-count window, independent of the byte cut.\n const lineCutTail = headLimit > 0 && offset + headLimit < total\n\n // Markers say \"lines\", not \"matches\" — in content mode the pagination\n // unit includes context lines and `--` separators.\n let out = capped.join('\\n')\n if (truncatedHead)\n out = `…(${offset} earlier lines skipped)…\\n${out}`\n if (byteCut)\n out = `${out}\\n…(output truncated at ${OUTPUT_BYTE_CAP} bytes after ${shown} of ${total - offset} matching lines; narrow the pattern or page with offset=${offset + shown})`\n else if (lineCutTail)\n out = `${out}\\n…(${total - offset - headLimit} more lines; re-run with offset=${offset + headLimit} or larger head_limit)`\n return out\n}\n\n/**\n * Drop output lines matching `exclude` (validated upfront). Context-group\n * `--` separators are kept only between surviving lines, never doubled or at\n * the edges.\n */\nfunction applyExclude(lines: string[], exclude: string | undefined): string[] {\n if (!exclude)\n return lines\n const re = new RegExp(exclude)\n const kept: string[] = []\n for (const line of lines) {\n if (line === '--') {\n if (kept.length > 0 && kept[kept.length - 1] !== '--')\n kept.push(line)\n continue\n }\n if (!re.test(line))\n kept.push(line)\n }\n while (kept.length > 0 && kept[kept.length - 1] === '--')\n kept.pop()\n return kept\n}\n\n/**\n * Clip one output line to `MAX_LINE_BYTES` at a UTF-8-safe boundary, appending\n * a marker that reports how many bytes were withheld. Lines within budget pass\n * through untouched.\n */\nfunction clipLine(line: string): string {\n if (Buffer.byteLength(line) <= MAX_LINE_BYTES)\n return line\n let cut = Math.min(line.length, MAX_LINE_BYTES)\n while (cut > 0 && Buffer.byteLength(line.slice(0, cut)) > MAX_LINE_BYTES)\n cut--\n const omitted = Buffer.byteLength(line) - Buffer.byteLength(line.slice(0, cut))\n return `${line.slice(0, cut)}… [line clipped, ${omitted} more bytes]`\n}\n","/**\n * Interaction tool — lets the agent request structured input from the outside world.\n *\n * Not included in any preset by default. Add it explicitly:\n *\n * import { createInteractionTool } from 'zidane'\n *\n * const askUser = createInteractionTool({\n * schema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] },\n * onRequest: async (payload) => {\n * const answer = await promptUser(payload.question)\n * return { answer }\n * },\n * })\n *\n * const preset = definePreset({ name: 'interactive', tools: { ...basicTools, ask_user: askUser } })\n */\n\nimport type { ToolContext, ToolDef } from './types'\nimport { toolPrompts } from './prompts'\n\nfunction abortReason(signal: AbortSignal): string {\n return typeof signal.reason === 'string' && signal.reason.length > 0\n ? signal.reason\n : 'Interaction aborted'\n}\n\n/** Options for {@link createInteractionTool}. */\nexport interface InteractionToolOptions {\n /** JSON Schema for the request payload the model sends */\n schema: Record<string, unknown>\n /** Tool name (default: 'interaction') */\n name?: string\n /** Tool description shown to the model */\n description?: string\n /** Called when the model invokes this tool. Receives the validated payload and tool context, returns data for the model. */\n onRequest: (payload: Record<string, unknown>, ctx: ToolContext) => Promise<Record<string, unknown> | string>\n}\n\n/**\n * Create an interaction tool that lets the agent request structured input.\n *\n * The model calls this tool with a payload matching the schema.\n * `onRequest` is called with the payload and should return the response\n * (string or object) that gets sent back to the model as the tool result.\n * @param options - Payload schema, optional name and description, and the `onRequest` handler.\n * @example\n * ```ts\n * import { createInteractionTool } from 'zidane/tools'\n *\n * const askUser = createInteractionTool({\n * name: 'ask_user',\n * schema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] },\n * onRequest: async payload => `Answer to: ${String(payload.question)}`,\n * })\n * ```\n */\nexport function createInteractionTool(options: InteractionToolOptions): ToolDef {\n const name = options.name ?? 'interaction'\n const description = options.description ?? toolPrompts.interaction\n\n return {\n spec: {\n name,\n description,\n inputSchema: options.schema,\n },\n async execute(input, ctx) {\n // Race the host resolver against the run's abort signal. `onRequest`\n // settles only on external (human/system) action, so without this an\n // `agent.abort()` / `agent.destroy()` — every teardown/cancel path —\n // would leave the tool body (and the run) hanging on a promise that can\n // never settle. On abort we reject so the loop unwinds cleanly.\n const { signal } = ctx\n if (signal?.aborted)\n throw new Error(abortReason(signal))\n\n let onAbort: (() => void) | undefined\n const abortPromise = signal\n ? new Promise<never>((_, reject) => {\n onAbort = () => reject(new Error(abortReason(signal)))\n signal.addEventListener('abort', onAbort, { once: true })\n })\n : undefined\n\n try {\n const result = abortPromise\n ? await Promise.race([options.onRequest(input, ctx), abortPromise])\n : await options.onRequest(input, ctx)\n return typeof result === 'string' ? result : JSON.stringify(result)\n }\n finally {\n if (signal && onAbort)\n signal.removeEventListener('abort', onAbort)\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;;AAGjC,MAAM,iBAAiB;;AAGvB,MAAM,sBAAsB;AA+B5B,SAAS,UAAU,SAAoD;CACrE,OAAO,QAAQ,SAAQ,WAAU,OAAO,OAAO,OAAO,KAAI,WAAU;EAAE;EAAQ;EAAO,KAAK,GAAG,OAAO,SAAS,GAAG,MAAM;CAAK,EAAE,CAAC;AAChI;AAEA,SAAS,mBAAmB,KAAsC;CAEhE,QADkB,IAAI,WAAW,SAAS,IAAI,YAAY,CAAC,IAAI,QAAQ,EAAA,CACtD,SAAS,aAAa;EACrC,MAAM,SAAS,SAAS;EACxB,OAAO,UAAU,OAAO,aAAa,CAAC,CAAC,YAAY,CAAC;GAAE,UAAU,SAAS;GAAM;EAAO,CAAC,IAAI,CAAC;CAC9F,CAAC;AACH;;AAGA,SAAS,UAA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,YAAY,MAAM,CAAC,CAAC;IACrD,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;GAC1D,CAAC,IACD,KAAA;GAEJ,IAAI;IACF,MAAM,SAAS,eACX,MAAM,QAAQ,KAAK,CAAC,QAAQ,UAAU,OAAO,GAAG,GAAG,YAAY,CAAC,IAChE,MAAM,QAAQ,UAAU,OAAO,GAAG;IACtC,OAAO,OAAO,WAAW,WAAW,SAAS,KAAK,UAAU,MAAM;GACpE,UACQ;IACN,IAAI,UAAU,SACZ,OAAO,oBAAoB,SAAS,OAAO;GAC/C;EACF;CACF;AACF"}
package/dist/tools.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { $T as ToolDescriptionOverride, $r as edit, $u as ExtensionSubagentDef, Ar as SkillsUseToolOptions, Br as RECORD_ARTIFACT_TOOL, Cr as writeFile, Da as ToolSearchToolOptions, Dr as validateToolArgs, Ea as LazyToolEntry, Er as ValidationResult, Fr as createSkillsReadTool, Gr as InteractionToolOptions, Hr as readFile, Ir as shellKill, Jr as glob, Kr as createInteractionTool, Lr as CreateShellToolOptions, Mr as SkillsRunScriptToolOptions, Nr as createSkillsRunScriptTool, Oa as createToolSearchTool, Or as TailTruncateOptions, Pr as SkillsReadToolOptions, QT as ToolDef, Qr as createGenerateImageTool, Qu as ChildAgent, Rr as createShellTool, Tr as waitTask, Ur as multiEdit, Vr as recordArtifact, Wr as listFiles, Xr as GenerateImageToolOptions, Yr as DEFAULT_IMAGE_DIR, ZT as ToolContext, Zr as ImageModelSource, aE as ReadStateMap, ad as SubagentDef, cE as hydrateReadStateFromSession, cd as createSpawnTool, dE as resolveReadStateMap, dd as SpawnModelEntry, eE as ToolDescriptionTarget, ed as SpawnTaskInput, fd as createModelSearchTool, iE as ReadStateEntry, id as SpawnToolState, jr as createSkillsUseTool, kr as tailTruncate, lE as hydrateReadStateFromSessionAsync, ld as withIsolatedSpawnTool, md as matchModelEntries, nE as ToolMap, nd as SpawnTool, oE as getReadState, od as SubagentOverride, pd as formatModelLine, qr as grep, rE as HydrateReadStateOptions, rd as SpawnToolOptions, sE as hashContent, sd as SubagentRegistry, tE as ToolDescriptions, td as SpawnTaskOutcome, uE as readStateKey, ud as isSpawnTool, wr as WAIT_TASK_TIMED_OUT_PREFIX, zr as shell } from "./index-DyQyDLX1.js";
1
+ import { $T as ToolDef, $r as edit, $u as ExtensionSubagentDef, Ar as SkillsUseToolOptions, Br as RECORD_ARTIFACT_TOOL, Cr as writeFile, Da as ToolSearchToolOptions, Dr as validateToolArgs, Ea as LazyToolEntry, Er as ValidationResult, Fr as createSkillsReadTool, Gr as InteractionToolOptions, Hr as readFile, Ir as shellKill, Jr as glob, Kr as createInteractionTool, Lr as CreateShellToolOptions, Mr as SkillsRunScriptToolOptions, Nr as createSkillsRunScriptTool, Oa as createToolSearchTool, Or as TailTruncateOptions, Pr as SkillsReadToolOptions, QT as ToolContext, Qr as createGenerateImageTool, Qu as ChildAgent, Rr as createShellTool, Tr as waitTask, Ur as multiEdit, Vr as recordArtifact, Wr as listFiles, Xr as GenerateImageToolOptions, Yr as DEFAULT_IMAGE_DIR, Zr as ImageModelSource, aE as ReadStateEntry, ad as SubagentDef, cE as hashContent, cd as createSpawnTool, dE as readStateKey, dd as SpawnModelEntry, eE as ToolDescriptionOverride, ed as SpawnTaskInput, fE as resolveReadStateMap, fd as createModelSearchTool, iE as HydrateReadStateOptions, id as SpawnToolState, jr as createSkillsUseTool, kr as tailTruncate, lE as hydrateReadStateFromSession, ld as withIsolatedSpawnTool, md as matchModelEntries, nE as ToolDescriptions, nd as SpawnTool, oE as ReadStateMap, od as SubagentOverride, pd as formatModelLine, qr as grep, rE as ToolMap, rd as SpawnToolOptions, sE as getReadState, sd as SubagentRegistry, tE as ToolDescriptionTarget, td as SpawnTaskOutcome, uE as hydrateReadStateFromSessionAsync, ud as isSpawnTool, wr as WAIT_TASK_TIMED_OUT_PREFIX, zr as shell } from "./index-4mDRyTGJ.js";
2
2
  import { n as toolPrompts, t as ToolPrompts } from "./prompts-DmY13jvF.js";
3
3
  export { type ChildAgent, type CreateShellToolOptions, DEFAULT_IMAGE_DIR, type ExtensionSubagentDef, type GenerateImageToolOptions, type HydrateReadStateOptions, type ImageModelSource, type InteractionToolOptions, type LazyToolEntry, RECORD_ARTIFACT_TOOL, type ReadStateEntry, type ReadStateMap, type SkillsReadToolOptions, type SkillsRunScriptToolOptions, type SkillsUseToolOptions, type SpawnModelEntry, type SpawnTaskInput, type SpawnTaskOutcome, type SpawnTool, type SpawnToolOptions, type SpawnToolState, type SubagentDef, type SubagentOverride, type SubagentRegistry, type TailTruncateOptions, type ToolContext, type ToolDef, type ToolDescriptionOverride, type ToolDescriptionTarget, type ToolDescriptions, type ToolMap, type ToolPrompts, type ToolSearchToolOptions, type ValidationResult, WAIT_TASK_TIMED_OUT_PREFIX, createGenerateImageTool, createInteractionTool, createModelSearchTool, createShellTool, createSkillsReadTool, createSkillsRunScriptTool, createSkillsUseTool, createSpawnTool, createToolSearchTool, edit, formatModelLine, getReadState, glob, grep, hashContent, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, isSpawnTool, listFiles, matchModelEntries, multiEdit, readFile, readStateKey, recordArtifact, resolveReadStateMap, shell, shellKill, tailTruncate, toolPrompts, validateToolArgs, waitTask, withIsolatedSpawnTool, writeFile };
package/dist/tools.js CHANGED
@@ -3,7 +3,7 @@ import { a as hydrateReadStateFromSessionAsync, c as readStateKey, i as hydrateR
3
3
  import { a as shell, f as tailTruncate, i as createShellTool, l as validateToolArgs, n as waitTask, r as shellKill, t as WAIT_TASK_TIMED_OUT_PREFIX } from "./wait-task-BZiNOAcc.js";
4
4
  import { a as createToolSearchTool, n as createSkillsRunScriptTool, r as createSkillsReadTool, t as createSkillsUseTool } from "./skills-use-CssTEaIj.js";
5
5
  import { toolPrompts } from "./tools/prompts.js";
6
- import { c as edit, d as recordArtifact, f as createSpawnTool, n as readFile, o as multiEdit, p as withIsolatedSpawnTool, s as listFiles, t as writeFile, u as RECORD_ARTIFACT_TOOL } from "./write-file-QYrcDdl3.js";
6
+ import { c as edit, d as recordArtifact, f as createSpawnTool, n as readFile, o as multiEdit, p as withIsolatedSpawnTool, s as listFiles, t as writeFile, u as RECORD_ARTIFACT_TOOL } from "./write-file-ChtRPdEL.js";
7
7
  import { g as matchModelEntries, h as formatModelLine, m as createModelSearchTool } from "./spawn-result-B4vmHy7T.js";
8
- import { a as createGenerateImageTool, i as DEFAULT_IMAGE_DIR, n as grep, r as glob, t as createInteractionTool } from "./tools-pZVFIJ_K.js";
8
+ import { a as createGenerateImageTool, i as DEFAULT_IMAGE_DIR, n as grep, r as glob, t as createInteractionTool } from "./tools-FHEIKGkh.js";
9
9
  export { DEFAULT_IMAGE_DIR, RECORD_ARTIFACT_TOOL, WAIT_TASK_TIMED_OUT_PREFIX, createGenerateImageTool, createInteractionTool, createModelSearchTool, createShellTool, createSkillsReadTool, createSkillsRunScriptTool, createSkillsUseTool, createSpawnTool, createToolSearchTool, edit, formatModelLine, getReadState, glob, grep, hashContent, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, isSpawnTool, listFiles, matchModelEntries, multiEdit, readFile, readStateKey, recordArtifact, resolveReadStateMap, shell, shellKill, tailTruncate, toolPrompts, validateToolArgs, waitTask, withIsolatedSpawnTool, writeFile };
@@ -4,21 +4,21 @@ import { a as projectRootOf, t as findGitRoot$1 } from "./project-root-BOgUA6n5.
4
4
  import { m as shortId, n as ageString, o as fmtTokens } from "./format-YgaIcuQ5.js";
5
5
  import { c as collectReferences, f as mergeSuggestions, s as applyInsert, u as findActiveTriggers } from "./inline-ghost-D-TefgOp.js";
6
6
  import { t as mergeReplyText } from "./reply-text-Qkc6DtEt.js";
7
- import { a as listMarkdownDefFiles, o as markdownDefRoots } from "./headless-R4pbpTkm.js";
7
+ import { a as listMarkdownDefFiles, o as markdownDefRoots } from "./headless-Bs9Lb4vs.js";
8
8
  import { t as projectUserPaths } from "./project-user-paths-DWqZyUgb.js";
9
9
  import { r as artifactKindLabel, u as renderArtifactRow } from "./builtin-artifact-kinds-BmorPkgz.js";
10
10
  import { B as normalizeGithubHost, L as githubClient, M as clockSkewMs, z as githubTokenSource } from "./row-fields-F0tyvIgg.js";
11
- import { O as formatBindingForDisplay } from "./extensions-BgBwogRW.js";
11
+ import { O as formatBindingForDisplay } from "./extensions-BJof-2mi.js";
12
12
  import { t as resolveStorageDirs } from "./xdg-CJS70jqe.js";
13
13
  import { p as oauthAccountLabel } from "./cred-keys-C0KaSRp7.js";
14
14
  import { l as resolveOAuthApiKey } from "./oauth-DRrs-65k.js";
15
- import { A as stepTranscriptCap, Ln as providerBrand, M as takeChars, O as smoothCharsForTick, g as appendThinkingLines, h as appendMarkdownDelta, kn as NATIVE_EXTENSIONS, vn as reduceMcpAuth } from "./transcript-reconcile-CPdrNbbR.js";
16
- import { P as settingsFromStored, f as enforceSettingsInvariants, v as DEFAULT_THEME } from "./secret-shapes-BjW4l6U0.js";
17
- import { C as foreignSkillScanPaths, S as foreignMcpConfigFiles, _ as parseMcpsFile, g as parseJsonTolerant, m as defaultMcpsConfigPaths, w as parseClaudeState } from "./host-scoped-settings-C-Nmb6vr.js";
18
- import { c as mcpsWritePath, i as supportsOAuth, u as upsertMcpServer } from "./oauth-7_48zR7n.js";
19
- import { i as deriveSessionTitle } from "./store-L01W0gGI.js";
20
- import { S as credKeyOf, g as storedCredentialsOf, n as credentialsPath, o as readCredentials } from "./credentials-B9DfBJP9.js";
21
- import { r as detectAuth } from "./cli-shared-E5m_pI8A.js";
15
+ import { A as stepTranscriptCap, Ln as providerBrand, M as takeChars, O as smoothCharsForTick, g as appendThinkingLines, h as appendMarkdownDelta, kn as NATIVE_EXTENSIONS, vn as reduceMcpAuth } from "./transcript-reconcile-D_SWw6dX.js";
16
+ import { P as settingsFromStored, f as enforceSettingsInvariants, v as DEFAULT_THEME } from "./secret-shapes-HvaYVzwc.js";
17
+ import { C as foreignSkillScanPaths, S as foreignMcpConfigFiles, _ as parseMcpsFile, g as parseJsonTolerant, m as defaultMcpsConfigPaths, w as parseClaudeState } from "./host-scoped-settings-DxxI_yRo.js";
18
+ import { c as mcpsWritePath, i as supportsOAuth, u as upsertMcpServer } from "./oauth-BwPiX0hL.js";
19
+ import { i as deriveSessionTitle } from "./store-BpkWIaSH.js";
20
+ import { S as credKeyOf, g as storedCredentialsOf, n as credentialsPath, o as readCredentials } from "./credentials-DxOQmset.js";
21
+ import { r as detectAuth } from "./cli-shared-GOehTeqk.js";
22
22
  import { Buffer } from "node:buffer";
23
23
  import { chmodSync, closeSync, cpSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
24
24
  import { basename, delimiter, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
@@ -5546,4 +5546,4 @@ function computeTurnAnchors(items) {
5546
5546
  //#endregion
5547
5547
  export { truncateTrailing as $, groupArtifacts as $t, buildToolToggle as A, buildRestartHint as At, useInteractionsActions as B, writeUpdateAppliedMarker as Bt, providerUsageSupported as C, claudeImportHostNote as Ct, fetchOAuthRedirect as D, previewClaudeImport as Dt, formatPathForCwd as E, importFromClaudeCode as Et, parentServerName as F, probeInstalledVersion as Ft, onboardingInstallSignals as G, detectLibc as Gt, connectorGithubToken as H, checkForUpdate as Ht, McpAuthProvider as I, readUpdateAppliedMarker as It, onboardingProviders as J, parseSemver as Jt, probeLocalModelServers as K, detectPackageManager as Kt, useMcpAuthDispatch as L, updateAppliedMarkerPath as Lt, useMcpToolToggleSet as M, useUpdateCheck as Mt, buildVisibleMcpRows as N, UPDATE_APPLIED_MARKER as Nt, normalizeRedirectPaste as O, bootProfileEnabled as Ot, indexOfServerRow as P, hasUpdateAppliedMarker as Pt, hintsLength as Q, resolvePlatformPackage as Qt, useMcpAuthState as R, useRestartRequired as Rt, fetchProviderUsageAccounts as S, CLAUDE_IMPORT_NOTES as St, usageSourceFor as T, hasClaudeCodeSetup as Tt, detectOnboardingEnvironment as U, checkTarballAvailable as Ut, useInteractionsQueue as V, findInstalledCompanion as Vt, detectOtherAgents as W, compareSemver as Wt, clipHintsToWidth as X, performSelfUpdate as Xt, EMPTY_HINTS as Y, performInPlaceSelfUpdate as Yt, hintLayout as Z, reinstallHint as Zt, withRunningCallStarts as _, useConfig as _t, useSurfaces as a, useEnabledToggleSet as at, fetchAllProviderUsage as b, scoreArtifacts as bt, useStreamBuffer as c, useSettings as ct, resolveSessionExportTarget as d, createDiscoverySlot as dt, summarizeArtifactCounts as en, fetchGithubUsage as et, writeSessionExport as f, DiscoveryProvider as ft, hasUntimedOpenCalls as g, ConfigProvider as gt, useSafeModeQueue as h, ConfigContext as ht, useSelectStyle as i, listProjectFiles as it, useMcpToolToggleMap as j, buildUpdateHint as jt, redirectUriFromAuthUrl as k, bootTick as kt, aggregateUsage as l, parseEditorCommand as lt, useSafeModeActions as m, useDiscoveryOptional as mt, ThemeProvider as n, shortChord as nt, useSyntaxStyles as o, SettingsOverride as ot, SafeModeProvider as p, useDiscovery as pt, FEATURED_PROVIDERS as q, overrideManager as qt, useColors as r, fileEntriesFromPaths as rt, useTheme as s, SettingsProvider as st, computeTurnAnchors as t, buildHints as tt, renderSession as u, quoteForShell as ut, USAGE_CACHE_TTL_MS as v, ARTIFACTS_COMPLETION_PROVIDER_ID as vt, usageChecksOptedOut as w, countClaudeSessionFiles as wt, fetchProviderUsage as x, useCompletion as xt, clearProviderUsageCache as y, createArtifactsCompletionProvider as yt, InteractionsProvider as z, watchInstalledVersion as zt };
5548
5548
 
5549
- //# sourceMappingURL=transcript-anchors-jHrg-r-H.js.map
5549
+ //# sourceMappingURL=transcript-anchors-BcFLh3ZA.js.map