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

fix(ruflo-ruos): align JobsApiTransport with the live ADR-105 jobs API

ruv1dd984d04a3f
diff --git a/plugins/ruflo-ruos/README.md b/plugins/ruflo-ruos/README.md
index f819d763f6..84b31fe8b9 100644
--- a/plugins/ruflo-ruos/README.md
+++ b/plugins/ruflo-ruos/README.md
@@ -25,7 +25,7 @@ Mint a **`desktop:control`** token with the narrowest lifetime. A read-only toke
- 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.
+**Jobs.** `--jobs auto` (the default) uses the live ruOS jobs API (ADR-105: long-poll, 64 KiB chunks) when your fleet answers it, 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
diff --git a/plugins/ruflo-ruos/scripts/lib/adapter.mjs b/plugins/ruflo-ruos/scripts/lib/adapter.mjs
index 3fccbc4f57..b2347af282 100644
--- a/plugins/ruflo-ruos/scripts/lib/adapter.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/adapter.mjs
@@ -274,6 +274,7 @@ export class RuosHostAdapter {
await this.jobs.cancel(desktop, jobId).catch(() => false);
throw new RuosError('timeout', `run exceeded ${o.timeoutSecs}s and was stopped`);
}
+ const polledAt = this.now();
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;
@@ -286,7 +287,9 @@ export class RuosHostAdapter {
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 };
+ // `exited` carries any exit code (ADR-105): only 0 is completed.
+ const status = p.state === 'cancelled' ? 'stopped' : p.state === 'exited' && p.exitCode === 0 ? 'completed' : 'failed';
+ return { status, 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`);
@@ -296,6 +299,9 @@ export class RuosHostAdapter {
lostOnce = true; // exit.code is written just after the runner exits: re-check once
continue;
}
+ // With long-poll the server already waited (wait_ms); only guard against
+ // a server that answers instantly so the loop never spins.
+ if (this.jobs.longPoll && this.now() - polledAt >= POLL_MIN_MS) continue;
await this.sleep(delay);
delay = Math.min(delay * 1.5, POLL_MAX_MS);
}
diff --git a/plugins/ruflo-ruos/scripts/lib/jobs.mjs b/plugins/ruflo-ruos/scripts/lib/jobs.mjs
index 6ebb7a55df..52d7fba9d0 100644
--- a/plugins/ruflo-ruos/scripts/lib/jobs.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/jobs.mjs
@@ -80,16 +80,31 @@ export function createExecPollTransport(exec, nonce = defaultNonce) {
}
/**
- * Minimal backend contract for the jobs API (REST or stdio MCP adapter).
+ * Backend contract for the ruOS jobs API (ruos-desktop ADR-105, live).
+ * @typedef {object} JobsRead
+ * @property {string} chunk base64
+ * @property {number} next_offset
+ * @property {boolean} running true while queued too: "keep polling"
+ * @property {string} state
+ * @property {number|null} exit_code
+ * @property {boolean} truncated
+ * @property {('up'|'asleep'|'unknown')=} desktop
+ * @property {string=} stop_at
+ * @property {string|null=} error
+ */
+/**
* @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 {(body: { machine: string, command: string, timeout_secs: number, idempotency_key: string }) => Promise<{ job_id: string, state?: string, idempotent_replay?: boolean }>} create
+ * @property {(jobId: string, offset: number, max: number, waitMs: number) => Promise<JobsRead>} 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;
+/** server long-poll cap is 25 000 ms; leave headroom under the request timeout */
+export const JOBS_WAIT_MS = 20_000;
+export const JOBS_TIMEOUT_MAX = 21_600;
/**
* @param {JobsBackend} backend
@@ -100,20 +115,22 @@ export const JOBS_CHUNK_MAX = 65536;
export function createJobsApiTransport(backend, exec, nonce = defaultNonce) {
return {
kind: 'jobs-api',
+ longPoll: true,
async start(desktop, spec) {
await stagePrompt(exec, desktop, spec, nonce);
const command = buildJobCommand(spec);
const { job_id } = await backend.create({
machine: desktop.flyMachineId ?? desktop.id,
command,
- timeout_secs: assertInt(spec.timeoutSecs, 1, 21600, 'timeoutSecs'),
+ // The server clamps above 21 600 s; we never ask for more.
+ timeout_secs: Math.min(assertInt(spec.timeoutSecs, 1, 7 * 86_400, 'timeoutSecs'), JOBS_TIMEOUT_MAX),
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 r = await backend.read(jobId, offset, JOBS_CHUNK_MAX, JOBS_WAIT_MS);
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.
@@ -121,29 +138,34 @@ export function createJobsApiTransport(backend, exec, nonce = defaultNonce) {
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);
+ await backend.cancel(jobId); // TERM, then KILL after 10 s β†’ cancelled
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
+ * REST backend for the live jobs API, Bearer token with `desktop:control`.
+ * Status mapping (ADR-105):
+ * POST 202 new Β· 200 `idempotent_replay` β†’ success, reuse job_id
+ * POST 409 β†’ same key, different request: a client bug, never retried
+ * POST 429 β†’ per-tenant cap (4), no server queue β†’ `capacity` (adapter backs off)
+ * GET 503 β†’ desktop up but the poll did not answer β†’ retried here with backoff
+ * 401 β†’ auth-expired Β· 403 β†’ insufficient-scope Β· 404 β†’ not-owned (never retried)
+ * @param {{ baseUrl: string, token: string, fetchImpl?: typeof fetch, sleep?: (ms: number) => Promise<void> }} o
* @returns {JobsBackend & { detect: (machine: string) => Promise<boolean> }}
*/
export function createRestJobsBackend(o) {
const f = o.fetchImpl ?? globalThis.fetch;
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
const base = new URL('/api/v1/desktop/jobs', o.baseUrl).toString();
/**
* @param {string} method
* @param {string} url
* @param {unknown=} body
+ * @param {number=} timeoutMs
*/
- const call = async (method, url, body) => {
+ const call = async (method, url, body, timeoutMs = 60_000) => {
/** @type {Response} */
let res;
try {
@@ -151,7 +173,7 @@ export function createRestJobsBackend(o) {
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),
+ signal: AbortSignal.timeout(timeoutMs),
});
} catch {
throw new RuosError('network-down', 'ruOS jobs API unreachable');
@@ -159,7 +181,9 @@ export function createRestJobsBackend(o) {
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.status === 409) throw new RuosError('invalid-input', 'idempotency key reused with a different request (client bug; not retried)');
+ if (res.status === 429) throw new RuosError('capacity', 'per-tenant job concurrency cap reached (no server queue)');
+ if (res.status === 503) throw new RuosError('timeout', 'desktop did not answer the poll (503)');
if (!res.ok) throw new RuosError('tool-error', `jobs API HTTP ${res.status}`);
const text = await res.text();
return text ? JSON.parse(text) : {};
@@ -168,13 +192,25 @@ export function createRestJobsBackend(o) {
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}`),
+ read: async (id, offset, max, waitMs) => {
+ const wait = Math.max(0, Math.min(25_000, Math.floor(waitMs)));
+ const url = `${jobUrl(id)}?offset=${offset}&max=${max}${wait ? `&wait_ms=${wait}` : ''}`;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await call('GET', url, undefined, wait + 30_000);
+ } catch (e) {
+ // 503 = desktop up but the poll did not answer: bounded backoff.
+ if (!(e instanceof RuosError) || e.code !== 'timeout' || attempt >= 3) throw e;
+ await sleep(1000 * 2 ** attempt);
+ }
+ }
+ },
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. */
+ /** Feature detection: the list route answers β†’ the jobs API is deployed. */
detect: async (machine) => {
try {
await call('GET', `${base}?machine=${encodeURIComponent(machine)}`);
diff --git a/plugins/ruflo-ruos/scripts/lib/types.mjs b/plugins/ruflo-ruos/scripts/lib/types.mjs
index 106635b1f9..ba69b8065a 100644
--- a/plugins/ruflo-ruos/scripts/lib/types.mjs
+++ b/plugins/ruflo-ruos/scripts/lib/types.mjs
@@ -68,6 +68,7 @@
/**
* @typedef {object} JobTransport
* @property {'exec-poll'|'jobs-api'} kind
+ * @property {boolean=} longPoll poll() itself waits server-side; no client sleep between polls
* @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
diff --git a/plugins/ruflo-ruos/tests/requirements.test.mjs b/plugins/ruflo-ruos/tests/requirements.test.mjs
index 22d571c656..8c718bdde5 100644
--- a/plugins/ruflo-ruos/tests/requirements.test.mjs
+++ b/plugins/ruflo-ruos/tests/requirements.test.mjs
@@ -204,3 +204,102 @@ test('LLM route: no route fails fast before any exec; unconfigured gateway only
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' }, N).split(N).join('<nonce>')), 'nonce-masked, stable hash');
});
+
+/**
+ * Mock of the LIVE ruos-desktop ADR-105 contract (fleet 64261be), exact codes:
+ * POST 202 new / 200 idempotent_replay / 409 same key + different request /
+ * 429 cap; GET 503 once (desktop up, poll unanswered), queued with running:true,
+ * wait_ms honoured; 404 for another tenant's id.
+ */
+function adr105Server() {
+ /** @type {Map<string, { body: any, out: Buffer, state: string, exit: number|null, polls: number }>} */
+ const byKey = new Map();
+ /** @type {any[]} */ const log = [];
+ let cap = 0;
+ let unanswered = 0;
+ /** @type {typeof fetch} */
+ const f = async (url, init) => {
+ const u = new URL(String(url));
+ const method = init?.method ?? 'GET';
+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;
+ log.push({ method, path: u.pathname, query: Object.fromEntries(u.searchParams), body });
+ const json = (/** @type {number} */ status, /** @type {unknown} */ b) => new Response(JSON.stringify(b), { status });
+ if (u.pathname === '/api/v1/desktop/jobs' && method === 'POST') {
+ if (!body.idempotency_key) return json(400, { error: 'idempotency_key required' });
+ const prev = byKey.get(body.idempotency_key);
+ if (prev) {
+ return JSON.stringify(prev.body) === JSON.stringify(body)
+ ? json(200, { job_id: `job_${body.idempotency_key.slice(2, 10)}`, state: prev.state, idempotent_replay: true })
+ : json(409, { error: 'idempotency key reused with a different request' });
+ }
+ if (cap-- > 0) return json(429, { error: 'concurrency cap' });
+ byKey.set(body.idempotency_key, { body, out: Buffer.from('exit three\n'), state: 'queued', exit: null, polls: 0 });
+ return json(202, { job_id: `job_${body.idempotency_key.slice(2, 10)}`, state: 'queued' });
+ }
+ if (u.pathname === '/api/v1/desktop/jobs' && method === 'GET') return json(200, { jobs: [] });
+ const id = u.pathname.split('/').pop() ?? '';
+ const job = [...byKey.entries()].find(([k]) => `job_${k.slice(2, 10)}` === id)?.[1];
+ if (!job) return json(404, { error: 'not found' });
+ if (method === 'DELETE') { job.state = 'cancelled'; return json(200, {}); }
+ if (unanswered-- > 0) return new Response('', { status: 503 });
+ job.polls++;
+ if (job.polls === 1) return json(200, { chunk: '', next_offset: 0, running: true, state: 'queued', exit_code: null, truncated: false, desktop: 'up' });
+ const off = Number(u.searchParams.get('offset'));
+ const chunk = job.out.subarray(off);
+ job.state = 'exited'; job.exit = 3; // `exited` carries ANY exit code
+ return json(200, { chunk: chunk.toString('base64'), next_offset: off + chunk.length, running: false, state: 'exited', exit_code: 3, truncated: false, desktop: 'up', stop_at: '2026-10-02T03:00:00.000Z' });
+ };
+ return { f, log, setCap: (/** @type {number} */ n) => { cap = n; }, setUnanswered: (/** @type {number} */ n) => { unanswered = n; } };
+}
+
+test('ADR-105 live contract: 202, 200 replay, 409, 429, 503, queued, exited≠0, wait_ms', async () => {
+ const srv = adr105Server();
+ /** @type {number[]} */ const backoffs = [];
+ const backend = createRestJobsBackend({ baseUrl: 'https://ruos.cognitum.one', token: 'tok', fetchImpl: srv.f, sleep: async (ms) => { backoffs.push(ms); } });
+ const body = { machine: FLY_ID, command: 'x', timeout_secs: 60, idempotency_key: RUN };
+ const created = await backend.create(body);
+ assert.match(created.job_id, /^job_/);
+ const replay = await backend.create(body);
+ assert.equal(replay.job_id, created.job_id, '200 replay reuses the job id');
+ assert.equal(replay.idempotent_replay, true);
+ const before = srv.log.length;
+ await assert.rejects(backend.create({ ...body, command: 'different' }), (e) => e instanceof RuosError && e.code === 'invalid-input' && /client bug/.test(e.message));
+ assert.equal(srv.log.length - before, 1, '409 is never retried');
+ srv.setCap(1);
+ await assert.rejects(backend.create({ ...body, idempotency_key: 'r-ffffffffffffffffffffffffffffffff' }), (e) => e instanceof RuosError && e.code === 'capacity');
+ srv.setUnanswered(2);
+ const first = await backend.read(created.job_id, 0, 65536, 20000);
+ assert.deepEqual(backoffs, [1000, 2000], '503 retried with backoff');
+ assert.equal(first.state, 'queued');
+ assert.equal(first.running, true, 'running is true while queued');
+ const getLog = srv.log.filter((r) => r.method === 'GET' && r.path.includes('/jobs/')).at(-1);
+ assert.equal(getLog.query.wait_ms, '20000');
+ assert.equal(getLog.query.max, '65536');
+});
+
+test('ADR-105 through the adapter: queued β†’ exited with exit 3 is failed, not completed; 429 backs off', async () => {
+ const srv = adr105Server();
+ srv.setCap(1);
+ const clock = fakeClock();
+ const backend = createRestJobsBackend({ baseUrl: 'https://ruos.cognitum.one', token: 'tok', fetchImpl: srv.f, sleep: clock.sleep });
+ const ledger = fakeLedger();
+ const adapter = new RuosHostAdapter({
+ fleet: fakeFleet([desktop({ heartbeatAt: Math.floor(clock.now() / 1000) })]),
+ jobs: createJobsApiTransport(backend, staging(), () => N),
+ ledger: /** @type {any} */ (ledger), now: clock.now, sleep: clock.sleep,
+ });
+ /** @type {string[]} */ const seen = [];
+ const out = await adapter.run({ desktop: 'Work Desktop', prompt: 'p', runId: RUN, agentId: 'a1', timeoutSecs: 900, onOutput: (c) => seen.push(c.toString()) });
+ assert.equal(out.status, 'failed', '`exited` with exit_code 3');
+ assert.equal(out.exitCode, 3);
+ assert.equal(seen.join(''), 'exit three\n');
+ assert.equal(srv.log.filter((r) => r.method === 'POST').length, 2, 'one 429, one accepted create');
+ assert.equal(srv.log.find((r) => r.method === 'POST' && r.body)?.body.timeout_secs, 900);
+});
+
+test('ADR-105: timeout_secs above 21600 is clamped client-side, never refused', async () => {
+ const srv = adr105Server();
+ const t = createJobsApiTransport(createRestJobsBackend({ baseUrl: 'https://ruos.cognitum.one', token: 'tok', fetchImpl: srv.f }), staging(), () => N);
+ await t.start(desktop(), { runId: RUN, prompt: 'p', runner: 'claude', timeoutSecs: 30000 });
+ assert.equal(srv.log.find((r) => r.method === 'POST')?.body.timeout_secs, 21600);
+});
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 d124c4b4df..b572c70dab 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-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)
+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 (async jobs API, live since 2026-10-01)
## Context
@@ -52,16 +52,31 @@ The adapter drives a `JobTransport` (`jobs.mjs`) through `start`, `poll(offset)`
- 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.
+- **`JobsApiTransport`** targets the ruOS async jobs API. That API is **live in production** since 2026-10-01 (ruos-desktop #380, fleet `64261be`, ruos-desktop ADR-105). `--jobs auto` (the default) feature-detects it with `GET /api/v1/desktop/jobs?machine=` and falls back to exec-poll.
+ - **Auth.** A Bearer token with `desktop:control` scope: a control `ruos_mcp_` token or the OAuth access token.
+ - **Create.** `POST /api/v1/desktop/jobs {machine, command, timeout_secs, idempotency_key}`.
+ - `idempotency_key` is required; it is the run id.
+ - A new job returns `202 {job_id, state}`.
+ - Replaying the same key returns `200 {…, idempotent_replay: true}`; the adapter treats that as success and reuses `job_id`.
+ - The same key with a different request returns `409`. That is a client bug, so it surfaces as `invalid-input` and is never retried.
+ - The per-tenant cap of 4 returns `429`, with no server-side queue. That maps to `capacity`, and the adapter backs off 5 s, 10 s and 20 s, so the queueing happens in the swarm.
+ - `timeout_secs` above 21 600 is clamped by the server; the client clamps too.
+ - **Read.** `GET …/jobs/{id}?offset&max=65536&wait_ms=20000` returns `chunk` (base64), `next_offset`, `running`, `state`, `exit_code`, `truncated`, `desktop` (`up|asleep|unknown`), `stop_at` and more.
+ - `running` stays true while the job is `queued`, meaning "keep polling".
+ - `wait_ms` is a long-poll, so the adapter skips its own sleep, guarded against a server that answers instantly.
+ - `503` means the desktop is up but the poll didn't answer; it is retried with 1 s, 2 s and 4 s backoff.
+ - Polls do not take the desktop's run lock.
+ - **Cancel and list.** `DELETE …/jobs/{id}` sends TERM, then KILL after 10 s, and the job becomes `cancelled`. `GET …/jobs?machine=` lists jobs newest first.
+ - **States.**
+ - `exited` carries any exit code; only 0 counts as `completed`.
+ - `failed` means the launch never reached the desktop, or the job's own timeout fired.
+ - `stopped` is re-pollable after `desktop_start`, so it is surfaced as resumable `auto-stopped`.
+ - `queued`, `running`, `cancelled` and `lost` are the others.
+ - **Errors.** A `404` means "not yours, or gone" and is never retried. 401 maps to `auth-expired`, 403 to `insufficient-scope`.
+ - **Backends.** REST with the tenant token, or the local stdio `@cognitum/ruos` server's `desktop_job_start/poll/list/cancel`. Those tools are stdio-only; the hosted remote MCP is unchanged at 42 tools (ruOS ADR-094).
+ - **Verification status:** **contract-tested, not exercised live.** Mocks reproduce the exact live codes and fields: 202, 200 replay, 409, 429, 503, 404, queued with `running: true`, `exited` with a non-zero code, and `wait_ms`. No live call was made, because no control-scoped token was available and a live run needs separate spend approval. ruOS's own 1195 service tests pass, but it has not yet run a live end-to-end of these endpoints either.
+
+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. Jobs-API polls long-poll server-side instead.
### Command construction
@@ -190,7 +205,7 @@ Residual risk: the remote `claude -p` runs with the desktop user's full trust. T
- The jobs API slots in behind the same interface when it lands.
**Negative:**
-- Until ADR-105 lands, streaming is poll-based over audited exec calls, with about 2 KiB per poll because of the head cap.
+- On the exec-poll fallback, streaming is poll-based over audited exec calls, with about 2 KiB per poll because of the head cap. The jobs API removes that limit, with 64 KiB chunks and long-polling.
- SSH works only desktop to desktop.
## Verification
@@ -219,4 +234,4 @@ Residual risk: the remote `claude -p` runs with the desktop user's full trust. T
Not verified live:
- SSH (6PN-only);
- the env-token terminal path;
-- the jobs API, which is not deployed yet.
+- the jobs API: it is live in production but only contract-tested here (see above).