@operad-io/pool 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/package.json +20 -4
- package/src/index.ts +309 -0
- package/src/places.ts +156 -0
- package/src/shared.ts +241 -0
- package/src/workers.ts +313 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yinghai Zhao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/pool",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts"
|
|
7
|
+
},
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@operad-io/engine": "0.0.1"
|
|
10
|
+
},
|
|
11
|
+
"description": "operad: the pool plugin, workers shared by runs (in development)",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/operad-io/operad.git",
|
|
15
|
+
"directory": "packages/pool"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"files": [
|
|
19
|
+
"src",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
]
|
|
22
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `pool` plugin: one step, `pool/agent`, that picks a worker with room in
|
|
3
|
+
* a pool, runs that worker's harness step and falls back to another worker
|
|
4
|
+
* when the model is unavailable. Two counts decide whether a worker may start:
|
|
5
|
+
* its own `count` in the repository and the home-wide cap on its harness.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { definePlugin, isRecord, type PluginStepResult, type StepContext, type StepRunOptions } from "@operad-io/engine";
|
|
9
|
+
import { reportWorkerPlaced } from "@operad-io/engine/platform";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { PlaceBook, type Claim, type Places } from "./places.ts";
|
|
12
|
+
import { FilePlaces } from "./shared.ts";
|
|
13
|
+
import {
|
|
14
|
+
harnessOf,
|
|
15
|
+
readResolved,
|
|
16
|
+
type WorkerDefinition,
|
|
17
|
+
} from "./workers.ts";
|
|
18
|
+
|
|
19
|
+
export * from "./workers.ts";
|
|
20
|
+
export { PlaceBook, type Claim, type ClaimResult, type Places } from "./places.ts";
|
|
21
|
+
export { FilePlaces } from "./shared.ts";
|
|
22
|
+
|
|
23
|
+
/** The event a waiting `pool/agent` sends. */
|
|
24
|
+
export const WAITING_EVENT = "pool.waiting";
|
|
25
|
+
/** The event a `pool/agent` sends when it got a place after it had waited. */
|
|
26
|
+
export const ACQUIRED_EVENT = "pool.acquired";
|
|
27
|
+
|
|
28
|
+
/** The settings a config.json section may set for this plugin. */
|
|
29
|
+
export const POOL_SETTINGS = {
|
|
30
|
+
type: "object" as const,
|
|
31
|
+
properties: {
|
|
32
|
+
harnesses: {
|
|
33
|
+
type: "object" as const,
|
|
34
|
+
additionalProperties: {
|
|
35
|
+
type: "integer" as const,
|
|
36
|
+
minimum: 1,
|
|
37
|
+
},
|
|
38
|
+
default: {},
|
|
39
|
+
description:
|
|
40
|
+
'How many runs through pool/agent may go at once in this home for one harness, as { "<harness plugin>": <count> }. A harness not listed has no limit. Takes effect with the next pool/agent step that starts.',
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** The settings keys, for the docs test. */
|
|
46
|
+
export const POOL_SETTING_NAMES: readonly string[] = Object.keys(POOL_SETTINGS.properties);
|
|
47
|
+
|
|
48
|
+
function capOf(
|
|
49
|
+
settings: Readonly<Record<string, unknown>>,
|
|
50
|
+
harness: string,
|
|
51
|
+
): number | undefined {
|
|
52
|
+
const map = settings.harnesses;
|
|
53
|
+
if (!isRecord(map)) return undefined;
|
|
54
|
+
const cap = map[harness];
|
|
55
|
+
return typeof cap === "number" ? cap : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** True when the harness step reported that it could not start at all. */
|
|
59
|
+
export function harnessDidNotStart(data: Readonly<Record<string, unknown>> | undefined): boolean {
|
|
60
|
+
return data?.reason === "missing" || data?.reason === "spawn";
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** True when the harness reported its model unavailable or at its usage limit. */
|
|
64
|
+
export function modelUnavailable(data: Readonly<Record<string, unknown>> | undefined): boolean {
|
|
65
|
+
const error = data?.modelError;
|
|
66
|
+
if (!isRecord(error)) return false;
|
|
67
|
+
return error.kind === "unavailable" || error.kind === "usage_limit";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function failed(reason: string, message: string, extra: Record<string, unknown> = {}): PluginStepResult {
|
|
71
|
+
return { result: "failed", data: { reason, message, ...extra } };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The params `pool/agent` reads itself; the harness step does not get them. */
|
|
75
|
+
const OWN_PARAMS = ["worker", "workers", "fallbacks", "prefix", "countPrefix", "holder"];
|
|
76
|
+
|
|
77
|
+
interface Place {
|
|
78
|
+
readonly worker: WorkerDefinition;
|
|
79
|
+
readonly release: () => Promise<void>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
type Attempt =
|
|
83
|
+
| { readonly kind: "result"; readonly result: PluginStepResult }
|
|
84
|
+
| { readonly kind: "threw"; readonly error: unknown };
|
|
85
|
+
|
|
86
|
+
export interface PoolPluginOptions {
|
|
87
|
+
/**
|
|
88
|
+
* Where the places live. A test passes a book to look at what is held; the
|
|
89
|
+
* plugin otherwise keeps them in a file under the home, because every step
|
|
90
|
+
* runs in a fresh worker thread that loads this plugin again.
|
|
91
|
+
*/
|
|
92
|
+
readonly book?: Places | undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function createPoolPlugin(options: PoolPluginOptions = {}) {
|
|
96
|
+
const places = (ctx: StepContext): Places =>
|
|
97
|
+
options.book ?? new FilePlaces(join(ctx.home, "pool"));
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Waits for the first of `candidates` whose own count and harness cap both
|
|
101
|
+
* have room and takes its places. Undefined when the signal aborts first.
|
|
102
|
+
*/
|
|
103
|
+
async function acquire(
|
|
104
|
+
ctx: StepContext,
|
|
105
|
+
prefix: string,
|
|
106
|
+
candidates: readonly WorkerDefinition[],
|
|
107
|
+
holder: string | undefined,
|
|
108
|
+
countPrefix: string = prefix,
|
|
109
|
+
): Promise<Place | undefined> {
|
|
110
|
+
const book = places(ctx);
|
|
111
|
+
let announced: string | undefined;
|
|
112
|
+
let announcements = 0;
|
|
113
|
+
for (;;) {
|
|
114
|
+
if (ctx.signal.aborted) return undefined;
|
|
115
|
+
const claims: Claim[] = candidates.map((worker) => {
|
|
116
|
+
const harness = harnessOf(worker.use);
|
|
117
|
+
return {
|
|
118
|
+
own: `count:${countPrefix}/${worker.name}`,
|
|
119
|
+
ownLimit: worker.count,
|
|
120
|
+
home: `harness:${harness}`,
|
|
121
|
+
homeLimit: capOf(ctx.settings, harness),
|
|
122
|
+
holder,
|
|
123
|
+
};
|
|
124
|
+
});
|
|
125
|
+
const got = await book.claim(claims);
|
|
126
|
+
if (got.kind === "taken") {
|
|
127
|
+
const worker = candidates[got.index];
|
|
128
|
+
if (worker === undefined) throw new Error("pool: a claim was taken for no worker");
|
|
129
|
+
if (announced !== undefined) {
|
|
130
|
+
await ctx.emit({
|
|
131
|
+
type: ACQUIRED_EVENT,
|
|
132
|
+
key: `${ctx.runId}:${prefix}:acquired`,
|
|
133
|
+
summary: `got a place in pool ${prefix}: ${worker.name}`,
|
|
134
|
+
data: { pool: prefix, worker: worker.name },
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return { worker, release: got.release };
|
|
138
|
+
}
|
|
139
|
+
const blocked = candidates.map((worker, index) => ({
|
|
140
|
+
worker: worker.name,
|
|
141
|
+
full: got.full[index] ?? "home",
|
|
142
|
+
holders: [...(got.holders[index] ?? [])],
|
|
143
|
+
}));
|
|
144
|
+
const full = blocked.every((item) => item.full === "flow") ? "flow" : "home";
|
|
145
|
+
const state = `${full}|${blocked.map((item) => item.holders.join(",")).join(";")}`;
|
|
146
|
+
if (announced !== state) {
|
|
147
|
+
announced = state;
|
|
148
|
+
announcements += 1;
|
|
149
|
+
const what =
|
|
150
|
+
full === "flow"
|
|
151
|
+
? "the flow's count of every worker is full"
|
|
152
|
+
: "the home cap of a harness is full";
|
|
153
|
+
await ctx.emit({
|
|
154
|
+
type: WAITING_EVENT,
|
|
155
|
+
key: `${ctx.runId}:${prefix}:${full}:${announcements}`,
|
|
156
|
+
summary: `waiting in pool ${prefix}: ${what}`,
|
|
157
|
+
data: { pool: prefix, full, workers: blocked },
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
if (!(await book.changed(got.stamp, ctx.signal))) return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** One run of one worker, with its places held only for the run. */
|
|
165
|
+
async function attempt(
|
|
166
|
+
ctx: StepContext,
|
|
167
|
+
prefix: string,
|
|
168
|
+
candidates: readonly WorkerDefinition[],
|
|
169
|
+
input: Record<string, unknown>,
|
|
170
|
+
options: StepRunOptions,
|
|
171
|
+
): Promise<
|
|
172
|
+
| { readonly kind: "aborted" }
|
|
173
|
+
| (Attempt & { readonly worker: WorkerDefinition })
|
|
174
|
+
> {
|
|
175
|
+
const holder = typeof input.holder === "string" ? input.holder : undefined;
|
|
176
|
+
// A worker's count is its own, whichever pool asks for it.
|
|
177
|
+
const countPrefix = typeof input.countPrefix === "string" ? input.countPrefix : prefix;
|
|
178
|
+
const place = await acquire(ctx, prefix, candidates, holder, countPrefix);
|
|
179
|
+
if (place === undefined) return { kind: "aborted" };
|
|
180
|
+
const { worker } = place;
|
|
181
|
+
reportWorkerPlaced(worker.name);
|
|
182
|
+
try {
|
|
183
|
+
const runStep = ctx.runStep;
|
|
184
|
+
if (runStep === undefined) {
|
|
185
|
+
throw new Error("the kernel did not offer a way to run the worker's harness step");
|
|
186
|
+
}
|
|
187
|
+
const rest: Record<string, unknown> = { ...input };
|
|
188
|
+
for (const key of OWN_PARAMS) delete rest[key];
|
|
189
|
+
const params = {
|
|
190
|
+
...rest,
|
|
191
|
+
args: worker.args,
|
|
192
|
+
...(worker.wallTimeSecs === undefined ? {} : { wallTimeSecs: worker.wallTimeSecs }),
|
|
193
|
+
...(worker.stallSecs === undefined ? {} : { stallSecs: worker.stallSecs }),
|
|
194
|
+
};
|
|
195
|
+
const result = await runStep(worker.use, params, options);
|
|
196
|
+
return { kind: "result", result, worker };
|
|
197
|
+
} catch (error) {
|
|
198
|
+
return { kind: "threw", error, worker };
|
|
199
|
+
} finally {
|
|
200
|
+
await place.release();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return definePlugin({
|
|
205
|
+
name: "pool",
|
|
206
|
+
kind: "stage",
|
|
207
|
+
version: "0.0.0",
|
|
208
|
+
settings: POOL_SETTINGS,
|
|
209
|
+
steps: [
|
|
210
|
+
{
|
|
211
|
+
name: "agent",
|
|
212
|
+
results: ["done", "failed", "interrupted"],
|
|
213
|
+
// A run waits for room and then runs an agent: as long as a harness step.
|
|
214
|
+
timeoutSecs: 8 * 3600,
|
|
215
|
+
async run(ctx, params): Promise<PluginStepResult> {
|
|
216
|
+
const at = "pool/agent";
|
|
217
|
+
if (!isRecord(params)) throw new Error(`${at}: params: must be an object`);
|
|
218
|
+
const prefix = params.prefix;
|
|
219
|
+
if (typeof prefix !== "string" || prefix.length === 0) {
|
|
220
|
+
throw new Error(`${at}: params.prefix: must be a non-empty string`);
|
|
221
|
+
}
|
|
222
|
+
const workers = readResolved(params.workers, `${at}: params.workers`);
|
|
223
|
+
if (workers.length === 0) {
|
|
224
|
+
throw new Error(`${at}: params.workers: must list at least one worker`);
|
|
225
|
+
}
|
|
226
|
+
const fallbacks =
|
|
227
|
+
params.fallbacks === undefined
|
|
228
|
+
? []
|
|
229
|
+
: readResolved(params.fallbacks, `${at}: params.fallbacks`);
|
|
230
|
+
const asked = params.worker;
|
|
231
|
+
if (asked !== undefined && typeof asked !== "string") {
|
|
232
|
+
throw new Error(`${at}: params.worker: must be a worker name`);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
let candidates = workers;
|
|
236
|
+
if (asked !== undefined) {
|
|
237
|
+
candidates = workers.filter((worker) => worker.name === asked);
|
|
238
|
+
if (candidates.length === 0) {
|
|
239
|
+
return failed(
|
|
240
|
+
"unknown_worker",
|
|
241
|
+
`the worker "${asked}" is not in pool ${prefix} (${workers.map((worker) => worker.name).join(", ")})`,
|
|
242
|
+
{ requested: asked },
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const options: StepRunOptions = {
|
|
248
|
+
runId: ctx.runId,
|
|
249
|
+
cwd: typeof params.cwd === "string" ? params.cwd : ctx.cwd,
|
|
250
|
+
...(ctx.object === undefined ? {} : { object: ctx.object }),
|
|
251
|
+
params: ctx.params,
|
|
252
|
+
access: ctx.access,
|
|
253
|
+
...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
|
|
254
|
+
signal: ctx.signal,
|
|
255
|
+
};
|
|
256
|
+
const interrupted = (): PluginStepResult => ({
|
|
257
|
+
result: "interrupted",
|
|
258
|
+
data: { reason: "cancelled", message: `stopped while waiting in pool ${prefix}` },
|
|
259
|
+
});
|
|
260
|
+
const record = (
|
|
261
|
+
result: PluginStepResult,
|
|
262
|
+
worker: WorkerDefinition,
|
|
263
|
+
from: WorkerDefinition | undefined,
|
|
264
|
+
): PluginStepResult => ({
|
|
265
|
+
result: result.result,
|
|
266
|
+
data: {
|
|
267
|
+
...(result.data ?? {}),
|
|
268
|
+
worker: worker.name,
|
|
269
|
+
harness: harnessOf(worker.use),
|
|
270
|
+
...(from === undefined ? {} : { fallbackFrom: from.name }),
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
const first = await attempt(ctx, prefix, candidates, params, options);
|
|
275
|
+
if (first.kind === "aborted") return interrupted();
|
|
276
|
+
const name = first.worker.fallback;
|
|
277
|
+
const triggered =
|
|
278
|
+
name !== undefined &&
|
|
279
|
+
!ctx.signal.aborted &&
|
|
280
|
+
(first.kind === "threw" ||
|
|
281
|
+
modelUnavailable(first.result.data) ||
|
|
282
|
+
(first.result.result === "failed" && harnessDidNotStart(first.result.data)));
|
|
283
|
+
if (!triggered) {
|
|
284
|
+
if (first.kind === "threw") throw first.error;
|
|
285
|
+
return record(first.result, first.worker, undefined);
|
|
286
|
+
}
|
|
287
|
+
const target = [...workers, ...fallbacks].find((worker) => worker.name === name);
|
|
288
|
+
if (target === undefined) {
|
|
289
|
+
return failed(
|
|
290
|
+
"unknown_fallback",
|
|
291
|
+
`the fallback "${name}" of "${first.worker.name}" is not in the definitions given to pool/agent`,
|
|
292
|
+
{ worker: first.worker.name },
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// The first worker's places are already released; wait for the fallback's.
|
|
297
|
+
// A session belongs to the worker that was asked for; the fallback starts its own.
|
|
298
|
+
const { resumeSession: _session, ...fallbackParams } = params;
|
|
299
|
+
const second = await attempt(ctx, prefix, [target], fallbackParams, options);
|
|
300
|
+
if (second.kind === "aborted") return interrupted();
|
|
301
|
+
if (second.kind === "threw") throw second.error;
|
|
302
|
+
return record(second.result, second.worker, first.worker);
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
],
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export default createPoolPlugin();
|
package/src/places.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The places a `pool/agent` run holds. The engine's step limiter only blocks;
|
|
3
|
+
* the pool must ask "is there room" for several workers and take the first,
|
|
4
|
+
* so the counts live here. One serve process owns one home, so one book per
|
|
5
|
+
* plugin instance is the home-wide count.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** One worker's two counts: its own in the flow and its harness at home. */
|
|
9
|
+
export interface Claim {
|
|
10
|
+
readonly own: string;
|
|
11
|
+
readonly ownLimit: number;
|
|
12
|
+
readonly home: string;
|
|
13
|
+
readonly homeLimit: number | undefined;
|
|
14
|
+
/** Who takes the place, so a waiter can say who holds it (a task id). */
|
|
15
|
+
readonly holder?: string | undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** What `claim` answers: a place held for claim `index`, or what is full. */
|
|
19
|
+
export type ClaimResult =
|
|
20
|
+
| { readonly kind: "taken"; readonly index: number; readonly release: () => Promise<void> }
|
|
21
|
+
| {
|
|
22
|
+
readonly kind: "blocked";
|
|
23
|
+
/** For each claim, the count that is full. */
|
|
24
|
+
readonly full: readonly ("flow" | "home")[];
|
|
25
|
+
/** For each claim, who holds the places of the count that is full. */
|
|
26
|
+
readonly holders: readonly (readonly string[])[];
|
|
27
|
+
/** Pass to `changed`: a release after it wakes the waiter. */
|
|
28
|
+
readonly stamp: number;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Where the places live: in memory (a test) or in the home (the plugin). */
|
|
32
|
+
export interface Places {
|
|
33
|
+
/** Atomically takes the first claim that has room in both counts. */
|
|
34
|
+
claim(claims: readonly Claim[]): Promise<ClaimResult>;
|
|
35
|
+
/**
|
|
36
|
+
* Resolves true once something may have been released after `since`, false
|
|
37
|
+
* when `signal` aborts first. A true answer may be spurious; ask again.
|
|
38
|
+
*/
|
|
39
|
+
changed(since: number, signal: AbortSignal): Promise<boolean>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class PlaceBook implements Places {
|
|
43
|
+
private readonly held = new Map<string, number>();
|
|
44
|
+
private readonly labels = new Map<string, string[]>();
|
|
45
|
+
private version = 0;
|
|
46
|
+
private readonly listeners = new Set<() => void>();
|
|
47
|
+
|
|
48
|
+
/** How many places are held under `key`. */
|
|
49
|
+
used(key: string): number {
|
|
50
|
+
return this.held.get(key) ?? 0;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** True when `key` has room for one more under `limit`; no limit means room. */
|
|
54
|
+
hasRoom(key: string, limit: number | undefined): boolean {
|
|
55
|
+
return limit === undefined || this.used(key) < limit;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
claim(claims: readonly Claim[]): Promise<ClaimResult> {
|
|
59
|
+
const full: ("flow" | "home")[] = [];
|
|
60
|
+
const holders: (readonly string[])[] = [];
|
|
61
|
+
for (const [index, claim] of claims.entries()) {
|
|
62
|
+
if (!this.hasRoom(claim.own, claim.ownLimit)) {
|
|
63
|
+
full.push("flow");
|
|
64
|
+
holders.push(this.labels.get(claim.own) ?? []);
|
|
65
|
+
} else if (!this.hasRoom(claim.home, claim.homeLimit)) {
|
|
66
|
+
full.push("home");
|
|
67
|
+
holders.push(this.labels.get(claim.home) ?? []);
|
|
68
|
+
} else {
|
|
69
|
+
const give = this.take([claim.own, claim.home], claim.holder);
|
|
70
|
+
return Promise.resolve({
|
|
71
|
+
kind: "taken",
|
|
72
|
+
index,
|
|
73
|
+
release: () => {
|
|
74
|
+
give();
|
|
75
|
+
return Promise.resolve();
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return Promise.resolve({ kind: "blocked", full, holders, stamp: this.version });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Holds one place under each key and returns the call that gives them back. */
|
|
84
|
+
take(keys: readonly string[], holder?: string): () => void {
|
|
85
|
+
for (const key of keys) {
|
|
86
|
+
this.held.set(key, this.used(key) + 1);
|
|
87
|
+
if (holder !== undefined) this.labels.set(key, [...(this.labels.get(key) ?? []), holder]);
|
|
88
|
+
}
|
|
89
|
+
let released = false;
|
|
90
|
+
return () => {
|
|
91
|
+
if (released) return;
|
|
92
|
+
released = true;
|
|
93
|
+
for (const key of keys) {
|
|
94
|
+
const left = this.used(key) - 1;
|
|
95
|
+
if (left <= 0) this.held.delete(key);
|
|
96
|
+
else this.held.set(key, left);
|
|
97
|
+
if (holder !== undefined) {
|
|
98
|
+
const rest = [...(this.labels.get(key) ?? [])];
|
|
99
|
+
const at = rest.indexOf(holder);
|
|
100
|
+
if (at >= 0) rest.splice(at, 1);
|
|
101
|
+
if (rest.length === 0) this.labels.delete(key);
|
|
102
|
+
else this.labels.set(key, rest);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
this.version += 1;
|
|
106
|
+
for (const listener of [...this.listeners]) listener();
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A number that changes whenever a place is released. */
|
|
111
|
+
stamp(): number {
|
|
112
|
+
return this.version;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Resolves true once a place has been released after `since`, or false when
|
|
117
|
+
* `signal` aborts first. Nothing is left registered afterwards.
|
|
118
|
+
*/
|
|
119
|
+
changed(since: number, signal: AbortSignal): Promise<boolean> {
|
|
120
|
+
if (this.version !== since) return Promise.resolve(true);
|
|
121
|
+
if (signal.aborted) return Promise.resolve(false);
|
|
122
|
+
return new Promise((resolve) => {
|
|
123
|
+
const done = (value: boolean): void => {
|
|
124
|
+
this.listeners.delete(onRelease);
|
|
125
|
+
signal.removeEventListener("abort", onAbort);
|
|
126
|
+
resolve(value);
|
|
127
|
+
};
|
|
128
|
+
const onRelease = (): void => done(true);
|
|
129
|
+
const onAbort = (): void => done(false);
|
|
130
|
+
this.listeners.add(onRelease);
|
|
131
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
132
|
+
this.parked();
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The number of steps parked in `changed`. */
|
|
137
|
+
waiting(): number {
|
|
138
|
+
return this.listeners.size;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Resolves once `count` steps are parked in `changed`; no polling. */
|
|
142
|
+
whenWaiting(count: number): Promise<void> {
|
|
143
|
+
if (this.listeners.size >= count) return Promise.resolve();
|
|
144
|
+
return new Promise((resolve) => this.parkWatchers.push({ count, resolve }));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private readonly parkWatchers: { count: number; resolve: () => void }[] = [];
|
|
148
|
+
|
|
149
|
+
private parked(): void {
|
|
150
|
+
for (const watcher of [...this.parkWatchers]) {
|
|
151
|
+
if (this.listeners.size < watcher.count) continue;
|
|
152
|
+
this.parkWatchers.splice(this.parkWatchers.indexOf(watcher), 1);
|
|
153
|
+
watcher.resolve();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
package/src/shared.ts
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The places of one home, shared by every step of every thread and process.
|
|
3
|
+
* The kernel runs each step in a fresh worker thread that loads the plugin
|
|
4
|
+
* again, so a count kept in memory would start from zero in every step. The
|
|
5
|
+
* counts live in one file under the home instead, changed under a lock file.
|
|
6
|
+
* A place records the pid that holds it; a place whose process is gone (a
|
|
7
|
+
* crashed serve) is dropped the next time anyone looks.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { watchDirectory, withLockFile } from "@operad-io/engine/platform";
|
|
14
|
+
import type { Claim, ClaimResult, Places } from "./places.ts";
|
|
15
|
+
import { isRecord } from "@operad-io/engine";
|
|
16
|
+
|
|
17
|
+
/** How often a waiter looks again when no change was announced. */
|
|
18
|
+
const RECHECK_MS = 1000;
|
|
19
|
+
/** How often a holder says it is still there. */
|
|
20
|
+
const HEARTBEAT_MS = 2000;
|
|
21
|
+
/** A place whose holder has not said so for this long is dropped. */
|
|
22
|
+
const LEASE_MS = 10000;
|
|
23
|
+
|
|
24
|
+
export interface FilePlacesOptions {
|
|
25
|
+
readonly now?: () => number;
|
|
26
|
+
readonly heartbeatMs?: number;
|
|
27
|
+
readonly leaseMs?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface Held {
|
|
31
|
+
readonly id: string;
|
|
32
|
+
readonly pid: number;
|
|
33
|
+
/** The last time the holder said it is alive; a terminated step thread stops saying it. */
|
|
34
|
+
readonly beat: number;
|
|
35
|
+
readonly keys: readonly string[];
|
|
36
|
+
/** Who took the place, when the claim said (a task id). */
|
|
37
|
+
readonly holder?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface Book {
|
|
41
|
+
readonly version: number;
|
|
42
|
+
readonly held: readonly Held[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseBook(text: string): Book {
|
|
46
|
+
try {
|
|
47
|
+
const raw: unknown = JSON.parse(text);
|
|
48
|
+
if (!isRecord(raw) || typeof raw.version !== "number" || !Array.isArray(raw.held)) {
|
|
49
|
+
return { version: 0, held: [] };
|
|
50
|
+
}
|
|
51
|
+
const held: Held[] = [];
|
|
52
|
+
for (const entry of raw.held) {
|
|
53
|
+
if (
|
|
54
|
+
isRecord(entry) &&
|
|
55
|
+
typeof entry.id === "string" &&
|
|
56
|
+
typeof entry.pid === "number" &&
|
|
57
|
+
Array.isArray(entry.keys) &&
|
|
58
|
+
entry.keys.every((key) => typeof key === "string")
|
|
59
|
+
) {
|
|
60
|
+
held.push({
|
|
61
|
+
id: entry.id,
|
|
62
|
+
pid: entry.pid,
|
|
63
|
+
beat: typeof entry.beat === "number" ? entry.beat : 0,
|
|
64
|
+
keys: entry.keys as string[],
|
|
65
|
+
...(typeof entry.holder === "string" ? { holder: entry.holder } : {}),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { version: raw.version, held };
|
|
70
|
+
} catch {
|
|
71
|
+
return { version: 0, held: [] };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** True when a process with this pid exists; sends no signal. */
|
|
76
|
+
function alive(pid: number): boolean {
|
|
77
|
+
if (pid === process.pid) return true;
|
|
78
|
+
try {
|
|
79
|
+
process.kill(pid, 0);
|
|
80
|
+
return true;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
return error instanceof Error && "code" in error && error.code === "EPERM";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class FilePlaces implements Places {
|
|
87
|
+
private readonly file: string;
|
|
88
|
+
private readonly lock: string;
|
|
89
|
+
private counter = 0;
|
|
90
|
+
|
|
91
|
+
private readonly now: () => number;
|
|
92
|
+
private readonly heartbeatMs: number;
|
|
93
|
+
private readonly leaseMs: number;
|
|
94
|
+
|
|
95
|
+
constructor(
|
|
96
|
+
private readonly dir: string,
|
|
97
|
+
options: FilePlacesOptions = {},
|
|
98
|
+
) {
|
|
99
|
+
this.now = options.now ?? Date.now;
|
|
100
|
+
this.heartbeatMs = options.heartbeatMs ?? HEARTBEAT_MS;
|
|
101
|
+
this.leaseMs = options.leaseMs ?? LEASE_MS;
|
|
102
|
+
this.file = join(dir, "places.json");
|
|
103
|
+
this.lock = join(dir, "places.lock");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private read(): Book {
|
|
107
|
+
try {
|
|
108
|
+
return parseBook(readFileSync(this.file, "utf8"));
|
|
109
|
+
} catch {
|
|
110
|
+
return { version: 0, held: [] };
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private write(book: Book): void {
|
|
115
|
+
mkdirSync(this.dir, { recursive: true });
|
|
116
|
+
const tmp = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
|
|
117
|
+
writeFileSync(tmp, JSON.stringify(book));
|
|
118
|
+
renameSync(tmp, this.file);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private quiet<T>(work: () => T): Promise<T> {
|
|
122
|
+
return withLockFile(this.lock, work, { onLog: () => undefined, label: "pool places" });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The book without the places of dead processes or of holders whose lease
|
|
127
|
+
* ran out (a step thread killed before it could release). The pruned book
|
|
128
|
+
* is written, so a waiter sees a version that is really on disk.
|
|
129
|
+
*/
|
|
130
|
+
private live(): Book {
|
|
131
|
+
const book = this.read();
|
|
132
|
+
const now = this.now();
|
|
133
|
+
const held = book.held.filter((entry) => alive(entry.pid) && now - entry.beat <= this.leaseMs);
|
|
134
|
+
if (held.length === book.held.length) return book;
|
|
135
|
+
const pruned = { version: book.version + 1, held };
|
|
136
|
+
this.write(pruned);
|
|
137
|
+
return pruned;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Keeps the lease of one place fresh until it is released. */
|
|
141
|
+
private beat(id: string): () => void {
|
|
142
|
+
const timer = setInterval(() => {
|
|
143
|
+
this.quiet(() => {
|
|
144
|
+
const book = this.read();
|
|
145
|
+
if (!book.held.some((entry) => entry.id === id)) return;
|
|
146
|
+
const now = this.now();
|
|
147
|
+
this.write({
|
|
148
|
+
version: book.version,
|
|
149
|
+
held: book.held.map((entry) => (entry.id === id ? { ...entry, beat: now } : entry)),
|
|
150
|
+
});
|
|
151
|
+
}).catch(() => undefined);
|
|
152
|
+
}, this.heartbeatMs);
|
|
153
|
+
timer.unref();
|
|
154
|
+
return () => clearInterval(timer);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
claim(claims: readonly Claim[]): Promise<ClaimResult> {
|
|
158
|
+
return this.quiet((): ClaimResult => {
|
|
159
|
+
const book = this.live();
|
|
160
|
+
const used = (key: string): number =>
|
|
161
|
+
book.held.filter((entry) => entry.keys.includes(key)).length;
|
|
162
|
+
const holding = (key: string): string[] =>
|
|
163
|
+
book.held.flatMap((entry) =>
|
|
164
|
+
entry.keys.includes(key) && entry.holder !== undefined ? [entry.holder] : [],
|
|
165
|
+
);
|
|
166
|
+
const full: ("flow" | "home")[] = [];
|
|
167
|
+
const holders: (readonly string[])[] = [];
|
|
168
|
+
for (const [index, claim] of claims.entries()) {
|
|
169
|
+
if (used(claim.own) >= claim.ownLimit) {
|
|
170
|
+
full.push("flow");
|
|
171
|
+
holders.push(holding(claim.own));
|
|
172
|
+
} else if (claim.homeLimit !== undefined && used(claim.home) >= claim.homeLimit) {
|
|
173
|
+
full.push("home");
|
|
174
|
+
holders.push(holding(claim.home));
|
|
175
|
+
} else {
|
|
176
|
+
this.counter += 1;
|
|
177
|
+
// Unique across instances: step threads share the pid and may share the millisecond.
|
|
178
|
+
const id = `${process.pid}-${randomUUID()}`;
|
|
179
|
+
this.write({
|
|
180
|
+
version: book.version + 1,
|
|
181
|
+
held: [
|
|
182
|
+
...book.held,
|
|
183
|
+
{
|
|
184
|
+
id,
|
|
185
|
+
pid: process.pid,
|
|
186
|
+
beat: this.now(),
|
|
187
|
+
keys: [claim.own, claim.home],
|
|
188
|
+
...(claim.holder === undefined ? {} : { holder: claim.holder }),
|
|
189
|
+
},
|
|
190
|
+
],
|
|
191
|
+
});
|
|
192
|
+
const stop = this.beat(id);
|
|
193
|
+
return {
|
|
194
|
+
kind: "taken",
|
|
195
|
+
index,
|
|
196
|
+
release: () => {
|
|
197
|
+
stop();
|
|
198
|
+
return this.release(id);
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return { kind: "blocked", full, holders, stamp: book.version };
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private release(id: string): Promise<void> {
|
|
208
|
+
return this.quiet(() => {
|
|
209
|
+
const book = this.read();
|
|
210
|
+
this.write({
|
|
211
|
+
version: book.version + 1,
|
|
212
|
+
held: book.held.filter((entry) => entry.id !== id),
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
changed(since: number, signal: AbortSignal): Promise<boolean> {
|
|
218
|
+
if (signal.aborted) return Promise.resolve(false);
|
|
219
|
+
if (this.read().version !== since) return Promise.resolve(true);
|
|
220
|
+
mkdirSync(this.dir, { recursive: true });
|
|
221
|
+
return new Promise((resolve) => {
|
|
222
|
+
const stop = watchDirectory(this.dir, () => {
|
|
223
|
+
if (this.read().version !== since) done(true);
|
|
224
|
+
});
|
|
225
|
+
const timer = setInterval(() => {
|
|
226
|
+
// A holder that died never announces; look again.
|
|
227
|
+
done(true);
|
|
228
|
+
}, RECHECK_MS);
|
|
229
|
+
const onAbort = (): void => done(false);
|
|
230
|
+
const done = (value: boolean): void => {
|
|
231
|
+
stop();
|
|
232
|
+
clearInterval(timer);
|
|
233
|
+
signal.removeEventListener("abort", onAbort);
|
|
234
|
+
resolve(value);
|
|
235
|
+
};
|
|
236
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
237
|
+
// A change between the first read and the watcher is not missed.
|
|
238
|
+
if (this.read().version !== since) done(true);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
package/src/workers.ts
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { isRecord } from "@operad-io/engine";
|
|
2
|
+
/**
|
|
3
|
+
* The worker definitions of a flow's settings: `workers` and `pools`. The
|
|
4
|
+
* parser here is the one place that knows their fields, defaults and
|
|
5
|
+
* refusals, so `dev` and later flows share them. `WORKER_FIELDS` and
|
|
6
|
+
* `POOL_FIELDS` are the list the parser and the docs test both read.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** A worker as a flow writes it, with every default filled. */
|
|
10
|
+
export interface WorkerDefinition {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
/** The harness step, `<plugin>/<step>`. */
|
|
13
|
+
readonly use: string;
|
|
14
|
+
readonly args: readonly string[];
|
|
15
|
+
/** How many runs of this worker may go at once in one repository. */
|
|
16
|
+
readonly count: number;
|
|
17
|
+
readonly wallTimeSecs?: number | undefined;
|
|
18
|
+
readonly stallSecs?: number | undefined;
|
|
19
|
+
/** Another worker of the same set to run when this one's model fails. */
|
|
20
|
+
readonly fallback?: string | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** One documented field of a worker definition. */
|
|
24
|
+
export interface FieldInfo {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
readonly type: string;
|
|
27
|
+
/** The default as the docs print it, or `none` when the field is optional. */
|
|
28
|
+
readonly default: unknown;
|
|
29
|
+
readonly required: boolean;
|
|
30
|
+
/** Words the docs must use for a default that is not a plain value. */
|
|
31
|
+
readonly defaultText?: string | undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The fields of one entry of `workers`. */
|
|
35
|
+
export const WORKER_FIELDS: readonly FieldInfo[] = [
|
|
36
|
+
{ name: "use", type: "string", default: undefined, required: true },
|
|
37
|
+
{ name: "args", type: "array of strings", default: [], required: false },
|
|
38
|
+
{ name: "count", type: "integer", default: 1, required: false },
|
|
39
|
+
{ name: "wallTimeSecs", type: "number", default: undefined, required: false },
|
|
40
|
+
{ name: "stallSecs", type: "number", default: undefined, required: false },
|
|
41
|
+
{ name: "fallback", type: "string", default: undefined, required: false },
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
/** The two settings of a flow that define workers. */
|
|
45
|
+
export const POOL_FIELDS: readonly FieldInfo[] = [
|
|
46
|
+
{ name: "workers", type: "object", default: undefined, required: true },
|
|
47
|
+
{
|
|
48
|
+
name: "pools",
|
|
49
|
+
type: "object",
|
|
50
|
+
default: undefined,
|
|
51
|
+
required: false,
|
|
52
|
+
defaultText: "one pool named `default`",
|
|
53
|
+
},
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
/** The pool that exists when `pools` is absent. */
|
|
57
|
+
export const DEFAULT_POOL = "default";
|
|
58
|
+
|
|
59
|
+
/** A refusal of worker definitions; `field` is the path of the bad value. */
|
|
60
|
+
export class WorkerDefinitionError extends Error {
|
|
61
|
+
readonly field: string;
|
|
62
|
+
constructor(field: string, message: string) {
|
|
63
|
+
super(`${field}: ${message}`);
|
|
64
|
+
this.name = "WorkerDefinitionError";
|
|
65
|
+
this.field = field;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function join(prefix: string, name: string): string {
|
|
70
|
+
return prefix === "" ? name : `${prefix}.${name}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function positiveNumber(value: unknown, field: string): number {
|
|
74
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
75
|
+
throw new WorkerDefinitionError(field, "must be a positive number of seconds");
|
|
76
|
+
}
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** True when `use` is `<plugin>/<step>`. */
|
|
81
|
+
export function isStepName(use: string): boolean {
|
|
82
|
+
return /^[^/\s]+\/[^/\s]+$/.test(use);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The plugin name of a `<plugin>/<step>` use. */
|
|
86
|
+
export function harnessOf(use: string): string {
|
|
87
|
+
return use.slice(0, use.indexOf("/"));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Reads one worker; `at` is its path, such as `workers.claude`. */
|
|
91
|
+
export function readWorker(name: string, value: unknown, at: string): WorkerDefinition {
|
|
92
|
+
if (!isRecord(value)) throw new WorkerDefinitionError(at, "must be an object");
|
|
93
|
+
const known = WORKER_FIELDS.map((field) => field.name);
|
|
94
|
+
for (const key of Object.keys(value)) {
|
|
95
|
+
if (!known.includes(key)) {
|
|
96
|
+
throw new WorkerDefinitionError(`${at}.${key}`, "is not a worker field");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const use = value.use;
|
|
100
|
+
if (typeof use !== "string" || !isStepName(use)) {
|
|
101
|
+
throw new WorkerDefinitionError(
|
|
102
|
+
`${at}.use`,
|
|
103
|
+
"must be a step name such as claude/agent",
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
let args: readonly string[] = [];
|
|
107
|
+
if (value.args !== undefined) {
|
|
108
|
+
if (!Array.isArray(value.args)) {
|
|
109
|
+
throw new WorkerDefinitionError(`${at}.args`, "must be an array of strings");
|
|
110
|
+
}
|
|
111
|
+
args = value.args.map((item: unknown, index: number) => {
|
|
112
|
+
if (typeof item !== "string") {
|
|
113
|
+
throw new WorkerDefinitionError(`${at}.args[${index}]`, "must be a string");
|
|
114
|
+
}
|
|
115
|
+
return item;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
let count = 1;
|
|
119
|
+
if (value.count !== undefined) {
|
|
120
|
+
if (typeof value.count !== "number" || !Number.isInteger(value.count) || value.count < 1) {
|
|
121
|
+
throw new WorkerDefinitionError(`${at}.count`, "must be an integer of 1 or more");
|
|
122
|
+
}
|
|
123
|
+
count = value.count;
|
|
124
|
+
}
|
|
125
|
+
const wallTimeSecs =
|
|
126
|
+
value.wallTimeSecs === undefined
|
|
127
|
+
? undefined
|
|
128
|
+
: positiveNumber(value.wallTimeSecs, `${at}.wallTimeSecs`);
|
|
129
|
+
const stallSecs =
|
|
130
|
+
value.stallSecs === undefined
|
|
131
|
+
? undefined
|
|
132
|
+
: positiveNumber(value.stallSecs, `${at}.stallSecs`);
|
|
133
|
+
let fallback: string | undefined;
|
|
134
|
+
if (value.fallback !== undefined) {
|
|
135
|
+
if (typeof value.fallback !== "string" || value.fallback.length === 0) {
|
|
136
|
+
throw new WorkerDefinitionError(`${at}.fallback`, "must be a worker name");
|
|
137
|
+
}
|
|
138
|
+
fallback = value.fallback;
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
name,
|
|
142
|
+
use,
|
|
143
|
+
args,
|
|
144
|
+
count,
|
|
145
|
+
...(wallTimeSecs === undefined ? {} : { wallTimeSecs }),
|
|
146
|
+
...(stallSecs === undefined ? {} : { stallSecs }),
|
|
147
|
+
...(fallback === undefined ? {} : { fallback }),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The workers of a flow and its pools, parsed and checked. */
|
|
152
|
+
export interface ParsedWorkers {
|
|
153
|
+
/** Every worker, in the order written. */
|
|
154
|
+
readonly workers: readonly WorkerDefinition[];
|
|
155
|
+
/** Pool name to its worker names, in order. */
|
|
156
|
+
readonly pools: Readonly<Record<string, readonly string[]>>;
|
|
157
|
+
/** Pool name to the `concurrency` its object form wrote; absent when none did. */
|
|
158
|
+
readonly poolConcurrency?: Readonly<Record<string, number>> | undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Parses the `workers` and `pools` values of a flow's settings. `prefix` is
|
|
163
|
+
* the path they sit under ("" when they are top-level fields), so a refusal
|
|
164
|
+
* names `workers.claude.fallback` or `settings.workers.claude.fallback`.
|
|
165
|
+
*/
|
|
166
|
+
export function parseWorkers(
|
|
167
|
+
workers: unknown,
|
|
168
|
+
pools: unknown,
|
|
169
|
+
prefix = "",
|
|
170
|
+
): ParsedWorkers {
|
|
171
|
+
const workersAt = join(prefix, "workers");
|
|
172
|
+
const poolsAt = join(prefix, "pools");
|
|
173
|
+
if (!isRecord(workers)) throw new WorkerDefinitionError(workersAt, "must be an object");
|
|
174
|
+
const list = Object.entries(workers).map(([name, value]) =>
|
|
175
|
+
readWorker(name, value, `${workersAt}.${name}`),
|
|
176
|
+
);
|
|
177
|
+
if (list.length === 0) {
|
|
178
|
+
throw new WorkerDefinitionError(workersAt, "must define at least one worker");
|
|
179
|
+
}
|
|
180
|
+
const byName = new Map(list.map((worker) => [worker.name, worker]));
|
|
181
|
+
|
|
182
|
+
for (const worker of list) {
|
|
183
|
+
const at = `${workersAt}.${worker.name}.fallback`;
|
|
184
|
+
if (worker.fallback === undefined) continue;
|
|
185
|
+
if (worker.fallback === worker.name) {
|
|
186
|
+
throw new WorkerDefinitionError(at, `"${worker.name}" cannot fall back to itself`);
|
|
187
|
+
}
|
|
188
|
+
const target = byName.get(worker.fallback);
|
|
189
|
+
if (target === undefined) {
|
|
190
|
+
throw new WorkerDefinitionError(at, `"${worker.fallback}" is not a worker in ${workersAt}`);
|
|
191
|
+
}
|
|
192
|
+
if (target.fallback !== undefined) {
|
|
193
|
+
if (target.fallback === worker.name) {
|
|
194
|
+
throw new WorkerDefinitionError(
|
|
195
|
+
at,
|
|
196
|
+
`"${worker.name}" and "${worker.fallback}" fall back to each other`,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
throw new WorkerDefinitionError(
|
|
200
|
+
at,
|
|
201
|
+
`a fallback chain is one step: "${worker.fallback}" already has a fallback`,
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const poolMap: Record<string, readonly string[]> = {};
|
|
207
|
+
const limits: Record<string, number> = {};
|
|
208
|
+
if (pools === undefined) {
|
|
209
|
+
poolMap[DEFAULT_POOL] = list.map((worker) => worker.name);
|
|
210
|
+
} else {
|
|
211
|
+
if (!isRecord(pools)) throw new WorkerDefinitionError(poolsAt, "must be an object");
|
|
212
|
+
const entries = Object.entries(pools);
|
|
213
|
+
if (entries.length === 0) {
|
|
214
|
+
throw new WorkerDefinitionError(poolsAt, "must define at least one pool");
|
|
215
|
+
}
|
|
216
|
+
for (const [pool, written] of entries) {
|
|
217
|
+
const at = `${poolsAt}.${pool}`;
|
|
218
|
+
let names: unknown = written;
|
|
219
|
+
if (isRecord(written)) {
|
|
220
|
+
for (const key of Object.keys(written)) {
|
|
221
|
+
if (key !== "workers" && key !== "concurrency") {
|
|
222
|
+
throw new WorkerDefinitionError(`${at}.${key}`, "is not a pool setting");
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
names = written.workers;
|
|
226
|
+
if (written.concurrency !== undefined) {
|
|
227
|
+
const limit = written.concurrency;
|
|
228
|
+
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) {
|
|
229
|
+
throw new WorkerDefinitionError(`${at}.concurrency`, "must be an integer of at least 1");
|
|
230
|
+
}
|
|
231
|
+
limits[pool] = limit;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const listAt = isRecord(written) ? `${at}.workers` : at;
|
|
235
|
+
if (!Array.isArray(names) || names.length === 0) {
|
|
236
|
+
throw new WorkerDefinitionError(listAt, "must be a non-empty list of worker names");
|
|
237
|
+
}
|
|
238
|
+
poolMap[pool] = names.map((name: unknown, index: number) => {
|
|
239
|
+
if (typeof name !== "string") {
|
|
240
|
+
throw new WorkerDefinitionError(`${listAt}[${index}]`, "must be a worker name");
|
|
241
|
+
}
|
|
242
|
+
if (!byName.has(name)) {
|
|
243
|
+
throw new WorkerDefinitionError(
|
|
244
|
+
`${listAt}[${index}]`,
|
|
245
|
+
`"${name}" is not a worker in ${workersAt}`,
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
return name;
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
workers: list,
|
|
254
|
+
pools: poolMap,
|
|
255
|
+
...(Object.keys(limits).length === 0 ? {} : { poolConcurrency: limits }),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** What a caller passes to `pool/agent` for one pool. */
|
|
260
|
+
export interface ResolvedPool {
|
|
261
|
+
/** The pool's workers, in order: the ones `pool/agent` picks among. */
|
|
262
|
+
readonly workers: readonly WorkerDefinition[];
|
|
263
|
+
/** Workers outside the pool that a member's `fallback` names. */
|
|
264
|
+
readonly fallbacks: readonly WorkerDefinition[];
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** The definitions of one pool, plus the fallback workers outside it. */
|
|
268
|
+
export function resolvePool(parsed: ParsedWorkers, pool: string): ResolvedPool {
|
|
269
|
+
const names = parsed.pools[pool];
|
|
270
|
+
if (names === undefined) {
|
|
271
|
+
throw new WorkerDefinitionError(`pools.${pool}`, "no such pool");
|
|
272
|
+
}
|
|
273
|
+
const byName = new Map(parsed.workers.map((worker) => [worker.name, worker]));
|
|
274
|
+
const members: WorkerDefinition[] = [];
|
|
275
|
+
for (const name of names) {
|
|
276
|
+
const worker = byName.get(name);
|
|
277
|
+
if (worker !== undefined) members.push(worker);
|
|
278
|
+
}
|
|
279
|
+
const fallbacks: WorkerDefinition[] = [];
|
|
280
|
+
for (const worker of members) {
|
|
281
|
+
if (worker.fallback === undefined) continue;
|
|
282
|
+
const target = byName.get(worker.fallback);
|
|
283
|
+
if (
|
|
284
|
+
target !== undefined &&
|
|
285
|
+
!names.includes(target.name) &&
|
|
286
|
+
!fallbacks.some((item) => item.name === target.name)
|
|
287
|
+
) {
|
|
288
|
+
fallbacks.push(target);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return { workers: members, fallbacks };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Reads the list `pool/agent` receives: each entry is a worker with its
|
|
296
|
+
* `name`. Same fields and refusals as `readWorker`.
|
|
297
|
+
*/
|
|
298
|
+
export function readResolved(value: unknown, at: string): readonly WorkerDefinition[] {
|
|
299
|
+
if (!Array.isArray(value)) throw new WorkerDefinitionError(at, "must be a list of workers");
|
|
300
|
+
const seen = new Set<string>();
|
|
301
|
+
return value.map((item: unknown, index: number) => {
|
|
302
|
+
const here = `${at}[${index}]`;
|
|
303
|
+
if (!isRecord(item) || typeof item.name !== "string" || item.name.length === 0) {
|
|
304
|
+
throw new WorkerDefinitionError(`${here}.name`, "must be a worker name");
|
|
305
|
+
}
|
|
306
|
+
if (seen.has(item.name)) {
|
|
307
|
+
throw new WorkerDefinitionError(`${here}.name`, `"${item.name}" is listed twice`);
|
|
308
|
+
}
|
|
309
|
+
seen.add(item.name);
|
|
310
|
+
const { name, ...rest } = item;
|
|
311
|
+
return readWorker(String(name), rest, here);
|
|
312
|
+
});
|
|
313
|
+
}
|
package/README.md
DELETED