@oyasmi/pipiclaw 0.9.0-beta.1 → 0.9.0-beta.3
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 +9 -0
- package/dist/agent/channel-runner.js +58 -4
- package/dist/agent/commands.js +11 -3
- package/dist/agent/job-manager.d.ts +6 -0
- package/dist/agent/job-manager.js +55 -1
- package/dist/agent/progress-formatter.js +3 -3
- package/dist/agent/run-queue.d.ts +10 -1
- package/dist/agent/run-queue.js +19 -2
- package/dist/agent/session-resource-gate.d.ts +17 -0
- package/dist/agent/session-resource-gate.js +33 -2
- package/dist/agent/status-render.js +1 -3
- package/dist/agent/types.d.ts +8 -0
- package/dist/runtime/bootstrap.d.ts +52 -0
- package/dist/runtime/bootstrap.js +192 -25
- package/dist/runtime/delivery.js +5 -5
- package/dist/runtime/dingtalk.d.ts +8 -0
- package/dist/runtime/durable-dispatch.d.ts +4 -0
- package/dist/runtime/durable-dispatch.js +16 -0
- package/dist/runtime/subagent-commands.d.ts +8 -6
- package/dist/runtime/subagent-commands.js +264 -64
- package/dist/security/logger.js +7 -0
- package/dist/shared/host-process.d.ts +7 -1
- package/dist/shared/host-process.js +7 -3
- package/dist/shared/jsonl-appender.d.ts +2 -0
- package/dist/shared/jsonl-appender.js +25 -13
- package/dist/shared/with-timeout.d.ts +14 -0
- package/dist/shared/with-timeout.js +38 -0
- package/dist/subagents/detached-discovery.d.ts +13 -0
- package/dist/subagents/detached-discovery.js +17 -0
- package/dist/subagents/external/run.d.ts +10 -0
- package/dist/subagents/external/run.js +47 -1
- package/dist/subagents/format.d.ts +12 -0
- package/dist/subagents/format.js +24 -0
- package/dist/subagents/runs.d.ts +38 -0
- package/dist/subagents/runs.js +171 -24
- package/dist/subagents/tool.d.ts +18 -0
- package/dist/subagents/tool.js +147 -89
- 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/tools/index.js +2 -0
- package/dist/tools/subagent-manage.d.ts +5 -0
- package/dist/tools/subagent-manage.js +68 -51
- package/dist/usage/ledger.d.ts +7 -0
- package/dist/usage/ledger.js +15 -2
- package/dist/usage/render.js +22 -0
- package/examples/sub-agents/README.md +12 -7
- package/examples/sub-agents/documenter.md +3 -3
- package/examples/sub-agents/git-committer.md +1 -1
- package/examples/sub-agents/reviewer.md +12 -6
- package/examples/sub-agents/verifier.md +5 -2
- package/examples/sub-agents/worker.md +1 -1
- package/package.json +1 -1
|
@@ -4,6 +4,7 @@ import { createWriteStream } from "node:fs";
|
|
|
4
4
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import * as log from "../../log.js";
|
|
7
|
+
import { logSecurityEvent } from "../../security/logger.js";
|
|
7
8
|
import { killProcessGroup } from "../../shared/host-process.js";
|
|
8
9
|
import { formatLocalTime } from "../../shared/local-time.js";
|
|
9
10
|
import { splitShellWords } from "../../shared/shell-words.js";
|
|
@@ -54,6 +55,22 @@ export async function launchExternalRun(input) {
|
|
|
54
55
|
systemPromptFile,
|
|
55
56
|
resumeSessionId: input.resumeSessionId,
|
|
56
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
|
+
});
|
|
57
74
|
const runManager = getSubAgentRunManager(input.channelId);
|
|
58
75
|
await runManager.register({
|
|
59
76
|
runId: input.runId,
|
|
@@ -71,6 +88,14 @@ export async function launchExternalRun(input) {
|
|
|
71
88
|
artifactDir: input.artifactDir,
|
|
72
89
|
leaseKey: input.leaseKey,
|
|
73
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
|
+
}
|
|
74
99
|
const eventsPath = join(input.artifactDir, "events.jsonl");
|
|
75
100
|
const stderrPath = join(input.artifactDir, "stderr.log");
|
|
76
101
|
const eventsStream = createWriteStream(eventsPath);
|
|
@@ -108,11 +133,18 @@ export async function launchExternalRun(input) {
|
|
|
108
133
|
return;
|
|
109
134
|
}
|
|
110
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
|
+
}
|
|
111
143
|
const fingerprint = randomBytes(6).toString("hex");
|
|
112
144
|
await runManager.setLaunched(input.runId, {
|
|
113
145
|
pid,
|
|
114
146
|
fingerprint,
|
|
115
|
-
argv:
|
|
147
|
+
argv: spawnedArgv,
|
|
116
148
|
sessionId: invocation.presetSessionId,
|
|
117
149
|
});
|
|
118
150
|
child.stdout?.on("data", (chunk) => eventsStream.write(chunk));
|
|
@@ -121,7 +153,9 @@ export async function launchExternalRun(input) {
|
|
|
121
153
|
child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
|
|
122
154
|
child.stdin.end(stdinContent);
|
|
123
155
|
}
|
|
156
|
+
let cancelled = false;
|
|
124
157
|
runManager.registerCancelHandle(input.runId, () => {
|
|
158
|
+
cancelled = true;
|
|
125
159
|
void killProcessGroup(pid);
|
|
126
160
|
});
|
|
127
161
|
const wallClockTimer = setTimeout(() => {
|
|
@@ -135,8 +169,20 @@ export async function launchExternalRun(input) {
|
|
|
135
169
|
}).then(async (exitCode) => {
|
|
136
170
|
clearTimeout(wallClockTimer);
|
|
137
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);
|
|
138
176
|
await new Promise((resolve) => eventsStream.end(resolve));
|
|
139
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
|
+
}
|
|
140
186
|
const eventsText = await readFile(eventsPath, "utf-8").catch(() => "");
|
|
141
187
|
const stderrTail = (await readFile(stderrPath, "utf-8").catch(() => "")).slice(-WAKE_OUTPUT_TAIL_CHARS);
|
|
142
188
|
const outcome = harness.parseOutcome({ eventsText, exitCode, stderrTail });
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RunRecord } from "./runs.js";
|
|
2
|
+
/**
|
|
3
|
+
* Shared display primitives for delegation runs (spec 041), used by both the model-facing
|
|
4
|
+
* `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
|
|
5
|
+
* are genuinely language/audience-neutral live here — duration math, the harness label, and the
|
|
6
|
+
* cost guard — not full line templates, since the two surfaces render in different languages.
|
|
7
|
+
*/
|
|
8
|
+
export declare function formatDuration(ms: number): string;
|
|
9
|
+
export declare function elapsedMs(record: RunRecord, now?: number): number;
|
|
10
|
+
export declare function harnessLabel(record: RunRecord): string;
|
|
11
|
+
/** `undefined` when cost genuinely is not known (e.g. `codex-cli`, `exec`) — never displayed as $0. */
|
|
12
|
+
export declare function formatCost(record: RunRecord): string | undefined;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared display primitives for delegation runs (spec 041), used by both the model-facing
|
|
3
|
+
* `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
|
|
4
|
+
* are genuinely language/audience-neutral live here — duration math, the harness label, and the
|
|
5
|
+
* cost guard — not full line templates, since the two surfaces render in different languages.
|
|
6
|
+
*/
|
|
7
|
+
export function formatDuration(ms) {
|
|
8
|
+
const seconds = Math.round(ms / 1000);
|
|
9
|
+
if (seconds < 60)
|
|
10
|
+
return `${seconds}s`;
|
|
11
|
+
return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
|
|
12
|
+
}
|
|
13
|
+
export function elapsedMs(record, now = Date.now()) {
|
|
14
|
+
return (record.finishedAt ?? now) - record.startedAt;
|
|
15
|
+
}
|
|
16
|
+
export function harnessLabel(record) {
|
|
17
|
+
return record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
|
|
18
|
+
}
|
|
19
|
+
/** `undefined` when cost genuinely is not known (e.g. `codex-cli`, `exec`) — never displayed as $0. */
|
|
20
|
+
export function formatCost(record) {
|
|
21
|
+
if (!record.costKnown)
|
|
22
|
+
return undefined;
|
|
23
|
+
return `$${record.usage.cost.total.toFixed(2)}`;
|
|
24
|
+
}
|
package/dist/subagents/runs.d.ts
CHANGED
|
@@ -29,6 +29,23 @@ export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 5;
|
|
|
29
29
|
/** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
|
|
30
30
|
* not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
|
|
31
31
|
export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
|
|
32
|
+
/**
|
|
33
|
+
* Human-typeable run ids (spec 041). Runs used to be identified by the dispatching tool call's
|
|
34
|
+
* own id, which on some providers is a `call_<24 chars>|fc_<50 chars>` composite — useless in a
|
|
35
|
+
* chat UI where a human has to read it back to cancel or inspect a run. `mintRunId()` on
|
|
36
|
+
* `SubAgentRunManager` produces `run_` + 6 chars instead; the alphabet excludes 0/1/i/l/o/u
|
|
37
|
+
* because those are the characters people misread on a phone screen or misspeak out loud.
|
|
38
|
+
*/
|
|
39
|
+
export declare const RUN_ID_PREFIX = "run_";
|
|
40
|
+
export type RunResolution = {
|
|
41
|
+
kind: "found";
|
|
42
|
+
record: RunRecord;
|
|
43
|
+
} | {
|
|
44
|
+
kind: "ambiguous";
|
|
45
|
+
candidates: RunRecord[];
|
|
46
|
+
} | {
|
|
47
|
+
kind: "not_found";
|
|
48
|
+
};
|
|
32
49
|
export interface RunUsage {
|
|
33
50
|
usage: UsageTotals;
|
|
34
51
|
/** False only for harnesses that cannot report tokens at all (`exec`). */
|
|
@@ -66,6 +83,9 @@ export interface RunRecord extends RunUsage {
|
|
|
66
83
|
usageRecorded?: boolean;
|
|
67
84
|
/** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
|
|
68
85
|
wakeEnqueued?: boolean;
|
|
86
|
+
/** Durable one-time relationship between the internally produced wake and task activation (T9). */
|
|
87
|
+
wakeClaimDispatchId?: string;
|
|
88
|
+
wakeConsumedAt?: number;
|
|
69
89
|
pid?: number;
|
|
70
90
|
fingerprint?: string;
|
|
71
91
|
argv?: string[];
|
|
@@ -127,6 +147,9 @@ export declare class SubAgentRunManager {
|
|
|
127
147
|
* kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
|
|
128
148
|
* the only thing that could reach an in-process worker anyway (D10.3). */
|
|
129
149
|
private readonly cancelHandles;
|
|
150
|
+
/** External launch intents exist before a safe live child handle does. A cancel in that window
|
|
151
|
+
* is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
|
|
152
|
+
private readonly externalLaunches;
|
|
130
153
|
private readonly queue;
|
|
131
154
|
constructor(channelId: string, options: RunManagerOptions);
|
|
132
155
|
private recordPath;
|
|
@@ -145,8 +168,19 @@ export declare class SubAgentRunManager {
|
|
|
145
168
|
/** Task ids a still-running delegation on this channel will eventually wake. Feeds `/tasks doctor`. */
|
|
146
169
|
runningTaskIds(): Set<string>;
|
|
147
170
|
runningCount(): number;
|
|
171
|
+
/** Mint a short, human-typeable run id (spec 041). Retried against currently known records;
|
|
172
|
+
* the id space (30^6 ≈ 7.3e8) makes a real collision astronomically unlikely, so this is a
|
|
173
|
+
* defensive check, not a real bottleneck. */
|
|
174
|
+
mintRunId(): string;
|
|
175
|
+
/** Resolve a user- or model-supplied id, exact or by unambiguous prefix (spec 041): `show
|
|
176
|
+
* a1b2c3` and `show run_a1b2c3` both work without retyping the full id. */
|
|
177
|
+
resolveRef(query: string): RunResolution;
|
|
148
178
|
/** Register the run's lifecycle before any work starts, and persist it immediately (D1). */
|
|
149
179
|
register(input: RegisterRunInput): Promise<RunRecord>;
|
|
180
|
+
/** Atomically crosses the external launch cancel window. The supplied live-handle callback is
|
|
181
|
+
* installed before this method resolves; a cancel queued during register is observed first and
|
|
182
|
+
* makes this return false, so the caller must not spawn. */
|
|
183
|
+
claimExternalLaunch(runId: string, cancel: () => void): Promise<boolean>;
|
|
150
184
|
/**
|
|
151
185
|
* Persist the pid once a spawn actually succeeds — the second half of D1's launch ordering.
|
|
152
186
|
* `register()` already durably recorded the intent (argv, working directory, artifact dir)
|
|
@@ -159,6 +193,10 @@ export declare class SubAgentRunManager {
|
|
|
159
193
|
argv: string[];
|
|
160
194
|
sessionId?: string;
|
|
161
195
|
}): Promise<void>;
|
|
196
|
+
/** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
|
|
197
|
+
* interrupted activation, while copied text or a different dispatch id can never claim it. */
|
|
198
|
+
beginWakeConsumption(runId: string, taskId: string, dispatchId: string): Promise<boolean>;
|
|
199
|
+
finishWakeConsumption(runId: string, dispatchId: string): Promise<void>;
|
|
162
200
|
/** Let a caller (subagent tool) register a way to abort this run's in-process worker. */
|
|
163
201
|
registerCancelHandle(runId: string, cancel: () => void): void;
|
|
164
202
|
clearCancelHandle(runId: string): void;
|
package/dist/subagents/runs.js
CHANGED
|
@@ -20,6 +20,33 @@ export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 5;
|
|
|
20
20
|
/** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
|
|
21
21
|
* not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
|
|
22
22
|
export const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
|
|
23
|
+
/**
|
|
24
|
+
* Human-typeable run ids (spec 041). Runs used to be identified by the dispatching tool call's
|
|
25
|
+
* own id, which on some providers is a `call_<24 chars>|fc_<50 chars>` composite — useless in a
|
|
26
|
+
* chat UI where a human has to read it back to cancel or inspect a run. `mintRunId()` on
|
|
27
|
+
* `SubAgentRunManager` produces `run_` + 6 chars instead; the alphabet excludes 0/1/i/l/o/u
|
|
28
|
+
* because those are the characters people misread on a phone screen or misspeak out loud.
|
|
29
|
+
*/
|
|
30
|
+
export const RUN_ID_PREFIX = "run_";
|
|
31
|
+
const RUN_ID_ALPHABET = "23456789abcdefghjkmnpqrstvwxyz";
|
|
32
|
+
const RUN_ID_SUFFIX_LEN = 6;
|
|
33
|
+
function randomRunIdSuffix() {
|
|
34
|
+
let suffix = "";
|
|
35
|
+
for (let i = 0; i < RUN_ID_SUFFIX_LEN; i++) {
|
|
36
|
+
suffix += RUN_ID_ALPHABET[Math.floor(Math.random() * RUN_ID_ALPHABET.length)];
|
|
37
|
+
}
|
|
38
|
+
return suffix;
|
|
39
|
+
}
|
|
40
|
+
/** Strips a leading `run_` (case-insensitive) so `show a1b2c3` and `show run_a1b2c3` resolve
|
|
41
|
+
* the same way — nobody should have to remember whether the prefix is required. */
|
|
42
|
+
function normalizeRunIdQuery(query) {
|
|
43
|
+
const lower = query.trim().toLowerCase();
|
|
44
|
+
return lower.startsWith(RUN_ID_PREFIX) ? lower.slice(RUN_ID_PREFIX.length) : lower;
|
|
45
|
+
}
|
|
46
|
+
/** Registration is serialized across channel managers so the host-wide count and insertion are
|
|
47
|
+
* one admission transaction. The per-run manager queue alone cannot protect the 19 -> 20 edge
|
|
48
|
+
* when two different channels register concurrently. */
|
|
49
|
+
const hostAdmissionQueue = createSerialQueue();
|
|
23
50
|
/** Bytes of the reply text carried inline in the completion wake, matching job-manager's tail budget. */
|
|
24
51
|
const WAKE_OUTPUT_TAIL_CHARS = 2_000;
|
|
25
52
|
function isTerminal(status) {
|
|
@@ -61,12 +88,15 @@ export class SubAgentRunManager {
|
|
|
61
88
|
* kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
|
|
62
89
|
* the only thing that could reach an in-process worker anyway (D10.3). */
|
|
63
90
|
this.cancelHandles = new Map();
|
|
91
|
+
/** External launch intents exist before a safe live child handle does. A cancel in that window
|
|
92
|
+
* is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
|
|
93
|
+
this.externalLaunches = new Map();
|
|
64
94
|
this.queue = createSerialQueue();
|
|
65
95
|
}
|
|
66
96
|
recordPath(runId) {
|
|
67
97
|
return this.options.stateDir ? join(this.options.stateDir, this.channelId, `${runId}.json`) : undefined;
|
|
68
98
|
}
|
|
69
|
-
async persist(record) {
|
|
99
|
+
async persist(record, required = false) {
|
|
70
100
|
const path = this.recordPath(record.runId);
|
|
71
101
|
if (!path)
|
|
72
102
|
return;
|
|
@@ -74,6 +104,8 @@ export class SubAgentRunManager {
|
|
|
74
104
|
await writeFileAtomically(path, `${JSON.stringify(record)}\n`);
|
|
75
105
|
}
|
|
76
106
|
catch (error) {
|
|
107
|
+
if (required)
|
|
108
|
+
throw error;
|
|
77
109
|
log.logWarning(`Failed to persist sub-agent run ${record.runId}`, errorMessage(error));
|
|
78
110
|
}
|
|
79
111
|
}
|
|
@@ -99,6 +131,7 @@ export class SubAgentRunManager {
|
|
|
99
131
|
async forget(record) {
|
|
100
132
|
this.runs.delete(record.runId);
|
|
101
133
|
this.cancelHandles.delete(record.runId);
|
|
134
|
+
this.externalLaunches.delete(record.runId);
|
|
102
135
|
const path = this.recordPath(record.runId);
|
|
103
136
|
if (path)
|
|
104
137
|
await unlink(path).catch(() => undefined);
|
|
@@ -122,30 +155,88 @@ export class SubAgentRunManager {
|
|
|
122
155
|
runningCount() {
|
|
123
156
|
return Array.from(this.runs.values()).filter((record) => record.status === "running").length;
|
|
124
157
|
}
|
|
158
|
+
/** Mint a short, human-typeable run id (spec 041). Retried against currently known records;
|
|
159
|
+
* the id space (30^6 ≈ 7.3e8) makes a real collision astronomically unlikely, so this is a
|
|
160
|
+
* defensive check, not a real bottleneck. */
|
|
161
|
+
mintRunId() {
|
|
162
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
163
|
+
const id = `${RUN_ID_PREFIX}${randomRunIdSuffix()}`;
|
|
164
|
+
if (!this.runs.has(id))
|
|
165
|
+
return id;
|
|
166
|
+
}
|
|
167
|
+
throw new Error("Could not mint a unique delegation run id.");
|
|
168
|
+
}
|
|
169
|
+
/** Resolve a user- or model-supplied id, exact or by unambiguous prefix (spec 041): `show
|
|
170
|
+
* a1b2c3` and `show run_a1b2c3` both work without retyping the full id. */
|
|
171
|
+
resolveRef(query) {
|
|
172
|
+
const trimmed = query.trim();
|
|
173
|
+
const exact = this.runs.get(trimmed);
|
|
174
|
+
if (exact)
|
|
175
|
+
return { kind: "found", record: exact };
|
|
176
|
+
const needle = normalizeRunIdQuery(trimmed);
|
|
177
|
+
if (!needle)
|
|
178
|
+
return { kind: "not_found" };
|
|
179
|
+
const candidates = Array.from(this.runs.values()).filter((record) => normalizeRunIdQuery(record.runId).startsWith(needle));
|
|
180
|
+
if (candidates.length === 1)
|
|
181
|
+
return { kind: "found", record: candidates[0] };
|
|
182
|
+
if (candidates.length > 1)
|
|
183
|
+
return { kind: "ambiguous", candidates };
|
|
184
|
+
return { kind: "not_found" };
|
|
185
|
+
}
|
|
125
186
|
/** Register the run's lifecycle before any work starts, and persist it immediately (D1). */
|
|
126
187
|
async register(input) {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
188
|
+
return hostAdmissionQueue.run("host", () => this.queue.run(input.runId, async () => {
|
|
189
|
+
// D10.2: a per-channel and a host-wide cap, both code constants (a local response to a
|
|
190
|
+
// runaway model, not a global cross-subsystem admission scheme — see the design doc's
|
|
191
|
+
// non-goals). Checked before anything is persisted, so a rejected run costs nothing.
|
|
192
|
+
if (this.runningCount() >= MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL) {
|
|
193
|
+
throw new Error(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
|
|
194
|
+
"Wait for one to finish, or cancel one with subagent_manage first.");
|
|
195
|
+
}
|
|
196
|
+
if (totalRunningSubAgentRuns() >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
|
|
197
|
+
throw new Error(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
|
|
198
|
+
"Wait for one to finish before dispatching another.");
|
|
199
|
+
}
|
|
200
|
+
if (this.runs.has(input.runId)) {
|
|
201
|
+
throw new Error(`Run id "${input.runId}" is already registered on this channel.`);
|
|
202
|
+
}
|
|
203
|
+
const record = {
|
|
204
|
+
...input,
|
|
205
|
+
status: "running",
|
|
206
|
+
startedAt: Date.now(),
|
|
207
|
+
usage: emptyUsage(),
|
|
208
|
+
usageKnown: true,
|
|
209
|
+
costKnown: true,
|
|
210
|
+
};
|
|
211
|
+
this.runs.set(record.runId, record);
|
|
212
|
+
if (record.runtime === "external")
|
|
213
|
+
this.externalLaunches.set(record.runId, { cancelRequested: false });
|
|
214
|
+
try {
|
|
215
|
+
await this.persist(record, true);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
this.runs.delete(record.runId);
|
|
219
|
+
this.externalLaunches.delete(record.runId);
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
return record;
|
|
223
|
+
}));
|
|
224
|
+
}
|
|
225
|
+
/** Atomically crosses the external launch cancel window. The supplied live-handle callback is
|
|
226
|
+
* installed before this method resolves; a cancel queued during register is observed first and
|
|
227
|
+
* makes this return false, so the caller must not spawn. */
|
|
228
|
+
async claimExternalLaunch(runId, cancel) {
|
|
229
|
+
return this.queue.run(runId, async () => {
|
|
230
|
+
const record = this.runs.get(runId);
|
|
231
|
+
const launch = this.externalLaunches.get(runId);
|
|
232
|
+
if (!record || record.status !== "running" || !launch || launch.cancelRequested) {
|
|
233
|
+
this.externalLaunches.delete(runId);
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
this.cancelHandles.set(runId, cancel);
|
|
237
|
+
this.externalLaunches.delete(runId);
|
|
238
|
+
return true;
|
|
239
|
+
});
|
|
149
240
|
}
|
|
150
241
|
/**
|
|
151
242
|
* Persist the pid once a spawn actually succeeds — the second half of D1's launch ordering.
|
|
@@ -164,7 +255,47 @@ export class SubAgentRunManager {
|
|
|
164
255
|
// at settle(), means a run that crashes before any output is still resumable.
|
|
165
256
|
if (info.sessionId)
|
|
166
257
|
record.sessionId = info.sessionId;
|
|
167
|
-
await this.persist(record);
|
|
258
|
+
await this.persist(record, true);
|
|
259
|
+
}
|
|
260
|
+
/** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
|
|
261
|
+
* interrupted activation, while copied text or a different dispatch id can never claim it. */
|
|
262
|
+
async beginWakeConsumption(runId, taskId, dispatchId) {
|
|
263
|
+
return this.queue.run(runId, async () => {
|
|
264
|
+
const record = this.runs.get(runId);
|
|
265
|
+
const expected = `subagent:${record?.channelId}:${runId}:done`;
|
|
266
|
+
if (!record?.settledAt ||
|
|
267
|
+
record.taskId !== taskId ||
|
|
268
|
+
dispatchId !== expected ||
|
|
269
|
+
record.wakeConsumedAt ||
|
|
270
|
+
(record.wakeClaimDispatchId && record.wakeClaimDispatchId !== dispatchId)) {
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
const previousClaim = record.wakeClaimDispatchId;
|
|
274
|
+
record.wakeClaimDispatchId = dispatchId;
|
|
275
|
+
try {
|
|
276
|
+
await this.persist(record, true);
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
record.wakeClaimDispatchId = previousClaim;
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
return true;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
async finishWakeConsumption(runId, dispatchId) {
|
|
286
|
+
await this.queue.run(runId, async () => {
|
|
287
|
+
const record = this.runs.get(runId);
|
|
288
|
+
if (!record || record.wakeClaimDispatchId !== dispatchId || record.wakeConsumedAt)
|
|
289
|
+
return;
|
|
290
|
+
record.wakeConsumedAt = Date.now();
|
|
291
|
+
try {
|
|
292
|
+
await this.persist(record, true);
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
record.wakeConsumedAt = undefined;
|
|
296
|
+
throw error;
|
|
297
|
+
}
|
|
298
|
+
});
|
|
168
299
|
}
|
|
169
300
|
/** Let a caller (subagent tool) register a way to abort this run's in-process worker. */
|
|
170
301
|
registerCancelHandle(runId, cancel) {
|
|
@@ -202,6 +333,7 @@ export class SubAgentRunManager {
|
|
|
202
333
|
releaseWorkspaceLease(record.leaseKey);
|
|
203
334
|
await this.persist(record);
|
|
204
335
|
this.cancelHandles.delete(runId);
|
|
336
|
+
this.externalLaunches.delete(runId);
|
|
205
337
|
if (!record.usageRecorded) {
|
|
206
338
|
record.usageRecorded = true;
|
|
207
339
|
this.options.ledger?.record({
|
|
@@ -290,6 +422,16 @@ export class SubAgentRunManager {
|
|
|
290
422
|
conversationId: "",
|
|
291
423
|
conversationType: record.channelId.startsWith("group_") ? "2" : "1",
|
|
292
424
|
dispatchId: `subagent:${record.channelId}:${record.runId}:done`,
|
|
425
|
+
...(record.taskId
|
|
426
|
+
? {
|
|
427
|
+
internalWake: {
|
|
428
|
+
kind: "subagent",
|
|
429
|
+
resourceId: record.runId,
|
|
430
|
+
taskId: record.taskId,
|
|
431
|
+
dispatchId: `subagent:${record.channelId}:${record.runId}:done`,
|
|
432
|
+
},
|
|
433
|
+
}
|
|
434
|
+
: {}),
|
|
293
435
|
};
|
|
294
436
|
try {
|
|
295
437
|
await this.options.dispatch(event);
|
|
@@ -314,6 +456,11 @@ export class SubAgentRunManager {
|
|
|
314
456
|
if (cancelHandle) {
|
|
315
457
|
cancelHandle();
|
|
316
458
|
}
|
|
459
|
+
else if (record.runtime === "external" && this.externalLaunches.has(runId)) {
|
|
460
|
+
// The process has not spawned yet; claimExternalLaunch() will observe this request
|
|
461
|
+
// and refuse to spawn instead of starting an uncancellable child.
|
|
462
|
+
this.externalLaunches.get(runId).cancelRequested = true;
|
|
463
|
+
}
|
|
317
464
|
else {
|
|
318
465
|
// No in-process handle (external runtime, not yet wired, or a run this process did
|
|
319
466
|
// not launch): mark it lost rather than pretend a cancel we could not perform happened.
|
package/dist/subagents/tool.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ import type { PipiclawMemoryRecallSettings } from "../settings.js";
|
|
|
8
8
|
import type { UsageTotals } from "../shared/types.js";
|
|
9
9
|
import type { PipiclawWebToolsConfig } from "../tools/config.js";
|
|
10
10
|
import { type ResolvedSubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
|
|
11
|
+
import { getSubAgentRunManager } from "./runs.js";
|
|
11
12
|
declare const subagentSchema: Type.TObject<{
|
|
12
13
|
label: Type.TString;
|
|
13
14
|
agent: Type.TOptional<Type.TString>;
|
|
@@ -80,10 +81,14 @@ export interface SubAgentToolOptions {
|
|
|
80
81
|
apiKey: string;
|
|
81
82
|
tools: AgentTool<any>[];
|
|
82
83
|
}) => SubAgentWorker;
|
|
84
|
+
/** Test seam for failures while constructing the scoped tool set after durable registration. */
|
|
85
|
+
buildTools?: typeof buildSubagentTools;
|
|
83
86
|
/** Test-only override for the D6 convergence-turn wall clock; defaults to CONVERGENCE_WALL_CLOCK_MS. */
|
|
84
87
|
convergenceWallClockMs?: number;
|
|
85
88
|
/** Test-only override for the D2 sync grace window; defaults to SYNC_GRACE_MS. */
|
|
86
89
|
syncGraceMs?: number;
|
|
90
|
+
/** Test seam for setup/admission failures. Production uses the process-wide channel manager. */
|
|
91
|
+
getRunManager?: typeof getSubAgentRunManager;
|
|
87
92
|
}
|
|
88
93
|
interface SubAgentWorker {
|
|
89
94
|
state: {
|
|
@@ -102,5 +107,18 @@ interface SubAgentWorker {
|
|
|
102
107
|
* only caps what gets echoed into the parent's context.
|
|
103
108
|
*/
|
|
104
109
|
export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
|
|
110
|
+
interface SubAgentRunContext {
|
|
111
|
+
runId: string;
|
|
112
|
+
purpose: "work" | "verify";
|
|
113
|
+
taskId?: string;
|
|
114
|
+
workingDirectory: string;
|
|
115
|
+
artifactDir: string;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
|
|
119
|
+
* available to sub-agents (files + web). Sub-agents run with their own security context
|
|
120
|
+
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
121
|
+
*/
|
|
122
|
+
declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
|
|
105
123
|
export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolDetails>;
|
|
106
124
|
export {};
|