@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
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@artieeez/cf-worker-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "default": "./dist/index.js"
9
+ }
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "src",
14
+ "!dist/.tsbuildinfo"
15
+ ],
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "engines": {
20
+ "node": ">=22.18.0"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/artieeez/code-factory.git",
25
+ "directory": "packages/worker-runtime"
26
+ },
27
+ "dependencies": {
28
+ "@artieeez/cf-client": "0.2.0",
29
+ "@artieeez/cf-sdk": "0.2.0",
30
+ "@artieeez/cf-plugin-host": "0.2.0",
31
+ "@artieeez/cf-core": "0.2.0"
32
+ },
33
+ "devDependencies": {
34
+ "zod": "^4.6.7",
35
+ "@artieeez/cf-plugin-linear": "0.2.0"
36
+ },
37
+ "nx": {
38
+ "//": "these tests also load the projects below by relative path: their files and their dependencies' files are test inputs, not dependencies, so the edge does not spread to projects that depend on this one",
39
+ "targets": {
40
+ "test": {
41
+ "inputs": [
42
+ "default",
43
+ "^default",
44
+ "testSetup",
45
+ {
46
+ "runtime": "node --version"
47
+ },
48
+ {
49
+ "input": "default",
50
+ "projects": [
51
+ "@cf/workflow-boss-sdd",
52
+ "@cf/workflow-brief-writer",
53
+ "@cf/workflow-hello",
54
+ "@cf/runner-agy",
55
+ "@artieeez/cf-runner-claude-code",
56
+ "@cf/runner-pi",
57
+ "@artieeez/cf-plugin-github"
58
+ ]
59
+ },
60
+ {
61
+ "input": "default",
62
+ "projects": [
63
+ "@cf/workflow-boss-sdd",
64
+ "@cf/workflow-brief-writer",
65
+ "@cf/workflow-hello",
66
+ "@cf/runner-agy",
67
+ "@artieeez/cf-runner-claude-code",
68
+ "@cf/runner-pi",
69
+ "@artieeez/cf-plugin-github"
70
+ ],
71
+ "dependencies": true
72
+ }
73
+ ]
74
+ }
75
+ }
76
+ },
77
+ "scripts": {
78
+ "build": "tsc -b tsconfig.build.json",
79
+ "test": "vitest run --root ../.. --project unit packages/worker-runtime/"
80
+ }
6
81
  }
