zapagent 1.14.13 → 1.14.15

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 (44) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +7 -3
  3. package/src/agent/buildAgentRuntime.ts +6 -1
  4. package/src/agent/goalPresentation.ts +43 -0
  5. package/src/agent/promptDiagnostics.ts +8 -1
  6. package/src/commands/dispatcher.ts +9 -3
  7. package/src/commands/status.ts +7 -32
  8. package/src/config.ts +7 -2
  9. package/src/goal-command.ts +12 -7
  10. package/src/goal-host.ts +2 -1
  11. package/src/goal-runner.ts +36 -6
  12. package/src/goal-session.ts +99 -0
  13. package/src/headless/goalPhase.ts +38 -9
  14. package/src/headless/runHeadless.ts +6 -2
  15. package/src/hooks/useAgentRunner.ts +48 -1
  16. package/src/hooks/useTurnDispatcher.ts +8 -0
  17. package/src/index.tsx +19 -3
  18. package/src/prompts/context.ts +4 -3
  19. package/src/prompts/registry.ts +4 -3
  20. package/src/prompts/required-sections.ts +26 -0
  21. package/src/prompts/sections/agents-md.ts +24 -11
  22. package/src/prompts/sections/concise.ts +2 -2
  23. package/src/prompts/sections/file-reading.ts +2 -2
  24. package/src/prompts/sections/identity.ts +2 -2
  25. package/src/prompts/sections/plan-discipline.ts +2 -2
  26. package/src/prompts/sections/safety.ts +1 -1
  27. package/src/prompts/sections/skills.ts +4 -3
  28. package/src/prompts/sections/system.ts +4 -3
  29. package/src/prompts/sections/tasks.ts +1 -1
  30. package/src/ui/slash-palette.tsx +1 -1
  31. package/zapsdk/agent/events.ts +3 -0
  32. package/zapsdk/agent/loop.ts +33 -62
  33. package/zapsdk/agent/output-text.ts +34 -0
  34. package/zapsdk/agent/prompt-output-guard.ts +138 -0
  35. package/zapsdk/agent/streaming-tool-executor.ts +16 -8
  36. package/zapsdk/agent/subagent-assembly.ts +1 -0
  37. package/zapsdk/builtin-tools/subagent.ts +4 -2
  38. package/zapsdk/merge/copy.ts +13 -4
  39. package/zapsdk/runtime/recovery-controller.ts +1 -0
  40. package/zapsdk/runtime/state-tracker.ts +2 -0
  41. package/zapsdk/runtime/state-types.ts +1 -0
  42. package/zapsdk/workspace/copy.ts +29 -4
  43. package/zapsdk/workspace/manager.ts +34 -3
  44. package/zapsdk/workspace/types.ts +2 -0
