strands-darwin 0.0.34 → 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 (88) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  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/refusal.d.ts +44 -7
  15. package/dist/src/agent/refusal.js +54 -8
  16. package/dist/src/agent/refusal.js.map +1 -1
  17. package/dist/src/agent/runtime.d.ts +25 -6
  18. package/dist/src/agent/runtime.js +65 -17
  19. package/dist/src/agent/runtime.js.map +1 -1
  20. package/dist/src/agent/stream-resumption.d.ts +5 -2
  21. package/dist/src/agent/stream-resumption.js +5 -2
  22. package/dist/src/agent/stream-resumption.js.map +1 -1
  23. package/dist/src/agent/system-prompt.d.ts +1 -1
  24. package/dist/src/agent/system-prompt.js +4 -1
  25. package/dist/src/agent/system-prompt.js.map +1 -1
  26. package/dist/src/agent/thinking.js +4 -2
  27. package/dist/src/agent/thinking.js.map +1 -1
  28. package/dist/src/agents/subagent-tool.js +4 -3
  29. package/dist/src/agents/subagent-tool.js.map +1 -1
  30. package/dist/src/agents/workflow-tool.js +2 -2
  31. package/dist/src/agents/workflow-tool.js.map +1 -1
  32. package/dist/src/cli-doctor.js +7 -5
  33. package/dist/src/cli-doctor.js.map +1 -1
  34. package/dist/src/commands/custom-commands.d.ts +1 -1
  35. package/dist/src/commands/custom-commands.js +7 -1
  36. package/dist/src/commands/custom-commands.js.map +1 -1
  37. package/dist/src/commands/init-command.d.ts +47 -0
  38. package/dist/src/commands/init-command.js +110 -0
  39. package/dist/src/commands/init-command.js.map +1 -0
  40. package/dist/src/config.d.ts +35 -3
  41. package/dist/src/config.js +127 -4
  42. package/dist/src/config.js.map +1 -1
  43. package/dist/src/dev-repl.js +17 -2
  44. package/dist/src/dev-repl.js.map +1 -1
  45. package/dist/src/headless-protocol.js +6 -5
  46. package/dist/src/headless-protocol.js.map +1 -1
  47. package/dist/src/headless-runner.js +5 -1
  48. package/dist/src/headless-runner.js.map +1 -1
  49. package/dist/src/headless.d.ts +11 -0
  50. package/dist/src/headless.js +33 -7
  51. package/dist/src/headless.js.map +1 -1
  52. package/dist/src/pricing/model-prices.d.ts +3 -1
  53. package/dist/src/pricing/model-prices.js +7 -1
  54. package/dist/src/pricing/model-prices.js.map +1 -1
  55. package/dist/src/tools/background-bash.d.ts +15 -3
  56. package/dist/src/tools/background-bash.js +18 -8
  57. package/dist/src/tools/background-bash.js.map +1 -1
  58. package/dist/src/tools/file-editor-serial.d.ts +14 -0
  59. package/dist/src/tools/file-editor-serial.js +15 -0
  60. package/dist/src/tools/file-editor-serial.js.map +1 -1
  61. package/dist/src/tools/shell-env.d.ts +77 -0
  62. package/dist/src/tools/shell-env.js +139 -0
  63. package/dist/src/tools/shell-env.js.map +1 -0
  64. package/dist/src/trajectory/replay.js +23 -0
  65. package/dist/src/trajectory/replay.js.map +1 -1
  66. package/dist/src/trajectory/writer.d.ts +44 -3
  67. package/dist/src/trajectory/writer.js +80 -14
  68. package/dist/src/trajectory/writer.js.map +1 -1
  69. package/dist/src/tui/App.d.ts +4 -1
  70. package/dist/src/tui/App.js +181 -36
  71. package/dist/src/tui/App.js.map +1 -1
  72. package/dist/src/tui/InputBox.d.ts +1 -1
  73. package/dist/src/tui/InputBox.js +1 -1
  74. package/dist/src/tui/instructions-format.d.ts +14 -0
  75. package/dist/src/tui/instructions-format.js +24 -0
  76. package/dist/src/tui/instructions-format.js.map +1 -0
  77. package/dist/src/tui/prompt-queue.js +4 -2
  78. package/dist/src/tui/prompt-queue.js.map +1 -1
  79. package/dist/src/tui/status-format.d.ts +15 -0
  80. package/dist/src/tui/status-format.js +25 -0
  81. package/dist/src/tui/status-format.js.map +1 -1
  82. package/dist/src/tui/tangent.d.ts +122 -0
  83. package/dist/src/tui/tangent.js +153 -0
  84. package/dist/src/tui/tangent.js.map +1 -0
  85. package/dist/src/tui/turn-state.d.ts +12 -1
  86. package/dist/src/tui/turn-state.js +11 -0
  87. package/dist/src/tui/turn-state.js.map +1 -1
  88. package/package.json +3 -3
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `stopReason: 'refusal'` — the model's safety classifiers declined the request.
2
+ * Refusal-class stop reasons — the provider or its classifiers declined the request.
3
3
  *
