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.
- 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 +114 -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,501 @@
|
|
|
1
|
+
/** Codex app-server session. Only Node built-ins may be shipped to a remote node.
|
|
2
|
+
* Wire contract: https://learn.chatgpt.com/docs/app-server.md
|
|
3
|
+
* Response types: openai/codex, app-server-protocol/schema/typescript (2026-11-09).
|
|
4
|
+
*/
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { createInterface } from 'node:readline';
|
|
9
|
+
import { codexHomes } from '../paths.mjs';
|
|
10
|
+
import { readJsonValue } from './result.mjs';
|
|
11
|
+
|
|
12
|
+
const controls = ['reply', 'interrupt', 'answer', 'fork', 'goal', 'limits', 'schema', 'review'];
|
|
13
|
+
const approvalMethods = new Set(['item/commandExecution/requestApproval', 'item/fileChange/requestApproval', 'item/permissions/requestApproval']);
|
|
14
|
+
const questionMethods = new Set(['tool/requestUserInput', 'item/tool/requestUserInput']);
|
|
15
|
+
const featureForMethod = { 'turn/steer': 'reply', 'turn/interrupt': 'interrupt', 'thread/fork': 'fork', 'thread/goal/set': 'goal' };
|
|
16
|
+
const textInput = text => [{ type: 'text', text }];
|
|
17
|
+
|
|
18
|
+
const nativeAuthFiles = ['auth.json', 'auth.lock', 'auth.json.lock'];
|
|
19
|
+
const sharedCodexFiles = [...nativeAuthFiles, 'config.toml', 'AGENTS.md', 'AGENTS.override.md',
|
|
20
|
+
'hooks.json', 'hooks', 'rules', 'skills', 'plugins'];
|
|
21
|
+
|
|
22
|
+
function importLegacyRollout(home, managed, sessionId) {
|
|
23
|
+
if (typeof sessionId !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(sessionId)) return;
|
|
24
|
+
const pattern = `**/rollout-*-${sessionId}.jsonl`;
|
|
25
|
+
const sessions = path.join(managed, 'sessions');
|
|
26
|
+
if (fs.globSync(pattern, { cwd: sessions }).length) return;
|
|
27
|
+
for (const directory of ['archived_sessions', 'sessions']) {
|
|
28
|
+
const source = path.join(home, directory);
|
|
29
|
+
const match = fs.globSync(pattern, { cwd: source })[0];
|
|
30
|
+
if (!match) continue;
|
|
31
|
+
const filename = path.basename(match);
|
|
32
|
+
const date = /^rollout-(\d{4})-(\d{2})-(\d{2})T/.exec(filename);
|
|
33
|
+
if (!date) throw new Error('Codex legacy rollout has no date.');
|
|
34
|
+
const destination = path.join(sessions, ...date.slice(1));
|
|
35
|
+
fs.mkdirSync(destination, { recursive: true, mode: 0o700 });
|
|
36
|
+
const temporary = fs.mkdtempSync(path.join(destination, '.import-'));
|
|
37
|
+
try {
|
|
38
|
+
const copy = path.join(temporary, filename);
|
|
39
|
+
fs.copyFileSync(path.join(source, match), copy);
|
|
40
|
+
fs.chmodSync(copy, 0o600);
|
|
41
|
+
// Publish the complete copy once. Another continuation can already own this thread.
|
|
42
|
+
try { fs.linkSync(copy, path.join(destination, filename)); }
|
|
43
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
44
|
+
} finally { fs.rmSync(temporary, { recursive: true, force: true }); }
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function managedCodexStorage(env, cwd, sessionId) {
|
|
50
|
+
const { interactive: home, managed } = codexHomes(env.CODEX_HOME, env.HOME || env.USERPROFILE, cwd);
|
|
51
|
+
const sqlite = path.join(managed, 'sqlite');
|
|
52
|
+
fs.mkdirSync(sqlite, { recursive: true, mode: 0o700 });
|
|
53
|
+
for (const directory of [managed, sqlite]) {
|
|
54
|
+
if (!fs.lstatSync(directory).isDirectory()) throw new Error(`Codex managed storage must be a directory: ${directory}`);
|
|
55
|
+
}
|
|
56
|
+
for (const name of sharedCodexFiles) {
|
|
57
|
+
const target = path.join(home, name);
|
|
58
|
+
const link = path.join(managed, name);
|
|
59
|
+
if (!nativeAuthFiles.includes(name) && !fs.existsSync(target)) continue;
|
|
60
|
+
// Link the credential and its locks so Codex owns one native sign-in and can refresh it in place.
|
|
61
|
+
// Keep the links valid across the operator's later configuration and sign-in changes.
|
|
62
|
+
try { fs.symlinkSync(target, link); }
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error.code !== 'EEXIST') throw error;
|
|
65
|
+
if (!fs.lstatSync(link).isSymbolicLink() || fs.readlinkSync(link) !== target) {
|
|
66
|
+
throw new Error(`Unexpected Codex managed-home entry: ${name}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// This Codex runtime resolves continuations within its own session store.
|
|
71
|
+
importLegacyRollout(home, managed, sessionId);
|
|
72
|
+
return { env: { ...env, CODEX_HOME: managed, CODEX_SQLITE_HOME: sqlite },
|
|
73
|
+
args: ['-c', `sqlite_home=${JSON.stringify(sqlite)}`] };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Codex sends outputSchema to OpenAI as a strict structured-output schema, which is
|
|
78
|
+
* refused unless every object lists all its properties in `required` and forbids
|
|
79
|
+
* others (400 invalid_json_schema). Send that strict copy; the result is still
|
|
80
|
+
* validated against the caller's schema, which a strict reply always satisfies.
|
|
81
|
+
*/
|
|
82
|
+
export function strictOutputSchema(schema) {
|
|
83
|
+
if (!schema || typeof schema !== 'object') return schema;
|
|
84
|
+
if (Array.isArray(schema)) return schema.map(strictOutputSchema);
|
|
85
|
+
const copy = {};
|
|
86
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
87
|
+
copy[key] = ['properties', '$defs', 'definitions'].includes(key) && value && typeof value === 'object'
|
|
88
|
+
? Object.fromEntries(Object.entries(value).map(([name, entry]) => [name, strictOutputSchema(entry)]))
|
|
89
|
+
: ['items', 'prefixItems', 'anyOf', 'allOf', 'oneOf', 'not', 'additionalProperties'].includes(key) ? strictOutputSchema(value) : value;
|
|
90
|
+
}
|
|
91
|
+
if (copy.properties && typeof copy.properties === 'object') {
|
|
92
|
+
copy.required = Object.keys(copy.properties);
|
|
93
|
+
copy.additionalProperties = false;
|
|
94
|
+
}
|
|
95
|
+
return copy;
|
|
96
|
+
}
|
|
97
|
+
const errorText = error => error?.message || String(error);
|
|
98
|
+
|
|
99
|
+
function answerPayload(request, value) {
|
|
100
|
+
if (questionMethods.has(request.method)) {
|
|
101
|
+
const questions = request.params.questions || [];
|
|
102
|
+
let answers = value?.answers ?? value;
|
|
103
|
+
if (typeof answers === 'string' || Array.isArray(answers)) {
|
|
104
|
+
if (questions.length !== 1) throw new Error('Answer each question by its question ID.');
|
|
105
|
+
answers = { [questions[0].id]: answers };
|
|
106
|
+
}
|
|
107
|
+
if (!answers || typeof answers !== 'object' || Array.isArray(answers)) throw new Error('Question answers must be an object.');
|
|
108
|
+
const result = {};
|
|
109
|
+
for (const [id, answer] of Object.entries(answers)) {
|
|
110
|
+
if (!questions.some(question => question.id === id)) throw new Error(`Unknown question ID: ${id}`);
|
|
111
|
+
const values = typeof answer === 'string' ? [answer] : Array.isArray(answer) ? answer : answer?.answers;
|
|
112
|
+
if (!Array.isArray(values) || values.some(entry => typeof entry !== 'string')) throw new Error(`Invalid answer for ${id}`);
|
|
113
|
+
result[id] = { answers: values };
|
|
114
|
+
}
|
|
115
|
+
return { answers: result };
|
|
116
|
+
}
|
|
117
|
+
if (request.method === 'item/permissions/requestApproval') {
|
|
118
|
+
const result = value === 'allow' || value === true
|
|
119
|
+
? { permissions: request.params.permissions || {}, scope: 'turn' }
|
|
120
|
+
: value === 'deny' || value === false ? { permissions: {}, scope: 'turn' } : value;
|
|
121
|
+
if (!result?.permissions || typeof result.permissions !== 'object' || Array.isArray(result.permissions) ||
|
|
122
|
+
(result.scope !== undefined && !['turn', 'session'].includes(result.scope))) throw new Error('Invalid permission grant.');
|
|
123
|
+
return { ...result, scope: result.scope || 'turn' };
|
|
124
|
+
}
|
|
125
|
+
let decision = value?.decision ?? value;
|
|
126
|
+
if (decision === 'allow' || decision === true) decision = 'accept';
|
|
127
|
+
if (decision === 'deny' || decision === false) decision = 'decline';
|
|
128
|
+
const amendment = request.method === 'item/commandExecution/requestApproval' && decision && typeof decision === 'object' &&
|
|
129
|
+
(decision.acceptWithExecpolicyAmendment || decision.applyNetworkPolicyAmendment);
|
|
130
|
+
if (!['accept', 'acceptForSession', 'decline', 'cancel'].includes(decision) && !amendment) throw new Error('Invalid approval decision.');
|
|
131
|
+
return { decision };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function createCodexDriver({ harness, binary = 'codex', args = [], cwd, env = process.env, job, options = {}, onEvent = () => {}, onFrame = () => {}, spawnFn = spawn }) {
|
|
135
|
+
const capabilities = Object.fromEntries(controls.map(key => [key, 'unsupported']));
|
|
136
|
+
const pending = new Map(), requests = new Map(), turnWaiters = new Map(), completedTurns = new Set(), messages = new Map();
|
|
137
|
+
const usage = { inputTokens: 0, outputTokens: 0, costUsd: null };
|
|
138
|
+
let child, lines, started, sessionId = null, activeTurn = null, sequence = 0;
|
|
139
|
+
let closed = false, exited = false, settled = false, closing, completion = null, finishTimer;
|
|
140
|
+
let queued = 0, controlTail = Promise.resolve(), limitError = null, stderr = '', bytes = 0;
|
|
141
|
+
let resolveDone, resolveExit;
|
|
142
|
+
let done = new Promise(resolve => { resolveDone = resolve; });
|
|
143
|
+
const exit = new Promise(resolve => { resolveExit = resolve; });
|
|
144
|
+
const emit = (kind, fields = {}) => {
|
|
145
|
+
try { onEvent({ kind, text: '', ...fields }); } catch { /* Observers do not own the session. */ }
|
|
146
|
+
};
|
|
147
|
+
const response = () => {
|
|
148
|
+
const items = [...messages.values()];
|
|
149
|
+
const final = items.filter(item => item.phase === 'final_answer');
|
|
150
|
+
return (final.length ? final : items).map(item => item.text || '').join('\n');
|
|
151
|
+
};
|
|
152
|
+
function settle(result) {
|
|
153
|
+
if (settled) return;
|
|
154
|
+
settled = true;
|
|
155
|
+
clearImmediate(finishTimer);
|
|
156
|
+
const value = { ok: false, response: response(), sessionId, usage: { ...usage }, structured: null, error: null, failureKind: null, ...result };
|
|
157
|
+
emit('finish', { text: value.ok ? 'Finished' : value.error, ...value });
|
|
158
|
+
resolveDone(value);
|
|
159
|
+
}
|
|
160
|
+
function rejectPending(error) {
|
|
161
|
+
for (const entry of pending.values()) { clearTimeout(entry.timer); entry.reject(error); }
|
|
162
|
+
for (const entry of turnWaiters.values()) { clearTimeout(entry.timer); entry.reject(error); }
|
|
163
|
+
pending.clear(); requests.clear(); turnWaiters.clear();
|
|
164
|
+
}
|
|
165
|
+
function fail(error, failureKind = 'protocol') {
|
|
166
|
+
if (limitError) failureKind = 'limit';
|
|
167
|
+
emit('error', { text: errorText(error), failureKind });
|
|
168
|
+
settle({ error: errorText(error), failureKind });
|
|
169
|
+
rejectPending(error);
|
|
170
|
+
void close();
|
|
171
|
+
}
|
|
172
|
+
function write(message) {
|
|
173
|
+
return new Promise((resolve, reject) => {
|
|
174
|
+
if (!child || exited || closed || child.stdin.destroyed) { reject(new Error('Codex session is closed.')); return; }
|
|
175
|
+
child.stdin.write(`${JSON.stringify(message)}\n`, error => error ? reject(error) : resolve());
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
function rpc(method, params) {
|
|
179
|
+
const id = ++sequence;
|
|
180
|
+
return new Promise((resolve, reject) => {
|
|
181
|
+
const timer = setTimeout(() => fail(new Error(`Codex request timed out: ${method}`)), 30_000);
|
|
182
|
+
timer.unref?.();
|
|
183
|
+
pending.set(id, { resolve, reject, timer, method });
|
|
184
|
+
write({ id, method, params }).catch(error => fail(error, 'transport'));
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
function finishWhenIdle() {
|
|
188
|
+
clearImmediate(finishTimer);
|
|
189
|
+
// Let controls submitted by event handlers, and responses in this JSONL batch, drain first.
|
|
190
|
+
finishTimer = setImmediate(() => {
|
|
191
|
+
if (!completion || activeTurn || queued || settled) return;
|
|
192
|
+
const turn = completion;
|
|
193
|
+
if (limitError) { settle({ error: limitError, failureKind: 'limit' }); return; }
|
|
194
|
+
if (turn.status !== 'completed') {
|
|
195
|
+
const info = turn.error?.codexErrorInfo;
|
|
196
|
+
settle({ error: turn.error?.message || `Codex turn ${turn.status}.`,
|
|
197
|
+
failureKind: turn.status === 'interrupted' ? 'cancelled' : info === 'usageLimitExceeded' ? 'quota' : 'agent' });
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
let structured = null;
|
|
201
|
+
if (options.resultSchema !== undefined) {
|
|
202
|
+
// Share the reply reader with run.mjs, so one fenced JSON block is
|
|
203
|
+
// accepted. An unreadable reply is a schema failure the caller may
|
|
204
|
+
// correct once, exactly as before.
|
|
205
|
+
const read = readJsonValue(response());
|
|
206
|
+
if (read.errors.length) { settle({ error: 'Codex returned invalid JSON for the result schema.', failureKind: 'schema' }); return; }
|
|
207
|
+
structured = read.value;
|
|
208
|
+
}
|
|
209
|
+
settle({ ok: true, structured });
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
function control(command, action) {
|
|
213
|
+
queued += 1;
|
|
214
|
+
const task = controlTail.then(async () => {
|
|
215
|
+
if (!started) throw new Error('Start the Codex session first.');
|
|
216
|
+
await started;
|
|
217
|
+
if (closed || exited) throw new Error('Codex session is closed.');
|
|
218
|
+
const result = await action();
|
|
219
|
+
emit('ack', { text: `${command} acknowledged`, command });
|
|
220
|
+
return result;
|
|
221
|
+
}).finally(() => { queued -= 1; finishWhenIdle(); });
|
|
222
|
+
controlTail = task.catch(() => {});
|
|
223
|
+
return task;
|
|
224
|
+
}
|
|
225
|
+
async function startTurn(text) {
|
|
226
|
+
if (limitError) throw new Error(limitError);
|
|
227
|
+
completion = null;
|
|
228
|
+
messages.clear();
|
|
229
|
+
const result = await rpc('turn/start', { threadId: sessionId, input: textInput(text),
|
|
230
|
+
...(options.effort ? { effort: options.effort } : {}),
|
|
231
|
+
...(options.resultSchema !== undefined ? { outputSchema: strictOutputSchema(options.resultSchema) } : {}) });
|
|
232
|
+
if (!result?.turn?.id) throw new Error('Codex turn/start returned no turn ID.');
|
|
233
|
+
if (!completedTurns.has(result.turn.id)) activeTurn = result.turn.id;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* A thread goal lets the app-server start a continuation turn by itself after a turn completes,
|
|
237
|
+
* and its turn/started can arrive after this driver settled. A new turn with a different output
|
|
238
|
+
* schema is then refused (ActiveTurnOutputSchemaMismatch). Stop the continuation and start again.
|
|
239
|
+
*/
|
|
240
|
+
async function startNextTurn(text, { wait = ms => new Promise(resolve => setTimeout(resolve, ms)) } = {}) {
|
|
241
|
+
// The interrupted continuation completes while this runs; it must not settle the new turn.
|
|
242
|
+
queued += 1;
|
|
243
|
+
try {
|
|
244
|
+
if (activeTurn) await interruptTurn();
|
|
245
|
+
try { await startTurn(text); }
|
|
246
|
+
catch (error) {
|
|
247
|
+
if (!/ActiveTurnOutputSchemaMismatch|active turn/i.test(`${error.message} ${JSON.stringify(error.data ?? '')}`)) throw error;
|
|
248
|
+
for (let i = 0; i < 50 && !activeTurn; i += 1) await wait(100);
|
|
249
|
+
if (activeTurn) await interruptTurn();
|
|
250
|
+
await startTurn(text);
|
|
251
|
+
}
|
|
252
|
+
} finally { queued -= 1; }
|
|
253
|
+
}
|
|
254
|
+
async function interruptTurn() {
|
|
255
|
+
const turnId = activeTurn;
|
|
256
|
+
if (!turnId) return;
|
|
257
|
+
// The RPC reply only acknowledges cancellation. Wait for turn/completed before
|
|
258
|
+
// returning, so an immediate continuation starts a new turn rather than steering it.
|
|
259
|
+
const stopped = new Promise((resolve, reject) => {
|
|
260
|
+
const timer = setTimeout(() => fail(new Error('Codex interrupt did not complete.')), 30_000);
|
|
261
|
+
timer.unref?.();
|
|
262
|
+
turnWaiters.set(turnId, { resolve, reject, timer });
|
|
263
|
+
});
|
|
264
|
+
try { await Promise.all([stopped, rpc('turn/interrupt', { threadId: sessionId, turnId })]); }
|
|
265
|
+
finally { clearTimeout(turnWaiters.get(turnId)?.timer); turnWaiters.delete(turnId); }
|
|
266
|
+
}
|
|
267
|
+
function itemEvent(method, params) {
|
|
268
|
+
const item = params.item;
|
|
269
|
+
if (item?.type === 'agentMessage' || item?.type === 'exitedReviewMode') {
|
|
270
|
+
if (item.type === 'exitedReviewMode') item.text = item.review;
|
|
271
|
+
messages.set(item.id, { ...item });
|
|
272
|
+
if (method === 'item/completed') emit('message', { text: item.text || '', item, itemId: item.id, phase: item.phase });
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (item) {
|
|
276
|
+
const text = item.command || item.text || item.review || item.query || item.tool || item.type;
|
|
277
|
+
emit(method === 'item/started' ? 'step-start' : 'step-end', { text, item, itemId: item.id });
|
|
278
|
+
if (item.type === 'collabToolCall') emit('subagent', { text: item.prompt || text, item });
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (method === 'item/agentMessage/delta') {
|
|
282
|
+
const previous = messages.get(params.itemId) || { id: params.itemId, type: 'agentMessage', text: '' };
|
|
283
|
+
messages.set(params.itemId, { ...previous, text: previous.text + (params.delta || '') });
|
|
284
|
+
}
|
|
285
|
+
if (typeof params.delta === 'string') emit('message', { text: params.delta, delta: true, itemId: params.itemId, method });
|
|
286
|
+
}
|
|
287
|
+
function notification(method, params) {
|
|
288
|
+
// A fork also emits thread/started. Never replace this driver's thread with that fork.
|
|
289
|
+
if (params.threadId && params.threadId !== sessionId) return;
|
|
290
|
+
if (method.startsWith('item/')) { itemEvent(method, params); return; }
|
|
291
|
+
switch (method) {
|
|
292
|
+
case 'turn/started':
|
|
293
|
+
if (!completedTurns.has(params.turn.id)) activeTurn = params.turn.id;
|
|
294
|
+
break;
|
|
295
|
+
case 'turn/completed': {
|
|
296
|
+
const turn = params.turn;
|
|
297
|
+
if (completedTurns.has(turn.id)) return;
|
|
298
|
+
if (activeTurn && activeTurn !== turn.id) return;
|
|
299
|
+
for (const item of turn.items || []) if (item.type === 'agentMessage') messages.set(item.id, item);
|
|
300
|
+
completedTurns.add(turn.id); activeTurn = null; completion = turn;
|
|
301
|
+
const waiting = turnWaiters.get(turn.id);
|
|
302
|
+
if (waiting) { clearTimeout(waiting.timer); waiting.resolve(); turnWaiters.delete(turn.id); }
|
|
303
|
+
for (const [id, request] of requests) if (request.params.turnId === turn.id) requests.delete(id);
|
|
304
|
+
finishWhenIdle();
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
case 'serverRequest/resolved': requests.delete(params.requestId); break;
|
|
308
|
+
case 'turn/plan/updated': emit('plan', { text: params.explanation || 'Plan updated', steps: params.plan || [] }); break;
|
|
309
|
+
case 'turn/diff/updated': emit('diff', { text: params.diff || '', summary: params.diff || '' }); break;
|
|
310
|
+
case 'model/rerouted': emit('reroute', { text: `${params.fromModel} → ${params.toModel}`, from: params.fromModel, to: params.toModel, reason: params.reason }); break;
|
|
311
|
+
case 'hook/started': case 'hook/completed':
|
|
312
|
+
emit('hook', { text: params.run?.eventName || '', name: params.run?.eventName, phase: method.split('/')[1], run: params.run }); break;
|
|
313
|
+
case 'thread/tokenUsage/updated': {
|
|
314
|
+
const total = params.tokenUsage?.total;
|
|
315
|
+
if (!total) return;
|
|
316
|
+
// These are cumulative thread snapshots. Summing them would count tokens twice.
|
|
317
|
+
usage.inputTokens = total.inputTokens ?? usage.inputTokens;
|
|
318
|
+
usage.outputTokens = total.outputTokens ?? usage.outputTokens;
|
|
319
|
+
emit('usage', { text: `${usage.inputTokens} in, ${usage.outputTokens} out tokens`, ...usage });
|
|
320
|
+
if (options.maxTokens !== undefined && !limitError && (total.totalTokens ?? usage.inputTokens + usage.outputTokens) >= options.maxTokens) {
|
|
321
|
+
limitError = `Codex token limit reached (${options.maxTokens}).`;
|
|
322
|
+
void control('interrupt', async () => {
|
|
323
|
+
if (activeTurn) await interruptTurn();
|
|
324
|
+
else settle({ error: limitError, failureKind: 'limit' });
|
|
325
|
+
}).catch(error => fail(error, 'limit'));
|
|
326
|
+
}
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
case 'error': emit('error', { text: params.error?.message || 'Codex error', error: params.error, willRetry: params.willRetry }); break;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
function frame(message) {
|
|
333
|
+
onFrame(message);
|
|
334
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) throw new Error('Invalid Codex JSON-RPC frame.');
|
|
335
|
+
if (message.method && Object.hasOwn(message, 'id')) {
|
|
336
|
+
if (approvalMethods.has(message.method) || questionMethods.has(message.method)) {
|
|
337
|
+
requests.set(message.id, message);
|
|
338
|
+
emit(questionMethods.has(message.method) ? 'question' : 'approval', {
|
|
339
|
+
requestId: message.id, request: message.params, method: message.method,
|
|
340
|
+
...(questionMethods.has(message.method) ? { questions: message.params.questions || [] } : {}) });
|
|
341
|
+
} else {
|
|
342
|
+
void write({ id: message.id, error: { code: -32601, message: `Unsupported client method: ${message.method}` } }).catch(error => fail(error, 'transport'));
|
|
343
|
+
}
|
|
344
|
+
} else if (Object.hasOwn(message, 'id')) {
|
|
345
|
+
const entry = pending.get(message.id);
|
|
346
|
+
if (!entry) return;
|
|
347
|
+
pending.delete(message.id); clearTimeout(entry.timer);
|
|
348
|
+
if (message.error) {
|
|
349
|
+
const feature = featureForMethod[entry.method];
|
|
350
|
+
if (feature && message.error.code === -32601) capabilities[feature] = 'unsupported';
|
|
351
|
+
entry.reject(Object.assign(new Error(message.error.message || 'Codex request failed.'), message.error));
|
|
352
|
+
} else if (Object.hasOwn(message, 'result')) entry.resolve(message.result);
|
|
353
|
+
else entry.reject(new Error('Codex response has no result or error.'));
|
|
354
|
+
} else if (typeof message.method === 'string') notification(message.method, message.params || {});
|
|
355
|
+
else throw new Error('Invalid Codex JSON-RPC frame.');
|
|
356
|
+
}
|
|
357
|
+
async function start(brief) {
|
|
358
|
+
if (started) throw new Error('Codex session has already started.');
|
|
359
|
+
if (closed) throw new Error('Codex session is closed.');
|
|
360
|
+
started = (async () => {
|
|
361
|
+
if (typeof brief !== 'string' || !brief.trim()) throw new Error('A non-empty brief is required.');
|
|
362
|
+
if (options.maxTokens !== undefined && (!Number.isSafeInteger(options.maxTokens) || options.maxTokens < 1)) throw new Error('maxTokens must be a positive integer.');
|
|
363
|
+
const storage = options.ephemeral ? { env, args: [] } : managedCodexStorage(env, cwd, options.sessionId);
|
|
364
|
+
try {
|
|
365
|
+
child = spawnFn(binary, [...args, 'app-server', '--listen', 'stdio://', ...storage.args], {
|
|
366
|
+
cwd, env: storage.env, shell: false, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
367
|
+
} catch (error) { error.failureKind = 'spawn'; throw error; }
|
|
368
|
+
child.on('error', error => { exited = true; resolveExit(); fail(error, 'spawn'); });
|
|
369
|
+
child.on('close', (code, signal) => {
|
|
370
|
+
exited = true; resolveExit(); lines?.close();
|
|
371
|
+
rejectPending(Object.assign(new Error(`Codex app-server closed (${signal || code}).${stderr ? ` ${stderr}` : ''}`), { failureKind: 'process' }));
|
|
372
|
+
if (!closed && !settled) {
|
|
373
|
+
// stdout has drained at close; allow a preceding turn/completed to settle first.
|
|
374
|
+
finishWhenIdle();
|
|
375
|
+
setImmediate(() => { if (!settled) fail(new Error(`Codex app-server exited before turn completion (${signal || code}).${stderr ? ` ${stderr}` : ''}`), 'process'); });
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
child.stdin.on('error', error => { if (!closed) fail(error, 'transport'); });
|
|
379
|
+
child.stderr.on('data', chunk => { stderr = (stderr + chunk.toString()).slice(-4096); });
|
|
380
|
+
child.stdout.on('data', chunk => {
|
|
381
|
+
bytes += chunk.length;
|
|
382
|
+
if (bytes > 32 * 1024 * 1024) fail(new Error('Codex transport output limit reached.'), 'limit');
|
|
383
|
+
});
|
|
384
|
+
lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
385
|
+
lines.on('line', line => {
|
|
386
|
+
if (!line.trim() || closed) return;
|
|
387
|
+
try { frame(JSON.parse(line)); } catch (error) { fail(error); }
|
|
388
|
+
});
|
|
389
|
+
const initialized = await rpc('initialize', {
|
|
390
|
+
clientInfo: { name: 'metaharness', title: 'Metaharness', version: '1.0.0' },
|
|
391
|
+
capabilities: { experimentalApi: true } });
|
|
392
|
+
if (!initialized || typeof initialized.userAgent !== 'string') throw new Error('Codex initialize returned no server identity.');
|
|
393
|
+
await write({ method: 'initialized', params: {} });
|
|
394
|
+
// InitializeResponse reports identity/platform, not a per-method feature list. Use the
|
|
395
|
+
// documented app-server surface after this handshake, never a version-string test.
|
|
396
|
+
Object.assign(capabilities, Object.fromEntries(controls.map(key => [key, key === 'limits' ? 'metaharness' : 'native'])));
|
|
397
|
+
if (options.ephemeral && (options.forkSession || options.sessionId)) throw new Error('An ephemeral Codex thread cannot resume or fork.');
|
|
398
|
+
const result = await rpc(options.forkSession ? 'thread/fork' : options.sessionId ? 'thread/resume' : 'thread/start', {
|
|
399
|
+
...(options.ephemeral ? { ephemeral: true } : {}),
|
|
400
|
+
...(options.sessionId ? { threadId: options.sessionId, excludeTurns: true } : {}),
|
|
401
|
+
...(options.forkSession && options.atTurn ? { lastTurnId: options.atTurn } : {}),
|
|
402
|
+
cwd, sandbox: 'danger-full-access', approvalPolicy: options.approvalPolicy === 'operator' || options.approvalPolicy === 'rules'
|
|
403
|
+
? 'on-request' : options.approvalPolicy === 'auto' || !options.approvalPolicy ? 'never' : options.approvalPolicy });
|
|
404
|
+
// The resumable handle is thread.id; thread.sessionId can name a fork's ancestor.
|
|
405
|
+
sessionId = result?.thread?.id;
|
|
406
|
+
if (!sessionId) throw new Error('Codex returned no thread ID.');
|
|
407
|
+
// Refuse before any turn when the server would persist a thread asked to be ephemeral.
|
|
408
|
+
if (options.ephemeral && result.thread.ephemeral !== true) throw new Error('Codex ignored ephemeral: true; refusing to run a persistent reasoning thread.');
|
|
409
|
+
if (!options.ephemeral) {
|
|
410
|
+
await rpc('thread/name/set', { threadId: sessionId, name: options.name || job?.name || job?.id || (typeof job === 'string' ? job : 'Metaharness job') });
|
|
411
|
+
if (options.goal) await rpc('thread/goal/set', { threadId: sessionId, objective: options.goal });
|
|
412
|
+
}
|
|
413
|
+
emit('session', { text: `Codex session ${sessionId}`, sessionId, session: sessionId, rootSessionId: result.thread.sessionId,
|
|
414
|
+
capabilities: { ...capabilities }, server: initialized, harness });
|
|
415
|
+
if (options.reviewTarget) {
|
|
416
|
+
const review = await rpc('review/start', { threadId: sessionId, delivery: 'inline', target: options.reviewTarget });
|
|
417
|
+
if (!review?.turn?.id) throw new Error('Codex review/start returned no turn ID.');
|
|
418
|
+
if (!completedTurns.has(review.turn.id)) activeTurn = review.turn.id;
|
|
419
|
+
} else await startTurn(brief);
|
|
420
|
+
})();
|
|
421
|
+
try { await started; }
|
|
422
|
+
catch (error) { fail(error, error.failureKind || 'protocol'); throw error; }
|
|
423
|
+
}
|
|
424
|
+
function send(text) {
|
|
425
|
+
return control('send', async () => {
|
|
426
|
+
if (typeof text !== 'string' || !text.trim()) throw new Error('A non-empty message is required.');
|
|
427
|
+
if (limitError) throw new Error(limitError);
|
|
428
|
+
if (activeTurn) {
|
|
429
|
+
const turnId = activeTurn;
|
|
430
|
+
try { await rpc('turn/steer', { threadId: sessionId, expectedTurnId: turnId, input: textInput(text) }); }
|
|
431
|
+
catch (error) {
|
|
432
|
+
// The turn can finish between selecting steer and the server handling it.
|
|
433
|
+
if (error.code === -32600 && !activeTurn && /no active turn|not active|turn.*mismatch/i.test(error.message)) await startTurn(text);
|
|
434
|
+
else throw error;
|
|
435
|
+
}
|
|
436
|
+
} else await startTurn(text);
|
|
437
|
+
return { ack: true, via: 'native' };
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
function interrupt() {
|
|
441
|
+
return control('interrupt', async () => {
|
|
442
|
+
await interruptTurn();
|
|
443
|
+
return { ack: true, via: 'native' };
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
async function answer(requestId, value) {
|
|
447
|
+
if (closed || exited) throw new Error('Codex session is closed.');
|
|
448
|
+
const id = requests.has(requestId) ? requestId : [...requests.keys()].find(key => String(key) === String(requestId));
|
|
449
|
+
const request = requests.get(id);
|
|
450
|
+
if (!request) throw new Error(`No pending Codex request: ${requestId}`);
|
|
451
|
+
const result = answerPayload(request, value);
|
|
452
|
+
// Reserve the request before yielding: two concurrent operator replies must not
|
|
453
|
+
// write two JSON-RPC responses for the same server request.
|
|
454
|
+
requests.delete(id);
|
|
455
|
+
queued += 1;
|
|
456
|
+
try {
|
|
457
|
+
await write({ id: request.id, result });
|
|
458
|
+
emit('ack', { text: 'answer acknowledged', command: 'answer', requestId: request.id });
|
|
459
|
+
return { ack: true, via: 'native' };
|
|
460
|
+
} finally { queued -= 1; finishWhenIdle(); }
|
|
461
|
+
}
|
|
462
|
+
function fork({ atTurn } = {}) {
|
|
463
|
+
return control('fork', async () => {
|
|
464
|
+
const result = await rpc('thread/fork', { threadId: sessionId, excludeTurns: true, ...(atTurn ? { lastTurnId: atTurn } : {}) });
|
|
465
|
+
if (!result?.thread?.id) throw new Error('Codex fork returned no thread ID.');
|
|
466
|
+
return { sessionId: result.thread.id };
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
function close() {
|
|
470
|
+
if (closing) return closing;
|
|
471
|
+
closed = true;
|
|
472
|
+
clearImmediate(finishTimer);
|
|
473
|
+
rejectPending(new Error('Codex session is closed.'));
|
|
474
|
+
if (!settled) settle({ error: limitError || 'Codex session closed.', failureKind: limitError ? 'limit' : 'cancelled' });
|
|
475
|
+
closing = (async () => {
|
|
476
|
+
if (!child) return;
|
|
477
|
+
const kill = signal => {
|
|
478
|
+
try { if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal); else child.kill(signal); }
|
|
479
|
+
catch { try { child.kill(signal); } catch { /* Already stopped. */ } }
|
|
480
|
+
};
|
|
481
|
+
if (!exited) child.stdin.end();
|
|
482
|
+
kill('SIGTERM');
|
|
483
|
+
const timer = setTimeout(() => kill('SIGKILL'), 500);
|
|
484
|
+
await exit;
|
|
485
|
+
// A server can exit while a descendant ignores TERM and has closed its pipes.
|
|
486
|
+
// Stop the owned group as well before releasing the session.
|
|
487
|
+
kill('SIGKILL'); clearTimeout(timer); lines?.close();
|
|
488
|
+
})();
|
|
489
|
+
return closing;
|
|
490
|
+
}
|
|
491
|
+
return { capabilities, start, send, interrupt, answer, fork, close, get done() { return done; },
|
|
492
|
+
setGoal: objective => control('goal', () => rpc('thread/goal/set', { threadId: sessionId, objective })),
|
|
493
|
+
async next(text, { resultSchema } = {}) {
|
|
494
|
+
if (!settled || closed || exited) throw new Error('The session is not ready for another turn.');
|
|
495
|
+
settled = false;
|
|
496
|
+
options.resultSchema = resultSchema;
|
|
497
|
+
done = new Promise(resolve => { resolveDone = resolve; });
|
|
498
|
+
await startNextTurn(text);
|
|
499
|
+
return done;
|
|
500
|
+
} };
|
|
501
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** Portable JSON Schema validation. Unsupported assertions fail closed. */
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
export function validateSchema(schema, value, root = schema, at = '$') {
|
|
4
|
+
if (schema === true) return [];
|
|
5
|
+
if (schema === false) return [`${at}: forbidden value`];
|
|
6
|
+
if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return [`${at}: invalid schema`];
|
|
7
|
+
const annotations = ['$schema', '$id', '$defs', 'definitions', 'title', 'description', 'default', 'examples', 'format', 'readOnly', 'writeOnly', '$comment'];
|
|
8
|
+
const supported = ['$ref', 'type', 'enum', 'const', 'required', 'properties', 'additionalProperties', 'items', 'prefixItems', 'minItems', 'maxItems', 'uniqueItems', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'allOf', 'anyOf', 'oneOf', 'not', 'minProperties', 'maxProperties'];
|
|
9
|
+
const errors = Object.keys(schema).filter(key => !supported.includes(key) && !annotations.includes(key)).map(key => `${at}: unsupported schema keyword ${key}`);
|
|
10
|
+
if (schema.$ref) {
|
|
11
|
+
if (!schema.$ref.startsWith('#/')) return [...errors, `${at}: only local schema references are supported`];
|
|
12
|
+
const ref = schema.$ref.slice(2).split('/').reduce((s, key) => s?.[key.replaceAll('~1', '/').replaceAll('~0', '~')], root);
|
|
13
|
+
if (!ref || ref === schema) return [...errors, `${at}: invalid or recursive schema reference`];
|
|
14
|
+
errors.push(...validateSchema(ref, value, root, at));
|
|
15
|
+
}
|
|
16
|
+
const equal = isDeepStrictEqual;
|
|
17
|
+
const type = name => name === 'null' ? value === null : name === 'array' ? Array.isArray(value)
|
|
18
|
+
: name === 'object' ? value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
19
|
+
: name === 'integer' ? Number.isInteger(value) : name === 'number' ? typeof value === 'number' && Number.isFinite(value) : typeof value === name;
|
|
20
|
+
if (schema.type && !(Array.isArray(schema.type) ? schema.type : [schema.type]).some(type)) errors.push(`${at}: expected ${schema.type}`);
|
|
21
|
+
if (schema.enum && !schema.enum.some(v => equal(v, value))) errors.push(`${at}: value is outside enum`);
|
|
22
|
+
if (Object.hasOwn(schema, 'const') && !equal(schema.const, value)) errors.push(`${at}: expected const`);
|
|
23
|
+
for (const key of ['allOf', 'anyOf', 'oneOf']) if (schema[key]) {
|
|
24
|
+
const matches = schema[key].filter(s => !validateSchema(s, value, root, at).length).length;
|
|
25
|
+
if (key === 'allOf' ? matches !== schema[key].length : key === 'oneOf' ? matches !== 1 : matches === 0) errors.push(`${at}: ${key} failed`);
|
|
26
|
+
}
|
|
27
|
+
if (schema.not && !validateSchema(schema.not, value, root, at).length) errors.push(`${at}: not failed`);
|
|
28
|
+
if (type('object')) {
|
|
29
|
+
for (const key of schema.required || []) if (!Object.hasOwn(value, key)) errors.push(`${at}.${key}: required`);
|
|
30
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
31
|
+
const child = schema.properties?.[key] ?? schema.additionalProperties ?? true;
|
|
32
|
+
errors.push(...validateSchema(child, entry, root, `${at}.${key}`));
|
|
33
|
+
}
|
|
34
|
+
if (schema.minProperties !== undefined && Object.keys(value).length < schema.minProperties) errors.push(`${at}: too few properties`);
|
|
35
|
+
if (schema.maxProperties !== undefined && Object.keys(value).length > schema.maxProperties) errors.push(`${at}: too many properties`);
|
|
36
|
+
}
|
|
37
|
+
if (Array.isArray(value)) {
|
|
38
|
+
value.forEach((entry, i) => errors.push(...validateSchema(schema.prefixItems?.[i] ?? schema.items ?? true, entry, root, `${at}[${i}]`)));
|
|
39
|
+
if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${at}: too few items`);
|
|
40
|
+
if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(`${at}: too many items`);
|
|
41
|
+
if (schema.uniqueItems && value.some((entry, i) => value.slice(0, i).some(previous => equal(entry, previous)))) errors.push(`${at}: duplicate items`);
|
|
42
|
+
}
|
|
43
|
+
if (typeof value === 'string') {
|
|
44
|
+
if (schema.minLength !== undefined && [...value].length < schema.minLength) errors.push(`${at}: text too short`);
|
|
45
|
+
if (schema.maxLength !== undefined && [...value].length > schema.maxLength) errors.push(`${at}: text too long`);
|
|
46
|
+
if (schema.pattern !== undefined && !new RegExp(schema.pattern).test(value)) errors.push(`${at}: pattern failed`);
|
|
47
|
+
}
|
|
48
|
+
if (typeof value === 'number') {
|
|
49
|
+
for (const [key, failed] of [['minimum', value < schema.minimum], ['maximum', value > schema.maximum],
|
|
50
|
+
['exclusiveMinimum', value <= schema.exclusiveMinimum], ['exclusiveMaximum', value >= schema.exclusiveMaximum],
|
|
51
|
+
['multipleOf', schema.multipleOf !== undefined && Math.abs(value / schema.multipleOf - Math.round(value / schema.multipleOf)) > 1e-9]]) {
|
|
52
|
+
if (failed) errors.push(`${at}: ${key} failed`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return errors;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const GOAL_SCHEMA = { type: 'object', required: ['met', 'evidence', 'remaining'], additionalProperties: false,
|
|
59
|
+
properties: { met: { type: 'boolean' }, evidence: { type: 'array', items: { type: 'string' } }, remaining: { type: 'array', items: { type: 'string' } },
|
|
60
|
+
notes: { type: 'array', items: { type: 'string' } } } };
|
|
61
|
+
|
|
62
|
+
// A reply may wrap its single JSON value in one fenced block, with or without
|
|
63
|
+
// prose around it. Two JSON blocks are ambiguous, so they stay invalid.
|
|
64
|
+
function fencedValue(text) {
|
|
65
|
+
if (typeof text !== 'string') return undefined;
|
|
66
|
+
const blocks = [...text.matchAll(/```[^\n]*\n([\s\S]*?)```/g)].map(match => match[1].trim());
|
|
67
|
+
if (blocks.length !== 1) return undefined;
|
|
68
|
+
try { return JSON.parse(blocks[0]); } catch { return undefined; }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Reads the single JSON value out of a reply, fenced or bare. Drivers share it. */
|
|
72
|
+
export function readJsonValue(text) {
|
|
73
|
+
if (typeof text !== 'string' || !text.trim()) return { value: undefined, errors: ['The final message must be JSON.'] };
|
|
74
|
+
try { return { value: JSON.parse(text), errors: [] }; }
|
|
75
|
+
catch {
|
|
76
|
+
const fenced = fencedValue(text);
|
|
77
|
+
if (fenced === undefined) return { value: undefined, errors: ['The final message must be JSON.'] };
|
|
78
|
+
return { value: fenced, errors: [] };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function readResult(result, schema) {
|
|
83
|
+
let value = result.structured;
|
|
84
|
+
if (value === undefined || value === null) {
|
|
85
|
+
const read = readJsonValue(result.response);
|
|
86
|
+
if (read.errors.length) return { errors: read.errors };
|
|
87
|
+
value = read.value;
|
|
88
|
+
}
|
|
89
|
+
return { value, errors: validateSchema(schema, value) };
|
|
90
|
+
}
|