strands-darwin 0.0.33 → 0.0.35

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 (142) hide show
  1. package/README.md +5 -1
  2. package/README.zh-CN.md +5 -1
  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/cache-miss.d.ts +143 -0
  9. package/dist/src/agent/cache-miss.js +182 -0
  10. package/dist/src/agent/cache-miss.js.map +1 -0
  11. package/dist/src/agent/compact.d.ts +28 -0
  12. package/dist/src/agent/compact.js +34 -0
  13. package/dist/src/agent/compact.js.map +1 -1
  14. package/dist/src/agent/context-breakdown.d.ts +110 -0
  15. package/dist/src/agent/context-breakdown.js +117 -0
  16. package/dist/src/agent/context-breakdown.js.map +1 -0
  17. package/dist/src/agent/instructions.d.ts +23 -4
  18. package/dist/src/agent/instructions.js +67 -34
  19. package/dist/src/agent/instructions.js.map +1 -1
  20. package/dist/src/agent/permission-rules.d.ts +81 -2
  21. package/dist/src/agent/permission-rules.js +226 -6
  22. package/dist/src/agent/permission-rules.js.map +1 -1
  23. package/dist/src/agent/permission.d.ts +116 -2
  24. package/dist/src/agent/permission.js +201 -26
  25. package/dist/src/agent/permission.js.map +1 -1
  26. package/dist/src/agent/prompt-cache.d.ts +12 -3
  27. package/dist/src/agent/prompt-cache.js +12 -3
  28. package/dist/src/agent/prompt-cache.js.map +1 -1
  29. package/dist/src/agent/refusal.d.ts +44 -7
  30. package/dist/src/agent/refusal.js +54 -8
  31. package/dist/src/agent/refusal.js.map +1 -1
  32. package/dist/src/agent/runtime.d.ts +112 -7
  33. package/dist/src/agent/runtime.js +240 -19
  34. package/dist/src/agent/runtime.js.map +1 -1
  35. package/dist/src/agent/stream-resumption.d.ts +5 -2
  36. package/dist/src/agent/stream-resumption.js +5 -2
  37. package/dist/src/agent/stream-resumption.js.map +1 -1
  38. package/dist/src/agent/system-prompt.d.ts +1 -1
  39. package/dist/src/agent/system-prompt.js +4 -1
  40. package/dist/src/agent/system-prompt.js.map +1 -1
  41. package/dist/src/agent/thinking.js +4 -2
  42. package/dist/src/agent/thinking.js.map +1 -1
  43. package/dist/src/agents/child-recipe.d.ts +9 -1
  44. package/dist/src/agents/child-recipe.js +2 -0
  45. package/dist/src/agents/child-recipe.js.map +1 -1
  46. package/dist/src/agents/dispatch-registry.d.ts +18 -0
  47. package/dist/src/agents/dispatch-registry.js +2 -0
  48. package/dist/src/agents/dispatch-registry.js.map +1 -1
  49. package/dist/src/agents/retained-children.d.ts +101 -0
  50. package/dist/src/agents/retained-children.js +101 -0
  51. package/dist/src/agents/retained-children.js.map +1 -0
  52. package/dist/src/agents/subagent-tool.d.ts +50 -1
  53. package/dist/src/agents/subagent-tool.js +151 -12
  54. package/dist/src/agents/subagent-tool.js.map +1 -1
  55. package/dist/src/agents/workflow-tool.js +2 -2
  56. package/dist/src/agents/workflow-tool.js.map +1 -1
  57. package/dist/src/cli-doctor.js +10 -6
  58. package/dist/src/cli-doctor.js.map +1 -1
  59. package/dist/src/cli-main.js +9 -3
  60. package/dist/src/cli-main.js.map +1 -1
  61. package/dist/src/commands/custom-commands.d.ts +1 -1
  62. package/dist/src/commands/custom-commands.js +12 -5
  63. package/dist/src/commands/custom-commands.js.map +1 -1
  64. package/dist/src/commands/init-command.d.ts +47 -0
  65. package/dist/src/commands/init-command.js +110 -0
  66. package/dist/src/commands/init-command.js.map +1 -0
  67. package/dist/src/config.d.ts +78 -8
  68. package/dist/src/config.js +167 -20
  69. package/dist/src/config.js.map +1 -1
  70. package/dist/src/dev-repl.js +17 -2
  71. package/dist/src/dev-repl.js.map +1 -1
  72. package/dist/src/headless-protocol.d.ts +1 -1
  73. package/dist/src/headless-protocol.js +6 -5
  74. package/dist/src/headless-protocol.js.map +1 -1
  75. package/dist/src/headless-runner.js +12 -3
  76. package/dist/src/headless-runner.js.map +1 -1
  77. package/dist/src/headless.d.ts +11 -0
  78. package/dist/src/headless.js +33 -7
  79. package/dist/src/headless.js.map +1 -1
  80. package/dist/src/hooks/tool-hooks.js +10 -6
  81. package/dist/src/hooks/tool-hooks.js.map +1 -1
  82. package/dist/src/pricing/model-prices.d.ts +3 -1
  83. package/dist/src/pricing/model-prices.js +7 -1
  84. package/dist/src/pricing/model-prices.js.map +1 -1
  85. package/dist/src/skills/builtin/self-evolution-research/SKILL.md +14 -1
  86. package/dist/src/skills/prompt.d.ts +17 -0
  87. package/dist/src/skills/prompt.js +20 -0
  88. package/dist/src/skills/prompt.js.map +1 -1
  89. package/dist/src/tools/background-bash.d.ts +15 -3
  90. package/dist/src/tools/background-bash.js +18 -8
  91. package/dist/src/tools/background-bash.js.map +1 -1
  92. package/dist/src/tools/file-editor-serial.d.ts +14 -0
  93. package/dist/src/tools/file-editor-serial.js +15 -0
  94. package/dist/src/tools/file-editor-serial.js.map +1 -1
  95. package/dist/src/tools/shell-env.d.ts +77 -0
  96. package/dist/src/tools/shell-env.js +139 -0
  97. package/dist/src/tools/shell-env.js.map +1 -0
  98. package/dist/src/trajectory/record.d.ts +169 -2
  99. package/dist/src/trajectory/record.js +135 -0
  100. package/dist/src/trajectory/record.js.map +1 -1
  101. package/dist/src/trajectory/replay.d.ts +34 -1
  102. package/dist/src/trajectory/replay.js +157 -4
  103. package/dist/src/trajectory/replay.js.map +1 -1
  104. package/dist/src/trajectory/resume-recap.js +10 -3
  105. package/dist/src/trajectory/resume-recap.js.map +1 -1
  106. package/dist/src/trajectory/spend.d.ts +14 -1
  107. package/dist/src/trajectory/spend.js +40 -6
  108. package/dist/src/trajectory/spend.js.map +1 -1
  109. package/dist/src/trajectory/writer.d.ts +89 -4
  110. package/dist/src/trajectory/writer.js +191 -17
  111. package/dist/src/trajectory/writer.js.map +1 -1
  112. package/dist/src/tui/App.d.ts +12 -5
  113. package/dist/src/tui/App.js +328 -67
  114. package/dist/src/tui/App.js.map +1 -1
  115. package/dist/src/tui/InputBox.d.ts +1 -1
  116. package/dist/src/tui/InputBox.js +1 -1
  117. package/dist/src/tui/context-format.d.ts +16 -0
  118. package/dist/src/tui/context-format.js +41 -0
  119. package/dist/src/tui/context-format.js.map +1 -1
  120. package/dist/src/tui/instructions-format.d.ts +14 -0
  121. package/dist/src/tui/instructions-format.js +24 -0
  122. package/dist/src/tui/instructions-format.js.map +1 -0
  123. package/dist/src/tui/prompt-queue.js +4 -2
  124. package/dist/src/tui/prompt-queue.js.map +1 -1
  125. package/dist/src/tui/status-format.d.ts +50 -16
  126. package/dist/src/tui/status-format.js +92 -8
  127. package/dist/src/tui/status-format.js.map +1 -1
  128. package/dist/src/tui/subagent-format.js +13 -1
  129. package/dist/src/tui/subagent-format.js.map +1 -1
  130. package/dist/src/tui/tangent.d.ts +122 -0
  131. package/dist/src/tui/tangent.js +153 -0
  132. package/dist/src/tui/tangent.js.map +1 -0
  133. package/dist/src/tui/terminal-notify.d.ts +40 -0
  134. package/dist/src/tui/terminal-notify.js +136 -0
  135. package/dist/src/tui/terminal-notify.js.map +1 -0
  136. package/dist/src/tui/terminal-title.d.ts +94 -0
  137. package/dist/src/tui/terminal-title.js +121 -0
  138. package/dist/src/tui/terminal-title.js.map +1 -0
  139. package/dist/src/tui/turn-state.d.ts +12 -1
  140. package/dist/src/tui/turn-state.js +11 -0
  141. package/dist/src/tui/turn-state.js.map +1 -1
  142. package/package.json +3 -3
