strands-darwin 0.0.34 → 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 (273) hide show
  1. package/README.md +22 -3
  2. package/README.zh-CN.md +22 -3
  3. package/dist/patches/@strands-agents+sdk+1.16.0.patch +29 -15
  4. package/dist/patches/ink+7.1.1.patch +58 -0
  5. package/dist/src/agent/background-delegation.d.ts +3 -3
  6. package/dist/src/agent/background-delegation.js +2 -2
  7. package/dist/src/agent/background-delegation.js.map +1 -1
  8. package/dist/src/agent/context-breakdown.d.ts +2 -1
  9. package/dist/src/agent/context-breakdown.js +2 -1
  10. package/dist/src/agent/context-breakdown.js.map +1 -1
  11. package/dist/src/agent/instructions.d.ts +22 -3
  12. package/dist/src/agent/instructions.js +67 -34
  13. package/dist/src/agent/instructions.js.map +1 -1
  14. package/dist/src/agent/prompt-cache.js +15 -2
  15. package/dist/src/agent/prompt-cache.js.map +1 -1
  16. package/dist/src/agent/refusal.d.ts +44 -7
  17. package/dist/src/agent/refusal.js +54 -8
  18. package/dist/src/agent/refusal.js.map +1 -1
  19. package/dist/src/agent/rewind.d.ts +2 -0
  20. package/dist/src/agent/rewind.js +4 -1
  21. package/dist/src/agent/rewind.js.map +1 -1
  22. package/dist/src/agent/runtime.d.ts +86 -13
  23. package/dist/src/agent/runtime.js +250 -43
  24. package/dist/src/agent/runtime.js.map +1 -1
  25. package/dist/src/agent/session.d.ts +96 -4
  26. package/dist/src/agent/session.js +249 -9
  27. package/dist/src/agent/session.js.map +1 -1
  28. package/dist/src/agent/stream-idle.d.ts +16 -0
  29. package/dist/src/agent/stream-idle.js +127 -0
  30. package/dist/src/agent/stream-idle.js.map +1 -0
  31. package/dist/src/agent/stream-resumption.d.ts +5 -2
  32. package/dist/src/agent/stream-resumption.js +5 -2
  33. package/dist/src/agent/stream-resumption.js.map +1 -1
  34. package/dist/src/agent/system-prompt.d.ts +1 -1
  35. package/dist/src/agent/system-prompt.js +4 -1
  36. package/dist/src/agent/system-prompt.js.map +1 -1
  37. package/dist/src/agent/thinking.js +4 -2
  38. package/dist/src/agent/thinking.js.map +1 -1
  39. package/dist/src/agent/working-context.d.ts +21 -1
  40. package/dist/src/agent/working-context.js +28 -1
  41. package/dist/src/agent/working-context.js.map +1 -1
  42. package/dist/src/agent/workspace-trust.d.ts +112 -0
  43. package/dist/src/agent/workspace-trust.js +207 -0
  44. package/dist/src/agent/workspace-trust.js.map +1 -0
  45. package/dist/src/agentcore/auto-policy.d.ts +7 -0
  46. package/dist/src/agentcore/auto-policy.js +50 -0
  47. package/dist/src/agentcore/auto-policy.js.map +1 -0
  48. package/dist/src/agentcore/auto-state.d.ts +43 -0
  49. package/dist/src/agentcore/auto-state.js +73 -0
  50. package/dist/src/agentcore/auto-state.js.map +1 -0
  51. package/dist/src/agentcore/cli.d.ts +2 -0
  52. package/dist/src/agentcore/cli.js +38 -0
  53. package/dist/src/agentcore/cli.js.map +1 -0
  54. package/dist/src/agentcore/config.d.ts +48 -0
  55. package/dist/src/agentcore/config.js +44 -0
  56. package/dist/src/agentcore/config.js.map +1 -0
  57. package/dist/src/agentcore/controller.d.ts +105 -0
  58. package/dist/src/agentcore/controller.js +979 -0
  59. package/dist/src/agentcore/controller.js.map +1 -0
  60. package/dist/src/agentcore/projection.d.ts +2 -0
  61. package/dist/src/agentcore/projection.js +8 -0
  62. package/dist/src/agentcore/projection.js.map +1 -0
  63. package/dist/src/agentcore/records.d.ts +41 -0
  64. package/dist/src/agentcore/records.js +149 -0
  65. package/dist/src/agentcore/records.js.map +1 -0
  66. package/dist/src/agentcore/state.d.ts +16 -0
  67. package/dist/src/agentcore/state.js +149 -0
  68. package/dist/src/agentcore/state.js.map +1 -0
  69. package/dist/src/agentcore/tools.d.ts +3 -0
  70. package/dist/src/agentcore/tools.js +11 -0
  71. package/dist/src/agentcore/tools.js.map +1 -0
  72. package/dist/src/agentcore/transport.d.ts +37 -0
  73. package/dist/src/agentcore/transport.js +242 -0
  74. package/dist/src/agentcore/transport.js.map +1 -0
  75. package/dist/src/agentcore/upload-projection.d.ts +208 -0
  76. package/dist/src/agentcore/upload-projection.js +823 -0
  77. package/dist/src/agentcore/upload-projection.js.map +1 -0
  78. package/dist/src/agents/child-recipe.js +4 -1
  79. package/dist/src/agents/child-recipe.js.map +1 -1
  80. package/dist/src/agents/loader.d.ts +12 -0
  81. package/dist/src/agents/loader.js +15 -1
  82. package/dist/src/agents/loader.js.map +1 -1
  83. package/dist/src/agents/subagent-tool.js +6 -7
  84. package/dist/src/agents/subagent-tool.js.map +1 -1
  85. package/dist/src/agents/workflow-tool.js +4 -6
  86. package/dist/src/agents/workflow-tool.js.map +1 -1
  87. package/dist/src/cli-doctor.js +14 -5
  88. package/dist/src/cli-doctor.js.map +1 -1
  89. package/dist/src/cli-import.d.ts +1 -0
  90. package/dist/src/cli-import.js +26 -0
  91. package/dist/src/cli-import.js.map +1 -0
  92. package/dist/src/cli-main.js +60 -10
  93. package/dist/src/cli-main.js.map +1 -1
  94. package/dist/src/cli-permissions.d.ts +2 -0
  95. package/dist/src/cli-permissions.js +20 -0
  96. package/dist/src/cli-permissions.js.map +1 -0
  97. package/dist/src/cli-sessions.js +6 -2
  98. package/dist/src/cli-sessions.js.map +1 -1
  99. package/dist/src/cli-usage.d.ts +9 -1
  100. package/dist/src/cli-usage.js +13 -0
  101. package/dist/src/cli-usage.js.map +1 -1
  102. package/dist/src/cli.js +19 -2
  103. package/dist/src/cli.js.map +1 -1
  104. package/dist/src/commands/custom-commands.d.ts +1 -1
  105. package/dist/src/commands/custom-commands.js +20 -6
  106. package/dist/src/commands/custom-commands.js.map +1 -1
  107. package/dist/src/commands/init-command.d.ts +47 -0
  108. package/dist/src/commands/init-command.js +110 -0
  109. package/dist/src/commands/init-command.js.map +1 -0
  110. package/dist/src/commands/review-command.d.ts +10 -0
  111. package/dist/src/commands/review-command.js +28 -0
  112. package/dist/src/commands/review-command.js.map +1 -0
  113. package/dist/src/config-file.d.ts +9 -0
  114. package/dist/src/config-file.js +82 -0
  115. package/dist/src/config-file.js.map +1 -0
  116. package/dist/src/config.d.ts +100 -7
  117. package/dist/src/config.js +253 -46
  118. package/dist/src/config.js.map +1 -1
  119. package/dist/src/dev-repl.js +33 -2
  120. package/dist/src/dev-repl.js.map +1 -1
  121. package/dist/src/headless-protocol.d.ts +24 -1
  122. package/dist/src/headless-protocol.js +24 -5
  123. package/dist/src/headless-protocol.js.map +1 -1
  124. package/dist/src/headless-runner.d.ts +8 -0
  125. package/dist/src/headless-runner.js +42 -2
  126. package/dist/src/headless-runner.js.map +1 -1
  127. package/dist/src/headless.d.ts +11 -0
  128. package/dist/src/headless.js +33 -7
  129. package/dist/src/headless.js.map +1 -1
  130. package/dist/src/hooks/hook-process.js +7 -2
  131. package/dist/src/hooks/hook-process.js.map +1 -1
  132. package/dist/src/hooks/lifecycle-hooks.js +3 -1
  133. package/dist/src/hooks/lifecycle-hooks.js.map +1 -1
  134. package/dist/src/hooks/tool-hooks.js +3 -1
  135. package/dist/src/hooks/tool-hooks.js.map +1 -1
  136. package/dist/src/import-claude-files.d.ts +28 -0
  137. package/dist/src/import-claude-files.js +227 -0
  138. package/dist/src/import-claude-files.js.map +1 -0
  139. package/dist/src/import-claude-snippets.d.ts +2 -0
  140. package/dist/src/import-claude-snippets.js +105 -0
  141. package/dist/src/import-claude-snippets.js.map +1 -0
  142. package/dist/src/import-claude.d.ts +13 -0
  143. package/dist/src/import-claude.js +287 -0
  144. package/dist/src/import-claude.js.map +1 -0
  145. package/dist/src/mcp/registry.d.ts +57 -1
  146. package/dist/src/mcp/registry.js +78 -6
  147. package/dist/src/mcp/registry.js.map +1 -1
  148. package/dist/src/memory/command.d.ts +1 -1
  149. package/dist/src/memory/command.js +89 -4
  150. package/dist/src/memory/command.js.map +1 -1
  151. package/dist/src/memory/controller.d.ts +32 -0
  152. package/dist/src/memory/controller.js +39 -3
  153. package/dist/src/memory/controller.js.map +1 -1
  154. package/dist/src/memory/state.d.ts +6 -0
  155. package/dist/src/memory/state.js +6 -1
  156. package/dist/src/memory/state.js.map +1 -1
  157. package/dist/src/memory/store.d.ts +13 -0
  158. package/dist/src/memory/store.js +38 -2
  159. package/dist/src/memory/store.js.map +1 -1
  160. package/dist/src/memory/tools.d.ts +7 -0
  161. package/dist/src/memory/tools.js +12 -1
  162. package/dist/src/memory/tools.js.map +1 -1
  163. package/dist/src/paths.js +3 -0
  164. package/dist/src/paths.js.map +1 -1
  165. package/dist/src/permissions-test.d.ts +18 -0
  166. package/dist/src/permissions-test.js +207 -0
  167. package/dist/src/permissions-test.js.map +1 -0
  168. package/dist/src/pricing/model-prices.d.ts +11 -6
  169. package/dist/src/pricing/model-prices.js +37 -16
  170. package/dist/src/pricing/model-prices.js.map +1 -1
  171. package/dist/src/project-identity.d.ts +3 -0
  172. package/dist/src/project-identity.js +8 -0
  173. package/dist/src/project-identity.js.map +1 -0
  174. package/dist/src/project-overrides.d.ts +57 -0
  175. package/dist/src/project-overrides.js +79 -0
  176. package/dist/src/project-overrides.js.map +1 -0
  177. package/dist/src/skills/builtin/setup-agentcore-memory/SKILL.md +158 -0
  178. package/dist/src/skills/loader.d.ts +1 -1
  179. package/dist/src/skills/loader.js +4 -1
  180. package/dist/src/skills/loader.js.map +1 -1
  181. package/dist/src/tools/background-bash.d.ts +21 -3
  182. package/dist/src/tools/background-bash.js +44 -8
  183. package/dist/src/tools/background-bash.js.map +1 -1
  184. package/dist/src/tools/file-editor-serial.d.ts +14 -0
  185. package/dist/src/tools/file-editor-serial.js +15 -0
  186. package/dist/src/tools/file-editor-serial.js.map +1 -1
  187. package/dist/src/tools/shell-env.d.ts +101 -0
  188. package/dist/src/tools/shell-env.js +173 -0
  189. package/dist/src/tools/shell-env.js.map +1 -0
  190. package/dist/src/trajectory/reader.d.ts +1 -1
  191. package/dist/src/trajectory/reader.js +23 -3
  192. package/dist/src/trajectory/reader.js.map +1 -1
  193. package/dist/src/trajectory/replay.js +23 -0
  194. package/dist/src/trajectory/replay.js.map +1 -1
  195. package/dist/src/trajectory/resume-recap.d.ts +11 -1
  196. package/dist/src/trajectory/resume-recap.js +10 -1
  197. package/dist/src/trajectory/resume-recap.js.map +1 -1
  198. package/dist/src/trajectory/rewind-history.d.ts +8 -0
  199. package/dist/src/trajectory/rewind-history.js +81 -0
  200. package/dist/src/trajectory/rewind-history.js.map +1 -0
  201. package/dist/src/trajectory/writer.d.ts +44 -3
  202. package/dist/src/trajectory/writer.js +80 -14
  203. package/dist/src/trajectory/writer.js.map +1 -1
  204. package/dist/src/tui/App.d.ts +8 -1
  205. package/dist/src/tui/App.js +453 -75
  206. package/dist/src/tui/App.js.map +1 -1
  207. package/dist/src/tui/InputBox.d.ts +1 -1
  208. package/dist/src/tui/InputBox.js +1 -1
  209. package/dist/src/tui/MessageList.js +1 -1
  210. package/dist/src/tui/MessageList.js.map +1 -1
  211. package/dist/src/tui/PermissionPrompt.js +5 -3
  212. package/dist/src/tui/PermissionPrompt.js.map +1 -1
  213. package/dist/src/tui/QueuedMessages.js +14 -8
  214. package/dist/src/tui/QueuedMessages.js.map +1 -1
  215. package/dist/src/tui/ToolCallPanel.js +2 -2
  216. package/dist/src/tui/ToolCallPanel.js.map +1 -1
  217. package/dist/src/tui/WorkspaceTrustPrompt.d.ts +8 -0
  218. package/dist/src/tui/WorkspaceTrustPrompt.js +37 -0
  219. package/dist/src/tui/WorkspaceTrustPrompt.js.map +1 -0
  220. package/dist/src/tui/draft-stash.d.ts +25 -0
  221. package/dist/src/tui/draft-stash.js +49 -0
  222. package/dist/src/tui/draft-stash.js.map +1 -0
  223. package/dist/src/tui/frame-budget.d.ts +2 -2
  224. package/dist/src/tui/frame-budget.js +3 -3
  225. package/dist/src/tui/frame-budget.js.map +1 -1
  226. package/dist/src/tui/help-format.d.ts +2 -2
  227. package/dist/src/tui/help-format.js +3 -3
  228. package/dist/src/tui/help-format.js.map +1 -1
  229. package/dist/src/tui/instructions-format.d.ts +14 -0
  230. package/dist/src/tui/instructions-format.js +24 -0
  231. package/dist/src/tui/instructions-format.js.map +1 -0
  232. package/dist/src/tui/mcp-format.d.ts +9 -0
  233. package/dist/src/tui/mcp-format.js +5 -3
  234. package/dist/src/tui/mcp-format.js.map +1 -1
  235. package/dist/src/tui/permission-rule-preview.d.ts +23 -0
  236. package/dist/src/tui/permission-rule-preview.js +38 -0
  237. package/dist/src/tui/permission-rule-preview.js.map +1 -0
  238. package/dist/src/tui/prompt-editor.d.ts +12 -0
  239. package/dist/src/tui/prompt-editor.js +38 -28
  240. package/dist/src/tui/prompt-editor.js.map +1 -1
  241. package/dist/src/tui/prompt-history-search.js +3 -2
  242. package/dist/src/tui/prompt-history-search.js.map +1 -1
  243. package/dist/src/tui/prompt-queue.d.ts +4 -2
  244. package/dist/src/tui/prompt-queue.js +22 -5
  245. package/dist/src/tui/prompt-queue.js.map +1 -1
  246. package/dist/src/tui/rewind-search.js +4 -3
  247. package/dist/src/tui/rewind-search.js.map +1 -1
  248. package/dist/src/tui/search-preview.d.ts +2 -0
  249. package/dist/src/tui/search-preview.js +9 -0
  250. package/dist/src/tui/search-preview.js.map +1 -0
  251. package/dist/src/tui/shell-command.js +4 -1
  252. package/dist/src/tui/shell-command.js.map +1 -1
  253. package/dist/src/tui/spinner.d.ts +1 -0
  254. package/dist/src/tui/spinner.js +6 -0
  255. package/dist/src/tui/spinner.js.map +1 -0
  256. package/dist/src/tui/status-format.d.ts +24 -0
  257. package/dist/src/tui/status-format.js +62 -2
  258. package/dist/src/tui/status-format.js.map +1 -1
  259. package/dist/src/tui/subagent-format.js +6 -0
  260. package/dist/src/tui/subagent-format.js.map +1 -1
  261. package/dist/src/tui/tangent.d.ts +122 -0
  262. package/dist/src/tui/tangent.js +153 -0
  263. package/dist/src/tui/tangent.js.map +1 -0
  264. package/dist/src/tui/task-format.d.ts +5 -0
  265. package/dist/src/tui/task-format.js +15 -0
  266. package/dist/src/tui/task-format.js.map +1 -1
  267. package/dist/src/tui/trust-format.d.ts +31 -0
  268. package/dist/src/tui/trust-format.js +102 -0
  269. package/dist/src/tui/trust-format.js.map +1 -0
  270. package/dist/src/tui/turn-state.d.ts +13 -1
  271. package/dist/src/tui/turn-state.js +13 -0
  272. package/dist/src/tui/turn-state.js.map +1 -1
  273. package/package.json +4 -3
