pi-spine 2.27.1 → 2.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-cli/cli-args.mjs +117 -0
  3. package/bin/spine-gate.mjs +28 -21
  4. package/bin/spine-integrate.mjs +28 -7
  5. package/bin/spine-issue.mjs +2 -1
  6. package/bin/spine-settings.mjs +7 -9
  7. package/bin/spine-tasks.mjs +1 -0
  8. package/bin/spine-worker-runner.mjs +21 -8
  9. package/bin/spine.mjs +10 -3
  10. package/package.json +1 -1
  11. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  12. package/skills/spine-release-operator/SKILL.md +14 -2
  13. package/src/batch/contract-exec.mjs +2 -3
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  16. package/src/batch/diagnosis-primary-failure.mjs +35 -0
  17. package/src/batch/engine-lanes/matrix-run.mjs +2 -0
  18. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  19. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  20. package/src/batch/engine-lanes/review-code.mjs +20 -0
  21. package/src/batch/engine-lanes/review-final.mjs +10 -2
  22. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  23. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  24. package/src/batch/engine-lanes.mjs +18 -17
  25. package/src/batch/evidence-command.mjs +18 -21
  26. package/src/batch/evidence-exec.mjs +79 -0
  27. package/src/batch/journal.mjs +5 -3
  28. package/src/batch/metrics-rollup.mjs +98 -4
  29. package/src/batch/metrics.mjs +134 -9
  30. package/src/batch/provider-quota.mjs +174 -6
  31. package/src/batch/quota-fallback.mjs +87 -6
  32. package/src/batch/reconcile-classify.mjs +28 -1
  33. package/src/batch/reconcile-diagnosis-context.mjs +2 -0
  34. package/src/batch/resume-lane-reviews.mjs +11 -10
  35. package/src/batch/retry-profile.mjs +77 -0
  36. package/src/batch/retry.mjs +32 -1
  37. package/src/batch/review-step-run.mjs +4 -0
  38. package/src/batch/review-step.mjs +1 -0
  39. package/src/batch/sequence-wait.mjs +7 -5
  40. package/src/batch/state-io.mjs +29 -3
  41. package/src/batch/worker-heartbeat.mjs +10 -2
  42. package/src/batch/worker-host.mjs +1 -1
  43. package/src/batch/worker-prompt.mjs +4 -5
  44. package/src/cli/deps.mjs +3 -2
  45. package/src/config/agent-model-resolve.mjs +144 -8
  46. package/src/config/contract.mjs +20 -0
  47. package/src/config/model-family.mjs +60 -0
  48. package/src/config/preflight/discovery.mjs +1 -0
  49. package/src/config/settings-fields.mjs +15 -0
  50. package/src/config/spine-config-schema.mjs +49 -0
  51. package/src/doctor/agent-model-inherit.mjs +78 -1
  52. package/src/doctor/agent-template-drift.mjs +65 -0
  53. package/src/doctor/run-doctor-checks.mjs +8 -1
  54. package/src/doctor/stet-capacity.mjs +171 -0
  55. package/src/metrics/quota-cli.mjs +16 -0
  56. package/src/metrics/quota-probes.mjs +228 -31
  57. package/src/metrics/quota-snapshot.mjs +21 -2
  58. package/src/planner/graph.mjs +7 -5
  59. package/src/planner/pending.mjs +2 -2
  60. package/src/planner/scope.mjs +3 -3
  61. package/src/tasks/packet/parse-prompt.mjs +47 -0
  62. package/src/tasks/packet/validate-prompt.mjs +156 -1
  63. package/templates/agents/reviewer.md +3 -1
  64. package/templates/agents/worker.md +15 -19
@@ -8,10 +8,72 @@
8
8
  */
9
9
 
10
10
  const USAGE_FIELDS = ["tokensIn", "tokensOut", "estimatedUsd"];
11
+ const REVIEW_TYPE_ORDER = ["plan", "code", "final"];
11
12
 