@@ -6,7 +6,7 @@
6
6
  * later) decide how to render.
7
7
  */
8
8
  import { Agent, BeforeInvocationEvent, SummarizingConversationManager, TextBlock } from '@strands-agents/sdk';
9
- import { fileEditor } from '@strands-agents/sdk/vended-tools/file-editor';
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';
@@ -23,11 +23,13 @@ import { SubagentDispatchRegistry, } from '../agents/dispatch-registry.js';
23
23
  import { SUBAGENT_TOOL_NAME, SubagentTool } from '../agents/subagent-tool.js';
24
24
  import { WORKFLOW_TOOL_NAME, WorkflowTool } from '../agents/workflow-tool.js';
25
25
  import { expandCustomCommand, loadCustomCommands, } from '../commands/custom-commands.js';
26
+ import { parseInitCommand } from '../commands/init-command.js';
26
27
  import { parseWorkflowCommand } from '../commands/workflow-command.js';
27
28
  import { appendAllowRule, applyThinkingEffort, createModelFromConfig, loadConfig, loadProjectPolicy, permissionRulesPath, removeAllowRules, saveEnabledModel, saveThinkingEffort, withModelChoice, } from '../config.js';
28
29
  import { BackgroundBashManager, createBackgroundBashTool, createForegroundBashTool, } from '../tools/background-bash.js';
