@artieeez/cf-worker-runtime 0.0.0-stage → 0.2.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.
Files changed (52) hide show
  1. package/README.md +12 -2
  2. package/dist/agents.d.ts +64 -0
  3. package/dist/agents.d.ts.map +1 -0
  4. package/dist/agents.js +324 -0
  5. package/dist/agents.js.map +1 -0
  6. package/dist/exec.d.ts +36 -0
  7. package/dist/exec.d.ts.map +1 -0
  8. package/dist/exec.js +186 -0
  9. package/dist/exec.js.map +1 -0
  10. package/dist/fatal.d.ts +5 -0
  11. package/dist/fatal.d.ts.map +1 -0
  12. package/dist/fatal.js +5 -0
  13. package/dist/fatal.js.map +1 -0
  14. package/dist/health.d.ts +49 -0
  15. package/dist/health.d.ts.map +1 -0
  16. package/dist/health.js +97 -0
  17. package/dist/health.js.map +1 -0
  18. package/dist/index.d.ts +80 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +1058 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/provenance.d.ts +11 -0
  23. package/dist/provenance.d.ts.map +1 -0
  24. package/dist/provenance.js +74 -0
  25. package/dist/provenance.js.map +1 -0
  26. package/dist/run.d.ts +17 -0
  27. package/dist/run.d.ts.map +1 -0
  28. package/dist/run.js +37 -0
  29. package/dist/run.js.map +1 -0
  30. package/dist/sessions.d.ts +14 -0
  31. package/dist/sessions.d.ts.map +1 -0
  32. package/dist/sessions.js +98 -0
  33. package/dist/sessions.js.map +1 -0
  34. package/dist/steps.d.ts +25 -0
  35. package/dist/steps.d.ts.map +1 -0
  36. package/dist/steps.js +62 -0
  37. package/dist/steps.js.map +1 -0
  38. package/dist/workspaces.d.ts +37 -0
  39. package/dist/workspaces.d.ts.map +1 -0
  40. package/dist/workspaces.js +68 -0
  41. package/dist/workspaces.js.map +1 -0
  42. package/package.json +78 -3
  43. package/src/agents.ts +387 -0
  44. package/src/exec.ts +184 -0
  45. package/src/fatal.ts +4 -0
  46. package/src/health.ts +119 -0
  47. package/src/index.ts +1142 -0
  48. package/src/provenance.ts +74 -0
  49. package/src/run.ts +40 -0
  50. package/src/sessions.ts +98 -0
  51. package/src/steps.ts +85 -0
  52. package/src/workspaces.ts +81 -0
