@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.2
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/dist/agent/channel-runner.d.ts +3 -0
- package/dist/agent/channel-runner.js +9 -0
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +9 -0
- package/dist/agent/job-manager.d.ts +11 -3
- package/dist/agent/job-manager.js +63 -6
- package/dist/agent/prompt/sections.js +46 -7
- package/dist/agent/prompt/types.d.ts +9 -0
- package/dist/agent/session-events.js +7 -42
- package/dist/agent/types.d.ts +4 -0
- package/dist/playbooks/agent-delegation.md +46 -21
- package/dist/playbooks/runtime-orientation.md +2 -2
- package/dist/runtime/bootstrap.d.ts +38 -0
- package/dist/runtime/bootstrap.js +167 -14
- package/dist/runtime/dingtalk.d.ts +9 -0
- package/dist/runtime/dingtalk.js +3 -0
- package/dist/runtime/durable-dispatch.d.ts +4 -0
- package/dist/runtime/durable-dispatch.js +16 -0
- package/dist/runtime/store.d.ts +7 -0
- package/dist/runtime/subagent-commands.d.ts +15 -0
- package/dist/runtime/subagent-commands.js +122 -0
- package/dist/runtime/task-commands.js +5 -1
- package/dist/security/logger.js +10 -1
- package/dist/security/types.d.ts +17 -1
- package/dist/shared/host-process.d.ts +21 -0
- package/dist/shared/host-process.js +44 -0
- package/dist/shared/jsonl-appender.d.ts +2 -0
- package/dist/shared/jsonl-appender.js +25 -13
- package/dist/shared/shell-words.d.ts +9 -0
- package/dist/shared/shell-words.js +52 -0
- package/dist/subagents/discovery.d.ts +42 -1
- package/dist/subagents/discovery.js +302 -69
- package/dist/subagents/external/claude-code.d.ts +2 -0
- package/dist/subagents/external/claude-code.js +152 -0
- package/dist/subagents/external/codex-cli.d.ts +2 -0
- package/dist/subagents/external/codex-cli.js +133 -0
- package/dist/subagents/external/exec.d.ts +2 -0
- package/dist/subagents/external/exec.js +38 -0
- package/dist/subagents/external/harness.d.ts +102 -0
- package/dist/subagents/external/harness.js +76 -0
- package/dist/subagents/external/registry.d.ts +2 -0
- package/dist/subagents/external/registry.js +11 -0
- package/dist/subagents/external/run.d.ts +49 -0
- package/dist/subagents/external/run.js +266 -0
- package/dist/subagents/runs.d.ts +230 -0
- package/dist/subagents/runs.js +615 -0
- package/dist/subagents/tool.d.ts +26 -0
- package/dist/subagents/tool.js +464 -182
- package/dist/subagents/workspace-lease.d.ts +36 -0
- package/dist/subagents/workspace-lease.js +48 -0
- package/dist/tasks/artifact-subject.js +50 -2
- package/dist/tasks/control.d.ts +12 -0
- package/dist/tasks/control.js +20 -0
- package/dist/tasks/store.d.ts +21 -0
- package/dist/tasks/store.js +80 -0
- package/dist/tasks/verification.d.ts +8 -0
- package/dist/tasks/verification.js +10 -2
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +12 -1
- package/dist/tools/registry.js +1 -0
- package/dist/tools/subagent-manage.d.ts +23 -0
- package/dist/tools/subagent-manage.js +154 -0
- package/dist/tools/tool-details.d.ts +1 -1
- package/dist/tui/app.js +2 -0
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- package/dist/usage/ledger.d.ts +13 -0
- package/dist/usage/ledger.js +15 -2
- package/dist/usage/render.js +22 -0
- package/examples/sub-agents/README.md +61 -12
- package/examples/sub-agents/builder-hard.md +45 -0
- package/examples/sub-agents/builder.md +41 -0
- package/examples/sub-agents/documenter.md +53 -0
- package/examples/sub-agents/log-sifter.md +43 -0
- package/examples/sub-agents/planner.md +42 -0
- package/examples/sub-agents/reviewer.md +38 -38
- package/examples/sub-agents/scout.md +31 -0
- package/examples/sub-agents/verifier.md +32 -36
- package/examples/sub-agents/worker.md +36 -0
- package/package.json +1 -1
- package/examples/sub-agents/researcher.md +0 -41
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { spawn as nodeSpawn } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { createWriteStream } from "node:fs";
|
|
4
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import * as log from "../../log.js";
|
|
7
|
+
import { logSecurityEvent } from "../../security/logger.js";
|
|
8
|
+
import { killProcessGroup } from "../../shared/host-process.js";
|
|
9
|
+
import { formatLocalTime } from "../../shared/local-time.js";
|
|
10
|
+
import { splitShellWords } from "../../shared/shell-words.js";
|
|
11
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
12
|
+
import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
|
|
13
|
+
import { parseVerificationVerdict, writeVerificationAttestation } from "../../tasks/verification.js";
|
|
14
|
+
import { getSubAgentRunManager } from "../runs.js";
|
|
15
|
+
import { classifyExternalOutcome } from "./harness.js";
|
|
16
|
+
import { getExternalHarness } from "./registry.js";
|
|
17
|
+
const WAKE_OUTPUT_TAIL_CHARS = 2_000;
|
|
18
|
+
function buildStdinContent(harnessId, systemPrompt, task) {
|
|
19
|
+
// claude-code has a real system-prompt flag (--append-system-prompt-file, D4); every other
|
|
20
|
+
// harness has no such channel, so the role's system prompt has nowhere to go but the prompt
|
|
21
|
+
// itself, folded ahead of the task.
|
|
22
|
+
if (harnessId === "claude-code")
|
|
23
|
+
return task;
|
|
24
|
+
return `${systemPrompt.trim()}\n\n---\n\n${task.trim()}\n`;
|
|
25
|
+
}
|
|
26
|
+
/** Launches an external run. Returns once the process is confirmed spawned (or fails fast if it
|
|
27
|
+
* never starts); the wait-for-exit-and-settle work continues in the background afterward. */
|
|
28
|
+
export async function launchExternalRun(input) {
|
|
29
|
+
const harness = getExternalHarness(input.harness);
|
|
30
|
+
if (!harness) {
|
|
31
|
+
throw new Error(`Unknown external harness "${input.harness}".`);
|
|
32
|
+
}
|
|
33
|
+
// `tool.ts` already creates the artifact dir for a fresh run; `follow_up` (subagent-manage.ts)
|
|
34
|
+
// mints a new runId/artifactDir on the spot, so this is the one place that must be reliable
|
|
35
|
+
// either way.
|
|
36
|
+
await mkdir(input.artifactDir, { recursive: true });
|
|
37
|
+
const promptFile = join(input.artifactDir, "prompt.txt");
|
|
38
|
+
const systemPromptFile = join(input.artifactDir, "system-prompt.txt");
|
|
39
|
+
const stdinContent = buildStdinContent(harness.id, input.systemPrompt, input.task);
|
|
40
|
+
await writeFile(promptFile, `${input.task.trim()}\n`, "utf-8");
|
|
41
|
+
await writeFile(systemPromptFile, `${input.systemPrompt.trim()}\n`, "utf-8");
|
|
42
|
+
// D9: an external verifier's advisory attestation needs a before/after subject snapshot the
|
|
43
|
+
// same way the internal path does — taken here, before the process starts, since this is the
|
|
44
|
+
// earliest point at which the run is committed to running against this workingDirectory.
|
|
45
|
+
const verifySubjectBefore = input.purpose === "verify" ? await workspaceSubjectHash(input.workingDirectory) : undefined;
|
|
46
|
+
const argv = input.shell ? [] : splitShellWords(input.command);
|
|
47
|
+
const invocation = input.shell
|
|
48
|
+
? { executable: "/bin/sh", args: ["-lc", input.command], resumable: false }
|
|
49
|
+
: harness.buildInvocation({
|
|
50
|
+
argv,
|
|
51
|
+
model: input.externalModelRef,
|
|
52
|
+
thinkingLevel: input.thinkingLevel,
|
|
53
|
+
artifactDir: input.artifactDir,
|
|
54
|
+
promptFile,
|
|
55
|
+
systemPromptFile,
|
|
56
|
+
resumeSessionId: input.resumeSessionId,
|
|
57
|
+
});
|
|
58
|
+
const spawnedArgv = [invocation.executable, ...invocation.args];
|
|
59
|
+
// Security gate: the final executable/argv/cwd/capability record must be durable before a
|
|
60
|
+
// process can exist. `external-agent` uses the strict appender path and rejects on queue or I/O
|
|
61
|
+
// failure; callers then release any admission lease without an unaudited child ever starting.
|
|
62
|
+
await logSecurityEvent(input.workspaceDir, input.securityConfig, {
|
|
63
|
+
type: "external-agent",
|
|
64
|
+
tool: "subagent",
|
|
65
|
+
channelId: input.channelId,
|
|
66
|
+
runId: input.runId,
|
|
67
|
+
agent: input.agent,
|
|
68
|
+
harness: harness.id,
|
|
69
|
+
argv: spawnedArgv,
|
|
70
|
+
workingDirectory: input.workingDirectory,
|
|
71
|
+
mutates: input.mutates ?? "read",
|
|
72
|
+
model: input.externalModelRef,
|
|
73
|
+
});
|
|
74
|
+
const runManager = getSubAgentRunManager(input.channelId);
|
|
75
|
+
await runManager.register({
|
|
76
|
+
runId: input.runId,
|
|
77
|
+
channelId: input.channelId,
|
|
78
|
+
runtime: "external",
|
|
79
|
+
harness: harness.id,
|
|
80
|
+
agent: input.agent,
|
|
81
|
+
label: input.label,
|
|
82
|
+
source: input.source,
|
|
83
|
+
tools: [],
|
|
84
|
+
model: input.externalModelRef,
|
|
85
|
+
purpose: input.purpose,
|
|
86
|
+
taskId: input.taskId,
|
|
87
|
+
workingDirectory: input.workingDirectory,
|
|
88
|
+
artifactDir: input.artifactDir,
|
|
89
|
+
leaseKey: input.leaseKey,
|
|
90
|
+
});
|
|
91
|
+
let cancelledBeforeSpawn = false;
|
|
92
|
+
const launchClaimed = await runManager.claimExternalLaunch(input.runId, () => {
|
|
93
|
+
cancelledBeforeSpawn = true;
|
|
94
|
+
});
|
|
95
|
+
if (!launchClaimed) {
|
|
96
|
+
await runManager.settle(input.runId, { ...failedSettleInput("Cancelled before the external process was spawned."), status: "cancelled" }, { announce: false });
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const eventsPath = join(input.artifactDir, "events.jsonl");
|
|
100
|
+
const stderrPath = join(input.artifactDir, "stderr.log");
|
|
101
|
+
const eventsStream = createWriteStream(eventsPath);
|
|
102
|
+
const stderrStream = createWriteStream(stderrPath);
|
|
103
|
+
// A stream closed before its "open" completes (e.g. the spawn-failure path below) can emit its
|
|
104
|
+
// own "error"; without a listener that becomes an uncaught exception rather than a settled run.
|
|
105
|
+
eventsStream.on("error", () => { });
|
|
106
|
+
stderrStream.on("error", () => { });
|
|
107
|
+
const spawnFn = input.spawnFn ?? nodeSpawn;
|
|
108
|
+
let child;
|
|
109
|
+
try {
|
|
110
|
+
child = spawnFn(invocation.executable, invocation.args, {
|
|
111
|
+
detached: true,
|
|
112
|
+
cwd: input.workingDirectory,
|
|
113
|
+
env: input.env ? { ...process.env, ...input.env } : process.env,
|
|
114
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
eventsStream.close();
|
|
119
|
+
stderrStream.close();
|
|
120
|
+
await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${errorMessage(error)}`), {
|
|
121
|
+
announce: true,
|
|
122
|
+
});
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const spawnFailure = await new Promise((resolve) => {
|
|
126
|
+
child.once("error", (error) => resolve(error));
|
|
127
|
+
child.once("spawn", () => resolve(undefined));
|
|
128
|
+
});
|
|
129
|
+
if (spawnFailure || !child.pid) {
|
|
130
|
+
eventsStream.close();
|
|
131
|
+
stderrStream.close();
|
|
132
|
+
await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${spawnFailure ? errorMessage(spawnFailure) : "no pid"}`), { announce: true });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const pid = child.pid;
|
|
136
|
+
if (cancelledBeforeSpawn) {
|
|
137
|
+
void killProcessGroup(pid);
|
|
138
|
+
eventsStream.close();
|
|
139
|
+
stderrStream.close();
|
|
140
|
+
await runManager.settle(input.runId, { ...failedSettleInput("Cancelled while the external process was spawning."), status: "cancelled" }, { announce: false });
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const fingerprint = randomBytes(6).toString("hex");
|
|
144
|
+
await runManager.setLaunched(input.runId, {
|
|
145
|
+
pid,
|
|
146
|
+
fingerprint,
|
|
147
|
+
argv: spawnedArgv,
|
|
148
|
+
sessionId: invocation.presetSessionId,
|
|
149
|
+
});
|
|
150
|
+
child.stdout?.on("data", (chunk) => eventsStream.write(chunk));
|
|
151
|
+
child.stderr?.on("data", (chunk) => stderrStream.write(chunk));
|
|
152
|
+
if (child.stdin) {
|
|
153
|
+
child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
|
|
154
|
+
child.stdin.end(stdinContent);
|
|
155
|
+
}
|
|
156
|
+
let cancelled = false;
|
|
157
|
+
runManager.registerCancelHandle(input.runId, () => {
|
|
158
|
+
cancelled = true;
|
|
159
|
+
void killProcessGroup(pid);
|
|
160
|
+
});
|
|
161
|
+
const wallClockTimer = setTimeout(() => {
|
|
162
|
+
void killProcessGroup(pid);
|
|
163
|
+
}, input.maxWallTimeSec * 1000);
|
|
164
|
+
wallClockTimer.unref?.();
|
|
165
|
+
// Deliberately not awaited by the caller (D2: external's sync grace window is 0) — this
|
|
166
|
+
// continues in the background and settles the run itself once the process exits.
|
|
167
|
+
void new Promise((resolve) => {
|
|
168
|
+
child.once("close", (code) => resolve(code ?? undefined));
|
|
169
|
+
}).then(async (exitCode) => {
|
|
170
|
+
clearTimeout(wallClockTimer);
|
|
171
|
+
runManager.clearCancelHandle(input.runId);
|
|
172
|
+
// The leader can exit before a detached descendant it spawned (e.g. a shell that forked and
|
|
173
|
+
// returned); `-pid` still reaches the whole group as long as the group itself is still
|
|
174
|
+
// around, so reap it unconditionally rather than only on an explicit cancel/timeout.
|
|
175
|
+
await killProcessGroup(pid);
|
|
176
|
+
await new Promise((resolve) => eventsStream.end(resolve));
|
|
177
|
+
await new Promise((resolve) => stderrStream.end(resolve));
|
|
178
|
+
if (cancelled) {
|
|
179
|
+
await runManager
|
|
180
|
+
.settle(input.runId, { ...failedSettleInput("Cancelled by request."), status: "cancelled" }, { announce: false })
|
|
181
|
+
.catch((error) => {
|
|
182
|
+
log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
|
|
183
|
+
});
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const eventsText = await readFile(eventsPath, "utf-8").catch(() => "");
|
|
187
|
+
const stderrTail = (await readFile(stderrPath, "utf-8").catch(() => "")).slice(-WAKE_OUTPUT_TAIL_CHARS);
|
|
188
|
+
const outcome = harness.parseOutcome({ eventsText, exitCode, stderrTail });
|
|
189
|
+
const classification = classifyExternalOutcome(harness.id, outcome);
|
|
190
|
+
// D9: the verdict is a fact the run reported, independent of whether the run itself
|
|
191
|
+
// "succeeded" — a verifier that cleanly concludes VERDICT: FAIL is still a completed run.
|
|
192
|
+
let verificationVerdict;
|
|
193
|
+
if (input.purpose === "verify" && input.taskId && input.channelDir && classification.status === "completed") {
|
|
194
|
+
const subjectAfter = await workspaceSubjectHash(input.workingDirectory);
|
|
195
|
+
const workspaceChanged = verifySubjectBefore !== undefined && subjectAfter !== undefined && verifySubjectBefore !== subjectAfter;
|
|
196
|
+
const declaredVerdict = parseVerificationVerdict(outcome.finalText);
|
|
197
|
+
verificationVerdict = declaredVerdict === "pass" && !workspaceChanged ? "pass" : "fail";
|
|
198
|
+
const evidence = workspaceChanged
|
|
199
|
+
? "Verifier's workspace subject changed; the attestation is invalid."
|
|
200
|
+
: !declaredVerdict
|
|
201
|
+
? "Verifier did not emit the required final VERDICT marker."
|
|
202
|
+
: outcome.finalText.trim().slice(0, 8_000);
|
|
203
|
+
await writeVerificationAttestation(input.channelDir, {
|
|
204
|
+
runId: input.runId,
|
|
205
|
+
taskId: input.taskId,
|
|
206
|
+
verdict: verificationVerdict,
|
|
207
|
+
checkedAt: formatLocalTime(),
|
|
208
|
+
evidence,
|
|
209
|
+
workspaceChanged,
|
|
210
|
+
subjectHash: workspaceChanged ? undefined : subjectAfter,
|
|
211
|
+
subjectDir: input.workingDirectory,
|
|
212
|
+
// External verifiers cannot have their tools structurally removed the way an
|
|
213
|
+
// internal verifier's are — the sandbox flag lives in the role's own `command`,
|
|
214
|
+
// unverifiable by pipiclaw. Advisory, not enforced (D9).
|
|
215
|
+
verificationStrength: "advisory",
|
|
216
|
+
}).catch((error) => {
|
|
217
|
+
log.logWarning(`Failed to write verification attestation for run ${input.runId}`, errorMessage(error));
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
await runManager
|
|
221
|
+
.settle(input.runId, {
|
|
222
|
+
status: classification.status,
|
|
223
|
+
failureReason: classification.failureReason,
|
|
224
|
+
usage: {
|
|
225
|
+
input: outcome.usage?.input ?? 0,
|
|
226
|
+
output: outcome.usage?.output ?? 0,
|
|
227
|
+
cacheRead: outcome.usage?.cacheRead ?? 0,
|
|
228
|
+
cacheWrite: outcome.usage?.cacheWrite ?? 0,
|
|
229
|
+
total: outcome.usage?.total ?? 0,
|
|
230
|
+
cost: outcome.usage?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
231
|
+
},
|
|
232
|
+
usageKnown: outcome.usageKnown,
|
|
233
|
+
costKnown: outcome.costKnown,
|
|
234
|
+
turns: 0,
|
|
235
|
+
toolCalls: 0,
|
|
236
|
+
durationMs: 0,
|
|
237
|
+
outputText: outcome.finalText,
|
|
238
|
+
sessionId: outcome.sessionId,
|
|
239
|
+
verificationVerdict,
|
|
240
|
+
verificationStrength: verificationVerdict ? "advisory" : undefined,
|
|
241
|
+
}, { announce: true })
|
|
242
|
+
.catch((error) => {
|
|
243
|
+
log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
function failedSettleInput(reason) {
|
|
247
|
+
return {
|
|
248
|
+
status: "failed",
|
|
249
|
+
failureReason: reason,
|
|
250
|
+
usage: {
|
|
251
|
+
input: 0,
|
|
252
|
+
output: 0,
|
|
253
|
+
cacheRead: 0,
|
|
254
|
+
cacheWrite: 0,
|
|
255
|
+
total: 0,
|
|
256
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
257
|
+
},
|
|
258
|
+
usageKnown: false,
|
|
259
|
+
costKnown: false,
|
|
260
|
+
turns: 0,
|
|
261
|
+
toolCalls: 0,
|
|
262
|
+
durationMs: 0,
|
|
263
|
+
outputText: "",
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import type { DingTalkEvent } from "../runtime/dingtalk.js";
|
|
2
|
+
import type { ChannelStore } from "../runtime/store.js";
|
|
3
|
+
import type { UsageTotals } from "../shared/types.js";
|
|
4
|
+
import type { UsageLedger } from "../usage/ledger.js";
|
|
5
|
+
/**
|
|
6
|
+
* The run: one abstraction level for delegation, whether it executes as an in-process sub-agent
|
|
7
|
+
* or (from spec 040 phase 2 onward) a short-lived external CLI process. See
|
|
8
|
+
* `docs/specs/040-async-delegation-and-external-agents/design.md`, D1.
|
|
9
|
+
*
|
|
10
|
+
* State machine vocabulary is borrowed from `job-manager.ts`'s `JobStatus` rather than inventing
|
|
11
|
+
* a second one. Only three facts are persisted as idempotent markers (D1/P5) because only three
|
|
12
|
+
* side effects cannot be safely replayed: settling (writes output, frees a lease), recording
|
|
13
|
+
* usage (a ledger write is a real charge), and enqueuing the completion wake (redelivery makes
|
|
14
|
+
* the parent agent re-process the same result). Everything else — duration, tool counts, verdict
|
|
15
|
+
* — is plain data that can be overwritten harmlessly.
|
|
16
|
+
*/
|
|
17
|
+
export type RunStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
|
|
18
|
+
export type RunRuntime = "internal" | "external";
|
|
19
|
+
export type RunHarness = "claude-code" | "codex-cli" | "exec";
|
|
20
|
+
export type RunMutates = "read" | "write";
|
|
21
|
+
/**
|
|
22
|
+
* Longest a dispatching tool call waits for its run to settle before returning a "still running"
|
|
23
|
+
* placeholder instead of the result (D2). A code constant, not a settings key, per CLAUDE.md's
|
|
24
|
+
* rule for numeric thresholds.
|
|
25
|
+
*/
|
|
26
|
+
export declare const SYNC_GRACE_MS = 120000;
|
|
27
|
+
/** D10.2: per-channel cap on concurrently running delegation runs, mirrors job-manager's MAX_RUNNING_JOBS. */
|
|
28
|
+
export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 5;
|
|
29
|
+
/** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
|
|
30
|
+
* not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
|
|
31
|
+
export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
|
|
32
|
+
export interface RunUsage {
|
|
33
|
+
usage: UsageTotals;
|
|
34
|
+
/** False only for harnesses that cannot report tokens at all (`exec`). */
|
|
35
|
+
usageKnown: boolean;
|
|
36
|
+
/** False for harnesses that omit a cost field (`codex-cli`, `exec`). */
|
|
37
|
+
costKnown: boolean;
|
|
38
|
+
}
|
|
39
|
+
export interface RunRecord extends RunUsage {
|
|
40
|
+
runId: string;
|
|
41
|
+
channelId: string;
|
|
42
|
+
runtime: RunRuntime;
|
|
43
|
+
harness?: RunHarness;
|
|
44
|
+
agent: string;
|
|
45
|
+
label: string;
|
|
46
|
+
source: "predefined" | "inline";
|
|
47
|
+
tools: string[];
|
|
48
|
+
model?: string;
|
|
49
|
+
purpose: "work" | "verify";
|
|
50
|
+
taskId?: string;
|
|
51
|
+
workingDirectory: string;
|
|
52
|
+
artifactDir: string;
|
|
53
|
+
status: RunStatus;
|
|
54
|
+
startedAt: number;
|
|
55
|
+
finishedAt?: number;
|
|
56
|
+
durationMs?: number;
|
|
57
|
+
failureReason?: string;
|
|
58
|
+
turns?: number;
|
|
59
|
+
toolCalls?: number;
|
|
60
|
+
verificationVerdict?: "pass" | "fail";
|
|
61
|
+
/** `enforced` for a built-in verifier (tools structurally removed); `advisory` for external (D9). */
|
|
62
|
+
verificationStrength?: "enforced" | "advisory";
|
|
63
|
+
/** Set once settlement (write output, free resources) has happened; guards against replay. */
|
|
64
|
+
settledAt?: number;
|
|
65
|
+
/** Set once this run's usage has been written to the ledger; guards against double billing. */
|
|
66
|
+
usageRecorded?: boolean;
|
|
67
|
+
/** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
|
|
68
|
+
wakeEnqueued?: boolean;
|
|
69
|
+
/** Durable one-time relationship between the internally produced wake and task activation (T9). */
|
|
70
|
+
wakeClaimDispatchId?: string;
|
|
71
|
+
wakeConsumedAt?: number;
|
|
72
|
+
pid?: number;
|
|
73
|
+
fingerprint?: string;
|
|
74
|
+
argv?: string[];
|
|
75
|
+
sessionId?: string;
|
|
76
|
+
leaseKey?: string;
|
|
77
|
+
mutates?: RunMutates;
|
|
78
|
+
}
|
|
79
|
+
export interface RegisterRunInput {
|
|
80
|
+
runId: string;
|
|
81
|
+
channelId: string;
|
|
82
|
+
runtime: RunRuntime;
|
|
83
|
+
harness?: RunHarness;
|
|
84
|
+
agent: string;
|
|
85
|
+
label: string;
|
|
86
|
+
source: "predefined" | "inline";
|
|
87
|
+
tools: string[];
|
|
88
|
+
model?: string;
|
|
89
|
+
purpose: "work" | "verify";
|
|
90
|
+
taskId?: string;
|
|
91
|
+
workingDirectory: string;
|
|
92
|
+
artifactDir: string;
|
|
93
|
+
/** Set only when the caller already holds a workspace write lease for this run (D10.1). */
|
|
94
|
+
leaseKey?: string;
|
|
95
|
+
}
|
|
96
|
+
export interface SettleInput {
|
|
97
|
+
status: "completed" | "failed" | "cancelled" | "lost";
|
|
98
|
+
failureReason?: string;
|
|
99
|
+
usage: UsageTotals;
|
|
100
|
+
usageKnown: boolean;
|
|
101
|
+
costKnown: boolean;
|
|
102
|
+
turns: number;
|
|
103
|
+
toolCalls: number;
|
|
104
|
+
durationMs: number;
|
|
105
|
+
/** Full reply text. Settlement saves it to `output.md`; only its tail goes in the wake. */
|
|
106
|
+
outputText: string;
|
|
107
|
+
verificationVerdict?: "pass" | "fail";
|
|
108
|
+
verificationStrength?: "enforced" | "advisory";
|
|
109
|
+
/** The harness's own session/thread id, captured even on failure so a later resume can still use it. */
|
|
110
|
+
sessionId?: string;
|
|
111
|
+
}
|
|
112
|
+
export interface RunManagerOptions {
|
|
113
|
+
/** Root of the per-channel record directories (`<stateDir>/<channelId>/`). Omit to skip persistence. */
|
|
114
|
+
stateDir?: string;
|
|
115
|
+
dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
|
|
116
|
+
ledger?: UsageLedger;
|
|
117
|
+
store?: ChannelStore;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Per-channel manager for delegation runs — the single settlement/usage/wake authority for both
|
|
121
|
+
* internal sub-agents and (once wired) external harnesses (D7). Modeled directly on
|
|
122
|
+
* `ChannelJobManager`; the two are not unified because a run's terminal status depends on a
|
|
123
|
+
* protocol verdict, not just process exit (D4), so the state machines genuinely differ.
|
|
124
|
+
*/
|
|
125
|
+
export declare class SubAgentRunManager {
|
|
126
|
+
private readonly channelId;
|
|
127
|
+
private readonly options;
|
|
128
|
+
private readonly runs;
|
|
129
|
+
/** In-memory cancel handles for runs alive in *this* process (internal runs; external process
|
|
130
|
+
* kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
|
|
131
|
+
* the only thing that could reach an in-process worker anyway (D10.3). */
|
|
132
|
+
private readonly cancelHandles;
|
|
133
|
+
/** External launch intents exist before a safe live child handle does. A cancel in that window
|
|
134
|
+
* is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
|
|
135
|
+
private readonly externalLaunches;
|
|
136
|
+
private readonly queue;
|
|
137
|
+
constructor(channelId: string, options: RunManagerOptions);
|
|
138
|
+
private recordPath;
|
|
139
|
+
private persist;
|
|
140
|
+
/**
|
|
141
|
+
* The full reply text always lands in `<artifactDir>/output.md` (spec 032 D4, carried into 040
|
|
142
|
+
* D1's settlement step). It is written here, in the one place every runtime settles, rather than
|
|
143
|
+
* in each caller: the completion wake points at this file, and it is what makes an inline-returned
|
|
144
|
+
* result self-recoverable after a crash (D2). A failed write must not block settlement — losing
|
|
145
|
+
* the artifact is bad, leaving the run stuck in `running` is worse.
|
|
146
|
+
*/
|
|
147
|
+
private writeOutputFile;
|
|
148
|
+
private forget;
|
|
149
|
+
get(runId: string): RunRecord | undefined;
|
|
150
|
+
list(): RunRecord[];
|
|
151
|
+
/** Task ids a still-running delegation on this channel will eventually wake. Feeds `/tasks doctor`. */
|
|
152
|
+
runningTaskIds(): Set<string>;
|
|
153
|
+
runningCount(): number;
|
|
154
|
+
/** Register the run's lifecycle before any work starts, and persist it immediately (D1). */
|
|
155
|
+
register(input: RegisterRunInput): Promise<RunRecord>;
|
|
156
|
+
/** Atomically crosses the external launch cancel window. The supplied live-handle callback is
|
|
157
|
+
* installed before this method resolves; a cancel queued during register is observed first and
|
|
158
|
+
* makes this return false, so the caller must not spawn. */
|
|
159
|
+
claimExternalLaunch(runId: string, cancel: () => void): Promise<boolean>;
|
|
160
|
+
/**
|
|
161
|
+
* Persist the pid once a spawn actually succeeds — the second half of D1's launch ordering.
|
|
162
|
+
* `register()` already durably recorded the intent (argv, working directory, artifact dir)
|
|
163
|
+
* with pid unknown; a crash between that persist and this one leaves an intent-only record
|
|
164
|
+
* that restore treats as `lost` rather than guessing (D1/D10.3).
|
|
165
|
+
*/
|
|
166
|
+
setLaunched(runId: string, info: {
|
|
167
|
+
pid: number;
|
|
168
|
+
fingerprint: string;
|
|
169
|
+
argv: string[];
|
|
170
|
+
sessionId?: string;
|
|
171
|
+
}): Promise<void>;
|
|
172
|
+
/** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
|
|
173
|
+
* interrupted activation, while copied text or a different dispatch id can never claim it. */
|
|
174
|
+
beginWakeConsumption(runId: string, taskId: string, dispatchId: string): Promise<boolean>;
|
|
175
|
+
finishWakeConsumption(runId: string, dispatchId: string): Promise<void>;
|
|
176
|
+
/** Let a caller (subagent tool) register a way to abort this run's in-process worker. */
|
|
177
|
+
registerCancelHandle(runId: string, cancel: () => void): void;
|
|
178
|
+
clearCancelHandle(runId: string): void;
|
|
179
|
+
/**
|
|
180
|
+
* Settle a run exactly once (D1/D7 order: settle → record usage/archive → enqueue wake).
|
|
181
|
+
* `announce: false` is the inline-return path (D2): the model already has the result in this
|
|
182
|
+
* same tool call, so `wakeEnqueued` is set without ever dispatching — waking the channel for a
|
|
183
|
+
* result it is already holding would burn a turn to say nothing.
|
|
184
|
+
*/
|
|
185
|
+
settle(runId: string, input: SettleInput, options: {
|
|
186
|
+
announce: boolean;
|
|
187
|
+
}): Promise<void>;
|
|
188
|
+
/**
|
|
189
|
+
* Dispatch the completion wake. Durable-dispatch persists its own pending record before this
|
|
190
|
+
* call can be interrupted (`DurableDispatchService.dispatch`), and `dispatch()` is idempotent on
|
|
191
|
+
* `dispatchId`, so calling it again after a crash between here and marking `wakeEnqueued` is
|
|
192
|
+
* harmless — this is the same fix as job-manager's `announce()` reordering (D7).
|
|
193
|
+
*/
|
|
194
|
+
private announce;
|
|
195
|
+
/** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
|
|
196
|
+
cancel(runId: string): Promise<RunStatus | "not_found">;
|
|
197
|
+
/**
|
|
198
|
+
* Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
|
|
199
|
+
* construction (D10.3): the worker lived in the process that just disappeared, so any record
|
|
200
|
+
* still `running` is settled as `lost` and the channel is woken to say so. External runs are
|
|
201
|
+
* left alone here — the harness-specific probe (spec 040 phase 2/3) reconciles those.
|
|
202
|
+
*/
|
|
203
|
+
restore(): Promise<number>;
|
|
204
|
+
/**
|
|
205
|
+
* Restart reconciliation for an external run still marked `running` (D10.3). Unlike internal
|
|
206
|
+
* runs, a `detached` external process outlives the daemon, so the first move is a liveness
|
|
207
|
+
* probe, not an automatic `lost`:
|
|
208
|
+
*
|
|
209
|
+
* - no `pid` at all: the intent was persisted but spawn was never confirmed — cannot prove it
|
|
210
|
+
* ever started, so it is judged `lost` the same as an internal run (D1).
|
|
211
|
+
* - `pid` alive: genuinely still running. Left alone; it will settle itself when it exits.
|
|
212
|
+
* - `pid` gone: the process finished or died while the daemon was down. `events.jsonl` is the
|
|
213
|
+
* only remaining evidence, so it drives the terminal judgement via the same D4 status table
|
|
214
|
+
* the live post-exit path uses.
|
|
215
|
+
*/
|
|
216
|
+
private reconcileExternalRun;
|
|
217
|
+
/** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
|
|
218
|
+
private collectGarbageIfExpired;
|
|
219
|
+
}
|
|
220
|
+
/** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
|
|
221
|
+
export declare function configureSubAgentRuntime(config: RunManagerOptions): void;
|
|
222
|
+
export declare function getSubAgentRunManager(channelId: string): SubAgentRunManager;
|
|
223
|
+
/** Read-only view for `/tasks doctor`, mirroring `channelJobTaskIds`. */
|
|
224
|
+
export declare function channelDelegationTaskIds(channelId: string): Set<string>;
|
|
225
|
+
/**
|
|
226
|
+
* Re-adopt every channel's persisted runs at startup, settling any internal run still marked
|
|
227
|
+
* `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
|
|
228
|
+
* like `restoreChannelJobs`.
|
|
229
|
+
*/
|
|
230
|
+
export declare function restoreAllSubAgentRuns(): Promise<number>;
|