@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/agent/channel-runner.d.ts +3 -0
  2. package/dist/agent/channel-runner.js +9 -0
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +9 -0
  5. package/dist/agent/job-manager.d.ts +11 -3
  6. package/dist/agent/job-manager.js +63 -6
  7. package/dist/agent/prompt/sections.js +46 -7
  8. package/dist/agent/prompt/types.d.ts +9 -0
  9. package/dist/agent/session-events.js +7 -42
  10. package/dist/agent/types.d.ts +4 -0
  11. package/dist/playbooks/agent-delegation.md +46 -21
  12. package/dist/playbooks/runtime-orientation.md +2 -2
  13. package/dist/runtime/bootstrap.d.ts +38 -0
  14. package/dist/runtime/bootstrap.js +167 -14
  15. package/dist/runtime/dingtalk.d.ts +9 -0
  16. package/dist/runtime/dingtalk.js +3 -0
  17. package/dist/runtime/durable-dispatch.d.ts +4 -0
  18. package/dist/runtime/durable-dispatch.js +16 -0
  19. package/dist/runtime/store.d.ts +7 -0
  20. package/dist/runtime/subagent-commands.d.ts +15 -0
  21. package/dist/runtime/subagent-commands.js +122 -0
  22. package/dist/runtime/task-commands.js +5 -1
  23. package/dist/security/logger.js +10 -1
  24. package/dist/security/types.d.ts +17 -1
  25. package/dist/shared/host-process.d.ts +21 -0
  26. package/dist/shared/host-process.js +44 -0
  27. package/dist/shared/jsonl-appender.d.ts +2 -0
  28. package/dist/shared/jsonl-appender.js +25 -13
  29. package/dist/shared/shell-words.d.ts +9 -0
  30. package/dist/shared/shell-words.js +52 -0
  31. package/dist/subagents/discovery.d.ts +42 -1
  32. package/dist/subagents/discovery.js +302 -69
  33. package/dist/subagents/external/claude-code.d.ts +2 -0
  34. package/dist/subagents/external/claude-code.js +152 -0
  35. package/dist/subagents/external/codex-cli.d.ts +2 -0
  36. package/dist/subagents/external/codex-cli.js +133 -0
  37. package/dist/subagents/external/exec.d.ts +2 -0
  38. package/dist/subagents/external/exec.js +38 -0
  39. package/dist/subagents/external/harness.d.ts +102 -0
  40. package/dist/subagents/external/harness.js +76 -0
  41. package/dist/subagents/external/registry.d.ts +2 -0
  42. package/dist/subagents/external/registry.js +11 -0
  43. package/dist/subagents/external/run.d.ts +49 -0
  44. package/dist/subagents/external/run.js +266 -0
  45. package/dist/subagents/runs.d.ts +230 -0
  46. package/dist/subagents/runs.js +615 -0
  47. package/dist/subagents/tool.d.ts +26 -0
  48. package/dist/subagents/tool.js +464 -182
  49. package/dist/subagents/workspace-lease.d.ts +36 -0
  50. package/dist/subagents/workspace-lease.js +48 -0
  51. package/dist/tasks/artifact-subject.js +50 -2
  52. package/dist/tasks/control.d.ts +12 -0
  53. package/dist/tasks/control.js +20 -0
  54. package/dist/tasks/store.d.ts +21 -0
  55. package/dist/tasks/store.js +80 -0
  56. package/dist/tasks/verification.d.ts +8 -0
  57. package/dist/tasks/verification.js +10 -2
  58. package/dist/tools/index.d.ts +1 -1
  59. package/dist/tools/index.js +12 -1
  60. package/dist/tools/registry.js +1 -0
  61. package/dist/tools/subagent-manage.d.ts +23 -0
  62. package/dist/tools/subagent-manage.js +154 -0
  63. package/dist/tools/tool-details.d.ts +1 -1
  64. package/dist/tui/app.js +2 -0
  65. package/dist/tui/commands.d.ts +1 -0
  66. package/dist/tui/commands.js +2 -0
  67. package/dist/tui/turn-controller.d.ts +1 -0
  68. package/dist/tui/turn-controller.js +1 -0
  69. package/dist/usage/ledger.d.ts +13 -0
  70. package/dist/usage/ledger.js +15 -2
  71. package/dist/usage/render.js +22 -0
  72. package/examples/sub-agents/README.md +61 -12
  73. package/examples/sub-agents/builder-hard.md +45 -0
  74. package/examples/sub-agents/builder.md +41 -0
  75. package/examples/sub-agents/documenter.md +53 -0
  76. package/examples/sub-agents/log-sifter.md +43 -0
  77. package/examples/sub-agents/planner.md +42 -0
  78. package/examples/sub-agents/reviewer.md +38 -38
  79. package/examples/sub-agents/scout.md +31 -0
  80. package/examples/sub-agents/verifier.md +32 -36
  81. package/examples/sub-agents/worker.md +36 -0
  82. package/package.json +1 -1
  83. package/examples/sub-agents/researcher.md +0 -41
