@diffra-ai/cli 0.1.4 → 0.2.1

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-YTASKTAG.js → anthropic-messages-UM2LSKVG.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-2JI3BQFX.js → azure-openai-responses-LLULQ6UR.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-CAD23HR7.js → chunk-37INV3TW.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-PCXT7GLW.js → chunk-6NW7EDTU.js} +116 -87
  7. package/dist/bundle/chunks/{chunk-7QEHJ36J.js → chunk-BSCVN57O.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-IDYI4NPC.js → chunk-I6QEKFFB.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-ZW3S4FQY.js → chunk-J2CQ7AOB.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-SI7T4LPD.js → chunk-J3RI6JJL.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-GNFHDZLP.js → chunk-MAMCTGRH.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-YDKIXS42.js → chunk-MWJ5PWKE.js} +1 -1
  13. package/dist/bundle/chunks/chunk-QCEU5NDS.js +2 -0
  14. package/dist/bundle/chunks/{chunk-6RKODDUE.js → chunk-UBBD6YWP.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-AI3Y7XHP.js → chunk-UIVU7TEF.js} +4 -4
  16. package/dist/bundle/chunks/{chunk-MPWP6WCT.js → chunk-Y5LGEDHU.js} +1 -1
  17. package/dist/bundle/chunks/{cli-2W6362ZV.js → cli-VEFNOOXB.js} +1 -1
  18. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-MN7VZOHO.js → cloudflare-workers-ai-system-one-VQHACWH5.js} +1 -1
  19. package/dist/bundle/chunks/{execute-OEFRHFHI.js → execute-YR7Q5B3S.js} +1 -1
  20. package/dist/bundle/chunks/{google-generative-ai-QROUBJ3Y.js → google-generative-ai-YFRD2UAD.js} +1 -1
  21. package/dist/bundle/chunks/{google-vertex-RHSCDEG4.js → google-vertex-7EWCT4BL.js} +1 -1
  22. package/dist/bundle/chunks/{llama-cpp-classify-QCKHKADQ.js → llama-cpp-classify-D5PC6EEP.js} +1 -1
  23. package/dist/bundle/chunks/{mistral-conversations-WO6QUI4U.js → mistral-conversations-ILNLXCLF.js} +1 -1
  24. package/dist/bundle/chunks/{openai-codex-responses-XFI3MXBY.js → openai-codex-responses-YESP5ZRN.js} +1 -1
  25. package/dist/bundle/chunks/{openai-completions-2UHGTBTY.js → openai-completions-BKYCRYVB.js} +1 -1
  26. package/dist/bundle/chunks/{openai-decisions-BPJODLLR.js → openai-decisions-OZVDLRU3.js} +1 -1
  27. package/dist/bundle/chunks/{openai-responses-CCD734Z2.js → openai-responses-GSXMBGMK.js} +1 -1
  28. package/dist/bundle/chunks/{openrouter-images-WSQ42OX2.js → openrouter-images-TK5PJTOE.js} +1 -1
  29. package/dist/bundle/chunks/{pi-messages-I264JUT4.js → pi-messages-AHAEGVU4.js} +1 -1
  30. package/dist/bundle/chunks/{typesafe-system-one-O3PSKAI2.js → typesafe-system-one-XHINCFVH.js} +1 -1
  31. package/dist/bundle/chunks/{virtual-modules-CMUMO27Q.js → virtual-modules-7F3I52A6.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 +69 -1
  36. package/dist/core/agent-session.d.ts.map +1 -1
  37. package/dist/core/agent-session.js +184 -17
  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 +9 -1
  125. package/dist/index.d.ts.map +1 -1
  126. package/dist/index.js +4 -1
  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 +63 -1
  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-RAT6HXXD.js +0 -2
@@ -24,6 +24,7 @@ import { sleep } from "../utils/sleep.js";
24
24
  import { normalizeToolResultImages } from "../utils/tool-result-images.js";
25
25
  import { APPROVAL_MODE_ENTRY, nextApprovalMode, readApprovalModeState, } from "./approval-mode.js";
26
26
  import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
27
+ import { BackgroundCommands } from "./background-commands.js";
27
28
  import { executeBashWithOperations } from "./bash-executor.js";
28
29
  import { generateBugReportSummary } from "./bug-report.js";
29
30
  import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateProjectedContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
@@ -44,9 +45,13 @@ import { getLatestCompactionEntry, SessionManager, } from "./session-manager.js"
44
45
  import { applyToolModifiers, DEFAULT_TOOL_NAMES, } from "./settings-manager.js";
45
46
  import { BUILTIN_PATH_PREFIX, createSyntheticSourceInfo, isSyntheticPath } from "./source-info.js";
46
47
  import { buildSystemPrompt, buildSystemPromptSections, diffSystemPromptSections, normalizeBuildSystemPromptOptions, } from "./system-prompt.js";
48
+ import { BACKGROUND_COMMAND_NOTIFICATION_TYPE, BASH_OUTPUT_TOOL_NAME, createBashOutputToolDefinition, createTaskStopToolDefinition, formatBackgroundCommandNotification, TASK_STOP_TOOL_NAME, } from "./tools/background-tasks.js";
47
49
  import { createLocalBashOperations } from "./tools/bash.js";
50
+ import { defaultEditOperations } from "./tools/edit.js";
48
51
  import { createAllToolDefinitions } from "./tools/index.js";
49
52
  import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
53
+ import { defaultWriteOperations } from "./tools/write.js";
54
+ import { readTurnFileChanges, recordTurnFileWrites, TURN_FILES_ENTRY, TURN_FILES_UNDO_ENTRY, TurnFileRecorder, undoTurnFiles, } from "./turn-files.js";
50
55
  import { addUsageToTotals, combineUsage, createUsageTotals } from "./usage-totals.js";
51
56
  import { findLatestResponse, getBranchSelection, getVirtualModelState, isVirtualModel, VIRTUAL_MODEL_STATE_ENTRY, } from "./virtual-models.js";
52
57
  /**
@@ -146,6 +151,16 @@ export class AgentSession {
146
151
  // Bash execution state
147
152
  _bashAbortControllers = new Set();
148
153
  _pendingBashMessages = [];
154
+ /** Commands the shell tools started with `run_in_background`. */
155
+ _backgroundCommands = new BackgroundCommands({
156
+ onStart: (command) => this._onBackgroundCommandStart(command),
157
+ onOutput: (id, chunk) => this._emit({ type: "background_command_output", id, chunk }),
158
+ onEnd: (command) => this._onBackgroundCommandEnd(command),
159
+ });
160
+ /** Collects the files the edit and write tools change while a run is active. */
161
+ _turnFileRecorder;
162
+ /** Settles after the last `undoTurn()` call, which the next call waits for. */
163
+ _turnUndoQueue = Promise.resolve();
149
164
  // Extension system
150
165
  _extensionRunner;
151
166
  _turnIndex = 0;
@@ -155,7 +170,10 @@ export class AgentSession {
155
170
  _lastActivityOutcome = "completed";
156
171
  _isBeforeSettle = false;
157
172
  _abortDuringBeforeSettle = false;
158
- _isEmittingAgentSettled = false;
173
+ // From the end of a run's loop until its agent_settled handlers return. The run still counts as
174
+ // streaming while it records its turn files, but its loop no longer reads the queues, so prompts and
175
+ // custom messages sent meanwhile wait in _deferredSettledActions instead of being queued into it.
176
+ _isSettling = false;
159
177
  _deferredSettledActions = [];
160
178
  _resourceLoader;
161
179
  _customTools;
@@ -745,14 +763,14 @@ export class AgentSession {
745
763
  async _emitAgentSettled() {
746
764
  this._cacheWarmer?.onAgentSettled();
747
765
  this._isAgentRunActive = false;
748
- this._isEmittingAgentSettled = true;
766
+ this._isSettling = true;
749
767
  try {
750
768
  const aborted = this._agentRunAbortRequested;
751
769
  await this._extensionRunner.emit({ type: "agent_settled", aborted });
752
770
  this._emit({ type: "agent_settled", aborted });
753
771
  }
754
772
  finally {
755
- this._isEmittingAgentSettled = false;
773
+ this._isSettling = false;
756
774
  }
757
775
  const deferred = this._deferredSettledActions.splice(0);
758
776
  if (deferred.length > 0) {
@@ -1080,6 +1098,7 @@ export class AgentSession {
1080
1098
  this.abortCompaction();
1081
1099
  this.abortBranchSummary();
1082
1100
  this.abortBash();
1101
+ this._backgroundCommands.dispose();
1083
1102
  this.agent.abort();
1084
1103
  }
1085
1104
  catch {
@@ -1205,10 +1224,13 @@ export class AgentSession {
1205
1224
  const action = request.kind === "command"
1206
1225
  ? `this command:\n\n ${request.command.slice(0, 300)}`
1207
1226
  : `writing ${request.path}:\n\n ${request.reason}`;
1227
+ const title = `The sandbox blocked ${action}\n\nRun it without the sandbox?`;
1228
+ if (ctx.ui.approve) {
1229
+ const answer = await ctx.ui.approve({ kind: "sandbox", title, action: request }, { signal: ctx.signal });
1230
+ return answer?.kind === "once";
1231
+ }
1208
1232
  const yes = "Yes, run it without the sandbox once";
1209
- const answer = await ctx.ui.select(`The sandbox blocked ${action}\n\nRun it without the sandbox?`, [yes, "No"], {
1210
- signal: ctx.signal,
1211
- });
1233
+ const answer = await ctx.ui.select(title, [yes, "No"], { signal: ctx.signal });
1212
1234
  return answer === yes;
1213
1235
  }
1214
1236
  _setActiveTools(toolNames) {
@@ -1227,10 +1249,20 @@ export class AgentSession {
1227
1249
  _isAllowedTool(name) {
1228
1250
  if (this._excludedTools?.(name))
1229
1251
  return false;
1230
- if (!this._allowedTools || this._allowedTools(name))
1252
+ if (!this._allowedTools || this._allowlistNames(this._allowedTools, name))
1231
1253
  return true;
1232
1254
  return !this._allowlistFiltersMcp && isMcpToolName(name);
1233
1255
  }
1256
+ /**
1257
+ * Whether the `--tools` allowlist names the tool. Naming a shell tool names `bash_output` and `task_stop`
1258
+ * too, so that background commands it starts can be read and stopped.
1259
+ */
1260
+ _allowlistNames(allowedTools, name) {
1261
+ if (allowedTools(name))
1262
+ return true;
1263
+ const backgroundTaskTool = name === BASH_OUTPUT_TOOL_NAME || name === TASK_STOP_TOOL_NAME;
1264
+ return backgroundTaskTool && (allowedTools("bash") || allowedTools("powershell"));
1265
+ }
1234
1266
  /**
1235
1267
  * Whether the tool may be active, which declares it to the model. MCP tools the allowlist keeps
1236
1268
  * without matching them are only for codemode and tool_search: they may be declared only when
@@ -1541,6 +1573,10 @@ export class AgentSession {
1541
1573
  // The run records the loadout in the transcript; restored tools that did not register by now
1542
1574
  // are dropped, so a tool that never registers does not stay pending.
1543
1575
  this._pendingToolNames.clear();
1576
+ // The entry of the starting message names the turn whose file changes the run records.
1577
+ const startMessage = trigger.messageType === "custom" ? trigger.message : messages.find((message) => message.role === "user");
1578
+ const turnFiles = new TurnFileRecorder();
1579
+ this._turnFileRecorder = turnFiles;
1544
1580
  try {
1545
1581
  await this.agent.prompt(messages);
1546
1582
  while (!this._agentRunAbortRequested) {
@@ -1558,12 +1594,15 @@ export class AgentSession {
1558
1594
  }
1559
1595
  }
1560
1596
  finally {
1597
+ this._isSettling = true;
1561
1598
  if (this._agentRunAbortRequested)
1562
1599
  this._finishCancelledRetry();
1563
1600
  this._failedResponse = undefined;
1564
1601
  this._runSystemPromptOptions = undefined;
1602
+ this._turnFileRecorder = undefined;
1565
1603
  this._flushPendingBashMessages();
1566
1604
  this._flushPendingCustomMessages();
1605
+ await this._recordTurnFiles(turnFiles, startMessage);
1567
1606
  await this._emitAgentSettled();
1568
1607
  }
1569
1608
  }
@@ -1725,7 +1764,7 @@ export class AgentSession {
1725
1764
  * @throws Error if no model selected or no API key available (when not streaming)
1726
1765
  */
1727
1766
  async prompt(text, options) {
1728
- if (this._isEmittingAgentSettled) {
1767
+ if (this._isSettling) {
1729
1768
  this._deferredSettledActions.push(async () => await this.prompt(text, options));
1730
1769
  return;
1731
1770
  }
@@ -1988,6 +2027,9 @@ export class AgentSession {
1988
2027
  if (options?.deliverAs === "nextTurn") {
1989
2028
  this._pendingNextTurnMessages.push(appMessage);
1990
2029
  }
2030
+ else if (this._isSettling && (this.isStreaming || options?.triggerTurn)) {
2031
+ this._deferredSettledActions.push(async () => await this.sendCustomMessage(message, options));
2032
+ }
1991
2033
  else if (this.isStreaming && options?.triggerTurn !== false) {
1992
2034
  if (options?.deliverAs === "followUp") {
1993
2035
  this.agent.followUp(appMessage);
@@ -1997,10 +2039,6 @@ export class AgentSession {
1997
2039
  }
1998
2040
  }
1999
2041
  else if (options?.triggerTurn) {
2000
- if (this._isEmittingAgentSettled) {
2001
- this._deferredSettledActions.push(async () => await this.sendCustomMessage(message, options));
2002
- return;
2003
- }
2004
2042
  await this._startRun({ messageType: "custom", message: appMessage });
2005
2043
  }
2006
2044
  else if (this.isStreaming) {
@@ -2978,6 +3016,7 @@ export class AgentSession {
2978
3016
  setThinkingLevel: (level) => this.setThinkingLevel(level),
2979
3017
  getApprovalMode: () => this.approvalMode,
2980
3018
  setApprovalMode: (mode, options) => this.setApprovalMode(mode, options),
3019
+ getBackgroundCommands: () => this.getBackgroundCommands(),
2981
3020
  }, {
2982
3021
  getModel: () => this.model,
2983
3022
  getScopedModels: () => this._scopedModels,
@@ -3043,6 +3082,8 @@ export class AgentSession {
3043
3082
  const allowedTools = this._allowedTools;
3044
3083
  const registeredTools = this._extensionRunner.getAllRegisteredTools();
3045
3084
  const allCustomTools = [
3085
+ // First, so that extension and SDK tools of the same name replace them.
3086
+ ...this._getBackgroundTaskTools(),
3046
3087
  ...registeredTools,
3047
3088
  ...this._customTools.map((definition) => ({
3048
3089
  definition,
@@ -3097,7 +3138,7 @@ export class AgentSession {
3097
3138
  for (const toolName of this._toolRegistry.keys()) {
3098
3139
  // Naming or matching a tool activates it even when it is not active by default. MCP tools
3099
3140
  // kept registered without being named stay inactive.
3100
- if (allowedTools(toolName) && this._isDeclarable(toolName)) {
3141
+ if (this._allowlistNames(allowedTools, toolName) && this._isDeclarable(toolName)) {
3101
3142
  nextActiveToolNames.push(toolName);
3102
3143
  }
3103
3144
  }
@@ -3128,6 +3169,25 @@ export class AgentSession {
3128
3169
  _isActivatedOnRegistration(name) {
3129
3170
  return this._isDeclarable(name) && this._toolDefinitions.get(name)?.definition.defaultActive !== false;
3130
3171
  }
3172
+ /**
3173
+ * `bash_output` and `task_stop`, once they have something to do: both once a shell tool started a background
3174
+ * command, `task_stop` also while an extension can stop background tasks of its own. Like extension tools, they
3175
+ * are activated when they register.
3176
+ */
3177
+ _getBackgroundTaskTools() {
3178
+ const hasCommands = this._backgroundCommands.size > 0;
3179
+ const getStoppers = () => this._extensionRunner.getTaskStoppers();
3180
+ const definitions = [
3181
+ ...(hasCommands ? [createBashOutputToolDefinition(this._backgroundCommands)] : []),
3182
+ ...(hasCommands || getStoppers().length > 0
3183
+ ? [createTaskStopToolDefinition(this._backgroundCommands, getStoppers)]
3184
+ : []),
3185
+ ];
3186
+ return definitions.map((definition) => ({
3187
+ definition,
3188
+ sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${definition.name}`, { source: "builtin" }),
3189
+ }));
3190
+ }
3131
3191
  _buildRuntime(options) {
3132
3192
  const autoResizeImages = this.settingsManager.getImageAutoResize();
3133
3193
  const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
@@ -3137,6 +3197,9 @@ export class AgentSession {
3137
3197
  policy: (cwd) => resolveSandboxPolicy(this.settingsManager.getSandboxSettings(), cwd),
3138
3198
  escalate: (request, ctx) => this._approveUnsandboxed(request, ctx),
3139
3199
  };
3200
+ // Writes are the one point every edit and write call that changes a file passes, and only those:
3201
+ // calls blocked by tool_call handlers or failing before they write never get there.
3202
+ const getTurnFileRecorder = () => this._turnFileRecorder;
3140
3203
  const baseToolDefinitions = this._baseToolsOverride
3141
3204
  ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
3142
3205
  name,
@@ -3144,10 +3207,10 @@ export class AgentSession {
3144
3207
  ]))
3145
3208
  : createAllToolDefinitions(this._cwd, {
3146
3209
  read: { autoResizeImages },
3147
- bash: { commandPrefix: shellCommandPrefix, shellPath, sandbox },
3148
- powershell: { sandbox },
3149
- write: { sandbox },
3150
- edit: { sandbox },
3210
+ bash: { commandPrefix: shellCommandPrefix, shellPath, sandbox, background: this._backgroundCommands },
3211
+ powershell: { sandbox, background: this._backgroundCommands },
3212
+ write: { sandbox, operations: recordTurnFileWrites(defaultWriteOperations, getTurnFileRecorder) },
3213
+ edit: { sandbox, operations: recordTurnFileWrites(defaultEditOperations, getTurnFileRecorder) },
3151
3214
  });
3152
3215
  this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
3153
3216
  const extensionsResult = this._resourceLoader.getExtensions();
@@ -3412,6 +3475,110 @@ export class AgentSession {
3412
3475
  this._refreshFinalizedContext();
3413
3476
  }
3414
3477
  // =========================================================================
3478
+ // Turn File Changes
3479
+ // =========================================================================
3480
+ /** Files the edit and write tools changed in each turn on the current branch, oldest first. */
3481
+ getTurnFileChanges() {
3482
+ return readTurnFileChanges(this.sessionManager.getBranch());
3483
+ }
3484
+ /**
3485
+ * Restore the files a turn changed to their content before it, deleting files it added, and record the undo
3486
+ * on the current branch. Refuses, changing nothing, while a run is active, when the branch has no record of
3487
+ * the turn or it was undone, when a file was too large to snapshot, when a later turn that was not undone
3488
+ * changed the same files, or when a file on disk no longer matches the end of the turn. Calls run one at a time.
3489
+ */
3490
+ undoTurn(turnId) {
3491
+ const result = this._turnUndoQueue.then(() => this._undoTurn(turnId));
3492
+ this._turnUndoQueue = result.catch(() => undefined);
3493
+ return result;
3494
+ }
3495
+ async _undoTurn(turnId) {
3496
+ if (this._isAgentRunActive)
3497
+ return { kind: "refused", reason: "running", paths: [] };
3498
+ const result = await undoTurnFiles(turnId, this.sessionManager);
3499
+ if (result.kind === "undone")
3500
+ this._appendTurnFilesEntry(turnId, TURN_FILES_UNDO_ENTRY, { turnId });
3501
+ return result;
3502
+ }
3503
+ /**
3504
+ * Record the files the run changed on the branch. A failure is reported to the error listeners instead of
3505
+ * thrown: the run has finished and must still settle.
3506
+ */
3507
+ async _recordTurnFiles(recorder, startMessage) {
3508
+ const turnId = startMessage && this._findPersistedMessageEntryId(startMessage);
3509
+ if (!turnId)
3510
+ return;
3511
+ try {
3512
+ const record = await recorder.record(turnId, this.sessionManager);
3513
+ if (record)
3514
+ this._appendTurnFilesEntry(turnId, TURN_FILES_ENTRY, record);
3515
+ }
3516
+ catch (error) {
3517
+ this._extensionRunner.emitError({
3518
+ extensionPath: "<runtime>",
3519
+ event: "turn_files",
3520
+ error: error instanceof Error ? error.message : String(error),
3521
+ stack: error instanceof Error ? error.stack : undefined,
3522
+ });
3523
+ }
3524
+ }
3525
+ /** Append a turn file entry and announce it with the turn's new state. */
3526
+ _appendTurnFilesEntry(turnId, customType, data) {
3527
+ const entry = this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(customType, data));
3528
+ if (entry)
3529
+ this._emit({ type: "entry_appended", entry });
3530
+ const turn = this.getTurnFileChanges().find((candidate) => candidate.turnId === turnId);
3531
+ if (turn)
3532
+ this._emit({ type: "turn_files", turn });
3533
+ }
3534
+ // =========================================================================
3535
+ // Background Commands
3536
+ // =========================================================================
3537
+ /** The commands the shell tools started with `run_in_background`, running and ended, oldest first. */
3538
+ getBackgroundCommands() {
3539
+ return this._backgroundCommands.list();
3540
+ }
3541
+ /**
3542
+ * The end of a background command's output held in memory: up to 512 Ki characters, and at least the last
3543
+ * 256 Ki once it wrote more. `outputFile` has all of it.
3544
+ */
3545
+ readBackgroundOutput(id) {
3546
+ return this._backgroundCommands.readTail(id);
3547
+ }
3548
+ /**
3549
+ * Kill a running background command with its child processes; `background_command_end` follows. Returns false
3550
+ * when no command with this id is running.
3551
+ */
3552
+ stopBackgroundCommand(id) {
3553
+ return this._backgroundCommands.stop(id);
3554
+ }
3555
+ _onBackgroundCommandStart(command) {
3556
+ // The first background command registers the tools that read and stop it.
3557
+ if (this._backgroundCommands.size === 1)
3558
+ this._refreshToolRegistry();
3559
+ this._emit({ type: "background_command_start", command });
3560
+ }
3561
+ /** Report the end to hosts, and to the agent when the command ended by itself. */
3562
+ _onBackgroundCommandEnd(command) {
3563
+ this._emit({ type: "background_command_end", command });
3564
+ // Whoever stopped a command already knows it ended.
3565
+ if (command.status === "stopped")
3566
+ return;
3567
+ this.sendCustomMessage({
3568
+ customType: BACKGROUND_COMMAND_NOTIFICATION_TYPE,
3569
+ content: formatBackgroundCommandNotification(command),
3570
+ display: true,
3571
+ details: command,
3572
+ }, { triggerTurn: true, deliverAs: "followUp" }).catch((error) => {
3573
+ this._extensionRunner.emitError({
3574
+ extensionPath: "<runtime>",
3575
+ event: "background_command_notification",
3576
+ error: error instanceof Error ? error.message : String(error),
3577
+ stack: error instanceof Error ? error.stack : undefined,
3578
+ });
3579
+ });
3580
+ }
3581
+ // =========================================================================
3415
3582
  // Session Management
3416
3583
  // =========================================================================
3417
3584
  /**