tr-plugin-meta-harness 0.0.0-stage → 0.5.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/DESIGN.md +86 -0
  2. package/README.md +310 -2
  3. package/capability/BRICK.md +59 -0
  4. package/capability/index.mjs +675 -0
  5. package/cli.mjs +524 -0
  6. package/package.json +32 -4
  7. package/plugin.json +1714 -0
  8. package/skills/meta-harness/SKILL.md +75 -0
  9. package/src/adapters/dsh.mjs +446 -0
  10. package/src/adoption.mjs +102 -0
  11. package/src/agent-user.mjs +194 -0
  12. package/src/alerts.mjs +229 -0
  13. package/src/cascade.mjs +185 -0
  14. package/src/chat.mjs +80 -0
  15. package/src/codex-models.mjs +54 -0
  16. package/src/compat-harness.mjs +114 -0
  17. package/src/control.mjs +145 -0
  18. package/src/coordinator.mjs +307 -0
  19. package/src/dispatch-request.mjs +76 -0
  20. package/src/dispatch.mjs +119 -0
  21. package/src/documentation-authority.mjs +57 -0
  22. package/src/documentation.mjs +240 -0
  23. package/src/executor.mjs +161 -0
  24. package/src/gate-adapters/agy.mjs +155 -0
  25. package/src/gate-adapters/claude.mjs +303 -0
  26. package/src/gate-adapters/cline.mjs +111 -0
  27. package/src/gate-adapters/codex.mjs +164 -0
  28. package/src/gate-adapters/cursor.mjs +164 -0
  29. package/src/gate-adapters/devin.mjs +116 -0
  30. package/src/gate-adapters/dsh.mjs +284 -0
  31. package/src/gate-adapters/grok.mjs +112 -0
  32. package/src/gate-adapters/hermes.mjs +217 -0
  33. package/src/gate-adapters/hook-files.mjs +156 -0
  34. package/src/gate-adapters/index.mjs +131 -0
  35. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  36. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  37. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  38. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  39. package/src/gate-adapters/openclaw.mjs +288 -0
  40. package/src/gate-adapters/pi.mjs +146 -0
  41. package/src/gate.mjs +18 -0
  42. package/src/harness-updates.mjs +170 -0
  43. package/src/included-usage.mjs +344 -0
  44. package/src/jobs.mjs +135 -0
  45. package/src/json-reply.mjs +22 -0
  46. package/src/learner.mjs +120 -0
  47. package/src/maintenance.mjs +18 -0
  48. package/src/mcp-server.mjs +228 -0
  49. package/src/model-catalog.mjs +195 -0
  50. package/src/model-selection.mjs +67 -0
  51. package/src/paths.mjs +23 -0
  52. package/src/pool.mjs +69 -0
  53. package/src/process-manager.mjs +246 -0
  54. package/src/process-worker.mjs +18 -0
  55. package/src/reasoning.mjs +231 -0
  56. package/src/remote-operation.mjs +76 -0
  57. package/src/review.mjs +241 -0
  58. package/src/reviews.mjs +25 -0
  59. package/src/router-benchmark-corpus.mjs +16 -0
  60. package/src/router-benchmark.mjs +208 -0
  61. package/src/router.mjs +334 -0
  62. package/src/runtime.mjs +58 -0
  63. package/src/session/claude.mjs +358 -0
  64. package/src/session/codex.mjs +501 -0
  65. package/src/session/result.mjs +90 -0
  66. package/src/session/resume.mjs +393 -0
  67. package/src/session/run.mjs +258 -0
  68. package/src/session-jobs.mjs +77 -0
  69. package/src/setup.mjs +38 -0
  70. package/src/ssss-store.mjs +20 -0
  71. package/src/telemetry.mjs +267 -0
  72. package/src/termination.mjs +28 -0
  73. package/src/threads.mjs +150 -0
  74. package/src/tracker.mjs +133 -0
  75. package/src/usage-queue.mjs +137 -0
  76. package/src/verify-ssss.mjs +102 -0
  77. package/src/worker.mjs +1104 -0
  78. package/src/worktree.mjs +244 -0
  79. package/ui/chunks/adapter-docs-freshness.md +16 -0
  80. package/ui/chunks/chat-handoff.md +26 -0
  81. package/ui/chunks/fleet-maintenance.md +21 -0
  82. package/ui/chunks/harness-inventory.md +21 -0
  83. package/ui/chunks/included-access.md +18 -0
  84. package/ui/chunks/included-usage-verification.md +15 -0
  85. package/ui/chunks/independent-review.md +17 -0
  86. package/ui/chunks/managed-execution.md +20 -0
  87. package/ui/chunks/official-documentation.md +18 -0
  88. package/ui/chunks/quota-recovery.md +21 -0
  89. package/ui/chunks/review-routing-decision.md +16 -0
  90. package/ui/chunks/route-work.md +18 -0
  91. package/ui/chunks/routing-evidence.md +18 -0
  92. package/ui/chunks/run-ledger.md +18 -0
  93. package/ui/chunks/session-controls.md +16 -0
  94. package/ui/home.js +198 -0
