strands-darwin 0.0.35 → 0.0.37

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 (254) hide show
  1. package/README.md +23 -6
  2. package/README.zh-CN.md +23 -6
  3. package/dist/patches/{@strands-agents+sdk+1.16.0.patch → @strands-agents+sdk+1.18.0.patch} +320 -9
  4. package/dist/src/agent/compact.js +1 -1
  5. package/dist/src/agent/prompt-cache.js +15 -2
  6. package/dist/src/agent/prompt-cache.js.map +1 -1
  7. package/dist/src/agent/rewind.d.ts +2 -0
  8. package/dist/src/agent/rewind.js +4 -1
  9. package/dist/src/agent/rewind.js.map +1 -1
  10. package/dist/src/agent/runtime.d.ts +81 -20
  11. package/dist/src/agent/runtime.js +227 -43
  12. package/dist/src/agent/runtime.js.map +1 -1
  13. package/dist/src/agent/session.d.ts +96 -4
  14. package/dist/src/agent/session.js +249 -9
  15. package/dist/src/agent/session.js.map +1 -1
  16. package/dist/src/agent/stream-idle.d.ts +16 -0
  17. package/dist/src/agent/stream-idle.js +127 -0
  18. package/dist/src/agent/stream-idle.js.map +1 -0
  19. package/dist/src/agent/system-prompt.d.ts +1 -1
  20. package/dist/src/agent/system-prompt.js +12 -0
  21. package/dist/src/agent/system-prompt.js.map +1 -1
  22. package/dist/src/agent/task-terminal-delivery.d.ts +25 -2
  23. package/dist/src/agent/task-terminal-delivery.js +80 -7
  24. package/dist/src/agent/task-terminal-delivery.js.map +1 -1
  25. package/dist/src/agent/working-context.d.ts +21 -1
  26. package/dist/src/agent/working-context.js +28 -1
  27. package/dist/src/agent/working-context.js.map +1 -1
  28. package/dist/src/agent/workspace-trust.d.ts +112 -0
  29. package/dist/src/agent/workspace-trust.js +207 -0
  30. package/dist/src/agent/workspace-trust.js.map +1 -0
  31. package/dist/src/agentcore/auto-policy.d.ts +7 -0
  32. package/dist/src/agentcore/auto-policy.js +50 -0
  33. package/dist/src/agentcore/auto-policy.js.map +1 -0
  34. package/dist/src/agentcore/auto-state.d.ts +43 -0
  35. package/dist/src/agentcore/auto-state.js +73 -0
  36. package/dist/src/agentcore/auto-state.js.map +1 -0
  37. package/dist/src/agentcore/cli.d.ts +2 -0
  38. package/dist/src/agentcore/cli.js +38 -0
  39. package/dist/src/agentcore/cli.js.map +1 -0
  40. package/dist/src/agentcore/config.d.ts +48 -0
  41. package/dist/src/agentcore/config.js +44 -0
  42. package/dist/src/agentcore/config.js.map +1 -0
  43. package/dist/src/agentcore/controller.d.ts +105 -0
  44. package/dist/src/agentcore/controller.js +979 -0
  45. package/dist/src/agentcore/controller.js.map +1 -0
  46. package/dist/src/agentcore/projection.d.ts +2 -0
  47. package/dist/src/agentcore/projection.js +8 -0
  48. package/dist/src/agentcore/projection.js.map +1 -0
  49. package/dist/src/agentcore/records.d.ts +41 -0
  50. package/dist/src/agentcore/records.js +149 -0
  51. package/dist/src/agentcore/records.js.map +1 -0
  52. package/dist/src/agentcore/state.d.ts +16 -0
  53. package/dist/src/agentcore/state.js +149 -0
  54. package/dist/src/agentcore/state.js.map +1 -0
  55. package/dist/src/agentcore/tools.d.ts +3 -0
  56. package/dist/src/agentcore/tools.js +11 -0
  57. package/dist/src/agentcore/tools.js.map +1 -0
  58. package/dist/src/agentcore/transport.d.ts +37 -0
  59. package/dist/src/agentcore/transport.js +242 -0
  60. package/dist/src/agentcore/transport.js.map +1 -0
  61. package/dist/src/agentcore/upload-projection.d.ts +208 -0
  62. package/dist/src/agentcore/upload-projection.js +823 -0
  63. package/dist/src/agentcore/upload-projection.js.map +1 -0
  64. package/dist/src/agents/child-recipe.js +4 -1
  65. package/dist/src/agents/child-recipe.js.map +1 -1
  66. package/dist/src/agents/loader.d.ts +12 -0
  67. package/dist/src/agents/loader.js +15 -1
  68. package/dist/src/agents/loader.js.map +1 -1
  69. package/dist/src/agents/subagent-tool.js +2 -4
  70. package/dist/src/agents/subagent-tool.js.map +1 -1
  71. package/dist/src/agents/workflow-tool.js +2 -4
  72. package/dist/src/agents/workflow-tool.js.map +1 -1
  73. package/dist/src/cli-doctor.js +7 -0
  74. package/dist/src/cli-doctor.js.map +1 -1
  75. package/dist/src/cli-import.d.ts +1 -0
  76. package/dist/src/cli-import.js +26 -0
  77. package/dist/src/cli-import.js.map +1 -0
  78. package/dist/src/cli-main.js +60 -10
  79. package/dist/src/cli-main.js.map +1 -1
  80. package/dist/src/cli-permissions.d.ts +2 -0
  81. package/dist/src/cli-permissions.js +20 -0
  82. package/dist/src/cli-permissions.js.map +1 -0
  83. package/dist/src/cli-sessions.js +6 -2
  84. package/dist/src/cli-sessions.js.map +1 -1
  85. package/dist/src/cli-usage.d.ts +9 -1
  86. package/dist/src/cli-usage.js +13 -0
  87. package/dist/src/cli-usage.js.map +1 -1
  88. package/dist/src/cli.js +19 -2
  89. package/dist/src/cli.js.map +1 -1
  90. package/dist/src/commands/custom-commands.d.ts +1 -1
  91. package/dist/src/commands/custom-commands.js +14 -6
  92. package/dist/src/commands/custom-commands.js.map +1 -1
  93. package/dist/src/commands/review-command.d.ts +10 -0
  94. package/dist/src/commands/review-command.js +28 -0
  95. package/dist/src/commands/review-command.js.map +1 -0
  96. package/dist/src/config-file.d.ts +9 -0
  97. package/dist/src/config-file.js +82 -0
  98. package/dist/src/config-file.js.map +1 -0
  99. package/dist/src/config.d.ts +66 -5
  100. package/dist/src/config.js +126 -42
  101. package/dist/src/config.js.map +1 -1
  102. package/dist/src/dev-repl.js +17 -1
  103. package/dist/src/dev-repl.js.map +1 -1
  104. package/dist/src/headless-protocol.d.ts +24 -1
  105. package/dist/src/headless-protocol.js +18 -0
  106. package/dist/src/headless-protocol.js.map +1 -1
  107. package/dist/src/headless-runner.d.ts +8 -0
  108. package/dist/src/headless-runner.js +37 -1
  109. package/dist/src/headless-runner.js.map +1 -1
  110. package/dist/src/hooks/hook-process.js +7 -2
  111. package/dist/src/hooks/hook-process.js.map +1 -1
  112. package/dist/src/hooks/lifecycle-hooks.js +3 -1
  113. package/dist/src/hooks/lifecycle-hooks.js.map +1 -1
  114. package/dist/src/hooks/tool-hooks.js +3 -1
  115. package/dist/src/hooks/tool-hooks.js.map +1 -1
  116. package/dist/src/import-claude-files.d.ts +28 -0
  117. package/dist/src/import-claude-files.js +227 -0
  118. package/dist/src/import-claude-files.js.map +1 -0
  119. package/dist/src/import-claude-snippets.d.ts +2 -0
  120. package/dist/src/import-claude-snippets.js +105 -0
  121. package/dist/src/import-claude-snippets.js.map +1 -0
  122. package/dist/src/import-claude.d.ts +13 -0
  123. package/dist/src/import-claude.js +287 -0
  124. package/dist/src/import-claude.js.map +1 -0
  125. package/dist/src/mcp/registry.d.ts +57 -1
  126. package/dist/src/mcp/registry.js +78 -6
  127. package/dist/src/mcp/registry.js.map +1 -1
  128. package/dist/src/memory/command.d.ts +1 -1
  129. package/dist/src/memory/command.js +89 -4
  130. package/dist/src/memory/command.js.map +1 -1
  131. package/dist/src/memory/controller.d.ts +32 -0
  132. package/dist/src/memory/controller.js +39 -3
  133. package/dist/src/memory/controller.js.map +1 -1
  134. package/dist/src/memory/state.d.ts +6 -0
  135. package/dist/src/memory/state.js +6 -1
  136. package/dist/src/memory/state.js.map +1 -1
  137. package/dist/src/memory/store.d.ts +13 -0
  138. package/dist/src/memory/store.js +38 -2
  139. package/dist/src/memory/store.js.map +1 -1
  140. package/dist/src/memory/tools.d.ts +7 -0
  141. package/dist/src/memory/tools.js +12 -1
  142. package/dist/src/memory/tools.js.map +1 -1
  143. package/dist/src/npm-package/patch-package-format.d.ts +5 -5
  144. package/dist/src/npm-package/patch-package-format.js +4 -4
  145. package/dist/src/paths.js +3 -0
  146. package/dist/src/paths.js.map +1 -1
  147. package/dist/src/permissions-test.d.ts +18 -0
  148. package/dist/src/permissions-test.js +207 -0
  149. package/dist/src/permissions-test.js.map +1 -0
  150. package/dist/src/pricing/model-prices.d.ts +8 -5
  151. package/dist/src/pricing/model-prices.js +30 -15
  152. package/dist/src/pricing/model-prices.js.map +1 -1
  153. package/dist/src/project-identity.d.ts +3 -0
  154. package/dist/src/project-identity.js +8 -0
  155. package/dist/src/project-identity.js.map +1 -0
  156. package/dist/src/project-overrides.d.ts +57 -0
  157. package/dist/src/project-overrides.js +79 -0
  158. package/dist/src/project-overrides.js.map +1 -0
  159. package/dist/src/sdk-patch-preflight.js +1 -1
  160. package/dist/src/skills/builtin/developer/SKILL.md +2 -0
  161. package/dist/src/skills/builtin/self-reflection/references/reflection-template.md +2 -1
  162. package/dist/src/skills/builtin/setup-agentcore-memory/SKILL.md +158 -0
  163. package/dist/src/skills/loader.d.ts +1 -1
  164. package/dist/src/skills/loader.js +4 -1
  165. package/dist/src/skills/loader.js.map +1 -1
  166. package/dist/src/tools/background-bash.d.ts +13 -1
  167. package/dist/src/tools/background-bash.js +36 -8
  168. package/dist/src/tools/background-bash.js.map +1 -1
  169. package/dist/src/tools/shell-env.d.ts +24 -0
  170. package/dist/src/tools/shell-env.js +34 -0
  171. package/dist/src/tools/shell-env.js.map +1 -1
  172. package/dist/src/trajectory/reader.d.ts +1 -1
  173. package/dist/src/trajectory/reader.js +23 -3
  174. package/dist/src/trajectory/reader.js.map +1 -1
  175. package/dist/src/trajectory/record.d.ts +50 -2
  176. package/dist/src/trajectory/record.js +32 -0
  177. package/dist/src/trajectory/record.js.map +1 -1
  178. package/dist/src/trajectory/replay.d.ts +12 -1
  179. package/dist/src/trajectory/replay.js +31 -2
  180. package/dist/src/trajectory/replay.js.map +1 -1
  181. package/dist/src/trajectory/resume-recap.d.ts +11 -1
  182. package/dist/src/trajectory/resume-recap.js +10 -1
  183. package/dist/src/trajectory/resume-recap.js.map +1 -1
  184. package/dist/src/trajectory/rewind-history.d.ts +8 -0
  185. package/dist/src/trajectory/rewind-history.js +81 -0
  186. package/dist/src/trajectory/rewind-history.js.map +1 -0
  187. package/dist/src/trajectory/writer.d.ts +14 -1
  188. package/dist/src/trajectory/writer.js +38 -0
  189. package/dist/src/trajectory/writer.js.map +1 -1
  190. package/dist/src/tui/App.d.ts +5 -1
  191. package/dist/src/tui/App.js +284 -51
  192. package/dist/src/tui/App.js.map +1 -1
  193. package/dist/src/tui/InputBox.d.ts +1 -1
  194. package/dist/src/tui/InputBox.js +3 -2
  195. package/dist/src/tui/InputBox.js.map +1 -1
  196. package/dist/src/tui/MessageList.js +1 -1
  197. package/dist/src/tui/MessageList.js.map +1 -1
  198. package/dist/src/tui/PermissionPrompt.js +5 -3
  199. package/dist/src/tui/PermissionPrompt.js.map +1 -1
  200. package/dist/src/tui/QueuedMessages.js +14 -8
  201. package/dist/src/tui/QueuedMessages.js.map +1 -1
  202. package/dist/src/tui/ToolCallPanel.js +2 -2
  203. package/dist/src/tui/ToolCallPanel.js.map +1 -1
  204. package/dist/src/tui/WorkspaceTrustPrompt.d.ts +8 -0
  205. package/dist/src/tui/WorkspaceTrustPrompt.js +37 -0
  206. package/dist/src/tui/WorkspaceTrustPrompt.js.map +1 -0
  207. package/dist/src/tui/draft-stash.d.ts +25 -0
  208. package/dist/src/tui/draft-stash.js +49 -0
  209. package/dist/src/tui/draft-stash.js.map +1 -0
  210. package/dist/src/tui/frame-budget.d.ts +2 -2
  211. package/dist/src/tui/frame-budget.js +3 -3
  212. package/dist/src/tui/frame-budget.js.map +1 -1
  213. package/dist/src/tui/help-format.d.ts +2 -2
  214. package/dist/src/tui/help-format.js +3 -3
  215. package/dist/src/tui/help-format.js.map +1 -1
  216. package/dist/src/tui/mcp-format.d.ts +9 -0
  217. package/dist/src/tui/mcp-format.js +5 -3
  218. package/dist/src/tui/mcp-format.js.map +1 -1
  219. package/dist/src/tui/permission-rule-preview.d.ts +23 -0
  220. package/dist/src/tui/permission-rule-preview.js +38 -0
  221. package/dist/src/tui/permission-rule-preview.js.map +1 -0
  222. package/dist/src/tui/prompt-editor.d.ts +12 -0
  223. package/dist/src/tui/prompt-editor.js +57 -37
  224. package/dist/src/tui/prompt-editor.js.map +1 -1
  225. package/dist/src/tui/prompt-history-search.js +3 -2
  226. package/dist/src/tui/prompt-history-search.js.map +1 -1
  227. package/dist/src/tui/prompt-queue.d.ts +4 -2
  228. package/dist/src/tui/prompt-queue.js +18 -3
  229. package/dist/src/tui/prompt-queue.js.map +1 -1
  230. package/dist/src/tui/rewind-search.js +4 -3
  231. package/dist/src/tui/rewind-search.js.map +1 -1
  232. package/dist/src/tui/search-preview.d.ts +2 -0
  233. package/dist/src/tui/search-preview.js +9 -0
  234. package/dist/src/tui/search-preview.js.map +1 -0
  235. package/dist/src/tui/shell-command.js +4 -1
  236. package/dist/src/tui/shell-command.js.map +1 -1
  237. package/dist/src/tui/spinner.d.ts +1 -0
  238. package/dist/src/tui/spinner.js +6 -0
  239. package/dist/src/tui/spinner.js.map +1 -0
  240. package/dist/src/tui/status-format.d.ts +9 -0
  241. package/dist/src/tui/status-format.js +37 -2
  242. package/dist/src/tui/status-format.js.map +1 -1
  243. package/dist/src/tui/subagent-format.js +6 -0
  244. package/dist/src/tui/subagent-format.js.map +1 -1
  245. package/dist/src/tui/task-format.d.ts +5 -0
  246. package/dist/src/tui/task-format.js +15 -0
  247. package/dist/src/tui/task-format.js.map +1 -1
  248. package/dist/src/tui/trust-format.d.ts +31 -0
  249. package/dist/src/tui/trust-format.js +102 -0
  250. package/dist/src/tui/trust-format.js.map +1 -0
  251. package/dist/src/tui/turn-state.d.ts +1 -0
  252. package/dist/src/tui/turn-state.js +2 -0
  253. package/dist/src/tui/turn-state.js.map +1 -1
  254. package/package.json +4 -3
