@dreamtree-org/harness-device 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/package.json +1 -1
- package/src/cli.js +9 -0
- package/src/config.js +7 -0
- package/src/durable.js +103 -0
- package/src/jobs.js +144 -31
- package/src/mcp/server.js +19 -0
- package/src/runloom.js +141 -0
- package/src/serve/scopes.js +1 -1
package/README.md
CHANGED
|
@@ -210,13 +210,25 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
|
|
|
210
210
|
| `workspace_create` / `workspace_list` / `workspace_status` / `workspace_archive` | Per-ticket workspaces of a cloned app. Each is a git worktree under `APPS_DIR/.worktrees/<app>/<ticket>` on branch `ticket/<TICKET>`, created from a pinned revision (`base`, default `origin/<branch>`; the SHA is recorded). It gets its own port (4100–4999, kept across retries) and is registered as the app `<app>--<ticket>`, so every app tool works on it. Creating it again returns the same workspace. Git operations on one repository are serialized by a lock. Archiving stops its process, removes the folder, frees the port and keeps the branch; uncommitted changes make it refuse unless the user agrees to discard them. `REPO_ALLOW` (owner/repo, owner/*) limits which repositories `git_clone` and workspaces accept. Per-workspace databases (`database: true`) answer BLOCKED until the shared development DB provisioner exists; no local database container is started instead |
|
|
211
211
|
| `preview_start` / `preview_list` / `preview_stop` / `preview_screenshot` | Protected previews of an app or workspace. Starts its dev server on its own port if nothing answers there and health-checks it; on failure it returns the app's last output and stops it. A per-preview proxy listens on 127.0.0.1 only and forwards to that one app port. Every request needs a token bound to the preview and its expiry, signed with a device key (`state/preview.key`). The link sets an HttpOnly cookie. The record is checked on each request, so a stopped preview is refused at once, and WebSocket upgrades are checked too. Reach it with the SSH tunnel command it returns. A public ngrok URL is opt-in (`public: true`, user-approved) and still needs the token. `preview_stop` revokes the link, stops the proxy, closes the tunnel and stops the app if the preview started it. Expired previews, and previews whose app or proxy is gone, are ended by `preview_list` and by every watchdog pass (`limits --enforce`). `preview_screenshot` (browser capability) loads it in the device browser and returns a PNG |
|
|
212
212
|
| `shell_exec` (`app exec <app> -- <cmd>`) | One command in the app folder: up to 120s inline, otherwise as a job. Through the pool it needs `device:admin` |
|
|
213
|
+
| `job_submit` | A durable job under an `effect_key`: steps, each an argv as in `exec` (same allowlist). The same key always returns the same job and never runs it twice; the same key with another payload is refused (`EFFECT_KEY_CONFLICT`). Finished steps are checkpointed. `retries` (up to 5, exponential backoff from `retry_backoff_seconds`) resume at the failed step. `artifacts` are recorded with size and sha256 |
|
|
213
214
|
| `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
|
|
214
215
|
|
|
215
216
|
**Recovering a job** (`exec`, clone, setup, deploy):
|
|
216
217
|
- `job_status {id}` shows its status, step, pid and the end of its log; `job_status {id, offset}` continues the log from a byte offset.
|
|
217
218
|
- `job_cancel {id}` ends a stuck one, killing its whole process group (TERM, then KILL after 5s).
|
|
218
219
|
- Records and logs are in `~/.harness-device/state/jobs/` and `logs/jobs/`, and the last 50 are kept. A job the watchdog stops for going over its caps ends as failed, with an event.
|
|
219
|
-
- A job whose runner died
|
|
220
|
+
- A job whose runner died (a crash or a reboot) is settled by the watchdog (`limits --enforce`), or at once by `harness-device job reconcile`:
|
|
221
|
+
- Whatever is left of its process tree is stopped.
|
|
222
|
+
- A `job_submit` job with `retry_interrupted: true` and retry budget left resumes from its last checkpoint.
|
|
223
|
+
- Any other job fails as **uncertain** (a step may have half-run) and is never run again. Check the state before submitting it under a new key.
|
|
224
|
+
|
|
225
|
+
**RunLoom worker** (`harness-device runloom`): this device claims leased tasks from RunLoom; RunLoom stays the scheduler.
|
|
226
|
+
- **Setup:** set `RUNLOOM_URL`, store the worker-pool credential as the device secret `RUNLOOM_CREDENTIAL`, and run it as a registered process (`proc_add`).
|
|
227
|
+
- **Tasks:** a task is an action with `{connector: "harness-device", operation: "job", input: <job_submit payload>}`. It runs as a durable job keyed by the task's `effect_key`, so a re-leased task finds the same job instead of running it again.
|
|
228
|
+
- **Heartbeats** carry `job:<id>:checkpoint:<n>`. A cancel request stops the job's process tree.
|
|
229
|
+
- **Stale leases:** a lost lease (409) stops the reporting, never the job; the next lease reports its result.
|
|
230
|
+
- **Failures** are reported as not retryable: retries happen on the device, within the job's budget.
|
|
231
|
+
- **Routing:** the claim API has no per-device queue yet, so give each device its own worker pool.
|
|
220
232
|
|
|
221
233
|
**Recovering a workspace:**
|
|
222
234
|
- `workspace_status` shows what is uncommitted and how far the branch is ahead.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dreamtree-org/harness-device",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Partha Preetham Krishna",
|
package/src/cli.js
CHANGED
|
@@ -277,6 +277,7 @@ export async function main(argv) {
|
|
|
277
277
|
if (f.enforce) {
|
|
278
278
|
const r = await limits.enforce(ctx);
|
|
279
279
|
try { for (const p of await (await import('./preview.js')).reconcile(ctx)) log.info(`preview ${p.id} ended: ${p.reason}`); } catch (e) { log.warn(`previews: ${e.message}`); }
|
|
280
|
+
try { for (const j of (await import('./jobs.js')).reconcileJobs(ctx)) log.warn(`job ${j.id} interrupted: ${j.action}${j.uncertain ? ' (effect uncertain, not re-run)' : ''}`); } catch (e) { log.warn(`jobs: ${e.message}`); }
|
|
280
281
|
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
281
282
|
for (const a of r.actions) log.warn(`stopped ${a.name}: ${a.reason}`);
|
|
282
283
|
if (!f.quiet && !r.actions.length) log.ok('all within limits');
|
|
@@ -351,11 +352,19 @@ export async function main(argv) {
|
|
|
351
352
|
return console.log(JSON.stringify(preview.listPreviews(ctx), null, 2));
|
|
352
353
|
}
|
|
353
354
|
|
|
355
|
+
case 'runloom': {
|
|
356
|
+
const ctx = loadContext(env);
|
|
357
|
+
const ac = new AbortController();
|
|
358
|
+
for (const sig of ['SIGTERM', 'SIGINT']) process.once(sig, () => { log.info('stopping: in-flight tasks finish first'); ac.abort(); });
|
|
359
|
+
return (await import('./runloom.js')).run(ctx, { signal: ac.signal, log: (m) => log.info(m) });
|
|
360
|
+
}
|
|
361
|
+
|
|
354
362
|
case 'job':
|
|
355
363
|
case 'jobs': {
|
|
356
364
|
const ctx = loadContext(env);
|
|
357
365
|
const jobs = await import('./jobs.js');
|
|
358
366
|
if (sub === 'run') { const j = await jobs.runJob(ctx, rest[0]); process.exitCode = j.status === 'done' ? 0 : 1; return; }
|
|
367
|
+
if (sub === 'reconcile') return console.log(JSON.stringify(jobs.reconcileJobs(ctx), null, 2));
|
|
359
368
|
if (!sub || sub === 'list') return console.log(JSON.stringify(jobs.listJobs(ctx), null, 2));
|
|
360
369
|
return console.log(JSON.stringify(jobs.describeJob(ctx, jobs.getJob(ctx, sub)), null, 2));
|
|
361
370
|
}
|
package/src/config.js
CHANGED
|
@@ -106,6 +106,11 @@ export function defaults(env = process.env) {
|
|
|
106
106
|
// Repositories git_clone and workspaces may use: comma list of owner/repo
|
|
107
107
|
// or owner/* (empty = any).
|
|
108
108
|
REPO_ALLOW: '',
|
|
109
|
+
// RunLoom worker (harness-device runloom): the RunLoom API this device
|
|
110
|
+
// claims leased tasks from, with the worker-pool credential stored as the
|
|
111
|
+
// device secret RUNLOOM_CREDENTIAL. Empty = not a RunLoom worker.
|
|
112
|
+
RUNLOOM_URL: '',
|
|
113
|
+
RUNLOOM_CONCURRENCY: '2',
|
|
109
114
|
};
|
|
110
115
|
}
|
|
111
116
|
|
|
@@ -219,6 +224,8 @@ export function validateConfig(cfg, env = process.env) {
|
|
|
219
224
|
if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
|
|
220
225
|
errs.push(...limitsMod.validate(cfg));
|
|
221
226
|
if (cfg.EXEC_ALLOW && !/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}(,[A-Za-z0-9][A-Za-z0-9._+-]{0,63})*$/.test(String(cfg.EXEC_ALLOW).replace(/\s/g, ''))) errs.push('EXEC_ALLOW must be a comma-separated list of program names.');
|
|
227
|
+
if (cfg.RUNLOOM_URL) { let u = null; try { u = new URL(cfg.RUNLOOM_URL); } catch { /* invalid */ } if (!u || !(u.protocol === 'https:' || ['localhost', '127.0.0.1'].includes(u.hostname)) || u.search || u.hash) errs.push('RUNLOOM_URL must be an https URL (no query), e.g. https://runloom.example.com.'); }
|
|
228
|
+
if (cfg.RUNLOOM_CONCURRENCY && !/^([1-9]|1[0-6])$/.test(String(cfg.RUNLOOM_CONCURRENCY))) errs.push('RUNLOOM_CONCURRENCY must be a number from 1 to 16.');
|
|
222
229
|
if (cfg.REPO_ALLOW && !String(cfg.REPO_ALLOW).split(',').map((x) => x.trim()).filter(Boolean).every((x) => /^[A-Za-z0-9_.-]+\/([A-Za-z0-9_.-]+|\*)$/.test(x))) errs.push('REPO_ALLOW must be a comma-separated list of owner/repo or owner/*.');
|
|
223
230
|
if (cfg.APPS_DIR && (!path.isAbsolute(String(cfg.APPS_DIR)) || /['"\t\n\\$`]/.test(String(cfg.APPS_DIR)))) errs.push('APPS_DIR must be an absolute path without quotes or special characters.');
|
|
224
231
|
if (cfg.POOL_SCOPES !== undefined && !/^device:(read|operate|admin)(,device:(read|operate|admin))*$/.test(String(cfg.POOL_SCOPES).replace(/\s/g, ''))) errs.push('POOL_SCOPES must be a comma-separated list of device:read, device:operate, device:admin.');
|
package/src/durable.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Durable job submission (HARNESS-3): submit a job under an effect key, once.
|
|
2
|
+
//
|
|
3
|
+
// The effect key names the effect, not the attempt: the same key always maps
|
|
4
|
+
// to the same job (its id is derived from the key), so a caller that retries
|
|
5
|
+
// after a timeout, a dropped link or a lost RunLoom lease gets the job that is
|
|
6
|
+
// already running or finished instead of a second run. Submitting the same key
|
|
7
|
+
// with a different payload is refused (EFFECT_KEY_CONFLICT): it would be a
|
|
8
|
+
// different effect under a name already used.
|
|
9
|
+
//
|
|
10
|
+
// The index (state/effects/<sha256(key)>.json) is created with O_EXCL, so two
|
|
11
|
+
// submitters racing on one key cannot both start a job.
|
|
12
|
+
//
|
|
13
|
+
// Payload: { app, steps: [{ argv, cwd? }], env_refs?, timeout_seconds?,
|
|
14
|
+
// max_output_kb?, retries?, retry_backoff_seconds?, retry_interrupted?,
|
|
15
|
+
// artifacts? }. Every step goes through the exec allowlist and confinement
|
|
16
|
+
// (src/exec.js), like the exec tool.
|
|
17
|
+
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { checkExec } from './exec.js';
|
|
22
|
+
import { startJob, getJob } from './jobs.js';
|
|
23
|
+
|
|
24
|
+
export const EFFECT_KEY = /^[\w.:@/-]{8,191}$/;
|
|
25
|
+
const LIMITS = { retries: 5, backoff: 300, timeout: 3600, outputKb: 4096, steps: 20, artifacts: 50 };
|
|
26
|
+
|
|
27
|
+
const sha = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
|
28
|
+
/** JSON with sorted keys: the same payload always hashes the same. */
|
|
29
|
+
export function canonical(v) {
|
|
30
|
+
if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
|
|
31
|
+
if (v && typeof v === 'object') return `{${Object.keys(v).filter((k) => v[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`;
|
|
32
|
+
return JSON.stringify(v ?? null);
|
|
33
|
+
}
|
|
34
|
+
const indexOf = (ctx, key) => path.join(ctx.paths.state, 'effects', `${sha(key)}.json`);
|
|
35
|
+
export const jobIdFor = (key) => `task-${sha(key).slice(0, 24)}`;
|
|
36
|
+
|
|
37
|
+
const fail = (code, message) => Object.assign(new Error(message), { code });
|
|
38
|
+
|
|
39
|
+
/** Check the payload and turn it into startJob options. Throws with a reason. */
|
|
40
|
+
export function plan(ctx, payload) {
|
|
41
|
+
const p = payload || {};
|
|
42
|
+
if (!Array.isArray(p.steps) || !p.steps.length) throw fail('VALIDATION', 'steps: give at least one step, { argv: [program, ...args], cwd? }');
|
|
43
|
+
if (p.steps.length > LIMITS.steps) throw fail('VALIDATION', `steps: at most ${LIMITS.steps}`);
|
|
44
|
+
const int = (v, name, max, dflt) => {
|
|
45
|
+
if (v === undefined || v === null) return dflt;
|
|
46
|
+
if (!Number.isInteger(v) || v < 0 || v > max) throw fail('VALIDATION', `${name} must be a whole number from 0 to ${max}`);
|
|
47
|
+
return v;
|
|
48
|
+
};
|
|
49
|
+
const checked = p.steps.map((s, i) => {
|
|
50
|
+
try { return checkExec(ctx, { app: p.app, argv: s?.argv, cwd: s?.cwd ?? '.', envRefs: p.env_refs || {} }); } catch (e) { throw fail('VALIDATION', `step ${i + 1}: ${e.message}`); }
|
|
51
|
+
});
|
|
52
|
+
const artifacts = p.artifacts === undefined ? null : p.artifacts;
|
|
53
|
+
if (artifacts && (!Array.isArray(artifacts) || artifacts.length > LIMITS.artifacts || artifacts.some((a) => typeof a !== 'string' || !a || path.isAbsolute(a) || a.split(/[\\/]/).includes('..')))) {
|
|
54
|
+
throw fail('VALIDATION', `artifacts: up to ${LIMITS.artifacts} paths relative to the app folder, without ..`);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
kind: 'task', app: checked[0].app.name, appDir: checked[0].app.dir, envRefs: checked[0].envRefs,
|
|
58
|
+
steps: checked.map((c) => ({ name: path.basename(c.exe), argv: c.argv, cwd: c.cwd })),
|
|
59
|
+
timeoutSeconds: int(p.timeout_seconds, 'timeout_seconds', LIMITS.timeout, 600) || 600,
|
|
60
|
+
maxOutputBytes: (int(p.max_output_kb, 'max_output_kb', LIMITS.outputKb, 256) || 256) * 1024,
|
|
61
|
+
retries: int(p.retries, 'retries', LIMITS.retries, 0),
|
|
62
|
+
backoffSeconds: int(p.retry_backoff_seconds, 'retry_backoff_seconds', LIMITS.backoff, 5),
|
|
63
|
+
retryInterrupted: p.retry_interrupted === true,
|
|
64
|
+
artifacts,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Submit `payload` under `effectKey`. Returns { job, existing }: existing=true
|
|
70
|
+
* when the key was already submitted (same payload); the job is not started
|
|
71
|
+
* again. Throws EFFECT_KEY_CONFLICT for the same key with another payload.
|
|
72
|
+
*/
|
|
73
|
+
export async function submit(ctx, { effectKey, payload }) {
|
|
74
|
+
if (!EFFECT_KEY.test(String(effectKey || ''))) throw fail('VALIDATION', 'effect_key: 8-191 characters of letters, digits and . : @ / _ -');
|
|
75
|
+
const hash = sha(canonical(payload || {}));
|
|
76
|
+
const idx = indexOf(ctx, effectKey);
|
|
77
|
+
fs.mkdirSync(path.dirname(idx), { recursive: true });
|
|
78
|
+
const id = jobIdFor(effectKey);
|
|
79
|
+
try {
|
|
80
|
+
fs.writeFileSync(idx, JSON.stringify({ key: effectKey, hash, job: id, at: new Date().toISOString() }), { flag: 'wx', mode: 0o600 });
|
|
81
|
+
} catch (e) {
|
|
82
|
+
if (e.code !== 'EEXIST') throw e;
|
|
83
|
+
const prev = JSON.parse(fs.readFileSync(idx, 'utf8'));
|
|
84
|
+
if (prev.hash !== hash) throw fail('EFFECT_KEY_CONFLICT', `effect_key ${effectKey} was already used for a different payload (job ${prev.job}); use a new key for a different effect`);
|
|
85
|
+
let job;
|
|
86
|
+
try { job = getJob(ctx, prev.job); } catch { throw fail('EFFECT_KEY_EXPIRED', `effect_key ${effectKey} ran as job ${prev.job}, whose record has since been pruned; it is not run again`); }
|
|
87
|
+
return { job, existing: true };
|
|
88
|
+
}
|
|
89
|
+
let opts;
|
|
90
|
+
try { opts = plan(ctx, payload); } catch (e) { fs.rmSync(idx, { force: true }); throw e; }
|
|
91
|
+
// Inline (tests): startJob runs the job and resolves at the end; the record exists at once.
|
|
92
|
+
startJob(ctx, { ...opts, id, effectKey }).catch(() => {});
|
|
93
|
+
return { job: getJob(ctx, id), existing: false };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The result a caller (or RunLoom) gets for a finished job. */
|
|
97
|
+
export function result(ctx, job, tail) {
|
|
98
|
+
return {
|
|
99
|
+
job_id: job.id, effect_key: job.effectKey, status: job.status, exit: job.exit, uncertain: !!job.uncertain,
|
|
100
|
+
timed_out: !!job.timedOut, cancelled: !!job.cancelled, attempts: (job.attempts || []).length, checkpoint: job.checkpoint,
|
|
101
|
+
steps: job.steps.length, artifacts: job.artifactInfo || [], error: job.error || null, output_tail: tail,
|
|
102
|
+
};
|
|
103
|
+
}
|
package/src/jobs.js
CHANGED
|
@@ -7,9 +7,22 @@
|
|
|
7
7
|
// that this module runs in-process (saving the app after a clone, restarting
|
|
8
8
|
// its process). Secrets reach git only through the environment, never the
|
|
9
9
|
// command line, the job file or the log.
|
|
10
|
+
//
|
|
11
|
+
// Durable jobs (HARNESS-3) add, per job:
|
|
12
|
+
// - checkpoint: the number of steps finished; a retry or a resume after a
|
|
13
|
+
// crash starts from there, never re-running finished steps;
|
|
14
|
+
// - retries / backoffSeconds: a bounded retry budget for a failed step
|
|
15
|
+
// (exponential backoff, cancellable); every attempt is kept in `attempts`;
|
|
16
|
+
// - runnerPid / runnerBoot: who runs it, so reconcileJobs() can tell a job
|
|
17
|
+
// whose runner died (crash, reboot) and settle it: the orphaned process
|
|
18
|
+
// tree is killed, and the job is resumed from its checkpoint only when it
|
|
19
|
+
// was declared safe to (retryInterrupted) with budget left; otherwise it
|
|
20
|
+
// fails as "uncertain" (a step may have half-run) and is never re-run;
|
|
21
|
+
// - artifacts: files (relative to the app) recorded with size and sha256.
|
|
10
22
|
|
|
11
23
|
import crypto from 'node:crypto';
|
|
12
24
|
import fs from 'node:fs';
|
|
25
|
+
import os from 'node:os';
|
|
13
26
|
import path from 'node:path';
|
|
14
27
|
import { spawn, spawnSync } from 'node:child_process';
|
|
15
28
|
import { readSecrets } from './context.js';
|
|
@@ -62,9 +75,11 @@ export function tail(file, lines = 80) {
|
|
|
62
75
|
* tokenSecret: the name of a device secret git may use for https://github.com.
|
|
63
76
|
* Returns the job.
|
|
64
77
|
*/
|
|
65
|
-
export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false, timeoutSeconds = null, maxOutputBytes = null, envRefs = null
|
|
66
|
-
|
|
78
|
+
export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false, timeoutSeconds = null, maxOutputBytes = null, envRefs = null,
|
|
79
|
+
id: givenId = null, effectKey = null, retries = 0, backoffSeconds = 5, retryInterrupted = false, artifacts = null, appDir = null }) {
|
|
80
|
+
const id = givenId || `${kind}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`.toLowerCase();
|
|
67
81
|
const job = {
|
|
82
|
+
effectKey, retries, backoffSeconds, retryInterrupted, artifacts, appDir, checkpoint: 0, attempts: [], runnerPid: null, runnerBoot: null, uncertain: false,
|
|
68
83
|
id, kind, app, status: 'queued', step: null,
|
|
69
84
|
steps: steps.map((s) => ({ name: s.name, cmd: s.cmd || null, argv: s.argv || null, cwd: s.cwd || null, internal: s.internal || null, args: s.args || null })),
|
|
70
85
|
tokenSecret, envRefs, timeoutSeconds, maxOutputBytes, exit: null, error: null, pid: null, timedOut: false, cancelRequested: false, cancelled: false,
|
|
@@ -74,6 +89,12 @@ export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inl
|
|
|
74
89
|
prune(ctx);
|
|
75
90
|
fs.mkdirSync(path.dirname(logOf(ctx, id)), { recursive: true });
|
|
76
91
|
if (inline || ctx.env.HD_JOBS_INLINE === '1') return runJob(ctx, id).then(() => getJob(ctx, id));
|
|
92
|
+
launch(ctx, id);
|
|
93
|
+
return Promise.resolve(job);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Start the detached runner of a job (`harness-device job run <id>`). */
|
|
97
|
+
function launch(ctx, id) {
|
|
77
98
|
const bin = path.join(PKG_ROOT, 'bin', 'harness-device.js');
|
|
78
99
|
const args = [process.execPath, bin, 'job', 'run', id];
|
|
79
100
|
if (ctx.platform.id === 'linux' && !scopesWork(ctx.env)) {
|
|
@@ -86,9 +107,13 @@ export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inl
|
|
|
86
107
|
} else {
|
|
87
108
|
ctx.platform.spawnDetached(ctx, `job-${id}`, args, logOf(ctx, id));
|
|
88
109
|
}
|
|
89
|
-
return Promise.resolve(job);
|
|
90
110
|
}
|
|
91
111
|
|
|
112
|
+
/** When this machine booted (seconds, rounded: stable across calls). */
|
|
113
|
+
export const bootTime = () => Math.round((Date.now() / 1000 - os.uptime()) / 30) * 30;
|
|
114
|
+
const alive = (pid) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
115
|
+
const groupAlive = (pgid) => { if (!pgid) return false; try { process.kill(-pgid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
116
|
+
|
|
92
117
|
/** The environment a job gets: never Anthropic keys, pool or serve credentials. */
|
|
93
118
|
export function cleanEnv(env) {
|
|
94
119
|
const e = { ...env };
|
|
@@ -185,7 +210,7 @@ function runStep(ctx, job, step, env, log, redact) {
|
|
|
185
210
|
child.stderr.on('data', (b) => out.write(b));
|
|
186
211
|
let timer = null;
|
|
187
212
|
if (job.timeoutSeconds) {
|
|
188
|
-
const left = Math.max(1, job.timeoutSeconds * 1000 - (Date.now() - Date.parse(job.startedAt)));
|
|
213
|
+
const left = Math.max(1, job.timeoutSeconds * 1000 - (Date.now() - Date.parse(job.attemptStartedAt || job.startedAt)));
|
|
189
214
|
timer = setTimeout(() => { job.timedOut = true; killGroup(child.pid, 3000); }, left);
|
|
190
215
|
}
|
|
191
216
|
child.on('error', (e) => { out.write(`${e.message}\n`); });
|
|
@@ -220,49 +245,137 @@ export async function runJob(ctx, id, internals = {}) {
|
|
|
220
245
|
const redact = (s) => hidden.reduce((acc, h) => acc.split(h).join('***'), s);
|
|
221
246
|
const env = { ...cleanEnv(ctx.env), ...gitAuthEnv(token), ...Object.fromEntries(refs), CI: '1' };
|
|
222
247
|
job.status = 'running';
|
|
223
|
-
job.startedAt
|
|
248
|
+
job.startedAt ||= new Date().toISOString();
|
|
249
|
+
job.runnerPid = process.pid;
|
|
250
|
+
job.runnerBoot = bootTime();
|
|
251
|
+
job.checkpoint ||= 0;
|
|
252
|
+
job.attempts ||= [];
|
|
224
253
|
write(ctx, job);
|
|
225
254
|
const say = (m) => fs.appendFileSync(log, `\n[harness-device] ${m}\n`);
|
|
226
255
|
const builtins = { ...(await import('./project.js')).INTERNALS, ...internals };
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
256
|
+
const cancelled = () => { job.cancelRequested = job.cancelRequested || getJob(ctx, id).cancelRequested; return job.cancelRequested; };
|
|
257
|
+
for (;;) {
|
|
258
|
+
const attempt = { n: job.attempts.length + 1, from: job.checkpoint, startedAt: new Date().toISOString() };
|
|
259
|
+
job.attemptStartedAt = attempt.startedAt;
|
|
260
|
+
job.timedOut = false;
|
|
261
|
+
if (attempt.n > 1) say(`attempt ${attempt.n} of ${(job.retries || 0) + 1}, from step ${job.checkpoint + 1}`);
|
|
262
|
+
try {
|
|
263
|
+
for (let i = job.checkpoint; i < job.steps.length; i++) {
|
|
264
|
+
const s = job.steps[i];
|
|
265
|
+
job.step = i;
|
|
266
|
+
write(ctx, job);
|
|
267
|
+
say(`step ${i + 1}/${job.steps.length}: ${s.name}${s.cmd ? `: ${redact(s.cmd)}` : ''}`);
|
|
268
|
+
if (s.internal) {
|
|
269
|
+
if (!builtins[s.internal]) throw new Error(`unknown internal step ${s.internal}`);
|
|
270
|
+
await builtins[s.internal](ctx, job, s.args || {});
|
|
271
|
+
} else {
|
|
272
|
+
if (cancelled()) throw new Error('cancelled');
|
|
273
|
+
const { code } = await runStep(ctx, job, s, env, log, redact);
|
|
274
|
+
job.pid = null;
|
|
275
|
+
job.exit = code;
|
|
276
|
+
if (cancelled()) throw new Error('cancelled');
|
|
277
|
+
if (job.timedOut) throw new Error(`timed out after ${job.timeoutSeconds}s`);
|
|
278
|
+
if (code !== 0) throw new Error(`"${s.name}" exited with ${code}`);
|
|
279
|
+
}
|
|
280
|
+
job.checkpoint = i + 1; // durable: a retry or a resume starts after this step
|
|
281
|
+
write(ctx, job);
|
|
282
|
+
}
|
|
283
|
+
job.status = 'done';
|
|
284
|
+
job.exit = 0;
|
|
285
|
+
job.attempts.push({ ...attempt, finishedAt: new Date().toISOString(), status: 'done' });
|
|
286
|
+
say('done');
|
|
287
|
+
break;
|
|
288
|
+
} catch (e) {
|
|
289
|
+
job.pid = null;
|
|
290
|
+
job.error = redact(String(e.message || e));
|
|
291
|
+
job.attempts.push({ ...attempt, finishedAt: new Date().toISOString(), status: job.cancelRequested ? 'cancelled' : job.timedOut ? 'timed out' : 'failed', step: job.step, exit: job.exit, error: job.error });
|
|
292
|
+
const left = (job.retries || 0) + 1 - job.attempts.length;
|
|
293
|
+
if (!job.cancelRequested && left > 0) {
|
|
294
|
+
const wait = Math.min(300, (job.backoffSeconds ?? 5) * 2 ** (job.attempts.length - 1));
|
|
295
|
+
say(`${job.error}: retrying in ${wait}s (${left} attempt${left === 1 ? '' : 's'} left)`);
|
|
296
|
+
write(ctx, job);
|
|
297
|
+
const until = Date.now() + wait * 1000;
|
|
298
|
+
while (Date.now() < until && !cancelled()) await new Promise((r) => setTimeout(r, Math.min(250, until - Date.now())));
|
|
299
|
+
if (!job.cancelRequested) continue;
|
|
236
300
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
job.
|
|
240
|
-
job.
|
|
241
|
-
|
|
242
|
-
if (job.timedOut) throw new Error(`timed out after ${job.timeoutSeconds}s`);
|
|
243
|
-
if (code !== 0) throw new Error(`"${s.name}" exited with ${code}`);
|
|
301
|
+
job.cancelled = !!job.cancelRequested;
|
|
302
|
+
job.status = job.cancelled ? 'cancelled' : 'failed';
|
|
303
|
+
if (job.cancelled) job.error = 'cancelled';
|
|
304
|
+
say(`${job.status}: ${job.error}${job.retries ? ` (after ${job.attempts.length} attempt${job.attempts.length === 1 ? '' : 's'})` : ''}`);
|
|
305
|
+
break;
|
|
244
306
|
}
|
|
245
|
-
job.status = 'done';
|
|
246
|
-
job.exit = 0;
|
|
247
|
-
say('done');
|
|
248
|
-
} catch (e) {
|
|
249
|
-
job.cancelled = !!job.cancelRequested;
|
|
250
|
-
job.status = job.cancelled ? 'cancelled' : 'failed';
|
|
251
|
-
job.error = redact(String(e.message || e));
|
|
252
|
-
say(`${job.status}: ${job.error}`);
|
|
253
307
|
}
|
|
308
|
+
if (job.artifacts?.length) job.artifactInfo = recordArtifacts(ctx, job);
|
|
254
309
|
job.pid = null;
|
|
255
310
|
job.finishedAt = new Date().toISOString();
|
|
256
311
|
write(ctx, job);
|
|
257
|
-
if (job.kind === 'exec') {
|
|
312
|
+
if (job.kind === 'exec' || job.kind === 'task') {
|
|
258
313
|
const { event } = await import('./state.js');
|
|
259
314
|
const s0 = job.steps[0] || {};
|
|
260
315
|
const secs = Math.round((Date.parse(job.finishedAt) - Date.parse(job.startedAt)) / 1000);
|
|
261
|
-
event(ctx,
|
|
316
|
+
event(ctx, `${job.kind} ${job.id}: ${s0.argv ? path.basename(s0.argv[0]) : 'shell'}${job.steps.length > 1 ? ` (+${job.steps.length - 1} steps)` : ''} in ${job.app || '?'} → ${job.status}${job.exit !== null ? ` (exit ${job.exit})` : ''}, ${secs}s, ${job.attempts.length} attempt(s), ${job.outputBytes} bytes out`);
|
|
262
317
|
}
|
|
263
318
|
return job;
|
|
264
319
|
}
|
|
265
320
|
|
|
321
|
+
/** Size and sha256 of each declared artifact (paths inside the app folder only). */
|
|
322
|
+
function recordArtifacts(ctx, job) {
|
|
323
|
+
let root;
|
|
324
|
+
try { root = fs.realpathSync(job.steps.find((s) => s.cwd)?.cwd || ''); } catch { return []; }
|
|
325
|
+
const appRoot = job.appDir ? fs.realpathSync(job.appDir) : root;
|
|
326
|
+
return job.artifacts.slice(0, 50).map((rel) => {
|
|
327
|
+
const abs = path.resolve(appRoot, rel);
|
|
328
|
+
let real;
|
|
329
|
+
try { real = fs.realpathSync(abs); } catch { return { path: rel, missing: true }; }
|
|
330
|
+
if (real !== appRoot && !real.startsWith(appRoot + path.sep)) return { path: rel, refused: 'outside the app folder' };
|
|
331
|
+
const st = fs.statSync(real);
|
|
332
|
+
if (!st.isFile()) return { path: rel, refused: 'not a file' };
|
|
333
|
+
const sha256 = st.size <= 512 * 1024 * 1024 ? crypto.createHash('sha256').update(fs.readFileSync(real)).digest('hex') : null;
|
|
334
|
+
return { path: rel, bytes: st.size, sha256 };
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Settle jobs whose runner is gone (the runner crashed, or the machine
|
|
340
|
+
* rebooted): kill what is left of the step's process tree, then resume from
|
|
341
|
+
* the checkpoint (retryInterrupted, with budget left) or fail as uncertain.
|
|
342
|
+
* Returns what was done.
|
|
343
|
+
*/
|
|
344
|
+
export function reconcileJobs(ctx) {
|
|
345
|
+
const out = [];
|
|
346
|
+
for (const job of listJobs(ctx, 10000)) {
|
|
347
|
+
if (!['queued', 'running'].includes(job.status) || !job.runnerPid) continue;
|
|
348
|
+
const rebooted = job.runnerBoot && Math.abs(job.runnerBoot - bootTime()) > 60;
|
|
349
|
+
if (!rebooted && alive(job.runnerPid)) continue;
|
|
350
|
+
const orphan = !rebooted && groupAlive(job.pid);
|
|
351
|
+
if (orphan) killGroup(job.pid, 2000);
|
|
352
|
+
const midStep = job.step !== null && job.step >= (job.checkpoint || 0);
|
|
353
|
+
const why = rebooted ? 'the device rebooted' : 'its runner stopped';
|
|
354
|
+
job.attempts = [...(job.attempts || []), { n: (job.attempts || []).length + 1, from: job.checkpoint || 0, status: 'interrupted', step: job.step, error: why, finishedAt: new Date().toISOString() }];
|
|
355
|
+
job.pid = null;
|
|
356
|
+
const left = (job.retries || 0) + 1 - job.attempts.length;
|
|
357
|
+
if (job.retryInterrupted && left > 0 && !job.cancelRequested) {
|
|
358
|
+
job.status = 'queued';
|
|
359
|
+
write(ctx, job);
|
|
360
|
+
fs.appendFileSync(logOf(ctx, job.id), `\n[harness-device] interrupted (${why}${orphan ? '; its leftover processes were stopped' : ''}): resuming from step ${(job.checkpoint || 0) + 1}\n`);
|
|
361
|
+
if (ctx.env.HD_JOBS_INLINE === '1') runJob(ctx, job.id).catch(() => {}); else launch(ctx, job.id);
|
|
362
|
+
out.push({ id: job.id, action: 'resumed', from: job.checkpoint || 0, orphanKilled: orphan });
|
|
363
|
+
} else {
|
|
364
|
+
job.status = job.cancelRequested ? 'cancelled' : 'failed';
|
|
365
|
+
job.cancelled = !!job.cancelRequested;
|
|
366
|
+
job.uncertain = midStep && !job.cancelRequested;
|
|
367
|
+
job.error = job.uncertain
|
|
368
|
+
? `interrupted mid-step ${job.step + 1} (${why}): its effect is uncertain, so it was not run again; check the state before retrying`
|
|
369
|
+
: `interrupted (${why})`;
|
|
370
|
+
job.finishedAt = new Date().toISOString();
|
|
371
|
+
write(ctx, job);
|
|
372
|
+
fs.appendFileSync(logOf(ctx, job.id), `\n[harness-device] ${job.status}: ${job.error}\n`);
|
|
373
|
+
out.push({ id: job.id, action: job.status, uncertain: job.uncertain, orphanKilled: orphan });
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return out;
|
|
377
|
+
}
|
|
378
|
+
|
|
266
379
|
/** Status plus the end of the log, for job_status. */
|
|
267
380
|
export function describeJob(ctx, job, lines = 80) {
|
|
268
381
|
return { ...job, log: tail(logOf(ctx, job.id), lines) };
|
package/src/mcp/server.js
CHANGED
|
@@ -251,6 +251,25 @@ export function buildServer(env = process.env, opts = {}) {
|
|
|
251
251
|
async (c, a) => ({ content: [{ type: 'image', data: await preview.screenshot(c, a.id, { width: a.width, height: a.height }), mimeType: 'image/png' }] }));
|
|
252
252
|
}
|
|
253
253
|
|
|
254
|
+
tool('job_submit', 'Submit a durable job under an effect key: steps run in order without a shell (each argv as in exec, same allowlist), in an app folder. The same effect_key always returns the same job (never run twice); the same key with a different payload is refused (EFFECT_KEY_CONFLICT). Finished steps are checkpointed: retries (0-5, exponential backoff from retry_backoff_seconds) resume at the failed step. If the device restarts mid-job, the job fails as uncertain (not re-run) unless retry_interrupted=true says its steps are safe to resume. artifacts: files (relative to the app) recorded with size and sha256. Waits up to wait_seconds (default 30), then follow it with job_status; stop it with job_cancel.',
|
|
255
|
+
{ effect_key: z.string().regex(/^[\w.:@/-]{8,191}$/), app: APP, steps: z.array(z.object({ argv: z.array(z.string().max(8000)).min(1).max(200), cwd: z.string().max(500).optional() })).min(1).max(20),
|
|
256
|
+
env_refs: z.record(z.string(), z.string()).optional(), timeout_seconds: z.number().int().min(1).max(3600).optional(), max_output_kb: z.number().int().min(1).max(4096).optional(),
|
|
257
|
+
retries: z.number().int().min(0).max(5).optional(), retry_backoff_seconds: z.number().int().min(0).max(300).optional(), retry_interrupted: z.boolean().optional(),
|
|
258
|
+
artifacts: z.array(z.string().max(500)).max(50).optional(), wait_seconds: z.number().int().min(0).max(120).optional(), ...FORCE },
|
|
259
|
+
async (c, a) => {
|
|
260
|
+
await guard(c, a, `submitting a job in ${a.app}`);
|
|
261
|
+
const { effect_key: effectKey, wait_seconds: wait, confirm: _c, force: _f, ...payload } = a;
|
|
262
|
+
const durable = await import('../durable.js');
|
|
263
|
+
let r;
|
|
264
|
+
try { r = await durable.submit(c, { effectKey, payload }); } catch (e) { if (e.code) return { isError: true, content: [{ type: 'text', text: `${e.code}: ${e.message}` }] }; throw e; }
|
|
265
|
+
const deadline = Date.now() + Math.min(wait ?? 30, 120) * 1000;
|
|
266
|
+
let job = r.job;
|
|
267
|
+
while (['queued', 'running'].includes(job.status) && Date.now() < deadline) { await new Promise((res) => setTimeout(res, 200)); job = jobs.getJob(c, job.id); }
|
|
268
|
+
const done = !['queued', 'running'].includes(job.status);
|
|
269
|
+
return { ...(done && job.status !== 'done' ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify({ ...durable.result(c, job, jobs.tail(jobs.logOf(c, job.id), 40)), existing: r.existing,
|
|
270
|
+
...(done ? {} : { next: `still running: job_status {"id":"${job.id}"}; job_cancel to stop it` }) }, null, 2) }] };
|
|
271
|
+
});
|
|
272
|
+
|
|
254
273
|
tool('job_cancel', 'Stop a running job (exec, clone, setup, deploy…): its whole process tree is terminated (TERM, then KILL after 5s); the job ends as cancelled.',
|
|
255
274
|
{ id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
|
|
256
275
|
async (c, a) => text(jobs.cancelJob(c, a.id)));
|
package/src/runloom.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// RunLoom lease adapter (HARNESS-3): this device as a RunLoom worker.
|
|
2
|
+
//
|
|
3
|
+
// RunLoom stays the scheduler (no second one here). The device claims leased
|
|
4
|
+
// `action` tasks from RunLoom's internal worker API with a worker-pool
|
|
5
|
+
// credential, the same contract as RunLoom's own Node worker
|
|
6
|
+
// (apps/workers-node/src/engine/worker.ts):
|
|
7
|
+
// POST /internal/v1/tasks/claim { max, wait_ms, worker_id, worker_version }
|
|
8
|
+
// POST /internal/v1/tasks/:id/heartbeat { lease_token, checkpoint_ref? } → { cancel_requested } | 409 STALE_LEASE
|
|
9
|
+
// POST /internal/v1/tasks/:id/complete { lease_token, output } → 200 | 409
|
|
10
|
+
// POST /internal/v1/tasks/:id/fail { lease_token, error_class, message, retryable } → 200 | 409
|
|
11
|
+
//
|
|
12
|
+
// A task for this device is an action with payload
|
|
13
|
+
// { connector: 'harness-device', operation: 'job', input: <durable job payload> }
|
|
14
|
+
// and is run as a durable job keyed by the task's effect_key (src/durable.js).
|
|
15
|
+
// So:
|
|
16
|
+
// - a retried task (new lease, same effect key) finds the same job: it is
|
|
17
|
+
// never run twice; its result is reported when it ends;
|
|
18
|
+
// - a lost lease (heartbeat or report answers 409) stops reporting, never the
|
|
19
|
+
// job: the next lease on the effect key picks up the same job;
|
|
20
|
+
// - cancel_requested cancels the job's process tree;
|
|
21
|
+
// - retries happen on the device (the job's budget); RunLoom gets one result,
|
|
22
|
+
// and failures are reported non-retryable so the engine does not run the
|
|
23
|
+
// effect again on top of the device's own retries.
|
|
24
|
+
//
|
|
25
|
+
// Routing: the claim API has no per-device task kind or queue yet, so a device
|
|
26
|
+
// gets RunLoom work by holding its own worker-pool credential (a pool per
|
|
27
|
+
// device); a shared pool would let any of its workers claim the task.
|
|
28
|
+
|
|
29
|
+
import os from 'node:os';
|
|
30
|
+
import { readSecrets } from './context.js';
|
|
31
|
+
import { PKG } from './util.js';
|
|
32
|
+
import * as durable from './durable.js';
|
|
33
|
+
import { getJob, cancelJob, tail, logOf, reconcileJobs } from './jobs.js';
|
|
34
|
+
|
|
35
|
+
export const CONNECTOR = 'harness-device';
|
|
36
|
+
const VERSION = PKG.version;
|
|
37
|
+
|
|
38
|
+
/** The worker API over HTTP, authenticated as this device's pool. */
|
|
39
|
+
export function httpClient({ url, credential, workerId, waitMs = 10_000, fetch: f = fetch }) {
|
|
40
|
+
const call = async (p, body) => {
|
|
41
|
+
const res = await f(`${url.replace(/\/$/, '')}/internal/v1/tasks${p}`, {
|
|
42
|
+
method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${credential}` }, body: JSON.stringify(body),
|
|
43
|
+
});
|
|
44
|
+
const json = await res.json().catch(() => ({}));
|
|
45
|
+
if (res.status >= 500 || res.status === 401 || res.status === 400) throw new Error(`RunLoom ${p} answered ${res.status} ${json.error?.code ?? ''}`.trim());
|
|
46
|
+
return { status: res.status, json };
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
async claim(max) { return (await call('/claim', { max, wait_ms: waitMs, worker_id: workerId, worker_version: VERSION })).json.data ?? []; },
|
|
50
|
+
async heartbeat(task, checkpointRef) {
|
|
51
|
+
const r = await call(`/${task.id}/heartbeat`, { lease_token: task.lease_token, ...(checkpointRef ? { checkpoint_ref: checkpointRef } : {}) });
|
|
52
|
+
return r.status === 409 ? null : (r.json.data ?? { cancel_requested: false });
|
|
53
|
+
},
|
|
54
|
+
async complete(task, output) { return (await call(`/${task.id}/complete`, { lease_token: task.lease_token, output })).status === 200; },
|
|
55
|
+
async fail(task, failure) { return (await call(`/${task.id}/fail`, { lease_token: task.lease_token, ...failure })).status === 200; },
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const FAILURE = {
|
|
60
|
+
VALIDATION: 'ValidationError', EFFECT_KEY_CONFLICT: 'EffectKeyConflict', EFFECT_KEY_EXPIRED: 'EffectKeyExpired',
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** Run one claimed task to its report. Returns what happened (for logs and tests). */
|
|
64
|
+
export async function handleTask(ctx, task, client, { log = () => {}, pollMs = 250 } = {}) {
|
|
65
|
+
const p = task.payload || {};
|
|
66
|
+
if (p.connector !== CONNECTOR || p.operation !== 'job') {
|
|
67
|
+
await client.fail(task, { error_class: 'UnknownConnector', message: `${p.connector}.${p.operation} is not run by harness-device (it runs ${CONNECTOR}.job)`, retryable: false });
|
|
68
|
+
return { outcome: 'refused' };
|
|
69
|
+
}
|
|
70
|
+
let job;
|
|
71
|
+
let existing;
|
|
72
|
+
try {
|
|
73
|
+
({ job, existing } = await durable.submit(ctx, { effectKey: task.effect_key, payload: p.input }));
|
|
74
|
+
} catch (e) {
|
|
75
|
+
const ok = await client.fail(task, { error_class: FAILURE[e.code] || 'Error', message: String(e.message).slice(0, 2000), retryable: false });
|
|
76
|
+
return { outcome: ok ? 'failed' : 'stale', error: e.code };
|
|
77
|
+
}
|
|
78
|
+
log(`task ${task.id} (${task.mission_id}/${task.step_id} attempt ${task.attempt}) → job ${job.id}${existing ? ' (already submitted: not run again)' : ''}`);
|
|
79
|
+
|
|
80
|
+
let leaseLost = false;
|
|
81
|
+
let cancelAsked = false;
|
|
82
|
+
const beatEvery = Math.max(250, Math.floor((task.heartbeat_ms || 30_000) / 3));
|
|
83
|
+
let nextBeat = 0;
|
|
84
|
+
for (;;) {
|
|
85
|
+
job = getJob(ctx, job.id);
|
|
86
|
+
if (!['queued', 'running'].includes(job.status)) break;
|
|
87
|
+
if (Date.now() >= nextBeat) {
|
|
88
|
+
nextBeat = Date.now() + beatEvery;
|
|
89
|
+
try {
|
|
90
|
+
const r = await client.heartbeat(task, `job:${job.id}:checkpoint:${job.checkpoint || 0}`);
|
|
91
|
+
if (r === null) { leaseLost = true; break; }
|
|
92
|
+
if (r.cancel_requested && !cancelAsked) { cancelAsked = true; cancelJob(ctx, job.id); log(`task ${task.id}: cancel requested → job ${job.id} cancelled`); }
|
|
93
|
+
} catch (e) { log(`task ${task.id}: heartbeat failed: ${e.message}`); }
|
|
94
|
+
}
|
|
95
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
96
|
+
}
|
|
97
|
+
if (leaseLost) {
|
|
98
|
+
log(`task ${task.id}: lease lost (stale); job ${job.id} keeps running and is reported on the next lease of ${task.effect_key}`);
|
|
99
|
+
return { outcome: 'stale', job: job.id };
|
|
100
|
+
}
|
|
101
|
+
const out = durable.result(ctx, job, tail(logOf(ctx, job.id), 40).slice(-4000));
|
|
102
|
+
const ok = job.status === 'done'
|
|
103
|
+
? await client.complete(task, out)
|
|
104
|
+
: await client.fail(task, {
|
|
105
|
+
error_class: job.cancelled ? 'Cancelled' : job.uncertain ? 'EffectUncertain' : job.timedOut ? 'Timeout' : 'JobFailed',
|
|
106
|
+
message: `job ${job.id} ${job.status}${job.exit !== null ? ` (exit ${job.exit})` : ''} after ${out.attempts} attempt(s): ${job.error || ''}`.slice(0, 2000),
|
|
107
|
+
retryable: false,
|
|
108
|
+
});
|
|
109
|
+
if (!ok) log(`task ${task.id}: the lease went stale before the report; job ${job.id} is ${job.status} and is reported on the next lease`);
|
|
110
|
+
return { outcome: ok ? job.status : 'stale', job: job.id };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Claim and run tasks until `signal` aborts; in-flight tasks finish (their jobs keep running anyway). */
|
|
114
|
+
export async function workerLoop(ctx, { client, concurrency = 2, signal, log = () => {}, idleMs = 250, errorMs = 2000 }) {
|
|
115
|
+
for (const r of reconcileJobs(ctx)) log(`job ${r.id}: ${r.action}${r.uncertain ? ' (uncertain effect)' : ''}`);
|
|
116
|
+
const inFlight = new Set();
|
|
117
|
+
const pause = (ms) => new Promise((res) => { const t = setTimeout(res, ms); signal?.addEventListener('abort', () => { clearTimeout(t); res(); }, { once: true }); });
|
|
118
|
+
while (!signal?.aborted) {
|
|
119
|
+
if (inFlight.size >= concurrency) { await Promise.race(inFlight); continue; }
|
|
120
|
+
let tasks = [];
|
|
121
|
+
try { tasks = await client.claim(concurrency - inFlight.size); } catch (e) { log(`claim failed: ${e.message}`); await pause(errorMs); continue; }
|
|
122
|
+
if (!tasks.length) { await pause(idleMs); continue; }
|
|
123
|
+
for (const t of tasks) {
|
|
124
|
+
const p = handleTask(ctx, t, client, { log }).catch((e) => log(`task ${t.id} crashed: ${e.message}`));
|
|
125
|
+
const tracked = p.finally(() => inFlight.delete(tracked));
|
|
126
|
+
inFlight.add(tracked);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
await Promise.all(inFlight);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** `harness-device runloom`: RUNLOOM_URL from config, the pool credential from the device secret RUNLOOM_CREDENTIAL. */
|
|
133
|
+
export async function run(ctx, { signal, log = console.log } = {}) {
|
|
134
|
+
const url = ctx.cfg.RUNLOOM_URL;
|
|
135
|
+
const credential = readSecrets(ctx.paths.secrets).RUNLOOM_CREDENTIAL;
|
|
136
|
+
if (!url) throw new Error('Set RUNLOOM_URL (harness-device config set RUNLOOM_URL=https://…) to the RunLoom API.');
|
|
137
|
+
if (!credential) throw new Error('Store the RunLoom worker-pool credential as the device secret RUNLOOM_CREDENTIAL (harness-device secrets set RUNLOOM_CREDENTIAL).');
|
|
138
|
+
const workerId = `harness-device:${ctx.cfg.DEVICE || os.hostname()}`;
|
|
139
|
+
log(`RunLoom worker ${workerId} → ${url}`);
|
|
140
|
+
await workerLoop(ctx, { client: httpClient({ url, credential, workerId }), concurrency: Number(ctx.cfg.RUNLOOM_CONCURRENCY) || 2, signal, log });
|
|
141
|
+
}
|
package/src/serve/scopes.js
CHANGED
|
@@ -15,7 +15,7 @@ const TOOLS = {
|
|
|
15
15
|
'app_list', 'file_read', 'job_status', 'workspace_list', 'workspace_status', 'preview_list', 'preview_screenshot'],
|
|
16
16
|
'device:operate': ['proc_add', 'proc_remove', 'session_new', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit',
|
|
17
17
|
'git_clone', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage',
|
|
18
|
-
'exec', 'job_cancel', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
|
|
18
|
+
'exec', 'job_submit', 'job_cancel', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
|
|
19
19
|
// shell_exec is not listed: it needs device:admin (unknown tools do).
|
|
20
20
|
};
|
|
21
21
|
|