package/src/agents.ts ADDED
@@ -0,0 +1,387 @@
1
+ import { accessSync, constants, statSync } from 'node:fs';
2
+ import { delimiter, join } from 'node:path';
3
+ import type { AgentContext, AgentRequest, AgentResult, AgentRunner, AgentUsage } from '@artieeez/cf-sdk';
4
+ import { WorkerFatalError } from './fatal.ts';
5
+
6
+ /**
7
+ * The runner `ctx.agent` calls (AD-029): `CF_AGENT_RUNNER` names one of `agents`; unset or empty
8
+ * picks `fake` when listed, else the only one listed. Undefined when none is listed. Any other
9
+ * value is a `WorkerFatalError` naming the runners.
10
+ */
11
+ export function pickAgent(env: NodeJS.ProcessEnv, agents: Record<string, AgentRunner> = {}): AgentRunner | undefined {
12
+ const names = Object.keys(agents);
13
+ if (names.length === 0) return undefined;
14
+ const wanted = env['CF_AGENT_RUNNER'] ?? '';
15
+ if (wanted === '') {
16
+ if (Object.hasOwn(agents, 'fake')) return agents['fake'];
17
+ if (names.length === 1) return agents[names[0]!];
18
+ } else if (Object.hasOwn(agents, wanted)) {
19
+ return agents[wanted];
20
+ }
21
+ throw new WorkerFatalError(`CF_AGENT_RUNNER must be one of ${names.join(', ')}`);
22
+ }
23
+
24
+ /** Default CLI binary and override env var for known coding agent harnesses (AD-037). */
25
+ export const DEFAULT_HARNESS_BINS: Record<string, { envVar: string; bin: string }> = {
26
+ 'claude-code': { envVar: 'CF_CLAUDE_BIN', bin: 'claude' },
27
+ pi: { envVar: 'CF_PI_BIN', bin: 'pi' },
28
+ agy: { envVar: 'CF_AGY_BIN', bin: 'agy' },
29
+ } as const;
30
+
31
+ export type BalanceStrategy = 'priority' | 'round-robin' | 'least-busy';
32
+
33
+ export type ModelMapper =
34
+ | string
35
+ | null
36
+ | Record<string, string | null>
37
+ | ((model: string | undefined, request: AgentRequest<unknown>) => string | undefined);
38
+
39
+ export interface BalanceTarget {
40
+ /** runner identifier (e.g. 'claude-code', 'pi', 'agy') */
41
+ name: string;
42
+ /** underlying AgentRunner to invoke */
43
+ runner: AgentRunner;
44
+ /**
45
+ * Binary name or path to probe before selecting; defaults to `DEFAULT_HARNESS_BINS[name]`
46
+ * (`CF_CLAUDE_BIN ?? 'claude'`, `CF_PI_BIN ?? 'pi'`, `CF_AGY_BIN ?? 'agy'`); set `false`
47
+ * to disable binary probing for this target.
48
+ */
49
+ bin?: string | false;
50
+ /** custom availability check; overrides the default binary probe when provided */
51
+ probe?: () => boolean | Promise<boolean>;
52
+ /** optional cap on concurrent in-flight sessions on this target */
53
+ maxConcurrency?: number;
54
+ /** optional role allowlist; when set, target only serves requests whose role is in `roles` */
55
+ roles?: readonly string[];
56
+ /** optional predicate for request hints / eligibility filtering */
57
+ match?: (request: AgentRequest<unknown>) => boolean;
58
+ /** optional per-target model override, strip (`null`), lookup map, or mapper function */
59
+ model?: ModelMapper;
60
+ }
61
+
62
+ export interface BalanceOptions {
63
+ /** routing strategy across healthy eligible targets; default `'priority'` */
64
+ strategy?: BalanceStrategy;
65
+ /** default cooldown duration in ms when `quota.resetsAt` is absent or not in the future; default `60_000` */
66
+ cooldownMs?: number;
67
+ /** utilization threshold in `(0, 1]` on `AgentUsage.quota.fiveHour` or `sevenDay`; default `0.95` */
68
+ quotaThreshold?: number;
69
+ /** worker environment used for binary resolution (`CF_*_BIN`, `PATH`); default `process.env` */
70
+ env?: NodeJS.ProcessEnv;
71
+ /** injectable clock in epoch ms; default `Date.now` */
72
+ now?: () => number;
73
+ /** custom binary probe `(bin, env) => boolean | Promise<boolean>`; default `isExecutableOnPath` */
74
+ probeBin?: (bin: string, env: NodeJS.ProcessEnv) => boolean | Promise<boolean>;
75
+ }
76
+
77
+ const ZERO_USAGE: AgentUsage = { inputTokens: 0, outputTokens: 0 };
78
+
79
+ const COOLDOWN_ERROR =
80
+ /rate[ _-]?limit|quota|429|too many requests|resource_exhausted|overloaded|usage limit|capacity|credit balance|^cannot run /i;
81
+
82
+ function isExecutableFile(filePath: string): boolean {
83
+ try {
84
+ const st = statSync(filePath);
85
+ if (!st.isFile() || (st.mode & 0o111) === 0) return false;
86
+ accessSync(filePath, constants.X_OK);
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Checks whether `bin` resolves (directly when containing `/`, or under an entry of `env.PATH`)
95
+ * to an existing regular file with execute permission (`X_OK`).
96
+ */
97
+ export function isExecutableOnPath(bin: string, env: NodeJS.ProcessEnv = process.env): boolean {
98
+ if (bin === '') return false;
99
+ if (bin.includes('/')) return isExecutableFile(bin);
100
+ const pathEnv = env['PATH'] ?? '';
101
+ for (const dir of pathEnv.split(delimiter)) {
102
+ if (dir === '') continue;
103
+ if (isExecutableFile(join(dir, bin))) return true;
104
+ }
105
+ return false;
106
+ }
107
+
108
+ /** A runner's `limit` when the server had no agent account: `no agent account available[ until <ISO>]`. */
109
+ const NO_ACCOUNT = /^no agent account available(?: until (\S+))?$/;
110
+
111
+ /** Whether an `AgentResult` error reason indicates a rate-limit, quota, overload, or binary spawn failure. */
112
+ export function isCooldownError(reason: string): boolean {
113
+ if (/^output (contract|facts):/.test(reason)) return false;
114
+ return COOLDOWN_ERROR.test(reason);
115
+ }
116
+
117
+ function resolveTargetBin(target: BalanceTarget, env: NodeJS.ProcessEnv): string | undefined {
118
+ if (target.bin === false) return undefined;
119
+ if (typeof target.bin === 'string' && target.bin !== '') return target.bin;
120
+ if (Object.hasOwn(DEFAULT_HARNESS_BINS, target.name)) {
121
+ const def = DEFAULT_HARNESS_BINS[target.name]!;
122
+ const fromEnv = env[def.envVar];
123
+ return typeof fromEnv === 'string' && fromEnv !== '' ? fromEnv : def.bin;
124
+ }
125
+ return undefined;
126
+ }
127
+
128
+ function mapRequestForTarget<T>(request: AgentRequest<T>, modelCfg: BalanceTarget['model']): AgentRequest<T> {
129
+ const copy: AgentRequest<T> = { ...request };
130
+ if (modelCfg === undefined) return copy;
131
+ let nextModel: string | undefined;
132
+ if (modelCfg === null) {
133
+ nextModel = undefined;
134
+ } else if (typeof modelCfg === 'string') {
135
+ nextModel = modelCfg !== '' ? modelCfg : undefined;
136
+ } else if (typeof modelCfg === 'function') {
137
+ const mapped = modelCfg(request.model, request as AgentRequest<unknown>);
138
+ nextModel = mapped !== undefined && mapped !== '' ? mapped : undefined;
139
+ } else if (request.model !== undefined && Object.hasOwn(modelCfg, request.model)) {
140
+ const mapped = modelCfg[request.model];
141
+ nextModel = mapped !== null && mapped !== undefined && mapped !== '' ? mapped : undefined;
142
+ } else {
143
+ nextModel = request.model;
144
+ }
145
+ if (nextModel === undefined) {
146
+ delete copy.model;
147
+ } else {
148
+ copy.model = nextModel;
149
+ }
150
+ return copy;
151
+ }
152
+
153
+ function resolveCooldownUntil(nowMs: number, cooldownMs: number, quota?: AgentUsage['quota']): number {
154
+ const raw = quota?.resetsAt;
155
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
156
+ const resetMs = raw < 1e12 ? raw * 1000 : raw;
157
+ if (resetMs > nowMs) return resetMs;
158
+ }
159
+ return nowMs + cooldownMs;
160
+ }
161
+
162
+ function quotaExceeded(quota: AgentUsage['quota'], threshold: number): string | undefined {
163
+ if (quota === undefined) return undefined;
164
+ if (typeof quota.fiveHour === 'number' && quota.fiveHour >= threshold) {
165
+ return `quota.fiveHour=${quota.fiveHour}`;
166
+ }
167
+ if (typeof quota.sevenDay === 'number' && quota.sevenDay >= threshold) {
168
+ return `quota.sevenDay=${quota.sevenDay}`;
169
+ }
170
+ return undefined;
171
+ }
172
+
173
+ interface TargetState {
174
+ index: number;
175
+ target: BalanceTarget;
176
+ inFlight: number;
177
+ cooldownUntil: number;
178
+ cooldownReason?: string;
179
+ }
180
+
181
+ /**
182
+ * A composite `AgentRunner` that assesses configured coding agent harnesses per `ctx.agent()` call,
183
+ * routes across healthy targets by strategy (`priority`, `round-robin`, `least-busy`), tracks quota
184
+ * and rate-limit cooldowns, fails over on rate-limit/quota/spawn errors, and logs its selection (AD-037).
185
+ */
186
+ export function balanceAgents(targets: readonly BalanceTarget[], opts: BalanceOptions = {}): AgentRunner {
187
+ const strategy: BalanceStrategy = opts.strategy ?? 'priority';
188
+ const cooldownMs = opts.cooldownMs ?? 60_000;
189
+ const quotaThreshold = opts.quotaThreshold ?? 0.95;
190
+ const env = opts.env ?? process.env;
191
+ const now = opts.now ?? Date.now;
192
+ const probeBin = opts.probeBin ?? isExecutableOnPath;
193
+
194
+ const states: TargetState[] = targets.map((target, index) => ({
195
+ index,
196
+ target,
197
+ inFlight: 0,
198
+ cooldownUntil: 0,
199
+ }));
200
+ let rrCursor = 0;
201
+ /** calls waiting for a target under its `maxConcurrency` (AD-081): woken when any call ends */
202
+ const waiting: (() => void)[] = [];
203
+ /** Resolves when a call ends, or with `false` when `signal` aborts first. */
204
+ const freed = (signal: AbortSignal): Promise<boolean> =>
205
+ new Promise((resolve) => {
206
+ if (signal.aborted) return resolve(false);
207
+ const onAbort = () => resolve(false);
208
+ signal.addEventListener('abort', onAbort, { once: true });
209
+ waiting.push(() => {
210
+ signal.removeEventListener('abort', onAbort);
211
+ resolve(true);
212
+ });
213
+ });
214
+
215
+ return async <T>(ctx: AgentContext, request: AgentRequest<T>): Promise<AgentResult<T>> => {
216
+ const tried = new Set<number>();
217
+ let lastErrorResult: AgentResult<T> | undefined;
218
+ let waitLogged = false;
219
+
220
+ for (;;) {
221
+ const nowMs = now();
222
+ const healthy: TargetState[] = [];
223
+ const cooledDownAvailable: TargetState[] = [];
224
+ const skipped: { index: number; name: string; reason: string }[] = [];
225
+
226
+ for (const state of states) {
227
+ if (tried.has(state.index)) continue;
228
+ const t = state.target;
229
+
230
+ if (
231
+ (t.roles !== undefined && !t.roles.includes(request.role)) ||
232
+ (t.match !== undefined && !t.match(request as AgentRequest<unknown>))
233
+ ) {
234
+ skipped.push({ index: state.index, name: t.name, reason: 'role-mismatch' });
235
+ continue;
236
+ }
237
+
238
+ const bin = resolveTargetBin(t, env);
239
+ const available =
240
+ t.probe !== undefined ? await t.probe() : bin !== undefined ? await probeBin(bin, env) : true;
241
+ if (!available) {
242
+ skipped.push({ index: state.index, name: t.name, reason: 'unavailable' });
243
+ continue;
244
+ }
245
+
246
+ if (t.maxConcurrency !== undefined && state.inFlight >= t.maxConcurrency) {
247
+ skipped.push({ index: state.index, name: t.name, reason: 'max-concurrency' });
248
+ continue;
249
+ }
250
+
251
+ if (state.cooldownUntil > nowMs) {
252
+ cooledDownAvailable.push(state);
253
+ skipped.push({ index: state.index, name: t.name, reason: 'cooldown' });
254
+ continue;
255
+ }
256
+
257
+ healthy.push(state);
258
+ }
259
+
260
+ let chosen: TargetState | undefined;
261
+ let pickReason = '';
262
+
263
+ if (healthy.length > 0) {
264
+ if (strategy === 'priority') {
265
+ chosen = healthy[0]!;
266
+ pickReason = tried.size > 0 ? 'failover' : 'healthy';
267
+ } else if (strategy === 'round-robin') {
268
+ for (let offset = 0; offset < states.length; offset++) {
269
+ const idx = (rrCursor + offset) % states.length;
270
+ const found = healthy.find((h) => h.index === idx);
271
+ if (found !== undefined) {
272
+ chosen = found;
273
+ rrCursor = (idx + 1) % states.length;
274
+ break;
275
+ }
276
+ }
277
+ pickReason = tried.size > 0 ? 'failover' : 'round-robin';
278
+ } else {
279
+ chosen = healthy.reduce((best, cur) => (cur.inFlight < best.inFlight ? cur : best), healthy[0]!);
280
+ pickReason = `${tried.size > 0 ? 'failover,' : ''}inFlight=${chosen.inFlight}`;
281
+ }
282
+ } else if (cooledDownAvailable.length > 0 && tried.size === 0) {
283
+ chosen = cooledDownAvailable.reduce(
284
+ (best, cur) => (cur.cooldownUntil < best.cooldownUntil ? cur : best),
285
+ cooledDownAvailable[0]!,
286
+ );
287
+ pickReason = 'cooldown-fallback';
288
+ }
289
+
290
+ if (chosen === undefined) {
291
+ // every eligible target is busy up to its maxConcurrency: wait for a call to end (AD-081)
292
+ const atCapacity = skipped.length > 0 && skipped.every((s) => s.reason === 'max-concurrency');
293
+ if (lastErrorResult === undefined && atCapacity) {
294
+ if (!waitLogged) {
295
+ waitLogged = true;
296
+ ctx.emit('log', {
297
+ level: 'info',
298
+ msg: `agent-balancer: waiting for a free runner; at max concurrency: ${skipped.map((s) => s.name).join(', ')}`,
299
+ });
300
+ }
301
+ if (await freed(ctx.signal)) continue;
302
+ return { status: 'cancelled', reason: 'cancelled', usage: ZERO_USAGE, turns: 0 };
303
+ }
304
+ if (lastErrorResult !== undefined) return lastErrorResult;
305
+ const summary = skipped.map((s) => `${s.name} (${s.reason})`).join(', ') || 'no targets configured';
306
+ const reason = `no available agent runner (${summary})`;
307
+ ctx.emit('log', { level: 'warn', msg: `agent-balancer: ${reason}` });
308
+ return { status: 'error', reason, usage: ZERO_USAGE, turns: 0 };
309
+ }
310
+
311
+ tried.add(chosen.index);
312
+ const mappedRequest = mapRequestForTarget(request, chosen.target.model);
313
+ const skippedList = skipped.filter((s) => s.index !== chosen.index).map((s) => `${s.name} (${s.reason})`);
314
+ const modelNote = mappedRequest.model !== request.model ? `, model=${mappedRequest.model ?? 'default'}` : '';
315
+ const skipNote = skippedList.length > 0 ? `; skipped: ${skippedList.join(', ')}` : '';
316
+ const level = pickReason === 'cooldown-fallback' ? 'warn' : 'info';
317
+ ctx.emit('log', {
318
+ level,
319
+ msg: `agent-balancer: selected ${chosen.target.name} (strategy=${strategy}, reason=${pickReason}${modelNote}${skipNote})`,
320
+ });
321
+
322
+ let streamedQuota: AgentUsage['quota'] | undefined;
323
+ const wrappedCtx: AgentContext = {
324
+ ...ctx,
325
+ emit: ((type: string, data: Record<string, unknown>) => {
326
+ if (type === 'agent.usage' && typeof data?.['quota'] === 'object' && data['quota'] !== null) {
327
+ streamedQuota = data['quota'] as AgentUsage['quota'];
328
+ }
329
+ (ctx.emit as (t: string, d: Record<string, unknown>) => void)(type, data);
330
+ }) as AgentContext['emit'],
331
+ };
332
+
333
+ chosen.inFlight += 1;
334
+ let result: AgentResult<T>;
335
+ try {
336
+ result = await chosen.target.runner(wrappedCtx, mappedRequest);
337
+ } finally {
338
+ chosen.inFlight -= 1;
339
+ for (const wake of waiting.splice(0)) wake();
340
+ }
341
+
342
+ const quota = result.usage?.quota ?? streamedQuota;
343
+ // the server had no agent account for this harness (agent-accounts AC 25): cool down until
344
+ // the account it named frees, and fail over as for a rate limit
345
+ const noAccount = result.status === 'limit' ? NO_ACCOUNT.exec(result.reason) : null;
346
+ if (noAccount !== null && result.status === 'limit') {
347
+ const at = noAccount[1] !== undefined ? Date.parse(noAccount[1]) : NaN;
348
+ const until = Number.isFinite(at) && at > now() ? at : now() + cooldownMs;
349
+ chosen.cooldownUntil = until;
350
+ chosen.cooldownReason = result.reason;
351
+ const waitSec = Math.max(1, Math.round((until - now()) / 1000));
352
+ ctx.emit('log', {
353
+ level: 'warn',
354
+ msg: `agent-balancer: ${chosen.target.name} cooled down for ${waitSec}s (${result.reason}); failing over`,
355
+ });
356
+ lastErrorResult = result;
357
+ continue;
358
+ }
359
+ if (result.status === 'error' && isCooldownError(result.reason)) {
360
+ const until = resolveCooldownUntil(now(), cooldownMs, quota);
361
+ chosen.cooldownUntil = until;
362
+ chosen.cooldownReason = result.reason;
363
+ const waitSec = Math.max(1, Math.round((until - now()) / 1000));
364
+ ctx.emit('log', {
365
+ level: 'warn',
366
+ msg: `agent-balancer: ${chosen.target.name} cooled down for ${waitSec}s (${result.reason}); failing over`,
367
+ });
368
+ lastErrorResult = result;
369
+ continue;
370
+ }
371
+
372
+ const qReason = quotaExceeded(quota, quotaThreshold);
373
+ if (qReason !== undefined) {
374
+ const until = resolveCooldownUntil(now(), cooldownMs, quota);
375
+ chosen.cooldownUntil = until;
376
+ chosen.cooldownReason = qReason;
377
+ const waitSec = Math.max(1, Math.round((until - now()) / 1000));
378
+ ctx.emit('log', {
379
+ level: 'info',
380
+ msg: `agent-balancer: ${chosen.target.name} cooled down for ${waitSec}s (${qReason})`,
381
+ });
382
+ }
383
+
384
+ return result;
385
+ }
386
+ };
387
+ }
package/src/exec.ts ADDED
@@ -0,0 +1,184 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { StringDecoder } from 'node:string_decoder';
5
+ import { cut } from '@artieeez/cf-core';
6
+ import type { Exec, ExecOptions, ExecResult } from '@artieeez/cf-sdk';
7
+
8
+ /** Worker env names a process run by `ctx.exec` never sees (run-workspace door 6, AD-010). */
9
+ export const SCRUBBED_ENV = /^(CF_|CLAUDE|ANTHROPIC_)/;
10
+ /** Longest logged line; longer ones are cut, ending in `…`. */
11
+ export const EXEC_LINE_MAX = 2000;
12
+ /** Lines logged per call; the rest are counted in one closing `log`. */
13
+ export const EXEC_LOG_LINES = 1000;
14
+ /** Between `SIGTERM` and `SIGKILL` to the process group. */
15
+ export const KILL_GRACE_MS = 5000;
16
+ const CAPTURE_MAX = 64 * 1024 * 1024;
17
+
18
+ /** The worker env minus the names in `SCRUBBED_ENV` and the loaded plugins' secret names (linear-plugin AC 28). */
19
+ export function scrubbedEnv(base: NodeJS.ProcessEnv = process.env, secrets: readonly string[] = []): Record<string, string> {
20
+ const out: Record<string, string> = {};
21
+ for (const [k, v] of Object.entries(base)) {
22
+ if (v !== undefined && !SCRUBBED_ENV.test(k) && !secrets.includes(k)) out[k] = v;
23
+ }
24
+ return out;
25
+ }
26
+
27
+ /** Whether `path` is `root` or under it. */
28
+ export function inside(root: string, path: string): boolean {
29
+ const rel = relative(root, path);
30
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
31
+ }
32
+
33
+ /**
34
+ * `rel` under `base`, refused when it leaves `root`: lexically, or through a symlink in the part
35
+ * that exists already.
36
+ */
37
+ export function confined(root: string, base: string, rel: string | undefined): string {
38
+ const target = rel === undefined ? base : resolve(base, rel);
39
+ if (!inside(root, target)) throw new Error(`${rel ?? base} is outside the run folder`);
40
+ const realRoot = realpathSync(root);
41
+ let probe = target;
42
+ while (!existsSync(probe) && inside(root, probe) && probe !== root) probe = resolve(probe, '..');
43
+ if (existsSync(probe) && !inside(realRoot, realpathSync(probe))) {
44
+ throw new Error(`${rel ?? base} is outside the run folder`);
45
+ }
46
+ return target;
47
+ }
48
+
49
+ export interface ExecHost {
50
+ /** where a relative `cwd` starts and where the process runs by default */
51
+ base: string;
52
+ /** what `cwd` may not leave */
53
+ root: string;
54
+ /** one output line or note, as the runtime reports it */
55
+ line(msg: string, stream: 'stdout' | 'stderr' | 'note'): void;
56
+ /** aborting it kills every running process group, which then resolves `cancelled: true` */
57
+ signal: AbortSignal;
58
+ /** env names the process never sees, on top of `SCRUBBED_ENV`: the loaded plugins' secrets */
59
+ secrets?: readonly string[];
60
+ }
61
+
62
+ /** A `ctx.exec` bound to one context, and a way to kill what it still runs. */
63
+ export function createExec(host: ExecHost): { exec: Exec; killAll(): void } {
64
+ const running = new Set<(why: 'cancelled' | 'timeout') => void>();
65
+ const killAll = () => {
66
+ for (const kill of running) kill('cancelled');
67
+ };
68
+ host.signal.addEventListener('abort', killAll, { once: true });
69
+
70
+ const exec: Exec = (cmd: string, args: string[], opts: ExecOptions = {}) => {
71
+ const cwd = confined(host.root, host.base, opts.cwd);
72
+ const started = Date.now();
73
+ return new Promise<ExecResult>((resolveResult) => {
74
+ let stdout = '';
75
+ let stderr = '';
76
+ let timedOut = false;
77
+ let cancelled = false;
78
+ let logged = 0;
79
+ let skipped = 0;
80
+ let settled = false;
81
+ const child = spawn(cmd, args, {
82
+ cwd,
83
+ env: { ...scrubbedEnv(process.env, host.secrets), ...(opts.env ?? {}) },
84
+ stdio: ['pipe', 'pipe', 'pipe'],
85
+ detached: true,
86
+ });
87
+
88
+ const signalGroup = (sig: NodeJS.Signals) => {
89
+ if (child.pid === undefined) return;
90
+ try {
91
+ process.kill(-child.pid, sig);
92
+ } catch {
93
+ /* the group is gone */
94
+ }
95
+ };
96
+ const groupGone = () => {
97
+ if (child.pid === undefined) return true;
98
+ try {
99
+ process.kill(-child.pid, 0);
100
+ return false;
101
+ } catch {
102
+ return true;
103
+ }
104
+ };
105
+ let killTimer: NodeJS.Timeout | undefined;
106
+ const kill = (why: 'cancelled' | 'timeout') => {
107
+ if (why === 'timeout') timedOut = true;
108
+ else cancelled = true;
109
+ signalGroup('SIGTERM');
110
+ killTimer ??= setTimeout(() => {
111
+ if (!groupGone()) signalGroup('SIGKILL');
112
+ }, KILL_GRACE_MS);
113
+ };
114
+ running.add(kill);
115
+ if (host.signal.aborted) kill('cancelled');
116
+ const timer = opts.timeoutMs !== undefined ? setTimeout(() => kill('timeout'), opts.timeoutMs) : undefined;
117
+
118
+ const emit = (stream: 'stdout' | 'stderr') => {
119
+ let rest = '';
120
+ return {
121
+ push(text: string) {
122
+ rest += text;
123
+ const lines = rest.split('\n');
124
+ rest = lines.pop()!;
125
+ for (const l of lines) out(l);
126
+ },
127
+ flush() {
128
+ if (rest !== '') out(rest);
129
+ rest = '';
130
+ },
131
+ };
132
+ function out(l: string) {
133
+ if (logged < EXEC_LOG_LINES) {
134
+ logged++;
135
+ host.line(cut(l, EXEC_LINE_MAX), stream);
136
+ } else skipped++;
137
+ }
138
+ };
139
+ const outLines = emit('stdout');
140
+ const errLines = emit('stderr');
141
+ // one decoder per stream: a character split across two chunks stays whole
142
+ const outText = new StringDecoder('utf8');
143
+ const errText = new StringDecoder('utf8');
144
+ const onOut = (text: string) => {
145
+ if (stdout.length < CAPTURE_MAX) stdout += text;
146
+ outLines.push(text);
147
+ };
148
+ const onErr = (text: string) => {
149
+ if (stderr.length < CAPTURE_MAX) stderr += text;
150
+ errLines.push(text);
151
+ };
152
+ child.stdout.on('data', (d: Buffer) => onOut(outText.write(d)));
153
+ child.stderr.on('data', (d: Buffer) => onErr(errText.write(d)));
154
+
155
+ const finish = (code: number | null, sig: NodeJS.Signals | null) => {
156
+ if (settled) return;
157
+ settled = true;
158
+ if (timer) clearTimeout(timer);
159
+ running.delete(kill);
160
+ onOut(outText.end());
161
+ onErr(errText.end());
162
+ outLines.flush();
163
+ errLines.flush();
164
+ if (skipped > 0) host.line(`${skipped} more output lines of ${cmd} not logged`, 'note');
165
+ if (killTimer !== undefined) {
166
+ // a grandchild may still hold the group: it dies at the grace deadline, unless the
167
+ // group is already empty, in which case its id is not signalled again
168
+ if (groupGone()) clearTimeout(killTimer);
169
+ else killTimer.unref();
170
+ }
171
+ resolveResult({ code, signal: sig, stdout, stderr, durationMs: Date.now() - started, timedOut, cancelled });
172
+ };
173
+ child.on('error', (err) => {
174
+ stderr += String(err);
175
+ finish(127, null);
176
+ });
177
+ child.on('close', (code, sig) => finish(code, sig));
178
+ child.stdin.on('error', () => {});
179
+ if (opts.input !== undefined) child.stdin.write(opts.input);
180
+ child.stdin.end();
181
+ });
182
+ };
183
+ return { exec, killAll };
184
+ }
package/src/fatal.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** The worker cannot continue (e.g. manifest conflict): print the message and exit non-zero. */
2
+ export class WorkerFatalError extends Error {
3
+ override name = 'WorkerFatalError';
4
+ }