strands-darwin 0.0.35 → 0.0.36

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 (231) hide show
  1. package/README.md +20 -3
  2. package/README.zh-CN.md +20 -3
  3. package/dist/src/agent/prompt-cache.js +15 -2
  4. package/dist/src/agent/prompt-cache.js.map +1 -1
  5. package/dist/src/agent/rewind.d.ts +2 -0
  6. package/dist/src/agent/rewind.js +4 -1
  7. package/dist/src/agent/rewind.js.map +1 -1
  8. package/dist/src/agent/runtime.d.ts +64 -10
  9. package/dist/src/agent/runtime.js +192 -33
  10. package/dist/src/agent/runtime.js.map +1 -1
  11. package/dist/src/agent/session.d.ts +96 -4
  12. package/dist/src/agent/session.js +249 -9
  13. package/dist/src/agent/session.js.map +1 -1
  14. package/dist/src/agent/stream-idle.d.ts +16 -0
  15. package/dist/src/agent/stream-idle.js +127 -0
  16. package/dist/src/agent/stream-idle.js.map +1 -0
  17. package/dist/src/agent/working-context.d.ts +21 -1
  18. package/dist/src/agent/working-context.js +28 -1
  19. package/dist/src/agent/working-context.js.map +1 -1
  20. package/dist/src/agent/workspace-trust.d.ts +112 -0
  21. package/dist/src/agent/workspace-trust.js +207 -0
  22. package/dist/src/agent/workspace-trust.js.map +1 -0
  23. package/dist/src/agentcore/auto-policy.d.ts +7 -0
  24. package/dist/src/agentcore/auto-policy.js +50 -0
  25. package/dist/src/agentcore/auto-policy.js.map +1 -0
  26. package/dist/src/agentcore/auto-state.d.ts +43 -0
  27. package/dist/src/agentcore/auto-state.js +73 -0
  28. package/dist/src/agentcore/auto-state.js.map +1 -0
  29. package/dist/src/agentcore/cli.d.ts +2 -0
  30. package/dist/src/agentcore/cli.js +38 -0
  31. package/dist/src/agentcore/cli.js.map +1 -0
  32. package/dist/src/agentcore/config.d.ts +48 -0
  33. package/dist/src/agentcore/config.js +44 -0
  34. package/dist/src/agentcore/config.js.map +1 -0
  35. package/dist/src/agentcore/controller.d.ts +105 -0
  36. package/dist/src/agentcore/controller.js +979 -0
  37. package/dist/src/agentcore/controller.js.map +1 -0
  38. package/dist/src/agentcore/projection.d.ts +2 -0
  39. package/dist/src/agentcore/projection.js +8 -0
  40. package/dist/src/agentcore/projection.js.map +1 -0
  41. package/dist/src/agentcore/records.d.ts +41 -0
  42. package/dist/src/agentcore/records.js +149 -0
  43. package/dist/src/agentcore/records.js.map +1 -0
  44. package/dist/src/agentcore/state.d.ts +16 -0
  45. package/dist/src/agentcore/state.js +149 -0
  46. package/dist/src/agentcore/state.js.map +1 -0
  47. package/dist/src/agentcore/tools.d.ts +3 -0
  48. package/dist/src/agentcore/tools.js +11 -0
  49. package/dist/src/agentcore/tools.js.map +1 -0
  50. package/dist/src/agentcore/transport.d.ts +37 -0
  51. package/dist/src/agentcore/transport.js +242 -0
  52. package/dist/src/agentcore/transport.js.map +1 -0
  53. package/dist/src/agentcore/upload-projection.d.ts +208 -0
  54. package/dist/src/agentcore/upload-projection.js +823 -0
  55. package/dist/src/agentcore/upload-projection.js.map +1 -0
  56. package/dist/src/agents/child-recipe.js +4 -1
  57. package/dist/src/agents/child-recipe.js.map +1 -1
  58. package/dist/src/agents/loader.d.ts +12 -0
  59. package/dist/src/agents/loader.js +15 -1
  60. package/dist/src/agents/loader.js.map +1 -1
  61. package/dist/src/agents/subagent-tool.js +2 -4
  62. package/dist/src/agents/subagent-tool.js.map +1 -1
  63. package/dist/src/agents/workflow-tool.js +2 -4
  64. package/dist/src/agents/workflow-tool.js.map +1 -1
  65. package/dist/src/cli-doctor.js +7 -0
  66. package/dist/src/cli-doctor.js.map +1 -1
  67. package/dist/src/cli-import.d.ts +1 -0
  68. package/dist/src/cli-import.js +26 -0
  69. package/dist/src/cli-import.js.map +1 -0
  70. package/dist/src/cli-main.js +60 -10
  71. package/dist/src/cli-main.js.map +1 -1
  72. package/dist/src/cli-permissions.d.ts +2 -0
  73. package/dist/src/cli-permissions.js +20 -0
  74. package/dist/src/cli-permissions.js.map +1 -0
  75. package/dist/src/cli-sessions.js +6 -2
  76. package/dist/src/cli-sessions.js.map +1 -1
  77. package/dist/src/cli-usage.d.ts +9 -1
  78. package/dist/src/cli-usage.js +13 -0
  79. package/dist/src/cli-usage.js.map +1 -1
  80. package/dist/src/cli.js +19 -2
  81. package/dist/src/cli.js.map +1 -1
  82. package/dist/src/commands/custom-commands.d.ts +1 -1
  83. package/dist/src/commands/custom-commands.js +14 -6
  84. package/dist/src/commands/custom-commands.js.map +1 -1
  85. package/dist/src/commands/review-command.d.ts +10 -0
  86. package/dist/src/commands/review-command.js +28 -0
  87. package/dist/src/commands/review-command.js.map +1 -0
  88. package/dist/src/config-file.d.ts +9 -0
  89. package/dist/src/config-file.js +82 -0
  90. package/dist/src/config-file.js.map +1 -0
  91. package/dist/src/config.d.ts +66 -5
  92. package/dist/src/config.js +126 -42
  93. package/dist/src/config.js.map +1 -1
  94. package/dist/src/dev-repl.js +17 -1
  95. package/dist/src/dev-repl.js.map +1 -1
  96. package/dist/src/headless-protocol.d.ts +24 -1
  97. package/dist/src/headless-protocol.js +18 -0
  98. package/dist/src/headless-protocol.js.map +1 -1
  99. package/dist/src/headless-runner.d.ts +8 -0
  100. package/dist/src/headless-runner.js +37 -1
  101. package/dist/src/headless-runner.js.map +1 -1
  102. package/dist/src/hooks/hook-process.js +7 -2
  103. package/dist/src/hooks/hook-process.js.map +1 -1
  104. package/dist/src/hooks/lifecycle-hooks.js +3 -1
  105. package/dist/src/hooks/lifecycle-hooks.js.map +1 -1
  106. package/dist/src/hooks/tool-hooks.js +3 -1
  107. package/dist/src/hooks/tool-hooks.js.map +1 -1
  108. package/dist/src/import-claude-files.d.ts +28 -0
  109. package/dist/src/import-claude-files.js +227 -0
  110. package/dist/src/import-claude-files.js.map +1 -0
  111. package/dist/src/import-claude-snippets.d.ts +2 -0
  112. package/dist/src/import-claude-snippets.js +105 -0
  113. package/dist/src/import-claude-snippets.js.map +1 -0
  114. package/dist/src/import-claude.d.ts +13 -0
  115. package/dist/src/import-claude.js +287 -0
  116. package/dist/src/import-claude.js.map +1 -0
  117. package/dist/src/mcp/registry.d.ts +57 -1
  118. package/dist/src/mcp/registry.js +78 -6
  119. package/dist/src/mcp/registry.js.map +1 -1
  120. package/dist/src/memory/command.d.ts +1 -1
  121. package/dist/src/memory/command.js +89 -4
  122. package/dist/src/memory/command.js.map +1 -1
  123. package/dist/src/memory/controller.d.ts +32 -0
  124. package/dist/src/memory/controller.js +39 -3
  125. package/dist/src/memory/controller.js.map +1 -1
  126. package/dist/src/memory/state.d.ts +6 -0
  127. package/dist/src/memory/state.js +6 -1
  128. package/dist/src/memory/state.js.map +1 -1
  129. package/dist/src/memory/store.d.ts +13 -0
  130. package/dist/src/memory/store.js +38 -2
  131. package/dist/src/memory/store.js.map +1 -1
  132. package/dist/src/memory/tools.d.ts +7 -0
  133. package/dist/src/memory/tools.js +12 -1
  134. package/dist/src/memory/tools.js.map +1 -1
  135. package/dist/src/paths.js +3 -0
  136. package/dist/src/paths.js.map +1 -1
  137. package/dist/src/permissions-test.d.ts +18 -0
  138. package/dist/src/permissions-test.js +207 -0
  139. package/dist/src/permissions-test.js.map +1 -0
  140. package/dist/src/pricing/model-prices.d.ts +8 -5
  141. package/dist/src/pricing/model-prices.js +30 -15
  142. package/dist/src/pricing/model-prices.js.map +1 -1
  143. package/dist/src/project-identity.d.ts +3 -0
  144. package/dist/src/project-identity.js +8 -0
  145. package/dist/src/project-identity.js.map +1 -0
  146. package/dist/src/project-overrides.d.ts +57 -0
  147. package/dist/src/project-overrides.js +79 -0
  148. package/dist/src/project-overrides.js.map +1 -0
  149. package/dist/src/skills/builtin/setup-agentcore-memory/SKILL.md +158 -0
  150. package/dist/src/skills/loader.d.ts +1 -1
  151. package/dist/src/skills/loader.js +4 -1
  152. package/dist/src/skills/loader.js.map +1 -1
  153. package/dist/src/tools/background-bash.d.ts +6 -0
  154. package/dist/src/tools/background-bash.js +26 -0
  155. package/dist/src/tools/background-bash.js.map +1 -1
  156. package/dist/src/tools/shell-env.d.ts +24 -0
  157. package/dist/src/tools/shell-env.js +34 -0
  158. package/dist/src/tools/shell-env.js.map +1 -1
  159. package/dist/src/trajectory/reader.d.ts +1 -1
  160. package/dist/src/trajectory/reader.js +23 -3
  161. package/dist/src/trajectory/reader.js.map +1 -1
  162. package/dist/src/trajectory/resume-recap.d.ts +11 -1
  163. package/dist/src/trajectory/resume-recap.js +10 -1
  164. package/dist/src/trajectory/resume-recap.js.map +1 -1
  165. package/dist/src/trajectory/rewind-history.d.ts +8 -0
  166. package/dist/src/trajectory/rewind-history.js +81 -0
  167. package/dist/src/trajectory/rewind-history.js.map +1 -0
  168. package/dist/src/tui/App.d.ts +5 -1
  169. package/dist/src/tui/App.js +284 -51
  170. package/dist/src/tui/App.js.map +1 -1
  171. package/dist/src/tui/InputBox.d.ts +1 -1
  172. package/dist/src/tui/InputBox.js +1 -1
  173. package/dist/src/tui/MessageList.js +1 -1
  174. package/dist/src/tui/MessageList.js.map +1 -1
  175. package/dist/src/tui/PermissionPrompt.js +5 -3
  176. package/dist/src/tui/PermissionPrompt.js.map +1 -1
  177. package/dist/src/tui/QueuedMessages.js +14 -8
  178. package/dist/src/tui/QueuedMessages.js.map +1 -1
  179. package/dist/src/tui/ToolCallPanel.js +2 -2
  180. package/dist/src/tui/ToolCallPanel.js.map +1 -1
  181. package/dist/src/tui/WorkspaceTrustPrompt.d.ts +8 -0
  182. package/dist/src/tui/WorkspaceTrustPrompt.js +37 -0
  183. package/dist/src/tui/WorkspaceTrustPrompt.js.map +1 -0
  184. package/dist/src/tui/draft-stash.d.ts +25 -0
  185. package/dist/src/tui/draft-stash.js +49 -0
  186. package/dist/src/tui/draft-stash.js.map +1 -0
  187. package/dist/src/tui/frame-budget.d.ts +2 -2
  188. package/dist/src/tui/frame-budget.js +3 -3
  189. package/dist/src/tui/frame-budget.js.map +1 -1
  190. package/dist/src/tui/help-format.d.ts +2 -2
  191. package/dist/src/tui/help-format.js +3 -3
  192. package/dist/src/tui/help-format.js.map +1 -1
  193. package/dist/src/tui/mcp-format.d.ts +9 -0
  194. package/dist/src/tui/mcp-format.js +5 -3
  195. package/dist/src/tui/mcp-format.js.map +1 -1
  196. package/dist/src/tui/permission-rule-preview.d.ts +23 -0
  197. package/dist/src/tui/permission-rule-preview.js +38 -0
  198. package/dist/src/tui/permission-rule-preview.js.map +1 -0
  199. package/dist/src/tui/prompt-editor.d.ts +12 -0
  200. package/dist/src/tui/prompt-editor.js +38 -28
  201. package/dist/src/tui/prompt-editor.js.map +1 -1
  202. package/dist/src/tui/prompt-history-search.js +3 -2
  203. package/dist/src/tui/prompt-history-search.js.map +1 -1
  204. package/dist/src/tui/prompt-queue.d.ts +4 -2
  205. package/dist/src/tui/prompt-queue.js +18 -3
  206. package/dist/src/tui/prompt-queue.js.map +1 -1
  207. package/dist/src/tui/rewind-search.js +4 -3
  208. package/dist/src/tui/rewind-search.js.map +1 -1
  209. package/dist/src/tui/search-preview.d.ts +2 -0
  210. package/dist/src/tui/search-preview.js +9 -0
  211. package/dist/src/tui/search-preview.js.map +1 -0
  212. package/dist/src/tui/shell-command.js +4 -1
  213. package/dist/src/tui/shell-command.js.map +1 -1
  214. package/dist/src/tui/spinner.d.ts +1 -0
  215. package/dist/src/tui/spinner.js +6 -0
  216. package/dist/src/tui/spinner.js.map +1 -0
  217. package/dist/src/tui/status-format.d.ts +9 -0
  218. package/dist/src/tui/status-format.js +37 -2
  219. package/dist/src/tui/status-format.js.map +1 -1
  220. package/dist/src/tui/subagent-format.js +6 -0
  221. package/dist/src/tui/subagent-format.js.map +1 -1
  222. package/dist/src/tui/task-format.d.ts +5 -0
  223. package/dist/src/tui/task-format.js +15 -0
  224. package/dist/src/tui/task-format.js.map +1 -1
  225. package/dist/src/tui/trust-format.d.ts +31 -0
  226. package/dist/src/tui/trust-format.js +102 -0
  227. package/dist/src/tui/trust-format.js.map +1 -0
  228. package/dist/src/tui/turn-state.d.ts +1 -0
  229. package/dist/src/tui/turn-state.js +2 -0
  230. package/dist/src/tui/turn-state.js.map +1 -1
  231. package/package.json +2 -1
