@diffra-ai/cli 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/dist/bundle/chunks/{anthropic-messages-5EMOURYI.js → anthropic-messages-T6QSBW2I.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-N67KWG2X.js → azure-openai-responses-QHACUEEL.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-CES65UJH.js → chunk-2CWIL3U7.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-PISJX26Y.js → chunk-3OQXW6CV.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-NEFH2K3C.js → chunk-ACRSTWI3.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-QYYUGS66.js → chunk-EMYFX4WY.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-RTPG7C5I.js → chunk-GU5QXRH2.js} +344 -315
  10. package/dist/bundle/chunks/{chunk-BF423NQ7.js → chunk-HGCDVLYI.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-SI7T4LPD.js → chunk-J3RI6JJL.js} +2 -2
  12. package/dist/bundle/chunks/{chunk-VOKUVFV4.js → chunk-JZ2OAQAK.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-HFTZ6OJJ.js → chunk-TXISM6X7.js} +4 -4
  14. package/dist/bundle/chunks/{chunk-3UNTEQ65.js → chunk-UVU7AFFV.js} +1 -1
  15. package/dist/bundle/chunks/chunk-YTFC5DOS.js +2 -0
  16. package/dist/bundle/chunks/{chunk-RLMZZV4Q.js → chunk-ZTDZEFOK.js} +1 -1
  17. package/dist/bundle/chunks/{cli-55VO5MAJ.js → cli-B74BATSM.js} +1 -1
  18. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-HB5U67WC.js → cloudflare-workers-ai-system-one-IRTLSYMY.js} +1 -1
  19. package/dist/bundle/chunks/{execute-OEFRHFHI.js → execute-YR7Q5B3S.js} +1 -1
  20. package/dist/bundle/chunks/{google-generative-ai-XRHE7R52.js → google-generative-ai-J4JVZXHV.js} +1 -1
  21. package/dist/bundle/chunks/{google-vertex-75CQOPKC.js → google-vertex-A36RXRWN.js} +1 -1
  22. package/dist/bundle/chunks/{llama-cpp-classify-LKIRB7ZR.js → llama-cpp-classify-WD5MJBC7.js} +1 -1
  23. package/dist/bundle/chunks/{mistral-conversations-KLGIHK73.js → mistral-conversations-YIKS5LKW.js} +1 -1
  24. package/dist/bundle/chunks/{openai-codex-responses-7L5VV67U.js → openai-codex-responses-UBNJIYCO.js} +1 -1
  25. package/dist/bundle/chunks/{openai-completions-RBF6UXDW.js → openai-completions-WBIL7MLK.js} +1 -1
  26. package/dist/bundle/chunks/{openai-decisions-W3PJQIOF.js → openai-decisions-6T6CQTOT.js} +1 -1
  27. package/dist/bundle/chunks/{openai-responses-W5ZMLOTR.js → openai-responses-W2CLKVKJ.js} +1 -1
  28. package/dist/bundle/chunks/{openrouter-images-4FW6VFV4.js → openrouter-images-ZP4QC3RD.js} +1 -1
  29. package/dist/bundle/chunks/{pi-messages-RT7FVQ4G.js → pi-messages-VHFVA66D.js} +1 -1
  30. package/dist/bundle/chunks/{typesafe-system-one-DSJ7OYVL.js → typesafe-system-one-GORHCFHB.js} +1 -1
  31. package/dist/bundle/chunks/{virtual-modules-M75O3ECA.js → virtual-modules-XMXHVMFN.js} +1 -1
  32. package/dist/bundle/cli-runtime.js +1 -1
  33. package/dist/bundle/index.js +1 -1
  34. package/dist/bundle/rpc-entry.js +1 -1
  35. package/dist/core/agent-session.d.ts +68 -0
  36. package/dist/core/agent-session.d.ts.map +1 -1
  37. package/dist/core/agent-session.js +173 -9
  38. package/dist/core/agent-session.js.map +1 -1
  39. package/dist/core/background-commands.d.ts +71 -0
  40. package/dist/core/background-commands.d.ts.map +1 -0
  41. package/dist/core/background-commands.js +158 -0
  42. package/dist/core/background-commands.js.map +1 -0
  43. package/dist/core/decisions.d.ts +144 -0
  44. package/dist/core/decisions.d.ts.map +1 -0
  45. package/dist/core/decisions.js +74 -0
  46. package/dist/core/decisions.js.map +1 -0
  47. package/dist/core/explain-tool-call.d.ts +20 -0
  48. package/dist/core/explain-tool-call.d.ts.map +1 -0
  49. package/dist/core/explain-tool-call.js +39 -0
  50. package/dist/core/explain-tool-call.js.map +1 -0
  51. package/dist/core/extensions/loader.d.ts.map +1 -1
  52. package/dist/core/extensions/loader.js +11 -0
  53. package/dist/core/extensions/loader.js.map +1 -1
  54. package/dist/core/extensions/runner.d.ts +3 -0
  55. package/dist/core/extensions/runner.d.ts.map +1 -1
  56. package/dist/core/extensions/runner.js +15 -0
  57. package/dist/core/extensions/runner.js.map +1 -1
  58. package/dist/core/extensions/types.d.ts +29 -1
  59. package/dist/core/extensions/types.d.ts.map +1 -1
  60. package/dist/core/extensions/types.js.map +1 -1
  61. package/dist/core/tools/background-tasks.d.ts +35 -0
  62. package/dist/core/tools/background-tasks.d.ts.map +1 -0
  63. package/dist/core/tools/background-tasks.js +110 -0
  64. package/dist/core/tools/background-tasks.js.map +1 -0
  65. package/dist/core/tools/bash.d.ts +11 -3
  66. package/dist/core/tools/bash.d.ts.map +1 -1
  67. package/dist/core/tools/bash.js +67 -17
  68. package/dist/core/tools/bash.js.map +1 -1
  69. package/dist/core/tools/edit-diff.d.ts +8 -0
  70. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  71. package/dist/core/tools/edit-diff.js +22 -0
  72. package/dist/core/tools/edit-diff.js.map +1 -1
  73. package/dist/core/tools/edit.d.ts +1 -0
  74. package/dist/core/tools/edit.d.ts.map +1 -1
  75. package/dist/core/tools/edit.js +1 -1
  76. package/dist/core/tools/edit.js.map +1 -1
  77. package/dist/core/tools/powershell.d.ts +1 -1
  78. package/dist/core/tools/powershell.d.ts.map +1 -1
  79. package/dist/core/tools/powershell.js.map +1 -1
  80. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  81. package/dist/core/tools/renderers/bash.js +2 -1
  82. package/dist/core/tools/renderers/bash.js.map +1 -1
  83. package/dist/core/tools/write.d.ts +1 -0
  84. package/dist/core/tools/write.d.ts.map +1 -1
  85. package/dist/core/tools/write.js +1 -1
  86. package/dist/core/tools/write.js.map +1 -1
  87. package/dist/core/trust-manager.d.ts +6 -0
  88. package/dist/core/trust-manager.d.ts.map +1 -1
  89. package/dist/core/trust-manager.js +15 -8
  90. package/dist/core/trust-manager.js.map +1 -1
  91. package/dist/core/turn-files.d.ts +99 -0
  92. package/dist/core/turn-files.d.ts.map +1 -0
  93. package/dist/core/turn-files.js +270 -0
  94. package/dist/core/turn-files.js.map +1 -0
  95. package/dist/extensions/agents/agent-tool.d.ts +0 -1
  96. package/dist/extensions/agents/agent-tool.d.ts.map +1 -1
  97. package/dist/extensions/agents/agent-tool.js +2 -1
  98. package/dist/extensions/agents/agent-tool.js.map +1 -1
  99. package/dist/extensions/agents/index.d.ts +4 -3
  100. package/dist/extensions/agents/index.d.ts.map +1 -1
  101. package/dist/extensions/agents/index.js +33 -32
  102. package/dist/extensions/agents/index.js.map +1 -1
  103. package/dist/extensions/approval/exit-plan-mode.d.ts +5 -1
  104. package/dist/extensions/approval/exit-plan-mode.d.ts.map +1 -1
  105. package/dist/extensions/approval/exit-plan-mode.js +131 -19
  106. package/dist/extensions/approval/exit-plan-mode.js.map +1 -1
  107. package/dist/extensions/approval/index.d.ts.map +1 -1
  108. package/dist/extensions/approval/index.js +46 -23
  109. package/dist/extensions/approval/index.js.map +1 -1
  110. package/dist/extensions/approval/policy.d.ts +5 -12
  111. package/dist/extensions/approval/policy.d.ts.map +1 -1
  112. package/dist/extensions/approval/policy.js +26 -4
  113. package/dist/extensions/approval/policy.js.map +1 -1
  114. package/dist/extensions/hooks/index.d.ts.map +1 -1
  115. package/dist/extensions/hooks/index.js +12 -1
  116. package/dist/extensions/hooks/index.js.map +1 -1
  117. package/dist/extensions/index.d.ts.map +1 -1
  118. package/dist/extensions/index.js +3 -1
  119. package/dist/extensions/index.js.map +1 -1
  120. package/dist/extensions/questions/index.d.ts +41 -0
  121. package/dist/extensions/questions/index.d.ts.map +1 -0
  122. package/dist/extensions/questions/index.js +132 -0
  123. package/dist/extensions/questions/index.js.map +1 -0
  124. package/dist/index.d.ts +11 -2
  125. package/dist/index.d.ts.map +1 -1
  126. package/dist/index.js +6 -2
  127. package/dist/index.js.map +1 -1
  128. package/docs/approval-modes.md +7 -3
  129. package/docs/cli.md +12 -1
  130. package/docs/codemode.md +1 -1
  131. package/docs/extensions.md +36 -1
  132. package/docs/json.md +19 -0
  133. package/docs/sdk.md +64 -0
  134. package/docs/session-format.md +2 -0
  135. package/docs/settings.md +1 -1
  136. package/docs/slash-commands.md +1 -1
  137. package/docs/subagents.md +2 -2
  138. package/package.json +6 -6
  139. package/dist/bundle/chunks/chunk-VWWMBH3G.js +0 -2
