@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +5 -3
- package/dist/agent/job-manager.js +8 -5
- 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.js +45 -1
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +3 -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 +3 -1
- package/dist/security/types.d.ts +17 -1
- package/dist/shared/host-process.d.ts +15 -0
- package/dist/shared/host-process.js +40 -0
- 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 +39 -0
- package/dist/subagents/external/run.js +220 -0
- package/dist/subagents/runs.d.ts +216 -0
- package/dist/subagents/runs.js +522 -0
- package/dist/subagents/tool.d.ts +8 -0
- package/dist/subagents/tool.js +350 -124
- 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/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 +10 -1
- package/dist/tools/registry.js +1 -0
- package/dist/tools/subagent-manage.d.ts +18 -0
- package/dist/tools/subagent-manage.js +141 -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 +6 -0
- package/examples/sub-agents/README.md +59 -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 +33 -39
- package/examples/sub-agents/scout.md +31 -0
- package/examples/sub-agents/verifier.md +29 -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,133 @@
|
|
|
1
|
+
import { detectExistingFlags, expandPlaceholders, } from "./harness.js";
|
|
2
|
+
/**
|
|
3
|
+
* `codex-cli` harness (spec 040, D3/D4). One prompt, one short-lived process, NDJSON on stdout
|
|
4
|
+
* (`--json -`). Chosen as the first structured harness because its process model already matches
|
|
5
|
+
* D3 with nothing to reduce — no FIFO, no long-lived session to reconcile.
|
|
6
|
+
*
|
|
7
|
+
* The event shapes below are the design doc's D4 table, not a live-verified schema snapshot: the
|
|
8
|
+
* risk section calls this out explicitly (CLI schema drift is an accepted, ongoing maintenance
|
|
9
|
+
* cost). `parseOutcome` is written so a shape mismatch degrades to `unparsable` rather than
|
|
10
|
+
* throwing — that contract is load-bearing, unlike the exact field names.
|
|
11
|
+
*/
|
|
12
|
+
// Codex's `thinkingLevel` values line up 1:1 with pipiclaw's own except at the bottom of the
|
|
13
|
+
// scale (D4's translation table): "off" has no weaker codex equivalent than "none", and "minimal"
|
|
14
|
+
// is model-dependent (some models 400 on it), so both clamp up to the next real level.
|
|
15
|
+
const THINKING_LEVEL_TO_CODEX_EFFORT = {
|
|
16
|
+
off: "none",
|
|
17
|
+
minimal: "low",
|
|
18
|
+
low: "low",
|
|
19
|
+
medium: "medium",
|
|
20
|
+
high: "high",
|
|
21
|
+
xhigh: "xhigh",
|
|
22
|
+
max: "max",
|
|
23
|
+
};
|
|
24
|
+
function toCodexEffort(level) {
|
|
25
|
+
if (!level)
|
|
26
|
+
return undefined;
|
|
27
|
+
return THINKING_LEVEL_TO_CODEX_EFFORT[level] ?? level;
|
|
28
|
+
}
|
|
29
|
+
export const codexCliHarness = {
|
|
30
|
+
id: "codex-cli",
|
|
31
|
+
buildInvocation(input) {
|
|
32
|
+
if (input.argv.length === 0) {
|
|
33
|
+
throw new Error("codex-cli: command produced no argv tokens");
|
|
34
|
+
}
|
|
35
|
+
const [executable, ...rest] = input.argv;
|
|
36
|
+
const existing = detectExistingFlags(rest);
|
|
37
|
+
const effort = toCodexEffort(input.thinkingLevel);
|
|
38
|
+
const { argv: expandedRest, used } = expandPlaceholders(rest, {
|
|
39
|
+
$MODEL: input.model,
|
|
40
|
+
$EFFORT: effort,
|
|
41
|
+
$PROMPT_FILE: input.promptFile,
|
|
42
|
+
$SYSTEM_PROMPT_FILE: input.systemPromptFile,
|
|
43
|
+
});
|
|
44
|
+
const baseArgs = [...expandedRest];
|
|
45
|
+
if (!existing.model && input.model && !used.has("$MODEL")) {
|
|
46
|
+
baseArgs.push("-m", input.model);
|
|
47
|
+
}
|
|
48
|
+
if (!existing.effort && effort && !used.has("$EFFORT")) {
|
|
49
|
+
baseArgs.push("-c", `model_reasoning_effort=${effort}`);
|
|
50
|
+
}
|
|
51
|
+
// Resume is a subcommand, not a flag: `<father args> resume <thread_id> --json -`, so the
|
|
52
|
+
// base flags above must come first and `--json -` last regardless (D4).
|
|
53
|
+
const args = input.resumeSessionId
|
|
54
|
+
? [...baseArgs, "resume", input.resumeSessionId, "--json", "-"]
|
|
55
|
+
: [...baseArgs, "--json", "-"];
|
|
56
|
+
return {
|
|
57
|
+
executable,
|
|
58
|
+
args,
|
|
59
|
+
resumable: true,
|
|
60
|
+
promptFiles: used.has("$PROMPT_FILE") ? [input.promptFile] : undefined,
|
|
61
|
+
};
|
|
62
|
+
},
|
|
63
|
+
parseOutcome(input) {
|
|
64
|
+
let finalText = "";
|
|
65
|
+
let sessionId;
|
|
66
|
+
let terminalSeen = false;
|
|
67
|
+
let protocolStatus = "absent";
|
|
68
|
+
let errorMessage;
|
|
69
|
+
let usage;
|
|
70
|
+
let usageKnown = false;
|
|
71
|
+
let parsedAnyLine = false;
|
|
72
|
+
for (const line of input.eventsText.split("\n")) {
|
|
73
|
+
const trimmed = line.trim();
|
|
74
|
+
if (!trimmed)
|
|
75
|
+
continue;
|
|
76
|
+
let event;
|
|
77
|
+
try {
|
|
78
|
+
event = JSON.parse(trimmed);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
continue; // Tolerate a torn or non-JSON line; judged by what *did* parse.
|
|
82
|
+
}
|
|
83
|
+
if (typeof event !== "object" || event === null)
|
|
84
|
+
continue;
|
|
85
|
+
parsedAnyLine = true;
|
|
86
|
+
const record = event;
|
|
87
|
+
const threadId = record.thread_id ?? record.thread?.id;
|
|
88
|
+
if (typeof threadId === "string")
|
|
89
|
+
sessionId = threadId;
|
|
90
|
+
if (record.type === "item.completed") {
|
|
91
|
+
const item = record.item;
|
|
92
|
+
if (item?.type === "agent_message" && typeof item.text === "string") {
|
|
93
|
+
finalText = item.text;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (record.type === "turn.completed") {
|
|
97
|
+
terminalSeen = true;
|
|
98
|
+
protocolStatus = "completed";
|
|
99
|
+
const rawUsage = record.usage;
|
|
100
|
+
if (rawUsage) {
|
|
101
|
+
const input_ = Number(rawUsage.input_tokens ?? 0);
|
|
102
|
+
const output_ = Number(rawUsage.output_tokens ?? 0);
|
|
103
|
+
if (Number.isFinite(input_) || Number.isFinite(output_)) {
|
|
104
|
+
usage = { input: input_ || 0, output: output_ || 0, total: (input_ || 0) + (output_ || 0) };
|
|
105
|
+
usageKnown = true;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (record.type === "turn.failed") {
|
|
110
|
+
terminalSeen = true;
|
|
111
|
+
protocolStatus = "failed";
|
|
112
|
+
const error = record.error;
|
|
113
|
+
errorMessage = typeof error?.message === "string" ? error.message : "codex-cli reported turn.failed";
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!parsedAnyLine && input.eventsText.trim()) {
|
|
117
|
+
protocolStatus = "unparsable";
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
finalText,
|
|
121
|
+
terminalSeen,
|
|
122
|
+
protocolStatus,
|
|
123
|
+
exitCode: input.exitCode,
|
|
124
|
+
sessionId,
|
|
125
|
+
usage,
|
|
126
|
+
usageKnown,
|
|
127
|
+
costKnown: false, // codex-cli never reports a cost field (D4).
|
|
128
|
+
outputTruncated: false,
|
|
129
|
+
stderrTail: input.stderrTail,
|
|
130
|
+
errorMessage,
|
|
131
|
+
};
|
|
132
|
+
},
|
|
133
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `exec` harness (spec 040, D3/D4/D9). The generic escape hatch: run the command as-is, prompt on
|
|
3
|
+
* stdin, whatever it prints on stdout is the result. No protocol, no flags, no placeholders beyond
|
|
4
|
+
* what the shared helper already offers — there is nothing harness-specific to inject because
|
|
5
|
+
* there is no known CLI contract to inject it into.
|
|
6
|
+
*
|
|
7
|
+
* This is the explicit exception to the D4 status table (see `classifyExternalOutcome`): `exec`
|
|
8
|
+
* has no terminal event to observe at all, so `terminalSeen` is always `false` and completion
|
|
9
|
+
* evidence is exit code alone — weaker than a structured harness, which is exactly why `exec` is
|
|
10
|
+
* barred from `purpose=verify` (D9) and always reports `usageKnown`/`costKnown: false`.
|
|
11
|
+
*/
|
|
12
|
+
const MAX_OUTPUT_CHARS = 16_000;
|
|
13
|
+
export const execHarness = {
|
|
14
|
+
id: "exec",
|
|
15
|
+
buildInvocation(input) {
|
|
16
|
+
if (input.argv.length === 0) {
|
|
17
|
+
throw new Error("exec: command produced no argv tokens");
|
|
18
|
+
}
|
|
19
|
+
const [executable, ...args] = input.argv;
|
|
20
|
+
return { executable, args, resumable: false };
|
|
21
|
+
},
|
|
22
|
+
parseOutcome(input) {
|
|
23
|
+
const text = input.eventsText;
|
|
24
|
+
const truncated = text.length > MAX_OUTPUT_CHARS;
|
|
25
|
+
const finalText = truncated ? text.slice(0, MAX_OUTPUT_CHARS) : text;
|
|
26
|
+
return {
|
|
27
|
+
finalText,
|
|
28
|
+
terminalSeen: false, // Always false, even on success — exec has no protocol terminal (D4/D9).
|
|
29
|
+
protocolStatus: input.exitCode === 0 ? "completed" : "failed",
|
|
30
|
+
exitCode: input.exitCode,
|
|
31
|
+
usageKnown: false,
|
|
32
|
+
costKnown: false,
|
|
33
|
+
outputTruncated: truncated,
|
|
34
|
+
stderrTail: input.stderrTail,
|
|
35
|
+
errorMessage: input.exitCode === 0 ? undefined : `exec exited with code ${input.exitCode ?? "unknown"}`,
|
|
36
|
+
};
|
|
37
|
+
},
|
|
38
|
+
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { UsageTotals } from "../../shared/types.js";
|
|
2
|
+
import type { SubAgentThinkingLevel } from "../discovery.js";
|
|
3
|
+
/**
|
|
4
|
+
* The harness adapter seam (spec 040, D4). Every external run is reduced to the same process
|
|
5
|
+
* model (D3: one prompt, one short-lived process); what differs between `claude-code`,
|
|
6
|
+
* `codex-cli`, and `exec` is only argv assembly and stdout parsing, and that is exactly what this
|
|
7
|
+
* interface covers. It carries no state machine of its own — `runs.ts` owns that.
|
|
8
|
+
*/
|
|
9
|
+
export interface ExternalInvocationInput {
|
|
10
|
+
/** The role's `command`, already shell-word-split (D4) — never re-parsed here, never shelled out. */
|
|
11
|
+
argv: string[];
|
|
12
|
+
/** The harness's own model string (`SubAgentConfig.externalModelRef`), passed through unresolved. */
|
|
13
|
+
model?: string;
|
|
14
|
+
thinkingLevel?: SubAgentThinkingLevel;
|
|
15
|
+
artifactDir: string;
|
|
16
|
+
/** Path to the stdin prompt file (D1 layout: `<artifactDir>/prompt.txt`). */
|
|
17
|
+
promptFile: string;
|
|
18
|
+
/** Path to the role's system-prompt file (`<artifactDir>/system-prompt.txt`), for harnesses
|
|
19
|
+
* that reference it by flag (e.g. claude-code's `--append-system-prompt-file`). */
|
|
20
|
+
systemPromptFile: string;
|
|
21
|
+
/** Set when this invocation continues an earlier run (`subagent_manage op=follow_up`, D6). */
|
|
22
|
+
resumeSessionId?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface BuildInvocationResult {
|
|
25
|
+
executable: string;
|
|
26
|
+
args: string[];
|
|
27
|
+
/** Whether this harness can be continued later via `resumeSessionId` (claude-code/codex-cli). */
|
|
28
|
+
resumable: boolean;
|
|
29
|
+
/** Paths this invocation references by flag, beyond stdin — kept for the `/subagents show` argv dump. */
|
|
30
|
+
promptFiles?: string[];
|
|
31
|
+
/**
|
|
32
|
+
* claude-code only (D4): a session id it picked and passed via `--session-id` *before* running,
|
|
33
|
+
* so `resume` does not depend on first successfully parsing a `result` event out of a run that
|
|
34
|
+
* might crash before producing one. The orchestrator persists this immediately after spawn,
|
|
35
|
+
* not just at settlement.
|
|
36
|
+
*/
|
|
37
|
+
presetSessionId?: string;
|
|
38
|
+
}
|
|
39
|
+
export type ExternalProtocolStatus = "completed" | "failed" | "absent" | "unparsable";
|
|
40
|
+
export interface ExternalOutcome {
|
|
41
|
+
finalText: string;
|
|
42
|
+
/** Whether a protocol terminal event was observed at all. `false` ⇒ status can never be `completed` (D4). */
|
|
43
|
+
terminalSeen: boolean;
|
|
44
|
+
protocolStatus: ExternalProtocolStatus;
|
|
45
|
+
exitCode?: number;
|
|
46
|
+
/** The harness's own session/thread id, captured for a later `resume` even if this run failed midway. */
|
|
47
|
+
sessionId?: string;
|
|
48
|
+
usage?: Partial<UsageTotals>;
|
|
49
|
+
/** `exec` is always false: it has no token accounting at all. */
|
|
50
|
+
usageKnown: boolean;
|
|
51
|
+
/** `codex-cli`/`exec` are always false: neither reports a cost field. */
|
|
52
|
+
costKnown: boolean;
|
|
53
|
+
outputTruncated: boolean;
|
|
54
|
+
stderrTail?: string;
|
|
55
|
+
errorMessage?: string;
|
|
56
|
+
}
|
|
57
|
+
export interface ParseOutcomeInput {
|
|
58
|
+
/** Raw contents of `events.jsonl` (structured harnesses) or captured stdout (`exec`). */
|
|
59
|
+
eventsText: string;
|
|
60
|
+
/** `undefined` when the process was killed by a signal rather than exiting normally. */
|
|
61
|
+
exitCode?: number;
|
|
62
|
+
stderrTail?: string;
|
|
63
|
+
}
|
|
64
|
+
export interface ExternalHarness {
|
|
65
|
+
readonly id: "claude-code" | "codex-cli" | "exec";
|
|
66
|
+
/** Assemble argv. The command line is never joined into a single shell string (D4). */
|
|
67
|
+
buildInvocation(input: ExternalInvocationInput): BuildInvocationResult;
|
|
68
|
+
/** Parse stdout into a unified outcome. Must never throw — a parse failure degrades to
|
|
69
|
+
* `protocolStatus: "unparsable"`, not an exception (D4). */
|
|
70
|
+
parseOutcome(input: ParseOutcomeInput): ExternalOutcome;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The D4 status table, shared by the live post-exit path and restart reconciliation (D10.3) so
|
|
74
|
+
* both judge a run identically. `exec` is the table's explicit exception (D4/D9): it has no
|
|
75
|
+
* protocol terminal at all, so its own `parseOutcome` already folds the exit code into
|
|
76
|
+
* `protocolStatus` directly — `terminalSeen` stays `false` even on success, so it must not be
|
|
77
|
+
* checked here for that one harness.
|
|
78
|
+
*/
|
|
79
|
+
export declare function classifyExternalOutcome(harnessId: ExternalHarness["id"], outcome: ExternalOutcome): {
|
|
80
|
+
status: "completed" | "failed";
|
|
81
|
+
failureReason?: string;
|
|
82
|
+
};
|
|
83
|
+
/** Flags a `command` frontmatter value can already carry, in which case a harness must not append the same-named one (D4). */
|
|
84
|
+
export interface ExistingFlags {
|
|
85
|
+
model: boolean;
|
|
86
|
+
effort: boolean;
|
|
87
|
+
}
|
|
88
|
+
/** Which flags the user's own `command` already spells out, so a harness never injects a duplicate (D4). */
|
|
89
|
+
export declare function detectExistingFlags(argv: string[]): ExistingFlags;
|
|
90
|
+
declare const PLACEHOLDERS: readonly ["$MODEL", "$EFFORT", "$PROMPT_FILE", "$SYSTEM_PROMPT_FILE"];
|
|
91
|
+
export type Placeholder = (typeof PLACEHOLDERS)[number];
|
|
92
|
+
/**
|
|
93
|
+
* Expand `$MODEL`/`$EFFORT`/`$PROMPT_FILE`/`$SYSTEM_PROMPT_FILE` wherever they appear in argv
|
|
94
|
+
* (D4). Returns which placeholders were actually found, so a harness knows whether it still needs
|
|
95
|
+
* to *append* the corresponding flag (a placeholder present ⇒ never append; absent ⇒ append per
|
|
96
|
+
* the harness's own rule).
|
|
97
|
+
*/
|
|
98
|
+
export declare function expandPlaceholders(argv: string[], values: Partial<Record<Placeholder, string>>): {
|
|
99
|
+
argv: string[];
|
|
100
|
+
used: Set<Placeholder>;
|
|
101
|
+
};
|
|
102
|
+
export {};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The D4 status table, shared by the live post-exit path and restart reconciliation (D10.3) so
|
|
3
|
+
* both judge a run identically. `exec` is the table's explicit exception (D4/D9): it has no
|
|
4
|
+
* protocol terminal at all, so its own `parseOutcome` already folds the exit code into
|
|
5
|
+
* `protocolStatus` directly — `terminalSeen` stays `false` even on success, so it must not be
|
|
6
|
+
* checked here for that one harness.
|
|
7
|
+
*/
|
|
8
|
+
export function classifyExternalOutcome(harnessId, outcome) {
|
|
9
|
+
if (harnessId === "exec") {
|
|
10
|
+
return outcome.protocolStatus === "completed"
|
|
11
|
+
? { status: "completed" }
|
|
12
|
+
: { status: "failed", failureReason: outcome.errorMessage ?? `exec exited with code ${outcome.exitCode}` };
|
|
13
|
+
}
|
|
14
|
+
if (outcome.terminalSeen && outcome.protocolStatus === "completed") {
|
|
15
|
+
return { status: "completed" };
|
|
16
|
+
}
|
|
17
|
+
if (outcome.protocolStatus === "failed") {
|
|
18
|
+
return { status: "failed", failureReason: outcome.errorMessage ?? "The harness reported a protocol failure." };
|
|
19
|
+
}
|
|
20
|
+
if (outcome.exitCode === 0 && outcome.protocolStatus === "absent") {
|
|
21
|
+
return {
|
|
22
|
+
status: "failed",
|
|
23
|
+
failureReason: "The process exited normally but no protocol terminal event was observed.",
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
if (outcome.protocolStatus === "unparsable") {
|
|
27
|
+
return { status: "failed", failureReason: outcome.errorMessage ?? "The harness output could not be parsed." };
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
status: "failed",
|
|
31
|
+
failureReason: outcome.errorMessage ?? "The process ended without a recognized terminal state.",
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const MODEL_FLAG_PATTERN = /^(--model|-m)$/;
|
|
35
|
+
const EFFORT_FLAG_PATTERN = /^(--effort|--thinking)$/;
|
|
36
|
+
const CODEX_EFFORT_FLAG_PATTERN = /^-c$/;
|
|
37
|
+
const CODEX_EFFORT_VALUE_PREFIX = "model_reasoning_effort=";
|
|
38
|
+
/** Which flags the user's own `command` already spells out, so a harness never injects a duplicate (D4). */
|
|
39
|
+
export function detectExistingFlags(argv) {
|
|
40
|
+
let model = false;
|
|
41
|
+
let effort = false;
|
|
42
|
+
for (let i = 0; i < argv.length; i++) {
|
|
43
|
+
const token = argv[i];
|
|
44
|
+
if (MODEL_FLAG_PATTERN.test(token))
|
|
45
|
+
model = true;
|
|
46
|
+
if (EFFORT_FLAG_PATTERN.test(token))
|
|
47
|
+
effort = true;
|
|
48
|
+
if (CODEX_EFFORT_FLAG_PATTERN.test(token) && argv[i + 1]?.startsWith(CODEX_EFFORT_VALUE_PREFIX))
|
|
49
|
+
effort = true;
|
|
50
|
+
if (token.startsWith("--model=") || token.startsWith("-m="))
|
|
51
|
+
model = true;
|
|
52
|
+
}
|
|
53
|
+
return { model, effort };
|
|
54
|
+
}
|
|
55
|
+
const PLACEHOLDERS = ["$MODEL", "$EFFORT", "$PROMPT_FILE", "$SYSTEM_PROMPT_FILE"];
|
|
56
|
+
/**
|
|
57
|
+
* Expand `$MODEL`/`$EFFORT`/`$PROMPT_FILE`/`$SYSTEM_PROMPT_FILE` wherever they appear in argv
|
|
58
|
+
* (D4). Returns which placeholders were actually found, so a harness knows whether it still needs
|
|
59
|
+
* to *append* the corresponding flag (a placeholder present ⇒ never append; absent ⇒ append per
|
|
60
|
+
* the harness's own rule).
|
|
61
|
+
*/
|
|
62
|
+
export function expandPlaceholders(argv, values) {
|
|
63
|
+
const used = new Set();
|
|
64
|
+
const expanded = argv.map((token) => {
|
|
65
|
+
let result = token;
|
|
66
|
+
for (const placeholder of PLACEHOLDERS) {
|
|
67
|
+
const value = values[placeholder];
|
|
68
|
+
if (value !== undefined && result.includes(placeholder)) {
|
|
69
|
+
used.add(placeholder);
|
|
70
|
+
result = result.split(placeholder).join(value);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
});
|
|
75
|
+
return { argv: expanded, used };
|
|
76
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { claudeCodeHarness } from "./claude-code.js";
|
|
2
|
+
import { codexCliHarness } from "./codex-cli.js";
|
|
3
|
+
import { execHarness } from "./exec.js";
|
|
4
|
+
const harnesses = {
|
|
5
|
+
"codex-cli": codexCliHarness,
|
|
6
|
+
"claude-code": claudeCodeHarness,
|
|
7
|
+
exec: execHarness,
|
|
8
|
+
};
|
|
9
|
+
export function getExternalHarness(id) {
|
|
10
|
+
return harnesses[id];
|
|
11
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { spawn as nodeSpawn } from "node:child_process";
|
|
2
|
+
import type { SubAgentThinkingLevel } from "../discovery.js";
|
|
3
|
+
/**
|
|
4
|
+
* The external-run orchestrator (spec 040, D1/D3/D4). One prompt, one short-lived, argv-direct,
|
|
5
|
+
* detached process. The launch order matters (D1): admission and the lease are the caller's job
|
|
6
|
+
* (tool.ts, shared with internal runs); this module owns everything from "persist launch intent"
|
|
7
|
+
* onward — spawn, pid persistence, stdin delivery, output capture, and settlement.
|
|
8
|
+
*/
|
|
9
|
+
export interface LaunchExternalRunInput {
|
|
10
|
+
runId: string;
|
|
11
|
+
channelId: string;
|
|
12
|
+
/** Needed only for `purpose=verify`: where the attestation gets written. */
|
|
13
|
+
channelDir?: string;
|
|
14
|
+
label: string;
|
|
15
|
+
agent: string;
|
|
16
|
+
source: "predefined" | "inline";
|
|
17
|
+
harness: string;
|
|
18
|
+
/** The role's raw `command` frontmatter — tokenized here, never handed to a shell (D4). */
|
|
19
|
+
command: string;
|
|
20
|
+
shell?: boolean;
|
|
21
|
+
env?: Record<string, string>;
|
|
22
|
+
externalModelRef?: string;
|
|
23
|
+
thinkingLevel?: SubAgentThinkingLevel;
|
|
24
|
+
maxWallTimeSec: number;
|
|
25
|
+
/** The role's system-prompt body (the role file's markdown). */
|
|
26
|
+
systemPrompt: string;
|
|
27
|
+
task: string;
|
|
28
|
+
workingDirectory: string;
|
|
29
|
+
artifactDir: string;
|
|
30
|
+
purpose: "work" | "verify";
|
|
31
|
+
taskId?: string;
|
|
32
|
+
leaseKey?: string;
|
|
33
|
+
resumeSessionId?: string;
|
|
34
|
+
/** Test seam: inject a fake `child_process.spawn`. */
|
|
35
|
+
spawnFn?: typeof nodeSpawn;
|
|
36
|
+
}
|
|
37
|
+
/** Launches an external run. Returns once the process is confirmed spawned (or fails fast if it
|
|
38
|
+
* never starts); the wait-for-exit-and-settle work continues in the background afterward. */
|
|
39
|
+
export declare function launchExternalRun(input: LaunchExternalRunInput): Promise<void>;
|
|
@@ -0,0 +1,220 @@
|
|
|
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 { killProcessGroup } from "../../shared/host-process.js";
|
|
8
|
+
import { formatLocalTime } from "../../shared/local-time.js";
|
|
9
|
+
import { splitShellWords } from "../../shared/shell-words.js";
|
|
10
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
11
|
+
import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
|
|
12
|
+
import { parseVerificationVerdict, writeVerificationAttestation } from "../../tasks/verification.js";
|
|
13
|
+
import { getSubAgentRunManager } from "../runs.js";
|
|
14
|
+
import { classifyExternalOutcome } from "./harness.js";
|
|
15
|
+
import { getExternalHarness } from "./registry.js";
|
|
16
|
+
const WAKE_OUTPUT_TAIL_CHARS = 2_000;
|
|
17
|
+
function buildStdinContent(harnessId, systemPrompt, task) {
|
|
18
|
+
// claude-code has a real system-prompt flag (--append-system-prompt-file, D4); every other
|
|
19
|
+
// harness has no such channel, so the role's system prompt has nowhere to go but the prompt
|
|
20
|
+
// itself, folded ahead of the task.
|
|
21
|
+
if (harnessId === "claude-code")
|
|
22
|
+
return task;
|
|
23
|
+
return `${systemPrompt.trim()}\n\n---\n\n${task.trim()}\n`;
|
|
24
|
+
}
|
|
25
|
+
/** Launches an external run. Returns once the process is confirmed spawned (or fails fast if it
|
|
26
|
+
* never starts); the wait-for-exit-and-settle work continues in the background afterward. */
|
|
27
|
+
export async function launchExternalRun(input) {
|
|
28
|
+
const harness = getExternalHarness(input.harness);
|
|
29
|
+
if (!harness) {
|
|
30
|
+
throw new Error(`Unknown external harness "${input.harness}".`);
|
|
31
|
+
}
|
|
32
|
+
// `tool.ts` already creates the artifact dir for a fresh run; `follow_up` (subagent-manage.ts)
|
|
33
|
+
// mints a new runId/artifactDir on the spot, so this is the one place that must be reliable
|
|
34
|
+
// either way.
|
|
35
|
+
await mkdir(input.artifactDir, { recursive: true });
|
|
36
|
+
const promptFile = join(input.artifactDir, "prompt.txt");
|
|
37
|
+
const systemPromptFile = join(input.artifactDir, "system-prompt.txt");
|
|
38
|
+
const stdinContent = buildStdinContent(harness.id, input.systemPrompt, input.task);
|
|
39
|
+
await writeFile(promptFile, `${input.task.trim()}\n`, "utf-8");
|
|
40
|
+
await writeFile(systemPromptFile, `${input.systemPrompt.trim()}\n`, "utf-8");
|
|
41
|
+
// D9: an external verifier's advisory attestation needs a before/after subject snapshot the
|
|
42
|
+
// same way the internal path does — taken here, before the process starts, since this is the
|
|
43
|
+
// earliest point at which the run is committed to running against this workingDirectory.
|
|
44
|
+
const verifySubjectBefore = input.purpose === "verify" ? await workspaceSubjectHash(input.workingDirectory) : undefined;
|
|
45
|
+
const argv = input.shell ? [] : splitShellWords(input.command);
|
|
46
|
+
const invocation = input.shell
|
|
47
|
+
? { executable: "/bin/sh", args: ["-lc", input.command], resumable: false }
|
|
48
|
+
: harness.buildInvocation({
|
|
49
|
+
argv,
|
|
50
|
+
model: input.externalModelRef,
|
|
51
|
+
thinkingLevel: input.thinkingLevel,
|
|
52
|
+
artifactDir: input.artifactDir,
|
|
53
|
+
promptFile,
|
|
54
|
+
systemPromptFile,
|
|
55
|
+
resumeSessionId: input.resumeSessionId,
|
|
56
|
+
});
|
|
57
|
+
const runManager = getSubAgentRunManager(input.channelId);
|
|
58
|
+
await runManager.register({
|
|
59
|
+
runId: input.runId,
|
|
60
|
+
channelId: input.channelId,
|
|
61
|
+
runtime: "external",
|
|
62
|
+
harness: harness.id,
|
|
63
|
+
agent: input.agent,
|
|
64
|
+
label: input.label,
|
|
65
|
+
source: input.source,
|
|
66
|
+
tools: [],
|
|
67
|
+
model: input.externalModelRef,
|
|
68
|
+
purpose: input.purpose,
|
|
69
|
+
taskId: input.taskId,
|
|
70
|
+
workingDirectory: input.workingDirectory,
|
|
71
|
+
artifactDir: input.artifactDir,
|
|
72
|
+
leaseKey: input.leaseKey,
|
|
73
|
+
});
|
|
74
|
+
const eventsPath = join(input.artifactDir, "events.jsonl");
|
|
75
|
+
const stderrPath = join(input.artifactDir, "stderr.log");
|
|
76
|
+
const eventsStream = createWriteStream(eventsPath);
|
|
77
|
+
const stderrStream = createWriteStream(stderrPath);
|
|
78
|
+
// A stream closed before its "open" completes (e.g. the spawn-failure path below) can emit its
|
|
79
|
+
// own "error"; without a listener that becomes an uncaught exception rather than a settled run.
|
|
80
|
+
eventsStream.on("error", () => { });
|
|
81
|
+
stderrStream.on("error", () => { });
|
|
82
|
+
const spawnFn = input.spawnFn ?? nodeSpawn;
|
|
83
|
+
let child;
|
|
84
|
+
try {
|
|
85
|
+
child = spawnFn(invocation.executable, invocation.args, {
|
|
86
|
+
detached: true,
|
|
87
|
+
cwd: input.workingDirectory,
|
|
88
|
+
env: input.env ? { ...process.env, ...input.env } : process.env,
|
|
89
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
eventsStream.close();
|
|
94
|
+
stderrStream.close();
|
|
95
|
+
await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${errorMessage(error)}`), {
|
|
96
|
+
announce: true,
|
|
97
|
+
});
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const spawnFailure = await new Promise((resolve) => {
|
|
101
|
+
child.once("error", (error) => resolve(error));
|
|
102
|
+
child.once("spawn", () => resolve(undefined));
|
|
103
|
+
});
|
|
104
|
+
if (spawnFailure || !child.pid) {
|
|
105
|
+
eventsStream.close();
|
|
106
|
+
stderrStream.close();
|
|
107
|
+
await runManager.settle(input.runId, failedSettleInput(`Failed to launch: ${spawnFailure ? errorMessage(spawnFailure) : "no pid"}`), { announce: true });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const pid = child.pid;
|
|
111
|
+
const fingerprint = randomBytes(6).toString("hex");
|
|
112
|
+
await runManager.setLaunched(input.runId, {
|
|
113
|
+
pid,
|
|
114
|
+
fingerprint,
|
|
115
|
+
argv: [invocation.executable, ...invocation.args],
|
|
116
|
+
sessionId: invocation.presetSessionId,
|
|
117
|
+
});
|
|
118
|
+
child.stdout?.on("data", (chunk) => eventsStream.write(chunk));
|
|
119
|
+
child.stderr?.on("data", (chunk) => stderrStream.write(chunk));
|
|
120
|
+
if (child.stdin) {
|
|
121
|
+
child.stdin.on("error", () => { }); // EPIPE if the process already exited; harmless.
|
|
122
|
+
child.stdin.end(stdinContent);
|
|
123
|
+
}
|
|
124
|
+
runManager.registerCancelHandle(input.runId, () => {
|
|
125
|
+
void killProcessGroup(pid);
|
|
126
|
+
});
|
|
127
|
+
const wallClockTimer = setTimeout(() => {
|
|
128
|
+
void killProcessGroup(pid);
|
|
129
|
+
}, input.maxWallTimeSec * 1000);
|
|
130
|
+
wallClockTimer.unref?.();
|
|
131
|
+
// Deliberately not awaited by the caller (D2: external's sync grace window is 0) — this
|
|
132
|
+
// continues in the background and settles the run itself once the process exits.
|
|
133
|
+
void new Promise((resolve) => {
|
|
134
|
+
child.once("close", (code) => resolve(code ?? undefined));
|
|
135
|
+
}).then(async (exitCode) => {
|
|
136
|
+
clearTimeout(wallClockTimer);
|
|
137
|
+
runManager.clearCancelHandle(input.runId);
|
|
138
|
+
await new Promise((resolve) => eventsStream.end(resolve));
|
|
139
|
+
await new Promise((resolve) => stderrStream.end(resolve));
|
|
140
|
+
const eventsText = await readFile(eventsPath, "utf-8").catch(() => "");
|
|
141
|
+
const stderrTail = (await readFile(stderrPath, "utf-8").catch(() => "")).slice(-WAKE_OUTPUT_TAIL_CHARS);
|
|
142
|
+
const outcome = harness.parseOutcome({ eventsText, exitCode, stderrTail });
|
|
143
|
+
const classification = classifyExternalOutcome(harness.id, outcome);
|
|
144
|
+
// D9: the verdict is a fact the run reported, independent of whether the run itself
|
|
145
|
+
// "succeeded" — a verifier that cleanly concludes VERDICT: FAIL is still a completed run.
|
|
146
|
+
let verificationVerdict;
|
|
147
|
+
if (input.purpose === "verify" && input.taskId && input.channelDir && classification.status === "completed") {
|
|
148
|
+
const subjectAfter = await workspaceSubjectHash(input.workingDirectory);
|
|
149
|
+
const workspaceChanged = verifySubjectBefore !== undefined && subjectAfter !== undefined && verifySubjectBefore !== subjectAfter;
|
|
150
|
+
const declaredVerdict = parseVerificationVerdict(outcome.finalText);
|
|
151
|
+
verificationVerdict = declaredVerdict === "pass" && !workspaceChanged ? "pass" : "fail";
|
|
152
|
+
const evidence = workspaceChanged
|
|
153
|
+
? "Verifier's workspace subject changed; the attestation is invalid."
|
|
154
|
+
: !declaredVerdict
|
|
155
|
+
? "Verifier did not emit the required final VERDICT marker."
|
|
156
|
+
: outcome.finalText.trim().slice(0, 8_000);
|
|
157
|
+
await writeVerificationAttestation(input.channelDir, {
|
|
158
|
+
runId: input.runId,
|
|
159
|
+
taskId: input.taskId,
|
|
160
|
+
verdict: verificationVerdict,
|
|
161
|
+
checkedAt: formatLocalTime(),
|
|
162
|
+
evidence,
|
|
163
|
+
workspaceChanged,
|
|
164
|
+
subjectHash: workspaceChanged ? undefined : subjectAfter,
|
|
165
|
+
subjectDir: input.workingDirectory,
|
|
166
|
+
// External verifiers cannot have their tools structurally removed the way an
|
|
167
|
+
// internal verifier's are — the sandbox flag lives in the role's own `command`,
|
|
168
|
+
// unverifiable by pipiclaw. Advisory, not enforced (D9).
|
|
169
|
+
verificationStrength: "advisory",
|
|
170
|
+
}).catch((error) => {
|
|
171
|
+
log.logWarning(`Failed to write verification attestation for run ${input.runId}`, errorMessage(error));
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
await runManager
|
|
175
|
+
.settle(input.runId, {
|
|
176
|
+
status: classification.status,
|
|
177
|
+
failureReason: classification.failureReason,
|
|
178
|
+
usage: {
|
|
179
|
+
input: outcome.usage?.input ?? 0,
|
|
180
|
+
output: outcome.usage?.output ?? 0,
|
|
181
|
+
cacheRead: outcome.usage?.cacheRead ?? 0,
|
|
182
|
+
cacheWrite: outcome.usage?.cacheWrite ?? 0,
|
|
183
|
+
total: outcome.usage?.total ?? 0,
|
|
184
|
+
cost: outcome.usage?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
185
|
+
},
|
|
186
|
+
usageKnown: outcome.usageKnown,
|
|
187
|
+
costKnown: outcome.costKnown,
|
|
188
|
+
turns: 0,
|
|
189
|
+
toolCalls: 0,
|
|
190
|
+
durationMs: 0,
|
|
191
|
+
outputText: outcome.finalText,
|
|
192
|
+
sessionId: outcome.sessionId,
|
|
193
|
+
verificationVerdict,
|
|
194
|
+
verificationStrength: verificationVerdict ? "advisory" : undefined,
|
|
195
|
+
}, { announce: true })
|
|
196
|
+
.catch((error) => {
|
|
197
|
+
log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
function failedSettleInput(reason) {
|
|
201
|
+
return {
|
|
202
|
+
status: "failed",
|
|
203
|
+
failureReason: reason,
|
|
204
|
+
usage: {
|
|
205
|
+
input: 0,
|
|
206
|
+
output: 0,
|
|
207
|
+
cacheRead: 0,
|
|
208
|
+
cacheWrite: 0,
|
|
209
|
+
total: 0,
|
|
210
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
211
|
+
},
|
|
212
|
+
usageKnown: false,
|
|
213
|
+
costKnown: false,
|
|
214
|
+
turns: 0,
|
|
215
|
+
toolCalls: 0,
|
|
216
|
+
durationMs: 0,
|
|
217
|
+
outputText: "",
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
}
|