tr-plugin-meta-harness 0.3.0 → 0.5.26

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 (94) hide show
  1. package/DESIGN.md +86 -0
  2. package/README.md +257 -11
  3. package/capability/BRICK.md +1 -1
  4. package/capability/index.mjs +154 -13
  5. package/cli.mjs +426 -41
  6. package/package.json +15 -3
  7. package/plugin.json +1457 -119
  8. package/skills/meta-harness/SKILL.md +63 -25
  9. package/src/adoption.mjs +102 -0
  10. package/src/agent-user.mjs +194 -0
  11. package/src/alerts.mjs +220 -14
  12. package/src/cascade.mjs +185 -0
  13. package/src/chat.mjs +80 -0
  14. package/src/codex-models.mjs +54 -0
  15. package/src/compat-harness.mjs +114 -0
  16. package/src/control.mjs +145 -0
  17. package/src/coordinator.mjs +267 -358
  18. package/src/dispatch-request.mjs +76 -0
  19. package/src/dispatch.mjs +119 -0
  20. package/src/documentation-authority.mjs +57 -0
  21. package/src/documentation.mjs +120 -32
  22. package/src/executor.mjs +101 -22
  23. package/src/gate-adapters/agy.mjs +155 -0
  24. package/src/gate-adapters/claude.mjs +303 -0
  25. package/src/gate-adapters/cline.mjs +111 -0
  26. package/src/gate-adapters/codex.mjs +164 -0
  27. package/src/gate-adapters/cursor.mjs +164 -0
  28. package/src/gate-adapters/devin.mjs +116 -0
  29. package/src/gate-adapters/dsh.mjs +284 -0
  30. package/src/gate-adapters/grok.mjs +112 -0
  31. package/src/gate-adapters/hermes.mjs +217 -0
  32. package/src/gate-adapters/hook-files.mjs +156 -0
  33. package/src/gate-adapters/index.mjs +131 -0
  34. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  35. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  36. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  37. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  38. package/src/gate-adapters/openclaw.mjs +288 -0
  39. package/src/gate-adapters/pi.mjs +146 -0
  40. package/src/gate.mjs +18 -0
  41. package/src/harness-updates.mjs +170 -0
  42. package/src/included-usage.mjs +344 -0
  43. package/src/jobs.mjs +135 -0
  44. package/src/json-reply.mjs +22 -0
  45. package/src/learner.mjs +97 -67
  46. package/src/maintenance.mjs +18 -0
  47. package/src/mcp-server.mjs +228 -0
  48. package/src/model-catalog.mjs +195 -0
  49. package/src/model-selection.mjs +67 -0
  50. package/src/paths.mjs +23 -0
  51. package/src/pool.mjs +69 -0
  52. package/src/process-manager.mjs +246 -0
  53. package/src/process-worker.mjs +18 -0
  54. package/src/reasoning.mjs +231 -0
  55. package/src/remote-operation.mjs +76 -0
  56. package/src/review.mjs +241 -0
  57. package/src/reviews.mjs +25 -0
  58. package/src/router-benchmark-corpus.mjs +16 -0
  59. package/src/router-benchmark.mjs +208 -0
  60. package/src/router.mjs +265 -346
  61. package/src/runtime.mjs +30 -8
  62. package/src/session/claude.mjs +358 -0
  63. package/src/session/codex.mjs +501 -0
  64. package/src/session/result.mjs +90 -0
  65. package/src/session/resume.mjs +393 -0
  66. package/src/session/run.mjs +258 -0
  67. package/src/session-jobs.mjs +77 -0
  68. package/src/setup.mjs +6 -3
  69. package/src/ssss-store.mjs +20 -0
  70. package/src/telemetry.mjs +267 -0
  71. package/src/termination.mjs +28 -0
  72. package/src/threads.mjs +150 -0
  73. package/src/usage-queue.mjs +137 -0
  74. package/src/verify-ssss.mjs +102 -0
  75. package/src/worker.mjs +955 -84
  76. package/src/worktree.mjs +244 -0
  77. package/ui/chunks/adapter-docs-freshness.md +16 -0
  78. package/ui/chunks/chat-handoff.md +26 -0
  79. package/ui/chunks/fleet-maintenance.md +21 -0
  80. package/ui/chunks/harness-inventory.md +21 -0
  81. package/ui/chunks/included-access.md +18 -0
  82. package/ui/chunks/included-usage-verification.md +15 -0
  83. package/ui/chunks/independent-review.md +17 -0
  84. package/ui/chunks/managed-execution.md +20 -0
  85. package/ui/chunks/official-documentation.md +18 -0
  86. package/ui/chunks/quota-recovery.md +21 -0
  87. package/ui/chunks/review-routing-decision.md +16 -0
  88. package/ui/chunks/route-work.md +18 -0
  89. package/ui/chunks/routing-evidence.md +18 -0
  90. package/ui/chunks/run-ledger.md +18 -0
  91. package/ui/chunks/session-controls.md +16 -0
  92. package/ui/home.js +198 -0
  93. package/ui/DESIGN.md +0 -32
  94. package/ui/card.js +0 -845
