tr-plugin-meta-harness 0.3.0 → 0.5.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +86 -0
- package/README.md +257 -11
- package/capability/BRICK.md +1 -1
- package/capability/index.mjs +154 -13
- package/cli.mjs +426 -41
- package/package.json +15 -3
- package/plugin.json +1457 -119
- package/skills/meta-harness/SKILL.md +63 -25
- package/src/adoption.mjs +102 -0
- package/src/agent-user.mjs +194 -0
- package/src/alerts.mjs +220 -14
- package/src/cascade.mjs +185 -0
- package/src/chat.mjs +80 -0
- package/src/codex-models.mjs +54 -0
- package/src/compat-harness.mjs +117 -0
- package/src/control.mjs +145 -0
- package/src/coordinator.mjs +267 -358
- package/src/dispatch-request.mjs +76 -0
- package/src/dispatch.mjs +119 -0
- package/src/documentation-authority.mjs +57 -0
- package/src/documentation.mjs +120 -32
- package/src/executor.mjs +101 -22
- package/src/gate-adapters/agy.mjs +155 -0
- package/src/gate-adapters/claude.mjs +303 -0
- package/src/gate-adapters/cline.mjs +111 -0
- package/src/gate-adapters/codex.mjs +164 -0
- package/src/gate-adapters/cursor.mjs +164 -0
- package/src/gate-adapters/devin.mjs +116 -0
- package/src/gate-adapters/dsh.mjs +284 -0
- package/src/gate-adapters/grok.mjs +112 -0
- package/src/gate-adapters/hermes.mjs +217 -0
- package/src/gate-adapters/hook-files.mjs +156 -0
- package/src/gate-adapters/index.mjs +131 -0
- package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
- package/src/gate-adapters/openclaw-plugin/index.js +25 -0
- package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
- package/src/gate-adapters/openclaw-plugin/package.json +15 -0
- package/src/gate-adapters/openclaw.mjs +288 -0
- package/src/gate-adapters/pi.mjs +146 -0
- package/src/gate.mjs +18 -0
- package/src/harness-updates.mjs +170 -0
- package/src/included-usage.mjs +344 -0
- package/src/jobs.mjs +135 -0
- package/src/json-reply.mjs +22 -0
- package/src/learner.mjs +97 -67
- package/src/maintenance.mjs +18 -0
- package/src/mcp-server.mjs +228 -0
- package/src/model-catalog.mjs +195 -0
- package/src/model-selection.mjs +67 -0
- package/src/paths.mjs +23 -0
- package/src/pool.mjs +69 -0
- package/src/process-manager.mjs +246 -0
- package/src/process-worker.mjs +18 -0
- package/src/reasoning.mjs +231 -0
- package/src/remote-operation.mjs +76 -0
- package/src/review.mjs +241 -0
- package/src/reviews.mjs +25 -0
- package/src/router-benchmark-corpus.mjs +16 -0
- package/src/router-benchmark.mjs +208 -0
- package/src/router.mjs +265 -346
- package/src/runtime.mjs +30 -8
- package/src/session/claude.mjs +358 -0
- package/src/session/codex.mjs +501 -0
- package/src/session/result.mjs +90 -0
- package/src/session/resume.mjs +393 -0
- package/src/session/run.mjs +258 -0
- package/src/session-jobs.mjs +77 -0
- package/src/setup.mjs +6 -3
- package/src/ssss-store.mjs +20 -0
- package/src/telemetry.mjs +267 -0
- package/src/termination.mjs +28 -0
- package/src/threads.mjs +150 -0
- package/src/usage-queue.mjs +137 -0
- package/src/verify-ssss.mjs +102 -0
- package/src/worker.mjs +955 -84
- package/src/worktree.mjs +244 -0
- package/ui/chunks/adapter-docs-freshness.md +16 -0
- package/ui/chunks/chat-handoff.md +26 -0
- package/ui/chunks/fleet-maintenance.md +21 -0
- package/ui/chunks/harness-inventory.md +21 -0
- package/ui/chunks/included-access.md +18 -0
- package/ui/chunks/included-usage-verification.md +15 -0
- package/ui/chunks/independent-review.md +17 -0
- package/ui/chunks/managed-execution.md +20 -0
- package/ui/chunks/official-documentation.md +18 -0
- package/ui/chunks/quota-recovery.md +21 -0
- package/ui/chunks/review-routing-decision.md +16 -0
- package/ui/chunks/route-work.md +18 -0
- package/ui/chunks/routing-evidence.md +18 -0
- package/ui/chunks/run-ledger.md +18 -0
- package/ui/chunks/session-controls.md +16 -0
- package/ui/home.js +198 -0
- package/ui/DESIGN.md +0 -32
- package/ui/card.js +0 -845
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which harness may run a requested model. Shape, operator policy and harness support come first
|
|
3
|
+
* (worker.mjs, so a remote destination enforces them too). Then the AI Models plugin, which owns the
|
|
4
|
+
* shared model catalog, decides when it answers `ai-models validate`. When it cannot answer, this
|
|
5
|
+
* machine's synced harness model lists decide; a harness without a list is accepted as unverified.
|
|
6
|
+
*/
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { modelRefusal } from './worker.mjs';
|
|
9
|
+
import { getModelCatalog, normalizeModelName } from './model-catalog.mjs';
|
|
10
|
+
import { codexModelRefusal } from './codex-models.mjs';
|
|
11
|
+
|
|
12
|
+
/** Ask the AI Models owner. Null means it gave no verdict (not installed, not implemented, or unreadable). */
|
|
13
|
+
export function queryAiModels(harness, model, { bin = process.env.TOTAL_RECALL_BIN || 'total-recall' } = {}) {
|
|
14
|
+
let output;
|
|
15
|
+
try {
|
|
16
|
+
output = execFileSync(bin, ['ai-models', 'validate', '--harness', harness, '--model', model, '--json'], { encoding: 'utf8', timeout: 20000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
17
|
+
} catch (error) {
|
|
18
|
+
// A refusal may exit nonzero with its verdict on stdout.
|
|
19
|
+
output = String(error.stdout || '');
|
|
20
|
+
}
|
|
21
|
+
const line = output.trim().split('\n').filter(Boolean).at(-1);
|
|
22
|
+
try {
|
|
23
|
+
const answer = JSON.parse(line);
|
|
24
|
+
if (!answer || typeof answer.ok !== 'boolean') return null;
|
|
25
|
+
// An error reply (an older ai-models without `validate` answers invalid_arguments) is the command
|
|
26
|
+
// failing, not a verdict on the model; reading it as one would refuse every model.
|
|
27
|
+
if (answer.error != null || answer.code != null) return null;
|
|
28
|
+
return answer;
|
|
29
|
+
} catch { return null; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One validator per decision: after the owner fails to answer once, it is not asked again. */
|
|
33
|
+
export function createModelValidator({ aiModels = queryAiModels, catalog = getModelCatalog, local = true, codexRefusal = codexModelRefusal } = {}) {
|
|
34
|
+
let ownerAnswers = true, listed;
|
|
35
|
+
return (harness, model) => {
|
|
36
|
+
const refusal = modelRefusal(harness, model);
|
|
37
|
+
if (refusal) return { ok: false, harness, model, source: 'policy', reason: refusal };
|
|
38
|
+
// The account's own list decides first: the API catalog also holds models the account cannot run.
|
|
39
|
+
const unavailable = local && harness === 'codex' ? codexRefusal(model) : null;
|
|
40
|
+
if (unavailable) return { ok: false, harness, model, source: 'codex-account', reason: unavailable };
|
|
41
|
+
if (ownerAnswers) {
|
|
42
|
+
const answer = aiModels(harness, model);
|
|
43
|
+
if (answer) return { ok: answer.ok, harness, model, source: 'ai-models', ...(answer.ok ? {} : { reason: answer.reason || `AI Models does not list ${model} for ${harness}` }) };
|
|
44
|
+
ownerAnswers = false;
|
|
45
|
+
}
|
|
46
|
+
// Another node's catalog is not this one's: its destination validates against its own.
|
|
47
|
+
if (!local) return { ok: true, harness, model, source: 'unverified', note: 'The destination node validates the model before launch.' };
|
|
48
|
+
listed ??= catalog().harnessModels || {};
|
|
49
|
+
const models = listed[harness];
|
|
50
|
+
if (Array.isArray(models) && models.length) {
|
|
51
|
+
const key = normalizeModelName(model);
|
|
52
|
+
if (models.some(row => row.id === model || normalizeModelName(row.id) === key)) return { ok: true, harness, model, source: 'catalog' };
|
|
53
|
+
return { ok: false, harness, model, source: 'catalog', reason: `${harness} does not list ${model}. Listed: ${models.slice(0, 12).map(row => row.id).join(', ')}` };
|
|
54
|
+
}
|
|
55
|
+
return { ok: true, harness, model, source: 'unverified', note: `No model list for ${harness}; only a completed run proves ${model} works there.` };
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Split a pool by whether each harness can run the model. */
|
|
60
|
+
export function filterPoolByModel(pool, model, validate) {
|
|
61
|
+
const checks = pool.ready.map(harness => validate(harness.id, model));
|
|
62
|
+
return {
|
|
63
|
+
pool: { ...pool, ready: pool.ready.filter((_, index) => checks[index].ok),
|
|
64
|
+
excluded: [...pool.excluded, ...checks.filter(check => !check.ok).map(check => ({ harness: check.harness, reason: check.reason, failureKind: 'model' }))] },
|
|
65
|
+
selection: { model, compatible: checks.filter(check => check.ok).map(check => check.harness), checks },
|
|
66
|
+
};
|
|
67
|
+
}
|
package/src/paths.mjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Every persistent path resolves here, at call time, so an isolated environment reaches no live store. */
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export function brainDir(env = process.env) {
|
|
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;
|
|
12
|
+
}
|
|
13
|
+
export const configDir = (env = process.env) => path.join(brainDir(env), 'config', 'meta-harness');
|
|
14
|
+
export const derivedDir = (env = process.env) => path.join(brainDir(env), 'memory-derived', 'meta-harness');
|
|
15
|
+
export const threadsFile = (env = process.env) => path.join(brainDir(env), 'config', 'meta-harness-threads.json');
|
|
16
|
+
export const receiptsFile = (env = process.env) => path.join(configDir(env), 'runs.jsonl');
|
|
17
|
+
|
|
18
|
+
const managedCodexHomeName = 'metaharness-jobs';
|
|
19
|
+
export function codexHomes(codexHome, home = os.homedir(), cwd = process.cwd()) {
|
|
20
|
+
const selected = path.resolve(cwd, codexHome || path.join(home, '.codex'));
|
|
21
|
+
const interactive = path.basename(selected) === managedCodexHomeName ? path.dirname(selected) : selected;
|
|
22
|
+
return { interactive, managed: path.join(interactive, managedCodexHomeName) };
|
|
23
|
+
}
|
package/src/pool.mjs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** The harnesses that can actually take work right now, and why the others cannot. */
|
|
2
|
+
import { ADAPTER_CATALOG } from '../capability/index.mjs';
|
|
3
|
+
import { inspectAgents, getActiveAdapters } from './worker.mjs';
|
|
4
|
+
import { readReceipts, activeQuotaWalls, activeCredentialBlocks, includedBillingReceipts } from './learner.mjs';
|
|
5
|
+
import { measuredWalls } from './telemetry.mjs';
|
|
6
|
+
import { claudeProofCurrent, claudeTokenCurrent, INCLUDED_AGENTS, readIncludedPolicy } from './included-usage.mjs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { codexModelRefusal } from './codex-models.mjs';
|
|
9
|
+
|
|
10
|
+
const describe = (id, extra = {}) => {
|
|
11
|
+
const cap = ADAPTER_CATALOG[id] || {};
|
|
12
|
+
const spec = getActiveAdapters().find(a => a.id === id) || {};
|
|
13
|
+
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 };
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function exclusionReason(agent, wall, credentialBlock, { allowUnknownAuth = false } = {}) {
|
|
17
|
+
if (!agent.installed) return 'not installed';
|
|
18
|
+
if (!agent.versionVerified) return 'did not report a version';
|
|
19
|
+
if (agent.authenticated === false) return 'not signed in';
|
|
20
|
+
if (agent.authenticated !== true && !allowUnknownAuth) return 'authentication is unverified; explicit --allow-unknown-auth is required';
|
|
21
|
+
if (agent.blockedBy === 'no-chat-model') return 'no chat model installed';
|
|
22
|
+
if (wall) return `out of quota until ${wall.until}`;
|
|
23
|
+
if (credentialBlock) return `missing credential: ${String(credentialBlock.message || '').slice(0, 160)}`;
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** An explicit list is the caller's decision and is not filtered. */
|
|
28
|
+
export async function resolvePool({ availableHarnesses, inspect = inspectAgents, receipts = readReceipts, allowUnknownAuth = false, policy, model, codexRefusal = codexModelRefusal } = {}) {
|
|
29
|
+
policy ??= await readIncludedPolicy();
|
|
30
|
+
if (!policy.enabled && Array.isArray(availableHarnesses) && availableHarnesses.length) return { ready: availableHarnesses.map(id => describe(id)), excluded: [], walls: {} };
|
|
31
|
+
// A token bound from Total Recall Auth stands in for any per-machine login, so no native login is probed.
|
|
32
|
+
const claudeToken = policy.enabled && claudeTokenCurrent(policy);
|
|
33
|
+
const claudePlan = policy.enabled && !claudeToken ? policy.claudePlan?.organization : undefined;
|
|
34
|
+
const [{ agents = [] }, entries] = await Promise.all([inspect({ env: process.env, claudePlan }), receipts()]);
|
|
35
|
+
const billingEntries = policy.enabled ? includedBillingReceipts(entries) : entries;
|
|
36
|
+
const walls = { ...activeQuotaWalls(billingEntries), ...(!policy.enabled ? measuredWalls() : {}) };
|
|
37
|
+
const blocks = activeCredentialBlocks(billingEntries);
|
|
38
|
+
const ready = [], excluded = [];
|
|
39
|
+
for (const installed of agents) {
|
|
40
|
+
// Antigravity has no sign-in probe: the operator's plan binding is its evidence, and a signed-out CLI fails the run.
|
|
41
|
+
const agent = policy.enabled && installed.id === 'claude' && !claudePlan ? { ...installed, authenticated: claudeToken || claudeProofCurrent(policy) }
|
|
42
|
+
: policy.enabled && installed.id === 'agy' && policy.agy ? { ...installed, authenticated: true } : installed;
|
|
43
|
+
const unbound = policy.enabled && agent.id === 'agy' && !policy.agy;
|
|
44
|
+
const policyBlocked = policy.enabled && (unbound || !INCLUDED_AGENTS.includes(agent.id) || (Array.isArray(availableHarnesses) && !availableHarnesses.includes(agent.id)));
|
|
45
|
+
const reason = unbound ? 'not bound to a Google plan; the operator runs: total-recall meta-harness included-bind-agy'
|
|
46
|
+
: policyBlocked ? 'outside the included usage route' : exclusionReason(agent, walls[agent.id], blocks[agent.id], { allowUnknownAuth: !policy.enabled && allowUnknownAuth })
|
|
47
|
+
// Without a requested model Codex runs its configured default, which the account may not have.
|
|
48
|
+
|| (agent.id === 'codex' && model === undefined ? codexRefusal() : null);
|
|
49
|
+
if (!reason) ready.push(describe(agent.id, { authVerified: agent.authenticated === true }));
|
|
50
|
+
else if (agent.installed) excluded.push({ harness: agent.id, reason,
|
|
51
|
+
...(policy.enabled && !policyBlocked && agent.authenticated === true && agent.versionVerified && !agent.blockedBy && walls[agent.id]
|
|
52
|
+
? { failureKind: 'quota', resetsAt: walls[agent.id].resetReported ? walls[agent.id].until : null } : {}) });
|
|
53
|
+
}
|
|
54
|
+
return { ready, excluded, walls };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function isLocalExecutionNode(node = 'local') {
|
|
58
|
+
const hostname = os.hostname();
|
|
59
|
+
return ['local', hostname, hostname.split('.')[0]].includes(node);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Automatic placement needs a workspace mapping before it can become a remote job. */
|
|
63
|
+
export function localExecutionNode(options = {}, placement) {
|
|
64
|
+
const node = options.node || placement?.node || 'local';
|
|
65
|
+
if (!isLocalExecutionNode(node)) {
|
|
66
|
+
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.`);
|
|
67
|
+
}
|
|
68
|
+
return 'local';
|
|
69
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
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), TR_META_HARNESS_RUN: '1' };
|
|
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, 'Metaharness 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
|
+
const record = updateAgentRecord(job.id, { status: result.ok ? 'completed' : 'failed', exitCode: result.exitCode ?? (result.ok ? 0 : 1), error: result.ok ? null : result.error,
|
|
173
|
+
...(result.queueId ? { queueId: result.queueId } : {}),
|
|
174
|
+
result: result.response || null, branch, commit, worktreePath: worktree, endedAt: new Date().toISOString() });
|
|
175
|
+
return {
|
|
176
|
+
...record,
|
|
177
|
+
...(Array.isArray(result.toolResults) ? {
|
|
178
|
+
toolResults: result.toolResults,
|
|
179
|
+
toolExecutionVerified: result.toolExecutionVerified,
|
|
180
|
+
commandExecutionVerified: result.commandExecutionVerified,
|
|
181
|
+
} : {}),
|
|
182
|
+
...(result.toolEvidenceError ? { toolEvidenceError: result.toolEvidenceError } : {}),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function killAgent(idOrPid, dependencies = {}) {
|
|
187
|
+
const record = findAgent(idOrPid);
|
|
188
|
+
if (record.remote) {
|
|
189
|
+
const result = await remoteCall(record.node, record.cwd, ['kill', record.id], dependencies);
|
|
190
|
+
if (result.success !== true) throw new Error(result.error || 'Remote owner did not confirm termination');
|
|
191
|
+
updateAgentRecord(record.id, { status: 'killed', endedAt: new Date().toISOString() });
|
|
192
|
+
return result;
|
|
193
|
+
}
|
|
194
|
+
if (!isProcessRunning(record.pid)) return { success: true, message: `Agent ${record.id} is already stopped` };
|
|
195
|
+
if (!ownsProcess(record)) throw new Error('Refusing to kill a process whose managed identity cannot be verified');
|
|
196
|
+
const tree = spawnSync('ps', ['-axo', 'pid=,ppid='], { encoding: 'utf8', timeout: 3000 });
|
|
197
|
+
if (tree.status !== 0) throw new Error('Cannot inspect managed process descendants');
|
|
198
|
+
const relations = tree.stdout.trim().split('\n').map(line => line.trim().split(/\s+/).map(Number));
|
|
199
|
+
const targets = [record.pid];
|
|
200
|
+
for (let i = 0; i < targets.length; i++) for (const [pid, parent] of relations) if (parent === targets[i] && !targets.includes(pid)) targets.push(pid);
|
|
201
|
+
const identities = targets.reverse().map(pid => ({ pid, identity: processIdentity(pid)?.hash })).filter(item => item.identity);
|
|
202
|
+
const stillOwned = item => processIdentity(item.pid)?.hash === item.identity;
|
|
203
|
+
for (const item of identities) if (stillOwned(item)) { try { process.kill(item.pid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; } }
|
|
204
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
205
|
+
for (const item of identities) if (stillOwned(item)) { try { process.kill(item.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; } }
|
|
206
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
207
|
+
if (identities.some(stillOwned)) throw new Error('Managed processes did not stop; isolation was retained');
|
|
208
|
+
const stopped = findAgent(record.id);
|
|
209
|
+
if (stopped.worktreePath) removeWorktree(stopped.cwd, stopped.worktreePath);
|
|
210
|
+
if (stopped.branch && !stopped.commit) deleteBranch(stopped.cwd, stopped.branch);
|
|
211
|
+
const { recordRunReceipt } = await import('./learner.mjs');
|
|
212
|
+
await recordRunReceipt({ harness: record.harness, role: 'Process', node: 'local', task: record.task, success: false, failureKind: 'cancelled', finishedReason: 'cancelled' });
|
|
213
|
+
updateAgentRecord(record.id, { status: 'killed', branch: stopped.commit ? stopped.branch : null, worktreePath: null, endedAt: new Date().toISOString() });
|
|
214
|
+
return { success: true, message: `Terminated managed agent ${record.id}` };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export async function getAgentLogs(idOrPid, tailLines = 50, dependencies = {}) {
|
|
218
|
+
const record = findAgent(idOrPid);
|
|
219
|
+
if (!Number.isInteger(tailLines) || tailLines < 1 || tailLines > 10000) throw new Error('Log tail must be between 1 and 10000 lines');
|
|
220
|
+
if (record.remote) {
|
|
221
|
+
const result = await remoteCall(record.node, record.cwd, ['logs', record.id, '--tail', String(tailLines)], dependencies);
|
|
222
|
+
if (typeof result.logs !== 'string') throw new Error('Remote owner returned no logs');
|
|
223
|
+
if (['starting', 'running'].includes(record.status)) {
|
|
224
|
+
for (const line of result.logs.trimEnd().split('\n').reverse()) {
|
|
225
|
+
let terminal;
|
|
226
|
+
try { terminal = JSON.parse(line); } catch { continue; }
|
|
227
|
+
if (terminal?.id !== record.id || !['completed', 'failed', 'killed'].includes(terminal.status) ||
|
|
228
|
+
typeof terminal.endedAt !== 'string' || !Number.isFinite(Date.parse(terminal.endedAt))) continue;
|
|
229
|
+
updateAgentRecord(record.id, {
|
|
230
|
+
status: terminal.status,
|
|
231
|
+
exitCode: Number.isInteger(terminal.exitCode) ? terminal.exitCode : null,
|
|
232
|
+
endedAt: terminal.endedAt,
|
|
233
|
+
});
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return result.logs;
|
|
238
|
+
}
|
|
239
|
+
if (path.dirname(record.logFile || '') !== logDirectory()) throw new Error('Invalid managed log path');
|
|
240
|
+
const stat = fs.lstatSync(record.logFile, { throwIfNoEntry: false });
|
|
241
|
+
if (!stat) return '';
|
|
242
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Unsafe managed log file');
|
|
243
|
+
const size = Math.min(stat.size, 4 * 1024 * 1024), buffer = Buffer.alloc(size), fd = fs.openSync(record.logFile, 'r');
|
|
244
|
+
try { fs.readSync(fd, buffer, 0, size, stat.size - size); } finally { fs.closeSync(fd); }
|
|
245
|
+
return buffer.toString('utf8').split('\n').slice(-tailLines).join('\n');
|
|
246
|
+
}
|
|
@@ -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
|
+
}
|