@@ -3,6 +3,8 @@ import { backgroundTaskLifecycle, describeBackgroundTaskLifecycle, type Backgrou
3
3
  import { describeCheckpointCoverage } from "../checkpoint/facts.js";
4
4
  import { conciseAgentProtocol, DELIVERABLE_SCOPE_GUIDANCE, resolvePromptProfile, type PromptProfile } from "./prompt-profile.js";
5
5
  import { executeNonStreamingTurn } from "./nonstreaming-tool-executor.js";
6
+ import { findPromptLeak, PromptOutputEmitter } from "./prompt-output-guard.js";
7
+ import { normalizeAssistantText } from "./output-text.js";
6
8
  import { earliestDeadlineAt } from "../execution/deadline.js";
7
9
  import { toolOutputTool } from "../builtin-tools/tool-output.js";
8
10
  import { assembleSubagentTool } from "./subagent-assembly.js";
@@ -25,7 +27,6 @@ import { ToolExecutor, type ApprovalCallback, type PostProcessCallback, type Too
25
27
  import { isEffectivelyReadOnly, unknownToolEffects } from "../tools/effects.js";
26
28
  import { formatToolResultForModel, formatToolResultContent, normalizeToolFailure, operationFailure } from "../execution/failure.js";
27
29
  import {
28
- AgentEventEmitter,
29
30
  nextContentId,
30
31
  type AgentEventType,
31
32
  type AgentEventHandler,
@@ -195,6 +196,7 @@ export interface SubagentConfig {
195
196
  /** Host-selected instructions shared by every descendant, independent of
196
197
  * model-authored briefings. Do not pass the parent's entire workflow prompt. */
197
198
  inheritedInstructions?: string;
199
+ publicPromptSections?: readonly string[];
198
200
  /** Max steps per subagent (default: 50, capped to main agent's maxSteps) */
199
201
  maxSteps?: number;
200
202
  /** Subagent execution timeout in ms (default: 600_000) */
@@ -229,6 +231,7 @@ export interface SubagentFactoryArgs {
229
231
  /** Non-secret Host connection identity used only for local cache statistics. */
230
232
  requestCacheScope?: string;
231
233
  inheritedInstructions?: string;
234
+ publicPromptSections?: readonly string[];
232
235
  promptProfile?: PromptProfile;
233
236
  getResultSchema?: () => "outcome-v1" | "legacy";
234
237
  provider: LLMProvider;
@@ -277,6 +280,8 @@ export interface LoopAgentOptions {
277
280
  registry: ToolRegistry;
278
281
  executor: ToolExecutor;
279
282
  systemPrompt?: string;
283
+ /** Host-classified project documents, safe to quote; never model-controlled. */
284
+ publicPromptSections?: readonly string[];
280
285
  /** Optional behavior profile; omitted SDK callers retain legacy prompt assembly. */
281
286
  promptProfile?: PromptProfile;
282
287
  maxSteps?: number;
@@ -489,7 +494,11 @@ export class LoopAgent {
489
494
  private readonly promptProfile: PromptProfile;
490
495
  private readonly explicitPromptProfile: boolean;
491
496
  private maxToolRetries: number;
492
- private emitter = new AgentEventEmitter();
497
+ private emitter = new PromptOutputEmitter(
498
+ (text, scanFrom) => this.guardOutput(text, scanFrom),
499
+ () => !!(this.systemPrompt || this.explicitPromptProfile || this.turnContextPrefix),
500
+ normalizeAssistantText,
501
+ );
493
502
  private conversation?: ConversationManager;
494
503
  private resultCompressor?: ResultCompressor;
495
504
  private fallbackProvider?: LLMProvider;
@@ -545,6 +554,7 @@ export class LoopAgent {
545
554
  * run(), cleared in finally. Read by guardOutput so memory content
546
555
  * living in the transient attachment is still scanned for leak. */
547
556
  private turnContextPrefix?: string;
557
+ private readonly publicPromptSections: readonly string[];
548
558
  /** Host callback fired the first time a run self-heals an image rejection. */
549
559
  private onImageStripSelfHeal?: () => void;
550
560
 
@@ -559,6 +569,7 @@ export class LoopAgent {
559
569
  this.registry = options.registry;
560
570
  this.executor = options.executor;
561
571
  this.systemPrompt = options.systemPrompt;
572
+ this.publicPromptSections = [...(options.publicPromptSections ?? [])];
562
573
  this.promptProfile = resolvePromptProfile(options.promptProfile);
563
574
  this.initialUsage = options.initialUsage;
564
575
  this.explicitPromptProfile = options.promptProfile !== undefined;
@@ -1630,6 +1641,7 @@ export class LoopAgent {
1630
1641
  throw err;
1631
1642
  }
1632
1643
  } finally {
1644
+ this.emitter.clearOutputBuffers();
1633
1645
  this.requestMeter?.close();
1634
1646
  this.emitter.off("content_abandoned", recordIncompleteUsage);
1635
1647
  this.emitter.off("provider_request", recordIncompleteUsage);
@@ -1664,14 +1676,16 @@ export class LoopAgent {
1664
1676
  protocolPrompt(): string {
1665
1677
  const toolNames = this.registry.definitions().map((t) => t.name).join(", ");
1666
1678
  if (this.promptProfile === "concise") {
1667
- return conciseAgentProtocol(toolNames, this.maxSteps, this.taskDecomposition === "required");
1679
+ return conciseAgentProtocol(toolNames, this.maxSteps, this.taskDecomposition === "required" && this.registry.has("todo_write"));
1668
1680
  }
1669
1681
  return (
1670
1682
  `[AGENT PROTOCOL]\n` +
1671
1683
  `Tools: ${toolNames}\n` +
1672
1684
  `Budget: ${this.maxSteps} steps\n` +
1673
1685
  `Rules:\n` +
1674
- `- Think before acting. For a non-trivial tool task, decompose it with todo_write before implementation: 3-5 ordered, observable items; one in_progress; each has acceptanceCriteria; include an early minimal end-to-end probe and a contingency for a slow/blocked dependency; final item is a concrete verification.\n` +
1686
+ (this.registry.has("todo_write")
1687
+ ? `- Think before acting. For a non-trivial tool task, decompose it with todo_write before implementation: 3-5 ordered, observable items; one in_progress; each has acceptanceCriteria; include an early minimal end-to-end probe and a contingency for a slow/blocked dependency; final item is a concrete verification.\n`
1688
+ : `- Think before acting. For non-trivial work, choose a useful plan and verify the result using only the exposed tools.\n`) +
1675
1689
  `- Search/scan first, then targeted reads. Don't read every file.\n` +
1676
1690
  `- For recovery or forensics tasks, preserve the original input before running a parser, database client, or repair command that could mutate it.\n` +
1677
1691
  `- Reuse prior read/search results while the workspace is unchanged; do not repeat them through bash/grep/sed.\n` +
@@ -1683,7 +1697,8 @@ export class LoopAgent {
1683
1697
  `- When a check fails, identify the competing explanations and run a small test that distinguishes them before changing more code. Record which hypothesis changed and whether the result improved; do not cycle through variants without new evidence.\n` +
1684
1698
  `- If a tool fails, read the error carefully. Fix the cause, don't blindly retry.\n` +
1685
1699
  `- For a build or test failure, diagnose the cause and retry after a relevant change to source, command arguments, configuration, or dependencies. The same output target does not make a corrected invocation a duplicate.\n` +
1686
- `- Use web_search results directly when snippets contain enough info. Only http_fetch when you need full page content.`
1700
+ (this.registry.has("web_search") ? `- Use web_search results directly when snippets contain enough info.` : "") +
1701
+ (this.registry.has("http_fetch") ? ` Only use http_fetch when you need full page content.` : "")
1687
1702
  );
1688
1703
  }
1689
1704
 
@@ -2726,28 +2741,11 @@ export class LoopAgent {
2726
2741
  }
2727
2742
 
2728
2743
  private cleanOutput(text: string): string {
2729
- if (!text) return text;
2730
-
2731
- let cleaned = text
2732
- .replace(/<\|?tool_call[s_a-z]*\|?>[^]*?<\/?[|]?tool_call[s_a-z]*[|]?>/gi, "")
2733
- .replace(/<\|?tool_calls_section_begin\|?>[^]*?<\|?tool_calls_section_end\|?>/gi, "")
2734
- .replace(/<arg_key>[^<]*<\/arg_key><arg_value>[^<]*<\/arg_value>/gi, "")
2735
- .trim();
2736
-
2737
- if (cleaned.startsWith("{") && cleaned.includes('"name"') && cleaned.includes('"arguments"')) {
2738
- return "";
2739
- }
2740
-
2741
- const toolCallStart = cleaned.lastIndexOf("<|tool_call");
2742
- if (toolCallStart !== -1 && !cleaned.includes("<|tool_call", toolCallStart + 1)) {
2743
- cleaned = cleaned.slice(0, toolCallStart).trim();
2744
- }
2745
-
2746
- return this.guardOutput(cleaned);
2744
+ return this.guardOutput(normalizeAssistantText(text));
2747
2745
  }
2748
2746
 
2749
2747
  /**
2750
- * Last-line defense against prompt / memory extraction. Scans the final
2748
+ * Shared defense for public streaming events and final responses. Scans
2751
2749
  * assistant text for fingerprints of the system prompt or injected memory
2752
2750
  * and, if found, replaces the whole response with a brief refusal plus an
2753
2751
  * observation event.
@@ -2761,50 +2759,23 @@ export class LoopAgent {
2761
2759
  * proof dumps that sidestep the header markers. 300 chars is large
2762
2760
  * enough that accidental match on common code/docs is implausible.
2763
2761
  */
2764
- private guardOutput(text: string): string {
2762
+ private guardOutput(text: string, scanFrom = 0): string {
2765
2763
  if (!text) return text;
2766
- if (!this.systemPrompt && !this.turnContextPrefix) return text;
2764
+ const system = this.effectiveSystemPrompt();
2765
+ if (!system && !this.turnContextPrefix) return text;
2767
2766
 
2768
2767
  // Scan against system prompt AND the per-turn context attachment.
2769
2768
  // Memory content used to live in systemPrompt; after the Phase 2 split
2770
2769
  // it's in turnContextPrefix. Either can leak verbatim, so both are
2771
2770
  // fair game for the detector.
2772
- const corpus = [this.systemPrompt, this.turnContextPrefix].filter(Boolean).join("\n\n");
2773
-
2774
- const hardMarkers = [
2775
- "# Persistent Memory",
2776
- "## Memory types",
2777
- "## How to save a memory",
2778
- "# Project Guidelines (from AGENTS.md)",
2779
- "[AGENT PROTOCOL]",
2780
- "<system-context>",
2781
- "<active_plan>",
2782
- "<system-reminder>",
2783
- ];
2784
- for (const marker of hardMarkers) {
2785
- if (corpus.includes(marker) && text.includes(marker)) {
2786
- this.emitter.emit({
2787
- type: "observation",
2788
- kind: "prompt_leak_blocked",
2789
- detail: { marker, replacedLength: text.length },
2790
- });
2791
- return REFUSAL_PROMPT_LEAK;
2792
- }
2793
- }
2794
-
2795
- const runLen = 300;
2796
- if (text.length >= runLen) {
2797
- for (let i = 0; i + runLen <= text.length; i += 60) {
2798
- const chunk = text.slice(i, i + runLen);
2799
- if (corpus.includes(chunk)) {
2800
- this.emitter.emit({
2801
- type: "observation",
2802
- kind: "prompt_leak_blocked",
2803
- detail: { reason: "long_verbatim_run", replacedLength: text.length },
2804
- });
2805
- return REFUSAL_PROMPT_LEAK;
2806
- }
2807
- }
2771
+ const privateSystem = this.publicPromptSections.reduce((prompt, section) => section ? prompt.split(section).join("\n\n") : prompt, system ?? "");
2772
+ const corpus = [privateSystem, this.turnContextPrefix].filter(Boolean).join("\n\n");
2773
+
2774
+ const leak = findPromptLeak(text, corpus, scanFrom, this.publicPromptSections);
2775
+ if (leak) {
2776
+ this.emitter.emit({ type: "observation", kind: "prompt_leak_blocked",
2777
+ detail: { ...leak, replacedLength: text.length } });
2778
+ return REFUSAL_PROMPT_LEAK;
2808
2779
  }
2809
2780
 
2810
2781
  return text;
@@ -0,0 +1,34 @@
1
+ /** Once control markup begins, later deletions can join text across nested
2
+ * structures. Quarantine that suffix through true stream EOF; ordinary text
3
+ * still streams once it is distinguishable from a partial control opener. */
4
+ function stableStreamPrefix(text: string): string {
5
+ const prefixes = ["<tool_call", "<|tool_call", "<arg_key>"];
6
+ for (let at = text.indexOf("<"); at >= 0; at = text.indexOf("<", at + 1)) {
7
+ const tail = text.slice(at), lower = tail.toLowerCase();
8
+ if (prefixes.some(prefix => prefix.startsWith(lower)) || /^<\|?tool_call[s_a-z]*\|?$/i.test(tail)
9
+ || /^<\|?tool_call[s_a-z]*\|?>/i.test(tail) || lower.startsWith("<arg_key>")) return text.slice(0, at);
10
+ }
11
+ return text;
12
+ }
13
+
14
+ /** Shared display projection; private matching and lookahead use these same
15
+ * characters, while the provider's original replay text remains untouched. */
16
+ export function normalizeAssistantText(text: string, final = true): string {
17
+ if (!text) return text;
18
+ let cleaned = final ? text : stableStreamPrefix(text);
19
+ let previous: string;
20
+ // Deletions may enable an outer pair. A fixed point makes the projection
21
+ // idempotent across the loop, event boundary and final result serialization.
22
+ do {
23
+ previous = cleaned;
24
+ cleaned = cleaned
25
+ .replace(/<\|?tool_call[s_a-z]*\|?>[^]*?<\/?[|]?tool_call[s_a-z]*[|]?>/gi, "")
26
+ .replace(/<\|?tool_calls_section_begin\|?>[^]*?<\|?tool_calls_section_end\|?>/gi, "")
27
+ .replace(/<arg_key>[^<]*<\/arg_key><arg_value>[^<]*<\/arg_value>/gi, "");
28
+ } while (cleaned !== previous);
29
+ cleaned = cleaned.trimStart();
30
+ if (final) cleaned = cleaned.trimEnd();
31
+ const toolCallStart = cleaned.lastIndexOf("<|tool_call");
32
+ if (toolCallStart !== -1 && !cleaned.includes("<|tool_call", toolCallStart + 1)) cleaned = cleaned.slice(0, toolCallStart).trimEnd();
33
+ return cleaned;
34
+ }
@@ -0,0 +1,138 @@
1
+ import { AgentEventEmitter, type AgentEvent } from "./events.js";
2
+
3
+ export const PROMPT_LEAK_RUN_LENGTH = 300;
4
+ const PROMPT_LEAK_MARKERS = [
5
+ "# Persistent Memory",
6
+ "## Memory types",
7
+ "## How to save a memory",
8
+ "# Project Guidelines (from AGENTS.md)",
9
+ "[AGENT PROTOCOL]",
10
+ "<system-context>",
11
+ "<active_plan>",
12
+ "<system-reminder>",
13
+ ];
14
+
15
+ /** Exempt only bytes matching a host-classified public source. A shared tag
16
+ * does not exempt a different/private body following it. */
17
+ function matchesPublicSource(text: string, offset: number, width: number, sources: readonly string[]): boolean {
18
+ return sources.some(source => source.includes(text.slice(offset, offset + width)));
19
+ }
20
+
21
+ export function findPromptLeak(text: string, corpus: string, scanFrom = 0, publicSources: readonly string[] = []): Record<string, string> | undefined {
22
+ for (const marker of PROMPT_LEAK_MARKERS) {
23
+ if (!corpus.includes(marker)) continue;
24
+ for (let at = text.indexOf(marker); at >= 0; at = text.indexOf(marker, at + 1)) {
25
+ let width = marker.length;
26
+ if (publicSources.length) {
27
+ // A public document may end with a literal tag. Its tag alone must
28
+ // not exempt private bytes that follow the same tag in host context.
29
+ for (let sourceAt = corpus.indexOf(marker); sourceAt >= 0; sourceAt = corpus.indexOf(marker, sourceAt + 1)) {
30
+ let matched = marker.length;
31
+ while (matched < PROMPT_LEAK_RUN_LENGTH && at + matched < text.length && sourceAt + matched < corpus.length
32
+ && text[at + matched] === corpus[sourceAt + matched]) matched++;
33
+ width = Math.max(width, matched);
34
+ }
35
+ }
36
+ if (!matchesPublicSource(text, at, width, publicSources)) return { marker };
37
+ }
38
+ }
39
+ for (let i = Math.max(0, scanFrom); i + PROMPT_LEAK_RUN_LENGTH <= text.length; i++) {
40
+ if (corpus.includes(text.slice(i, i + PROMPT_LEAK_RUN_LENGTH))
41
+ && !matchesPublicSource(text, i, PROMPT_LEAK_RUN_LENGTH, publicSources)) return { reason: "long_verbatim_run" };
42
+ }
43
+ return undefined;
44
+ }
45
+
46
+ interface OutputBuffer {
47
+ text: string;
48
+ visible: string;
49
+ released: number;
50
+ finalized: number;
51
+ blocked?: string;
52
+ }
53
+
54
+ /** Guard the public event boundary, including preambles and visible reasoning.
55
+ * Keep a possible match private until the detector has enough characters to decide.
56
+ * Provider replay data and tool lifecycle events are left intact. */
57
+ export class PromptOutputEmitter extends AgentEventEmitter {
58
+ private buffers = new Map<string, OutputBuffer>();
59
+
60
+ constructor(
61
+ private guard: (text: string, scanFrom?: number) => string,
62
+ private enabled: () => boolean = () => true,
63
+ private normalize: (text: string, final: boolean) => string = text => text,
64
+ ) {
65
+ super();
66
+ }
67
+
68
+ clearOutputBuffers(): void {
69
+ this.buffers.clear();
70
+ }
71
+
72
+ override emit(event: AgentEvent): void {
73
+ // Descendants guard their own output against their own prompt and memory.
74
+ if (!this.enabled() || event.path?.length) { super.emit(event); return; }
75
+ if (event.type === "content_abandoned") this.buffers.delete(event.id);
76
+ if ((event.type !== "content_delta" && event.type !== "content_final")
77
+ || (event.kind !== "text" && event.kind !== "thinking")) {
78
+ super.emit(event);
79
+ return;
80
+ }
81
+ const buffer = this.buffers.get(event.id);
82
+ if (event.type === "content_final") {
83
+ // A tool preamble boundary is not EOF. Retain both the lookahead and
84
+ // unstable markup; previews keep their buffer until the complete final.
85
+ if (event.streamContinues) return;
86
+ const state = buffer ?? { text: event.text, visible: "", released: 0, finalized: 0 };
87
+ const projected = this.normalize(state.text, true);
88
+ const rawSafe = state.blocked ?? this.guard(state.text);
89
+ const safe = state.blocked ?? (rawSafe !== state.text ? rawSafe : this.guard(projected));
90
+ // A final may already have been replaced by the loop's output policy.
91
+ // Only release the checked projection, never a different raw tail.
92
+ const finalSafe = this.guard(this.normalize(event.text, true));
93
+ const isReplacement = finalSafe !== this.normalize(event.text, true)
94
+ || (buffer && event.text !== buffer.text && event.text !== buffer.text.slice(buffer.text.length - event.text.length)
95
+ && event.text !== projected);
96
+ const complete = state.blocked ?? (safe !== projected ? safe : isReplacement ? finalSafe : projected);
97
+ if (buffer && !buffer.blocked) {
98
+ const prefix = state.visible.slice(0, state.released);
99
+ const delta = complete.startsWith(prefix) ? complete.slice(state.released)
100
+ : prefix.startsWith(complete) ? "" : complete;
101
+ if (delta) super.emit({ ...event, type: "content_delta", text: delta });
102
+ }
103
+ const segment = state.blocked || complete !== projected ? complete : complete.slice(state.finalized);
104
+ if (complete !== projected) state.blocked = complete;
105
+ state.visible = complete;
106
+ state.released = complete.length;
107
+ state.finalized = complete.length;
108
+ this.buffers.set(event.id, state);
109
+ super.emit({ ...event, text: segment });
110
+ return;
111
+ }
112
+
113
+ const state = buffer ?? { text: "", visible: "", released: 0, finalized: 0 };
114
+ this.buffers.set(event.id, state);
115
+ if (state.blocked) return;
116
+ const scanFrom = Math.max(0, state.text.length - PROMPT_LEAK_RUN_LENGTH + 1);
117
+ state.text += event.text;
118
+ const visible = this.normalize(state.text, false);
119
+ const rawSafe = this.guard(state.text, scanFrom);
120
+ const safe = rawSafe !== state.text ? rawSafe : this.guard(visible,
121
+ visible.startsWith(state.visible) ? Math.max(0, state.visible.length - PROMPT_LEAK_RUN_LENGTH + 1) : 0);
122
+ if (rawSafe !== state.text || safe !== visible) {
123
+ state.blocked = safe;
124
+ super.emit({ ...event, text: safe });
125
+ return;
126
+ }
127
+ const prefix = state.visible.slice(0, state.released);
128
+ state.visible = visible;
129
+ if (!visible.startsWith(prefix)) return;
130
+ let end = Math.max(0, visible.length - PROMPT_LEAK_RUN_LENGTH + 1);
131
+ // Do not split a UTF-16 surrogate pair at the release boundary.
132
+ if (end > 0 && /[\uD800-\uDBFF]/.test(visible[end - 1]!)) end--;
133
+ end = Math.max(state.released, end);
134
+ const delta = visible.slice(state.released, end);
135
+ state.released = end;
136
+ if (delta) super.emit({ ...event, text: delta });
137
+ }
138
+ }
@@ -170,17 +170,23 @@ export class StreamingToolExecutor {
170
170
  // end-of-stream for thinking/text, arriving AFTER tool_call/tool_result
171
171
  // events — UI renders them in the wrong order.
172
172
  let textFinalized = false;
173
+ let textFinalizedAt = 0;
173
174
  let thinkingFinalized = false;
174
- const finalizeThinking = () => {
175
- if (thinkingId && thinking && !thinkingFinalized) {
176
- this.emitter.emit({ type: "content_final", kind: "thinking", id: thinkingId, text: thinking });
175
+ let thinkingFinalizedAt = 0;
176
+ const finalizeThinking = (complete = false) => {
177
+ if (thinkingId && (thinking.length > thinkingFinalizedAt || (complete && thinkingFinalized))) {
178
+ this.emitter.emit({ type: "content_final", kind: "thinking", id: thinkingId, text: thinking.slice(thinkingFinalizedAt),
179
+ ...(!complete ? { streamContinues: true } : {}) });
177
180
  thinkingFinalized = true;
181
+ thinkingFinalizedAt = thinking.length;
178
182
  }
179
183
  };
180
- const finalizeText = () => {
181
- if (textId && text && !textFinalized) {
182
- this.emitter.emit({ type: "content_final", kind: "text", id: textId, text });
184
+ const finalizeText = (complete = false) => {
185
+ if (textId && (text.length > textFinalizedAt || (complete && textFinalized))) {
186
+ this.emitter.emit({ type: "content_final", kind: "text", id: textId, text: text.slice(textFinalizedAt),
187
+ ...(!complete ? { streamContinues: true } : {}) });
183
188
  textFinalized = true;
189
+ textFinalizedAt = text.length;
184
190
  }
185
191
  };
186
192
  let finishReason: string | undefined;
@@ -346,7 +352,8 @@ export class StreamingToolExecutor {
346
352
  }
347
353
  }
348
354
  } catch (error) {
349
- finalizeThinking();
355
+ finalizeThinking(true);
356
+ finalizeText(true);
350
357
  const partial = { text, textId, textFinalEmitted: textFinalized, thinking, thinkingId, raw };
351
358
  if (signal?.aborted) throw await this.buildAbortError(partial);
352
359
  // Thinking-only failures retain RetryProvider's existing bounded retry
@@ -366,7 +373,8 @@ export class StreamingToolExecutor {
366
373
  // Stream ended without a tool_call_start (pure text or pure thinking
367
374
  // response). Catch any sections that weren't finalized yet in-loop. The
368
375
  // finalize* helpers no-op if already called, so this is idempotent.
369
- finalizeThinking();
376
+ finalizeThinking(true);
377
+ if (textFinalized || signal?.aborted) finalizeText(true);
370
378
  // Note: text is intentionally NOT finalized here — when there are no
371
379
  // tool calls, loop.ts applies cleanOutput to strip XML-style markup
372
380
  // before emitting. Finalizing raw text here would double-emit. The
@@ -20,6 +20,7 @@ export function assembleSubagentTool(input: AssemblyInput): { registry: ToolRegi
20
20
  if (registry.has("agent")) registry.unregister("agent");
21
21
  registry.register(input.factory({
22
22
  inheritedInstructions: config.inheritedInstructions,
23
+ publicPromptSections: config.publicPromptSections,
23
24
  provider: input.provider,
24
25
  promptProfile: input.promptProfile,
25
26
  getResultSchema: input.getResultSchema,
@@ -31,6 +31,7 @@ import type { DeferredAgentCoordinatorExecutor } from "../coordinator/executor-b
31
31
  export interface SubagentToolOptions {
32
32
  /** Host-owned constraints, preserved across custom roles and descendants. */
33
33
  inheritedInstructions?: string;
34
+ publicPromptSections?: readonly string[];
34
35
  /** Host-selected behavior profile, inherited by descendants. */
35
36
  promptProfile?: PromptProfile;
36
37
  getResultSchema?: () => "outcome-v1" | "legacy";
@@ -317,7 +318,7 @@ const AGENT_TYPES: Record<string, AgentTypeConfig> = {
317
318
  description: "File editing; see runtime shell capabilities below.",
318
319
  tools: null,
319
320
  basePrompt:
320
- "You are a writing subagent. Complete the given task using the tools available in your assigned workspace. Respect its execution and isolation boundaries. Output only your final result — the main agent will synthesize it.",
321
+ "You are a task subagent. Complete the given task using the tools available in your assigned workspace. Respect its execution and isolation boundaries. Output only your final result — the main agent will synthesize it.",
321
322
  },
322
323
  explore: {
323
324
  description: "Read-only inspection.",
@@ -328,7 +329,7 @@ const AGENT_TYPES: Record<string, AgentTypeConfig> = {
328
329
  description: "Read-only planning.",
329
330
  tools: PLAN_TOOLS,
330
331
  basePrompt:
331
- "You are an architecture subagent. Explore the codebase, then produce a clear step-by-step implementation plan. Do NOT write or modify code. Include: files to change, functions to add/modify, and potential risks.",
332
+ "You are a planning subagent. Inspect the relevant materials, then produce a clear step-by-step plan for the user's objective. Do NOT modify files. Include the expected deliverables, verification steps, dependencies and potential risks; do not assume the task requires programming.",
332
333
  },
333
334
  };
334
335
 
@@ -805,6 +806,7 @@ function createDirectSubagentTool(options: SubagentToolOptions): Tool {
805
806
  });
806
807
 
807
808
  const subagent = new LoopAgent({
809
+ publicPromptSections: options.publicPromptSections,
808
810
  provider: options.provider,
809
811
  registry,
810
812
  executor,
@@ -99,17 +99,22 @@ export async function mergeCopyArtifacts(
99
99
  .sort((a, b) => a.path.split("/").length - b.path.split("/").length);
100
100
  for (const operation of directories) operation.workingMode = operation.beforeMode! | 0o700;
101
101
  async function checkRoot(): Promise<string[]> {
102
- const current = await scanCopyTree(root, true);
102
+ const rawLinks: Record<string, string> = Object.create(null);
103
+ const current = await scanCopyTree(root, true, true, true, undefined, undefined, rawLinks);
103
104
  const conflicts = new Set<string>();
104
105
  for (const path of changedPaths) {
105
106
  if (!sameEntry(current[path], base[path])) conflicts.add(path);
107
+ const originalLink = manager.originalSourceLink(path) ?? (base[path]?.kind === "symlink" ? base[path].target : undefined);
108
+ if (originalLink !== undefined && originalLink !== rawLinks[path]) conflicts.add(path);
106
109
  // A replaced/deleted directory also owns its descendants. Never discard
107
110
  // concurrent additions or excluded private/control files inside it.
108
111
  if (base[path]?.kind === "directory" && desired[path]?.kind !== "directory") {
109
112
  for (const child of new Set([...Object.keys(base), ...Object.keys(current)])) {
110
113
  if (descendant(child, path) && !sameEntry(current[child], base[child])) conflicts.add(child);
111
114
  }
112
- const complete = await scanCopyTree(join(root, path));
115
+ // Root validation above already checked link targets; this subtree
116
+ // inventory never follows links and may contain links to root siblings.
117
+ const complete = await scanCopyTree(join(root, path), false, false);
113
118
  for (const child of Object.keys(complete)) {
114
119
  // Excluded environments may contain only regular files (--copies).
115
120
  // Replacing their parent must not silently delete those local files.
@@ -140,15 +145,19 @@ export async function mergeCopyArtifacts(
140
145
  // on failure if rollback cannot complete; never discard the user's originals.
141
146
  const transaction = join(root, `.zap-copy-merge-${randomUUID()}`);
142
147
  for (const operation of operations) {
143
- operation.before = await operationOid(join(snapshot, operation.path), operation.modeOnly);
148
+ operation.before = await operationOid(join(root, operation.path), operation.modeOnly);
144
149
  operation.after = await operationOid(join(staging, operation.path), operation.modeOnly);
145
150
  if (!operation.modeOnly && operation.beforeMode !== undefined) {
146
- operation.beforeWorking = await copyPathOid(join(snapshot, operation.path), operation.beforeMode | 0o700);
151
+ operation.beforeWorking = await copyPathOid(join(root, operation.path), operation.beforeMode | 0o700);
147
152
  }
148
153
  if (!operation.modeOnly && operation.afterMode !== undefined) {
149
154
  operation.afterWorking = await copyPathOid(join(staging, operation.path), operation.afterMode | 0o700);
150
155
  }
151
156
  }
157
+ // Compare the canonical baseline again after binding the original raw bytes
158
+ // for rollback (source absolute symlinks are relocated in snapshots).
159
+ drift = await checkRoot();
160
+ if (drift.length) return rejected("Root workspace changed while binding the merge", drift);
152
161
  const journal: CopyMergeJournal = { version: 1, root, transaction, artifactIds, operations, state: "applying" };
153
162
  await writeCopyMergeJournal(batch, journal);
154
163
  await mkdir(transaction, { mode: 0o700 });
@@ -191,6 +191,7 @@ function leaseFromState(workspace: PersistedWorkspaceState): WorkspaceLease {
191
191
  repoPath: workspace.repoPath,
192
192
  baseOid: workspace.baseOid,
193
193
  batchPath: workspace.batchPath,
194
+ ...(workspace.sourceLinksHash ? { sourceLinksHash: workspace.sourceLinksHash } : {}),
194
195
  };
195
196
  }
196
197
 
@@ -431,6 +431,7 @@ export class RuntimeStateTracker {
431
431
  mode: event.lease.mode,
432
432
  path: event.lease.path,
433
433
  batchPath: event.lease.batchPath,
434
+ ...(event.lease.sourceLinksHash ? { sourceLinksHash: event.lease.sourceLinksHash } : {}),
434
435
  status: "acquiring",
435
436
  acquiredAt: event.timestamp,
436
437
  updatedAt: event.timestamp,
@@ -449,6 +450,7 @@ export class RuntimeStateTracker {
449
450
  repoPath: event.lease.repoPath,
450
451
  baseOid: event.lease.baseOid,
451
452
  batchPath: event.lease.batchPath,
453
+ ...(event.lease.sourceLinksHash ? { sourceLinksHash: event.lease.sourceLinksHash } : {}),
452
454
  status: event.type === "workspace_hydrated" ? "preserved" : "active",
453
455
  acquiredAt: existing?.acquiredAt ?? event.timestamp,
454
456
  updatedAt: event.timestamp,
@@ -134,6 +134,7 @@ export interface PersistedWorkspaceState {
134
134
  repoPath?: string;
135
135
  baseOid?: string;
136
136
  batchPath?: string;
137
+ sourceLinksHash?: string;
137
138
  status: WorkspaceStateStatus;
138
139
  acquiredAt: number;
139
140
  updatedAt: number;
@@ -105,10 +105,26 @@ async function fileEntry(path: string, mode: number): Promise<CopyEntry> {
105
105
  } finally { await handle.close(); }
106
106
  }
107
107
 
108
+ /** Find the source-root spelling without flattening any link inside it. */
109
+ async function sourceLinkPath(root: string, canonicalRoot: string, target: string): Promise<string> {
110
+ for (const spelling of [resolve(root), canonicalRoot]) {
111
+ if (target === spelling) return "";
112
+ if (target.startsWith(spelling + sep)) return target.slice(spelling.length + 1);
113
+ }
114
+ // A host prefix such as /tmp may itself alias /private/tmp. Resolve only
115
+ // ancestors that denote the root, preserving the target's internal chain.
116
+ for (let parent = target; ; parent = dirname(parent)) {
117
+ if (await realpath(parent) === canonicalRoot) return target === parent ? "" : target.slice(parent.length + 1);
118
+ if (dirname(parent) === parent) break;
119
+ }
120
+ throw new Error("Absolute symlink does not name this source workspace");
121
+ }
122
+
108
123
  /** Never follows directory links. Hashing is streamed, including large inputs.
109
124
  * source=true excludes private/control files from the initial snapshot only;
110
125
  * introducing one in a child is rejected rather than silently losing edits. */
111
- export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>, privateGit?: PrivateGitBinding): Promise<CopyTree> {
126
+ export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>, privateGit?: PrivateGitBinding, originalLinks?: Record<string, string>): Promise<CopyTree> {
127
+ const canonicalRoot = await realpath(root);
112
128
  const info = await lstat(root);
113
129
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`Unsafe copy workspace root: ${root}`);
114
130
  const validatePrivateGit = async () => {
@@ -134,16 +150,25 @@ export async function scanCopyTree(root: string, source = false, validateLinks =
134
150
  const full = join(root, path);
135
151
  const stat = await lstat(full);
136
152
  if (stat.isSymbolicLink()) {
137
- const target = await readlink(full);
138
- if (validateLinks && (isAbsolute(target) || !isWithin(root, resolve(dirname(full), target)))) {
153
+ let target = await readlink(full);
154
+ if (originalLinks) originalLinks[path] = target;
155
+ if (validateLinks && (!source && isAbsolute(target) || !isAbsolute(target) && !isWithin(root, resolve(dirname(full), target)))) {
139
156
  throw new Error(`Symlink escapes copy workspace: ${path}`);
140
157
  }
141
158
  // Reject dangling/cyclic links, and links which escape indirectly.
142
159
  if (validateLinks) {
143
160
  const resolved = await realpath(full);
144
- if (!isWithin(root, resolved) || excludedCopyPath(relative(root, resolved).split(sep).join("/"))) {
161
+ if (!isWithin(canonicalRoot, resolved) || excludedCopyPath(relative(canonicalRoot, resolved).split(sep).join("/"))) {
145
162
  throw new Error(`Unsafe copy workspace symlink: ${path}`);
146
163
  }
164
+ // Source links may name a host path inside the same tree. Relocate
165
+ // only that verified target; snapshots must never point at the host.
166
+ if (source && isAbsolute(target)) {
167
+ const sourcePath = await sourceLinkPath(root, canonicalRoot, target);
168
+ if (excludedCopyPath(sourcePath)) throw new Error(`Unsafe copy workspace symlink: ${path}`);
169
+ const depth = dirname(path) === "." ? 0 : dirname(path).split("/").length;
170
+ target = "../".repeat(depth) + (sourcePath || ".");
171
+ }
147
172
  }
148
173
  tree[path] = { kind: "symlink", target };
149
174
  } else if (stat.isDirectory()) {