@@ -5,8 +5,8 @@
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';
9
- import { fileEditor } from '@strands-agents/sdk/vended-tools/file-editor';
8
+ import { Agent, AfterToolCallEvent, BeforeToolCallEvent, BeforeToolsEvent, ToolResultEvent, HookOrder, BeforeInvocationEvent, SummarizingConversationManager, TextBlock } from '@strands-agents/sdk';
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';
12
12
  import { LocalFileStorage } from '@strands-agents/sdk/storage';
@@ -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';
@@ -23,11 +24,14 @@ import { SubagentDispatchRegistry, } from '../agents/dispatch-registry.js';
23
24
  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';
27
+ import { parseInitCommand } from '../commands/init-command.js';
28
+ import { parseReviewCommand } from '../commands/review-command.js';
26
29
  import { parseWorkflowCommand } from '../commands/workflow-command.js';
27
30
  import { appendAllowRule, applyThinkingEffort, createModelFromConfig, loadConfig, loadProjectPolicy, permissionRulesPath, removeAllowRules, saveEnabledModel, saveThinkingEffort, withModelChoice, } from '../config.js';
28
31
  import { BackgroundBashManager, createBackgroundBashTool, createForegroundBashTool, } from '../tools/background-bash.js';
29
- import { SerializedFileEditorTool } from '../tools/file-editor-serial.js';
32
+ import { FILE_EDITOR_DESCRIPTION, SerializedFileEditorTool } from '../tools/file-editor-serial.js';
30
33
  import { createImageViewerTool, normalizeRestoredImages } from '../tools/image-viewer.js';
