zapagent 1.14.25 → 1.14.26
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/package.json +1 -1
- package/src/agent/contextAttachments.ts +4 -2
- package/src/agent-factory.ts +2 -10
- package/src/headless/goalPhase.ts +3 -3
- package/src/headless/runHeadless.ts +4 -5
- package/src/singletons.ts +4 -14
- package/src/ui/dialog-rewind.tsx +1 -1
- package/zapsdk/agent/loop.ts +51 -4
- package/zapsdk/agent/tool-execution-guards.ts +23 -37
- package/zapsdk/builtin-tools/index.ts +11 -16
- package/zapsdk/builtin-tools/plan-mode.ts +1 -1
- package/zapsdk/builtin-tools/subagent.ts +2 -2
package/package.json
CHANGED
|
@@ -1371,11 +1371,13 @@ function buildDiagnosticsFromSegments(segments: ContextSegment[], fullText: stri
|
|
|
1371
1371
|
|
|
1372
1372
|
/** Review observed work against the original request before natural finish.
|
|
1373
1373
|
* LoopAgent bounds this to one reminder and permits an honest incomplete
|
|
1374
|
-
* response.
|
|
1374
|
+
* response. The review costs a model call, so it runs only when there is
|
|
1375
|
+
* something to reconcile: an unfinished todo or a failed tool call, even if
|
|
1376
|
+
* the todo list was cleared afterwards. */
|
|
1375
1377
|
export function makeTurnEndGuard(getTodos: () => Todo[]): (result?: Pick<LoopAgentResult, "toolResults">) => string | null {
|
|
1376
1378
|
return (result) => {
|
|
1377
1379
|
const active = getTodos().find((t) => t.status === "in_progress")
|
|
1378
|
-
if (!active && !result?.toolResults.
|
|
1380
|
+
if (!active && !result?.toolResults.some((r) => !r.success)) return null
|
|
1379
1381
|
return (
|
|
1380
1382
|
"<system-reminder>\n" +
|
|
1381
1383
|
(active ? `Todo "${escapeContextText(active.content)}" remains in_progress.\n` : "") +
|
package/src/agent-factory.ts
CHANGED
|
@@ -29,7 +29,7 @@ import type { CheckpointManager } from "../zapsdk/checkpoint/index.js"
|
|
|
29
29
|
import { loadAllSkills } from "../zapsdk/skills/loader.js"
|
|
30
30
|
import type { SkillDefinition } from "../zapsdk/skills/types.js"
|
|
31
31
|
import type { AgentEventHandler } from "../zapsdk/agent/events.js"
|
|
32
|
-
import { autoMemory,
|
|
32
|
+
import { autoMemory, taskStore, mdStore, globalMdStore, globalMemoryDir, delegateProviders, delegateEventBridge } from "./singletons.js"
|
|
33
33
|
import { memorySaveTool } from "../zapsdk/builtin-tools/memory.js"
|
|
34
34
|
import type { AgentObjects } from "./agent/types.js"
|
|
35
35
|
import type { LLMProvider } from "../zapsdk/core/llm.js"
|
|
@@ -38,7 +38,7 @@ import { createExecutionEnvironment, resolveExecutionBackend, type ExecutionEnvi
|
|
|
38
38
|
|
|
39
39
|
const CWD_SENSITIVE_TOOLS = new Set([
|
|
40
40
|
"read_file", "write_file", "edit_file", "multi_edit",
|
|
41
|
-
"delete_file", "
|
|
41
|
+
"delete_file", "list_tree", "bash",
|
|
42
42
|
"search_files", "glob_files", "read_document", "browser_screenshot", "delegate_agent", "generate_image",
|
|
43
43
|
])
|
|
44
44
|
|
|
@@ -164,7 +164,6 @@ export function buildAgentObjects(
|
|
|
164
164
|
editFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
165
165
|
multiEdit: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
166
166
|
deleteFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
167
|
-
moveFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
168
167
|
listTree: { allowedPaths, useExecutionGrants: true },
|
|
169
168
|
searchFiles: { allowedPaths, useExecutionGrants: true },
|
|
170
169
|
globFiles: { allowedPaths, useExecutionGrants: true },
|
|
@@ -204,12 +203,6 @@ export function buildAgentObjects(
|
|
|
204
203
|
}
|
|
205
204
|
},
|
|
206
205
|
} : undefined,
|
|
207
|
-
// Cron + monitor: session-scoped singleton handles owned by the CLI
|
|
208
|
-
// (see singletons.ts). Subagents strip these out of their cloned
|
|
209
|
-
// registry — jobs created in a subagent would otherwise outlive it
|
|
210
|
-
// and fire with main-agent authority.
|
|
211
|
-
cronHandle,
|
|
212
|
-
monitorHandle,
|
|
213
206
|
taskTools: { store: taskStore },
|
|
214
207
|
// Delegate (claude / codex CLI hand-off): only registered when the PATH
|
|
215
208
|
// probe in singletons.ts found at least one provider. The onEvent forwards
|
|
@@ -243,7 +236,6 @@ export function buildAgentObjects(
|
|
|
243
236
|
editFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
244
237
|
multiEdit: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
245
238
|
deleteFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
246
|
-
moveFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
|
|
247
239
|
listTree: { allowedPaths, useExecutionGrants: true },
|
|
248
240
|
searchFiles: { allowedPaths, useExecutionGrants: true },
|
|
249
241
|
globFiles: { allowedPaths, useExecutionGrants: true },
|
|
@@ -58,13 +58,13 @@ export async function runGoalMachineCommand(command: string, execute: () => Prom
|
|
|
58
58
|
|
|
59
59
|
/** These local tools do not launch opaque model requests. */
|
|
60
60
|
const GOAL_TOOLS = new Set([
|
|
61
|
-
"read_file", "write_file", "edit_file", "multi_edit", "delete_file",
|
|
61
|
+
"read_file", "write_file", "edit_file", "multi_edit", "delete_file",
|
|
62
62
|
"list_tree", "read_document", "read_pdf", "read_docx",
|
|
63
|
-
"read_tool_output", "todo_write",
|
|
63
|
+
"read_tool_output", "todo_write",
|
|
64
64
|
])
|
|
65
65
|
const READ_ONLY_GOAL_TOOLS = new Set([
|
|
66
66
|
"read_file", "list_tree", "read_document", "read_pdf", "read_docx",
|
|
67
|
-
"read_tool_output",
|
|
67
|
+
"read_tool_output",
|
|
68
68
|
])
|
|
69
69
|
|
|
70
70
|
export interface GoalPhaseInput {
|
|
@@ -55,7 +55,7 @@ import {
|
|
|
55
55
|
readCheckpointJournal,
|
|
56
56
|
peekJournalLogIndex,
|
|
57
57
|
} from "../session.js"
|
|
58
|
-
import { conversation, autoMemory, taskStore,
|
|
58
|
+
import { conversation, autoMemory, taskStore, mdStore, globalMdStore, globalMemoryDir, memorySemanticRetriever, tokenAccounting, delegateProvidersReady } from "../singletons.js"
|
|
59
59
|
import { buildAgentObjects } from "../agent-factory.js"
|
|
60
60
|
import { CheckpointManager } from "../../zapsdk/checkpoint/index.js"
|
|
61
61
|
import {
|
|
@@ -531,7 +531,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
531
531
|
if (host.readOnlyWorkspace) {
|
|
532
532
|
// No network tools: read-only Goal roles take worker output and workspace
|
|
533
533
|
// files as untrusted input, and an injected URL could carry them off-host.
|
|
534
|
-
const names = new Set(["read_file", "list_tree", "read_document", "read_pdf", "read_docx", "read_tool_output"
|
|
534
|
+
const names = new Set(["read_file", "list_tree", "read_document", "read_pdf", "read_docx", "read_tool_output"])
|
|
535
535
|
if (sandboxConfined && registry.has("bash")) {
|
|
536
536
|
registry.unregister("bash"); registry.register(readOnlyBashTool(cwd)); names.add("bash")
|
|
537
537
|
}
|
|
@@ -540,7 +540,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
540
540
|
await host.prepareRegistry?.(registry)
|
|
541
541
|
if (publicChecks) {
|
|
542
542
|
// These tools start work outside the root provider admission budget.
|
|
543
|
-
for (const name of ["agent", "delegate_agent"
|
|
543
|
+
for (const name of ["agent", "delegate_agent"]) registry.unregister(name)
|
|
544
544
|
}
|
|
545
545
|
|
|
546
546
|
// ── System prompt + per-turn attachments (mirror useAgentRunner) ─────
|
|
@@ -778,7 +778,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
778
778
|
//
|
|
779
779
|
// Fix: strip the singleton signal handlers for the duration of the run.
|
|
780
780
|
// The `process.on("exit", _shutdown)` hook in singletons still fires on
|
|
781
|
-
// natural exit, so taskStore
|
|
781
|
+
// natural exit, so taskStore cleanup is preserved.
|
|
782
782
|
const previousSigintListeners = process.listeners("SIGINT")
|
|
783
783
|
const previousSigtermListeners = process.listeners("SIGTERM")
|
|
784
784
|
process.removeAllListeners("SIGINT")
|
|
@@ -888,7 +888,6 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
888
888
|
// (singletons.ts already wires process.on("exit") cleanup; calling here
|
|
889
889
|
// ensures cleanup before exit code is set when running embedded.)
|
|
890
890
|
try { taskStore.stopAll("SIGTERM") } catch {}
|
|
891
|
-
try { cronHandle.stop() } catch {}
|
|
892
891
|
|
|
893
892
|
if (outcomeFailure) return outcomeFailure.code === "REPAIR_CANCELLED" ? 130
|
|
894
893
|
: outcomeFailure.code === "REPAIR_DEADLINE_EXCEEDED" ? 124 : EXIT_ERROR
|
package/src/singletons.ts
CHANGED
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
AgentLogger,
|
|
16
16
|
} from "../zapsdk/index.js"
|
|
17
17
|
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
18
|
-
import {
|
|
18
|
+
import { detectProviders, type DetectedProvider } from "../zapsdk/builtin-tools/index.js"
|
|
19
19
|
import { TaskStore } from "../zapsdk/tasks/store.js"
|
|
20
20
|
import { buildTaskNotificationXml, classifyTaskExit } from "../zapsdk/tasks/notification.js"
|
|
21
21
|
import { pushSystemEvent } from "./queue/systemInbox.js"
|
|
@@ -106,17 +106,9 @@ export const tokenAccounting = {
|
|
|
106
106
|
promptOverhead: 0,
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
//
|
|
110
|
-
// Singletons (not per-config-reload): session-only jobs should survive
|
|
111
|
-
// config changes but die with the process. No `agentId` → main agent has
|
|
112
|
-
// team-lead semantics (sees and deletes all jobs). `onFire` is left
|
|
113
|
-
// undefined until the CLI prompt-queue integration is wired — fires are
|
|
114
|
-
// recorded on the job (lastFiredAt) but do not inject into agent turns yet.
|
|
115
|
-
export const cronHandle = cronTools({})
|
|
116
|
-
// Single shared TaskStore — monitor, bash bg, and future task_* tools all
|
|
109
|
+
// Single shared TaskStore — bash background commands and the task_* tools
|
|
117
110
|
// register and look up tasks here so the UI gets a unified view.
|
|
118
111
|
export const taskStore = new TaskStore({ projectCwd: process.cwd() })
|
|
119
|
-
export const monitorHandle = monitorTool({ store: taskStore })
|
|
120
112
|
|
|
121
113
|
// ─── Task-completion → systemInbox bridge ───
|
|
122
114
|
// When a background task exits, build a `<task-notification>` XML payload
|
|
@@ -142,15 +134,13 @@ taskStore.on("exited", (e) => {
|
|
|
142
134
|
})
|
|
143
135
|
|
|
144
136
|
// ─── Process shutdown cleanup ───
|
|
145
|
-
// Kill every still-running
|
|
146
|
-
// processes orphaned.
|
|
147
|
-
// process; calling stop() is belt-and-suspenders.
|
|
137
|
+
// Kill every still-running background command so Ctrl-C doesn't leave
|
|
138
|
+
// processes orphaned.
|
|
148
139
|
let _shutdownRan = false
|
|
149
140
|
function _shutdown(): void {
|
|
150
141
|
if (_shutdownRan) return
|
|
151
142
|
_shutdownRan = true
|
|
152
143
|
try { taskStore.stopAll("SIGTERM") } catch {}
|
|
153
|
-
try { cronHandle.stop() } catch {}
|
|
154
144
|
}
|
|
155
145
|
process.on("exit", _shutdown)
|
|
156
146
|
const shutdownOnInterrupt = () => { _shutdown(); process.exit(130) }
|
package/src/ui/dialog-rewind.tsx
CHANGED
|
@@ -153,7 +153,7 @@ export function RewindDialog({ checkpoint, logs, onApply, onCancel, isRunning }:
|
|
|
153
153
|
{diag.enabled && diag.pendingCount === 0 && (
|
|
154
154
|
<Box marginTop={1} flexDirection="column">
|
|
155
155
|
<Text color={c.text.faint}>Recovery points are created before each turn. File undo covers:</Text>
|
|
156
|
-
<Text color={c.text.faint}> write_file · edit_file · multi_edit · delete_file
|
|
156
|
+
<Text color={c.text.faint}> write_file · edit_file · multi_edit · delete_file</Text>
|
|
157
157
|
<Text color={c.text.faint}>File edits via bash (sed -i, cat > …) are not tracked.</Text>
|
|
158
158
|
</Box>
|
|
159
159
|
)}
|
package/zapsdk/agent/loop.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { normalizeAssistantText } from "./output-text.js";
|
|
|
8
8
|
import { earliestDeadlineAt } from "../execution/deadline.js";
|
|
9
9
|
import { toolOutputTool } from "../builtin-tools/tool-output.js";
|
|
10
10
|
import { assembleSubagentTool } from "./subagent-assembly.js";
|
|
11
|
-
import { type TaskDecompositionMode, primaryArgSig, stepSignature, createRunToolExecutionHooks, isRepeatFriendlyStep, isLiveTaskWait, progressPollSignature } from "./tool-execution-guards.js";
|
|
11
|
+
import { type TaskDecompositionMode, primaryArgSig, stepSignature, createRunToolExecutionHooks, duplicateQueryKey, isDuplicateQuery, isRepeatFriendlyStep, isLiveTaskWait, progressPollSignature } from "./tool-execution-guards.js";
|
|
12
12
|
import type { LLMProvider, LLMCallOptions } from "../core/llm.js";
|
|
13
13
|
import { hasMeaningfulOutput } from "../core/provider-request.js";
|
|
14
14
|
import { assertProviderRequestAllowed } from "../core/provider-deadline.js";
|
|
@@ -962,6 +962,10 @@ export class LoopAgent {
|
|
|
962
962
|
} else {
|
|
963
963
|
localMessages = msgs;
|
|
964
964
|
}
|
|
965
|
+
// Pruning and compaction shorten earlier results. A duplicate notice
|
|
966
|
+
// must never point the model at output it can no longer see.
|
|
967
|
+
seenFiles.clear();
|
|
968
|
+
toolExecutionHooks.forgetObservations();
|
|
965
969
|
};
|
|
966
970
|
this.recoveryContext = (requestMessages) => {
|
|
967
971
|
let revision: string | undefined;
|
|
@@ -2486,7 +2490,9 @@ export class LoopAgent {
|
|
|
2486
2490
|
seenFiles: SeenFiles,
|
|
2487
2491
|
success: boolean,
|
|
2488
2492
|
): { content: string; suppression?: "duplicate" } {
|
|
2489
|
-
if (!toolCall.name.includes("read_file") && toolCall.name !== "pr_file_content")
|
|
2493
|
+
if (!toolCall.name.includes("read_file") && toolCall.name !== "pr_file_content") {
|
|
2494
|
+
return this.deduplicateQuery(toolCall, resultContent, seenFiles, success);
|
|
2495
|
+
}
|
|
2490
2496
|
if (!(toolCall.arguments as any).path && !(toolCall.arguments as any).ref) return { content: resultContent };
|
|
2491
2497
|
|
|
2492
2498
|
const filePath = String((toolCall.arguments as any).path ?? (toolCall.arguments as any).ref ?? "");
|
|
@@ -2507,6 +2513,36 @@ export class LoopAgent {
|
|
|
2507
2513
|
return { content: resultContent };
|
|
2508
2514
|
}
|
|
2509
2515
|
|
|
2516
|
+
/** Fold a repeated search or read-only shell query whose output has not
|
|
2517
|
+
* changed. The query has already run, so a change made outside the agent's
|
|
2518
|
+
* tools still reaches the model. */
|
|
2519
|
+
private deduplicateQuery(
|
|
2520
|
+
toolCall: ToolCallRequest,
|
|
2521
|
+
resultContent: string,
|
|
2522
|
+
seenFiles: SeenFiles,
|
|
2523
|
+
success: boolean,
|
|
2524
|
+
): { content: string; suppression?: "duplicate" } {
|
|
2525
|
+
const args = (toolCall.arguments ?? {}) as Record<string, unknown>;
|
|
2526
|
+
if (!isDuplicateQuery(toolCall.name, args)) return { content: resultContent };
|
|
2527
|
+
const key = duplicateQueryKey(toolCall.name, args);
|
|
2528
|
+
if (!success) {
|
|
2529
|
+
seenFiles.delete(key);
|
|
2530
|
+
return { content: resultContent };
|
|
2531
|
+
}
|
|
2532
|
+
const contentHash = createHash("sha256").update(resultContent).digest("hex");
|
|
2533
|
+
if (seenFiles.get(key) === contentHash) {
|
|
2534
|
+
const target = primaryArgSig(toolCall.name, args) || "the same arguments";
|
|
2535
|
+
this.emitter.emit({ type: "observation", kind: "duplicate_tool_suppressed", detail: { tool: toolCall.name, target } });
|
|
2536
|
+
return {
|
|
2537
|
+
content: `[Duplicate ${toolCall.name} suppressed for ${target}. It returned the same output as the previous call; ` +
|
|
2538
|
+
"reuse that result and choose the next concrete action.]",
|
|
2539
|
+
suppression: "duplicate",
|
|
2540
|
+
};
|
|
2541
|
+
}
|
|
2542
|
+
seenFiles.set(key, contentHash);
|
|
2543
|
+
return { content: resultContent };
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2510
2546
|
/** Append error classification hints or system notices to the result content. */
|
|
2511
2547
|
private classifyError(
|
|
2512
2548
|
toolCall: ToolCallRequest,
|
|
@@ -2515,12 +2551,23 @@ export class LoopAgent {
|
|
|
2515
2551
|
resultContent: string,
|
|
2516
2552
|
): string {
|
|
2517
2553
|
if (result.success) {
|
|
2518
|
-
|
|
2554
|
+
// A successful change to the workspace makes every earlier failure
|
|
2555
|
+
// worth retrying: rerunning tests after an edit is not a blind retry.
|
|
2556
|
+
const readOnly = this.executor.workspaceGate
|
|
2557
|
+
? !!result.runtime?.effects && isEffectivelyReadOnly(result.runtime.effects)
|
|
2558
|
+
: this.executor.isReadOnly(toolCall.name, toolCall.arguments);
|
|
2559
|
+
if (readOnly) errorTracker.delete(toolCall.name);
|
|
2560
|
+
else errorTracker.clear();
|
|
2519
2561
|
return resultContent;
|
|
2520
2562
|
}
|
|
2521
2563
|
if (!result.error) return resultContent;
|
|
2522
2564
|
|
|
2523
|
-
|
|
2565
|
+
// Count only the identical call failing identically. Error headers such as
|
|
2566
|
+
// "Command failed: <cmd> … Message: <first line>" repeat across different
|
|
2567
|
+
// test failures, so the whole observation is part of the signature.
|
|
2568
|
+
const errorSig = createHash("sha256")
|
|
2569
|
+
.update(JSON.stringify([toolCall.arguments ?? {}, result.error, result.output ?? ""]))
|
|
2570
|
+
.digest("hex");
|
|
2524
2571
|
if (!errorTracker.has(toolCall.name)) errorTracker.set(toolCall.name, new Map());
|
|
2525
2572
|
const toolErrors = errorTracker.get(toolCall.name)!;
|
|
2526
2573
|
const count = (toolErrors.get(errorSig) ?? 0) + 1;
|
|
@@ -2,7 +2,6 @@ import type { ToolResult } from "../tools/types.js";
|
|
|
2
2
|
import type { ToolExecutor } from "../tools/executor.js";
|
|
3
3
|
import type { ToolExecutionHooks } from "./streaming-tool-executor.js";
|
|
4
4
|
import { operationFailure } from "../execution/failure.js";
|
|
5
|
-
import { isEffectivelyReadOnly } from "../tools/effects.js";
|
|
6
5
|
import { canonicalizeJsonSchema } from "../tools/schema.js";
|
|
7
6
|
import { sliceHeadCodePoints } from "../utils/logical-lines.js";
|
|
8
7
|
import { createHash } from "node:crypto";
|
|
@@ -103,11 +102,11 @@ const READ_ONLY_GIT_SUBCOMMANDS = new Set([
|
|
|
103
102
|
|
|
104
103
|
/**
|
|
105
104
|
* The shell tool declares a conservative read+write effect because arbitrary
|
|
106
|
-
* shell is impossible to prove safe. For duplicate
|
|
105
|
+
* shell is impossible to prove safe. For duplicate folding we can still
|
|
107
106
|
* recognise a deliberately tiny subset of inspection commands. This is not
|
|
108
|
-
* a permission decision: it
|
|
109
|
-
*
|
|
110
|
-
*
|
|
107
|
+
* a permission decision: it only lets an identical repeated result be folded.
|
|
108
|
+
* Anything involving shell composition or a potentially writing flag is never
|
|
109
|
+
* folded.
|
|
111
110
|
*/
|
|
112
111
|
function isMemoizableBashQuery(args: Record<string, unknown>): boolean {
|
|
113
112
|
if (args.run_in_background === true || typeof args.command !== "string") return false;
|
|
@@ -146,7 +145,11 @@ function isMemoizableBashQuery(args: Record<string, unknown>): boolean {
|
|
|
146
145
|
return true;
|
|
147
146
|
}
|
|
148
147
|
|
|
149
|
-
|
|
148
|
+
/** Local queries whose identical repeated output may be folded into a pointer
|
|
149
|
+
* to the earlier result. They still execute: a file can change outside the
|
|
150
|
+
* agent's own tools (the user's editor, a background job), and only the fresh
|
|
151
|
+
* output can show that. */
|
|
152
|
+
export function isDuplicateQuery(name: string, args: Record<string, unknown>): boolean {
|
|
150
153
|
return DUPLICATE_QUERY_TOOLS.has(name) || (name === "bash" && isMemoizableBashQuery(args));
|
|
151
154
|
}
|
|
152
155
|
|
|
@@ -160,7 +163,7 @@ function httpFetchKey(name: string, args: Record<string, unknown>): string | und
|
|
|
160
163
|
return `${method} ${args.url}${args.raw === true ? " raw" : ""}`;
|
|
161
164
|
}
|
|
162
165
|
|
|
163
|
-
function duplicateQueryKey(name: string, args: Record<string, unknown>): string {
|
|
166
|
+
export function duplicateQueryKey(name: string, args: Record<string, unknown>): string {
|
|
164
167
|
return `${name}:${JSON.stringify(canonicalizeJsonSchema(args))}`;
|
|
165
168
|
}
|
|
166
169
|
|
|
@@ -220,22 +223,28 @@ function taskPlanRequiredResult(mode: TaskDecompositionMode): ToolResult {
|
|
|
220
223
|
};
|
|
221
224
|
}
|
|
222
225
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
226
|
+
export interface RunToolExecutionHooks extends ToolExecutionHooks {
|
|
227
|
+
/** Forget fetched pages once history is rewritten: their results may have
|
|
228
|
+
* been compacted away, so "reuse that result" would point at nothing. */
|
|
229
|
+
forgetObservations(): void;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Reuse a recent remote fetch instead of repeating it. Local reads and
|
|
233
|
+
* searches are not suppressed here; LoopAgent folds an identical result after
|
|
234
|
+
* it runs. */
|
|
228
235
|
export function createRunToolExecutionHooks(
|
|
229
236
|
executor: ToolExecutor,
|
|
230
237
|
onSuppressed: (name: string, args: Record<string, unknown>) => void,
|
|
231
238
|
taskDecomposition: TaskDecompositionMode,
|
|
232
239
|
hasTodoTool: boolean,
|
|
233
|
-
):
|
|
234
|
-
const completedOrInFlight = new Set<string>();
|
|
240
|
+
): RunToolExecutionHooks {
|
|
235
241
|
// Remote GETs do not depend on the workspace, so a mutation must not forget them.
|
|
236
242
|
const fetchedUrls = new Map<string, number>();
|
|
237
243
|
const planState: TaskPlanGateState = { ready: false, baselineReads: 0 };
|
|
238
244
|
return {
|
|
245
|
+
forgetObservations() {
|
|
246
|
+
fetchedUrls.clear();
|
|
247
|
+
},
|
|
239
248
|
beforeExecute(name, args) {
|
|
240
249
|
// Planning is not a permission boundary. Only an explicitly required
|
|
241
250
|
// plan may block execution; auto must not turn a short task into retries.
|
|
@@ -265,20 +274,7 @@ export function createRunToolExecutionHooks(
|
|
|
265
274
|
);
|
|
266
275
|
}
|
|
267
276
|
fetchedUrls.set(fetchKey, Date.now());
|
|
268
|
-
return undefined;
|
|
269
|
-
}
|
|
270
|
-
if (!isDuplicateQuery(name, args)) return undefined;
|
|
271
|
-
const key = duplicateQueryKey(name, args);
|
|
272
|
-
if (completedOrInFlight.has(key)) {
|
|
273
|
-
onSuppressed(name, args);
|
|
274
|
-
const target = primaryArgSig(name, args) || "the same arguments";
|
|
275
|
-
return duplicateSuppression(
|
|
276
|
-
`[Duplicate ${name} suppressed for ${target}. ` +
|
|
277
|
-
"Reuse the previous result; the workspace has not changed since it was returned. " +
|
|
278
|
-
"Choose the next concrete action instead of reading/searching it again.]",
|
|
279
|
-
);
|
|
280
277
|
}
|
|
281
|
-
completedOrInFlight.add(key);
|
|
282
278
|
return undefined;
|
|
283
279
|
},
|
|
284
280
|
afterExecute(name, args, result) {
|
|
@@ -287,19 +283,9 @@ export function createRunToolExecutionHooks(
|
|
|
287
283
|
if (!result.success) fetchedUrls.delete(fetchedKey);
|
|
288
284
|
return;
|
|
289
285
|
}
|
|
290
|
-
if (isDuplicateQuery(name, args)) {
|
|
291
|
-
if (!result.success) completedOrInFlight.delete(duplicateQueryKey(name, args));
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
286
|
if (name === "todo_write" && result.success) {
|
|
295
287
|
planState.ready = true;
|
|
296
288
|
}
|
|
297
|
-
const readOnly = executor.workspaceGate
|
|
298
|
-
? !!result.runtime?.effects && isEffectivelyReadOnly(result.runtime.effects)
|
|
299
|
-
: executor.isReadOnly(name, args);
|
|
300
|
-
if (result.success && !readOnly) {
|
|
301
|
-
completedOrInFlight.clear();
|
|
302
|
-
}
|
|
303
289
|
},
|
|
304
290
|
};
|
|
305
291
|
}
|
|
@@ -3,27 +3,24 @@ import {
|
|
|
3
3
|
readFileTool,
|
|
4
4
|
writeFileTool,
|
|
5
5
|
deleteFileTool,
|
|
6
|
-
moveFileTool,
|
|
7
6
|
type ReadFileOptions,
|
|
8
7
|
type WriteFileOptions,
|
|
9
8
|
type DeleteFileOptions,
|
|
10
|
-
type MoveFileOptions,
|
|
11
9
|
} from "./filesystem.js";
|
|
12
10
|
import { editFileTool, type EditFileOptions } from "./edit.js";
|
|
13
11
|
import { multiEditTool, type MultiEditOptions } from "./multi-edit.js";
|
|
14
12
|
import { listTreeTool, type ListTreeOptions } from "./list-tree.js";
|
|
15
13
|
import { executeCommandTool, type ExecuteCommandOptions } from "./command.js";
|
|
16
|
-
import { httpFetchTool,
|
|
14
|
+
import { httpFetchTool, type HttpFetchOptions } from "./http.js";
|
|
17
15
|
import { searchFilesTool, type SearchFilesOptions } from "./search.js";
|
|
18
16
|
import { globFilesTool, type GlobFilesOptions } from "./glob.js";
|
|
19
17
|
import { webSearchTool, type WebSearchOptions } from "./web-search.js";
|
|
20
|
-
import { currentTimeTool } from "./time.js";
|
|
21
18
|
import { readDocumentTool, readPdfTool, readDocxTool, type DocumentReadOptions } from "./document.js";
|
|
22
19
|
import { todoWriteTool, type TodoWriteToolOptions, type TodoStore, type Todo, type TodoStatus } from "./todo.js";
|
|
23
20
|
import { askUserQuestionTool, type AskUserToolOptions } from "./ask-user.js";
|
|
24
21
|
import { generateImageTool, type GenerateImageOptions } from "./generate-image.js";
|
|
25
22
|
import { browserScreenshotTool, type BrowserScreenshotOptions } from "./browser.js";
|
|
26
|
-
import {
|
|
23
|
+
import { exitPlanModeTool, type PlanModeToolsOptions } from "./plan-mode.js";
|
|
27
24
|
import { skillTool, type SkillToolOptions } from "./skill.js";
|
|
28
25
|
import type { CronToolsHandle } from "./cron.js";
|
|
29
26
|
import type { MonitorToolHandle } from "./monitor.js";
|
|
@@ -90,10 +87,8 @@ export interface BuiltinToolsOptions {
|
|
|
90
87
|
editFile?: EditFileOptions;
|
|
91
88
|
multiEdit?: MultiEditOptions;
|
|
92
89
|
deleteFile?: DeleteFileOptions;
|
|
93
|
-
moveFile?: MoveFileOptions;
|
|
94
90
|
executeCommand?: ExecuteCommandOptions;
|
|
95
91
|
httpFetch?: HttpFetchOptions;
|
|
96
|
-
httpRequest?: HttpFetchOptions;
|
|
97
92
|
searchFiles?: SearchFilesOptions;
|
|
98
93
|
globFiles?: GlobFilesOptions;
|
|
99
94
|
listTree?: ListTreeOptions;
|
|
@@ -106,8 +101,10 @@ export interface BuiltinToolsOptions {
|
|
|
106
101
|
* subagent registries), `todo_write` is not registered — mirrors CCB's
|
|
107
102
|
* "todos are main-agent-only" choice. */
|
|
108
103
|
todoWrite?: TodoWriteToolOptions;
|
|
109
|
-
/** Required for the main agent to get `
|
|
110
|
-
*
|
|
104
|
+
/** Required for the main agent to get `exit_plan_mode`. Omit to skip
|
|
105
|
+
* registration (subagent registries don't manage plan mode). Entering plan
|
|
106
|
+
* mode is a user action; register `enterPlanModeTool` explicitly to let the
|
|
107
|
+
* model request it. */
|
|
111
108
|
planMode?: PlanModeToolsOptions;
|
|
112
109
|
/** Main agent in an interactive UI only. Omit (headless, subagents) to leave
|
|
113
110
|
* `ask_user_question` unregistered: nobody is there to answer. */
|
|
@@ -140,6 +137,10 @@ export interface BuiltinToolsOptions {
|
|
|
140
137
|
exclude?: string[];
|
|
141
138
|
}
|
|
142
139
|
|
|
140
|
+
/** Registers the core tool set. Specialized tools (`move_file`, `http_request`,
|
|
141
|
+
* `current_time`, `enter_plan_mode`, cron, monitor) remain exported for hosts
|
|
142
|
+
* that register them explicitly; each one the model sees costs prompt tokens
|
|
143
|
+
* on every request and widens its choice of tools. */
|
|
143
144
|
export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRegistry {
|
|
144
145
|
const registry = new ToolRegistry();
|
|
145
146
|
const exclude = new Set(options.exclude ?? []);
|
|
@@ -150,25 +151,19 @@ export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRe
|
|
|
150
151
|
if (!exclude.has("edit_file")) registry.register(editFileTool({ defaultCwd, ...options.editFile }));
|
|
151
152
|
if (!exclude.has("multi_edit")) registry.register(multiEditTool({ defaultCwd, ...options.multiEdit }));
|
|
152
153
|
if (!exclude.has("delete_file")) registry.register(deleteFileTool({ defaultCwd, ...options.deleteFile }));
|
|
153
|
-
if (!exclude.has("move_file")) registry.register(moveFileTool({ defaultCwd, ...options.moveFile }));
|
|
154
154
|
if (!exclude.has("list_tree")) registry.register(listTreeTool({ defaultCwd, ...options.listTree }));
|
|
155
155
|
if (options.generateImage && !exclude.has("generate_image")) registry.register(generateImageTool({ defaultCwd, ...options.generateImage }));
|
|
156
156
|
if (!exclude.has("bash")) registry.register(executeCommandTool(options.executeCommand));
|
|
157
157
|
if (!exclude.has("http_fetch")) registry.register(httpFetchTool(options.httpFetch));
|
|
158
|
-
if (!exclude.has("http_request")) registry.register(httpRequestTool(options.httpRequest));
|
|
159
158
|
if (!exclude.has("search_files")) registry.register(searchFilesTool({ defaultCwd, ...options.searchFiles }));
|
|
160
159
|
if (!exclude.has("glob_files")) registry.register(globFilesTool({ defaultCwd, ...options.globFiles }));
|
|
161
160
|
if (!exclude.has("web_search")) registry.register(webSearchTool(options.webSearch));
|
|
162
|
-
if (!exclude.has("current_time")) registry.register(currentTimeTool());
|
|
163
161
|
if (!exclude.has("browser_screenshot")) registry.register(browserScreenshotTool({ defaultCwd, ...options.browserScreenshot }));
|
|
164
162
|
if (!exclude.has("read_document")) registry.register(readDocumentTool({ defaultCwd, ...options.documentRead }));
|
|
165
163
|
if (options.todoWrite && !exclude.has("todo_write")) {
|
|
166
164
|
registry.register(todoWriteTool(options.todoWrite));
|
|
167
165
|
}
|
|
168
|
-
if (options.planMode)
|
|
169
|
-
if (!exclude.has("enter_plan_mode")) registry.register(enterPlanModeTool(options.planMode));
|
|
170
|
-
if (!exclude.has("exit_plan_mode")) registry.register(exitPlanModeTool(options.planMode));
|
|
171
|
-
}
|
|
166
|
+
if (options.planMode && !exclude.has("exit_plan_mode")) registry.register(exitPlanModeTool(options.planMode));
|
|
172
167
|
if (options.askUser && !exclude.has("ask_user_question")) registry.register(askUserQuestionTool(options.askUser));
|
|
173
168
|
if (options.skill && !exclude.has("skill")) {
|
|
174
169
|
registry.register(skillTool(options.skill));
|
|
@@ -105,7 +105,7 @@ export function exitPlanModeTool(options: PlanModeToolsOptions): Tool {
|
|
|
105
105
|
success: false,
|
|
106
106
|
output: "",
|
|
107
107
|
error:
|
|
108
|
-
"Not in plan mode — nothing to exit.
|
|
108
|
+
"Not in plan mode — nothing to exit. Present the plan in your reply instead; the user enters plan mode with /mode plan.",
|
|
109
109
|
};
|
|
110
110
|
}
|
|
111
111
|
const plan = args.plan as string;
|
|
@@ -282,12 +282,12 @@ export function readOnlyBashTool(defaultCwd?: string): Tool {
|
|
|
282
282
|
|
|
283
283
|
const EXPLORE_TOOLS = new Set([
|
|
284
284
|
"read_file", "glob_files", "search_files", "list_tree",
|
|
285
|
-
"web_search", "http_fetch", "
|
|
285
|
+
"web_search", "http_fetch", "bash",
|
|
286
286
|
]);
|
|
287
287
|
|
|
288
288
|
const PLAN_TOOLS = new Set([
|
|
289
289
|
"read_file", "glob_files", "search_files", "list_tree",
|
|
290
|
-
"web_search", "http_fetch", "
|
|
290
|
+
"web_search", "http_fetch", "bash",
|
|
291
291
|
]);
|
|
292
292
|
|
|
293
293
|
type Thoroughness = "quick" | "medium" | "thorough";
|