pi-durable-subagents 1.3.2 → 1.4.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 CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.4.0
4
+
5
+ - Model slots inside a provider: `providers.<p>.models` maps a model id to `{ "slots": N }`. A call on `p/id` holds a
6
+ slot of `p` and, when `id` is listed, a slot of that model on `p`; it starts, switches, spills, fails over or resumes
7
+ onto `p/id` only when both have room. Unlisted models are limited by the provider's slots only; with `models`,
8
+ `slots` may be omitted (no provider-wide limit). One endpoint serving several models no longer needs alias provider
9
+ entries in pi's `models.json` to split its capacity.
10
+ - A freed slot goes only to a waiter whose model also has room; a waiter blocked only by its own model's limit holds
11
+ no provider slot back. The precedence among eligible waiters is unchanged.
12
+ - `status` lists a provider's model holdings after its slots (`gw 7/10 (a 3/6, b 2/6, c 2/4)`), and JSON adds
13
+ `modelSlots`. A queued call held back by its model names that model (`queued`, `poolWait`, the `waiting` event);
14
+ a live switch to a full model is refused with `model-full`.
15
+ - Without `models` the behaviour, output and config hash are those of 1.3.2.
16
+
3
17
  ## 1.3.2
4
18
 
5
19
  - The exact fork works on a provider whose model name on the wire is not its pi catalog id (a gateway alias that
package/README.md CHANGED
@@ -1204,7 +1204,17 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
1204
1204
  "defaultModel": "provider/id",
1205
1205
  "onQuit": "pause",
1206
1206
  "pools": { "fast": ["anthropic/claude-haiku-4-5", "openai/gpt-5-mini"] },
1207
- "providers": { "anthropic": { "slots": 4 } },
1207
+ "providers": {
1208
+ "anthropic": { "slots": 4 },
1209
+ "gateway": {
1210
+ "slots": 10,
1211
+ "models": {
1212
+ "deepseek-v4.1-flash": { "slots": 6 },
1213
+ "MiniMax-M3.1-Flash": { "slots": 6 },
1214
+ "gemini-4-argon": { "slots": 4 }
1215
+ }
1216
+ }
1217
+ },
1208
1218
  "memory": { "reserveMb": 2048, "perChildMb": 300 },
1209
1219
  "writerLock": "queue",
1210
1220
  "askRequireDecision": false,
@@ -1284,6 +1294,28 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
1284
1294
  anew for each execution: a call launched again (after a loss or a launch
1285
1295
  that failed) starts its wait over. `status` names the holders per origin when more than one
1286
1296
  holds a provider: `anthropic 4/4 (3 cli:alice@host, 1 session 01a11a3b)`.
1297
+ - **Model slots inside a provider:** `"models": { "<id>": { "slots": N } }` on
1298
+ a provider limits each listed model there as well. A call on `provider/id`
1299
+ holds one slot of the provider and, when `id` is listed, one of that model;
1300
+ it starts (or switches, spills, fails over or resumes onto it) only when both
1301
+ have room. The id is the part of `provider/id[:thinking]` after the first
1302
+ `/`, without the thinking suffix, compared exactly (it may contain `/`). A
1303
+ model that is not listed is limited by the provider's slots only. With
1304
+ `models`, `slots` may be omitted: then only the model limits apply. In the
1305
+ example one gateway takes 10 requests in flight, at most 6 of DeepSeek, 6 of
1306
+ MiniMax and 4 of Gemini, and a model at its limit does not stop the others.
1307
+ This replaces registering the same endpoint again under alias provider names
1308
+ in pi's `models.json` (one per model, each with its own `slots`), which
1309
+ split the capacity statically and repeated the configuration. A freed slot
1310
+ goes only to a waiter whose model also has room; among those the precedence
1311
+ above applies, and a waiter blocked only by its own model holds no slot
1312
+ back. Used-up detection (`exhaustedPatterns`, `probeMs`) stays per provider.
1313
+ `status` shows the models under their provider,
1314
+ `gateway 7/10 (deepseek-v4.1-flash 3/6, MiniMax-M3.1-Flash 2/6, gemini-4-argon 2/4)`
1315
+ (JSON: `modelSlots: { "<provider>": { "<id>": { held, slots } } }`), and a
1316
+ queued call held back by its model names it (`waiting for a free slot
1317
+ (gateway/gemini-4-argon 4/4)`). A live switch to a full model is refused
1318
+ with `model-full`.
1287
1319
  - **Memory:** new subagents wait while memory is short. Running ones are
1288
1320
  never stopped for memory.
1289
1321
  - **Writer lock:** `"queue"` (default) runs one writing call per git
@@ -1323,7 +1355,7 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
1323
1355
  - **Changes apply without a restart:** the orchestrator re-reads the file
1324
1356
  when it changes (`askRequireDecision` reaches a child at execution start,
1325
1357
  not mid-execution). A new slot limit, pool or default model applies to the
1326
- next slot acquisition; slots already held are kept when a limit drops. An
1358
+ next slot acquisition (model limits too); slots already held are kept when a limit drops. An
1327
1359
  invalid change is not applied, and `status` reports it next to the settings
1328
1360
  still in effect (`config: <hash> since …`) and the slots held per provider.
1329
1361
 
@@ -24,7 +24,7 @@
24
24
  import { JT } from "../types.js";
25
25
  import { EVENT_SEQ_SKIP, WAIT_REASONS } from "./types.js";
26
26
  import { emptyLedger, foldLedger, settingsOf } from "../orchestrator/ledger.js";
27
- import { exhaustedLine, heldIn, slotLine } from "../orchestrator/snapshot.js";
27
+ import { candidateSlots, exhaustedLine, heldIn } from "../orchestrator/snapshot.js";
28
28
  import { parseModel, resolveModel } from "../compat/model.js";
29
29
  import { leaseCalls, leaseState } from "../platform/lease.js";
30
30
  import { requestId } from "../requests.js";
@@ -222,9 +222,10 @@ export function leaseWaits(state, now) {
222
222
  out.set(t.call, { detail: lines.get(t.call) ?? "", since: Math.min(out.get(t.call)?.since ?? Infinity, t.since) });
223
223
  return out;
224
224
  }
225
- const providerOf = (model) => { if (!model)
225
+ const providerOf = (model) => modelOf(model)?.provider;
226
+ const modelOf = (model) => { if (!model)
226
227
  return undefined; try {
227
- return parseModel(model).provider;
228
+ return parseModel(model);
228
229
  }
229
230
  catch {
230
231
  return undefined;
@@ -245,7 +246,7 @@ export function waitInput(f, c, env, agentModel) {
245
246
  if (item.kind === "question" && item.exec === c.exec)
246
247
  asking = true;
247
248
  }
248
- let providers = [];
249
+ let providers = [], candidates = [];
249
250
  if (live && selected) {
250
251
  const p = providerOf(c.model);
251
252
  if (p)
@@ -257,27 +258,20 @@ export function waitInput(f, c, env, agentModel) {
257
258
  const pools = settings.pools ?? {}, raw = c.wanted ?? (c.agent ? agentModel?.(c.agent) : undefined) ?? settings.defaultModel;
258
259
  if (raw && Object.hasOwn(pools, raw)) {
259
260
  try {
260
- providers = [...new Set(resolveModel(raw, pools).map(m => m.provider).filter((p) => !!p))];
261
+ candidates = resolveModel(raw, pools);
261
262
  }
262
263
  catch { /* an invalid pool: unknown */ }
263
264
  }
264
265
  else {
265
- const p = providerOf(c.model ?? raw);
266
- if (p)
267
- providers = [p];
266
+ const m = modelOf(c.model ?? raw);
267
+ if (m?.provider)
268
+ candidates = [m];
268
269
  }
270
+ providers = [...new Set(candidates.map(m => m.provider).filter((p) => !!p))];
269
271
  }
270
- let full = live && !selected && providers.length > 0;
271
- const slot = live && !selected && providers.length ? providers.map(p => {
272
- let held = 0;
273
- for (const h of env.ledger.held.values())
274
- if (h.pool === p)
275
- held++;
276
- const limit = settings.providers?.[p]?.slots;
277
- if (limit === undefined || held < limit)
278
- full = false;
279
- return slotLine(p, held, limit);
280
- }).join(", ") : undefined;
272
+ // Every candidate full: its provider's slots, or (providers.<p>.models) its model's, which the line then names.
273
+ const slots = live && !selected && providers.length ? candidateSlots(candidates, env.ledger.held.values(), settings.providers) : undefined;
274
+ const full = !!slots?.full, slot = slots?.lines.join(", ");
281
275
  const lease = live && selected ? env.leases?.get(c.call) : undefined;
282
276
  return {
283
277
  asking,
@@ -59,8 +59,20 @@ export function configProblem(raw) {
59
59
  if (!record(providers))
60
60
  return "providers must map provider names to { slots }";
61
61
  for (const [name, p] of Object.entries(providers)) {
62
- if (!record(p) || !Number.isSafeInteger(p.slots) || Number(p.slots) < 0)
62
+ // `slots` may be omitted when `models` is given: then only the model limits apply.
63
+ if (!record(p) || (p.slots !== undefined || p.models === undefined) && (!Number.isSafeInteger(p.slots) || Number(p.slots) < 0))
63
64
  return `providers.${name}.slots must be a nonnegative integer`;
65
+ if (p.models !== undefined) {
66
+ if (!record(p.models))
67
+ return `providers.${name}.models must map model ids to { slots }`;
68
+ for (const [id, m] of Object.entries(p.models)) {
69
+ if (!record(m) || !Number.isSafeInteger(m.slots) || Number(m.slots) < 0)
70
+ return `providers.${name}.models.${id}.slots must be a nonnegative integer`;
71
+ const extra = Object.keys(m).find(k => k !== "slots");
72
+ if (extra)
73
+ return `providers.${name}.models.${id}.${extra} is not a model entry key (slots)`;
74
+ }
75
+ }
64
76
  if (p.exhaustedPatterns !== undefined) {
65
77
  if (!Array.isArray(p.exhaustedPatterns) || p.exhaustedPatterns.some(v => typeof v !== "string"))
66
78
  return `providers.${name}.exhaustedPatterns must be a list of regular expression strings`;
@@ -43,6 +43,7 @@ import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./dige
43
43
  import { exhaustedPatterns } from "../providers.js";
44
44
  import { exactDecision, modelConfigured, readPinnedCapture } from "../exact.js";
45
45
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
46
+ import { modelLimit, modelPool, slotsFull } from "../slots.js";
46
47
  import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.js";
47
48
  import { activeTotal } from "./time.js";
48
49
  import { callEntries, entriesOf, forwardsTo, trackedState, usageIds } from "./indexes.js";
@@ -728,11 +729,16 @@ export default function createExecutor(ledgers, options = {}) {
728
729
  return o;
729
730
  }
730
731
  const widOf = (exec) => exec.slice(0, exec.indexOf("@"));
731
- /** Slot precedence: every acquisition waiting now. `blockedOn`: the providers its latest attempt (at `at`) found full. */
732
+ /** Slot precedence: every acquisition waiting now. `blockedOn`: the providers (and model pools) its latest attempt (at
733
+ * `at`) found full; `tried`: per provider, the model ids that attempt found full at either level. */
732
734
  const acquiring = new Map();
733
- /** Whether another waiter with precedence for `provider` found it full on a recent attempt: then `exec` leaves the
734
- * free slot to it. Precedence: a call that ran before (its session, cache and worktree are ready; a parent waits on it)
735
- * before a fresh one; then the workflow origin holding fewer of the provider's slots; then the longer wait; then call id. */
735
+ /** Whether one more call on `provider/id` has room at both levels (provider slots, and the model's when it has any). */
736
+ const room = (provider, id) => { const full = slotsFull(settings().providers, holdings(), provider, id); return !full.provider && !full.model; };
737
+ /** Whether another waiter with precedence for `provider` found it (or its model there) full on a recent attempt and
738
+ * could take a slot now (its model has room too): then `exec` leaves the free slot to it. A waiter blocked only by
739
+ * its own model's limit holds back nothing. Precedence: a call that ran before (its session, cache and worktree are
740
+ * ready; a parent waits on it) before a fresh one; then the workflow origin holding fewer of the provider's slots;
741
+ * then the longer wait; then call id. */
736
742
  function yields(exec, provider) {
737
743
  const me = acquiring.get(exec);
738
744
  if (!me)
@@ -751,7 +757,10 @@ export default function createExecutor(ledgers, options = {}) {
751
757
  return held.get(origin) ?? 0;
752
758
  };
753
759
  for (const [other, w] of acquiring) {
754
- if (other === exec || !w.blockedOn.has(provider) || now - w.at >= recent || interrupted(w.a))
760
+ if (other === exec || now - w.at >= recent || interrupted(w.a))
761
+ continue;
762
+ const ids = w.tried.get(provider);
763
+ if (!ids || ![...ids].some(id => room(provider, id)))
755
764
  continue;
756
765
  if (w.resume !== me.resume) {
757
766
  if (w.resume)
@@ -775,7 +784,7 @@ export default function createExecutor(ledgers, options = {}) {
775
784
  const t = a.ticket, since = Date.now();
776
785
  // An execution that never started (its launch failed for a reason of the environment) does not make a resume.
777
786
  const resume = !!t.continueFrom || t.journal.entries().some(e => e.type === JT.exec && e.call === t.callId && e.exec !== exec && !has(t.journal, "spawn-env-failed", String(e.exec)));
778
- const mine = { a, call: t.callId, origin: originOf(t.wid), since, resume, blockedOn: new Set(), at: since };
787
+ const mine = { a, call: t.callId, origin: originOf(t.wid), since, resume, blockedOn: new Set(), tried: new Map(), at: since };
779
788
  acquiring.set(exec, mine);
780
789
  try {
781
790
  return await acquireLoop(a, exec, decide, mine, writer);
@@ -791,7 +800,7 @@ export default function createExecutor(ledgers, options = {}) {
791
800
  for (;;) {
792
801
  let signal;
793
802
  const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
794
- const blocked = new Set();
803
+ const blocked = new Set(), tried = new Map();
795
804
  const chosen = await serial(async () => {
796
805
  try {
797
806
  if (interrupted(a) || await workflowReached(a.ticket))
@@ -801,7 +810,7 @@ export default function createExecutor(ledgers, options = {}) {
801
810
  const decision = await decide(), pool = decision.pool;
802
811
  let models = decision.candidates;
803
812
  const pinned = decision.spill?.[0];
804
- const full = (m) => holdings().filter(h => h.pool === m.provider).length >= (settings().providers?.[m.provider ?? ""]?.slots ?? Infinity);
813
+ const full = (m) => { const f = slotsFull(settings().providers, holdings(), m.provider, m.id); return f.provider || f.model; };
805
814
  if (pinned && full(pinned)) {
806
815
  if (!sameModel(pinnedWait?.model, pinned))
807
816
  pinnedWait = { model: pinned, since: Date.now() };
@@ -832,9 +841,19 @@ export default function createExecutor(ledgers, options = {}) {
832
841
  const probe = provider !== undefined && folded().exhausted.has(provider);
833
842
  const holders = holdings().filter(e => e.pool === provider);
834
843
  const limit = settings().providers?.[provider ?? ""]?.slots ?? Infinity;
835
- if (!capacity({ kind: "provider", holders: holders.length, capacity: limit })) {
836
- if (provider)
837
- blocked.add(provider);
844
+ // The model's own slots on its provider (when `providers.<p>.models[id]` exists) must have room too.
845
+ const mpool = provider !== undefined ? modelPool(provider, model.id) : "", mlimit = modelLimit(settings().providers, provider, model.id);
846
+ const mholders = mlimit === undefined ? [] : holdings().filter(e => e.pool === mpool);
847
+ const providerFull = !capacity({ kind: "provider", holders: holders.length, capacity: limit });
848
+ const modelFull = mlimit !== undefined && !capacity({ kind: "provider", holders: mholders.length, capacity: mlimit });
849
+ if (providerFull || modelFull) {
850
+ if (provider) {
851
+ if (providerFull)
852
+ blocked.add(provider);
853
+ if (modelFull)
854
+ blocked.add(mpool);
855
+ tried.set(provider, (tried.get(provider) ?? new Set()).add(model.id));
856
+ }
838
857
  continue;
839
858
  }
840
859
  if (provider && yields(exec, provider))
@@ -862,6 +881,12 @@ export default function createExecutor(ledgers, options = {}) {
862
881
  while (holders.some(e => e.slot === slot))
863
882
  slot++;
864
883
  await orch.append("hold", { pool: provider, slot, exec });
884
+ if (mlimit !== undefined) {
885
+ let mslot = 0;
886
+ while (mholders.some(e => e.slot === mslot))
887
+ mslot++;
888
+ await orch.append("hold", { pool: mpool, slot: mslot, exec });
889
+ }
865
890
  // After its next try, the first call admitted to a used-up provider is its probe: its first request
866
891
  // either goes through (the provider is available again) or is refused, which uses no quota.
867
892
  if (probe)
@@ -878,6 +903,7 @@ export default function createExecutor(ledgers, options = {}) {
878
903
  }
879
904
  finally {
880
905
  mine.blockedOn = blocked;
906
+ mine.tried = tried;
881
907
  mine.at = Date.now();
882
908
  }
883
909
  });
@@ -1077,12 +1103,14 @@ export default function createExecutor(ledgers, options = {}) {
1077
1103
  return;
1078
1104
  }
1079
1105
  }
1080
- const target = holdings().find(h => h.exec === exec && h.pool === provider && h.reserved);
1081
- if (!target)
1082
- return;
1083
- if (!folded().observed.has(`${exec}\n${target.rid}`)) {
1106
+ // A reserved slot of the provider proves the switch by the provider answering; a reserved slot of a model on the
1107
+ // provider the execution already ran on (a switch inside one provider) only by that model answering.
1108
+ const reserved = holdings().filter(h => h.exec === exec && h.reserved && !folded().observed.has(`${exec}\n${h.rid}`));
1109
+ const target = reserved.find(h => h.pool === provider) ?? (message.role === "assistant" && message.model
1110
+ ? reserved.find(h => h.pool.startsWith(`${provider}/`) && answersAs(journal, exec, provider, h.pool.slice(provider.length + 1), message.model)) : undefined);
1111
+ if (target) {
1084
1112
  await orch.append("switch-observed", { exec, rid: target.rid, pool: provider });
1085
- for (const h of holdings().filter(h => h.exec === exec && h.pool !== provider && h.pool !== "memory"))
1113
+ for (const h of holdings().filter(h => h.exec === exec && h.pool !== provider && h.pool !== "memory" && h.rid !== target.rid))
1086
1114
  await orch.append("release", { pool: h.pool, slot: h.slot, exec });
1087
1115
  }
1088
1116
  });
@@ -1147,7 +1175,7 @@ export default function createExecutor(ledgers, options = {}) {
1147
1175
  if (t.journal.entries().some(e => e.type === "forward" && e.rid === rid))
1148
1176
  return;
1149
1177
  const probe = folded().exhausted.has(m.provider); // its next try is due (`unavailable` said so): this is its probe
1150
- if (!await reserveSwitch(exec, m.provider, rid))
1178
+ if (await reserveSwitch(exec, m.provider, m.id, rid))
1151
1179
  continue;
1152
1180
  if (probe)
1153
1181
  await orch.append("provider-probe", { provider: m.provider, exec });
@@ -1159,18 +1187,38 @@ export default function createExecutor(ledgers, options = {}) {
1159
1187
  return;
1160
1188
  }
1161
1189
  }
1162
- /** Hold a slot of `provider` for a running execution's switch, unless it holds one; false when it is full. */
1163
- async function reserveSwitch(exec, provider, rid) {
1164
- if (holdings().some(h => h.exec === exec && h.pool === provider))
1165
- return true;
1166
- const target = holdings().filter(h => h.pool === provider);
1167
- if (!capacity({ kind: "provider", holders: target.length, capacity: settings().providers?.[provider]?.slots ?? Infinity }))
1168
- return false;
1169
- let slot = 0;
1170
- while (target.some(h => h.slot === slot))
1171
- slot++;
1172
- await orch.append("hold", { pool: provider, slot, exec, reserved: true, rid });
1173
- return true;
1190
+ /** Hold a slot of `provider` for a running execution's switch to model `id`, unless it holds one, and a slot of the
1191
+ * model there when it has a limit; the reason (holding nothing new) when either is full. Switching inside a provider
1192
+ * away from a model whose slot it holds also reserves the new model's pool (unlimited without an entry): its
1193
+ * observation releases the old model's slot, which stays held until then. */
1194
+ async function reserveSwitch(exec, provider, id, rid) {
1195
+ const mine = holdings().filter(h => h.exec === exec), mpool = modelPool(provider, id), mlimit = modelLimit(settings().providers, provider, id);
1196
+ const holdsProvider = mine.some(h => h.pool === provider);
1197
+ const needModel = !mine.some(h => h.pool === mpool) &&
1198
+ (mlimit !== undefined || holdsProvider && mine.some(h => h.pool.startsWith(`${provider}/`) && h.pool !== mpool));
1199
+ if (holdsProvider && !needModel)
1200
+ return;
1201
+ const target = holdings().filter(h => h.pool === provider), mtarget = holdings().filter(h => h.pool === mpool);
1202
+ if (!holdsProvider && !capacity({ kind: "provider", holders: target.length, capacity: settings().providers?.[provider]?.slots ?? Infinity }))
1203
+ return "provider-full";
1204
+ if (needModel && !capacity({ kind: "provider", holders: mtarget.length, capacity: mlimit ?? Infinity }))
1205
+ return "model-full";
1206
+ if (!holdsProvider) {
1207
+ let slot = 0;
1208
+ while (target.some(h => h.slot === slot))
1209
+ slot++;
1210
+ await orch.append("hold", { pool: provider, slot, exec, reserved: true, rid });
1211
+ }
1212
+ if (needModel) {
1213
+ let slot = 0;
1214
+ while (mtarget.some(h => h.slot === slot))
1215
+ slot++;
1216
+ await orch.append("hold", { pool: mpool, slot, exec, reserved: true, rid });
1217
+ }
1218
+ }
1219
+ /** Whether an answer of `wire` on `provider` is model `id` of it: the same name, or the model pi reported ready for it. */
1220
+ function answersAs(journal, exec, provider, id, wire) {
1221
+ return wire === id || journal.entries().some(e => e.type === "model-ready" && e.exec === exec && sameModel(e.selected, { provider, id }) && e.model?.id === wire);
1174
1222
  }
1175
1223
  /** An answer from a used-up provider, requested after it was found used up: available again. */
1176
1224
  async function answered(t, exec, event) {
@@ -2155,9 +2203,10 @@ export default function createExecutor(ledgers, options = {}) {
2155
2203
  catch {
2156
2204
  return { action: "reject", reason: "unknown-model" };
2157
2205
  }
2158
- const free = (p) => idle || holdings().some(h => h.exec === exec && h.pool === p) ||
2159
- capacity({ kind: "provider", holders: holdings().filter(h => h.pool === p).length, capacity: settings().providers?.[p]?.slots ?? Infinity });
2160
- const m = models.find(m => m.provider && m.afterMs === undefined && !unavailable(m.provider) && free(m.provider));
2206
+ const free = (p, id) => idle || (holdings().some(h => h.exec === exec && h.pool === p) ||
2207
+ capacity({ kind: "provider", holders: holdings().filter(h => h.pool === p).length, capacity: settings().providers?.[p]?.slots ?? Infinity })) &&
2208
+ (holdings().some(h => h.exec === exec && h.pool === modelPool(p, id)) || !slotsFull(settings().providers, holdings(), p, id).model);
2209
+ const m = models.find(m => m.provider && m.afterMs === undefined && !unavailable(m.provider) && free(m.provider, m.id));
2161
2210
  if (!m)
2162
2211
  return { action: "reject", reason: "pool-unavailable" };
2163
2212
  model = `${m.provider}/${m.id}${m.thinking ? `:${m.thinking}` : ""}`;
@@ -2178,8 +2227,9 @@ export default function createExecutor(ledgers, options = {}) {
2178
2227
  return { action: "reject", reason: "call-starting" };
2179
2228
  if (!idle && pendingSwitch(exec))
2180
2229
  return { action: "reject", reason: "switch-pending" };
2181
- if (!idle && !await reserveSwitch(exec, body.provider, rid))
2182
- return { action: "reject", reason: "provider-full" };
2230
+ const full = idle ? undefined : await reserveSwitch(exec, body.provider, body.model, rid);
2231
+ if (full)
2232
+ return { action: "reject", reason: full };
2183
2233
  await note(req.rid, model, idle ? "next-execution" : "next-request", pool);
2184
2234
  const entry = await ctx.journal.append("forward", { rid, rid2, dest, hash, envelope, choice });
2185
2235
  await replayForward(entry);
@@ -0,0 +1,26 @@
1
+ /** The pool name of the slots of model `id` on `provider` in hold/release entries. */
2
+ export const modelPool = (provider, id) => `${provider}/${id}`;
3
+ /** Whether a held pool is a model's (`modelPool`), not a provider's or memory. */
4
+ export const isModelPool = (pool) => pool.includes("/");
5
+ /** The provider-wide slot limit, undefined for none. */
6
+ export const providerLimit = (providers, provider) => provider === undefined ? undefined : providers?.[provider]?.slots;
7
+ /** The slot limit of model `id` on `provider` (the id compared exactly), undefined for none. */
8
+ export function modelLimit(providers, provider, id) {
9
+ const models = provider === undefined ? undefined : providers?.[provider]?.models;
10
+ return models && Object.hasOwn(models, id) ? models[id].slots : undefined;
11
+ }
12
+ /** How many holdings are on `pool`. */
13
+ export function heldOn(held, pool) {
14
+ let n = 0;
15
+ for (const h of held)
16
+ if (h.pool === pool)
17
+ n++;
18
+ return n;
19
+ }
20
+ /** Which level is full for one more call on `provider/id`: the provider's slots, the model's, both or neither. */
21
+ export function slotsFull(providers, held, provider, id) {
22
+ if (provider === undefined)
23
+ return { provider: false, model: false };
24
+ const list = [...held], pl = providerLimit(providers, provider), ml = modelLimit(providers, provider, id);
25
+ return { provider: pl !== undefined && heldOn(list, provider) >= pl, model: ml !== undefined && heldOn(list, modelPool(provider, id)) >= ml };
26
+ }
@@ -9,6 +9,7 @@ import { readCache, writeCache } from "../kernel/cache.js";
9
9
  import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
10
10
  import { JT, askText, attentionEntries, isEntry } from "../types.js";
11
11
  import { parseModel, resolveModel } from "../compat/model.js";
12
+ import { heldOn, isModelPool, modelLimit, modelPool, slotsFull } from "./slots.js";
12
13
  import {} from "./ledger.js";
13
14
  import { awaitingRuns, readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
14
15
  import { packageVersion } from "../version.js";
@@ -26,7 +27,7 @@ const modelStatus = (c) => Object.fromEntries(Object.entries(c).filter(([key]) =
26
27
  /** Scheduling and model identity facts shared by detailed and compact text status. */
27
28
  export function modelStatusText(c, now = Date.now()) {
28
29
  const w = c.poolWait, s = c.spill, m = c.modelMismatch;
29
- return (w ? ` (queued ${age(now - w.since)} on ${w.model.split("/")[0]} (full)${w.free.length ? `; pool has free slots: ${w.free.join(", ")}` : ""})` : "") +
30
+ return (w ? ` (queued ${age(now - w.since)} on ${w.blocker ?? w.model.split("/")[0]} (full)${w.free.length ? `; pool has free slots: ${w.free.join(", ")}` : ""})` : "") +
30
31
  (s ? ` (spilled after ${age(s.waitedMs)}: ${s.from.split("/")[0]} full -> ${s.to})` : "") +
31
32
  (c.routedModel ? ` (routed ${c.routedModel})` : "") +
32
33
  (m ? ` (used ${m.used}, selected ${m.selected})` : "") + (c.modelUnavailable ? ` (model-unavailable: ${c.modelUnavailable})` : "");
@@ -1019,12 +1020,6 @@ const startingChecks = new WeakMap();
1019
1020
  export function queuedText(w, now = Date.now(), span = age) {
1020
1021
  return w.reason === "starting" ? `orchestrator starting (${span(now - (w.since ?? now))})` : w.detail;
1021
1022
  }
1022
- const providerOf = (model) => { try {
1023
- return parseModel(model).provider;
1024
- }
1025
- catch {
1026
- return undefined;
1027
- } };
1028
1023
  /** Why a queued call waits, from what the orchestrator ledger records (precedence as events/waiting.ts): the
1029
1024
  * orchestrator still recovering; every candidate provider used up and not admitted now; the writer lock of its worktree;
1030
1025
  * every candidate provider full. Undefined when none is known: a call is never said to wait for a slot without a full
@@ -1037,18 +1032,19 @@ export function queueWait(c, state, now = Date.now(), starting = orchestratorSta
1037
1032
  return { reason: "starting", detail: "orchestrator starting", since: starting.since };
1038
1033
  // A command call takes no provider slot: only the orchestrator's start and a writer lock hold it back.
1039
1034
  const settings = state.config?.settings ?? {}, pools = settings.pools ?? {}, wanted = c.command !== undefined ? undefined : c.poolWait?.model ?? c.model ?? settings.defaultModel;
1040
- let providers = [];
1035
+ let candidates = [];
1041
1036
  if (wanted && Object.hasOwn(pools, wanted)) {
1042
1037
  try {
1043
- providers = [...new Set(resolveModel(wanted, pools).map(m => m.provider).filter((p) => !!p))];
1038
+ candidates = resolveModel(wanted, pools);
1044
1039
  }
1045
1040
  catch { /* an invalid pool: unknown */ }
1046
1041
  }
1047
1042
  else if (wanted) {
1048
- const p = providerOf(wanted);
1049
- if (p)
1050
- providers = [p];
1043
+ const m = modelOf(wanted);
1044
+ if (m?.provider)
1045
+ candidates = [m];
1051
1046
  }
1047
+ const providers = [...new Set(candidates.map(m => m.provider).filter((p) => !!p))];
1052
1048
  const used = providers.map(p => [p, state.exhausted.get(p)]);
1053
1049
  if (used.length && used.every(([, x]) => x && (now < x.nextTry || x.probe !== undefined)))
1054
1050
  return { reason: "provider-exhausted", detail: `${providers.join(", ")} usage window${providers.length > 1 ? "s" : ""} used up` };
@@ -1056,18 +1052,38 @@ export function queueWait(c, state, now = Date.now(), starting = orchestratorSta
1056
1052
  return { reason: "writer-lock", detail: `waiting for the writer lock of ${c.writerWait.root}` };
1057
1053
  if (!providers.length)
1058
1054
  return undefined;
1059
- let full = true;
1060
- const lines = providers.map(p => {
1061
- let held = 0;
1062
- for (const h of state.held.values())
1063
- if (h.pool === p)
1064
- held++;
1065
- const limit = settings.providers?.[p]?.slots;
1066
- if (limit === undefined || held < limit)
1055
+ const { full, lines } = candidateSlots(candidates, state.held.values(), settings.providers);
1056
+ return full ? { reason: "slot", detail: `waiting for a free slot (${lines.join(", ")})` } : undefined;
1057
+ }
1058
+ const modelOf = (model) => { try {
1059
+ return parseModel(model);
1060
+ }
1061
+ catch {
1062
+ return undefined;
1063
+ } };
1064
+ /** The slot lines of a queued call's candidate models, and whether every candidate is full. One line per provider
1065
+ * ("<provider> <held>/<limit>"), except a provider with room whose candidate models are all full at their own limit
1066
+ * (`providers.<p>.models`): then the full models' lines ("<provider>/<id> <held>/<limit>"), since they are the blocker. */
1067
+ export function candidateSlots(candidates, held, providers) {
1068
+ const list = [...held], byProvider = new Map();
1069
+ for (const m of candidates)
1070
+ if (m.provider) {
1071
+ const ids = byProvider.get(m.provider) ?? [];
1072
+ byProvider.set(m.provider, ids);
1073
+ if (!ids.includes(m.id))
1074
+ ids.push(m.id);
1075
+ }
1076
+ let full = byProvider.size > 0;
1077
+ const lines = [...byProvider].map(([p, ids]) => {
1078
+ const limit = providers?.[p]?.slots, count = heldOn(list, p);
1079
+ const providerFull = limit !== undefined && count >= limit;
1080
+ if (!providerFull && ids.length && ids.every(id => slotsFull(providers, list, p, id).model))
1081
+ return ids.map(id => slotLine(modelPool(p, id), heldOn(list, modelPool(p, id)), modelLimit(providers, p, id))).join(", ");
1082
+ if (!providerFull)
1067
1083
  full = false;
1068
- return slotLine(p, held, limit);
1084
+ return slotLine(p, count, limit);
1069
1085
  });
1070
- return full ? { reason: "slot", detail: `waiting for a free slot (${lines.join(", ")})` } : undefined;
1086
+ return { full, lines };
1071
1087
  }
1072
1088
  /** A mark of the ledger facts a workflow's queued calls show: they are derived again when it changes. */
1073
1089
  function queueMark(wf, state, mark) {
@@ -1082,6 +1098,7 @@ function withLedgerFacts(wf, state) {
1082
1098
  const held = new Map(), now = Date.now(), starting = orchestratorStarting(state);
1083
1099
  for (const h of state.held.values())
1084
1100
  held.set(h.pool, (held.get(h.pool) ?? 0) + 1);
1101
+ const heldList = [...state.held.values()];
1085
1102
  const pools = state.config?.settings.pools, limits = state.config?.settings.providers;
1086
1103
  return { ...wf, calls: wf.calls.map(c => {
1087
1104
  const why = queueWait(c, state, now, starting);
@@ -1090,17 +1107,22 @@ function withLedgerFacts(wf, state) {
1090
1107
  const wait = c.poolWait;
1091
1108
  if (!wait)
1092
1109
  return c;
1093
- let providers = [];
1110
+ let candidates = [];
1094
1111
  if (wait.pool && pools?.[wait.pool]) {
1095
1112
  try {
1096
- providers = resolveModel(wait.pool, pools).map(m => m.provider).filter((p) => !!p);
1113
+ candidates = resolveModel(wait.pool, pools);
1097
1114
  }
1098
1115
  catch { /* A removed or invalid pool has no available entries to show. */ }
1099
1116
  }
1117
+ const providers = candidates.map(m => m.provider).filter((p) => !!p);
1100
1118
  const pinned = wait.model.split("/")[0];
1119
+ // A provider has a free slot for the call when some candidate model of it has room at its own limit too.
1120
+ const modelRoom = (p) => candidates.some(m => m.provider === p && !slotsFull(limits, heldList, p, m.id).model);
1101
1121
  const free = [...new Set(providers)].filter(p => p !== pinned && (held.get(p) ?? 0) < (limits?.[p]?.slots ?? Infinity) &&
1102
- !(state.exhausted.get(p)?.nextTry && state.exhausted.get(p).nextTry > Date.now()));
1103
- return { ...c, poolWait: { ...wait, free } };
1122
+ !(state.exhausted.get(p)?.nextTry && state.exhausted.get(p).nextTry > Date.now()) && modelRoom(p));
1123
+ // The pinned model held back by its own limit on a provider with room: the status names the model.
1124
+ const pm = modelOf(wait.model), pf = pm?.provider ? slotsFull(limits, heldList, pm.provider, pm.id) : undefined;
1125
+ return { ...c, poolWait: { ...wait, free, ...(pf?.model && !pf.provider ? { blocker: wait.model } : {}) } };
1104
1126
  }) };
1105
1127
  }
1106
1128
  /** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
@@ -1394,10 +1416,12 @@ export function slotsView(home, now = Date.now()) {
1394
1416
  const { held, config, rejected } = state, used = state.exhausted;
1395
1417
  const exhausted = [...used].sort(([a], [b]) => a.localeCompare(b)).map(([p, x]) => exhaustedLine(p, x, now));
1396
1418
  const limits = config?.settings.providers ?? {};
1397
- const holders = new Map(), byOrigin = new Map();
1419
+ const holders = new Map(), byOrigin = new Map(), modelHeld = new Map();
1398
1420
  const created = ix.created;
1399
1421
  for (const e of held.values())
1400
- if (e.pool !== "memory") {
1422
+ if (isModelPool(e.pool))
1423
+ modelHeld.set(e.pool, (modelHeld.get(e.pool) ?? 0) + 1);
1424
+ else if (e.pool !== "memory") {
1401
1425
  holders.set(e.pool, (holders.get(e.pool) ?? 0) + 1);
1402
1426
  // exec "<wid>@<rev>/<key>@<gen>#<n>" -> the origin of its workflow
1403
1427
  const origin = originLabel(created.get(e.exec.slice(0, e.exec.indexOf("@")))?.origin);
@@ -1413,8 +1437,22 @@ export function slotsView(home, now = Date.now()) {
1413
1437
  return ` (${[...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([o, n]) => `${n} ${o}`).join(", ")})`;
1414
1438
  };
1415
1439
  const names = [...new Set([...Object.keys(limits), ...holders.keys()])].sort();
1416
- const slots = names.map(p => slotLine(p, holders.get(p) ?? 0, limits[p]?.slots) + who(p));
1417
- return { ...orchestratorView(state, packageVersion(), now), ...(slots.length ? { slots } : {}), ...(config ? { config: `${config.hash} since ${age(now - config.ts)} ago` } : {}),
1440
+ // A provider with `models`: its configured models' holdings, in the order config.json lists them.
1441
+ const modelSlots = {};
1442
+ for (const p of names) {
1443
+ const models = Object.hasOwn(limits, p) ? limits[p].models : undefined;
1444
+ if (models)
1445
+ modelSlots[p] = Object.fromEntries(Object.entries(models).map(([id, m]) => [id, { held: modelHeld.get(modelPool(p, id)) ?? 0, slots: m.slots }]));
1446
+ }
1447
+ const perModel = (p) => {
1448
+ const models = modelSlots[p];
1449
+ if (!models)
1450
+ return "";
1451
+ const list = Object.entries(models).map(([id, m]) => slotLine(id, m.held, m.slots));
1452
+ return list.length ? ` (${list.join(", ")})` : "";
1453
+ };
1454
+ const slots = names.map(p => slotLine(p, holders.get(p) ?? 0, limits[p]?.slots) + perModel(p) + who(p));
1455
+ return { ...orchestratorView(state, packageVersion(), now), ...(slots.length ? { slots } : {}), ...(Object.keys(modelSlots).length ? { modelSlots } : {}), ...(config ? { config: `${config.hash} since ${age(now - config.ts)} ago` } : {}),
1418
1456
  ...(exhausted.length ? { exhausted } : {}),
1419
1457
  ...(rejected ? { configRejected: `${clip(rejected.error, 200)} (${age(now - rejected.ts)} ago); ${config ? config.hash : "the start settings"} stay in effect` } : {}) };
1420
1458
  }
package/dist/ui/view.js CHANGED
@@ -91,6 +91,8 @@ export function plainReason(reason) {
91
91
  return "a model switch is already on its way; it takes effect when the current step ends";
92
92
  if (r === "provider-full")
93
93
  return "that model's provider has no free slot right now";
94
+ if (r === "model-full")
95
+ return "that model has no free slot on its provider right now";
94
96
  if (r === "call-not-running")
95
97
  return "the subagent is not running right now (waiting for a slot, paused or finished)";
96
98
  if (r === "unknown-model")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",