4
4
  * Claude Fable 5.1 (and the Mythos line) end such a turn *successfully* from the
5
5
  * SDK's point of view: the agent loop sees a non-`toolUse` stop and returns an
@@ -8,13 +8,50 @@
8
8
  * reported as `succeeded`. The drivers and delegation tools ask here and state the
9
9
  * outcome; the loop itself is never touched (the SDK owns the stop, darwin only
10
10
  * names it).
11
+ *
12
+ * The stop-reason vocabulary differs per provider, so the class is a fixed set of
13
+ * exactly three SDK words, not one provider's string (SRF-029 — a Bedrock session
14
+ * lost three turns to `contentFiltered` while only `refusal` was recognised):
15
+ *
16
+ * - `refusal` — the direct Anthropic provider (`models/anthropic.js`) passes the
17
+ * API's `stop_reason: "refusal"` through unchanged: the model's own classifiers
18
+ * blocked the response.
19
+ * - `contentFiltered` — the Bedrock provider's `STOP_REASON_MAP` (`models/bedrock.js`)
20
+ * for Converse's `content_filtered`: the same classifier block, reached through
21
+ * Bedrock, which spells it differently.
22
+ * - `guardrailIntervened` — the same map's `guardrail_intervened`: a configured
23
+ * Bedrock Guardrail, not the model, stopped the turn. Kept distinguishable from the
24
+ * classifier block because the remedy differs (the guardrail is the account's).
25
+ *
26
+ * Nothing else qualifies. `maxTokens`, `stopSequence`, `endTurn` and `toolUse` are
27
+ * the model finishing on its own terms; `cancelled`, `interrupt` and `checkpoint`
28
+ * are darwin's or the SDK's own stops. Every user-facing string names the reason
29
+ * actually received, so a reader can tell the three apart.
11
30
  */
12
- /** The SDK's stop reason for a model-side refusal, on every provider. */
13
- export declare const REFUSAL_STOP_REASON = "refusal";
31
+ /** The SDK stop reasons that mean "the provider or its classifiers declined". */
32
+ export declare const REFUSAL_STOP_REASONS: readonly ["refusal", "contentFiltered", "guardrailIntervened"];
33
+ export type RefusalStopReason = (typeof REFUSAL_STOP_REASONS)[number];
34
+ export declare function isRefusalStop(stopReason: string): stopReason is RefusalStopReason;
14
35
  /** One bounded user-facing line for the transcript or stderr. */
15
- export declare const REFUSAL_NOTICE = "model declined this request (stop_reason: refusal) \u2014 rephrase it or start a new turn";
36
+ export declare function refusalNotice(stopReason: string): string;
37
+ /**
38
+ * The TUI's variant of {@link refusalNotice}: the same line plus the remedy only the
39
+ * TUI can offer (SRF-030). A refused turn still appended the prompt and the declined
40
+ * reply to the SDK conversation, and `AgentRuntime.send` now catalogues its pre-prompt
41
+ * checkpoint, so `/rewind` to that prompt is the one user-chosen way to cut the
42
+ * exchange out before rephrasing — darwin never removes it on its own. Headless
43
+ * drivers have no `/rewind` and keep printing the base line.
44
+ */
45
+ export declare function refusalNoticeWithRewind(stopReason: string): string;
16
46
  /** The error a headless run ends with when a refusal left no reply at all. */
17
- export declare const REFUSAL_EMPTY_REPLY_ERROR = "The model declined this request (stop_reason: refusal) and produced no reply.";
47
+ export declare function refusalEmptyReplyError(stopReason: string): string;
18
48
  /** The fixed note a refused child's failure carries back to the parent. */
19
- export declare const CHILD_REFUSAL_ERROR = "child model declined the delegated task (stop_reason: refusal)";
20
- export declare function isRefusalStop(stopReason: string): boolean;
49
+ export declare function childRefusalError(stopReason: string): string;
50
+ /**
51
+ * The one line replay (and therefore `/export` and the resume recap) prints in the
52
+ * answer slot of a refusal-class turn, after whatever partial text it streamed. The
53
+ * live session showed {@link refusalNotice} instead — its remedy is advice for the
54
+ * moment, meaningless in a transcript read later — so the transcript states only
55
+ * the fact and the reason, parenthesised because it is not the model's text.
56
+ */
57
+ export declare function refusalTranscriptLine(stopReason: string): string;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `stopReason: 'refusal'` — the model's safety classifiers declined the request.
2
+ * Refusal-class stop reasons — the provider or its classifiers declined the request.
3
3
  *
4
4
  * Claude Fable 5.1 (and the Mythos line) end such a turn *successfully* from the
5
5
  * SDK's point of view: the agent loop sees a non-`toolUse` stop and returns an
@@ -8,16 +8,62 @@
8
8
  * reported as `succeeded`. The drivers and delegation tools ask here and state the
9
9
  * outcome; the loop itself is never touched (the SDK owns the stop, darwin only
10
10
  * names it).
11
+ *
12
+ * The stop-reason vocabulary differs per provider, so the class is a fixed set of
13
+ * exactly three SDK words, not one provider's string (SRF-029 — a Bedrock session
14
+ * lost three turns to `contentFiltered` while only `refusal` was recognised):
15
+ *
16
+ * - `refusal` — the direct Anthropic provider (`models/anthropic.js`) passes the
17
+ * API's `stop_reason: "refusal"` through unchanged: the model's own classifiers
18
+ * blocked the response.
19
+ * - `contentFiltered` — the Bedrock provider's `STOP_REASON_MAP` (`models/bedrock.js`)
20
+ * for Converse's `content_filtered`: the same classifier block, reached through
21
+ * Bedrock, which spells it differently.
22
+ * - `guardrailIntervened` — the same map's `guardrail_intervened`: a configured
23
+ * Bedrock Guardrail, not the model, stopped the turn. Kept distinguishable from the
24
+ * classifier block because the remedy differs (the guardrail is the account's).
25
+ *
26
+ * Nothing else qualifies. `maxTokens`, `stopSequence`, `endTurn` and `toolUse` are
27
+ * the model finishing on its own terms; `cancelled`, `interrupt` and `checkpoint`
28
+ * are darwin's or the SDK's own stops. Every user-facing string names the reason
29
+ * actually received, so a reader can tell the three apart.
11
30
  */
12
- /** The SDK's stop reason for a model-side refusal, on every provider. */
13
- export const REFUSAL_STOP_REASON = 'refusal';
31
+ /** The SDK stop reasons that mean "the provider or its classifiers declined". */
32
+ export const REFUSAL_STOP_REASONS = Object.freeze(['refusal', 'contentFiltered', 'guardrailIntervened']);
33
+ export function isRefusalStop(stopReason) {
34
+ return REFUSAL_STOP_REASONS.includes(stopReason);
35
+ }
14
36
  /** One bounded user-facing line for the transcript or stderr. */
15
- export const REFUSAL_NOTICE = 'model declined this request (stop_reason: refusal) — rephrase it or start a new turn';
37
+ export function refusalNotice(stopReason) {
38
+ return `model declined this request (stop_reason: ${stopReason}) — rephrase it or start a new turn`;
39
+ }
40
+ /**
41
+ * The TUI's variant of {@link refusalNotice}: the same line plus the remedy only the
42
+ * TUI can offer (SRF-030). A refused turn still appended the prompt and the declined
43
+ * reply to the SDK conversation, and `AgentRuntime.send` now catalogues its pre-prompt
44
+ * checkpoint, so `/rewind` to that prompt is the one user-chosen way to cut the
45
+ * exchange out before rephrasing — darwin never removes it on its own. Headless
46
+ * drivers have no `/rewind` and keep printing the base line.
47
+ */
48
+ export function refusalNoticeWithRewind(stopReason) {
49
+ return `${refusalNotice(stopReason)} — the declined reply stays in the conversation; /rewind to this prompt removes it before you rephrase`;
50
+ }
16
51
  /** The error a headless run ends with when a refusal left no reply at all. */
17
- export const REFUSAL_EMPTY_REPLY_ERROR = 'The model declined this request (stop_reason: refusal) and produced no reply.';
52
+ export function refusalEmptyReplyError(stopReason) {
53
+ return `The model declined this request (stop_reason: ${stopReason}) and produced no reply.`;
54
+ }
18
55
  /** The fixed note a refused child's failure carries back to the parent. */
19
- export const CHILD_REFUSAL_ERROR = 'child model declined the delegated task (stop_reason: refusal)';
20
- export function isRefusalStop(stopReason) {
21
- return stopReason === REFUSAL_STOP_REASON;
56
+ export function childRefusalError(stopReason) {
57
+ return `child model declined the delegated task (stop_reason: ${stopReason})`;
58
+ }
59
+ /**
60
+ * The one line replay (and therefore `/export` and the resume recap) prints in the
61
+ * answer slot of a refusal-class turn, after whatever partial text it streamed. The
62
+ * live session showed {@link refusalNotice} instead — its remedy is advice for the
63
+ * moment, meaningless in a transcript read later — so the transcript states only
64
+ * the fact and the reason, parenthesised because it is not the model's text.
65
+ */
66
+ export function refusalTranscriptLine(stopReason) {
67
+ return `(model declined this request — stop_reason: ${stopReason})`;
22
68
  }
23
69
  //# sourceMappingURL=refusal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"refusal.js","sourceRoot":"","sources":["../../../src/agent/refusal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,yEAAyE;AACzE,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC;AAE7C,iEAAiE;AACjE,MAAM,CAAC,MAAM,cAAc,GACzB,sFAAsF,CAAC;AAEzF,8EAA8E;AAC9E,MAAM,CAAC,MAAM,yBAAyB,GACpC,+EAA+E,CAAC;AAElF,2EAA2E;AAC3E,MAAM,CAAC,MAAM,mBAAmB,GAAG,gEAAgE,CAAC;AAEpG,MAAM,UAAU,aAAa,CAAC,UAAkB;IAC9C,OAAO,UAAU,KAAK,mBAAmB,CAAC;AAC5C,CAAC"}
1
+ {"version":3,"file":"refusal.js","sourceRoot":"","sources":["../../../src/agent/refusal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,iFAAiF;AACjF,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,iBAAiB,EAAE,qBAAqB,CAAU,CAAC,CAAC;AAIlH,MAAM,UAAU,aAAa,CAAC,UAAkB;IAC9C,OAAQ,oBAA0C,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;AAC1E,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,aAAa,CAAC,UAAkB;IAC9C,OAAO,6CAA6C,UAAU,qCAAqC,CAAC;AACtG,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uBAAuB,CAAC,UAAkB;IACxD,OAAO,GAAG,aAAa,CAAC,UAAU,CAAC,wGAAwG,CAAC;AAC9I,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,sBAAsB,CAAC,UAAkB;IACvD,OAAO,iDAAiD,UAAU,0BAA0B,CAAC;AAC/F,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,iBAAiB,CAAC,UAAkB;IAClD,OAAO,yDAAyD,UAAU,GAAG,CAAC;AAChF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CAAC,UAAkB;IACtD,OAAO,+CAA+C,UAAU,GAAG,CAAC;AACtE,CAAC"}
@@ -17,7 +17,7 @@ import type { MemoryStatus } from '../memory/store.js';
17
17
  import type { ContextCompactedEntry, TaskNotificationFields } from '../trajectory/record.js';
18
18
  import { type RecorderOptions, type TrajectoryStatus } from '../trajectory/writer.js';
19
19
  import { type ContextBreakdown } from './context-breakdown.js';
20
- import { type ProjectInstructionsSummary } from './instructions.js';
20
+ import { type InstructionsFilename, type ProjectInstructionsSummary } from './instructions.js';
21
21
  import { type AllowRuleEntry, type ApprovalMode, type PermissionBridge, type PermissionModeChange } from './permission.js';
22
22
  import { type PromptCachePlan } from './prompt-cache.js';
23
23
  import { type SessionSelector } from './session.js';
@@ -147,6 +147,9 @@ export type ExpandedSlashCommand = ({
147
147
  } & ExpandedCustomCommand) | {
148
148
  kind: 'workflow';
149
149
  message: string;
150
+ } | {
151
+ kind: 'init';
152
+ message: string;
150
153
  };
151
154
  /** Estimated size of the next request's context, plus the model's window. */
152
155
  export interface ContextEstimate {
@@ -202,10 +205,12 @@ export interface RuntimeInfo {
202
205
  file: string;
203
206
  reason: string;
204
207
  }[];
205
- /** AGENTS.md preloaded from the run directory, or undefined when there is none. */
208
+ /** AGENTS.md (or the CLAUDE.md fallback) preloaded from the run directory, or undefined when there is none. */
206
209
  projectInstructions: ProjectInstructionsSummary | undefined;
207
- /** Why a present AGENTS.md was skipped; undefined when there is no such file. */
210
+ /** Why a present instructions file was skipped; undefined when there is no such file. */
208
211
  projectInstructionsProblem: string | undefined;
212
+ /** Which file `projectInstructionsProblem` is about; undefined exactly when it is. */
213
+ projectInstructionsProblemFile: InstructionsFilename | undefined;
209
214
  /** Where the base system prompt came from: built-in, config, or override file. */
210
215
  systemPromptSource: SystemPromptSource;
211
216
  /** Path of the system prompt override file, when one is in effect. */
@@ -253,6 +258,16 @@ export interface RuntimeInfo {
253
258
  directory: string;
254
259
  shadowed: string[];
255
260
  }[];
261
+ /**
262
+ * What model-spawned shells were denied at startup (SER-082): the sorted names
263
+ * withheld from the persistent shell and background jobs, plus the configured
264
+ * passthrough entries. Names only — no value is ever stored or shown. Read by the
265
+ * startup notice and `/status`; the map itself lives in the bash tools.
266
+ */
267
+ shellEnv: {
268
+ withheld: string[];
269
+ passthrough: string[];
270
+ };
256
271
  mcpIgnoredConfigPath: string | undefined;
257
272
  /** Number of MCP servers configured (some may have failed to connect). */
258
273
  mcpServerCount: number;
@@ -919,10 +934,14 @@ export declare class AgentRuntime {
919
934
  private captureRewindCheckpoint;
920
935
  /**
921
936
  * Expands a built-in prompt command, a skill, or a project command into the
922
- * prompt sent to the model. `/workflow` is checked first: built-in
937
+ * prompt sent to the model. `/workflow` and `/init` are checked first: built-in
923
938
  * reservation precedes skills and custom commands, so no extension can
924
- * shadow it. Its bare form returns null — the drivers own that local usage
925
- * notice, and the runtime never fabricates a turn. Skills are checked before
939
+ * shadow them. Bare `/workflow` returns null — the drivers own that local usage
940
+ * notice, and the runtime never fabricates a turn — while bare `/init` is the
941
+ * trigger itself. `/init` decides create-versus-improve from the instructions
942
+ * summary this runtime captured at startup (the header's own data), never from
943
+ * a fresh filesystem read, so every driver — TUI, dev-repl, headless — gets the
944
+ * same branch through this one seam. Skills are checked before
926
945
  * custom commands as a defensive backstop to the loader's collision
927
946
  * filtering. Unknown slash input remains ordinary user input.
928
947
  */
@@ -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';
@@ -49,6 +51,7 @@ import { measureContextBreakdown } from './context-breakdown.js';
49
51
  import { composeSystemPrompt, loadProjectInstructions, } from './instructions.js';
50
52
  import { PermissionGate } from './permission.js';
51
53
  import { applySystemPromptCachePoint, canUpdateSystemPromptCache, planPromptCache, } from './prompt-cache.js';
54
+ import { isRefusalStop } from './refusal.js';
52
55
  import { createModelClassifier } from './safety-classifier.js';
53
56
  import { createSessionManager, diagnosticsPath, resolveSession, sessionPaths, trajectoryPath, writePointer, } from './session.js';
54
57
  import { setSdkVerboseSink } from './sdk-logging.js';
@@ -401,15 +404,23 @@ export class AgentRuntime {
401
404
  const backgroundBash = options.inherit?.backgroundBash ?? new BackgroundBashManager(options.projectRoot, session.sessionId);
402
405
  if (options.inherit === undefined)
403
406
  startupBackgroundBash = backgroundBash;
404
- 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);
405
416
  // The parent's wording states the runtime truth: only a driver that drains SER-069
406
417
  // task wakes, with the config key on, may tell the model that ending the turn is
407
418
  // followed by a `<task-notification>` turn. Children get the same manager and
408
419
  // foreground tool behind the no-wake wording (`childBash` below): a child's job
409
420
  // wakes the parent TUI, never the child.
410
421
  const completionWakes = options.backgroundCompletionWakes === true && config.backgroundTaskWake !== false;
411
- const bash = createBackgroundBashTool(backgroundBash, foregroundBash, { completionWakes });
412
- 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;
413
424
  const imageViewer = createImageViewerTool(options.projectRoot);
414
425
  const conversationManager = new SummarizingConversationManager({
415
426
  summaryRatio: config.summaryRatio,
@@ -443,11 +454,19 @@ export class AgentRuntime {
443
454
  : undefined;
444
455
  const memoryController = config.memory === true ? new MemoryToolController(options.projectRoot, config.memoryHorizonDays ?? 28) : undefined;
445
456
  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];
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
+ ];
451
470
  // SER-064: the two delegation tools are the only ones the model may route to the
452
471
  // SDK's background executor; everything else — the ordinary tools by name, and by
453
472
  // wildcard whatever `initialize()` discovers later — stays foreground. Cap and
@@ -612,9 +631,13 @@ export class AgentRuntime {
612
631
  }
613
632
  runtimeCreateCheckpoint?.('after-initialize');
614
633
  // 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
634
+ // must not be able to influence assembly. It creates no file here — the first
616
635
  // recorded turn creates it, so a session that never runs one leaves nothing
617
- // 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.
618
641
  const thinkingPlan = planThinking(config);
619
642
  const trajectory = config.trajectory === false
620
643
  ? undefined
@@ -646,6 +669,7 @@ export class AgentRuntime {
646
669
  ...(memoryController === undefined ? {} : { onTurnSettled: (settlement) => memoryController.settle(settlement) }),
647
670
  });
648
671
  trajectoryAudit = trajectory;
672
+ await trajectory?.open();
649
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, {
650
674
  config,
651
675
  projectRoot: options.projectRoot,
@@ -660,8 +684,14 @@ export class AgentRuntime {
660
684
  agentProblems: agentDefinitions.problems.map((problem) => ({ ...problem })),
661
685
  projectInstructions: instructions === undefined
662
686
  ? undefined
663
- : { 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
+ },
664
693
  projectInstructionsProblem: loadedInstructions.problem,
694
+ projectInstructionsProblemFile: loadedInstructions.problemFile,
665
695
  systemPromptSource: basePrompt.source,
666
696
  systemPromptPath: basePrompt.path,
667
697
  systemPromptProblem: basePrompt.problem,
@@ -681,6 +711,7 @@ export class AgentRuntime {
681
711
  ...notice,
682
712
  shadowed: [...notice.shadowed],
683
713
  })),
714
+ shellEnv: { withheld: [...shellEnv.withheld], passthrough: [...shellPassthrough] },
684
715
  mcpIgnoredConfigPath: mcp.ignoredConfigPath,
685
716
  mcpServerCount: mcp.clients.length,
686
717
  toolNames: agent.tools.map((tool) => tool.name).sort(),
@@ -753,6 +784,11 @@ export class AgentRuntime {
753
784
  checkpointId = await this.captureRewindCheckpoint();
754
785
  }
755
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;
756
792
  let sealed = false;
757
793
  try {
758
794
  // A multimodal turn's durable text is the literal submitted prompt. Expanded
@@ -787,6 +823,8 @@ export class AgentRuntime {
787
823
  for await (const event of recordStream(stream, recording)) {
788
824
  if (event.type === 'agentResultEvent' && event.result.stopReason === 'endTurn')
789
825
  completed = true;
826
+ if (event.type === 'agentResultEvent' && isRefusalStop(event.result.stopReason))
827
+ refused = true;
790
828
  // Observed at the same point `recordStream` observes: synchronously, between
791
829
  // `stream()` and the `yield`, so `/usage` asked mid-turn already counts the
792
830
  // calls that completed. Cannot throw — see {@link observeCallStats}.
@@ -798,7 +836,7 @@ export class AgentRuntime {
798
836
  }
799
837
  this.memoryController?.seal(completed && this.trajectory?.status.active !== false);
800
838
  sealed = true;
801
- if (completed && checkpointId !== undefined) {
839
+ if ((completed || refused) && checkpointId !== undefined) {
802
840
  const catalogue = await appendRewindCheckpoint(this.projectRoot, this.info.sessionId, {
803
841
  snapshotId: checkpointId,
804
842
  prompt: input,
@@ -1758,10 +1796,14 @@ export class AgentRuntime {
1758
1796
  }
1759
1797
  /**
1760
1798
  * 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
1799
+ * prompt sent to the model. `/workflow` and `/init` are checked first: built-in
1762
1800
  * 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
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
1765
1807
  * custom commands as a defensive backstop to the loader's collision
1766
1808
  * filtering. Unknown slash input remains ordinary user input.
1767
1809
  */
@@ -1771,6 +1813,12 @@ export class AgentRuntime {
1771
1813
  return null;
1772
1814
  if (workflow !== null)
1773
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 };
1774
1822
  const skill = await expandSkillCommand(this.skills, input);
1775
1823
  if (skill !== null)
1776
1824
  return { kind: 'skill', ...skill };