12
13
  /**
14
+ * Group `recordType: "review"` rows by `(reviewType, model)` (SP-837 / #325).
15
+ * Tolerates rows missing any new field (`—` / `inherit` buckets, zero counts).
16
+ *
13
17
  * @param {object[]} lines
14
- * @returns {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object> } | null}
18
+ * @returns {Array<{ reviewType: string, model: string, count: number, verdicts: Record<string, number>, meanAttempts: number | null, failures: Record<string, number>, failureCount: number }>}
19
+ */
20
+ export function rollupReviews(lines) {
21
+ /** @type {Map<string, { reviewType: string, model: string, count: number, verdicts: Record<string, number>, attemptSum: number, attemptCount: number, failures: Record<string, number>, failureCount: number }>} */
22
+ const groups = new Map();
23
+ for (const line of lines) {
24
+ if (!line || typeof line !== "object" || line.recordType !== "review") continue;
25
+ const reviewType = typeof line.reviewType === "string" ? line.reviewType : "—";
26
+ const model = typeof line.model === "string" && line.model !== "" ? line.model : "inherit";
27
+ const key = `${reviewType}\u0000${model}`;
28
+ let group = groups.get(key);
29
+ if (!group) {
30
+ group = {
31
+ reviewType,
32
+ model,
33
+ count: 0,
34
+ verdicts: {},
35
+ attemptSum: 0,
36
+ attemptCount: 0,
37
+ failures: {},
38
+ failureCount: 0,
39
+ };
40
+ groups.set(key, group);
41
+ }
42
+ group.count += 1;
43
+ const isFailure = typeof line.outcome === "string" && line.outcome !== "verdict";
44
+ if (isFailure) {
45
+ group.failures[line.outcome] = (group.failures[line.outcome] ?? 0) + 1;
46
+ group.failureCount += 1;
47
+ } else {
48
+ const verdict = typeof line.verdict === "string" && line.verdict !== "" ? line.verdict : "—";
49
+ group.verdicts[verdict] = (group.verdicts[verdict] ?? 0) + 1;
50
+ if (Number.isFinite(line.attempt)) {
51
+ group.attemptSum += line.attempt;
52
+ group.attemptCount += 1;
53
+ }
54
+ }
55
+ }
56
+
57
+ const orderOf = (type) => {
58
+ const index = REVIEW_TYPE_ORDER.indexOf(type);
59
+ return index === -1 ? REVIEW_TYPE_ORDER.length : index;
60
+ };
61
+ return [...groups.values()]
62
+ .sort(
63
+ (a, b) =>
64
+ orderOf(a.reviewType) - orderOf(b.reviewType) ||
65
+ a.reviewType.localeCompare(b.reviewType) ||
66
+ a.model.localeCompare(b.model),
67
+ )
68
+ .map(({ attemptSum, attemptCount, ...group }) => ({
69
+ ...group,
70
+ meanAttempts: attemptCount > 0 ? attemptSum / attemptCount : null,
71
+ }));
72
+ }
73
+
74
+ /**
75
+ * @param {object[]} lines
76
+ * @returns {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object>, reviews: ReturnType<typeof rollupReviews> } | null}
15
77
  */
16
78
  export function rollupMetrics(lines) {
17
79
  /** @type {Record<string, Record<string, number>>} */
@@ -31,8 +93,9 @@ export function rollupMetrics(lines) {
31
93
  if (hitBatch || hitModel || hitRole) anyUsage = true;
32
94
  }
33
95
 
34
- if (!anyUsage) return null;
35
- return { byBatch, byModel, byRole };
96
+ const reviews = rollupReviews(lines);
97
+ if (!anyUsage && reviews.length === 0) return null;
98
+ return { byBatch, byModel, byRole, reviews };
36
99
  }
37
100
 
38
101
  /**
@@ -64,7 +127,7 @@ function addUsage(store, key, line) {
64
127
  /**
65
128
  * Format rollups as a short human-readable section with one table per grouping.
66
129
  *
67
- * @param {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object> }} rollups
130
+ * @param {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object>, reviews?: ReturnType<typeof rollupReviews> }} rollups
68
131
  * @returns {string}
69
132
  */
