tr-plugin-meta-harness 0.3.0 → 0.5.27
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/DESIGN.md +86 -0
- package/README.md +257 -11
- package/capability/BRICK.md +1 -1
- package/capability/index.mjs +154 -13
- package/cli.mjs +426 -41
- package/package.json +15 -3
- package/plugin.json +1457 -119
- package/skills/meta-harness/SKILL.md +63 -25
- package/src/adoption.mjs +102 -0
- package/src/agent-user.mjs +194 -0
- package/src/alerts.mjs +220 -14
- package/src/cascade.mjs +185 -0
- package/src/chat.mjs +80 -0
- package/src/codex-models.mjs +54 -0
- package/src/compat-harness.mjs +117 -0
- package/src/control.mjs +145 -0
- package/src/coordinator.mjs +267 -358
- package/src/dispatch-request.mjs +76 -0
- package/src/dispatch.mjs +119 -0
- package/src/documentation-authority.mjs +57 -0
- package/src/documentation.mjs +120 -32
- package/src/executor.mjs +101 -22
- package/src/gate-adapters/agy.mjs +155 -0
- package/src/gate-adapters/claude.mjs +303 -0
- package/src/gate-adapters/cline.mjs +111 -0
- package/src/gate-adapters/codex.mjs +164 -0
- package/src/gate-adapters/cursor.mjs +164 -0
- package/src/gate-adapters/devin.mjs +116 -0
- package/src/gate-adapters/dsh.mjs +284 -0
- package/src/gate-adapters/grok.mjs +112 -0
- package/src/gate-adapters/hermes.mjs +217 -0
- package/src/gate-adapters/hook-files.mjs +156 -0
- package/src/gate-adapters/index.mjs +131 -0
- package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
- package/src/gate-adapters/openclaw-plugin/index.js +25 -0
- package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
- package/src/gate-adapters/openclaw-plugin/package.json +15 -0
- package/src/gate-adapters/openclaw.mjs +288 -0
- package/src/gate-adapters/pi.mjs +146 -0
- package/src/gate.mjs +18 -0
- package/src/harness-updates.mjs +170 -0
- package/src/included-usage.mjs +344 -0
- package/src/jobs.mjs +135 -0
- package/src/json-reply.mjs +22 -0
- package/src/learner.mjs +97 -67
- package/src/maintenance.mjs +18 -0
- package/src/mcp-server.mjs +228 -0
- package/src/model-catalog.mjs +195 -0
- package/src/model-selection.mjs +67 -0
- package/src/paths.mjs +23 -0
- package/src/pool.mjs +69 -0
- package/src/process-manager.mjs +246 -0
- package/src/process-worker.mjs +18 -0
- package/src/reasoning.mjs +231 -0
- package/src/remote-operation.mjs +76 -0
- package/src/review.mjs +241 -0
- package/src/reviews.mjs +25 -0
- package/src/router-benchmark-corpus.mjs +16 -0
- package/src/router-benchmark.mjs +208 -0
- package/src/router.mjs +265 -346
- package/src/runtime.mjs +30 -8
- package/src/session/claude.mjs +358 -0
- package/src/session/codex.mjs +501 -0
- package/src/session/result.mjs +90 -0
- package/src/session/resume.mjs +393 -0
- package/src/session/run.mjs +258 -0
- package/src/session-jobs.mjs +77 -0
- package/src/setup.mjs +6 -3
- package/src/ssss-store.mjs +20 -0
- package/src/telemetry.mjs +267 -0
- package/src/termination.mjs +28 -0
- package/src/threads.mjs +150 -0
- package/src/usage-queue.mjs +137 -0
- package/src/verify-ssss.mjs +102 -0
- package/src/worker.mjs +955 -84
- package/src/worktree.mjs +244 -0
- package/ui/chunks/adapter-docs-freshness.md +16 -0
- package/ui/chunks/chat-handoff.md +26 -0
- package/ui/chunks/fleet-maintenance.md +21 -0
- package/ui/chunks/harness-inventory.md +21 -0
- package/ui/chunks/included-access.md +18 -0
- package/ui/chunks/included-usage-verification.md +15 -0
- package/ui/chunks/independent-review.md +17 -0
- package/ui/chunks/managed-execution.md +20 -0
- package/ui/chunks/official-documentation.md +18 -0
- package/ui/chunks/quota-recovery.md +21 -0
- package/ui/chunks/review-routing-decision.md +16 -0
- package/ui/chunks/route-work.md +18 -0
- package/ui/chunks/routing-evidence.md +18 -0
- package/ui/chunks/run-ledger.md +18 -0
- package/ui/chunks/session-controls.md +16 -0
- package/ui/home.js +198 -0
- package/ui/DESIGN.md +0 -32
- package/ui/card.js +0 -845
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
/** One-shot harness sessions. Portable: this module uses Node built-ins only. */
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
8
|
+
|
|
9
|
+
// Match the one-shot adapters in worker.mjs. Callers can supply their prepared
|
|
10
|
+
// args (model, permissions and provider settings), without the prompt operand.
|
|
11
|
+
const COMMANDS = {
|
|
12
|
+
agy: ['--mode', 'accept-edits', '--sandbox', '--output-format', 'json', '-p'],
|
|
13
|
+
cursor: ['--print', '--output-format', 'json'],
|
|
14
|
+
dsh: ['--profile', 'headless', '--json', '-'],
|
|
15
|
+
grok: ['--output-format', 'json', '-p'],
|
|
16
|
+
muse: ['exec', '--json'],
|
|
17
|
+
pi: ['--print', '--mode', 'json', '--provider', 'openrouter', '--tools', 'read,bash', '--no-extensions'],
|
|
18
|
+
hermes: ['chat', '--oneshot', '--format', 'stream-json', '--query-file', '-'],
|
|
19
|
+
openclaw: ['agent', '--message'],
|
|
20
|
+
aider: ['--yes', '--message'],
|
|
21
|
+
goose: ['run', '--text'],
|
|
22
|
+
openhands: ['--headless', '--json', '--task'],
|
|
23
|
+
cline: ['--json'],
|
|
24
|
+
ollama: ['run'],
|
|
25
|
+
};
|
|
26
|
+
const STDIN = new Set(['dsh', 'pi', 'hermes', 'ollama']);
|
|
27
|
+
const PLAIN = new Set(['ollama', 'aider', 'goose']);
|
|
28
|
+
// Verified 2026-11-09. No "latest" selectors: parallel jobs must not share state.
|
|
29
|
+
// antigravity.google/docs/cli/reference/; cursor.com/docs/cli/reference/parameters
|
|
30
|
+
// docs.x.ai/build/cli/reference; dev.meta.ai/docs/muse-code/extending
|
|
31
|
+
// github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/cli.md
|
|
32
|
+
// github.com/NousResearch/hermes-agent/blob/main/website/docs/reference/cli-commands.md
|
|
33
|
+
// docs.openclaw.ai/cli/agent; aider.chat/docs/config/options.html
|
|
34
|
+
// goose-docs.ai/docs/guides/goose-cli-commands/
|
|
35
|
+
// github.com/OpenHands/OpenHands-CLI; github.com/cline/cline/blob/main/docs/cli/cli-reference.mdx
|
|
36
|
+
const SELECTOR = { agy: '--conversation', cursor: '--resume', grok: '--resume',
|
|
37
|
+
muse: '--session-id', pi: '--session', hermes: '--resume', openclaw: '--session-id',
|
|
38
|
+
cline: '--id', openhands: '--resume' };
|
|
39
|
+
const emptyUsage = () => ({ inputTokens: null, outputTokens: null, costUsd: null });
|
|
40
|
+
const number = (...values) => values.find(value => typeof value === 'number' && Number.isFinite(value) && value >= 0) ?? null;
|
|
41
|
+
const sumUsage = (a, b) => Object.fromEntries(Object.keys(a).map(key => [key,
|
|
42
|
+
a[key] === null && b[key] === null ? null : (a[key] ?? 0) + (b[key] ?? 0)]));
|
|
43
|
+
const usageOf = value => ({
|
|
44
|
+
inputTokens: number(value?.inputTokens, value?.input_tokens, value?.input),
|
|
45
|
+
outputTokens: number(value?.outputTokens, value?.output_tokens, value?.output),
|
|
46
|
+
costUsd: number(value?.costUsd, value?.cost_usd, value?.total_cost_usd, value?.cost?.total),
|
|
47
|
+
});
|
|
48
|
+
const textOf = content => typeof content === 'string' ? content : Array.isArray(content)
|
|
49
|
+
? content.filter(part => part?.type === 'text').map(part => part.text || '').join('\n') : '';
|
|
50
|
+
const errorText = value => typeof value === 'string' ? value : value?.message;
|
|
51
|
+
const failureKind = text => /quota|rate.?limit|resource_exhausted|\b429\b|insufficient credits/i.test(text) ? 'quota'
|
|
52
|
+
: /not logged in|unauthenticated|\b401\b|invalid api key/i.test(text) ? 'auth' : 'agent';
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* `args` are the existing one-shot command, before prompt injection. Unknown
|
|
56
|
+
* adapters may pass { id, input } as harness. Their controls stay unsupported.
|
|
57
|
+
* Queued replies are returned in done.pendingMessages and job.pendingMessages,
|
|
58
|
+
* so the next attempt can carry them without pretending they were delivered.
|
|
59
|
+
*/
|
|
60
|
+
export function createResumeDriver({ harness, binary, args = [], cwd, env, job,
|
|
61
|
+
options = {}, onEvent = () => {}, onFrame = () => {}, spawnFn = spawn }) {
|
|
62
|
+
for (const key of ['maxTurns', 'maxTokens', 'maxBudgetUsd']) {
|
|
63
|
+
const value = options[key];
|
|
64
|
+
if (value != null && (typeof value !== 'number' || !Number.isFinite(value) || value < 0 ||
|
|
65
|
+
(key !== 'maxBudgetUsd' && !Number.isInteger(value)))) throw new Error(`Invalid ${key}.`);
|
|
66
|
+
}
|
|
67
|
+
const id = typeof harness === 'string' ? harness : harness?.id;
|
|
68
|
+
const inputMode = harness?.input || (STDIN.has(id) ? 'stdin' : id === 'muse' ? 'file' : 'argument');
|
|
69
|
+
const baseArgs = [...(args.length ? args : COMMANDS[id] || [])];
|
|
70
|
+
const knownResume = Boolean(SELECTOR[id] || ['aider', 'goose'].includes(id));
|
|
71
|
+
const canFork = ['grok', 'pi'].includes(id);
|
|
72
|
+
const pendingMessages = Array.isArray(job?.pendingMessages)
|
|
73
|
+
? job.pendingMessages.filter(item => typeof item?.text === 'string').map(item => ({ ...item })) : [];
|
|
74
|
+
let sessionId = options.sessionId || null, active = null, settled = false, closed = false, closeRequested = false;
|
|
75
|
+
let started = false, directory, totalUsage = emptyUsage(), totalTurns = 0, limitError;
|
|
76
|
+
let resolveDone, controls = Promise.resolve(), lastResponse;
|
|
77
|
+
let done = new Promise(resolve => { resolveDone = resolve; });
|
|
78
|
+
const capabilities = { reply: 'unsupported', interrupt: 'metaharness', answer: 'unsupported',
|
|
79
|
+
fork: 'unsupported', goal: 'unsupported', limits: 'metaharness', schema: 'unsupported', review: 'unsupported' };
|
|
80
|
+
const emit = event => { try { onEvent(event); } catch { /* A view cannot stop a job. */ } };
|
|
81
|
+
const refresh = () => {
|
|
82
|
+
const resume = knownResume && Boolean(sessionId);
|
|
83
|
+
capabilities.reply = capabilities.answer = resume ? 'metaharness' : 'unsupported';
|
|
84
|
+
capabilities.fork = resume && canFork ? 'metaharness' : 'unsupported';
|
|
85
|
+
};
|
|
86
|
+
const setSession = value => {
|
|
87
|
+
if (typeof value !== 'string' || !value) return;
|
|
88
|
+
active?.sessionReady?.(value);
|
|
89
|
+
if (value === sessionId) return;
|
|
90
|
+
sessionId = value; refresh();
|
|
91
|
+
emit({ kind: 'session', text: `${id} session ${value}`, sessionId: value, session: value });
|
|
92
|
+
};
|
|
93
|
+
const resultUsage = () => sumUsage(totalUsage, active?.usage || emptyUsage());
|
|
94
|
+
const finish = result => {
|
|
95
|
+
if (settled) return;
|
|
96
|
+
settled = true;
|
|
97
|
+
if (directory) fs.rmSync(directory, { recursive: true, force: true });
|
|
98
|
+
const value = { response: null, structured: null, error: null, failureKind: null, ...result,
|
|
99
|
+
sessionId, usage: resultUsage(), ...(pendingMessages.length ? { pendingMessages: [...pendingMessages] } : {}) };
|
|
100
|
+
lastResponse = value.response;
|
|
101
|
+
emit({ kind: 'finish', text: value.ok ? 'Finished' : value.error, ...value });
|
|
102
|
+
resolveDone(value);
|
|
103
|
+
};
|
|
104
|
+
const serialize = action => {
|
|
105
|
+
const next = controls.then(action);
|
|
106
|
+
controls = next.catch(() => {});
|
|
107
|
+
return next;
|
|
108
|
+
};
|
|
109
|
+
const checkOpen = () => { if (closed || closeRequested || settled) throw new Error('The session is closed.'); };
|
|
110
|
+
const signal = (run, name) => {
|
|
111
|
+
try {
|
|
112
|
+
if (process.platform !== 'win32' && run.child.pid) process.kill(-run.child.pid, name);
|
|
113
|
+
else run.child.kill(name);
|
|
114
|
+
} catch { /* It may have exited. */ }
|
|
115
|
+
};
|
|
116
|
+
const stop = async reason => {
|
|
117
|
+
const run = active;
|
|
118
|
+
if (!run || run.exited) return;
|
|
119
|
+
run.stopReason ||= reason;
|
|
120
|
+
signal(run, 'SIGTERM');
|
|
121
|
+
// Wait for close (all output drained) before a replacement can start.
|
|
122
|
+
// Harnesses write their final result (session id, usage) after SIGTERM; give them time on a busy machine.
|
|
123
|
+
const timer = setTimeout(() => signal(run, 'SIGKILL'), options.stopGraceMs ?? 5000);
|
|
124
|
+
try { await run.exit; } finally {
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
// A descendant can keep running after its parent exits on SIGTERM.
|
|
127
|
+
if (process.platform !== 'win32') signal(run, 'SIGKILL');
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
const checkLimits = () => {
|
|
131
|
+
const usage = resultUsage();
|
|
132
|
+
const turns = totalTurns + (active?.turns || 0);
|
|
133
|
+
const cap = options.maxTokens != null && (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0) >= options.maxTokens ? 'token'
|
|
134
|
+
: options.maxBudgetUsd != null && (usage.costUsd ?? 0) >= options.maxBudgetUsd ? 'budget'
|
|
135
|
+
: options.maxTurns != null && turns >= options.maxTurns ? 'turn' : null;
|
|
136
|
+
if (cap && !limitError) {
|
|
137
|
+
limitError = `Metaharness ${cap} limit reached.`;
|
|
138
|
+
void stop('limit').then(() => finish({ ok: false, error: limitError, failureKind: 'limit' }));
|
|
139
|
+
}
|
|
140
|
+
return Boolean(limitError);
|
|
141
|
+
};
|
|
142
|
+
const frame = (run, value) => {
|
|
143
|
+
onFrame(value);
|
|
144
|
+
if (!value || typeof value !== 'object') return;
|
|
145
|
+
if (Array.isArray(value)) { for (const item of value) frame(run, item); return; }
|
|
146
|
+
run.frames.push(value);
|
|
147
|
+
const agentMeta = value.result?.meta?.agentMeta || value.meta?.agentMeta || value.payload?.meta?.agentMeta;
|
|
148
|
+
setSession(value.session_id || value.sessionId || value.conversation_id || value.conversationId ||
|
|
149
|
+
(value.type === 'session' ? value.id : null) || agentMeta?.sessionId);
|
|
150
|
+
const type = value.type;
|
|
151
|
+
const message = value.message;
|
|
152
|
+
// dsh reports a turn end as a status phase and starts tools with tool_call.
|
|
153
|
+
const dshPhase = id === 'dsh' && type === 'status' ? value.phase : null;
|
|
154
|
+
if (['turn_start', 'turn.started'].includes(type)) emit({ kind: 'step-start', text: 'Turn started' });
|
|
155
|
+
if (['tool_use', 'tool_execution_start'].includes(type)) emit({ kind: 'step-start', text: value.name || value.toolName || 'Tool started' });
|
|
156
|
+
if (type === 'tool_call' && id === 'dsh') emit({ kind: 'step-start', text: value.tool || value.name || 'Tool started' });
|
|
157
|
+
if (['tool_result', 'tool_execution_end'].includes(type)) emit({ kind: 'step-end', text: value.name || value.toolName || 'Tool finished' });
|
|
158
|
+
const text = type === 'text' ? value.text : type === 'message_update' ? value.assistantMessageEvent?.delta
|
|
159
|
+
: type === 'message_end' && message?.role === 'assistant' ? textOf(message.content) : null;
|
|
160
|
+
if (text) emit({ kind: 'message', text });
|
|
161
|
+
if (type === 'turn_end') { run.turns += 1; emit({ kind: 'step-end', text: 'Turn finished' }); }
|
|
162
|
+
if (dshPhase === 'turn_end') { run.turns += 1; emit({ kind: 'step-end', text: 'Turn finished' }); }
|
|
163
|
+
if (typeof value.num_turns === 'number') run.turns = Math.max(run.turns, value.num_turns);
|
|
164
|
+
const error = errorText(value.error) || (value.is_error ? value.result : null);
|
|
165
|
+
if (error || type === 'error') { run.error = String(error || value.message || 'Agent failed'); emit({ kind: 'error', text: run.error }); }
|
|
166
|
+
if (value.structured_output !== undefined) run.structured = value.structured_output;
|
|
167
|
+
|
|
168
|
+
// Pi usage is cumulative within a message; agent_end repeats completed
|
|
169
|
+
// messages. Do not add both the updates and the final snapshot.
|
|
170
|
+
let usage;
|
|
171
|
+
if (id === 'pi') {
|
|
172
|
+
if (type === 'message_start' && message?.role === 'assistant') run.partialUsage = emptyUsage();
|
|
173
|
+
if (type === 'message_update' && value.usage) run.partialUsage = usageOf(value.usage);
|
|
174
|
+
if (type === 'message_end' && message?.role === 'assistant') {
|
|
175
|
+
run.messageUsage = sumUsage(run.messageUsage, usageOf(message.usage));
|
|
176
|
+
run.partialUsage = emptyUsage();
|
|
177
|
+
}
|
|
178
|
+
if (type === 'agent_end' && Array.isArray(value.messages)) {
|
|
179
|
+
// agent_end covers one low-level run; message_end remains authoritative
|
|
180
|
+
// when it was observed, including across automatic retries.
|
|
181
|
+
if (!run.sawMessageUsage) run.messageUsage = value.messages.filter(m => m.role === 'assistant')
|
|
182
|
+
.reduce((sum, m) => sumUsage(sum, usageOf(m.usage)), emptyUsage());
|
|
183
|
+
}
|
|
184
|
+
if (type === 'message_end' && message?.role === 'assistant') run.sawMessageUsage = true;
|
|
185
|
+
usage = sumUsage(run.messageUsage, run.partialUsage);
|
|
186
|
+
} else if (id === 'dsh') {
|
|
187
|
+
// dsh reports each step's own usage; cache reads are separate and uncounted.
|
|
188
|
+
if (dshPhase === 'step_end') {
|
|
189
|
+
run.stepUsage = sumUsage(run.stepUsage, usageOf(value.usage));
|
|
190
|
+
usage = run.stepUsage;
|
|
191
|
+
}
|
|
192
|
+
} else if (value.usage || value.tokens || value.total_cost_usd !== undefined || agentMeta?.usage) {
|
|
193
|
+
usage = usageOf(value.usage || value.tokens || agentMeta?.usage);
|
|
194
|
+
usage.costUsd = number(value.total_cost_usd, value.costUsd, usage.costUsd);
|
|
195
|
+
}
|
|
196
|
+
if (usage && Object.values(usage).some(n => n !== null)) {
|
|
197
|
+
run.usage = { ...run.usage, ...Object.fromEntries(Object.entries(usage).filter(([, n]) => n !== null)) };
|
|
198
|
+
emit({ kind: 'usage', text: 'Usage reported', ...resultUsage() });
|
|
199
|
+
}
|
|
200
|
+
checkLimits();
|
|
201
|
+
};
|
|
202
|
+
const queue = (text, command, requestId) => {
|
|
203
|
+
pendingMessages.push({ command, text, ...(requestId === undefined ? {} : { requestId }) });
|
|
204
|
+
if (job && typeof job === 'object') job.pendingMessages = [...pendingMessages];
|
|
205
|
+
const ack = { ack: true, via: 'metaharness', queued: true, reply: 'unsupported' };
|
|
206
|
+
emit({ kind: 'ack', text: 'Queued for the next attempt; this harness cannot resume this session.', command, ...ack });
|
|
207
|
+
return ack;
|
|
208
|
+
};
|
|
209
|
+
const launch = async (text, { resume = false, fork = false } = {}) => {
|
|
210
|
+
checkOpen();
|
|
211
|
+
if (checkLimits()) return;
|
|
212
|
+
directory ||= fs.mkdtempSync(path.join(os.tmpdir(), 'metaharness-resume-'));
|
|
213
|
+
let argv = [...baseArgs], extra = [];
|
|
214
|
+
if (resume) {
|
|
215
|
+
// Remove an earlier selector before setting the exact saved session.
|
|
216
|
+
const selectors = new Set(['--conversation', '--resume', '--session', '--session-id', '--id']);
|
|
217
|
+
argv = argv.filter((arg, i, all) => !selectors.has(arg) && !selectors.has(all[i - 1]));
|
|
218
|
+
if (id === 'aider') extra.push('--restore-chat-history');
|
|
219
|
+
else if (id === 'goose') extra.push('--resume', '--name', sessionId);
|
|
220
|
+
else extra.push(SELECTOR[id], sessionId);
|
|
221
|
+
if (fork) {
|
|
222
|
+
if (id === 'pi') extra = ['--fork', sessionId];
|
|
223
|
+
else extra.push('--fork-session');
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (id === 'aider') {
|
|
227
|
+
const history = argv.indexOf('--chat-history-file');
|
|
228
|
+
if (history >= 0) sessionId = argv[history + 1];
|
|
229
|
+
else {
|
|
230
|
+
sessionId ||= path.join(os.tmpdir(), `metaharness-aider-${randomUUID()}.history.md`);
|
|
231
|
+
extra.push('--chat-history-file', sessionId);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (id === 'goose' && !resume) { sessionId ||= `metaharness-${randomUUID()}`; extra.push('--name', sessionId); }
|
|
235
|
+
if (['grok', 'openclaw'].includes(id) && !resume && !argv.includes('--session-id')) {
|
|
236
|
+
sessionId ||= randomUUID(); extra.push('--session-id', sessionId);
|
|
237
|
+
}
|
|
238
|
+
refresh();
|
|
239
|
+
// The worker supplies an unfilled prompt option. Keep its operand next to
|
|
240
|
+
// it even when provider or model options were appended to the command.
|
|
241
|
+
const promptOption = ['agy', 'grok'].includes(id) ? '-p'
|
|
242
|
+
: ['openclaw', 'aider'].includes(id) ? '--message' : id === 'goose' ? '--text' : id === 'openhands' ? '--task' : null;
|
|
243
|
+
if (promptOption) argv = argv.filter(arg => arg !== promptOption);
|
|
244
|
+
argv.push(...extra);
|
|
245
|
+
const prompt = [text, ...pendingMessages.splice(0).map(item => item.text)].join('\n\n');
|
|
246
|
+
if (job && typeof job === 'object') job.pendingMessages = [];
|
|
247
|
+
if (inputMode === 'file') {
|
|
248
|
+
const file = path.join(directory, `${randomUUID()}.txt`);
|
|
249
|
+
fs.writeFileSync(file, prompt, { mode: 0o600 }); argv.push('--prompt-file', file);
|
|
250
|
+
} else if (inputMode !== 'stdin') argv.push(...(promptOption ? [promptOption] : []), prompt);
|
|
251
|
+
let child;
|
|
252
|
+
try { child = spawnFn(binary, argv, { cwd, env, shell: false, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] }); }
|
|
253
|
+
catch (error) { finish({ ok: false, error: error.message, failureKind: 'process' }); throw error; }
|
|
254
|
+
let resolveExit, resolveSession;
|
|
255
|
+
const run = { child, awaitingHeader: ['pi', 'hermes'].includes(id), frames: [], stdout: '', stderr: '', buffer: '', bytes: 0, turns: 0,
|
|
256
|
+
usage: emptyUsage(), messageUsage: emptyUsage(), partialUsage: emptyUsage(), stepUsage: emptyUsage(),
|
|
257
|
+
exit: new Promise(resolve => { resolveExit = resolve; }),
|
|
258
|
+
session: new Promise(resolve => { resolveSession = resolve; }), sessionReady: value => resolveSession(value) };
|
|
259
|
+
active = run;
|
|
260
|
+
const decoder = new StringDecoder('utf8');
|
|
261
|
+
const line = text => { try { frame(run, JSON.parse(text)); } catch { /* Plain output is valid for some adapters. */ } };
|
|
262
|
+
const collect = chunk => {
|
|
263
|
+
run.bytes += chunk.length;
|
|
264
|
+
if (run.bytes > 32 * 1024 * 1024) { void stop('output-limit'); return; }
|
|
265
|
+
const text = decoder.write(chunk); run.stdout += text; run.buffer += text;
|
|
266
|
+
let end;
|
|
267
|
+
while ((end = run.buffer.indexOf('\n')) >= 0) { line(run.buffer.slice(0, end)); run.buffer = run.buffer.slice(end + 1); }
|
|
268
|
+
};
|
|
269
|
+
child.stdout.on('data', collect);
|
|
270
|
+
child.stderr.on('data', chunk => { run.stderr = (run.stderr + chunk).slice(-8000); });
|
|
271
|
+
child.stdin.on('error', () => {});
|
|
272
|
+
const exit = (code, signalName) => {
|
|
273
|
+
if (run.exited) return;
|
|
274
|
+
run.buffer += decoder.end();
|
|
275
|
+
if (run.buffer.trim()) line(run.buffer);
|
|
276
|
+
// Pretty-printed JSON is not JSONL.
|
|
277
|
+
if (!run.frames.length) { try { frame(run, JSON.parse(run.stdout)); } catch {} }
|
|
278
|
+
run.exited = true;
|
|
279
|
+
if (!run.turns) run.turns = 1;
|
|
280
|
+
checkLimits();
|
|
281
|
+
totalUsage = sumUsage(totalUsage, run.usage); totalTurns += run.turns;
|
|
282
|
+
active = null; resolveSession(null); resolveExit();
|
|
283
|
+
if (limitError) { finish({ ok: false, error: limitError, failureKind: 'limit' }); return; }
|
|
284
|
+
if (['replace', 'interrupt'].includes(run.stopReason)) return;
|
|
285
|
+
if (run.stopReason === 'close') { finish({ ok: false, error: 'Session closed.', failureKind: 'cancelled' }); return; }
|
|
286
|
+
const frames = run.frames, last = frames.at(-1);
|
|
287
|
+
const clineResult = id === 'cline' && !harness?.custom ? frames.findLast(event => event.type === 'run_result') : null;
|
|
288
|
+
const openHands = id === 'openhands' && !harness?.custom;
|
|
289
|
+
const openHandsMessage = openHands ? frames.findLast(event => event.kind === 'MessageEvent' &&
|
|
290
|
+
event.source === 'agent' && event.llm_message?.role === 'assistant') : null;
|
|
291
|
+
if (openHands) setSession(run.stdout.match(/^Conversation ID: ([\da-f]{32})\s*$/im)?.[1]);
|
|
292
|
+
const agentError = run.error || (last?.exit_code ? `Agent exited ${last.exit_code}` : null) ||
|
|
293
|
+
(['FAILED', 'ERROR', 'CANCELED', 'WAITING'].includes(last?.status) ? last.status : null) ||
|
|
294
|
+
(last?.messages?.some(m => ['error', 'aborted'].includes(m.stopReason)) ? 'Agent turn failed' : null) ||
|
|
295
|
+
(clineResult && clineResult.finishReason !== 'completed' ? `Cline run ended: ${clineResult.finishReason || 'unknown'}` : null);
|
|
296
|
+
let response = last?.result ?? last?.response ?? last?.text;
|
|
297
|
+
if (id === 'cline' && !harness?.custom) response = clineResult?.text;
|
|
298
|
+
// The installed OpenHands CLI mixes SDK events with display text. It writes
|
|
299
|
+
// this marker after conversation.run() returns, even when stdout is piped.
|
|
300
|
+
if (openHands) response = /^Agent finished\r?$/m.test(run.stdout) ? textOf(openHandsMessage?.llm_message.content) : null;
|
|
301
|
+
if (id === 'pi') response = frames.filter(f => f.type === 'agent_end').flatMap(f => f.messages || [])
|
|
302
|
+
.filter(m => m.role === 'assistant').map(m => textOf(m.content)).join('\n');
|
|
303
|
+
if (id === 'openclaw') response = (last?.result?.payloads || last?.payload?.payloads || last?.payloads || []).map(p => p.text || '').join('\n') || response;
|
|
304
|
+
if (PLAIN.has(id) || id === 'muse' || !COMMANDS[id] || harness?.custom) response ||= run.stdout.trim();
|
|
305
|
+
const error = run.spawnError || agentError || (run.stopReason ? `Agent stopped: ${run.stopReason}` : null) ||
|
|
306
|
+
(code !== 0 ? run.stderr.trim() || `Agent process exited ${code ?? signalName}` : null) ||
|
|
307
|
+
(typeof response !== 'string' || !response.trim() ? 'Agent returned no completed result.' : null);
|
|
308
|
+
finish({ ok: !error, response: typeof response === 'string' ? response : null, structured: run.structured ?? null,
|
|
309
|
+
...(options.captureExecution ? { execution: { stdout: run.stdout, stderr: run.stderr, exitCode: code } } : {}),
|
|
310
|
+
error, failureKind: error ? run.spawnError || run.stopReason ? 'process' : failureKind(error) : null });
|
|
311
|
+
};
|
|
312
|
+
child.once('close', exit);
|
|
313
|
+
const live = new Promise((resolve, reject) => {
|
|
314
|
+
child.once('spawn', resolve);
|
|
315
|
+
child.once('error', error => { run.spawnError = error.message; exit(null); reject(error); });
|
|
316
|
+
});
|
|
317
|
+
child.stdin.end(inputMode === 'stdin' ? prompt : '');
|
|
318
|
+
await live;
|
|
319
|
+
// These streams have a documented session header. Wait until the resumed
|
|
320
|
+
// process has read its input before accepting another replacement.
|
|
321
|
+
if (run.awaitingHeader) await run.session;
|
|
322
|
+
run.awaitingHeader = false;
|
|
323
|
+
return run;
|
|
324
|
+
};
|
|
325
|
+
refresh();
|
|
326
|
+
const deliver = (text, command, requestId) => serialize(async () => {
|
|
327
|
+
checkOpen();
|
|
328
|
+
if (typeof text !== 'string' || !text.trim()) throw new Error('A non-empty message is required.');
|
|
329
|
+
if (!knownResume || !started) return queue(text, command, requestId);
|
|
330
|
+
await stop('replace');
|
|
331
|
+
if (settled || limitError) throw new Error(limitError || 'The session has finished.');
|
|
332
|
+
// JSON-only harnesses may report their ID only while shutting down. Read
|
|
333
|
+
// that final output before deciding whether this session can be resumed.
|
|
334
|
+
if (!sessionId) {
|
|
335
|
+
const ack = queue(text, command, requestId);
|
|
336
|
+
finish({ ok: false, error: 'The harness did not report a resumable session ID.', failureKind: 'process' });
|
|
337
|
+
return ack;
|
|
338
|
+
}
|
|
339
|
+
await launch(text, { resume: true });
|
|
340
|
+
const ack = { ack: true, via: 'metaharness' };
|
|
341
|
+
emit({ kind: 'ack', text: 'Resumed with the message.', command, ...ack });
|
|
342
|
+
return ack;
|
|
343
|
+
});
|
|
344
|
+
return {
|
|
345
|
+
capabilities,
|
|
346
|
+
start: brief => serialize(async () => {
|
|
347
|
+
checkOpen();
|
|
348
|
+
if (active || started) throw new Error('The session has already started.');
|
|
349
|
+
if (typeof brief !== 'string' || !brief.trim()) throw new Error('A non-empty brief is required.');
|
|
350
|
+
started = true;
|
|
351
|
+
if (options.sessionId && !knownResume) throw new Error('Resume is unsupported for this harness.');
|
|
352
|
+
if (options.forkSession && (!canFork || options.atTurn !== undefined)) throw new Error('Fork is unsupported for this harness or turn.');
|
|
353
|
+
await launch(brief, { resume: Boolean(options.sessionId && knownResume), fork: options.forkSession === true });
|
|
354
|
+
}),
|
|
355
|
+
send: text => deliver(text, 'send'),
|
|
356
|
+
answer: (requestId, value) => deliver(typeof value === 'string' ? value : JSON.stringify(value), 'answer', requestId),
|
|
357
|
+
interrupt: () => {
|
|
358
|
+
// A startup hook can wait before the header. It must remain stoppable
|
|
359
|
+
// while start() is waiting, rather than blocking behind that wait.
|
|
360
|
+
const startup = active?.awaitingHeader ? stop('interrupt') : null;
|
|
361
|
+
return serialize(async () => { checkOpen(); await startup; await stop('interrupt'); emit({ kind: 'ack', text: 'Interrupted.', command: 'interrupt' }); });
|
|
362
|
+
},
|
|
363
|
+
fork: ({ atTurn } = {}) => serialize(async () => {
|
|
364
|
+
checkOpen();
|
|
365
|
+
if (capabilities.fork === 'unsupported' || atTurn !== undefined) throw new Error('Fork is unsupported for this harness or turn.');
|
|
366
|
+
await stop('replace');
|
|
367
|
+
const previous = sessionId;
|
|
368
|
+
const run = await launch('Continue from this session.', { resume: true, fork: true });
|
|
369
|
+
const forked = await run?.session;
|
|
370
|
+
if (!forked || forked === previous) throw new Error('The harness did not report a forked session ID.');
|
|
371
|
+
return { sessionId: forked };
|
|
372
|
+
}),
|
|
373
|
+
close: () => {
|
|
374
|
+
closeRequested = true;
|
|
375
|
+
const startup = active?.awaitingHeader ? stop('close') : null;
|
|
376
|
+
return serialize(async () => {
|
|
377
|
+
if (closed) return;
|
|
378
|
+
closed = true; await startup; await stop('close');
|
|
379
|
+
if (!settled) finish({ ok: false, error: 'Session closed.', failureKind: 'cancelled' });
|
|
380
|
+
});
|
|
381
|
+
},
|
|
382
|
+
get done() { return done; },
|
|
383
|
+
next: async text => {
|
|
384
|
+
await serialize(async () => {
|
|
385
|
+
if (!settled || closed || closeRequested) throw new Error('The session is not ready for another turn.');
|
|
386
|
+
settled = false;
|
|
387
|
+
done = new Promise(resolve => { resolveDone = resolve; });
|
|
388
|
+
await launch(knownResume && sessionId ? text : `Previous result:\n${lastResponse}\n\n${text}`, { resume: Boolean(knownResume && sessionId) });
|
|
389
|
+
});
|
|
390
|
+
return done;
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
}
|