@oyasmi/pipiclaw 0.7.6 → 0.8.0
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/README.md +13 -0
- package/dist/agent/channel-runner.d.ts +3 -0
- package/dist/agent/channel-runner.js +14 -4
- package/dist/agent/commands.js +8 -2
- package/dist/agent/prompt-builder.js +46 -0
- package/dist/agent/session-events.js +5 -0
- package/dist/agent/types.d.ts +2 -0
- package/dist/memory/recall.js +6 -0
- package/dist/memory/task-digest.js +17 -0
- package/dist/models/api-keys.d.ts +5 -1
- package/dist/models/api-keys.js +10 -4
- package/dist/runtime/bootstrap.d.ts +5 -0
- package/dist/runtime/bootstrap.js +59 -2
- package/dist/runtime/dingtalk.d.ts +2 -0
- package/dist/runtime/dingtalk.js +13 -1
- package/dist/runtime/durable-dispatch.d.ts +28 -0
- package/dist/runtime/durable-dispatch.js +144 -0
- package/dist/runtime/events.d.ts +4 -2
- package/dist/runtime/events.js +12 -8
- package/dist/runtime/task-commands.d.ts +9 -0
- package/dist/runtime/task-commands.js +429 -2
- package/dist/runtime/task-driver.d.ts +32 -0
- package/dist/runtime/task-driver.js +270 -0
- package/dist/settings.d.ts +12 -0
- package/dist/settings.js +30 -0
- package/dist/shared/atomic-file.js +23 -3
- package/dist/shared/task-events.d.ts +32 -0
- package/dist/shared/task-events.js +29 -0
- package/dist/shared/task-ledger.d.ts +53 -0
- package/dist/shared/task-ledger.js +246 -8
- package/dist/subagents/tool.d.ts +13 -0
- package/dist/subagents/tool.js +229 -15
- package/dist/tasks/artifact-subject.d.ts +6 -0
- package/dist/tasks/artifact-subject.js +29 -0
- package/dist/tasks/control.d.ts +83 -0
- package/dist/tasks/control.js +292 -0
- package/dist/tasks/store.d.ts +32 -0
- package/dist/tasks/store.js +142 -0
- package/dist/tasks/verification.d.ts +23 -0
- package/dist/tasks/verification.js +68 -0
- package/dist/tools/registry.d.ts +1 -1
- package/dist/tools/registry.js +6 -4
- package/dist/tools/task-manage.d.ts +51 -3
- package/dist/tools/task-manage.js +491 -37
- package/dist/tools/web-fetch.js +3 -0
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.js +1 -1
- package/package.json +1 -1
package/dist/subagents/tool.js
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
1
3
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
2
4
|
import { convertToLlm } from "@earendil-works/pi-coding-agent";
|
|
3
5
|
import { Type } from "typebox";
|
|
4
|
-
import { readChannelSession } from "../memory/files.js";
|
|
6
|
+
import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
|
|
5
7
|
import { recallRelevantMemory } from "../memory/recall.js";
|
|
6
8
|
import { formatModelReference } from "../models/utils.js";
|
|
7
9
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
8
10
|
import { splitH1Sections } from "../shared/markdown-sections.js";
|
|
9
|
-
import {
|
|
11
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
12
|
+
import { clipText, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
|
|
13
|
+
import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
|
|
14
|
+
import { applyTaskControlPatch } from "../tasks/control.js";
|
|
15
|
+
import { readStoredTask, updateStoredTask } from "../tasks/store.js";
|
|
16
|
+
import { parseVerificationVerdict, writeVerificationAttestation } from "../tasks/verification.js";
|
|
10
17
|
import { buildToolSet } from "../tools/registry.js";
|
|
11
18
|
import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, } from "./discovery.js";
|
|
12
19
|
const subagentSchema = Type.Object({
|
|
@@ -32,6 +39,14 @@ const subagentSchema = Type.Object({
|
|
|
32
39
|
paths: Type.Optional(Type.Array(Type.String(), {
|
|
33
40
|
description: "Optional preferred file or directory paths for the sub-agent to focus on.",
|
|
34
41
|
})),
|
|
42
|
+
purpose: Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
|
|
43
|
+
description: 'Use "verify" for an independent, read-only task acceptance check.',
|
|
44
|
+
})),
|
|
45
|
+
taskId: Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." })),
|
|
46
|
+
isolation: Type.Optional(Type.Union([Type.Literal("shared"), Type.Literal("worktree")], {
|
|
47
|
+
description: '"worktree" runs in a dedicated git worktree (host sandbox only).',
|
|
48
|
+
})),
|
|
49
|
+
worktreePath: Type.Optional(Type.String({ description: "Reuse an existing task-owned worktree; must be under channel tasks/worktrees/." })),
|
|
35
50
|
});
|
|
36
51
|
const DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS = {
|
|
37
52
|
enabled: true,
|
|
@@ -44,6 +59,130 @@ const SESSION_SECTION_ORDER = ["Current State", "User Intent", "Active Files", "
|
|
|
44
59
|
const MAX_SESSION_SECTION_CHARS = 280;
|
|
45
60
|
const MAX_SESSION_CONTEXT_CHARS = 1800;
|
|
46
61
|
const MAX_RECALL_CONTEXT_CHARS = 2200;
|
|
62
|
+
const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
63
|
+
class DirectoryExecutor {
|
|
64
|
+
constructor(base, directory) {
|
|
65
|
+
this.base = base;
|
|
66
|
+
this.directory = directory;
|
|
67
|
+
}
|
|
68
|
+
exec(command, options) {
|
|
69
|
+
return this.base.exec(`cd ${shellEscape(this.directory)} && ${command}`, options);
|
|
70
|
+
}
|
|
71
|
+
getWorkspacePath(hostPath) {
|
|
72
|
+
return this.base.getWorkspacePath(hostPath);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function safeRunSegment(value) {
|
|
76
|
+
return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
|
|
77
|
+
}
|
|
78
|
+
function safeGitBranchSegment(value) {
|
|
79
|
+
return (value
|
|
80
|
+
.replace(/[^A-Za-z0-9_-]/g, "-")
|
|
81
|
+
.replace(/^-+|-+$/g, "")
|
|
82
|
+
.slice(0, 48) || "run");
|
|
83
|
+
}
|
|
84
|
+
async function prepareRunContext(runId, params, options) {
|
|
85
|
+
const purpose = params.purpose ?? "work";
|
|
86
|
+
const taskId = params.taskId?.trim() || undefined;
|
|
87
|
+
if (purpose === "verify" && !taskId)
|
|
88
|
+
throw new Error("purpose=verify requires taskId.");
|
|
89
|
+
if (taskId && !TASK_ID_PATTERN.test(taskId))
|
|
90
|
+
throw new Error(`Invalid taskId: ${taskId}`);
|
|
91
|
+
const ownedTask = taskId ? await readStoredTask(options.channelDir, taskId) : undefined;
|
|
92
|
+
if (taskId && !ownedTask) {
|
|
93
|
+
throw new Error(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
|
|
94
|
+
}
|
|
95
|
+
const isolation = params.isolation ?? "shared";
|
|
96
|
+
if (isolation === "shared") {
|
|
97
|
+
if (params.worktreePath)
|
|
98
|
+
throw new Error("worktreePath requires isolation=worktree.");
|
|
99
|
+
const workingDirectory = options.runtimeContext.sandbox === "host"
|
|
100
|
+
? resolve(options.workingDirectory ?? process.cwd())
|
|
101
|
+
: options.runtimeContext.workspacePath;
|
|
102
|
+
return { runId, purpose, taskId, isolation, workingDirectory };
|
|
103
|
+
}
|
|
104
|
+
if (options.runtimeContext.sandbox !== "host") {
|
|
105
|
+
throw new Error("Git worktree isolation currently requires the host sandbox. Use isolation=shared, or run this task in host mode.");
|
|
106
|
+
}
|
|
107
|
+
if (!taskId)
|
|
108
|
+
throw new Error("isolation=worktree requires taskId so the worktree has a durable owner.");
|
|
109
|
+
if (!ownedTask?.fields.control) {
|
|
110
|
+
throw new Error(`Task ${taskId} has no governed control metadata. Normalize it with task_manage set first.`);
|
|
111
|
+
}
|
|
112
|
+
const baseDir = resolve(options.channelDir, "tasks", "worktrees");
|
|
113
|
+
await mkdir(baseDir, { recursive: true });
|
|
114
|
+
if (params.worktreePath) {
|
|
115
|
+
const existing = resolve(params.worktreePath);
|
|
116
|
+
const rel = relative(baseDir, existing);
|
|
117
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
|
|
118
|
+
throw new Error(`worktreePath must be inside ${baseDir}.`);
|
|
119
|
+
}
|
|
120
|
+
const check = await options.executor.exec(`git -C ${shellEscape(existing)} rev-parse --is-inside-work-tree`);
|
|
121
|
+
if (check.code !== 0 || check.stdout.trim() !== "true") {
|
|
122
|
+
throw new Error(`worktreePath is not a usable git worktree: ${existing}`);
|
|
123
|
+
}
|
|
124
|
+
const branchResult = await options.executor.exec(`git -C ${shellEscape(existing)} branch --show-current`);
|
|
125
|
+
const context = {
|
|
126
|
+
runId,
|
|
127
|
+
purpose,
|
|
128
|
+
taskId,
|
|
129
|
+
isolation,
|
|
130
|
+
workingDirectory: existing,
|
|
131
|
+
worktreePath: existing,
|
|
132
|
+
worktreeBranch: branchResult.code === 0 ? branchResult.stdout.trim() || undefined : undefined,
|
|
133
|
+
};
|
|
134
|
+
await recordTaskWorktree(options.channelDir, taskId, context);
|
|
135
|
+
return context;
|
|
136
|
+
}
|
|
137
|
+
const sourceDirectory = resolve(options.workingDirectory ?? process.cwd());
|
|
138
|
+
const rootResult = await options.executor.exec(`git -C ${shellEscape(sourceDirectory)} rev-parse --show-toplevel`);
|
|
139
|
+
if (rootResult.code !== 0 || !rootResult.stdout.trim()) {
|
|
140
|
+
throw new Error("Cannot create an isolated worktree: the current working directory is not inside a git repository.");
|
|
141
|
+
}
|
|
142
|
+
const repoRoot = rootResult.stdout.trim();
|
|
143
|
+
const runSegment = safeRunSegment(runId).slice(-16);
|
|
144
|
+
const taskSegment = safeRunSegment(taskId);
|
|
145
|
+
const path = join(baseDir, taskSegment, runSegment);
|
|
146
|
+
const branch = `pipiclaw-task/${safeGitBranchSegment(taskId)}/${safeGitBranchSegment(runId).slice(-16)}`;
|
|
147
|
+
await mkdir(join(baseDir, taskSegment), { recursive: true });
|
|
148
|
+
const created = await options.executor.exec(`git -C ${shellEscape(repoRoot)} worktree add -b ${shellEscape(branch)} ${shellEscape(path)} HEAD`, { timeout: 60 });
|
|
149
|
+
if (created.code !== 0) {
|
|
150
|
+
throw new Error(`Could not create git worktree for task ${taskId}: ${created.stderr || created.stdout}. Remove the stale worktree/branch or use isolation=shared.`);
|
|
151
|
+
}
|
|
152
|
+
const context = {
|
|
153
|
+
runId,
|
|
154
|
+
purpose,
|
|
155
|
+
taskId,
|
|
156
|
+
isolation,
|
|
157
|
+
workingDirectory: path,
|
|
158
|
+
worktreePath: path,
|
|
159
|
+
worktreeBranch: branch,
|
|
160
|
+
};
|
|
161
|
+
try {
|
|
162
|
+
await recordTaskWorktree(options.channelDir, taskId, context);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
await options.executor.exec(`git -C ${shellEscape(repoRoot)} worktree remove --force ${shellEscape(path)}`);
|
|
166
|
+
await options.executor.exec(`git -C ${shellEscape(repoRoot)} branch -D ${shellEscape(branch)}`);
|
|
167
|
+
throw new Error(`Created the worktree but could not record its ownership on task ${taskId}; the temporary worktree was removed. ${error instanceof Error ? error.message : String(error)}`);
|
|
168
|
+
}
|
|
169
|
+
return context;
|
|
170
|
+
}
|
|
171
|
+
async function recordTaskWorktree(channelDir, taskId, context) {
|
|
172
|
+
await updateStoredTask(channelDir, taskId, (task) => {
|
|
173
|
+
if (!task.fields.control || !context.worktreePath)
|
|
174
|
+
return;
|
|
175
|
+
task.fields.control = applyTaskControlPatch(task.fields.control, {
|
|
176
|
+
isolation: "worktree",
|
|
177
|
+
worktreePath: context.worktreePath,
|
|
178
|
+
worktreeBranch: context.worktreeBranch,
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
async function gitWorkspaceState(executor) {
|
|
183
|
+
const result = await executor.exec("git status --porcelain=v1 --untracked-files=all", { timeout: 30 });
|
|
184
|
+
return result.code === 0 ? result.stdout : undefined;
|
|
185
|
+
}
|
|
47
186
|
function createEmptyUsageTotals() {
|
|
48
187
|
return {
|
|
49
188
|
input: 0,
|
|
@@ -83,20 +222,43 @@ function buildStoppedText(config, reason, finalText) {
|
|
|
83
222
|
}
|
|
84
223
|
return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
|
|
85
224
|
}
|
|
225
|
+
/**
|
|
226
|
+
* Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
|
|
227
|
+
* context (task text), never the "don't touch MEMORY.md/HISTORY.md/SESSION.md, use
|
|
228
|
+
* memory_manage instead" rule the main agent gets in its system prompt (memory_manage
|
|
229
|
+
* itself is withheld from sub-agents). Denying these paths at the path-guard level closes
|
|
230
|
+
* that gap structurally instead of relying on a sub-agent to infer an instruction it never
|
|
231
|
+
* received — a stray write/edit here would race the shared memory serial queue
|
|
232
|
+
* (channel-maintenance-queue) and silently corrupt durable memory.
|
|
233
|
+
*/
|
|
234
|
+
function withSubagentMemoryWriteDeny(securityConfig, channelDir) {
|
|
235
|
+
const protectedPaths = [
|
|
236
|
+
getChannelMemoryPath(channelDir),
|
|
237
|
+
getChannelHistoryPath(channelDir),
|
|
238
|
+
getChannelSessionPath(channelDir),
|
|
239
|
+
];
|
|
240
|
+
return {
|
|
241
|
+
...securityConfig,
|
|
242
|
+
pathGuard: {
|
|
243
|
+
...securityConfig.pathGuard,
|
|
244
|
+
writeDeny: [...securityConfig.pathGuard.writeDeny, ...protectedPaths],
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
86
248
|
/**
|
|
87
249
|
* Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
|
|
88
250
|
* available to sub-agents (files + web). Sub-agents run with their own security context
|
|
89
251
|
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
90
252
|
*/
|
|
91
|
-
function buildSubagentTools(executor, bashTimeoutSec, options) {
|
|
92
|
-
const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
|
|
253
|
+
function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
254
|
+
const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir);
|
|
93
255
|
return buildToolSet({
|
|
94
256
|
executor,
|
|
95
257
|
securityConfig,
|
|
96
258
|
securityContext: {
|
|
97
259
|
workspaceDir: options.workspaceDir,
|
|
98
260
|
workspacePath: options.runtimeContext.workspacePath,
|
|
99
|
-
cwd:
|
|
261
|
+
cwd: runContext.workingDirectory,
|
|
100
262
|
},
|
|
101
263
|
channelId: options.runtimeContext.channelId,
|
|
102
264
|
channelDir: options.channelDir,
|
|
@@ -105,9 +267,9 @@ function buildSubagentTools(executor, bashTimeoutSec, options) {
|
|
|
105
267
|
webConfig: options.webConfig,
|
|
106
268
|
rtkEnabled: options.rtkEnabled,
|
|
107
269
|
bashDefaultTimeoutSeconds: bashTimeoutSec,
|
|
108
|
-
}, { forSubagent: true });
|
|
270
|
+
}, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
|
|
109
271
|
}
|
|
110
|
-
function buildSubAgentTask(task, config, runtimeContext, contextBlocks) {
|
|
272
|
+
function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
|
|
111
273
|
const taskText = task.trim();
|
|
112
274
|
const lines = [
|
|
113
275
|
`Runtime context:`,
|
|
@@ -115,7 +277,8 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks) {
|
|
|
115
277
|
`- Channel id: ${runtimeContext.channelId}`,
|
|
116
278
|
`- Channel directory: ${runtimeContext.workspacePath}/${runtimeContext.channelId}`,
|
|
117
279
|
`- Sandbox: ${runtimeContext.sandbox}`,
|
|
118
|
-
`-
|
|
280
|
+
`- Working directory: ${runContext.workingDirectory}`,
|
|
281
|
+
`- Filesystem isolation: ${runContext.isolation === "worktree" ? "dedicated git worktree" : "shared with parent"}`,
|
|
119
282
|
`- Your configured role: ${config.name}`,
|
|
120
283
|
];
|
|
121
284
|
for (const block of contextBlocks) {
|
|
@@ -125,6 +288,10 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks) {
|
|
|
125
288
|
lines.push("", block.trim());
|
|
126
289
|
}
|
|
127
290
|
lines.push("", `Task:`, taskText);
|
|
291
|
+
if (runContext.purpose === "verify") {
|
|
292
|
+
const taskPath = join(runtimeContext.workspacePath, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
|
|
293
|
+
lines.push("", "Verification protocol:", `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`, "- You are the checker, not the maker. Do not edit files or fix failures; report them.", "- Run deterministic checks when available and distinguish observed evidence from assumptions.", "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.");
|
|
294
|
+
}
|
|
128
295
|
return lines.join("\n");
|
|
129
296
|
}
|
|
130
297
|
function buildSessionContextBlock(sessionMarkdown) {
|
|
@@ -191,7 +358,6 @@ async function buildContextualBlocks(task, config, options, currentModel) {
|
|
|
191
358
|
maxInjected: recallSettings.maxInjected,
|
|
192
359
|
maxChars: Math.min(recallSettings.maxChars, MAX_RECALL_CONTEXT_CHARS),
|
|
193
360
|
rerankWithModel: recallSettings.rerankWithModel,
|
|
194
|
-
autoRerank: HAN_REGEX.test(recallQuery),
|
|
195
361
|
model: currentModel,
|
|
196
362
|
resolveApiKey: options.resolveApiKey,
|
|
197
363
|
allowedSources: ["workspace-memory", "channel-memory", "channel-history"],
|
|
@@ -207,7 +373,7 @@ function filterToolsByName(allTools, names) {
|
|
|
207
373
|
const allowed = new Set(names);
|
|
208
374
|
return allTools.filter((tool) => allowed.has(tool.name));
|
|
209
375
|
}
|
|
210
|
-
function createDetails(config, usage, turns, toolCalls, durationMs, failed, failureReason) {
|
|
376
|
+
function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict) {
|
|
211
377
|
return {
|
|
212
378
|
kind: "subagent",
|
|
213
379
|
agent: config.name,
|
|
@@ -223,6 +389,13 @@ function createDetails(config, usage, turns, toolCalls, durationMs, failed, fail
|
|
|
223
389
|
...usage,
|
|
224
390
|
cost: { ...usage.cost },
|
|
225
391
|
},
|
|
392
|
+
runId: runContext.runId,
|
|
393
|
+
purpose: runContext.purpose,
|
|
394
|
+
taskId: runContext.taskId,
|
|
395
|
+
isolation: runContext.isolation,
|
|
396
|
+
worktreePath: runContext.worktreePath,
|
|
397
|
+
worktreeBranch: runContext.worktreeBranch,
|
|
398
|
+
verificationVerdict,
|
|
226
399
|
};
|
|
227
400
|
}
|
|
228
401
|
function linkAbortSignals(parentSignal, childController) {
|
|
@@ -260,6 +433,8 @@ export function createSubAgentTool(options) {
|
|
|
260
433
|
throw new Error(`${invocation.error}\n\nAvailable predefined sub-agents:\n${formatSubAgentList(discovery.agents)}`);
|
|
261
434
|
}
|
|
262
435
|
const config = invocation.config;
|
|
436
|
+
const runContext = await prepareRunContext(_toolCallId, params, options);
|
|
437
|
+
const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
|
|
263
438
|
const apiKey = await options.resolveApiKey(config.model);
|
|
264
439
|
const startedAt = Date.now();
|
|
265
440
|
const usage = createEmptyUsageTotals();
|
|
@@ -275,10 +450,14 @@ export function createSubAgentTool(options) {
|
|
|
275
450
|
lastUpdateText = nextText;
|
|
276
451
|
onUpdate?.({
|
|
277
452
|
content: [{ type: "text", text: nextText }],
|
|
278
|
-
details: createDetails(config, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
|
|
453
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
|
|
279
454
|
});
|
|
280
455
|
};
|
|
281
|
-
const availableTools = buildSubagentTools(
|
|
456
|
+
const availableTools = buildSubagentTools(scopedExecutor, config.bashTimeoutSec, options, runContext);
|
|
457
|
+
const verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
458
|
+
const verifierSubjectBefore = runContext.purpose === "verify" && options.runtimeContext.sandbox === "host"
|
|
459
|
+
? await workspaceSubjectHash(runContext.workingDirectory)
|
|
460
|
+
: undefined;
|
|
282
461
|
const worker = options.createWorker?.({
|
|
283
462
|
subAgent: config,
|
|
284
463
|
apiKey,
|
|
@@ -343,7 +522,7 @@ export function createSubAgentTool(options) {
|
|
|
343
522
|
childController.signal.addEventListener("abort", abortWorker, { once: true });
|
|
344
523
|
try {
|
|
345
524
|
const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
|
|
346
|
-
await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks));
|
|
525
|
+
await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
|
|
347
526
|
await worker.waitForIdle();
|
|
348
527
|
}
|
|
349
528
|
finally {
|
|
@@ -370,6 +549,41 @@ export function createSubAgentTool(options) {
|
|
|
370
549
|
(lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
|
|
371
550
|
? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
|
|
372
551
|
: undefined);
|
|
552
|
+
const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
553
|
+
const verifierSubjectAfter = runContext.purpose === "verify" && options.runtimeContext.sandbox === "host"
|
|
554
|
+
? await workspaceSubjectHash(runContext.workingDirectory)
|
|
555
|
+
: undefined;
|
|
556
|
+
const workspaceChanged = runContext.purpose === "verify" &&
|
|
557
|
+
(verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
|
|
558
|
+
? verifierSubjectBefore !== verifierSubjectAfter
|
|
559
|
+
: verifierGitStateBefore !== undefined &&
|
|
560
|
+
verifierGitStateAfter !== undefined &&
|
|
561
|
+
verifierGitStateBefore !== verifierGitStateAfter);
|
|
562
|
+
const declaredVerdict = runContext.purpose === "verify" ? parseVerificationVerdict(finalText) : undefined;
|
|
563
|
+
const verificationVerdict = runContext.purpose === "verify"
|
|
564
|
+
? declaredVerdict === "pass" && !effectiveFailureReason && !workspaceChanged
|
|
565
|
+
? "pass"
|
|
566
|
+
: "fail"
|
|
567
|
+
: undefined;
|
|
568
|
+
if (runContext.purpose === "verify" && runContext.taskId && verificationVerdict) {
|
|
569
|
+
const evidence = workspaceChanged
|
|
570
|
+
? "Verifier changed tracked workspace files; the attestation is invalid."
|
|
571
|
+
: !declaredVerdict
|
|
572
|
+
? "Verifier did not emit the required final VERDICT marker."
|
|
573
|
+
: finalText.trim().slice(0, 8_000);
|
|
574
|
+
await writeVerificationAttestation(options.channelDir, {
|
|
575
|
+
runId: runContext.runId,
|
|
576
|
+
taskId: runContext.taskId,
|
|
577
|
+
verdict: verificationVerdict,
|
|
578
|
+
agent: config.name,
|
|
579
|
+
model: formatModelReference(config.model),
|
|
580
|
+
checkedAt: new Date().toISOString(),
|
|
581
|
+
evidence,
|
|
582
|
+
workspaceChanged: Boolean(workspaceChanged),
|
|
583
|
+
subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
|
|
584
|
+
output: finalText,
|
|
585
|
+
});
|
|
586
|
+
}
|
|
373
587
|
if (effectiveFailureReason) {
|
|
374
588
|
if (!finalText.trim()) {
|
|
375
589
|
emitUpdate(formatStatus(config.name, "failed"));
|
|
@@ -378,12 +592,12 @@ export function createSubAgentTool(options) {
|
|
|
378
592
|
emitUpdate(formatStatus(config.name, "stopped"));
|
|
379
593
|
return {
|
|
380
594
|
content: [{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalText) }],
|
|
381
|
-
details: createDetails(config, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason),
|
|
595
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict),
|
|
382
596
|
};
|
|
383
597
|
}
|
|
384
598
|
return {
|
|
385
599
|
content: [{ type: "text", text: finalText || `(Sub-agent ${config.name} completed with no text output)` }],
|
|
386
|
-
details: createDetails(config, usage, assistantTurns, toolCalls, durationMs, false),
|
|
600
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict),
|
|
387
601
|
};
|
|
388
602
|
},
|
|
389
603
|
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A compact, deterministic description of the code/artifact subject a verifier
|
|
3
|
+
* observed. It intentionally uses only Git's own view, keeping verification
|
|
4
|
+
* cheap and understandable for a local coding runtime.
|
|
5
|
+
*/
|
|
6
|
+
export declare function workspaceSubjectHash(workingDirectory: string): Promise<string | undefined>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
const execFileAsync = promisify(execFile);
|
|
5
|
+
/**
|
|
6
|
+
* A compact, deterministic description of the code/artifact subject a verifier
|
|
7
|
+
* observed. It intentionally uses only Git's own view, keeping verification
|
|
8
|
+
* cheap and understandable for a local coding runtime.
|
|
9
|
+
*/
|
|
10
|
+
export async function workspaceSubjectHash(workingDirectory) {
|
|
11
|
+
try {
|
|
12
|
+
const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "status", "--porcelain=v1", "--untracked-files=all"], { maxBuffer: 4 * 1024 * 1024 });
|
|
13
|
+
const [head, unstaged, staged] = await Promise.all([
|
|
14
|
+
execFileAsync("git", ["-C", workingDirectory, "rev-parse", "HEAD"], { maxBuffer: 1024 * 1024 }),
|
|
15
|
+
execFileAsync("git", ["-C", workingDirectory, "diff", "--no-ext-diff", "--binary"], {
|
|
16
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
17
|
+
}),
|
|
18
|
+
execFileAsync("git", ["-C", workingDirectory, "diff", "--cached", "--no-ext-diff", "--binary"], {
|
|
19
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
20
|
+
}),
|
|
21
|
+
]);
|
|
22
|
+
return createHash("sha256")
|
|
23
|
+
.update([head.stdout.trim(), stdout, unstaged.stdout, staged.stdout].join("\0"))
|
|
24
|
+
.digest("hex");
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export type TaskPriority = "low" | "normal" | "high" | "critical";
|
|
2
|
+
export type TaskIsolation = "shared" | "worktree";
|
|
3
|
+
export type TaskSideEffects = "read-only" | "workspace" | "external";
|
|
4
|
+
export type TaskVerificationMode = "evidence" | "independent";
|
|
5
|
+
export type TaskVerificationStatus = "pending" | "passed" | "failed";
|
|
6
|
+
export type TaskOutcome = "pending" | "running" | "progress" | "blocked" | "failed" | "verified";
|
|
7
|
+
export interface TaskBudget {
|
|
8
|
+
maxAttempts: number;
|
|
9
|
+
maxTokens?: number;
|
|
10
|
+
maxCostUsd?: number;
|
|
11
|
+
maxWallTimeMinutes?: number;
|
|
12
|
+
}
|
|
13
|
+
export interface TaskUsage {
|
|
14
|
+
attempts: number;
|
|
15
|
+
tokens: number;
|
|
16
|
+
costUsd: number;
|
|
17
|
+
wallTimeMinutes: number;
|
|
18
|
+
}
|
|
19
|
+
export interface TaskVerification {
|
|
20
|
+
mode: TaskVerificationMode;
|
|
21
|
+
status: TaskVerificationStatus;
|
|
22
|
+
runId?: string;
|
|
23
|
+
evidence?: string;
|
|
24
|
+
bodyHash?: string;
|
|
25
|
+
checkedAt?: string;
|
|
26
|
+
subjectHash?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface TaskWorktree {
|
|
29
|
+
path: string;
|
|
30
|
+
branch?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface TaskControl {
|
|
33
|
+
version: 1;
|
|
34
|
+
priority: TaskPriority;
|
|
35
|
+
deadline?: string;
|
|
36
|
+
nextAction?: string;
|
|
37
|
+
lastOutcome: TaskOutcome;
|
|
38
|
+
blockedReason?: string;
|
|
39
|
+
parent?: string;
|
|
40
|
+
dependsOn: string[];
|
|
41
|
+
isolation: TaskIsolation;
|
|
42
|
+
sideEffects: TaskSideEffects;
|
|
43
|
+
externalApproval: "not-required" | "required" | "granted";
|
|
44
|
+
approvalBy?: string;
|
|
45
|
+
approvedAt?: string;
|
|
46
|
+
approvalBodyHash?: string;
|
|
47
|
+
budget: TaskBudget;
|
|
48
|
+
usage: TaskUsage;
|
|
49
|
+
verification: TaskVerification;
|
|
50
|
+
worktree?: TaskWorktree;
|
|
51
|
+
lastStartedAt?: string;
|
|
52
|
+
lastFinishedAt?: string;
|
|
53
|
+
/** Identifier of the currently open recurring-task cycle, when applicable. */
|
|
54
|
+
cycleId?: string;
|
|
55
|
+
}
|
|
56
|
+
export interface TaskControlPatch {
|
|
57
|
+
priority?: TaskPriority;
|
|
58
|
+
deadline?: string;
|
|
59
|
+
nextAction?: string;
|
|
60
|
+
lastOutcome?: TaskOutcome;
|
|
61
|
+
blockedReason?: string;
|
|
62
|
+
parent?: string;
|
|
63
|
+
dependsOn?: string[];
|
|
64
|
+
isolation?: TaskIsolation;
|
|
65
|
+
sideEffects?: TaskSideEffects;
|
|
66
|
+
externalApproval?: "not-required" | "required" | "granted";
|
|
67
|
+
maxAttempts?: number;
|
|
68
|
+
maxTokens?: number;
|
|
69
|
+
maxCostUsd?: number;
|
|
70
|
+
maxWallTimeMinutes?: number;
|
|
71
|
+
verificationMode?: TaskVerificationMode;
|
|
72
|
+
worktreePath?: string;
|
|
73
|
+
worktreeBranch?: string;
|
|
74
|
+
}
|
|
75
|
+
export declare function createDefaultTaskControl(mode?: TaskVerificationMode): TaskControl;
|
|
76
|
+
export declare function parseTaskControl(raw: string): TaskControl;
|
|
77
|
+
/** Reset state which is meaningful only within one recurring task cycle. */
|
|
78
|
+
export declare function resetTaskControlForCycle(control: TaskControl, cycleId: string): TaskControl;
|
|
79
|
+
export declare function applyTaskControlPatch(control: TaskControl, patch: TaskControlPatch): TaskControl;
|
|
80
|
+
export declare function taskPriorityRank(priority: TaskPriority): number;
|
|
81
|
+
export declare function taskBudgetViolation(control: TaskControl, nowMs: number): string | undefined;
|
|
82
|
+
export declare function invalidateTaskVerification(control: TaskControl): TaskControl;
|
|
83
|
+
export declare function invalidateTaskApproval(control: TaskControl): TaskControl;
|