tr-plugin-meta-harness 0.3.0 → 0.5.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/DESIGN.md +86 -0
  2. package/README.md +257 -11
  3. package/capability/BRICK.md +1 -1
  4. package/capability/index.mjs +154 -13
  5. package/cli.mjs +426 -41
  6. package/package.json +15 -3
  7. package/plugin.json +1457 -119
  8. package/skills/meta-harness/SKILL.md +63 -25
  9. package/src/adoption.mjs +102 -0
  10. package/src/agent-user.mjs +194 -0
  11. package/src/alerts.mjs +220 -14
  12. package/src/cascade.mjs +185 -0
  13. package/src/chat.mjs +80 -0
  14. package/src/codex-models.mjs +54 -0
  15. package/src/compat-harness.mjs +114 -0
  16. package/src/control.mjs +145 -0
  17. package/src/coordinator.mjs +267 -358
  18. package/src/dispatch-request.mjs +76 -0
  19. package/src/dispatch.mjs +119 -0
  20. package/src/documentation-authority.mjs +57 -0
  21. package/src/documentation.mjs +120 -32
  22. package/src/executor.mjs +101 -22
  23. package/src/gate-adapters/agy.mjs +155 -0
  24. package/src/gate-adapters/claude.mjs +303 -0
  25. package/src/gate-adapters/cline.mjs +111 -0
  26. package/src/gate-adapters/codex.mjs +164 -0
  27. package/src/gate-adapters/cursor.mjs +164 -0
  28. package/src/gate-adapters/devin.mjs +116 -0
  29. package/src/gate-adapters/dsh.mjs +284 -0
  30. package/src/gate-adapters/grok.mjs +112 -0
  31. package/src/gate-adapters/hermes.mjs +217 -0
  32. package/src/gate-adapters/hook-files.mjs +156 -0
  33. package/src/gate-adapters/index.mjs +131 -0
  34. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  35. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  36. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  37. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  38. package/src/gate-adapters/openclaw.mjs +288 -0
  39. package/src/gate-adapters/pi.mjs +146 -0
  40. package/src/gate.mjs +18 -0
  41. package/src/harness-updates.mjs +170 -0
  42. package/src/included-usage.mjs +344 -0
  43. package/src/jobs.mjs +135 -0
  44. package/src/json-reply.mjs +22 -0
  45. package/src/learner.mjs +97 -67
  46. package/src/maintenance.mjs +18 -0
  47. package/src/mcp-server.mjs +228 -0
  48. package/src/model-catalog.mjs +195 -0
  49. package/src/model-selection.mjs +67 -0
  50. package/src/paths.mjs +23 -0
  51. package/src/pool.mjs +69 -0
  52. package/src/process-manager.mjs +246 -0
  53. package/src/process-worker.mjs +18 -0
  54. package/src/reasoning.mjs +231 -0
  55. package/src/remote-operation.mjs +76 -0
  56. package/src/review.mjs +241 -0
  57. package/src/reviews.mjs +25 -0
  58. package/src/router-benchmark-corpus.mjs +16 -0
  59. package/src/router-benchmark.mjs +208 -0
  60. package/src/router.mjs +265 -346
  61. package/src/runtime.mjs +30 -8
  62. package/src/session/claude.mjs +358 -0
  63. package/src/session/codex.mjs +501 -0
  64. package/src/session/result.mjs +90 -0
  65. package/src/session/resume.mjs +393 -0
  66. package/src/session/run.mjs +258 -0
  67. package/src/session-jobs.mjs +77 -0
  68. package/src/setup.mjs +6 -3
  69. package/src/ssss-store.mjs +20 -0
  70. package/src/telemetry.mjs +267 -0
  71. package/src/termination.mjs +28 -0
  72. package/src/threads.mjs +150 -0
  73. package/src/usage-queue.mjs +137 -0
  74. package/src/verify-ssss.mjs +102 -0
  75. package/src/worker.mjs +955 -84
  76. package/src/worktree.mjs +244 -0
  77. package/ui/chunks/adapter-docs-freshness.md +16 -0
  78. package/ui/chunks/chat-handoff.md +26 -0
  79. package/ui/chunks/fleet-maintenance.md +21 -0
  80. package/ui/chunks/harness-inventory.md +21 -0
  81. package/ui/chunks/included-access.md +18 -0
  82. package/ui/chunks/included-usage-verification.md +15 -0
  83. package/ui/chunks/independent-review.md +17 -0
  84. package/ui/chunks/managed-execution.md +20 -0
  85. package/ui/chunks/official-documentation.md +18 -0
  86. package/ui/chunks/quota-recovery.md +21 -0
  87. package/ui/chunks/review-routing-decision.md +16 -0
  88. package/ui/chunks/route-work.md +18 -0
  89. package/ui/chunks/routing-evidence.md +18 -0
  90. package/ui/chunks/run-ledger.md +18 -0
  91. package/ui/chunks/session-controls.md +16 -0
  92. package/ui/home.js +198 -0
  93. package/ui/DESIGN.md +0 -32
  94. package/ui/card.js +0 -845
