@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/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # worker-runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lease loop, heartbeats, cancellation, hooks, run workspaces, run folder + wd, deferred
4
+ effects, event emission. Embeddable in custom worker images.
5
+
6
+ A worker registers with a worker token: `opts.token`, else `CF_WORKER_TOKEN`, else the one
7
+ saved in `<CF_DATA_DIR>/workers/<name>.json`. With none, a local worker creates its own
8
+ through the server's `POST /api/workers`, limited to its workflows, and saves it there; that
9
+ works only while the server's auth is off (AD-064). Against a server with auth on, create a
10
+ token on the Workers page or with `cf worker create` and set `CF_WORKER_TOKEN`; every pod of
11
+ a deployment can use the same one.
12
+
13
+ See [docs/design](../../docs/design/README.md).
@@ -0,0 +1,64 @@
1
+ import type { AgentRequest, AgentRunner } from '@artieeez/cf-sdk';
2
+ /**
3
+ * The runner `ctx.agent` calls (AD-029): `CF_AGENT_RUNNER` names one of `agents`; unset or empty
4
+ * picks `fake` when listed, else the only one listed. Undefined when none is listed. Any other
5
+ * value is a `WorkerFatalError` naming the runners.
6
+ */
7
+ export declare function pickAgent(env: NodeJS.ProcessEnv, agents?: Record<string, AgentRunner>): AgentRunner | undefined;
8
+ /** Default CLI binary and override env var for known coding agent harnesses (AD-037). */
9
+ export declare const DEFAULT_HARNESS_BINS: Record<string, {
10
+ envVar: string;
11
+ bin: string;
12
+ }>;
13
+ export type BalanceStrategy = 'priority' | 'round-robin' | 'least-busy';
14
+ export type ModelMapper = string | null | Record<string, string | null> | ((model: string | undefined, request: AgentRequest<unknown>) => string | undefined);
15
+ export interface BalanceTarget {
16
+ /** runner identifier (e.g. 'claude-code', 'pi', 'agy') */
17
+ name: string;
18
+ /** underlying AgentRunner to invoke */
19
+ runner: AgentRunner;
20
+ /**
21
+ * Binary name or path to probe before selecting; defaults to `DEFAULT_HARNESS_BINS[name]`
22
+ * (`CF_CLAUDE_BIN ?? 'claude'`, `CF_PI_BIN ?? 'pi'`, `CF_AGY_BIN ?? 'agy'`); set `false`
23
+ * to disable binary probing for this target.
24
+ */
25
+ bin?: string | false;
26
+ /** custom availability check; overrides the default binary probe when provided */
27
+ probe?: () => boolean | Promise<boolean>;
28
+ /** optional cap on concurrent in-flight sessions on this target */
29
+ maxConcurrency?: number;
30
+ /** optional role allowlist; when set, target only serves requests whose role is in `roles` */
31
+ roles?: readonly string[];
32
+ /** optional predicate for request hints / eligibility filtering */
33
+ match?: (request: AgentRequest<unknown>) => boolean;
34
+ /** optional per-target model override, strip (`null`), lookup map, or mapper function */
35
+ model?: ModelMapper;
36
+ }
37
+ export interface BalanceOptions {
38
+ /** routing strategy across healthy eligible targets; default `'priority'` */
39
+ strategy?: BalanceStrategy;
40
+ /** default cooldown duration in ms when `quota.resetsAt` is absent or not in the future; default `60_000` */
41
+ cooldownMs?: number;
42
+ /** utilization threshold in `(0, 1]` on `AgentUsage.quota.fiveHour` or `sevenDay`; default `0.95` */
43
+ quotaThreshold?: number;
44
+ /** worker environment used for binary resolution (`CF_*_BIN`, `PATH`); default `process.env` */
45
+ env?: NodeJS.ProcessEnv;
46
+ /** injectable clock in epoch ms; default `Date.now` */
47
+ now?: () => number;
48
+ /** custom binary probe `(bin, env) => boolean | Promise<boolean>`; default `isExecutableOnPath` */
49
+ probeBin?: (bin: string, env: NodeJS.ProcessEnv) => boolean | Promise<boolean>;
50
+ }
51
+ /**
52
+ * Checks whether `bin` resolves (directly when containing `/`, or under an entry of `env.PATH`)
53
+ * to an existing regular file with execute permission (`X_OK`).
54
+ */
55
+ export declare function isExecutableOnPath(bin: string, env?: NodeJS.ProcessEnv): boolean;
56
+ /** Whether an `AgentResult` error reason indicates a rate-limit, quota, overload, or binary spawn failure. */
57
+ export declare function isCooldownError(reason: string): boolean;
58
+ /**
59
+ * A composite `AgentRunner` that assesses configured coding agent harnesses per `ctx.agent()` call,
60
+ * routes across healthy targets by strategy (`priority`, `round-robin`, `least-busy`), tracks quota
61
+ * and rate-limit cooldowns, fails over on rate-limit/quota/spawn errors, and logs its selection (AD-037).
62
+ */
63
+ export declare function balanceAgents(targets: readonly BalanceTarget[], opts?: BalanceOptions): AgentRunner;
64
+ //# sourceMappingURL=agents.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../src/agents.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAgB,YAAY,EAAe,WAAW,EAAc,MAAM,kBAAkB,CAAC;AAGzG;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAM,GAAG,WAAW,GAAG,SAAS,CAWnH;AAED,yFAAyF;AACzF,eAAO,MAAM,oBAAoB,EAAE,MAAM,CAAC,MAAM,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAIvE,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG,UAAU,GAAG,aAAa,GAAG,YAAY,CAAC;AAExE,MAAM,MAAM,WAAW,GACnB,MAAM,GACN,IAAI,GACJ,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,GAC7B,CAAC,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC;AAExF,MAAM,WAAW,aAAa;IAC5B,0DAA0D;IAC1D,IAAI,EAAE,MAAM,CAAC;IACb,uCAAuC;IACvC,MAAM,EAAE,WAAW,CAAC;IACpB;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACrB,kFAAkF;IAClF,KAAK,CAAC,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,mEAAmE;IACnE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8FAA8F;IAC9F,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,mEAAmE;IACnE,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC;IACpD,yFAAyF;IACzF,KAAK,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,cAAc;IAC7B,6EAA6E;IAC7E,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,6GAA6G;IAC7G,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qGAAqG;IACrG,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gGAAgG;IAChG,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,uDAAuD;IACvD,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,mGAAmG;IACnG,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,UAAU,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAChF;AAkBD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAS7F;AAKD,8GAA8G;AAC9G,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAGvD;AAkED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,SAAS,aAAa,EAAE,EAAE,IAAI,GAAE,cAAmB,GAAG,WAAW,CAyMvG"}
package/dist/agents.js ADDED
@@ -0,0 +1,324 @@
1
+ import { accessSync, constants, statSync } from 'node:fs';
2
+ import { delimiter, join } from 'node:path';
3
+ import { WorkerFatalError } from "./fatal.js";
4
+ /**
5
+ * The runner `ctx.agent` calls (AD-029): `CF_AGENT_RUNNER` names one of `agents`; unset or empty
6
+ * picks `fake` when listed, else the only one listed. Undefined when none is listed. Any other
7
+ * value is a `WorkerFatalError` naming the runners.
8
+ */
9
+ export function pickAgent(env, agents = {}) {
10
+ const names = Object.keys(agents);
11
+ if (names.length === 0)
12
+ return undefined;
13
+ const wanted = env['CF_AGENT_RUNNER'] ?? '';
14
+ if (wanted === '') {
15
+ if (Object.hasOwn(agents, 'fake'))
16
+ return agents['fake'];
17
+ if (names.length === 1)
18
+ return agents[names[0]];
19
+ }
20
+ else if (Object.hasOwn(agents, wanted)) {
21
+ return agents[wanted];
22
+ }
23
+ throw new WorkerFatalError(`CF_AGENT_RUNNER must be one of ${names.join(', ')}`);
24
+ }
25
+ /** Default CLI binary and override env var for known coding agent harnesses (AD-037). */
26
+ export const DEFAULT_HARNESS_BINS = {
27
+ 'claude-code': { envVar: 'CF_CLAUDE_BIN', bin: 'claude' },
28
+ pi: { envVar: 'CF_PI_BIN', bin: 'pi' },
29
+ agy: { envVar: 'CF_AGY_BIN', bin: 'agy' },
30
+ };
31
+ const ZERO_USAGE = { inputTokens: 0, outputTokens: 0 };
32
+ const COOLDOWN_ERROR = /rate[ _-]?limit|quota|429|too many requests|resource_exhausted|overloaded|usage limit|capacity|credit balance|^cannot run /i;
33
+ function isExecutableFile(filePath) {
34
+ try {
35
+ const st = statSync(filePath);
36
+ if (!st.isFile() || (st.mode & 0o111) === 0)
37
+ return false;
38
+ accessSync(filePath, constants.X_OK);
39
+ return true;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ /**
46
+ * Checks whether `bin` resolves (directly when containing `/`, or under an entry of `env.PATH`)
47
+ * to an existing regular file with execute permission (`X_OK`).
48
+ */
49
+ export function isExecutableOnPath(bin, env = process.env) {
50
+ if (bin === '')
51
+ return false;
52
+ if (bin.includes('/'))
53
+ return isExecutableFile(bin);
54
+ const pathEnv = env['PATH'] ?? '';
55
+ for (const dir of pathEnv.split(delimiter)) {
56
+ if (dir === '')
57
+ continue;
58
+ if (isExecutableFile(join(dir, bin)))
59
+ return true;
60
+ }
61
+ return false;
62
+ }
63
+ /** A runner's `limit` when the server had no agent account: `no agent account available[ until <ISO>]`. */
64
+ const NO_ACCOUNT = /^no agent account available(?: until (\S+))?$/;
65
+ /** Whether an `AgentResult` error reason indicates a rate-limit, quota, overload, or binary spawn failure. */
66
+ export function isCooldownError(reason) {
67
+ if (/^output (contract|facts):/.test(reason))
68
+ return false;
69
+ return COOLDOWN_ERROR.test(reason);
70
+ }
71
+ function resolveTargetBin(target, env) {
72
+ if (target.bin === false)
73
+ return undefined;
74
+ if (typeof target.bin === 'string' && target.bin !== '')
75
+ return target.bin;
76
+ if (Object.hasOwn(DEFAULT_HARNESS_BINS, target.name)) {
77
+ const def = DEFAULT_HARNESS_BINS[target.name];
78
+ const fromEnv = env[def.envVar];
79
+ return typeof fromEnv === 'string' && fromEnv !== '' ? fromEnv : def.bin;
80
+ }
81
+ return undefined;
82
+ }
83
+ function mapRequestForTarget(request, modelCfg) {
84
+ const copy = { ...request };
85
+ if (modelCfg === undefined)
86
+ return copy;
87
+ let nextModel;
88
+ if (modelCfg === null) {
89
+ nextModel = undefined;
90
+ }
91
+ else if (typeof modelCfg === 'string') {
92
+ nextModel = modelCfg !== '' ? modelCfg : undefined;
93
+ }
94
+ else if (typeof modelCfg === 'function') {
95
+ const mapped = modelCfg(request.model, request);
96
+ nextModel = mapped !== undefined && mapped !== '' ? mapped : undefined;
97
+ }
98
+ else if (request.model !== undefined && Object.hasOwn(modelCfg, request.model)) {
99
+ const mapped = modelCfg[request.model];
100
+ nextModel = mapped !== null && mapped !== undefined && mapped !== '' ? mapped : undefined;
101
+ }
102
+ else {
103
+ nextModel = request.model;
104
+ }
105
+ if (nextModel === undefined) {
106
+ delete copy.model;
107
+ }
108
+ else {
109
+ copy.model = nextModel;
110
+ }
111
+ return copy;
112
+ }
113
+ function resolveCooldownUntil(nowMs, cooldownMs, quota) {
114
+ const raw = quota?.resetsAt;
115
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
116
+ const resetMs = raw < 1e12 ? raw * 1000 : raw;
117
+ if (resetMs > nowMs)
118
+ return resetMs;
119
+ }
120
+ return nowMs + cooldownMs;
121
+ }
122
+ function quotaExceeded(quota, threshold) {
123
+ if (quota === undefined)
124
+ return undefined;
125
+ if (typeof quota.fiveHour === 'number' && quota.fiveHour >= threshold) {
126
+ return `quota.fiveHour=${quota.fiveHour}`;
127
+ }
128
+ if (typeof quota.sevenDay === 'number' && quota.sevenDay >= threshold) {
129
+ return `quota.sevenDay=${quota.sevenDay}`;
130
+ }
131
+ return undefined;
132
+ }
133
+ /**
134
+ * A composite `AgentRunner` that assesses configured coding agent harnesses per `ctx.agent()` call,
135
+ * routes across healthy targets by strategy (`priority`, `round-robin`, `least-busy`), tracks quota
136
+ * and rate-limit cooldowns, fails over on rate-limit/quota/spawn errors, and logs its selection (AD-037).
137
+ */
138
+ export function balanceAgents(targets, opts = {}) {
139
+ const strategy = opts.strategy ?? 'priority';
140
+ const cooldownMs = opts.cooldownMs ?? 60_000;
141
+ const quotaThreshold = opts.quotaThreshold ?? 0.95;
142
+ const env = opts.env ?? process.env;
143
+ const now = opts.now ?? Date.now;
144
+ const probeBin = opts.probeBin ?? isExecutableOnPath;
145
+ const states = targets.map((target, index) => ({
146
+ index,
147
+ target,
148
+ inFlight: 0,
149
+ cooldownUntil: 0,
150
+ }));
151
+ let rrCursor = 0;
152
+ /** calls waiting for a target under its `maxConcurrency` (AD-081): woken when any call ends */
153
+ const waiting = [];
154
+ /** Resolves when a call ends, or with `false` when `signal` aborts first. */
155
+ const freed = (signal) => new Promise((resolve) => {
156
+ if (signal.aborted)
157
+ return resolve(false);
158
+ const onAbort = () => resolve(false);
159
+ signal.addEventListener('abort', onAbort, { once: true });
160
+ waiting.push(() => {
161
+ signal.removeEventListener('abort', onAbort);
162
+ resolve(true);
163
+ });
164
+ });
165
+ return async (ctx, request) => {
166
+ const tried = new Set();
167
+ let lastErrorResult;
168
+ let waitLogged = false;
169
+ for (;;) {
170
+ const nowMs = now();
171
+ const healthy = [];
172
+ const cooledDownAvailable = [];
173
+ const skipped = [];
174
+ for (const state of states) {
175
+ if (tried.has(state.index))
176
+ continue;
177
+ const t = state.target;
178
+ if ((t.roles !== undefined && !t.roles.includes(request.role)) ||
179
+ (t.match !== undefined && !t.match(request))) {
180
+ skipped.push({ index: state.index, name: t.name, reason: 'role-mismatch' });
181
+ continue;
182
+ }
183
+ const bin = resolveTargetBin(t, env);
184
+ const available = t.probe !== undefined ? await t.probe() : bin !== undefined ? await probeBin(bin, env) : true;
185
+ if (!available) {
186
+ skipped.push({ index: state.index, name: t.name, reason: 'unavailable' });
187
+ continue;
188
+ }
189
+ if (t.maxConcurrency !== undefined && state.inFlight >= t.maxConcurrency) {
190
+ skipped.push({ index: state.index, name: t.name, reason: 'max-concurrency' });
191
+ continue;
192
+ }
193
+ if (state.cooldownUntil > nowMs) {
194
+ cooledDownAvailable.push(state);
195
+ skipped.push({ index: state.index, name: t.name, reason: 'cooldown' });
196
+ continue;
197
+ }
198
+ healthy.push(state);
199
+ }
200
+ let chosen;
201
+ let pickReason = '';
202
+ if (healthy.length > 0) {
203
+ if (strategy === 'priority') {
204
+ chosen = healthy[0];
205
+ pickReason = tried.size > 0 ? 'failover' : 'healthy';
206
+ }
207
+ else if (strategy === 'round-robin') {
208
+ for (let offset = 0; offset < states.length; offset++) {
209
+ const idx = (rrCursor + offset) % states.length;
210
+ const found = healthy.find((h) => h.index === idx);
211
+ if (found !== undefined) {
212
+ chosen = found;
213
+ rrCursor = (idx + 1) % states.length;
214
+ break;
215
+ }
216
+ }
217
+ pickReason = tried.size > 0 ? 'failover' : 'round-robin';
218
+ }
219
+ else {
220
+ chosen = healthy.reduce((best, cur) => (cur.inFlight < best.inFlight ? cur : best), healthy[0]);
221
+ pickReason = `${tried.size > 0 ? 'failover,' : ''}inFlight=${chosen.inFlight}`;
222
+ }
223
+ }
224
+ else if (cooledDownAvailable.length > 0 && tried.size === 0) {
225
+ chosen = cooledDownAvailable.reduce((best, cur) => (cur.cooldownUntil < best.cooldownUntil ? cur : best), cooledDownAvailable[0]);
226
+ pickReason = 'cooldown-fallback';
227
+ }
228
+ if (chosen === undefined) {
229
+ // every eligible target is busy up to its maxConcurrency: wait for a call to end (AD-081)
230
+ const atCapacity = skipped.length > 0 && skipped.every((s) => s.reason === 'max-concurrency');
231
+ if (lastErrorResult === undefined && atCapacity) {
232
+ if (!waitLogged) {
233
+ waitLogged = true;
234
+ ctx.emit('log', {
235
+ level: 'info',
236
+ msg: `agent-balancer: waiting for a free runner; at max concurrency: ${skipped.map((s) => s.name).join(', ')}`,
237
+ });
238
+ }
239
+ if (await freed(ctx.signal))
240
+ continue;
241
+ return { status: 'cancelled', reason: 'cancelled', usage: ZERO_USAGE, turns: 0 };
242
+ }
243
+ if (lastErrorResult !== undefined)
244
+ return lastErrorResult;
245
+ const summary = skipped.map((s) => `${s.name} (${s.reason})`).join(', ') || 'no targets configured';
246
+ const reason = `no available agent runner (${summary})`;
247
+ ctx.emit('log', { level: 'warn', msg: `agent-balancer: ${reason}` });
248
+ return { status: 'error', reason, usage: ZERO_USAGE, turns: 0 };
249
+ }
250
+ tried.add(chosen.index);
251
+ const mappedRequest = mapRequestForTarget(request, chosen.target.model);
252
+ const skippedList = skipped.filter((s) => s.index !== chosen.index).map((s) => `${s.name} (${s.reason})`);
253
+ const modelNote = mappedRequest.model !== request.model ? `, model=${mappedRequest.model ?? 'default'}` : '';
254
+ const skipNote = skippedList.length > 0 ? `; skipped: ${skippedList.join(', ')}` : '';
255
+ const level = pickReason === 'cooldown-fallback' ? 'warn' : 'info';
256
+ ctx.emit('log', {
257
+ level,
258
+ msg: `agent-balancer: selected ${chosen.target.name} (strategy=${strategy}, reason=${pickReason}${modelNote}${skipNote})`,
259
+ });
260
+ let streamedQuota;
261
+ const wrappedCtx = {
262
+ ...ctx,
263
+ emit: ((type, data) => {
264
+ if (type === 'agent.usage' && typeof data?.['quota'] === 'object' && data['quota'] !== null) {
265
+ streamedQuota = data['quota'];
266
+ }
267
+ ctx.emit(type, data);
268
+ }),
269
+ };
270
+ chosen.inFlight += 1;
271
+ let result;
272
+ try {
273
+ result = await chosen.target.runner(wrappedCtx, mappedRequest);
274
+ }
275
+ finally {
276
+ chosen.inFlight -= 1;
277
+ for (const wake of waiting.splice(0))
278
+ wake();
279
+ }
280
+ const quota = result.usage?.quota ?? streamedQuota;
281
+ // the server had no agent account for this harness (agent-accounts AC 25): cool down until
282
+ // the account it named frees, and fail over as for a rate limit
283
+ const noAccount = result.status === 'limit' ? NO_ACCOUNT.exec(result.reason) : null;
284
+ if (noAccount !== null && result.status === 'limit') {
285
+ const at = noAccount[1] !== undefined ? Date.parse(noAccount[1]) : NaN;
286
+ const until = Number.isFinite(at) && at > now() ? at : now() + cooldownMs;
287
+ chosen.cooldownUntil = until;
288
+ chosen.cooldownReason = result.reason;
289
+ const waitSec = Math.max(1, Math.round((until - now()) / 1000));
290
+ ctx.emit('log', {
291
+ level: 'warn',
292
+ msg: `agent-balancer: ${chosen.target.name} cooled down for ${waitSec}s (${result.reason}); failing over`,
293
+ });
294
+ lastErrorResult = result;
295
+ continue;
296
+ }
297
+ if (result.status === 'error' && isCooldownError(result.reason)) {
298
+ const until = resolveCooldownUntil(now(), cooldownMs, quota);
299
+ chosen.cooldownUntil = until;
300
+ chosen.cooldownReason = result.reason;
301
+ const waitSec = Math.max(1, Math.round((until - now()) / 1000));
302
+ ctx.emit('log', {
303
+ level: 'warn',
304
+ msg: `agent-balancer: ${chosen.target.name} cooled down for ${waitSec}s (${result.reason}); failing over`,
305
+ });
306
+ lastErrorResult = result;
307
+ continue;
308
+ }
309
+ const qReason = quotaExceeded(quota, quotaThreshold);
310
+ if (qReason !== undefined) {
311
+ const until = resolveCooldownUntil(now(), cooldownMs, quota);
312
+ chosen.cooldownUntil = until;
313
+ chosen.cooldownReason = qReason;
314
+ const waitSec = Math.max(1, Math.round((until - now()) / 1000));
315
+ ctx.emit('log', {
316
+ level: 'info',
317
+ msg: `agent-balancer: ${chosen.target.name} cooled down for ${waitSec}s (${qReason})`,
318
+ });
319
+ }
320
+ return result;
321
+ }
322
+ };
323
+ }
324
+ //# sourceMappingURL=agents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents.js","sourceRoot":"","sources":["../src/agents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAC,GAAsB,EAAE,SAAsC,EAAE;IACxF,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAClC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACzC,MAAM,MAAM,GAAG,GAAG,CAAC,iBAAiB,CAAC,IAAI,EAAE,CAAC;IAC5C,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;QAClB,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;YAAE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC;IACnD,CAAC;SAAM,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;QACzC,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC;IACD,MAAM,IAAI,gBAAgB,CAAC,kCAAkC,KAAK,CAAC,IAAI,CAAC,IAAI,CAA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,CAAC,cAAc,GAAG,OAAO,CAAC;gBAChC,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;gBAChE,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE;oBACd,KAAK,EAAE,MAAM;oBACb,GAAG,EAAE,mBAAmB,MAAM,CAAC,MAAM,CAAC,IAAI,oBAAoB,OAAO,MAAM,OAAO,GAAG;iBACtF,CAAC,CAAC;YACL,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/exec.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { Exec } from '@artieeez/cf-sdk';
2
+ /** Worker env names a process run by `ctx.exec` never sees (run-workspace door 6, AD-010). */
3
+ export declare const SCRUBBED_ENV: RegExp;
4
+ /** Longest logged line; longer ones are cut, ending in `…`. */
5
+ export declare const EXEC_LINE_MAX = 2000;
6
+ /** Lines logged per call; the rest are counted in one closing `log`. */
7
+ export declare const EXEC_LOG_LINES = 1000;
8
+ /** Between `SIGTERM` and `SIGKILL` to the process group. */
9
+ export declare const KILL_GRACE_MS = 5000;
10
+ /** The worker env minus the names in `SCRUBBED_ENV` and the loaded plugins' secret names (linear-plugin AC 28). */
11
+ export declare function scrubbedEnv(base?: NodeJS.ProcessEnv, secrets?: readonly string[]): Record<string, string>;
12
+ /** Whether `path` is `root` or under it. */
13
+ export declare function inside(root: string, path: string): boolean;
14
+ /**
15
+ * `rel` under `base`, refused when it leaves `root`: lexically, or through a symlink in the part
16
+ * that exists already.
17
+ */
18
+ export declare function confined(root: string, base: string, rel: string | undefined): string;
19
+ export interface ExecHost {
20
+ /** where a relative `cwd` starts and where the process runs by default */
21
+ base: string;
22
+ /** what `cwd` may not leave */
23
+ root: string;
24
+ /** one output line or note, as the runtime reports it */
25
+ line(msg: string, stream: 'stdout' | 'stderr' | 'note'): void;
26
+ /** aborting it kills every running process group, which then resolves `cancelled: true` */
27
+ signal: AbortSignal;
28
+ /** env names the process never sees, on top of `SCRUBBED_ENV`: the loaded plugins' secrets */
29
+ secrets?: readonly string[];
30
+ }
31
+ /** A `ctx.exec` bound to one context, and a way to kill what it still runs. */
32
+ export declare function createExec(host: ExecHost): {
33
+ exec: Exec;
34
+ killAll(): void;
35
+ };
36
+ //# sourceMappingURL=exec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,IAAI,EAA2B,MAAM,kBAAkB,CAAC;AAEtE,8FAA8F;AAC9F,eAAO,MAAM,YAAY,QAA6B,CAAC;AACvD,+DAA+D;AAC/D,eAAO,MAAM,aAAa,OAAO,CAAC;AAClC,wEAAwE;AACxE,eAAO,MAAM,cAAc,OAAO,CAAC;AACnC,4DAA4D;AAC5D,eAAO,MAAM,aAAa,OAAO,CAAC;AAGlC,mHAAmH;AACnH,wBAAgB,WAAW,CAAC,IAAI,GAAE,MAAM,CAAC,UAAwB,EAAE,OAAO,GAAE,SAAS,MAAM,EAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAM1H;AAED,4CAA4C;AAC5C,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAG1D;AAED;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAUpF;AAED,MAAM,WAAW,QAAQ;IACvB,0EAA0E;IAC1E,IAAI,EAAE,MAAM,CAAC;IACb,+BAA+B;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,yDAAyD;IACzD,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,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