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,258 @@
|
|
|
1
|
+
/** Job lifecycle around a native session. All dependencies ship with the worker. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { createClaudeDriver } from './claude.mjs';
|
|
6
|
+
import { createCodexDriver } from './codex.mjs';
|
|
7
|
+
import { createResumeDriver } from './resume.mjs';
|
|
8
|
+
import { GOAL_SCHEMA, readResult } from './result.mjs';
|
|
9
|
+
import { tailInbox, appendEvent, waitingRequests } from '../control.mjs';
|
|
10
|
+
import { mcpConfigFor, createMcpTools, NO_ANSWER, QUESTION_TIMEOUT_MS } from '../mcp-server.mjs';
|
|
11
|
+
|
|
12
|
+
// A routed attempt or coordination stage shares its CLI job's limits. Each
|
|
13
|
+
// driver reports its own usage; the job sums those reports without double count.
|
|
14
|
+
const budgets = new Map();
|
|
15
|
+
|
|
16
|
+
/** Opens every Total Recall reasoning brief, so persisted transcripts are never reviewed again. Core matches it. */
|
|
17
|
+
export const INTERNAL_JOB_MARKER = '[total-recall:internal-job]';
|
|
18
|
+
|
|
19
|
+
export function sessionOptions(request) {
|
|
20
|
+
const result = {};
|
|
21
|
+
if (request.sessionId) result.resumeSession = true;
|
|
22
|
+
for (const key of ['goal', 'maxTurns', 'maxTokens', 'maxBudgetUsd', 'resultSchema', 'approvalPolicy', 'questionTimeoutMs', 'sessionId', 'forkSession', 'atTurn', 'name', 'effort', 'fallbackModel', 'reviewTarget', 'internalReasoning']) {
|
|
23
|
+
if (request[key] !== undefined) result[key] = request[key];
|
|
24
|
+
}
|
|
25
|
+
for (const key of ['maxTurns', 'maxTokens', 'questionTimeoutMs']) if (result[key] !== undefined && (!Number.isSafeInteger(result[key]) || result[key] < 1)) throw new Error(`${key} must be a positive integer.`);
|
|
26
|
+
if (result.maxBudgetUsd !== undefined && (!Number.isFinite(result.maxBudgetUsd) || result.maxBudgetUsd < 0)) throw new Error('maxBudgetUsd must be nonnegative.');
|
|
27
|
+
if (result.internalReasoning !== undefined && typeof result.internalReasoning !== 'boolean') throw new Error('internalReasoning must be a boolean.');
|
|
28
|
+
if (result.internalReasoning) {
|
|
29
|
+
// Internal reasoning is read-only, single-turn and token bounded, so no coding task can use it to skip its goal check.
|
|
30
|
+
if (result.sessionId || result.forkSession || result.reviewTarget) throw new Error('Internal reasoning runs in a new ephemeral session.');
|
|
31
|
+
if (request.permissions?.write === true) throw new Error('Internal reasoning is read-only.');
|
|
32
|
+
if (result.maxTurns !== 1) throw new Error('Internal reasoning requires maxTurns 1.');
|
|
33
|
+
if (result.maxTokens === undefined) throw new Error('Internal reasoning requires a token bound.');
|
|
34
|
+
}
|
|
35
|
+
if (result.goal !== undefined && (typeof result.goal !== 'string' || !result.goal.trim() || result.goal.length > 4000)) throw new Error('goal must have 1..4000 characters.');
|
|
36
|
+
if (result.approvalPolicy !== undefined && !['auto', 'operator', 'rules'].includes(result.approvalPolicy)) throw new Error('Approval policy must be auto, operator, or rules.');
|
|
37
|
+
if (typeof result.resultSchema === 'string') result.resultSchema = JSON.parse(fs.readFileSync(path.resolve(request.cwd, result.resultSchema), 'utf8'));
|
|
38
|
+
if (result.resultSchema !== undefined && typeof result.resultSchema !== 'boolean' && (!result.resultSchema || typeof result.resultSchema !== 'object' || Array.isArray(result.resultSchema))) throw new Error('resultSchema must be a JSON Schema.');
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The goal-check prompt. When Metaharness owns the commit (an isolated job checkout), committing happens
|
|
44
|
+
* after this check; counting it as remaining failed every finished writing job (route mx41fcky, 2026-12-01).
|
|
45
|
+
*/
|
|
46
|
+
export function goalCheckPrompt(goal, request = {}) {
|
|
47
|
+
const harnessCommits = request.isolated === true || (typeof request.contextCwd === 'string' && typeof request.cwd === 'string' &&
|
|
48
|
+
path.resolve(request.contextCwd) !== path.resolve(request.cwd));
|
|
49
|
+
return `Check the goal against what you did. Goal: ${goal}\nReturn only JSON with schema ${JSON.stringify(GOAL_SCHEMA)}. List concrete evidence and, in remaining, only unfinished work of this goal. Put anything else, such as work outside this goal, in notes.${harnessCommits ? ' Metaharness commits your changes on the job branch after this check, so uncommitted changes are expected: never list committing, pushing or branch creation as remaining.' : ''}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function runSession({ request, adapter, binary, args, env, prompt, progress, register = () => () => {},
|
|
53
|
+
driverFactory, controlToolsFactory = createMcpTools, onFrame = () => {}, runAs } = {}) {
|
|
54
|
+
const options = sessionOptions(request);
|
|
55
|
+
options.captureExecution = adapter.id === 'openclaw';
|
|
56
|
+
options.trackTurns = true;
|
|
57
|
+
// Internal reasoning is one bounded, unsaved generation: no native goal and no goal-check turn.
|
|
58
|
+
const internal = options.internalReasoning === true;
|
|
59
|
+
let goal = options.goal || request.contextTask || request.prompt;
|
|
60
|
+
if (internal) { delete options.goal; options.ephemeral = true; } else options.goal = goal.slice(0, 4000);
|
|
61
|
+
const job = request.jobId || process.env.TR_METAHARNESS_JOB || `session-${randomUUID()}`;
|
|
62
|
+
const budget = budgets.get(job) || new Map();
|
|
63
|
+
budgets.set(job, budget);
|
|
64
|
+
const runId = randomUUID();
|
|
65
|
+
const config = mcpConfigFor(job, options);
|
|
66
|
+
if (adapter.id === 'claude') options.mcpConfig = config.claude;
|
|
67
|
+
if (adapter.id === 'codex') {
|
|
68
|
+
// exec flags belong to the old one-shot surface, not app-server.
|
|
69
|
+
const start = args.indexOf('exec');
|
|
70
|
+
const prefix = start < 0 ? [] : args.slice(0, start);
|
|
71
|
+
const model = args.lastIndexOf('--model');
|
|
72
|
+
args = [...prefix, ...(model >= 0 ? ['-c', `model=${JSON.stringify(args[model + 1])}`] : []), ...config.codex];
|
|
73
|
+
}
|
|
74
|
+
let driver, tools, watcher, deferredWatcher, replyWaiter = null, timer, stopResult, stopTask, turns = 0;
|
|
75
|
+
const deferredReplies = new Map();
|
|
76
|
+
let resolveStop;
|
|
77
|
+
const stopped = new Promise(resolve => { resolveStop = resolve; });
|
|
78
|
+
const usage = { inputTokens: null, outputTokens: null, costUsd: null };
|
|
79
|
+
const totals = () => [...budget.values()].reduce((sum, entry) => ({
|
|
80
|
+
inputTokens: sum.inputTokens + (entry.usage.inputTokens || 0), outputTokens: sum.outputTokens + (entry.usage.outputTokens || 0),
|
|
81
|
+
costUsd: sum.costUsd + (entry.usage.costUsd || 0), turns: sum.turns + entry.turns,
|
|
82
|
+
}), { inputTokens: 0, outputTokens: 0, costUsd: 0, turns: 0 });
|
|
83
|
+
const toolResults = [];
|
|
84
|
+
const emit = event => progress ? progress.event(event) : appendEvent(job, event);
|
|
85
|
+
const stop = (failureKind, error) => {
|
|
86
|
+
if (stopResult) return;
|
|
87
|
+
stopResult = { ok: false, failureKind, error };
|
|
88
|
+
resolveStop(stopResult);
|
|
89
|
+
stopTask = Promise.resolve(driver?.interrupt()).catch(() => {});
|
|
90
|
+
};
|
|
91
|
+
budget.set(runId, { usage, turns: 0, stop });
|
|
92
|
+
const limit = error => { for (const entry of budget.values()) entry.stop?.('limit', error); };
|
|
93
|
+
const onEvent = event => {
|
|
94
|
+
if (event.kind !== 'usage') emit(['question', 'approval'].includes(event.kind) ? { ...event, kind: 'native-request' } : event);
|
|
95
|
+
if (event.kind === 'usage') {
|
|
96
|
+
for (const key of ['inputTokens', 'outputTokens', 'costUsd']) if (event[key] != null) {
|
|
97
|
+
usage[key] = adapter.id === 'claude' ? (usage[key] || 0) + event[key] : event[key];
|
|
98
|
+
}
|
|
99
|
+
const used = totals();
|
|
100
|
+
emit({ ...event, ...used, limits: { maxTurns: options.maxTurns, maxTokens: options.maxTokens, maxBudgetUsd: options.maxBudgetUsd } });
|
|
101
|
+
if (options.maxTokens !== undefined && used.inputTokens + used.outputTokens >= options.maxTokens) limit('Job token limit reached.');
|
|
102
|
+
if (options.maxBudgetUsd !== undefined && usage.costUsd !== null && used.costUsd >= options.maxBudgetUsd) limit('Job budget limit reached.');
|
|
103
|
+
if (options.maxBudgetUsd !== undefined && usage.costUsd === null && adapter.id !== 'claude') stop('limit', 'The harness did not report cost, so the USD cap cannot be enforced.');
|
|
104
|
+
}
|
|
105
|
+
if (event.kind === 'finish' || event.kind === 'turn-finish') {
|
|
106
|
+
turns += event.turns || 1;
|
|
107
|
+
budget.get(runId).turns = turns;
|
|
108
|
+
if (options.maxTurns !== undefined && totals().turns > options.maxTurns) limit('Job turn limit reached.');
|
|
109
|
+
}
|
|
110
|
+
const item = event.item;
|
|
111
|
+
if (event.kind === 'step-end' && toolResults.length < 20 && (event.toolUseId || item?.type === 'commandExecution')) {
|
|
112
|
+
toolResults.push({ tool: item ? 'shell' : 'tool', status: event.isError || item?.exitCode ? 'failed' : 'completed',
|
|
113
|
+
...(Number.isInteger(item?.exitCode) ? { exitCode: item.exitCode } : {}), output: String(item?.aggregatedOutput || event.text || '').slice(0, 4096) });
|
|
114
|
+
}
|
|
115
|
+
if (event.kind === 'question' || event.kind === 'approval') {
|
|
116
|
+
// Native requests use the same policy, timeout and operator path as MCP.
|
|
117
|
+
void Promise.resolve().then(async () => {
|
|
118
|
+
if (!tools) return;
|
|
119
|
+
const answer = await tools.call(event.kind === 'question' ? 'ask' : 'approve', event.kind === 'question'
|
|
120
|
+
? { questions: event.questions || event.request?.questions || [event.text || 'Reply to the agent.'] }
|
|
121
|
+
: { tool_name: event.request?.tool_name || event.request?.command || event.method || 'tool', input: event.request || {} },
|
|
122
|
+
// A native request pauses the harness itself with no model call, so it waits for the answer here.
|
|
123
|
+
{ defer: false });
|
|
124
|
+
let value = answer.content[0].text;
|
|
125
|
+
if (event.kind === 'approval') {
|
|
126
|
+
const approval = JSON.parse(value);
|
|
127
|
+
value = adapter.id === 'claude' ? approval : approval.behavior === 'allow' ? 'allow' : 'deny';
|
|
128
|
+
}
|
|
129
|
+
await driver.answer(event.requestId, value);
|
|
130
|
+
emit({ kind: 'ack', requestId: event.requestId, ok: true, text: 'Native request answered.' });
|
|
131
|
+
}).catch(error => emit({ kind: 'error', text: error.message }));
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const factory = driverFactory || (adapter.id === 'claude' ? createClaudeDriver : adapter.id === 'codex' ? createCodexDriver : createResumeDriver);
|
|
135
|
+
const used = totals();
|
|
136
|
+
const driverOptions = { ...options,
|
|
137
|
+
...(options.maxTurns !== undefined ? { maxTurns: Math.max(1, options.maxTurns - used.turns) } : {}),
|
|
138
|
+
...(options.maxBudgetUsd !== undefined ? { maxBudgetUsd: Math.max(0, options.maxBudgetUsd - used.costUsd) } : {}),
|
|
139
|
+
...(options.maxTokens !== undefined ? { maxTokens: Math.max(1, options.maxTokens - used.inputTokens - used.outputTokens) } : {}) };
|
|
140
|
+
driver = factory({ harness: adapter, binary, args, cwd: request.cwd,
|
|
141
|
+
env: { ...env, TR_METAHARNESS_JOB: job }, job: { id: job }, options: driverOptions, onEvent, onFrame,
|
|
142
|
+
...(runAs ? { runAs } : {}) });
|
|
143
|
+
tools = controlToolsFactory({ job, approvalPolicy: options.approvalPolicy || 'auto', questionTimeoutMs: options.questionTimeoutMs });
|
|
144
|
+
const unregister = register(() => { stop('cancelled', 'Job cancelled.'); void driver.close(); });
|
|
145
|
+
const wait = promise => Promise.race([promise, stopped]);
|
|
146
|
+
const capabilities = () => ({ ...driver.capabilities,
|
|
147
|
+
goal: driver.capabilities.goal === 'native' ? 'native' : 'metaharness',
|
|
148
|
+
schema: driver.capabilities.schema === 'native' ? 'native' : 'metaharness',
|
|
149
|
+
limits: options.maxTokens !== undefined || adapter.id !== 'claude' ? 'metaharness' : driver.capabilities.limits });
|
|
150
|
+
const next = async (text, schema) => {
|
|
151
|
+
if (options.maxTurns !== undefined && totals().turns >= options.maxTurns) return { ok: false, failureKind: 'limit', error: 'Job turn limit reached.' };
|
|
152
|
+
return wait(driver.next(text, { resultSchema: schema,
|
|
153
|
+
...(options.maxTurns !== undefined ? { maxTurns: options.maxTurns - totals().turns } : {}),
|
|
154
|
+
...(options.maxBudgetUsd !== undefined && usage.costUsd !== null ? { maxBudgetUsd: Math.max(0, options.maxBudgetUsd - totals().costUsd) } : {}) }));
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
timer = setTimeout(() => stop('process', 'Session timeout.'), request.timeoutMs || 900000);
|
|
158
|
+
if (options.maxTurns !== undefined && used.turns >= options.maxTurns || options.maxTokens !== undefined && used.inputTokens + used.outputTokens >= options.maxTokens || options.maxBudgetUsd !== undefined && used.costUsd >= options.maxBudgetUsd) {
|
|
159
|
+
return { ok: false, failureKind: 'limit', error: 'Job limit reached before launch.', usage, turns };
|
|
160
|
+
}
|
|
161
|
+
if (options.maxBudgetUsd === 0) return { ok: false, failureKind: 'limit', error: 'Job budget limit reached before launch.', usage, turns };
|
|
162
|
+
await wait(driver.start(internal ? `${INTERNAL_JOB_MARKER}\n${prompt}` : `${prompt}\n\nJob goal: ${goal}`));
|
|
163
|
+
if (stopResult) return stopResult;
|
|
164
|
+
emit({ kind: 'capabilities', text: 'Session controls reported.', capabilities: capabilities() });
|
|
165
|
+
deferredWatcher = tailInbox(job, command => {
|
|
166
|
+
if (command.type !== 'reply' || !command.requestId) return false;
|
|
167
|
+
deferredReplies.set(command.requestId, command.text);
|
|
168
|
+
replyWaiter?.();
|
|
169
|
+
return { via: 'metaharness' };
|
|
170
|
+
}, { recipient: 'deferred' });
|
|
171
|
+
watcher = tailInbox(job, async command => {
|
|
172
|
+
if (command.type === 'reply') return driver.send(command.text);
|
|
173
|
+
if (command.type === 'approve') return driver.answer(command.requestId, command.value);
|
|
174
|
+
if (command.type === 'interrupt') { await driver.interrupt(); stop('interrupted', 'Turn interrupted; the session can be resumed.'); return { via: 'metaharness' }; }
|
|
175
|
+
if (command.type === 'goal') {
|
|
176
|
+
if (driver.setGoal) await driver.setGoal(command.text); else await driver.send(`Job goal: ${command.text}`);
|
|
177
|
+
goal = command.text;
|
|
178
|
+
return { via: driver.setGoal ? 'native' : 'metaharness' };
|
|
179
|
+
}
|
|
180
|
+
if (command.type === 'fork') {
|
|
181
|
+
const fork = await driver.fork({ atTurn: command.atTurn });
|
|
182
|
+
emit({ kind: 'fork', commandId: command.id, ...fork });
|
|
183
|
+
return { via: driver.capabilities.fork };
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
186
|
+
});
|
|
187
|
+
let result = await wait(driver.done);
|
|
188
|
+
// Deferred questions (A-125): the agent ended its turn after asking. Hold the session with no
|
|
189
|
+
// model calls until the operator replies, then start the next turn with the answer.
|
|
190
|
+
while (result.ok && !stopResult && !internal) {
|
|
191
|
+
const open = waitingRequests(job).filter(r => r.kind === 'question' && r.source === 'deferred');
|
|
192
|
+
if (!open.length) break;
|
|
193
|
+
emit({ kind: 'waiting', text: `Waiting for the operator on ${open.length} question(s); no model calls until a reply.` });
|
|
194
|
+
const answer = await wait(new Promise(resolve => {
|
|
195
|
+
const check = () => { const hit = open.find(r => deferredReplies.has(r.requestId)); if (hit) { replyWaiter = null; clearTimeout(limit); resolve({ request: hit, text: deferredReplies.get(hit.requestId) }); } };
|
|
196
|
+
const limit = setTimeout(() => { replyWaiter = null; resolve({ request: open[0], text: NO_ANSWER, timeout: true }); }, options.questionTimeoutMs ?? QUESTION_TIMEOUT_MS);
|
|
197
|
+
replyWaiter = check; check();
|
|
198
|
+
}));
|
|
199
|
+
if (!answer || stopResult) break;
|
|
200
|
+
appendEvent(job, { kind: 'ack', command: 'ask', requestId: answer.request.requestId, ok: true, value: answer.text, text: answer.text, ...(answer.timeout ? { timeout: true } : {}) });
|
|
201
|
+
result = await next(`The operator answered your question ${answer.request.text}: ${answer.text}\nContinue the task.`);
|
|
202
|
+
}
|
|
203
|
+
if (result.ok && options.maxTokens !== undefined && usage.inputTokens === null && usage.outputTokens === null) {
|
|
204
|
+
result = { ...result, ok: false, failureKind: 'limit', error: 'The harness did not report token usage, so the token cap cannot be enforced.' };
|
|
205
|
+
}
|
|
206
|
+
if (result.ok && options.maxBudgetUsd !== undefined && usage.costUsd === null) {
|
|
207
|
+
result = { ...result, ok: false, failureKind: 'limit', error: 'The harness did not report cost, so the USD cap cannot be enforced.' };
|
|
208
|
+
}
|
|
209
|
+
if ((result.ok || result.failureKind === 'schema') && options.resultSchema !== undefined) {
|
|
210
|
+
let parsed = readResult(result, options.resultSchema);
|
|
211
|
+
if (parsed.errors.length && !internal) {
|
|
212
|
+
const corrected = await next(`Correct your final result once. Return only JSON matching ${JSON.stringify(options.resultSchema)}. Errors: ${parsed.errors.join('; ')}`, options.resultSchema);
|
|
213
|
+
if (!corrected.ok) return { ...corrected, usage: { ...usage }, turns, capabilities: { ...driver.capabilities } };
|
|
214
|
+
result = corrected; parsed = readResult(result, options.resultSchema);
|
|
215
|
+
}
|
|
216
|
+
if (parsed.errors.length) result = { ...result, ok: false, failureKind: 'schema', error: parsed.errors.join('; ') };
|
|
217
|
+
else result.structured = parsed.value;
|
|
218
|
+
}
|
|
219
|
+
const work = result;
|
|
220
|
+
if (result.ok && !internal) {
|
|
221
|
+
const goalPrompt = goalCheckPrompt(goal, request);
|
|
222
|
+
let check = await next(goalPrompt, GOAL_SCHEMA);
|
|
223
|
+
// Like a result schema, the goal check gets one correction turn when its
|
|
224
|
+
// reply does not parse (a schema failure) or does not validate; a second
|
|
225
|
+
// bad reply fails as before.
|
|
226
|
+
let parsed = check.ok || check.failureKind === 'schema' ? readResult(check, GOAL_SCHEMA) : { errors: [] };
|
|
227
|
+
if (check.failureKind === 'schema' || (check.ok && parsed.errors.length)) {
|
|
228
|
+
const why = check.failureKind === 'schema' ? check.error : parsed.errors.join('; ');
|
|
229
|
+
check = await next(`Correct your goal check once. Return only JSON matching ${JSON.stringify(GOAL_SCHEMA)}. Errors: ${why}`, GOAL_SCHEMA);
|
|
230
|
+
parsed = check.ok || check.failureKind === 'schema' ? readResult(check, GOAL_SCHEMA) : { errors: [] };
|
|
231
|
+
}
|
|
232
|
+
// A failed goal check is a goal failure, even when its reply would not
|
|
233
|
+
// parse: the driver's schema error belongs to the goal check.
|
|
234
|
+
if (!check.ok) result = check.failureKind === 'schema'
|
|
235
|
+
? { ...work, ok: false, failureKind: 'goal', error: check.error, response: check.response ?? work.response, usage: check.usage ?? work.usage }
|
|
236
|
+
: { ...work, ...check };
|
|
237
|
+
else result = { ...work, goalCheck: parsed.value, ...(parsed.errors.length ? { ok: false, failureKind: 'goal', error: parsed.errors.join('; ') }
|
|
238
|
+
: !parsed.value.met ? { ok: false, failureKind: 'goal', error: parsed.value.remaining.join('\n') || 'The goal was not met.' }
|
|
239
|
+
: !parsed.value.evidence.length || parsed.value.remaining.length ? { ok: false, failureKind: 'goal', error: 'The goal check needs evidence and no remaining work.' } : {}) };
|
|
240
|
+
}
|
|
241
|
+
return { ...result, ...stopResult, usage: { ...usage }, turns,
|
|
242
|
+
capabilities: capabilities(),
|
|
243
|
+
toolResults, toolExecutionVerified: toolResults.length > 0, commandExecutionVerified: toolResults.some(t => t.tool === 'shell' && t.status === 'completed') };
|
|
244
|
+
} finally {
|
|
245
|
+
budget.get(runId).stop = null;
|
|
246
|
+
clearTimeout(timer); unregister();
|
|
247
|
+
// Close outstanding questions before waiting for the inbox consumer.
|
|
248
|
+
await tools.close();
|
|
249
|
+
if (stopTask) {
|
|
250
|
+
let grace;
|
|
251
|
+
try { await Promise.race([stopTask, new Promise(resolve => { grace = setTimeout(resolve, 1000); })]); }
|
|
252
|
+
finally { clearTimeout(grace); }
|
|
253
|
+
}
|
|
254
|
+
await driver.close();
|
|
255
|
+
await watcher?.close();
|
|
256
|
+
await deferredWatcher?.close();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** Continue a stored job on its branch, without reusing a deleted checkout. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { configDir } from './paths.mjs';
|
|
8
|
+
import { resolveJob } from './jobs.mjs';
|
|
9
|
+
import { appendCommand, jobPaths } from './control.mjs';
|
|
10
|
+
import { createWorktree, removeWorktree, commitAll, isDirty, provideDependencies } from './worktree.mjs';
|
|
11
|
+
import { dispatchWithReceipt } from './dispatch.mjs';
|
|
12
|
+
import { continuationTimeoutMs } from './dispatch-request.mjs';
|
|
13
|
+
|
|
14
|
+
export async function continueJob(target, text, { fork = false, atTurn, dispatchFn, execFileFn = promisify(execFile), timeoutMs = 30000,
|
|
15
|
+
deadlineMs, background = false } = {}) {
|
|
16
|
+
const job = resolveJob(target);
|
|
17
|
+
if (!fork && !job.result) throw new Error('Resume requires a finished job; use reply for a running job.');
|
|
18
|
+
if (typeof text !== 'string' || !text.trim()) throw new Error('A continuation message is required.');
|
|
19
|
+
const owner = job.result?.execution?.node || job.record?.node;
|
|
20
|
+
if (owner && owner !== 'local') {
|
|
21
|
+
const quote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
22
|
+
const argv = [fork ? 'fork' : 'resume', job.result?.execution?.remoteJob || job.record?.remoteJob || job.id, ...(fork ? atTurn ? ['--at', atTurn] : [] : [text]),
|
|
23
|
+
...(deadlineMs !== undefined ? ['--timeout-ms', String(deadlineMs)] : []), '--json'];
|
|
24
|
+
const report = await execFileFn(process.env.TOTAL_RECALL_BIN || 'total-recall', ['mesh', 'exec', owner,
|
|
25
|
+
`total-recall meta-harness ${argv.map(quote).join(' ')}`], { encoding: 'utf8', timeout: 600000 });
|
|
26
|
+
return JSON.parse(report.stdout);
|
|
27
|
+
}
|
|
28
|
+
const attempt = job.result?.attempts?.at(-1) || job.result;
|
|
29
|
+
const file = attempt?.progressFile || job.result?.progressFile || path.join(configDir(), 'jobs', `${job.id}.events.jsonl`);
|
|
30
|
+
let saved, status;
|
|
31
|
+
try {
|
|
32
|
+
saved = JSON.parse(fs.readFileSync(file.replace('.events.jsonl', '.session.json'), 'utf8'));
|
|
33
|
+
status = JSON.parse(fs.readFileSync(file.replace('.events.jsonl', '.status.json'), 'utf8'));
|
|
34
|
+
} catch { throw new Error('This job has no stored session.'); }
|
|
35
|
+
saved.request = { ...saved.request,
|
|
36
|
+
timeoutMs: continuationTimeoutMs({ override: deadlineMs, saved: saved.request?.timeoutMs, background }) };
|
|
37
|
+
let sessionId = attempt?.sessionId || status.session_id;
|
|
38
|
+
if (!sessionId) throw new Error('This job has no resumable session ID.');
|
|
39
|
+
if (fork && !job.result) {
|
|
40
|
+
const delivery = await appendCommand(job.id, { type: 'fork', atTurn });
|
|
41
|
+
const deadline = Date.now() + timeoutMs;
|
|
42
|
+
let event;
|
|
43
|
+
while (!event && Date.now() < deadline) {
|
|
44
|
+
const rows = fs.readFileSync(jobPaths(job.id).events, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse);
|
|
45
|
+
const ack = rows.find(row => row.commandId === delivery.command.id && row.kind === 'ack');
|
|
46
|
+
if (ack?.ok === false) throw new Error(ack.text);
|
|
47
|
+
event = rows.find(row => row.commandId === delivery.command.id && row.kind === 'fork');
|
|
48
|
+
if (!event) await new Promise(resolve => setTimeout(resolve, 20));
|
|
49
|
+
}
|
|
50
|
+
if (!event?.sessionId) throw new Error('Fork did not return a session ID before the timeout.');
|
|
51
|
+
sessionId = event.sessionId;
|
|
52
|
+
}
|
|
53
|
+
const parentBranch = attempt?.branch || job.result?.branch || saved.branch;
|
|
54
|
+
if (!fork && (!parentBranch || !parentBranch.startsWith('meta-harness/'))) {
|
|
55
|
+
// A dispatch job worked in its own folder and has no job branch: resume it there, as it ran (A-123).
|
|
56
|
+
if (!saved.workspace) throw new Error('This job has no saved job branch or workspace.');
|
|
57
|
+
const result = await dispatchWithReceipt({ ...saved.request, sessionId, cwd: saved.workspace, contextCwd: saved.workspace,
|
|
58
|
+
contextTask: text, prompt: text, permissions: saved.request?.permissions || { read: true, write: true } },
|
|
59
|
+
{ dispatchFn, role: 'Resume' });
|
|
60
|
+
return { ...result, parentJob: job.id, workspace: saved.workspace };
|
|
61
|
+
}
|
|
62
|
+
const branch = fork ? `meta-harness/fork-${randomUUID()}` : parentBranch;
|
|
63
|
+
const cwd = saved.workspace;
|
|
64
|
+
const directory = createWorktree(cwd, { branch, existingBranch: !fork, ref: parentBranch || 'HEAD' });
|
|
65
|
+
let result, keep = false;
|
|
66
|
+
try {
|
|
67
|
+
provideDependencies(cwd, directory);
|
|
68
|
+
result = await dispatchWithReceipt({ ...saved.request, sessionId, forkSession: fork && Boolean(job.result), atTurn,
|
|
69
|
+
cwd: directory, contextCwd: cwd, contextTask: text, prompt: text, isolated: true,
|
|
70
|
+
permissions: { read: true, write: true } }, { dispatchFn, role: fork ? 'Fork' : 'Resume' });
|
|
71
|
+
const commit = commitAll(directory, `meta-harness: ${fork ? 'fork' : 'resume'} ${job.id}`);
|
|
72
|
+
return { ...result, parentJob: job.id, branch, ...(commit ? result.ok ? { commit } : { wip: commit } : {}) };
|
|
73
|
+
} catch (error) {
|
|
74
|
+
keep = isDirty(directory);
|
|
75
|
+
return { ok: false, error: error.message, branch, ...(keep ? { keptWorktree: directory } : {}) };
|
|
76
|
+
} finally { if (!keep) removeWorktree(cwd, directory); }
|
|
77
|
+
}
|
package/src/setup.mjs
CHANGED
|
@@ -26,10 +26,13 @@ export async function setupIntegrations({ node, cwd = process.cwd(), env = proce
|
|
|
26
26
|
const target=mesh.findMeshNode(node);
|
|
27
27
|
if(!target)throw new Error('Maintenance node is not recorded in the mesh');
|
|
28
28
|
const plugin=getPlugin('meta-harness',cwd) || getPlugin('cli-agents',cwd);
|
|
29
|
-
if(!plugin?.valid)throw new Error('
|
|
30
|
-
await ensurePluginRecord(plugin);
|
|
29
|
+
if(!plugin?.valid)throw new Error('Metaharness (cli-agents) is not installed in the selected workspace');
|
|
30
|
+
const record=await ensurePluginRecord(plugin);
|
|
31
31
|
placement=target.hostname;
|
|
32
|
-
|
|
32
|
+
const manifest=JSON.parse(fs.readFileSync(new URL('../plugin.json',import.meta.url),'utf8'));
|
|
33
|
+
const taskNodes={...(record?.task_nodes || {})};
|
|
34
|
+
for(const task of manifest.tasks.filter(task=>task.placement==='selected-node'))taskNodes[task.command]=placement;
|
|
35
|
+
await patchPluginRecord(plugin,{task_nodes:taskNodes});
|
|
33
36
|
}
|
|
34
37
|
return {ok:true,connected,universalInstructions:'AGENTS.md; every dispatch also receives a freshly generated bootstrap',maintenanceNode:placement};
|
|
35
38
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Bind only to the verified native Total Recall storage contract. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
function resolveStateStoreSource() {
|
|
7
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const candidates = [process.env.TR_PACKAGE_ROOT, path.resolve(here, '..', '..', 'total-recall'), path.resolve(process.cwd(), '..', 'total-recall'), process.cwd()].filter(Boolean);
|
|
9
|
+
for (const root of candidates) {
|
|
10
|
+
try {
|
|
11
|
+
if (JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).name !== 'total-recall-brain') continue;
|
|
12
|
+
const file = path.join(root, 'src/core/plugin-state-store.mjs');
|
|
13
|
+
if (fs.existsSync(file)) return file;
|
|
14
|
+
} catch { /* try the next candidate */ }
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
const source = resolveStateStoreSource();
|
|
19
|
+
if (!source) throw new Error('Cannot bind the native Total Recall storage contract: no total-recall-brain host found. Run inside a Total Recall host or set TR_PACKAGE_ROOT.');
|
|
20
|
+
export const { PluginStateStore } = await import(pathToFileURL(source).href);
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/** Usage figures the harnesses themselves recorded on this machine. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { codexHomes } from './paths.mjs';
|
|
6
|
+
|
|
7
|
+
function recentSessionFiles(dir, depth = 3, limit = 5) {
|
|
8
|
+
let names;
|
|
9
|
+
try { names = fs.readdirSync(dir).sort().reverse(); } catch { return []; }
|
|
10
|
+
const files = [];
|
|
11
|
+
for (const name of names) {
|
|
12
|
+
const full = path.join(dir, name);
|
|
13
|
+
if (depth > 0) files.push(...recentSessionFiles(full, depth - 1, limit));
|
|
14
|
+
else if (name.endsWith('.jsonl')) files.push(full);
|
|
15
|
+
if (files.length >= limit) break;
|
|
16
|
+
}
|
|
17
|
+
return files;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Codex logs its real rate-limit windows. A window whose reset has passed no longer applies. */
|
|
21
|
+
export function readCodexRateLimits({ sessionsDir, now = Date.now() } = {}) {
|
|
22
|
+
const homes = codexHomes(process.env.CODEX_HOME, process.env.HOME);
|
|
23
|
+
const dirs = sessionsDir ? [sessionsDir] : Object.values(homes).map(home => path.join(home, 'sessions'));
|
|
24
|
+
return dirs.map(dir => latestCodexRateLimits(dir, now)).filter(Boolean)
|
|
25
|
+
.sort((a, b) => Date.parse(b.observedAt) - Date.parse(a.observedAt))[0] || null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function latestCodexRateLimits(sessionsDir, now) {
|
|
29
|
+
const live = window => (window && typeof window.used_percent === 'number' && window.resets_at * 1000 > now ? window : null);
|
|
30
|
+
for (const file of recentSessionFiles(sessionsDir)) {
|
|
31
|
+
const lines = fs.readFileSync(file, 'utf8').trim().split('\n').reverse();
|
|
32
|
+
for (const line of lines) {
|
|
33
|
+
if (!line.includes('"used_percent"')) continue;
|
|
34
|
+
try {
|
|
35
|
+
const event = JSON.parse(line);
|
|
36
|
+
const limits = event.payload?.rate_limits;
|
|
37
|
+
if (!limits?.primary && !limits?.secondary) continue;
|
|
38
|
+
return { observedAt: event.timestamp || null, primary: live(limits.primary), secondary: live(limits.secondary) };
|
|
39
|
+
} catch { /* a partial line */ }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Name Codex windows by their real length. A plan with no five-hour limit reports one weekly
|
|
47
|
+
* window as `primary`, so slot order alone mislabels it. Without a length, the order is the only guide.
|
|
48
|
+
*/
|
|
49
|
+
export function codexWindowsByLength(limits) {
|
|
50
|
+
const windows = [limits?.primary, limits?.secondary].filter(Boolean);
|
|
51
|
+
const measured = windows.filter(window => Number.isFinite(window.window_minutes));
|
|
52
|
+
if (!measured.length) return { fiveHour: limits?.primary || null, weekly: limits?.secondary || null };
|
|
53
|
+
return {
|
|
54
|
+
fiveHour: measured.find(window => window.window_minutes <= 300) || null,
|
|
55
|
+
weekly: measured.find(window => window.window_minutes >= 7 * 24 * 60) || null,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Quota walls from measured usage: a live window at 100% blocks the harness until it resets. */
|
|
60
|
+
export function measuredWalls(limits = readCodexRateLimits()) {
|
|
61
|
+
const full = [limits?.primary, limits?.secondary].filter(window => window && window.used_percent >= 100);
|
|
62
|
+
if (!full.length) return {};
|
|
63
|
+
const until = Math.max(...full.map(window => window.resets_at)) * 1000;
|
|
64
|
+
return { codex: { until: new Date(until).toISOString(), resetReported: true, observedAt: limits.observedAt, message: 'Codex session log shows a rate-limit window at 100%.' } };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
function walkJsonlFiles(dir, cutoffMs, out = []) {
|
|
69
|
+
let entries;
|
|
70
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
|
|
71
|
+
for (const ent of entries) {
|
|
72
|
+
const p = path.join(dir, ent.name);
|
|
73
|
+
if (ent.isDirectory()) walkJsonlFiles(p, cutoffMs, out);
|
|
74
|
+
else if (ent.isFile() && p.endsWith('.jsonl')) {
|
|
75
|
+
try { if (fs.statSync(p).mtimeMs >= cutoffMs) out.push(p); } catch { /* ignore */ }
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const INTERNAL_MARKERS = [
|
|
82
|
+
'[total-recall:internal-job]',
|
|
83
|
+
'You are a Session Post-Mortem Analyst for an AI memory system called Total Recall.',
|
|
84
|
+
'You are a Rule Compliance Auditor for an AI memory system.',
|
|
85
|
+
];
|
|
86
|
+
const hasInternalMarker = text => typeof text === 'string' && INTERNAL_MARKERS.some(marker => text.includes(marker));
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The text of a Claude prompt the session was given, or null for a tool result or meta entry.
|
|
90
|
+
* Only the first prompt can mark a session internal: a session that reads Metaharness source or logs
|
|
91
|
+
* meets the marker text in tool results without being an internal job.
|
|
92
|
+
*/
|
|
93
|
+
function claudePromptText(entry) {
|
|
94
|
+
if (entry.type !== 'user' || entry.isMeta || !entry.message?.content) return null;
|
|
95
|
+
const { content } = entry.message;
|
|
96
|
+
if (typeof content === 'string') return content;
|
|
97
|
+
if (!Array.isArray(content) || content.some(block => block?.type === 'tool_result')) return null;
|
|
98
|
+
const text = content.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text);
|
|
99
|
+
return text.length ? text.join('\n') : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function emptyBucket() {
|
|
103
|
+
return { sessions: 0, interactiveSessions: 0, backgroundSessions: 0, internalSessions: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, totalTokens: 0, codexCredits: 0 };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function addToBucket(b, { internal, background, input = 0, cached = 0, output = 0, credits = 0 }) {
|
|
107
|
+
b.sessions += 1;
|
|
108
|
+
if (internal) b.internalSessions += 1;
|
|
109
|
+
if (background) b.backgroundSessions += 1; else b.interactiveSessions += 1;
|
|
110
|
+
b.inputTokens += input;
|
|
111
|
+
b.cachedTokens += cached;
|
|
112
|
+
b.outputTokens += output;
|
|
113
|
+
b.totalTokens += input + output;
|
|
114
|
+
b.codexCredits += credits;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Scan recent Claude and Codex session logs across 15m, 1h, 24h, and 7d windows.
|
|
119
|
+
* A session is background when it carries the internal-job marker, when Metaharness ran it
|
|
120
|
+
* (`backgroundSessionIds`, from its job records), or when it is a Claude subagent of such a session.
|
|
121
|
+
* Every other session, and every subagent it starts, is interactive: the operator's own foreground work.
|
|
122
|
+
*/
|
|
123
|
+
export function readSessionUsageAnalytics({
|
|
124
|
+
now = Date.now(),
|
|
125
|
+
home = process.env.HOME || os.homedir(),
|
|
126
|
+
codexHome = process.env.CODEX_HOME,
|
|
127
|
+
claudeHome = process.env.CLAUDE_HOME,
|
|
128
|
+
// Sessions that started earlier than this are skipped before their logs are parsed.
|
|
129
|
+
windowMs = 7 * 86400_000,
|
|
130
|
+
rollingHour = false,
|
|
131
|
+
backgroundSessionIds = new Set(),
|
|
132
|
+
} = {}) {
|
|
133
|
+
const win = { m15: 15 * 60_000, h1: 3600_000, h24: 86400_000, d7: 7 * 86400_000 };
|
|
134
|
+
const cutoff = now - Math.min(windowMs, win.d7);
|
|
135
|
+
const tooOld = (firstTs) => firstTs > 0 && now - firstTs > windowMs;
|
|
136
|
+
const makeHarness = () => ({ m15: emptyBucket(), h1: emptyBucket(), h24: emptyBucket(), d7: emptyBucket() });
|
|
137
|
+
const codex = makeHarness();
|
|
138
|
+
const claude = makeHarness();
|
|
139
|
+
const rolling = { totalTokens: 0, backgroundTokens: 0, interactiveTokens: 0, sessions: [] };
|
|
140
|
+
const seenHourlyClaude = new Set();
|
|
141
|
+
const inHour = time => rollingHour && time >= now - win.h1 && time <= now;
|
|
142
|
+
const addRolling = ({ id, harness, internal, background, subagent, startedAt, tokens1h }) => {
|
|
143
|
+
rolling.totalTokens += tokens1h;
|
|
144
|
+
if (background) rolling.backgroundTokens += tokens1h; else rolling.interactiveTokens += tokens1h;
|
|
145
|
+
rolling.sessions.push({ id: id || null, harness, internal, background, subagent, startedAt: startedAt || null, tokens1h });
|
|
146
|
+
};
|
|
147
|
+
const addBuckets = (harness, firstTs, row) => {
|
|
148
|
+
const age = now - firstTs;
|
|
149
|
+
if (age > win.d7 || tooOld(firstTs)) return;
|
|
150
|
+
if (age <= win.m15) addToBucket(harness.m15, row);
|
|
151
|
+
if (age <= win.h1) addToBucket(harness.h1, row);
|
|
152
|
+
if (age <= win.h24) addToBucket(harness.h24, row);
|
|
153
|
+
addToBucket(harness.d7, row);
|
|
154
|
+
};
|
|
155
|
+
const delta = (current = 0, previous = 0) => current >= previous ? current - previous : current;
|
|
156
|
+
|
|
157
|
+
const homes = codexHomes(codexHome, home);
|
|
158
|
+
const codexFiles = Object.entries(homes).flatMap(([type, base]) =>
|
|
159
|
+
['sessions', 'archived_sessions'].flatMap(dir => walkJsonlFiles(path.join(base, dir), cutoff))
|
|
160
|
+
.map(file => ({ file, managed: type === 'managed' })));
|
|
161
|
+
// A continued legacy rollout also exists in the desktop home. Count its managed copy once.
|
|
162
|
+
const codexRollouts = new Map(codexFiles.map(entry => [path.basename(entry.file), entry]));
|
|
163
|
+
for (const { file, managed } of codexRollouts.values()) {
|
|
164
|
+
let raw;
|
|
165
|
+
try { raw = fs.readFileSync(file, 'utf8'); } catch { continue; }
|
|
166
|
+
let internal = false, firstPromptSeen = false, lastTotal = null, firstTs = 0, model = '', sessionId;
|
|
167
|
+
let hourTokens = 0;
|
|
168
|
+
for (const line of raw.split('\n')) {
|
|
169
|
+
if (!line) continue;
|
|
170
|
+
let o;
|
|
171
|
+
try { o = JSON.parse(line); } catch { continue; }
|
|
172
|
+
const at = Date.parse(o.timestamp);
|
|
173
|
+
if (!firstTs && Number.isFinite(at)) firstTs = at;
|
|
174
|
+
if (!rollingHour && tooOld(firstTs)) break;
|
|
175
|
+
if (o.type === 'session_meta' && !sessionId && o.payload?.id) sessionId = String(o.payload.id);
|
|
176
|
+
if ((o.type === 'turn_context' || o.type === 'session_meta') && o.payload?.model) model = String(o.payload.model);
|
|
177
|
+
if (o.type === 'event_msg' && o.payload?.type === 'thread_goal_updated' && hasInternalMarker(o.payload.goal?.objective)) internal = true;
|
|
178
|
+
// Only the first prompt marks a session: later turns can quote the marker without being internal work.
|
|
179
|
+
if (o.type === 'event_msg' && o.payload?.type === 'user_message' && !firstPromptSeen) {
|
|
180
|
+
firstPromptSeen = true;
|
|
181
|
+
if (hasInternalMarker(o.payload.message)) internal = true;
|
|
182
|
+
}
|
|
183
|
+
if (o.type === 'event_msg' && o.payload?.type === 'token_count' && o.payload?.info?.total_token_usage) {
|
|
184
|
+
const usage = o.payload.info.total_token_usage;
|
|
185
|
+
if (inHour(at)) {
|
|
186
|
+
// Cached input is a re-read of context already paid for, not new spend (A-130).
|
|
187
|
+
const input = delta(usage.input_tokens, lastTotal?.input_tokens);
|
|
188
|
+
const cachedInput = Math.min(input, delta(usage.cached_input_tokens || 0, lastTotal?.cached_input_tokens || 0));
|
|
189
|
+
hourTokens += input - cachedInput + delta(usage.output_tokens, lastTotal?.output_tokens);
|
|
190
|
+
}
|
|
191
|
+
lastTotal = usage;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (!firstTs) { try { firstTs = fs.statSync(file).mtimeMs; } catch { continue; } }
|
|
195
|
+
const background = managed || internal || (sessionId !== undefined && backgroundSessionIds.has(sessionId));
|
|
196
|
+
if (rollingHour) addRolling({ id: sessionId, harness: 'codex', internal, background, subagent: false, startedAt: firstTs, tokens1h: hourTokens });
|
|
197
|
+
const input = lastTotal?.input_tokens || 0;
|
|
198
|
+
const cached = lastTotal?.cached_input_tokens || 0;
|
|
199
|
+
const output = lastTotal?.output_tokens || 0;
|
|
200
|
+
const uncached = Math.max(0, input - cached);
|
|
201
|
+
const isLuna = model.includes('luna');
|
|
202
|
+
const credits = isLuna
|
|
203
|
+
? (uncached * 2.5 + cached * 0.25 + output * 12.5) / 1e6
|
|
204
|
+
: (uncached * 50 + cached * 2.5 + output * 250) / 1e6;
|
|
205
|
+
addBuckets(codex, firstTs, { internal, background, input, cached, output, credits });
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// A Claude subagent log carries its parent's sessionId, so it is classified after every parent is read.
|
|
209
|
+
const claudeRows = [];
|
|
210
|
+
const claudeBase = claudeHome || path.join(home, '.claude', 'projects');
|
|
211
|
+
for (const file of walkJsonlFiles(claudeBase, cutoff)) {
|
|
212
|
+
let raw;
|
|
213
|
+
try { raw = fs.readFileSync(file, 'utf8'); } catch { continue; }
|
|
214
|
+
let internal = false, firstPromptSeen = false, subagent = false, firstTs = 0, input = 0, cached = 0, output = 0, sessionId;
|
|
215
|
+
let hourTokens = 0;
|
|
216
|
+
const seen = new Set();
|
|
217
|
+
for (const line of raw.split('\n')) {
|
|
218
|
+
if (!line) continue;
|
|
219
|
+
let o;
|
|
220
|
+
try { o = JSON.parse(line); } catch { continue; }
|
|
221
|
+
const at = Date.parse(o.timestamp);
|
|
222
|
+
if (!firstTs && Number.isFinite(at)) firstTs = at;
|
|
223
|
+
if (!rollingHour && tooOld(firstTs)) break;
|
|
224
|
+
if (!sessionId && typeof o.sessionId === 'string' && o.sessionId) sessionId = o.sessionId;
|
|
225
|
+
if (o.isSidechain === true) subagent = true;
|
|
226
|
+
if (!firstPromptSeen) {
|
|
227
|
+
const prompt = claudePromptText(o);
|
|
228
|
+
if (prompt !== null) {
|
|
229
|
+
firstPromptSeen = true;
|
|
230
|
+
if (hasInternalMarker(prompt)) internal = true;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (o.type === 'assistant' && o.message?.usage) {
|
|
234
|
+
const msgId = o.message.id || o.uuid;
|
|
235
|
+
const u = o.message.usage;
|
|
236
|
+
if (inHour(at) && (!msgId || !seenHourlyClaude.has(msgId))) {
|
|
237
|
+
if (msgId) seenHourlyClaude.add(msgId);
|
|
238
|
+
// Cache reads are re-reads of context already paid for, not new spend (A-130).
|
|
239
|
+
hourTokens += (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.output_tokens || 0);
|
|
240
|
+
}
|
|
241
|
+
if (msgId && seen.has(msgId)) continue;
|
|
242
|
+
if (msgId) seen.add(msgId);
|
|
243
|
+
input += (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0);
|
|
244
|
+
cached += u.cache_read_input_tokens || 0;
|
|
245
|
+
output += u.output_tokens || 0;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (!firstTs) { try { firstTs = fs.statSync(file).mtimeMs; } catch { continue; } }
|
|
249
|
+
// Claude keeps a subagent's log under <parent session>/subagents/.
|
|
250
|
+
if (!sessionId && subagent) {
|
|
251
|
+
const parts = file.split(path.sep);
|
|
252
|
+
const at = parts.lastIndexOf('subagents');
|
|
253
|
+
if (at > 0) sessionId = parts[at - 1];
|
|
254
|
+
}
|
|
255
|
+
claudeRows.push({ sessionId, internal, subagent, firstTs, hourTokens, input, cached, output });
|
|
256
|
+
}
|
|
257
|
+
// A subagent shares its parent's sessionId, so a Metaharness job's subagents match backgroundSessionIds directly.
|
|
258
|
+
const internalParents = new Set(claudeRows.filter(row => !row.subagent && row.internal && row.sessionId).map(row => row.sessionId));
|
|
259
|
+
for (const row of claudeRows) {
|
|
260
|
+
const internal = row.internal || (row.subagent && internalParents.has(row.sessionId));
|
|
261
|
+
const background = internal || (row.sessionId !== undefined && backgroundSessionIds.has(row.sessionId));
|
|
262
|
+
if (rollingHour) addRolling({ id: row.sessionId, harness: 'claude', internal, background, subagent: row.subagent, startedAt: row.firstTs, tokens1h: row.hourTokens });
|
|
263
|
+
addBuckets(claude, row.firstTs, { internal, background, input: row.input + row.cached, cached: row.cached, output: row.output, credits: 0 });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return { observedAt: new Date(now).toISOString(), codex, claude, ...(rollingHour ? { rolling } : {}) };
|
|
267
|
+
}
|