29
- import { SerializedFileEditorTool } from '../tools/file-editor-serial.js';
30
+ import { FILE_EDITOR_DESCRIPTION, SerializedFileEditorTool } from '../tools/file-editor-serial.js';
30
31
  import { createImageViewerTool, normalizeRestoredImages } from '../tools/image-viewer.js';
32
+ import { scrubShellEnv } from '../tools/shell-env.js';
31
33
  import { createUpdatePlanTool } from '../tools/update-plan.js';
32
34
  import { webFetch } from '../tools/web-fetch.js';
33
35
  import { LifecycleHookRunner, lifecycleHooksFromConfig, } from '../hooks/lifecycle-hooks.js';
@@ -45,9 +47,11 @@ import { recordStream } from '../trajectory/stream.js';
45
47
  import { TrajectoryRecorder, } from '../trajectory/writer.js';
46
48
  import { DARWIN_VERSION } from '../version.js';
47
49
  import { TerminalDeliveryLedger } from './task-terminal-delivery.js';
50
+ import { measureContextBreakdown } from './context-breakdown.js';
48
51
  import { composeSystemPrompt, loadProjectInstructions, } from './instructions.js';
49
52
  import { PermissionGate } from './permission.js';
50
53
  import { applySystemPromptCachePoint, canUpdateSystemPromptCache, planPromptCache, } from './prompt-cache.js';
54
+ import { isRefusalStop } from './refusal.js';
51
55
  import { createModelClassifier } from './safety-classifier.js';
52
56
  import { createSessionManager, diagnosticsPath, resolveSession, sessionPaths, trajectoryPath, writePointer, } from './session.js';
53
57
  import { setSdkVerboseSink } from './sdk-logging.js';
@@ -55,8 +59,9 @@ import { loadSystemPrompt } from './system-prompt.js';
55
59
  import { applyWorkingContext, buildWorkingContext } from './working-context.js';
56
60
  import { planThinking } from './thinking.js';
57
61
  import { MAX_REWIND_CHECKPOINTS, appendRewindCheckpoint, newestRewindCheckpoints, readRewindCatalogue, rewindPromptEligible, } from './rewind.js';
58
- import { deltaUsage, startCallSpend, startTurnSpend, sumUsage } from './usage.js';
59
- import { emptyCallStats, recordCompletedCall, } from './call-stats.js';
62
+ import { deltaUsage, requestInputTokens, startCallSpend, startTurnSpend, sumUsage, usageBuckets } from './usage.js';
63
+ import { emptyCallStats, readCallUsage, recordCompletedCall, } from './call-stats.js';
64
+ import { CacheMissTracker, promptCacheTtlMs } from './cache-miss.js';
60
65
  import { anchorFromCall, resolveAnchor } from './context-anchor.js';
61
66
  import { defaultModelPriceStore } from '../pricing/model-prices.js';
62
67
  let runtimeCreateCheckpoint;