@@ -0,0 +1,152 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { detectExistingFlags, expandPlaceholders, } from "./harness.js";
3
+ /**
4
+ * `claude-code` harness (spec 040, D3/D4). Same one-prompt-one-process model as codex-cli; the
5
+ * differences are argv shape and stdout schema.
6
+ *
7
+ * The `--session-id`-before-running approach (rather than parsing it out of the first `result`
8
+ * event) is a deliberate improvement flagged in the design doc's review: it means `resume` does
9
+ * not depend on the run having produced *any* successful output — a run that crashes on turn one
10
+ * is still resumable. `--input-format stream-json`, `--include-partial-messages`, and
11
+ * `--replay-user-messages` are deliberately not used: they exist for long-lived, bidirectional
12
+ * sessions (agentmux's use case), and D3 already reduced every harness to one prompt = one
13
+ * process, so none of those apply here.
14
+ *
15
+ * Event shapes are the design doc's D4 table, not a live-verified schema: same schema-drift risk
16
+ * as codex-cli, and `parseOutcome` is written the same way — degrade, never throw.
17
+ */
18
+ const THINKING_LEVEL_TO_CLAUDE_EFFORT = {
19
+ off: "low", // claude-code has no weaker level than "low" (D4 clamp table).
20
+ minimal: "low",
21
+ low: "low",
22
+ medium: "medium",
23
+ high: "high",
24
+ xhigh: "xhigh",
25
+ max: "max",
26
+ };
27
+ function toClaudeEffort(level) {
28
+ if (!level)
29
+ return undefined;
30
+ return THINKING_LEVEL_TO_CLAUDE_EFFORT[level] ?? level;
31
+ }
32
+ export const claudeCodeHarness = {
33
+ id: "claude-code",
34
+ buildInvocation(input) {
35
+ if (input.argv.length === 0) {
36
+ throw new Error("claude-code: command produced no argv tokens");
37
+ }
38
+ const [executable, ...rest] = input.argv;
39
+ const existing = detectExistingFlags(rest);
40
+ // D4's addendum table lists no auto-appended effort flag for claude-code — only $EFFORT
41
+ // expansion for a role author whose wrapper accepts one.
42
+ const effort = toClaudeEffort(input.thinkingLevel);
43
+ const { argv: expandedRest, used } = expandPlaceholders(rest, {
44
+ $MODEL: input.model,
45
+ $EFFORT: effort,
46
+ $PROMPT_FILE: input.promptFile,
47
+ $SYSTEM_PROMPT_FILE: input.systemPromptFile,
48
+ });
49
+ const args = [...expandedRest, "-p", "--output-format", "stream-json", "--verbose"];
50
+ if (!existing.model && input.model && !used.has("$MODEL")) {
51
+ args.push("--model", input.model);
52
+ }
53
+ if (!used.has("$SYSTEM_PROMPT_FILE")) {
54
+ args.push("--append-system-prompt-file", input.systemPromptFile);
55
+ }
56
+ let presetSessionId;
57
+ if (input.resumeSessionId) {
58
+ args.push("--resume", input.resumeSessionId);
59
+ }
60
+ else {
61
+ presetSessionId = randomUUID();
62
+ args.push("--session-id", presetSessionId);
63
+ }
64
+ const promptFiles = [input.systemPromptFile, ...(used.has("$PROMPT_FILE") ? [input.promptFile] : [])];
65
+ return { executable, args, resumable: true, promptFiles, presetSessionId };
66
+ },
67
+ parseOutcome(input) {
68
+ let finalText = "";
69
+ let sessionId;
70
+ let terminalSeen = false;
71
+ let protocolStatus = "absent";
72
+ let errorMessage;
73
+ let usage;
74
+ let usageKnown = false;
75
+ let costKnown = false;
76
+ let costTotal;
77
+ let parsedAnyLine = false;
78
+ for (const line of input.eventsText.split("\n")) {
79
+ const trimmed = line.trim();
80
+ if (!trimmed)
81
+ continue;
82
+ let event;
83
+ try {
84
+ event = JSON.parse(trimmed);
85
+ }
86
+ catch {
87
+ continue; // Tolerate a torn or non-JSON line.
88
+ }
89
+ if (typeof event !== "object" || event === null)
90
+ continue;
91
+ parsedAnyLine = true;
92
+ const record = event;
93
+ const sid = record.session_id;
94
+ if (typeof sid === "string")
95
+ sessionId = sid;
96
+ if (record.type === "result") {
97
+ terminalSeen = true;
98
+ const isError = record.is_error === true;
99
+ protocolStatus = isError ? "failed" : "completed";
100
+ if (typeof record.result === "string")
101
+ finalText = record.result;
102
+ if (isError) {
103
+ errorMessage =
104
+ typeof record.result === "string" && record.result
105
+ ? record.result
106
+ : typeof record.subtype === "string"
107
+ ? `claude-code reported ${record.subtype}`
108
+ : "claude-code reported an error result";
109
+ }
110
+ const cost = record.total_cost_usd;
111
+ if (typeof cost === "number") {
112
+ costTotal = cost;
113
+ costKnown = true;
114
+ }
115
+ const rawUsage = record.usage;
116
+ if (rawUsage) {
117
+ const inputTokens = Number(rawUsage.input_tokens ?? 0);
118
+ const outputTokens = Number(rawUsage.output_tokens ?? 0);
119
+ const cacheRead = Number(rawUsage.cache_read_input_tokens ?? 0);
120
+ const cacheWrite = Number(rawUsage.cache_creation_input_tokens ?? 0);
121
+ usage = {
122
+ input: inputTokens || 0,
123
+ output: outputTokens || 0,
124
+ cacheRead: cacheRead || 0,
125
+ cacheWrite: cacheWrite || 0,
126
+ total: (inputTokens || 0) + (outputTokens || 0) + (cacheRead || 0) + (cacheWrite || 0),
127
+ ...(costTotal !== undefined
128
+ ? { cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: costTotal } }
129
+ : {}),
130
+ };
131
+ usageKnown = true;
132
+ }
133
+ }
134
+ }
135
+ if (!parsedAnyLine && input.eventsText.trim()) {
136
+ protocolStatus = "unparsable";
137
+ }
138
+ return {
139
+ finalText,
140
+ terminalSeen,
141
+ protocolStatus,
142
+ exitCode: input.exitCode,
143
+ sessionId,
144
+ usage,
145
+ usageKnown,
146
+ costKnown,
147
+ outputTruncated: false,
148
+ stderrTail: input.stderrTail,
149
+ errorMessage,
150
+ };
151
+ },
152
+ };
@@ -0,0 +1,2 @@
1
+ import { type ExternalHarness } from "./harness.js";
2
+ export declare const codexCliHarness: ExternalHarness;
@@ -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,2 @@
1
+ import type { ExternalHarness } from "./harness.js";
2
+ export declare const execHarness: ExternalHarness;
@@ -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,2 @@
1
+ import type { ExternalHarness } from "./harness.js";
2
+ export declare function getExternalHarness(id: string): ExternalHarness | undefined;
@@ -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,49 @@
1
+ import { spawn as nodeSpawn } from "node:child_process";
2
+ import type { SecurityConfig } from "../../security/types.js";
3
+ import type { SubAgentThinkingLevel } from "../discovery.js";
4
+ import { type RunMutates } from "../runs.js";
5
+ /**
6
+ * The external-run orchestrator (spec 040, D1/D3/D4). One prompt, one short-lived, argv-direct,
7
+ * detached process. The launch order matters (D1): admission and the lease are the caller's job
8
+ * (tool.ts, shared with internal runs); this module owns everything from "persist launch intent"
9
+ * onward — spawn, pid persistence, stdin delivery, output capture, and settlement.
10
+ */
11
+ export interface LaunchExternalRunInput {
12
+ runId: string;
13
+ channelId: string;
14
+ /** Needed only for `purpose=verify`: where the attestation gets written. */
15
+ channelDir?: string;
16
+ label: string;
17
+ agent: string;
18
+ source: "predefined" | "inline";
19
+ harness: string;
20
+ /** The role's raw `command` frontmatter — tokenized here, never handed to a shell (D4). */
21
+ command: string;
22
+ shell?: boolean;
23
+ env?: Record<string, string>;
24
+ externalModelRef?: string;
25
+ thinkingLevel?: SubAgentThinkingLevel;
26
+ maxWallTimeSec: number;
27
+ /** The role's system-prompt body (the role file's markdown). */
28
+ systemPrompt: string;
29
+ task: string;
30
+ workingDirectory: string;
31
+ artifactDir: string;
32
+ purpose: "work" | "verify";
33
+ taskId?: string;
34
+ leaseKey?: string;
35
+ resumeSessionId?: string;
36
+ /** The role's own `mutates` declaration, carried through to the dispatch audit event (D8.1). */
37
+ mutates?: RunMutates;
38
+ /** Where the audit trail lives (`<workspaceDir>/.pipiclaw/security.log` by default) and whether
39
+ * it is enabled — every external dispatch writes an `external-agent` audit event (D8.1), since
40
+ * external processes never pass through command-guard and this is the only record of what
41
+ * actually ran. */
42
+ workspaceDir: string;
43
+ securityConfig: SecurityConfig;
44
+ /** Test seam: inject a fake `child_process.spawn`. */
45
+ spawnFn?: typeof nodeSpawn;
46
+ }
47
+ /** Launches an external run. Returns once the process is confirmed spawned (or fails fast if it
48
+ * never starts); the wait-for-exit-and-settle work continues in the background afterward. */
49
+ export declare function launchExternalRun(input: LaunchExternalRunInput): Promise<void>;