34
+ import { scrubShellEnv, withDarwinMarker } from '../tools/shell-env.js';
31
35
  import { createUpdatePlanTool } from '../tools/update-plan.js';
32
36
  import { webFetch } from '../tools/web-fetch.js';
33
37
  import { LifecycleHookRunner, lifecycleHooksFromConfig, } from '../hooks/lifecycle-hooks.js';
@@ -41,6 +45,8 @@ import { orderOfficialSkillsPrompt } from '../skills/prompt.js';
41
45
  import { runMemoryCommand } from '../memory/command.js';
42
46
  import { MemoryToolController } from '../memory/controller.js';
43
47
  import { createMemoryTools } from '../memory/tools.js';
48
+ import { CloudMemory } from '../agentcore/controller.js';
49
+ import { createCloudMemoryTools } from '../agentcore/tools.js';
44
50
  import { recordStream } from '../trajectory/stream.js';
45
51
  import { TrajectoryRecorder, } from '../trajectory/writer.js';
46
52
  import { DARWIN_VERSION } from '../version.js';
@@ -49,12 +55,14 @@ import { measureContextBreakdown } from './context-breakdown.js';
49
55
  import { composeSystemPrompt, loadProjectInstructions, } from './instructions.js';
50
56
  import { PermissionGate } from './permission.js';
