tr-plugin-meta-harness 0.0.0-stage → 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 +310 -2
  3. package/capability/BRICK.md +59 -0
  4. package/capability/index.mjs +675 -0
  5. package/cli.mjs +524 -0
  6. package/package.json +32 -4
  7. package/plugin.json +1714 -0
  8. package/skills/meta-harness/SKILL.md +75 -0
  9. package/src/adapters/dsh.mjs +446 -0
  10. package/src/adoption.mjs +102 -0
  11. package/src/agent-user.mjs +194 -0
  12. package/src/alerts.mjs +229 -0
  13. package/src/cascade.mjs +185 -0
  14. package/src/chat.mjs +80 -0
  15. package/src/codex-models.mjs +54 -0
  16. package/src/compat-harness.mjs +114 -0
  17. package/src/control.mjs +145 -0
  18. package/src/coordinator.mjs +307 -0
  19. package/src/dispatch-request.mjs +76 -0
  20. package/src/dispatch.mjs +119 -0
  21. package/src/documentation-authority.mjs +57 -0
  22. package/src/documentation.mjs +240 -0
  23. package/src/executor.mjs +161 -0
  24. package/src/gate-adapters/agy.mjs +155 -0
  25. package/src/gate-adapters/claude.mjs +303 -0
  26. package/src/gate-adapters/cline.mjs +111 -0
  27. package/src/gate-adapters/codex.mjs +164 -0
  28. package/src/gate-adapters/cursor.mjs +164 -0
  29. package/src/gate-adapters/devin.mjs +116 -0
  30. package/src/gate-adapters/dsh.mjs +284 -0
  31. package/src/gate-adapters/grok.mjs +112 -0
  32. package/src/gate-adapters/hermes.mjs +217 -0
  33. package/src/gate-adapters/hook-files.mjs +156 -0
  34. package/src/gate-adapters/index.mjs +131 -0
  35. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  36. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  37. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  38. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  39. package/src/gate-adapters/openclaw.mjs +288 -0
  40. package/src/gate-adapters/pi.mjs +146 -0
  41. package/src/gate.mjs +18 -0
  42. package/src/harness-updates.mjs +170 -0
  43. package/src/included-usage.mjs +344 -0
  44. package/src/jobs.mjs +135 -0
  45. package/src/json-reply.mjs +22 -0
  46. package/src/learner.mjs +120 -0
  47. package/src/maintenance.mjs +18 -0
  48. package/src/mcp-server.mjs +228 -0
  49. package/src/model-catalog.mjs +195 -0
  50. package/src/model-selection.mjs +67 -0
  51. package/src/paths.mjs +23 -0
  52. package/src/pool.mjs +69 -0
  53. package/src/process-manager.mjs +246 -0
  54. package/src/process-worker.mjs +18 -0
  55. package/src/reasoning.mjs +231 -0
  56. package/src/remote-operation.mjs +76 -0
  57. package/src/review.mjs +241 -0
  58. package/src/reviews.mjs +25 -0
  59. package/src/router-benchmark-corpus.mjs +16 -0
  60. package/src/router-benchmark.mjs +208 -0
  61. package/src/router.mjs +334 -0
  62. package/src/runtime.mjs +58 -0
  63. package/src/session/claude.mjs +358 -0
  64. package/src/session/codex.mjs +501 -0
  65. package/src/session/result.mjs +90 -0
  66. package/src/session/resume.mjs +393 -0
  67. package/src/session/run.mjs +258 -0
  68. package/src/session-jobs.mjs +77 -0
  69. package/src/setup.mjs +38 -0
  70. package/src/ssss-store.mjs +20 -0
  71. package/src/telemetry.mjs +267 -0
  72. package/src/termination.mjs +28 -0
  73. package/src/threads.mjs +150 -0
  74. package/src/tracker.mjs +133 -0
  75. package/src/usage-queue.mjs +137 -0
  76. package/src/verify-ssss.mjs +102 -0
  77. package/src/worker.mjs +1104 -0
  78. package/src/worktree.mjs +244 -0
  79. package/ui/chunks/adapter-docs-freshness.md +16 -0
  80. package/ui/chunks/chat-handoff.md +26 -0
  81. package/ui/chunks/fleet-maintenance.md +21 -0
  82. package/ui/chunks/harness-inventory.md +21 -0
  83. package/ui/chunks/included-access.md +18 -0
  84. package/ui/chunks/included-usage-verification.md +15 -0
  85. package/ui/chunks/independent-review.md +17 -0
  86. package/ui/chunks/managed-execution.md +20 -0
  87. package/ui/chunks/official-documentation.md +18 -0
  88. package/ui/chunks/quota-recovery.md +21 -0
  89. package/ui/chunks/review-routing-decision.md +16 -0
  90. package/ui/chunks/route-work.md +18 -0
  91. package/ui/chunks/routing-evidence.md +18 -0
  92. package/ui/chunks/run-ledger.md +18 -0
  93. package/ui/chunks/session-controls.md +16 -0
  94. package/ui/home.js +198 -0