@@ -0,0 +1,75 @@
1
+ ---
2
+ name: meta-harness
3
+ description: Discover, route, coordinate, review and run coding agent harnesses through Total Recall across mesh nodes.
4
+ version: 0.5.25
5
+ repo_scoped: false
6
+ ---
7
+
8
+ # Metaharness
9
+
10
+ Coordinates coding agent harnesses across mesh nodes. `cli-agents` is an alias of `meta-harness`. Run `total-recall meta-harness --help` for flags.
11
+
12
+ ## Rules
13
+ 1. **Believe the status words.** `ready` was proved by a login probe. `unverified` has no probe, so only a completed run proves it. `needs_auth`, `blocked` and `exhausted` cannot take work; the reason is in `quotaNote` and in `excluded`.
14
+ 2. **No figure without a source.** `benchmarks` shows only fetched figures with their source and time. A dash means nobody measured it. Adapter quality and cost scores are configured priors, not measurements.
15
+ 3. **Code is written through `route --execute`, `coordinate --execute` or race**, each on its own `meta-harness/...` branch. Nothing merges into your branch; review it and merge it yourself. `dispatch` keeps edits only with `permissions: {"read": true, "write": true}`; without it the agent works in a disposable checkout and its edits are discarded. The first line dispatch prints to stderr says which (`edits`).
16
+ 4. **Use the calling harness's native background function.** Give it `total-recall meta-harness orchestrate "<task>" --execute --json` as one command. The command returns the final result and exit status to that background task. Executed `route` and `coordinate`, and `dispatch`, `fork` and `resume`, also return terminal results by default. `--background` (or `--background true`) explicitly detaches for callers that need only a job ID; `--background false` stays attached. `dispatch --stdin` reads JSON `{agent, cwd, prompt, timeoutMs?}`. An attached or remote dispatch runs 5 minutes and a local detached one 60 minutes unless `timeoutMs` changes it; the limits are 90 minutes for a detached or terminal/background-task call (the host passes its timer as TR_PLUGIN_TIMEOUT_MS) and 9 minutes otherwise. Pipeline implementer stages run up to 60 minutes and other stages 15. `resume` and `fork` keep the saved job's deadline, and `--timeout-ms` overrides it within the same limits. Use `cancel <job>` to stop a job and preserve changed work on its branch.
17
+ 5. **Check the outcome, not the status word.** `running` says the process is alive. A job whose process is gone reads `failed` with `failureKind: lost`. Work is done when the result is `ok`, the branch holds the commit and the gate passed.
18
+ 6. **Cost and circuit breakers.** dsh, hermes and other metered harnesses bill per token, and `route` warns when it picks one. Before every `dispatch` and `reasoning` run, and in `alerts check` (every 5 minutes), the breakers stop background work above 15 internal agent launches in 15 minutes, 40 background agent launches in 15 minutes (a job's own record and a run that never launched an agent do not count), or 15M new background tokens in 1 hour (cache reads are not counted, because they re-read context already paid for). The operator's own sessions never trip them.
19
+ 7. **Billing is a policy, never a fallback.** With included usage required, automatic routing uses only subscription harnesses and never moves to paid use. To run a metered harness on purpose, name it: `route "<task>" --execute --agent dsh`. It runs alone, does not escalate to another harness, and still passes every admission check.
20
+
21
+ ## Commands
22
+ - `router-benchmark [--k 20] [--repeats 3] [--catalog-samples 24] [--corpus file.json] [--min-recall 0.8] [--min-mrr 0.5] [--max-p95-ms 1000] [--baseline report.json] [--max-recall-drop 0] [--save] --json`: measure actual host capability retrieval separately from owner harness readiness scenarios. No provider or plugin tasks run. Explicit save creates an owner SSSS report/event, separate from execution receipts. API/MCP/router cases and capability refusals are unsupported until the production router supports them.
23
+ - `status`, `inspect --node <id>`, `upstream`, `changelog <agent>`, `catalog`, `nodes`: what is installed, signed in and current.
24
+ - `quota [--node <id>]`: readiness, measured usage and walls, OpenRouter balance, and memory across the fleet.
25
+ - `benchmarks`: pricing, Artificial Analysis indices, SWE-bench Pro, and pass rates from this machine's receipts. Refresh with `maintenance --models`.
26
+ - `maintenance --harnesses [--agent <id>] [--dry-run]`: update each installed harness with its own update command (claude, codex, agy, grok, cursor, hermes, pi, cline, openclaw; dsh through npm, forward only), daily on the maintenance node. Hermes is asked first with `hermes update --check`, because its update restarts the gateway. pi, cline, openclaw and dsh wait while a copy is running (`busy`), and a pinned runtime is left to its installer (`managed`).
27
+ - `route "<task>" [--jev] [--model <id>] [--agent <id>] [--prefer-local|--prefer-frontier] [--allow-unknown-auth] [--execute [--gate] [--tier fast|full|remote] [--wait]]`: pick a harness; with `--execute`, run it on its branch and escalate on failure. `--agent` runs that harness only. A Codex model must be on the signed-in account's own list; when Codex's configured default is not, Codex is excluded with the reason until the default changes or `--model` names a listed one.
28
+ - `coordinate "<task>" --mode pipeline|council|race [--execute] [--gate] [--auto-review] [--allow-same-family] [--background]`: without `--execute` it only reports the plan and its blockers.
29
+ - `decompose "<task>"`: the stages and which ready harness takes each.
30
+ - `review [<git-range>] [--staged] [--author <id>] [--reviewer <id>] [--thread <id>]`: review by another model family. `NO_DIFF` means there was nothing to review.
31
+ - `dispatch --stdin [--background]` with JSON `{agent, cwd, prompt, permissions, timeoutMs, model, node, allowUnknownAuth}`; any other field is refused: one bootstrapped run with a receipt.
32
+ - `cancel <job>`: stop a running local job by ID prefix or log path. Wait up to 60 seconds for its cancelled result. Finished and unknown jobs return an error. Use `watch <job>` to read progress.
33
+ - `reply <job> "<text>"`: steer the running turn or answer its oldest question. `approve <job> <request> allow|deny` answers an approval. Native requests and MCP requests use the same approval policy.
34
+ - `watch <job> [--node <owner>] --json`: query the active attempt or terminal failure locally or across the mesh. Use this for an explicit status request. Native background tasks deliver completion to their originating session.
35
+ - `interrupt <job>`: stop the current turn and keep its session for `resume`. `goal <job> "<text>"` replaces the running job's goal.
36
+ - `fork <job> [--at <turn>] [--background]`: start a new job from the session history on a new branch. Selected turns require native support. `resume <job> "<text>" [--background]` continues a finished session on its saved branch. Both commands keep the parent's history.
37
+ - `route`, `coordinate` and `dispatch` accept `--goal`, `--max-turns`, `--max-budget-usd`, `--max-tokens`, `--result-schema <file>`, `--approvals auto|operator|rules` and `--question-timeout-ms`. Dispatch accepts the same fields in camelCase in its stdin JSON (`approvalPolicy` selects approvals). The default goal is the task. Completion requires a separate goal check with concrete evidence. File changes alone do not prove completion. A limit fails the job without escalation. Structured results get one correction turn if validation fails, and the goal check gets the same single correction turn before the job fails. A result or goal reply may be bare JSON or exactly one fenced JSON block, with or without prose around it; no JSON or more than one block is invalid. The goal check carries optional `notes` for unfinished work outside this goal (Codex receives a strict copy of every output schema, with all properties required); notes never fail a job, while a non-empty `remaining` still does.
38
+ - `mcp [--approvals auto|operator|rules] [--question-timeout-ms <ms>]`: serve the job's `ask` and `approve` tools over stdio. Metaharness configures this server for Claude and Codex. `watch <job>` includes capabilities, usage, plans, diffs, hooks, model reroutes and waiting requests.
39
+ - A routed change gets a review from another model family after its gate and before its push. A blocking finding or an unreadable review stops the push. The job result contains the review.
40
+ - A token or USD cap requires measured usage. A harness that cannot report the required usage fails with `failureKind: limit`. A zero USD cap starts no agent turn. Goal checks and JSON corrections count toward job limits. JSON Schema assertions outside the portable validator's supported set fail validation. For DSH only, each `status`/`step_end` frame carries that step's own usage, which is summed across the run (cached input is reported separately and not counted) and checked after every step; `turn_end` counts one turn and `tool_call` starts a step named by its tool, while `tool_result` still ends it. Other harnesses are unchanged.
41
+ - `reasoning-config [--agent <id>] [--model <model>] [--max-usage-percent <1-100>] [--enable <id>] [--disable <id>]`: the harness and model for background reasoning such as lesson reviews. With nothing configured, background reasoning is refused; it never falls back to adapter order. Codex reasoning is held, with no model call, while Codex usage is at or above the threshold, and callers retry after 30 minutes. A harness with an operator OpenRouter binding (`openrouter-bind`) may be listed and is billed through it. No flags shows the saved file and the effective order.
42
+ - `threads list|show|create|close|delete`, `learn`, `alerts check|test [--dry-run]`, `adapter list|add|remove`.
43
+ - `reviews`: read the durable review ledger, including selected diff, commit, reviewer, verdict and disposition. Thread deletion does not remove reviews.
44
+ - `threads cleanup-fixtures [--dry-run]`: one-time cleanup of exact test fixture titles. The atomic SSSS record lists removed and retained IDs. Real end-to-end job threads stay in place.
45
+ - `adoption [--node <id> | --all]`: inspect native gate activity and real managed run receipts separately from installation and login.
46
+ - `docs-status`, `docs-refresh`, `docs-search --query <q>`, `docs-read`, `maintenance`, `setup`, `runtime <agent> <maintenance-command>`. Use dispatch for agent tasks and the service owner for gateway changes.
47
+
48
+ `setup --node <recorded-node>` places documentation maintenance, model maintenance
49
+ and quota alerts through the existing daemon. The `maintenance` placement owns
50
+ official documentation. Peers use `docs-status`, `docs-read`, and `docs-search` to
51
+ query that source through the mesh. Maintenance reports setup, gate, and documentation failures separately.
52
+ It also removes job records whose files are all older than 30 days, except jobs
53
+ whose process is still alive, so `watch`, `cancel` and `continue` cover the last 30 days.
54
+
55
+ Managed Codex jobs save resumable history in the `metaharness-jobs` directory under
56
+ the native Codex home, outside the interactive chat list. Use Metaharness `watch`,
57
+ `resume` and `fork` for those jobs. Internal reasoning sessions remain ephemeral.
58
+
59
+ - `orchestrate "<task>" [--orchestrator <id>] [--execute] [--auto-review] [--gate] [--allow-same-family] [--wait|--background]`: the default for project work. It fans out subagents and returns their verified result to the caller.
60
+ - `process <action> [target] [task] [--node] [--cwd] [--name] [--tools] [--setting-sources] [--model] [--tail] [--read-only] [--no-detach] [--allow-unknown-auth]`: manage owned agent processes with SSSS lifecycle records.
61
+ - `run-command` (JSON on stdin): run an explicit plugin command through the selected agent and node.
62
+ - `chat-target --brains <list>`, `chat-default <adapter> [--url <url>]`: the default Chat harness for the selected brains.
63
+ - `priority-cache [--add <checkout>|--remove <checkout>]`: operator only; show or change prioritized checkouts.
64
+ - `included-status [--probe codex]`, `included-enforce`, `included-bind-claude`, `included-bind-claude-plan`, `included-bind-claude-token --key <name>`, `included-bind-agy`, `openrouter-bind <agent> <key> --model <id>`: the billing policy and its evidence. Operator only. `included-bind-agy` lets Antigravity run on the signed-in personal Google plan (Free, Pro or Ultra); a bound run is launched with the plan forced and with no Google API key or Cloud project in its environment, and it is refused while Antigravity's saved settings select an API key, paid AI credits or a Cloud project.
65
+ - `usage-queue`, `usage-retry <job>`, `usage-cancel <job>`: jobs waiting for included usage.
66
+ - `usage-reconcile [--apply]`: preview or archive expired internal reasoning records that have no replay request. Their originating workflows own future retries.
67
+ - `agent-user [<name>|--clear]`: the non-root user Claude runs as when Metaharness runs as root on Linux.
68
+ - `docs-ensure [--agent <id>]`, `docs-sources`, `docs-read --agent <id> --url <url>`: refresh missing documentation, list approved sources, read cached pages.
69
+
70
+ Other options: `watch --tail <n>`; `reply|approve|interrupt|goal --local-delivery` (set by remote delivery, not by hand); `learn --void <id> --reason <text>`; `alerts check --threshold <percent>`; `threads --title --summary --status --platform --branch`; `review --allow-unknown-auth`; `coordinate --allow-unknown-auth`; `router-benchmark --core-root <path> --allow-catalog-change`.
71
+
72
+ Use `--timeout-ms` on route, coordinate, orchestrate or review to bound a remote operation. The calling harness also needs a background-task deadline long enough for the command.
73
+
74
+ ## When something fails
75
+ Read `failureKind` on the result. `lost`: the process died without a result; read its branch and events, then run it again. `circuit-breaker`: a breaker stopped it; the message names the limit. `model`: the harness cannot run that model. `limit`: a cap was reached, or the harness cannot report the usage the cap needs (DSH reports no USD). `quota` carries `resetsAt`, and routing avoids that harness until then. `auth` and `not-ready` mean the operator must sign in or install something. These do not count against a harness's pass rate; `agent` and `gate` failures do.
@@ -0,0 +1,446 @@
1
+ /**
2
+ * DSH CLI — query DeepSeek Harness state from Total Recall.
3
+ * Ran as `total-recall cli-agents runtime dsh <subcommand>`
4
+ * @module @total-recall/plugin-dsh
5
+ */
6
+
7
+ import { spawnSync } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+
12
+ // The DSH Web/desktop GUI binds an EPHEMERAL port chosen at launch (observed
13
+ // 49661 -> 49703 -> 52406 within one session), so no fixed port list can ever
14
+ // be correct. Earlier revisions hardcoded [53626, 54866, 54055] and therefore
15
+ // reported "DeepSeek Harness is not running" against a live GUI.
16
+ //
17
+ // Discover by PROCESS IDENTITY instead: find the DSH process, then read the
18
+ // port it is actually listening on. The debugger port (9229/9230) is excluded.
19
+ const DSH_RUNTIME = process.env.DSH_RUNTIME || defaultRuntime();
20
+ const DEBUG_PORTS = new Set([9229, 9230]);
21
+ /** Process-name fragments that identify a DSH surface. */
22
+ const DSH_PROCESS_HINTS = ['Harness Dev.app', 'dsh-desktop', '@deepseek-ai/dsh'];
23
+
24
+ /** Locate the DSH checkout when DSH_RUNTIME is unset. */
25
+ function defaultRuntime() {
26
+ const candidates = [
27
+ process.env.DSH_CHECKOUT,
28
+ path.join(os.homedir(), 'github', 'deepseek-harness'),
29
+ path.join(os.homedir(), 'deepseek-harness')
30
+ ].filter(Boolean);
31
+ for (const dir of candidates) {
32
+ if (fs.existsSync(path.join(dir, 'packages'))) return dir;
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ /** PIDs whose command line looks like a DSH surface. */
38
+ function dshPids() {
39
+ const res = spawnSync('ps', ['-Ao', 'pid=,command='], { timeout: 4000, encoding: 'utf8' });
40
+ if (res.status !== 0 || !res.stdout) return [];
41
+ const pids = [];
42
+ for (const line of res.stdout.split('\n')) {
43
+ const trimmed = line.trim();
44
+ if (!trimmed) continue;
45
+ const match = /^(\d+)\s+(.*)$/.exec(trimmed);
46
+ if (!match) continue;
47
+ const [, pid, command] = match;
48
+ // Skip the CLI itself and any grep-like helper.
49
+ if (command.includes('tr-plugin-dsh') || command.includes('lsof') || command.includes('ps -Ao')) continue;
50
+ if (DSH_PROCESS_HINTS.some((hint) => command.includes(hint))) pids.push(Number(pid));
51
+ }
52
+ return pids;
53
+ }
54
+
55
+ /** Listening ports held by the given PIDs, debugger ports excluded. */
56
+ function listenPorts(pids) {
57
+ const ports = [];
58
+ for (const pid of pids) {
59
+ const res = spawnSync('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-a', '-p', String(pid)],
60
+ { timeout: 4000, encoding: 'utf8' });
61
+ if (res.status !== 0 || !res.stdout) continue;
62
+ for (const line of res.stdout.split('\n').slice(1)) {
63
+ // lsof columns end with `TCP host:port (LISTEN)`; match the address form
64
+ // directly rather than assuming the port is the last field, which yields
65
+ // the literal '(LISTEN)'.
66
+ const match = /TCP\s+\S*:(\d+)\s+\(LISTEN\)/.exec(line);
67
+ if (!match) continue;
68
+ const port = Number(match[1]);
69
+ if (port && !DEBUG_PORTS.has(port) && !ports.includes(port)) ports.push(port);
70
+ }
71
+ }
72
+ return ports;
73
+ }
74
+
75
+ /**
76
+ * Is this port the DSH Web/desktop GUI?
77
+ *
78
+ * The GUI is not always open: it answers with an authentication notice
79
+ * ("dsh web authentication required; reopen the URL printed by dsh web") rather
80
+ * than the boot payload, so probing for `__DSH_BOOT__` alone would reject the
81
+ * real GUI and fall through to the Electron devtools port.
82
+ */
83
+ function servesDsh(port) {
84
+ if (fetchBootInfo(port) !== null) return true;
85
+ const res = spawnSync('curl', ['-s', '-m', '4', `http://127.0.0.1:${port}/`],
86
+ { timeout: 5000, encoding: 'utf8' });
87
+ return res.status === 0 && typeof res.stdout === 'string' && res.stdout.includes('dsh web');
88
+ }
89
+
90
+ function findDsh() {
91
+ const pids = dshPids();
92
+ if (pids.length === 0) return null;
93
+
94
+ // Prefer a PID whose port actually serves the DSH boot payload; fall back to
95
+ // the first PID that merely holds a listening socket.
96
+ let fallback = null;
97
+ for (const pid of pids) {
98
+ for (const port of listenPorts([pid])) {
99
+ const entry = () => {
100
+ const cmd = spawnSync('ps', ['-p', String(pid), '-o', 'comm='], { timeout: 2000, encoding: 'utf8' });
101
+ const startTime = spawnSync('ps', ['-p', String(pid), '-o', 'lstart='], { timeout: 2000, encoding: 'utf8' });
102
+ return {
103
+ pid,
104
+ port,
105
+ name: (cmd.stdout || '').toString().trim(),
106
+ started: (startTime.stdout || '').toString().trim()
107
+ };
108
+ };
109
+ if (servesDsh(port)) return entry();
110
+ fallback ??= entry();
111
+ }
112
+ }
113
+ return fallback;
114
+ }
115
+
116
+ // --- Model configuration -----------------------------------------------------
117
+ //
118
+ // The configured default model lives in each profile's cordis.patch.yml under
119
+ // `- id: agent-default-model`. DSH keeps profiles in more than one home: the
120
+ // shared ~/.dsh and the desktop app's isolated build home. Reading only one is
121
+ // how a stale default (V3) stayed invisible in the others.
122
+
123
+ const DEFAULT_MODEL_PREF = path.join(os.homedir(), '.dsh', 'default-model.txt');
124
+
125
+ /** Every DSH home that holds profiles, in precedence order. */
126
+ function profileHomes() {
127
+ const homes = [path.join(os.homedir(), '.dsh')];
128
+ if (DSH_RUNTIME) {
129
+ homes.push(path.join(DSH_RUNTIME, 'apps', 'desktop', '.desktop-build', 'development', 'home'));
130
+ }
131
+ return homes;
132
+ }
133
+
134
+ /** Read the default model + provider from one profile patch. */
135
+ function readProfileDefault(patchFile) {
136
+ try {
137
+ const text = fs.readFileSync(patchFile, 'utf8');
138
+ const block = text.split('- id: agent-default-model')[1];
139
+ if (!block) return null;
140
+ const model = /^\s+model:\s*(\S+)/m.exec(block);
141
+ const provider = /^\s+provider:\s*(\S+)/m.exec(block);
142
+ if (!model) return null;
143
+ return { model: model[1], provider: provider ? provider[1] : 'unknown' };
144
+ } catch { return null; }
145
+ }
146
+
147
+ /** Every profile's configured default across all homes. */
148
+ function allProfileDefaults() {
149
+ const found = [];
150
+ for (const home of profileHomes()) {
151
+ const dir = path.join(home, 'profiles');
152
+ if (!fs.existsSync(dir)) continue;
153
+ for (const name of fs.readdirSync(dir)) {
154
+ const patch = path.join(dir, name, 'cordis.patch.yml');
155
+ if (!fs.existsSync(patch)) continue;
156
+ const def = readProfileDefault(patch);
157
+ if (def) found.push({ home: home.replace(os.homedir(), '~'), profile: name, ...def });
158
+ }
159
+ }
160
+ return found;
161
+ }
162
+
163
+ /** Catalogue cached by the model refresh script, when present. */
164
+ function cachedCatalogue() {
165
+ const file = path.join(os.homedir(), '.dsh', 'openrouter-models.json');
166
+ try {
167
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
168
+ const list = Array.isArray(parsed) ? parsed : parsed.data;
169
+ return Array.isArray(list) ? list : [];
170
+ } catch { return []; }
171
+ }
172
+
173
+ /** Provider packages compiled into the DSH tree. */
174
+ function providerPackages() {
175
+ const providers = [];
176
+ if (!DSH_RUNTIME) return providers;
177
+ const providerDir = path.join(DSH_RUNTIME, 'node_modules', '@deepseek-ai');
178
+ if (!fs.existsSync(providerDir)) return providers;
179
+ for (const pkg of fs.readdirSync(providerDir)) {
180
+ if (!(pkg.includes('llm') || pkg.includes('model') || pkg.includes('provider'))) continue;
181
+ const pkgPath = path.join(providerDir, pkg, 'package.json');
182
+ if (!fs.existsSync(pkgPath)) continue;
183
+ try {
184
+ const meta = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
185
+ providers.push({ name: meta.name, version: meta.version, desc: (meta.description || '').slice(0, 80) });
186
+ } catch { /* unreadable package */ }
187
+ }
188
+ return providers;
189
+ }
190
+
191
+ function calcUptime(started) {
192
+ if (!started) return 'unknown';
193
+ const start = new Date(started);
194
+ const now = new Date();
195
+ const diff = (now - start) / 1000;
196
+ const days = Math.floor(diff / 86400);
197
+ const hours = Math.floor((diff % 86400) / 3600);
198
+ const mins = Math.floor((diff % 3600) / 60);
199
+ const parts = [];
200
+ if (days > 0) parts.push(`${days}d`);
201
+ if (hours > 0) parts.push(`${hours}h`);
202
+ parts.push(`${mins}m`);
203
+ return parts.join(' ');
204
+ }
205
+
206
+ function fetchBootInfo(port) {
207
+ try {
208
+ const res = spawnSync('curl', ['-s', `http://127.0.0.1:${port}/`], { timeout: 5000, encoding: 'utf8' });
209
+ if (res.status !== 0) return null;
210
+ const html = res.stdout;
211
+ // Extract __DSH_BOOT__ JSON
212
+ const idx = html.indexOf('__DSH_BOOT__');
213
+ if (idx === -1) return null;
214
+ const brace = html.indexOf('{', idx);
215
+ let depth = 0, end = brace;
216
+ for (let i = brace; i < html.length; i++) {
217
+ if (html[i] === '{') depth++;
218
+ else if (html[i] === '}') depth--;
219
+ if (depth === 0) { end = i + 1; break; }
220
+ }
221
+ const boot = JSON.parse(html.slice(brace, end));
222
+ return boot;
223
+ } catch { return null; }
224
+ }
225
+
226
+ export async function run(argv) {
227
+ const subcommand = argv.includes('--help') || argv.includes('-h') ? 'help' : argv[3] || 'help';
228
+
229
+ const dsh = findDsh();
230
+ // `model`/`models` read profile files on disk, so they work without a running
231
+ // DSH; every other subcommand needs the live process.
232
+ const FILE_ONLY = new Set(['model', 'models']);
233
+ if (!dsh && subcommand !== 'help' && !FILE_ONLY.has(subcommand)) {
234
+ console.error(' DeepSeek Harness is not running.');
235
+ process.exitCode = 1;
236
+ return;
237
+ }
238
+
239
+ const bootInfo = dsh ? fetchBootInfo(dsh.port) : null;
240
+
241
+ switch (subcommand) {
242
+
243
+ case 'status': {
244
+ const mem = spawnSync('ps', ['-p', String(dsh.pid), '-o', 'rss='], { timeout: 2000 });
245
+ const rss = parseInt(mem.stdout.toString().trim()) || 0;
246
+ const uptime = calcUptime(dsh.started);
247
+
248
+ console.log(`\n DeepSeek Harness — Runtime\n`);
249
+ console.log(` PID: ${dsh.pid}`);
250
+ console.log(` Memory: ${(rss / 1024).toFixed(1)} MB`);
251
+ console.log(` Port: ${dsh.port}`);
252
+ console.log(` Process: ${dsh.name}`);
253
+ console.log(` Uptime: ${uptime}`);
254
+ console.log(` Revision: ${bootInfo?.rev || 'unknown'}`);
255
+ console.log(` Plugins: ${bootInfo?.entries?.length || 'unknown'} client plugins loaded`);
256
+ console.log(` Web GUI: ${process.env.DSH_WEB_URL || 'http://127.0.0.1:' + dsh.port}\n`);
257
+ return { data: { pid: dsh.pid, port: dsh.port, memory: (rss / 1024).toFixed(1), uptime, revision: bootInfo?.rev } };
258
+ }
259
+
260
+ case 'sessions': {
261
+ // DSH sessions are Cordis-managed. Report what we can observe externally
262
+ const elapsed = calcUptime(dsh.started);
263
+ const pluginCount = bootInfo?.entries?.length || 0;
264
+
265
+ console.log(`\n DeepSeek Harness — Sessions\n`);
266
+ console.log(` Status: Running since ${dsh.started} (${elapsed})`);
267
+ console.log(` Web GUI: ${process.env.DSH_WEB_URL || 'http://127.0.0.1:' + dsh.port}`);
268
+ console.log(` API Port: ${dsh.port}`);
269
+ console.log(` Revision: ${bootInfo?.rev || 'unknown'}`);
270
+ console.log(` Plugins: ${pluginCount} active`);
271
+ console.log(`\n Open the Web GUI to view and manage active sessions.`);
272
+ console.log(` Session state, conversation logs, and tool usage are`);
273
+ console.log(` available through the browser interface.\n`);
274
+ return { data: { status: 'running', port: dsh.port, uptime: elapsed, plugins: pluginCount, revision: bootInfo?.rev } };
275
+ }
276
+
277
+ case 'models': {
278
+ const providers = providerPackages();
279
+ const defaults = allProfileDefaults();
280
+ const catalogue = cachedCatalogue();
281
+
282
+ console.log(`\n DeepSeek Harness — Models\n`);
283
+
284
+ console.log(` Configured default model (per profile):\n`);
285
+ if (defaults.length === 0) {
286
+ console.log(` (no profile declares agent-default-model)\n`);
287
+ } else {
288
+ for (const d of defaults) {
289
+ console.log(` ${d.home}/${d.profile}`);
290
+ console.log(` model: ${d.model}`);
291
+ console.log(` provider: ${d.provider}`);
292
+ }
293
+ const distinct = [...new Set(defaults.map((d) => d.model))];
294
+ if (distinct.length > 1) {
295
+ console.log(`\n WARNING profiles disagree: ${distinct.join(', ')}`);
296
+ console.log(` A refresh that hardcodes a model id will revert these.`);
297
+ }
298
+ console.log();
299
+ }
300
+
301
+ let pref = '';
302
+ try { pref = fs.readFileSync(DEFAULT_MODEL_PREF, 'utf8').trim(); } catch { /* unset */ }
303
+ console.log(` Persisted preference: ${pref || '(unset)'}`);
304
+ console.log(` ${DEFAULT_MODEL_PREF}`);
305
+ console.log(` The model refresh keeps this model instead of a hardcoded id.\n`);
306
+
307
+ console.log(` Catalogue cache: ${catalogue.length} models`);
308
+ console.log(` ~/.dsh/openrouter-models.json\n`);
309
+
310
+ console.log(` Provider packages: ${providers.length}\n`);
311
+ for (const p of providers) {
312
+ console.log(` • ${p.name} v${p.version}`);
313
+ if (p.desc) console.log(` ${p.desc}`);
314
+ }
315
+ console.log(`\n Cache the catalogue for offline reads: total-recall cli-agents runtime dsh model --cache\n`);
316
+ return { data: { defaults, preference: pref || null, catalogueSize: catalogue.length, providers: providers.map((p) => p.name) } };
317
+ }
318
+
319
+ case 'model': {
320
+ // Model caching: read live configuration and (optionally) cache it.
321
+ const defaults = allProfileDefaults();
322
+ const catalogue = cachedCatalogue();
323
+ const asJson = argv.includes('--json');
324
+ const wantCache = argv.includes('--cache');
325
+
326
+ const payload = {
327
+ generatedAt: new Date().toISOString(),
328
+ runtime: DSH_RUNTIME || null,
329
+ preference: (() => {
330
+ try { return fs.readFileSync(DEFAULT_MODEL_PREF, 'utf8').trim(); } catch { return null; }
331
+ })(),
332
+ defaults,
333
+ catalogueSize: catalogue.length
334
+ };
335
+
336
+ if (wantCache) {
337
+ // Cache through SSSS memory so `total-recall recall` can answer model
338
+ // questions offline and on any mesh node.
339
+ const summary = [
340
+ `DSH model configuration cached ${payload.generatedAt}.`,
341
+ payload.preference ? `Persisted preference: ${payload.preference}.` : 'No persisted preference file.',
342
+ ...defaults.map((d) => `${d.home}/${d.profile} -> ${d.model} (${d.provider}).`),
343
+ `OpenRouter catalogue cache holds ${catalogue.length} models.`
344
+ ].join(' ');
345
+ const res = spawnSync('total-recall', [
346
+ 'remember', 'fact', summary,
347
+ '--title', 'DSH model configuration (cached)',
348
+ '--slug', 'dsh-model-configuration-cache',
349
+ '--tags', 'dsh,model,cache,openrouter',
350
+ '--global'
351
+ ], { timeout: 60000, encoding: 'utf8' });
352
+ payload.cached = res.status === 0;
353
+ payload.cacheOutput = (res.stdout || '').trim().split('\n').slice(-1)[0] || '';
354
+ if (res.status !== 0) {
355
+ console.error(` Cache write failed: ${(res.stderr || '').trim().split('\n')[0] || 'unknown error'}`);
356
+ }
357
+ }
358
+
359
+ if (asJson) {
360
+ console.log(JSON.stringify(payload, null, 2));
361
+ return { data: payload };
362
+ }
363
+
364
+ console.log(`\n DeepSeek Harness — Model Cache\n`);
365
+ console.log(` Preference: ${payload.preference || '(unset)'}`);
366
+ console.log(` Profiles: ${defaults.length}`);
367
+ for (const d of defaults) {
368
+ console.log(` • ${d.home}/${d.profile} -> ${d.model}`);
369
+ }
370
+ console.log(` Catalogue: ${catalogue.length} models cached`);
371
+ if (wantCache) {
372
+ console.log(` SSSS cache: ${payload.cached ? 'written' : 'FAILED'}`);
373
+ } else {
374
+ console.log(`\n Write the cache: total-recall cli-agents runtime dsh model --cache`);
375
+ }
376
+ console.log();
377
+ return { data: payload };
378
+ }
379
+
380
+ case 'plugins': {
381
+ const entries = bootInfo?.entries || [];
382
+
383
+ console.log(`\n DeepSeek Harness — Client Plugins\n`);
384
+ console.log(` Total: ${entries.length} plugins loaded\n`);
385
+ for (const e of entries) {
386
+ const deps = e.inject?.length ? ` [deps: ${e.inject.join(', ')}]` : '';
387
+ const imm = e.immediately ? ' [immediate]' : '';
388
+ console.log(` • ${e.id}${imm}${deps}`);
389
+ }
390
+ console.log(`\n Dynamic Cordis Plugins (from current session):`);
391
+ console.log(` Use cordis_inspect_self inside a DSH session to list them.\n`);
392
+ return { data: { pluginCount: entries.length, plugins: entries.map(e => e.id) } };
393
+ }
394
+
395
+ case 'tools': {
396
+ // Parse available plug-in packages for tool-related ones
397
+ const pluginDir = path.join(DSH_RUNTIME, 'node_modules', '@deepseek-ai');
398
+ const tools = [];
399
+ if (fs.existsSync(pluginDir)) {
400
+ for (const pkg of fs.readdirSync(pluginDir)) {
401
+ if (pkg.includes('tool') || pkg.includes('skill') || pkg.includes('command')) {
402
+ const pkgPath = path.join(pluginDir, pkg, 'package.json');
403
+ if (fs.existsSync(pkgPath)) {
404
+ try {
405
+ const meta = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
406
+ tools.push({ name: meta.name, version: meta.version, desc: (meta.description || '').slice(0, 100) });
407
+ } catch {}
408
+ }
409
+ }
410
+ }
411
+ }
412
+
413
+ // Known tool packages specific to DSH
414
+ const knownTools = []; // Only observed packages are reported; no fabricated live tool registry.
415
+
416
+ console.log(`\n DeepSeek Harness — Tool Registry\n`);
417
+ console.log(` Built-in Agent Tools:\n`);
418
+ for (const t of knownTools) {
419
+ console.log(` • ${t.name} — ${t.desc}`);
420
+ }
421
+
422
+ if (tools.length > 0) {
423
+ console.log(`\n Tool-related Packages:\n`);
424
+ for (const t of tools) {
425
+ console.log(` • ${t.name} v${t.version}`);
426
+ if (t.desc) console.log(` ${t.desc}`);
427
+ }
428
+ }
429
+ console.log(`\n To see the complete live tool registry:`);
430
+ console.log(` Use cordis_inspect_list inside a DSH session, or`);
431
+ console.log(` check the Settings → Plugins panel in the Web GUI.\n`);
432
+ return { data: { builtIn: knownTools.map(t => t.name), packages: tools.map(t => t.name) } };
433
+ }
434
+
435
+ default:
436
+ console.log(`\n DeepSeek Harness — Total Recall Plugin\n`);
437
+ console.log('Usage: total-recall cli-agents runtime dsh <subcommand>\n');
438
+ console.log(' dsh status DSH runtime status (PID, port, memory, uptime)');
439
+ console.log(' dsh sessions Session status and Web GUI info');
440
+ console.log(' dsh tools Registered tool inventory');
441
+ console.log(' dsh models Configured default model per profile + providers');
442
+ console.log(' dsh model Model cache (--cache writes an SSSS node, --json)');
443
+ console.log(' dsh plugins Client plugin inventory\n');
444
+ return;
445
+ }
446
+ }
@@ -0,0 +1,102 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import { executeOnNode, listTargets } from './executor.mjs';
4
+ import { readReceipts } from './learner.mjs';
5
+ import { agentEnvironment, findBinary, inspectAgents, runProcess } from './worker.mjs';
6
+
7
+ const { version } = JSON.parse(fs.readFileSync(new URL('../plugin.json', import.meta.url), 'utf8'));
8
+
9
+ async function readPreflight(args) {
10
+ const binary = findBinary('total-recall');
11
+ if (!binary) throw new Error('Total Recall CLI is unavailable');
12
+ const result = await runProcess(binary, ['preflight', ...args, '--json'], {
13
+ cwd: os.homedir(), env: agentEnvironment(), timeoutMs: 25000,
14
+ });
15
+ if (result.reason || result.exitCode !== 0) throw new Error(`Preflight query failed: ${result.reason || `exit ${result.exitCode}`}`);
16
+ return JSON.parse(result.stdout);
17
+ }
18
+
19
+ const describeRun = run => run ? {
20
+ id: run.id, at: run.timestamp, success: run.success === true, exitCode: run.exitCode ?? null,
21
+ failureKind: run.failureKind ?? null,
22
+ ...(run.billingMode ? { billingMode: run.billingMode } : {}),
23
+ ...(run.tools?.length ? { tools: run.tools } : {}),
24
+ } : null;
25
+
26
+ function latestRuns(receipts) {
27
+ const runs = new Map();
28
+ for (const row of receipts) {
29
+ const time = Date.parse(row.timestamp);
30
+ if (row.node !== 'local' || !Number.isFinite(time)) continue;
31
+ const state = runs.get(row.harness) || {};
32
+ if (!state.attempt || time >= Date.parse(state.attempt.timestamp)) state.attempt = row;
33
+ if (row.success === true && row.exitCode === 0 && (!state.completed || time >= Date.parse(state.completed.timestamp))) state.completed = row;
34
+ runs.set(row.harness, state);
35
+ }
36
+ return runs;
37
+ }
38
+
39
+ /** This query never launches an agent or treats a synthetic hook test as live activity. */
40
+ export async function inspectLocalAdoption({ inspect = inspectAgents, receipts = readReceipts, preflight = readPreflight } = {}) {
41
+ const [inventory, history, gates] = await Promise.allSettled([
42
+ inspect(), receipts(), preflight(['report']),
43
+ ]);
44
+ const issues = [];
45
+ const inventoryRows = Array.isArray(inventory.value?.agents) ? inventory.value.agents : null;
46
+ const receiptRows = Array.isArray(history.value) ? history.value : null;
47
+ const adapterRows = Array.isArray(gates.value?.adapters) ? gates.value.adapters : null;
48
+ const decisions = gates.value?.compliance?.byHarness;
49
+ if (!inventoryRows) issues.push('Agent inventory unavailable');
50
+ if (!receiptRows) issues.push('Managed run receipts unavailable');
51
+ if (!adapterRows || !decisions) issues.push('Native preflight evidence unavailable');
52
+ const runs = latestRuns(receiptRows || []);
53
+ const adapters = new Map((adapterRows || []).map(row => [row.id, row.verification]));
54
+ const agents = (inventoryRows || []).map(({ id, name, installed, authenticated, version, blockedBy }) => {
55
+ const gate = adapters.get(id);
56
+ const decisionCount = decisions ? (Object.hasOwn(decisions, id) ? decisions[id]?.total ?? 0 : 0) : null;
57
+ const hookStatus = !adapterRows ? 'unknown' : !gate || gate.level === 'not wired' ? 'unsupported' : gate.installed ? 'configured' : 'missing';
58
+ const { attempt, completed } = runs.get(id) || {};
59
+ return {
60
+ id, name, installed, authenticated, version: version ?? null, ...(blockedBy ? { blockedBy } : {}),
61
+ nativeGate: { status: hookStatus, recentDecisions: decisionCount },
62
+ managedRun: { lastAttempt: describeRun(attempt), lastCompleted: describeRun(completed) },
63
+ };
64
+ });
65
+ const installed = agents.filter(agent => agent.installed);
66
+ const managedCompletions = installed.filter(agent => agent.managedRun.lastCompleted).length;
67
+ return {
68
+ ok: issues.length === 0, pluginVersion: version,
69
+ issues, agents,
70
+ summary: { installed: installed.length, managedCompletions, liveHookActivity: installed.filter(agent => agent.nativeGate.recentDecisions > 0).length },
71
+ };
72
+ }
73
+
74
+ export async function inspectFleetAdoption({ node, inventory = listTargets, readLocal = inspectLocalAdoption, execute = executeOnNode } = {}) {
75
+ const targets = await inventory();
76
+ const nodes = node ? targets.nodes.filter(row => row.id === node || row.name === node) : targets.nodes;
77
+ if (!nodes.length) throw new Error('Select a recorded node from meta-harness nodes');
78
+ const results = await Promise.all(nodes.map(async target => {
79
+ const row = { node: target.id, name: target.name };
80
+ if (!target.self && target.online === false) return { ...row, status: 'offline' };
81
+ if (!target.self && !target.accessConfigured) return { ...row, status: 'no-cli-access' };
82
+ try {
83
+ let report;
84
+ if (target.self) report = await readLocal();
85
+ else {
86
+ const result = await execute(target.id, {
87
+ operation: 'direct', useHome: true, timeoutMs: 40000,
88
+ argv: ['total-recall', 'meta-harness', 'adoption', '--json'],
89
+ });
90
+ try { report = JSON.parse(result.output); } catch { /* The installed CLI did not supply an adoption report. */ }
91
+ if (report?.error === 'Unknown operation: adoption') return { ...row, status: 'update-required', error: 'The installed Metaharness does not support adoption reports.' };
92
+ if (!report || !Array.isArray(report.agents) || typeof report.pluginVersion !== 'string' || typeof report.ok !== 'boolean' || (report.ok && !result.ok)) {
93
+ return { ...row, status: 'adoption-unavailable', error: 'The installed Metaharness did not return an adoption report. Verify its version and CLI availability.' };
94
+ }
95
+ }
96
+ return { ...row, status: report.ok ? 'inspected' : 'partial', report };
97
+ } catch (error) {
98
+ return { ...row, status: 'probe-failed', error: String(error?.message || error).slice(0, 400) };
99
+ }
100
+ }));
101
+ return { ok: !targets.meshError && results.every(row => row.status === 'inspected'), ...(targets.meshError ? { meshError: targets.meshError } : {}), nodes: results };
102
+ }