@@ -0,0 +1,110 @@
1
+ /**
2
+ * What the model sees of background tasks: `bash_output` reads background shell commands, `task_stop`
3
+ * stops them and the background tasks of extensions, such as background subagents, and a
4
+ * `<task-notification>` reports a command that ended by itself.
5
+ */
6
+ import { Type } from "typebox";
7
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
8
+ export const BASH_OUTPUT_TOOL_NAME = "bash_output";
9
+ export const TASK_STOP_TOOL_NAME = "task_stop";
10
+ /** `customType` of the message that reports a background command that ended by itself. */
11
+ export const BACKGROUND_COMMAND_NOTIFICATION_TYPE = "background-command-notification";
12
+ const bashOutputSchema = Type.Object({
13
+ task_id: Type.String({ description: "The task_id of a command started with run_in_background" }),
14
+ });
15
+ /** Create `bash_output`, which reads the output of the session's background commands. */
16
+ export function createBashOutputToolDefinition(commands) {
17
+ return {
18
+ name: BASH_OUTPUT_TOOL_NAME,
19
+ label: "bash_output",
20
+ description: `Read the output a background shell command (started by bash or powershell with run_in_background) wrote since the last ${BASH_OUTPUT_TOOL_NAME} call for it, and its status: running, exited with its exit code, stopped, or failed. New output is truncated to its last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB; the full output stays in the command's output file. Call it when you need the output, for example to check that a dev server is ready; you need not poll for the command to end, a <task-notification> reports that.`,
21
+ parameters: bashOutputSchema,
22
+ async execute(_toolCallId, { task_id }) {
23
+ const read = commands.readNew(task_id);
24
+ if (!read)
25
+ throw new Error(`No background command found with ID "${task_id}".`);
26
+ const { command, droppedChars } = read;
27
+ const truncation = truncateTail(read.output);
28
+ const lines = [`Background command ${describeBackgroundCommand(command)}.`];
29
+ if (command.outputFile)
30
+ lines.push(`Output file: ${command.outputFile}`);
31
+ lines.push("", truncation.content || "(no new output)");
32
+ if (droppedChars > 0) {
33
+ lines.push("", `[${droppedChars} earlier characters of new output are no longer in memory; see the output file]`);
34
+ }
35
+ if (truncation.truncated) {
36
+ lines.push("", `[Showing the last ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)}) of new output; see the output file for the rest]`);
37
+ }
38
+ return { content: [{ type: "text", text: lines.join("\n") }], details: undefined };
39
+ },
40
+ };
41
+ }
42
+ const taskStopSchema = Type.Object({
43
+ task_id: Type.String({ description: "The task_id of the background task to stop" }),
44
+ });
45
+ /** Create `task_stop`, which stops background commands and the background tasks of extensions. */
46
+ export function createTaskStopToolDefinition(commands, getStoppers) {
47
+ return {
48
+ name: TASK_STOP_TOOL_NAME,
49
+ label: "TaskStop",
50
+ description: "Stop a background task by its ID. A shell command started with run_in_background is killed with its child processes before this returns. A background agent is cancelled; its final task-notification follows.",
51
+ parameters: taskStopSchema,
52
+ async execute(_toolCallId, { task_id }) {
53
+ const ended = commands.ended(task_id);
54
+ if (ended) {
55
+ if (!commands.stop(task_id)) {
56
+ throw new Error(`Background task "${task_id}" is not running (status: ${(await ended).status}).`);
57
+ }
58
+ return {
59
+ content: [{ type: "text", text: `Background command ${describeBackgroundCommand(await ended)}.` }],
60
+ details: undefined,
61
+ };
62
+ }
63
+ for (const stop of getStoppers()) {
64
+ const text = stop(task_id);
65
+ if (text !== undefined)
66
+ return { content: [{ type: "text", text }], details: undefined };
67
+ }
68
+ throw new Error(`No background task found with ID "${task_id}".`);
69
+ },
70
+ };
71
+ }
72
+ /** The `<task-notification>` the agent receives when a background command ended by itself. */
73
+ export function formatBackgroundCommandNotification(command) {
74
+ return [
75
+ "<task-notification>",
76
+ `<task-id>${escapeXml(command.id)}</task-id>`,
77
+ `<tool-use-id>${escapeXml(command.toolCallId)}</tool-use-id>`,
78
+ `<status>${command.status}</status>`,
79
+ `<summary>${escapeXml(`Background command ${describeBackgroundCommand(command)}. Read its output with ${BASH_OUTPUT_TOOL_NAME}.`)}</summary>`,
80
+ ...(command.outputFile ? [`<output-file>${escapeXml(command.outputFile)}</output-file>`] : []),
81
+ "</task-notification>",
82
+ ].join("\n");
83
+ }
84
+ /** The command and its state in a few words, such as `"npm run dev" exited with code 1`. */
85
+ export function describeBackgroundCommand(command) {
86
+ return `${commandLabel(command)} ${describeStatus(command)}`;
87
+ }
88
+ /** The command's first line, quoted and cut to 80 characters. */
89
+ export function commandLabel(command) {
90
+ const text = command.command.trim();
91
+ const firstLine = text.split(/\r?\n/, 1)[0];
92
+ const cut = firstLine.length > 80 || firstLine.length < text.length;
93
+ return `"${cut ? `${firstLine.slice(0, 80)}…` : firstLine}"`;
94
+ }
95
+ function describeStatus(command) {
96
+ switch (command.status) {
97
+ case "running":
98
+ return "is running";
99
+ case "exited":
100
+ return `exited with code ${command.exitCode}`;
101
+ case "stopped":
102
+ return "was stopped";
103
+ case "failed":
104
+ return `failed: ${command.error}`;
105
+ }
106
+ }
107
+ function escapeXml(text) {
108
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
109
+ }
110
+ //# sourceMappingURL=background-tasks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-tasks.js","sourceRoot":"","sources":["../../../src/core/tools/background-tasks.ts"],"names":[],"mappings":"AAAA;;;;GAIG;A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,CAAC,OAAO,CAAC,IAAI,cAAc,CAAC,OAAO,CAAC,EAAE,CAAC;AAC9D,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,YAAY,CAAC,OAA0B;IACtD,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;IACpC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5C,MAAM,GAAG,GAAG,SAAS,CAAC,MAAM,GAAG,EAAE,IAAI,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IACpE,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC;AAC9D,CAAC;AAED,SAAS,cAAc,CAAC,OAA0B;IACjD,QAAQ,OAAO,CAAC,MAAM,EAAE,CAAC;QACxB,KAAK,SAAS;YACb,OAAO,YAAY,CAAC;QACrB,KAAK,QAAQ;YACZ,OAAO,oBAAoB,OAAO,CAAC,QAAQ,EAAE,CAAC;QAC/C,KAAK,SAAS;YACb,OAAO,aAAa,CAAC;QACtB,KAAK,QAAQ;YACZ,OAAO,WAAW,OAAO,CAAC,KAAK,EAAE,CAAC;IACpC,CAAC;AACF,CAAC;AAED,SAAS,SAAS,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAChF,CAAC","sourcesContent":["/**\n * What the model sees of background tasks: `bash_output` reads background shell commands, `task_stop`\n * stops them and the background tasks of extensions, such as background subagents, and a\n * `<task-notification>` reports a command that ended by itself.\n */\n\nimport { Type } from \"typebox\";\nimport type { BackgroundCommand, BackgroundCommands } from \"../background-commands.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from \"./truncate.ts\";\n\nexport const BASH_OUTPUT_TOOL_NAME = \"bash_output\";\nexport const TASK_STOP_TOOL_NAME = \"task_stop\";\n\n/** `customType` of the message that reports a background command that ended by itself. */\nexport const BACKGROUND_COMMAND_NOTIFICATION_TYPE = \"background-command-notification\";\n\n/**\n * Stops an extension's background task for `task_stop`: returns the model-facing result for an id of the\n * extension's tasks and `undefined` for other ids, and throws when that task already finished.\n */\nexport type TaskStopper = (taskId: string) => string | undefined;\n\nconst bashOutputSchema = Type.Object({\n\ttask_id: Type.String({ description: \"The task_id of a command started with run_in_background\" }),\n});\n\n/** Create `bash_output`, which reads the output of the session's background commands. */\nexport function createBashOutputToolDefinition(\n\tcommands: BackgroundCommands,\n): ToolDefinition<typeof bashOutputSchema, undefined> {\n\treturn {\n\t\tname: BASH_OUTPUT_TOOL_NAME,\n\t\tlabel: \"bash_output\",\n\t\tdescription: `Read the output a background shell command (started by bash or powershell with run_in_background) wrote since the last ${BASH_OUTPUT_TOOL_NAME} call for it, and its status: running, exited with its exit code, stopped, or failed. New output is truncated to its last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB; the full output stays in the command's output file. Call it when you need the output, for example to check that a dev server is ready; you need not poll for the command to end, a <task-notification> reports that.`,\n\t\tparameters: bashOutputSchema,\n\t\tasync execute(_toolCallId, { task_id }) {\n\t\t\tconst read = commands.readNew(task_id);\n\t\t\tif (!read) throw new Error(`No background command found with ID \"${task_id}\".`);\n\t\t\tconst { command, droppedChars } = read;\n\t\t\tconst truncation = truncateTail(read.output);\n\t\t\tconst lines = [`Background command ${describeBackgroundCommand(command)}.`];\n\t\t\tif (command.outputFile) lines.push(`Output file: ${command.outputFile}`);\n\t\t\tlines.push(\"\", truncation.content || \"(no new output)\");\n\t\t\tif (droppedChars > 0) {\n\t\t\t\tlines.push(\n\t\t\t\t\t\"\",\n\t\t\t\t\t`[${droppedChars} earlier characters of new output are no longer in memory; see the output file]`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (truncation.truncated) {\n\t\t\t\tlines.push(\n\t\t\t\t\t\"\",\n\t\t\t\t\t`[Showing the last ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)}) of new output; see the output file for the rest]`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { content: [{ type: \"text\", text: lines.join(\"\\n\") }], details: undefined };\n\t\t},\n\t};\n}\n\nconst taskStopSchema = Type.Object({\n\ttask_id: Type.String({ description: \"The task_id of the background task to stop\" }),\n});\n\n/** Create `task_stop`, which stops background commands and the background tasks of extensions. */\nexport function createTaskStopToolDefinition(\n\tcommands: BackgroundCommands,\n\tgetStoppers: () => readonly TaskStopper[],\n): ToolDefinition<typeof taskStopSchema, undefined> {\n\treturn {\n\t\tname: TASK_STOP_TOOL_NAME,\n\t\tlabel: \"TaskStop\",\n\t\tdescription:\n\t\t\t\"Stop a background task by its ID. A shell command started with run_in_background is killed with its child processes before this returns. A background agent is cancelled; its final task-notification follows.\",\n\t\tparameters: taskStopSchema,\n\t\tasync execute(_toolCallId, { task_id }) {\n\t\t\tconst ended = commands.ended(task_id);\n\t\t\tif (ended) {\n\t\t\t\tif (!commands.stop(task_id)) {\n\t\t\t\t\tthrow new Error(`Background task \"${task_id}\" is not running (status: ${(await ended).status}).`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Background command ${describeBackgroundCommand(await ended)}.` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tfor (const stop of getStoppers()) {\n\t\t\t\tconst text = stop(task_id);\n\t\t\t\tif (text !== undefined) return { content: [{ type: \"text\", text }], details: undefined };\n\t\t\t}\n\t\t\tthrow new Error(`No background task found with ID \"${task_id}\".`);\n\t\t},\n\t};\n}\n\n/** The `<task-notification>` the agent receives when a background command ended by itself. */\nexport function formatBackgroundCommandNotification(command: BackgroundCommand): string {\n\treturn [\n\t\t\"<task-notification>\",\n\t\t`<task-id>${escapeXml(command.id)}</task-id>`,\n\t\t`<tool-use-id>${escapeXml(command.toolCallId)}</tool-use-id>`,\n\t\t`<status>${command.status}</status>`,\n\t\t`<summary>${escapeXml(`Background command ${describeBackgroundCommand(command)}. Read its output with ${BASH_OUTPUT_TOOL_NAME}.`)}</summary>`,\n\t\t...(command.outputFile ? [`<output-file>${escapeXml(command.outputFile)}</output-file>`] : []),\n\t\t\"</task-notification>\",\n\t].join(\"\\n\");\n}\n\n/** The command and its state in a few words, such as `\"npm run dev\" exited with code 1`. */\nexport function describeBackgroundCommand(command: BackgroundCommand): string {\n\treturn `${commandLabel(command)} ${describeStatus(command)}`;\n}\n\n/** The command's first line, quoted and cut to 80 characters. */\nexport function commandLabel(command: BackgroundCommand): string {\n\tconst text = command.command.trim();\n\tconst firstLine = text.split(/\\r?\\n/, 1)[0];\n\tconst cut = firstLine.length > 80 || firstLine.length < text.length;\n\treturn `\"${cut ? `${firstLine.slice(0, 80)}…` : firstLine}\"`;\n}\n\nfunction describeStatus(command: BackgroundCommand): string {\n\tswitch (command.status) {\n\t\tcase \"running\":\n\t\t\treturn \"is running\";\n\t\tcase \"exited\":\n\t\t\treturn `exited with code ${command.exitCode}`;\n\t\tcase \"stopped\":\n\t\t\treturn \"was stopped\";\n\t\tcase \"failed\":\n\t\t\treturn `failed: ${command.error}`;\n\t}\n}\n\nfunction escapeXml(text: string): string {\n\treturn text.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { type Static, Type } from "typebox";
2
2
  import { type ShellConfig } from "../../utils/shell.ts";
