zapagent 1.14.12 → 1.14.14
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.
- package/bundled-dependencies.json +201 -201
- package/package.json +1 -1
- package/src/agent/buildAgentRuntime.ts +6 -1
- package/src/agent/promptDiagnostics.ts +8 -1
- package/src/commands/dispatcher.ts +1 -1
- package/src/commands/status.ts +7 -32
- package/src/config.ts +7 -2
- package/src/goal-command.ts +44 -17
- package/src/goal-host.ts +71 -38
- package/src/goal-runner.ts +1 -1
- package/src/headless/goalPhase.ts +17 -8
- package/src/headless/runHeadless.ts +6 -2
- package/src/hooks/useAgentRunner.ts +2 -1
- package/src/hooks/useTurnDispatcher.ts +3 -0
- package/src/prompts/context.ts +4 -3
- package/src/prompts/registry.ts +4 -3
- package/src/prompts/required-sections.ts +26 -0
- package/src/prompts/sections/agents-md.ts +24 -11
- package/src/prompts/sections/concise.ts +2 -2
- package/src/prompts/sections/file-reading.ts +2 -2
- package/src/prompts/sections/identity.ts +2 -2
- package/src/prompts/sections/plan-discipline.ts +2 -2
- package/src/prompts/sections/safety.ts +1 -1
- package/src/prompts/sections/skills.ts +4 -3
- package/src/prompts/sections/system.ts +4 -3
- package/src/prompts/sections/tasks.ts +1 -1
- package/src/ui/slash-palette.tsx +1 -0
- package/zapsdk/agent/events.ts +3 -0
- package/zapsdk/agent/loop.ts +33 -62
- package/zapsdk/agent/output-text.ts +34 -0
- package/zapsdk/agent/prompt-output-guard.ts +138 -0
- package/zapsdk/agent/streaming-tool-executor.ts +16 -8
- package/zapsdk/agent/subagent-assembly.ts +1 -0
- package/zapsdk/builtin-tools/subagent.ts +4 -2
- package/zapsdk/goal/acceptance.ts +2 -0
- package/zapsdk/goal/contracts.ts +14 -2
- package/zapsdk/goal/controller.ts +123 -66
- package/zapsdk/goal/errors.ts +17 -0
- package/zapsdk/goal/scheduler.ts +34 -0
- package/zapsdk/goal/store.ts +42 -6
- package/zapsdk/goal/structured-output.ts +84 -0
package/zapsdk/agent/loop.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
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
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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 &&
|
|
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
|
|
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
|
|
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,
|
|
@@ -18,12 +18,14 @@ export interface GoalAcceptanceReceipt {
|
|
|
18
18
|
planRevision: number;
|
|
19
19
|
taskSpecRevision: number;
|
|
20
20
|
verifierVersion: string;
|
|
21
|
+
verificationId?: string;
|
|
21
22
|
}
|
|
22
23
|
export interface GoalAcceptanceBinding {
|
|
23
24
|
goalSpecRevision: number;
|
|
24
25
|
planRevision: number;
|
|
25
26
|
taskSpecRevision: number;
|
|
26
27
|
verifierVersion: string;
|
|
28
|
+
verificationId?: string;
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
/** Host-only: the supplied verifiers must execute independently under the
|
package/zapsdk/goal/contracts.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Goal control records are Host-owned. Agent output is a proposal, never a state transition. */
|
|
2
|
-
export type GoalStatus = "created" | "running" | "paused" | "blocked" | "awaiting_acceptance" | "ready_for_delivery" | "completed" | "cancelled" | "failed";
|
|
2
|
+
export type GoalStatus = "created" | "running" | "paused" | "blocked" | "awaiting_acceptance" | "budget_limited" | "ready_for_delivery" | "completed" | "cancelled" | "failed";
|
|
3
3
|
export type GoalPhase = "planning" | "executing" | "verifying" | "repairing" | "integrating" | "final_verifying" | "delivering" | "sealing";
|
|
4
4
|
export interface GoalTask {
|
|
5
5
|
id: string;
|
|
@@ -22,6 +22,8 @@ export interface GoalReceipt {
|
|
|
22
22
|
/** Immutable record returned by the host verifier; never the worker's claim. */
|
|
23
23
|
evidence: unknown;
|
|
24
24
|
detail?: string;
|
|
25
|
+
/** Stable failed-check identity, excluding model prose and timestamps. */
|
|
26
|
+
failureFingerprint?: string;
|
|
25
27
|
}
|
|
26
28
|
export interface GoalRecord {
|
|
27
29
|
id: string;
|
|
@@ -31,6 +33,8 @@ export interface GoalRecord {
|
|
|
31
33
|
/** User-authorized, host-managed dependency preparation. */
|
|
32
34
|
dependencyInstall?: "npm";
|
|
33
35
|
permissionMode: "default" | "acceptEdits" | "plan" | "bypassPermissions";
|
|
36
|
+
/** Present for TUI-created Goals; foreground input in another chat cannot pause it. */
|
|
37
|
+
sessionId?: string;
|
|
34
38
|
cwd: string;
|
|
35
39
|
stateRevision: number;
|
|
36
40
|
specRevision: number;
|
|
@@ -40,15 +44,22 @@ export interface GoalRecord {
|
|
|
40
44
|
stopReason?: string;
|
|
41
45
|
createdAt: number;
|
|
42
46
|
updatedAt: number;
|
|
43
|
-
|
|
47
|
+
/** Optional user-imposed deadline; absent Goals run until accepted or interrupted. */
|
|
48
|
+
deadlineAt?: number;
|
|
44
49
|
ownerEpoch: number;
|
|
45
50
|
owner?: { instanceId: string; pid: number };
|
|
46
51
|
/** Intent persisted before external work. Recovery must reconcile before retry. */
|
|
47
52
|
inFlight?: { operationId: string; phase: GoalPhase; taskId?: string; opaqueBefore?: number };
|
|
48
53
|
control?: "pause" | "cancel";
|
|
54
|
+
/** Foreground input yields at a sealed phase boundary, without killing a live tool. */
|
|
55
|
+
yieldRequested?: boolean;
|
|
49
56
|
tasks: GoalTask[];
|
|
50
57
|
integration?: unknown;
|
|
58
|
+
finalCandidate?: GoalCandidate;
|
|
51
59
|
finalReceipt?: GoalReceipt;
|
|
60
|
+
/** Host-observed progress across failed attempts; persists across runner restarts. */
|
|
61
|
+
progress?: Record<string, { fingerprint: string; stalled: number; checks: number }>;
|
|
62
|
+
failure?: { code: string; phase?: GoalPhase; operationId?: string; taskId?: string; candidateId?: string; snapshotId?: string };
|
|
52
63
|
delivery?: unknown;
|
|
53
64
|
}
|
|
54
65
|
export interface GoalPlanProposal {
|
|
@@ -59,6 +70,7 @@ export interface GoalCandidate {
|
|
|
59
70
|
snapshotId: string;
|
|
60
71
|
specDigest: string;
|
|
61
72
|
value: unknown;
|
|
73
|
+
activity?: { toolCalls: number; changed: boolean; fingerprint: string };
|
|
62
74
|
}
|
|
63
75
|
export interface GoalOperationContext {
|
|
64
76
|
goal: Readonly<GoalRecord>;
|