strands-darwin 0.0.32 → 0.0.34

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 (117) hide show
  1. package/README.md +3 -1
  2. package/README.zh-CN.md +3 -1
  3. package/dist/src/agent/background-delegation.d.ts +69 -11
  4. package/dist/src/agent/background-delegation.js +156 -28
  5. package/dist/src/agent/background-delegation.js.map +1 -1
  6. package/dist/src/agent/cache-miss.d.ts +143 -0
  7. package/dist/src/agent/cache-miss.js +182 -0
  8. package/dist/src/agent/cache-miss.js.map +1 -0
  9. package/dist/src/agent/compact.d.ts +28 -0
  10. package/dist/src/agent/compact.js +34 -0
  11. package/dist/src/agent/compact.js.map +1 -1
  12. package/dist/src/agent/context-breakdown.d.ts +109 -0
  13. package/dist/src/agent/context-breakdown.js +116 -0
  14. package/dist/src/agent/context-breakdown.js.map +1 -0
  15. package/dist/src/agent/instructions.d.ts +1 -1
  16. package/dist/src/agent/instructions.js.map +1 -1
  17. package/dist/src/agent/permission-rules.d.ts +81 -2
  18. package/dist/src/agent/permission-rules.js +226 -6
  19. package/dist/src/agent/permission-rules.js.map +1 -1
  20. package/dist/src/agent/permission.d.ts +116 -2
  21. package/dist/src/agent/permission.js +201 -26
  22. package/dist/src/agent/permission.js.map +1 -1
  23. package/dist/src/agent/prompt-cache.d.ts +12 -3
  24. package/dist/src/agent/prompt-cache.js +12 -3
  25. package/dist/src/agent/prompt-cache.js.map +1 -1
  26. package/dist/src/agent/runtime.d.ts +141 -1
  27. package/dist/src/agent/runtime.js +259 -13
  28. package/dist/src/agent/runtime.js.map +1 -1
  29. package/dist/src/agent/task-terminal-delivery.d.ts +43 -0
  30. package/dist/src/agent/task-terminal-delivery.js +115 -0
  31. package/dist/src/agent/task-terminal-delivery.js.map +1 -0
  32. package/dist/src/agents/child-recipe.d.ts +9 -1
  33. package/dist/src/agents/child-recipe.js +2 -0
  34. package/dist/src/agents/child-recipe.js.map +1 -1
  35. package/dist/src/agents/dispatch-registry.d.ts +18 -0
  36. package/dist/src/agents/dispatch-registry.js +2 -0
  37. package/dist/src/agents/dispatch-registry.js.map +1 -1
  38. package/dist/src/agents/retained-children.d.ts +101 -0
  39. package/dist/src/agents/retained-children.js +101 -0
  40. package/dist/src/agents/retained-children.js.map +1 -0
  41. package/dist/src/agents/subagent-tool.d.ts +56 -1
  42. package/dist/src/agents/subagent-tool.js +148 -10
  43. package/dist/src/agents/subagent-tool.js.map +1 -1
  44. package/dist/src/agents/workflow-tool.d.ts +2 -0
  45. package/dist/src/agents/workflow-tool.js +1 -1
  46. package/dist/src/agents/workflow-tool.js.map +1 -1
  47. package/dist/src/cli-doctor.js +3 -1
  48. package/dist/src/cli-doctor.js.map +1 -1
  49. package/dist/src/cli-main.js +14 -3
  50. package/dist/src/cli-main.js.map +1 -1
  51. package/dist/src/commands/custom-commands.js +5 -4
  52. package/dist/src/commands/custom-commands.js.map +1 -1
  53. package/dist/src/config.d.ts +57 -6
  54. package/dist/src/config.js +43 -16
  55. package/dist/src/config.js.map +1 -1
  56. package/dist/src/headless-protocol.d.ts +1 -1
  57. package/dist/src/headless-runner.js +7 -2
  58. package/dist/src/headless-runner.js.map +1 -1
  59. package/dist/src/hooks/tool-hooks.js +10 -6
  60. package/dist/src/hooks/tool-hooks.js.map +1 -1
  61. package/dist/src/skills/builtin/self-evolution-research/SKILL.md +14 -1
  62. package/dist/src/skills/prompt.d.ts +17 -0
  63. package/dist/src/skills/prompt.js +20 -0
  64. package/dist/src/skills/prompt.js.map +1 -1
  65. package/dist/src/tools/background-bash.d.ts +11 -2
  66. package/dist/src/tools/background-bash.js +11 -5
  67. package/dist/src/tools/background-bash.js.map +1 -1
  68. package/dist/src/tools/background-tail.d.ts +1 -0
  69. package/dist/src/tools/background-tail.js +2 -1
  70. package/dist/src/tools/background-tail.js.map +1 -1
  71. package/dist/src/tools/background-wait-contract.d.ts +7 -0
  72. package/dist/src/tools/background-wait-contract.js +17 -0
  73. package/dist/src/tools/background-wait-contract.js.map +1 -1
  74. package/dist/src/trajectory/record.d.ts +212 -2
  75. package/dist/src/trajectory/record.js +138 -0
  76. package/dist/src/trajectory/record.js.map +1 -1
  77. package/dist/src/trajectory/replay.d.ts +34 -1
  78. package/dist/src/trajectory/replay.js +148 -4
  79. package/dist/src/trajectory/replay.js.map +1 -1
  80. package/dist/src/trajectory/resume-recap.js +10 -3
  81. package/dist/src/trajectory/resume-recap.js.map +1 -1
  82. package/dist/src/trajectory/spend.d.ts +14 -1
  83. package/dist/src/trajectory/spend.js +40 -6
  84. package/dist/src/trajectory/spend.js.map +1 -1
  85. package/dist/src/trajectory/writer.d.ts +57 -6
  86. package/dist/src/trajectory/writer.js +141 -9
  87. package/dist/src/trajectory/writer.js.map +1 -1
  88. package/dist/src/tui/App.d.ts +8 -4
  89. package/dist/src/tui/App.js +302 -55
  90. package/dist/src/tui/App.js.map +1 -1
  91. package/dist/src/tui/background-tool-presentation.js +2 -2
  92. package/dist/src/tui/background-tool-presentation.js.map +1 -1
  93. package/dist/src/tui/context-format.d.ts +16 -0
  94. package/dist/src/tui/context-format.js +41 -0
  95. package/dist/src/tui/context-format.js.map +1 -1
  96. package/dist/src/tui/prompt-queue.d.ts +52 -8
  97. package/dist/src/tui/prompt-queue.js +68 -8
  98. package/dist/src/tui/prompt-queue.js.map +1 -1
  99. package/dist/src/tui/status-format.d.ts +35 -16
  100. package/dist/src/tui/status-format.js +67 -8
  101. package/dist/src/tui/status-format.js.map +1 -1
  102. package/dist/src/tui/subagent-format.d.ts +8 -0
  103. package/dist/src/tui/subagent-format.js +24 -1
  104. package/dist/src/tui/subagent-format.js.map +1 -1
  105. package/dist/src/tui/task-wake.d.ts +75 -0
  106. package/dist/src/tui/task-wake.js +201 -0
  107. package/dist/src/tui/task-wake.js.map +1 -0
  108. package/dist/src/tui/terminal-notify.d.ts +40 -0
  109. package/dist/src/tui/terminal-notify.js +136 -0
  110. package/dist/src/tui/terminal-notify.js.map +1 -0
  111. package/dist/src/tui/terminal-title.d.ts +94 -0
  112. package/dist/src/tui/terminal-title.js +121 -0
  113. package/dist/src/tui/terminal-title.js.map +1 -0
  114. package/dist/src/tui/turn-state.d.ts +10 -1
  115. package/dist/src/tui/turn-state.js +17 -1
  116. package/dist/src/tui/turn-state.js.map +1 -1
  117. package/package.json +1 -1
