@oyasmi/pipiclaw 0.9.0-beta.5 → 0.9.0-beta.6
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 +146 -177
- package/dist/playbooks/agent-delegation.md +9 -8
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/catalog.d.ts +2 -2
- package/dist/playbooks/catalog.js +20 -9
- package/dist/playbooks/event-scheduling.md +1 -1
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/outbound-media.md +5 -5
- package/dist/playbooks/runtime-orientation.md +1 -1
- package/dist/playbooks/task-driving.md +1 -1
- package/dist/playbooks/task-planning.md +1 -1
- package/dist/runtime/bootstrap.d.ts +2 -2
- package/dist/runtime/bootstrap.js +8 -4
- package/dist/shared/host-process.d.ts +5 -5
- package/dist/shared/host-process.js +19 -0
- package/dist/subagents/discovery.d.ts +8 -0
- package/dist/subagents/discovery.js +32 -9
- package/dist/subagents/external/claude-code.js +1 -3
- package/dist/subagents/external/codex-cli.js +1 -7
- package/dist/subagents/external/exec.js +7 -2
- package/dist/subagents/external/harness.d.ts +0 -3
- package/dist/subagents/external/run.d.ts +5 -0
- package/dist/subagents/external/run.js +67 -31
- package/dist/subagents/runs.d.ts +40 -9
- package/dist/subagents/runs.js +187 -21
- package/dist/subagents/tool.d.ts +3 -1
- package/dist/subagents/tool.js +33 -14
- package/dist/tools/subagent-manage.js +18 -1
- package/examples/sub-agents/README.md +10 -2
- package/examples/sub-agents/documenter.md +0 -2
- package/examples/sub-agents/git-committer.md +1 -0
- package/examples/sub-agents/reviewer.md +0 -2
- package/examples/sub-agents/scout.md +0 -2
- package/examples/sub-agents/verifier.md +0 -2
- package/examples/sub-agents/worker.md +0 -2
- package/package.json +1 -1
|
@@ -150,9 +150,9 @@ interface RuntimeContextOptions {
|
|
|
150
150
|
/** Override the `/stop` watchdog's grace window (tests use a short one). */
|
|
151
151
|
stopForceEndGraceMs?: number;
|
|
152
152
|
}
|
|
153
|
-
export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
|
|
153
|
+
export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
|
|
154
154
|
bot: DingTalkBot;
|
|
155
|
-
}
|
|
155
|
+
}>;
|
|
156
156
|
/**
|
|
157
157
|
* Transport-neutral app services shared by the DingTalk runtime and the terminal
|
|
158
158
|
* TUI: loads settings (surfacing load errors) and reports tool/security config
|
|
@@ -19,7 +19,7 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
|
19
19
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
20
20
|
import { errorMessage } from "../shared/text-utils.js";
|
|
21
21
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
22
|
-
import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, } from "../subagents/runs.js";
|
|
22
|
+
import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentSweeper, } from "../subagents/runs.js";
|
|
23
23
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
24
24
|
import { activateWaitingTaskAndClaimAttempt, finishTaskAttempt, finishWakeTaskActivation, rollbackWakeTaskActivation, } from "../tasks/store.js";
|
|
25
25
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
@@ -499,7 +499,7 @@ export async function forceEndStuckTurnAfterStop(input) {
|
|
|
499
499
|
.catch(() => undefined);
|
|
500
500
|
return true;
|
|
501
501
|
}
|
|
502
|
-
export function createRuntimeContext(options) {
|
|
502
|
+
export async function createRuntimeContext(options) {
|
|
503
503
|
const startServices = options.startServices ?? true;
|
|
504
504
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
505
505
|
const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
|
|
@@ -952,7 +952,10 @@ export function createRuntimeContext(options) {
|
|
|
952
952
|
ledger: getUsageLedger(),
|
|
953
953
|
store,
|
|
954
954
|
});
|
|
955
|
-
|
|
955
|
+
// Admission (bot.start() below) must not open until every persisted run is back in memory
|
|
956
|
+
// (P0-1): a message arriving mid-restore would see partial running-count/short-id/lease state,
|
|
957
|
+
// and durableDispatch's redelivery of a pending completion wake would find no record to claim.
|
|
958
|
+
await restoreAllSubAgentRuns();
|
|
956
959
|
const eventsWatcher = options.createEventsWatcher
|
|
957
960
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
958
961
|
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
|
|
@@ -1028,6 +1031,7 @@ export function createRuntimeContext(options) {
|
|
|
1028
1031
|
durableDispatch?.stop();
|
|
1029
1032
|
memoryMaintenanceScheduler.stop();
|
|
1030
1033
|
eventsWatcher.stop();
|
|
1034
|
+
stopSubAgentSweeper();
|
|
1031
1035
|
await bot.stop();
|
|
1032
1036
|
const runningTasks = Array.from(activeTasks);
|
|
1033
1037
|
if (runningTasks.length > 0) {
|
|
@@ -1171,7 +1175,7 @@ export async function bootstrap(argv, options = {}) {
|
|
|
1171
1175
|
dingtalkConfig.stateDir = paths.workspaceDir;
|
|
1172
1176
|
prepareAppServices(paths);
|
|
1173
1177
|
log.logStartup(paths.workspaceDir);
|
|
1174
|
-
const runtime = createRuntimeContext({
|
|
1178
|
+
const runtime = await createRuntimeContext({
|
|
1175
1179
|
paths,
|
|
1176
1180
|
dingtalkConfig,
|
|
1177
1181
|
registerSignalHandlers,
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* children); this is for callers that spawn argv-direct, detached children of their own (D3/D4).
|
|
2
|
+
* A live pid's start time, as `ps` reports it — the only OS-verifiable way to tell a still-running
|
|
3
|
+
* process apart from an unrelated one that later reused the same pid (spec 040, D10.3). `undefined`
|
|
4
|
+
* when the pid is gone or `ps` itself is unavailable; callers must treat that as "cannot verify",
|
|
5
|
+
* never as proof either way.
|
|
7
6
|
*/
|
|
7
|
+
export declare function readProcessStartTime(pid: number): Promise<string | undefined>;
|
|
8
8
|
/** True if `pid` names a live process this user can at least see, without sending a real signal. */
|
|
9
9
|
export declare function isProcessAlive(pid: number): boolean;
|
|
10
10
|
/**
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
1
3
|
/**
|
|
2
4
|
* Stateless host-process operations shared by background jobs and external delegation runs
|
|
3
5
|
* (spec 040, D1): a liveness probe and a process-group kill. Nothing here is job- or run-specific
|
|
@@ -5,6 +7,23 @@
|
|
|
5
7
|
* machine. `job-manager.ts` still probes through its shell `Executor` (its jobs are shell
|
|
6
8
|
* children); this is for callers that spawn argv-direct, detached children of their own (D3/D4).
|
|
7
9
|
*/
|
|
10
|
+
const execFileAsync = promisify(execFile);
|
|
11
|
+
/**
|
|
12
|
+
* A live pid's start time, as `ps` reports it — the only OS-verifiable way to tell a still-running
|
|
13
|
+
* process apart from an unrelated one that later reused the same pid (spec 040, D10.3). `undefined`
|
|
14
|
+
* when the pid is gone or `ps` itself is unavailable; callers must treat that as "cannot verify",
|
|
15
|
+
* never as proof either way.
|
|
16
|
+
*/
|
|
17
|
+
export async function readProcessStartTime(pid) {
|
|
18
|
+
try {
|
|
19
|
+
const { stdout } = await execFileAsync("ps", ["-p", String(pid), "-o", "lstart="]);
|
|
20
|
+
const value = stdout.trim();
|
|
21
|
+
return value || undefined;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
8
27
|
/** True if `pid` names a live process this user can at least see, without sending a real signal. */
|
|
9
28
|
export function isProcessAlive(pid) {
|
|
10
29
|
try {
|
|
@@ -43,6 +43,14 @@ export declare const SUB_AGENT_EFFORT_PRESETS: {
|
|
|
43
43
|
readonly bashTimeoutSec: 180;
|
|
44
44
|
};
|
|
45
45
|
};
|
|
46
|
+
/**
|
|
47
|
+
* External runs have no turn/tool-call budget (D5) — `effort` only ever moves wall time, and at
|
|
48
|
+
* external scale, not the internal tuple above (P1-3: those numbers previously leaked onto
|
|
49
|
+
* external roles unchanged, where `deep` at 900s was *shorter* than the external default).
|
|
50
|
+
* `standard` and an unset `effort` both keep the role's own `maxWallTimeSec` (or the external
|
|
51
|
+
* default), so this only has entries for the two presets that actually override it.
|
|
52
|
+
*/
|
|
53
|
+
export declare const SUB_AGENT_EXTERNAL_EFFORT_WALL_TIME_SEC: Partial<Record<keyof typeof SUB_AGENT_EFFORT_PRESETS, number>>;
|
|
46
54
|
export type SubAgentEffort = keyof typeof SUB_AGENT_EFFORT_PRESETS;
|
|
47
55
|
/**
|
|
48
56
|
* The invocation-side spelling of `contextMode` + `memory`. Those two frontmatter knobs
|
|
@@ -42,6 +42,17 @@ export const SUB_AGENT_EFFORT_PRESETS = {
|
|
|
42
42
|
},
|
|
43
43
|
deep: { maxTurns: 48, maxToolCalls: 96, maxWallTimeSec: 900, bashTimeoutSec: 180 },
|
|
44
44
|
};
|
|
45
|
+
/**
|
|
46
|
+
* External runs have no turn/tool-call budget (D5) — `effort` only ever moves wall time, and at
|
|
47
|
+
* external scale, not the internal tuple above (P1-3: those numbers previously leaked onto
|
|
48
|
+
* external roles unchanged, where `deep` at 900s was *shorter* than the external default).
|
|
49
|
+
* `standard` and an unset `effort` both keep the role's own `maxWallTimeSec` (or the external
|
|
50
|
+
* default), so this only has entries for the two presets that actually override it.
|
|
51
|
+
*/
|
|
52
|
+
export const SUB_AGENT_EXTERNAL_EFFORT_WALL_TIME_SEC = {
|
|
53
|
+
quick: 600,
|
|
54
|
+
deep: 5400,
|
|
55
|
+
};
|
|
45
56
|
const ALLOWED_EFFORTS = Object.keys(SUB_AGENT_EFFORT_PRESETS);
|
|
46
57
|
/**
|
|
47
58
|
* The invocation-side spelling of `contextMode` + `memory`. Those two frontmatter knobs
|
|
@@ -618,16 +629,28 @@ subagentDefaultModelRef) {
|
|
|
618
629
|
if (effortOverride.error) {
|
|
619
630
|
return { error: effortOverride.error };
|
|
620
631
|
}
|
|
632
|
+
const effectiveRuntime = baseConfig?.runtime ?? "internal";
|
|
621
633
|
// An explicit `effort` replaces the whole budget tuple rather than merging field by
|
|
622
|
-
// field, so a preset never produces a combination no preset describes.
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
634
|
+
// field, so a preset never produces a combination no preset describes. External is a
|
|
635
|
+
// separate branch (P1-3): it has no turn/tool-call budget, and effort's wall-time numbers
|
|
636
|
+
// are at external scale, not the internal tuple.
|
|
637
|
+
const budget = effectiveRuntime === "external"
|
|
638
|
+
? {
|
|
639
|
+
maxTurns: DEFAULT_MAX_TURNS,
|
|
640
|
+
maxToolCalls: DEFAULT_MAX_TOOL_CALLS,
|
|
641
|
+
maxWallTimeSec: (effortOverride.value && SUB_AGENT_EXTERNAL_EFFORT_WALL_TIME_SEC[effortOverride.value]) ??
|
|
642
|
+
baseConfig?.maxWallTimeSec ??
|
|
643
|
+
DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC,
|
|
644
|
+
bashTimeoutSec: DEFAULT_BASH_TIMEOUT_SEC,
|
|
645
|
+
}
|
|
646
|
+
: effortOverride.value
|
|
647
|
+
? SUB_AGENT_EFFORT_PRESETS[effortOverride.value]
|
|
648
|
+
: {
|
|
649
|
+
maxTurns: baseConfig?.maxTurns ?? DEFAULT_MAX_TURNS,
|
|
650
|
+
maxToolCalls: baseConfig?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS,
|
|
651
|
+
maxWallTimeSec: baseConfig?.maxWallTimeSec ?? DEFAULT_MAX_WALL_TIME_SEC,
|
|
652
|
+
bashTimeoutSec: baseConfig?.bashTimeoutSec ?? DEFAULT_BASH_TIMEOUT_SEC,
|
|
653
|
+
};
|
|
631
654
|
const contextOverride = parseContextChoice(overrides.context);
|
|
632
655
|
if (contextOverride.error) {
|
|
633
656
|
return { error: contextOverride.error };
|
|
@@ -61,8 +61,7 @@ export const claudeCodeHarness = {
|
|
|
61
61
|
presetSessionId = randomUUID();
|
|
62
62
|
args.push("--session-id", presetSessionId);
|
|
63
63
|
}
|
|
64
|
-
|
|
65
|
-
return { executable, args, resumable: true, promptFiles, presetSessionId };
|
|
64
|
+
return { executable, args, resumable: true, presetSessionId };
|
|
66
65
|
},
|
|
67
66
|
parseOutcome(input) {
|
|
68
67
|
let finalText = "";
|
|
@@ -144,7 +143,6 @@ export const claudeCodeHarness = {
|
|
|
144
143
|
usage,
|
|
145
144
|
usageKnown,
|
|
146
145
|
costKnown,
|
|
147
|
-
outputTruncated: false,
|
|
148
146
|
stderrTail: input.stderrTail,
|
|
149
147
|
errorMessage,
|
|
150
148
|
};
|
|
@@ -53,12 +53,7 @@ export const codexCliHarness = {
|
|
|
53
53
|
const args = input.resumeSessionId
|
|
54
54
|
? [...baseArgs, "resume", input.resumeSessionId, "--json", "-"]
|
|
55
55
|
: [...baseArgs, "--json", "-"];
|
|
56
|
-
return {
|
|
57
|
-
executable,
|
|
58
|
-
args,
|
|
59
|
-
resumable: true,
|
|
60
|
-
promptFiles: used.has("$PROMPT_FILE") ? [input.promptFile] : undefined,
|
|
61
|
-
};
|
|
56
|
+
return { executable, args, resumable: true };
|
|
62
57
|
},
|
|
63
58
|
parseOutcome(input) {
|
|
64
59
|
let finalText = "";
|
|
@@ -125,7 +120,6 @@ export const codexCliHarness = {
|
|
|
125
120
|
usage,
|
|
126
121
|
usageKnown,
|
|
127
122
|
costKnown: false, // codex-cli never reports a cost field (D4).
|
|
128
|
-
outputTruncated: false,
|
|
129
123
|
stderrTail: input.stderrTail,
|
|
130
124
|
errorMessage,
|
|
131
125
|
};
|
|
@@ -22,7 +22,13 @@ export const execHarness = {
|
|
|
22
22
|
parseOutcome(input) {
|
|
23
23
|
const text = input.eventsText;
|
|
24
24
|
const truncated = text.length > MAX_OUTPUT_CHARS;
|
|
25
|
-
|
|
25
|
+
// The full, untruncated capture always stays on disk as this run's events.jsonl (spec 040
|
|
26
|
+
// D1's layout, unconditional for every external run) — a truncated reply must say so
|
|
27
|
+
// explicitly rather than silently dropping the tail (P1-3: the playbook's "full text is
|
|
28
|
+
// always recoverable" promise did not actually hold for a chatty `exec` role).
|
|
29
|
+
const finalText = truncated
|
|
30
|
+
? `${text.slice(0, MAX_OUTPUT_CHARS)}\n\n[... output truncated at ${MAX_OUTPUT_CHARS} characters; the full capture is this run's events.jsonl ...]`
|
|
31
|
+
: text;
|
|
26
32
|
return {
|
|
27
33
|
finalText,
|
|
28
34
|
terminalSeen: false, // Always false, even on success — exec has no protocol terminal (D4/D9).
|
|
@@ -30,7 +36,6 @@ export const execHarness = {
|
|
|
30
36
|
exitCode: input.exitCode,
|
|
31
37
|
usageKnown: false,
|
|
32
38
|
costKnown: false,
|
|
33
|
-
outputTruncated: truncated,
|
|
34
39
|
stderrTail: input.stderrTail,
|
|
35
40
|
errorMessage: input.exitCode === 0 ? undefined : `exec exited with code ${input.exitCode ?? "unknown"}`,
|
|
36
41
|
};
|
|
@@ -26,8 +26,6 @@ export interface BuildInvocationResult {
|
|
|
26
26
|
args: string[];
|
|
27
27
|
/** Whether this harness can be continued later via `resumeSessionId` (claude-code/codex-cli). */
|
|
28
28
|
resumable: boolean;
|
|
29
|
-
/** Paths this invocation references by flag, beyond stdin — kept for the `/subagents show` argv dump. */
|
|
30
|
-
promptFiles?: string[];
|
|
31
29
|
/**
|
|
32
30
|
* claude-code only (D4): a session id it picked and passed via `--session-id` *before* running,
|
|
33
31
|
* so `resume` does not depend on first successfully parsing a `result` event out of a run that
|
|
@@ -50,7 +48,6 @@ export interface ExternalOutcome {
|
|
|
50
48
|
usageKnown: boolean;
|
|
51
49
|
/** `codex-cli`/`exec` are always false: neither reports a cost field. */
|
|
52
50
|
costKnown: boolean;
|
|
53
|
-
outputTruncated: boolean;
|
|
54
51
|
stderrTail?: string;
|
|
55
52
|
errorMessage?: string;
|
|
56
53
|
}
|
|
@@ -7,6 +7,11 @@ import { type RunMutates } from "../runs.js";
|
|
|
7
7
|
* detached process. The launch order matters (D1): admission and the lease are the caller's job
|
|
8
8
|
* (tool.ts, shared with internal runs); this module owns everything from "persist launch intent"
|
|
9
9
|
* onward — spawn, pid persistence, stdin delivery, output capture, and settlement.
|
|
10
|
+
*
|
|
11
|
+
* stdout/stderr are opened as real files and handed to the child directly via `stdio` (P0-1): the
|
|
12
|
+
* child writes its own output, so it survives the daemon disappearing mid-run instead of writing
|
|
13
|
+
* into a pipe nobody is reading. A restart's own recovery (`SubAgentRunManager.restore()` /
|
|
14
|
+
* `sweep()`) reads the same files back once the process is confirmed gone.
|
|
10
15
|
*/
|
|
11
16
|
export interface LaunchExternalRunInput {
|
|
12
17
|
runId: string;
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { spawn as nodeSpawn } from "node:child_process";
|
|
2
|
-
import {
|
|
3
|
-
import { createWriteStream } from "node:fs";
|
|
2
|
+
import { closeSync, openSync } from "node:fs";
|
|
4
3
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
4
|
import { join } from "node:path";
|
|
6
5
|
import * as log from "../../log.js";
|
|
7
6
|
import { logSecurityEvent } from "../../security/logger.js";
|
|
8
|
-
import { killProcessGroup } from "../../shared/host-process.js";
|
|
7
|
+
import { killProcessGroup, readProcessStartTime } from "../../shared/host-process.js";
|
|
9
8
|
import { formatLocalTime } from "../../shared/local-time.js";
|
|
10
9
|
import { splitShellWords } from "../../shared/shell-words.js";
|
|
11
10
|
import { errorMessage } from "../../shared/text-utils.js";
|
|
@@ -98,12 +97,18 @@ export async function launchExternalRun(input) {
|
|
|
98
97
|
}
|
|
99
98
|
const eventsPath = join(input.artifactDir, "events.jsonl");
|
|
100
99
|
const stderrPath = join(input.artifactDir, "stderr.log");
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
100
|
+
let eventsFd;
|
|
101
|
+
let stderrFd;
|
|
102
|
+
try {
|
|
103
|
+
eventsFd = openSync(eventsPath, "a");
|
|
104
|
+
stderrFd = openSync(stderrPath, "a");
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
await runManager.settle(input.runId, failedSettleInput(`Failed to open output files: ${errorMessage(error)}`), {
|
|
108
|
+
announce: true,
|
|
109
|
+
});
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
107
112
|
const spawnFn = input.spawnFn ?? nodeSpawn;
|
|
108
113
|
let child;
|
|
109
114
|
try {
|
|
@@ -111,73 +116,104 @@ export async function launchExternalRun(input) {
|
|
|
111
116
|
detached: true,
|
|
112
117
|
cwd: input.workingDirectory,
|
|
113
118
|
env: input.env ? { ...process.env, ...input.env } : process.env,
|
|
114
|
-
|
|
119
|
+
// stdout/stderr point straight at the artifact files (P0-1): the child writes them
|
|
120
|
+
// itself, so they land on disk even if this daemon disappears before it exits.
|
|
121
|
+
stdio: ["pipe", eventsFd, stderrFd],
|
|
115
122
|
});
|
|
116
123
|
}
|
|
117
124
|
catch (error) {
|
|
118
|
-
|
|
119
|
-
|
|
125
|
+
closeSync(eventsFd);
|
|
126
|
+
closeSync(stderrFd);
|
|
120
127
|
await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${errorMessage(error)}`), {
|
|
121
128
|
announce: true,
|
|
122
129
|
});
|
|
123
130
|
return;
|
|
124
131
|
}
|
|
132
|
+
// The child has its own duped copy of both fds now; ours would otherwise leak across the
|
|
133
|
+
// lifetime of a long-running daemon dispatching many external runs.
|
|
134
|
+
closeSync(eventsFd);
|
|
135
|
+
closeSync(stderrFd);
|
|
125
136
|
const spawnFailure = await new Promise((resolve) => {
|
|
126
137
|
child.once("error", (error) => resolve(error));
|
|
127
138
|
child.once("spawn", () => resolve(undefined));
|
|
128
139
|
});
|
|
129
140
|
if (spawnFailure || !child.pid) {
|
|
130
|
-
eventsStream.close();
|
|
131
|
-
stderrStream.close();
|
|
132
141
|
await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${spawnFailure ? errorMessage(spawnFailure) : "no pid"}`), { announce: true });
|
|
133
142
|
return;
|
|
134
143
|
}
|
|
135
144
|
const pid = child.pid;
|
|
145
|
+
const processStartedAt = Date.now();
|
|
146
|
+
// Attached immediately, before any further `await`: a very fast process (e.g. `exec` running
|
|
147
|
+
// `printf`) can exit and fire "close" before a listener registered after an async gap ever
|
|
148
|
+
// gets attached — `EventEmitter` does not replay missed events, so that gap would hang this
|
|
149
|
+
// run in `running` forever.
|
|
150
|
+
const closePromise = new Promise((resolve) => {
|
|
151
|
+
child.once("close", (code) => resolve(code ?? undefined));
|
|
152
|
+
});
|
|
136
153
|
if (cancelledBeforeSpawn) {
|
|
137
154
|
void killProcessGroup(pid);
|
|
138
|
-
eventsStream.close();
|
|
139
|
-
stderrStream.close();
|
|
140
155
|
await runManager.settle(input.runId, { ...failedSettleInput("Cancelled while the external process was spawning."), status: "cancelled" }, { announce: false });
|
|
141
156
|
return;
|
|
142
157
|
}
|
|
143
|
-
|
|
158
|
+
// The OS-verifiable identity check (D10.3): a restart tells this pid apart from an unrelated
|
|
159
|
+
// process that later reuses the same number. `undefined` when `ps` itself is unavailable —
|
|
160
|
+
// restore()/sweep() then fall back to trusting `isProcessAlive` alone.
|
|
161
|
+
const pidStartedAt = await readProcessStartTime(pid);
|
|
162
|
+
const deadlineAt = processStartedAt + input.maxWallTimeSec * 1000;
|
|
144
163
|
await runManager.setLaunched(input.runId, {
|
|
145
164
|
pid,
|
|
146
|
-
|
|
165
|
+
pidStartedAt,
|
|
147
166
|
argv: spawnedArgv,
|
|
167
|
+
deadlineAt,
|
|
148
168
|
sessionId: invocation.presetSessionId,
|
|
149
169
|
});
|
|
150
|
-
child.stdout?.on("data", (chunk) => eventsStream.write(chunk));
|
|
151
|
-
child.stderr?.on("data", (chunk) => stderrStream.write(chunk));
|
|
152
170
|
if (child.stdin) {
|
|
153
171
|
child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
|
|
154
172
|
child.stdin.end(stdinContent);
|
|
155
173
|
}
|
|
156
|
-
let cancelled = false;
|
|
157
174
|
runManager.registerCancelHandle(input.runId, () => {
|
|
158
|
-
cancelled = true;
|
|
159
175
|
void killProcessGroup(pid);
|
|
160
176
|
});
|
|
161
|
-
|
|
177
|
+
// The narrow window between the pre-spawn placeholder handle (claimExternalLaunch) and the
|
|
178
|
+
// real one just above: a cancel arriving there durably marked `terminationReason` (P1-1) but
|
|
179
|
+
// had no live process to kill yet. Act on it now.
|
|
180
|
+
if (runManager.get(input.runId)?.terminationReason === "cancelled") {
|
|
162
181
|
void killProcessGroup(pid);
|
|
182
|
+
}
|
|
183
|
+
// Prompt, same-process enforcement (the sweeper is the cross-restart backstop for this
|
|
184
|
+
// deadline, at coarser granularity — see SWEEP_INTERVAL_MS in runs.ts).
|
|
185
|
+
const wallClockTimer = setTimeout(() => {
|
|
186
|
+
void runManager.markTerminationReason(input.runId, "timeout").then(() => killProcessGroup(pid));
|
|
163
187
|
}, input.maxWallTimeSec * 1000);
|
|
164
188
|
wallClockTimer.unref?.();
|
|
165
189
|
// Deliberately not awaited by the caller (D2: external's sync grace window is 0) — this
|
|
166
190
|
// continues in the background and settles the run itself once the process exits.
|
|
167
|
-
void
|
|
168
|
-
child.once("close", (code) => resolve(code ?? undefined));
|
|
169
|
-
}).then(async (exitCode) => {
|
|
191
|
+
void closePromise.then(async (exitCode) => {
|
|
170
192
|
clearTimeout(wallClockTimer);
|
|
171
193
|
runManager.clearCancelHandle(input.runId);
|
|
172
194
|
// The leader can exit before a detached descendant it spawned (e.g. a shell that forked and
|
|
173
195
|
// returned); `-pid` still reaches the whole group as long as the group itself is still
|
|
174
196
|
// around, so reap it unconditionally rather than only on an explicit cancel/timeout.
|
|
175
197
|
await killProcessGroup(pid);
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
if (cancelled) {
|
|
198
|
+
const durationMs = Date.now() - processStartedAt;
|
|
199
|
+
const terminationReason = runManager.get(input.runId)?.terminationReason;
|
|
200
|
+
if (terminationReason === "cancelled") {
|
|
201
|
+
await runManager
|
|
202
|
+
.settle(input.runId, { ...failedSettleInput("Cancelled by request."), status: "cancelled", durationMs }, { announce: false })
|
|
203
|
+
.catch((error) => {
|
|
204
|
+
log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (terminationReason === "timeout") {
|
|
209
|
+
// A distinct failure reason from "no protocol terminal event" (P1-1): the process was
|
|
210
|
+
// killed on purpose, not just silent — even if a CLI happened to emit a success terminal
|
|
211
|
+
// right before SIGTERM landed, the budget is what ended this run.
|
|
179
212
|
await runManager
|
|
180
|
-
.settle(input.runId, {
|
|
213
|
+
.settle(input.runId, {
|
|
214
|
+
...failedSettleInput(`Wall time budget exceeded (${input.maxWallTimeSec}s)`),
|
|
215
|
+
durationMs,
|
|
216
|
+
}, { announce: true })
|
|
181
217
|
.catch((error) => {
|
|
182
218
|
log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
|
|
183
219
|
});
|
|
@@ -233,7 +269,7 @@ export async function launchExternalRun(input) {
|
|
|
233
269
|
costKnown: outcome.costKnown,
|
|
234
270
|
turns: 0,
|
|
235
271
|
toolCalls: 0,
|
|
236
|
-
durationMs
|
|
272
|
+
durationMs,
|
|
237
273
|
outputText: outcome.finalText,
|
|
238
274
|
sessionId: outcome.sessionId,
|
|
239
275
|
verificationVerdict,
|
package/dist/subagents/runs.d.ts
CHANGED
|
@@ -24,8 +24,8 @@ export type RunMutates = "read" | "write";
|
|
|
24
24
|
* rule for numeric thresholds.
|
|
25
25
|
*/
|
|
26
26
|
export declare const SYNC_GRACE_MS = 120000;
|
|
27
|
-
/** D10.2: per-channel cap on concurrently running delegation runs
|
|
28
|
-
export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL =
|
|
27
|
+
/** D10.2: per-channel cap on concurrently running delegation runs. */
|
|
28
|
+
export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
|
|
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;
|
|
@@ -87,7 +87,16 @@ export interface RunRecord extends RunUsage {
|
|
|
87
87
|
wakeClaimDispatchId?: string;
|
|
88
88
|
wakeConsumedAt?: number;
|
|
89
89
|
pid?: number;
|
|
90
|
-
|
|
90
|
+
/** `ps`'s `lstart` for `pid` at launch — the OS-verifiable identity check that tells this
|
|
91
|
+
* process apart from an unrelated one that later reuses the same pid (D10.3). */
|
|
92
|
+
pidStartedAt?: string;
|
|
93
|
+
/** Wall-clock deadline (`setLaunched` time + `maxWallTimeSec`), so a restart can resume
|
|
94
|
+
* enforcing it — an in-process timer dies with the process that set it. */
|
|
95
|
+
deadlineAt?: number;
|
|
96
|
+
/** Set before the kill signal is sent, so whichever code path eventually settles this run (the
|
|
97
|
+
* live in-process watcher or the cross-restart sweeper) reports why, instead of guessing from
|
|
98
|
+
* protocol output alone (P1-1). */
|
|
99
|
+
terminationReason?: "timeout" | "cancelled";
|
|
91
100
|
argv?: string[];
|
|
92
101
|
sessionId?: string;
|
|
93
102
|
leaseKey?: string;
|
|
@@ -189,8 +198,9 @@ export declare class SubAgentRunManager {
|
|
|
189
198
|
*/
|
|
190
199
|
setLaunched(runId: string, info: {
|
|
191
200
|
pid: number;
|
|
192
|
-
|
|
201
|
+
pidStartedAt?: string;
|
|
193
202
|
argv: string[];
|
|
203
|
+
deadlineAt: number;
|
|
194
204
|
sessionId?: string;
|
|
195
205
|
}): Promise<void>;
|
|
196
206
|
/** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
|
|
@@ -199,6 +209,10 @@ export declare class SubAgentRunManager {
|
|
|
199
209
|
finishWakeConsumption(runId: string, dispatchId: string): Promise<void>;
|
|
200
210
|
/** Let a caller (subagent tool) register a way to abort this run's in-process worker. */
|
|
201
211
|
registerCancelHandle(runId: string, cancel: () => void): void;
|
|
212
|
+
/** Record why a still-running external run is about to be killed, before the signal is sent
|
|
213
|
+
* (P1-1) — see the `terminationReason` field doc. A no-op once the run is no longer running.
|
|
214
|
+
* Called by both the live in-process watcher (`external/run.ts`) and `sweep()` below. */
|
|
215
|
+
markTerminationReason(runId: string, reason: "timeout" | "cancelled"): Promise<void>;
|
|
202
216
|
clearCancelHandle(runId: string): void;
|
|
203
217
|
/**
|
|
204
218
|
* Settle a run exactly once (D1/D7 order: settle → record usage/archive → enqueue wake).
|
|
@@ -225,22 +239,39 @@ export declare class SubAgentRunManager {
|
|
|
225
239
|
* left alone here — the harness-specific probe (spec 040 phase 2/3) reconciles those.
|
|
226
240
|
*/
|
|
227
241
|
restore(): Promise<number>;
|
|
242
|
+
/** Whether `record.pid` is still the same process that was launched, when that can be checked
|
|
243
|
+
* at all (D10.3). A missing `pidStartedAt` (an older record, or a `ps` that failed once at
|
|
244
|
+
* launch) means there is nothing to compare against — trust `isProcessAlive` alone rather
|
|
245
|
+
* than manufacture a false negative. */
|
|
246
|
+
private isSameProcess;
|
|
228
247
|
/**
|
|
229
|
-
* Restart reconciliation for an external run still marked `running` (D10.3)
|
|
248
|
+
* Restart reconciliation for an external run still marked `running` (D10.3), and the terminal
|
|
249
|
+
* judgement `sweep()` uses once an adopted run's process is confirmed gone. Unlike internal
|
|
230
250
|
* runs, a `detached` external process outlives the daemon, so the first move is a liveness
|
|
231
251
|
* probe, not an automatic `lost`:
|
|
232
252
|
*
|
|
233
253
|
* - no `pid` at all: the intent was persisted but spawn was never confirmed — cannot prove it
|
|
234
254
|
* ever started, so it is judged `lost` the same as an internal run (D1).
|
|
235
|
-
* - `pid` alive: genuinely still running. Left alone
|
|
236
|
-
* - `pid` gone
|
|
237
|
-
*
|
|
238
|
-
* the
|
|
255
|
+
* - `pid` alive under the same identity: genuinely still running. Left alone.
|
|
256
|
+
* - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
|
|
257
|
+
* while the daemon was down. A `terminationReason` set before the kill (P1-1) takes priority
|
|
258
|
+
* over guessing from output; absent that, `events.jsonl` drives the same D4 status table the
|
|
259
|
+
* live post-exit path uses.
|
|
239
260
|
*/
|
|
240
261
|
private reconcileExternalRun;
|
|
262
|
+
/**
|
|
263
|
+
* Periodic host-wide check for external runs (spec 040, D10.3): kills anything past its
|
|
264
|
+
* deadline, and reconciles anything a `close` event will never fire for — a run adopted from a
|
|
265
|
+
* previous daemon via `restore()`, or (rarely) one whose local watcher already unwound without
|
|
266
|
+
* settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
|
|
267
|
+
* so sweeping one this process itself launched is harmless, not just adopted ones.
|
|
268
|
+
*/
|
|
269
|
+
sweep(now?: number): Promise<void>;
|
|
241
270
|
/** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
|
|
242
271
|
private collectGarbageIfExpired;
|
|
243
272
|
}
|
|
273
|
+
/** Test seam: stop the background sweeper so it doesn't outlive a test's own fake timers or run. */
|
|
274
|
+
export declare function stopSubAgentSweeper(): void;
|
|
244
275
|
/** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
|
|
245
276
|
export declare function configureSubAgentRuntime(config: RunManagerOptions): void;
|
|
246
277
|
export declare function getSubAgentRunManager(channelId: string): SubAgentRunManager;
|