@abelxiaoxing/cadence 1.0.13 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -13
- package/agents/contract-reviewer.md +2 -2
- package/agents/design-explorer.md +1 -1
- package/agents/diagnosis-worker.md +6 -3
- package/agents/implementation-worker.md +14 -9
- package/config/.env.example +5 -17
- package/config/routes.example.json +42 -0
- package/package.json +3 -3
- package/prompts/abel-design.md +150 -228
- package/prompts/abel-diagnose.md +37 -18
- package/prompts/abel-implement.md +111 -178
- package/prompts/abel-init.md +36 -33
- package/skills/abel-workflow/SKILL.md +156 -168
- package/src/apply-transaction.ts +1427 -0
- package/src/artifact-store.ts +204 -0
- package/src/child-session.ts +136 -17
- package/src/contracts.ts +105 -696
- package/src/control-contracts.ts +259 -0
- package/src/delivery-compiler.ts +1088 -0
- package/src/file-snapshot.ts +5 -0
- package/src/implement-graph.ts +11 -4
- package/src/index.ts +1465 -133
- package/src/isolation-backend.ts +269 -0
- package/src/packet-runtime.ts +533 -0
- package/src/parent-provider.ts +23 -4
- package/src/route-policy.ts +483 -0
- package/src/run-state.ts +393 -0
- package/src/run-store.ts +918 -0
- package/src/safe-path.ts +11 -0
- package/src/scoped-tools.ts +36 -0
- package/src/state-root.ts +215 -0
- package/src/subagent-activity.ts +526 -27
- package/src/submit-tool.ts +274 -0
- package/src/task-ledger.ts +1380 -0
- package/src/verification-capability.ts +529 -42
- package/src/worker-broker.ts +703 -0
- package/src/workflow-engine.ts +7391 -0
- package/src/workspace-store.ts +544 -0
- package/src/candidate-preflight.ts +0 -1618
- package/src/drain.ts +0 -20
- package/src/patch.ts +0 -505
- package/src/result-store.ts +0 -312
- package/src/runtime.ts +0 -2436
- package/src/scheduler.ts +0 -384
- package/src/subagent-endpoint.ts +0 -158
- package/src/worker.ts +0 -204
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
import {
|
|
2
|
+
inspectRoutePolicy,
|
|
3
|
+
type RouteDialect,
|
|
4
|
+
type RoutePolicy,
|
|
5
|
+
type WorkerRole,
|
|
6
|
+
type WorkerRoutePolicy,
|
|
7
|
+
} from "./route-policy.ts";
|
|
8
|
+
|
|
9
|
+
export const ROUTE_ATTEMPT_BOUNDS = Object.freeze({
|
|
10
|
+
connectMs: 5_000,
|
|
11
|
+
firstResponseMs: 30_000,
|
|
12
|
+
idleMs: 60_000,
|
|
13
|
+
totalMs: 10 * 60_000,
|
|
14
|
+
cooldownMs: 30_000,
|
|
15
|
+
attemptsPerRoute: 1,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export type RouteHealthState = "healthy" | "open" | "half-open";
|
|
19
|
+
|
|
20
|
+
export interface RouteRequirements {
|
|
21
|
+
dialects?: RouteDialect[];
|
|
22
|
+
minContextWindow?: number;
|
|
23
|
+
minOutputTokens?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface RouteHealth {
|
|
27
|
+
state: RouteHealthState;
|
|
28
|
+
retryAt?: number;
|
|
29
|
+
probeInFlight?: boolean;
|
|
30
|
+
probeExpiresAt?: number;
|
|
31
|
+
lastCode?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface RouteHealthStore {
|
|
35
|
+
get(fingerprint: string): RouteHealth | undefined;
|
|
36
|
+
set(fingerprint: string, health: RouteHealth): void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
class MemoryRouteHealthStore implements RouteHealthStore {
|
|
40
|
+
readonly #values = new Map<string, RouteHealth>();
|
|
41
|
+
|
|
42
|
+
get(fingerprint: string): RouteHealth | undefined {
|
|
43
|
+
const value = this.#values.get(fingerprint);
|
|
44
|
+
return value ? structuredClone(value) : undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
set(fingerprint: string, health: RouteHealth): void {
|
|
48
|
+
this.#values.set(fingerprint, structuredClone(health));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface WorkerBrokerOptions {
|
|
53
|
+
now?: () => number;
|
|
54
|
+
healthStore?: RouteHealthStore;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface RunWorkerAttemptInput<T> {
|
|
58
|
+
runId: string;
|
|
59
|
+
operationId: string;
|
|
60
|
+
role: WorkerRole;
|
|
61
|
+
requirements?: RouteRequirements;
|
|
62
|
+
signal?: AbortSignal;
|
|
63
|
+
onActivity?: (event: BrokerActivityUpdate) => void;
|
|
64
|
+
execute(context: RouteAttemptContext): Promise<T>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface RouteAttemptContext {
|
|
68
|
+
route: WorkerRoutePolicy;
|
|
69
|
+
signal: AbortSignal;
|
|
70
|
+
onHeaders(): void;
|
|
71
|
+
onProgress(): void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface BrokerAttemptEvidence {
|
|
75
|
+
routeId: string;
|
|
76
|
+
code: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface BrokerActivityUpdate {
|
|
80
|
+
state: "connecting" | "waiting-first-response" | "running" | "retrying";
|
|
81
|
+
attempt: number;
|
|
82
|
+
maxAttempts: number;
|
|
83
|
+
code?: string;
|
|
84
|
+
wait?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function emitBrokerActivity(
|
|
88
|
+
observer: ((event: BrokerActivityUpdate) => void) | undefined,
|
|
89
|
+
event: BrokerActivityUpdate,
|
|
90
|
+
): void {
|
|
91
|
+
try {
|
|
92
|
+
observer?.(structuredClone(event));
|
|
93
|
+
} catch {
|
|
94
|
+
// Presentation cannot influence route selection or attempt control.
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
class RouteAttemptStop extends Error {
|
|
99
|
+
readonly code:
|
|
100
|
+
| "connect-timeout"
|
|
101
|
+
| "first-response-timeout"
|
|
102
|
+
| "idle-timeout"
|
|
103
|
+
| "phase-timeout"
|
|
104
|
+
| "cancelled";
|
|
105
|
+
|
|
106
|
+
constructor(code: RouteAttemptStop["code"]) {
|
|
107
|
+
super(code);
|
|
108
|
+
this.name = "RouteAttemptStop";
|
|
109
|
+
this.code = code;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isRole(value: unknown): value is WorkerRole {
|
|
114
|
+
return [
|
|
115
|
+
"design-explorer",
|
|
116
|
+
"contract-reviewer",
|
|
117
|
+
"implementation-worker",
|
|
118
|
+
"diagnosis-worker",
|
|
119
|
+
].includes(String(value));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function validRequirements(value: unknown): value is RouteRequirements {
|
|
123
|
+
if (value === undefined) return true;
|
|
124
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
125
|
+
const candidate = value as Record<string, unknown>;
|
|
126
|
+
if (
|
|
127
|
+
Object.keys(candidate).some(
|
|
128
|
+
(key) =>
|
|
129
|
+
!["dialects", "minContextWindow", "minOutputTokens"].includes(key),
|
|
130
|
+
)
|
|
131
|
+
) {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
return (
|
|
135
|
+
(candidate.dialects === undefined ||
|
|
136
|
+
(Array.isArray(candidate.dialects) &&
|
|
137
|
+
candidate.dialects.length > 0 &&
|
|
138
|
+
candidate.dialects.every((dialect) =>
|
|
139
|
+
[
|
|
140
|
+
"openai-completions",
|
|
141
|
+
"openai-responses",
|
|
142
|
+
"anthropic-messages",
|
|
143
|
+
].includes(String(dialect)),
|
|
144
|
+
))) &&
|
|
145
|
+
(candidate.minContextWindow === undefined ||
|
|
146
|
+
(Number.isSafeInteger(candidate.minContextWindow) &&
|
|
147
|
+
(candidate.minContextWindow as number) > 0)) &&
|
|
148
|
+
(candidate.minOutputTokens === undefined ||
|
|
149
|
+
(Number.isSafeInteger(candidate.minOutputTokens) &&
|
|
150
|
+
(candidate.minOutputTokens as number) > 0))
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function capable(
|
|
155
|
+
route: WorkerRoutePolicy,
|
|
156
|
+
role: WorkerRole,
|
|
157
|
+
requirements: RouteRequirements,
|
|
158
|
+
): boolean {
|
|
159
|
+
const dialects = requirements.dialects ?? [];
|
|
160
|
+
return (
|
|
161
|
+
route.capabilities.roles.includes(role) &&
|
|
162
|
+
dialects.every((dialect) =>
|
|
163
|
+
route.capabilities.dialects.includes(dialect),
|
|
164
|
+
) &&
|
|
165
|
+
route.capabilities.contextWindow >= (requirements.minContextWindow ?? 0) &&
|
|
166
|
+
route.capabilities.maxTokens >= (requirements.minOutputTokens ?? 0)
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function safeFailureCode(error: unknown): string {
|
|
171
|
+
if (error instanceof RouteAttemptStop) return error.code;
|
|
172
|
+
return "transport-failure";
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export class WorkerBroker {
|
|
176
|
+
readonly #policy: RoutePolicy;
|
|
177
|
+
readonly #now: () => number;
|
|
178
|
+
readonly #healthStore: RouteHealthStore;
|
|
179
|
+
readonly #health = new Map<string, RouteHealth>();
|
|
180
|
+
|
|
181
|
+
constructor(policy: RoutePolicy, options: WorkerBrokerOptions = {}) {
|
|
182
|
+
this.#policy = structuredClone(policy);
|
|
183
|
+
this.#now = options.now ?? Date.now;
|
|
184
|
+
this.#healthStore = options.healthStore ?? new MemoryRouteHealthStore();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
#routeHealth(routeId: string): RouteHealth {
|
|
188
|
+
const route = this.#policy.routes[routeId];
|
|
189
|
+
return (
|
|
190
|
+
this.#health.get(routeId) ??
|
|
191
|
+
(route ? this.#healthStore.get(route.fingerprint) : undefined) ?? {
|
|
192
|
+
state: "healthy",
|
|
193
|
+
}
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
#setRouteHealth(routeId: string, health: RouteHealth): void {
|
|
198
|
+
const route = this.#policy.routes[routeId];
|
|
199
|
+
if (!route) throw new Error("route-not-declared");
|
|
200
|
+
this.#health.set(routeId, structuredClone(health));
|
|
201
|
+
this.#healthStore.set(route.fingerprint, health);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
markFailure(routeId: string, code: string): void {
|
|
205
|
+
if (!Object.hasOwn(this.#policy.routes, routeId)) {
|
|
206
|
+
throw new Error("route-not-declared");
|
|
207
|
+
}
|
|
208
|
+
this.#setRouteHealth(routeId, {
|
|
209
|
+
state: "open",
|
|
210
|
+
retryAt: this.#now() + ROUTE_ATTEMPT_BOUNDS.cooldownMs,
|
|
211
|
+
lastCode: code,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
markSuccess(routeId: string): void {
|
|
216
|
+
if (!Object.hasOwn(this.#policy.routes, routeId)) {
|
|
217
|
+
throw new Error("route-not-declared");
|
|
218
|
+
}
|
|
219
|
+
this.#setRouteHealth(routeId, { state: "healthy" });
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
select(input: {
|
|
223
|
+
role: WorkerRole;
|
|
224
|
+
dialects?: RouteDialect[];
|
|
225
|
+
minContextWindow?: number;
|
|
226
|
+
minOutputTokens?: number;
|
|
227
|
+
exclude?: readonly string[];
|
|
228
|
+
routeId?: string;
|
|
229
|
+
}):
|
|
230
|
+
| { ok: true; route: WorkerRoutePolicy; health: RouteHealthState }
|
|
231
|
+
| { ok: false; code: "endpoint-unavailable" | "route-not-declared" } {
|
|
232
|
+
const requirements: RouteRequirements = {
|
|
233
|
+
...(input.dialects ? { dialects: input.dialects } : {}),
|
|
234
|
+
...(input.minContextWindow === undefined
|
|
235
|
+
? {}
|
|
236
|
+
: { minContextWindow: input.minContextWindow }),
|
|
237
|
+
...(input.minOutputTokens === undefined
|
|
238
|
+
? {}
|
|
239
|
+
: { minOutputTokens: input.minOutputTokens }),
|
|
240
|
+
};
|
|
241
|
+
if (!isRole(input.role) || !validRequirements(requirements)) {
|
|
242
|
+
return { ok: false, code: "endpoint-unavailable" };
|
|
243
|
+
}
|
|
244
|
+
const declared = this.#policy.roles[input.role];
|
|
245
|
+
const candidates = input.routeId
|
|
246
|
+
? declared.includes(input.routeId)
|
|
247
|
+
? [input.routeId]
|
|
248
|
+
: []
|
|
249
|
+
: declared;
|
|
250
|
+
if (input.routeId && candidates.length === 0) {
|
|
251
|
+
return { ok: false, code: "route-not-declared" };
|
|
252
|
+
}
|
|
253
|
+
const excluded = new Set(input.exclude ?? []);
|
|
254
|
+
for (const routeId of candidates) {
|
|
255
|
+
if (excluded.has(routeId)) continue;
|
|
256
|
+
const route = this.#policy.routes[routeId];
|
|
257
|
+
if (!route || !capable(route, input.role, requirements)) continue;
|
|
258
|
+
const health = this.#routeHealth(routeId);
|
|
259
|
+
if (
|
|
260
|
+
health.state === "open" &&
|
|
261
|
+
health.retryAt !== undefined &&
|
|
262
|
+
health.retryAt > this.#now()
|
|
263
|
+
) {
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (
|
|
267
|
+
(health.state === "open" || health.state === "half-open") &&
|
|
268
|
+
health.probeInFlight &&
|
|
269
|
+
health.probeExpiresAt !== undefined &&
|
|
270
|
+
health.probeExpiresAt > this.#now()
|
|
271
|
+
) {
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (health.state === "open") {
|
|
275
|
+
return { ok: true, route: structuredClone(route), health: "half-open" };
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
ok: true,
|
|
279
|
+
route: structuredClone(route),
|
|
280
|
+
health: health.state,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
return { ok: false, code: "endpoint-unavailable" };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async #attempt<T>(
|
|
287
|
+
route: WorkerRoutePolicy,
|
|
288
|
+
execute: (context: RouteAttemptContext) => Promise<T>,
|
|
289
|
+
parentSignal?: AbortSignal,
|
|
290
|
+
onActivity?: (state: "waiting-first-response" | "running") => void,
|
|
291
|
+
): Promise<T> {
|
|
292
|
+
const controller = new AbortController();
|
|
293
|
+
const timers = new Set<ReturnType<typeof setTimeout>>();
|
|
294
|
+
let headersSeen = false;
|
|
295
|
+
let connectTimer: ReturnType<typeof setTimeout> | undefined;
|
|
296
|
+
let firstResponseTimer: ReturnType<typeof setTimeout> | undefined;
|
|
297
|
+
let idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
298
|
+
|
|
299
|
+
const stop = (code: RouteAttemptStop["code"]) => {
|
|
300
|
+
if (!controller.signal.aborted)
|
|
301
|
+
controller.abort(new RouteAttemptStop(code));
|
|
302
|
+
};
|
|
303
|
+
const schedule = (code: RouteAttemptStop["code"], milliseconds: number) => {
|
|
304
|
+
const timer = setTimeout(() => stop(code), milliseconds);
|
|
305
|
+
timers.add(timer);
|
|
306
|
+
return timer;
|
|
307
|
+
};
|
|
308
|
+
const clear = (timer: ReturnType<typeof setTimeout> | undefined) => {
|
|
309
|
+
if (timer !== undefined) {
|
|
310
|
+
clearTimeout(timer);
|
|
311
|
+
timers.delete(timer);
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
const onParentAbort = () => stop("cancelled");
|
|
315
|
+
if (parentSignal?.aborted) stop("cancelled");
|
|
316
|
+
else parentSignal?.addEventListener("abort", onParentAbort, { once: true });
|
|
317
|
+
|
|
318
|
+
connectTimer = schedule("connect-timeout", ROUTE_ATTEMPT_BOUNDS.connectMs);
|
|
319
|
+
schedule("phase-timeout", ROUTE_ATTEMPT_BOUNDS.totalMs);
|
|
320
|
+
let removeAbortRace: () => void = () => {};
|
|
321
|
+
try {
|
|
322
|
+
const execution = Promise.resolve().then(() =>
|
|
323
|
+
execute({
|
|
324
|
+
route: structuredClone(route),
|
|
325
|
+
signal: controller.signal,
|
|
326
|
+
onHeaders: () => {
|
|
327
|
+
if (controller.signal.aborted || headersSeen) return;
|
|
328
|
+
headersSeen = true;
|
|
329
|
+
clear(connectTimer);
|
|
330
|
+
onActivity?.("waiting-first-response");
|
|
331
|
+
firstResponseTimer = schedule(
|
|
332
|
+
"first-response-timeout",
|
|
333
|
+
ROUTE_ATTEMPT_BOUNDS.firstResponseMs,
|
|
334
|
+
);
|
|
335
|
+
},
|
|
336
|
+
onProgress: () => {
|
|
337
|
+
if (controller.signal.aborted) return;
|
|
338
|
+
clear(connectTimer);
|
|
339
|
+
clear(firstResponseTimer);
|
|
340
|
+
clear(idleTimer);
|
|
341
|
+
idleTimer = schedule("idle-timeout", ROUTE_ATTEMPT_BOUNDS.idleMs);
|
|
342
|
+
onActivity?.("running");
|
|
343
|
+
},
|
|
344
|
+
}),
|
|
345
|
+
);
|
|
346
|
+
// A timed-out Provider may ignore its AbortSignal and settle later. The
|
|
347
|
+
// broker owns the bounded result, so absorb that late settlement.
|
|
348
|
+
void execution.catch(() => undefined);
|
|
349
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
350
|
+
const onAbort = () =>
|
|
351
|
+
reject(
|
|
352
|
+
controller.signal.reason instanceof Error
|
|
353
|
+
? controller.signal.reason
|
|
354
|
+
: new RouteAttemptStop("cancelled"),
|
|
355
|
+
);
|
|
356
|
+
removeAbortRace = () =>
|
|
357
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
358
|
+
if (controller.signal.aborted) onAbort();
|
|
359
|
+
else
|
|
360
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
361
|
+
});
|
|
362
|
+
return await Promise.race([execution, aborted]);
|
|
363
|
+
} finally {
|
|
364
|
+
removeAbortRace();
|
|
365
|
+
for (const timer of timers) clearTimeout(timer);
|
|
366
|
+
parentSignal?.removeEventListener("abort", onParentAbort);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async run<T>(input: {
|
|
371
|
+
operationId: string;
|
|
372
|
+
role: WorkerRole;
|
|
373
|
+
requirements?: RouteRequirements;
|
|
374
|
+
signal?: AbortSignal;
|
|
375
|
+
onActivity?: (event: BrokerActivityUpdate) => void;
|
|
376
|
+
execute: (context: RouteAttemptContext) => Promise<T>;
|
|
377
|
+
}): Promise<
|
|
378
|
+
| { ok: true; routeId: string; value: T; attempts: BrokerAttemptEvidence[] }
|
|
379
|
+
| {
|
|
380
|
+
ok: false;
|
|
381
|
+
state: "paused" | "cancelled";
|
|
382
|
+
code: string;
|
|
383
|
+
attempts: BrokerAttemptEvidence[];
|
|
384
|
+
}
|
|
385
|
+
> {
|
|
386
|
+
if (
|
|
387
|
+
typeof input.operationId !== "string" ||
|
|
388
|
+
input.operationId.length === 0 ||
|
|
389
|
+
!isRole(input.role) ||
|
|
390
|
+
!validRequirements(input.requirements)
|
|
391
|
+
) {
|
|
392
|
+
return {
|
|
393
|
+
ok: false,
|
|
394
|
+
state: "paused",
|
|
395
|
+
code: "broker-input-invalid",
|
|
396
|
+
attempts: [],
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
const attempted = new Set<string>();
|
|
400
|
+
const evidence: BrokerAttemptEvidence[] = [];
|
|
401
|
+
const maxAttempts = this.#policy.roles[input.role].filter((routeId) => {
|
|
402
|
+
const route = this.#policy.routes[routeId];
|
|
403
|
+
return route
|
|
404
|
+
? capable(route, input.role, input.requirements ?? {})
|
|
405
|
+
: false;
|
|
406
|
+
}).length;
|
|
407
|
+
for (;;) {
|
|
408
|
+
const selection = this.select({
|
|
409
|
+
role: input.role,
|
|
410
|
+
...(input.requirements ?? {}),
|
|
411
|
+
exclude: [...attempted],
|
|
412
|
+
});
|
|
413
|
+
if (!selection.ok) {
|
|
414
|
+
return {
|
|
415
|
+
ok: false,
|
|
416
|
+
state: "paused",
|
|
417
|
+
code: evidence.at(-1)?.code ?? selection.code,
|
|
418
|
+
attempts: evidence,
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
const routeId = selection.route.id;
|
|
422
|
+
attempted.add(routeId);
|
|
423
|
+
if (selection.health === "half-open") {
|
|
424
|
+
this.#setRouteHealth(routeId, {
|
|
425
|
+
...this.#routeHealth(routeId),
|
|
426
|
+
state: "half-open",
|
|
427
|
+
probeInFlight: true,
|
|
428
|
+
probeExpiresAt: this.#now() + ROUTE_ATTEMPT_BOUNDS.totalMs,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
const attempt = evidence.length + 1;
|
|
432
|
+
emitBrokerActivity(input.onActivity, {
|
|
433
|
+
state: "connecting",
|
|
434
|
+
attempt,
|
|
435
|
+
maxAttempts,
|
|
436
|
+
wait: "connection",
|
|
437
|
+
});
|
|
438
|
+
try {
|
|
439
|
+
const value = await this.#attempt(
|
|
440
|
+
selection.route,
|
|
441
|
+
input.execute,
|
|
442
|
+
input.signal,
|
|
443
|
+
(state) =>
|
|
444
|
+
emitBrokerActivity(input.onActivity, {
|
|
445
|
+
state,
|
|
446
|
+
attempt,
|
|
447
|
+
maxAttempts,
|
|
448
|
+
wait:
|
|
449
|
+
state === "waiting-first-response"
|
|
450
|
+
? "first-response"
|
|
451
|
+
: "worker-progress",
|
|
452
|
+
}),
|
|
453
|
+
);
|
|
454
|
+
this.markSuccess(routeId);
|
|
455
|
+
return { ok: true, routeId, value, attempts: evidence };
|
|
456
|
+
} catch (error) {
|
|
457
|
+
const code = safeFailureCode(error);
|
|
458
|
+
evidence.push({ routeId, code });
|
|
459
|
+
if (code === "cancelled") {
|
|
460
|
+
const health = this.#routeHealth(routeId);
|
|
461
|
+
if (health.state === "half-open" && health.probeInFlight) {
|
|
462
|
+
this.#setRouteHealth(routeId, {
|
|
463
|
+
state: "open",
|
|
464
|
+
retryAt: this.#now(),
|
|
465
|
+
...(health.lastCode ? { lastCode: health.lastCode } : {}),
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
return { ok: false, state: "cancelled", code, attempts: evidence };
|
|
469
|
+
}
|
|
470
|
+
this.markFailure(routeId, code);
|
|
471
|
+
if (attempted.size < maxAttempts) {
|
|
472
|
+
emitBrokerActivity(input.onActivity, {
|
|
473
|
+
state: "retrying",
|
|
474
|
+
attempt,
|
|
475
|
+
maxAttempts,
|
|
476
|
+
code,
|
|
477
|
+
wait: "bounded-policy",
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
rebind(input: Record<string, unknown>):
|
|
485
|
+
| { ok: true; runId: string; route: WorkerRoutePolicy }
|
|
486
|
+
| {
|
|
487
|
+
ok: false;
|
|
488
|
+
code:
|
|
489
|
+
| "approval-boundary"
|
|
490
|
+
| "route-not-declared"
|
|
491
|
+
| "route-capability-insufficient";
|
|
492
|
+
} {
|
|
493
|
+
const allowed = new Set(["runId", "role", "routeId", "requirements"]);
|
|
494
|
+
if (Object.keys(input).some((key) => !allowed.has(key))) {
|
|
495
|
+
return { ok: false, code: "approval-boundary" };
|
|
496
|
+
}
|
|
497
|
+
if (
|
|
498
|
+
typeof input.runId !== "string" ||
|
|
499
|
+
input.runId.length === 0 ||
|
|
500
|
+
!isRole(input.role) ||
|
|
501
|
+
typeof input.routeId !== "string" ||
|
|
502
|
+
!validRequirements(input.requirements)
|
|
503
|
+
) {
|
|
504
|
+
return { ok: false, code: "route-capability-insufficient" };
|
|
505
|
+
}
|
|
506
|
+
const selection = this.select({
|
|
507
|
+
role: input.role,
|
|
508
|
+
...(input.requirements ?? {}),
|
|
509
|
+
routeId: input.routeId,
|
|
510
|
+
});
|
|
511
|
+
if (!selection.ok) {
|
|
512
|
+
return {
|
|
513
|
+
ok: false,
|
|
514
|
+
code:
|
|
515
|
+
selection.code === "route-not-declared"
|
|
516
|
+
? "route-not-declared"
|
|
517
|
+
: "route-capability-insufficient",
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
return {
|
|
521
|
+
ok: true,
|
|
522
|
+
runId: input.runId,
|
|
523
|
+
route: structuredClone(selection.route),
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
status(): Record<string, unknown> {
|
|
528
|
+
const health = Object.fromEntries(
|
|
529
|
+
Object.keys(this.#policy.routes).map((routeId) => {
|
|
530
|
+
const value = this.#routeHealth(routeId);
|
|
531
|
+
return [
|
|
532
|
+
routeId,
|
|
533
|
+
{
|
|
534
|
+
state: value.state,
|
|
535
|
+
...(value.retryAt === undefined ? {} : { retryAt: value.retryAt }),
|
|
536
|
+
},
|
|
537
|
+
];
|
|
538
|
+
}),
|
|
539
|
+
);
|
|
540
|
+
return inspectRoutePolicy(
|
|
541
|
+
{
|
|
542
|
+
ok: true,
|
|
543
|
+
source: { kind: "project", path: "<injected>" },
|
|
544
|
+
policy: this.#policy,
|
|
545
|
+
},
|
|
546
|
+
health,
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Adds stable run/role route bindings to the stateless route-attempt broker.
|
|
553
|
+
* Attempt credentials and provider objects remain disposable and are never
|
|
554
|
+
* retained by this facade.
|
|
555
|
+
*/
|
|
556
|
+
export class RunWorkerBroker {
|
|
557
|
+
#policy: RoutePolicy;
|
|
558
|
+
readonly #options: WorkerBrokerOptions;
|
|
559
|
+
#defaultBroker: WorkerBroker;
|
|
560
|
+
readonly #bindings = new Map<
|
|
561
|
+
string,
|
|
562
|
+
{ routeId: string; fingerprint: string }
|
|
563
|
+
>();
|
|
564
|
+
readonly #boundBrokers = new Map<string, WorkerBroker>();
|
|
565
|
+
|
|
566
|
+
constructor(policy: RoutePolicy, options: WorkerBrokerOptions = {}) {
|
|
567
|
+
this.#policy = structuredClone(policy);
|
|
568
|
+
this.#options = options;
|
|
569
|
+
this.#defaultBroker = new WorkerBroker(this.#policy, options);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
#bindingKey(runId: string, role: WorkerRole): string {
|
|
573
|
+
return `${runId}\0${role}`;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
#brokerFor(runId: string, role: WorkerRole): WorkerBroker {
|
|
577
|
+
const binding = this.#bindings.get(this.#bindingKey(runId, role));
|
|
578
|
+
if (!binding) return this.#defaultBroker;
|
|
579
|
+
const routeId = binding.routeId;
|
|
580
|
+
const key = `${role}\0${routeId}`;
|
|
581
|
+
const existing = this.#boundBrokers.get(key);
|
|
582
|
+
if (existing) return existing;
|
|
583
|
+
const ordered = [
|
|
584
|
+
routeId,
|
|
585
|
+
...this.#policy.roles[role].filter((candidate) => candidate !== routeId),
|
|
586
|
+
];
|
|
587
|
+
const policy: RoutePolicy = {
|
|
588
|
+
...structuredClone(this.#policy),
|
|
589
|
+
roles: Object.freeze({
|
|
590
|
+
...structuredClone(this.#policy.roles),
|
|
591
|
+
[role]: Object.freeze(ordered),
|
|
592
|
+
}),
|
|
593
|
+
};
|
|
594
|
+
const broker = new WorkerBroker(policy, this.#options);
|
|
595
|
+
this.#boundBrokers.set(key, broker);
|
|
596
|
+
return broker;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async run<T>(input: RunWorkerAttemptInput<T>) {
|
|
600
|
+
if (
|
|
601
|
+
typeof input.runId !== "string" ||
|
|
602
|
+
input.runId.length === 0 ||
|
|
603
|
+
typeof input.operationId !== "string" ||
|
|
604
|
+
input.operationId.length === 0
|
|
605
|
+
) {
|
|
606
|
+
return {
|
|
607
|
+
ok: false as const,
|
|
608
|
+
state: "paused" as const,
|
|
609
|
+
code: "broker-input-invalid",
|
|
610
|
+
attempts: [],
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
const result = await this.#brokerFor(input.runId, input.role).run({
|
|
614
|
+
operationId: input.operationId,
|
|
615
|
+
role: input.role,
|
|
616
|
+
...(input.requirements ? { requirements: input.requirements } : {}),
|
|
617
|
+
...(input.signal ? { signal: input.signal } : {}),
|
|
618
|
+
...(input.onActivity ? { onActivity: input.onActivity } : {}),
|
|
619
|
+
execute: input.execute,
|
|
620
|
+
});
|
|
621
|
+
if (result.ok) {
|
|
622
|
+
const route = this.#policy.routes[result.routeId];
|
|
623
|
+
if (!route) throw new Error("broker-route-result-invalid");
|
|
624
|
+
this.#bindings.set(this.#bindingKey(input.runId, input.role), {
|
|
625
|
+
routeId: route.id,
|
|
626
|
+
fingerprint: route.fingerprint,
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
return result;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
rebind(input: {
|
|
633
|
+
runId: string;
|
|
634
|
+
role: WorkerRole;
|
|
635
|
+
routeId: string;
|
|
636
|
+
requirements?: RouteRequirements;
|
|
637
|
+
}) {
|
|
638
|
+
const result = this.#defaultBroker.rebind(input);
|
|
639
|
+
if (result.ok) {
|
|
640
|
+
this.#bindings.set(this.#bindingKey(input.runId, input.role), {
|
|
641
|
+
routeId: result.route.id,
|
|
642
|
+
fingerprint: result.route.fingerprint,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
return result;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
resumeBinding(input: {
|
|
649
|
+
runId: string;
|
|
650
|
+
role: WorkerRole;
|
|
651
|
+
routeId: string;
|
|
652
|
+
expectedFingerprint?: string;
|
|
653
|
+
requirements?: RouteRequirements;
|
|
654
|
+
}) {
|
|
655
|
+
const binding = this.#bindings.get(
|
|
656
|
+
this.#bindingKey(input.runId, input.role),
|
|
657
|
+
);
|
|
658
|
+
const route = this.#policy.routes[input.routeId];
|
|
659
|
+
if (!binding) {
|
|
660
|
+
if (
|
|
661
|
+
!route ||
|
|
662
|
+
input.expectedFingerprint === undefined ||
|
|
663
|
+
route.fingerprint !== input.expectedFingerprint
|
|
664
|
+
) {
|
|
665
|
+
return { ok: false as const, code: "route-rebind-required" as const };
|
|
666
|
+
}
|
|
667
|
+
return this.rebind({
|
|
668
|
+
runId: input.runId,
|
|
669
|
+
role: input.role,
|
|
670
|
+
routeId: input.routeId,
|
|
671
|
+
...(input.requirements ? { requirements: input.requirements } : {}),
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
if (
|
|
675
|
+
binding.routeId !== input.routeId ||
|
|
676
|
+
!route ||
|
|
677
|
+
route.fingerprint !== binding.fingerprint ||
|
|
678
|
+
(input.expectedFingerprint !== undefined &&
|
|
679
|
+
binding.fingerprint !== input.expectedFingerprint)
|
|
680
|
+
) {
|
|
681
|
+
return { ok: false as const, code: "route-rebind-required" as const };
|
|
682
|
+
}
|
|
683
|
+
return {
|
|
684
|
+
ok: true as const,
|
|
685
|
+
runId: input.runId,
|
|
686
|
+
route: structuredClone(route),
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
updatePolicy(policy: RoutePolicy): void {
|
|
691
|
+
this.#policy = structuredClone(policy);
|
|
692
|
+
this.#defaultBroker = new WorkerBroker(this.#policy, this.#options);
|
|
693
|
+
this.#boundBrokers.clear();
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
binding(runId: string, role: WorkerRole): string | undefined {
|
|
697
|
+
return this.#bindings.get(this.#bindingKey(runId, role))?.routeId;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
status(): Record<string, unknown> {
|
|
701
|
+
return this.#defaultBroker.status();
|
|
702
|
+
}
|
|
703
|
+
}
|