pi-spine 2.25.0 → 2.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +14 -1
  4. package/package.json +3 -3
  5. package/skills/spine-release-operator/SKILL.md +3 -0
  6. package/src/batch/abort.mjs +74 -38
  7. package/src/batch/attached-engine-handoff.mjs +2 -2
  8. package/src/batch/attached-runner-promote.mjs +1 -1
  9. package/src/batch/attached-runner-reconcile.mjs +1 -1
  10. package/src/batch/batch-meta-reconstruct.mjs +9 -1
  11. package/src/batch/batch-state-lock.mjs +173 -31
  12. package/src/batch/contract-exec.mjs +48 -47
  13. package/src/batch/contract-parse.mjs +2 -2
  14. package/src/batch/contract-prelanded.mjs +2 -2
  15. package/src/batch/contract-spawn.mjs +225 -0
  16. package/src/batch/contract-verify.mjs +2 -1
  17. package/src/batch/detached-wait.mjs +1 -1
  18. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  19. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  20. package/src/batch/engine-lanes/matrix-run.mjs +6 -6
  21. package/src/batch/engine-lanes/merge.mjs +135 -34
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  24. package/src/batch/engine-lanes/review-code.mjs +1 -0
  25. package/src/batch/engine-lanes/review-final.mjs +83 -46
  26. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  27. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  28. package/src/batch/engine-lanes.mjs +17 -16
  29. package/src/batch/engine.mjs +10 -10
  30. package/src/batch/journal.mjs +15 -0
  31. package/src/batch/lifecycle-archive.mjs +76 -1
  32. package/src/batch/lifecycle-cleanup.mjs +110 -0
  33. package/src/batch/lifecycle.mjs +100 -72
  34. package/src/batch/metrics.mjs +13 -1
  35. package/src/batch/parent-session-monitor.mjs +77 -70
  36. package/src/batch/pause.mjs +92 -25
  37. package/src/batch/post-merge-limbo.mjs +35 -5
  38. package/src/batch/provider-quota.mjs +220 -0
  39. package/src/batch/quota-fallback.mjs +319 -0
  40. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  41. package/src/batch/resume-gate-reopen.mjs +24 -8
  42. package/src/batch/resume-multi-queue.mjs +25 -10
  43. package/src/batch/resume-multi.mjs +1 -1
  44. package/src/batch/resume.mjs +1 -1
  45. package/src/batch/review-artifacts.mjs +93 -15
  46. package/src/batch/review-spawn-retry.mjs +106 -0
  47. package/src/batch/review-spawn.mjs +48 -2
  48. package/src/batch/review-step-run.mjs +96 -6
  49. package/src/batch/reviewer-output.mjs +162 -0
  50. package/src/batch/sequence-run.mjs +26 -8
  51. package/src/batch/sequence-wait.mjs +87 -8
  52. package/src/batch/state-guards.mjs +39 -7
  53. package/src/batch/state-io.mjs +131 -17
  54. package/src/batch/state.mjs +1 -0
  55. package/src/batch/worker-host.mjs +81 -7
  56. package/src/config/cursor-rules/discover.mjs +2 -2
  57. package/src/config/cursor-rules/match-globs.mjs +6 -4
  58. package/src/config/defaults.mjs +15 -1
  59. package/src/config/env-overrides.mjs +41 -4
  60. package/src/config/preflight/git-batch.mjs +47 -0
  61. package/src/config/settings-fields.mjs +6 -0
  62. package/src/config/spine-config-schema.mjs +91 -1
  63. package/src/doctor/quota-risk.mjs +45 -0
  64. package/src/fs/atomic-write.mjs +37 -1
  65. package/src/planner/file-scope.mjs +6 -6
  66. package/src/tasks/packet/validate-contract.mjs +3 -3
@@ -5,12 +5,14 @@
5
5
  */
6
6
 
7
7
  import { isProcessAlive } from "../process/liveness.mjs";
8
+ import { withBatchStateLockAsync } from "./batch-state-lock.mjs";
8
9
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
9
10
  import { recordResumePhaseTransition } from "./resume-common.mjs";
10
11
  import {
11
12
  loadSpineBatchState,
12
13
  readBatchEnginePid,
13
14
  saveSpineBatchState,
15
+ updateSpineBatchState,
14
16
  } from "./state.mjs";
15
17
 
16
18
  /** Grace period for attached engine to persist phase: paused (SP-376). */