70
133
  export function formatMetricsRollups(rollups) {
@@ -74,12 +137,43 @@ export function formatMetricsRollups(rollups) {
74
137
  formatRollupTable("Usage by batch", rollups.byBatch),
75
138
  formatRollupTable("Usage by model", rollups.byModel),
76
139
  formatRollupTable("Usage by role", rollups.byRole),
140
+ formatReviewRollupTable(rollups.reviews),
77
141
  ];
78
142
  const body = sections.filter(Boolean).join("\n");
79
143
  if (!body) return "";
80
144
  return `\n${body}`;
81
145
  }
82
146
 
147
+ /**
148
+ * @param {ReturnType<typeof rollupReviews> | undefined} reviews
149
+ * @returns {string}
150
+ */
151
+ function formatReviewRollupTable(reviews) {
152
+ if (!Array.isArray(reviews) || reviews.length === 0) return "";
153
+
154
+ const header = ["Review", "Model", "Records", "Verdicts", "Mean Attempts", "Failures"];
155
+ const formatCounts = (counts) =>
156
+ Object.entries(counts)
157
+ .map(([name, count]) => `${name}=${count}`)
158
+ .join(" ") || "—";
159
+ const rows = reviews.map((group) => [
160
+ group.reviewType,
161
+ group.model,
162
+ String(group.count),
163
+ formatCounts(group.verdicts),
164
+ group.meanAttempts == null ? "—" : group.meanAttempts.toFixed(2),
165
+ group.failureCount > 0 ? formatCounts(group.failures) : "0",
166
+ ]);
167
+
168
+ const widths = header.map((col, index) =>
169
+ Math.max(col.length, ...rows.map((row) => String(row[index]).length)),
170
+ );
171
+ const formatRow = (row) =>
172
+ row.map((cell, index) => String(cell).padStart(widths[index])).join(" ");
173
+
174
+ return `Reviews by type and model:\n${[formatRow(header), ...rows.map(formatRow)].join("\n")}`;
175
+ }
176
+
83
177
  /**
84
178
  * @param {string} title
85
179
  * @param {Record<string, object>} groups
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
+ import { resolveReviewerModelPin, resolveReviewerThinkingPin } from "../config/agent-model-resolve.mjs";
9
10
  import { METRICS_DEFAULTS } from "../config/defaults.mjs";
10
11
  import { redactSecretsDeep } from "../util/secret-redact.mjs";
11
12
  import { readReviewLevel } from "./review.mjs";
@@ -13,6 +14,7 @@ import { readReviewLevel } from "./review.mjs";
13
14
  // Metrics additionally redacts prompt text (worker prompts may embed
14
15
  // secrets) while preserving usage counters for cost rollup.
15
16
  const METRICS_REDACT_KEY_PATTERN = /key|token|secret|password|prompt/i;
17
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
16
18
  const USAGE_KEYS = new Set(["tokensIn", "tokensOut", "estimatedUsd"]);
17
19
 
18
20
  /**
@@ -141,18 +143,16 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
141
143
  : typeof worker.model === "string"
142
144
  ? worker.model
143
145
  : "inherit",
144
- thinking:
145
- worker.thinking === "off" ||
146
- worker.thinking === "low" ||
147
- worker.thinking === "medium" ||
148
- worker.thinking === "high"
149
- ? worker.thinking
150
- : "high",
146
+ // SP-835 (#340): prefer the per-attempt pin (`**Thinking:**` / profile) over batch-start config.
147
+ thinking: [task.workerThinking, worker.thinking].find((level) => THINKING_LEVELS.includes(level)) ?? "high",
151
148
  startedAt: new Date(startedMs).toISOString(),
152
149
  endedAt: new Date(endedMs).toISOString(),
153
150
  outcome: resolveTaskMetricOutcome(task),
154
151
  };
155
152
 
153
+ if (typeof task.workerProfile === "string" && task.workerProfile !== "") {
154
+ record.profile = task.workerProfile;
155
+ }
156
156
  if (Number.isFinite(resolvedLaneNumber) && resolvedLaneNumber > 0) {
157
157
  record.laneNumber = resolvedLaneNumber;
158
158
  }
@@ -216,6 +216,126 @@ export function recordTaskTerminalMetric({
216
216
  return appendTaskMetric(projectRoot, record, config);
217
217
  }
218
218
 
219
+ /** Reviewer row outcomes: a recorded verdict, or why no verdict was produced. */
220
+ export const REVIEW_METRIC_OUTCOMES = Object.freeze([
221
+ "verdict",
222
+ "spawn_failed",
223
+ "timeout",
224
+ "provider_error",
225
+ "blocked",
226
+ ]);
227
+
228
+ /**
229
+ * Effective reviewer pins for a review type on the config the review ran with
230
+ * (`"inherit"` when the pin resolves to null).
231
+ *
232
+ * @param {object} config
233
+ * @param {"plan"|"code"|"final"} reviewType
234
+ * @returns {{ model: string, thinking: string }}
235
+ */
236
+ export function resolveReviewMetricPins(config, reviewType) {
237
+ return {
238
+ model: resolveReviewerModelPin(config, reviewType) ?? "inherit",
239
+ thinking: resolveReviewerThinkingPin(config, reviewType) ?? "inherit",
240
+ };
241
+ }
242
+
243
+ /**
244
+ * One `recordType: "review"` row per reviewer verdict or reviewer failure (SP-837 / #325).
245
+ *
246
+ * @param {object} params
247
+ * @param {string} params.batchId
248
+ * @param {string} params.taskId
249
+ * @param {number} [params.laneNumber]
250
+ * @param {"plan"|"code"|"final"} params.reviewType
251
+ * @param {number} [params.stepNumber] Plan/code review step (code/plan reviews are per task today).
252
+ * @param {string} [params.model]
253
+ * @param {string} [params.thinking]
254
+ * @param {string} [params.profile]
255
+ * @param {string} [params.verdict] Recorded verdict (APPROVE/PASS/REVISE/REPLAN) for `outcome: "verdict"`.
256
+ * @param {number} [params.attempt] 1-based review attempt index.
257
+ * @param {number} [params.durationMs]
258
+ * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
259
+ * @param {string} [params.failureReason]
260
+ * @param {number} [params.endedAtMs]
261
+ */
262
+ export function buildReviewMetricRecord({
263
+ batchId,
264
+ taskId,
265
+ laneNumber,
266
+ reviewType,
267
+ stepNumber,
268
+ model,
269
+ thinking,
270
+ profile,
271
+ verdict,
272
+ attempt,
273
+ durationMs,
274
+ outcome = "verdict",
275
+ failureReason,
276
+ endedAtMs = Date.now(),
277
+ }) {
278
+ /** @type {Record<string, unknown>} */
279
+ const record = {
280
+ recordType: "review",
281
+ schemaVersion: 1,
282
+ batchId,
283
+ taskId,
284
+ agentRole: "reviewer",
285
+ role: "reviewer",
286
+ reviewType,
287
+ model: typeof model === "string" && model !== "" ? model : "inherit",
288
+ thinking: THINKING_LEVELS.includes(/** @type {string} */ (thinking)) ? thinking : "inherit",
289
+ endedAt: new Date(endedAtMs).toISOString(),
290
+ outcome: REVIEW_METRIC_OUTCOMES.includes(outcome) ? outcome : "verdict",
291
+ };
292
+
293
+ if (Number.isFinite(laneNumber) && /** @type {number} */ (laneNumber) > 0) record.laneNumber = laneNumber;
294
+ if (Number.isFinite(stepNumber)) record.stepNumber = stepNumber;
295
+ if (typeof profile === "string" && profile !== "") record.profile = profile;
296
+ if (typeof verdict === "string" && verdict !== "") record.verdict = verdict;
297
+ if (Number.isFinite(attempt)) record.attempt = attempt;
298
+ if (Number.isFinite(durationMs)) record.durationMs = Math.max(0, /** @type {number} */ (durationMs));
299
+ if (typeof failureReason === "string" && failureReason !== "") record.failureReason = failureReason;
300
+
301
+ return sanitizeMetricRecord(record);
302
+ }
303
+
304
+ /**
305
+ * @param {string} projectRoot
306
+ * @param {object} record
307
+ * @param {object} [config]
308
+ */
309
+ export function appendReviewMetric(projectRoot, record, config = {}) {
310
+ return appendTaskMetric(projectRoot, record, config);
311
+ }
312
+
313
+ /**
314
+ * Build and append a reviewer row, resolving model/thinking from the pins on
315
+ * the config the review ran with. No-op when `metrics.enabled` is false.
316
+ *
317
+ * @param {object} params
318
+ * @param {string} params.projectRoot
319
+ * @param {object} [params.config] Per-task review config (effective reviewer pins).
320
+ * @param {"plan"|"code"|"final"} params.reviewType
321
+ * @param {string} params.batchId
322
+ * @param {string} params.taskId
323
+ * @param {number} [params.laneNumber]
324
+ * @param {number} [params.stepNumber]
325
+ * @param {string} [params.model] Overrides the config-resolved model.
326
+ * @param {string} [params.verdict]
327
+ * @param {number} [params.attempt]
328
+ * @param {number} [params.durationMs]
329
+ * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
330
+ * @param {string} [params.failureReason]
331
+ */
332
+ export function recordReviewMetric({ projectRoot, config = {}, model, ...rest }) {
333
+ if (!isMetricsEnabled(config)) return null;
334
+ const pins = resolveReviewMetricPins(config, rest.reviewType);
335
+ const record = buildReviewMetricRecord({ ...rest, model: model ?? pins.model, thinking: pins.thinking });
336
+ return appendReviewMetric(projectRoot, record, config);
337
+ }
338
+
219
339
  /**
220
340
  * @param {object} params
221
341
  * @param {string} params.batchId
@@ -322,10 +442,15 @@ export function formatMetricsTable(lines) {
322
442
 
323
443
  const header = ["Type", "Batch", "Task", "Outcome", "Diagnosis", "Ended"];
324
444
  const rows = lines.map((line) => [
325
- line.recordType ?? "—",
445
+ line.recordType === "review" && typeof line.reviewType === "string"
446
+ ? `review:${line.reviewType}`
447
+ : (line.recordType ?? "—"),
326
448
  line.batchId ?? "—",
327
449
  line.taskId ?? "—",
328
- line.outcome ?? line.diagnosis ?? "—",
450
+ (line.recordType === "review" && line.outcome === "verdict" ? line.verdict : null) ??
451
+ line.outcome ??
452
+ line.diagnosis ??
453
+ "—",
329
454
  line.diagnosis ?? "—",
330
455
  line.endedAt ?? "—",
331
456
  ]);
@@ -23,7 +23,7 @@ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
23
23
  * @property {ProviderQuotaKind} kind Why the output was classified.
24
24
  * @property {string} poolId Shared quota pool the model belongs to (`resolvePoolId`).
25
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.
26
+ * @property {string|null} providerCode z.ai `code`, Kimi/Anthropic `error.type`, or Google `error.status` of the matched rule, when matched.
27
27
  * @property {string|null} resetAtRaw Raw text after "reset at" in the provider message (z.ai), when present.
28
28
  * @property {null} resetAt Always null for now: the z.ai reset text carries no timezone (UTC+8 is inferred, not confirmed — #329).
29
29
  * @property {string} message Provider message string, truncated to 300 characters.
@@ -83,15 +83,49 @@ function extractBalancedObject(text, startIndex) {
83
83
  }
84
84
 
85
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.
86
+ * Matches the opening of an unprefixed provider error envelope: Google /
87
+ * OpenAI style `{"error":{...}}` and Anthropic style `{"type":"error",...}`.
88
+ * The key must be the object's first member so arbitrary objects embedded in
89
+ * logs do not qualify.
90
+ */
91
+ const BARE_ENVELOPE_PATTERN = /\{\s*"(?:error|type)"\s*:/g;
92
+
93
+ /** Anthropic SDK reports overload as HTTP 529; mid-stream SSE errors drop the prefix. */
94
+ const ANTHROPIC_OVERLOADED_STATUS = 529;
95
+
96
+ /**
97
+ * Derives the HTTP status of an unprefixed provider envelope, or null when
98
+ * the object is not a recognised provider error envelope (#351):
99
+ * - `{"error":{"code":<3-digit>,...}}` (Google) → `error.code`.
100
+ * - `{"type":"error","error":{"type":"overloaded_error",...}}` (Anthropic
101
+ * mid-stream SSE) → 529.
102
+ *
103
+ * @param {Record<string, any>} payload
104
+ * @returns {number|null}
105
+ */
106
+ function bareEnvelopeStatus(payload) {
107
+ const error = payload.error && typeof payload.error === "object" ? payload.error : null;
108
+ if (!error) return null;
109
+ if (Number.isInteger(error.code) && error.code >= 100 && error.code <= 999) return error.code;
110
+ if (payload.type === "error" && error.type === "overloaded_error") return ANTHROPIC_OVERLOADED_STATUS;
111
+ return null;
112
+ }
113
+
114
+ /**
115
+ * Collects every provider error JSON payload in the output, in order of
116
+ * appearance: status-prefixed payloads (`429 {...}`) plus unprefixed
117
+ * envelopes recognised by {@link bareEnvelopeStatus} (Google `ApiError`
118
+ * text, Anthropic mid-stream SSE). A bare envelope nested inside a
119
+ * status-prefixed payload is not collected separately. Fragments that do not
120
+ * parse as JSON objects are ignored — they are not provider payloads.
89
121
  *
90
122
  * @param {string} output
91
123
  * @returns {{httpStatus: number, payload: Record<string, any>}[]}
92
124
  */
93
125
  export function collectStatusPayloads(output) {
94
126
  const candidates = [];
127
+ /** @type {{start: number, end: number}[]} */
128
+ const prefixedRanges = [];
95
129
  STATUS_JSON_PATTERN.lastIndex = 0;
96
130
  let match;
97
131
  while ((match = STATUS_JSON_PATTERN.exec(output)) !== null) {
@@ -101,13 +135,35 @@ export function collectStatusPayloads(output) {
101
135
  try {
102
136
  const payload = JSON.parse(raw);
103
137
  if (payload && typeof payload === "object" && !Array.isArray(payload)) {
104
- candidates.push({ httpStatus: Number(match[1]), payload });
138
+ candidates.push({ httpStatus: Number(match[1]), payload, position: objectStart });
139
+ prefixedRanges.push({ start: objectStart, end: objectStart + raw.length });
105
140
  }
106
141
  } catch {
107
142
  // Malformed JSON is not a provider payload; keep scanning.
108
143
  }
109
144
  }
110
- return candidates;
145
+
146
+ BARE_ENVELOPE_PATTERN.lastIndex = 0;
147
+ while ((match = BARE_ENVELOPE_PATTERN.exec(output)) !== null) {
148
+ const objectStart = match.index;
149
+ if (prefixedRanges.some((range) => objectStart >= range.start && objectStart < range.end)) continue;
150
+ const raw = extractBalancedObject(output, objectStart);
151
+ if (raw === null) continue;
152
+ // Skip nested objects of this envelope whether or not it is accepted.
153
+ BARE_ENVELOPE_PATTERN.lastIndex = objectStart + raw.length;
154
+ try {
155
+ const payload = JSON.parse(raw);
156
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) continue;
157
+ const httpStatus = bareEnvelopeStatus(payload);
158
+ if (httpStatus !== null) candidates.push({ httpStatus, payload, position: objectStart });
159
+ } catch {
160
+ // Malformed JSON is not a provider payload; keep scanning.
161
+ }
162
+ }
163
+
164
+ // "Last payload wins" must hold across both passes: order by position.
165
+ candidates.sort((a, b) => a.position - b.position);
166
+ return candidates.map(({ httpStatus, payload }) => ({ httpStatus, payload }));
111
167
  }
112
168
 
113
169
  /**
@@ -124,6 +180,50 @@ function extractResetAtRaw(message) {
124
180
  return match[1].trim().replace(/[.!]+$/, "");
125
181
  }
126
182
 
183
+ /** Kimi's flat-body `type` for the weekly (7-day) usage limit (#367). */
184
+ const KIMI_WEEKLY_QUOTA_TYPE = "exceeded_current_quota_error";
185
+
186
+ /** Google retry hints below this many seconds mean a short (per-minute) window. */
187
+ const GOOGLE_TRANSIENT_RETRY_SECONDS = 120;
188
+
189
+ /**
190
+ * Parses a Google `RetryInfo.retryDelay` duration string such as `"34s"` or
191
+ * `"34.5s"` into seconds.
192
+ *
193
+ * @param {unknown} retryDelay
194
+ * @returns {number|null} Seconds, or null when absent or unparseable.
195
+ */
196
+ function parseRetryDelaySeconds(retryDelay) {
197
+ if (typeof retryDelay !== "string") return null;
198
+ const match = retryDelay.trim().match(/^(\d+(?:\.\d+)?)s$/);
199
+ return match ? Number(match[1]) : null;
200
+ }
201
+
202
+ /**
203
+ * Reads Google `error.details[]`: the `RetryInfo.retryDelay` string and
204
+ * whether any `QuotaFailure.violations[].quotaId` names a per-minute quota.
205
+ *
206
+ * @param {unknown} details
207
+ * @returns {{retryDelay: string|null, perMinute: boolean}}
208
+ */
209
+ function readGoogleQuotaDetails(details) {
210
+ let retryDelay = null;
211
+ let perMinute = false;
212
+ if (!Array.isArray(details)) return { retryDelay, perMinute };
213
+ for (const detail of details) {
214
+ if (!detail || typeof detail !== "object") continue;
215
+ const type = typeof detail["@type"] === "string" ? detail["@type"] : "";
216
+ if (type.endsWith("google.rpc.RetryInfo") && typeof detail.retryDelay === "string") {
217
+ retryDelay = detail.retryDelay;
218
+ } else if (type.endsWith("google.rpc.QuotaFailure") && Array.isArray(detail.violations)) {
219
+ for (const violation of detail.violations) {
220
+ if (typeof violation?.quotaId === "string" && violation.quotaId.includes("PerMinute")) perMinute = true;
221
+ }
222
+ }
223
+ }
224
+ return { retryDelay, perMinute };
225
+ }
226
+
127
227
  /**
128
228
  * Applies the classification rules to a single payload. The HTTP status is
129
229
  * part of every rule so unrelated 4xx/5xx output never matches; a payload
@@ -132,10 +232,19 @@ function extractResetAtRaw(message) {
132
232
  * Rules (#329):
133
233
  * - z.ai 429, top-level `code` "1308" (5-hour window) or "1310"
134
234
  * (weekly/monthly) → quota_exhausted.
235
+ * - Kimi 429, flat top-level `type` "exceeded_current_quota_error"
236
+ * (weekly 7-day limit) → quota_exhausted (#367).
135
237
  * - Kimi 403, `error.type` "permission_error", message mentions
136
238
  * "usage limit" (billing-cycle exhaustion) → quota_exhausted.
137
239
  * - Kimi 429, `error.type` "rate_limit_error", message mentions
138
240
  * "currently overloaded" → transient_overload.
241
+ * - Google 429, `error.code` 429 + `error.status` "RESOURCE_EXHAUSTED" →
242
+ * transient_overload when a `QuotaFailure` quotaId contains "PerMinute" or
243
+ * `RetryInfo.retryDelay` < 120 s, else quota_exhausted (#351).
244
+ * - Anthropic 529 (or unprefixed SSE) `overloaded_error` → transient_overload;
245
+ * 429 `rate_limit_error` (not Kimi's "currently overloaded") →
246
+ * transient_overload; 400 `invalid_request_error` "credit balance is too
247
+ * low" → quota_exhausted (#351).
139
248
  *
140
249
  * @param {number} httpStatus
141
250
  * @param {Record<string, any>} payload
@@ -153,6 +262,20 @@ function classifyPayload(httpStatus, payload) {
153
262
  };
154
263
  }
155
264
 
265
+ // Kimi weekly (7-day) limit: flat `{"message":"...","type":"exceeded_current_quota_error"}` (#367).
266
+ if (
267
+ httpStatus === 429 &&
268
+ payload.type === KIMI_WEEKLY_QUOTA_TYPE &&
269
+ typeof payload.message === "string"
270
+ ) {
271
+ return {
272
+ kind: "quota_exhausted",
273
+ providerCode: KIMI_WEEKLY_QUOTA_TYPE,
274
+ resetAtRaw: null,
275
+ message: truncateMessage(payload.message),
276
+ };
277
+ }
278
+
156
279
  // Kimi: nested error envelope `{"error":{"type":...,"message":...}}`.
157
280
  const error = payload.error && typeof payload.error === "object" ? payload.error : null;
158
281
  const errorMessage = typeof error?.message === "string" ? error.message : null;
@@ -182,6 +305,51 @@ function classifyPayload(httpStatus, payload) {
182
305
  message: truncateMessage(errorMessage),
183
306
  };
184
307
  }
308
+
309
+ // Google: `{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[...]}}`.
310
+ if (httpStatus === 429 && error.code === 429 && error.status === "RESOURCE_EXHAUSTED") {
311
+ const { retryDelay, perMinute } = readGoogleQuotaDetails(error.details);
312
+ const retrySeconds = parseRetryDelaySeconds(retryDelay);
313
+ const transient = perMinute || (retrySeconds !== null && retrySeconds < GOOGLE_TRANSIENT_RETRY_SECONDS);
314
+ return {
315
+ kind: transient ? "transient_overload" : "quota_exhausted",
316
+ providerCode: "RESOURCE_EXHAUSTED",
317
+ resetAtRaw: retryDelay !== null ? `retry in ${retryDelay}` : null,
318
+ message: truncateMessage(errorMessage),
319
+ };
320
+ }
321
+
322
+ // Anthropic: `{"type":"error","error":{"type":...,"message":...}}`.
323
+ if (httpStatus === ANTHROPIC_OVERLOADED_STATUS && error.type === "overloaded_error") {
324
+ return {
325
+ kind: "transient_overload",
326
+ providerCode: "overloaded_error",
327
+ resetAtRaw: null,
328
+ message: truncateMessage(errorMessage),
329
+ };
330
+ }
331
+ if (httpStatus === 429 && error.type === "rate_limit_error") {
332
+ // Kimi's "currently overloaded" wording is handled (first) above; any
333
+ // other rate_limit_error is Anthropic's per-minute limit.
334
+ return {
335
+ kind: "transient_overload",
336
+ providerCode: "rate_limit_error",
337
+ resetAtRaw: null,
338
+ message: truncateMessage(errorMessage),
339
+ };
340
+ }
341
+ if (
342
+ httpStatus === 400 &&
343
+ error.type === "invalid_request_error" &&
344
+ errorMessage.toLowerCase().includes("credit balance is too low")
345
+ ) {
346
+ return {
347
+ kind: "quota_exhausted",
348
+ providerCode: "credit_balance_too_low",
349
+ resetAtRaw: null,
350
+ message: truncateMessage(errorMessage),
351
+ };
352
+ }
185
353
  return null;
186
354
  }
187
355