tr-plugin-meta-harness 0.3.0 → 0.5.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/DESIGN.md +86 -0
  2. package/README.md +257 -11
  3. package/capability/BRICK.md +1 -1
  4. package/capability/index.mjs +154 -13
  5. package/cli.mjs +426 -41
  6. package/package.json +15 -3
  7. package/plugin.json +1457 -119
  8. package/skills/meta-harness/SKILL.md +63 -25
  9. package/src/adoption.mjs +102 -0
  10. package/src/agent-user.mjs +194 -0
  11. package/src/alerts.mjs +220 -14
  12. package/src/cascade.mjs +185 -0
  13. package/src/chat.mjs +80 -0
  14. package/src/codex-models.mjs +54 -0
  15. package/src/compat-harness.mjs +114 -0
  16. package/src/control.mjs +145 -0
  17. package/src/coordinator.mjs +267 -358
  18. package/src/dispatch-request.mjs +76 -0
  19. package/src/dispatch.mjs +119 -0
  20. package/src/documentation-authority.mjs +57 -0
  21. package/src/documentation.mjs +120 -32
  22. package/src/executor.mjs +101 -22
  23. package/src/gate-adapters/agy.mjs +155 -0
  24. package/src/gate-adapters/claude.mjs +303 -0
  25. package/src/gate-adapters/cline.mjs +111 -0
  26. package/src/gate-adapters/codex.mjs +164 -0
  27. package/src/gate-adapters/cursor.mjs +164 -0
  28. package/src/gate-adapters/devin.mjs +116 -0
  29. package/src/gate-adapters/dsh.mjs +284 -0
  30. package/src/gate-adapters/grok.mjs +112 -0
  31. package/src/gate-adapters/hermes.mjs +217 -0
  32. package/src/gate-adapters/hook-files.mjs +156 -0
  33. package/src/gate-adapters/index.mjs +131 -0
  34. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  35. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  36. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  37. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  38. package/src/gate-adapters/openclaw.mjs +288 -0
  39. package/src/gate-adapters/pi.mjs +146 -0
  40. package/src/gate.mjs +18 -0
  41. package/src/harness-updates.mjs +170 -0
  42. package/src/included-usage.mjs +344 -0
  43. package/src/jobs.mjs +135 -0
  44. package/src/json-reply.mjs +22 -0
  45. package/src/learner.mjs +97 -67
  46. package/src/maintenance.mjs +18 -0
  47. package/src/mcp-server.mjs +228 -0
  48. package/src/model-catalog.mjs +195 -0
  49. package/src/model-selection.mjs +67 -0
  50. package/src/paths.mjs +23 -0
  51. package/src/pool.mjs +69 -0
  52. package/src/process-manager.mjs +246 -0
  53. package/src/process-worker.mjs +18 -0
  54. package/src/reasoning.mjs +231 -0
  55. package/src/remote-operation.mjs +76 -0
  56. package/src/review.mjs +241 -0
  57. package/src/reviews.mjs +25 -0
  58. package/src/router-benchmark-corpus.mjs +16 -0
  59. package/src/router-benchmark.mjs +208 -0
  60. package/src/router.mjs +265 -346
  61. package/src/runtime.mjs +30 -8
  62. package/src/session/claude.mjs +358 -0
  63. package/src/session/codex.mjs +501 -0
  64. package/src/session/result.mjs +90 -0
  65. package/src/session/resume.mjs +393 -0
  66. package/src/session/run.mjs +258 -0
  67. package/src/session-jobs.mjs +77 -0
  68. package/src/setup.mjs +6 -3
  69. package/src/ssss-store.mjs +20 -0
  70. package/src/telemetry.mjs +267 -0
  71. package/src/termination.mjs +28 -0
  72. package/src/threads.mjs +150 -0
  73. package/src/usage-queue.mjs +137 -0
  74. package/src/verify-ssss.mjs +102 -0
  75. package/src/worker.mjs +955 -84
  76. package/src/worktree.mjs +244 -0
  77. package/ui/chunks/adapter-docs-freshness.md +16 -0
  78. package/ui/chunks/chat-handoff.md +26 -0
  79. package/ui/chunks/fleet-maintenance.md +21 -0
  80. package/ui/chunks/harness-inventory.md +21 -0
  81. package/ui/chunks/included-access.md +18 -0
  82. package/ui/chunks/included-usage-verification.md +15 -0
  83. package/ui/chunks/independent-review.md +17 -0
  84. package/ui/chunks/managed-execution.md +20 -0
  85. package/ui/chunks/official-documentation.md +18 -0
  86. package/ui/chunks/quota-recovery.md +21 -0
  87. package/ui/chunks/review-routing-decision.md +16 -0
  88. package/ui/chunks/route-work.md +18 -0
  89. package/ui/chunks/routing-evidence.md +18 -0
  90. package/ui/chunks/run-ledger.md +18 -0
  91. package/ui/chunks/session-controls.md +16 -0
  92. package/ui/home.js +198 -0
  93. package/ui/DESIGN.md +0 -32
  94. package/ui/card.js +0 -845
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Hook files for harnesses that read Claude Code's shape: an event maps to groups, and each
3
+ * group holds a matcher and a `hooks` array. An entry with `command` directly on the group is
4
+ * skipped by these harnesses, so earlier installs that wrote that form never fired.
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ export const gateCommand = (harness) => `total-recall preflight gate --harness ${harness}`;
10
+
11
+ /**
12
+ * The gate command with the binary's full path, for a harness that may run outside this
13
+ * shell's PATH (a background gateway) and fails closed when it cannot find the command.
14
+ */
15
+ export function gateCommandWithPath(harness, env = process.env) {
16
+ for (const dir of String(env.PATH || '').split(path.delimiter)) {
17
+ const candidate = path.join(dir || '.', 'total-recall');
18
+ try {
19
+ fs.accessSync(candidate, fs.constants.X_OK);
20
+ return `${candidate} preflight gate --harness ${harness}`;
21
+ } catch { /* keep looking */ }
22
+ }
23
+ return gateCommand(harness);
24
+ }
25
+
26
+ /**
27
+ * Seconds a launcher waits for a command an update is replacing: the one measured outage ran
28
+ * past 13 seconds. The hook timeout covers the wait and the gate's own run.
29
+ */
30
+ export const LAUNCHER_WAIT_SECONDS = 15;
31
+ export const LAUNCHER_HOOK_TIMEOUT_SECONDS = 30;
32
+
33
+ /** The binary a gate command runs, with its full path when it is on PATH. */
34
+ export const gateBinary = (harness, env = process.env) => gateCommandWithPath(harness, env).slice(0, -` preflight gate --harness ${harness}`.length);
35
+
36
+ /**
37
+ * A launcher for a harness that blocks every call when its hook command is missing.
38
+ *
39
+ * Such a harness tells the agent only that the command was not found. An update replaces the
40
+ * Total Recall command, so on every release it is absent for some seconds, and then present but
41
+ * unfinished for a few more. The launcher lives outside that package, so it is always there: it
42
+ * keeps the payload, waits for the command, passes a real decision through untouched, and when
43
+ * the gate still gives none it answers in the harness's own shape with what happened and what to
44
+ * do. `denial` builds that answer from a message placeholder.
45
+ * @param {string} cli
46
+ * @param {(message: string) => object} denial
47
+ */
48
+ export function gateLauncherScript(cli, denial) {
49
+ const quoted = `'${String(cli).replace(/'/g, `'\\''`)}'`;
50
+ const template = JSON.stringify(denial('%s')).replace(/'/g, `'\\''`);
51
+ const slots = template.split('%s').length - 1;
52
+ return `#!/bin/sh
53
+ # Total Recall gate launcher. Written by Total Recall when it installs its gate; edits are
54
+ # overwritten. It is not the Total Recall command: it runs the one named in CLI below.
55
+ #
56
+ # This harness blocks every tool call when a hook command is missing and says only that it was
57
+ # not found. An update replaces the Total Recall command, so it is briefly missing on every
58
+ # release. This file is outside that package: it waits for the command, and says what to do when
59
+ # the gate cannot run.
60
+ CLI=${quoted}
61
+ payload=$(cat)
62
+ wait=\${TR_GATE_WAIT_SECONDS:-${LAUNCHER_WAIT_SECONDS}}
63
+ tries=0
64
+ why='is missing'
65
+ while [ "$tries" -le "$wait" ]; do
66
+ if command -v "$CLI" >/dev/null 2>&1; then
67
+ out=$(printf '%s' "$payload" | "$CLI" "$@")
68
+ code=$?
69
+ if [ "$code" -eq 0 ] || [ "$code" -eq 2 ]; then
70
+ [ -n "$out" ] && printf '%s\\n' "$out"
71
+ exit "$code"
72
+ fi
73
+ why="exited with status $code and gave no decision"
74
+ fi
75
+ tries=$((tries + 1))
76
+ [ "$tries" -le "$wait" ] && sleep 1
77
+ done
78
+ msg="The Total Recall gate could not run: the total-recall command $why. An update replacing it is the usual cause, and this is not about your preflight. Wait 30 seconds and repeat the same call. If it still fails after two minutes, stop and tell the operator that total-recall needs repair on this machine."
79
+ printf '${template}\\n' ${Array(slots).fill('"$msg"').join(' ')}
80
+ exit 2
81
+ `;
82
+ }
83
+
84
+ /** Write a launcher when it is missing or differs. Returns what was done, or null. */
85
+ export function writeGateLauncher(file, script, { dryRun = false } = {}) {
86
+ const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
87
+ if (current === script) return null;
88
+ if (!dryRun) {
89
+ fs.mkdirSync(path.dirname(file), { recursive: true });
90
+ const pending = `${file}.${process.pid}.tmp`;
91
+ fs.writeFileSync(pending, script, { mode: 0o755 });
92
+ fs.renameSync(pending, file);
93
+ }
94
+ return current === null ? 'gate launcher' : 'gate launcher (updated)';
95
+ }
96
+
97
+ const isGate = (command, harness) => String(command || '').includes(`preflight gate --harness ${harness}`);
98
+ const nested = (group, harness) => Array.isArray(group?.hooks) && group.hooks.some((hook) => isGate(hook?.command, harness));
99
+ const flat = (group, harness) => isGate(group?.command, harness);
100
+
101
+ /** True when the gate is in the form the harness runs. */
102
+ export function hasGate(groups, harness) {
103
+ return Array.isArray(groups) && groups.some((group) => nested(group, harness));
104
+ }
105
+
106
+ /**
107
+ * The groups for one event with the gate present, or absent when `remove` is set. Other
108
+ * hooks are left alone. An entry in the form the harness skips is replaced.
109
+ */
110
+ export function mergeGate(groups, harness, { remove = false, matcher = '*', timeout = 10, command = gateCommand(harness) } = {}) {
111
+ const existing = Array.isArray(groups) ? groups : [];
112
+ const added = [];
113
+ const removed = [];
114
+ const kept = existing.filter((group) => {
115
+ if (flat(group, harness)) { removed.push('gate entry in a form the harness skips'); return false; }
116
+ if (remove && nested(group, harness)) { removed.push('managed gate'); return false; }
117
+ return true;
118
+ });
119
+ if (!remove && !hasGate(kept, harness)) {
120
+ kept.push({ ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command, timeout }] });
121
+ added.push('managed PreToolUse gate');
122
+ }
123
+ return { groups: kept, added, removed };
124
+ }
125
+
126
+ export function readJsonFile(file, fallback = {}) {
127
+ if (!fs.existsSync(file)) return fallback;
128
+ try {
129
+ return JSON.parse(fs.readFileSync(file, 'utf8') || '{}');
130
+ } catch (err) {
131
+ throw new Error(`${file} is not valid JSON; fix it before installing hooks: ${err.message}`);
132
+ }
133
+ }
134
+
135
+ export function readJsonQuietly(file) {
136
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return {}; }
137
+ }
138
+
139
+ export function writeJsonFile(file, value) {
140
+ fs.mkdirSync(path.dirname(file), { recursive: true });
141
+ if (fs.existsSync(file)) fs.copyFileSync(file, `${file}.bak-total-recall`);
142
+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
143
+ }
144
+
145
+ /**
146
+ * Delete a file an earlier install wrote where the harness never looks. Only a file whose
147
+ * sole content is this gate goes; anything else in it means someone else is using it.
148
+ */
149
+ export function removeDeadGateFile(file, harness, { dryRun = false } = {}) {
150
+ if (!fs.existsSync(file)) return [];
151
+ const text = fs.readFileSync(file, 'utf8');
152
+ const commands = [...text.matchAll(/"command"\s*:\s*"([^"]*)"/g)].map((match) => match[1]);
153
+ if (!commands.length || !commands.every((command) => isGate(command, harness))) return [];
154
+ if (!dryRun) fs.rmSync(file);
155
+ return [`${path.basename(file)}, which the harness does not read`];
156
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Gate Adapters registry for Metaharness (tr-plugin-cli-agents).
3
+ * Provides harness-specific parsing, emission, installation and verification.
4
+ */
5
+ import { claudeAdapter } from './claude.mjs';
6
+ import { agyAdapter } from './agy.mjs';
7
+ import { codexAdapter } from './codex.mjs';
8
+ import { dshAdapter } from './dsh.mjs';
9
+ import { hermesAdapter } from './hermes.mjs';
10
+ import { openclawAdapter } from './openclaw.mjs';
11
+ import { cursorAdapter } from './cursor.mjs';
12
+ import { devinAdapter } from './devin.mjs';
13
+ import { grokAdapter } from './grok.mjs';
14
+ import { clineAdapter } from './cline.mjs';
15
+ import { piAdapter } from './pi.mjs';
16
+
17
+ const ADAPTERS = new Map([
18
+ ['claude', claudeAdapter],
19
+ ['claude-code', claudeAdapter],
20
+ ['agy', agyAdapter],
21
+ ['antigravity', agyAdapter],
22
+ ['codex', codexAdapter],
23
+ ['dsh', dshAdapter],
24
+ ['hermes', hermesAdapter],
25
+ ['openclaw', openclawAdapter],
26
+ ['cursor', cursorAdapter],
27
+ ['devin', devinAdapter],
28
+ ['windsurf', devinAdapter],
29
+ ['grok', grokAdapter],
30
+ ['cline', clineAdapter],
31
+ ['pi', piAdapter]
32
+ ]);
33
+
34
+ export function get(harnessId) {
35
+ if (!harnessId) return null;
36
+ return ADAPTERS.get(String(harnessId).toLowerCase()) || null;
37
+ }
38
+
39
+ export function list() {
40
+ const seen = new Set();
41
+ const result = [];
42
+ for (const adapter of ADAPTERS.values()) {
43
+ if (!seen.has(adapter.id)) {
44
+ seen.add(adapter.id);
45
+ result.push(adapter);
46
+ }
47
+ }
48
+ return result;
49
+ }
50
+
51
+ export function install(harnessId, opts = {}) {
52
+ const adapter = get(harnessId);
53
+ if (!adapter) throw new Error(`Unknown harness adapter: ${harnessId}`);
54
+ if (typeof adapter.install !== 'function') {
55
+ throw new Error(`Harness adapter ${harnessId} does not support installation`);
56
+ }
57
+ return adapter.install(opts);
58
+ }
59
+
60
+ const BINARIES = { claude: 'claude', agy: 'agy', codex: 'codex', dsh: 'dsh', hermes: 'hermes', openclaw: 'openclaw', cursor: 'cursor-agent', devin: 'devin', grok: 'grok', cline: 'cline', pi: 'pi' };
61
+
62
+ /**
63
+ * Install the gate for every harness present on this machine. Safe to run repeatedly.
64
+ * A harness that fails is reported, never skipped silently. The worker is imported here
65
+ * because the preflight gate loads this module on every tool call.
66
+ */
67
+ export async function installAll({ home, env = process.env, dryRun = false } = {}) {
68
+ const { findBinary } = await import('../worker.mjs');
69
+ const rows = [];
70
+ for (const adapter of list()) {
71
+ const binary = BINARIES[adapter.id] || adapter.id;
72
+ if (!findBinary(binary, env)) { rows.push({ harness: adapter.id, status: 'not-present' }); continue; }
73
+ try {
74
+ const result = adapter.install({ ...(home ? { home } : {}), dryRun });
75
+ if (result.unsupported) rows.push({ harness: adapter.id, status: 'unsupported', reason: result.unsupported });
76
+ else rows.push({ harness: adapter.id, status: dryRun ? 'would-install' : 'installed', settings: result.settings, ...(result.note ? { note: result.note } : {}) });
77
+ } catch (err) {
78
+ rows.push({ harness: adapter.id, status: 'failed', error: err.message });
79
+ }
80
+ }
81
+ return { ok: rows.every((row) => row.status !== 'failed'), rows };
82
+ }
83
+
84
+ /**
85
+ * Take the gate out of every harness, for `total-recall uninstall` only. A fail-closed hook that
86
+ * outlives Total Recall would deny every call in that harness. A harness that fails is reported.
87
+ */
88
+ export function removeAll({ home, env, dryRun = false } = {}) {
89
+ const rows = [];
90
+ for (const adapter of list()) {
91
+ try {
92
+ const result = adapter.install({ ...(home ? { home } : {}), ...(env ? { env } : {}), dryRun, remove: true });
93
+ const removed = result.removed || [];
94
+ rows.push({ harness: adapter.id, status: removed.length ? 'removed' : 'absent', removed, ...(result.note ? { note: result.note } : {}) });
95
+ } catch (err) {
96
+ rows.push({ harness: adapter.id, status: 'failed', error: err.message });
97
+ }
98
+ }
99
+ return { ok: rows.every((row) => row.status !== 'failed'), rows };
100
+ }
101
+
102
+ export function verify(harnessId, opts = {}) {
103
+ const adapter = get(harnessId);
104
+ if (!adapter) throw new Error(`Unknown harness adapter: ${harnessId}`);
105
+ if (typeof adapter.verify !== 'function') {
106
+ throw new Error(`Harness adapter ${harnessId} does not support verification`);
107
+ }
108
+ return adapter.verify(opts);
109
+ }
110
+
111
+ export default {
112
+ get,
113
+ list,
114
+ install,
115
+ installAll,
116
+ removeAll,
117
+ verify,
118
+ adapters: {
119
+ claude: claudeAdapter,
120
+ agy: agyAdapter,
121
+ codex: codexAdapter,
122
+ dsh: dshAdapter,
123
+ hermes: hermesAdapter,
124
+ openclaw: openclawAdapter,
125
+ cursor: cursorAdapter,
126
+ devin: devinAdapter,
127
+ grok: grokAdapter,
128
+ cline: clineAdapter,
129
+ pi: piAdapter
130
+ }
131
+ };
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The OpenClaw side of the Total Recall gate. It decides nothing: it asks
3
+ * `total-recall preflight gate --harness openclaw` about each tool call and carries the answer.
4
+ */
5
+ import { spawn } from 'node:child_process';
6
+ import path from 'node:path';
7
+
8
+ const GATE_ARGS = ['preflight', 'gate', '--harness', 'openclaw'];
9
+ /** OpenClaw blocks a call whose hook runs out of time, so the gate's limit sits inside the hook's. */
10
+ export const GATE_TIMEOUT_MS = 8000;
11
+ export const HOOK_TIMEOUT_MS = 10000;
12
+ /** A block ends the call, so the gate runs before any other plugin's hook. */
13
+ const HOOK_PRIORITY = 1000;
14
+ const MAX_HELD_NOTES = 200;
15
+
16
+ /** The gate reads these. A tool's other params, such as file contents, stay out of its process. */
17
+ const PARAMS_THE_GATE_READS = ['command', 'workdir', 'path', 'file_path', 'filePath'];
18
+ const KEPT_ENV = ['HOME', 'USER', 'LOGNAME', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'AGENT_DIR'];
19
+ const KEPT_ENV_PREFIXES = ['TR_', 'TOTAL_RECALL_'];
20
+ const NEVER_KEPT_ENV = new Set(['TR_SECRETS_PASSWORD']);
21
+
22
+ const PLAIN_TR = /^(cd\s+\S+\s*&&\s*)?(npx\s+)?total-recall\s/;
23
+
24
+ /** One Total Recall command with nothing chained after it. Mirrors core's isPlainTotalRecall. */
25
+ function isPlainTotalRecall(command) {
26
+ const text = String(command || '').trim();
27
+ if (!PLAIN_TR.test(text)) return false;
28
+ const runnable = text.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "''").replace(PLAIN_TR, '');
29
+ return !/[;&|`\n<>]|\$\(/.test(runnable);
30
+ }
31
+
32
+ /** The gateway holds model and channel keys, and the gate needs none of them. */
33
+ export function gateEnv(settings = {}, env = process.env) {
34
+ const kept = {};
35
+ for (const key of KEPT_ENV) if (env[key]) kept[key] = env[key];
36
+ for (const [key, value] of Object.entries(env)) {
37
+ if (KEPT_ENV_PREFIXES.some((prefix) => key.startsWith(prefix)) && !NEVER_KEPT_ENV.has(key)) kept[key] = value;
38
+ }
39
+ kept.PATH = [...(settings.path || []), env.PATH].filter(Boolean).join(path.delimiter);
40
+ return kept;
41
+ }
42
+
43
+ /** A subagent's session key, as OpenClaw writes it: agent:<id>:subagent:<uuid>. */
44
+ export function isSubagentSession(sessionKey) {
45
+ return typeof sessionKey === 'string' && /(^|:)subagent:/.test(sessionKey);
46
+ }
47
+
48
+ /**
49
+ * The call as the gate reads it. `ctx.agentId` names the configured agent, such as `main`, on every
50
+ * call, so it must never reach the gate as `agent_id`, which would mark every call a subagent's.
51
+ */
52
+ export function payloadFor(event = {}, ctx = {}, cwd) {
53
+ const params = {};
54
+ for (const key of PARAMS_THE_GATE_READS) {
55
+ if (event.params?.[key] !== undefined) params[key] = event.params[key];
56
+ }
57
+ const payload = { event: 'before_tool_call', toolName: event.toolName, params, cwd };
58
+ const toolKind = event.toolKind || ctx.toolKind;
59
+ if (toolKind) payload.toolKind = toolKind;
60
+ if (event.derivedPaths?.length) payload.derivedPaths = [...event.derivedPaths];
61
+ const session = ctx.sessionId || ctx.sessionKey;
62
+ if (session) payload.session_id = session;
63
+ if (isSubagentSession(ctx.sessionKey)) payload.agent_id = ctx.sessionKey;
64
+ return payload;
65
+ }
66
+
67
+ function reasonFrom(stderr) {
68
+ const lines = String(stderr || '').split('\n').map((line) => line.trim()).filter(Boolean);
69
+ return (lines.find((line) => /error/i.test(line)) || lines.at(-1) || '').slice(0, 300);
70
+ }
71
+
72
+ /** What one run of the gate said, or `failed` when it reached no decision. */
73
+ export function readAnswer(code, stdout, stderr) {
74
+ let answer = null;
75
+ try { answer = JSON.parse(stdout); } catch { /* no decision on stdout */ }
76
+ if (answer?.block === true || answer?.decision === 'deny') {
77
+ return { block: true, reason: answer.blockReason || answer.reason || reasonFrom(stderr) || 'The Total Recall gate denied this call.' };
78
+ }
79
+ if (code === 0) return { block: false, warning: typeof answer?.warning === 'string' ? answer.warning : null };
80
+ if (code === 2) return { block: true, reason: reasonFrom(stderr) || 'The Total Recall gate denied this call.' };
81
+ return { failed: reasonFrom(stderr) || `it exited with ${code ?? 'a signal'} and gave no decision` };
82
+ }
83
+
84
+ /** Never rejects. A real process, so a call never waits on the gateway's event loop. */
85
+ export function askGate(command, payload, { env, signal, timeoutMs = GATE_TIMEOUT_MS } = {}) {
86
+ return new Promise((resolve) => {
87
+ let stdout = '';
88
+ let stderr = '';
89
+ let settled = false;
90
+ let timer = null;
91
+ const finish = (answer) => {
92
+ if (settled) return;
93
+ settled = true;
94
+ clearTimeout(timer);
95
+ resolve(answer);
96
+ };
97
+ let child;
98
+ try {
99
+ child = spawn(command, GATE_ARGS, { env, signal, stdio: ['pipe', 'pipe', 'pipe'] });
100
+ } catch (err) {
101
+ finish({ failed: err.message });
102
+ return;
103
+ }
104
+ timer = setTimeout(() => {
105
+ child.kill('SIGKILL');
106
+ finish({ failed: `no answer within ${timeoutMs} ms` });
107
+ }, timeoutMs);
108
+ child.on('error', (err) => finish({ failed: err.message }));
109
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
110
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
111
+ child.stdin.on('error', () => { /* it exited first, and `close` reports that */ });
112
+ child.on('close', (code) => finish(readAnswer(code, stdout, stderr)));
113
+ child.stdin.end(JSON.stringify(payload));
114
+ });
115
+ }
116
+
117
+ function inside(target, from, folder) {
118
+ if (!folder || typeof target !== 'string' || !target) return false;
119
+ const full = path.resolve(from, target);
120
+ return full === folder || full.startsWith(`${folder}${path.sep}`);
121
+ }
122
+
123
+ /**
124
+ * The gate could not run, so core's `whenGateFails` never ran either, and OpenClaw blocks a hook
125
+ * that throws. The same rule lives here: work stays denied, and what can repair the gate stays open.
126
+ */
127
+ export function whenGateCannotRun(event = {}, cwd, why, settings = {}) {
128
+ const { open = [], shell = [], write = [] } = settings.tools || {};
129
+ const name = event.toolName;
130
+ const params = event.params || {};
131
+ const from = typeof params.workdir === 'string' && params.workdir.trim() ? path.resolve(cwd, params.workdir) : cwd;
132
+ const repairs = open.includes(name)
133
+ || (shell.includes(name) && (isPlainTotalRecall(params.command) || inside(from, cwd, settings.package)))
134
+ || (write.includes(name) && [params.path, params.file_path, params.filePath, ...(event.derivedPaths || [])].some((target) => inside(target, cwd, settings.package)));
135
+ if (repairs) return undefined;
136
+ const scope = settings.package ? `, plain Total Recall commands and changes inside ${settings.package}` : ' and plain Total Recall commands';
137
+ return {
138
+ block: true,
139
+ blockReason: `TR-PREFLIGHT gate could not run: ${why}. The gate fails closed. Reading${scope} stay open so it can be repaired. An operator on this machine can also run: openclaw plugins disable total-recall-gate`,
140
+ };
141
+ }
142
+
143
+ /** The agent's real workspace. The hook context has no working folder, and the gateway's own is not it. */
144
+ function workspaceOf(api, ctx) {
145
+ const agentId = ctx?.agentId || /^agent:([^:]+):/.exec(ctx?.sessionKey || '')?.[1] || 'main';
146
+ try {
147
+ return api.runtime.agent.resolveAgentWorkspaceDir(api.config, agentId) || process.cwd();
148
+ } catch {
149
+ return process.cwd();
150
+ }
151
+ }
152
+
153
+ export function registerGate(api, settings = {}) {
154
+ const command = settings.command || 'total-recall';
155
+ const env = gateEnv(settings);
156
+ const held = new Map();
157
+
158
+ const hold = (key, note) => {
159
+ if (!key) return;
160
+ if (held.size >= MAX_HELD_NOTES && !held.has(key)) held.delete(held.keys().next().value);
161
+ held.set(key, held.has(key) ? `${held.get(key)} ${note}` : note);
162
+ };
163
+ const take = (...keys) => {
164
+ for (const key of keys) {
165
+ if (key && held.has(key)) {
166
+ const note = held.get(key);
167
+ held.delete(key);
168
+ return note;
169
+ }
170
+ }
171
+ return null;
172
+ };
173
+
174
+ api.on('before_tool_call', async (event, ctx) => {
175
+ let cwd = process.cwd();
176
+ try {
177
+ cwd = workspaceOf(api, ctx);
178
+ const answer = await askGate(command, payloadFor(event, ctx, cwd), { env, signal: ctx?.abortSignal });
179
+ if (answer.failed) {
180
+ api.logger?.warn?.(`Total Recall gate could not run: ${answer.failed}`);
181
+ return whenGateCannotRun(event, cwd, answer.failed, settings);
182
+ }
183
+ if (answer.block) return { block: true, blockReason: answer.reason };
184
+ if (answer.warning) hold(event.toolCallId || ctx?.toolCallId || ctx?.sessionKey || ctx?.sessionId, answer.warning);
185
+ return undefined;
186
+ } catch (err) {
187
+ api.logger?.warn?.(`Total Recall gate could not run: ${err.message}`);
188
+ return whenGateCannotRun(event, cwd, err.message, settings);
189
+ }
190
+ }, { priority: HOOK_PRIORITY, timeoutMs: HOOK_TIMEOUT_MS });
191
+
192
+ // The hook has no text field that lets a tool run, so a warning travels with the tool's result.
193
+ try {
194
+ api.registerAgentToolResultMiddleware((event, ctx) => {
195
+ const note = take(event.toolCallId, ctx?.sessionKey, ctx?.sessionId);
196
+ if (!note) return undefined;
197
+ const content = Array.isArray(event.result?.content) ? event.result.content : [];
198
+ return { result: { ...event.result, content: [...content, { type: 'text', text: note }] } };
199
+ });
200
+ } catch (err) {
201
+ api.logger?.warn?.(`Total Recall gate cannot deliver warnings: ${err.message}`);
202
+ }
203
+
204
+ api.logger?.info?.(`Total Recall gate asks ${command}`);
205
+ }
@@ -0,0 +1,25 @@
1
+ // Total Recall preflight gate for OpenClaw. Installed by `total-recall preflight install`.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { definePluginEntry } from 'openclaw/plugin-sdk/plugin-entry';
6
+ import { registerGate } from './gate-client.js';
7
+
8
+ /** This machine's paths, written beside the plugin at install. The gate still runs without them. */
9
+ function readSettings(rootDir) {
10
+ const folder = rootDir || path.dirname(fileURLToPath(import.meta.url));
11
+ try {
12
+ return JSON.parse(fs.readFileSync(path.join(folder, 'gate.json'), 'utf8'));
13
+ } catch {
14
+ return {};
15
+ }
16
+ }
17
+
18
+ export default definePluginEntry({
19
+ id: 'total-recall-gate',
20
+ name: 'Total Recall Gate',
21
+ description: 'Asks Total Recall whether each tool call may run.',
22
+ register(api) {
23
+ registerGate(api, readSettings(api.rootDir));
24
+ },
25
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "id": "total-recall-gate",
3
+ "name": "Total Recall Gate",
4
+ "description": "Asks Total Recall whether each tool call may run.",
5
+ "categories": ["other"],
6
+ "activation": { "onStartup": true },
7
+ "contracts": { "agentToolResultMiddleware": ["openclaw", "codex", "agentsapi"] },
8
+ "configSchema": { "type": "object", "additionalProperties": false }
9
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "total-recall-gate",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "Total Recall preflight gate for OpenClaw.",
7
+ "license": "MIT",
8
+ "openclaw": {
9
+ "extensions": ["./index.js"],
10
+ "compat": {
11
+ "pluginApi": ">=2026.11.1",
12
+ "minGatewayVersion": "2026.11.1"
13
+ }
14
+ }
15
+ }