@@ -62,31 +64,61 @@ export function mergeEngineStateWithDiskPause(projectRoot, state) {
62
64
  /**
63
65
  * Persist engine state while honoring an operator pause already on disk or in the journal.
64
66
  *
67
+ * The pause merge (a disk read) and the save run inside one async
68
+ * `withBatchStateLockAsync` hold (SP-791 / #301, SP-797 / #302): previously the
69
+ * merge ran before the lock, so an operator pause landing between the merge and
70
+ * the write was clobbered by the engine's whole-file snapshot; and the wait for
71
+ * a contended lock must not block the engine's event loop. The lock is
72
+ * re-entrant per process, so the nested `saveSpineBatchState` acquisition
73
+ * composes instead of self-deadlocking. All callers are engine-side and async
74
+ * (Step 0 of SP-797 found no synchronous non-engine callers), so no sync
75
+ * fallback path is kept — CLI callers keep the synchronous
76
+ * `withBatchStateLock` via `state-io.mjs` / `updateSpineBatchState`.
77
+ *
65
78
  * @param {string} projectRoot
66
79
  * @param {object} state
67
- * @param {{ bypassWriteGuard?: boolean }} [options]
80
+ * @param {{ bypassOwnerCheck?: boolean }} [options]
81
+ * @returns {Promise<unknown>}
68
82
  */
69
- export function saveEngineBatchState(projectRoot, state, options = {}) {
70
- mergeEngineStateWithDiskPause(projectRoot, state);
71
- return saveSpineBatchState(projectRoot, state, options);
83
+ export async function saveEngineBatchState(projectRoot, state, options = {}) {
84
+ return withBatchStateLockAsync(projectRoot, () => {
85
+ mergeEngineStateWithDiskPause(projectRoot, state);
86
+ return saveSpineBatchState(projectRoot, state, options);
87
+ });
72
88
  }
73
89
 
74
90
  /**
75
91
  * Re-assert phase: paused on disk when the operator paused but a running engine overwrote it.
76
92
  *
93
+ * The read-modify-write runs through `updateSpineBatchState` so the phase check
94
+ * and the write are one atomic section (SP-791 / #301). Returns true when the
95
+ * disk ends up paused — already paused (nothing to re-assert) or re-asserted by
96
+ * this call — and false when there is no usable state, no batchId, no active
97
+ * pause, or the write was refused.
98
+ *
77
99
  * @param {string} projectRoot
78
100
  * @returns {boolean}
79
101
  */
80
102
  export function enforceOperatorPauseOnDisk(projectRoot) {
81
- const loaded = loadSpineBatchState(projectRoot);
82
- if (!loaded.raw) return false;
83
- const batchId = String(loaded.raw.batchId ?? "");
84
- if (!batchId) return false;
85
- if (loaded.raw.phase === "paused") return true;
86
- if (!isOperatorPauseActive(projectRoot, batchId)) return false;
87
- loaded.raw.phase = "paused";
88
- saveSpineBatchState(projectRoot, loaded.raw, { bypassWriteGuard: true });
89
- return true;
103
+ let enforced = false;
104
+ const result = updateSpineBatchState(
105
+ projectRoot,
106
+ (draft, { diskState }) => {
107
+ const batchId = String(diskState.batchId ?? "");
108
+ if (!batchId) return false;
109
+ if (diskState.phase === "paused") {
110
+ // Operator pause is already on disk — nothing to re-assert.
111
+ enforced = true;
112
+ return false;
113
+ }
114
+ if (!isOperatorPauseActive(projectRoot, batchId)) return false;
115
+ draft.phase = "paused";
116
+ enforced = true;
117
+ return true;
118
+ },
119
+ { bypassOwnerCheck: true },
120
+ );
121
+ return result.ok === true && enforced;
90
122
  }
91
123
 
92
124
  /**
@@ -96,10 +128,10 @@ export function enforceOperatorPauseOnDisk(projectRoot) {
96
128
  * @param {string} params.batchId
97
129
  * @returns {{ stop: boolean }}
98
130
  */
99
- export function adoptPauseIfRequested({ projectRoot, state, batchId }) {
131
+ export async function adoptPauseIfRequested({ projectRoot, state, batchId }) {
100
132
  const paused = mergeEngineStateWithDiskPause(projectRoot, state);
101
133
  if (!paused) return { stop: false };
102
- saveEngineBatchState(projectRoot, state);
134
+ await saveEngineBatchState(projectRoot, state);
103
135
  appendJournalEvent(projectRoot, batchId, "engine.pause_observed", {
104
136
  enginePid: process.pid,
105
137
  });
@@ -182,8 +214,33 @@ export async function pauseBatch({
182
214
  const attachedEngineAlive =
183
215
  enginePid != null && enginePid !== process.pid && isProcessAlive(enginePid);
184
216
 
185
- state.phase = "paused";
186
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
217
+ // Initial pause write as an atomic read-modify-write (SP-791 / #301): the
218
+ // phase is re-checked under the lock so a state change that landed after the
219
+ // pre-load (operator re-pause, engine completing the batch) is respected
220
+ // instead of being overwritten by this potentially stale snapshot.
221
+ const pauseWrite = updateSpineBatchState(
222
+ projectRoot,
223
+ (draft, { diskState }) => {
224
+ const diskPhase = String(diskState.phase ?? "");
225
+ if (diskPhase !== "running" && diskPhase !== "planning") return false;
226
+ draft.phase = "paused";
227
+ return true;
228
+ },
229
+ { bypassOwnerCheck: true },
230
+ );
231
+ const diskPhase = String(pauseWrite.state?.phase ?? phase ?? "unknown");
232
+ if (!pauseWrite.ok || (!pauseWrite.changed && diskPhase !== "paused")) {
233
+ // State changed (or vanished/corrupted) between the pre-load and the
234
+ // locked write — report the observed phase rather than the stale one.
235
+ return {
236
+ ok: false,
237
+ exitCode: 1,
238
+ error: "cannot_pause",
239
+ output: `Cannot pause batch in phase ${diskPhase}. Only running or planning batches can be paused.\n`,
240
+ batchId,
241
+ phase: diskPhase,
242
+ };
243
+ }
187
244
 
188
245
  if (attachedEngineAlive) {
189
246
  const confirmed = await waitForPauseConfirmation({
@@ -194,20 +251,30 @@ export async function pauseBatch({
194
251
  });
195
252
 
196
253
  if (!confirmed) {
197
- const current = loadSpineBatchState(projectRoot).raw;
198
- const currentPhase = String(current?.phase ?? "unknown");
199
- if (current) {
200
- current.phase = fromPhase;
201
- saveSpineBatchState(projectRoot, current, { bypassWriteGuard: true });
202
- }
254
+ // Roll back only while the disk phase is still our unconfirmed "paused";
255
+ // a terminal phase (completed/failed/aborted/merge_blocked) or an engine
256
+ // rewrite that landed during the grace window must never be reverted to
257
+ // fromPhase (SP-791 / #301 — the rollback could otherwise resurrect a
258
+ // completed batch as running).
259
+ let observedPhase = "unknown";
260
+ updateSpineBatchState(
261
+ projectRoot,
262
+ (draft, { diskState }) => {
263
+ observedPhase = String(diskState.phase ?? "unknown");
264
+ if (diskState.phase !== "paused") return false;
265
+ draft.phase = fromPhase;
266
+ return true;
267
+ },
268
+ { bypassOwnerCheck: true },
269
+ );
203
270
  appendJournalEvent(projectRoot, batchId, "batch.pause_failed", {
204
271
  fromPhase,
205
272
  enginePid,
206
- observedPhase: currentPhase,
273
+ observedPhase,
207
274
  graceMs: confirmGraceMs,
208
275
  });
209
276
  const output =
210
- `Pause not confirmed: batch-state phase is still "${currentPhase}" after ${confirmGraceMs}ms.\n` +
277
+ `Pause not confirmed: batch-state phase is still "${observedPhase}" after ${confirmGraceMs}ms.\n` +
211
278
  `Attached engine (PID ${enginePid}) did not persist phase: paused — batch.paused was not recorded.\n` +
212
279
  "Stop the attached engine or wait for the current step to finish, then run spine batch pause again.\n" +
213
280
  "spine batch retry is blocked while phase is running — retry only after phase is paused.\n";
@@ -23,6 +23,7 @@ import {
23
23
  recordBatchEnginePid,
24
24
  saveSpineBatchState,
25
25
  } from "./state.mjs";
26
+ import { isBatchArchived } from "./state-guards.mjs";
26
27
 
27
28
  export { isPostMergeLimbo } from "./limbo-detect.mjs";
28
29
  export { hydrateMergeResultsFromJournal, isLastWaveIndex } from "./post-merge-finalize.mjs";
@@ -168,7 +169,7 @@ export function ensureLandLoopFinalizedAfterGateOrIntegrate({
168
169
  }
169
170
 
170
171
  if (changed) {
171
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
172
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
172
173
  }
173
174
 
174
175
  return {
@@ -241,7 +242,7 @@ export function finalizeAttachedLandLoopBeforeExit({
241
242
  });
242
243
  if (finalizeResult?.ok) {
243
244
  clearBatchEnginePid(state);
244
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
245
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
245
246
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
246
247
  signal,
247
248
  action: "finalized_in_process",
@@ -266,7 +267,7 @@ export function finalizeAttachedLandLoopBeforeExit({
266
267
  const fresh = loadSpineBatchState(projectRoot);
267
268
  if (fresh.raw && enginePid) {
268
269
  recordBatchEnginePid(fresh.raw, enginePid);
269
- saveSpineBatchState(projectRoot, fresh.raw, { bypassWriteGuard: true });
270
+ saveSpineBatchState(projectRoot, fresh.raw, { bypassOwnerCheck: true });
270
271
  }
271
272
 
272
273
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
@@ -375,7 +376,7 @@ export function finalizeBatchForIntegrate({
375
376
 
376
377
  // Persist PID clear before evidence collection can hang (#198 / SP-636).
377
378
  clearBatchEnginePid(state);
378
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
379
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
379
380
 
380
381
  const gateResult = openIntegrateGateAfterBatchComplete({
381
382
  projectRoot,
@@ -383,6 +384,35 @@ export function finalizeBatchForIntegrate({
383
384
  batchState: { ...state, phase: "completed" },
384
385
  });
385
386
 
387
+ // Late-finalize no-op after archive (#293 / SP-790): the operator can run
388
+ // gate approve → integrate → batch complete while extended evidence collection
389
+ // above is still running. `batch complete` archives and removes the active state
390
+ // file; persisting from this late path would resurrect a phantom completed batch
391
+ // that blocks the next `spine batch start`. Skip the land-loop finalize and the
392
+ // final save — the write guard would reject the write anyway — and journal the
393
+ // skip so the no-op is visible instead of silent.
394
+ const activeStateAfterGate = loadSpineBatchState(projectRoot);
395
+ if (!activeStateAfterGate.raw && isBatchArchived(projectRoot, batchId)) {
396
+ appendJournalEvent(projectRoot, batchId, "batch.late_finalize_skipped", {
397
+ batchId,
398
+ reason: "archived",
399
+ });
400
+ return {
401
+ ok: true,
402
+ exitCode: 0,
403
+ batchId,
404
+ taskIds,
405
+ taskId: taskIds.length === 1 ? taskIds[0] : undefined,
406
+ orchBranch,
407
+ mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
408
+ gateResult,
409
+ lateFinalizeSkipped: "archived",
410
+ output:
411
+ `Batch ${batchId} archived while finalizing: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
412
+ " → late land-loop finalize skipped — batch already completed and archived\n",
413
+ };
414
+ }
415
+
386
416
  // Always mark completed in memory before ensure so a prior land-loop journal
387
417
  // (e.g. start then pause/resume) still persists phase: completed on disk.
388
418
  if (!alreadyCompleted) {
@@ -398,7 +428,7 @@ export function finalizeBatchForIntegrate({
398
428
  source: landLoopSource,
399
429
  });
400
430
  // Ensure may no-op when journal events already exist; always persist phase/PID.
401
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
431
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
402
432
 
403
433
  const completionLabel = resumed ? "resumed and completed" : "completed";
404
434
  const nextSteps = resumed
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Pure classifier for provider quota exhaustion and transient overload in
3
+ * worker output (SP-804, partial #329).
4
+ *
5
+ * The worker runner forwards pi's stderr/stdout on a non-zero exit
6
+ * (`bin/spine-worker-runner.mjs`), so provider API error payloads end up
7
+ * verbatim inside `workerResult.output`. This module recognizes the payload
8
+ * shapes seen in retained `task.failed` events — Z.ai usage-limit JSON
9
+ * (`{"code":"1308",...}`) and Kimi error envelopes
10
+ * (`{"error":{"type":...}}`) — and reports the shared quota pool the model
11
+ * belongs to. Matching depends only on the payload text, never on the model;
12
+ * the model is used solely to resolve the pool id via `resolvePoolId`, so a
13
+ * mislabelled model cannot fabricate or hide a quota signal.
14
+ */
15
+ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
16
+
17
+ /**
18
+ * @typedef {"quota_exhausted"|"transient_overload"} ProviderQuotaKind
19
+ */
20
+
21
+ /**
22
+ * @typedef {object} ProviderQuotaError
23
+ * @property {ProviderQuotaKind} kind Why the output was classified.
24
+ * @property {string} poolId Shared quota pool the model belongs to (`resolvePoolId`).
25
+ * @property {number|null} httpStatus Three-digit HTTP status preceding the JSON payload, when present.
26
+ * @property {string|null} providerCode z.ai `code` or Kimi `error.type` of the matched rule, when matched.
27
+ * @property {string|null} resetAtRaw Raw text after "reset at" in the provider message (z.ai), when present.
28
+ * @property {null} resetAt Always null for now: the z.ai reset text carries no timezone (UTC+8 is inferred, not confirmed — #329).
29
+ * @property {string} message Provider message string, truncated to 300 characters.
30
+ */
31
+
32
+ /** Provider messages can embed long URLs/pricing pitches; keep a bounded slice. */
33
+ const MAX_MESSAGE_LENGTH = 300;
34
+
35
+ /**
36
+ * Matches a standalone three-digit HTTP status immediately followed —
37
+ * optionally via `:` and/or whitespace — by a JSON object, exactly as
38
+ * providers and pi print it, e.g. `429: {"code":"1308",...}` or
39
+ * `403 {"error":{...}}`. The `\b` anchors keep multi-digit numbers
40
+ * (timestamps, token counts) from matching.
41
+ */
42
+ const STATUS_JSON_PATTERN = /\b(\d{3})\b\s*:?\s*\{/g;
43
+
44
+ /**
45
+ * Truncates a provider message to {@link MAX_MESSAGE_LENGTH} characters.
46
+ *
47
+ * @param {string} message
48
+ * @returns {string}
49
+ */
50
+ function truncateMessage(message) {
51
+ return message.length > MAX_MESSAGE_LENGTH ? message.slice(0, MAX_MESSAGE_LENGTH) : message;
52
+ }
53
+
54
+ /**
55
+ * Extracts the substring of a balanced JSON object starting at `startIndex`
56
+ * (which must point at `{`). Tracks string and escape state so braces inside
57
+ * message text cannot truncate the payload.
58
+ *
59
+ * @param {string} text
60
+ * @param {number} startIndex
61
+ * @returns {string|null} The object substring, or null when unbalanced.
62
+ */
63
+ function extractBalancedObject(text, startIndex) {
64
+ let depth = 0;
65
+ let inString = false;
66
+ let escaped = false;
67
+ for (let i = startIndex; i < text.length; i++) {
68
+ const ch = text[i];
69
+ if (inString) {
70
+ if (escaped) escaped = false;
71
+ else if (ch === "\\") escaped = true;
72
+ else if (ch === '"') inString = false;
73
+ continue;
74
+ }
75
+ if (ch === '"') inString = true;
76
+ else if (ch === "{") depth++;
77
+ else if (ch === "}") {
78
+ depth--;
79
+ if (depth === 0) return text.slice(startIndex, i + 1);
80
+ }
81
+ }
82
+ return null;
83
+ }
84
+
85
+ /**
86
+ * Collects every status-prefixed JSON payload in the output, in order of
87
+ * appearance. Fragments that do not parse as JSON objects are ignored — they
88
+ * are not provider payloads.
89
+ *
90
+ * @param {string} output
91
+ * @returns {{httpStatus: number, payload: Record<string, any>}[]}
92
+ */
93
+ function collectStatusPayloads(output) {
94
+ const candidates = [];
95
+ STATUS_JSON_PATTERN.lastIndex = 0;
96
+ let match;
97
+ while ((match = STATUS_JSON_PATTERN.exec(output)) !== null) {
98
+ const objectStart = match.index + match[0].length - 1;
99
+ const raw = extractBalancedObject(output, objectStart);
100
+ if (raw === null) continue;
101
+ try {
102
+ const payload = JSON.parse(raw);
103
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
104
+ candidates.push({ httpStatus: Number(match[1]), payload });
105
+ }
106
+ } catch {
107
+ // Malformed JSON is not a provider payload; keep scanning.
108
+ }
109
+ }
110
+ return candidates;
111
+ }
112
+
113
+ /**
114
+ * Extracts the raw text following "reset at" in a z.ai usage-limit message.
115
+ * The timestamp carries no timezone, so it is kept verbatim; parsing it into
116
+ * a Date would require guessing UTC+8 (#329).
117
+ *
118
+ * @param {string} message
119
+ * @returns {string|null}
120
+ */
121
+ function extractResetAtRaw(message) {
122
+ const match = message.match(/reset at\s+(.+)$/i);
123
+ if (!match) return null;
124
+ return match[1].trim().replace(/[.!]+$/, "");
125
+ }
126
+
127
+ /**
128
+ * Applies the classification rules to a single payload. The HTTP status is
129
+ * part of every rule so unrelated 4xx/5xx output never matches; a payload
130
+ * that matches no rule returns null rather than a best guess.
131
+ *
132
+ * Rules (#329):
133
+ * - z.ai 429, top-level `code` "1308" (5-hour window) or "1310"
134
+ * (weekly/monthly) → quota_exhausted.
135
+ * - Kimi 403, `error.type` "permission_error", message mentions
136
+ * "usage limit" (billing-cycle exhaustion) → quota_exhausted.
137
+ * - Kimi 429, `error.type` "rate_limit_error", message mentions
138
+ * "currently overloaded" → transient_overload.
139
+ *
140
+ * @param {number} httpStatus
141
+ * @param {Record<string, any>} payload
142
+ * @returns {{kind: ProviderQuotaKind, providerCode: string, resetAtRaw: string|null, message: string}|null}
143
+ */
144
+ function classifyPayload(httpStatus, payload) {
145
+ // Z.ai usage limits: flat `{"code":"1308","message":"..."}` right after the status.
146
+ if (httpStatus === 429 && typeof payload.code === "string" && typeof payload.message === "string") {
147
+ if (payload.code !== "1308" && payload.code !== "1310") return null;
148
+ return {
149
+ kind: "quota_exhausted",
150
+ providerCode: payload.code,
151
+ resetAtRaw: extractResetAtRaw(payload.message),
152
+ message: truncateMessage(payload.message),
153
+ };
154
+ }
155
+
156
+ // Kimi: nested error envelope `{"error":{"type":...,"message":...}}`.
157
+ const error = payload.error && typeof payload.error === "object" ? payload.error : null;
158
+ const errorMessage = typeof error?.message === "string" ? error.message : null;
159
+ if (!error || errorMessage === null) return null;
160
+
161
+ if (
162
+ httpStatus === 403 &&
163
+ error.type === "permission_error" &&
164
+ errorMessage.toLowerCase().includes("usage limit")
165
+ ) {
166
+ return {
167
+ kind: "quota_exhausted",
168
+ providerCode: "permission_error",
169
+ resetAtRaw: null,
170
+ message: truncateMessage(errorMessage),
171
+ };
172
+ }
173
+ if (
174
+ httpStatus === 429 &&
175
+ error.type === "rate_limit_error" &&
176
+ errorMessage.toLowerCase().includes("currently overloaded")
177
+ ) {
178
+ return {
179
+ kind: "transient_overload",
180
+ providerCode: "rate_limit_error",
181
+ resetAtRaw: null,
182
+ message: truncateMessage(errorMessage),
183
+ };
184
+ }
185
+ return null;
186
+ }
187
+
188
+ /**
189
+ * Classifies provider quota exhaustion / transient overload in raw worker
190
+ * output. Pure: no I/O, no clocks, no configuration reads. When several
191
+ * status-prefixed payloads appear, the last one is classified — it is the
192
+ * terminal error the worker actually died on — and if it matches no rule the
193
+ * result is null even when an earlier payload would have matched.
194
+ *
195
+ * @param {string|null|undefined} output Forwarded worker stderr/stdout.
196
+ * @param {string|null|undefined} [model] Model identifier used only for the pool id.
197
+ * @returns {ProviderQuotaError|null}
198
+ */
199
+ export function classifyProviderQuotaError(output, model) {
200
+ if (typeof output !== "string" || !output) return null;
201
+
202
+ const candidates = collectStatusPayloads(output);
203
+ const last = candidates.length > 0 ? candidates[candidates.length - 1] : null;
204
+ if (!last) return null;
205
+
206
+ const classified = classifyPayload(last.httpStatus, last.payload);
207
+ if (!classified) return null;
208
+
209
+ return {
210
+ kind: classified.kind,
211
+ // Narrow null → undefined for resolvePoolId's optional string param; the
212
+ // JSDoc accepts null from callers, and both map to pool "unknown".
213
+ poolId: resolvePoolId(model ?? undefined),
214
+ httpStatus: last.httpStatus,
215
+ providerCode: classified.providerCode,
216
+ resetAtRaw: classified.resetAtRaw,
217
+ resetAt: null,
218
+ message: classified.message,
219
+ };
220
+ }