@@ -0,0 +1,74 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { arch, hostname, platform } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import type { Provenance } from '@artieeez/cf-core';
7
+
8
+ /** The code-factory packages whose versions a worker reports, when they resolve from it. */
9
+ export const PROVENANCE_PACKAGES = ['@artieeez/cf-worker-runtime', '@artieeez/cf-sdk', '@artieeez/cf-runner-claude-code', '@cf/runner-fake'];
10
+
11
+ /** The `version` of the nearest `package.json` named `name` at or above `file`. */
12
+ function versionAbove(file: string, name: string): string | undefined {
13
+ let dir = dirname(file);
14
+ for (;;) {
15
+ const p = join(dir, 'package.json');
16
+ if (existsSync(p)) {
17
+ const pkg = JSON.parse(readFileSync(p, 'utf8')) as { name?: string; version?: string };
18
+ if (pkg.name === name) return pkg.version;
19
+ }
20
+ const up = dirname(dir);
21
+ if (up === dir) return undefined;
22
+ dir = up;
23
+ }
24
+ }
25
+
26
+ /** Versions of `names` that resolve from this module, the main script or the cwd. */
27
+ function packageVersions(names: string[], cwd: string): Record<string, string> {
28
+ const froms = [import.meta.filename, process.argv[1] ? resolve(process.argv[1]) : undefined, join(cwd, 'noop.js')];
29
+ const out: Record<string, string> = {};
30
+ for (const name of names) {
31
+ for (const from of froms) {
32
+ if (from === undefined) continue;
33
+ try {
34
+ const version = versionAbove(createRequire(from).resolve(name), name);
35
+ if (version !== undefined) {
36
+ out[name] = version;
37
+ break;
38
+ }
39
+ } catch {
40
+ /* not resolvable from there */
41
+ }
42
+ }
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** `CF_BUILD_COMMIT`, else the git `HEAD` of `cwd` with `dirty`, else nothing (door 5). */
48
+ export function commitOf(env: NodeJS.ProcessEnv, cwd: string): { commit?: string; dirty?: boolean } {
49
+ const fromEnv = env['CF_BUILD_COMMIT'];
50
+ if (fromEnv) return { commit: fromEnv };
51
+ try {
52
+ const git = (args: string[]) =>
53
+ execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
54
+ const commit = git(['rev-parse', 'HEAD']);
55
+ return { commit, dirty: git(['status', '--porcelain']) !== '' };
56
+ } catch {
57
+ return {};
58
+ }
59
+ }
60
+
61
+ /** What runs this worker, sent at register and stamped on each `unit.leased` (run-workspace door 5). */
62
+ export function provenance(worker: string, env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): Provenance {
63
+ return {
64
+ v: 1,
65
+ worker,
66
+ node: process.version,
67
+ platform: `${platform()}-${arch()}`,
68
+ packages: packageVersions(PROVENANCE_PACKAGES, cwd),
69
+ ...commitOf(env, cwd),
70
+ plugins: {},
71
+ // which replica of the worker this process is (worker-tokens door 4)
72
+ host: hostname(),
73
+ };
74
+ }
package/src/run.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { AgentRunner } from '@artieeez/cf-sdk';
2
+ import { pickAgent } from './agents.ts';
3
+ import { WorkerFatalError } from './fatal.ts';
4
+ import { startWorker, type WorkerOptions } from './index.ts';
5
+
6
+ export interface RunWorkerOptions extends Omit<WorkerOptions, 'signal' | 'kill' | 'agent'> {
7
+ /** the runners `ctx.agent` may call, by the name `CF_AGENT_RUNNER` picks (AD-029) */
8
+ agents?: Record<string, AgentRunner>;
9
+ }
10
+
11
+ /**
12
+ * A worker process's whole entry (door 1): picks the agent runner, runs `startWorker`, and on a
13
+ * `WorkerFatalError` prints its message to stderr and exits 1. The first SIGINT or SIGTERM stops
14
+ * it: it leases no more and lets its units in flight finish for up to `CF_DRAIN_TIMEOUT_MS`
15
+ * (AD-090); a second one drops them at once. Any other error before a stop rejects; one after a
16
+ * stop is ignored.
17
+ *
18
+ * await runWorker({ name: 'hello-worker', workflows: [hello], agents: { fake, 'claude-code': runClaudeCode } });
19
+ */
20
+ export async function runWorker(opts: RunWorkerOptions): Promise<void> {
21
+ const { agents, ...rest } = opts;
22
+ const stop = new AbortController();
23
+ const kill = new AbortController();
24
+ const onSignal = () => (stop.signal.aborted ? kill.abort() : stop.abort());
25
+ process.on('SIGINT', onSignal);
26
+ process.on('SIGTERM', onSignal);
27
+ try {
28
+ const agent = pickAgent(process.env, agents);
29
+ await startWorker({ ...rest, ...(agent !== undefined ? { agent } : {}), signal: stop.signal, kill: kill.signal });
30
+ } catch (err) {
31
+ if (err instanceof WorkerFatalError) {
32
+ console.error(err.message);
33
+ process.exit(1);
34
+ }
35
+ if (!stop.signal.aborted) throw err;
36
+ } finally {
37
+ process.off('SIGINT', onSignal);
38
+ process.off('SIGTERM', onSignal);
39
+ }
40
+ }
@@ -0,0 +1,98 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import type { AgentSessions, PersistedSession } from '@artieeez/cf-sdk';
4
+ import { inside } from './exec.ts';
5
+
6
+ /** Session ids safe to delete inside `<configDir>/projects/<project>/` (AD-066). */
7
+ export const SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
8
+
9
+ function isSafeSessionId(id: string): boolean {
10
+ return id !== '.' && id !== '..' && SAFE_SESSION_ID.test(id);
11
+ }
12
+
13
+ /** Path of a run's local session ledger under the workspace root (beside `.ready/<runId>`). */
14
+ export function sessionLedgerPath(root: string, runId: string): string {
15
+ return join(root, '.sessions', `${runId}.jsonl`);
16
+ }
17
+
18
+ function readLedger(ledgerPath: string): PersistedSession[] {
19
+ if (!existsSync(ledgerPath)) return [];
20
+ const entries: PersistedSession[] = [];
21
+ for (const line of readFileSync(ledgerPath, 'utf8').split('\n')) {
22
+ if (line.trim() === '') continue;
23
+ try {
24
+ const parsed = JSON.parse(line) as Record<string, unknown>;
25
+ if (
26
+ typeof parsed['runner'] === 'string' &&
27
+ typeof parsed['sessionId'] === 'string' &&
28
+ typeof parsed['configDir'] === 'string' &&
29
+ typeof parsed['cwd'] === 'string'
30
+ ) {
31
+ entries.push({
32
+ runner: parsed['runner'],
33
+ sessionId: parsed['sessionId'],
34
+ configDir: parsed['configDir'],
35
+ cwd: parsed['cwd'],
36
+ });
37
+ }
38
+ } catch {
39
+ // ignore corrupted ledger lines
40
+ }
41
+ }
42
+ return entries;
43
+ }
44
+
45
+ /** Per-run session ledger backed by `<workspaceRoot>/.sessions/<runId>.jsonl` (AD-066). */
46
+ export function createRunSessions(root: string, runId: string): AgentSessions {
47
+ const ledgerPath = sessionLedgerPath(root, runId);
48
+ return {
49
+ record(entry) {
50
+ if (entry.sessionId === '') return;
51
+ const existing = readLedger(ledgerPath);
52
+ if (
53
+ existing.some(
54
+ (e) => e.runner === entry.runner && e.sessionId === entry.sessionId && e.configDir === entry.configDir,
55
+ )
56
+ ) {
57
+ return;
58
+ }
59
+ mkdirSync(dirname(ledgerPath), { recursive: true });
60
+ appendFileSync(ledgerPath, JSON.stringify(entry) + '\n');
61
+ },
62
+ has(sessionId, configDir) {
63
+ if (sessionId === '') return false;
64
+ return readLedger(ledgerPath).some((e) => e.sessionId === sessionId && e.configDir === configDir);
65
+ },
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Deletes every recorded `<sessionId>.jsonl` and `<sessionId>` directory under
71
+ * `<configDir>/projects/<project>/` for `runId`, then deletes the run's ledger file (AD-066).
72
+ * Never touches sibling runs' sessions, non-session account files, or invalid/traversal ids.
73
+ */
74
+ export function cleanupRunSessions(root: string, runId: string): void {
75
+ const ledgerPath = sessionLedgerPath(root, runId);
76
+ const entries = readLedger(ledgerPath);
77
+ for (const entry of entries) {
78
+ if (!isSafeSessionId(entry.sessionId)) continue;
79
+ if (entry.configDir === '') continue;
80
+ const projectsDir = resolve(entry.configDir, 'projects');
81
+ if (!existsSync(projectsDir)) continue;
82
+ let projects: { name: string; isDirectory(): boolean }[];
83
+ try {
84
+ projects = readdirSync(projectsDir, { withFileTypes: true });
85
+ } catch {
86
+ continue;
87
+ }
88
+ for (const proj of projects) {
89
+ if (!proj.isDirectory()) continue;
90
+ const projDir = join(projectsDir, proj.name);
91
+ for (const target of [join(projDir, `${entry.sessionId}.jsonl`), join(projDir, entry.sessionId)]) {
92
+ if (!inside(projDir, target)) continue;
93
+ if (existsSync(target)) rmSync(target, { recursive: true, force: true });
94
+ }
95
+ }
96
+ }
97
+ rmSync(ledgerPath, { force: true });
98
+ }
package/src/steps.ts ADDED
@@ -0,0 +1,85 @@
1
+ import { parsePath } from '@artieeez/cf-core';
2
+ import type { AnyStep, Body, VisitRecord, WorkflowDefinition } from '@artieeez/cf-sdk';
3
+
4
+ /** Where a step object sits in its workflow: the fan-outs it is nested in, then its id. */
5
+ interface Place {
6
+ /** each enclosing fan-out, outermost first; a parallel branch names its branch */
7
+ fanouts: { step: string; branch?: string }[];
8
+ id: string;
9
+ }
10
+
11
+ const shown = (p: Place) => [...p.fanouts.map((f) => (f.branch === undefined ? f.step : `${f.step}.${f.branch}`)), p.id].join('.');
12
+
13
+ /** Every step object of a workflow, at every depth, with each place it is used. */
14
+ export function stepIndex(def: WorkflowDefinition): Map<object, Place[]> {
15
+ const index = new Map<object, Place[]>();
16
+ const walk = (steps: Record<string, AnyStep>, fanouts: Place['fanouts']) => {
17
+ for (const [id, step] of Object.entries(steps)) {
18
+ index.set(step, [...(index.get(step) ?? []), { fanouts, id }]);
19
+ if (step.kind === 'map') walk((step.body as Body).steps, [...fanouts, { step: id }]);
20
+ if (step.kind === 'parallel') {
21
+ for (const [branch, body] of Object.entries(step.branches)) walk(body.steps, [...fanouts, { step: id, branch }]);
22
+ }
23
+ }
24
+ };
25
+ walk(def.steps as Record<string, AnyStep>, []);
26
+ return index;
27
+ }
28
+
29
+ /**
30
+ * Resolves `step` in `index` to its key in `ctx.outputs` or `ctx.visits`: top-level id, or its
31
+ * concrete path in the branch `unitPath` runs in; `undefined` when outside that branch.
32
+ */
33
+ function stepKey(
34
+ index: Map<object, Place[]>,
35
+ workflow: string,
36
+ step: object,
37
+ unitPath: string,
38
+ byId: 'ctx.outputs' | 'ctx.visits',
39
+ ): string | undefined {
40
+ const places = index.get(step);
41
+ if (places === undefined) throw new Error(`step is not in workflow ${workflow}`);
42
+ if (places.length > 1) throw new Error(`step is used as ${places.map(shown).join(', ')}; read ${byId} by id`);
43
+ const place = places[0]!;
44
+ if (place.fanouts.length === 0) return place.id;
45
+ const segs = parsePath(unitPath);
46
+ const concrete: string[] = [];
47
+ for (const [i, f] of place.fanouts.entries()) {
48
+ const seg = segs[i];
49
+ if (seg === undefined || seg.step !== f.step || seg.key === undefined) return undefined;
50
+ if (f.branch !== undefined && seg.key !== f.branch) return undefined;
51
+ concrete.push(`${seg.step}[${seg.key}]`);
52
+ }
53
+ return [...concrete, place.id].join('.');
54
+ }
55
+
56
+ /**
57
+ * `ctx.output(step)`: the step's latest output in `outputs`, under its id at the top level, or
58
+ * under its path in the branch the unit at `unitPath` runs in; `undefined` from outside it.
59
+ */
60
+ export function outputOf(
61
+ index: Map<object, Place[]>,
62
+ workflow: string,
63
+ step: object,
64
+ unitPath: string,
65
+ outputs: Record<string, unknown>,
66
+ ): unknown {
67
+ const key = stepKey(index, workflow, step, unitPath, 'ctx.outputs');
68
+ return key !== undefined && Object.hasOwn(outputs, key) ? outputs[key] : undefined;
69
+ }
70
+
71
+ /**
72
+ * `ctx.visitsOf(step)`: every earlier ended visit of `step` in `visits`, under its id at the top
73
+ * level, or under its path in the branch the unit at `unitPath` runs in; `[]` when absent or from
74
+ * outside it. The array is a copy: changing it leaves the lease's `visits` alone.
75
+ */
76
+ export function visitsOf(
77
+ index: Map<object, Place[]>,
78
+ workflow: string,
79
+ step: object,
80
+ unitPath: string,
81
+ visits: Record<string, VisitRecord[]>,
82
+ ): VisitRecord[] {
83
+ const key = stepKey(index, workflow, step, unitPath, 'ctx.visits');
84
+ return key !== undefined && Object.hasOwn(visits, key) ? [...visits[key]!] : [];
85
+ }
@@ -0,0 +1,81 @@
1
+ import { lstat, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import type { WorkspaceStatus } from '@artieeez/cf-client';
4
+
5
+ /** Longest run id `POST /w/workspaces/check` takes (run-affinity door 5). */
6
+ export const RUN_ID_MAX = 200;
7
+
8
+ /** `<workflow id>-<digits>`: a workflow id is a lowercase slug, the number all digits. */
9
+ const RUN_ID = /^[a-z][a-z0-9-]*-\d+$/;
10
+
11
+ /** Whether a folder name is a run id, whichever workflow it belongs to (ART-226). */
12
+ export function isRunId(name: string): boolean {
13
+ return name.length <= RUN_ID_MAX && RUN_ID.test(name);
14
+ }
15
+
16
+ export type KeepWorkspace = 'never' | 'onFailure' | 'always';
17
+
18
+ export interface DecideParams {
19
+ /** the folder's workflow's `keepWorkspace`; undefined is `onFailure` */
20
+ policy: KeepWorkspace | undefined;
21
+ status: WorkspaceStatus;
22
+ /** when the run ended (ISO), or null when the server gave no time */
23
+ endedAt: string | null;
24
+ now: number;
25
+ /** how long a kept failed or aborted run folder stays; 0 keeps it forever */
26
+ retainMs: number;
27
+ }
28
+
29
+ /**
30
+ * Whether the collector deletes a run folder (run-affinity door 5, ART-226). A running run is
31
+ * always kept. `never` deletes every ended or unknown run; `always` keeps every one; `onFailure`
32
+ * deletes `succeeded` and `missing` runs, and `failed` or `aborted` ones once they ended at least
33
+ * `retainMs` ago (never with a 0 retention or no end time).
34
+ */
35
+ export function decide({ policy = 'onFailure', status, endedAt, now, retainMs }: DecideParams): 'delete' | 'keep' {
36
+ if (status === 'running' || policy === 'always') return 'keep';
37
+ if (policy === 'never' || status === 'succeeded' || status === 'missing') return 'delete';
38
+ if (retainMs <= 0 || endedAt === null) return 'keep';
39
+ const ended = Date.parse(endedAt);
40
+ return Number.isFinite(ended) && now - ended >= retainMs ? 'delete' : 'keep';
41
+ }
42
+
43
+ /**
44
+ * A folder's size in bytes and its latest change (ms), walked without following symlinks: a link
45
+ * counts as itself, never as what it points to. What cannot be read counts as nothing.
46
+ *
47
+ * Asynchronous, `concurrency` entries at a time: a run folder holds a checkout and its
48
+ * `node_modules` (~50k entries), and on NFS a synchronous walk of a few of them blocked the event
49
+ * loop for ~30 s, so heartbeats missed the lease TTL, probes timed out and the server closed the
50
+ * idle keep-alive sockets under the worker ("other side closed").
51
+ */
52
+ export async function folderSize(path: string, concurrency = 32): Promise<{ bytes: number; modifiedMs: number }> {
53
+ let bytes = 0;
54
+ let modifiedMs = 0;
55
+ let level = [path];
56
+ while (level.length > 0) {
57
+ const next: string[] = [];
58
+ for (let i = 0; i < level.length; i += concurrency) {
59
+ await Promise.all(
60
+ level.slice(i, i + concurrency).map(async (at) => {
61
+ let st;
62
+ try {
63
+ st = await lstat(at);
64
+ } catch {
65
+ return;
66
+ }
67
+ bytes += st.isDirectory() ? 0 : st.size;
68
+ modifiedMs = Math.max(modifiedMs, st.mtimeMs);
69
+ if (!st.isDirectory()) return;
70
+ try {
71
+ for (const name of await readdir(at)) next.push(join(at, name));
72
+ } catch {
73
+ /* unreadable: its entries count as nothing */
74
+ }
75
+ }),
76
+ );
77
+ }
78
+ level = next;
79
+ }
80
+ return { bytes, modifiedMs };
81
+ }