@@ -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,
@@ -141,6 +148,8 @@ export class AgentRuntime {
141
148
  trajectory;
142
149
  diagnosticsLog;
143
150
  memoryController;
151
+ cloudMemory;
152
+ lease;
144
153
  info;
145
154
  createOptions;
146
155
  /**
@@ -241,7 +250,13 @@ export class AgentRuntime {
241
250
  /** Undefined unless `diagnostics: true` asked for the log. Off is the default. */
242
251
  diagnosticsLog,
243
252
  /** Undefined only when effective config disables derived project context. */
244
- memoryController, info,
253
+ memoryController, cloudMemory,
254
+ /**
255
+ * This process's hold on `info.sessionId` (SER-091). Released by {@link shutdown}
256
+ * and by {@link retire} — the `/clear` and `/rewind` successor takes its own lease
257
+ * on its own id through `create()` — and only while the file still names this pid.
258
+ */
259
+ lease, info,
245
260
  /**
246
261
  * What this runtime was created with, so {@link startNewSession} can assemble its
247
262
  * successor through the same factory instead of a second, drifting assembly.
@@ -268,22 +283,24 @@ export class AgentRuntime {
268
283
  this.trajectory = trajectory;
269
284
  this.diagnosticsLog = diagnosticsLog;
270
285
  this.memoryController = memoryController;
286
+ this.cloudMemory = cloudMemory;
287
+ this.lease = lease;
271
288
  this.info = info;
272
289
  this.createOptions = createOptions;
273
290
  this.thinkingPlan = info.thinking;
274
291
  this.liveConfig = info.config;
275
292
  this.promptCachePlan = info.promptCache;
276
293
  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.
294
+ // Fire and forget: priced/fresh-negative ids cost one file read; missing or
295
+ // expired-negative ids start one bounded fetch. Startup and the first turn do
296
+ // not await it; it cannot reject or become a startup failure.
280
297
  void this.modelPrices.ensure(this.liveConfig);
281
298
  }
282
299
  /**
283
300
  * Releases startup-owned observers and external clients when construction fails.
284
301
  * Successful creation transfers the same resources to `shutdown()` instead.
285
302
  */
286
- static async unwindCreate(diagnosticsLog, mcpClients = [], backgroundBash, memoryController, lifecycleHooks, codexHooks) {
303
+ static async unwindCreate(diagnosticsLog, mcpClients = [], backgroundBash, memoryController, lifecycleHooks, codexHooks, cloudMemory) {
287
304
  if (diagnosticsLog !== undefined)
288
305
  setSdkVerboseSink(undefined);
289
306
  await Promise.allSettled([
@@ -293,6 +310,7 @@ export class AgentRuntime {
293
310
  memoryController?.close() ?? Promise.resolve(),
294
311
  lifecycleHooks?.close() ?? Promise.resolve(),
295
312
  codexHooks?.close() ?? Promise.resolve(),
313
+ cloudMemory?.close() ?? Promise.resolve(),
296
314
  ]);
297
315
  }
298
316
  static async create(options) {
@@ -300,11 +318,25 @@ export class AgentRuntime {
300
318
  // selector must fail locally without initializing anything billable.
301
319
  const session = await resolveSession(options.projectRoot, options.session, AGENT_ID);
302
320
  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);
321
+ let config;
322
+ let policy;
323
+ // SER-090: the driver's trust decision decides whether the checkout's own hook
324
+ // files, MCP servers and legacy rule fallback are read at all. Held layers are
325
+ // skipped by the loaders, not failed — the user declined them.
326
+ const projectLayers = options.workspaceTrust === undefined || projectLayersArmed(options.workspaceTrust) ? 'armed' : 'held';
327
+ try {
328
+ // A successor created by `/clear` takes the predecessor's *live* config instead of
329
+ // re-reading the file, so a `/model` or `/effort` change made this session survives
330
+ // the switch (see InheritedRuntimeResources).
331
+ config = options.inherit?.config ?? (await loadConfig(options.projectRoot));
332
+ policy = await loadProjectPolicy(options.projectRoot, { projectLayers });
333
+ }
334
+ catch (error) {
335
+ // SER-091: a `ConfigError` here ends the process; the lease must not outlive the
336
+ // session it was taken for, or the next launch would report a takeover.
337
+ await session.lease.release();
338
+ throw error;
339
+ }
308
340
  // Built here, before the model, the MCP clients and the skills plugin, because all
309
341
  // three log at `debug` while they start up (MCP tool renames, skill discovery) and
310
342
  // a diagnostics log that begins after startup cannot answer a question about
@@ -328,6 +360,7 @@ export class AgentRuntime {
328
360
  let startupMcpClients = [];
329
361
  let startupBackgroundBash;
330
362
  let startupMemoryController;
363
+ let startupCloudMemory;
331
364
  let startupLifecycleHooks;
332
365
  let startupCodexHooks;
333
366
  // Keep assembly in one function so one catch owns every resource acquired
@@ -344,6 +377,7 @@ export class AgentRuntime {
344
377
  : `${basePrompt.prompt}\n\n${options.systemPromptSuffix}`;
345
378
  const mcp = options.inherit?.mcp ?? await loadMcpClients(options.projectRoot, {
346
379
  quietStdioStderr: options.quietMcpStderr === true,
380
+ projectLayer: projectLayers,
347
381
  });
348
382
  // Inherited resources belong to a predecessor that is still alive: if this
349
383
  // assembly fails, the unwind must not release them out from under it.
@@ -410,17 +444,20 @@ export class AgentRuntime {
410
444
  // reuse `foregroundBash` and the manager through `childBash`), get this map.
411
445
  // Names only are kept for `/status` and the startup notice; values never leave
412
446
  // `shellEnv.env`. User `!` commands, hooks and MCP servers are not routed here.
447
+ // SER-094: the spawned shells additionally carry `DARWIN=1` (a preset `DARWIN`
448
+ // wins) — added after the scrub so the marker is never a withheld name.
413
449
  const shellPassthrough = config.shellEnv?.passthrough ?? [];
414
450
  const shellEnv = scrubShellEnv(process.env, shellPassthrough);
415
- const foregroundBash = createForegroundBashTool(options.projectRoot, shellEnv.env);
451
+ const spawnEnv = withDarwinMarker(shellEnv.env);
452
+ const foregroundBash = createForegroundBashTool(options.projectRoot, spawnEnv);
416
453
  // The parent's wording states the runtime truth: only a driver that drains SER-069
417
454
  // task wakes, with the config key on, may tell the model that ending the turn is
418
455
  // followed by a `<task-notification>` turn. Children get the same manager and
419
456
  // foreground tool behind the no-wake wording (`childBash` below): a child's job
420
457
  // wakes the parent TUI, never the child.
421
458
  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;
459
+ const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes, env: spawnEnv });
460
+ const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash, { env: spawnEnv }) : bash;
424
461
  const imageViewer = createImageViewerTool(options.projectRoot);
425
462
  const conversationManager = new SummarizingConversationManager({
426
463
  summaryRatio: config.summaryRatio,
@@ -454,6 +491,8 @@ export class AgentRuntime {
454
491
  : undefined;
455
492
  const memoryController = config.memory === true ? new MemoryToolController(options.projectRoot, config.memoryHorizonDays ?? 28) : undefined;
456
493
  startupMemoryController = memoryController;
494
+ const cloudMemory = config.agentCoreMemory === undefined ? undefined : new CloudMemory(config.agentCoreMemory, options.projectRoot, session.sessionId);
495
+ startupCloudMemory = cloudMemory;
457
496
  // The fileEditor is the SDK vended tool — `makeFileEditor({ description })`, the
458
497
  // same factory as the singleton with the SDK's default text plus the SRF-032
459
498
  // payload bound — behind a same-path ordering wrapper (SRF-020): substituted here
@@ -504,9 +543,20 @@ export class AgentRuntime {
504
543
  // Darwin's own hook + middleware below keep the same schedule (SER-066).
505
544
  retryStrategy: null,
506
545
  });
546
+ if (cloudMemory !== undefined) {
547
+ agent.addHook(BeforeToolsEvent, event => cloudMemory.uploadObserver?.batch(event), { order: HookOrder.SDK_LAST });
548
+ agent.addHook(BeforeToolCallEvent, event => cloudMemory.uploadObserver?.before(event), { order: HookOrder.SDK_LAST });
549
+ // Pre-after-hook execution evidence, not necessarily final model-visible output.
550
+ agent.addHook(AfterToolCallEvent, event => cloudMemory.uploadObserver?.after(event), { order: HookOrder.SDK_FIRST });
551
+ // Batch cancellation, executor failure and background acknowledgement may
552
+ // have no AfterToolCallEvent. Never overwrite an original snapshot.
553
+ agent.addHook(ToolResultEvent, event => cloudMemory.uploadObserver?.fallback(event), { order: HookOrder.SDK_LAST });
554
+ }
507
555
  toolForName = (name) => agent.tools.find((candidate) => candidate.name === name);
508
556
  installMaxTokensRecovery(agent);
509
557
  const modelRetry = installModelRetry(agent);
558
+ // Registered inside retry: deliberate backoff is never stream inactivity.
559
+ installStreamIdleWatchdog(agent, config.streamIdleTimeoutSeconds);
510
560
  backgroundDelegation.install(agent);
511
561
  // The constructor does not initialize; the SDK defers it to the first
512
562
  // invocation. Session restore runs on InitializedEvent, MCP tools are
@@ -575,6 +625,9 @@ export class AgentRuntime {
575
625
  agent.toolRegistry.add(createUpdatePlanTool());
576
626
  if (memoryController !== undefined)
577
627
  agent.toolRegistry.add(createMemoryTools(memoryController));
628
+ if (cloudMemory !== undefined) {
629
+ agent.toolRegistry.add(createCloudMemoryTools(cloudMemory));
630
+ }
578
631
  // Children build their models through the same factory seam as the parent: in
579
632
  // production it *is* `createModelFromConfig`; offline suites can script a child
580
633
  // (`spike/verify-background-delegation.ts`) without a provider.
@@ -615,8 +668,10 @@ export class AgentRuntime {
615
668
  // session overwrites `systemPrompt` with the snapshot's copy, so composing it
616
669
  // earlier would leave a resumed run advertising the previous run's date and
617
670
  // 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);
671
+ // prompt can still be corrected by. The registry is complete here — MCP
672
+ // discovery ran inside initialize() and every parent-only tool is added above —
673
+ // so the block can name the tools this run really has.
674
+ const workingContext = await buildWorkingContext(options.projectRoot, new Date(), { toolNames: agent.tools.map((tool) => tool.name) });
620
675
  if (!applyWorkingContext(agent, workingContext.fragment)) {
621
676
  throw new Error('Could not refresh working context on the restored system prompt.');
622
677
  }
@@ -666,16 +721,20 @@ export class AgentRuntime {
666
721
  }),
667
722
  },
668
723
  ...runtimeRecorderOverrides,
669
- ...(memoryController === undefined ? {} : { onTurnSettled: (settlement) => memoryController.settle(settlement) }),
724
+ ...((memoryController === undefined && cloudMemory === undefined) ? {} : { onTurnSettled: (settlement) => {
725
+ memoryController?.settle(settlement);
726
+ cloudMemory?.settle(settlement);
727
+ } }),
670
728
  });
671
729
  trajectoryAudit = trajectory;
672
730
  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, {
731
+ 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, cloudMemory, session.lease, {
674
732
  config,
675
733
  projectRoot: options.projectRoot,
676
734
  permissionMode,
677
735
  sessionId: session.sessionId,
678
736
  resumed: session.restoreRequested && agent.messages.length > 0,
737
+ ...(session.leaseNotice === undefined ? {} : { leaseNotice: session.leaseNotice }),
679
738
  skillNames: skills.skills.map((skill) => skill.name),
680
739
  skillProblems: skills.problems.map((problem) => ({ ...problem })),
681
740
  commandNames: commands.commands.map((command) => command.name),
@@ -712,6 +771,7 @@ export class AgentRuntime {
712
771
  shadowed: [...notice.shadowed],
713
772
  })),
714
773
  shellEnv: { withheld: [...shellEnv.withheld], passthrough: [...shellPassthrough] },
774
+ workspaceTrust: workspaceTrustReport(options.workspaceTrust),
715
775
  mcpIgnoredConfigPath: mcp.ignoredConfigPath,
716
776
  mcpServerCount: mcp.clients.length,
717
777
  toolNames: agent.tools.map((tool) => tool.name).sort(),
@@ -729,7 +789,8 @@ export class AgentRuntime {
729
789
  return runtime;
730
790
  };
731
791
  return assemble().catch(async (error) => {
732
- await AgentRuntime.unwindCreate(diagnosticsLog, startupMcpClients, startupBackgroundBash, startupMemoryController, startupLifecycleHooks, startupCodexHooks);
792
+ await AgentRuntime.unwindCreate(diagnosticsLog, startupMcpClients, startupBackgroundBash, startupMemoryController, startupLifecycleHooks, startupCodexHooks, startupCloudMemory);
793
+ await session.lease.release();
733
794
  throw error;
734
795
  });
735
796
  }
@@ -777,6 +838,7 @@ export class AgentRuntime {
777
838
  if (submitted !== undefined && !submitted.allowed) {
778
839
  throw new Error(submitted.reason ?? 'UserPromptSubmit hook blocked this prompt.');
779
840
  }
841
+ const cloudGeneration = await this.prepareCloudPreferences();
780
842
  const modelInput = injectCodexContext(input, submitted?.context);
781
843
  let checkpointId;
782
844
  // A text-only checkpoint cannot truthfully reproduce a multimodal boundary.
@@ -790,6 +852,9 @@ export class AgentRuntime {
790
852
  // memory sealing and terminal delivery keep meaning `endTurn`.
791
853
  let refused = false;
792
854
  let sealed = false;
855
+ let naturallyCompleted = false;
856
+ let uploadTurn;
857
+ let streamStarted = false;
793
858
  try {
794
859
  // A multimodal turn's durable text is the literal submitted prompt. Expanded
795
860
  // command text and held shell reports still reach the model, but image bytes
@@ -804,6 +869,10 @@ export class AgentRuntime {
804
869
  // actually submitted. Drivers pass that raw text as the second argument. A
805
870
  // session-originated wake has no user text to quote from at all.
806
871
  this.memoryController?.openTurn(recording?.turn, origin === undefined ? userInput : '');
872
+ if (recording !== undefined && this.cloudMemory?.uploadObserver !== undefined) {
873
+ uploadTurn = recording.turn;
874
+ this.cloudMemory.begin(recording.turn, origin === undefined ? userInput : '');
875
+ }
807
876
  // The current input is the one exception to fire-and-forget recording: make it
808
877
  // readable to offline observers before Agent.stream() can invoke a provider or
809
878
  // tool. The recorder owns the bound and resolves on write failure/timeout, so
@@ -819,8 +888,14 @@ export class AgentRuntime {
819
888
  // next SDK event, so the recorder and every driver see one ordinary
820
889
  // before/after pair for a delegation the model routed to the background.
821
890
  const invocation = image === undefined ? modelInput : [new TextBlock(modelInput), image];
891
+ this.checkCloudPreparation(cloudGeneration);
892
+ streamStarted = true;
822
893
  const stream = this.backgroundDelegation.observe(this.agent.stream(invocation));
823
894
  for await (const event of recordStream(stream, recording)) {
895
+ if (event.type === 'afterToolCallEvent')
896
+ this.cloudMemory?.uploadObserver?.forwarded(event);
897
+ if (event.type !== 'beforeToolCallEvent' && event.type !== 'afterToolCallEvent')
898
+ this.cloudMemory?.uploadObserver?.internal();
824
899
  if (event.type === 'agentResultEvent' && event.result.stopReason === 'endTurn')
825
900
  completed = true;
826
901
  if (event.type === 'agentResultEvent' && isRefusalStop(event.result.stopReason))
@@ -841,17 +916,24 @@ export class AgentRuntime {
841
916
  snapshotId: checkpointId,
842
917
  prompt: input,
843
918
  completedAt: new Date().toISOString(),
919
+ ...(recording === undefined ? {} : { trajectoryTurn: recording.turn }),
844
920
  });
845
921
  if (catalogue.problem !== undefined) {
846
922
  this.diagnosticsLog?.notice(`rewind checkpoint not catalogued: ${catalogue.problem}`, 'warn');
847
923
  }
848
924
  }
925
+ naturallyCompleted = true;
849
926
  }
850
927
  finally {
928
+ if (uploadTurn !== undefined)
929
+ this.cloudMemory?.sealTurn(uploadTurn, naturallyCompleted && completed && cloudGeneration === this.cloudMemory.cancelGeneration);
851
930
  // Seeing an endTurn event is not enough when the consumer abandons this
852
931
  // generator before natural completion: only the natural path above seals.
853
932
  if (!sealed)
854
933
  this.memoryController?.discard();
934
+ this.cloudMemory?.uploadObserver?.end();
935
+ if (uploadTurn !== undefined && (!streamStarted || this.trajectory?.status.active === false))
936
+ this.cloudMemory?.discardTurn(uploadTurn);
855
937
  // Only a turn that ran to `endTurn` commits what its `wait`/`status` results
856
938
  // delivered; an abandoned or failed turn forgets them, so the wake still fires.
857
939
  this.terminalDelivery.closeTurn(sealed && completed);
@@ -934,10 +1016,49 @@ export class AgentRuntime {
934
1016
  get memoryStatus() {
935
1017
  return this.memoryController?.status;
936
1018
  }
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
- */
1019
+ /** Cloud status is a projection, never an implicit retrieval. */
1020
+ get cloudMemoryStatus() { return this.cloudMemory?.status() ?? 'AgentCore: disabled (local project memory unchanged)'; }
1021
+ checkCloudPreparation(generation) {
1022
+ if (generation !== this.cloudMemory?.cancelGeneration)
1023
+ throw new Error('AgentCore preparation cancelled before model invocation');
1024
+ }
1025
+ async refreshCloudPolicy() {
1026
+ if (this.cloudMemory === undefined)
1027
+ return;
1028
+ await this.cloudMemory.refreshPolicy();
1029
+ this.liveConfig = { ...this.liveConfig, agentCoreMemory: this.cloudMemory.config };
1030
+ }
1031
+ async prepareCloudPreferences() {
1032
+ if (this.cloudMemory === undefined)
1033
+ return;
1034
+ const generation = this.cloudMemory.cancelGeneration;
1035
+ await this.refreshCloudPolicy();
1036
+ await this.cloudMemory.startup(); // One cloud fetch per runtime; local revocations are checked on every request.
1037
+ this.checkCloudPreparation(generation);
1038
+ await this.applyCloudPreferences();
1039
+ this.checkCloudPreparation(generation); // Includes working-context and local approval reads.
1040
+ return generation;
1041
+ }
1042
+ async manageCloudMemory(input) {
1043
+ if (this.cloudMemory === undefined)
1044
+ return this.cloudMemoryStatus;
1045
+ const result = await this.cloudMemory.command(input, 'user');
1046
+ this.liveConfig = { ...this.liveConfig, agentCoreMemory: this.cloudMemory.config };
1047
+ await this.applyCloudPreferences();
1048
+ return result;
1049
+ }
1050
+ async applyCloudPreferences() {
1051
+ if (this.cloudMemory === undefined)
1052
+ return;
1053
+ const context = await buildWorkingContext(this.projectRoot, new Date(), { toolNames: this.agent.tools.map((tool) => tool.name) });
1054
+ const preferences = await this.cloudMemory.context();
1055
+ // Callback replacement preserves literal $&, $`, and $' in reviewed data.
1056
+ if (!applyWorkingContext(this.agent, context.fragment.replace('</working-context>', () => `${preferences}\n</working-context>`))) {
1057
+ throw new Error('AgentCore working-context refresh refused; model invocation blocked');
1058
+ }
1059
+ if (this.promptCache.parts.includes('system prompt'))
1060
+ applySystemPromptCachePoint(this.agent, this.promptCache);
1061
+ }
941
1062
  async manageMemory(input) {
942
1063
  if (this.liveConfig.memory !== true) {
943
1064
  return { changed: false, text: 'project memory is off — remove memory: false if set, and enable trajectory recording in ~/.darwin/config.json' };
@@ -967,6 +1088,8 @@ export class AgentRuntime {
967
1088
  const pre = await this.codexHooks?.preCompact('manual');
968
1089
  if (pre !== undefined && !pre.allowed)
969
1090
  throw new Error(pre.reason ?? 'PreCompact hook blocked compaction.');
1091
+ const cloudGeneration = await this.prepareCloudPreferences();
1092
+ this.checkCloudPreparation(cloudGeneration);
970
1093
  try {
971
1094
  const result = await compactConversation({
972
1095
  agent: this.agent,
@@ -1088,7 +1211,16 @@ export class AgentRuntime {
1088
1211
  */
1089
1212
  async saveAllowRule(rule) {
1090
1213
  this.gate.addAllowRule(rule);
1091
- await appendAllowRule(this.projectRoot, rule);
1214
+ await appendAllowRule(this.projectRoot, rule, this.projectLayerOptions());
1215
+ }
1216
+ /**
1217
+ * The `loadProjectPolicy` layer option this runtime was created with (SER-090), so
1218
+ * the two rule writers below promote legacy rules only from a layer that was in
1219
+ * force — an untrusted project's committed `.darwin/config.json` never reaches the
1220
+ * user-owned file through an "always allow" answer.
1221
+ */
1222
+ projectLayerOptions() {
1223
+ return { projectLayers: this.info.workspaceTrust.state === 'trusted' ? 'armed' : 'held' };
1092
1224
  }
1093
1225
  /**
1094
1226
  * The live allow-rules with their provenance — config-loaded vs granted this
@@ -1134,7 +1266,9 @@ export class AgentRuntime {
1134
1266
  */
1135
1267
  revokeAllowRules(rules) {
1136
1268
  const removed = rules.filter((rule) => this.gate.removeAllowRule(rule));
1137
- const saved = removed.length === 0 ? Promise.resolve() : removeAllowRules(this.projectRoot, removed);
1269
+ const saved = removed.length === 0
1270
+ ? Promise.resolve()
1271
+ : removeAllowRules(this.projectRoot, removed, this.projectLayerOptions());
1138
1272
  return { removed, saved };
1139
1273
  }
1140
1274
  /**
@@ -1263,6 +1397,7 @@ export class AgentRuntime {
1263
1397
  * describe a model that is no longer there.
1264
1398
  */
1265
1399
  async changeModel(target) {
1400
+ await this.refreshCloudPolicy();
1266
1401
  const next = withModelChoice(this.liveConfig, target);
1267
1402
  // Built before anything is mutated: a failure here (a missing peer dependency,
1268
1403
  // a bad region) must leave the session on the model it was already using. Same
@@ -1504,6 +1639,13 @@ export class AgentRuntime {
1504
1639
  listBackgroundTasks() {
1505
1640
  return this.backgroundBash.list();
1506
1641
  }
1642
+ /** Live in-memory activity for the TUI; no log reads or tool invocation. */
1643
+ get runningBackgroundTaskCount() {
1644
+ return this.backgroundBash.runningCount;
1645
+ }
1646
+ subscribeToBackgroundTaskActivity(listener) {
1647
+ return this.backgroundBash.subscribeActivity(listener);
1648
+ }
1507
1649
  /** Publishes future terminal task snapshots until the returned closure is called. */
1508
1650
  subscribeToBackgroundTasks(listener) {
1509
1651
  return this.backgroundBash.subscribe(listener);
@@ -1571,6 +1713,7 @@ export class AgentRuntime {
1571
1713
  * ends with `stopReason: 'cancelled'` rather than throwing.
1572
1714
  */
1573
1715
  cancel() {
1716
+ this.cloudMemory?.cancel();
1574
1717
  this.lifecycleHooks?.cancel();
1575
1718
  this.codexHooks?.cancel();
1576
1719
  this.subagents.cancelActive();
@@ -1625,6 +1768,8 @@ export class AgentRuntime {
1625
1768
  */
1626
1769
  async startRewind(checkpoint) {
1627
1770
  this.refuseWhileDelegationsTracked('/rewind');
1771
+ await this.cloudMemory?.stopAutoForSuccessor();
1772
+ await this.refreshCloudPolicy();
1628
1773
  const catalogue = await readRewindCatalogue(this.projectRoot, this.info.sessionId);
1629
1774
  if (catalogue.problem !== undefined)
1630
1775
  throw new Error(catalogue.problem);
@@ -1689,8 +1834,8 @@ export class AgentRuntime {
1689
1834
  * the user the conversation they just set aside. The successor claims the pointer on
1690
1835
  * its first finished turn, through the ordinary path.
1691
1836
  *
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
1837
+ * If assembling the successor fails, conversation/tools stay usable; predecessor auto
1838
+ * uploads remain conservatively stopped (cloud status states it). The diagnostics tap is put back
1694
1839
  * (the failed successor's unwind clears the process-global sink).
1695
1840
  *
1696
1841
  * Refused while a background delegation is tracked (SER-070): `retire()` would cancel
@@ -1700,6 +1845,8 @@ export class AgentRuntime {
1700
1845
  */
1701
1846
  async startNewSession() {
1702
1847
  this.refuseWhileDelegationsTracked('/clear');
1848
+ await this.cloudMemory?.stopAutoForSuccessor();
1849
+ await this.refreshCloudPolicy();
1703
1850
  let successor;
1704
1851
  try {
1705
1852
  successor = await AgentRuntime.create({
@@ -1753,13 +1900,16 @@ export class AgentRuntime {
1753
1900
  ]);
1754
1901
  // Closing trajectory first publishes the final settlement. The controller then
1755
1902
  // discards unresolved staging and waits only for commits already accepted.
1756
- await Promise.allSettled([Promise.resolve(ownedWork), this.memoryController?.close() ?? Promise.resolve()]);
1903
+ await Promise.allSettled([Promise.resolve(ownedWork), this.memoryController?.close() ?? Promise.resolve(), this.cloudMemory?.close() ?? Promise.resolve()]);
1757
1904
  // SessionEnd is the final advisory boundary: all session-owned work above has
1758
1905
  // settled, while diagnostics remains open to retain a bounded hook problem.
1759
1906
  await Promise.allSettled([
1760
1907
  this.codexHooks?.sessionEnd('other').then(() => this.codexHooks?.close()) ?? Promise.resolve(),
1761
1908
  ]);
1762
1909
  await Promise.allSettled([this.diagnosticsLog?.close() ?? Promise.resolve()]);
1910
+ // SER-091: last, after the trajectory is durable — the successor already holds its
1911
+ // own lease on its own id, so this session is simply no longer open anywhere.
1912
+ await this.lease.release();
1763
1913
  }
1764
1914
  /**
1765
1915
  * Creates one bounded rewind snapshot, serialized so concurrent callers cannot
@@ -1796,13 +1946,14 @@ export class AgentRuntime {
1796
1946
  }
1797
1947
  /**
1798
1948
  * 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
1949
+ * prompt sent to the model. `/workflow`, `/init` and `/review` come first: built-in
1800
1950
  * reservation precedes skills and custom commands, so no extension can
1801
1951
  * shadow them. Bare `/workflow` returns null — the drivers own that local usage
1802
1952
  * notice, and the runtime never fabricates a turn — while bare `/init` is the
1803
- * trigger itself. `/init` decides create-versus-improve from the instructions
1953
+ * trigger itself, as is bare `/review`. `/review` is guidance only, with no mode
1954
+ * change or executor. `/init` decides create-versus-improve from the instructions
1804
1955
  * 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
1956
+ * a fresh filesystem read, so TUI, dev-repl and both headless drivers get the
1806
1957
  * same branch through this one seam. Skills are checked before
1807
1958
  * custom commands as a defensive backstop to the loader's collision
1808
1959
  * filtering. Unknown slash input remains ordinary user input.
@@ -1819,6 +1970,9 @@ export class AgentRuntime {
1819
1970
  });
1820
1971
  if (init !== null)
1821
1972
  return { kind: 'init', ...init };
1973
+ const review = parseReviewCommand(input);
1974
+ if (review !== null)
1975
+ return { kind: 'review', ...review };
1822
1976
  const skill = await expandSkillCommand(this.skills, input);
1823
1977
  if (skill !== null)
1824
1978
  return { kind: 'skill', ...skill };
@@ -1832,6 +1986,7 @@ export class AgentRuntime {
1832
1986
  * exiting.
1833
1987
  */
1834
1988
  async shutdown(options = {}) {
1989
+ this.cloudMemory?.cancel();
1835
1990
  const results = await Promise.allSettled([
1836
1991
  this.subagents.shutdown(),
1837
1992
  this.workflows.shutdown(),
@@ -1843,7 +1998,7 @@ export class AgentRuntime {
1843
1998
  // unawaited; cleanup only waits for a commit after durable acceptance.
1844
1999
  this.trajectory?.close() ?? Promise.resolve(),
1845
2000
  ]);
1846
- const memoryResults = await Promise.allSettled([this.memoryController?.close() ?? Promise.resolve()]);
2001
+ const memoryResults = await Promise.allSettled([this.memoryController?.close() ?? Promise.resolve(), this.cloudMemory?.close() ?? Promise.resolve()]);
1847
2002
  results.push(...memoryResults);
1848
2003
  // SessionEnd is advisory but ordered after owned work. Keep diagnostics open
1849
2004
  // through it, then detach the process-global SDK tap before closing the file.
@@ -1853,6 +2008,10 @@ export class AgentRuntime {
1853
2008
  if (this.diagnosticsLog !== undefined)
1854
2009
  setSdkVerboseSink(undefined);
1855
2010
  results.push(...await Promise.allSettled([this.diagnosticsLog?.close() ?? Promise.resolve()]));
2011
+ // SER-091: the lease goes last, once every writer above has settled, and only if
2012
+ // the file still names this process. Non-throwing: a lease that stays behind is
2013
+ // stale the moment this pid is gone, and the next launch takes it over.
2014
+ await this.lease.release();
1856
2015
  const failures = results.flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
1857
2016
  if (options.throwOnError === true && failures.length > 0) {
1858
2017
  throw new AggregateError(failures, `${failures.length} runtime cleanup operation(s) failed`);