Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(ruflo-ruos): JobTransport (exec-poll + ruOS jobs API), live-run fixes, ruOS design rules

ruv30cd360b6b40
diff --git a/plugins/ruflo-ruos/README.md b/plugins/ruflo-ruos/README.md
index f3d69df309..d16720fe2f 100644
--- a/plugins/ruflo-ruos/README.md
+++ b/plugins/ruflo-ruos/README.md
@@ -15,10 +15,17 @@ Design and threat model: [ADR-405](../../v3/docs/adr/ADR-405-ruos-desktops-as-sw
| Transport | When | Configure |
|---|---|---|
-| ruOS fleet MCP (default) | Always the control plane. Exec from anywhere. | In Claude Code: the connected `mcp__ruos__*` tools. In a terminal: `RUOS_MCP_URL`, `RUOS_MCP_TOKEN` |
-| Per-tenant SSH `:2222` | Only when ruflo runs on one of your ruOS desktops (Fly 6PN) | `--transport ssh`, `RUOS_SSH_KEY`, optional `RUOS_SSH_USER`, `RUOS_FLY_APP` |
+| ruOS fleet MCP / REST (default) | **The only path from outside your ruOS tenant** (laptops, workstations, CI) | In Claude Code: the connected `mcp__ruos__*` tools. In a terminal: `RUOS_MCP_URL` + `RUOS_MCP_TOKEN`, or the `@cognitum/ruos` login (`~/.config/ruos/credentials.json`) |
+| Per-tenant SSH `:2222` | Only desktop to desktop inside your tenant's Fly 6PN, i.e. when ruflo runs ON one of your ruOS desktops | `--transport ssh`, `RUOS_SSH_KEY`, optional `RUOS_SSH_USER`, `RUOS_FLY_APP`. Peers come from `~/.claude/federation/peers.json` |
-The plugin never contacts the desktop executor on `:17870`. That executor has no per-tenant auth (ruOS ADR-070). Credentials are read from the environment only. With them unset, every networked command exits 2 and makes no request.
+Mint a **`desktop:control`** token with the narrowest lifetime. A read-only token can list desktops but cannot exec, start or stop them.
+
+- The plugin never contacts the desktop executor on `:17870`, which has no per-tenant auth (ruOS ADR-070).
+- It never calls `desktop_delete` or `secret_delete`.
+- It never logs your token.
+- With no credentials, every networked command exits 2 and makes no request.
+
+**Jobs.** `--jobs auto` (the default) uses the ruOS jobs API (ADR-105) when it is deployed, and otherwise polls `desktop_exec`. The poll path is a detached `nohup` runner under `~/.ruflo-ruos/runs/`, read by byte offset about 2 KiB at a time, because `desktop_exec` output is head-capped at about 4 KiB.
## Commands
@@ -27,7 +34,7 @@ The plugin never contacts the desktop executor on `:17870`. That executor has no
| `/ruflo-ruos:hosts` | Lists your desktops: state, heartbeat, and the ruflo agents on each |
| `/ruflo-ruos:run` | Runs `claude -p` on a desktop, streams the output, and records the agent and its claim |
| `/ruflo-ruos:view` | Delegates to `/ruos view` if installed, otherwise to a view-only `desktop_share` link |
-| `/ruflo-ruos:deploy` | Read-only: branch, HEAD, dirty and ahead counts of a repo on the desktop. Never pushes. |
+| `/ruflo-ruos:deploy` | Read-only hand-off: branch, HEAD, dirty and ahead counts of a repo, plus a summary for a human to review, merge and deploy. Never pushes, deploys or publishes. |
Skill: `ruos-host-run`, the session path that uses the connected fleet MCP. Agent: `ruos-host-operator`.
@@ -41,6 +48,7 @@ $CLI run --desktop "Work Desktop" --prompt-file task.txt --model sonnet --timeou
$CLI run --desktop <id> --prompt-file task.txt --start # wakes a stopped desktop (billable)
$CLI stop --desktop <id> --run <runId> --confirm
$CLI desktop-stop --desktop <id> --confirm
+$CLI attach --desktop <id> --run <runId> # re-read a run after a restart (HOME persists)
$CLI logs --run <runId>
$CLI build --prompt-file task.txt # exact desktop_exec strings for the session path
$CLI record start|output|end --run <runId> ...
@@ -52,6 +60,7 @@ $CLI deploy-info --desktop <id> --repo projects/app
Remote agents are recorded with ruflo's own tools: `agent_spawn` with `config.host = {kind: "ruos", desktopId, desktopName, transport, runId}`, then `agent_update`, then `claims_claim`/`claims_release` on `ruos-run-<runId>`. The plugin itself writes only to `.claude-flow/ruos/`:
- `events.jsonl`: lifecycle events, with ids and sizes only;
+- `audit.jsonl`: one record per run (desktop, command sha256, start, end, exit, bytes), because ruOS does not audit the detached output;
- `hosts.json`: the current host snapshot;
- `runs/<runId>.log`: the run output, mode 0600.
diff --git a/plugins/ruflo-ruos/agents/ruos-host-operator.md b/plugins/ruflo-ruos/agents/ruos-host-operator.md
index 0a14dc46b2..b31186e316 100644
--- a/plugins/ruflo-ruos/agents/ruos-host-operator.md
+++ b/plugins/ruflo-ruos/agents/ruos-host-operator.md
@@ -6,9 +6,11 @@ model: sonnet
You operate ruOS desktops as remote execution hosts for a ruflo swarm (ADR-405).
Hard rules:
-- Transports: the tenant-authenticated ruOS fleet MCP (`desktop_status`, `desktop_exec`,
- `desktop_start`, `desktop_stop`, `desktop_keepawake`) or per-tenant SSH on :2222. Never
- the desktop executor on :17870, never a forged `Host` header.
+- Transports: the tenant-authenticated ruOS fleet MCP/REST is the only path from outside
+ the tenant. Per-tenant SSH on :2222 is only desktop to desktop inside the tenant. Never
+ use the desktop executor on :17870, and never forge a `Host` header.
+- Never call `desktop_delete` or `secret_delete`. Deletion is a human action.
+- Check `llm_route_get` before launching `claude -p`.
- Desktops come only from the caller's own `desktop_status`. Refuse anything else.
- Remote commands come only from `scripts/cli.mjs build` (the audited builder). Task
text never enters a command line.
@@ -19,7 +21,8 @@ Hard rules:
- Record every remote agent through ruflo's existing ledger (`cli.mjs record` or
`cli.mjs run`), which uses `agent_spawn`/`agent_update` and `claims_claim`/`claims_release`.
Do not invent another claims or state store.
-- Deploy is the user's decision: report repo state with `cli.mjs deploy-info`, never push.
+- Deploy is read-only. Report repo state with `cli.mjs deploy-info` and hand a branch or PR
+ plus the summary to a human. Never push, deploy or publish.
Workflow: follow the `ruos-host-run` skill. Report per run: desktop, runId, agentId,
status, exit code, bytes, and any ledger warnings.
diff --git a/plugins/ruflo-ruos/commands/deploy.md b/plugins/ruflo-ruos/commands/deploy.md
index 633eb9adeb..f814d45d5f 100644
--- a/plugins/ruflo-ruos/commands/deploy.md
+++ b/plugins/ruflo-ruos/commands/deploy.md
@@ -9,7 +9,9 @@ decide on a deploy:
`node "${CLAUDE_PLUGIN_ROOT}/scripts/cli.mjs" deploy-info --desktop "<ref>" --repo <path-relative-to-$HOME>`
-It returns branch, HEAD, dirty file count and commits ahead of upstream. It does **not**
-push, merge or deploy: ruOS's exec filter refuses `git push` / `fly deploy` literals by
-design, and deploying is the user's decision through their own ruOS or project tooling.
-Present the summary and stop.
+It returns branch, HEAD, dirty file count and commits ahead of upstream. The hand-off is:
+
+- a branch or PR;
+- this summary, for a human to review, merge and deploy.
+
+The swarm is read-only for deploys. It never pushes, merges, deploys or publishes, and ruOS has no deploy tool to call. Present the summary and stop.
diff --git a/plugins/ruflo-ruos/scripts/bench.mjs b/plugins/ruflo-ruos/scripts/bench.mjs
index c6b55e2909..b8439ed8d0 100644
--- a/plugins/ruflo-ruos/scripts/bench.mjs
+++ b/plugins/ruflo-ruos/scripts/bench.mjs
@@ -17,6 +17,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { RuosHostAdapter } from './lib/adapter.mjs';
import { createLedger } from './lib/ledger.mjs';
+import { createExecPollTransport } from './lib/jobs.mjs';
const n = Number(process.argv[process.argv.indexOf('--n') + 1]) || 20;
const root = mkdtempSync(join(tmpdir(), 'ruflo-ruos-bench-'));
@@ -39,6 +40,7 @@ const desk = { id: 'a'.repeat(32), flyMachineId: null, name: 'local', displayNam
const fleet = {
listDesktops: async () => [{ ...desk, heartbeatAt: Math.floor(Date.now() / 1000) }],
start: async () => {}, stop: async () => {}, keepAwake: async () => {},
+ llmRoute: async () => ({ route: 'shared', provider: 'local', gateway: 'configured', keyPresent: true }),
};
const prompt = 'Summarise the repository README in three bullet points.\n'.repeat(20);
@@ -59,9 +61,9 @@ for (let i = 0; i < n; i++) {
raw.push(performance.now() - t);
const ledger = createLedger({ cwd: join(root, 'proj'), callTool: null });
- const adapter = new RuosHostAdapter({ fleet, transport, ledger, sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 20))) });
+ const adapter = new RuosHostAdapter({ fleet, jobs: createExecPollTransport(transport), ledger, sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 20))) });
t = performance.now();
- const out = await adapter.run({ desktop: desk.id, prompt, runId: `r-bench-${String(i).padStart(4, '0')}`, agentId: `bench-${i}`, timeoutSecs: 60, ignoreAutoStop: true });
+ const out = await adapter.run({ desktop: desk.id, prompt, runId: `r-bench${String(i).padStart(28, '0')}`, agentId: `bench-${i}`, timeoutSecs: 60, ignoreAutoStop: true });
total.push(performance.now() - t);
if (out.firstOutputMs !== null) firstOut.push(out.firstOutputMs);
}
@@ -72,6 +74,6 @@ const result = {
rawCallMs: stats(raw),
adapterFirstOutputMs: stats(firstOut),
adapterTotalMs: stats(total),
- note: 'local /bin/sh, zero network; adapter = prepare + 1 chunk + launch + >=1 poll + ledger files. Poll sleep capped at 20ms here; production backs off 1s->5s.',
+ note: 'local /bin/sh, zero network; adapter = prepare + 1 chunk + launch + >=1 poll + ledger files. Poll sleep capped at 20ms here; production backs off 1s->10s.',
};
console.log(JSON.stringify(result, null, 2));
diff --git a/plugins/ruflo-ruos/scripts/cli.mjs b/plugins/ruflo-ruos/scripts/cli.mjs
index 601ba6852c..dcd7a5d152 100755
--- a/plugins/ruflo-ruos/scripts/cli.mjs
+++ b/plugins/ruflo-ruos/scripts/cli.mjs
@@ -6,7 +6,9 @@
* hosts list your ruOS desktops (fleet MCP)
* run --desktop <ref> (--prompt <t> | --prompt-file <f>) [--agent-type coder]
* [--model haiku|sonnet|opus] [--timeout 900] [--max-budget-usd n]
- * [--start] [--ignore-autostop] [--transport fleet-mcp|ssh] [--json]
+ * [--start] [--ignore-autostop] [--transport fleet-mcp|ssh]
+ * [--jobs auto|exec-poll|jobs-api] [--json]
+ * attach --desktop <ref> --run <id> [--offset n] re-read a run (e.g. after a restart)
* stop --desktop <ref> --run <id> --confirm
* desktop-stop --desktop <ref> --confirm
* logs --run <id>
@@ -17,8 +19,10 @@
* read-only: what a deploy from that repo would ship
* status transport configuration (no network)
*
- * With no RUOS_MCP_URL/RUOS_MCP_TOKEN (and no RUOS_SSH_KEY for ssh) every
- * networked command exits 2 with `not-configured` and makes no request.
+ * Credentials: RUOS_MCP_URL + RUOS_MCP_TOKEN, or ~/.config/ruos/credentials.json
+ * from @cognitum/ruos. With neither, every networked command exits 2 with
+ * `not-configured` and makes no request. SSH (--transport ssh) works only
+ * when this CLI runs on a same-tenant ruOS desktop (Fly 6PN).
*/
import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
@@ -30,6 +34,7 @@ import { createLedger, resolveCallTool, projectCwd } from './lib/ledger.mjs';
import { RuosHostAdapter } from './lib/adapter.mjs';
import { newRunId, assertRunId, assertAgentId, resolveDesktop, assertInt } from './lib/validate.mjs';
import { buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, buildProbe, buildRepoSummary, parseRepoSummary } from './lib/command-builder.mjs';
+import { createExecPollTransport, createJobsApiTransport, createRestJobsBackend } from './lib/jobs.mjs';
import { nextAutoStop } from './lib/autostop.mjs';
/**
@@ -62,12 +67,35 @@ async function buildAdapter(args, env) {
const client = new FleetMcpClient(fleetConfigFromEnv(env));
client.assertConfigured(); // the fleet MCP is always the control plane
const kind = str(args.transport) ?? env.RUOS_TRANSPORT ?? 'fleet-mcp';
- const transport = kind === 'ssh'
+ const exec = kind === 'ssh'
? createSshTransport(sshConfigFromEnv(env))
: kind === 'fleet-mcp' ? createFleetTransport(client) : null;
- if (!transport) throw new RuosError('invalid-input', 'transport must be fleet-mcp or ssh');
+ if (!exec) throw new RuosError('invalid-input', 'transport must be fleet-mcp or ssh');
+ const fleet = createFleet(client);
+ const jobs = await pickJobTransport(str(args.jobs) ?? env.RUOS_JOBS ?? 'auto', client, fleet, exec, env);
const ledger = createLedger({ cwd: projectCwd(env), callTool: await resolveCallTool(projectCwd(env), env) });
- return { adapter: new RuosHostAdapter({ fleet: createFleet(client), transport, ledger }), ledger };
+ return { adapter: new RuosHostAdapter({ fleet, jobs, ledger, transportKind: /** @type {'fleet-mcp'|'ssh'} */ (kind) }), ledger, exec };
+}
+
+/**
+ * Use the ruOS jobs API (ADR-105) when it is deployed, else exec-poll.
+ * @param {string} mode
+ * @param {FleetMcpClient} client
+ * @param {import('./lib/types.mjs').Fleet} fleet
+ * @param {import('./lib/types.mjs').Transport} exec
+ * @param {NodeJS.ProcessEnv} env
+ */
+async function pickJobTransport(mode, client, fleet, exec, env) {
+ if (mode === 'exec-poll') return createExecPollTransport(exec);
+ if (mode !== 'auto' && mode !== 'jobs-api') throw new RuosError('invalid-input', 'jobs must be auto, exec-poll or jobs-api');
+ const baseUrl = env.RUOS_API_URL || (client.url ? new URL(client.url).origin : undefined);
+ const token = /** @type {any} */ (client).token;
+ if (!baseUrl || !token) return createExecPollTransport(exec);
+ const rest = createRestJobsBackend({ baseUrl, token });
+ const first = (await fleet.listDesktops())[0];
+ const available = first ? await rest.detect(first.flyMachineId ?? first.id) : false;
+ if (!available && mode === 'jobs-api') throw new RuosError('not-configured', 'the ruOS jobs API is not available on this fleet yet');
+ return available ? createJobsApiTransport(rest, exec) : createExecPollTransport(exec);
}
/** @param {unknown} o */
@@ -98,6 +126,7 @@ export async function main(argv, env = process.env) {
const f = fleetConfigFromEnv(env);
print({
fleetMcp: f.url && f.token ? 'configured' : 'not-configured',
+ credentialSource: f.source,
ssh: env.RUOS_SSH_KEY ? 'configured' : 'not-configured',
transport: env.RUOS_TRANSPORT ?? 'fleet-mcp',
nextAutoStop: new Date(nextAutoStop(Date.now())).toISOString(),
@@ -114,7 +143,7 @@ export async function main(argv, env = process.env) {
}
case 'run': {
const { adapter } = await buildAdapter(args, env);
- const runId = newRunId(Date.now, randomBytes);
+ const runId = newRunId(randomBytes);
const outcome = await adapter.run({
desktop: String(args.desktop ?? ''),
prompt: readPrompt(args),
@@ -144,13 +173,20 @@ export async function main(argv, env = process.env) {
}
case 'deploy-info': {
// Read-only hand-off: report repo state; never push or deploy.
- const { adapter } = await buildAdapter(args, env);
+ const { adapter, exec } = await buildAdapter(args, env);
const cmdline = buildRepoSummary(String(args.repo ?? ''));
const d = await adapter.resolve(String(args.desktop ?? ''));
- print({ desktopId: d.id, repo: args.repo, ...parseRepoSummary((await adapter.transport.exec(d, cmdline, 30)).stdout),
- next: 'review the diff, then deploy with your ruOS/project tooling; ruflo-ruos does not push or deploy' });
+ print({ desktopId: d.id, repo: args.repo, ...parseRepoSummary((await exec.exec(d, cmdline, 30)).stdout),
+ next: 'prepare a branch/PR and this summary for a human to review, merge and deploy; ruflo-ruos never pushes, deploys or publishes' });
return 0;
}
+ case 'attach': {
+ const { adapter } = await buildAdapter(args, env);
+ const r = await adapter.attach({ desktop: String(args.desktop ?? ''), runId: String(args.run ?? ''), offset: str(args.offset) ? Number(args.offset) : 0,
+ onOutput: args.json ? undefined : (c) => process.stdout.write(c) });
+ if (args.json) print(r); else process.stderr.write(`\n[ruflo-ruos] ${r.status} exit=${r.exitCode} offset=${r.offset}\n`);
+ return r.status === 'completed' ? 0 : 1;
+ }
case 'logs': {
const runId = assertRunId(args.run);
const f = join(projectCwd(env), '.claude-flow', 'ruos', 'runs', `${runId}.log`);
@@ -160,7 +196,7 @@ export async function main(argv, env = process.env) {
}
case 'build': {
// Session path: Claude calls mcp__ruos__desktop_exec with these strings.
- const runId = str(args.run) ? assertRunId(args.run) : newRunId(Date.now, randomBytes);
+ const runId = str(args.run) ? assertRunId(args.run) : newRunId(randomBytes);
const prompt = readPrompt(args);
const chunks = buildPromptChunks(runId, prompt);
print({
@@ -176,7 +212,7 @@ export async function main(argv, env = process.env) {
case 'record':
return record(args, env);
default:
- print('usage: cli.mjs <status|hosts|run|stop|desktop-stop|logs|build|record|deploy-info> [options] (see header)');
+ print('usage: cli.mjs <status|hosts|run|attach|stop|desktop-stop|logs|build|record|deploy-info> [options] (see header)');
return cmd ? 2 : 0;
}
}
@@ -199,7 +235,8 @@ async function record(args, env) {
if (!statusFile) throw new RuosError('invalid-input', 'record start needs --desktop-status-file (desktop_status JSON)');
const d = resolveDesktop(normalizeDesktops(JSON.parse(readFileSync(statusFile, 'utf8'))), String(args.desktop ?? ''));
if (!(await ledger.claim(runId, agentId, agentType))) throw new RuosError('invalid-input', 'run already claimed');
- await ledger.registerAgent(agentId, agentType, { kind: 'ruos', desktopId: d.id, desktopName: d.displayName ?? d.name, transport: 'fleet-mcp', runId }, String(args.task ?? ''));
+ const stopAt = d.flyMachineId ? new Date(nextAutoStop(Date.now())).toISOString() : null;
+ await ledger.registerAgent(agentId, agentType, { kind: 'ruos', desktopId: d.id, desktopName: d.displayName ?? d.name, transport: 'fleet-mcp', jobs: 'exec-poll', runId, stopAt }, String(args.task ?? ''));
ledger.snapshotHosts([d]);
ledger.setHostAgent(d.id, agentId, true);
ledger.event({ type: 'run.started', runId, agentId, desktopId: d.id, desktopName: d.displayName ?? d.name });
diff --git a/plugins/ruflo-ruos/scripts/lib/adapter.mjs b/plugins/ruflo-ruos/scripts/lib/adapter.mjs
index c9164f18ac..3fccbc4f57 100644
--- a/plugins/ruflo-ruos/scripts/lib/adapter.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/adapter.mjs
@@ -2,15 +2,17 @@
/**
* ruOS host adapter (ADR-405): discover → (opt-in start) → launch → stream →
* stop, with typed failures. Collaborators are injected (London-school):
- * Fleet (control plane), Transport (exec), Ledger (swarm state), clock.
+ * Fleet (control plane), JobTransport (launch/poll/cancel), Ledger (swarm
+ * state + audit), clock.
*/
import { RuosError } from './types.mjs';
-import { resolveDesktop, assertRunId, assertAgentId, assertInt } from './validate.mjs';
-import {
- buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, parsePoll, parseLaunch,
-} from './command-builder.mjs';
+import { resolveDesktop, assertRunId, assertAgentId, assertInt, assertPrompt } from './validate.mjs';
import { checkWindow } from './autostop.mjs';
+const TERMINAL = new Set(['exited', 'failed', 'cancelled']);
+export const POLL_MIN_MS = 1000;
+export const POLL_MAX_MS = 10_000;
+
/** heartbeat older than this is not evidence the desktop is up */
export const HEARTBEAT_FRESH_SECS = 180;
@@ -27,7 +29,8 @@ export function isUp(d, nowMs) {
/**
* @typedef {object} AdapterDeps
* @property {import('./types.mjs').Fleet} fleet
- * @property {import('./types.mjs').Transport} transport
+ * @property {import('./types.mjs').JobTransport} jobs
+ * @property {'fleet-mcp'|'ssh'=} transportKind the exec path under the job transport
* @property {import('./ledger.mjs').Ledger} ledger
* @property {() => number=} now
* @property {(ms: number) => Promise<void>=} sleep
@@ -61,14 +64,19 @@ export function isUp(d, nowMs) {
* @property {number|null} firstOutputMs local call → first output byte
* @property {number} totalMs
* @property {string} swarmLedger
+ * @property {string|null} stopAt
+ * @property {'exec-poll'|'jobs-api'} jobs
* @property {string[]} warnings
*/
+/** @typedef {{ bytes: number, firstOutputMs: number|null, offset: number }} Stream */
+
export class RuosHostAdapter {
/** @param {AdapterDeps} deps */
constructor(deps) {
this.fleet = deps.fleet;
- this.transport = deps.transport;
+ this.jobs = deps.jobs;
+ this.transportKind = deps.transportKind ?? 'fleet-mcp';
this.ledger = deps.ledger;
this.now = deps.now ?? Date.now;
this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
@@ -115,19 +123,6 @@ export class RuosHostAdapter {
throw new RuosError('timeout', 'desktop did not report a fresh heartbeat after start');
}
- /**
- * @param {import('./types.mjs').Desktop} desktop
- * @param {string} command
- * @param {number=} timeoutSecs
- */
- async exec(desktop, command, timeoutSecs = 30) {
- const r = await this.transport.exec(desktop, command, timeoutSecs);
- if (r.exitCode !== null && r.exitCode !== 0) {
- throw new RuosError('remote-error', `remote command failed (exit ${r.exitCode}): ${(r.stdout + r.stderr).slice(0, 200)}`);
- }
- return r;
- }
-
/**
* After a transport failure mid-run: did the desktop stop under us?
* @param {import('./types.mjs').Desktop} desktop
@@ -146,6 +141,44 @@ export class RuosHostAdapter {
return err instanceof RuosError ? err : new RuosError('remote-error', String(err), err);
}
+ /**
+ * Fail fast when the desktop has no LLM route for `claude -p`. Observed
+ * live: `gateway: "unconfigured"` with `route: "shared"` still ran, so only
+ * a missing/disabled route is fatal; an unconfigured gateway is a warning.
+ */
+ async checkLlmRoute() {
+ let r;
+ try {
+ r = await this.fleet.llmRoute();
+ } catch (err) {
+ if (err instanceof RuosError && (err.code === 'auth-expired' || err.code === 'network-down')) throw err;
+ this.ledger.warnings.push('llm_route_get unavailable; launching without a route check');
+ return;
+ }
+ if (!r.route || ['none', 'disabled', 'off'].includes(r.route)) {
+ throw new RuosError('llm-unconfigured', 'the desktop has no LLM route for claude -p; configure one in ruOS (llm_route_set) first');
+ }
+ if (r.gateway === 'unconfigured' && !r.keyPresent) {
+ this.ledger.warnings.push(`llm route "${r.route}" with no gateway key; relying on the shared route`);
+ }
+ }
+
+ /**
+ * @param {import('./types.mjs').Desktop} desktop
+ * @param {import('./types.mjs').RunSpec & { timeoutSecs: number }} spec
+ */
+ async startWithBackoff(desktop, spec) {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await this.jobs.start(desktop, spec);
+ } catch (err) {
+ if (!(err instanceof RuosError) || err.code !== 'capacity' || attempt >= 3) throw err;
+ this.ledger.warnings.push(`job concurrency cap reached; retry ${attempt + 1}/3`);
+ await this.sleep(5000 * 2 ** attempt);
+ }
+ }
+ }
+
/**
* @param {RunOptions} o
* @returns {Promise<RunOutcome>}
@@ -156,6 +189,7 @@ export class RuosHostAdapter {
const agentId = assertAgentId(o.agentId);
const agentType = assertAgentId(o.agentType ?? 'coder');
const timeoutSecs = assertInt(o.timeoutSecs ?? 900, 30, 6 * 3600, 'timeoutSecs');
+ assertPrompt(o.prompt); // validate before any remote call
let desktop = await this.resolve(o.desktop);
// The 23:00 auto-stop applies to cloud desktops only, not enrolled devices.
@@ -164,31 +198,29 @@ export class RuosHostAdapter {
throw new RuosError('autostop-window', `run may outlast the next auto-stop in ${win.minutesUntilStop} min (weekday 23:00 America/Toronto); shorten --timeout or pass --ignore-autostop`);
}
desktop = await this.ensureUp(desktop, { allowStart: o.allowStart });
+ await this.checkLlmRoute();
const name = desktop.displayName ?? desktop.name;
+ const stopAt = desktop.flyMachineId ? new Date(win.nextStopMs).toISOString() : null;
/** @type {import('./types.mjs').HostRef} */
- const host = { kind: 'ruos', desktopId: desktop.id, desktopName: name, transport: this.transport.kind, runId };
+ const host = { kind: 'ruos', desktopId: desktop.id, desktopName: name, transport: this.transportKind, jobs: this.jobs.kind, runId, stopAt };
- const chunks = buildPromptChunks(runId, o.prompt); // validates the prompt before any remote call
const claimed = await this.ledger.claim(runId, agentId, agentType);
if (!claimed) throw new RuosError('invalid-input', `run ${runId} is already claimed`);
await this.ledger.registerAgent(agentId, agentType, host, o.prompt);
this.ledger.snapshotHosts([desktop]);
this.ledger.setHostAgent(desktop.id, agentId, true);
- let bytes = 0;
- /** @type {number|null} */ let firstOutputMs = null;
+ /** @type {Stream} */
+ const st = { bytes: 0, firstOutputMs: null, offset: 0 };
let dispatchMs = 0;
/** @type {RunOutcome['status']} */ let status = 'failed';
/** @type {number|null} */ let exitCode = null;
+ let commandSha256 = '';
+ let jobId = runId;
try {
- await this.exec(desktop, buildPrepare(runId));
- for (const c of chunks.commands) await this.exec(desktop, c);
- const lr = await this.transport.exec(desktop, buildLaunch({ runId, prompt: o.prompt, runner: 'claude', model: o.model, maxBudgetUsd: o.maxBudgetUsd }), 60);
- const launched = parseLaunch(lr.stdout);
- if (launched.noRunner) throw new RuosError('remote-error', 'claude is not installed on the desktop');
- if (lr.exitCode !== null && lr.exitCode !== 0) throw new RuosError('remote-error', `launch failed (exit ${lr.exitCode})`);
- if (launched.sha256 !== chunks.sha256) throw new RuosError('remote-error', 'prompt integrity check failed (sha256 mismatch)');
- if (launched.pid === null) throw new RuosError('remote-error', 'runner did not report a pid');
+ const started = await this.startWithBackoff(desktop, { runId, prompt: o.prompt, runner: 'claude', model: o.model, maxBudgetUsd: o.maxBudgetUsd, timeoutSecs });
+ jobId = started.jobId;
+ commandSha256 = started.commandSha256;
dispatchMs = this.now() - t0;
this.ledger.event({ type: 'run.started', runId, agentId, desktopId: desktop.id, desktopName: name });
if (desktop.flyMachineId) {
@@ -196,65 +228,106 @@ export class RuosHostAdapter {
this.ledger.warnings.push('keepawake failed; idle autosleep may stop the run');
});
}
-
- let offset = 0;
- let delay = 1000;
- for (;;) {
- if (o.signal?.aborted) {
- await this.transport.exec(desktop, buildStop(runId), 30).catch(() => {});
- status = 'stopped';
- break;
- }
- if (this.now() - t0 > timeoutSecs * 1000) {
- await this.transport.exec(desktop, buildStop(runId), 30).catch(() => {});
- throw new RuosError('timeout', `run exceeded ${timeoutSecs}s and was stopped`);
- }
- const p = parsePoll((await this.transport.exec(desktop, buildPoll(runId, offset), 30)).stdout);
- if (p === 'norun') throw new RuosError('remote-error', 'run directory vanished on the desktop');
- if (p.chunk.length > 0) {
- if (firstOutputMs === null) firstOutputMs = this.now() - t0;
- offset += p.chunk.length;
- bytes += p.chunk.length;
- this.ledger.appendOutput(runId, p.chunk);
- o.onOutput?.(p.chunk);
- this.ledger.event({ type: 'run.output', runId, agentId, desktopId: desktop.id, bytes: p.chunk.length });
- delay = 1000;
- }
- if (p.exitCode === null && !p.alive && p.chunk.length === 0) {
- // Re-check once: exit.code is written just after the runner exits.
- const again = parsePoll((await this.transport.exec(desktop, buildPoll(runId, offset), 30)).stdout);
- if (again !== 'norun' && again.exitCode === null && !again.alive) {
- throw new RuosError('remote-error', 'runner died without an exit code (killed on the desktop?)');
- }
- continue;
- }
- if (p.exitCode !== null && offset >= p.size) {
- exitCode = p.exitCode;
- status = exitCode === 0 ? 'completed' : 'failed';
- break;
- }
- if (p.chunk.length === 0) {
- await this.sleep(delay);
- delay = Math.min(delay * 1.5, 5000);
- }
- }
+ const end = await this.stream(desktop, jobId, runId, agentId, st, { t0, timeoutSecs, signal: o.signal, onOutput: o.onOutput });
+ status = end.status;
+ exitCode = end.exitCode;
} catch (err) {
const e = await this.classifyMidRun(desktop, err);
this.ledger.event({ type: 'run.failed', runId, agentId, desktopId: desktop.id, error: e.code ?? 'remote-error' });
- await this.finish(desktop.id, agentId, agentType, runId, 'failed', null, bytes);
+ this.audit({ runId, jobId, desktopId: desktop.id, agentId, commandSha256, t0, status: 'failed', exitCode: null, bytes: st.bytes, error: e.code });
+ await this.finish(desktop.id, agentId, agentType, runId, 'failed', null, st.bytes);
throw e;
}
this.ledger.event({
type: status === 'stopped' ? 'run.stopped' : status === 'completed' ? 'run.completed' : 'run.failed',
- runId, agentId, desktopId: desktop.id, exitCode, bytes,
+ runId, agentId, desktopId: desktop.id, exitCode, bytes: st.bytes,
});
- await this.finish(desktop.id, agentId, agentType, runId, status, exitCode, bytes);
+ this.audit({ runId, jobId, desktopId: desktop.id, agentId, commandSha256, t0, status, exitCode, bytes: st.bytes });
+ await this.finish(desktop.id, agentId, agentType, runId, status, exitCode, st.bytes);
return {
- runId, agentId, desktopId: desktop.id, status, exitCode, bytes, dispatchMs, firstOutputMs,
- totalMs: this.now() - t0, swarmLedger: this.ledger.swarmLedger, warnings: [...this.ledger.warnings],
+ runId, agentId, desktopId: desktop.id, status, exitCode, bytes: st.bytes, dispatchMs, firstOutputMs: st.firstOutputMs,
+ totalMs: this.now() - t0, swarmLedger: this.ledger.swarmLedger, stopAt, jobs: this.jobs.kind, warnings: [...this.ledger.warnings],
};
}
+ /**
+ * Poll a job to a terminal state with adaptive backoff (1 s while output
+ * flows, up to 10 s when idle). Each exec poll is audited on ruOS and
+ * waits behind the desktop's run lock, so idle polling must stay sparse.
+ * @param {import('./types.mjs').Desktop} desktop
+ * @param {string} jobId
+ * @param {string} runId
+ * @param {string} agentId
+ * @param {Stream} st
+ * @param {{ t0: number, timeoutSecs: number, signal?: AbortSignal, onOutput?: (c: Buffer) => void }} o
+ * @returns {Promise<{ status: RunOutcome['status'], exitCode: number|null }>}
+ */
+ async stream(desktop, jobId, runId, agentId, st, o) {
+ let delay = POLL_MIN_MS;
+ let lostOnce = false;
+ for (;;) {
+ if (o.signal?.aborted) {
+ await this.jobs.cancel(desktop, jobId).catch(() => false);
+ return { status: 'stopped', exitCode: null };
+ }
+ if (this.now() - o.t0 > o.timeoutSecs * 1000) {
+ await this.jobs.cancel(desktop, jobId).catch(() => false);
+ throw new RuosError('timeout', `run exceeded ${o.timeoutSecs}s and was stopped`);
+ }
+ const p = await this.jobs.poll(desktop, jobId, st.offset);
+ if (p.chunk.length > 0) {
+ if (st.firstOutputMs === null) st.firstOutputMs = this.now() - o.t0;
+ st.bytes += p.chunk.length;
+ this.ledger.appendOutput(runId, p.chunk);
+ o.onOutput?.(p.chunk);
+ this.ledger.event({ type: 'run.output', runId, agentId, desktopId: desktop.id, bytes: p.chunk.length });
+ }
+ st.offset = Math.max(st.offset + p.chunk.length, p.nextOffset);
+ if (p.truncated) this.ledger.warnings.push('job output exceeded the server cap; tail truncated');
+ if (p.chunk.length > 0) { delay = POLL_MIN_MS; continue; }
+ if (TERMINAL.has(p.state)) {
+ return { status: p.state === 'exited' ? 'completed' : p.state === 'cancelled' ? 'stopped' : 'failed', exitCode: p.exitCode };
+ }
+ if (p.state === 'stopped') {
+ throw new RuosError('auto-stopped', `desktop stopped mid-run; HOME persists — wake it and \`attach --run ${runId}\` to read the output`);
+ }
+ if (p.state === 'lost') {
+ if (lostOnce) throw new RuosError('remote-error', 'runner died without an exit code (killed on the desktop?)');
+ lostOnce = true; // exit.code is written just after the runner exits: re-check once
+ continue;
+ }
+ await this.sleep(delay);
+ delay = Math.min(delay * 1.5, POLL_MAX_MS);
+ }
+ }
+
+ /**
+ * Re-attach to an existing run (e.g. after a desktop restart: HOME
+ * survives, the process does not). Reads output from `offset`; no claim.
+ * @param {{ desktop: string, runId: string, agentId?: string, offset?: number, timeoutSecs?: number, onOutput?: (c: Buffer) => void }} o
+ */
+ async attach(o) {
+ const runId = assertRunId(o.runId);
+ const desktop = await this.resolve(o.desktop);
+ /** @type {Stream} */
+ const st = { bytes: 0, firstOutputMs: null, offset: assertInt(o.offset ?? 0, 0, Number.MAX_SAFE_INTEGER, 'offset') };
+ const end = await this.stream(desktop, runId, runId, o.agentId ?? `ruos-${runId}`, st, { t0: this.now(), timeoutSecs: o.timeoutSecs ?? 300, onOutput: o.onOutput });
+ return { runId, desktopId: desktop.id, ...end, bytes: st.bytes, offset: st.offset };
+ }
+
+ /**
+ * ruflo's own per-run audit record: the detached process's output is not
+ * in the ruOS activity feed (ruOS ADR-045 covers only chat-proxy runs).
+ * @param {{ runId: string, jobId: string, desktopId: string, agentId: string, commandSha256: string, t0: number, status: string, exitCode: number|null, bytes: number, error?: string }} r
+ */
+ audit(r) {
+ this.ledger.audit({
+ runId: r.runId, jobId: r.jobId, desktopId: r.desktopId, agentId: r.agentId, jobs: this.jobs.kind,
+ commandSha256: r.commandSha256, startedAt: new Date(r.t0).toISOString(), endedAt: new Date(this.now()).toISOString(),
+ status: r.status, exitCode: r.exitCode, bytes: r.bytes, ...(r.error ? { error: r.error } : {}),
+ });
+ }
+
/**
* @param {string} desktopId
* @param {string} agentId
@@ -272,14 +345,13 @@ export class RuosHostAdapter {
/**
* Stop a run (its process group) — explicit confirm required.
- * @param {{ desktop: string, runId: string, confirm?: boolean }} o
+ * @param {{ desktop: string, runId: string, jobId?: string, confirm?: boolean }} o
*/
async stopRun(o) {
if (!o.confirm) throw new RuosError('confirm-required', 'stopping a run interrupts work; pass --confirm');
const runId = assertRunId(o.runId);
const desktop = await this.resolve(o.desktop);
- const r = await this.transport.exec(desktop, buildStop(runId), 30);
- const stopped = r.stdout.includes('RUOS_STOPPED');
+ const stopped = await this.jobs.cancel(desktop, o.jobId ?? runId);
this.ledger.event({ type: 'run.stopped', runId, desktopId: desktop.id, state: stopped ? 'stopped' : 'not-running' });
return { runId, desktopId: desktop.id, stopped };
}
diff --git a/plugins/ruflo-ruos/scripts/lib/command-builder.mjs b/plugins/ruflo-ruos/scripts/lib/command-builder.mjs
index e76d246fc9..a72a0f7431 100644
--- a/plugins/ruflo-ruos/scripts/lib/command-builder.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/command-builder.mjs
@@ -21,8 +21,13 @@ import { RuosError } from './types.mjs';
import { assertRunId, assertModel, assertBudget, assertInt, assertPrompt } from './validate.mjs';
export const MAX_COMMAND_BYTES = 4000;
-/** largest output slice a single poll returns (raw bytes, before base64) */
-export const POLL_SLICE_BYTES = 48 * 1024;
+/**
+ * Largest output slice one poll returns (raw bytes, before base64).
+ * desktop_exec head-caps stdout at ~4 KiB INCLUDING its `▶ run:` echo of the
+ * ~430-byte poll command (measured live 2026-10-01): 2048 raw bytes → 2732
+ * base64 chars leaves headroom. parsePoll also tolerates truncation.
+ */
+export const POLL_SLICE_BYTES = 2048;
const B64_RE = /^[A-Za-z0-9+/=]*$/;
@@ -167,8 +172,8 @@ export function buildRepoSummary(repoPath) {
* @returns {{ found: boolean, branch?: string, head?: string, dirty?: number, ahead?: string }}
*/
export function parseRepoSummary(stdout) {
- if (stdout.includes('RUOS_NOREPO')) return { found: false };
- const get = (/** @type {string} */ k) => new RegExp(`RUOS_${k}:(.*)`).exec(stdout)?.[1]?.trim() ?? '';
+ if (/^RUOS_NOREPO$/m.test(stdout)) return { found: false };
+ const get = (/** @type {string} */ k) => new RegExp(`^RUOS_${k}:(.*)$`, 'm').exec(stdout)?.[1]?.trim() ?? '';
return { found: true, branch: get('BRANCH'), head: get('HEAD'), dirty: Number(get('DIRTY')) || 0, ahead: get('AHEAD') };
}
@@ -185,13 +190,19 @@ export function buildProbe() {
* @property {Buffer} chunk
*/
+/*
+ * All parsers match markers as WHOLE LINES. desktop_exec echoes the command
+ * it ran, and every builder command contains its own marker names, so a
+ * substring match would always fire (found live, 2026-10-01).
+ */
+
/**
* @param {string} stdout
* @returns {PollResult|'norun'}
*/
export function parsePoll(stdout) {
- if (stdout.includes('RUOS_NORUN')) return 'norun';
- const m = /RUOS_POLL:(-|\d+):(\d+):([01]):([A-Za-z0-9+/=]*)/.exec(stdout);
+ if (/^RUOS_NORUN$/m.test(stdout)) return 'norun';
+ const m = /^RUOS_POLL:(-|\d+):(\d+):([01]):([A-Za-z0-9+/=]*)$/m.exec(stdout);
if (!m) throw new RuosError('remote-error', 'unparseable poll output');
// If the transport truncated the result mid-quantum, decode only whole
// quanta: the offset then advances by exactly what was received and the
@@ -210,11 +221,35 @@ export function parsePoll(stdout) {
* @returns {{ sha256: string|null, pid: number|null, noRunner: boolean }}
*/
export function parseLaunch(stdout) {
- const sha = /RUOS_SHA:([0-9a-f]{64})/.exec(stdout);
- const pid = /RUOS_PID:(\d+)/.exec(stdout);
+ const sha = /^RUOS_SHA:([0-9a-f]{64})$/m.exec(stdout);
+ const pid = /^RUOS_PID:(\d+)$/m.exec(stdout);
return {
sha256: sha ? sha[1] : null,
pid: pid ? Number(pid[1]) : null,
- noRunner: stdout.includes('RUOS_NO_RUNNER'),
+ noRunner: /^RUOS_NO_RUNNER$/m.test(stdout),
};
}
+
+/** @param {string} stdout */
+export const parseStopped = (stdout) => /^RUOS_STOPPED$/m.test(stdout);
+
+/** @param {string} cmd */
+export const commandSha256 = (cmd) => createHash('sha256').update(cmd, 'utf8').digest('hex');
+
+/**
+ * The command handed to the ruOS jobs API (ADR-105), which owns detaching,
+ * output capture, exit status and cancel. The prompt is staged first with
+ * buildPrepare + buildPromptChunks (same base64 path); this only decodes it
+ * and runs the runner in the foreground of the job.
+ * @param {import('./types.mjs').RunSpec} spec
+ */
+export function buildJobCommand(spec) {
+ const d = runDir(spec.runId);
+ if (spec.runner !== 'claude') throw new RuosError('invalid-input', 'runner must be claude');
+ const model = assertModel(spec.model);
+ const budget = assertBudget(spec.maxBudgetUsd);
+ const flags = ['--output-format text'];
+ if (model) flags.push(`--model ${model}`);
+ if (budget !== undefined) flags.push(`--max-budget-usd ${budget.toFixed(2)}`);
+ return seal(`umask 077 ; cd ${d} || exit 3 ; base64 -d prompt.b64 > prompt.txt || exit 5 ; exec claude -p ${flags.join(' ')} < prompt.txt`);
+}
diff --git a/plugins/ruflo-ruos/scripts/lib/fleet-mcp.mjs b/plugins/ruflo-ruos/scripts/lib/fleet-mcp.mjs
index 07b8a4d437..07b184ac56 100644
--- a/plugins/ruflo-ruos/scripts/lib/fleet-mcp.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/fleet-mcp.mjs
@@ -1,52 +1,84 @@
// @ts-check
/**
- * Fleet MCP transport (ADR-405 transport 1) — the tenant-authenticated ruOS
- * fleet MCP over streamable HTTP. The caller's own bearer comes from the
- * environment (RUOS_MCP_URL + RUOS_MCP_TOKEN); nothing is embedded, and with
- * either unset the client refuses before touching the network.
+ * Fleet MCP client (ADR-405) — the tenant-authenticated ruOS fleet MCP over
+ * streamable HTTP. This is the ONLY transport from outside a tenant's Fly
+ * 6PN (laptops, workstations, CI). Remote `/mcp` is stateless, so every call
+ * is a single `tools/call` with no initialize handshake.
*
- * This client never talks to a desktop directly. In particular it never
- * reaches the desktop executor on :17870 (no per-tenant auth, ADR-070).
+ * Credentials: RUOS_MCP_URL + RUOS_MCP_TOKEN (a `ruos_mcp_` bearer), or the
+ * `@cognitum/ruos` credentials file (~/.config/ruos/credentials.json). Never
+ * embedded, logged or echoed; every error message is redacted.
+ *
+ * Never reaches the desktop executor on :17870 (no per-tenant auth, ruOS
+ * ADR-070) and refuses to issue deletion tools (deletes stay human).
*/
+import { readFileSync as nodeReadFileSync } from 'node:fs';
+import { join } from 'node:path';
import { RuosError } from './types.mjs';
import { FLY_ID_RE, DESKTOP_ID_RE } from './validate.mjs';
const PROTOCOL_VERSION = '2025-06-18';
+export const DEFAULT_MCP_URL = 'https://ruos.cognitum.one/mcp';
+/** Deletion is a human action (ruOS guard gates these); the swarm never sends them. */
+export const FORBIDDEN_TOOLS = Object.freeze(['desktop_delete', 'secret_delete']);
+/** Tools that need a `desktop:control` scoped token. */
+export const CONTROL_TOOLS = Object.freeze(['desktop_exec', 'desktop_start', 'desktop_stop', 'desktop_keepawake']);
/**
* @typedef {object} FleetMcpOptions
* @property {string|undefined} url
* @property {string|undefined} token
+ * @property {'env'|'credentials-file'|'none'=} source
* @property {typeof fetch=} fetchImpl
* @property {number=} requestTimeoutMs
*/
-/** @param {NodeJS.ProcessEnv} env */
-export function fleetConfigFromEnv(env) {
- return { url: env.RUOS_MCP_URL || undefined, token: env.RUOS_MCP_TOKEN || undefined };
+/**
+ * Resolve credentials: env first, then the @cognitum/ruos credentials file.
+ * @param {NodeJS.ProcessEnv} env
+ * @param {(p: string) => string=} readFile
+ * @returns {{ url: string|undefined, token: string|undefined, source: 'env'|'credentials-file'|'none' }}
+ */
+export function fleetConfigFromEnv(env, readFile = (p) => nodeReadFileSync(p, 'utf8')) {
+ if (env.RUOS_MCP_URL && env.RUOS_MCP_TOKEN) return { url: env.RUOS_MCP_URL, token: env.RUOS_MCP_TOKEN, source: 'env' };
+ const home = env.HOME || env.USERPROFILE;
+ if (home) {
+ try {
+ const c = JSON.parse(readFile(join(env.XDG_CONFIG_HOME || join(home, '.config'), 'ruos', 'credentials.json')));
+ const token = c.access_token ?? c.accessToken ?? c.token;
+ if (typeof token === 'string' && token.length > 0) {
+ const url = env.RUOS_MCP_URL || (typeof c.mcp_url === 'string' ? c.mcp_url : DEFAULT_MCP_URL);
+ return { url, token, source: 'credentials-file' };
+ }
+ } catch { /* no credentials file */ }
+ }
+ return { url: undefined, token: undefined, source: 'none' };
}
export class FleetMcpClient {
/** @param {FleetMcpOptions} opts */
constructor(opts) {
this.url = opts.url;
+ /** @private */
this.token = opts.token;
+ this.source = opts.source ?? (opts.token ? 'env' : 'none');
this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
this.requestTimeoutMs = opts.requestTimeoutMs ?? 330_000;
- /** @type {string|null} */
- this.sessionId = null;
this.nextId = 1;
- /** @type {Promise<void>|null} */
- this.ready = null;
}
get configured() {
return Boolean(this.url && this.token);
}
+ /** @param {string} s */
+ redact(s) {
+ return this.token ? s.split(this.token).join('[redacted]') : s;
+ }
+
assertConfigured() {
if (!this.configured) {
- throw new RuosError('not-configured', 'set RUOS_MCP_URL and RUOS_MCP_TOKEN to use the fleet MCP transport');
+ throw new RuosError('not-configured', 'set RUOS_MCP_URL + RUOS_MCP_TOKEN (a desktop:control ruos_mcp_ token, narrowest lifetime) or sign in with @cognitum/ruos');
}
const u = new URL(/** @type {string} */ (this.url));
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && (u.hostname === '127.0.0.1' || u.hostname === 'localhost'))) {
@@ -56,86 +88,64 @@ export class FleetMcpClient {
}
/**
- * @param {string} method
- * @param {Record<string, unknown>=} params
- * @param {boolean=} notification
+ * Call a fleet tool and return its structured payload (stateless tools/call).
+ * @param {string} name
+ * @param {Record<string, unknown>} args
+ * @returns {Promise<any>}
*/
- async rpc(method, params, notification = false) {
+ async callTool(name, args) {
+ if (FORBIDDEN_TOOLS.includes(name)) {
+ throw new RuosError('invalid-input', `${name} is a human action; ruflo-ruos never issues it`);
+ }
this.assertConfigured();
- /** @type {Record<string, string>} */
- const headers = {
- 'content-type': 'application/json',
- accept: 'application/json, text/event-stream',
- authorization: `Bearer ${this.token}`,
- 'mcp-protocol-version': PROTOCOL_VERSION,
- };
- if (this.sessionId) headers['mcp-session-id'] = this.sessionId;
- const body = notification
- ? { jsonrpc: '2.0', method, params: params ?? {} }
- : { jsonrpc: '2.0', id: this.nextId++, method, params: params ?? {} };
/** @type {Response} */
let res;
try {
res = await this.fetchImpl(/** @type {string} */ (this.url), {
method: 'POST',
- headers,
- body: JSON.stringify(body),
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ authorization: `Bearer ${this.token}`,
+ 'mcp-protocol-version': PROTOCOL_VERSION,
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id: this.nextId++, method: 'tools/call', params: { name, arguments: args } }),
signal: AbortSignal.timeout(this.requestTimeoutMs),
});
} catch (err) {
const e = /** @type {Error} */ (err);
- if (e && e.name === 'TimeoutError') throw new RuosError('timeout', 'fleet MCP request timed out', err);
- throw new RuosError('network-down', 'fleet MCP unreachable', err);
+ if (e && e.name === 'TimeoutError') throw new RuosError('timeout', 'fleet MCP request timed out');
+ throw new RuosError('network-down', 'fleet MCP unreachable');
}
- if (res.status === 401 || res.status === 403) {
- throw new RuosError('auth-expired', `fleet MCP refused the credential (HTTP ${res.status}); refresh RUOS_MCP_TOKEN`);
- }
- if (!res.ok && res.status !== 202) {
- throw new RuosError('tool-error', `fleet MCP HTTP ${res.status}`);
- }
- const sid = res.headers.get('mcp-session-id');
- if (sid) this.sessionId = sid;
- if (notification || res.status === 202) return undefined;
- const text = await res.text();
- const msg = parseRpcBody(text, res.headers.get('content-type') || '');
+ if (res.status === 401) throw new RuosError('auth-expired', 'fleet MCP refused the credential (HTTP 401); mint a new token');
+ if (res.status === 403) throw this.scopeError(name, 'HTTP 403');
+ if (!res.ok) throw new RuosError('tool-error', `fleet MCP HTTP ${res.status}`);
+ const msg = parseRpcBody(await res.text(), res.headers.get('content-type') || '');
if (msg.error) {
- const code = /unauthori|expired|invalid token/i.test(String(msg.error.message)) ? 'auth-expired' : 'tool-error';
- throw new RuosError(code, `fleet MCP error: ${String(msg.error.message).slice(0, 200)}`);
- }
- return msg.result;
- }
-
- async init() {
- if (!this.ready) {
- this.ready = (async () => {
- await this.rpc('initialize', {
- protocolVersion: PROTOCOL_VERSION,
- capabilities: {},
- clientInfo: { name: 'ruflo-ruos', version: '0.1.0' },
- });
- await this.rpc('notifications/initialized', {}, true);
- })();
- this.ready.catch(() => { this.ready = null; });
+ const text = this.redact(String(msg.error.message ?? ''));
+ if (/scope|forbidden|desktop:control/i.test(text)) throw this.scopeError(name, text);
+ const code = /unauthori|expired|invalid token/i.test(text) ? 'auth-expired' : 'tool-error';
+ throw new RuosError(code, `fleet MCP error: ${text.slice(0, 200)}`);
}
- return this.ready;
- }
-
- /**
- * Call a fleet tool and return its structured payload.
- * @param {string} name
- * @param {Record<string, unknown>} args
- * @returns {Promise<any>}
- */
- async callTool(name, args) {
- await this.init();
- const result = /** @type {any} */ (await this.rpc('tools/call', { name, arguments: args }));
+ const result = /** @type {any} */ (msg.result);
const payload = toolPayload(result);
if (result && result.isError) {
- const text = typeof payload === 'string' ? payload : JSON.stringify(payload);
+ const text = this.redact(typeof payload === 'string' ? payload : JSON.stringify(payload));
+ if (/scope|desktop:control/i.test(text)) throw this.scopeError(name, text);
throw classifyToolError(text);
}
return payload;
}
+
+ /**
+ * @param {string} tool
+ * @param {string} detail
+ */
+ scopeError(tool, detail) {
+ return CONTROL_TOOLS.includes(tool)
+ ? new RuosError('insufficient-scope', `${tool} needs a desktop:control token; the current token can only read status (${detail.slice(0, 80)})`)
+ : new RuosError('auth-expired', `fleet MCP refused the credential (${detail.slice(0, 80)})`);
+ }
}
/**
@@ -174,21 +184,23 @@ export function toolPayload(result) {
/** @param {string} text */
export function classifyToolError(text) {
const t = text.slice(0, 300);
- if (/unauthori|expired|forbidden|scope/i.test(t)) return new RuosError('auth-expired', `fleet: ${t}`);
+ if (/unauthori|expired|forbidden/i.test(t)) return new RuosError('auth-expired', `fleet: ${t}`);
if (/not running|stopped|asleep|suspended|not started|no heartbeat/i.test(t)) return new RuosError('desktop-stopped', `fleet: ${t}`);
- if (/not found|not owned|unknown machine/i.test(t)) return new RuosError('not-owned', `fleet: ${t}`);
+ if (/not found|not owned|unknown machine|no shell|lite/i.test(t)) return new RuosError('not-owned', `fleet: ${t}`);
if (/timed? ?out/i.test(t)) return new RuosError('timeout', `fleet: ${t}`);
return new RuosError('tool-error', `fleet: ${t}`);
}
/**
+ * Hosted desktops only. Lite browsers (separate `lite_browsers` array,
+ * `lite-` ids) have no shell and are never host candidates.
* @param {any} raw
* @returns {import('./types.mjs').Desktop[]}
*/
export function normalizeDesktops(raw) {
const list = raw && Array.isArray(raw.desktops) ? raw.desktops : [];
return list
- .filter((/** @type {any} */ d) => typeof d.machine_id === 'string' && DESKTOP_ID_RE.test(d.machine_id))
+ .filter((/** @type {any} */ d) => typeof d.machine_id === 'string' && DESKTOP_ID_RE.test(d.machine_id) && d.kind !== 'lite_browser')
.map((/** @type {any} */ d) => ({
id: d.machine_id,
flyMachineId: typeof d.fly_machine_id === 'string' && FLY_ID_RE.test(d.fly_machine_id) ? d.fly_machine_id : null,
@@ -202,20 +214,40 @@ export function normalizeDesktops(raw) {
}
/**
+ * desktop_exec (ruOS ADR-081) returns `{status, exitCode, stdout, ...}` where
+ * stdout is framed: a `▶ run: <command>` echo first, then output, then
+ * `✓ SUCCESS…` / `📝 transcript:` trailers, and `… [output truncated]` when
+ * the ~4 KiB head cap hits. The echo would let markers inside the command
+ * false-match, so the frame is stripped here (measured live 2026-10-01).
* @param {any} raw
* @returns {import('./types.mjs').ExecResult}
*/
export function normalizeExec(raw) {
- if (typeof raw === 'string') return { stdout: raw, stderr: '', exitCode: null };
- const r = raw ?? {};
- const exit = r.exit_code ?? r.exitCode ?? r.code ?? r.status;
+ const r = typeof raw === 'string' ? { stdout: raw } : (raw ?? {});
+ const exit = r.exitCode ?? r.exit_code ?? null;
+ let lines = String(r.stdout ?? r.output ?? '').split('\n');
+ let truncated = false;
+ if (lines.length && lines[0].startsWith('▶ run:')) lines = lines.slice(1);
+ lines = lines.filter((l) => {
+ if (/^… \[output truncated\]/.test(l)) { truncated = true; return false; }
+ return !/^(✓|✗|⚠) [A-Z]+ in \d|^📝 transcript:/.test(l);
+ });
return {
- stdout: String(r.stdout ?? r.output ?? ''),
+ stdout: lines.join('\n').replace(/^\n+/, ''),
stderr: String(r.stderr ?? ''),
exitCode: typeof exit === 'number' ? exit : null,
+ truncated,
};
}
+/**
+ * @typedef {object} LlmRoute
+ * @property {string|null} route
+ * @property {string|null} provider
+ * @property {string|null} gateway
+ * @property {boolean} keyPresent
+ */
+
/**
* Fleet control-plane operations bound to one client.
* @param {FleetMcpClient} client
@@ -229,6 +261,10 @@ export function createFleet(client) {
keepAwake: async (fly, minutes) => {
await client.callTool('desktop_keepawake', { machine: fly, minutes });
},
+ llmRoute: async () => {
+ const r = (await client.callTool('llm_route_get', {})) ?? {};
+ return { route: r.route ?? null, provider: r.provider ?? null, gateway: r.gateway ?? null, keyPresent: r.key_present === true };
+ },
};
}
@@ -241,7 +277,7 @@ export function createFleetTransport(client) {
kind: 'fleet-mcp',
exec: async (desktop, command, timeoutSecs) => {
const timeout = Math.max(1, Math.min(300, Math.floor(timeoutSecs)));
- // desktop_exec's `machine` takes the Fly machine id (desktop_connect_info).
+ // Verified live: desktop_exec accepts the Fly machine id as `machine`.
const machine = desktop.flyMachineId ?? desktop.id;
return normalizeExec(await client.callTool('desktop_exec', { command, machine, timeout_secs: timeout }));
},
diff --git a/plugins/ruflo-ruos/scripts/lib/jobs.mjs b/plugins/ruflo-ruos/scripts/lib/jobs.mjs
new file mode 100644
index 0000000000..8cb45064dc
--- /dev/null
+++ b/plugins/ruflo-ruos/scripts/lib/jobs.mjs
@@ -0,0 +1,176 @@
+// @ts-check
+/**
+ * Job transports (ADR-405 §Jobs). The adapter drives a JobTransport; two
+ * implementations:
+ *
+ * - ExecPollTransport — available now. Stages the prompt and launches a
+ * detached `nohup setsid` runner via desktop_exec, then polls the log by
+ * byte offset. All strings come from command-builder.mjs.
+ * - JobsApiTransport — ruOS ADR-105 jobs API (`feat/ruos-jobs`), used when
+ * feature-detected. The server owns detach, capture, exit, cancel,
+ * keepawake and audit. Backends: REST with the tenant token, or the local
+ * stdio `@cognitum/ruos` MCP server (`desktop_job_*` — stdio-only, never on
+ * the remote connector). The run id is the idempotency key.
+ */
+import { RuosError } from './types.mjs';
+import { assertRunId, assertInt } from './validate.mjs';
+import {
+ buildPrepare, buildPromptChunks, buildLaunch, buildPoll, buildStop, buildJobCommand,
+ parsePoll, parseLaunch, parseStopped, commandSha256,
+} from './command-builder.mjs';
+
+/**
+ * @param {import('./types.mjs').Transport} exec
+ * @param {import('./types.mjs').Desktop} desktop
+ * @param {import('./types.mjs').RunSpec} spec
+ */
+async function stagePrompt(exec, desktop, spec) {
+ const chunks = buildPromptChunks(spec.runId, spec.prompt);
+ const run = async (/** @type {string} */ c) => {
+ const r = await exec.exec(desktop, c, 30);
+ if (r.exitCode !== null && r.exitCode !== 0) throw new RuosError('remote-error', `staging failed (exit ${r.exitCode})`);
+ return r;
+ };
+ await run(buildPrepare(spec.runId));
+ for (const c of chunks.commands) await run(c);
+ return chunks;
+}
+
+/**
+ * @param {import('./types.mjs').Transport} exec
+ * @returns {import('./types.mjs').JobTransport}
+ */
+export function createExecPollTransport(exec) {
+ return {
+ kind: 'exec-poll',
+ async start(desktop, spec) {
+ const chunks = await stagePrompt(exec, desktop, spec);
+ const cmd = buildLaunch(spec);
+ const lr = await exec.exec(desktop, cmd, 60);
+ const launched = parseLaunch(lr.stdout);
+ if (launched.noRunner) throw new RuosError('remote-error', 'claude is not installed on the desktop');
+ if (lr.exitCode !== null && lr.exitCode !== 0) throw new RuosError('remote-error', `launch failed (exit ${lr.exitCode})`);
+ if (launched.sha256 !== chunks.sha256) throw new RuosError('remote-error', 'prompt integrity check failed (sha256 mismatch)');
+ if (launched.pid === null) throw new RuosError('remote-error', 'runner did not report a pid');
+ return { jobId: spec.runId, commandSha256: commandSha256(cmd) };
+ },
+ async poll(desktop, jobId, offset) {
+ const p = parsePoll((await exec.exec(desktop, buildPoll(jobId, offset), 30)).stdout);
+ if (p === 'norun') throw new RuosError('remote-error', 'run directory vanished on the desktop');
+ const next = offset + p.chunk.length;
+ /** @type {import('./types.mjs').JobState} */
+ const state = p.exitCode !== null ? (p.exitCode === 0 ? 'exited' : 'failed') : p.alive ? 'running' : 'lost';
+ return { chunk: p.chunk, nextOffset: next, running: state === 'running', state, exitCode: p.exitCode, truncated: false };
+ },
+ async cancel(desktop, jobId) {
+ return parseStopped((await exec.exec(desktop, buildStop(jobId), 30)).stdout);
+ },
+ };
+}
+
+/**
+ * Minimal backend contract for the jobs API (REST or stdio MCP adapter).
+ * @typedef {object} JobsBackend
+ * @property {(body: { machine: string, command: string, timeout_secs: number, idempotency_key: string }) => Promise<{ job_id: string }>} create
+ * @property {(jobId: string, offset: number, max: number) => Promise<{ chunk: string, next_offset: number, running: boolean, state: string, exit_code: number|null, truncated: boolean }>} read
+ * @property {(jobId: string) => Promise<void>} cancel
+ * @property {(machine: string) => Promise<unknown[]>} list
+ */
+
+const STATES = new Set(['queued', 'running', 'exited', 'failed', 'cancelled', 'stopped', 'lost']);
+export const JOBS_CHUNK_MAX = 65536;
+
+/**
+ * @param {JobsBackend} backend
+ * @param {import('./types.mjs').Transport} exec used only to stage the prompt file
+ * @returns {import('./types.mjs').JobTransport}
+ */
+export function createJobsApiTransport(backend, exec) {
+ return {
+ kind: 'jobs-api',
+ async start(desktop, spec) {
+ await stagePrompt(exec, desktop, spec);
+ const command = buildJobCommand(spec);
+ const { job_id } = await backend.create({
+ machine: desktop.flyMachineId ?? desktop.id,
+ command,
+ timeout_secs: assertInt(spec.timeoutSecs, 1, 21600, 'timeoutSecs'),
+ idempotency_key: assertRunId(spec.runId),
+ });
+ if (typeof job_id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(job_id)) throw new RuosError('remote-error', 'jobs API returned an invalid job id');
+ return { jobId: job_id, commandSha256: commandSha256(command) };
+ },
+ async poll(_desktop, jobId, offset) {
+ const r = await backend.read(jobId, offset, JOBS_CHUNK_MAX);
+ const state = STATES.has(r.state) ? /** @type {import('./types.mjs').JobState} */ (r.state) : 'lost';
+ const chunk = Buffer.from(String(r.chunk ?? ''), 'base64');
+ // Trust byte offsets, not chunk length: the server may skip a capped tail.
+ const nextOffset = typeof r.next_offset === 'number' && r.next_offset >= offset ? r.next_offset : offset + chunk.length;
+ return { chunk, nextOffset, running: r.running === true, state, exitCode: typeof r.exit_code === 'number' ? r.exit_code : null, truncated: r.truncated === true };
+ },
+ async cancel(_desktop, jobId) {
+ await backend.cancel(jobId);
+ return true;
+ },
+ };
+}
+
+/**
+ * REST backend for the jobs API with the tenant token. Status mapping:
+ * 401 → auth-expired, 403 → insufficient-scope, 404 → not-owned (another
+ * tenant's id or gone — never retried), 409/429 → capacity (per-tenant
+ * RUOS_JOBS_MAX_CONCURRENT cap; the adapter backs off).
+ * @param {{ baseUrl: string, token: string, fetchImpl?: typeof fetch }} o
+ * @returns {JobsBackend & { detect: (machine: string) => Promise<boolean> }}
+ */
+export function createRestJobsBackend(o) {
+ const f = o.fetchImpl ?? globalThis.fetch;
+ const base = new URL('/api/v1/desktop/jobs', o.baseUrl).toString();
+ /**
+ * @param {string} method
+ * @param {string} url
+ * @param {unknown=} body
+ */
+ const call = async (method, url, body) => {
+ /** @type {Response} */
+ let res;
+ try {
+ res = await f(url, {
+ method,
+ headers: { authorization: `Bearer ${o.token}`, 'content-type': 'application/json', accept: 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(60_000),
+ });
+ } catch {
+ throw new RuosError('network-down', 'ruOS jobs API unreachable');
+ }
+ if (res.status === 401) throw new RuosError('auth-expired', 'jobs API refused the credential');
+ if (res.status === 403) throw new RuosError('insufficient-scope', 'jobs API needs a desktop:control token');
+ if (res.status === 404) throw new RuosError('not-owned', 'job not found (not yours, or gone)');
+ if (res.status === 409 || res.status === 429) throw new RuosError('capacity', 'per-tenant job concurrency cap reached');
+ if (!res.ok) throw new RuosError('tool-error', `jobs API HTTP ${res.status}`);
+ const text = await res.text();
+ return text ? JSON.parse(text) : {};
+ };
+ /** @param {string} id */
+ const jobUrl = (id) => `${base}/${encodeURIComponent(id)}`;
+ return {
+ create: (body) => call('POST', base, body),
+ read: (id, offset, max) => call('GET', `${jobUrl(id)}?offset=${offset}&max=${max}`),
+ cancel: async (id) => { await call('DELETE', jobUrl(id)); },
+ list: async (machine) => {
+ const r = await call('GET', `${base}?machine=${encodeURIComponent(machine)}`);
+ return Array.isArray(r.jobs) ? r.jobs : Array.isArray(r) ? r : [];
+ },
+ /** Feature detection: the list route exists → the jobs API is deployed. */
+ detect: async (machine) => {
+ try {
+ await call('GET', `${base}?machine=${encodeURIComponent(machine)}`);
+ return true;
+ } catch (e) {
+ if (e instanceof RuosError && (e.code === 'auth-expired' || e.code === 'insufficient-scope')) throw e;
+ return false;
+ }
+ },
+ };
+}
diff --git a/plugins/ruflo-ruos/scripts/lib/ledger.mjs b/plugins/ruflo-ruos/scripts/lib/ledger.mjs
index aec5e6eab2..8fe59b0840 100644
--- a/plugins/ruflo-ruos/scripts/lib/ledger.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/ledger.mjs
@@ -11,6 +11,8 @@
*
* The plugin additionally owns `.claude-flow/ruos/`:
* events.jsonl append-only lifecycle events (ids/sizes/states only)
+ * audit.jsonl one record per run: runId, desktop, command sha256,
+ * start/end, exit, bytes (ruOS does not audit detached output)
* hosts.json snapshot of the caller's desktops + which agents run there
* runs/<id>.log local copy of the remote output (mode 0600)
* If ruflo's CLI cannot be resolved, or policy denies a call, the ledger
@@ -37,6 +39,7 @@ import { pathToFileURL } from 'node:url';
* @property {(desktops: import('./types.mjs').Desktop[]) => void} snapshotHosts merge host state, keep agent placements
* @property {(desktopId: string|null, agentId: string, present: boolean) => void} setHostAgent null desktopId + present=false removes the agent from every host
* @property {(runId: string, chunk: Buffer) => void} appendOutput
+ * @property {(record: Record<string, unknown>) => void} audit per-run record → audit.jsonl (no prompt/output text)
* @property {string[]} warnings
*/
@@ -191,6 +194,10 @@ export function createLedger({ cwd, callTool, now = () => new Date() }) {
hosts.set(desktopId, { ...h, agents: present ? [...rest, agentId] : rest });
});
},
+ audit(record) {
+ ensure();
+ appendFileSync(join(dir, 'audit.jsonl'), JSON.stringify({ ts: now().toISOString(), ...record }) + '\n', { mode: 0o600 });
+ },
appendOutput(runId, chunk) {
ensure();
appendFileSync(join(runsDir, `${runId}.log`), chunk, { mode: 0o600 });
diff --git a/plugins/ruflo-ruos/scripts/lib/types.mjs b/plugins/ruflo-ruos/scripts/lib/types.mjs
index 2c542f76c8..106635b1f9 100644
--- a/plugins/ruflo-ruos/scripts/lib/types.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/types.mjs
@@ -26,6 +26,7 @@
* @property {string} stdout
* @property {string} stderr
* @property {number|null} exitCode
+ * @property {boolean=} truncated the fleet head-capped stdout
*/
/**
@@ -41,6 +42,35 @@
* @property {(id: string) => Promise<void>} start
* @property {(id: string) => Promise<void>} stop
* @property {(flyMachineId: string|null, minutes: number) => Promise<void>} keepAwake
+ * @property {() => Promise<{ route: string|null, provider: string|null, gateway: string|null, keyPresent: boolean }>} llmRoute
+ */
+
+/**
+ * A detached job on a desktop. Two implementations (jobs.mjs):
+ * ExecPollTransport (nohup + offset polling over desktop_exec, available
+ * now) and JobsApiTransport (ruOS ADR-105 jobs API, feature-detected).
+ * @typedef {object} JobStart
+ * @property {string} jobId
+ * @property {string} commandSha256 hash of the launched command (audit record)
+ */
+/**
+ * @typedef {'queued'|'running'|'exited'|'failed'|'cancelled'|'stopped'|'lost'} JobState
+ */
+/**
+ * @typedef {object} JobPoll
+ * @property {Buffer} chunk
+ * @property {number} nextOffset
+ * @property {boolean} running
+ * @property {JobState} state
+ * @property {number|null} exitCode
+ * @property {boolean} truncated
+ */
+/**
+ * @typedef {object} JobTransport
+ * @property {'exec-poll'|'jobs-api'} kind
+ * @property {(desktop: Desktop, spec: RunSpec & { timeoutSecs: number }) => Promise<JobStart>} start
+ * @property {(desktop: Desktop, jobId: string, offset: number) => Promise<JobPoll>} poll
+ * @property {(desktop: Desktop, jobId: string) => Promise<boolean>} cancel
*/
/**
@@ -50,7 +80,9 @@
* @property {string} desktopId
* @property {string} desktopName
* @property {'fleet-mcp'|'ssh'} transport
+ * @property {'exec-poll'|'jobs-api'=} jobs
* @property {string} runId
+ * @property {string|null=} stopAt next forced 23:00 America/Toronto stop (cloud desktops)
*/
/**
@@ -82,7 +114,7 @@
* @property {string=} state
*/
-/** @typedef {'not-configured'|'invalid-input'|'not-owned'|'ambiguous'|'confirm-required'|'auth-expired'|'network-down'|'desktop-stopped'|'auto-stopped'|'autostop-window'|'tool-error'|'remote-error'|'timeout'} RuosErrorCode */
+/** @typedef {'not-configured'|'invalid-input'|'not-owned'|'ambiguous'|'confirm-required'|'auth-expired'|'network-down'|'desktop-stopped'|'auto-stopped'|'autostop-window'|'tool-error'|'remote-error'|'timeout'|'insufficient-scope'|'capacity'|'llm-unconfigured'} RuosErrorCode */
export class RuosError extends Error {
/**
diff --git a/plugins/ruflo-ruos/scripts/lib/validate.mjs b/plugins/ruflo-ruos/scripts/lib/validate.mjs
index 1c0956ef18..d46b7d2250 100644
--- a/plugins/ruflo-ruos/scripts/lib/validate.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/validate.mjs
@@ -123,11 +123,10 @@ export function resolveDesktop(owned, ref) {
}
/**
- * A deterministic-length, path-safe run id.
- * @param {() => number} now
+ * A path-safe run id with 128 random bits; also the jobs-API idempotency key.
* @param {(n: number) => Buffer} randomBytes
* @returns {string}
*/
-export function newRunId(now, randomBytes) {
- return `r-${now().toString(36)}-${randomBytes(4).toString('hex')}`;
+export function newRunId(randomBytes) {
+ return `r-${randomBytes(16).toString('hex')}`;
}
diff --git a/plugins/ruflo-ruos/scripts/smoke.sh b/plugins/ruflo-ruos/scripts/smoke.sh
index fba54cb880..8a1ccce152 100755
--- a/plugins/ruflo-ruos/scripts/smoke.sh
+++ b/plugins/ruflo-ruos/scripts/smoke.sh
@@ -30,7 +30,7 @@ long=$(find "$ROOT/scripts" "$ROOT/tests" -name '*.mjs' -exec awk 'END{if(NR>500
step "4. no source path opens the :17870 executor"
# The only allowed mentions are refusals/assertions, never a URL or connect.
-hits=$(grep -rnE "17870" "$ROOT/scripts" --include="*.mjs" | grep -vE "refus|never|ADR-070|includes\('17870'\)|port === '17870'" || true)
+hits=$(grep -rnE "17870" "$ROOT/scripts" --include="*.mjs" | grep -viE "refus|never|ADR-070|includes\('17870'\)|port === '17870'" || true)
[[ -z "$hits" ]] && ok || bad "$hits"
step "5. ssh is spawned with a fixed argv and shell:false"
diff --git a/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md b/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md
index 68da21db9c..95286c935a 100644
--- a/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md
+++ b/plugins/ruflo-ruos/skills/ruos-host-run/SKILL.md
@@ -2,7 +2,7 @@
name: ruos-host-run
description: Run a ruflo swarm agent on the user's own ruOS cloud desktop through the tenant-authenticated fleet MCP, stream its output, and record it in ruflo's swarm state. Use when the user wants an agent to run on a ruOS desktop, asks to "run this on my ruOS desktop", or places a swarm agent on a remote ruOS host.
argument-hint: "<desktop> <task>"
-allowed-tools: Bash(node *) mcp__ruos__desktop_status mcp__ruos__desktop_exec mcp__ruos__desktop_keepawake mcp__ruos__desktop_start
+allowed-tools: Bash(node *) mcp__ruos__desktop_status mcp__ruos__desktop_exec mcp__ruos__desktop_keepawake mcp__ruos__desktop_start mcp__ruos__llm_route_get
---
# Run a ruflo agent on a ruOS desktop (session path, ADR-405)
@@ -15,6 +15,11 @@ Transport rules — non-negotiable:
`CLI` below is `node "${CLAUDE_PLUGIN_ROOT}/scripts/cli.mjs"`.
+`desktop_exec` output is framed: the first line echoes your command (`▶ run: …`), and the
+last lines are `✓ SUCCESS…` and `📝 transcript:`. Read markers only from their own lines,
+never from the echo. Output is capped at about 4 KiB, so `poll` returns 2 KiB slices.
+Never call `desktop_delete` or `secret_delete`; deleting is the user's job.
+
1. **Pick the host.** Call `desktop_status`. Resolve the user's desktop by `machine_id`,
`fly_machine_id` or exact `display_name`; if it is not in that list, stop. Save the raw
JSON to a temp file (`status.json`) for step 4.
@@ -30,6 +35,8 @@ Transport rules — non-negotiable:
- `CLI record start --run <runId> --desktop "<ref>" --desktop-status-file status.json --task "<one-line summary>"`
— registers the agent through ruflo's `agent_spawn` (with `config.host`) and claims
`ruos-run-<runId>` via `claims_claim`.
+ Before launching, call `llm_route_get`. Stop if the desktop has no route. If the gateway is
+ "unconfigured" but the route is "shared", warn and continue.
5. **Launch.** Call `desktop_exec` with each `steps[i]` in order (`machine` = the desktop's
`fly_machine_id`). The last step prints `RUOS_SHA:<hash>` — it must equal
`promptSha256`, else `desktop_exec` the `stop` string and abort. `RUOS_NO_RUNNER` means
diff --git a/plugins/ruflo-ruos/tests/adapter.test.mjs b/plugins/ruflo-ruos/tests/adapter.test.mjs
index 3ff91c1750..661e268890 100644
--- a/plugins/ruflo-ruos/tests/adapter.test.mjs
+++ b/plugins/ruflo-ruos/tests/adapter.test.mjs
@@ -2,6 +2,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { RuosHostAdapter, isUp } from '../scripts/lib/adapter.mjs';
+import { createExecPollTransport } from '../scripts/lib/jobs.mjs';
import { buildPromptChunks } from '../scripts/lib/command-builder.mjs';
import { RuosError } from '../scripts/lib/types.mjs';
import { desktop, fakeClock, fakeFleet, fakeTransport, fakeLedger, ok, DESKTOP_ID, FLY_ID } from './fakes.mjs';
@@ -23,7 +24,9 @@ function remote(polls, o = {}) {
if (cmd.startsWith("printf '%s'")) return ok('');
if (cmd.includes('RUOS_NO_RUNNER')) return ok(o.launch ?? `RUOS_SHA:${o.sha ?? SHA}\nRUOS_PID:4242\n`);
if (cmd.includes('RUOS_POLL')) {
- const p = polls[Math.min(i++, polls.length - 1)];
+ // Once the script is exhausted, repeat the last state with no new
+ // bytes — what a real desktop returns once the offset caught up.
+ const p = i < polls.length ? polls[i++] : polls[polls.length - 1].replace(/:[A-Za-z0-9+/=]*$/, ':');
if (p === 'THROW') throw new RuosError('network-down', 'gone');
return ok(p);
}
@@ -39,7 +42,7 @@ function setup(over = {}) {
const fleet = over.fleet ?? fakeFleet(ds);
const transport = over.transport ?? remote([`RUOS_POLL:-:6:1:${b64('hello ')}`, 'RUOS_POLL:-:6:1:', `RUOS_POLL:0:12:0:${b64('world\n')}`]);
const ledger = fakeLedger();
- const adapter = new RuosHostAdapter({ fleet, transport, ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });
+ const adapter = new RuosHostAdapter({ fleet, jobs: createExecPollTransport(transport), ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });
return { adapter, fleet, transport, ledger, clock };
}
@@ -59,7 +62,8 @@ test('happy path: launch, stream, ledger + claims, keepawake', async () => {
assert.deepEqual(names.filter((n) => n !== 'snapshotHosts'), ['claim', 'registerAgent', 'setHostAgent', 'setHostAgent', 'updateAgent', 'release']);
assert.deepEqual(ledger.calls.filter((c) => c[0] === 'setHostAgent').map((c) => c[1][2]), [true, false], 'placed, then removed');
const host = /** @type {any} */ (ledger.calls.find((c) => c[0] === 'registerAgent'))[1][2];
- assert.deepEqual(host, { kind: 'ruos', desktopId: DESKTOP_ID, desktopName: 'Work Desktop', transport: 'fleet-mcp', runId: RUN });
+ assert.deepEqual(host, { kind: 'ruos', desktopId: DESKTOP_ID, desktopName: 'Work Desktop', transport: 'fleet-mcp', jobs: 'exec-poll', runId: RUN, stopAt: '2026-10-02T03:00:00.000Z' });
+ assert.equal(out.stopAt, '2026-10-02T03:00:00.000Z', 'the 23:00 deadline is surfaced in swarm state');
assert.deepEqual(ledger.events.map((e) => e.type), ['run.started', 'run.output', 'run.output', 'run.completed']);
assert.ok(ledger.events.every((e) => !JSON.stringify(e).includes(PROMPT)), 'events never carry the prompt');
assert.deepEqual(fleet.calls.find((c) => c[0] === 'keepAwake'), ['keepAwake', [FLY_ID, 15]]);
@@ -85,7 +89,7 @@ test('--start wakes the desktop and waits for a fresh heartbeat (not `ready`)',
fleet.start = async (/** @type {string} */ id) => { started = true; return origStart(id); };
const ledger = fakeLedger();
const transport = remote([`RUOS_POLL:0:2:0:${b64('ok')}`]);
- const adapter = new RuosHostAdapter({ fleet, transport, ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });
+ const adapter = new RuosHostAdapter({ fleet, jobs: createExecPollTransport(transport), ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });
const out = await adapter.run({ ...base, allowStart: true });
assert.equal(out.status, 'completed');
assert.deepEqual(fleet.calls.find((/** @type {any} */ c) => c[0] === 'start'), ['start', [DESKTOP_ID]]);
@@ -97,7 +101,7 @@ test('desktop auto-stopped mid-run is reported as auto-stopped and released', as
let calls = 0;
const fleet = fakeFleet(() => [desktop(++calls <= 1 ? { heartbeatAt: Math.floor(clock.now() / 1000) } : { state: 'stopped', heartbeatStatus: 'asleep' })]);
const ledger = fakeLedger();
- const adapter = new RuosHostAdapter({ fleet, transport: remote([`RUOS_POLL:-:2:1:${b64('hi')}`, 'THROW']), ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });
+ const adapter = new RuosHostAdapter({ fleet, jobs: createExecPollTransport(remote([`RUOS_POLL:-:2:1:${b64('hi')}`, 'THROW'])), ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });
await assert.rejects(adapter.run(base), (e) => e instanceof RuosError && e.code === 'auto-stopped');
assert.ok(ledger.calls.some((c) => c[0] === 'release'), 'claim released on failure');
assert.equal(ledger.events.at(-1).type, 'run.failed');
@@ -112,7 +116,7 @@ test('auth expired mid-run surfaces as auth-expired', async () => {
if (cmd.includes('RUOS_NO_RUNNER')) return ok(`RUOS_SHA:${SHA}\nRUOS_PID:1\n`);
return ok('RUOS_PREPARED\n');
});
- adapter.transport = t;
+ adapter.jobs = createExecPollTransport(t);
await assert.rejects(adapter.run(base), (e) => e instanceof RuosError && e.code === 'auth-expired');
});
@@ -136,7 +140,7 @@ test('a run that would cross the 23:00 Toronto auto-stop is refused unless overr
const clock = fakeClock(Date.parse('2026-10-02T02:45:00Z')); // Thu 22:45 EDT
const fleet = fakeFleet([desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })]);
const transport = remote([`RUOS_POLL:0:0:0:`]);
- const adapter = new RuosHostAdapter({ fleet, transport, ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });
+ const adapter = new RuosHostAdapter({ fleet, jobs: createExecPollTransport(transport), ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });
await assert.rejects(adapter.run({ ...base, timeoutSecs: 3600 }), (e) => e instanceof RuosError && e.code === 'autostop-window');
assert.equal(transport.commands.length, 0);
const out = await adapter.run({ ...base, timeoutSecs: 3600, ignoreAutoStop: true });
@@ -192,7 +196,7 @@ test('runner killed without an exit code is detected, not waited out', async ()
test('enrolled devices (no Fly id) are not subject to the cloud auto-stop window', async () => {
const clock = fakeClock(Date.parse('2026-10-02T02:45:00Z'));
const fleet = fakeFleet([desktop({ flyMachineId: null, heartbeatAt: Math.floor(clock.now() / 1000) })]);
- const adapter = new RuosHostAdapter({ fleet, transport: remote(['RUOS_POLL:0:0:0:']), ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });
+ const adapter = new RuosHostAdapter({ fleet, jobs: createExecPollTransport(remote(['RUOS_POLL:0:0:0:'])), ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });
assert.equal((await adapter.run({ ...base, timeoutSecs: 3600 })).status, 'completed');
});
diff --git a/plugins/ruflo-ruos/tests/command-builder.test.mjs b/plugins/ruflo-ruos/tests/command-builder.test.mjs
index e776305372..d5e43684c2 100644
--- a/plugins/ruflo-ruos/tests/command-builder.test.mjs
+++ b/plugins/ruflo-ruos/tests/command-builder.test.mjs
@@ -21,6 +21,7 @@ const HOSTILE = [
'a\r\ntouch /tmp/ruflo-ruos-pwned',
'${IFS}touch${IFS}/tmp/ruflo-ruos-pwned',
'| touch /tmp/ruflo-ruos-pwned &',
+ "'\\'' ; touch /tmp/ruflo-ruos-pwned ; sh -c '", // sh -c '...' quote-break attempt
'ünïcödé ✓ 🚀 ‮⁦ rtl',
'\\x27 \\" %s %n',
];
diff --git a/plugins/ruflo-ruos/tests/fakes.mjs b/plugins/ruflo-ruos/tests/fakes.mjs
index 4a1ea1e52b..1cfea80c0a 100644
--- a/plugins/ruflo-ruos/tests/fakes.mjs
+++ b/plugins/ruflo-ruos/tests/fakes.mjs
@@ -45,6 +45,7 @@ export function fakeFleet(desktops) {
start: async (/** @type {string} */ id) => { calls.push(['start', [id]]); },
stop: async (/** @type {string} */ id) => { calls.push(['stop', [id]]); },
keepAwake: async (/** @type {string|null} */ f, /** @type {number} */ m) => { calls.push(['keepAwake', [f, m]]); },
+ llmRoute: async () => { calls.push(['llmRoute', []]); return { route: 'shared', provider: 'cognitum', gateway: 'unconfigured', keyPresent: false }; },
};
}
@@ -88,5 +89,7 @@ export function fakeLedger() {
snapshotHosts: (/** @type {unknown[]} */ ...a) => { calls.push(['snapshotHosts', a]); },
setHostAgent: (/** @type {unknown[]} */ ...a) => { calls.push(['setHostAgent', a]); },
appendOutput: (/** @type {string} */ _r, /** @type {Buffer} */ c) => { output.push(c); },
+ audits: /** @type {any[]} */ ([]),
+ audit(/** @type {any} */ r) { this.audits.push(r); },
};
}
diff --git a/plugins/ruflo-ruos/tests/ledger-cli.test.mjs b/plugins/ruflo-ruos/tests/ledger-cli.test.mjs
index 6a915cefb6..5ece0e9120 100644
--- a/plugins/ruflo-ruos/tests/ledger-cli.test.mjs
+++ b/plugins/ruflo-ruos/tests/ledger-cli.test.mjs
@@ -74,7 +74,9 @@ test('real ruflo CLI: agent store carries config.host and claims round-trip', {
assert.equal(start.swarmLedger, 'cli');
const store = JSON.parse(readFileSync(join(cwd, '.claude-flow/agents/store.json'), 'utf8'));
assert.equal(store.agents['ruos-int-1'].status, 'busy');
- assert.deepEqual(store.agents['ruos-int-1'].config.host, { kind: 'ruos', desktopId: DESKTOP_ID, desktopName: 'Work Desktop', transport: 'fleet-mcp', runId: 'r-ledger-0002' });
+ const h = store.agents['ruos-int-1'].config.host;
+ assert.deepEqual({ ...h, stopAt: undefined }, { kind: 'ruos', desktopId: DESKTOP_ID, desktopName: 'Work Desktop', transport: 'fleet-mcp', jobs: 'exec-poll', runId: 'r-ledger-0002', stopAt: undefined });
+ assert.match(h.stopAt, /T0[34]:00:00\.000Z$/, '23:00 Toronto deadline recorded');
const claims = JSON.parse(readFileSync(join(cwd, '.claude-flow/claims/claims.json'), 'utf8'));
assert.equal(claims.claims['ruos-run-r-ledger-0002'].claimant.agentId, 'ruos-int-1');
run(['record', 'output', '--run', 'r-ledger-0002', '--agent-id', 'ruos-int-1', '--b64', Buffer.from('hi').toString('base64')]);
diff --git a/plugins/ruflo-ruos/tests/requirements.test.mjs b/plugins/ruflo-ruos/tests/requirements.test.mjs
new file mode 100644
index 0000000000..74ee625620
--- /dev/null
+++ b/plugins/ruflo-ruos/tests/requirements.test.mjs
@@ -0,0 +1,190 @@
+// @ts-check
+/**
+ * Requirements from the live E2E (2026-10-01) and the ruOS lane's design
+ * rules: exec framing, jobs-API contract (ADR-105), no deletion tools,
+ * credentials + redaction, Lite filtering, LLM route check, audit record.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { FleetMcpClient, fleetConfigFromEnv, normalizeExec, normalizeDesktops, FORBIDDEN_TOOLS } from '../scripts/lib/fleet-mcp.mjs';
+import { parseLaunch, parsePoll, parseStopped, buildLaunch, buildPoll, buildStop, buildPromptChunks, commandSha256 } from '../scripts/lib/command-builder.mjs';
+import { createJobsApiTransport, createRestJobsBackend, createExecPollTransport } from '../scripts/lib/jobs.mjs';
+import { RuosHostAdapter } from '../scripts/lib/adapter.mjs';
+import { RuosError } from '../scripts/lib/types.mjs';
+import { desktop, fakeClock, fakeFleet, fakeTransport, fakeLedger, ok, FLY_ID } from './fakes.mjs';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const RUN = 'r-0123456789abcdef0123456789abcdef';
+const frame = (/** @type {string} */ cmd, /** @type {string} */ out) => ({
+ status: 'ok', exitCode: 0, completionVerified: true,
+ stdout: `▶ run: ${cmd}\n\n${out}\n\n✓ SUCCESS in 0s · 1 lines\n📝 transcript: /home/ruv/.ruos/activity/x.log\n`,
+});
+
+test('live framing: the echoed command never false-matches a marker', () => {
+ const spec = { runId: RUN, prompt: 'x', runner: /** @type {'claude'} */ ('claude') };
+ const launch = normalizeExec(frame(buildLaunch(spec), `RUOS_SHA:${'a'.repeat(64)}\nRUOS_PID:1995`));
+ assert.deepEqual(parseLaunch(launch.stdout), { sha256: 'a'.repeat(64), pid: 1995, noRunner: false });
+ const poll = normalizeExec(frame(buildPoll(RUN, 0), 'RUOS_POLL:0:22:0:UlVGTE9fUlVPU19MSVZFX09LIDQyCg=='));
+ const p = parsePoll(poll.stdout);
+ assert.ok(p !== 'norun' && p.chunk.toString() === 'RUFLO_RUOS_LIVE_OK 42\n');
+ // The raw (un-normalised) echo alone must not parse as a result either.
+ const echoOnly = `▶ run: ${buildLaunch(spec)}`;
+ assert.equal(parseLaunch(echoOnly).noRunner, false);
+ assert.equal(parseStopped(`▶ run: ${buildStop(RUN)}\nRUOS_NOT_RUNNING`), false);
+ assert.throws(() => parsePoll(`▶ run: ${buildPoll(RUN, 0)}`), RuosError);
+ const capped = normalizeExec({ stdout: '▶ run: seq\n\n0001 0002\n… [output truncated]\n', exitCode: 0 });
+ assert.equal(capped.truncated, true);
+ assert.equal(capped.stdout.trim(), '0001 0002');
+});
+
+/** In-memory jobs API that follows the ADR-105 contract. */
+function jobsServer() {
+ /** @type {Map<string, { owner: string, out: Buffer, state: string, exit: number|null, key: string }>} */
+ const jobs = new Map();
+ /** @type {any[]} */ const log = [];
+ let capHits = 0;
+ /** @type {typeof fetch} */
+ const f = async (url, init) => {
+ const u = new URL(String(url));
+ const method = init?.method ?? 'GET';
+ log.push({ method, path: u.pathname, search: u.search, body: init?.body ? JSON.parse(String(init.body)) : undefined, auth: /** @type {any} */ (init?.headers)?.authorization });
+ const json = (/** @type {number} */ status, /** @type {unknown} */ b) => new Response(JSON.stringify(b), { status });
+ if (u.pathname === '/api/v1/desktop/jobs' && method === 'GET') return json(200, { jobs: [...jobs.keys()] });
+ if (u.pathname === '/api/v1/desktop/jobs' && method === 'POST') {
+ if (capHits-- > 0) return json(429, { error: 'concurrency cap' });
+ const b = JSON.parse(String(init?.body));
+ for (const [id, j] of jobs) if (j.key === b.idempotency_key) return json(200, { job_id: id });
+ const id = `job_${jobs.size + 1}`;
+ jobs.set(id, { owner: 'me', out: Buffer.from('hello from the jobs api\n'), state: 'running', exit: null, key: b.idempotency_key });
+ return json(200, { job_id: id });
+ }
+ const id = decodeURIComponent(u.pathname.split('/').pop() ?? '');
+ const j = jobs.get(id);
+ if (!j || j.owner !== 'me') return json(404, { error: 'not found' });
+ if (method === 'DELETE') { j.state = 'cancelled'; return json(200, {}); }
+ const off = Number(u.searchParams.get('offset'));
+ const chunk = j.out.subarray(off, off + Number(u.searchParams.get('max')));
+ if (off + chunk.length >= j.out.length && j.state === 'running') { j.state = 'exited'; j.exit = 0; }
+ return json(200, { chunk: chunk.toString('base64'), next_offset: off + chunk.length, running: j.state === 'running', state: j.state, exit_code: j.exit, truncated: false });
+ };
+ return { f, log, jobs, setCapHits: (/** @type {number} */ n) => { capHits = n; }, foreign: (/** @type {string} */ id) => jobs.set(id, { owner: 'other', out: Buffer.alloc(0), state: 'running', exit: null, key: 'x' }) };
+}
+
+const staging = () => fakeTransport((cmd) => ok(cmd.includes('RUOS_PREPARED') ? 'RUOS_PREPARED' : ''));
+
+test('jobs API transport: start with idempotency key, stream to exit, audit, through the adapter', async () => {
+ const srv = jobsServer();
+ srv.setCapHits(1); // first create hits the per-tenant cap → adapter backs off
+ const backend = createRestJobsBackend({ baseUrl: 'https://fleet.example.test', token: 'tok', fetchImpl: srv.f });
+ assert.equal(await backend.detect(FLY_ID), true);
+ const clock = fakeClock();
+ const ledger = fakeLedger();
+ const adapter = new RuosHostAdapter({
+ fleet: fakeFleet([desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })]),
+ jobs: createJobsApiTransport(backend, staging()),
+ ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep,
+ });
+ /** @type {string[]} */ const seen = [];
+ const out = await adapter.run({ desktop: 'Work Desktop', prompt: 'secret task text', runId: RUN, agentId: 'a1', timeoutSecs: 600, onOutput: (c) => seen.push(c.toString()) });
+ assert.equal(out.status, 'completed');
+ assert.equal(out.jobs, 'jobs-api');
+ assert.equal(seen.join(''), 'hello from the jobs api\n');
+ const creates = srv.log.filter((r) => r.method === 'POST');
+ assert.equal(creates.length, 2, 'one capped attempt, one retry');
+ assert.deepEqual(Object.keys(creates[1].body).sort(), ['command', 'idempotency_key', 'machine', 'timeout_secs']);
+ assert.equal(creates[1].body.idempotency_key, RUN);
+ assert.equal(creates[1].body.machine, FLY_ID);
+ assert.ok(!JSON.stringify(creates).includes('secret task text'), 'prompt never in the job command');
+ assert.ok(ledger.warnings.some((w) => w.includes('concurrency cap')));
+ // Audit record: hash of the launched command, no prompt text.
+ assert.equal(ledger.audits.length, 1);
+ assert.match(ledger.audits[0].commandSha256, /^[0-9a-f]{64}$/);
+ assert.ok(!JSON.stringify(ledger.audits).includes('secret task text'));
+});
+
+test('jobs API: another tenant\'s id is 404 → not-owned, never retried', async () => {
+ const srv = jobsServer();
+ srv.foreign('job_other');
+ const t = createJobsApiTransport(createRestJobsBackend({ baseUrl: 'https://fleet.example.test', token: 'tok', fetchImpl: srv.f }), staging());
+ const before = srv.log.length;
+ await assert.rejects(t.poll(desktop(), 'job_other', 0), (e) => e instanceof RuosError && e.code === 'not-owned');
+ assert.equal(srv.log.length - before, 1, 'exactly one request');
+});
+
+test('jobs API: states map; a stopped desktop is resumable, not a silent success', async () => {
+ const backend = {
+ create: async () => ({ job_id: 'j1' }),
+ read: async () => ({ chunk: '', next_offset: 0, running: false, state: 'stopped', exit_code: null, truncated: false }),
+ cancel: async () => {},
+ list: async () => [],
+ };
+ const clock = fakeClock();
+ const adapter = new RuosHostAdapter({ fleet: fakeFleet([desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })]), jobs: createJobsApiTransport(backend, staging()), ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });
+ await assert.rejects(adapter.run({ desktop: 'Work Desktop', prompt: 'x', runId: RUN, agentId: 'a1' }), (e) => e instanceof RuosError && e.code === 'auto-stopped' && /attach/.test(e.message));
+ const missing = createRestJobsBackend({ baseUrl: 'https://fleet.example.test', token: 'tok', fetchImpl: async () => new Response('', { status: 404 }) });
+ assert.equal(await missing.detect(FLY_ID), false, 'jobs API not deployed → fall back to exec-poll');
+});
+
+test('no code path issues desktop_delete or secret_delete', async () => {
+ // Runtime guard: refused before any network request.
+ let fetched = false;
+ const c = new FleetMcpClient({ url: 'https://fleet.example.test/mcp', token: 'tok', fetchImpl: async () => { fetched = true; return new Response('{}'); } });
+ for (const name of FORBIDDEN_TOOLS) await assert.rejects(c.callTool(name, {}), RuosError);
+ assert.equal(fetched, false);
+ // Static guard: the names appear only in the FORBIDDEN_TOOLS definition.
+ const root = join(here, '..');
+ /** @param {string} d @returns {string[]} */
+ const walk = (d) => readdirSync(d).filter((n) => !n.startsWith('.') || n === '.claude-plugin').flatMap((n) => { const p = join(d, n); return statSync(p).isDirectory() ? walk(p) : [p]; });
+ for (const file of walk(root).filter((p) => !p.includes(`${join(root, 'tests')}`) && /\.(mjs|md|sh|json)$/.test(p))) {
+ const text = readFileSync(file, 'utf8');
+ for (const name of FORBIDDEN_TOOLS) {
+ const hits = text.split('\n').filter((l) => l.includes(name) && !l.includes('FORBIDDEN_TOOLS = ') && !/never|human/i.test(l));
+ assert.deepEqual(hits, [], `${file} mentions ${name}`);
+ }
+ }
+});
+
+test('credentials: env first, then @cognitum/ruos file; token never echoed', async () => {
+ assert.equal(fleetConfigFromEnv({ RUOS_MCP_URL: 'https://a/mcp', RUOS_MCP_TOKEN: 't' }, () => { throw new Error('no'); }).source, 'env');
+ const fromFile = fleetConfigFromEnv({ HOME: '/home/u' }, (p) => { assert.equal(p, '/home/u/.config/ruos/credentials.json'); return JSON.stringify({ access_token: 'oauth-tok' }); });
+ assert.deepEqual(fromFile, { url: 'https://ruos.cognitum.one/mcp', token: 'oauth-tok', source: 'credentials-file' });
+ assert.equal(fleetConfigFromEnv({ HOME: '/home/u' }, () => { throw new Error('ENOENT'); }).source, 'none');
+ const token = 'ruos_mcp_SUPERSECRET123';
+ const c = new FleetMcpClient({ url: 'https://fleet.example.test/mcp', token, fetchImpl: async () => new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, error: { message: `bad token ${token}` } }), { status: 200 }) });
+ await assert.rejects(c.callTool('desktop_status', {}), (e) => e instanceof Error && !e.message.includes(token) && e.message.includes('[redacted]'));
+});
+
+test('Lite browsers are never host candidates', () => {
+ const raw = {
+ desktops: [{ machine_id: 'a'.repeat(32), fly_machine_id: 'b'.repeat(14), name: 'w' }],
+ lite_browsers: [{ machine_id: 'lite-2be6c1bd3e06f05ae8da5f470e4737c3', kind: 'lite_browser', state: 'running' }],
+ };
+ assert.deepEqual(normalizeDesktops(raw).map((d) => d.id), ['a'.repeat(32)]);
+ assert.deepEqual(normalizeDesktops({ desktops: [{ machine_id: 'c'.repeat(32), kind: 'lite_browser' }] }), []);
+});
+
+test('LLM route: no route fails fast before any exec; unconfigured gateway only warns', async () => {
+ const clock = fakeClock();
+ const t = fakeTransport(() => ok(''));
+ const fleet = fakeFleet([desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })]);
+ fleet.llmRoute = async () => ({ route: null, provider: null, gateway: null, keyPresent: false });
+ const adapter = new RuosHostAdapter({ fleet, jobs: createExecPollTransport(t), ledger: /** @type {any} */ (fakeLedger()), now: clock.now, sleep: clock.sleep });
+ await assert.rejects(adapter.run({ desktop: 'Work Desktop', prompt: 'x', runId: RUN, agentId: 'a1' }), (e) => e instanceof RuosError && e.code === 'llm-unconfigured');
+ assert.equal(t.commands.length, 0);
+
+ const sha = buildPromptChunks(RUN, 'x').sha256;
+ const t2 = fakeTransport((cmd) => {
+ if (cmd.includes('RUOS_NO_RUNNER')) return ok(`RUOS_SHA:${sha}\nRUOS_PID:1`);
+ if (cmd.includes('RUOS_POLL')) return ok('RUOS_POLL:0:0:0:');
+ return ok('RUOS_PREPARED');
+ });
+ const ledger = fakeLedger();
+ const a2 = new RuosHostAdapter({ fleet: fakeFleet([desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })]), jobs: createExecPollTransport(t2), ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep });
+ const out = await a2.run({ desktop: 'Work Desktop', prompt: 'x', runId: RUN, agentId: 'a1' });
+ assert.equal(out.status, 'completed');
+ assert.ok(out.warnings.some((w) => w.includes('shared route')), 'live-observed shape: gateway unconfigured, route shared → warn, not fail');
+ assert.equal(ledger.audits[0].commandSha256, commandSha256(buildLaunch({ runId: RUN, prompt: 'x', runner: 'claude' })));
+});
diff --git a/plugins/ruflo-ruos/tests/transports.test.mjs b/plugins/ruflo-ruos/tests/transports.test.mjs
index e49145d56b..3c2f9b7ef7 100644
--- a/plugins/ruflo-ruos/tests/transports.test.mjs
+++ b/plugins/ruflo-ruos/tests/transports.test.mjs
@@ -52,7 +52,7 @@ test('fleet MCP: refuses http and the executor port', async () => {
}
});
-test('fleet MCP: handshake, bearer, session id, SSE and structured payloads', async () => {
+test('fleet MCP: stateless tools/call, bearer, SSE and structured payloads', async () => {
const { f, requests } = fakeFetch((name) => name === 'desktop_status'
? { result: text({ desktops: [{ machine_id: 'a'.repeat(32), fly_machine_id: 'b'.repeat(14), name: 'n', display_name: 'D', state: 'started', heartbeat_status: 'ok', last_heartbeat_at: 5, ready: true }, { machine_id: 'bogus' }] }), sse: true }
: { result: { structuredContent: { stdout: 'RUOS_RUNNER_OK\n', exit_code: 0 } } });
@@ -61,17 +61,19 @@ test('fleet MCP: handshake, bearer, session id, SSE and structured payloads', as
assert.equal(ds.length, 1, 'malformed ids are dropped');
assert.equal(ds[0].flyMachineId, 'b'.repeat(14));
const r = await createFleetTransport(client).exec(ds[0], 'echo', 999);
- assert.deepEqual(r, { stdout: 'RUOS_RUNNER_OK\n', stderr: '', exitCode: 0 });
+ assert.deepEqual(r, { stdout: 'RUOS_RUNNER_OK\n', stderr: '', exitCode: 0, truncated: false });
const call = requests.at(-1);
assert.equal(call.headers.authorization, `Bearer ${TOKEN}`);
- assert.equal(call.headers['mcp-session-id'], 'sess-1');
+ assert.equal(call.body.method, 'tools/call');
+ assert.ok(!requests.some((r) => r.body.method === 'initialize'), 'remote /mcp is stateless: no handshake');
assert.deepEqual(call.body.params.arguments, { command: 'echo', machine: 'b'.repeat(14), timeout_secs: 300 });
});
test('fleet MCP failure typing: auth expired, network down, stopped, timeout', async () => {
const mk = (/** @type {any} */ r) => new FleetMcpClient({ url: URL_, token: TOKEN, fetchImpl: fakeFetch(() => r).f });
await assert.rejects(mk({ status: 401 }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'auth-expired');
- await assert.rejects(mk({ status: 403 }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'auth-expired');
+ await assert.rejects(mk({ status: 403 }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'insufficient-scope', 'read-only token on a control tool');
+ await assert.rejects(mk({ status: 403 }).callTool('desktop_status', {}), (e) => e instanceof RuosError && e.code === 'auth-expired');
await assert.rejects(mk({ throws: new TypeError('fetch failed') }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'network-down');
const timeoutErr = Object.assign(new Error('t'), { name: 'TimeoutError' });
await assert.rejects(mk({ throws: timeoutErr }).callTool('desktop_exec', {}), (e) => e instanceof RuosError && e.code === 'timeout');
diff --git a/plugins/ruflo-ruos/tests/validate-autostop.test.mjs b/plugins/ruflo-ruos/tests/validate-autostop.test.mjs
index 6fd155ee9b..4f09f35ccb 100644
--- a/plugins/ruflo-ruos/tests/validate-autostop.test.mjs
+++ b/plugins/ruflo-ruos/tests/validate-autostop.test.mjs
@@ -33,8 +33,9 @@ test('budget and model validation', () => {
});
test('run ids are path-safe', () => {
- const id = newRunId(() => 1_790_000_000_000, (n) => Buffer.alloc(n, 0xab));
+ const id = newRunId((n) => Buffer.alloc(n, 0xab));
assert.match(id, RUN_ID_RE);
+ assert.equal(id, `r-${'ab'.repeat(16)}`, '128 random bits');
});
const iso = (/** @type {number} */ ms) => new Date(ms).toISOString();
diff --git a/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md b/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md
index 723cb3da7f..fb54c40632 100644
--- a/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md
+++ b/v3/docs/adr/ADR-405-ruos-desktops-as-swarm-hosts.md
@@ -4,7 +4,7 @@ Status: Proposed
Date: 2026 10 01
-Related: ADR 150 (removable integrations), ADR 324 (policy chokepoint), ADR 325 (claims plane), ruOS ADR-043 (exec literal filter), ruOS ADR-053 (per-tenant SSH :2222), ruOS ADR-070 (the desktop executor has no peer authentication), ruOS ADR-071 (remote MCP endpoint)
+Related: ADR 150 (removable integrations), ADR 324 (policy chokepoint), ADR 325 (claims plane), ruOS ADR-043 (exec literal filter), ruOS ADR-045 (activity tee), ruOS ADR-053 (per-tenant SSH :2222), ruOS ADR-070 (the desktop executor has no peer authentication), ruOS ADR-071 (remote MCP endpoint and tokens), ruOS ADR-081 (`desktop_exec`), ruOS ADR-094 (frozen remote tool contract), ruOS ADR-105 (jobs API, in progress)
## Context
@@ -12,81 +12,121 @@ ruOS gives each user their own cloud Linux desktops (Fly machines), plus enrolle
There are three ways into a ruOS desktop. They have different trust properties:
-| Path | Authentication | Usable from |
+| Path | Authentication | Reachable from |
|---|---|---|
-| ruOS fleet MCP (`desktop_status`, `desktop_exec`, `desktop_start`, `desktop_stop`, `desktop_keepawake`) | The caller's tenant credential. The fleet enforces machine ownership on every call. | Anywhere |
-| sshd on `:2222` (ruOS ADR-053 Phase 2) | Pubkey-only, with a per-tenant ed25519 key minted by the fleet. `authorized_keys` is replaced with that tenant's key each time the desktop is armed. | Only inside the Fly 6PN, so only from another of the same tenant's desktops |
+| ruOS fleet MCP / REST (`desktop_status`, `desktop_exec`, `desktop_start`, `desktop_stop`, `desktop_keepawake`, `llm_route_get`) | The caller's tenant token: a `ruos_mcp_` bearer or the `@cognitum/ruos` OAuth login. The fleet enforces machine ownership on every call. | **Anywhere.** This is the only path from outside a tenant. |
+| sshd on `:2222` (ruOS ADR-053 Phase 2) | Pubkey-only, with a per-tenant ed25519 key minted by the fleet. `authorized_keys` is replaced with that tenant's key each time the desktop is armed. No API returns the private key to an external client. | **Only inside the tenant's Fly 6PN**, i.e. desktop to desktop |
| Desktop executor on `:17870` | None per tenant. It is guarded only by a spoofable `Host` header, binds all interfaces, and every tenant shares one flat Fly 6PN app (ruOS ADR-070). | Any machine on the 6PN |
## Decision
### Host model
-A ruOS desktop is a remote execution host for one or more ruflo swarm agents. The `ruflo-ruos` plugin places an agent on a host, launches `claude -p` there detached, streams its output back, and records the agent in ruflo's swarm state. The swarm topology, routing and coordination stay local. The desktop only runs the agent process.
+A ruOS desktop is a remote execution host for one or more ruflo swarm agents. The `ruflo-ruos` plugin places an agent on a host, starts `claude -p` there as a detached job, streams its output back, and records the agent in ruflo's swarm state. The swarm topology, routing and coordination stay local. The desktop only runs the agent process.
### Transports
-Two transports are allowed, both implemented in `plugins/ruflo-ruos/scripts/lib/`:
-
-1. **The fleet MCP** (`fleet-mcp.mjs`). This is the default and the only control plane, used for discovery, start, stop and keepawake. In a Claude Code session the user's connected `mcp__ruos__*` tools are used directly. A terminal run reads `RUOS_MCP_URL` and `RUOS_MCP_TOKEN` from the environment. Neither value is embedded or defaulted. With either unset the CLI exits 2 with `not-configured` and makes no request. The client refuses plain `http` (except localhost) and any URL on port 17870.
-2. **Per-tenant SSH on `:2222`** (`ssh.mjs`). It is opt-in (`--transport ssh`, `RUOS_SSH_KEY`) and works only when ruflo itself runs on one of the same tenant's ruOS desktops. `ssh` is spawned with a fixed argv and `shell: false`, with `BatchMode`, `IdentitiesOnly` and `StrictHostKeyChecking=accept-new`. The host is derived from the validated Fly machine id: `<fly-id>.vm.<app>.internal`. ADR-053 records that arming is probabilistic, so `Permission denied (publickey)` maps to `auth-expired` ("desktop not armed with this key").
-
-The `:17870` executor is excluded. Any path that called it from a ruflo swarm would extend ADR-070's cross-tenant shell exposure into ruflo. The plugin sends no `Host` header and opens no connection to that port, and its smoke contract greps for any use of it. If ruOS ADR-070 lands per-request fleet authentication on the executor, a follow-up ADR can reconsider; until then the fleet MCP is the boundary.
+1. **External: the fleet MCP / REST only** (`fleet-mcp.mjs`). This covers discovery, start, stop, keepawake, the LLM-route check, and exec.
+ - **Credentials.** `RUOS_MCP_URL` + `RUOS_MCP_TOKEN` from the environment, or the `@cognitum/ruos` credentials file (`~/.config/ruos/credentials.json`).
+ - Never embedded, logged or echoed; error messages redact the token.
+ - With neither present, every networked command exits 2 (`not-configured`) and sends no request.
+ - **Token scope.** Exec, start, stop and keepawake need a `desktop:control` token. A read-only token degrades to discovery and status, and control calls fail with `insufficient-scope`. Users should mint a control token with the narrowest lifetime.
+ - **Stateless.** Remote `/mcp` is stateless, so each call is a single `tools/call` with no handshake.
+ - **Refusals.** The client refuses plain `http` (except localhost) and any URL on port 17870.
+2. **In-tenant fan-out: SSH `:2222`** (`ssh.mjs`, opt-in with `--transport ssh` and `RUOS_SSH_KEY`).
+ - It works only when ruflo itself runs on one of the tenant's ruOS desktops, reaching sibling desktops at `<fly-id>.vm.<app>.internal`.
+ - Peers come from `~/.claude/federation/peers.json` or `GET /api/v1/cluster/peers` on that desktop.
+ - `ssh` is spawned with a fixed argv and `shell: false`, with `BatchMode` and `IdentitiesOnly`.
+ - `Permission denied (publickey)` maps to `auth-expired`, because arming is probabilistic per ruOS ADR-053.
+ - It is never usable from a laptop or workstation.
+
+The `:17870` executor is excluded. Any path that called it would extend ADR-070's cross-tenant shell exposure into ruflo swarms. The plugin opens no connection to that port and sends no `Host` header, and its smoke contract greps for any use of it.
+
+### Jobs: a `JobTransport` with two implementations
+
+The adapter drives a `JobTransport` (`jobs.mjs`) through `start`, `poll(offset)` and `cancel`:
+
+- **`ExecPollTransport`** is available now. It uses `desktop_exec` (ruOS ADR-081), which is synchronous. Its timeout defaults to 30 s and is clamped to 1–300 s; the same timeout bounds the wait for the desktop's run lock, so exec calls on one desktop serialise. Each call is audited and owner-scoped.
+ - **Launch.** The prompt is staged as base64 chunks into `~/.ruflo-ruos/runs/<runId>/`. HOME survives the 23:00 stop; `/tmp` does not. A detached `nohup setsid sh -c '<constant>'` runner then starts, and launch prints the prompt's sha256 and the runner's pid.
+ - **Poll.** Each poll returns `RUOS_POLL:<exit>:<size>:<alive>:<base64 slice>`.
+ - Only whole base64 quanta are decoded, so a truncated result never skips bytes.
+ - The `alive` flag (`kill -0`) detects a runner killed before it wrote its exit code. The exit code is written atomically (`tmp` + `mv`).
+ - The offset is tracked client-side.
+- **`JobsApiTransport`** is used when ruOS ADR-105 is detected: `GET /api/v1/desktop/jobs` exists.
+ - **Calls.** `POST /api/v1/desktop/jobs {machine, command, timeout_secs ≤ 21600, idempotency_key}` creates a job, `GET …/{id}?offset&max=65536` reads it by byte offset (base64 chunks, `truncated` flag), and `DELETE` cancels it.
+ - **States.** `queued | running | exited | failed | cancelled | stopped | lost`.
+ - **Server-side.** The server owns detach, capture, exit, cancel, keepawake and audit.
+ - **Idempotency.** The run id is the idempotency key, so a retried create returns the same job.
+ - **Error mapping.** A 404 means "not yours, or gone" and is never retried. A 409 or 429 means the per-tenant concurrency cap (`RUOS_JOBS_MAX_CONCURRENT`) was hit; the adapter backs off 5 s, 10 s, 20 s and then fails.
+ - **Backends.** Either REST with the tenant token, or the local stdio `@cognitum/ruos` server's `desktop_job_*` tools. Those tools are stdio-only and never exposed on the remote connector, which is frozen by ruOS ADR-094.
+ - **Selection.** `--jobs auto` (the default) feature-detects and falls back to exec-poll.
+
+Polling is adaptive: 1 s while output flows, backing off to 10 s when idle. Every exec poll is an audited call that waits behind the run lock.
### Command construction
-Every shell string sent to a desktop comes from one audited module, `command-builder.mjs`. The same strings go over both transports.
+Every shell string sent to a desktop comes from one audited module, `command-builder.mjs`. The same strings go over every transport.
-- Each command is one line of at most 4000 bytes, the `desktop_exec` limit.
+- Each command is one line of at most 4000 bytes.
- The only variable regions are:
- - a run id matching `^[a-z0-9][a-z0-9-]{5,62}$`;
+ - a run id: `r-` + 128 random bits in hex;
- integers;
- a model name from a fixed enum;
- a canonicalised budget number;
- base64 text inside single quotes.
-- Prompt text travels only as base64. It is appended to a file in chunks, decoded on the desktop, and fed to `claude -p` on stdin, so no shell ever parses it.
-- The decoded prompt's sha256 is checked against the local hash before the run is trusted.
-- Output returns as `RUOS_POLL:<exit>:<size>:<alive>:<base64 slice>`, so arbitrary bytes survive the JSON tool result. Only whole base64 quanta are decoded, so a truncated result never skips bytes. The `alive` flag (`kill -0` on the pid) detects a runner killed before it wrote its exit code.
-- Run files live in `~/.ruflo-ruos/runs/<runId>/` with `umask 077`. The exit code is written atomically (`tmp` + `mv`), so a poll never reads a half-written file.
-- The runner starts as `nohup setsid sh -c '<constant>'`. Stop signals its process group, after re-validating the pid file as digits on the desktop.
+- Prompt text travels only as base64 and reaches `claude -p` on stdin.
+- No command contains push, deploy or destructive literals, so ruOS's `validate_run` filter (ADR-043) never misfires. That filter is a mistake guard, not a sandbox.
-The ADR-043 literal filter passes these commands: `nohup`, `setsid` and `sh -c` are not on its denylist. That filter is a mistake guard, not a sandbox. The fleet's ownership check is the boundary.
+**Live finding:** `desktop_exec` stdout is framed. It begins with a `▶ run: <command>` echo and ends with `✓ SUCCESS…` and `📝 transcript:` trailers.
-### Swarm state and claims
+- Because the echo repeats the command, which contains its own marker names, every marker is matched as a whole line, and `normalizeExec` strips the frame.
+- stdout is head-capped at about 4 KiB, including that echo (`… [output truncated]`), so a poll slice is 2 KiB raw.
+
+### Swarm state, claims and audit
The plugin does not add a claims system or an agent store. ADR-325 already describes four disconnected claim mechanisms. This plugin uses ruflo's local work-ownership board, the `claims_*` MCP tools (`.claude-flow/claims/claims.json`), which is ADR-325's "work ownership" responsibility in single-node form.
| What | ruflo tool (called in-process via `callMCPTool`, so ADR-324 policy applies) |
|---|---|
-| Register a remote agent | `agent_spawn` with `domain: "ruos"`, `config.host = {kind:"ruos", desktopId, desktopName, transport, runId}` |
+| Register a remote agent | `agent_spawn` with `domain: "ruos"`, `config.host = {kind:"ruos", desktopId, desktopName, transport, jobs, runId, stopAt}` |
| Running / done | `agent_update` (`busy` → `idle`, `config.lastRemoteResult`) |
| Ownership of the run | `claims_claim` / `claims_release`, issue `ruos-run-<runId>`, claimant `agent:<agentId>:<agentType>` |
+`stopAt` is the next forced 23:00 America/Toronto stop for cloud desktops. A scheduler can use it to avoid starting long jobs near the stop.
+
The plugin itself owns only `.claude-flow/ruos/`:
-- `events.jsonl` holds lifecycle events carrying ids, sizes and states, never prompt or output text.
-- `hosts.json` is a snapshot of hosts and their agents.
+- `events.jsonl` holds lifecycle events: ids, sizes and states, never prompt or output text.
+- `hosts.json` is a merged snapshot of hosts and their current agents.
+- `audit.jsonl` holds one record per run: run id, job id, desktop, transport, the sha256 of the launched command, start, end, status, exit code and bytes. The detached process's output is not in the ruOS activity feed (ruOS ADR-045 tees only chat-proxy runs), so ruflo keeps its own record.
- `runs/<runId>.log` is a local copy of the output, mode 0600.
-The swarm pane (`ruflo-swarm`) reads agents with `config.host.kind === "ruos"` plus these two files. If the CLI cannot be resolved, or policy denies a call, the ledger degrades to the plugin files and reports `swarmLedger: "unavailable"`. A remote run is never aborted because bookkeeping failed.
+If the CLI cannot be resolved, or policy denies a call, the ledger degrades to the plugin files and reports `swarmLedger: "unavailable"`.
+
+### LLM route
+
+`claude -p` on the desktop uses the desktop's own Claude auth and LLM route. Before launch the adapter calls `llm_route_get`:
+
+- **No route, or a disabled route:** the run fails fast with `llm-unconfigured`.
+- **`gateway: "unconfigured"` with `route: "shared"`:** this is only a warning. It was observed live, and `claude -p` succeeded with that shape.
### Cost and auto-stop
- Starting a desktop is billable. The adapter starts one only with an explicit `--start`, and then waits for a fresh `last_heartbeat_at`, not `ready`.
-- The fleet stops cloud desktops at 23:00 America/Toronto every weekday. `desktop_keepawake` blocks idle autosleep but does not override that stop. The adapter computes the next stop with `Intl`, so DST is handled. A run whose timeout crosses it is refused unless the user passes `--ignore-autostop`.
-- At launch the adapter calls `desktop_keepawake` for the run's timeout plus 5 minutes.
-- Polls back off from 1 s to 5 s. Each poll is an audited `desktop_exec` that waits behind the desktop's run lock.
+- The fleet stops cloud desktops at 23:00 America/Toronto every weekday. `desktop_keepawake` blocks only idle autosleep. The adapter computes the next stop with `Intl` (DST-aware) and refuses a run whose timeout crosses it unless the user passes `--ignore-autostop`. At launch it holds keepawake for the timeout plus 5 minutes.
+- A desktop stopped mid-run is reported as `auto-stopped` and treated as resumable. HOME persists, so after `desktop_start`, `attach --run <id>` re-reads the run directory from any offset.
-### Deploy hand-off
+### Deletion and deploy
-After a run, `deploy-info` reports a repo's branch, HEAD, dirty count and commits ahead of upstream on the desktop. It never pushes or deploys. ruOS's exec filter refuses `git push` and `fly deploy` literals by design, and the deploy decision stays with the user.
+- The swarm never issues `desktop_delete` or `secret_delete`; deletion stays a human action. The client refuses those names before any request, and a test asserts that no file in the plugin emits them.
+- Deploy is **read-only**. After a run, `deploy-info` reports branch, HEAD, dirty count and commits ahead on the desktop. The hand-off is a branch or PR plus that summary, for a human to review, merge and deploy. ruflo-ruos never pushes, deploys or publishes, and there is no ruOS deploy tool to call.
### Removability (ADR-150 style)
- ruflo works identically when the plugin is absent. The PR changes no file under `v3/`, apart from this ADR.
- The plugin has no npm dependencies.
- The ruflo CLI is resolved at runtime and is optional.
-- The `$.ruos` and `$.ruflo` Claude Code mod nouns are feature-detected and never required.
+- The `$.ruos` and `$.ruflo` Claude Code mod nouns are feature-detected and never required. `$.ruos.desktops()` makes no network calls and may be stale, so freshness always comes from `desktop_status`.
## Failure modes
@@ -94,34 +134,39 @@ Each failure surfaces as a typed `RuosError` code:
| Failure | Detection | Code |
|---|---|---|
-| Fleet credential expired or revoked | HTTP 401/403, or a tool error mentioning auth | `auth-expired` |
+| Credential expired or revoked | HTTP 401, or a tool error mentioning auth | `auth-expired` |
+| Read-only token on a control tool | HTTP 403 or a scope error | `insufficient-scope` |
| Fleet unreachable | `fetch` network error | `network-down` |
| Request hangs | `AbortSignal.timeout` | `timeout` |
| Desktop stopped before the run | Heartbeat not fresh, and `--start` not given | `desktop-stopped` |
-| Desktop stopped mid-run (23:00 stop, idle autosleep) | A poll fails, then `desktop_status` shows the desktop down | `auto-stopped` |
-| Run would cross the auto-stop | `checkWindow` | `autostop-window` |
-| Desktop not the caller's | Not in `desktop_status` | `not-owned` |
+| Desktop stopped mid-run | Poll fails and `desktop_status` shows the desktop down, or the jobs API reports `stopped` | `auto-stopped` (resumable) |
+| Run would cross the auto-stop | `checkWindow` (cloud desktops only) | `autostop-window` |
+| Desktop not the caller's, or a Lite browser | Not in the hosted `desktop_status` list | `not-owned` |
+| Job id belongs to another tenant, or is gone | Jobs API 404 | `not-owned` (no retry) |
+| Tenant job concurrency cap | Jobs API 409/429 | `capacity`, after 3 backoffs |
+| No LLM route on the desktop | `llm_route_get` | `llm-unconfigured` |
| Prompt corrupted in transit | sha256 mismatch | `remote-error` |
-| `claude` missing on the desktop | `RUOS_NO_RUNNER` | `remote-error` |
-| SSH key not armed | ssh exit 255 + `publickey` | `auth-expired` |
-| Run outlives its timeout | Wall-clock check; the process group is stopped | `timeout` |
-| Runner killed without an exit code | Poll shows `alive=0` and no exit code, twice | `remote-error` |
+| `claude` missing on the desktop | `RUOS_NO_RUNNER` line | `remote-error` |
+| Runner killed without an exit code | `alive=0` and no exit code, twice | `remote-error` |
+| Run outlives its timeout | Wall-clock check; the job is cancelled | `timeout` |
-On every failure the agent is set `idle` and the claim is released.
+On every failure the agent is set `idle`, the claim is released, and an audit record is written.
## Threat model
| Threat | Mitigation |
|---|---|
-| Cross-tenant shell via `:17870` | Transport excluded. Smoke check 4. Client refuses the port. |
-| Acting on another tenant's desktop | Ids resolve only against the caller's own `desktop_status`. The fleet re-checks ownership on every call. |
-| Shell injection from task text (including a prompt-injected agent writing the task) | Base64-only payloads. One builder. Tests run hostile prompts through a real `/bin/sh`. |
+| Cross-tenant shell via `:17870` | Transport excluded. Smoke check. Client refuses the port. |
+| Acting on another tenant's desktop or job | Ids resolve only against the caller's own `desktop_status`. The fleet re-checks ownership. A jobs-API 404 is never retried. |
+| Shell injection from task text (including a prompt-injected agent writing the task) | Base64-only payloads. One builder. Tests run hostile prompts through a real `/bin/sh`, and also attempt to break out of the `sh -c '…'` quoting. |
| Injection via ids, model, budget, offset or repo path | Allow-list regexes. Canonical numbers. `..` and leading `-` refused. |
-| Credential leakage | Bearer token and SSH key path come only from the environment. They are never logged or written to events. |
-| Prompt or output leakage into shared state | Events carry ids and sizes only. Output is kept in a 0600 local file and a 0700 remote run dir. |
-| Accidental spend | No start without `--start`. Auto-stop window check. `--max-budget-usd` passes through to `claude -p`. |
-| Destructive operations | `stop` and `desktop-stop` require `--confirm`. No delete or provision verbs. |
-| Silent success (cognitum#620 pattern) | Every run needs a positive exit code from the desktop. A missing run dir or a missing pid is an error. |
+| Marker spoofing via the exec echo | Frame stripped. Whole-line marker matching. Tested with live-captured output. |
+| Credential leakage | Token comes only from env or the credentials file. Never logged or written to events or audit. Redacted in errors. |
+| Prompt or output leakage into shared state | Events and audit carry ids, hashes and sizes only. Output is kept in a 0600 local file and a 0700 remote run dir. |
+| Accidental spend | No start without `--start`. Auto-stop window check. `--max-budget-usd` passes through to `claude -p`. Capacity backoff is bounded. |
+| Destructive operations | Cancel and `desktop-stop` require `--confirm`. `desktop_delete` and `secret_delete` are never issued. Deploy is read-only. |
+| Silent success (cognitum#620 pattern) | Every run needs a positive terminal state with an exit code. A lost runner, a missing run dir or a missing pid is an error. |
+| SSH host-key trust | **Accepted risk:** `StrictHostKeyChecking=accept-new` is trust-on-first-use. This is acceptable only inside one tenant's 6PN, where the peer set comes from the fleet and the key is per-tenant. |
Residual risk: the remote `claude -p` runs with the desktop user's full trust. That is the user's own desktop, and its tool permissions are governed by its own Claude Code settings.
@@ -130,15 +175,37 @@ Residual risk: the remote `claude -p` runs with the desktop user's full trust. T
**Positive:**
- Swarm agents can run on the user's own ruOS desktops, visible in the swarm pane.
- No new trust path is added.
-- Swarm state stays one source of truth.
+- One source of truth for swarm state.
+- The jobs API slots in behind the same interface when it lands.
**Negative:**
-- Streaming is poll-based, because `desktop_exec` is request/response. Each poll costs one audited fleet call.
-- SSH works only desktop-to-desktop.
-- The fleet MCP's `desktop_exec` output shape is normalised defensively (`stdout|output`, `exit_code|exitCode`). A change on the ruOS side is caught by the live check, not by unit tests.
+- Until ADR-105 lands, streaming is poll-based over audited exec calls, with about 2 KiB per poll because of the head cap.
+- SSH works only desktop to desktop.
## Verification
-- `bash plugins/ruflo-ruos/scripts/smoke.sh` runs the structural checks, the no-`:17870` grep, an offline exit-2 check, and the full `node --test` suite.
-- The suite includes London-school adapter tests, transport failure typing with injected `fetch` and `spawn`, injection tests, real-`/bin/sh` execution of the builder output, and an integration test against the in-tree CLI's real `agent_spawn` and `claims_*` tools.
-- The live end-to-end and benchmark results are recorded in the PR.
+- `bash plugins/ruflo-ruos/scripts/smoke.sh` runs the structural checks, the no-`:17870` grep, an offline exit-2 check, `tsc --checkJs`, and the full `node --test` suite.
+- The suite includes:
+ - London-school adapter tests;
+ - transport failure typing;
+ - jobs-API contract mocks: idempotency, 404, capacity, states;
+ - injection tests through a real `/bin/sh`;
+ - parsing of live-captured exec output;
+ - the deletion-tool guard;
+ - an integration test against the in-tree CLI's `agent_spawn` and `claims_*`.
+
+**Live end-to-end, 2026-10-01**, on rUv's existing "Work Desktop" (approved, bounded):
+
+- **Window:** `desktop_start` at 21:45:48Z, `desktop_stop` at 21:47:35Z. `desktop_status` then showed `state: stopped`, `heartbeat_status: asleep`.
+- **LLM route:** `llm_route_get` returned `{route: "shared", gateway: "unconfigured", key_present: false}`.
+- **Run:** the builder's launch steps started `claude -p --model haiku --max-budget-usd 0.10`.
+ - The prompt's sha256 matched on the desktop.
+ - The detached runner survived the exec returning (`alive=1`).
+ - The second poll returned exit 0 with `RUFLO_RUOS_LIVE_OK 42`, about 11 s after launch.
+- **Latency:** spacing between 9 back-to-back `desktop_exec` calls, measured on the desktop clock, had a median of 676 ms, p95 842 ms and minimum 174 ms. The whole batch of 10 calls took 9.45 s including session overhead.
+- **Output cap:** about 4 KiB, including the echo.
+
+Not verified live:
+- SSH (6PN-only);
+- the env-token terminal path;
+- the jobs API, which is not deployed yet.