@@ -0,0 +1,344 @@
1
+ /** Admission for the operator's included-usage policy. No provider generation happens here. */
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { createHash } from 'node:crypto';
6
+ import { spawn } from 'node:child_process';
7
+ import { createInterface } from 'node:readline';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { configDir } from './paths.mjs';
10
+ import { agentEnvironment, CODEX_PLAN_ARGS, findBinary, OPENROUTER_AGENTS, readClaudeMaxOrganization, readClaudeTokenAccount, claudeTokenAccepted } from './worker.mjs';
11
+ import { activeQuotaWalls, includedBillingReceipts, readReceipts } from './learner.mjs';
12
+
13
+ export const INCLUDED_AGENTS = ['claude', 'codex', 'agy'];
14
+ const AGY_PLAN = 'google-personal';
15
+ const VERSION = 1;
16
+ const DEFAULT = { version: VERSION, enabled: false, claude: null };
17
+ const sha256 = key => createHash('sha256').update(key).digest('hex');
18
+ const validKeyName = name => typeof name === 'string' && /^[A-Z][A-Z0-9_]{1,100}$/.test(name);
19
+ const validModel = model => typeof model === 'string' && /^[\w.-]+\/[\w./:-]+$/.test(model) && model.length <= 180;
20
+ const validOpenRouterBinding = (agent, binding) => OPENROUTER_AGENTS.includes(agent) &&
21
+ validKeyName(binding?.keyName) && validModel(binding?.model);
22
+
23
+ async function policyStore() {
24
+ const { PluginStateStore } = await import('./ssss-store.mjs');
25
+ return new PluginStateStore(path.join(configDir(), 'included-usage.json'), 'meta-harness');
26
+ }
27
+
28
+ export async function readIncludedPolicy(store) {
29
+ store ??= await policyStore();
30
+ const state = store.read(DEFAULT);
31
+ if (state?.version !== VERSION || typeof state.enabled !== 'boolean' ||
32
+ (state.claude !== null && (!/^[a-f0-9]{64}$/.test(state.claude?.fingerprint || '') ||
33
+ typeof state.claude.keyName !== 'string' || typeof state.claude.organization !== 'string' ||
34
+ !Number.isFinite(Date.parse(state.claude.expiresAt)))) ||
35
+ (state.claudePlan !== undefined && (!/^[\w-]{1,100}$/.test(state.claudePlan?.organization || '') ||
36
+ state.claudePlan.usageCreditsEnabled !== false || !Number.isFinite(Date.parse(state.claudePlan.verifiedAt)))) ||
37
+ (state.claudeToken !== undefined && (!validKeyName(state.claudeToken?.keyName) ||
38
+ !/^[a-f0-9]{64}$/.test(state.claudeToken.fingerprint || '') || !Number.isFinite(Date.parse(state.claudeToken.verifiedAt)) ||
39
+ (state.claudeToken.organization != null && !/^[\w-]{1,100}$/.test(state.claudeToken.organization)))) ||
40
+ (state.agy !== undefined && (state.agy?.plan !== AGY_PLAN || !Number.isFinite(Date.parse(state.agy.boundAt)))) ||
41
+ (state.openRouter !== undefined && (!state.openRouter || typeof state.openRouter !== 'object' ||
42
+ Array.isArray(state.openRouter) || !Object.entries(state.openRouter).every(([agent, binding]) => validOpenRouterBinding(agent, binding))))) {
43
+ throw new Error('Included usage policy is invalid; dispatch stopped.');
44
+ }
45
+ return state;
46
+ }
47
+
48
+ function requireOperator() {
49
+ if (process.env.TR_META_HARNESS_RUN) throw new Error('Only the operator may change the included usage policy.');
50
+ }
51
+
52
+ export async function enforceIncludedUsage() {
53
+ requireOperator();
54
+ const store = await policyStore();
55
+ const state = await readIncludedPolicy(store);
56
+ if (!state.enabled) store.write({ ...state, enabled: true });
57
+ return includedUsageStatus();
58
+ }
59
+
60
+ async function authRuntime() {
61
+ const root = process.env.TR_PACKAGE_ROOT;
62
+ if (!root || !path.isAbsolute(root) ||
63
+ JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).name !== 'total-recall-brain') {
64
+ throw new Error('Verified Total Recall Auth runtime required.');
65
+ }
66
+ const { loadPluginModule } = await import(pathToFileURL(path.join(root, 'src/core/plugin-runtime.mjs')).href);
67
+ const { hostSecretsBrainDir } = await loadPluginModule('auth', 'host-secrets-store', { activeRequired: true });
68
+ return { brain: hostSecretsBrainDir(), load: module => loadPluginModule('auth', module, { activeRequired: true }) };
69
+ }
70
+
71
+ async function authValue(keyName) {
72
+ const { brain, load } = await authRuntime();
73
+ const { getSecret } = await load('secrets-store');
74
+ const result = await getSecret(brain, keyName, { action: 'use', actor: 'meta-harness' });
75
+ return result.found && typeof result.value === 'string' ? result.value : '';
76
+ }
77
+
78
+ async function authKey(keyName) {
79
+ const value = await authValue(keyName);
80
+ if (!/^sk-ant-api[0-9]+-[\w-]+$/.test(value)) {
81
+ throw new Error('The selected Anthropic API key is missing or invalid in Total Recall Auth.');
82
+ }
83
+ return value;
84
+ }
85
+
86
+ /** The Claude subscription token (claude setup-token) stored in Total Recall Auth. Never an API key. */
87
+ async function authClaudeToken(keyName) {
88
+ const value = (await authValue(keyName)).trim();
89
+ if (!/^sk-ant-oat[0-9]+-[\w-]+$/.test(value)) {
90
+ throw new Error(`${keyName} in Total Recall Auth is missing or is not a Claude subscription token (create one with claude setup-token).`);
91
+ }
92
+ return value;
93
+ }
94
+
95
+ async function verifyOpenRouterKey(keyName) {
96
+ const { brain, load } = await authRuntime();
97
+ const { syncSecretAccount } = await load('provider-account-sync');
98
+ const result = await syncSecretAccount(brain, keyName);
99
+ return result.provider === 'openrouter' && result.key_valid === true && result.tracking_status === 'ok';
100
+ }
101
+
102
+ /** OpenRouter opt-in is per harness and per destination, with no subscription fallback. */
103
+ export async function bindOpenRouter(agent, keyName, model, { verify = verifyOpenRouterKey } = {}) {
104
+ requireOperator();
105
+ const binding = { keyName, model };
106
+ if (!validOpenRouterBinding(agent, binding)) throw new Error('Select a supported OpenRouter harness, an Auth key name and a catalog model ID.');
107
+ if (!(await verify(keyName))) throw new Error('Total Recall Auth could not verify this OpenRouter key.');
108
+ const store = await policyStore();
109
+ const state = await readIncludedPolicy(store);
110
+ store.write({ ...state, enabled: true, openRouter: { ...state.openRouter, [agent]: binding } });
111
+ return { ok: true, agent, ...binding };
112
+ }
113
+
114
+ export async function openRouterAdmission(agent, policy, { readKey = authValue } = {}) {
115
+ const binding = policy.openRouter?.[agent];
116
+ if (!validOpenRouterBinding(agent, binding)) return { ok: false, failureKind: 'billing-policy', error: 'No approved OpenRouter binding for this harness.' };
117
+ const key = await readKey(binding.keyName);
118
+ if (!/^sk-or-v1-[\w-]+$/.test(key)) return { ok: false, failureKind: 'auth', error: 'The approved OpenRouter key is unavailable in Total Recall Auth.' };
119
+ return { ok: true, openRouter: { key, keyName: binding.keyName, model: binding.model } };
120
+ }
121
+
122
+ /** Bind the operator's Console observation to the actual secret without recording its value or hint. */
123
+ export async function bindClaudeIncludedKey(evidence, { readKey = authKey, now = Date.now() } = {}) {
124
+ requireOperator();
125
+ const { keyName, organization, keyHint, expiresAt, creditSource, autoReload, paymentMethod, invoiced, paidBalanceCents } = evidence || {};
126
+ const expiry = Date.parse(expiresAt);
127
+ const hint = typeof keyHint === 'string' && /^(sk-ant-api[0-9]+-[\w-]{2,20})(?:\.{3}|…)([\w-]{4,12})$/.exec(keyHint);
128
+ if (!/^[A-Z][A-Z0-9_]{1,100}$/.test(keyName || '') || !/^[\w-]{1,100}$/.test(organization || '') ||
129
+ !hint || !Number.isFinite(expiry) || expiry <= now || expiry > now + 35 * 86400000 ||
130
+ creditSource !== 'claude-max' || autoReload !== false || paymentMethod !== false || invoiced !== false || paidBalanceCents !== 0) {
131
+ throw new Error('Binding requires verified Max credit expiry, Console key hint, and a prepaid organization with no paid balance, auto-reload, or payment method.');
132
+ }
133
+ const key = await readKey(keyName);
134
+ if (!key.startsWith(hint[1]) || !key.endsWith(hint[2])) throw new Error('The Console key hint does not match the selected Total Recall Auth key.');
135
+ const store = await policyStore();
136
+ const state = await readIncludedPolicy(store);
137
+ store.write({ ...state, enabled: true, claude: { keyName, organization, expiresAt: new Date(expiry).toISOString(),
138
+ verifiedAt: new Date(now).toISOString(), fingerprint: sha256(key) } });
139
+ return includedUsageStatus();
140
+ }
141
+
142
+ export const claudeProofCurrent = (policy, now = Date.now()) => Date.parse(policy.claude?.expiresAt) > now;
143
+ export const claudeTokenCurrent = policy => Boolean(policy?.claudeToken?.fingerprint);
144
+ export const readClaudeToken = keyName => authClaudeToken(keyName).catch(() => null);
145
+
146
+ /**
147
+ * Bind Claude to the subscription token in Total Recall Auth (Greg, 2026-11-15: everything uses the auth
148
+ * plugin). Claude must accept it as a first-party login, never an API key. Only its fingerprint is kept,
149
+ * so a replaced token must be bound again before it is used.
150
+ */
151
+ export async function bindClaudeToken({ keyName = 'CLAUDE_CODE_OAUTH_TOKEN' } = {}, { readKey = authClaudeToken, readAccount = readClaudeTokenAccount } = {}) {
152
+ requireOperator();
153
+ if (!validKeyName(keyName)) throw new Error('Name the Total Recall Auth key that holds the Claude token.');
154
+ const token = await readKey(keyName);
155
+ const account = await readAccount(token);
156
+ if (!claudeTokenAccepted(account)) {
157
+ throw new Error(`Claude did not accept ${keyName} as a subscription login${account?.authMethod ? ` (it reported ${account.authMethod})` : ''}.`);
158
+ }
159
+ if (account.subscriptionType && account.subscriptionType !== 'max') throw new Error(`${keyName} belongs to a ${account.subscriptionType} plan, not Max.`);
160
+ const store = await policyStore();
161
+ const state = await readIncludedPolicy(store);
162
+ const organization = /^[\w-]{1,100}$/.test(account.orgId || '') ? account.orgId : null;
163
+ store.write({ ...state, enabled: true, claudeToken: { keyName, organization, verifiedAt: new Date().toISOString(), fingerprint: sha256(token) } });
164
+ return includedUsageStatus();
165
+ }
166
+
167
+ /** Bind the observed account setting to this host's native Claude Max login. */
168
+ export async function bindClaudeMaxPlan(evidence, { readOrganization = readClaudeMaxOrganization } = {}) {
169
+ requireOperator();
170
+ const { organization, usageCreditsEnabled } = evidence || {};
171
+ if (!/^[\w-]{1,100}$/.test(organization || '') || usageCreditsEnabled !== false) {
172
+ throw new Error('Confirm Usage credits are off in the signed-in Max account before binding it.');
173
+ }
174
+ if (organization !== await readOrganization(process.cwd())) {
175
+ throw new Error('The native Claude Max login does not match the verified organization.');
176
+ }
177
+ const store = await policyStore();
178
+ const state = await readIncludedPolicy(store);
179
+ store.write({ ...state, enabled: true, claudePlan: { organization, usageCreditsEnabled, verifiedAt: new Date().toISOString() } });
180
+ return includedUsageStatus();
181
+ }
182
+
183
+ /**
184
+ * Why Antigravity's saved CLI settings would bill something other than the signed-in personal Google plan.
185
+ * Keys from the official CLI reference ("Configuration keys (settings.json)", read 2026-12-01): an empty
186
+ * modelProvider uses the plan and "gemini" bills GEMINI_API_KEY; useG1Credits spends paid AI credits after
187
+ * the plan's quota; gcp is saved by the Google Cloud project sign-in. No file means every default.
188
+ */
189
+ export function agyPlanProblems({ home = process.env.HOME || os.homedir(), read = file => fs.readFileSync(file, 'utf8') } = {}) {
190
+ let settings;
191
+ try { settings = JSON.parse(read(path.join(home, '.gemini', 'antigravity-cli', 'settings.json'))); }
192
+ catch (error) {
193
+ if (error.code === 'ENOENT') return [];
194
+ return ['Antigravity settings.json cannot be read, so its billing route is unknown.'];
195
+ }
196
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) return ['Antigravity settings.json is not a settings object, so its billing route is unknown.'];
197
+ const problems = [];
198
+ if (settings.modelProvider) problems.push(`Antigravity is set to the "${String(settings.modelProvider).slice(0, 40)}" model provider, which bills an API key; clear modelProvider to use the Google plan.`);
199
+ if (settings.useG1Credits === true) problems.push('Antigravity is set to spend paid AI credits after the plan quota (useG1Credits); turn it off.');
200
+ if (settings.gcp && typeof settings.gcp === 'object' && Object.keys(settings.gcp).length) problems.push('Antigravity is signed in through a Google Cloud project, which is billed per use; sign in with the personal Google account.');
201
+ return problems;
202
+ }
203
+
204
+ /**
205
+ * Let Antigravity run on the operator's personal Google plan. The CLI has no account read that sends no
206
+ * model request, so the plan tier is not verified here: the operator states it by binding, and every run
207
+ * is launched so it can use that sign-in and nothing that bills.
208
+ */
209
+ export async function bindAgyPlan({ problems = agyPlanProblems, find = findBinary, now = Date.now() } = {}) {
210
+ requireOperator();
211
+ if (!find('agy', process.env)) throw new Error('Antigravity (agy) is not installed on this node.');
212
+ const found = problems();
213
+ if (found.length) throw new Error(found.join(' '));
214
+ const store = await policyStore();
215
+ const state = await readIncludedPolicy(store);
216
+ store.write({ ...state, enabled: true, agy: { plan: AGY_PLAN, boundAt: new Date(now).toISOString() } });
217
+ return includedUsageStatus();
218
+ }
219
+
220
+ export async function includedUsageStatus({ probe = false } = {}) {
221
+ const policy = await readIncludedPolicy();
222
+ const claude = policy.claude ? { organization: policy.claude.organization, verifiedAt: policy.claude.verifiedAt,
223
+ expiresAt: policy.claude.expiresAt, current: claudeProofCurrent(policy) } : null;
224
+ const claudeToken = policy.claudeToken ? { keyName: policy.claudeToken.keyName, organization: policy.claudeToken.organization,
225
+ verifiedAt: policy.claudeToken.verifiedAt } : null;
226
+ return { ok: true, policyVersion: VERSION, enabled: policy.enabled, claude, claudePlan: policy.claudePlan ?? null, claudeToken,
227
+ openRouter: policy.openRouter ?? {}, agy: policy.agy ?? null,
228
+ ...(probe ? { codex: await readCodexAllowance(process.cwd()) } : {}) };
229
+ }
230
+
231
+ /** Use only the documented account reads on stdio. No turn/start is sent. */
232
+ export function queryCodexAccount(cwd, { env = process.env, timeoutMs = 10000 } = {}) {
233
+ const binary = findBinary('codex', env);
234
+ if (!binary) throw new Error('Codex CLI is unavailable.');
235
+ return new Promise((resolve, reject) => {
236
+ const child = spawn(binary, [...CODEX_PLAN_ARGS, 'app-server', '--listen', 'stdio://'], {
237
+ cwd, env: agentEnvironment(env), stdio: ['pipe', 'pipe', 'ignore'],
238
+ });
239
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
240
+ let account, limits, size = 0, outcome;
241
+ const send = message => child.stdin.write(JSON.stringify(message) + '\n');
242
+ const fail = error => {
243
+ outcome ||= { error };
244
+ child.kill('SIGTERM');
245
+ };
246
+ const timer = setTimeout(() => { outcome ||= { error: 'Codex account read timed out.' }; child.kill('SIGKILL'); }, timeoutMs);
247
+ const closed = () => {
248
+ clearTimeout(timer);
249
+ lines.close();
250
+ if (outcome?.result) resolve(outcome.result);
251
+ else reject(new Error(outcome?.error || 'Codex account read ended without a complete result.'));
252
+ };
253
+ child.once('error', () => { outcome = { error: 'Could not start Codex account read.' }; });
254
+ child.once('close', closed);
255
+ child.stdin.on('error', () => fail('Codex account read input closed.'));
256
+ child.stdout.on('data', chunk => { size += chunk.length; if (size > 256 * 1024) fail('Codex account response exceeded its bound.'); });
257
+ lines.on('line', line => {
258
+ if (outcome) return;
259
+ let frame;
260
+ try { frame = JSON.parse(line); } catch { fail('Codex returned invalid account data.'); return; }
261
+ if (![1, 2, 3].includes(frame?.id)) return;
262
+ if (!frame.result || frame.error) { fail('Codex could not read the signed-in account or its limits.'); return; }
263
+ if (frame.id === 1) {
264
+ send({ method: 'initialized', params: {} });
265
+ send({ id: 2, method: 'account/read', params: { refreshToken: false } });
266
+ send({ id: 3, method: 'account/rateLimits/read' });
267
+ } else if (frame.id === 2) account = frame.result;
268
+ else limits = frame.result;
269
+ if (account && limits) {
270
+ outcome = { result: { account, limits } };
271
+ child.stdin.end();
272
+ child.kill('SIGTERM');
273
+ }
274
+ });
275
+ send({ id: 1, method: 'initialize', params: { clientInfo: { name: 'meta_harness', title: 'Metaharness', version: '1' } } });
276
+ });
277
+ }
278
+
279
+ export function evaluateCodexAllowance({ account, limits }, now = Date.now()) {
280
+ const plan = account?.account?.planType;
281
+ if (account?.account?.type !== 'chatgpt' || !/^(plus|pro|prolite|go|free)(?:[_-]\w+)?$/i.test(plan || '')) {
282
+ return { ok: false, failureKind: 'auth', error: 'Codex requires a verified personal ChatGPT plan with included limits.' };
283
+ }
284
+ const rate = limits?.rateLimits;
285
+ const buckets = [rate, ...Object.values(limits?.rateLimitsByLimitId || {})].filter(Boolean);
286
+ const windows = [rate?.primary, rate?.secondary].filter(Boolean);
287
+ if (!windows.length || windows.some(window => typeof window.usedPercent !== 'number')) {
288
+ return { ok: false, plan, failureKind: 'billing-policy', error: 'Codex did not report current included usage.' };
289
+ }
290
+ const credits = buckets.map(bucket => bucket.credits).filter(Boolean);
291
+ if (!credits.length || credits.some(c => c.hasCredits !== false || c.unlimited !== false ||
292
+ (c.balance != null && !/^0(?:\.0+)?$/.test(String(c.balance))))) {
293
+ return { ok: false, plan, failureKind: 'billing-policy', error: 'Codex did not confirm that paid credits are unavailable.' };
294
+ }
295
+ const full = windows.filter(window => window.usedPercent >= 100);
296
+ if (full.length) {
297
+ const resets = full.map(window => window.resetsAt * 1000);
298
+ return { ok: false, plan, failureKind: 'quota', error: 'Codex has reached an included usage limit.',
299
+ resetsAt: resets.every(reset => Number.isFinite(reset) && reset > now) ? new Date(Math.max(...resets)).toISOString() : null };
300
+ }
301
+ return { ok: true, plan, usagePercent: Math.max(...windows.map(window => window.usedPercent)) };
302
+ }
303
+
304
+ export async function readCodexAllowance(cwd, { query = queryCodexAccount } = {}) {
305
+ try { return evaluateCodexAllowance(await query(cwd)); }
306
+ catch (error) { return { ok: false, failureKind: 'billing-policy', error: error.message }; }
307
+ }
308
+
309
+ export async function includedAdmission(agent, cwd, policy, { readKey = authKey, readToken = authClaudeToken, codex = readCodexAllowance,
310
+ receipts = readReceipts, agy = agyPlanProblems } = {}) {
311
+ if (!INCLUDED_AGENTS.includes(agent)) return { ok: false, failureKind: 'billing-policy', error: 'This harness is outside the included usage policy.' };
312
+ if (agent === 'agy' && !policy.agy) {
313
+ return { ok: false, failureKind: 'billing-policy', error: 'Antigravity is not bound to a Google plan on this node; the operator binds it with: total-recall meta-harness included-bind-agy' };
314
+ }
315
+ if (agent === 'claude' && !claudeTokenCurrent(policy) && !policy.claudePlan && !claudeProofCurrent(policy)) {
316
+ return { ok: false, failureKind: 'billing-policy', error: 'Store a Claude subscription token (claude setup-token) in Total Recall Auth and bind it with included-bind-claude-token.' };
317
+ }
318
+ const wall = activeQuotaWalls(includedBillingReceipts(await receipts()))[agent];
319
+ if (wall) return { ok: false, failureKind: 'quota', error: 'This harness is waiting for included usage.', resetsAt: wall.resetReported ? wall.until : null };
320
+ if (agent === 'codex') return codex(cwd);
321
+ if (agent === 'agy') {
322
+ // Checked on every run: the saved settings can change after the binding.
323
+ const problems = agy();
324
+ return problems.length ? { ok: false, failureKind: 'billing-policy', error: problems[0] } : { ok: true, agy: { plan: policy.agy.plan } };
325
+ }
326
+ // The token in Total Recall Auth comes first: it works on every node without a per-machine login.
327
+ if (claudeTokenCurrent(policy)) {
328
+ try {
329
+ const token = await readToken(policy.claudeToken.keyName);
330
+ if (sha256(token) !== policy.claudeToken.fingerprint) throw new Error(`${policy.claudeToken.keyName} changed in Total Recall Auth; bind it again with included-bind-claude-token.`);
331
+ return { ok: true, claudeToken: token };
332
+ } catch (error) {
333
+ return { ok: false, failureKind: 'auth', error: error.message };
334
+ }
335
+ }
336
+ if (policy.claudePlan) return { ok: true, claudePlan: policy.claudePlan.organization };
337
+ try {
338
+ const key = await readKey(policy.claude.keyName);
339
+ if (sha256(key) !== policy.claude.fingerprint) throw new Error('The Claude key changed; verify the new key against the Max grant.');
340
+ return { ok: true, key };
341
+ } catch (error) {
342
+ return { ok: false, failureKind: 'auth', error: error.message };
343
+ }
344
+ }
package/src/jobs.mjs ADDED
@@ -0,0 +1,135 @@
1
+ /** Local job identity and cancellation. A terminal log result is the completion record. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { configDir } from './paths.mjs';
6
+ import { createProgress } from './worker.mjs';
7
+
8
+ const jobsDir = () => path.join(configDir(), 'jobs');
9
+ export const newJobId = () => `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
10
+
11
+ export function startJob(operation, { id = newJobId() } = {}) {
12
+ if (!/^[a-z0-9-]+$/.test(id)) throw new Error('Invalid job ID.');
13
+ const directory = jobsDir();
14
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
15
+ const log = path.join(directory, `${id}.log`);
16
+ const pidFile = path.join(directory, `${id}.pid`);
17
+ const record = { job: id, pid: process.pid, operation, startedAt: new Date().toISOString() };
18
+ fs.appendFileSync(log, `${JSON.stringify(record)}\n`, { mode: 0o600 });
19
+ fs.writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600, flag: 'wx' });
20
+ // The worker mirrors its live events into this file and owns the watchdog.
21
+ const progress = createProgress({ file: path.join(directory, `${id}.events.jsonl`), harness: operation, watchdog: false, startFields: { record: 'job' } });
22
+ return { ...record, log, finish(result) {
23
+ progress.close(result);
24
+ fs.appendFileSync(log, `${JSON.stringify(result)}\n`, { mode: 0o600 });
25
+ fs.rmSync(pidFile, { force: true });
26
+ } };
27
+ }
28
+
29
+ function readJob(log) {
30
+ const lines = fs.readFileSync(log, 'utf8').trim().split('\n');
31
+ let record;
32
+ try { record = JSON.parse(lines[0]); } catch { /* old log without PID */ }
33
+ let result = null;
34
+ for (const line of lines.slice(1).reverse()) {
35
+ try {
36
+ const value = JSON.parse(line);
37
+ if (typeof value.ok === 'boolean') { result = value; break; }
38
+ } catch { /* progress text */ }
39
+ }
40
+ return { record, result };
41
+ }
42
+
43
+ export function resolveJob(target) {
44
+ if (!target) throw new Error('cancel requires a job ID or log path.');
45
+ const directory = jobsDir();
46
+ const prefix = path.basename(target).replace(/\.(?:log|pid|events\.jsonl|status\.json)$/, '');
47
+ const files = fs.existsSync(directory) ? fs.readdirSync(directory) : [];
48
+ let names = files.filter(name => name.endsWith('.log') && name.startsWith(prefix));
49
+ if (!names.length) {
50
+ // An attempt ID from watch resolves to its owning job, never directly to a PID.
51
+ const events = files.filter(name => name.endsWith('.events.jsonl') && name.startsWith(prefix))
52
+ .sort((a, b) => fs.statSync(path.join(directory, b)).mtimeMs - fs.statSync(path.join(directory, a)).mtimeMs);
53
+ let pid;
54
+ try { pid = JSON.parse(fs.readFileSync(path.join(directory, events[0].replace('.events.jsonl', '.status.json')), 'utf8')).pid; } catch { /* no matching status */ }
55
+ if (pid) names = files.filter(name => name.endsWith('.log') && readJob(path.join(directory, name)).record?.pid === pid);
56
+ }
57
+ const exact = names.find(name => name === `${prefix}.log`);
58
+ if (!names.length) throw new Error(`No job log matches ${target}.`);
59
+ if (!exact && names.length > 1) throw new Error(`More than one job matches ${target}. Use a longer job ID.`);
60
+ const log = path.join(directory, exact || names[0]);
61
+ return { id: path.basename(log, '.log'), log, ...readJob(log) };
62
+ }
63
+
64
+ const JOB_FILE = /^(.+?)\.(log|pid|events\.jsonl|status\.json|session\.json|inbox\.jsonl)$/;
65
+ export const JOB_RETENTION_DAYS = 30;
66
+
67
+ function pidAlive(pid) {
68
+ try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
69
+ }
70
+
71
+ function jobRunning(directory, id, files, isAlive) {
72
+ const pids = [];
73
+ if (files.includes(`${id}.pid`)) {
74
+ try { pids.push(Number(fs.readFileSync(path.join(directory, `${id}.pid`), 'utf8').trim())); } catch { /* removed meanwhile */ }
75
+ }
76
+ if (files.includes(`${id}.status.json`)) {
77
+ try { pids.push(JSON.parse(fs.readFileSync(path.join(directory, `${id}.status.json`), 'utf8')).pid); } catch { /* unreadable status */ }
78
+ }
79
+ return pids.some(pid => Number.isSafeInteger(pid) && pid > 1 && isAlive(pid));
80
+ }
81
+
82
+ /**
83
+ * Remove each job whose files are all older than the retention period. Job records were never
84
+ * deleted, so the folder grew without limit (13,299 files on 2026-11-29). A job whose recorded
85
+ * process is alive is kept at any age, and files that are not job records are never touched.
86
+ */
87
+ export function pruneJobs({ retentionDays = JOB_RETENTION_DAYS, now = Date.now(), directory = jobsDir(), isAlive = pidAlive } = {}) {
88
+ if (!(retentionDays > 0)) throw new Error('Job retention must be a positive number of days.');
89
+ if (!fs.existsSync(directory)) return { ok: true, removed: 0, kept: 0, freedBytes: 0 };
90
+ const cutoff = now - retentionDays * 86_400_000;
91
+ const groups = new Map();
92
+ for (const name of fs.readdirSync(directory)) {
93
+ const match = name.match(JOB_FILE);
94
+ if (!match) continue;
95
+ let stat;
96
+ try { stat = fs.statSync(path.join(directory, name)); } catch { continue; }
97
+ if (!stat.isFile()) continue;
98
+ const group = groups.get(match[1]) || { files: [], newest: 0, bytes: 0 };
99
+ group.files.push(name);
100
+ group.newest = Math.max(group.newest, stat.mtimeMs);
101
+ group.bytes += stat.size;
102
+ groups.set(match[1], group);
103
+ }
104
+ let removed = 0, kept = 0, freedBytes = 0;
105
+ for (const [id, group] of groups) {
106
+ if (group.newest >= cutoff || jobRunning(directory, id, group.files, isAlive)) { kept += 1; continue; }
107
+ for (const name of group.files) fs.rmSync(path.join(directory, name), { force: true });
108
+ removed += 1;
109
+ freedBytes += group.bytes;
110
+ }
111
+ return { ok: true, removed, kept, freedBytes };
112
+ }
113
+
114
+ export async function cancelJob(target, { timeoutMs = 60_000, pollMs = 100 } = {}) {
115
+ const job = resolveJob(target);
116
+ if (job.result) throw new Error(`Job ${job.id} has finished${job.result.cancelled ? ' (cancelled)' : ''}.`);
117
+ const pidFile = path.join(jobsDir(), `${job.id}.pid`);
118
+ let pid;
119
+ try { pid = Number(fs.readFileSync(pidFile, 'utf8').trim()); } catch { /* stale or old job */ }
120
+ if (!Number.isSafeInteger(pid) || pid <= 1 || job.record?.pid !== pid || job.record?.job !== job.id) {
121
+ throw new Error(`Job ${job.id} has no active PID record.`);
122
+ }
123
+ try { process.kill(pid, 'SIGTERM'); }
124
+ catch (error) { throw new Error(`Cannot cancel job ${job.id}: ${error.code === 'ESRCH' ? 'the process has stopped' : error.message}.`); }
125
+ const deadline = Date.now() + Math.min(timeoutMs, 60_000);
126
+ do {
127
+ const { result } = readJob(job.log);
128
+ if (result) {
129
+ if (!result.cancelled) throw new Error(`Job ${job.id} finished before it could be cancelled.`);
130
+ return { ...result, job: job.id, log: job.log };
131
+ }
132
+ await new Promise(resolve => setTimeout(resolve, pollMs));
133
+ } while (Date.now() < deadline);
134
+ throw new Error(`Job ${job.id} did not report cancellation within ${Math.min(timeoutMs, 60_000) / 1000} seconds. Log: ${job.log}`);
135
+ }
@@ -0,0 +1,22 @@
1
+ /** Agents wrap their answer in prose and code. Find the last well-formed object that carries the expected key. */
2
+ export function lastJsonWith(text, key) {
3
+ const source = String(text || '');
4
+ for (let start = source.lastIndexOf('{'); start >= 0; start = source.lastIndexOf('{', start - 1)) {
5
+ let depth = 0, inString = false;
6
+ for (let i = start; i < source.length; i += 1) {
7
+ const c = source[i];
8
+ if (inString) { if (c === '\\') i += 1; else if (c === '"') inString = false; continue; }
9
+ if (c === '"') inString = true;
10
+ else if (c === '{') depth += 1;
11
+ else if (c === '}') {
12
+ depth -= 1;
13
+ if (depth === 0) {
14
+ try { const value = JSON.parse(source.slice(start, i + 1)); if (value && Object.hasOwn(value, key)) return value; } catch { /* keep looking */ }
15
+ break;
16
+ }
17
+ }
18
+ }
19
+ if (start === 0) break;
20
+ }
21
+ return null;
22
+ }