3
+ import type { BackgroundCommands } from "../background-commands.ts";
3
4
  import type { ToolDefinition } from "../extensions/types.ts";
4
5
  import { type SandboxOptions } from "../sandbox/escalation.ts";
5
6
  import type { SandboxPolicyResolver } from "../sandbox/policy.ts";
@@ -8,6 +9,7 @@ import { type TruncationResult } from "./truncate.ts";
8
9
  declare const bashSchema: Type.TObject<{
9
10
  command: Type.TString;
10
11
  timeout: Type.TOptional<Type.TNumber>;
12
+ run_in_background: Type.TOptional<Type.TBoolean>;
11
13
  }>;
12
14
  export declare const bashToolSystemPromptContribution: {
13
15
  readonly snippet: "Execute bash commands (ls, grep, find, etc.)";
@@ -17,14 +19,18 @@ export type BashToolInput = Static<typeof bashSchema>;
17
19
  /**
18
20
  * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.
19
21
  * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.
22
+ * A command started with `run_in_background` resolves to its task id instead.
20
23
  */
21
- declare const bashOutputSchema: Type.TObject<{
24
+ declare const bashOutputSchema: Type.TUnion<[Type.TObject<{
22
25
  output: Type.TString;
23
26
  truncated: Type.TBoolean;
24
27
  full_output_path: Type.TOptional<Type.TString>;
25
28
  exit_code: Type.TNumber;
26
29
  wall_time_seconds: Type.TNumber;
27
- }>;
30
+ }>, Type.TObject<{
31
+ task_id: Type.TString;
32
+ output_file: Type.TOptional<Type.TString>;
33
+ }>]>;
28
34
  export type BashToolOutput = Static<typeof bashOutputSchema>;
29
35
  export interface BashToolDetails {
30
36
  truncation?: TruncationResult;
@@ -86,6 +92,8 @@ export interface BashToolOptions {
86
92
  spawnHook?: BashSpawnHook;
87
93
  /** Sandbox of the local shell backend, and who may allow a denied command. Ignored with custom operations. */
88
94
  sandbox?: SandboxOptions;
95
+ /** The session's background commands. Without them, `run_in_background` calls fail. */
96
+ background?: BackgroundCommands;
89
97
  }
90
98
  export type BashRenderState = {
91
99
  startedAt: number | undefined;
@@ -93,7 +101,7 @@ export type BashRenderState = {
93
101
  interval: NodeJS.Timeout | undefined;
94
102
  };
95
103
  export interface ShellToolConfig {
96
- name: string;
104
+ name: "bash" | "powershell";
97
105
  label: string;
98
106
  shellName: string;
99
107
  pr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,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CAyNjF;AAaD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CAEjF;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC,OAAO,UAAU,CAAC,CAQ1G"}
@@ -7,6 +7,7 @@ import { waitForChildProcess } from "../../utils/child-process.js";
7
7
  import { getShellConfig, getShellEnv, killProcessTree, trackDetachedChildPid, untrackDetachedChildPid, } from "../../utils/shell.js";
8
8
  import { withUnsandboxedRetry } from "../sandbox/escalation.js";
9
9
  import { wrapForSandbox } from "../sandbox/launch.js";
10
+ import { BASH_OUTPUT_TOOL_NAME, TASK_STOP_TOOL_NAME } from "./background-tasks.js";
10
11
  import { OutputAccumulator } from "./output-accumulator.js";
11
12
  import { BASH_UPDATE_THROTTLE_MS, createShellRenderers } from "./renderers/bash.js";
12
13
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
@@ -30,6 +31,9 @@ function resolveTimeoutMs(timeout) {
30
31
  const bashSchema = Type.Object({
31
32
  command: Type.String({ description: "Shell command to execute" }),
32
33
  timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
34
+ run_in_background: Type.Optional(Type.Boolean({
35
+ description: "Start the command and return its task_id at once instead of waiting for it. For commands that keep running or take long: dev servers, watchers, long builds and test runs. Do not append `&` to run a command in the background.",
36
+ })),
33
37
  });
34
38
  export const bashToolSystemPromptContribution = {
35
39
  snippet: "Execute bash commands (ls, grep, find, etc.)",
@@ -38,14 +42,21 @@ export const bashToolSystemPromptContribution = {
38
42
  /**
39
43
  * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.
40
44
  * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.
45
+ * A command started with `run_in_background` resolves to its task id instead.
41
46
  */
42
- const bashOutputSchema = Type.Object({
43
- output: Type.String({ description: "Combined stdout and stderr, possibly truncated" }),
44
- truncated: Type.Boolean(),
45
- full_output_path: Type.Optional(Type.String({ description: "Full output, when truncated" })),
46
- exit_code: Type.Number(),
47
- wall_time_seconds: Type.Number(),
48
- });
47
+ const bashOutputSchema = Type.Union([
48
+ Type.Object({
49
+ output: Type.String({ description: "Combined stdout and stderr, possibly truncated" }),
50
+ truncated: Type.Boolean(),
51
+ full_output_path: Type.Optional(Type.String({ description: "Full output, when truncated" })),
52
+ exit_code: Type.Number(),
53
+ wall_time_seconds: Type.Number(),
54
+ }),
55
+ Type.Object({
56
+ task_id: Type.String({ description: "ID of the command started with run_in_background" }),
57
+ output_file: Type.Optional(Type.String({ description: "File that receives the command's full output" })),
58
+ }),
59
+ ]);
49
60
  /**
50
61
  * Timeout of the local shell backend. Its message keeps the `timeout:<seconds>` form custom operations throw.
51
62
  * `shellExit` is set when the shell itself exited before the deadline, so the tool was only still waiting
@@ -58,6 +69,15 @@ class ShellTimeoutError extends Error {
58
69
  this.shellExit = shellExit;
59
70
  }
60
71
  }
72
+ /** The status line of a command that ran into its timeout, from an error whose message is `timeout:<seconds>`. */
73
+ function timeoutStatus(error) {
74
+ const status = `Command timed out after ${error.message.split(":")[1]} seconds`;
75
+ // Both facts matter: the command's real result, and that its background processes were still writing
76
+ // output when the timeout hit (#11613).
77
+ return error instanceof ShellTimeoutError && error.shellExit
78
+ ? `${status}. The shell exited with code ${error.shellExit.exitCode} after ${error.shellExit.afterSeconds} seconds, but background processes it started kept writing output until the timeout.`
79
+ : status;
80
+ }
61
81
  /**
62
82
  * Shared process execution used by the built-in shell tools. With `resolveSandbox`, commands run under the
63
83
  * sandbox policy of their working folder, or fail when this platform has no sandbox backend.
@@ -199,18 +219,55 @@ export function createShellToolDefinition(cwd, config, options) {
199
219
  const commandPrefix = options?.commandPrefix;
200
220
  const exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;
201
221
  const spawnHook = options?.spawnHook;
222
+ const background = options?.background;
223
+ const backgroundDescription = background
224
+ ? ` Set run_in_background to start a command that keeps running or takes long, such as a dev server, a file watcher, or a long build, without waiting for it: the call returns a task_id at once. Read its new output with ${BASH_OUTPUT_TOOL_NAME} and stop it with ${TASK_STOP_TOOL_NAME}; a <task-notification> arrives when it exits by itself. Background commands keep running after your turn and are killed when the session ends.`
225
+ : "";
202
226
  return {
203
227
  name: config.name,
204
228
  label: config.label,
205
- description: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
229
+ description: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.${backgroundDescription}`,
206
230
  promptSnippet: config.promptSnippet,
207
231
  promptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,
208
232
  parameters: bashSchema,
209
233
  outputSchema: bashOutputSchema,
210
234
  constrainedSampling: { type: "json_schema", strict: "prefer" },
211
- async execute(_toolCallId, { command, timeout }, signal, onUpdate, ctx) {
235
+ async execute(toolCallId, { command, timeout, run_in_background }, signal, onUpdate, ctx) {
212
236
  const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;
213
237
  const spawnContext = resolveSpawnContext(resolvedCommand, ctx?.cwd || cwd, spawnHook, exposeSessionEnvironment, ctx);
238
+ if (run_in_background) {
239
+ if (!background) {
240
+ throw new Error(`run_in_background is not available: this ${config.name} tool does not belong to a session.`);
241
+ }
242
+ // Without the unsandboxed retry: nobody waits for a background command to ask whether it may leave the sandbox.
243
+ const run = (onData, runSignal) => ops
244
+ .exec(spawnContext.command, spawnContext.cwd, {
245
+ onData,
246
+ signal: runSignal,
247
+ timeout,
248
+ env: spawnContext.env,
249
+ })
250
+ .catch((error) => {
251
+ throw error instanceof Error && error.message.startsWith("timeout:")
252
+ ? new Error(timeoutStatus(error))
253
+ : error;
254
+ });
255
+ const started = background.start({ toolCallId, command, cwd: spawnContext.cwd, shell: config.name }, run);
256
+ const structuredContent = {
257
+ task_id: started.id,
258
+ ...(started.outputFile ? { output_file: started.outputFile } : {}),
259
+ };
260
+ return {
261
+ content: [
262
+ {
263
+ type: "text",
264
+ text: `Command running in the background with task_id: ${started.id}${started.outputFile ? `\nOutput file: ${started.outputFile}` : ""}\nRead its new output with ${BASH_OUTPUT_TOOL_NAME} and stop it with ${TASK_STOP_TOOL_NAME}. A <task-notification> arrives when it exits by itself; do not poll ${BASH_OUTPUT_TOOL_NAME} to wait for that.`,
265
+ },
266
+ ],
267
+ details: undefined,
268
+ structuredContent,
269
+ };
270
+ }
214
271
  const output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });
215
272
  let acceptingOutput = true;
216
273
  let updateTimer;
@@ -314,14 +371,7 @@ export function createShellToolDefinition(cwd, config, options) {
314
371
  throw new Error(appendStatus(text, "Command aborted"));
315
372
  }
316
373
  if (err instanceof Error && err.message.startsWith("timeout:")) {
317
- const timeoutSecs = err.message.split(":")[1];
318
- let status = `Command timed out after ${timeoutSecs} seconds`;
319
- if (err instanceof ShellTimeoutError && err.shellExit) {
320
- // Both facts matter: the command's real result, and that its background processes
321
- // were still writing output when the timeout hit (#11613).
322
- status += `. The shell exited with code ${err.shellExit.exitCode} after ${err.shellExit.afterSeconds} seconds, but background processes it started kept writing output until the timeout.`;
323
- }
324
- throw new Error(appendStatus(text, status));
374
+ throw new Error(appendStatus(text, timeoutStatus(err)));
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BAAyB,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;CAClH,CAAC;AAEF,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB;IAEzB,OAAO,yBAAyB,CAAC,GAAG,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,MAAM,UAAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { type SandboxOptions, withUnsandboxedRetry } from \"../sandbox/escalation.ts\";\nimport { type SandboxLaunch, wrapForSandbox } from \"../sandbox/launch.ts\";\nimport type { SandboxPolicyResolver } from \"../sandbox/policy.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS, createShellRenderers } from \"./renderers/bash.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n/** Output limit of `structuredContent.output`, which programmatic callers such as codemode scripts receive. */\nconst STRUCTURED_OUTPUT_MAX_BYTES = 1024 * 1024;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.\n * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.\n */\nconst bashOutputSchema = Type.Object({\n\toutput: Type.String({ description: \"Combined stdout and stderr, possibly truncated\" }),\n\ttruncated: Type.Boolean(),\n\tfull_output_path: Type.Optional(Type.String({ description: \"Full output, when truncated\" })),\n\texit_code: Type.Number(),\n\twall_time_seconds: Type.Number(),\n});\n\nexport type BashToolOutput = Static<typeof bashOutputSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/**\n * Timeout of the local shell backend. Its message keeps the `timeout:<seconds>` form custom operations throw.\n * `shellExit` is set when the shell itself exited before the deadline, so the tool was only still waiting\n * because background processes kept writing to the inherited stdout/stderr pipes (#11613).\n */\nclass ShellTimeoutError extends Error {\n\treadonly shellExit: { exitCode: number; afterSeconds: number } | undefined;\n\n\tconstructor(timeout: number | undefined, shellExit: { exitCode: number; afterSeconds: number } | undefined) {\n\t\tsuper(`timeout:${timeout}`);\n\t\tthis.shellExit = shellExit;\n\t}\n}\n\n/**\n * Shared process execution used by the built-in shell tools. With `resolveSandbox`, commands run under the\n * sandbox policy of their working folder, or fail when this platform has no sandbox backend.\n */\nexport function createLocalShellOperations(\n\tshellName: string,\n\tresolveShellConfig: () => ShellConfig,\n\tresolveSandbox?: SandboxPolicyResolver,\n): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst shellLaunch: SandboxLaunch = {\n\t\t\t\tcommand: shellConfig.shell,\n\t\t\t\targs: commandFromStdin ? shellConfig.args : [...shellConfig.args, command],\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t};\n\t\t\tconst policy = resolveSandbox?.(cwd);\n\t\t\tconst launch = policy ? await wrapForSandbox(policy, shellLaunch, cwd) : shellLaunch;\n\t\t\tconst child = spawn(launch.command, launch.args, {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: launch.env,\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tconst startedAt = performance.now();\n\t\t\tlet shellExitedAfterMs: number | undefined;\n\t\t\tchild.once(\"exit\", () => {\n\t\t\t\tshellExitedAfterMs = performance.now() - startedAt;\n\t\t\t});\n\t\t\tlet timedOut = false;\n\t\t\tlet exitedBeforeDeadlineAfterMs: number | undefined;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\texitedBeforeDeadlineAfterMs = shellExitedAfterMs;\n\t\t\t\t\t\t// Also when the shell already exited: on Unix the group kill still reaches background\n\t\t\t\t\t\t// processes holding the pipes. Windows cannot find them once the shell pid is gone.\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\tconst resolvedExitCode = exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1);\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new ShellTimeoutError(\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\texitedBeforeDeadlineAfterMs !== undefined\n\t\t\t\t\t\t\t? { exitCode: resolvedExitCode, afterSeconds: Math.round(exitedBeforeDeadlineAfterMs / 100) / 10 }\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { exitCode: resolvedExitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using diffra's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want diffra's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: {\n\tshellPath?: string;\n\tsandbox?: SandboxPolicyResolver;\n}): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath), options?.sandbox);\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.DIFFRA_SESSION_ID;\n\tdelete env.DIFFRA_SESSION_FILE;\n\tdelete env.DIFFRA_PROVIDER;\n\tdelete env.DIFFRA_MODEL;\n\tdelete env.DIFFRA_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.DIFFRA_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.DIFFRA_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.DIFFRA_PROVIDER = model.provider;\n\t\t\tenv.DIFFRA_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.DIFFRA_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Diffra session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n\t/** Sandbox of the local shell backend, and who may allow a denied command. Ignored with custom operations. */\n\tsandbox?: SandboxOptions;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n\t/** The local backend of the tool, under `sandbox` when given. */\n\tcreateLocalOperations: (options: BashToolOptions | undefined, sandbox?: SandboxPolicyResolver) => BashOperations;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst sandbox = options?.operations ? undefined : options?.sandbox;\n\tconst ops = options?.operations ?? config.createLocalOperations(options, sandbox?.policy);\n\tconst escalate = sandbox?.escalate;\n\tconst unsandboxedOps = escalate ? config.createLocalOperations(options) : undefined;\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${startLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst startedAt = performance.now();\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\t// Only a command that runs sandboxed can be denied by the sandbox.\n\t\t\t\tconst callOps =\n\t\t\t\t\tescalate && unsandboxedOps && sandbox?.policy(spawnContext.cwd)\n\t\t\t\t\t\t? withUnsandboxedRetry(ops, unsandboxedOps, (command) => escalate({ kind: \"command\", command }, ctx))\n\t\t\t\t\t\t: ops;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await callOps.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tlet status = `Command timed out after ${timeoutSecs} seconds`;\n\t\t\t\t\t\tif (err instanceof ShellTimeoutError && err.shellExit) {\n\t\t\t\t\t\t\t// Both facts matter: the command's real result, and that its background processes\n\t\t\t\t\t\t\t// were still writing output when the timeout hit (#11613).\n\t\t\t\t\t\t\tstatus += `. The shell exited with code ${err.shellExit.exitCode} after ${err.shellExit.afterSeconds} seconds, but background processes it started kept writing output until the timeout.`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new Error(appendStatus(text, status));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode === null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, \"Command terminated without an exit code\"));\n\t\t\t\t}\n\t\t\t\tconst wallTimeSeconds = Math.round((performance.now() - startedAt) / 100) / 10;\n\t\t\t\tconst fullOutput = await output.readFullOutput(STRUCTURED_OUTPUT_MAX_BYTES);\n\t\t\t\tconst structuredContent: BashToolOutput = {\n\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t...(fullOutput.truncated && snapshot.fullOutputPath\n\t\t\t\t\t\t? { full_output_path: snapshot.fullOutputPath }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\twall_time_seconds: wallTimeSeconds,\n\t\t\t\t};\n\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: appendStatus(outputText, `Command exited with code ${exitCode}`) }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t\tstructuredContent,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details, structuredContent };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\t...createShellRenderers(config.prompt),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"diffra-bash\",\n\tcreateLocalOperations: (options, sandbox) => createLocalBashOperations({ shellPath: options?.shellPath, sandbox }),\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): TypeBoxAgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EAEf,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAuB,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrF,OAAO,EAAsB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE1E,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACpF,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,UAAU,EAAyB,MAAM,eAAe,CAAC;AAExG,MAAM,cAAc,GAAG,aAA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,yBAAyB,CAAC,GAAG,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,MAAM,UAAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { BackgroundCommandRun, BackgroundCommands } from \"../background-commands.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { type SandboxOptions, withUnsandboxedRetry } from \"../sandbox/escalation.ts\";\nimport { type SandboxLaunch, wrapForSandbox } from \"../sandbox/launch.ts\";\nimport type { SandboxPolicyResolver } from \"../sandbox/policy.ts\";\nimport { BASH_OUTPUT_TOOL_NAME, TASK_STOP_TOOL_NAME } from \"./background-tasks.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS, createShellRenderers } from \"./renderers/bash.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n/** Output limit of `structuredContent.output`, which programmatic callers such as codemode scripts receive. */\nconst STRUCTURED_OUTPUT_MAX_BYTES = 1024 * 1024;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\trun_in_background: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"Start the command and return its task_id at once instead of waiting for it. For commands that keep running or take long: dev servers, watchers, long builds and test runs. Do not append `&` to run a command in the background.\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.\n * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.\n * A command started with `run_in_background` resolves to its task id instead.\n */\nconst bashOutputSchema = Type.Union([\n\tType.Object({\n\t\toutput: Type.String({ description: \"Combined stdout and stderr, possibly truncated\" }),\n\t\ttruncated: Type.Boolean(),\n\t\tfull_output_path: Type.Optional(Type.String({ description: \"Full output, when truncated\" })),\n\t\texit_code: Type.Number(),\n\t\twall_time_seconds: Type.Number(),\n\t}),\n\tType.Object({\n\t\ttask_id: Type.String({ description: \"ID of the command started with run_in_background\" }),\n\t\toutput_file: Type.Optional(Type.String({ description: \"File that receives the command's full output\" })),\n\t}),\n]);\n\nexport type BashToolOutput = Static<typeof bashOutputSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/**\n * Timeout of the local shell backend. Its message keeps the `timeout:<seconds>` form custom operations throw.\n * `shellExit` is set when the shell itself exited before the deadline, so the tool was only still waiting\n * because background processes kept writing to the inherited stdout/stderr pipes (#11613).\n */\nclass ShellTimeoutError extends Error {\n\treadonly shellExit: { exitCode: number; afterSeconds: number } | undefined;\n\n\tconstructor(timeout: number | undefined, shellExit: { exitCode: number; afterSeconds: number } | undefined) {\n\t\tsuper(`timeout:${timeout}`);\n\t\tthis.shellExit = shellExit;\n\t}\n}\n\n/** The status line of a command that ran into its timeout, from an error whose message is `timeout:<seconds>`. */\nfunction timeoutStatus(error: Error): string {\n\tconst status = `Command timed out after ${error.message.split(\":\")[1]} seconds`;\n\t// Both facts matter: the command's real result, and that its background processes were still writing\n\t// output when the timeout hit (#11613).\n\treturn error instanceof ShellTimeoutError && error.shellExit\n\t\t? `${status}. The shell exited with code ${error.shellExit.exitCode} after ${error.shellExit.afterSeconds} seconds, but background processes it started kept writing output until the timeout.`\n\t\t: status;\n}\n\n/**\n * Shared process execution used by the built-in shell tools. With `resolveSandbox`, commands run under the\n * sandbox policy of their working folder, or fail when this platform has no sandbox backend.\n */\nexport function createLocalShellOperations(\n\tshellName: string,\n\tresolveShellConfig: () => ShellConfig,\n\tresolveSandbox?: SandboxPolicyResolver,\n): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst shellLaunch: SandboxLaunch = {\n\t\t\t\tcommand: shellConfig.shell,\n\t\t\t\targs: commandFromStdin ? shellConfig.args : [...shellConfig.args, command],\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t};\n\t\t\tconst policy = resolveSandbox?.(cwd);\n\t\t\tconst launch = policy ? await wrapForSandbox(policy, shellLaunch, cwd) : shellLaunch;\n\t\t\tconst child = spawn(launch.command, launch.args, {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: launch.env,\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tconst startedAt = performance.now();\n\t\t\tlet shellExitedAfterMs: number | undefined;\n\t\t\tchild.once(\"exit\", () => {\n\t\t\t\tshellExitedAfterMs = performance.now() - startedAt;\n\t\t\t});\n\t\t\tlet timedOut = false;\n\t\t\tlet exitedBeforeDeadlineAfterMs: number | undefined;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\texitedBeforeDeadlineAfterMs = shellExitedAfterMs;\n\t\t\t\t\t\t// Also when the shell already exited: on Unix the group kill still reaches background\n\t\t\t\t\t\t// processes holding the pipes. Windows cannot find them once the shell pid is gone.\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\tconst resolvedExitCode = exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1);\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new ShellTimeoutError(\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\texitedBeforeDeadlineAfterMs !== undefined\n\t\t\t\t\t\t\t? { exitCode: resolvedExitCode, afterSeconds: Math.round(exitedBeforeDeadlineAfterMs / 100) / 10 }\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { exitCode: resolvedExitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using diffra's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want diffra's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: {\n\tshellPath?: string;\n\tsandbox?: SandboxPolicyResolver;\n}): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath), options?.sandbox);\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.DIFFRA_SESSION_ID;\n\tdelete env.DIFFRA_SESSION_FILE;\n\tdelete env.DIFFRA_PROVIDER;\n\tdelete env.DIFFRA_MODEL;\n\tdelete env.DIFFRA_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.DIFFRA_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.DIFFRA_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.DIFFRA_PROVIDER = model.provider;\n\t\t\tenv.DIFFRA_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.DIFFRA_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Diffra session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n\t/** Sandbox of the local shell backend, and who may allow a denied command. Ignored with custom operations. */\n\tsandbox?: SandboxOptions;\n\t/** The session's background commands. Without them, `run_in_background` calls fail. */\n\tbackground?: BackgroundCommands;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: \"bash\" | \"powershell\";\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n\t/** The local backend of the tool, under `sandbox` when given. */\n\tcreateLocalOperations: (options: BashToolOptions | undefined, sandbox?: SandboxPolicyResolver) => BashOperations;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst sandbox = options?.operations ? undefined : options?.sandbox;\n\tconst ops = options?.operations ?? config.createLocalOperations(options, sandbox?.policy);\n\tconst escalate = sandbox?.escalate;\n\tconst unsandboxedOps = escalate ? config.createLocalOperations(options) : undefined;\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\tconst background = options?.background;\n\tconst backgroundDescription = background\n\t\t? ` Set run_in_background to start a command that keeps running or takes long, such as a dev server, a file watcher, or a long build, without waiting for it: the call returns a task_id at once. Read its new output with ${BASH_OUTPUT_TOOL_NAME} and stop it with ${TASK_STOP_TOOL_NAME}; a <task-notification> arrives when it exits by itself. Background commands keep running after your turn and are killed when the session ends.`\n\t\t: \"\";\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.${backgroundDescription}`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{ command, timeout, run_in_background }: BashToolInput,\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\n\t\t\tif (run_in_background) {\n\t\t\t\tif (!background) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`run_in_background is not available: this ${config.name} tool does not belong to a session.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Without the unsandboxed retry: nobody waits for a background command to ask whether it may leave the sandbox.\n\t\t\t\tconst run: BackgroundCommandRun = (onData, runSignal) =>\n\t\t\t\t\tops\n\t\t\t\t\t\t.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\t\tonData,\n\t\t\t\t\t\t\tsignal: runSignal,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\t\t\tthrow error instanceof Error && error.message.startsWith(\"timeout:\")\n\t\t\t\t\t\t\t\t? new Error(timeoutStatus(error))\n\t\t\t\t\t\t\t\t: error;\n\t\t\t\t\t\t});\n\t\t\t\tconst started = background.start({ toolCallId, command, cwd: spawnContext.cwd, shell: config.name }, run);\n\t\t\t\tconst structuredContent: BashToolOutput = {\n\t\t\t\t\ttask_id: started.id,\n\t\t\t\t\t...(started.outputFile ? { output_file: started.outputFile } : {}),\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Command running in the background with task_id: ${started.id}${started.outputFile ? `\\nOutput file: ${started.outputFile}` : \"\"}\\nRead its new output with ${BASH_OUTPUT_TOOL_NAME} and stop it with ${TASK_STOP_TOOL_NAME}. A <task-notification> arrives when it exits by itself; do not poll ${BASH_OUTPUT_TOOL_NAME} to wait for that.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t\tstructuredContent,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${startLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst startedAt = performance.now();\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\t// Only a command that runs sandboxed can be denied by the sandbox.\n\t\t\t\tconst callOps =\n\t\t\t\t\tescalate && unsandboxedOps && sandbox?.policy(spawnContext.cwd)\n\t\t\t\t\t\t? withUnsandboxedRetry(ops, unsandboxedOps, (command) => escalate({ kind: \"command\", command }, ctx))\n\t\t\t\t\t\t: ops;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await callOps.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, timeoutStatus(err)));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode === null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, \"Command terminated without an exit code\"));\n\t\t\t\t}\n\t\t\t\tconst wallTimeSeconds = Math.round((performance.now() - startedAt) / 100) / 10;\n\t\t\t\tconst fullOutput = await output.readFullOutput(STRUCTURED_OUTPUT_MAX_BYTES);\n\t\t\t\tconst structuredContent: BashToolOutput = {\n\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t...(fullOutput.truncated && snapshot.fullOutputPath\n\t\t\t\t\t\t? { full_output_path: snapshot.fullOutputPath }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\twall_time_seconds: wallTimeSeconds,\n\t\t\t\t};\n\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: appendStatus(outputText, `Command exited with code ${exitCode}`) }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t\tstructuredContent,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details, structuredContent };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\t...createShellRenderers(config.prompt),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"diffra-bash\",\n\tcreateLocalOperations: (options, sandbox) => createLocalBashOperations({ shellPath: options?.shellPath, sandbox }),\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): TypeBoxAgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
@@ -77,6 +77,14 @@ export declare function generateDiffString(oldContent: string, newContent: strin
77
77
  diff: string;
78
78
  firstChangedLine: number | undefined;
79
79
  };
80
+ /**
81
+ * Lines added and removed from `oldContent` to `newContent` by a line diff. A change of more than 1000
82
+ * lines counts as replacing every line, which bounds the cost of diffing a rewritten file.
83
+ */
84
+ export declare function countChangedLines(oldContent: string, newContent: string): {
85
+ additions: number;
86
+ deletions: number;
87
+ };
80
88
  /** Display diff and unified patch of an edit, as returned in the edit tool's details. */
81
89
  export interface EditDiff {
82
90
  diff: string;
@@ -1 +1 @@
1
- {"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../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AAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CA0BzC;AAED;;;GAGG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC"}
@@ -320,6 +320,28 @@ export function generateDiffString(oldContent, newContent, contextLines = 4) {
320
320
  const { output, firstChangedLine } = formatDisplayDiff(Diff.diffLines(oldContent, newContent), 1, 1, lineNumWidth, contextLines);
321
321
  return { diff: output.join("\n"), firstChangedLine };
322
322
  }
323
+ /** Changed lines past which countChangedLines stops diffing: diffLines takes time in proportion to them. */
324
+ const COUNT_CHANGED_LINES_MAX_EDIT = 1000;
325
+ /**
326
+ * Lines added and removed from `oldContent` to `newContent` by a line diff. A change of more than 1000
327
+ * lines counts as replacing every line, which bounds the cost of diffing a rewritten file.
328
+ */
329
+ export function countChangedLines(oldContent, newContent) {
330
+ const parts = Diff.diffLines(oldContent, newContent, { maxEditLength: COUNT_CHANGED_LINES_MAX_EDIT });
331
+ if (!parts) {
332
+ const lines = (text) => text.length === 0 ? 0 : countLineFeeds(text, 0, text.length) + (text.endsWith("\n") ? 0 : 1);
333
+ return { additions: lines(newContent), deletions: lines(oldContent) };
334
+ }
335
+ let additions = 0;
336
+ let deletions = 0;
337
+ for (const part of parts) {
338
+ if (part.added)
339
+ additions += part.count;
340
+ else if (part.removed)
341
+ deletions += part.count;
342
+ }
343
+ return { additions, deletions };
344
+ }
323
345
  /** Number of lines as `text.split("\n").length` counts them, without building the array. */
324
346
  function countLines(text) {
325
347
  return countLineFeeds(text, 0, text.length) + 1;