@@ -78,6 +83,27 @@ export function setRuntimeRecorderOverridesForTest(overrides) {
78
83
  * previous snapshots from `--resume`.
79
84
  */
80
85
  const AGENT_ID = 'darwin';
86
+ /**
87
+ * The gate's published decision as the recorder's structural record fields (SER-079).
88
+ *
89
+ * The two shapes are spelled independently on purpose — `src/trajectory/**` imports
90
+ * no gate type — and this is the one seam where they meet, so a field the gate adds
91
+ * tomorrow does not reach the file until someone names it here. Copies exactly the
92
+ * audit fields; there is no input on the gate's object to leave out.
93
+ */
94
+ function permissionDecisionEntry(decision) {
95
+ return {
96
+ toolUseId: decision.toolUseId,
97
+ toolName: decision.toolName,
98
+ kind: decision.kind,
99
+ risk: decision.risk,
100
+ mode: decision.mode,
101
+ source: decision.source,
102
+ outcome: decision.outcome,
103
+ ...(decision.rule === undefined ? {} : { rule: decision.rule }),
104
+ promptedUser: decision.promptedUser,
105
+ };
106
+ }
81
107
  /**
82
108
  * Parent-registered tools that never enter the child catalogue: the offloader's
83
109
  * retrieval tool (parent-session storage) and both network tools (children are
@@ -167,6 +193,18 @@ export class AgentRuntime {
167
193
  * `/context` to the plain heuristic line rather than to a wrong number.
168
194
  */
169
195
  contextAnchorBroken = false;
196
+ /**
197
+ * Why the prompt cache missed, per completed call (SER-074): the same
198
+ * `afterModelCallEvent` counters the call stats fold, joined with the invalidating
199
+ * events this runtime performed (`/model`, `/effort`, `/compact`) and the TTL.
200
+ * Parent-only and session-scoped like the two observers above; built in the
201
+ * constructor so `/clear`'s successor starts empty. Read through
202
+ * {@link cacheMissReport} and {@link cacheWarmth}, both silent unless the live
203
+ * cache plan has Darwin-managed cache points.
204
+ */
205
+ cacheMisses;
206
+ /** Latched on the first tracker failure — its own latch, so it cannot break the others. */
207
+ cacheMissesBroken = false;
170
208
  /**
171
209
  * Which background jobs' terminal states completed turns already carried to the
172
210
  * model through `wait`/`status` results (SER-069): the interactive drain asks it
@@ -235,6 +273,7 @@ export class AgentRuntime {
235
273
  this.thinkingPlan = info.thinking;
236
274
  this.liveConfig = info.config;
237
275
  this.promptCachePlan = info.promptCache;
276
+ this.cacheMisses = new CacheMissTracker(() => promptCacheTtlMs(this.promptCachePlan.ttl), info.resumed);
238
277
  // Fire and forget: a mapped id costs one file read, an unmapped one starts the
239
278
  // single bounded background fetch. Nothing awaits it — not startup, not the
240
279
  // first turn — and it cannot reject, so it cannot become a startup failure.
@@ -315,16 +354,24 @@ export class AgentRuntime {
315
354
  // children that do not exist yet, and only the narrow resolver crosses over —
316
355
  // the permission layer never learns about the delegation tool itself.
317
356
  const subagentDispatches = new SubagentDispatchRegistry();
357
+ // The recorder is built last (below), after the Agent, so the gate's audit
358
+ // observer binds to it late: a decision published before the binding — none
359
+ // can be, since no turn runs during assembly — or with recording off is dropped.
360
+ let trajectoryAudit;
318
361
  const gate = new PermissionGate({
319
362
  mode: permissionMode,
320
363
  projectRoot: options.projectRoot,
321
364
  ask: options.permissionBridge,
322
365
  allowRules: policy.allowRules,
366
+ denyRules: policy.denyRules,
323
367
  dispatchSource: (agentId) => subagentDispatches.sourceFor(agentId),
324
368
  // Built for every run, not only an `auto` one: `/mode auto` can arrive
325
369
  // mid-session and the gate must have a classifier to consult. Costs nothing
326
370
  // until it is used — the closure defers building its model to the first call.
327
371
  classifier: createModelClassifier(config, options.projectRoot),
372
+ // SER-079: one bounded `permissionDecision` record per settled decision. The
373
+ // adapter below is the only place the gate's object meets the record's shape.
374
+ onDecision: (decision) => trajectoryAudit?.recordPermissionDecision(permissionDecisionEntry(decision)),
328
375
  });
329
376
  const codexHooks = policy.codexHooks === undefined ? undefined : new CodexHookRunner({
330
377
  projectRoot: options.projectRoot,
@@ -357,15 +404,23 @@ export class AgentRuntime {
357
404
  const backgroundBash = options.inherit?.backgroundBash ?? new BackgroundBashManager(options.projectRoot, session.sessionId);
358
405
  if (options.inherit === undefined)
359
406
  startupBackgroundBash = backgroundBash;
360
- const foregroundBash = createForegroundBashTool(options.projectRoot);
407
+ // SER-082: what a model-spawned shell inherits, decided once per runtime from
408
+ // this process's environment and the config passthrough list — the persistent
409
+ // foreground shell and every `start` job, parent and children alike (children
410
+ // reuse `foregroundBash` and the manager through `childBash`), get this map.
411
+ // Names only are kept for `/status` and the startup notice; values never leave
412
+ // `shellEnv.env`. User `!` commands, hooks and MCP servers are not routed here.
413
+ const shellPassthrough = config.shellEnv?.passthrough ?? [];
414
+ const shellEnv = scrubShellEnv(process.env, shellPassthrough);
415
+ const foregroundBash = createForegroundBashTool(options.projectRoot, shellEnv.env);
361
416
  // The parent's wording states the runtime truth: only a driver that drains SER-069
362
417
  // task wakes, with the config key on, may tell the model that ending the turn is
363
418
  // followed by a `<task-notification>` turn. Children get the same manager and
364
419
  // foreground tool behind the no-wake wording (`childBash` below): a child's job
365
420
  // wakes the parent TUI, never the child.
366
421
  const completionWakes = options.backgroundCompletionWakes === true && config.backgroundTaskWake !== false;
367
- const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes });
368
- const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash) : bash;
422
+ const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes, env: shellEnv.env });
423
+ const childBash = completionWakes ? createBackgroundBashTool(backgroundBash, foregroundBash, { env: shellEnv.env }) : bash;
369
424
  const imageViewer = createImageViewerTool(options.projectRoot);
370
425
  const conversationManager = new SummarizingConversationManager({
371
426
  summaryRatio: config.summaryRatio,
@@ -399,11 +454,19 @@ export class AgentRuntime {
399
454
  : undefined;
400
455
  const memoryController = config.memory === true ? new MemoryToolController(options.projectRoot, config.memoryHorizonDays ?? 28) : undefined;
401
456
  startupMemoryController = memoryController;
402
- // The fileEditor is the SDK singleton behind a same-path ordering wrapper
403
- // (SRF-020): substituted here rather than `addOrReplace`d after construction
404
- // because it is static, so the raw tool is never registered, and `childTools`
405
- // below hands children the same wrapper with per-Agent chains.
406
- const ordinaryTools = [bash, new SerializedFileEditorTool(fileEditor), imageViewer, httpRequest, webFetch];
457
+ // The fileEditor is the SDK vended tool — `makeFileEditor({ description })`, the
458
+ // same factory as the singleton with the SDK's default text plus the SRF-032
459
+ // payload bound — behind a same-path ordering wrapper (SRF-020): substituted here
460
+ // rather than `addOrReplace`d after construction because it is static, so the raw
461
+ // tool is never registered, and `childTools` below hands children the same
462
+ // wrapper with per-Agent chains.
463
+ const ordinaryTools = [
464
+ bash,
465
+ new SerializedFileEditorTool(makeFileEditor({ description: FILE_EDITOR_DESCRIPTION })),
466
+ imageViewer,
467
+ httpRequest,
468
+ webFetch,
469
+ ];
407
470
  // SER-064: the two delegation tools are the only ones the model may route to the
408
471
  // SDK's background executor; everything else — the ordinary tools by name, and by
409
472
  // wildcard whatever `initialize()` discovers later — stays foreground. Cap and
@@ -568,9 +631,13 @@ export class AgentRuntime {
568
631
  }
569
632
  runtimeCreateCheckpoint?.('after-initialize');
570
633
  // Built last and given nothing but facts: the recorder is an observer, so it
571
- // must not be able to influence assembly. It opens no file here — the first
634
+ // must not be able to influence assembly. It creates no file here — the first
572
635
  // recorded turn creates it, so a session that never runs one leaves nothing
573
- // behind, the same rule `markResumable()` follows for the resume pointer.
636
+ // behind, the same rule `markResumable()` follows for the resume pointer. It
637
+ // does *read* an existing file's tail (SRF-031): the seed that numbers a resumed
638
+ // run's first turn `max + 1` has to be in place before `send()` can hand out a
639
+ // turn ordinal, and `create()` is the one point no driver can get ahead of.
640
+ // The wait is bounded by the recorder itself.
574
641
  const thinkingPlan = planThinking(config);
575
642
  const trajectory = config.trajectory === false
576
643
  ? undefined
@@ -586,10 +653,23 @@ export class AgentRuntime {
586
653
  thinkingEffort: thinkingPlan.effective,
587
654
  resumed: session.restoreRequested && agent.messages.length > 0,
588
655
  restoredMessages: agent.messages.length,
656
+ // A rewind successor is `resumed: false` with a restored count the
657
+ // record could not otherwise explain (SRF-028): name the checkpoint
658
+ // it branched from. Absent — not undefined — for every other session.
659
+ ...(options.rewindRestore === undefined
660
+ ? {}
661
+ : {
662
+ rewindFrom: {
663
+ session: options.rewindRestore.sourceSessionId,
664
+ snapshotId: options.rewindRestore.snapshotId,
665
+ },
666
+ }),
589
667
  },
590
668
  ...runtimeRecorderOverrides,
591
669
  ...(memoryController === undefined ? {} : { onTurnSettled: (settlement) => memoryController.settle(settlement) }),
592
670
  });
671
+ trajectoryAudit = trajectory;
672
+ await trajectory?.open();
593
673
  const runtime = new AgentRuntime(agent, model, options.projectRoot, mcp, skills, commands, subagents, workflows, subagentDispatches, backgroundDelegation, modelRetry, backgroundBash, gate, lifecycleHooks, policy.toolHookLayers, codexHooks, sessionManager, config.preserveRecentMessages, trajectory, diagnosticsLog, memoryController, {
594
674
  config,
595
675
  projectRoot: options.projectRoot,
@@ -604,11 +684,18 @@ export class AgentRuntime {
604
684
  agentProblems: agentDefinitions.problems.map((problem) => ({ ...problem })),
605
685
  projectInstructions: instructions === undefined
606
686
  ? undefined
607
- : { path: instructions.path, bytes: instructions.bytes, truncated: instructions.truncated },
687
+ : {
688
+ filename: instructions.filename,
689
+ path: instructions.path,
690
+ bytes: instructions.bytes,
691
+ truncated: instructions.truncated,
692
+ },
608
693
  projectInstructionsProblem: loadedInstructions.problem,
694
+ projectInstructionsProblemFile: loadedInstructions.problemFile,
609
695
  systemPromptSource: basePrompt.source,
610
696
  systemPromptPath: basePrompt.path,
611
697
  systemPromptProblem: basePrompt.problem,
698
+ promptSections: { base: basePromptText, instructions: instructions?.fragment },
612
699
  workingContextProblem: workingContext.problem,
613
700
  promptCache,
614
701
  // Recomputed rather than returned from createModelFromConfig: the model
@@ -624,6 +711,7 @@ export class AgentRuntime {
624
711
  ...notice,
625
712
  shadowed: [...notice.shadowed],
626
713
  })),
714
+ shellEnv: { withheld: [...shellEnv.withheld], passthrough: [...shellPassthrough] },
627
715
  mcpIgnoredConfigPath: mcp.ignoredConfigPath,
628
716
  mcpServerCount: mcp.clients.length,
629
717
  toolNames: agent.tools.map((tool) => tool.name).sort(),
@@ -696,6 +784,11 @@ export class AgentRuntime {
696
784
  checkpointId = await this.captureRewindCheckpoint();
697
785
  }
698
786
  let completed = false;
787
+ // A refusal-class stop (SRF-030): the SDK loop still ran to its end and appended
788
+ // both messages, so the pre-prompt checkpoint is a valid rewind boundary — the
789
+ // one that removes the declined exchange. Read only by the catalogue call below;
790
+ // memory sealing and terminal delivery keep meaning `endTurn`.
791
+ let refused = false;
699
792
  let sealed = false;
700
793
  try {
701
794
  // A multimodal turn's durable text is the literal submitted prompt. Expanded
@@ -730,17 +823,20 @@ export class AgentRuntime {
730
823
  for await (const event of recordStream(stream, recording)) {
731
824
  if (event.type === 'agentResultEvent' && event.result.stopReason === 'endTurn')
732
825
  completed = true;
826
+ if (event.type === 'agentResultEvent' && isRefusalStop(event.result.stopReason))
827
+ refused = true;
733
828
  // Observed at the same point `recordStream` observes: synchronously, between
734
829
  // `stream()` and the `yield`, so `/usage` asked mid-turn already counts the
735
830
  // calls that completed. Cannot throw — see {@link observeCallStats}.
736
831
  this.observeCallStats(event);
737
832
  this.observeContextAnchor(event);
833
+ this.observeCacheMiss(event);
738
834
  this.terminalDelivery.observe(event);
739
835
  yield event;
740
836
  }
741
837
  this.memoryController?.seal(completed && this.trajectory?.status.active !== false);
742
838
  sealed = true;
743
- if (completed && checkpointId !== undefined) {
839
+ if ((completed || refused) && checkpointId !== undefined) {
744
840
  const catalogue = await appendRewindCheckpoint(this.projectRoot, this.info.sessionId, {
745
841
  snapshotId: checkpointId,
746
842
  prompt: input,
@@ -803,6 +899,17 @@ export class AgentRuntime {
803
899
  recordShellCommand(entry) {
804
900
  this.trajectory?.recordShellCommand(entry);
805
901
  }
902
+ /**
903
+ * Records one successful `/compact` (SRF-027) in the session's trajectory.
904
+ *
905
+ * A passthrough on {@link recordShellCommand}'s terms: the driver that ran the
906
+ * compaction reports what it already knows (the `CompactResult` counts, its own
907
+ * pre-compaction estimate, whether a focus was given) and nothing else — never the
908
+ * summary, never the focus text. No-op when recording is off or has latched off.
909
+ */
910
+ recordContextCompacted(entry) {
911
+ this.trajectory?.recordContextCompacted(entry);
912
+ }
806
913
  /**
807
914
  * The diagnostics log, or `undefined` when nobody asked for one.
808
915
  *
@@ -872,6 +979,9 @@ export class AgentRuntime {
872
979
  },
873
980
  });
874
981
  await this.codexHooks?.postCompact('manual');
982
+ // A rewritten history is a new cache prefix; a no-op pass left it as it was.
983
+ if (result.compacted)
984
+ this.markCacheInvalidated('compact');
875
985
  return result;
876
986
  }
877
987
  catch (error) {
@@ -942,6 +1052,26 @@ export class AgentRuntime {
942
1052
  ...(tailTokens === undefined ? {} : { tailTokens }),
943
1053
  };
944
1054
  }
1055
+ /**
1056
+ * What the next request is made of, component by component — the `/context`
1057
+ * breakdown (SER-077, `src/agent/context-breakdown.ts`).
1058
+ *
1059
+ * Deliberately a separate accessor rather than an option on
1060
+ * {@link contextEstimate}: the estimate is read after every turn by the pressure
1061
+ * advisory and by `/status`, and must stay one `countTokens` call at most. This one
1062
+ * makes one call per component through the same `model.countTokens`, so it runs only
1063
+ * when the user asks — `/context` is its sole caller. Reads live state, mutates
1064
+ * nothing, and never throws for a component: a failed count is an absent row.
1065
+ */
1066
+ contextBreakdown() {
1067
+ return measureContextBreakdown({
1068
+ systemPrompt: this.agent.systemPrompt,
1069
+ composed: this.info.promptSections,
1070
+ tools: this.agent.tools,
1071
+ servers: this.listMcpServers(),
1072
+ messages: this.agent.messages,
1073
+ }, (messages, options) => this.model.countTokens(messages, options));
1074
+ }
945
1075
  /**
946
1076
  * How many wildcard allow-rules are in effect right now — config plus anything
947
1077
  * accepted this session. Read live from the gate rather than snapshotted into
@@ -968,6 +1098,19 @@ export class AgentRuntime {
968
1098
  listAllowRules() {
969
1099
  return this.gate.listAllowRules();
970
1100
  }
1101
+ /**
1102
+ * The configured deny-rules (SER-076), for `/permissions` and `/status`. Read
1103
+ * from the gate like {@link listAllowRules}; the gate's list is frozen and the
1104
+ * session has no grant or revoke path for a deny, so this is exactly what the
1105
+ * rules file said at startup.
1106
+ */
1107
+ listDenyRules() {
1108
+ return this.gate.denyRules;
1109
+ }
1110
+ /** How many deny-rules are in force — counted apart from allow-rules. */
1111
+ get denyRuleCount() {
1112
+ return this.gate.denyRules.length;
1113
+ }
971
1114
  /**
972
1115
  * The configured MCP servers with their live connection state and registered
973
1116
  * tool names, for the `/mcp` report. A read-only projection — names, states and
@@ -1038,10 +1181,17 @@ export class AgentRuntime {
1038
1181
  * cache breakpoint (switching thinking *modes* would).
1039
1182
  */
1040
1183
  changeThinkingEffort(effort) {
1184
+ const before = this.thinkingPlan.effective;
1041
1185
  this.thinkingPlan = applyThinkingEffort(this.model, this.liveConfig, effort);
1186
+ // Only a change in what is actually sent alters the request; a clamped or
1187
+ // repeated level is a no-op for the cache and must not be blamed for a miss.
1188
+ const effectiveChanged = this.thinkingPlan.effective !== before;
1189
+ if (effectiveChanged)
1190
+ this.markCacheInvalidated('effort');
1042
1191
  return {
1043
1192
  plan: this.thinkingPlan,
1044
1193
  saved: saveThinkingEffort(this.projectRoot, effort),
1194
+ effectiveChanged,
1045
1195
  };
1046
1196
  }
1047
1197
  /** The config in effect now — the startup one until `/model` changes it. */
@@ -1142,6 +1292,8 @@ export class AgentRuntime {
1142
1292
  this.codexHooks?.updateConfig(next);
1143
1293
  this.thinkingPlan = thinkingPlan;
1144
1294
  this.promptCachePlan = promptCachePlan;
1295
+ // A different model keys a different cache: the next call re-reads uncached.
1296
+ this.markCacheInvalidated('model');
1145
1297
  const choice = next.modelChoices.find((entry) => entry.index === target.index);
1146
1298
  return {
1147
1299
  choice,
@@ -1250,6 +1402,65 @@ export class AgentRuntime {
1250
1402
  this.contextAnchorBroken = true;
1251
1403
  }
1252
1404
  }
1405
+ /**
1406
+ * Folds one completed call into the cache-miss tracker (SER-074): the call's cache
1407
+ * read and request total through the same `usageBuckets`/`requestInputTokens`
1408
+ * arithmetic `/usage` and `/context` use, stamped with the wall clock. Same
1409
+ * observer discipline and its own latch, like the two above. Unreported counters
1410
+ * are passed as unknown — the tracker returns no verdict for them.
1411
+ */
1412
+ observeCacheMiss(event) {
1413
+ if (this.cacheMissesBroken || event.type !== 'afterModelCallEvent')
1414
+ return;
1415
+ try {
1416
+ const stopData = event.stopData;
1417
+ if (stopData === undefined)
1418
+ return;
1419
+ const usage = readCallUsage(stopData.message?.metadata?.usage);
1420
+ this.cacheMisses.observe({
1421
+ at: Date.now(),
1422
+ cacheRead: usage === undefined ? undefined : usageBuckets(usage, this.liveConfig).cacheRead,
1423
+ requestInput: usage === undefined ? undefined : requestInputTokens(usage, this.liveConfig),
1424
+ });
1425
+ }
1426
+ catch {
1427
+ this.cacheMissesBroken = true;
1428
+ }
1429
+ }
1430
+ /** One invalidating event since the last completed call; a broken tracker ignores it. */
1431
+ markCacheInvalidated(event) {
1432
+ if (this.cacheMissesBroken)
1433
+ return;
1434
+ try {
1435
+ this.cacheMisses.mark(event);
1436
+ }
1437
+ catch {
1438
+ this.cacheMissesBroken = true;
1439
+ }
1440
+ }
1441
+ /**
1442
+ * The likely causes of this session's prompt-cache misses, for `/usage` and
1443
+ * `/status` — empty (`misses: 0`, no last miss) until one is observed, after a
1444
+ * tracker failure, and whenever the live plan places no Darwin-managed cache
1445
+ * point (caching off, an unsupported model, or OpenAI's provider-managed cache),
1446
+ * so those reports stay byte-identical to before the feature existed.
1447
+ */
1448
+ cacheMissReport() {
1449
+ if (this.cacheMissesBroken || !this.promptCachePlan.enabled)
1450
+ return { lastMiss: undefined, misses: 0 };
1451
+ return this.cacheMisses.report();
1452
+ }
1453
+ /**
1454
+ * Whether the last completed call's cache entries are still readable at `now` —
1455
+ * warm iff that call read from the cache and finished less than the TTL ago. What
1456
+ * `/model` and `/effort` consult before a switch. `undefined` until a call has
1457
+ * completed, and under the same silence rule as {@link cacheMissReport}.
1458
+ */
1459
+ cacheWarmth(now) {
1460
+ if (this.cacheMissesBroken || !this.promptCachePlan.enabled)
1461
+ return undefined;
1462
+ return this.cacheMisses.warmth(now);
1463
+ }
1253
1464
  /**
1254
1465
  * Per-model-call efficiency stats for this session's parent agent, or
1255
1466
  * `undefined` until a completed call has been observed — so every surface that
@@ -1585,10 +1796,14 @@ export class AgentRuntime {
1585
1796
  }
1586
1797
  /**
1587
1798
  * Expands a built-in prompt command, a skill, or a project command into the
1588
- * prompt sent to the model. `/workflow` is checked first: built-in
1799
+ * prompt sent to the model. `/workflow` and `/init` are checked first: built-in
1589
1800
  * reservation precedes skills and custom commands, so no extension can
1590
- * shadow it. Its bare form returns null — the drivers own that local usage
1591
- * notice, and the runtime never fabricates a turn. Skills are checked before
1801
+ * shadow them. Bare `/workflow` returns null — the drivers own that local usage
1802
+ * notice, and the runtime never fabricates a turn — while bare `/init` is the
1803
+ * trigger itself. `/init` decides create-versus-improve from the instructions
1804
+ * summary this runtime captured at startup (the header's own data), never from
1805
+ * a fresh filesystem read, so every driver — TUI, dev-repl, headless — gets the
1806
+ * same branch through this one seam. Skills are checked before
1592
1807
  * custom commands as a defensive backstop to the loader's collision
1593
1808
  * filtering. Unknown slash input remains ordinary user input.
1594
1809
  */
@@ -1598,6 +1813,12 @@ export class AgentRuntime {
1598
1813
  return null;
1599
1814
  if (workflow !== null)
1600
1815
  return { kind: 'workflow', ...workflow };
1816
+ const init = parseInitCommand(input, {
1817
+ loaded: this.info.projectInstructions,
1818
+ problemFile: this.info.projectInstructionsProblemFile,
1819
+ });
1820
+ if (init !== null)
1821
+ return { kind: 'init', ...init };
1601
1822
  const skill = await expandSkillCommand(this.skills, input);
1602
1823
  if (skill !== null)
1603
1824
  return { kind: 'skill', ...skill };