@@ -13,7 +13,7 @@ import { LocalFileStorage } from '@strands-agents/sdk/storage';
13
13
  import path from 'node:path';
14
14
  import { compactConversation, countConversationTokens, createCompactionManager, normalizeCompactFocus, stripReasoningFromUserMessages, } from './compact.js';
15
15
  import { DiagnosticsLog } from './diagnostics.js';
16
- import { BackgroundDelegationObserver, backgroundDelegationConfig, MANAGE_BACKGROUND_TASK_TOOL_NAME, } from './background-delegation.js';
16
+ import { BackgroundDelegationObserver, backgroundDelegationConfig, liveBackgroundDelegationRefusal, MANAGE_BACKGROUND_TASK_TOOL_NAME, } from './background-delegation.js';
17
17
  import { installMaxTokensRecovery } from './max-tokens-recovery.js';
18
18
  import { installModelCallBudget } from './model-call-budget.js';
19
19
  import { installModelRetry } from './model-retry.js';
@@ -44,6 +44,8 @@ import { createMemoryTools } from '../memory/tools.js';
44
44
  import { recordStream } from '../trajectory/stream.js';
45
45
  import { TrajectoryRecorder, } from '../trajectory/writer.js';
46
46
  import { DARWIN_VERSION } from '../version.js';
47
+ import { TerminalDeliveryLedger } from './task-terminal-delivery.js';
48
+ import { measureContextBreakdown } from './context-breakdown.js';
47
49
  import { composeSystemPrompt, loadProjectInstructions, } from './instructions.js';
48
50
  import { PermissionGate } from './permission.js';
49
51
  import { applySystemPromptCachePoint, canUpdateSystemPromptCache, planPromptCache, } from './prompt-cache.js';