51
57
  import { applySystemPromptCachePoint, canUpdateSystemPromptCache, planPromptCache, } from './prompt-cache.js';
58
+ import { isRefusalStop } from './refusal.js';
52
59
  import { createModelClassifier } from './safety-classifier.js';
53
60
  import { createSessionManager, diagnosticsPath, resolveSession, sessionPaths, trajectoryPath, writePointer, } from './session.js';
54
61
  import { setSdkVerboseSink } from './sdk-logging.js';
55
62
  import { loadSystemPrompt } from './system-prompt.js';
56
63
  import { applyWorkingContext, buildWorkingContext } from './working-context.js';
57
64
  import { planThinking } from './thinking.js';
65
+ import { projectLayersArmed, workspaceTrustReport, } from './workspace-trust.js';
58
66
  import { MAX_REWIND_CHECKPOINTS, appendRewindCheckpoint, newestRewindCheckpoints, readRewindCatalogue, rewindPromptEligible, } from './rewind.js';
59
67
  import { deltaUsage, requestInputTokens, startCallSpend, startTurnSpend, sumUsage, usageBuckets } from './usage.js';
60
68
  import { emptyCallStats, readCallUsage, recordCompletedCall, } from './call-stats.js';
@@ -112,6 +120,8 @@ const PARENT_ONLY_TOOL_NAMES = new Set([
112
120
  'retrieve_offloaded_content',
113
121
  httpRequest.name,
114
122
  webFetch.name,
123
+ 'episodic_recall',
124
+ 'reflection_recall',
115
125
  // Registered by the SDK's backgroundTasks plugin during initialize(); a child has
116
126
  // no plugin, so the tool would list nothing and could not cancel anything.
117
127
  MANAGE_BACKGROUND_TASK_TOOL_NAME,
@@ -138,6 +148,8 @@ export class AgentRuntime {
138
148
  trajectory;
139
149
  diagnosticsLog;
140
150
  memoryController;
151
+ cloudMemory;
152
+ lease;
141
153
  info;
142
154
  createOptions;
143
155
  /**
@@ -238,7 +250,13 @@ export class AgentRuntime {
238
250
  /** Undefined unless `diagnostics: true` asked for the log. Off is the default. */
239
251
  diagnosticsLog,
240
252
  /** Undefined only when effective config disables derived project context. */
241
- 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,
242
260
  /**
243
261
  * What this runtime was created with, so {@link startNewSession} can assemble its
244
262
  * successor through the same factory instead of a second, drifting assembly.
@@ -265,22 +283,24 @@ export class AgentRuntime {
265
283
  this.trajectory = trajectory;
266
284
  this.diagnosticsLog = diagnosticsLog;
267
285
  this.memoryController = memoryController;
286
+ this.cloudMemory = cloudMemory;
287
+ this.lease = lease;
268
288
  this.info = info;
269
289
  this.createOptions = createOptions;
270
290
  this.thinkingPlan = info.thinking;
271
291
  this.liveConfig = info.config;
272
292
  this.promptCachePlan = info.promptCache;
273
293
  this.cacheMisses = new CacheMissTracker(() => promptCacheTtlMs(this.promptCachePlan.ttl), info.resumed);
274
- // Fire and forget: a mapped id costs one file read, an unmapped one starts the
275
- // single bounded background fetch. Nothing awaits it — not startup, not the
276
- // 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.
277
297
  void this.modelPrices.ensure(this.liveConfig);
278
298
  }
279
299
  /**
280
300
  * Releases startup-owned observers and external clients when construction fails.
281
301
  * Successful creation transfers the same resources to `shutdown()` instead.
282
302
  */
283
- static async unwindCreate(diagnosticsLog, mcpClients = [], backgroundBash, memoryController, lifecycleHooks, codexHooks) {
303
+ static async unwindCreate(diagnosticsLog, mcpClients = [], backgroundBash, memoryController, lifecycleHooks, codexHooks, cloudMemory) {
284
304
  if (diagnosticsLog !== undefined)
285
305
  setSdkVerboseSink(undefined);
286
306
  await Promise.allSettled([
@@ -290,6 +310,7 @@ export class AgentRuntime {
290
310
  memoryController?.close() ?? Promise.resolve(),
291
311
  lifecycleHooks?.close() ?? Promise.resolve(),
292
312
  codexHooks?.close() ?? Promise.resolve(),
313
+ cloudMemory?.close() ?? Promise.resolve(),
293
314
  ]);
294
315
  }
295
316
  static async create(options) {
@@ -297,11 +318,25 @@ export class AgentRuntime {
297
318
  // selector must fail locally without initializing anything billable.
298
319
  const session = await resolveSession(options.projectRoot, options.session, AGENT_ID);
299
320
  options.onSessionResolved?.(session.sessionId);
300
- // A successor created by `/clear` takes the predecessor's *live* config instead of
301
- // re-reading the file, so a `/model` or `/effort` change made this session survives
302
- // the switch (see InheritedRuntimeResources).
303
- const config = options.inherit?.config ?? (await loadConfig(options.projectRoot));
304
- 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
+ }
305
340
  // Built here, before the model, the MCP clients and the skills plugin, because all
306
341
  // three log at `debug` while they start up (MCP tool renames, skill discovery) and
307
342
  // a diagnostics log that begins after startup cannot answer a question about
@@ -325,6 +360,7 @@ export class AgentRuntime {
325
360
  let startupMcpClients = [];
326
361
  let startupBackgroundBash;
327
362
  let startupMemoryController;
363
+ let startupCloudMemory;
328
364
  let startupLifecycleHooks;
329
365
  let startupCodexHooks;
330
366
  // Keep assembly in one function so one catch owns every resource acquired
@@ -341,6 +377,7 @@ export class AgentRuntime {
341
377
  : `${basePrompt.prompt}\n\n${options.systemPromptSuffix}`;
342
378
  const mcp = options.inherit?.mcp ?? await loadMcpClients(options.projectRoot, {
343
379
  quietStdioStderr: options.quietMcpStderr === true,
380
+ projectLayer: projectLayers,
344
381
  });
345
382
  // Inherited resources belong to a predecessor that is still alive: if this
346
383
  // assembly fails, the unwind must not release them out from under it.
@@ -401,15 +438,26 @@ export class AgentRuntime {
401
438
  const backgroundBash = options.inherit?.backgroundBash ?? new BackgroundBashManager(options.projectRoot, session.sessionId);
402
439
  if (options.inherit === undefined)
403
440
  startupBackgroundBash = backgroundBash;
404
- const foregroundBash = createForegroundBashTool(options.projectRoot);
441
+ // SER-082: what a model-spawned shell inherits, decided once per runtime from
442
+ // this process's environment and the config passthrough list — the persistent
443
+ // foreground shell and every `start` job, parent and children alike (children
444
+ // reuse `foregroundBash` and the manager through `childBash`), get this map.
445
+ // Names only are kept for `/status` and the startup notice; values never leave
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.
449
+ const shellPassthrough = config.shellEnv?.passthrough ?? [];
450
+ const shellEnv = scrubShellEnv(process.env, shellPassthrough);
451
+ const spawnEnv = withDarwinMarker(shellEnv.env);
452
+ const foregroundBash = createForegroundBashTool(options.projectRoot, spawnEnv);
405
453
  // The parent's wording states the runtime truth: only a driver that drains SER-069
406
454
  // task wakes, with the config key on, may tell the model that ending the turn is
407
455
  // followed by a `<task-notification>` turn. Children get the same manager and
408
456
  // foreground tool behind the no-wake wording (`childBash` below): a child's job
409
457
  // wakes the parent TUI, never the child.
410
458
  const completionWakes = options.backgroundCompletionWakes === true && config.backgroundTaskWake !== false;
411
- const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes });
412
- const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash) : bash;
459
+ const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes, env: spawnEnv });
460
+ const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash, { env: spawnEnv }) : bash;
413
461
  const imageViewer = createImageViewerTool(options.projectRoot);
414
462
  const conversationManager = new SummarizingConversationManager({
415
463
  summaryRatio: config.summaryRatio,
@@ -443,11 +491,21 @@ export class AgentRuntime {
443
491
  : undefined;
444
492
  const memoryController = config.memory === true ? new MemoryToolController(options.projectRoot, config.memoryHorizonDays ?? 28) : undefined;
445
493
  startupMemoryController = memoryController;
446
- // The fileEditor is the SDK singleton behind a same-path ordering wrapper
447
- // (SRF-020): substituted here rather than `addOrReplace`d after construction
448
- // because it is static, so the raw tool is never registered, and `childTools`
449
- // below hands children the same wrapper with per-Agent chains.
450
- const ordinaryTools = [bash, new SerializedFileEditorTool(fileEditor), imageViewer, httpRequest, webFetch];
494
+ const cloudMemory = config.agentCoreMemory === undefined ? undefined : new CloudMemory(config.agentCoreMemory, options.projectRoot, session.sessionId);
495
+ startupCloudMemory = cloudMemory;
496
+ // The fileEditor is the SDK vended tool — `makeFileEditor({ description })`, the
497
+ // same factory as the singleton with the SDK's default text plus the SRF-032
498
+ // payload bound — behind a same-path ordering wrapper (SRF-020): substituted here
499
+ // rather than `addOrReplace`d after construction because it is static, so the raw
500
+ // tool is never registered, and `childTools` below hands children the same
501
+ // wrapper with per-Agent chains.
502
+ const ordinaryTools = [
503
+ bash,
504
+ new SerializedFileEditorTool(makeFileEditor({ description: FILE_EDITOR_DESCRIPTION })),
505
+ imageViewer,
506
+ httpRequest,
507
+ webFetch,
508
+ ];
451
509
  // SER-064: the two delegation tools are the only ones the model may route to the
452
510
  // SDK's background executor; everything else — the ordinary tools by name, and by
453
511
  // wildcard whatever `initialize()` discovers later — stays foreground. Cap and
@@ -485,9 +543,20 @@ export class AgentRuntime {
485
543
  // Darwin's own hook + middleware below keep the same schedule (SER-066).
486
544
  retryStrategy: null,
487
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
+ }
488
555
  toolForName = (name) => agent.tools.find((candidate) => candidate.name === name);
489
556
  installMaxTokensRecovery(agent);
490
557
  const modelRetry = installModelRetry(agent);
558
+ // Registered inside retry: deliberate backoff is never stream inactivity.
559
+ installStreamIdleWatchdog(agent, config.streamIdleTimeoutSeconds);
491
560
  backgroundDelegation.install(agent);
492
561
  // The constructor does not initialize; the SDK defers it to the first
493
562
  // invocation. Session restore runs on InitializedEvent, MCP tools are
@@ -556,6 +625,9 @@ export class AgentRuntime {
556
625
  agent.toolRegistry.add(createUpdatePlanTool());
557
626
  if (memoryController !== undefined)
558
627
  agent.toolRegistry.add(createMemoryTools(memoryController));
628
+ if (cloudMemory !== undefined) {
629
+ agent.toolRegistry.add(createCloudMemoryTools(cloudMemory));
630
+ }
559
631
  // Children build their models through the same factory seam as the parent: in
560
632
  // production it *is* `createModelFromConfig`; offline suites can script a child
561
633
  // (`spike/verify-background-delegation.ts`) without a provider.
@@ -596,8 +668,10 @@ export class AgentRuntime {
596
668
  // session overwrites `systemPrompt` with the snapshot's copy, so composing it
597
669
  // earlier would leave a resumed run advertising the previous run's date and
598
670
  // directory listing. Applied last, it is also the only fragment a resumed
599
- // prompt can still be corrected by.
600
- 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) });
601
675
  if (!applyWorkingContext(agent, workingContext.fragment)) {
602
676
  throw new Error('Could not refresh working context on the restored system prompt.');
603
677
  }
@@ -612,9 +686,13 @@ export class AgentRuntime {
612
686
  }
613
687
  runtimeCreateCheckpoint?.('after-initialize');
614
688
  // Built last and given nothing but facts: the recorder is an observer, so it
615
- // must not be able to influence assembly. It opens no file here — the first
689
+ // must not be able to influence assembly. It creates no file here — the first
616
690
  // recorded turn creates it, so a session that never runs one leaves nothing
617
- // behind, the same rule `markResumable()` follows for the resume pointer.
691
+ // behind, the same rule `markResumable()` follows for the resume pointer. It
692
+ // does *read* an existing file's tail (SRF-031): the seed that numbers a resumed
693
+ // run's first turn `max + 1` has to be in place before `send()` can hand out a
694
+ // turn ordinal, and `create()` is the one point no driver can get ahead of.
695
+ // The wait is bounded by the recorder itself.
618
696
  const thinkingPlan = planThinking(config);
619
697
  const trajectory = config.trajectory === false
620
698
  ? undefined
@@ -643,15 +721,20 @@ export class AgentRuntime {
643
721
  }),
644
722
  },
645
723
  ...runtimeRecorderOverrides,
646
- ...(memoryController === undefined ? {} : { onTurnSettled: (settlement) => memoryController.settle(settlement) }),
724
+ ...((memoryController === undefined && cloudMemory === undefined) ? {} : { onTurnSettled: (settlement) => {
725
+ memoryController?.settle(settlement);
726
+ cloudMemory?.settle(settlement);
727
+ } }),
647
728
  });
648
729
  trajectoryAudit = trajectory;
649
- 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, {
730
+ await trajectory?.open();
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, {
650
732
  config,
651
733
  projectRoot: options.projectRoot,
652
734
  permissionMode,
653
735
  sessionId: session.sessionId,
654
736
  resumed: session.restoreRequested && agent.messages.length > 0,
737
+ ...(session.leaseNotice === undefined ? {} : { leaseNotice: session.leaseNotice }),
655
738
  skillNames: skills.skills.map((skill) => skill.name),
656
739
  skillProblems: skills.problems.map((problem) => ({ ...problem })),
657
740
  commandNames: commands.commands.map((command) => command.name),
@@ -660,8 +743,14 @@ export class AgentRuntime {
660
743
  agentProblems: agentDefinitions.problems.map((problem) => ({ ...problem })),
661
744
  projectInstructions: instructions === undefined
662
745
  ? undefined
663
- : { path: instructions.path, bytes: instructions.bytes, truncated: instructions.truncated },
746
+ : {
747
+ filename: instructions.filename,
748
+ path: instructions.path,
749
+ bytes: instructions.bytes,
750
+ truncated: instructions.truncated,
751
+ },
664
752
  projectInstructionsProblem: loadedInstructions.problem,
753
+ projectInstructionsProblemFile: loadedInstructions.problemFile,
665
754
  systemPromptSource: basePrompt.source,
666
755
  systemPromptPath: basePrompt.path,
667
756
  systemPromptProblem: basePrompt.problem,
@@ -681,6 +770,8 @@ export class AgentRuntime {
681
770
  ...notice,
682
771
  shadowed: [...notice.shadowed],
683
772
  })),
773
+ shellEnv: { withheld: [...shellEnv.withheld], passthrough: [...shellPassthrough] },
774
+ workspaceTrust: workspaceTrustReport(options.workspaceTrust),
684
775
  mcpIgnoredConfigPath: mcp.ignoredConfigPath,
685
776
  mcpServerCount: mcp.clients.length,
686
777
  toolNames: agent.tools.map((tool) => tool.name).sort(),
@@ -698,7 +789,8 @@ export class AgentRuntime {
698
789
  return runtime;
699
790
  };
700
791
  return assemble().catch(async (error) => {
701
- 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();
702
794
  throw error;
703
795
  });
704
796
  }
@@ -746,6 +838,7 @@ export class AgentRuntime {
746
838
  if (submitted !== undefined && !submitted.allowed) {
747
839
  throw new Error(submitted.reason ?? 'UserPromptSubmit hook blocked this prompt.');
748
840
  }
841
+ const cloudGeneration = await this.prepareCloudPreferences();
749
842
  const modelInput = injectCodexContext(input, submitted?.context);
750
843
  let checkpointId;
751
844
  // A text-only checkpoint cannot truthfully reproduce a multimodal boundary.
@@ -753,7 +846,15 @@ export class AgentRuntime {
753
846
  checkpointId = await this.captureRewindCheckpoint();
754
847
  }
755
848
  let completed = false;
849
+ // A refusal-class stop (SRF-030): the SDK loop still ran to its end and appended
850
+ // both messages, so the pre-prompt checkpoint is a valid rewind boundary — the
851
+ // one that removes the declined exchange. Read only by the catalogue call below;
852
+ // memory sealing and terminal delivery keep meaning `endTurn`.
853
+ let refused = false;
756
854
  let sealed = false;
855
+ let naturallyCompleted = false;
856
+ let uploadTurn;
857
+ let streamStarted = false;
757
858
  try {
758
859
  // A multimodal turn's durable text is the literal submitted prompt. Expanded
759
860
  // command text and held shell reports still reach the model, but image bytes
@@ -768,6 +869,10 @@ export class AgentRuntime {
768
869
  // actually submitted. Drivers pass that raw text as the second argument. A
769
870
  // session-originated wake has no user text to quote from at all.
770
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
+ }
771
876
  // The current input is the one exception to fire-and-forget recording: make it
772
877
  // readable to offline observers before Agent.stream() can invoke a provider or
773
878
  // tool. The recorder owns the bound and resolves on write failure/timeout, so
@@ -783,10 +888,18 @@ export class AgentRuntime {
783
888
  // next SDK event, so the recorder and every driver see one ordinary
784
889
  // before/after pair for a delegation the model routed to the background.
785
890
  const invocation = image === undefined ? modelInput : [new TextBlock(modelInput), image];
891
+ this.checkCloudPreparation(cloudGeneration);
892
+ streamStarted = true;
786
893
  const stream = this.backgroundDelegation.observe(this.agent.stream(invocation));
787
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();
788
899
  if (event.type === 'agentResultEvent' && event.result.stopReason === 'endTurn')
789
900
  completed = true;
901
+ if (event.type === 'agentResultEvent' && isRefusalStop(event.result.stopReason))
902
+ refused = true;
790
903
  // Observed at the same point `recordStream` observes: synchronously, between
791
904
  // `stream()` and the `yield`, so `/usage` asked mid-turn already counts the
792
905
  // calls that completed. Cannot throw — see {@link observeCallStats}.
@@ -798,22 +911,29 @@ export class AgentRuntime {
798
911
  }
799
912
  this.memoryController?.seal(completed && this.trajectory?.status.active !== false);
800
913
  sealed = true;
801
- if (completed && checkpointId !== undefined) {
914
+ if ((completed || refused) && checkpointId !== undefined) {
802
915
  const catalogue = await appendRewindCheckpoint(this.projectRoot, this.info.sessionId, {
803
916
  snapshotId: checkpointId,
804
917
  prompt: input,
805
918
  completedAt: new Date().toISOString(),
919
+ ...(recording === undefined ? {} : { trajectoryTurn: recording.turn }),
806
920
  });
807
921
  if (catalogue.problem !== undefined) {
808
922
  this.diagnosticsLog?.notice(`rewind checkpoint not catalogued: ${catalogue.problem}`, 'warn');
809
923
  }
810
924
  }
925
+ naturallyCompleted = true;
811
926
  }
812
927
  finally {
928
+ if (uploadTurn !== undefined)
929
+ this.cloudMemory?.sealTurn(uploadTurn, naturallyCompleted && completed && cloudGeneration === this.cloudMemory.cancelGeneration);
813
930
  // Seeing an endTurn event is not enough when the consumer abandons this
814
931
  // generator before natural completion: only the natural path above seals.
815
932
  if (!sealed)
816
933
  this.memoryController?.discard();
934
+ this.cloudMemory?.uploadObserver?.end();
935
+ if (uploadTurn !== undefined && (!streamStarted || this.trajectory?.status.active === false))
936
+ this.cloudMemory?.discardTurn(uploadTurn);
817
937
  // Only a turn that ran to `endTurn` commits what its `wait`/`status` results
818
938
  // delivered; an abandoned or failed turn forgets them, so the wake still fires.
819
939
  this.terminalDelivery.closeTurn(sealed && completed);
@@ -896,10 +1016,49 @@ export class AgentRuntime {
896
1016
  get memoryStatus() {
897
1017
  return this.memoryController?.status;
898
1018
  }
899
- /**
900
- * Runs the user-only local `/memory` command and refreshes the verified Darwin-owned
901
- * prompt block before a successful mutation returns. No Agent invocation is made.
902
- */
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
+ }
903
1062
  async manageMemory(input) {
904
1063
  if (this.liveConfig.memory !== true) {
905
1064
  return { changed: false, text: 'project memory is off — remove memory: false if set, and enable trajectory recording in ~/.darwin/config.json' };
@@ -929,6 +1088,8 @@ export class AgentRuntime {
929
1088
  const pre = await this.codexHooks?.preCompact('manual');
930
1089
  if (pre !== undefined && !pre.allowed)
931
1090
  throw new Error(pre.reason ?? 'PreCompact hook blocked compaction.');
1091
+ const cloudGeneration = await this.prepareCloudPreferences();
1092
+ this.checkCloudPreparation(cloudGeneration);
932
1093
  try {
933
1094
  const result = await compactConversation({
934
1095
  agent: this.agent,
@@ -1050,7 +1211,16 @@ export class AgentRuntime {
1050
1211
  */
1051
1212
  async saveAllowRule(rule) {
1052
1213
  this.gate.addAllowRule(rule);
1053
- 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' };
1054
1224
  }
1055
1225
  /**
1056
1226
  * The live allow-rules with their provenance — config-loaded vs granted this
@@ -1096,7 +1266,9 @@ export class AgentRuntime {
1096
1266
  */
1097
1267
  revokeAllowRules(rules) {
1098
1268
  const removed = rules.filter((rule) => this.gate.removeAllowRule(rule));
1099
- 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());
1100
1272
  return { removed, saved };
1101
1273
  }
1102
1274
  /**
@@ -1225,6 +1397,7 @@ export class AgentRuntime {
1225
1397
  * describe a model that is no longer there.
1226
1398
  */
1227
1399
  async changeModel(target) {
1400
+ await this.refreshCloudPolicy();
1228
1401
  const next = withModelChoice(this.liveConfig, target);
1229
1402
  // Built before anything is mutated: a failure here (a missing peer dependency,
1230
1403
  // a bad region) must leave the session on the model it was already using. Same
@@ -1466,6 +1639,13 @@ export class AgentRuntime {
1466
1639
  listBackgroundTasks() {
1467
1640
  return this.backgroundBash.list();
1468
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
+ }
1469
1649
  /** Publishes future terminal task snapshots until the returned closure is called. */
1470
1650
  subscribeToBackgroundTasks(listener) {
1471
1651
  return this.backgroundBash.subscribe(listener);
@@ -1533,6 +1713,7 @@ export class AgentRuntime {
1533
1713
  * ends with `stopReason: 'cancelled'` rather than throwing.
1534
1714
  */
1535
1715
  cancel() {
1716
+ this.cloudMemory?.cancel();
1536
1717
  this.lifecycleHooks?.cancel();
1537
1718
  this.codexHooks?.cancel();
1538
1719
  this.subagents.cancelActive();
@@ -1587,6 +1768,8 @@ export class AgentRuntime {
1587
1768
  */
1588
1769
  async startRewind(checkpoint) {
1589
1770
  this.refuseWhileDelegationsTracked('/rewind');
1771
+ await this.cloudMemory?.stopAutoForSuccessor();
1772
+ await this.refreshCloudPolicy();
1590
1773
  const catalogue = await readRewindCatalogue(this.projectRoot, this.info.sessionId);
1591
1774
  if (catalogue.problem !== undefined)
1592
1775
  throw new Error(catalogue.problem);
@@ -1651,8 +1834,8 @@ export class AgentRuntime {
1651
1834
  * the user the conversation they just set aside. The successor claims the pointer on
1652
1835
  * its first finished turn, through the ordinary path.
1653
1836
  *
1654
- * If assembling the successor fails, this runtime stays fully usable: nothing it owns
1655
- * 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
1656
1839
  * (the failed successor's unwind clears the process-global sink).
1657
1840
  *
1658
1841
  * Refused while a background delegation is tracked (SER-070): `retire()` would cancel
@@ -1662,6 +1845,8 @@ export class AgentRuntime {
1662
1845
  */
1663
1846
  async startNewSession() {
1664
1847
  this.refuseWhileDelegationsTracked('/clear');
1848
+ await this.cloudMemory?.stopAutoForSuccessor();
1849
+ await this.refreshCloudPolicy();
1665
1850
  let successor;
1666
1851
  try {
1667
1852
  successor = await AgentRuntime.create({
@@ -1715,13 +1900,16 @@ export class AgentRuntime {
1715
1900
  ]);
1716
1901
  // Closing trajectory first publishes the final settlement. The controller then
1717
1902
  // discards unresolved staging and waits only for commits already accepted.
1718
- 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()]);
1719
1904
  // SessionEnd is the final advisory boundary: all session-owned work above has
1720
1905
  // settled, while diagnostics remains open to retain a bounded hook problem.
1721
1906
  await Promise.allSettled([
1722
1907
  this.codexHooks?.sessionEnd('other').then(() => this.codexHooks?.close()) ?? Promise.resolve(),
1723
1908
  ]);
1724
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();
1725
1913
  }
1726
1914
  /**
1727
1915
  * Creates one bounded rewind snapshot, serialized so concurrent callers cannot
@@ -1758,10 +1946,15 @@ export class AgentRuntime {
1758
1946
  }
1759
1947
  /**
1760
1948
  * Expands a built-in prompt command, a skill, or a project command into the
1761
- * prompt sent to the model. `/workflow` is checked first: built-in
1949
+ * prompt sent to the model. `/workflow`, `/init` and `/review` come first: built-in
1762
1950
  * reservation precedes skills and custom commands, so no extension can
1763
- * shadow it. Its bare form returns null — the drivers own that local usage
1764
- * notice, and the runtime never fabricates a turn. Skills are checked before
1951
+ * shadow them. Bare `/workflow` returns null — the drivers own that local usage
1952
+ * notice, and the runtime never fabricates a turn — while bare `/init` is the
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
1955
+ * summary this runtime captured at startup (the header's own data), never from
1956
+ * a fresh filesystem read, so TUI, dev-repl and both headless drivers get the
1957
+ * same branch through this one seam. Skills are checked before
1765
1958
  * custom commands as a defensive backstop to the loader's collision
1766
1959
  * filtering. Unknown slash input remains ordinary user input.
1767
1960
  */
@@ -1771,6 +1964,15 @@ export class AgentRuntime {
1771
1964
  return null;
1772
1965
  if (workflow !== null)
1773
1966
  return { kind: 'workflow', ...workflow };
1967
+ const init = parseInitCommand(input, {
1968
+ loaded: this.info.projectInstructions,
1969
+ problemFile: this.info.projectInstructionsProblemFile,
1970
+ });
1971
+ if (init !== null)
1972
+ return { kind: 'init', ...init };
1973
+ const review = parseReviewCommand(input);
1974
+ if (review !== null)
1975
+ return { kind: 'review', ...review };
1774
1976
  const skill = await expandSkillCommand(this.skills, input);
1775
1977
  if (skill !== null)
1776
1978
  return { kind: 'skill', ...skill };
@@ -1784,6 +1986,7 @@ export class AgentRuntime {
1784
1986
  * exiting.
1785
1987
  */
1786
1988
  async shutdown(options = {}) {
1989
+ this.cloudMemory?.cancel();
1787
1990
  const results = await Promise.allSettled([
1788
1991
  this.subagents.shutdown(),
1789
1992
  this.workflows.shutdown(),
@@ -1795,7 +1998,7 @@ export class AgentRuntime {
1795
1998
  // unawaited; cleanup only waits for a commit after durable acceptance.
1796
1999
  this.trajectory?.close() ?? Promise.resolve(),
1797
2000
  ]);
1798
- 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()]);
1799
2002
  results.push(...memoryResults);
1800
2003
  // SessionEnd is advisory but ordered after owned work. Keep diagnostics open
1801
2004
  // through it, then detach the process-global SDK tap before closing the file.
@@ -1805,6 +2008,10 @@ export class AgentRuntime {
1805
2008
  if (this.diagnosticsLog !== undefined)
1806
2009
  setSdkVerboseSink(undefined);
1807
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();
1808
2015
  const failures = results.flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
1809
2016
  if (options.throwOnError === true && failures.length > 0) {
1810
2017
  throw new AggregateError(failures, `${failures.length} runtime cleanup operation(s) failed`);