opencode-model-router 2.8.0 → 2.9.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/CHANGELOG.md +364 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/output.ts +23 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2656 -114
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
// Adaptive per-provider concurrency (Phase 3.1.3, memo phase-3.1.md §3 M14-M20, §7 M35 capacity metric, §8).
|
|
2
|
+
// Imports `./types` only (memo §1 dependency table).
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
classifyProviderError,
|
|
6
|
+
ExecutorError,
|
|
7
|
+
HEAVY_CAP_PER_PROVIDER,
|
|
8
|
+
type CapacityController,
|
|
9
|
+
type CapacityView,
|
|
10
|
+
type Clock,
|
|
11
|
+
type ExecutorEvent,
|
|
12
|
+
type InboxItem,
|
|
13
|
+
type IsoTime,
|
|
14
|
+
type JsonValue,
|
|
15
|
+
type MetricPayload,
|
|
16
|
+
type ProviderSignal,
|
|
17
|
+
type RouteResolver,
|
|
18
|
+
type TaskId,
|
|
19
|
+
type TaskNode,
|
|
20
|
+
type TaskRoute,
|
|
21
|
+
} from "./types";
|
|
22
|
+
|
|
23
|
+
/** The `capacity` variant of `MetricPayload` (memo §7 M35). */
|
|
24
|
+
export type CapacityMetric = Extract<MetricPayload, { name: "capacity" }>;
|
|
25
|
+
|
|
26
|
+
/** Persistable per-provider state; `holdUntilMs` 0 means no hold. */
|
|
27
|
+
export interface CapacityProviderState {
|
|
28
|
+
limit: number;
|
|
29
|
+
holdUntilMs: number;
|
|
30
|
+
lastSignalAtMs: number | null;
|
|
31
|
+
pausedUntilMs: number | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CapacityOptions {
|
|
35
|
+
/** Initial limit and cap (1-8, D13). */
|
|
36
|
+
maxParallel: number;
|
|
37
|
+
/** `capacityCooldownMs`: hold after a decrease, quiet time before growth, retry-stop threshold. */
|
|
38
|
+
cooldownMs: number;
|
|
39
|
+
/** `capacityPauseMs`: pause length when a quota error carries no future zoned instant. */
|
|
40
|
+
pauseMs: number;
|
|
41
|
+
/** Concurrent heavy children per provider before `min(·, limit)`; default `HEAVY_CAP_PER_PROVIDER`. */
|
|
42
|
+
heavyCap?: number;
|
|
43
|
+
clock: Clock;
|
|
44
|
+
onMetric(m: CapacityMetric): void;
|
|
45
|
+
restore?: Readonly<Record<string, CapacityProviderState>>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
type OnSignalResult = ReturnType<CapacityController["onSignal"]>;
|
|
49
|
+
type InboxInput = Omit<InboxItem, "id" | "createdAt" | "answer">;
|
|
50
|
+
|
|
51
|
+
interface ProviderRuntime extends CapacityProviderState {
|
|
52
|
+
used: number;
|
|
53
|
+
heavyUsed: number;
|
|
54
|
+
/** QA-3.1-13: token sequence number at the last increase; only tokens acquired after it may raise the limit again. */
|
|
55
|
+
lastIncreaseSeq: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface TokenRecord {
|
|
59
|
+
provider: string;
|
|
60
|
+
heavy: boolean;
|
|
61
|
+
taskId: TaskId;
|
|
62
|
+
attempt: number;
|
|
63
|
+
acquiredAtMs: number;
|
|
64
|
+
seq: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** QA-3.1-15: the controller sees step keys but no end-of-step signal, so its per-step maps are bounded (oldest dropped). */
|
|
68
|
+
export const MAX_TRACKED_STEPS = 2048;
|
|
69
|
+
|
|
70
|
+
/** M17: the first zoned ISO instant in `message` that is later than `nowMs`; zoneless and past instants are ignored
|
|
71
|
+
* (a past instant would pause zero time; ADR 0007 words this as "the first ISO instant"). */
|
|
72
|
+
const ISO_INSTANT = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})/g;
|
|
73
|
+
|
|
74
|
+
export function pauseUntilFromMessage(message: string, nowMs: number): number | null {
|
|
75
|
+
for (const m of message.matchAll(ISO_INSTANT)) {
|
|
76
|
+
const t = Date.parse(m[0]);
|
|
77
|
+
if (Number.isFinite(t) && t > nowMs) return t;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Free-slot queries of controllers built here; `CapacityController` itself exposes no counters. */
|
|
83
|
+
const FREE = new WeakMap<CapacityController, (provider: string, heavy: boolean) => number>();
|
|
84
|
+
|
|
85
|
+
function clampLimit(limit: number, maxParallel: number): number {
|
|
86
|
+
if (!Number.isFinite(limit)) return maxParallel;
|
|
87
|
+
return Math.min(maxParallel, Math.max(1, Math.floor(limit)));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function createCapacityController(o: CapacityOptions): CapacityController {
|
|
91
|
+
const maxParallel = Math.max(1, Math.floor(o.maxParallel));
|
|
92
|
+
const heavyCap = Math.max(0, Math.floor(o.heavyCap ?? HEAVY_CAP_PER_PROVIDER));
|
|
93
|
+
const { cooldownMs, pauseMs, clock } = o;
|
|
94
|
+
|
|
95
|
+
const providers = new Map<string, ProviderRuntime>();
|
|
96
|
+
const tokens = new Map<string, TokenRecord>();
|
|
97
|
+
/** M15: first rate-limit/overload signal per stepKey (dedupe and M18 age). */
|
|
98
|
+
const firstSignalAt = new Map<string, number>();
|
|
99
|
+
/** M18: `retry-stop` is emitted once per stepKey. */
|
|
100
|
+
const retryStopped = new Set<string>();
|
|
101
|
+
let tokenSeq = 0;
|
|
102
|
+
|
|
103
|
+
/** Insertion order is recency order: re-adding moves a key to the end, overflow drops the first (oldest) key. */
|
|
104
|
+
const touchBounded = (map: Map<string, number> | Set<string>, key: string, value: number): void => {
|
|
105
|
+
if (map instanceof Map) {
|
|
106
|
+
map.delete(key);
|
|
107
|
+
map.set(key, value);
|
|
108
|
+
} else {
|
|
109
|
+
map.delete(key);
|
|
110
|
+
map.add(key);
|
|
111
|
+
}
|
|
112
|
+
while (map.size > MAX_TRACKED_STEPS) {
|
|
113
|
+
const oldest = map.keys().next();
|
|
114
|
+
if (oldest.done === true) break;
|
|
115
|
+
map.delete(oldest.value);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
for (const [p, s] of Object.entries(o.restore ?? {})) {
|
|
120
|
+
providers.set(p, {
|
|
121
|
+
limit: clampLimit(s.limit, maxParallel),
|
|
122
|
+
holdUntilMs: s.holdUntilMs,
|
|
123
|
+
lastSignalAtMs: s.lastSignalAtMs,
|
|
124
|
+
pausedUntilMs: s.pausedUntilMs,
|
|
125
|
+
used: 0,
|
|
126
|
+
heavyUsed: 0,
|
|
127
|
+
lastIncreaseSeq: 0,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Called only after the state change it reports, so a throwing sink leaves the state consistent. */
|
|
132
|
+
const emit = (m: Omit<CapacityMetric, "name">): void => {
|
|
133
|
+
o.onMetric({ name: "capacity", ...m });
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const state = (provider: string): ProviderRuntime => {
|
|
137
|
+
let s = providers.get(provider);
|
|
138
|
+
if (s === undefined) {
|
|
139
|
+
s = { limit: maxParallel, holdUntilMs: 0, lastSignalAtMs: null, pausedUntilMs: null, used: 0, heavyUsed: 0, lastIncreaseSeq: 0 };
|
|
140
|
+
providers.set(provider, s);
|
|
141
|
+
}
|
|
142
|
+
return s;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/** M17 lazy resume: any call at or after `pausedUntil` lifts the pause (metric `resume`, limit unchanged). */
|
|
146
|
+
const current = (provider: string, now: number): ProviderRuntime => {
|
|
147
|
+
const s = state(provider);
|
|
148
|
+
if (s.pausedUntilMs !== null && now >= s.pausedUntilMs) {
|
|
149
|
+
s.pausedUntilMs = null;
|
|
150
|
+
emit({ provider, change: "resume", from: s.limit, to: s.limit, until: null, errorType: null, status: null });
|
|
151
|
+
}
|
|
152
|
+
return s;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const heavyLimit = (s: ProviderRuntime): number => Math.min(heavyCap, s.limit);
|
|
156
|
+
|
|
157
|
+
const free = (provider: string, heavy: boolean): number => {
|
|
158
|
+
const s = current(provider, clock.now());
|
|
159
|
+
const normal = s.pausedUntilMs !== null ? 0 : Math.max(0, s.limit - s.used);
|
|
160
|
+
return heavy ? Math.min(normal, Math.max(0, heavyLimit(s) - s.heavyUsed)) : normal;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const isoOrNull = (ms: number | null): IsoTime | null => (ms === null ? null : clock.iso(ms));
|
|
164
|
+
|
|
165
|
+
const controller: CapacityController = {
|
|
166
|
+
limit(provider) {
|
|
167
|
+
return current(provider, clock.now()).limit;
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
canAcquire(provider, heavy) {
|
|
171
|
+
return free(provider, heavy) > 0;
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
acquire(provider, heavy, taskId, attempt, opts) {
|
|
175
|
+
const now = clock.now();
|
|
176
|
+
const s = current(provider, now);
|
|
177
|
+
if (opts?.force !== true && free(provider, heavy) <= 0) {
|
|
178
|
+
throw new ExecutorError("E_CAPACITY", `no ${heavy ? "heavy " : ""}capacity for provider ${provider}`, {
|
|
179
|
+
provider, heavy, taskId, attempt, limit: s.limit, used: s.used, heavyUsed: s.heavyUsed,
|
|
180
|
+
pausedUntil: isoOrNull(s.pausedUntilMs),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
tokenSeq += 1;
|
|
184
|
+
const id = `cap-${tokenSeq}`;
|
|
185
|
+
tokens.set(id, { provider, heavy, taskId, attempt, acquiredAtMs: now, seq: tokenSeq });
|
|
186
|
+
s.used += 1;
|
|
187
|
+
if (heavy) s.heavyUsed += 1;
|
|
188
|
+
return { id };
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
release(token, result) {
|
|
192
|
+
const t = tokens.get(token.id);
|
|
193
|
+
if (t === undefined) return; // idempotent; unknown ids are ignored
|
|
194
|
+
tokens.delete(token.id);
|
|
195
|
+
const now = clock.now();
|
|
196
|
+
const s = current(t.provider, now);
|
|
197
|
+
s.used = Math.max(0, s.used - 1);
|
|
198
|
+
if (t.heavy) s.heavyUsed = Math.max(0, s.heavyUsed - 1);
|
|
199
|
+
if (result !== "success" || s.limit >= maxParallel) return;
|
|
200
|
+
// M16: grow by 1 only after a quiet cooldown, and only from a child started at or after the last signal.
|
|
201
|
+
if (s.pausedUntilMs !== null || now < s.holdUntilMs) return;
|
|
202
|
+
if (s.lastSignalAtMs !== null && (now - s.lastSignalAtMs < cooldownMs || t.acquiredAtMs < s.lastSignalAtMs)) return;
|
|
203
|
+
// QA-3.1-13: one increase per generation; a token acquired before the last increase no longer qualifies.
|
|
204
|
+
if (t.seq <= s.lastIncreaseSeq) return;
|
|
205
|
+
const from = s.limit;
|
|
206
|
+
s.limit = from + 1;
|
|
207
|
+
s.lastIncreaseSeq = tokenSeq;
|
|
208
|
+
emit({ provider: t.provider, change: "increase", from, to: s.limit, until: null, errorType: null, status: null });
|
|
209
|
+
},
|
|
210
|
+
|
|
211
|
+
onSignal(sig: ProviderSignal): OnSignalResult {
|
|
212
|
+
const now = clock.now();
|
|
213
|
+
const s = current(sig.provider, now);
|
|
214
|
+
const cls = classifyProviderError(sig.error);
|
|
215
|
+
const errorType = sig.error.type;
|
|
216
|
+
const status = sig.error.status;
|
|
217
|
+
|
|
218
|
+
if (cls === "rate-limit" || cls === "overload") {
|
|
219
|
+
s.lastSignalAtMs = now;
|
|
220
|
+
const seen = firstSignalAt.get(sig.stepKey);
|
|
221
|
+
if (seen !== undefined) {
|
|
222
|
+
touchBounded(firstSignalAt, sig.stepKey, seen);
|
|
223
|
+
return { decreased: false, pausedUntil: isoOrNull(s.pausedUntilMs), inbox: null };
|
|
224
|
+
}
|
|
225
|
+
touchBounded(firstSignalAt, sig.stepKey, now);
|
|
226
|
+
// A first signal at the floor (limit 1) still renews the hold and emits `decrease` 1 -> 1 (`decreased: false`).
|
|
227
|
+
const from = s.limit;
|
|
228
|
+
s.limit = Math.max(1, Math.floor(from / 2));
|
|
229
|
+
s.holdUntilMs = now + cooldownMs;
|
|
230
|
+
emit({ provider: sig.provider, change: "decrease", from, to: s.limit, until: clock.iso(s.holdUntilMs), errorType, status });
|
|
231
|
+
return { decreased: s.limit < from, pausedUntil: isoOrNull(s.pausedUntilMs), inbox: null };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (cls === "quota") {
|
|
235
|
+
const until = pauseUntilFromMessage(sig.error.message, now) ?? now + pauseMs;
|
|
236
|
+
const starting = s.pausedUntilMs === null;
|
|
237
|
+
if (!starting && s.pausedUntilMs !== null && until <= s.pausedUntilMs) {
|
|
238
|
+
return { decreased: false, pausedUntil: clock.iso(s.pausedUntilMs), inbox: null };
|
|
239
|
+
}
|
|
240
|
+
s.pausedUntilMs = until;
|
|
241
|
+
const untilIso = clock.iso(until);
|
|
242
|
+
emit({ provider: sig.provider, change: "pause", from: s.limit, to: s.limit, until: untilIso, errorType, status });
|
|
243
|
+
const inbox: InboxInput | null = starting
|
|
244
|
+
? usageLimitItem(sig.provider, untilIso, errorType)
|
|
245
|
+
: null;
|
|
246
|
+
return { decreased: false, pausedUntil: untilIso, inbox };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return { decreased: false, pausedUntil: isoOrNull(s.pausedUntilMs), inbox: null };
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
shouldStopRetry(i) {
|
|
253
|
+
const now = clock.now();
|
|
254
|
+
const s = current(i.provider, now);
|
|
255
|
+
if (!i.planChild) return false;
|
|
256
|
+
const first = firstSignalAt.get(i.stepKey);
|
|
257
|
+
const stop = s.pausedUntilMs !== null || (first !== undefined && now - first > cooldownMs);
|
|
258
|
+
if (stop && !retryStopped.has(i.stepKey)) {
|
|
259
|
+
touchBounded(retryStopped, i.stepKey, 0);
|
|
260
|
+
emit({
|
|
261
|
+
provider: i.provider, change: "retry-stop", from: s.limit, to: s.limit, until: null,
|
|
262
|
+
errorType: null, status: null,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
return stop;
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
pausedUntil(provider) {
|
|
269
|
+
return isoOrNull(current(provider, clock.now()).pausedUntilMs);
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
snapshot(): JsonValue {
|
|
273
|
+
const now = clock.now();
|
|
274
|
+
const out: { [k: string]: JsonValue } = {};
|
|
275
|
+
for (const p of [...providers.keys()].sort()) {
|
|
276
|
+
const s = current(p, now);
|
|
277
|
+
out[p] = {
|
|
278
|
+
limit: s.limit,
|
|
279
|
+
used: s.used,
|
|
280
|
+
heavyUsed: s.heavyUsed,
|
|
281
|
+
holdUntil: s.holdUntilMs > now ? clock.iso(s.holdUntilMs) : null,
|
|
282
|
+
lastSignalAt: isoOrNull(s.lastSignalAtMs),
|
|
283
|
+
pausedUntil: isoOrNull(s.pausedUntilMs),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
return { maxParallel, heavyCap, cooldownMs, pauseMs, tokens: tokens.size, providers: out };
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
FREE.set(controller, free);
|
|
291
|
+
return controller;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** M15: the inbox input raised once when a pause starts. `taskId` stays null here: the controller sees sessions, not
|
|
295
|
+
* tasks; the runtime fills in the plan child's task when it knows it. */
|
|
296
|
+
function usageLimitItem(provider: string, untilIso: IsoTime, errorType: string): InboxInput {
|
|
297
|
+
return {
|
|
298
|
+
kind: "usage-limit",
|
|
299
|
+
severity: "info",
|
|
300
|
+
taskId: null,
|
|
301
|
+
text: `provider ${provider} paused until ${untilIso} (${errorType})`,
|
|
302
|
+
options: [],
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** A per-tick view: `routeOf` memoized per task id, `free` per M14. A controller not built by
|
|
307
|
+
* `createCapacityController` exposes no counters, so its view answers at most 1 (only ever delays). */
|
|
308
|
+
export function capacityView(c: CapacityController, routes: RouteResolver): CapacityView {
|
|
309
|
+
const memo = new Map<TaskId, TaskRoute>();
|
|
310
|
+
const free = FREE.get(c) ?? ((p: string, heavy: boolean): number => (c.canAcquire(p, heavy) ? 1 : 0));
|
|
311
|
+
return {
|
|
312
|
+
routeOf(task: TaskNode): TaskRoute {
|
|
313
|
+
let r = memo.get(task.id);
|
|
314
|
+
if (r === undefined) {
|
|
315
|
+
r = routes.route(task);
|
|
316
|
+
memo.set(task.id, r);
|
|
317
|
+
}
|
|
318
|
+
return r;
|
|
319
|
+
},
|
|
320
|
+
free,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** M20: replays the history's `capacity` metrics per provider: the last `to`, and a still-future hold or pause. */
|
|
325
|
+
export function capacityRestoreFromEvents(
|
|
326
|
+
events: readonly ExecutorEvent[],
|
|
327
|
+
o: { maxParallel: number; nowMs: number },
|
|
328
|
+
): Record<string, CapacityProviderState> {
|
|
329
|
+
const maxParallel = Math.max(1, Math.floor(o.maxParallel));
|
|
330
|
+
const out: Record<string, CapacityProviderState> = {};
|
|
331
|
+
for (const e of events) {
|
|
332
|
+
if (e.type !== "metric" || e.metric.name !== "capacity") continue;
|
|
333
|
+
const m = e.metric;
|
|
334
|
+
const s = (out[m.provider] ??= { limit: maxParallel, holdUntilMs: 0, lastSignalAtMs: null, pausedUntilMs: null });
|
|
335
|
+
s.limit = clampLimit(m.to, maxParallel);
|
|
336
|
+
const untilMs = m.until === null ? Number.NaN : Date.parse(m.until);
|
|
337
|
+
switch (m.change) {
|
|
338
|
+
case "decrease": {
|
|
339
|
+
s.holdUntilMs = Number.isFinite(untilMs) ? untilMs : 0;
|
|
340
|
+
const at = Date.parse(e.at);
|
|
341
|
+
s.lastSignalAtMs = Number.isFinite(at) ? at : null;
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
case "pause":
|
|
345
|
+
if (Number.isFinite(untilMs) && (s.pausedUntilMs === null || untilMs > s.pausedUntilMs)) s.pausedUntilMs = untilMs;
|
|
346
|
+
break;
|
|
347
|
+
case "resume":
|
|
348
|
+
s.pausedUntilMs = null;
|
|
349
|
+
break;
|
|
350
|
+
default:
|
|
351
|
+
break;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
for (const s of Object.values(out)) {
|
|
355
|
+
if (s.holdUntilMs <= o.nowMs) {
|
|
356
|
+
s.holdUntilMs = 0;
|
|
357
|
+
s.lastSignalAtMs = null;
|
|
358
|
+
}
|
|
359
|
+
if (s.pausedUntilMs !== null && s.pausedUntilMs <= o.nowMs) s.pausedUntilMs = null;
|
|
360
|
+
}
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Executor children move between plugin locations. Publish rounds process-wide, including across module copies. */
|
|
2
|
+
export interface ExecutorChildRound {
|
|
3
|
+
readonly round: number;
|
|
4
|
+
readonly agent: string;
|
|
5
|
+
readonly cap: number | "none" | null;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface Registry {
|
|
9
|
+
version: 1;
|
|
10
|
+
sequence: number;
|
|
11
|
+
children: Map<string, ExecutorChildRound>;
|
|
12
|
+
}
|
|
13
|
+
const KEY = Symbol.for("opencode-model-router.executor-child-guards@1");
|
|
14
|
+
|
|
15
|
+
function registry(): Registry {
|
|
16
|
+
const value: unknown = Reflect.get(globalThis, KEY);
|
|
17
|
+
if (typeof value === "object" && value !== null) {
|
|
18
|
+
const existing = value as Partial<Registry>;
|
|
19
|
+
if (existing.version === 1 && typeof existing.sequence === "number" && existing.children instanceof Map) return existing as Registry;
|
|
20
|
+
}
|
|
21
|
+
const created: Registry = { version: 1, sequence: 0, children: new Map() };
|
|
22
|
+
Reflect.set(globalThis, KEY, created);
|
|
23
|
+
return created;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function publishExecutorChildRound(child: string, agent: string, cap: ExecutorChildRound["cap"], resume: boolean): void {
|
|
27
|
+
const reg = registry();
|
|
28
|
+
const previous = reg.children.get(child);
|
|
29
|
+
reg.children.delete(child);
|
|
30
|
+
reg.children.set(child, { round: ++reg.sequence, agent, cap: resume ? cap ?? previous?.cap ?? null : cap });
|
|
31
|
+
while (reg.children.size > 4096) reg.children.delete(reg.children.keys().next().value!);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function executorChildRound(child: string): ExecutorChildRound | undefined {
|
|
35
|
+
return registry().children.get(child);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function forgetExecutorChildRound(child: string): void {
|
|
39
|
+
registry().children.delete(child);
|
|
40
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/plan` slash command (v2 only, registered by Phase 5.1). The factory turns the typed subcommand into orchestrator
|
|
3
|
+
* instructions: they name the `router_plan` action to call and its exact arguments. Unknown or malformed input prints
|
|
4
|
+
* the `/plan` help instead.
|
|
5
|
+
*/
|
|
6
|
+
import { buildPlanHelp } from "../commands/output.js";
|
|
7
|
+
import type { ExecutorRuntime } from "./types.js";
|
|
8
|
+
|
|
9
|
+
/** Arguments of one `router_plan` call, as built from a `/plan` line. */
|
|
10
|
+
export type PlanCallArgs =
|
|
11
|
+
| { action: "compile"; path: string; phases?: string[]; doneBefore?: string }
|
|
12
|
+
| { action: "status"; planId?: string; inbox?: true }
|
|
13
|
+
| { action: "answer"; planId?: string; inboxId: string; text: string }
|
|
14
|
+
| { action: "approve" | "pause" | "resume" | "abort" | "land" | "adopt"; planId: string };
|
|
15
|
+
|
|
16
|
+
export type ParsedPlanCommand =
|
|
17
|
+
| { kind: "call"; call: PlanCallArgs }
|
|
18
|
+
| { kind: "help"; reason: string | null };
|
|
19
|
+
|
|
20
|
+
interface Token {
|
|
21
|
+
value: string;
|
|
22
|
+
/** Offset of the token's first character (the opening quote when quoted) and one past its last. */
|
|
23
|
+
start: number;
|
|
24
|
+
end: number;
|
|
25
|
+
quoted: boolean;
|
|
26
|
+
/** A quote in it has no closing quote: the token then runs to the end of the input (QA-4.1-11). */
|
|
27
|
+
unterminated: boolean;
|
|
28
|
+
/** The bare text before the token's first quote (all of it when unquoted): `--plan=` for `--plan="p2"`. */
|
|
29
|
+
prefix: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Whitespace-separated tokens. A `"…"` or `'…'` run is one token with the quotes removed and may hold spaces (a Windows path
|
|
34
|
+
* such as `"C:\My Plans\x.md"`). Backslashes are literal: there are no escapes. An unterminated quote runs to the end and
|
|
35
|
+
* marks the token `unterminated`; every subcommand refuses such a token except in the free answer text.
|
|
36
|
+
*/
|
|
37
|
+
function tokenize(input: string): Token[] {
|
|
38
|
+
const out: Token[] = [];
|
|
39
|
+
let i = 0;
|
|
40
|
+
while (i < input.length) {
|
|
41
|
+
if (/\s/.test(input[i] ?? "")) {
|
|
42
|
+
i++;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const start = i;
|
|
46
|
+
let value = "";
|
|
47
|
+
let quoted = false;
|
|
48
|
+
let unterminated = false;
|
|
49
|
+
let prefix: string | null = null;
|
|
50
|
+
while (i < input.length && !/\s/.test(input[i] ?? "")) {
|
|
51
|
+
const ch = input[i] as string;
|
|
52
|
+
if (ch === '"' || ch === "'") {
|
|
53
|
+
if (!quoted) prefix = value;
|
|
54
|
+
quoted = true;
|
|
55
|
+
const close = input.indexOf(ch, i + 1);
|
|
56
|
+
if (close === -1) unterminated = true;
|
|
57
|
+
const stop = close === -1 ? input.length : close;
|
|
58
|
+
value += input.slice(i + 1, stop);
|
|
59
|
+
i = close === -1 ? input.length : close + 1;
|
|
60
|
+
} else {
|
|
61
|
+
value += ch;
|
|
62
|
+
i++;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
out.push({ value, start, end: i, quoted, unterminated, prefix: prefix ?? value });
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const help = (reason: string | null = null): ParsedPlanCommand => ({ kind: "help", reason });
|
|
71
|
+
|
|
72
|
+
const UNTERMINATED =
|
|
73
|
+
"unterminated quote: a ' or \" starts a quoted argument and needs a closing quote (wrap a path that holds ' in \"…\")";
|
|
74
|
+
|
|
75
|
+
/** Help for the first unterminated token among `tokens`, or null when every quote is closed. */
|
|
76
|
+
function unterminated(tokens: readonly Token[]): ParsedPlanCommand | null {
|
|
77
|
+
return tokens.some((t) => t.unterminated) ? help(UNTERMINATED) : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* `--phases` takes comma-separated phase ids (QA-4.1-15): `--phases 1.1,1.2`. A space between ids is refused (null), so
|
|
82
|
+
* `--phases 1.1 1.2` never silently drops `1.2`.
|
|
83
|
+
*/
|
|
84
|
+
function phaseIds(raw: string): string[] | null {
|
|
85
|
+
const list = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
86
|
+
return list.some((s) => /\s/.test(s)) ? null : list;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const PHASES_FORMAT = "--phases takes comma-separated phase ids without spaces, for example --phases 1.1,1.2";
|
|
90
|
+
|
|
91
|
+
function parseRun(tokens: Token[]): ParsedPlanCommand {
|
|
92
|
+
let path: string | undefined;
|
|
93
|
+
let phases: string[] | undefined;
|
|
94
|
+
let doneBefore: string | undefined;
|
|
95
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
96
|
+
const t = tokens[i] as Token;
|
|
97
|
+
const flag = t.quoted ? null : /^(--phases|--done-before)(?:=(.*))?$/.exec(t.value);
|
|
98
|
+
if (flag === null) {
|
|
99
|
+
if (!t.quoted && t.value.startsWith("--")) return help(`unknown option ${t.value}`);
|
|
100
|
+
if (path !== undefined) {
|
|
101
|
+
return help(`unexpected argument ${t.value}${phases !== undefined ? ` (${PHASES_FORMAT})` : ""}`);
|
|
102
|
+
}
|
|
103
|
+
path = t.value;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
let value = flag[2];
|
|
107
|
+
if (value === undefined) {
|
|
108
|
+
const next = tokens[i + 1];
|
|
109
|
+
if (next === undefined) return help(`${flag[1]} needs a value`);
|
|
110
|
+
value = next.value;
|
|
111
|
+
i++;
|
|
112
|
+
}
|
|
113
|
+
if (flag[1] === "--phases") {
|
|
114
|
+
const list = phaseIds(value);
|
|
115
|
+
if (list === null) return help(PHASES_FORMAT);
|
|
116
|
+
if (list.length === 0) return help("--phases needs at least one phase id");
|
|
117
|
+
phases = list;
|
|
118
|
+
} else {
|
|
119
|
+
const id = value.trim();
|
|
120
|
+
if (id.length === 0) return help("--done-before needs a phase id");
|
|
121
|
+
doneBefore = id;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (path === undefined || path.length === 0) return help("/plan run needs a plan path");
|
|
125
|
+
const call: PlanCallArgs = { action: "compile", path };
|
|
126
|
+
if (phases !== undefined) call.phases = phases;
|
|
127
|
+
if (doneBefore !== undefined) call.doneBefore = doneBefore;
|
|
128
|
+
return { kind: "call", call };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* A leading `--plan <planId>` (or `--plan=<planId>`) of `/plan inbox` and `/plan answer` (QA-4.1-5): the plan id and the
|
|
133
|
+
* number of tokens it took; `used: 0` when absent; a help when it has no id.
|
|
134
|
+
*/
|
|
135
|
+
function planFlag(rest: readonly Token[]): { planId?: string; used: number } | ParsedPlanCommand {
|
|
136
|
+
const t = rest[0];
|
|
137
|
+
if (t === undefined) return { used: 0 };
|
|
138
|
+
// The flag is typed bare; only its `=<id>` may be quoted (`--plan="p2"`, `--plan='p2'`). A quoted `"--plan"` is text.
|
|
139
|
+
if (t.prefix.startsWith("--plan=")) {
|
|
140
|
+
const id = t.value.slice("--plan=".length);
|
|
141
|
+
return id.length > 0 ? { planId: id, used: 1 } : help("--plan needs a plan id");
|
|
142
|
+
}
|
|
143
|
+
if (t.quoted || t.value !== "--plan") return { used: 0 };
|
|
144
|
+
const next = rest[1];
|
|
145
|
+
if (next === undefined || next.value.length === 0) return help("--plan needs a plan id");
|
|
146
|
+
return { planId: next.value, used: 2 };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Parse the text after `/plan`. Pure: no I/O. */
|
|
150
|
+
export function parsePlanCommand(args: string): ParsedPlanCommand {
|
|
151
|
+
const tokens = tokenize(args);
|
|
152
|
+
const sub = tokens[0]?.value.toLowerCase();
|
|
153
|
+
const rest = tokens.slice(1);
|
|
154
|
+
// The answer text is kept as typed (an apostrophe in it is fine); every other token must close its quotes.
|
|
155
|
+
if (sub !== "answer") {
|
|
156
|
+
const bad = unterminated(tokens);
|
|
157
|
+
if (bad !== null) return bad;
|
|
158
|
+
}
|
|
159
|
+
switch (sub) {
|
|
160
|
+
case "run":
|
|
161
|
+
return parseRun(rest);
|
|
162
|
+
case "status": {
|
|
163
|
+
if (rest.length > 1) return help("/plan status takes at most one plan id");
|
|
164
|
+
const planId = rest[0]?.value;
|
|
165
|
+
return { kind: "call", call: planId === undefined ? { action: "status" } : { action: "status", planId } };
|
|
166
|
+
}
|
|
167
|
+
case "inbox": {
|
|
168
|
+
const f = planFlag(rest);
|
|
169
|
+
if ("kind" in f) return f;
|
|
170
|
+
if (rest.length > f.used) return help("/plan inbox takes only --plan <planId>");
|
|
171
|
+
const call: PlanCallArgs = { action: "status", inbox: true };
|
|
172
|
+
if (f.planId !== undefined) call.planId = f.planId;
|
|
173
|
+
return { kind: "call", call };
|
|
174
|
+
}
|
|
175
|
+
case "answer": {
|
|
176
|
+
const f = planFlag(rest);
|
|
177
|
+
if ("kind" in f) return f;
|
|
178
|
+
// `--plan <planId>` and the item id must close their quotes; only the text after them is free.
|
|
179
|
+
const bad = unterminated(rest.slice(0, f.used + 1));
|
|
180
|
+
if (bad !== null) return bad;
|
|
181
|
+
const id = rest[f.used];
|
|
182
|
+
const first = rest[f.used + 1];
|
|
183
|
+
if (id === undefined || first === undefined) return help("/plan answer needs an id and the answer text");
|
|
184
|
+
// Only --plan is an option here; any other bare `--x` before the text is refused, never taken as the item id.
|
|
185
|
+
if (!id.quoted && id.value.startsWith("--")) return help(`unknown option ${id.value}`);
|
|
186
|
+
const last = rest[rest.length - 1] as Token;
|
|
187
|
+
// The text is kept as typed; a single, properly quoted token is unwrapped.
|
|
188
|
+
const unwrap = rest.length === f.used + 2 && first.quoted && !first.unterminated;
|
|
189
|
+
const text = unwrap ? first.value : args.slice(first.start, last.end);
|
|
190
|
+
const call: PlanCallArgs = { action: "answer", inboxId: id.value, text };
|
|
191
|
+
if (f.planId !== undefined) call.planId = f.planId;
|
|
192
|
+
return { kind: "call", call };
|
|
193
|
+
}
|
|
194
|
+
case "approve":
|
|
195
|
+
case "pause":
|
|
196
|
+
case "resume":
|
|
197
|
+
case "abort":
|
|
198
|
+
case "land":
|
|
199
|
+
case "adopt": {
|
|
200
|
+
const planId = rest[0]?.value;
|
|
201
|
+
if (planId === undefined || rest.length > 1) return help(`/plan ${sub} needs exactly one plan id`);
|
|
202
|
+
return { kind: "call", call: { action: sub, planId } };
|
|
203
|
+
}
|
|
204
|
+
default:
|
|
205
|
+
return help();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* What to do with the `router_plan action=compile` result (QA-4.1-1, QA-4.1-7): compiling never starts a plan; a
|
|
211
|
+
* residue step goes to an architect, and approval is the user's.
|
|
212
|
+
*/
|
|
213
|
+
const COMPILE_FOLLOW_UP: readonly string[] = [
|
|
214
|
+
"Then act on the `status:` line of the result:",
|
|
215
|
+
"- `awaiting-residue`: dispatch the residue prompt of the result, unchanged, to an architect subagent (architect role, " +
|
|
216
|
+
"or heavy tier); then call `router_plan` with `action=residue`, the `planId` of the result and `text=<its complete " +
|
|
217
|
+
"JSON reply>`, and act on that result's `status:` line the same way.",
|
|
218
|
+
// QA-4.1-16: this `/plan run` request is in the conversation and must not read as approval.
|
|
219
|
+
"- `awaiting-approval`: show the summary to the user and stop. This plan is not approved, and this `/plan run` " +
|
|
220
|
+
"request is not approval. Call `router_plan action=approve` only when the user approves this plan after seeing the " +
|
|
221
|
+
"summary, or types `/plan approve <planId>`.",
|
|
222
|
+
"- anything else (approved and running, or a refusal): report the tool result to the user verbatim.",
|
|
223
|
+
"Do nothing else for this command.",
|
|
224
|
+
];
|
|
225
|
+
|
|
226
|
+
/** The orchestrator instruction for one parsed call. */
|
|
227
|
+
export function planInstructions(call: PlanCallArgs): string {
|
|
228
|
+
// A compile can take a residue call after it (the follow-up), so its intro does not say "once".
|
|
229
|
+
const intro =
|
|
230
|
+
call.action === "compile"
|
|
231
|
+
? "Call the `router_plan` tool with exactly these arguments to compile the plan; then follow the instructions below:"
|
|
232
|
+
: "Call the `router_plan` tool once with exactly these arguments:";
|
|
233
|
+
return [
|
|
234
|
+
intro,
|
|
235
|
+
"",
|
|
236
|
+
"```json",
|
|
237
|
+
JSON.stringify(call),
|
|
238
|
+
"```",
|
|
239
|
+
"",
|
|
240
|
+
...(call.action === "compile"
|
|
241
|
+
? COMPILE_FOLLOW_UP
|
|
242
|
+
: ["Then report the tool result to the user verbatim. Do nothing else for this command."]),
|
|
243
|
+
].join("\n");
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export interface PlanCommand {
|
|
247
|
+
readonly name: "plan";
|
|
248
|
+
readonly description: string;
|
|
249
|
+
/** The command text for `/plan <args>`: orchestrator instructions, or the help text. */
|
|
250
|
+
execute(args: string): string;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Factory of the `/plan` command; registration is Phase 5.1's job. */
|
|
254
|
+
export function createPlanCommand(_runtime: ExecutorRuntime): PlanCommand {
|
|
255
|
+
return {
|
|
256
|
+
name: "plan",
|
|
257
|
+
description: "Run and manage a plan with the plan executor",
|
|
258
|
+
execute(args: string): string {
|
|
259
|
+
const parsed = parsePlanCommand(args);
|
|
260
|
+
if (parsed.kind === "call") return planInstructions(parsed.call);
|
|
261
|
+
const text = buildPlanHelp();
|
|
262
|
+
return parsed.reason === null ? text : `${parsed.reason}\n\n${text}`;
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
}
|