package/src/chat.mjs ADDED
@@ -0,0 +1,80 @@
1
+ import path from 'node:path';
2
+ import { configDir } from './paths.mjs';
3
+ import { PluginStateStore } from './ssss-store.mjs';
4
+ import { getActiveAdapters } from './worker.mjs';
5
+
6
+ const CODEX_DRAFT = 'codex://threads/new';
7
+ const MAX_SELECTION_BYTES = 16_384;
8
+ const MAX_DRAFT_LINK_LENGTH = 8_192;
9
+ const UNSAFE_TEXT = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
10
+ const BRAIN_ID = /^(?:global|project:[^,]+|tenant:[a-zA-Z0-9._-]+)$/u;
11
+ const ADAPTER_ID = /^[a-z][a-z0-9-]{0,63}$/;
12
+
13
+ // Chat preferences follow the dashboard's brain. The auth store override is
14
+ // exclusively for credentials and may point outside an isolated dashboard.
15
+ const chatStore = () => new PluginStateStore(
16
+ path.join(configDir({ ...process.env, TR_SECRETS_BRAIN: undefined }), 'chat-default.json'),
17
+ 'meta-harness',
18
+ );
19
+ const displayAdapter = ({ id, name }) => ({ id, name });
20
+
21
+ function brainContext(selection) {
22
+ if (typeof selection !== 'string' || Buffer.byteLength(selection) > MAX_SELECTION_BYTES || UNSAFE_TEXT.test(selection)) {
23
+ throw new Error('Chat requires a bounded comma-separated list of brain IDs');
24
+ }
25
+ const ids = [...new Set(selection.split(',').map(id => id.trim()))];
26
+ if (ids.some(id => !BRAIN_ID.test(id))) throw new Error('Chat brain IDs must use global, project:<name>, or tenant:<name>');
27
+ return `Use this Total Recall brain selection for Chat: ${JSON.stringify(ids)}. Resolve the selected IDs through Total Recall before retrieving or writing memory.`;
28
+ }
29
+
30
+ function launchUrl(adapterId, value) {
31
+ if (value === undefined) return undefined;
32
+ const message = 'Use an HTTPS launch URL without credentials, a query or a fragment, or a Codex Chat link for Codex';
33
+ if (typeof value !== 'string' || value.length > 2048 || UNSAFE_TEXT.test(value) || /\s|\\/u.test(value)) {
34
+ throw new Error(message);
35
+ }
36
+ if (adapterId === 'codex' && /^codex:\/\/threads\/[a-zA-Z0-9_-]{1,128}$/.test(value)) return value;
37
+ if (!value.startsWith('https://') || /[?#]/.test(value)) throw new Error(message);
38
+ const url = URL.parse(value);
39
+ if (!url?.hostname || url.username || url.password) throw new Error(message);
40
+ return url.href;
41
+ }
42
+
43
+ function resolveTarget(settings, adapters, context) {
44
+ const choices = adapters.map(displayAdapter);
45
+ if (!settings) return { ok: true, configured: false, choices, context };
46
+ const adapter = adapters.find(({ id }) => id === settings.adapterId);
47
+ if (!adapter) {
48
+ return {
49
+ ok: true, configured: false, choices, context,
50
+ warning: 'The saved Chat harness is unavailable. Choose a new default.',
51
+ };
52
+ }
53
+
54
+ const target = launchUrl(adapter.id, settings.url) ?? (adapter.id === 'codex' ? CODEX_DRAFT : undefined);
55
+ let href = target;
56
+ if (target === CODEX_DRAFT) {
57
+ const draft = `${target}?prompt=${encodeURIComponent(context)}`;
58
+ if (draft.length <= MAX_DRAFT_LINK_LENGTH) href = draft;
59
+ }
60
+ return { ok: true, configured: true, choices, context, harness: displayAdapter(adapter), ...(href ? { href } : {}) };
61
+ }
62
+
63
+ /** Return a draft target. The caller decides when to open it and the operator submits in the harness. */
64
+ export function chatTarget(brains = 'global') {
65
+ const context = brainContext(brains);
66
+ const settings = chatStore().read(null);
67
+ if (settings !== null && (!settings || typeof settings.adapterId !== 'string' || !ADAPTER_ID.test(settings.adapterId))) {
68
+ throw new Error('The saved Chat default is invalid');
69
+ }
70
+ return resolveTarget(settings, getActiveAdapters(), context);
71
+ }
72
+
73
+ /** Only the adapter and optional launch URL are persistent. */
74
+ export function setChatDefault(adapterId, url) {
75
+ const adapters = getActiveAdapters();
76
+ if (!adapters.some(({ id }) => id === adapterId)) throw new Error('Choose a registered Metaharness adapter for Chat');
77
+ const settings = { adapterId, url: launchUrl(adapterId, url) };
78
+ chatStore().write(settings);
79
+ return resolveTarget(settings, adapters, brainContext('global'));
80
+ }
@@ -0,0 +1,54 @@
1
+ /** The models the signed-in Codex account can run, as the installed Codex CLI last listed them. */
2
+ import { execFileSync } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ const MAX_AGE_MS = 7 * 86400_000;
8
+ const codexHome = env => env.CODEX_HOME || path.join(env.HOME || os.homedir(), '.codex');
9
+
10
+ let installed;
11
+ /** The installed Codex CLI's version, read once per process; null when it does not answer. */
12
+ function installedCliVersion() {
13
+ if (installed === undefined) {
14
+ try { installed = execFileSync('codex', ['--version'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).match(/\d+\.\d+\.\d+/)?.[0] ?? null; }
15
+ catch { installed = null; }
16
+ }
17
+ return installed;
18
+ }
19
+
20
+ /**
21
+ * Model ids, or null when there is no verdict. Every Codex client (desktop app, IDE, CLI) overwrites
22
+ * this list with the models its own version can run, so only the CLI's own list counts.
23
+ */
24
+ export function codexAccountModels({ env = process.env, now = Date.now(), cliVersion = installedCliVersion } = {}) {
25
+ try {
26
+ const cache = JSON.parse(fs.readFileSync(path.join(codexHome(env), 'models_cache.json'), 'utf8'));
27
+ const at = Date.parse(cache.fetched_at);
28
+ if (!Number.isFinite(at) || now - at > MAX_AGE_MS) return null;
29
+ if (!cache.client_version || cache.client_version !== cliVersion()) return null;
30
+ const ids = (cache.models || []).map(model => model?.slug).filter(slug => typeof slug === 'string');
31
+ return ids.length ? ids : null;
32
+ } catch { return null; }
33
+ }
34
+
35
+ /** The model Codex runs when a request names none. Profiles and other tables are not read. */
36
+ export function codexDefaultModel({ env = process.env } = {}) {
37
+ try {
38
+ for (const line of fs.readFileSync(path.join(codexHome(env), 'config.toml'), 'utf8').split('\n')) {
39
+ if (/^\s*\[/.test(line)) return null;
40
+ const found = line.match(/^\s*model\s*=\s*["']([^"']+)["']/);
41
+ if (found) return found[1];
42
+ }
43
+ } catch { /* no configuration */ }
44
+ return null;
45
+ }
46
+
47
+ /** Why Codex cannot run this model, or null when it can or nothing is known. */
48
+ export function codexModelRefusal(model, options = {}) {
49
+ const listed = codexAccountModels(options);
50
+ const wanted = model ?? codexDefaultModel(options);
51
+ if (!listed || !wanted || listed.includes(wanted)) return null;
52
+ const version = (options.cliVersion || installedCliVersion)();
53
+ return `Codex's ${model ? 'requested' : 'default'} model ${wanted} is not available to the signed-in account in Codex CLI ${version}. Available: ${listed.join(', ')}. A newer CLI may list more.`;
54
+ }
@@ -0,0 +1,114 @@
1
+ /** Compatibility interfaces for native hosts. All execution uses the plugin's common boundary. */
2
+ import path from 'node:path';
3
+ import { getActiveAdapters, findBinary, inspectAgents, agentEnvironment } from './worker.mjs';
4
+ import { getInstalledVersion, getLatestVersion } from './tracker.mjs';
5
+
6
+ export const HARNESS_SPECS = Object.fromEntries(getActiveAdapters().map(adapter => [adapter.id, {
7
+ ...adapter, defaultFlags: adapter.args, execType: adapter.input === 'stdin' ? 'pipe_stdin' : 'flag_last',
8
+ enforcement: 'advisory', enforcementEvidence: 'Use the measured preflight adapter report for enforcement evidence',
9
+ }]));
10
+
11
+ export function normalizeToolSelection(tools) {
12
+ if (tools === undefined || tools === null) return null;
13
+ const values = (Array.isArray(tools) ? tools : String(tools).split(',')).map(value => String(value).trim()).filter(Boolean);
14
+ if (!values.length || (values.length === 1 && values[0] === 'none')) return '';
15
+ if (values.length === 1 && ['all', 'default'].includes(values[0])) return null;
16
+ return values.join(',');
17
+ }
18
+
19
+ export function validateHarnessOptions(id, options = {}) {
20
+ const adapter = getActiveAdapters().find(item => item.id === id);
21
+ if (!adapter) throw new Error(`Unknown harness ID "${id}"`);
22
+ if ((normalizeToolSelection(options.tools) !== null || options.settingSources !== undefined) && id !== 'claude') {
23
+ throw new Error(`Harness "${adapter.name}" does not support choosing its tool set or --setting-sources`);
24
+ }
25
+ if (options.settingSources !== undefined && (typeof options.settingSources !== 'string' || !/^(user|project|local)(,(user|project|local))*$/.test(options.settingSources))) throw new Error('Invalid --setting-sources');
26
+ if (options.allowUnknownAuth !== undefined && typeof options.allowUnknownAuth !== 'boolean') throw new Error('allowUnknownAuth must be an explicit boolean');
27
+ return adapter;
28
+ }
29
+
30
+ /** Legacy inspection helper only; execution flags are built by worker.mjs. */
31
+ export function buildHarnessArgs(spec, options = {}) {
32
+ const adapter = validateHarnessOptions(spec.id, options);
33
+ const args = [...adapter.args], extra = [];
34
+ const tools = normalizeToolSelection(options.tools);
35
+ if (tools !== null) extra.push('--tools', tools);
36
+ if (options.settingSources !== undefined) extra.push('--setting-sources', options.settingSources);
37
+ const promptFlag = args.at(-1) === '-p' ? args.pop() : null;
38
+ return [...args, ...extra, ...(promptFlag ? [promptFlag] : [])];
39
+ }
40
+
41
+ export const shellQuote = value => "'" + String(value).replaceAll("'", "'\\''") + "'";
42
+
43
+ export function detectHarnesses() {
44
+ return getActiveAdapters().map(adapter => {
45
+ const binaryPath = findBinary(adapter.binary);
46
+ return { id: adapter.id, name: adapter.name, available: Boolean(binaryPath), binaryPath, description: adapter.docs, execType: adapter.input };
47
+ });
48
+ }
49
+
50
+ export async function detectHarnessesWithAuth(options = {}) {
51
+ const result = await (options.inspect || inspectAgents)(options);
52
+ return result.agents.map(agent => ({ ...agent, available: agent.installed, authed: agent.authenticated === true && !agent.blockedBy, authRoute: agent.authenticated === 'unknown' ? 'unknown' : agent.authenticated ? 'measured-login' : 'needs-auth' }));
53
+ }
54
+
55
+ /** Kept for callers preparing environments; only an adapter's declared credentials may be resolved. */
56
+ export async function resolveHarnessEnv(spec, baseEnv = process.env, { readSecret } = {}) {
57
+ const adapter = validateHarnessOptions(spec.id);
58
+ const env = agentEnvironment(baseEnv);
59
+ if (!Object.keys(adapter.credentials || {}).length) return env;
60
+ if (!readSecret) {
61
+ const { runProcess } = await import('./worker.mjs');
62
+ const binary = findBinary(baseEnv.TOTAL_RECALL_BIN || 'total-recall', baseEnv);
63
+ if (!binary) throw new Error('Total Recall auth owner is unavailable');
64
+ readSecret = async key => {
65
+ const result = await runProcess(binary, ['auth', 'secret', 'get', key], { env: agentEnvironment(baseEnv) });
66
+ return result.exitCode === 0 ? result.stdout.trim() : null;
67
+ };
68
+ }
69
+ for (const [name, keys] of Object.entries(adapter.credentials)) {
70
+ for (const key of keys) { const value = await readSecret(key); if (value) { env[name] = value; break; } }
71
+ if (!env[name]) throw new Error(`Configure ${name} through auth before dispatch`);
72
+ }
73
+ return env;
74
+ }
75
+
76
+ export async function dispatchTask(id, prompt, options = {}, dependencies = {}) {
77
+ validateHarnessOptions(id, options);
78
+ const remote = options.node && options.node !== 'local';
79
+ if (remote && (typeof options.cwd !== 'string' || (!path.posix.isAbsolute(options.cwd) && !path.win32.isAbsolute(options.cwd)))) throw new Error('Choose an explicit absolute workspace on the remote node');
80
+ const { dispatchWithReceipt } = await import('./dispatch.mjs');
81
+ const result = await (dependencies.dispatch || dispatchWithReceipt)({
82
+ agent: id, cwd: remote ? options.cwd : path.resolve(options.cwd || process.cwd()), prompt,
83
+ node: options.node || 'local', permissions: { read: true, write: options.write === true },
84
+ allowUnknownAuth: options.allowUnknownAuth === true, timeoutMs: options.timeoutMs,
85
+ tools: options.tools, settingSources: options.settingSources, model: options.model,
86
+ ...(options.internalReasoning === true ? { internalReasoning: true } : {}),
87
+ ...(options.includedPlanOnly === true ? { includedPlanOnly: true } : {}),
88
+ ...(options.maxTurns !== undefined ? { maxTurns: options.maxTurns } : {}),
89
+ ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),
90
+ }, { node: options.node || 'local', role: options.role || 'Dispatch' });
91
+ return { ...result, harnessId: id, harnessName: HARNESS_SPECS[id]?.name || id, success: result.ok === true };
92
+ }
93
+
94
+ export async function runCouncil(prompt, ids, options = {}) {
95
+ const { coordinateTask } = await import('./coordinator.mjs');
96
+ return coordinateTask(prompt, { ...options, mode: 'council', execute: true, ...(ids ? { availableHarnesses: ids } : {}) });
97
+ }
98
+
99
+ export const getInstalledHarnessVersion = id => getInstalledVersion(id) || 'unknown';
100
+ export const getLatestHarnessVersion = (id, installed) => getLatestVersion(id, installed);
101
+
102
+ export async function queryHarnessUsage(options = {}) {
103
+ const { inspectQuotas } = await import('./router.mjs');
104
+ const report = await (options.inspectQuotas || inspectQuotas)(options);
105
+ if (!report.ok) throw new Error(report.error || 'Harness usage is unavailable');
106
+ const remaining = value => typeof value === 'number' ? `${Math.max(0, 100 - value)}%` : '—';
107
+ return Object.entries(report.quotas || {}).filter(([id]) => !['system', 'metered'].includes(id)).map(([id, quota]) => ({
108
+ id, name: HARNESS_SPECS[id]?.name || id, available: quota.installed === true,
109
+ authed: quota.status === 'ready', authRoute: quota.status, status: quota.status,
110
+ version: quota.version || 'unknown', latestVersion: quota.latestVersion || null, isCurrent: quota.latestVersion ? quota.version === quota.latestVersion : null,
111
+ rolling5hRemainingPct: remaining(quota.rolling5hUsedPercent), weeklyRemainingPct: remaining(quota.weeklyUsedPercent),
112
+ quotaRemaining: quota.quotaNote || 'No usage source', enforcement: 'advisory', enforcementEvidence: null,
113
+ }));
114
+ }
@@ -0,0 +1,145 @@
1
+ /** Job commands and events. The inbox is append-only; ack events are its cursor. */
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
+
10
+ const execute = promisify(execFile);
11
+ export function jobPaths(job) {
12
+ const id = typeof job === 'string' ? job : job?.id || job?.job;
13
+ if (typeof id !== 'string' || !/^[a-z0-9-]+$/.test(id)) throw new Error('Invalid job ID.');
14
+ const base = path.join(configDir(), 'jobs', id);
15
+ return { id, inbox: `${base}.inbox.jsonl`, events: `${base}.events.jsonl` };
16
+ }
17
+
18
+ function readLines(file) {
19
+ let data;
20
+ try { data = fs.readFileSync(file, 'utf8'); }
21
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
22
+ // An append from another process can still be incomplete.
23
+ return data.split('\n').slice(0, -1).filter(Boolean).map(line => JSON.parse(line));
24
+ }
25
+
26
+ export function appendEvent(job, event) {
27
+ const { events } = jobPaths(job);
28
+ fs.mkdirSync(path.dirname(events), { recursive: true, mode: 0o700 });
29
+ const entry = { ...event, t: new Date().toISOString() };
30
+ fs.appendFileSync(events, JSON.stringify(entry) + '\n', { mode: 0o600 });
31
+ return entry;
32
+ }
33
+
34
+ /** Read all requests, including requests older than watch's --tail. */
35
+ export function waitingRequests(job) {
36
+ const file = typeof job === 'string' && job.endsWith('.events.jsonl') ? job : jobPaths(job).events;
37
+ const waiting = new Map();
38
+ for (const event of readLines(file)) {
39
+ if (['question', 'approval'].includes(event.kind) && event.requestId) waiting.set(event.requestId, event);
40
+ if (event.kind === 'ack' && event.requestId && event.ok !== false) waiting.delete(event.requestId);
41
+ }
42
+ return [...waiting.values()];
43
+ }
44
+
45
+ function normalizeCommand(command) {
46
+ if (!command || typeof command !== 'object' || Array.isArray(command)) throw new Error('A job command is required.');
47
+ const type = command.type || command.command || command.kind;
48
+ if (!['reply', 'approve', 'interrupt', 'goal', 'fork'].includes(type)) throw new Error('Unsupported job command.');
49
+ if (['reply', 'goal'].includes(type) && (typeof command.text !== 'string' || !command.text.trim())) throw new Error(`${type} requires text.`);
50
+ if (type === 'approve' && (typeof command.requestId !== 'string' || !command.requestId || !['allow', 'deny'].includes(command.value))) {
51
+ throw new Error('approve requires a request ID and allow or deny.');
52
+ }
53
+ if (command.requestId !== undefined && (typeof command.requestId !== 'string' || !command.requestId)) throw new Error('Invalid request ID.');
54
+ return { ...command, type, command: type, id: command.id || randomUUID(), t: new Date().toISOString() };
55
+ }
56
+
57
+ const quote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
58
+
59
+ /** Resolve prefixes through the same owner as cancel. Remote delivery never writes a local inbox. */
60
+ export async function appendCommand(target, command, { local = false, execFileFn = execute } = {}) {
61
+ const job = resolveJob(typeof target === 'string' ? target : target?.id || target?.job);
62
+ if (job.result) throw new Error(`Job ${job.id} has finished.`);
63
+ const entry = normalizeCommand(command);
64
+ const node = job.record?.node;
65
+ if (!local && node && node !== 'local') {
66
+ if (typeof node !== 'string' || node.startsWith('-') || /[\0\r\n]/.test(node)) throw new Error('Invalid job node.');
67
+ const args = [entry.type, job.record.remoteJob || job.id];
68
+ if (entry.type === 'approve') args.push(entry.requestId, entry.value);
69
+ else if (!['interrupt', 'fork'].includes(entry.type)) args.push(entry.text);
70
+ if (entry.type === 'fork' && entry.atTurn) args.push('--at', entry.atTurn);
71
+ args.push('--local-delivery', '--json');
72
+ const remote = `total-recall meta-harness ${args.map(quote).join(' ')}`;
73
+ const result = await execFileFn(process.env.TOTAL_RECALL_BIN || 'total-recall', ['mesh', 'exec', node, remote],
74
+ { encoding: 'utf8', timeout: 60_000, maxBuffer: 1024 * 1024 });
75
+ if (result.exitCode && result.exitCode !== 0) throw new Error(result.stderr || 'Remote command failed.');
76
+ // mesh exec may wrap the remote result. Transport failures must not look like delivery.
77
+ let report;
78
+ try { report = JSON.parse(result.stdout); } catch { /* mesh can return plain command output */ }
79
+ if (report?.ok === false) throw new Error(report.error || 'Remote command failed.');
80
+ return { ok: true, job: job.id, node, remote: true, command: entry, ...(report ? { delivery: report } : {}) };
81
+ }
82
+ const waiting = waitingRequests(job.id);
83
+ const reserved = new Set(readLines(jobPaths(job.id).inbox).map(row => row.requestId).filter(Boolean));
84
+ const request = entry.requestId ? waiting.find(row => row.requestId === entry.requestId)
85
+ : entry.type === 'reply' ? waiting.find(row => row.kind === 'question' && !reserved.has(row.requestId)) : null;
86
+ if (entry.requestId && !request) throw new Error(`No waiting request matches ${entry.requestId}.`);
87
+ if (request && entry.type === 'approve' && request.kind !== 'approval') throw new Error('The request is not an approval.');
88
+ if (request && entry.type === 'reply' && request.kind !== 'question') throw new Error('The request is not a question.');
89
+ if (request) {
90
+ if (reserved.has(request.requestId)) throw new Error('The request already has an answer in the inbox.');
91
+ entry.requestId = request.requestId;
92
+ if (request.source === 'mcp') entry.recipient = 'mcp';
93
+ // A deferred question is answered by the session runner, which starts the next turn with it.
94
+ else if (request.source === 'deferred') entry.recipient = 'deferred';
95
+ }
96
+ const { inbox } = jobPaths(job.id);
97
+ fs.mkdirSync(path.dirname(inbox), { recursive: true, mode: 0o700 });
98
+ fs.appendFileSync(inbox, JSON.stringify(entry) + '\n', { mode: 0o600 });
99
+ return { ok: true, job: job.id, command: entry };
100
+ }
101
+
102
+ /**
103
+ * One consumer handles commands in file order. A false return leaves a command for
104
+ * another consumer. MCP answers have their own recipient so a worker cannot also
105
+ * send them to the driver. Await close() before releasing the driver.
106
+ */
107
+ export function tailInbox(job, onCommand, { pollMs = 50, recipient = 'driver', onError = () => {} } = {}) {
108
+ const { inbox, events } = jobPaths(job);
109
+ fs.mkdirSync(path.dirname(inbox), { recursive: true, mode: 0o700 });
110
+ fs.closeSync(fs.openSync(inbox, 'a', 0o600));
111
+ let closed = false, running = null;
112
+ const seen = new Set();
113
+ const poll = () => {
114
+ if (closed || running) return running;
115
+ running = (async () => {
116
+ const acknowledged = new Set(readLines(events).filter(row => row.kind === 'ack' && row.commandId).map(row => row.commandId));
117
+ for (const command of readLines(inbox)) {
118
+ if (closed) break;
119
+ if (!command.id || seen.has(command.id) || acknowledged.has(command.id) || (command.recipient || 'driver') !== recipient) continue;
120
+ let result;
121
+ try { result = await onCommand(command); }
122
+ catch (error) {
123
+ // A failed command is reported once; do not repeat an agent side effect.
124
+ seen.add(command.id);
125
+ appendEvent(job, { kind: 'ack', command: command.type || command.command, commandId: command.id,
126
+ requestId: command.requestId, ok: false, text: error.message });
127
+ onError(error);
128
+ continue;
129
+ }
130
+ if (result === false || result?.handled === false) continue;
131
+ seen.add(command.id);
132
+ appendEvent(job, { kind: 'ack', command: command.type || command.command, commandId: command.id,
133
+ requestId: command.requestId, ok: true, text: `Handled ${command.type || command.command}`, ...(result?.via ? { via: result.via } : {}) });
134
+ }
135
+ })().catch(onError).finally(() => { running = null; });
136
+ return running;
137
+ };
138
+ const timer = setInterval(poll, pollMs);
139
+ poll();
140
+ const close = async () => { closed = true; clearInterval(timer); await running; };
141
+ // A function is convenient for existing watcher callers; properties support explicit lifecycle use.
142
+ close.close = close;
143
+ close.poll = poll;
144
+ return close;
145
+ }