@@ -54,8 +56,9 @@ import { loadSystemPrompt } from './system-prompt.js';
54
56
  import { applyWorkingContext, buildWorkingContext } from './working-context.js';
55
57
  import { planThinking } from './thinking.js';
56
58
  import { MAX_REWIND_CHECKPOINTS, appendRewindCheckpoint, newestRewindCheckpoints, readRewindCatalogue, rewindPromptEligible, } from './rewind.js';
57
- import { deltaUsage, startCallSpend, startTurnSpend, sumUsage } from './usage.js';
58
- import { emptyCallStats, recordCompletedCall, } from './call-stats.js';
59
+ import { deltaUsage, requestInputTokens, startCallSpend, startTurnSpend, sumUsage, usageBuckets } from './usage.js';
60
+ import { emptyCallStats, readCallUsage, recordCompletedCall, } from './call-stats.js';
61
+ import { CacheMissTracker, promptCacheTtlMs } from './cache-miss.js';
59
62
  import { anchorFromCall, resolveAnchor } from './context-anchor.js';
60
63
  import { defaultModelPriceStore } from '../pricing/model-prices.js';
61
64
  let runtimeCreateCheckpoint;
@@ -77,6 +80,27 @@ export function setRuntimeRecorderOverridesForTest(overrides) {
77
80
  * previous snapshots from `--resume`.
78
81
  */
79
82
  const AGENT_ID = 'darwin';
83
+ /**
84
+ * The gate's published decision as the recorder's structural record fields (SER-079).
85
+ *
86
+ * The two shapes are spelled independently on purpose — `src/trajectory/**` imports
87
+ * no gate type — and this is the one seam where they meet, so a field the gate adds
88
+ * tomorrow does not reach the file until someone names it here. Copies exactly the
89
+ * audit fields; there is no input on the gate's object to leave out.
90
+ */
91
+ function permissionDecisionEntry(decision) {
92
+ return {
93
+ toolUseId: decision.toolUseId,
94
+ toolName: decision.toolName,
95
+ kind: decision.kind,
96
+ risk: decision.risk,
97
+ mode: decision.mode,
98
+ source: decision.source,
99
+ outcome: decision.outcome,
100
+ ...(decision.rule === undefined ? {} : { rule: decision.rule }),
101
+ promptedUser: decision.promptedUser,
102
+ };
103
+ }
80
104
  /**
81
105
  * Parent-registered tools that never enter the child catalogue: the offloader's
82
106
  * retrieval tool (parent-session storage) and both network tools (children are
@@ -166,6 +190,25 @@ export class AgentRuntime {
166
190
  * `/context` to the plain heuristic line rather than to a wrong number.
167
191
  */
168
192
  contextAnchorBroken = false;
193
+ /**
194
+ * Why the prompt cache missed, per completed call (SER-074): the same
195
+ * `afterModelCallEvent` counters the call stats fold, joined with the invalidating
196
+ * events this runtime performed (`/model`, `/effort`, `/compact`) and the TTL.
197
+ * Parent-only and session-scoped like the two observers above; built in the
198
+ * constructor so `/clear`'s successor starts empty. Read through
199
+ * {@link cacheMissReport} and {@link cacheWarmth}, both silent unless the live
200
+ * cache plan has Darwin-managed cache points.
201
+ */
202
+ cacheMisses;
203
+ /** Latched on the first tracker failure — its own latch, so it cannot break the others. */
204
+ cacheMissesBroken = false;
205
+ /**
206
+ * Which background jobs' terminal states completed turns already carried to the
207
+ * model through `wait`/`status` results (SER-069): the interactive drain asks it
208
+ * before sending a wake, so a job the model already saw finish never starts a
209
+ * duplicate turn. Session-scoped like the anchor; a `/clear` successor starts empty.
210
+ */
211
+ terminalDelivery = new TerminalDeliveryLedger();
169
212
  /** Serializes the bounded list/save/list critical section across concurrent callers. */
170
213
  rewindCaptureTail = Promise.resolve();
171
214
  /**
@@ -227,6 +270,7 @@ export class AgentRuntime {
227
270
  this.thinkingPlan = info.thinking;
228
271
  this.liveConfig = info.config;
229
272
  this.promptCachePlan = info.promptCache;
273
+ this.cacheMisses = new CacheMissTracker(() => promptCacheTtlMs(this.promptCachePlan.ttl), info.resumed);
230
274
  // Fire and forget: a mapped id costs one file read, an unmapped one starts the
231
275
  // single bounded background fetch. Nothing awaits it — not startup, not the
232
276
  // first turn — and it cannot reject, so it cannot become a startup failure.
@@ -307,16 +351,24 @@ export class AgentRuntime {
307
351
  // children that do not exist yet, and only the narrow resolver crosses over —
308
352
  // the permission layer never learns about the delegation tool itself.
309
353
  const subagentDispatches = new SubagentDispatchRegistry();
354
+ // The recorder is built last (below), after the Agent, so the gate's audit
355
+ // observer binds to it late: a decision published before the binding — none
356
+ // can be, since no turn runs during assembly — or with recording off is dropped.
357
+ let trajectoryAudit;
310
358
  const gate = new PermissionGate({
311
359
  mode: permissionMode,
312
360
  projectRoot: options.projectRoot,
313
361
  ask: options.permissionBridge,
314
362
  allowRules: policy.allowRules,
363
+ denyRules: policy.denyRules,
315
364
  dispatchSource: (agentId) => subagentDispatches.sourceFor(agentId),
316
365
  // Built for every run, not only an `auto` one: `/mode auto` can arrive
317
366
  // mid-session and the gate must have a classifier to consult. Costs nothing
318
367
  // until it is used — the closure defers building its model to the first call.
319
368
  classifier: createModelClassifier(config, options.projectRoot),
369
+ // SER-079: one bounded `permissionDecision` record per settled decision. The
370
+ // adapter below is the only place the gate's object meets the record's shape.
371
+ onDecision: (decision) => trajectoryAudit?.recordPermissionDecision(permissionDecisionEntry(decision)),
320
372
  });
321
373
  const codexHooks = policy.codexHooks === undefined ? undefined : new CodexHookRunner({
322
374
  projectRoot: options.projectRoot,
@@ -340,15 +392,24 @@ export class AgentRuntime {
340
392
  : new LifecycleHookRunner(options.projectRoot, lifecycleConfig);
341
393
  startupLifecycleHooks = lifecycleHooks;
342
394
  const sessionManager = createSessionManager(options.projectRoot, session.sessionId);
343
- // One manager and wrapper are shared by the main Agent and every child tool
344
- // catalogue. Foreground calls still delegate with the caller's ToolContext.
395
+ // One manager is shared by the main Agent and every child tool catalogue; the
396
+ // wrapper differs only in wording (see `childBash`). Foreground calls still
397
+ // delegate with the caller's ToolContext.
345
398
  // Across `/clear` the manager is inherited, not rebuilt: its jobs are running
346
399
  // processes owned by this process, and a second manager would leave them
347
400
  // unlistable and unreaped.
348
401
  const backgroundBash = options.inherit?.backgroundBash ?? new BackgroundBashManager(options.projectRoot, session.sessionId);
349
402
  if (options.inherit === undefined)
350
403
  startupBackgroundBash = backgroundBash;
351
- const bash = createBackgroundBashTool(backgroundBash, createForegroundBashTool(options.projectRoot));
404
+ const foregroundBash = createForegroundBashTool(options.projectRoot);
405
+ // The parent's wording states the runtime truth: only a driver that drains SER-069
406
+ // task wakes, with the config key on, may tell the model that ending the turn is
407
+ // followed by a `<task-notification>` turn. Children get the same manager and
408
+ // foreground tool behind the no-wake wording (`childBash` below): a child's job
409
+ // wakes the parent TUI, never the child.
410
+ const completionWakes = options.backgroundCompletionWakes === true && config.backgroundTaskWake !== false;
411
+ const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes });
412
+ const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash) : bash;
352
413
  const imageViewer = createImageViewerTool(options.projectRoot);
353
414
  const conversationManager = new SummarizingConversationManager({
354
415
  summaryRatio: config.summaryRatio,
@@ -391,7 +452,9 @@ export class AgentRuntime {
391
452
  // SDK's background executor; everything else — the ordinary tools by name, and by
392
453
  // wildcard whatever `initialize()` discovers later — stays foreground. Cap and
393
454
  // delegation tools are the parent's; children are built by `buildRecipeChild`
394
- // and never receive this option.
455
+ // and never receive this option. SER-070: only a waking driver lets the dispatching
456
+ // turn end with the child running (`waitForCompletion: false`); headless keeps the
457
+ // SDK's in-invocation wait so its one run still contains the report.
395
458
  const backgroundDelegationTools = [SUBAGENT_TOOL_NAME, WORKFLOW_TOOL_NAME];
396
459
  const backgroundDelegation = new BackgroundDelegationObserver(backgroundDelegationTools);
397
460
  const agent = new Agent({
@@ -412,6 +475,7 @@ export class AgentRuntime {
412
475
  delegationTools: backgroundDelegationTools,
413
476
  ordinaryToolNames: ordinaryTools.map((tool) => tool.name),
414
477
  maxConcurrency: concurrencyCap(config),
478
+ completionWakes,
415
479
  }),
416
480
  // Required: the SDK's own printer writes to stdout and would interleave
417
481
  // with our rendering (and fight Ink for the terminal in step 5).
@@ -484,7 +548,8 @@ export class AgentRuntime {
484
548
  // plugin/storage contract, so never hand them a dangling retrieval tool.
485
549
  // Network access (`http_request`, `web_fetch`) stays parent-only too: the
486
550
  // documented invariant is that children work on reads inside the workspace.
487
- const childTools = agent.tools.filter((tool) => !PARENT_ONLY_TOOL_NAMES.has(tool.name));
551
+ const childTools = agent.tools.filter((tool) => !PARENT_ONLY_TOOL_NAMES.has(tool.name))
552
+ .map((tool) => (tool.name === 'bash' ? childBash : tool));
488
553
  const agentDefinitions = await loadAgentDefinitions(options.projectRoot, childTools.map((tool) => tool.name));
489
554
  // Progress belongs to the parent turn. Register only after the child catalogue
490
555
  // and allowlists are fixed, so no child can author an unrelated checklist.
@@ -503,6 +568,7 @@ export class AgentRuntime {
503
568
  config,
504
569
  createModel: createChildModel,
505
570
  dispatches: subagentDispatches,
571
+ backgroundCompletionWakes: completionWakes,
506
572
  ...(codexHooks === undefined ? {} : { codexHooks }),
507
573
  });
508
574
  agent.toolRegistry.add(subagents.tool);
@@ -516,6 +582,7 @@ export class AgentRuntime {
516
582
  config,
517
583
  createModel: createChildModel,
518
584
  dispatches: subagentDispatches,
585
+ backgroundCompletionWakes: completionWakes,
519
586
  ...(codexHooks === undefined ? {} : { codexHooks }),
520
587
  });
521
588
  agent.toolRegistry.add(workflows.tool);
@@ -563,10 +630,22 @@ export class AgentRuntime {
563
630
  thinkingEffort: thinkingPlan.effective,
564
631
  resumed: session.restoreRequested && agent.messages.length > 0,
565
632
  restoredMessages: agent.messages.length,
633
+ // A rewind successor is `resumed: false` with a restored count the
634
+ // record could not otherwise explain (SRF-028): name the checkpoint
635
+ // it branched from. Absent — not undefined — for every other session.
636
+ ...(options.rewindRestore === undefined
637
+ ? {}
638
+ : {
639
+ rewindFrom: {
640
+ session: options.rewindRestore.sourceSessionId,
641
+ snapshotId: options.rewindRestore.snapshotId,
642
+ },
643
+ }),
566
644
  },
567
645
  ...runtimeRecorderOverrides,
568
646
  ...(memoryController === undefined ? {} : { onTurnSettled: (settlement) => memoryController.settle(settlement) }),
569
647
  });
648
+ trajectoryAudit = trajectory;
570
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, {
571
650
  config,
572
651
  projectRoot: options.projectRoot,
@@ -586,6 +665,7 @@ export class AgentRuntime {
586
665
  systemPromptSource: basePrompt.source,
587
666
  systemPromptPath: basePrompt.path,
588
667
  systemPromptProblem: basePrompt.problem,
668
+ promptSections: { base: basePromptText, instructions: instructions?.fragment },
589
669
  workingContextProblem: workingContext.problem,
590
670
  promptCache,
591
671
  // Recomputed rather than returned from createModelFromConfig: the model
@@ -647,8 +727,15 @@ export class AgentRuntime {
647
727
  *
648
728
  * One `before` snapshot feeds both the meter and `lastTurnDelta`, so what the record
649
729
  * says a turn cost and what `/usage` says it cost cannot be two different readings.
730
+ *
731
+ * `origin` marks a turn the session started rather than the user (SER-069, a
732
+ * background-task wake): the opening record is then a `taskNotification` carrying
733
+ * the literal `userInput` text, no `userInput` line is written, no rewind
734
+ * checkpoint is catalogued (the chooser lists the user's prompts) and memory gets
735
+ * no user quote to anchor to. Everything else — hooks, gate, recording, delivery
736
+ * ledger — is the ordinary turn.
650
737
  */
651
- async *send(input, userInput = input, image) {
738
+ async *send(input, userInput = input, image, origin) {
652
739
  const before = this.usage;
653
740
  // The config this turn is attributed to, for the recorded spend and the in-process
654
741
  // per-model tally alike. `/model` is refused while a turn is busy, so the live
@@ -662,7 +749,7 @@ export class AgentRuntime {
662
749
  const modelInput = injectCodexContext(input, submitted?.context);
663
750
  let checkpointId;
664
751
  // A text-only checkpoint cannot truthfully reproduce a multimodal boundary.
665
- if (image === undefined && rewindPromptEligible(input)) {
752
+ if (image === undefined && origin === undefined && rewindPromptEligible(input)) {
666
753
  checkpointId = await this.captureRewindCheckpoint();
667
754
  }
668
755
  let completed = false;
@@ -675,11 +762,12 @@ export class AgentRuntime {
675
762
  // The per-call spend projector, injected beside the turn meter and for its
676
763
  // reason: the `modelCall` record needs the live provider/model config, which
677
764
  // `src/trajectory/**` must never import.
678
- startCallSpend(turnConfig));
765
+ startCallSpend(turnConfig), origin);
679
766
  // The model may receive an expanded skill/custom-command prompt, but
680
767
  // preference/identity provenance is allowed to quote only what the user
681
- // actually submitted. Drivers pass that raw text as the second argument.
682
- this.memoryController?.openTurn(recording?.turn, userInput);
768
+ // actually submitted. Drivers pass that raw text as the second argument. A
769
+ // session-originated wake has no user text to quote from at all.
770
+ this.memoryController?.openTurn(recording?.turn, origin === undefined ? userInput : '');
683
771
  // The current input is the one exception to fire-and-forget recording: make it
684
772
  // readable to offline observers before Agent.stream() can invoke a provider or
685
773
  // tool. The recorder owns the bound and resolves on write failure/timeout, so
@@ -704,6 +792,8 @@ export class AgentRuntime {
704
792
  // calls that completed. Cannot throw — see {@link observeCallStats}.
705
793
  this.observeCallStats(event);
706
794
  this.observeContextAnchor(event);
795
+ this.observeCacheMiss(event);
796
+ this.terminalDelivery.observe(event);
707
797
  yield event;
708
798
  }
709
799
  this.memoryController?.seal(completed && this.trajectory?.status.active !== false);
@@ -724,6 +814,9 @@ export class AgentRuntime {
724
814
  // generator before natural completion: only the natural path above seals.
725
815
  if (!sealed)
726
816
  this.memoryController?.discard();
817
+ // Only a turn that ran to `endTurn` commits what its `wait`/`status` results
818
+ // delivered; an abandoned or failed turn forgets them, so the wake still fires.
819
+ this.terminalDelivery.closeTurn(sealed && completed);
727
820
  this.lastTurnDelta = deltaUsage(before, this.usage);
728
821
  this.tallyTurnUsage(turnConfig, this.lastTurnDelta);
729
822
  }
@@ -768,6 +861,17 @@ export class AgentRuntime {
768
861
  recordShellCommand(entry) {
769
862
  this.trajectory?.recordShellCommand(entry);
770
863
  }
864
+ /**
865
+ * Records one successful `/compact` (SRF-027) in the session's trajectory.
866
+ *
867
+ * A passthrough on {@link recordShellCommand}'s terms: the driver that ran the
868
+ * compaction reports what it already knows (the `CompactResult` counts, its own
869
+ * pre-compaction estimate, whether a focus was given) and nothing else — never the
870
+ * summary, never the focus text. No-op when recording is off or has latched off.
871
+ */
872
+ recordContextCompacted(entry) {
873
+ this.trajectory?.recordContextCompacted(entry);
874
+ }
771
875
  /**
772
876
  * The diagnostics log, or `undefined` when nobody asked for one.
773
877
  *
@@ -837,6 +941,9 @@ export class AgentRuntime {
837
941
  },
838
942
  });
839
943
  await this.codexHooks?.postCompact('manual');
944
+ // A rewritten history is a new cache prefix; a no-op pass left it as it was.
945
+ if (result.compacted)
946
+ this.markCacheInvalidated('compact');
840
947
  return result;
841
948
  }
842
949
  catch (error) {
@@ -907,6 +1014,26 @@ export class AgentRuntime {
907
1014
  ...(tailTokens === undefined ? {} : { tailTokens }),
908
1015
  };
909
1016
  }
1017
+ /**
1018
+ * What the next request is made of, component by component — the `/context`
1019
+ * breakdown (SER-077, `src/agent/context-breakdown.ts`).
1020
+ *
1021
+ * Deliberately a separate accessor rather than an option on
1022
+ * {@link contextEstimate}: the estimate is read after every turn by the pressure
1023
+ * advisory and by `/status`, and must stay one `countTokens` call at most. This one
1024
+ * makes one call per component through the same `model.countTokens`, so it runs only
1025
+ * when the user asks — `/context` is its sole caller. Reads live state, mutates
1026
+ * nothing, and never throws for a component: a failed count is an absent row.
1027
+ */
1028
+ contextBreakdown() {
1029
+ return measureContextBreakdown({
1030
+ systemPrompt: this.agent.systemPrompt,
1031
+ composed: this.info.promptSections,
1032
+ tools: this.agent.tools,
1033
+ servers: this.listMcpServers(),
1034
+ messages: this.agent.messages,
1035
+ }, (messages, options) => this.model.countTokens(messages, options));
1036
+ }
910
1037
  /**
911
1038
  * How many wildcard allow-rules are in effect right now — config plus anything
912
1039
  * accepted this session. Read live from the gate rather than snapshotted into
@@ -933,6 +1060,19 @@ export class AgentRuntime {
933
1060
  listAllowRules() {
934
1061
  return this.gate.listAllowRules();
935
1062
  }
1063
+ /**
1064
+ * The configured deny-rules (SER-076), for `/permissions` and `/status`. Read
1065
+ * from the gate like {@link listAllowRules}; the gate's list is frozen and the
1066
+ * session has no grant or revoke path for a deny, so this is exactly what the
1067
+ * rules file said at startup.
1068
+ */
1069
+ listDenyRules() {
1070
+ return this.gate.denyRules;
1071
+ }
1072
+ /** How many deny-rules are in force — counted apart from allow-rules. */
1073
+ get denyRuleCount() {
1074
+ return this.gate.denyRules.length;
1075
+ }
936
1076
  /**
937
1077
  * The configured MCP servers with their live connection state and registered
938
1078
  * tool names, for the `/mcp` report. A read-only projection — names, states and
@@ -1003,10 +1143,17 @@ export class AgentRuntime {
1003
1143
  * cache breakpoint (switching thinking *modes* would).
1004
1144
  */
1005
1145
  changeThinkingEffort(effort) {
1146
+ const before = this.thinkingPlan.effective;
1006
1147
  this.thinkingPlan = applyThinkingEffort(this.model, this.liveConfig, effort);
1148
+ // Only a change in what is actually sent alters the request; a clamped or
1149
+ // repeated level is a no-op for the cache and must not be blamed for a miss.
1150
+ const effectiveChanged = this.thinkingPlan.effective !== before;
1151
+ if (effectiveChanged)
1152
+ this.markCacheInvalidated('effort');
1007
1153
  return {
1008
1154
  plan: this.thinkingPlan,
1009
1155
  saved: saveThinkingEffort(this.projectRoot, effort),
1156
+ effectiveChanged,
1010
1157
  };
1011
1158
  }
1012
1159
  /** The config in effect now — the startup one until `/model` changes it. */
@@ -1107,6 +1254,8 @@ export class AgentRuntime {
1107
1254
  this.codexHooks?.updateConfig(next);
1108
1255
  this.thinkingPlan = thinkingPlan;
1109
1256
  this.promptCachePlan = promptCachePlan;
1257
+ // A different model keys a different cache: the next call re-reads uncached.
1258
+ this.markCacheInvalidated('model');
1110
1259
  const choice = next.modelChoices.find((entry) => entry.index === target.index);
1111
1260
  return {
1112
1261
  choice,
@@ -1215,6 +1364,65 @@ export class AgentRuntime {
1215
1364
  this.contextAnchorBroken = true;
1216
1365
  }
1217
1366
  }
1367
+ /**
1368
+ * Folds one completed call into the cache-miss tracker (SER-074): the call's cache
1369
+ * read and request total through the same `usageBuckets`/`requestInputTokens`
1370
+ * arithmetic `/usage` and `/context` use, stamped with the wall clock. Same
1371
+ * observer discipline and its own latch, like the two above. Unreported counters
1372
+ * are passed as unknown — the tracker returns no verdict for them.
1373
+ */
1374
+ observeCacheMiss(event) {
1375
+ if (this.cacheMissesBroken || event.type !== 'afterModelCallEvent')
1376
+ return;
1377
+ try {
1378
+ const stopData = event.stopData;
1379
+ if (stopData === undefined)
1380
+ return;
1381
+ const usage = readCallUsage(stopData.message?.metadata?.usage);
1382
+ this.cacheMisses.observe({
1383
+ at: Date.now(),
1384
+ cacheRead: usage === undefined ? undefined : usageBuckets(usage, this.liveConfig).cacheRead,
1385
+ requestInput: usage === undefined ? undefined : requestInputTokens(usage, this.liveConfig),
1386
+ });
1387
+ }
1388
+ catch {
1389
+ this.cacheMissesBroken = true;
1390
+ }
1391
+ }
1392
+ /** One invalidating event since the last completed call; a broken tracker ignores it. */
1393
+ markCacheInvalidated(event) {
1394
+ if (this.cacheMissesBroken)
1395
+ return;
1396
+ try {
1397
+ this.cacheMisses.mark(event);
1398
+ }
1399
+ catch {
1400
+ this.cacheMissesBroken = true;
1401
+ }
1402
+ }
1403
+ /**
1404
+ * The likely causes of this session's prompt-cache misses, for `/usage` and
1405
+ * `/status` — empty (`misses: 0`, no last miss) until one is observed, after a
1406
+ * tracker failure, and whenever the live plan places no Darwin-managed cache
1407
+ * point (caching off, an unsupported model, or OpenAI's provider-managed cache),
1408
+ * so those reports stay byte-identical to before the feature existed.
1409
+ */
1410
+ cacheMissReport() {
1411
+ if (this.cacheMissesBroken || !this.promptCachePlan.enabled)
1412
+ return { lastMiss: undefined, misses: 0 };
1413
+ return this.cacheMisses.report();
1414
+ }
1415
+ /**
1416
+ * Whether the last completed call's cache entries are still readable at `now` —
1417
+ * warm iff that call read from the cache and finished less than the TTL ago. What
1418
+ * `/model` and `/effort` consult before a switch. `undefined` until a call has
1419
+ * completed, and under the same silence rule as {@link cacheMissReport}.
1420
+ */
1421
+ cacheWarmth(now) {
1422
+ if (this.cacheMissesBroken || !this.promptCachePlan.enabled)
1423
+ return undefined;
1424
+ return this.cacheMisses.warmth(now);
1425
+ }
1218
1426
  /**
1219
1427
  * Per-model-call efficiency stats for this session's parent agent, or
1220
1428
  * `undefined` until a completed call has been observed — so every surface that
@@ -1262,6 +1470,16 @@ export class AgentRuntime {
1262
1470
  subscribeToBackgroundTasks(listener) {
1263
1471
  return this.backgroundBash.subscribe(listener);
1264
1472
  }
1473
+ /**
1474
+ * True once a *completed* turn of this session carried the task's terminal state
1475
+ * to the model through a `wait`/`status`/`stop`/`list` result (SER-069). The
1476
+ * interactive drain drops a queued wake for such a task instead of sending it: the
1477
+ * conversation already knows, and a second turn about it would be the duplicate
1478
+ * the peer design produces. Synchronous, no I/O.
1479
+ */
1480
+ terminalStateDelivered(taskId) {
1481
+ return this.terminalDelivery.has(taskId);
1482
+ }
1265
1483
  /**
1266
1484
  * Every subagent dispatch of this run, in start order, running and finished
1267
1485
  * alike. Synchronous — unlike {@link listBackgroundTasks}, which snapshots live
@@ -1289,6 +1507,27 @@ export class AgentRuntime {
1289
1507
  cancelSubagentDispatch(dispatchId) {
1290
1508
  return this.subagentDispatches.cancel(dispatchId);
1291
1509
  }
1510
+ /**
1511
+ * Every background delegation the SDK still tracks (SER-070): dispatched with
1512
+ * `_background_execution` and not yet delivered to the model as its result pair —
1513
+ * running, or settled and waiting for the next model call. Synchronous, no I/O: the
1514
+ * observer's ledger, fed by the parent's own stream and hook. Non-empty means
1515
+ * `/clear` and `/rewind` must refuse (the SDK's `assertCanLoadSnapshot` would throw,
1516
+ * and a successor would orphan the children).
1517
+ */
1518
+ listBackgroundDelegations() {
1519
+ return this.backgroundDelegation.list();
1520
+ }
1521
+ /** Publishes each background delegation's one settlement snapshot until the closure is called. */
1522
+ subscribeToBackgroundDelegations(listener) {
1523
+ return this.backgroundDelegation.subscribe(listener);
1524
+ }
1525
+ /** Synchronous, before any release: the same sentence the TUI's local check prints. */
1526
+ refuseWhileDelegationsTracked(command) {
1527
+ const tracked = this.backgroundDelegation.list();
1528
+ if (tracked.length > 0)
1529
+ throw new Error(liveBackgroundDelegationRefusal(command, tracked));
1530
+ }
1292
1531
  /**
1293
1532
  * Asks the agent to stop the current turn at its next safe point. The stream
1294
1533
  * ends with `stopReason: 'cancelled'` rather than throwing.
@@ -1347,6 +1586,7 @@ export class AgentRuntime {
1347
1586
  * fresh successor id receives a latest snapshot.
1348
1587
  */
1349
1588
  async startRewind(checkpoint) {
1589
+ this.refuseWhileDelegationsTracked('/rewind');
1350
1590
  const catalogue = await readRewindCatalogue(this.projectRoot, this.info.sessionId);
1351
1591
  if (catalogue.problem !== undefined)
1352
1592
  throw new Error(catalogue.problem);
@@ -1414,8 +1654,14 @@ export class AgentRuntime {
1414
1654
  * If assembling the successor fails, this runtime stays fully usable: nothing it owns
1415
1655
  * has been released yet, and the diagnostics tap it installed at startup is put back
1416
1656
  * (the failed successor's unwind clears the process-global sink).
1657
+ *
1658
+ * Refused while a background delegation is tracked (SER-070): `retire()` would cancel
1659
+ * the children through `subagents.shutdown()`, destroying their work silently, and
1660
+ * the result pair the SDK still owes would be orphaned. The user decided the exits are
1661
+ * `/agents cancel <id>` or waiting for the completion wake — never an implicit cancel.
1417
1662
  */
1418
1663
  async startNewSession() {
1664
+ this.refuseWhileDelegationsTracked('/clear');
1419
1665
  let successor;
1420
1666
  try {
1421
1667
  successor = await AgentRuntime.create({