package/src/runtime.mjs CHANGED
@@ -1,22 +1,44 @@
1
- /** One native runtime-management boundary for every installed agent. */
1
+ /** Runtime observations and explicit maintenance. Agent work belongs to dispatch. */
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { getActiveAdapters, findBinary, runProcess, agentEnvironment } from './worker.mjs';
6
6
 
7
+ const DSH_OBSERVATIONS = ['status', 'sessions', 'tools', 'models', 'model', 'plugins', 'help'];
8
+ const MAINTENANCE = new Map([
9
+ ['claude', [['auth', 'status']]],
10
+ ['codex', [['login', 'status']]],
11
+ ['cursor', [['status']]],
12
+ ['dsh', [...DSH_OBSERVATIONS.map(operation => [operation]), ['model', '--cache']]],
13
+ ['hermes', [['status'], ['status', '--full'], ['gateway', 'status'], ['skills', 'list'], ['plugins', 'list'], ['auth']]],
14
+ ['ollama', [['list'], ['ps']]],
15
+ ['openclaw', [['status'], ['health'], ['gateway', 'status'], ['plugins', 'list']]],
16
+ ]);
17
+
18
+ export function validateRuntimeOperation(agent, args = []) {
19
+ if (typeof agent !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(agent)) throw new Error('Invalid agent adapter');
20
+ if (!Array.isArray(args) || args.length > 64 || args.some(arg => typeof arg !== 'string' || arg.length > 8192)) throw new Error('Invalid native runtime arguments');
21
+ if (args.some(arg => /(?:api[-_]?key|password|secret|access[-_]?token|refresh[-_]?token)/i.test(arg))) throw new Error('Credential values and mutations belong to the auth owner, never runtime argv');
22
+ const command = args.length ? args : [agent === 'dsh' ? 'status' : '--help'];
23
+ const supported = [['--help'], ['-h'], ['--version'], ...(MAINTENANCE.get(agent) || [])];
24
+ if (!supported.some(tuple => tuple.length === command.length && tuple.every((word, index) => word === command[index]))) {
25
+ throw new Error('Runtime accepts only supported maintenance commands. Use meta-harness dispatch or route --execute for agent work, or the owning plugin for service changes.');
26
+ }
27
+ return command;
28
+ }
29
+
7
30
  export async function manageRuntime(agent, args = [], { env = process.env, probe = runProcess, cwd = process.cwd() } = {}) {
31
+ args = validateRuntimeOperation(agent, args);
8
32
  const adapter = getActiveAdapters().find(item => item.id === agent);
9
33
  if (!adapter) throw new Error('Unknown agent adapter');
10
- if (!Array.isArray(args) || args.length > 64 || args.some(arg => typeof arg !== 'string' || arg.length > 8192)) throw new Error('Invalid native runtime arguments');
11
- if (args.some(arg => /(?:api[-_]?key|password|secret|access[-_]?token|refresh[-_]?token)/i.test(arg))) throw new Error('Credential values and mutations belong to the auth owner, never runtime argv');
12
- if (agent === 'dsh' && ['status','sessions','tools','models','model','plugins','help','--help','-h'].includes(args[0] || 'status')) {
34
+ if (agent === 'dsh' && DSH_OBSERVATIONS.includes(args[0])) {
13
35
  const { run } = await import('./adapters/dsh.mjs');
14
36
  const lines = [], errors = [], log = console.log, error = console.error;
15
37
  const previous = process.exitCode;
16
38
  let result, code;
17
39
  try {
18
40
  console.log = (...parts) => lines.push(parts.join(' ')); console.error = (...parts) => errors.push(parts.join(' '));
19
- result = await run([process.execPath, 'cli-agents', 'dsh', ...args]);
41
+ result = await run([process.execPath, 'meta-harness', 'dsh', ...args]);
20
42
  code = process.exitCode || 0;
21
43
  } finally { console.log = log; console.error = error; process.exitCode = previous; }
22
44
  return { ok:code === 0, agent, exitCode:code, data:result?.data, output:lines.join('\n'), error:errors.join('\n') || undefined };
@@ -26,11 +48,11 @@ export async function manageRuntime(agent, args = [], { env = process.env, probe
26
48
  if (!binary) throw new Error('Total Recall auth CLI is unavailable');
27
49
  const home = env.HERMES_HOME || path.join(env.HOME || os.homedir(), '.hermes');
28
50
  fs.mkdirSync(home, { recursive:true, mode:0o700 });
29
- const result = await probe(binary, ['auth','secret','export-env','--path',home,'--keys','OPENROUTER_API_KEY,TELEGRAM_BOT_TOKEN,TELEGRAM_ALLOWED_USERS'], { cwd, timeoutMs:30000, env:agentEnvironment(env) });
51
+ const result = await probe(binary, ['auth','secret','export-env','--path',home,'--keys','OPENROUTER_API_KEY,HERMES_TELEGRAM_BOT_TOKEN,TELEGRAM_ALLOWED_USERS','--rename','HERMES_TELEGRAM_BOT_TOKEN=TELEGRAM_BOT_TOKEN','--no-example'], { cwd:home, timeoutMs:30000, env:agentEnvironment(env) });
30
52
  return { ok:result.exitCode===0 && !result.reason, agent, authority:'auth', exitCode:result.exitCode, output:result.stdout, error:result.reason || (result.exitCode ? 'Auth projection failed' : undefined) };
31
53
  }
32
54
  const binary = findBinary(adapter.binary, env);
33
55
  if (!binary) throw new Error(`${adapter.name} is not installed on the selected node`);
34
- const result = await probe(binary, args.length ? args : ['--help'], { cwd, timeoutMs:60000, env:agentEnvironment(env) });
35
- return { ok:result.exitCode===0 && !result.reason, agent, exitCode:result.exitCode, output:result.stdout, error:result.reason || (result.exitCode ? result.stderr || 'Runtime command failed' : undefined) };
56
+ const result = await probe(binary, args, { cwd, timeoutMs:60000, env:agentEnvironment(env) });
57
+ return { ok:result.exitCode===0 && !result.reason, agent, exitCode:result.exitCode, output:result.stdout || (result.exitCode === 0 ? result.stderr : ''), error:result.reason || (result.exitCode ? result.stderr || 'Runtime command failed' : undefined) };
36
58
  }
@@ -0,0 +1,358 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { createInterface } from 'node:readline';
4
+
5
+ // Protocol sources: code.claude.com/docs/en/{cli-reference,headless}.md and
6
+ // agent-sdk/{streaming-vs-single-mode,typescript}.md (updated 2026-11-30).
7
+ const controls = ['reply', 'interrupt', 'answer', 'fork', 'goal', 'limits', 'schema', 'review'];
8
+ const metaharnessCommand = /(?:^|[\s/])total-recall[ \t]+(?:meta-harness|cli-agents)[ \t]+(?:orchestrate|route|coordinate|dispatch|fork|resume)(?=\s|$)/;
9
+ const ownedValues = new Set(['--input-format', '--output-format', '--session-id', '--name', '-n',
10
+ '--max-turns', '--max-budget-usd', '--json-schema', '--effort', '--fallback-model', '--mcp-config',
11
+ '--permission-prompt-tool']);
12
+ const ownedSwitches = new Set(['-p', '--print', '--verbose', '--replay-user-messages',
13
+ '--include-hook-events', '--forward-subagent-text', '--no-session-persistence']);
14
+ const textOf = content => typeof content === 'string' ? content : Array.isArray(content)
15
+ ? content.filter(block => block.type === 'text').map(block => block.text).join('\n') : '';
16
+ const failureKind = (text, subtype) => /error_max_(turns|budget_usd)/.test(subtype || '') ? 'limit'
17
+ : /quota|rate.?limit|usage limit|credit|\b429\b/i.test(text) ? 'quota'
18
+ : /not (?:logged|signed) in|authenticat|invalid api key|\b401\b/i.test(text) ? 'auth' : 'agent';
19
+
20
+ /** Own one Claude stream-json process. Only Node built-ins are used on remote nodes. */
21
+ export function createClaudeDriver({ harness, binary, args = [], cwd, env, job,
22
+ options = {}, onEvent = () => {}, onFrame = () => {}, spawnFn = spawn, runAs } = {}) {
23
+ const capabilities = Object.fromEntries(controls.map(key => [key, 'unsupported']));
24
+ let sessionId = options.forkSession ? randomUUID() : options.sessionId || randomUUID();
25
+ let child, lines, started = false, closing = false, exited = false, initialized = false;
26
+ let settled = false, stderr = '', response = '', closePromise, continuation;
27
+ let usage = { inputTokens: 0, outputTokens: 0, costUsd: 0 };
28
+ let processCostUsd = 0;
29
+ let resolveReady, rejectReady, resolveDone, resolveExit;
30
+ const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
31
+ ready.catch(() => {}); // start() is the public reader of startup errors.
32
+ let done = new Promise(resolve => { resolveDone = resolve; });
33
+ const exit = new Promise(resolve => { resolveExit = resolve; });
34
+ const signal = name => {
35
+ try { if (process.platform !== 'win32' && child?.pid) process.kill(-child.pid, name); else child?.kill(name); return true; }
36
+ catch { return false; }
37
+ };
38
+ const pending = new Map();
39
+ const requests = new Map();
40
+ const backgroundTools = new Set();
41
+ const backgroundTasks = new Map();
42
+ const emit = (kind, fields = {}) => { try { onEvent({ kind, text: '', ...fields }); } catch { /* observers do not own the process */ } };
43
+ const rejectPending = error => {
44
+ for (const entry of pending.values()) { clearTimeout(entry.timer); entry.reject(error); }
45
+ pending.clear();
46
+ requests.clear();
47
+ };
48
+ const complete = result => {
49
+ if (settled) return;
50
+ settled = true;
51
+ resolveDone({ ok: false, response, sessionId, usage: { ...usage }, structured: undefined,
52
+ error: null, failureKind: null, ...result });
53
+ };
54
+ const fail = error => {
55
+ const message = String(error?.message || error);
56
+ rejectReady(new Error(message));
57
+ rejectPending(new Error(message));
58
+ emit('error', { text: message });
59
+ complete({ error: message, failureKind: failureKind(message) });
60
+ };
61
+ const writable = () => {
62
+ if (!started || closing || exited || !child?.stdin?.writable) throw new Error('Claude session is not open.');
63
+ };
64
+ const write = frame => {
65
+ writable();
66
+ child.stdin.write(`${JSON.stringify(frame)}\n`, error => { if (error) fail(error); });
67
+ };
68
+ const userMessage = text => ({ type: 'user', uuid: randomUUID(), session_id: sessionId,
69
+ message: { role: 'user', content: text }, parent_tool_use_id: null });
70
+ const acknowledge = (id, value) => {
71
+ const entry = pending.get(id);
72
+ if (!entry) return;
73
+ pending.delete(id); clearTimeout(entry.timer);
74
+ emit('ack', { command: entry.command, requestId: id, via: 'native' });
75
+ entry.resolve(value);
76
+ };
77
+ const handle = frame => {
78
+ onFrame(frame);
79
+ if (!frame || typeof frame !== 'object') throw new Error('Invalid Claude stream message.');
80
+ const parent = frame.parent_tool_use_id;
81
+ const parentFields = parent ? { parent_tool_use_id: parent } : {};
82
+ if (frame.type === 'system' && frame.subtype === 'init') {
83
+ sessionId = frame.session_id || sessionId;
84
+ const reported = Array.isArray(frame.capabilities) ? frame.capabilities : [];
85
+ Object.assign(capabilities, { reply: 'native',
86
+ interrupt: reported.includes('interrupt_receipt_v1') || reported.includes('interrupt_cancel_queued_v1') ? 'native' : 'metaharness',
87
+ answer: 'metaharness', fork: 'native', goal: 'metaharness', limits: 'native', schema: 'native', review: 'metaharness' });
88
+ initialized = true;
89
+ emit('session', { text: `Claude session ${sessionId}`, sessionId, session: sessionId,
90
+ capabilities: { ...capabilities }, nativeCapabilities: [...reported], model: frame.model });
91
+ resolveReady();
92
+ return;
93
+ }
94
+ if (frame.type === 'control_response') {
95
+ const receipt = frame.response;
96
+ const entry = pending.get(receipt?.request_id);
97
+ if (entry?.command !== 'interrupt') return;
98
+ if (receipt.subtype === 'error') {
99
+ pending.delete(receipt.request_id); clearTimeout(entry.timer);
100
+ entry.reject(new Error(receipt.error || 'Claude rejected the interrupt.'));
101
+ } else acknowledge(receipt.request_id, { ack: true, via: 'native', ...receipt.response });
102
+ return;
103
+ }
104
+ if (frame.type === 'control_request') {
105
+ if (frame.request?.subtype === 'can_use_tool') {
106
+ requests.set(frame.request_id, frame.request);
107
+ emit('approval', { text: `Approval for ${frame.request.tool_name}`, requestId: frame.request_id, request: frame.request });
108
+ }
109
+ return;
110
+ }
111
+ if (frame.type === 'system' && frame.subtype === 'api_retry') {
112
+ emit('error', { text: `API retry ${frame.attempt}/${frame.max_retries}: ${frame.error}`,
113
+ retry: true, attempt: frame.attempt, maxRetries: frame.max_retries,
114
+ retryDelayMs: frame.retry_delay_ms, errorStatus: frame.error_status });
115
+ return;
116
+ }
117
+ if (frame.type === 'system' && ['hook_started', 'hook_progress', 'hook_response'].includes(frame.subtype)) {
118
+ emit('hook', { text: frame.output || frame.hook_name || '', name: frame.hook_name,
119
+ phase: frame.subtype.slice(5), hookId: frame.hook_id, hookEvent: frame.hook_event,
120
+ outcome: frame.outcome, stdout: frame.stdout, stderr: frame.stderr, exitCode: frame.exit_code });
121
+ return;
122
+ }
123
+ if (frame.type === 'system' && frame.subtype === 'permission_denied') {
124
+ emit('error', { text: `Permission denied: ${frame.tool_name || frame.message || ''}` });
125
+ return;
126
+ }
127
+ if (frame.type === 'system' && frame.subtype === 'task_started' && frame.task_type === 'local_bash' &&
128
+ frame.is_backgrounded === true && backgroundTools.delete(frame.tool_use_id)) {
129
+ backgroundTasks.set(frame.task_id, { runId: frame.run_id, notified: false });
130
+ return;
131
+ }
132
+ if (frame.type === 'system' && frame.subtype === 'task_notification') {
133
+ const task = backgroundTasks.get(frame.task_id);
134
+ if (task && (!frame.run_id || frame.run_id === task.runId)) {
135
+ task.notified = true;
136
+ emit('task-notification', { text: frame.summary, taskId: frame.task_id, status: frame.status, sessionId });
137
+ }
138
+ return;
139
+ }
140
+ if (frame.type === 'assistant' || frame.type === 'user') {
141
+ const content = frame.message?.content;
142
+ const blocks = Array.isArray(content) ? content : typeof content === 'string' ? [{ type: 'text', text: content }] : [];
143
+ if (frame.type === 'user' && !parent && !blocks.some(block => block.type === 'tool_result')) {
144
+ // Only a replay with our UUID acknowledges delivery. Tool results and subagent
145
+ // prompts must not acknowledge a user's pending message with the same text.
146
+ if (pending.get(frame.uuid)?.command === 'reply') acknowledge(frame.uuid, { ack: true, via: 'native' });
147
+ return;
148
+ }
149
+ for (const block of blocks) {
150
+ if (frame.type === 'assistant' && block.type === 'tool_use') {
151
+ if (!parent && block.name === 'Bash' && block.input?.run_in_background === true &&
152
+ typeof block.input.command === 'string' && metaharnessCommand.test(block.input.command)) {
153
+ backgroundTools.add(block.id);
154
+ }
155
+ emit('step-start', { text: `${block.name}: ${JSON.stringify(block.input || {})}`,
156
+ toolUseId: block.id, tool: block.name, input: block.input, ...parentFields });
157
+ } else if (block.type === 'tool_result') {
158
+ emit('step-end', { text: textOf(block.content) || (block.is_error ? 'Tool returned an error' : 'Tool finished'),
159
+ toolUseId: block.tool_use_id, isError: block.is_error === true, ...parentFields });
160
+ } else if (block.type === 'text' || (parent && block.type === 'thinking')) {
161
+ const text = block.text || block.thinking || '';
162
+ if (parent) emit('subagent', { text, ...parentFields });
163
+ else if (frame.type === 'assistant') {
164
+ response += text;
165
+ emit('message', { text });
166
+ }
167
+ }
168
+ }
169
+ if (frame.error) emit('error', { text: String(frame.error), ...parentFields });
170
+ return;
171
+ }
172
+ if (frame.type === 'result') {
173
+ sessionId = frame.session_id || sessionId;
174
+ // Claude reports per-turn tokens and total spend so far for this CLI process.
175
+ const reportedCost = frame.total_cost_usd ?? processCostUsd;
176
+ usage = { inputTokens: frame.usage?.input_tokens ?? 0,
177
+ outputTokens: frame.usage?.output_tokens ?? 0, costUsd: Math.max(0, reportedCost - processCostUsd) };
178
+ processCostUsd = reportedCost;
179
+ const ok = frame.subtype === 'success' && !frame.is_error;
180
+ const error = ok ? null : frame.errors?.join('\n') || frame.result || frame.subtype || 'Claude reported failure.';
181
+ const result = { ok, response: frame.result ?? response, sessionId, usage: { ...usage },
182
+ ...(options.trackTurns ? { turns: frame.num_turns || 1 } : {}),
183
+ structured: frame.structured_output, error, failureKind: ok ? null : failureKind(error, frame.subtype) };
184
+ if (frame.origin?.kind === 'task-notification') {
185
+ const notifiedTasks = [...backgroundTasks].filter(([, task]) => task.notified);
186
+ const completedTask = frame.origin.runId ? notifiedTasks.find(([, task]) => task.runId === frame.origin.runId)
187
+ : notifiedTasks.length === 1 ? notifiedTasks[0] : undefined;
188
+ if (completedTask) backgroundTasks.delete(completedTask[0]);
189
+ }
190
+ emit('usage', { ...usage });
191
+ response = '';
192
+ if (ok && backgroundTasks.size) {
193
+ // A result can mean the agent yielded. Leave stdin open and let Claude
194
+ // deliver the native completion and run its next turn in this process.
195
+ emit('turn-finish', { text: 'Waiting for native MetaHarness background completion.', ...result });
196
+ return;
197
+ }
198
+ emit('finish', { text: ok ? 'Finished' : error, ...result });
199
+ complete(result);
200
+ return;
201
+ }
202
+ if (frame.type === 'error') emit('error', { text: String(frame.error?.message || frame.message || frame.error) });
203
+ };
204
+
205
+ function launchArgs() {
206
+ const result = [];
207
+ for (let i = 0; i < args.length; i++) {
208
+ const flag = args[i].split('=')[0];
209
+ if (ownedValues.has(flag)) { if (!args[i].includes('=')) i++; continue; }
210
+ if (ownedSwitches.has(flag)) continue;
211
+ // The MCP prompt tool must get approval requests under an operator/rules policy.
212
+ if (options.approvalPolicy && options.approvalPolicy !== 'auto') {
213
+ if (flag === '--dangerously-skip-permissions') continue;
214
+ if (flag === '--permission-mode') { if (!args[i].includes('=')) i++; continue; }
215
+ }
216
+ result.push(args[i]);
217
+ }
218
+ result.push('-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',
219
+ '--replay-user-messages', '--include-hook-events', '--forward-subagent-text');
220
+ // Print mode only: the session is not saved to disk and cannot be resumed.
221
+ if (options.ephemeral) result.push('--no-session-persistence');
222
+ if (options.resumeSession) result.push('--resume', options.sessionId);
223
+ else result.push('--session-id', sessionId);
224
+ if (options.forkSession) {
225
+ if (options.atTurn !== undefined) throw new Error('Claude CLI cannot fork at a selected turn.');
226
+ result.push('--fork-session');
227
+ result.push('--session-id', sessionId);
228
+ }
229
+ const name = options.name ?? (typeof job === 'string' ? job : job?.id ?? job?.job);
230
+ for (const [flag, value] of [['--name', name], ['--max-turns', options.maxTurns],
231
+ ['--max-budget-usd', options.maxBudgetUsd], ['--json-schema', options.resultSchema],
232
+ ['--effort', options.effort], ['--fallback-model', options.fallbackModel], ['--mcp-config', options.mcpConfig]]) {
233
+ if (value !== undefined && value !== null) result.push(flag, typeof value === 'object' ? JSON.stringify(value) : String(value));
234
+ }
235
+ result.push('--permission-prompt-tool', 'mcp__metaharness__approve');
236
+ return result;
237
+ }
238
+
239
+ return {
240
+ capabilities, get done() { return done; },
241
+ async next(text, { resultSchema, maxTurns = options.maxTurns, maxBudgetUsd = options.maxBudgetUsd } = {}) {
242
+ if (continuation) return continuation.next(text, { resultSchema, maxTurns, maxBudgetUsd });
243
+ writable();
244
+ if (!settled) throw new Error('The current turn has not finished.');
245
+ // The schema is a process flag. Reopen the same native session when a
246
+ // goal-check turn needs a different schema from the requested result.
247
+ if (JSON.stringify(resultSchema) !== JSON.stringify(options.resultSchema) || maxTurns !== options.maxTurns || maxBudgetUsd !== options.maxBudgetUsd) {
248
+ await this.close();
249
+ continuation = createClaudeDriver({ harness, binary, args, cwd, env, job, spawnFn, onEvent, onFrame, runAs,
250
+ options: { ...options, sessionId, resumeSession: true, forkSession: false, resultSchema, maxTurns, maxBudgetUsd } });
251
+ await continuation.start(text);
252
+ done = continuation.done;
253
+ return done;
254
+ }
255
+ settled = false; response = '';
256
+ done = new Promise(resolve => { resolveDone = resolve; });
257
+ write(userMessage(text));
258
+ return done;
259
+ },
260
+ async start(brief) {
261
+ if (started) return ready;
262
+ if (closing) throw new Error('Claude session is closed.');
263
+ if (typeof brief !== 'string') throw new TypeError('The brief must be text.');
264
+ started = true;
265
+ try {
266
+ child = spawnFn(binary || harness?.binary || 'claude', launchArgs(), {
267
+ cwd, env, shell: false, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'],
268
+ ...(runAs ? { uid: runAs.uid, gid: runAs.gid } : {}),
269
+ });
270
+ child.once('error', error => { fail(error); if (!child.pid) { exited = true; resolveExit(); } });
271
+ child.stdin.on('error', error => { if (!closing && !exited) fail(error); });
272
+ child.stderr.setEncoding('utf8');
273
+ child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-65536); });
274
+ lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
275
+ lines.on('line', line => {
276
+ if (!line.trim()) return;
277
+ try { handle(JSON.parse(line)); }
278
+ catch (error) { fail(new Error(`Invalid Claude stream: ${error.message}`)); signal('SIGTERM'); }
279
+ });
280
+ child.once('close', (code, signal) => {
281
+ exited = true; lines.close(); resolveExit();
282
+ const error = new Error(stderr.trim() || `Claude closed without a result (${signal || code}).`);
283
+ rejectPending(error);
284
+ if (!initialized) rejectReady(error);
285
+ if (!settled) fail(error);
286
+ });
287
+ // The CLI reads its first user message before it emits system/init.
288
+ write(userMessage(brief));
289
+ } catch (error) { exited = true; resolveExit(); fail(error); }
290
+ return ready;
291
+ },
292
+ async send(text) {
293
+ if (continuation) return continuation.send(text);
294
+ if (typeof text !== 'string') throw new TypeError('The reply must be text.');
295
+ writable();
296
+ const frame = userMessage(text);
297
+ return new Promise((resolve, reject) => {
298
+ pending.set(frame.uuid, { command: 'reply', resolve, reject });
299
+ try { write(frame); } catch (error) { pending.delete(frame.uuid); reject(error); }
300
+ });
301
+ },
302
+ async interrupt() {
303
+ if (continuation) return continuation.interrupt();
304
+ writable();
305
+ if (!initialized) throw new Error('Claude session is not live.');
306
+ if (capabilities.interrupt !== 'native') {
307
+ if (!signal('SIGTERM')) throw new Error('Cannot interrupt Claude.');
308
+ emit('ack', { command: 'interrupt', via: 'metaharness' });
309
+ return { ack: true, via: 'metaharness' };
310
+ }
311
+ const requestId = randomUUID();
312
+ return new Promise((resolve, reject) => {
313
+ const timer = setTimeout(() => { pending.delete(requestId); reject(new Error('Claude interrupt receipt timed out.')); }, 30000);
314
+ pending.set(requestId, { command: 'interrupt', resolve, reject, timer });
315
+ try { write({ type: 'control_request', request_id: requestId, request: { subtype: 'interrupt' } }); }
316
+ catch (error) { clearTimeout(timer); pending.delete(requestId); reject(error); }
317
+ });
318
+ },
319
+ async answer(requestId, value) {
320
+ if (continuation) return continuation.answer(requestId, value);
321
+ if (!requests.has(requestId)) throw new Error('No native approval has this ID. Answer MCP requests through the Metaharness inbox.');
322
+ write({ type: 'control_response', response: { subtype: 'success', request_id: requestId, response: value } });
323
+ requests.delete(requestId);
324
+ emit('ack', { command: 'approve', requestId, via: 'native' });
325
+ return { ack: true, via: 'native' };
326
+ },
327
+ async fork({ atTurn } = {}) {
328
+ if (continuation) return continuation.fork({ atTurn });
329
+ if (!initialized) throw new Error('Claude session is not live.');
330
+ if (atTurn !== undefined) throw new Error('Claude CLI cannot fork at a selected turn.');
331
+ const fork = createClaudeDriver({ harness, binary, args,
332
+ cwd, env, job, options: { ...options, sessionId, resumeSession: true, forkSession: true }, spawnFn, runAs });
333
+ try {
334
+ // /rename is a documented local print-mode command. It materializes the fork
335
+ // without replaying the brief or asking a model to do more work.
336
+ await fork.start(`/rename ${options.name || 'Metaharness fork'}`);
337
+ const result = await fork.done;
338
+ if (!result.ok) throw new Error(result.error);
339
+ return { sessionId: result.sessionId };
340
+ } finally { await fork.close(); }
341
+ },
342
+ async close() {
343
+ if (continuation) return continuation.close();
344
+ if (closePromise) return closePromise;
345
+ closing = true;
346
+ rejectPending(new Error('Claude session is closed.'));
347
+ if (!started) { exited = true; rejectReady(new Error('Claude session is closed.')); complete({ error: 'Claude session was not started.', failureKind: 'agent' }); resolveExit(); }
348
+ closePromise = (async () => {
349
+ if (exited) return;
350
+ child.stdin.end();
351
+ const term = setTimeout(() => signal('SIGTERM'), 1000);
352
+ const kill = setTimeout(() => signal('SIGKILL'), 2000);
353
+ try { await exit; } finally { signal('SIGKILL'); clearTimeout(term); clearTimeout(kill); }
354
+ })();
355
+ return closePromise;
356
+ },
357
+ };
358
+ }