@@ -5,7 +5,7 @@
5
5
  * raw event stream to whatever is driving it. Callers (the dev REPL now, Ink
6
6
  * later) decide how to render.
7
7
  */
8
- import { Agent, BeforeInvocationEvent, SummarizingConversationManager, TextBlock } from '@strands-agents/sdk';
8
+ import { Agent, AfterToolCallEvent, BeforeToolCallEvent, BeforeToolsEvent, ToolResultEvent, HookOrder, BeforeInvocationEvent, SummarizingConversationManager, TextBlock } from '@strands-agents/sdk';
9
9
  import { makeFileEditor } from '@strands-agents/sdk/vended-tools/file-editor';
10
10
  import { httpRequest } from '@strands-agents/sdk/vended-tools/http-request';
11
11
  import { ContextOffloader } from '@strands-agents/sdk/vended-plugins/context-offloader';
@@ -15,6 +15,7 @@ import { compactConversation, countConversationTokens, createCompactionManager,
15
15
  import { DiagnosticsLog } from './diagnostics.js';
16
16
  import { BackgroundDelegationObserver, backgroundDelegationConfig, liveBackgroundDelegationRefusal, MANAGE_BACKGROUND_TASK_TOOL_NAME, } from './background-delegation.js';
17
17
  import { installMaxTokensRecovery } from './max-tokens-recovery.js';
18
+ import { installStreamIdleWatchdog } from './stream-idle.js';
18
19
  import { installModelCallBudget } from './model-call-budget.js';
19
20
  import { installModelRetry } from './model-retry.js';
20
21
  import { loadAgentDefinitions } from '../agents/loader.js';
@@ -24,12 +25,13 @@ import { SUBAGENT_TOOL_NAME, SubagentTool } from '../agents/subagent-tool.js';
24
25
  import { WORKFLOW_TOOL_NAME, WorkflowTool } from '../agents/workflow-tool.js';
25
26
  import { expandCustomCommand, loadCustomCommands, } from '../commands/custom-commands.js';
26
27
  import { parseInitCommand } from '../commands/init-command.js';
28
+ import { parseReviewCommand } from '../commands/review-command.js';
27
29
  import { parseWorkflowCommand } from '../commands/workflow-command.js';
28
30
  import { appendAllowRule, applyThinkingEffort, createModelFromConfig, loadConfig, loadProjectPolicy, permissionRulesPath, removeAllowRules, saveEnabledModel, saveThinkingEffort, withModelChoice, } from '../config.js';
29
31
  import { BackgroundBashManager, createBackgroundBashTool, createForegroundBashTool, } from '../tools/background-bash.js';
30
32
  import { FILE_EDITOR_DESCRIPTION, SerializedFileEditorTool } from '../tools/file-editor-serial.js';
31
33
  import { createImageViewerTool, normalizeRestoredImages } from '../tools/image-viewer.js';
32
- import { scrubShellEnv } from '../tools/shell-env.js';
34
+ import { scrubShellEnv, withDarwinMarker } from '../tools/shell-env.js';
33
35
  import { createUpdatePlanTool } from '../tools/update-plan.js';
34
36
  import { webFetch } from '../tools/web-fetch.js';
35
37
  import { LifecycleHookRunner, lifecycleHooksFromConfig, } from '../hooks/lifecycle-hooks.js';
@@ -43,6 +45,8 @@ import { orderOfficialSkillsPrompt } from '../skills/prompt.js';
43
45
  import { runMemoryCommand } from '../memory/command.js';
44
46
  import { MemoryToolController } from '../memory/controller.js';
45
47
  import { createMemoryTools } from '../memory/tools.js';
48
+ import { CloudMemory } from '../agentcore/controller.js';
49
+ import { createCloudMemoryTools } from '../agentcore/tools.js';
46
50
  import { recordStream } from '../trajectory/stream.js';
47
51
  import { TrajectoryRecorder, } from '../trajectory/writer.js';
48
52
  import { DARWIN_VERSION } from '../version.js';
@@ -58,6 +62,7 @@ import { setSdkVerboseSink } from './sdk-logging.js';
58
62
  import { loadSystemPrompt } from './system-prompt.js';
59
63
  import { applyWorkingContext, buildWorkingContext } from './working-context.js';
60
64
  import { planThinking } from './thinking.js';
65
+ import { projectLayersArmed, workspaceTrustReport, } from './workspace-trust.js';
61
66
  import { MAX_REWIND_CHECKPOINTS, appendRewindCheckpoint, newestRewindCheckpoints, readRewindCatalogue, rewindPromptEligible, } from './rewind.js';
62
67
  import { deltaUsage, requestInputTokens, startCallSpend, startTurnSpend, sumUsage, usageBuckets } from './usage.js';
63
68
  import { emptyCallStats, readCallUsage, recordCompletedCall, } from './call-stats.js';
@@ -115,6 +120,8 @@ const PARENT_ONLY_TOOL_NAMES = new Set([
115
120
  'retrieve_offloaded_content',
116
121
  httpRequest.name,
117
122
  webFetch.name,
123
+ 'episodic_recall',
124
+ 'reflection_recall',
118
125
  // Registered by the SDK's backgroundTasks plugin during initialize(); a child has
119
126
  // no plugin, so the tool would list nothing and could not cancel anything.
120
127
  MANAGE_BACKGROUND_TASK_TOOL_NAME,
@@ -130,6 +137,7 @@ export class AgentRuntime {
130
137
  workflows;
131
138
  subagentDispatches;
132
139
  backgroundDelegation;
140
+ terminalDelivery;
133
141
  modelRetry;
134
142
  backgroundBash;
135
143
  gate;
@@ -141,6 +149,8 @@ export class AgentRuntime {
141
149
  trajectory;
142
150
  diagnosticsLog;
143
151
  memoryController;
152
+ cloudMemory;
153
+ lease;
144
154
  info;
145
155
  createOptions;
146
156
  /**
@@ -205,13 +215,6 @@ export class AgentRuntime {
205
215
  cacheMisses;
206
216
  /** Latched on the first tracker failure — its own latch, so it cannot break the others. */
207
217
  cacheMissesBroken = false;
208
- /**
209
- * Which background jobs' terminal states completed turns already carried to the
210
- * model through `wait`/`status` results (SER-069): the interactive drain asks it
211
- * before sending a wake, so a job the model already saw finish never starts a
212
- * duplicate turn. Session-scoped like the anchor; a `/clear` successor starts empty.
213
- */
214
- terminalDelivery = new TerminalDeliveryLedger();
215
218
  /** Serializes the bounded list/save/list critical section across concurrent callers. */
216
219
  rewindCaptureTail = Promise.resolve();
217
220
  /**
@@ -228,6 +231,14 @@ export class AgentRuntime {
228
231
  mcp, skills, commands, subagents, workflows, subagentDispatches,
229
232
  /** Forwards background runs' `AfterToolCallEvent`s into `send()`'s stream (SER-064). */
230
233
  backgroundDelegation,
234
+ /**
235
+ * Which background jobs' terminal states completed turns already carried to the
236
+ * model through `wait`/`status` results (SER-069): the interactive drain asks it
237
+ * before sending a wake, so a job the model already saw finish never starts a
238
+ * duplicate turn. Session-scoped like the anchor; a `/clear` successor starts empty.
239
+ * Built in `create()` because its pre-offload hook is installed on the Agent (SRF-036).
240
+ */
241
+ terminalDelivery,
231
242
  /** The parent Agent's own retry state; children keep theirs behind their installer (SER-066). */
232
243
  modelRetry, backgroundBash, gate,
233
244
  /** Undefined when neither native lifecycle event is configured. */
@@ -241,7 +252,13 @@ export class AgentRuntime {
241
252
  /** Undefined unless `diagnostics: true` asked for the log. Off is the default. */
242
253
  diagnosticsLog,
243
254
  /** Undefined only when effective config disables derived project context. */
244
- memoryController, info,
255
+ memoryController, cloudMemory,
256
+ /**
257
+ * This process's hold on `info.sessionId` (SER-091). Released by {@link shutdown}
258
+ * and by {@link retire} — the `/clear` and `/rewind` successor takes its own lease
259
+ * on its own id through `create()` — and only while the file still names this pid.
260
+ */
261
+ lease, info,
245
262
  /**
246
263
  * What this runtime was created with, so {@link startNewSession} can assemble its
247
264
  * successor through the same factory instead of a second, drifting assembly.
@@ -257,6 +274,7 @@ export class AgentRuntime {
257
274
  this.workflows = workflows;
258
275
  this.subagentDispatches = subagentDispatches;
259
276
  this.backgroundDelegation = backgroundDelegation;
277
+ this.terminalDelivery = terminalDelivery;
260
278
  this.modelRetry = modelRetry;
261
279
  this.backgroundBash = backgroundBash;
262
280
  this.gate = gate;
@@ -268,22 +286,24 @@ export class AgentRuntime {
268
286
  this.trajectory = trajectory;
269
287
  this.diagnosticsLog = diagnosticsLog;
270
288
  this.memoryController = memoryController;
289
+ this.cloudMemory = cloudMemory;
290
+ this.lease = lease;
271
291
  this.info = info;
272
292
  this.createOptions = createOptions;
273
293
  this.thinkingPlan = info.thinking;
274
294
  this.liveConfig = info.config;
275
295
  this.promptCachePlan = info.promptCache;
276
296
  this.cacheMisses = new CacheMissTracker(() => promptCacheTtlMs(this.promptCachePlan.ttl), info.resumed);
277
- // Fire and forget: a mapped id costs one file read, an unmapped one starts the
278
- // single bounded background fetch. Nothing awaits it — not startup, not the
279
- // first turn — and it cannot reject, so it cannot become a startup failure.
297
+ // Fire and forget: priced/fresh-negative ids cost one file read; missing or
298
+ // expired-negative ids start one bounded fetch. Startup and the first turn do
299
+ // not await it; it cannot reject or become a startup failure.
280
300
  void this.modelPrices.ensure(this.liveConfig);
281
301
  }
282
302
  /**
283
303
  * Releases startup-owned observers and external clients when construction fails.
284
304
  * Successful creation transfers the same resources to `shutdown()` instead.
285
305
  */
286
- static async unwindCreate(diagnosticsLog, mcpClients = [], backgroundBash, memoryController, lifecycleHooks, codexHooks) {
306
+ static async unwindCreate(diagnosticsLog, mcpClients = [], backgroundBash, memoryController, lifecycleHooks, codexHooks, cloudMemory) {
287
307
  if (diagnosticsLog !== undefined)
288
308
  setSdkVerboseSink(undefined);
289
309
  await Promise.allSettled([
@@ -293,6 +313,7 @@ export class AgentRuntime {
293
313
  memoryController?.close() ?? Promise.resolve(),
294
314
  lifecycleHooks?.close() ?? Promise.resolve(),
295
315
  codexHooks?.close() ?? Promise.resolve(),
316
+ cloudMemory?.close() ?? Promise.resolve(),
296
317
  ]);
297
318
  }
298
319
  static async create(options) {
@@ -300,11 +321,25 @@ export class AgentRuntime {
300
321
  // selector must fail locally without initializing anything billable.
301
322
  const session = await resolveSession(options.projectRoot, options.session, AGENT_ID);
302
323
  options.onSessionResolved?.(session.sessionId);
303
- // A successor created by `/clear` takes the predecessor's *live* config instead of
304
- // re-reading the file, so a `/model` or `/effort` change made this session survives
305
- // the switch (see InheritedRuntimeResources).
306
- const config = options.inherit?.config ?? (await loadConfig(options.projectRoot));
307
- const policy = await loadProjectPolicy(options.projectRoot);
324
+ let config;
325
+ let policy;
326
+ // SER-090: the driver's trust decision decides whether the checkout's own hook
327
+ // files, MCP servers and legacy rule fallback are read at all. Held layers are
328
+ // skipped by the loaders, not failed — the user declined them.
329
+ const projectLayers = options.workspaceTrust === undefined || projectLayersArmed(options.workspaceTrust) ? 'armed' : 'held';
330
+ try {
331
+ // A successor created by `/clear` takes the predecessor's *live* config instead of
332
+ // re-reading the file, so a `/model` or `/effort` change made this session survives
333
+ // the switch (see InheritedRuntimeResources).
334
+ config = options.inherit?.config ?? (await loadConfig(options.projectRoot));
335
+ policy = await loadProjectPolicy(options.projectRoot, { projectLayers });
336
+ }
337
+ catch (error) {
338
+ // SER-091: a `ConfigError` here ends the process; the lease must not outlive the
339
+ // session it was taken for, or the next launch would report a takeover.
340
+ await session.lease.release();
341
+ throw error;
342
+ }
308
343
  // Built here, before the model, the MCP clients and the skills plugin, because all
309
344
  // three log at `debug` while they start up (MCP tool renames, skill discovery) and
310
345
  // a diagnostics log that begins after startup cannot answer a question about
@@ -328,6 +363,7 @@ export class AgentRuntime {
328
363
  let startupMcpClients = [];
329
364
  let startupBackgroundBash;
330
365
  let startupMemoryController;
366
+ let startupCloudMemory;
331
367
  let startupLifecycleHooks;
332
368
  let startupCodexHooks;
333
369
  // Keep assembly in one function so one catch owns every resource acquired
@@ -344,6 +380,7 @@ export class AgentRuntime {
344
380
  : `${basePrompt.prompt}\n\n${options.systemPromptSuffix}`;
345
381
  const mcp = options.inherit?.mcp ?? await loadMcpClients(options.projectRoot, {
346
382
  quietStdioStderr: options.quietMcpStderr === true,
383
+ projectLayer: projectLayers,
347
384
  });
348
385
  // Inherited resources belong to a predecessor that is still alive: if this
349
386
  // assembly fails, the unwind must not release them out from under it.
@@ -410,17 +447,20 @@ export class AgentRuntime {
410
447
  // reuse `foregroundBash` and the manager through `childBash`), get this map.
411
448
  // Names only are kept for `/status` and the startup notice; values never leave
412
449
  // `shellEnv.env`. User `!` commands, hooks and MCP servers are not routed here.
450
+ // SER-094: the spawned shells additionally carry `DARWIN=1` (a preset `DARWIN`
451
+ // wins) — added after the scrub so the marker is never a withheld name.
413
452
  const shellPassthrough = config.shellEnv?.passthrough ?? [];
414
453
  const shellEnv = scrubShellEnv(process.env, shellPassthrough);
415
- const foregroundBash = createForegroundBashTool(options.projectRoot, shellEnv.env);
454
+ const spawnEnv = withDarwinMarker(shellEnv.env);
455
+ const foregroundBash = createForegroundBashTool(options.projectRoot, spawnEnv);
416
456
  // The parent's wording states the runtime truth: only a driver that drains SER-069
417
457
  // task wakes, with the config key on, may tell the model that ending the turn is
418
458
  // followed by a `<task-notification>` turn. Children get the same manager and
419
459
  // foreground tool behind the no-wake wording (`childBash` below): a child's job
420
460
  // wakes the parent TUI, never the child.
421
461
  const completionWakes = options.backgroundCompletionWakes === true && config.backgroundTaskWake !== false;
422
- const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes, env: shellEnv.env });
423
- const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash, { env: shellEnv.env }) : bash;
462
+ const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes, env: spawnEnv });
463
+ const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash, { env: spawnEnv }) : bash;
424
464
  const imageViewer = createImageViewerTool(options.projectRoot);
425
465
  const conversationManager = new SummarizingConversationManager({
426
466
  summaryRatio: config.summaryRatio,
@@ -454,6 +494,8 @@ export class AgentRuntime {
454
494
  : undefined;
455
495
  const memoryController = config.memory === true ? new MemoryToolController(options.projectRoot, config.memoryHorizonDays ?? 28) : undefined;
456
496
  startupMemoryController = memoryController;
497
+ const cloudMemory = config.agentCoreMemory === undefined ? undefined : new CloudMemory(config.agentCoreMemory, options.projectRoot, session.sessionId);
498
+ startupCloudMemory = cloudMemory;
457
499
  // The fileEditor is the SDK vended tool — `makeFileEditor({ description })`, the
458
500
  // same factory as the singleton with the SDK's default text plus the SRF-032
459
501
  // payload bound — behind a same-path ordering wrapper (SRF-020): substituted here
@@ -504,9 +546,26 @@ export class AgentRuntime {
504
546
  // Darwin's own hook + middleware below keep the same schedule (SER-066).
505
547
  retryStrategy: null,
506
548
  });
549
+ if (cloudMemory !== undefined) {
550
+ agent.addHook(BeforeToolsEvent, event => cloudMemory.uploadObserver?.batch(event), { order: HookOrder.SDK_LAST });
551
+ agent.addHook(BeforeToolCallEvent, event => cloudMemory.uploadObserver?.before(event), { order: HookOrder.SDK_LAST });
552
+ // Pre-after-hook execution evidence, not necessarily final model-visible output.
553
+ agent.addHook(AfterToolCallEvent, event => cloudMemory.uploadObserver?.after(event), { order: HookOrder.SDK_FIRST });
554
+ // Batch cancellation, executor failure and background acknowledgement may
555
+ // have no AfterToolCallEvent. Never overwrite an original snapshot.
556
+ agent.addHook(ToolResultEvent, event => cloudMemory.uploadObserver?.fallback(event), { order: HookOrder.SDK_LAST });
557
+ }
558
+ // SRF-036: one read-only SDK_FIRST AfterToolCallEvent hook hands the ledger the
559
+ // original `bash` result before the ContextOffloader's default-order hook can
560
+ // replace it with a preview; `send()`'s stream-side `observe` resolves it.
561
+ // Parent only: children never construct a ledger.
562
+ const terminalDelivery = new TerminalDeliveryLedger();
563
+ terminalDelivery.install(agent);
507
564
  toolForName = (name) => agent.tools.find((candidate) => candidate.name === name);
508
565
  installMaxTokensRecovery(agent);
509
566
  const modelRetry = installModelRetry(agent);
567
+ // Registered inside retry: deliberate backoff is never stream inactivity.
568
+ installStreamIdleWatchdog(agent, config.streamIdleTimeoutSeconds);
510
569
  backgroundDelegation.install(agent);
511
570
  // The constructor does not initialize; the SDK defers it to the first
512
571
  // invocation. Session restore runs on InitializedEvent, MCP tools are
@@ -575,6 +634,9 @@ export class AgentRuntime {
575
634
  agent.toolRegistry.add(createUpdatePlanTool());
576
635
  if (memoryController !== undefined)
577
636
  agent.toolRegistry.add(createMemoryTools(memoryController));
637
+ if (cloudMemory !== undefined) {
638
+ agent.toolRegistry.add(createCloudMemoryTools(cloudMemory));
639
+ }
578
640
  // Children build their models through the same factory seam as the parent: in
579
641
  // production it *is* `createModelFromConfig`; offline suites can script a child
580
642
  // (`spike/verify-background-delegation.ts`) without a provider.
@@ -615,8 +677,10 @@ export class AgentRuntime {
615
677
  // session overwrites `systemPrompt` with the snapshot's copy, so composing it
616
678
  // earlier would leave a resumed run advertising the previous run's date and
617
679
  // directory listing. Applied last, it is also the only fragment a resumed
618
- // prompt can still be corrected by.
619
- const workingContext = await buildWorkingContext(options.projectRoot);
680
+ // prompt can still be corrected by. The registry is complete here — MCP
681
+ // discovery ran inside initialize() and every parent-only tool is added above —
682
+ // so the block can name the tools this run really has.
683
+ const workingContext = await buildWorkingContext(options.projectRoot, new Date(), { toolNames: agent.tools.map((tool) => tool.name) });
620
684
  if (!applyWorkingContext(agent, workingContext.fragment)) {
621
685
  throw new Error('Could not refresh working context on the restored system prompt.');
622
686
  }
@@ -666,16 +730,20 @@ export class AgentRuntime {
666
730
  }),
667
731
  },
668
732
  ...runtimeRecorderOverrides,
669
- ...(memoryController === undefined ? {} : { onTurnSettled: (settlement) => memoryController.settle(settlement) }),
733
+ ...((memoryController === undefined && cloudMemory === undefined) ? {} : { onTurnSettled: (settlement) => {
734
+ memoryController?.settle(settlement);
735
+ cloudMemory?.settle(settlement);
736
+ } }),
670
737
  });
671
738
  trajectoryAudit = trajectory;
672
739
  await trajectory?.open();
673
- const runtime = new AgentRuntime(agent, model, options.projectRoot, mcp, skills, commands, subagents, workflows, subagentDispatches, backgroundDelegation, modelRetry, backgroundBash, gate, lifecycleHooks, policy.toolHookLayers, codexHooks, sessionManager, config.preserveRecentMessages, trajectory, diagnosticsLog, memoryController, {
740
+ const runtime = new AgentRuntime(agent, model, options.projectRoot, mcp, skills, commands, subagents, workflows, subagentDispatches, backgroundDelegation, terminalDelivery, modelRetry, backgroundBash, gate, lifecycleHooks, policy.toolHookLayers, codexHooks, sessionManager, config.preserveRecentMessages, trajectory, diagnosticsLog, memoryController, cloudMemory, session.lease, {
674
741
  config,
675
742
  projectRoot: options.projectRoot,
676
743
  permissionMode,
677
744
  sessionId: session.sessionId,
678
745
  resumed: session.restoreRequested && agent.messages.length > 0,
746
+ ...(session.leaseNotice === undefined ? {} : { leaseNotice: session.leaseNotice }),
679
747
  skillNames: skills.skills.map((skill) => skill.name),
680
748
  skillProblems: skills.problems.map((problem) => ({ ...problem })),
681
749
  commandNames: commands.commands.map((command) => command.name),
@@ -712,6 +780,7 @@ export class AgentRuntime {
712
780
  shadowed: [...notice.shadowed],
713
781
  })),
714
782
  shellEnv: { withheld: [...shellEnv.withheld], passthrough: [...shellPassthrough] },
783
+ workspaceTrust: workspaceTrustReport(options.workspaceTrust),
715
784
  mcpIgnoredConfigPath: mcp.ignoredConfigPath,
716
785
  mcpServerCount: mcp.clients.length,
717
786
  toolNames: agent.tools.map((tool) => tool.name).sort(),
@@ -729,7 +798,8 @@ export class AgentRuntime {
729
798
  return runtime;
730
799
  };
731
800
  return assemble().catch(async (error) => {
732
- await AgentRuntime.unwindCreate(diagnosticsLog, startupMcpClients, startupBackgroundBash, startupMemoryController, startupLifecycleHooks, startupCodexHooks);
801
+ await AgentRuntime.unwindCreate(diagnosticsLog, startupMcpClients, startupBackgroundBash, startupMemoryController, startupLifecycleHooks, startupCodexHooks, startupCloudMemory);
802
+ await session.lease.release();
733
803
  throw error;
734
804
  });
735
805
  }
@@ -777,6 +847,7 @@ export class AgentRuntime {
777
847
  if (submitted !== undefined && !submitted.allowed) {
778
848
  throw new Error(submitted.reason ?? 'UserPromptSubmit hook blocked this prompt.');
779
849
  }
850
+ const cloudGeneration = await this.prepareCloudPreferences();
780
851
  const modelInput = injectCodexContext(input, submitted?.context);
781
852
  let checkpointId;
782
853
  // A text-only checkpoint cannot truthfully reproduce a multimodal boundary.
@@ -790,6 +861,9 @@ export class AgentRuntime {
790
861
  // memory sealing and terminal delivery keep meaning `endTurn`.
791
862
  let refused = false;
792
863
  let sealed = false;
864
+ let naturallyCompleted = false;
865
+ let uploadTurn;
866
+ let streamStarted = false;
793
867
  try {
794
868
  // A multimodal turn's durable text is the literal submitted prompt. Expanded
795
869
  // command text and held shell reports still reach the model, but image bytes
@@ -804,6 +878,10 @@ export class AgentRuntime {
804
878
  // actually submitted. Drivers pass that raw text as the second argument. A
805
879
  // session-originated wake has no user text to quote from at all.
806
880
  this.memoryController?.openTurn(recording?.turn, origin === undefined ? userInput : '');
881
+ if (recording !== undefined && this.cloudMemory?.uploadObserver !== undefined) {
882
+ uploadTurn = recording.turn;
883
+ this.cloudMemory.begin(recording.turn, origin === undefined ? userInput : '');
884
+ }
807
885
  // The current input is the one exception to fire-and-forget recording: make it
808
886
  // readable to offline observers before Agent.stream() can invoke a provider or
809
887
  // tool. The recorder owns the bound and resolves on write failure/timeout, so
@@ -819,8 +897,14 @@ export class AgentRuntime {
819
897
  // next SDK event, so the recorder and every driver see one ordinary
820
898
  // before/after pair for a delegation the model routed to the background.
821
899
  const invocation = image === undefined ? modelInput : [new TextBlock(modelInput), image];
900
+ this.checkCloudPreparation(cloudGeneration);
901
+ streamStarted = true;
822
902
  const stream = this.backgroundDelegation.observe(this.agent.stream(invocation));
823
903
  for await (const event of recordStream(stream, recording)) {
904
+ if (event.type === 'afterToolCallEvent')
905
+ this.cloudMemory?.uploadObserver?.forwarded(event);
906
+ if (event.type !== 'beforeToolCallEvent' && event.type !== 'afterToolCallEvent')
907
+ this.cloudMemory?.uploadObserver?.internal();
824
908
  if (event.type === 'agentResultEvent' && event.result.stopReason === 'endTurn')
825
909
  completed = true;
826
910
  if (event.type === 'agentResultEvent' && isRefusalStop(event.result.stopReason))
@@ -841,17 +925,24 @@ export class AgentRuntime {
841
925
  snapshotId: checkpointId,
842
926
  prompt: input,
843
927
  completedAt: new Date().toISOString(),
928
+ ...(recording === undefined ? {} : { trajectoryTurn: recording.turn }),
844
929
  });
845
930
  if (catalogue.problem !== undefined) {
846
931
  this.diagnosticsLog?.notice(`rewind checkpoint not catalogued: ${catalogue.problem}`, 'warn');
847
932
  }
848
933
  }
934
+ naturallyCompleted = true;
849
935
  }
850
936
  finally {
937
+ if (uploadTurn !== undefined)
938
+ this.cloudMemory?.sealTurn(uploadTurn, naturallyCompleted && completed && cloudGeneration === this.cloudMemory.cancelGeneration);
851
939
  // Seeing an endTurn event is not enough when the consumer abandons this
852
940
  // generator before natural completion: only the natural path above seals.
853
941
  if (!sealed)
854
942
  this.memoryController?.discard();
943
+ this.cloudMemory?.uploadObserver?.end();
944
+ if (uploadTurn !== undefined && (!streamStarted || this.trajectory?.status.active === false))
945
+ this.cloudMemory?.discardTurn(uploadTurn);
855
946
  // Only a turn that ran to `endTurn` commits what its `wait`/`status` results
856
947
  // delivered; an abandoned or failed turn forgets them, so the wake still fires.
857
948
  this.terminalDelivery.closeTurn(sealed && completed);
@@ -934,10 +1025,49 @@ export class AgentRuntime {
934
1025
  get memoryStatus() {
935
1026
  return this.memoryController?.status;
936
1027
  }
937
- /**
938
- * Runs the user-only local `/memory` command and refreshes the verified Darwin-owned
939
- * prompt block before a successful mutation returns. No Agent invocation is made.
940
- */
1028
+ /** Cloud status is a projection, never an implicit retrieval. */
1029
+ get cloudMemoryStatus() { return this.cloudMemory?.status() ?? 'AgentCore: disabled (local project memory unchanged)'; }
1030
+ checkCloudPreparation(generation) {
1031
+ if (generation !== this.cloudMemory?.cancelGeneration)
1032
+ throw new Error('AgentCore preparation cancelled before model invocation');
1033
+ }
1034
+ async refreshCloudPolicy() {
1035
+ if (this.cloudMemory === undefined)
1036
+ return;
1037
+ await this.cloudMemory.refreshPolicy();
1038
+ this.liveConfig = { ...this.liveConfig, agentCoreMemory: this.cloudMemory.config };
1039
+ }
1040
+ async prepareCloudPreferences() {
1041
+ if (this.cloudMemory === undefined)
1042
+ return;
1043
+ const generation = this.cloudMemory.cancelGeneration;
1044
+ await this.refreshCloudPolicy();
1045
+ await this.cloudMemory.startup(); // One cloud fetch per runtime; local revocations are checked on every request.
1046
+ this.checkCloudPreparation(generation);
1047
+ await this.applyCloudPreferences();
1048
+ this.checkCloudPreparation(generation); // Includes working-context and local approval reads.
1049
+ return generation;
1050
+ }
1051
+ async manageCloudMemory(input) {
1052
+ if (this.cloudMemory === undefined)
1053
+ return this.cloudMemoryStatus;
1054
+ const result = await this.cloudMemory.command(input, 'user');
1055
+ this.liveConfig = { ...this.liveConfig, agentCoreMemory: this.cloudMemory.config };
1056
+ await this.applyCloudPreferences();
1057
+ return result;
1058
+ }
1059
+ async applyCloudPreferences() {
1060
+ if (this.cloudMemory === undefined)
1061
+ return;
1062
+ const context = await buildWorkingContext(this.projectRoot, new Date(), { toolNames: this.agent.tools.map((tool) => tool.name) });
1063
+ const preferences = await this.cloudMemory.context();
1064
+ // Callback replacement preserves literal $&, $`, and $' in reviewed data.
1065
+ if (!applyWorkingContext(this.agent, context.fragment.replace('</working-context>', () => `${preferences}\n</working-context>`))) {
1066
+ throw new Error('AgentCore working-context refresh refused; model invocation blocked');
1067
+ }
1068
+ if (this.promptCache.parts.includes('system prompt'))
1069
+ applySystemPromptCachePoint(this.agent, this.promptCache);
1070
+ }
941
1071
  async manageMemory(input) {
942
1072
  if (this.liveConfig.memory !== true) {
943
1073
  return { changed: false, text: 'project memory is off — remove memory: false if set, and enable trajectory recording in ~/.darwin/config.json' };
@@ -967,6 +1097,8 @@ export class AgentRuntime {
967
1097
  const pre = await this.codexHooks?.preCompact('manual');
968
1098
  if (pre !== undefined && !pre.allowed)
969
1099
  throw new Error(pre.reason ?? 'PreCompact hook blocked compaction.');
1100
+ const cloudGeneration = await this.prepareCloudPreferences();
1101
+ this.checkCloudPreparation(cloudGeneration);
970
1102
  try {
971
1103
  const result = await compactConversation({
972
1104
  agent: this.agent,
@@ -1088,7 +1220,16 @@ export class AgentRuntime {
1088
1220
  */
1089
1221
  async saveAllowRule(rule) {
1090
1222
  this.gate.addAllowRule(rule);
1091
- await appendAllowRule(this.projectRoot, rule);
1223
+ await appendAllowRule(this.projectRoot, rule, this.projectLayerOptions());
1224
+ }
1225
+ /**
1226
+ * The `loadProjectPolicy` layer option this runtime was created with (SER-090), so
1227
+ * the two rule writers below promote legacy rules only from a layer that was in
1228
+ * force — an untrusted project's committed `.darwin/config.json` never reaches the
1229
+ * user-owned file through an "always allow" answer.
1230
+ */
1231
+ projectLayerOptions() {
1232
+ return { projectLayers: this.info.workspaceTrust.state === 'trusted' ? 'armed' : 'held' };
1092
1233
  }
1093
1234
  /**
1094
1235
  * The live allow-rules with their provenance — config-loaded vs granted this
@@ -1134,7 +1275,9 @@ export class AgentRuntime {
1134
1275
  */
1135
1276
  revokeAllowRules(rules) {
1136
1277
  const removed = rules.filter((rule) => this.gate.removeAllowRule(rule));
1137
- const saved = removed.length === 0 ? Promise.resolve() : removeAllowRules(this.projectRoot, removed);
1278
+ const saved = removed.length === 0
1279
+ ? Promise.resolve()
1280
+ : removeAllowRules(this.projectRoot, removed, this.projectLayerOptions());
1138
1281
  return { removed, saved };
1139
1282
  }
1140
1283
  /**
@@ -1254,15 +1397,22 @@ export class AgentRuntime {
1254
1397
  * instead of rebuilding the agent — which is the whole point: the history, the
1255
1398
  * session file, the tools and the permission gate all survive. Both switch
1256
1399
  * directions were measured to carry a conversation containing tool calls
1257
- * (`spike/probe-model-switch.ts`); a Claude reasoning block in the history is
1258
- * dropped with a warning by the OpenAI adapter rather than rejected, which is
1259
- * why the TUI routes SDK warnings into notices.
1400
+ * (`spike/probe-model-switch.ts`). Reasoning crosses a switch only where it is
1401
+ * provably the target's own (SER-101, the pinned SDK patch): the OpenAI Responses
1402
+ * adapter tags what it captures with the producing model id and replays only a
1403
+ * tag matching the live model; every foreign or untagged block — a Claude one, or
1404
+ * another Responses model's — is still dropped with the SDK warning, which is why
1405
+ * the TUI routes SDK warnings into notices. Converse, Anthropic and Chat
1406
+ * Completions never send a tagged block, and Converse drops signature-less
1407
+ * (Kimi) reasoning for a Claude id, which Claude would otherwise reject
1408
+ * (`spike/verify-responses-reasoning-live.ts` measures every hand-off).
1260
1409
  *
1261
1410
  * The thinking and cache plans are recomputed rather than carried over: effort
1262
1411
  * clamping is per-model and caching is per-provider, so the old plans would
1263
1412
  * describe a model that is no longer there.
1264
1413
  */
1265
1414
  async changeModel(target) {
1415
+ await this.refreshCloudPolicy();
1266
1416
  const next = withModelChoice(this.liveConfig, target);
1267
1417
  // Built before anything is mutated: a failure here (a missing peer dependency,
1268
1418
  // a bad region) must leave the session on the model it was already using. Same
@@ -1280,6 +1430,7 @@ export class AgentRuntime {
1280
1430
  if (promptCachePlan.parts.includes('system prompt') !== cacheUpdated) {
1281
1431
  throw new Error('Could not update the final cache point on the assembled system prompt.');
1282
1432
  }
1433
+ const from = { provider: this.liveConfig.provider, model: this.liveConfig.model };
1283
1434
  this.agent.model = model;
1284
1435
  this.model = model;
1285
1436
  this.liveConfig = next;
@@ -1294,6 +1445,15 @@ export class AgentRuntime {
1294
1445
  this.promptCachePlan = promptCachePlan;
1295
1446
  // A different model keys a different cache: the next call re-reads uncached.
1296
1447
  this.markCacheInvalidated('model');
1448
+ // SRF-038: the swap has happened, so the record says so — `runStarted` keeps
1449
+ // naming the startup model byte for byte. Observer-only (synchronous, no await,
1450
+ // non-throwing); a factory failure or a refused cache shape threw above and never
1451
+ // reaches here, and a failed config save is still a switch that ran.
1452
+ this.trajectory?.recordModelChanged({
1453
+ from,
1454
+ to: { provider: next.provider, model: next.model },
1455
+ thinkingEffort: thinkingPlan.effective,
1456
+ });
1297
1457
  const choice = next.modelChoices.find((entry) => entry.index === target.index);
1298
1458
  return {
1299
1459
  choice,
@@ -1504,6 +1664,13 @@ export class AgentRuntime {
1504
1664
  listBackgroundTasks() {
1505
1665
  return this.backgroundBash.list();
1506
1666
  }
1667
+ /** Live in-memory activity for the TUI; no log reads or tool invocation. */
1668
+ get runningBackgroundTaskCount() {
1669
+ return this.backgroundBash.runningCount;
1670
+ }
1671
+ subscribeToBackgroundTaskActivity(listener) {
1672
+ return this.backgroundBash.subscribeActivity(listener);
1673
+ }
1507
1674
  /** Publishes future terminal task snapshots until the returned closure is called. */
1508
1675
  subscribeToBackgroundTasks(listener) {
1509
1676
  return this.backgroundBash.subscribe(listener);
@@ -1571,6 +1738,7 @@ export class AgentRuntime {
1571
1738
  * ends with `stopReason: 'cancelled'` rather than throwing.
1572
1739
  */
1573
1740
  cancel() {
1741
+ this.cloudMemory?.cancel();
1574
1742
  this.lifecycleHooks?.cancel();
1575
1743
  this.codexHooks?.cancel();
1576
1744
  this.subagents.cancelActive();
@@ -1625,6 +1793,8 @@ export class AgentRuntime {
1625
1793
  */
1626
1794
  async startRewind(checkpoint) {
1627
1795
  this.refuseWhileDelegationsTracked('/rewind');
1796
+ await this.cloudMemory?.stopAutoForSuccessor();
1797
+ await this.refreshCloudPolicy();
1628
1798
  const catalogue = await readRewindCatalogue(this.projectRoot, this.info.sessionId);
1629
1799
  if (catalogue.problem !== undefined)
1630
1800
  throw new Error(catalogue.problem);
@@ -1689,8 +1859,8 @@ export class AgentRuntime {
1689
1859
  * the user the conversation they just set aside. The successor claims the pointer on
1690
1860
  * its first finished turn, through the ordinary path.
1691
1861
  *
1692
- * If assembling the successor fails, this runtime stays fully usable: nothing it owns
1693
- * has been released yet, and the diagnostics tap it installed at startup is put back
1862
+ * If assembling the successor fails, conversation/tools stay usable; predecessor auto
1863
+ * uploads remain conservatively stopped (cloud status states it). The diagnostics tap is put back
1694
1864
  * (the failed successor's unwind clears the process-global sink).
1695
1865
  *
1696
1866
  * Refused while a background delegation is tracked (SER-070): `retire()` would cancel
@@ -1700,6 +1870,8 @@ export class AgentRuntime {
1700
1870
  */
1701
1871
  async startNewSession() {
1702
1872
  this.refuseWhileDelegationsTracked('/clear');
1873
+ await this.cloudMemory?.stopAutoForSuccessor();
1874
+ await this.refreshCloudPolicy();
1703
1875
  let successor;
1704
1876
  try {
1705
1877
  successor = await AgentRuntime.create({
@@ -1753,13 +1925,16 @@ export class AgentRuntime {
1753
1925
  ]);
1754
1926
  // Closing trajectory first publishes the final settlement. The controller then
1755
1927
  // discards unresolved staging and waits only for commits already accepted.
1756
- await Promise.allSettled([Promise.resolve(ownedWork), this.memoryController?.close() ?? Promise.resolve()]);
1928
+ await Promise.allSettled([Promise.resolve(ownedWork), this.memoryController?.close() ?? Promise.resolve(), this.cloudMemory?.close() ?? Promise.resolve()]);
1757
1929
  // SessionEnd is the final advisory boundary: all session-owned work above has
1758
1930
  // settled, while diagnostics remains open to retain a bounded hook problem.
1759
1931
  await Promise.allSettled([
1760
1932
  this.codexHooks?.sessionEnd('other').then(() => this.codexHooks?.close()) ?? Promise.resolve(),
1761
1933
  ]);
1762
1934
  await Promise.allSettled([this.diagnosticsLog?.close() ?? Promise.resolve()]);
1935
+ // SER-091: last, after the trajectory is durable — the successor already holds its
1936
+ // own lease on its own id, so this session is simply no longer open anywhere.
1937
+ await this.lease.release();
1763
1938
  }
1764
1939
  /**
1765
1940
  * Creates one bounded rewind snapshot, serialized so concurrent callers cannot
@@ -1796,13 +1971,14 @@ export class AgentRuntime {
1796
1971
  }
1797
1972
  /**
1798
1973
  * Expands a built-in prompt command, a skill, or a project command into the
1799
- * prompt sent to the model. `/workflow` and `/init` are checked first: built-in
1974
+ * prompt sent to the model. `/workflow`, `/init` and `/review` come first: built-in
1800
1975
  * reservation precedes skills and custom commands, so no extension can
1801
1976
  * shadow them. Bare `/workflow` returns null — the drivers own that local usage
1802
1977
  * notice, and the runtime never fabricates a turn — while bare `/init` is the
1803
- * trigger itself. `/init` decides create-versus-improve from the instructions
1978
+ * trigger itself, as is bare `/review`. `/review` is guidance only, with no mode
1979
+ * change or executor. `/init` decides create-versus-improve from the instructions
1804
1980
  * summary this runtime captured at startup (the header's own data), never from
1805
- * a fresh filesystem read, so every driver — TUI, dev-repl, headless — gets the
1981
+ * a fresh filesystem read, so TUI, dev-repl and both headless drivers get the
1806
1982
  * same branch through this one seam. Skills are checked before
1807
1983
  * custom commands as a defensive backstop to the loader's collision
1808
1984
  * filtering. Unknown slash input remains ordinary user input.
@@ -1819,6 +1995,9 @@ export class AgentRuntime {
1819
1995
  });
1820
1996
  if (init !== null)
1821
1997
  return { kind: 'init', ...init };
1998
+ const review = parseReviewCommand(input);
1999
+ if (review !== null)
2000
+ return { kind: 'review', ...review };
1822
2001
  const skill = await expandSkillCommand(this.skills, input);
1823
2002
  if (skill !== null)
1824
2003
  return { kind: 'skill', ...skill };
@@ -1832,6 +2011,7 @@ export class AgentRuntime {
1832
2011
  * exiting.
1833
2012
  */
1834
2013
  async shutdown(options = {}) {
2014
+ this.cloudMemory?.cancel();
1835
2015
  const results = await Promise.allSettled([
1836
2016
  this.subagents.shutdown(),
1837
2017
  this.workflows.shutdown(),
@@ -1843,7 +2023,7 @@ export class AgentRuntime {
1843
2023
  // unawaited; cleanup only waits for a commit after durable acceptance.
1844
2024
  this.trajectory?.close() ?? Promise.resolve(),
1845
2025
  ]);
1846
- const memoryResults = await Promise.allSettled([this.memoryController?.close() ?? Promise.resolve()]);
2026
+ const memoryResults = await Promise.allSettled([this.memoryController?.close() ?? Promise.resolve(), this.cloudMemory?.close() ?? Promise.resolve()]);
1847
2027
  results.push(...memoryResults);
1848
2028
  // SessionEnd is advisory but ordered after owned work. Keep diagnostics open
1849
2029
  // through it, then detach the process-global SDK tap before closing the file.
@@ -1853,6 +2033,10 @@ export class AgentRuntime {
1853
2033
  if (this.diagnosticsLog !== undefined)
1854
2034
  setSdkVerboseSink(undefined);
1855
2035
  results.push(...await Promise.allSettled([this.diagnosticsLog?.close() ?? Promise.resolve()]));
2036
+ // SER-091: the lease goes last, once every writer above has settled, and only if
2037
+ // the file still names this process. Non-throwing: a lease that stays behind is
2038
+ // stale the moment this pid is gone, and the next launch takes it over.
2039
+ await this.lease.release();
1856
2040
  const failures = results.flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
1857
2041
  if (options.throwOnError === true && failures.length > 0) {
1858
2042
  throw new AggregateError(failures, `${failures.length} runtime cleanup operation(s) failed`);