@oyasmi/pipiclaw 0.7.7 → 0.8.1
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 +23 -2
- package/dist/agent/channel-runner.d.ts +4 -4
- package/dist/agent/channel-runner.js +25 -23
- package/dist/agent/commands.js +7 -2
- package/dist/agent/job-manager.d.ts +5 -5
- package/dist/agent/prompt-builder.d.ts +3 -13
- package/dist/agent/prompt-builder.js +49 -159
- package/dist/agent/run-queue.js +2 -1
- package/dist/agent/runner-factory.d.ts +1 -2
- package/dist/agent/runner-factory.js +2 -2
- package/dist/agent/status-render.d.ts +0 -7
- package/dist/agent/status-render.js +8 -3
- package/dist/agent/types.d.ts +2 -0
- package/dist/agent/workspace-resources.d.ts +1 -1
- package/dist/agent/workspace-resources.js +3 -15
- package/dist/executor.d.ts +20 -0
- package/dist/{sandbox.js → executor.js} +3 -95
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/log.d.ts +1 -1
- package/dist/log.js +1 -2
- package/dist/memory/files.js +0 -0
- package/dist/memory/lifecycle.js +6 -5
- package/dist/memory/maintenance-jobs.d.ts +0 -1
- package/dist/memory/maintenance-jobs.js +2 -2
- package/dist/memory/maintenance-state.js +2 -1
- package/dist/memory/post-turn-review.d.ts +0 -1
- package/dist/memory/post-turn-review.js +4 -4
- package/dist/memory/scheduler.d.ts +0 -1
- package/dist/memory/scheduler.js +2 -2
- package/dist/memory/session.js +2 -2
- package/dist/memory/task-digest.js +17 -0
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +11 -0
- package/dist/playbooks/catalog.d.ts +9 -0
- package/dist/playbooks/catalog.js +44 -0
- package/dist/playbooks/event-scheduling.md +43 -0
- package/dist/playbooks/memory-and-learning.md +45 -0
- package/dist/playbooks/runtime-orientation.md +48 -0
- package/dist/playbooks/task-closeout.md +45 -0
- package/dist/playbooks/task-delegation.md +44 -0
- package/dist/playbooks/task-driving.md +43 -0
- package/dist/playbooks/task-planning.md +47 -0
- package/dist/playbooks/task-recurring.md +42 -0
- package/dist/playbooks/task-repair.md +43 -0
- package/dist/runtime/bootstrap.d.ts +12 -11
- package/dist/runtime/bootstrap.js +81 -57
- package/dist/runtime/delivery.js +4 -3
- package/dist/runtime/dingtalk.d.ts +2 -0
- package/dist/runtime/dingtalk.js +15 -14
- package/dist/runtime/durable-dispatch.d.ts +30 -0
- package/dist/runtime/durable-dispatch.js +172 -0
- package/dist/runtime/event-commands.js +4 -4
- package/dist/runtime/events.d.ts +5 -3
- package/dist/runtime/events.js +17 -13
- package/dist/runtime/task-commands.d.ts +6 -0
- package/dist/runtime/task-commands.js +292 -6
- package/dist/runtime/task-driver.d.ts +32 -0
- package/dist/runtime/task-driver.js +268 -0
- package/dist/security/config.js +2 -1
- package/dist/security/network.js +9 -2
- package/dist/security/path-guard.js +12 -24
- package/dist/security/types.d.ts +0 -1
- package/dist/settings.d.ts +12 -0
- package/dist/settings.js +30 -0
- package/dist/shared/jsonl-appender.js +2 -1
- package/dist/shared/task-ledger.d.ts +35 -0
- package/dist/shared/task-ledger.js +229 -15
- package/dist/shared/text-utils.d.ts +1 -0
- package/dist/shared/text-utils.js +3 -0
- package/dist/subagents/discovery.js +3 -2
- package/dist/subagents/tool.d.ts +15 -3
- package/dist/subagents/tool.js +194 -17
- 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 +293 -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 +69 -0
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +3 -5
- package/dist/tools/command-optimizer.d.ts +1 -1
- package/dist/tools/command-optimizer.js +4 -6
- package/dist/tools/config.js +4 -3
- package/dist/tools/edit.d.ts +1 -1
- package/dist/tools/edit.js +0 -0
- package/dist/tools/event-manage.d.ts +0 -1
- package/dist/tools/event-manage.js +9 -14
- package/dist/tools/grep.d.ts +1 -1
- package/dist/tools/grep.js +4 -6
- package/dist/tools/index.d.ts +1 -3
- package/dist/tools/index.js +1 -4
- package/dist/tools/read.d.ts +1 -1
- package/dist/tools/read.js +1 -2
- package/dist/tools/registry.d.ts +2 -3
- package/dist/tools/registry.js +5 -11
- package/dist/tools/skill-manage.d.ts +0 -1
- package/dist/tools/skill-manage.js +7 -14
- package/dist/tools/task-manage.d.ts +37 -4
- package/dist/tools/task-manage.js +398 -39
- package/dist/tools/write-content.d.ts +1 -1
- package/dist/tools/write-content.js +0 -1
- package/dist/tools/write.d.ts +1 -1
- package/dist/tui/app.d.ts +0 -2
- package/dist/tui/app.js +12 -7
- package/dist/tui/cli.d.ts +0 -2
- package/dist/tui/cli.js +3 -25
- package/dist/tui/turn-controller.d.ts +7 -3
- package/dist/tui/turn-controller.js +9 -6
- package/dist/web/client.js +2 -1
- package/package.json +2 -2
- package/dist/sandbox.d.ts +0 -42
package/dist/subagents/tool.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
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";
|
|
@@ -6,7 +8,12 @@ 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, errorMessage, 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.',
|
|
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,122 @@ 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
|
+
}
|
|
72
|
+
function safeRunSegment(value) {
|
|
73
|
+
return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
|
|
74
|
+
}
|
|
75
|
+
function safeGitBranchSegment(value) {
|
|
76
|
+
return (value
|
|
77
|
+
.replace(/[^A-Za-z0-9_-]/g, "-")
|
|
78
|
+
.replace(/^-+|-+$/g, "")
|
|
79
|
+
.slice(0, 48) || "run");
|
|
80
|
+
}
|
|
81
|
+
async function prepareRunContext(runId, params, options) {
|
|
82
|
+
const purpose = params.purpose ?? "work";
|
|
83
|
+
const taskId = params.taskId?.trim() || undefined;
|
|
84
|
+
if (purpose === "verify" && !taskId)
|
|
85
|
+
throw new Error("purpose=verify requires taskId.");
|
|
86
|
+
if (taskId && !TASK_ID_PATTERN.test(taskId))
|
|
87
|
+
throw new Error(`Invalid taskId: ${taskId}`);
|
|
88
|
+
const ownedTask = taskId ? await readStoredTask(options.channelDir, taskId) : undefined;
|
|
89
|
+
if (taskId && !ownedTask) {
|
|
90
|
+
throw new Error(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
|
|
91
|
+
}
|
|
92
|
+
const isolation = params.isolation ?? "shared";
|
|
93
|
+
if (isolation === "shared") {
|
|
94
|
+
if (params.worktreePath)
|
|
95
|
+
throw new Error("worktreePath requires isolation=worktree.");
|
|
96
|
+
const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
|
|
97
|
+
return { runId, purpose, taskId, isolation, workingDirectory };
|
|
98
|
+
}
|
|
99
|
+
if (!taskId)
|
|
100
|
+
throw new Error("isolation=worktree requires taskId so the worktree has a durable owner.");
|
|
101
|
+
if (!ownedTask?.fields.control) {
|
|
102
|
+
throw new Error(`Task ${taskId} has no governed control metadata. Normalize it with task_manage set first.`);
|
|
103
|
+
}
|
|
104
|
+
const baseDir = resolve(options.channelDir, "tasks", "worktrees");
|
|
105
|
+
await mkdir(baseDir, { recursive: true });
|
|
106
|
+
if (params.worktreePath) {
|
|
107
|
+
const existing = resolve(params.worktreePath);
|
|
108
|
+
const rel = relative(baseDir, existing);
|
|
109
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
|
|
110
|
+
throw new Error(`worktreePath must be inside ${baseDir}.`);
|
|
111
|
+
}
|
|
112
|
+
const check = await options.executor.exec(`git -C ${shellEscape(existing)} rev-parse --is-inside-work-tree`);
|
|
113
|
+
if (check.code !== 0 || check.stdout.trim() !== "true") {
|
|
114
|
+
throw new Error(`worktreePath is not a usable git worktree: ${existing}`);
|
|
115
|
+
}
|
|
116
|
+
const branchResult = await options.executor.exec(`git -C ${shellEscape(existing)} branch --show-current`);
|
|
117
|
+
const context = {
|
|
118
|
+
runId,
|
|
119
|
+
purpose,
|
|
120
|
+
taskId,
|
|
121
|
+
isolation,
|
|
122
|
+
workingDirectory: existing,
|
|
123
|
+
worktreePath: existing,
|
|
124
|
+
worktreeBranch: branchResult.code === 0 ? branchResult.stdout.trim() || undefined : undefined,
|
|
125
|
+
};
|
|
126
|
+
await recordTaskWorktree(options.channelDir, taskId, context);
|
|
127
|
+
return context;
|
|
128
|
+
}
|
|
129
|
+
const sourceDirectory = resolve(options.workingDirectory ?? process.cwd());
|
|
130
|
+
const rootResult = await options.executor.exec(`git -C ${shellEscape(sourceDirectory)} rev-parse --show-toplevel`);
|
|
131
|
+
if (rootResult.code !== 0 || !rootResult.stdout.trim()) {
|
|
132
|
+
throw new Error("Cannot create an isolated worktree: the current working directory is not inside a git repository.");
|
|
133
|
+
}
|
|
134
|
+
const repoRoot = rootResult.stdout.trim();
|
|
135
|
+
const runSegment = safeRunSegment(runId).slice(-16);
|
|
136
|
+
const taskSegment = safeRunSegment(taskId);
|
|
137
|
+
const path = join(baseDir, taskSegment, runSegment);
|
|
138
|
+
const branch = `pipiclaw-task/${safeGitBranchSegment(taskId)}/${safeGitBranchSegment(runId).slice(-16)}`;
|
|
139
|
+
await mkdir(join(baseDir, taskSegment), { recursive: true });
|
|
140
|
+
const created = await options.executor.exec(`git -C ${shellEscape(repoRoot)} worktree add -b ${shellEscape(branch)} ${shellEscape(path)} HEAD`, { timeout: 60 });
|
|
141
|
+
if (created.code !== 0) {
|
|
142
|
+
throw new Error(`Could not create git worktree for task ${taskId}: ${created.stderr || created.stdout}. Remove the stale worktree/branch or use isolation=shared.`);
|
|
143
|
+
}
|
|
144
|
+
const context = {
|
|
145
|
+
runId,
|
|
146
|
+
purpose,
|
|
147
|
+
taskId,
|
|
148
|
+
isolation,
|
|
149
|
+
workingDirectory: path,
|
|
150
|
+
worktreePath: path,
|
|
151
|
+
worktreeBranch: branch,
|
|
152
|
+
};
|
|
153
|
+
try {
|
|
154
|
+
await recordTaskWorktree(options.channelDir, taskId, context);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
await options.executor.exec(`git -C ${shellEscape(repoRoot)} worktree remove --force ${shellEscape(path)}`);
|
|
158
|
+
await options.executor.exec(`git -C ${shellEscape(repoRoot)} branch -D ${shellEscape(branch)}`);
|
|
159
|
+
throw new Error(`Created the worktree but could not record its ownership on task ${taskId}; the temporary worktree was removed. ${errorMessage(error)}`);
|
|
160
|
+
}
|
|
161
|
+
return context;
|
|
162
|
+
}
|
|
163
|
+
async function recordTaskWorktree(channelDir, taskId, context) {
|
|
164
|
+
await updateStoredTask(channelDir, taskId, (task) => {
|
|
165
|
+
if (!task.fields.control || !context.worktreePath)
|
|
166
|
+
return;
|
|
167
|
+
task.fields.control = applyTaskControlPatch(task.fields.control, {
|
|
168
|
+
isolation: "worktree",
|
|
169
|
+
worktreePath: context.worktreePath,
|
|
170
|
+
worktreeBranch: context.worktreeBranch,
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
async function gitWorkspaceState(executor) {
|
|
175
|
+
const result = await executor.exec("git status --porcelain=v1 --untracked-files=all", { timeout: 30 });
|
|
176
|
+
return result.code === 0 ? result.stdout : undefined;
|
|
177
|
+
}
|
|
47
178
|
function createEmptyUsageTotals() {
|
|
48
179
|
return {
|
|
49
180
|
input: 0,
|
|
@@ -111,34 +242,32 @@ function withSubagentMemoryWriteDeny(securityConfig, channelDir) {
|
|
|
111
242
|
* available to sub-agents (files + web). Sub-agents run with their own security context
|
|
112
243
|
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
113
244
|
*/
|
|
114
|
-
function buildSubagentTools(executor, bashTimeoutSec, options) {
|
|
245
|
+
function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
115
246
|
const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir);
|
|
116
247
|
return buildToolSet({
|
|
117
248
|
executor,
|
|
118
249
|
securityConfig,
|
|
119
250
|
securityContext: {
|
|
120
251
|
workspaceDir: options.workspaceDir,
|
|
121
|
-
|
|
122
|
-
cwd: process.cwd(),
|
|
252
|
+
cwd: runContext.workingDirectory,
|
|
123
253
|
},
|
|
124
254
|
channelId: options.runtimeContext.channelId,
|
|
125
255
|
channelDir: options.channelDir,
|
|
126
256
|
workspaceDir: options.workspaceDir,
|
|
127
|
-
workspacePath: options.runtimeContext.workspacePath,
|
|
128
257
|
webConfig: options.webConfig,
|
|
129
258
|
rtkEnabled: options.rtkEnabled,
|
|
130
259
|
bashDefaultTimeoutSeconds: bashTimeoutSec,
|
|
131
|
-
}, { forSubagent: true });
|
|
260
|
+
}, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
|
|
132
261
|
}
|
|
133
|
-
function buildSubAgentTask(task, config, runtimeContext, contextBlocks) {
|
|
262
|
+
function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
|
|
134
263
|
const taskText = task.trim();
|
|
135
264
|
const lines = [
|
|
136
265
|
`Runtime context:`,
|
|
137
|
-
`- Workspace root: ${runtimeContext.
|
|
266
|
+
`- Workspace root: ${runtimeContext.workspaceDir}`,
|
|
138
267
|
`- Channel id: ${runtimeContext.channelId}`,
|
|
139
|
-
`- Channel directory: ${runtimeContext.
|
|
140
|
-
`-
|
|
141
|
-
`- Filesystem isolation:
|
|
268
|
+
`- Channel directory: ${runtimeContext.workspaceDir}/${runtimeContext.channelId}`,
|
|
269
|
+
`- Working directory: ${runContext.workingDirectory}`,
|
|
270
|
+
`- Filesystem isolation: ${runContext.isolation === "worktree" ? "dedicated git worktree" : "shared with parent"}`,
|
|
142
271
|
`- Your configured role: ${config.name}`,
|
|
143
272
|
];
|
|
144
273
|
for (const block of contextBlocks) {
|
|
@@ -148,6 +277,10 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks) {
|
|
|
148
277
|
lines.push("", block.trim());
|
|
149
278
|
}
|
|
150
279
|
lines.push("", `Task:`, taskText);
|
|
280
|
+
if (runContext.purpose === "verify") {
|
|
281
|
+
const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
|
|
282
|
+
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.");
|
|
283
|
+
}
|
|
151
284
|
return lines.join("\n");
|
|
152
285
|
}
|
|
153
286
|
function buildSessionContextBlock(sessionMarkdown) {
|
|
@@ -229,7 +362,7 @@ function filterToolsByName(allTools, names) {
|
|
|
229
362
|
const allowed = new Set(names);
|
|
230
363
|
return allTools.filter((tool) => allowed.has(tool.name));
|
|
231
364
|
}
|
|
232
|
-
function createDetails(config, usage, turns, toolCalls, durationMs, failed, failureReason) {
|
|
365
|
+
function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict) {
|
|
233
366
|
return {
|
|
234
367
|
kind: "subagent",
|
|
235
368
|
agent: config.name,
|
|
@@ -245,6 +378,13 @@ function createDetails(config, usage, turns, toolCalls, durationMs, failed, fail
|
|
|
245
378
|
...usage,
|
|
246
379
|
cost: { ...usage.cost },
|
|
247
380
|
},
|
|
381
|
+
runId: runContext.runId,
|
|
382
|
+
purpose: runContext.purpose,
|
|
383
|
+
taskId: runContext.taskId,
|
|
384
|
+
isolation: runContext.isolation,
|
|
385
|
+
worktreePath: runContext.worktreePath,
|
|
386
|
+
worktreeBranch: runContext.worktreeBranch,
|
|
387
|
+
verificationVerdict,
|
|
248
388
|
};
|
|
249
389
|
}
|
|
250
390
|
function linkAbortSignals(parentSignal, childController) {
|
|
@@ -282,6 +422,8 @@ export function createSubAgentTool(options) {
|
|
|
282
422
|
throw new Error(`${invocation.error}\n\nAvailable predefined sub-agents:\n${formatSubAgentList(discovery.agents)}`);
|
|
283
423
|
}
|
|
284
424
|
const config = invocation.config;
|
|
425
|
+
const runContext = await prepareRunContext(_toolCallId, params, options);
|
|
426
|
+
const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
|
|
285
427
|
const apiKey = await options.resolveApiKey(config.model);
|
|
286
428
|
const startedAt = Date.now();
|
|
287
429
|
const usage = createEmptyUsageTotals();
|
|
@@ -297,10 +439,12 @@ export function createSubAgentTool(options) {
|
|
|
297
439
|
lastUpdateText = nextText;
|
|
298
440
|
onUpdate?.({
|
|
299
441
|
content: [{ type: "text", text: nextText }],
|
|
300
|
-
details: createDetails(config, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
|
|
442
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
|
|
301
443
|
});
|
|
302
444
|
};
|
|
303
|
-
const availableTools = buildSubagentTools(
|
|
445
|
+
const availableTools = buildSubagentTools(scopedExecutor, config.bashTimeoutSec, options, runContext);
|
|
446
|
+
const verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
447
|
+
const verifierSubjectBefore = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
|
|
304
448
|
const worker = options.createWorker?.({
|
|
305
449
|
subAgent: config,
|
|
306
450
|
apiKey,
|
|
@@ -365,7 +509,7 @@ export function createSubAgentTool(options) {
|
|
|
365
509
|
childController.signal.addEventListener("abort", abortWorker, { once: true });
|
|
366
510
|
try {
|
|
367
511
|
const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
|
|
368
|
-
await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks));
|
|
512
|
+
await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
|
|
369
513
|
await worker.waitForIdle();
|
|
370
514
|
}
|
|
371
515
|
finally {
|
|
@@ -392,6 +536,39 @@ export function createSubAgentTool(options) {
|
|
|
392
536
|
(lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
|
|
393
537
|
? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
|
|
394
538
|
: undefined);
|
|
539
|
+
const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
540
|
+
const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
|
|
541
|
+
const workspaceChanged = runContext.purpose === "verify" &&
|
|
542
|
+
(verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
|
|
543
|
+
? verifierSubjectBefore !== verifierSubjectAfter
|
|
544
|
+
: verifierGitStateBefore !== undefined &&
|
|
545
|
+
verifierGitStateAfter !== undefined &&
|
|
546
|
+
verifierGitStateBefore !== verifierGitStateAfter);
|
|
547
|
+
const declaredVerdict = runContext.purpose === "verify" ? parseVerificationVerdict(finalText) : undefined;
|
|
548
|
+
const verificationVerdict = runContext.purpose === "verify"
|
|
549
|
+
? declaredVerdict === "pass" && !effectiveFailureReason && !workspaceChanged
|
|
550
|
+
? "pass"
|
|
551
|
+
: "fail"
|
|
552
|
+
: undefined;
|
|
553
|
+
if (runContext.purpose === "verify" && runContext.taskId && verificationVerdict) {
|
|
554
|
+
const evidence = workspaceChanged
|
|
555
|
+
? "Verifier changed tracked workspace files; the attestation is invalid."
|
|
556
|
+
: !declaredVerdict
|
|
557
|
+
? "Verifier did not emit the required final VERDICT marker."
|
|
558
|
+
: finalText.trim().slice(0, 8_000);
|
|
559
|
+
await writeVerificationAttestation(options.channelDir, {
|
|
560
|
+
runId: runContext.runId,
|
|
561
|
+
taskId: runContext.taskId,
|
|
562
|
+
verdict: verificationVerdict,
|
|
563
|
+
agent: config.name,
|
|
564
|
+
model: formatModelReference(config.model),
|
|
565
|
+
checkedAt: new Date().toISOString(),
|
|
566
|
+
evidence,
|
|
567
|
+
workspaceChanged: Boolean(workspaceChanged),
|
|
568
|
+
subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
|
|
569
|
+
output: finalText,
|
|
570
|
+
});
|
|
571
|
+
}
|
|
395
572
|
if (effectiveFailureReason) {
|
|
396
573
|
if (!finalText.trim()) {
|
|
397
574
|
emitUpdate(formatStatus(config.name, "failed"));
|
|
@@ -400,12 +577,12 @@ export function createSubAgentTool(options) {
|
|
|
400
577
|
emitUpdate(formatStatus(config.name, "stopped"));
|
|
401
578
|
return {
|
|
402
579
|
content: [{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalText) }],
|
|
403
|
-
details: createDetails(config, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason),
|
|
580
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict),
|
|
404
581
|
};
|
|
405
582
|
}
|
|
406
583
|
return {
|
|
407
584
|
content: [{ type: "text", text: finalText || `(Sub-agent ${config.name} completed with no text output)` }],
|
|
408
|
-
details: createDetails(config, usage, assistantTurns, toolCalls, durationMs, false),
|
|
585
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict),
|
|
409
586
|
};
|
|
410
587
|
},
|
|
411
588
|
};
|
|
@@ -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;
|