total-recall-brain 3.41.6 → 3.42.0
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/package.json +1 -1
- package/scaffold/.agent/skills/total-recall/plugins/auth/package-lock.json +3118 -17
- package/scaffold/.agent/skills/total-recall/plugins/auth/package.json +7 -2
- package/scaffold/.agent/skills/total-recall/plugins/auth/src/cli-secret.mjs +84 -40
- package/scaffold/.agent/skills/total-recall/plugins/auth/src/exit-after-flush.mjs +22 -0
- package/scaffold/.agent/skills/total-recall/plugins/auth/src/provider-api-rotation.mjs +61 -6
- package/scaffold/.agent/skills/total-recall/plugins/auth/src/provider-catalog.mjs +1 -0
- package/scaffold/.agent/skills/total-recall/plugins/auth/src/secrets-remote-deploy.mjs +8 -0
- package/scaffold/.agent/skills/total-recall/plugins/auth/src/secrets-rotate.mjs +20 -1
- package/scaffold/.agent/skills/total-recall/plugins/auth/src/secrets-store.mjs +3 -0
- package/scaffold/.agent/skills/total-recall/plugins/code-quality/core/state.mjs +15 -7
- package/scaffold/.agent/skills/total-recall/plugins/code-quality/package-lock.json +4 -4
- package/scaffold/.agent/skills/total-recall/plugins/composable-cli/package-lock.json +4 -4
- package/scaffold/.agent/skills/total-recall/plugins/embeddings/package-lock.json +4 -4
- package/scaffold/.agent/skills/total-recall/plugins/git-sentinel/package-lock.json +4 -4
- package/scaffold/.agent/skills/total-recall/plugins/mesh/package-lock.json +4 -4
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/README.md +51 -7
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/cli.mjs +67 -25
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/package-lock.json +4 -4
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/plugin.json +52 -6
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/skills/meta-harness/SKILL.md +1 -1
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/cascade.mjs +21 -8
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/compat-harness.mjs +110 -0
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/coordinator.mjs +48 -22
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/dispatch.mjs +9 -4
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/documentation.mjs +21 -9
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/executor.mjs +9 -5
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/gate.mjs +10 -4
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/learner.mjs +30 -3
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/paths.mjs +6 -1
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/pool.mjs +19 -3
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/process-manager.mjs +222 -0
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/process-worker.mjs +18 -0
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/reasoning.mjs +94 -0
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/remote-operation.mjs +70 -0
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/review.mjs +60 -19
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/router.mjs +32 -7
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/termination.mjs +24 -0
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/threads.mjs +88 -125
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/worker.mjs +110 -29
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/src/worktree.mjs +35 -0
- package/scaffold/.agent/skills/total-recall/plugins/meta-harness/ui/card.js +95 -5
- package/scaffold/.agent/skills/total-recall/plugins/openwiki/cli.mjs +13 -1
- package/scaffold/.agent/skills/total-recall/plugins/openwiki/package-lock.json +5 -5
- package/scaffold/.agent/skills/total-recall/plugins/openwiki/plugin.json +78 -0
- package/scaffold/.agent/skills/total-recall/plugins/openwiki/src/context-provider.mjs +113 -0
- package/scaffold/.agent/skills/total-recall/plugins/security/package-lock.json +4 -4
- package/src/cli/agent.mjs +11 -6
- package/src/cli/compact.mjs +3 -3
- package/src/cli/context.mjs +52 -19
- package/src/cli/harness.mjs +65 -147
- package/src/cli/init.mjs +4 -2
- package/src/cli/preflight.mjs +56 -13
- package/src/core/agent-manager.mjs +23 -329
- package/src/core/context-compactor.mjs +2 -1
- package/src/core/context-compiler.mjs +16 -25
- package/src/core/context-providers.mjs +69 -0
- package/src/core/meta-harness.mjs +27 -749
- package/src/core/plugin-runner.mjs +12 -5
- package/src/core/plugin-runtime.mjs +4 -2
- package/src/core/runtime.mjs +30 -604
- package/src/core/task-context.mjs +122 -0
- package/src/server/routes/context.mjs +4 -1
- package/scaffold/.agent/skills/decision/SKILL.md +0 -20
- package/scaffold/.agent/skills/decision/references/integration.md +0 -25
- package/scaffold/.agent/skills/decision/references/use-cases.md +0 -20
- package/scaffold/.agent/skills/meta-harness/SKILL.md +0 -15
- package/scaffold/.agent/skills/meta-harness/references/optimized/index.md +0 -20
- package/scaffold/.agent/skills/meta-harness/references/optimized/manifest.json +0 -79
- package/scaffold/.agent/skills/meta-harness/references/optimized/original.md +0 -135
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-01.md +0 -5
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-02.md +0 -17
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-03.md +0 -8
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-04.md +0 -2
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-05.md +0 -6
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-06.md +0 -14
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-07.md +0 -8
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-08.md +0 -4
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-09.md +0 -20
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-10.md +0 -6
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-11.md +0 -5
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-12.md +0 -7
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-13.md +0 -4
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-14.md +0 -7
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-15.md +0 -9
- package/scaffold/.agent/skills/meta-harness/references/optimized/section-16.md +0 -5
|
@@ -5,12 +5,33 @@
|
|
|
5
5
|
import { spawnSync } from 'node:child_process';
|
|
6
6
|
import { computeEmpiricalScorecard } from '../capability/index.mjs';
|
|
7
7
|
import { receiptsFile } from './paths.mjs';
|
|
8
|
+
import { classifyFailure } from './worker.mjs';
|
|
8
9
|
|
|
9
10
|
async function store() {
|
|
10
11
|
const { PluginStateStore } = await import('./ssss-store.mjs');
|
|
11
12
|
return new PluginStateStore(receiptsFile(), 'meta-harness');
|
|
12
13
|
}
|
|
13
|
-
|
|
14
|
+
/** Classify old failures with today's knowledge, so an early misreading cannot keep penalizing a harness. */
|
|
15
|
+
export const readReceipts = async () => liveReceipts((await store()).read([])).map(run => (run.failureKind === 'agent' && run.error ? { ...run, ...withoutAgent(classifyFailure(run.error, new Date(run.timestamp)), run) } : run));
|
|
16
|
+
const withoutAgent = (found, run) => (found.failureKind === 'agent' ? {} : { failureKind: found.failureKind, resetsAt: run.resetsAt || found.resetsAt || null });
|
|
17
|
+
|
|
18
|
+
/** The ledger is append-only, so a wrong row is voided by a later entry, never rewritten. Both stay on record. */
|
|
19
|
+
function liveReceipts(rows) {
|
|
20
|
+
const voided = new Set(rows.flatMap(row => row.voids || []));
|
|
21
|
+
return rows.filter(row => !row.voids && !voided.has(row.id));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function voidReceipts({ ids = [], reason = '' } = {}) {
|
|
25
|
+
if (!ids.length) throw new Error('--void needs at least one receipt id');
|
|
26
|
+
if (!String(reason).trim()) throw new Error('--void needs a --reason: a voided receipt stays on record with why');
|
|
27
|
+
const ledger = await store();
|
|
28
|
+
const live = new Set(liveReceipts(ledger.read([])).map(row => row.id));
|
|
29
|
+
const unknown = ids.filter(id => !live.has(id));
|
|
30
|
+
if (unknown.length) throw new Error(`No live receipt with id: ${unknown.join(', ')}`);
|
|
31
|
+
const entry = { id: `void-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`, timestamp: new Date().toISOString(), voids: ids, reason: String(reason) };
|
|
32
|
+
ledger.append(entry);
|
|
33
|
+
return { ok: true, voided: ids.length, id: entry.id, reason: entry.reason };
|
|
34
|
+
}
|
|
14
35
|
|
|
15
36
|
export async function recordRunReceipt(receipt = {}) {
|
|
16
37
|
if (!receipt.harness) throw new Error('A run receipt must name its harness');
|
|
@@ -18,6 +39,9 @@ export async function recordRunReceipt(receipt = {}) {
|
|
|
18
39
|
id: receipt.id || `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
19
40
|
timestamp: new Date().toISOString(),
|
|
20
41
|
harness: receipt.harness,
|
|
42
|
+
model: receipt.model ?? null,
|
|
43
|
+
exitCode: receipt.exitCode ?? null,
|
|
44
|
+
finishedReason: receipt.finishedReason ?? null,
|
|
21
45
|
role: receipt.role || null,
|
|
22
46
|
node: receipt.node || 'local',
|
|
23
47
|
task: String(receipt.task || '').slice(0, 300),
|
|
@@ -85,8 +109,11 @@ export async function learnFromHistory({ emit = false, runner = spawnSync } = {}
|
|
|
85
109
|
const proposals = proposalsFrom(scorecard, entries);
|
|
86
110
|
const emitted = [];
|
|
87
111
|
if (emit) for (const proposal of proposals) {
|
|
88
|
-
const result = runner(process.env.TOTAL_RECALL_BIN || 'total-recall', ['remember', '
|
|
89
|
-
|
|
112
|
+
const result = runner(process.env.TOTAL_RECALL_BIN || 'total-recall', ['remember', 'fact', `${proposal.reason} ${proposal.recommendation}`, '--project', '--slug', proposal.id, '--tags', `meta-harness,${proposal.id}`], { encoding: 'utf8', timeout: 30000 });
|
|
113
|
+
const output = `${result.stdout || ''}\n${result.stderr || ''}`;
|
|
114
|
+
// The slug is the proposal's identity, so an open proposal is reported once, however often learn runs.
|
|
115
|
+
const existing = result.status !== 0 && /already exists/i.test(output);
|
|
116
|
+
emitted.push({ id: proposal.id, ok: result.status === 0 || existing, ...(existing ? { existing: true } : {}), error: result.status === 0 || existing ? undefined : String(result.stderr || result.error || 'remember failed').slice(0, 300) });
|
|
90
117
|
}
|
|
91
118
|
return { ok: emitted.every(row => row.ok), totalHistoryRuns: entries.length, scorecard, walls: activeQuotaWalls(entries), credentialBlocks: activeCredentialBlocks(entries), proposals, ...(emit ? { emitted } : {}) };
|
|
92
119
|
}
|
|
@@ -3,7 +3,12 @@ import os from 'node:os';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
|
|
5
5
|
export function brainDir(env = process.env) {
|
|
6
|
-
|
|
6
|
+
const dir = env.TR_SECRETS_BRAIN || path.join(env.AGENT_DIR || path.join(env.HOME || os.homedir(), '.agent'), 'skills/total-recall');
|
|
7
|
+
// The node test runner marks its children. A run without test/isolate.mjs must fail, not write fake runs into the live ledger.
|
|
8
|
+
if (env.NODE_TEST_CONTEXT && !path.resolve(dir).startsWith(path.resolve(os.tmpdir()))) {
|
|
9
|
+
throw new Error(`Refusing to reach the live store ${dir} from a test: run the suite with npm test.`);
|
|
10
|
+
}
|
|
11
|
+
return dir;
|
|
7
12
|
}
|
|
8
13
|
export const configDir = (env = process.env) => path.join(brainDir(env), 'config', 'meta-harness');
|
|
9
14
|
export const derivedDir = (env = process.env) => path.join(brainDir(env), 'memory-derived', 'meta-harness');
|
|
@@ -3,6 +3,7 @@ import { ADAPTER_CATALOG } from '../capability/index.mjs';
|
|
|
3
3
|
import { inspectAgents, getActiveAdapters } from './worker.mjs';
|
|
4
4
|
import { readReceipts, activeQuotaWalls, activeCredentialBlocks } from './learner.mjs';
|
|
5
5
|
import { measuredWalls } from './telemetry.mjs';
|
|
6
|
+
import os from 'node:os';
|
|
6
7
|
|
|
7
8
|
const describe = (id, extra = {}) => {
|
|
8
9
|
const cap = ADAPTER_CATALOG[id] || {};
|
|
@@ -10,10 +11,11 @@ const describe = (id, extra = {}) => {
|
|
|
10
11
|
return { id, name: cap.name || spec.name || id, family: cap.family || spec.family || 'custom', tier: cap.tier || spec.tier || 'budget', qualityScore: cap.qualityScore ?? spec.qualityScore ?? 6, costScore: cap.costScore ?? spec.costScore ?? 4, ...extra };
|
|
11
12
|
};
|
|
12
13
|
|
|
13
|
-
export function exclusionReason(agent, wall, credentialBlock) {
|
|
14
|
+
export function exclusionReason(agent, wall, credentialBlock, { allowUnknownAuth = false } = {}) {
|
|
14
15
|
if (!agent.installed) return 'not installed';
|
|
15
16
|
if (!agent.versionVerified) return 'did not report a version';
|
|
16
17
|
if (agent.authenticated === false) return 'not signed in';
|
|
18
|
+
if (agent.authenticated !== true && !allowUnknownAuth) return 'authentication is unverified; explicit --allow-unknown-auth is required';
|
|
17
19
|
if (agent.blockedBy === 'no-chat-model') return 'no chat model installed';
|
|
18
20
|
if (wall) return `out of quota until ${wall.until}`;
|
|
19
21
|
if (credentialBlock) return `missing credential: ${String(credentialBlock.message || '').slice(0, 160)}`;
|
|
@@ -21,16 +23,30 @@ export function exclusionReason(agent, wall, credentialBlock) {
|
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
/** An explicit list is the caller's decision and is not filtered. */
|
|
24
|
-
export async function resolvePool({ availableHarnesses, inspect = inspectAgents, receipts = readReceipts } = {}) {
|
|
26
|
+
export async function resolvePool({ availableHarnesses, inspect = inspectAgents, receipts = readReceipts, allowUnknownAuth = false } = {}) {
|
|
25
27
|
if (Array.isArray(availableHarnesses) && availableHarnesses.length) return { ready: availableHarnesses.map(id => describe(id)), excluded: [], walls: {} };
|
|
26
28
|
const [{ agents = [] }, entries] = await Promise.all([inspect({ env: process.env }), receipts()]);
|
|
27
29
|
const walls = { ...activeQuotaWalls(entries), ...measuredWalls() };
|
|
28
30
|
const blocks = activeCredentialBlocks(entries);
|
|
29
31
|
const ready = [], excluded = [];
|
|
30
32
|
for (const agent of agents) {
|
|
31
|
-
const reason = exclusionReason(agent, walls[agent.id], blocks[agent.id]);
|
|
33
|
+
const reason = exclusionReason(agent, walls[agent.id], blocks[agent.id], { allowUnknownAuth });
|
|
32
34
|
if (!reason) ready.push(describe(agent.id, { authVerified: agent.authenticated === true }));
|
|
33
35
|
else if (agent.installed) excluded.push({ harness: agent.id, reason });
|
|
34
36
|
}
|
|
35
37
|
return { ready, excluded, walls };
|
|
36
38
|
}
|
|
39
|
+
|
|
40
|
+
export function isLocalExecutionNode(node = 'local') {
|
|
41
|
+
const hostname = os.hostname();
|
|
42
|
+
return ['local', hostname, hostname.split('.')[0]].includes(node);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Automatic placement needs a workspace mapping before it can become a remote job. */
|
|
46
|
+
export function localExecutionNode(options = {}, placement) {
|
|
47
|
+
const node = options.node || placement?.node || 'local';
|
|
48
|
+
if (!isLocalExecutionNode(node)) {
|
|
49
|
+
throw new Error(`Automatic placement on mesh node ${node} has no explicit remote workspace. Select --node and an absolute --cwd before execution; no local fallback was run.`);
|
|
50
|
+
}
|
|
51
|
+
return 'local';
|
|
52
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/** Managed agent processes. Metadata is SSSS state; native dispatch is always receipt-bearing. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { PluginStateStore } from './ssss-store.mjs';
|
|
9
|
+
import { configDir, brainDir } from './paths.mjs';
|
|
10
|
+
import { agentEnvironment } from './worker.mjs';
|
|
11
|
+
import { normalizeToolSelection, validateHarnessOptions, shellQuote } from './compat-harness.mjs';
|
|
12
|
+
import { createWorktree, removeWorktree, deleteBranch, commitAll, headCommit, isGitRepo } from './worktree.mjs';
|
|
13
|
+
|
|
14
|
+
const workerFile = fileURLToPath(new URL('./process-worker.mjs', import.meta.url));
|
|
15
|
+
const logDirectory = () => path.join(brainDir(), 'logs', 'meta-harness', 'agents');
|
|
16
|
+
const stateStore = () => new PluginStateStore(path.join(configDir(), 'processes.json'), 'meta-harness');
|
|
17
|
+
const validId = id => typeof id === 'string' && /^agent-[a-z0-9-]{1,120}$/.test(id);
|
|
18
|
+
|
|
19
|
+
function validateRecords(value) {
|
|
20
|
+
if (!Array.isArray(value) || value.some(record => !record || !validId(record.id) || typeof record.harness !== 'string' || typeof record.status !== 'string')) throw new Error('Invalid managed agent state');
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
export function loadAgentState() { return validateRecords(stateStore().read([])); }
|
|
24
|
+
export function saveAgentState(value) { const store = stateStore(); store.read([]); store.write(validateRecords(value)); }
|
|
25
|
+
|
|
26
|
+
/** Compare-and-write retries preserve concurrent processes; the native store enforces ownership. */
|
|
27
|
+
export function updateAgentRecord(id, patch) {
|
|
28
|
+
if (!validId(id)) throw new Error('Invalid agent identifier');
|
|
29
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
30
|
+
const store = stateStore(), records = validateRecords(store.read([]));
|
|
31
|
+
const index = records.findIndex(record => record.id === id);
|
|
32
|
+
const before = index < 0 ? { id } : records[index];
|
|
33
|
+
const record = { ...before, ...patch, id };
|
|
34
|
+
if (index < 0) records.unshift(record); else records[index] = record;
|
|
35
|
+
try { store.write(validateRecords(records)); return record; }
|
|
36
|
+
catch (error) { if (!/version|conflict|changed|precondition/i.test(error.message) || attempt === 4) throw error; }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isProcessRunning(pid) {
|
|
41
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
42
|
+
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
43
|
+
}
|
|
44
|
+
function processIdentity(pid) {
|
|
45
|
+
if (!isProcessRunning(pid)) return null;
|
|
46
|
+
const result = spawnSync('ps', ['-p', String(pid), '-o', 'lstart=,command='], { encoding: 'utf8', timeout: 3000 });
|
|
47
|
+
if (result.status !== 0 || !result.stdout.trim()) return null;
|
|
48
|
+
return { text: result.stdout.trim(), hash: crypto.createHash('sha256').update(result.stdout.trim()).digest('hex') };
|
|
49
|
+
}
|
|
50
|
+
function ownsProcess(record) {
|
|
51
|
+
const identity = processIdentity(record.pid);
|
|
52
|
+
return Boolean(identity && identity.text.includes(workerFile) && identity.text.includes(record.id) && identity.hash === record.processIdentity);
|
|
53
|
+
}
|
|
54
|
+
export function listAgents() {
|
|
55
|
+
return loadAgentState().map(record => {
|
|
56
|
+
if (record.remote || !['starting', 'running'].includes(record.status)) return record;
|
|
57
|
+
if (!record.pid) return { ...record, status: 'starting' };
|
|
58
|
+
return ownsProcess(record) ? record : { ...record, status: 'stopped', statusNote: 'Managed worker is no longer running' };
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function findAgent(idOrPid) {
|
|
63
|
+
const record = loadAgentState().find(item => item.id === idOrPid || String(item.pid) === String(idOrPid));
|
|
64
|
+
if (!record) throw new Error(`Agent "${idOrPid}" not found`);
|
|
65
|
+
return record;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function buildRemoteSpawnCommand(id, prompt, options = {}) {
|
|
69
|
+
const args = ['total-recall', 'meta-harness', 'process', 'spawn', id, prompt];
|
|
70
|
+
for (const [key, flag] of [['name', '--name'], ['cwd', '--cwd'], ['tools', '--tools'], ['settingSources', '--setting-sources'], ['model', '--model']]) {
|
|
71
|
+
if (options[key] !== undefined && options[key] !== null) args.push(flag, Array.isArray(options[key]) ? options[key].join(',') : String(options[key]));
|
|
72
|
+
}
|
|
73
|
+
if (options.detach === false) args.push('--no-detach');
|
|
74
|
+
if (options.write === false) args.push('--read-only');
|
|
75
|
+
if (options.allowUnknownAuth === true) args.push('--allow-unknown-auth');
|
|
76
|
+
args.push('--json');
|
|
77
|
+
return args.map(shellQuote).join(' ');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function remoteCall(node, cwd, args, dependencies = {}) {
|
|
81
|
+
const { executeOnNode } = await import('./executor.mjs');
|
|
82
|
+
const result = await (dependencies.executeOnNode || executeOnNode)(node, { operation: 'direct', cwd, argv: ['total-recall', 'meta-harness', 'process', ...args, '--json'] });
|
|
83
|
+
if (!result.ok) throw new Error(result.error || result.stderr || 'Remote process operation failed');
|
|
84
|
+
try { return JSON.parse(result.stdout || result.output || result.response); }
|
|
85
|
+
catch { throw new Error('Remote process owner returned invalid JSON'); }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function spawnAgent(harness, task, options = {}, dependencies = {}) {
|
|
89
|
+
validateHarnessOptions(harness, options);
|
|
90
|
+
if (typeof task !== 'string' || !task.trim() || Buffer.byteLength(task) > 65536) throw new Error('A bounded nonempty agent task is required');
|
|
91
|
+
if (options.node && options.node !== 'local') {
|
|
92
|
+
if (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');
|
|
93
|
+
const requested = options.cwd;
|
|
94
|
+
const args = ['spawn', harness, task, '--cwd', requested];
|
|
95
|
+
for (const [key, flag] of [['name', '--name'], ['tools', '--tools'], ['settingSources', '--setting-sources'], ['model', '--model']]) if (options[key] !== undefined) args.push(flag, Array.isArray(options[key]) ? options[key].join(',') : String(options[key]));
|
|
96
|
+
if (options.detach === false) args.push('--no-detach');
|
|
97
|
+
if (options.write === false) args.push('--read-only');
|
|
98
|
+
if (options.allowUnknownAuth === true) args.push('--allow-unknown-auth');
|
|
99
|
+
const result = await remoteCall(options.node, requested, args, dependencies);
|
|
100
|
+
if (!validId(result.id)) throw new Error('Remote process owner returned no valid agent identifier');
|
|
101
|
+
return updateAgentRecord(result.id, { ...result, harness, node: options.node, cwd: requested, remote: true });
|
|
102
|
+
}
|
|
103
|
+
const requested = options.cwd || process.cwd();
|
|
104
|
+
const cwd = path.resolve(/^~(?=$|\/)/.test(requested) ? path.join(os.homedir(), requested.slice(1)) : requested);
|
|
105
|
+
if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new Error(`Working directory does not exist: ${cwd}`);
|
|
106
|
+
if (options.write !== false && !isGitRepo(cwd)) throw new Error('Writing agent processes require a git repository for isolation');
|
|
107
|
+
const id = `agent-${harness}-${crypto.randomUUID()}`;
|
|
108
|
+
fs.mkdirSync(logDirectory(), { recursive: true, mode: 0o700 });
|
|
109
|
+
const logFile = path.join(logDirectory(), `${id}.log`);
|
|
110
|
+
const logFd = fs.openSync(logFile, 'ax', 0o600);
|
|
111
|
+
updateAgentRecord(id, { harness, name: options.name || `${harness} Worker`, task, cwd, logFile,
|
|
112
|
+
status: 'starting', startedAt: new Date().toISOString(), tools: normalizeToolSelection(options.tools) ?? 'default', detached: options.detach !== false });
|
|
113
|
+
const env = { ...agentEnvironment(process.env) };
|
|
114
|
+
for (const key of ['AGENT_DIR', 'TR_SECRETS_BRAIN', 'TR_PACKAGE_ROOT', 'TOTAL_RECALL_BIN']) if (process.env[key]) env[key] = process.env[key];
|
|
115
|
+
let child, completion;
|
|
116
|
+
try {
|
|
117
|
+
child = (dependencies.spawn || spawn)(process.execPath, [workerFile, '--job', id], { cwd, env, detached: true, stdio: ['pipe', logFd, logFd] });
|
|
118
|
+
completion = new Promise((resolve, reject) => {
|
|
119
|
+
child.once('error', reject);
|
|
120
|
+
child.once('close', code => resolve(code));
|
|
121
|
+
});
|
|
122
|
+
// Attach error handling before returning even for a detached process.
|
|
123
|
+
completion.catch(error => updateAgentRecord(id, { status: 'failed', error: error.message, endedAt: new Date().toISOString() }));
|
|
124
|
+
await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
|
|
125
|
+
const identity = (dependencies.identity || processIdentity)(child.pid);
|
|
126
|
+
if (!identity) throw new Error('Cannot establish managed process identity');
|
|
127
|
+
updateAgentRecord(id, { pid: child.pid, processIdentity: identity.hash, status: 'running' });
|
|
128
|
+
child.stdin.on('error', error => { updateAgentRecord(id, { status: 'failed', error: `Worker input failed: ${error.message}`, endedAt: new Date().toISOString() }); });
|
|
129
|
+
child.stdin.end(JSON.stringify({ id, harness, task, cwd, options: { write: options.write !== false, tools: options.tools, settingSources: options.settingSources, model: options.model, allowUnknownAuth: options.allowUnknownAuth === true, timeoutMs: options.timeoutMs } }));
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (child?.pid) { try { child.kill('SIGTERM'); } catch { /* process already stopped */ } }
|
|
132
|
+
updateAgentRecord(id, { status: 'failed', error: error.message, endedAt: new Date().toISOString() });
|
|
133
|
+
throw error;
|
|
134
|
+
} finally { fs.closeSync(logFd); }
|
|
135
|
+
if (options.detach !== false) { child.unref(); return findAgent(id); }
|
|
136
|
+
const code = await completion;
|
|
137
|
+
const result = findAgent(id);
|
|
138
|
+
if (!['completed', 'failed', 'killed'].includes(result.status)) return updateAgentRecord(id, { status: 'failed', exitCode: code, error: 'Managed worker exited without a completion record', endedAt: new Date().toISOString() });
|
|
139
|
+
return { ...result, output: result.result || await getAgentLogs(id, 200) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Run inside the managed worker. The original checkout is never writable to the agent. */
|
|
143
|
+
export async function executeProcessTask(job, dependencies = {}) {
|
|
144
|
+
const { dispatchWithReceipt } = await import('./dispatch.mjs');
|
|
145
|
+
validateHarnessOptions(job.harness, job.options);
|
|
146
|
+
let worktree = null, branch = null, commit = null;
|
|
147
|
+
let result;
|
|
148
|
+
try {
|
|
149
|
+
let cwd = job.cwd;
|
|
150
|
+
if (job.options.write === true) {
|
|
151
|
+
if (!isGitRepo(job.cwd)) throw new Error('Writing agent processes require a git repository for isolation');
|
|
152
|
+
branch = `meta-harness/${job.id}`;
|
|
153
|
+
const baseCommit = headCommit(job.cwd);
|
|
154
|
+
worktree = createWorktree(job.cwd, { branch, ref: baseCommit, prefix: 'meta-harness-process-' });
|
|
155
|
+
cwd = worktree;
|
|
156
|
+
updateAgentRecord(job.id, { branch, worktreePath: worktree, baseCommit });
|
|
157
|
+
}
|
|
158
|
+
result = await (dependencies.dispatch || dispatchWithReceipt)({
|
|
159
|
+
agent: job.harness, prompt: job.task, cwd, contextCwd: job.cwd, contextTask: job.task,
|
|
160
|
+
isolated: Boolean(worktree), permissions: { read: true, write: job.options.write === true },
|
|
161
|
+
tools: job.options.tools, settingSources: job.options.settingSources, model: job.options.model,
|
|
162
|
+
allowUnknownAuth: job.options.allowUnknownAuth === true, timeoutMs: job.options.timeoutMs,
|
|
163
|
+
}, { role: 'Process', node: 'local' });
|
|
164
|
+
if (result.ok && worktree) commit = commitAll(worktree, 'Meta Harness managed agent work');
|
|
165
|
+
} catch (error) {
|
|
166
|
+
result = { ok: false, error: error.message };
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
if (worktree) { (dependencies.removeWorktree || removeWorktree)(job.cwd, worktree); worktree = null; }
|
|
170
|
+
if (branch && !commit) { (dependencies.deleteBranch || deleteBranch)(job.cwd, branch); branch = null; }
|
|
171
|
+
} catch (error) { result = { ...result, ok: false, error: `${result.error ? result.error + '; ' : ''}Isolation cleanup failed: ${error.message}` }; }
|
|
172
|
+
return updateAgentRecord(job.id, { status: result.ok ? 'completed' : 'failed', exitCode: result.exitCode ?? (result.ok ? 0 : 1), error: result.ok ? null : result.error,
|
|
173
|
+
result: result.response || null, branch, commit, worktreePath: worktree, endedAt: new Date().toISOString() });
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function killAgent(idOrPid, dependencies = {}) {
|
|
177
|
+
const record = findAgent(idOrPid);
|
|
178
|
+
if (record.remote) {
|
|
179
|
+
const result = await remoteCall(record.node, record.cwd, ['kill', record.id], dependencies);
|
|
180
|
+
if (result.success !== true) throw new Error(result.error || 'Remote owner did not confirm termination');
|
|
181
|
+
updateAgentRecord(record.id, { status: 'killed', endedAt: new Date().toISOString() });
|
|
182
|
+
return result;
|
|
183
|
+
}
|
|
184
|
+
if (!isProcessRunning(record.pid)) return { success: true, message: `Agent ${record.id} is already stopped` };
|
|
185
|
+
if (!ownsProcess(record)) throw new Error('Refusing to kill a process whose managed identity cannot be verified');
|
|
186
|
+
const tree = spawnSync('ps', ['-axo', 'pid=,ppid='], { encoding: 'utf8', timeout: 3000 });
|
|
187
|
+
if (tree.status !== 0) throw new Error('Cannot inspect managed process descendants');
|
|
188
|
+
const relations = tree.stdout.trim().split('\n').map(line => line.trim().split(/\s+/).map(Number));
|
|
189
|
+
const targets = [record.pid];
|
|
190
|
+
for (let i = 0; i < targets.length; i++) for (const [pid, parent] of relations) if (parent === targets[i] && !targets.includes(pid)) targets.push(pid);
|
|
191
|
+
const identities = targets.reverse().map(pid => ({ pid, identity: processIdentity(pid)?.hash })).filter(item => item.identity);
|
|
192
|
+
const stillOwned = item => processIdentity(item.pid)?.hash === item.identity;
|
|
193
|
+
for (const item of identities) if (stillOwned(item)) { try { process.kill(item.pid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; } }
|
|
194
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
195
|
+
for (const item of identities) if (stillOwned(item)) { try { process.kill(item.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; } }
|
|
196
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
197
|
+
if (identities.some(stillOwned)) throw new Error('Managed processes did not stop; isolation was retained');
|
|
198
|
+
const stopped = findAgent(record.id);
|
|
199
|
+
if (stopped.worktreePath) removeWorktree(stopped.cwd, stopped.worktreePath);
|
|
200
|
+
if (stopped.branch && !stopped.commit) deleteBranch(stopped.cwd, stopped.branch);
|
|
201
|
+
const { recordRunReceipt } = await import('./learner.mjs');
|
|
202
|
+
await recordRunReceipt({ harness: record.harness, role: 'Process', node: 'local', task: record.task, success: false, failureKind: 'cancelled', finishedReason: 'cancelled' });
|
|
203
|
+
updateAgentRecord(record.id, { status: 'killed', branch: stopped.commit ? stopped.branch : null, worktreePath: null, endedAt: new Date().toISOString() });
|
|
204
|
+
return { success: true, message: `Terminated managed agent ${record.id}` };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export async function getAgentLogs(idOrPid, tailLines = 50, dependencies = {}) {
|
|
208
|
+
const record = findAgent(idOrPid);
|
|
209
|
+
if (!Number.isInteger(tailLines) || tailLines < 1 || tailLines > 10000) throw new Error('Log tail must be between 1 and 10000 lines');
|
|
210
|
+
if (record.remote) {
|
|
211
|
+
const result = await remoteCall(record.node, record.cwd, ['logs', record.id, '--tail', String(tailLines)], dependencies);
|
|
212
|
+
if (typeof result.logs !== 'string') throw new Error('Remote owner returned no logs');
|
|
213
|
+
return result.logs;
|
|
214
|
+
}
|
|
215
|
+
if (path.dirname(record.logFile || '') !== logDirectory()) throw new Error('Invalid managed log path');
|
|
216
|
+
const stat = fs.lstatSync(record.logFile, { throwIfNoEntry: false });
|
|
217
|
+
if (!stat) return '';
|
|
218
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Unsafe managed log file');
|
|
219
|
+
const size = Math.min(stat.size, 4 * 1024 * 1024), buffer = Buffer.alloc(size), fd = fs.openSync(record.logFile, 'r');
|
|
220
|
+
try { fs.readSync(fd, buffer, 0, size, stat.size - size); } finally { fs.closeSync(fd); }
|
|
221
|
+
return buffer.toString('utf8').split('\n').slice(-tailLines).join('\n');
|
|
222
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Internal worker entry; argv carries only a process identity, never credentials or prompts. */
|
|
2
|
+
import { executeProcessTask, updateAgentRecord } from './process-manager.mjs';
|
|
3
|
+
|
|
4
|
+
const id = process.argv[3];
|
|
5
|
+
if (process.argv[2] !== '--job' || !/^agent-[a-z0-9-]{1,120}$/.test(id || '')) throw new Error('Managed worker identity required');
|
|
6
|
+
try {
|
|
7
|
+
let input = '';
|
|
8
|
+
for await (const chunk of process.stdin) { input += chunk; if (Buffer.byteLength(input) > 131072) throw new Error('Managed task exceeds input limit'); }
|
|
9
|
+
const job = JSON.parse(input);
|
|
10
|
+
if (job.id !== id) throw new Error('Managed worker identity mismatch');
|
|
11
|
+
const result = await executeProcessTask(job);
|
|
12
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
13
|
+
if (result.status !== 'completed') process.exitCode = 1;
|
|
14
|
+
} catch (error) {
|
|
15
|
+
updateAgentRecord(id, { status: 'failed', error: error.message, endedAt: new Date().toISOString() });
|
|
16
|
+
process.stderr.write(`${error.message}\n`);
|
|
17
|
+
process.exitCode = 1;
|
|
18
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** Headless reasoning belongs to Meta Harness, including config, readiness and receipts. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { brainDir } from './paths.mjs';
|
|
5
|
+
import { getActiveAdapters, inspectAgents } from './worker.mjs';
|
|
6
|
+
import { dispatchTask } from './compat-harness.mjs';
|
|
7
|
+
|
|
8
|
+
function readConfig(file) {
|
|
9
|
+
if (!fs.existsSync(file)) return {};
|
|
10
|
+
let value;
|
|
11
|
+
try { value = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
12
|
+
catch (error) { throw new Error(`Invalid reasoning configuration: ${error.message}`); }
|
|
13
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Reasoning configuration must be an object');
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function loadRuntimeConfig(_legacyPath, options = {}) {
|
|
18
|
+
const env = options.env || process.env, argv = options.argv || process.argv;
|
|
19
|
+
const root = options.brainDir || brainDir(env);
|
|
20
|
+
const config = readConfig(path.join(root, 'config', 'meta-harness', 'reasoning.json'));
|
|
21
|
+
const brain = readConfig(path.join(root, 'config', 'brain.json'));
|
|
22
|
+
const adapters = getActiveAdapters();
|
|
23
|
+
let agents = adapters.map((adapter, index) => ({ name: adapter.id, binary: adapter.binary, enabled: true, priority: index + 1 }));
|
|
24
|
+
if (config.agents !== undefined) {
|
|
25
|
+
if (!Array.isArray(config.agents)) throw new Error('Reasoning agents must be an array');
|
|
26
|
+
agents = config.agents.filter(agent => agent.enabled !== false).map((agent, index) => {
|
|
27
|
+
const adapter = adapters.find(item => item.id === agent.name || item.id === agent.id);
|
|
28
|
+
if (!adapter) throw new Error(`Unknown reasoning harness ${agent.name || agent.id}`);
|
|
29
|
+
if (agent.flags !== undefined || (agent.binary && agent.binary !== adapter.binary)) throw new Error('Native flags belong to the adapter registry');
|
|
30
|
+
return { name: adapter.id, binary: adapter.binary, enabled: true, priority: agent.priority ?? index + 1, model: agent.model || null };
|
|
31
|
+
}).sort((a, b) => a.priority - b.priority);
|
|
32
|
+
}
|
|
33
|
+
let preferred = argv.find(value => value.startsWith('--agent='))?.slice(8) || env.TR_CLI_AGENT || config.preferredAgent || brain.preferred_agent;
|
|
34
|
+
if (!preferred) {
|
|
35
|
+
for (const file of [options.instructionsFile, options.surfaceDir && path.join(options.surfaceDir, 'AGENTS.md')].filter(Boolean)) {
|
|
36
|
+
if (!fs.existsSync(file)) continue;
|
|
37
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
38
|
+
preferred = (text.match(/preferred\s+CLI\s+agent\s+is\s+([a-zA-Z0-9_-]+)/i) || text.match(/preferred_cli_agent:\s*([a-zA-Z0-9_-]+)/i))?.[1]?.toLowerCase();
|
|
39
|
+
if (preferred) break;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (preferred) {
|
|
43
|
+
const selected = agents.find(agent => agent.name === preferred);
|
|
44
|
+
if (!selected) throw new Error(`Preferred reasoning harness ${preferred} is not configured`);
|
|
45
|
+
selected.priority = 0;
|
|
46
|
+
agents.sort((a, b) => a.priority - b.priority);
|
|
47
|
+
}
|
|
48
|
+
if (env.TR_CLI_MODEL && agents.length) agents[0].model = env.TR_CLI_MODEL;
|
|
49
|
+
const timeout = Number(env.TR_CLI_TIMEOUT || config.timeout || 300);
|
|
50
|
+
if (!Number.isFinite(timeout) || timeout <= 0) throw new Error('Reasoning timeout must be positive');
|
|
51
|
+
return { agents, timeout, maxRetries: config.maxRetries ?? 0, embedding: config.embedding || options.embedding,
|
|
52
|
+
allowUnknownAuth: config.allowUnknownAuth === true, preferredAgent: preferred || null };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function checkRuntimeHealth(config, { inspect = inspectAgents } = {}) {
|
|
56
|
+
const desired = (config?.agents || loadRuntimeConfig().agents).filter(agent => agent.enabled !== false);
|
|
57
|
+
const report = await inspect({ ids: desired.map(agent => agent.name) });
|
|
58
|
+
const available = desired.flatMap(agent => {
|
|
59
|
+
const observed = report.agents.find(item => item.id === agent.name);
|
|
60
|
+
return observed?.installed && observed.authenticated === true && observed.versionVerified && !observed.blockedBy
|
|
61
|
+
? [{ name: agent.name, binary: agent.binary, priority: agent.priority }] : [];
|
|
62
|
+
});
|
|
63
|
+
return { status: available.length ? 'healthy' : 'degraded', available, primary: available[0]?.name || null,
|
|
64
|
+
...(available.length ? {} : { reason: 'No configured harness has verified login and runtime readiness' }) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function callLocalRuntime(prompt, system, config, dependencies = {}) {
|
|
68
|
+
if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('A nonempty reasoning task is required');
|
|
69
|
+
config ||= loadRuntimeConfig();
|
|
70
|
+
const text = system ? `${system}\n\n---\n\n${prompt}` : prompt;
|
|
71
|
+
const agents = (config.agents || []).filter(agent => agent.enabled !== false).sort((a, b) => a.priority - b.priority);
|
|
72
|
+
if (!agents.length) throw new Error('No CLI agents are configured');
|
|
73
|
+
const { resolvePool } = await import('./pool.mjs');
|
|
74
|
+
const pool = await (dependencies.resolvePool || resolvePool)({ allowUnknownAuth: config.allowUnknownAuth === true });
|
|
75
|
+
const candidates = agents.filter(agent => pool.ready.some(ready => ready.id === agent.name));
|
|
76
|
+
if (!candidates.length) throw new Error(`No configured CLI agent is ready: ${(pool.excluded || []).map(item => `${item.harness}: ${item.reason}`).join('; ') || 'no verified runtime'}`);
|
|
77
|
+
const failures = [];
|
|
78
|
+
for (const agent of candidates) {
|
|
79
|
+
const result = await (dependencies.dispatch || dispatchTask)(agent.name, text, {
|
|
80
|
+
cwd: config.cwd || process.cwd(), node: config.node || 'local', timeoutMs: (config.timeout || 300) * 1000,
|
|
81
|
+
model: agent.model || undefined, write: false, role: 'Reasoning', allowUnknownAuth: config.allowUnknownAuth === true,
|
|
82
|
+
});
|
|
83
|
+
if (result.ok === true || result.success === true) return result.response || '';
|
|
84
|
+
failures.push(`${agent.name}: ${result.error || 'dispatch failed'}`);
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`All CLI agents failed (${failures.join('; ')})`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function callLocalRuntimeRaw(messages, config, _tools, dependencies) {
|
|
90
|
+
if (!Array.isArray(messages)) throw new Error('Reasoning messages must be an array');
|
|
91
|
+
const system = messages.filter(message => message.role === 'system').map(message => message.content).join('\n');
|
|
92
|
+
const user = messages.filter(message => message.role !== 'system').map(message => message.content).join('\n');
|
|
93
|
+
return { role: 'assistant', content: await callLocalRuntime(user, system, config, dependencies) };
|
|
94
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Forward a complete owning-plugin job through the existing verified mesh executor. */
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { executeOnNode } from './executor.mjs';
|
|
4
|
+
import { isLocalExecutionNode } from './pool.mjs';
|
|
5
|
+
|
|
6
|
+
const BOOLEAN_FLAGS = {
|
|
7
|
+
execute: '--execute', gate: '--gate', jev: '--jev', preferLocal: '--prefer-local', preferFrontier: '--prefer-frontier',
|
|
8
|
+
autoReview: '--auto-review', allowSameFamily: '--allow-same-family', allowUnknownAuth: '--allow-unknown-auth', staged: '--staged',
|
|
9
|
+
};
|
|
10
|
+
const VALUE_FLAGS = {
|
|
11
|
+
mode: '--mode', orchestrator: '--orchestrator', explorer: '--explorer', architect: '--architect', implementer: '--implementer',
|
|
12
|
+
verifier: '--verifier', reviewer: '--reviewer', author: '--author', threadId: '--thread', branch: '--branch',
|
|
13
|
+
};
|
|
14
|
+
const OPERATION_KEYS = {
|
|
15
|
+
route: ['execute', 'gate', 'jev', 'preferLocal', 'preferFrontier', 'allowUnknownAuth'],
|
|
16
|
+
coordinate: ['execute', 'gate', 'autoReview', 'allowSameFamily', 'allowUnknownAuth', 'mode', 'orchestrator', 'explorer', 'architect', 'implementer', 'verifier', 'reviewer', 'branch'],
|
|
17
|
+
review: ['staged', 'allowUnknownAuth', 'reviewer', 'author', 'threadId'],
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export async function forwardRemoteOperation(operation, task, options = {}) {
|
|
21
|
+
if (!options.node || isLocalExecutionNode(options.node)) return null;
|
|
22
|
+
if (!Object.hasOwn(OPERATION_KEYS, operation)) throw new Error('Unsupported remote operation');
|
|
23
|
+
if (typeof options.node !== 'string' || /[\0\r\n]/.test(options.node)) throw new Error('Explicit recorded mesh node required');
|
|
24
|
+
if (typeof options.cwd !== 'string' || !path.isAbsolute(options.cwd) || options.cwd.includes('\0')) throw new Error('Remote execution requires an explicit absolute workspace (--cwd) on the selected node');
|
|
25
|
+
// A job runs several agents, so its budget is the maximum, not one agent's.
|
|
26
|
+
const timeoutMs = options.timeoutMs ?? 3600000;
|
|
27
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3600000) throw new Error('Remote operation timeout must be between 1 ms and one hour');
|
|
28
|
+
|
|
29
|
+
const argv = ['total-recall', 'meta-harness', operation];
|
|
30
|
+
if (operation === 'review') {
|
|
31
|
+
if (options.target) argv.push(String(options.target));
|
|
32
|
+
} else {
|
|
33
|
+
if (typeof task !== 'string' || !task.trim()) throw new Error('Remote operation requires a task description');
|
|
34
|
+
argv.push(task);
|
|
35
|
+
}
|
|
36
|
+
for (const key of OPERATION_KEYS[operation]) {
|
|
37
|
+
if (BOOLEAN_FLAGS[key]) { if (options[key] === true) argv.push(BOOLEAN_FLAGS[key]); }
|
|
38
|
+
else if (options[key] !== undefined && options[key] !== null) {
|
|
39
|
+
if (typeof options[key] !== 'string' || !options[key] || /\0/.test(options[key])) throw new Error(`Invalid remote ${key}`);
|
|
40
|
+
argv.push(VALUE_FLAGS[key], options[key]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (operation === 'coordinate' && options.subagents === false) argv.push('--no-subagents');
|
|
44
|
+
if (['route', 'coordinate'].includes(operation) && options.gateOptions?.tier) argv.push('--tier', options.gateOptions.tier);
|
|
45
|
+
// Force destination-local execution so a forwarded job cannot recursively forward itself.
|
|
46
|
+
argv.push('--cwd', options.cwd, '--node', 'local', '--json');
|
|
47
|
+
const execution = { node: options.node, workspace: options.cwd, remote: true, operation };
|
|
48
|
+
let transport;
|
|
49
|
+
try {
|
|
50
|
+
transport = await (options.executeOnNodeFn || executeOnNode)(options.node, { operation: 'direct', cwd: options.cwd, argv, timeoutMs });
|
|
51
|
+
} catch (error) {
|
|
52
|
+
return { ok: false, execution, failureKind: 'transport', error: `Remote ${operation} transport failed: ${error.message}. The job may still be running on ${options.node}; check its branches and threads before starting it again.` };
|
|
53
|
+
}
|
|
54
|
+
let payload;
|
|
55
|
+
try {
|
|
56
|
+
payload = JSON.parse(transport.output || '');
|
|
57
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload) || typeof payload.ok !== 'boolean') throw new Error('Missing operation outcome');
|
|
58
|
+
} catch {
|
|
59
|
+
return { ok: false, execution, failureKind: 'transport', transportExitCode: transport.exitCode ?? null,
|
|
60
|
+
error: transport.error || 'Remote operation returned no valid structured result' };
|
|
61
|
+
}
|
|
62
|
+
const result = { ...payload, ok: transport.ok === true && payload.ok === true, execution, transportExitCode: transport.exitCode ?? null,
|
|
63
|
+
...(!transport.ok ? { failureKind: 'transport' } : {}) };
|
|
64
|
+
if (!result.ok && !result.error) result.error = transport.error || `Remote ${operation} failed`;
|
|
65
|
+
if (result.ok && payload.branch) result.deliverable = { node: options.node, workspace: options.cwd, branch: payload.branch, commit: payload.commit ?? null };
|
|
66
|
+
const threadId = payload.threadId || options.threadId;
|
|
67
|
+
if (threadId) result.threadRef = { node: options.node, workspace: options.cwd, id: threadId };
|
|
68
|
+
if (payload.review) result.review = { ...payload.review, node: options.node, workspace: options.cwd, ...(threadId ? { threadId } : {}) };
|
|
69
|
+
return result;
|
|
70
|
+
}
|