pi-spine 2.26.0 → 2.27.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.
- package/README.md +1 -1
- package/bin/spine-review-step.mjs +8 -1
- package/bin/spine-worker-runner.mjs +15 -1
- package/package.json +3 -3
- package/skills/create-spine-tasks/SKILL.md +60 -33
- package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
- package/skills/create-spine-tasks/references/contract-template.md +52 -7
- package/skills/create-spine-tasks/references/prompt-template.md +72 -8
- package/skills/spine-release-operator/SKILL.md +33 -51
- package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
- package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
- package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
- package/skills/spine-release-operator/references/publish-recovery.md +62 -0
- package/src/batch/batch-meta-reconstruct.mjs +3 -0
- package/src/batch/contract-exec.mjs +2 -2
- package/src/batch/contract-parse.mjs +2 -2
- package/src/batch/contract-prelanded.mjs +2 -2
- package/src/batch/diagnosis-alternatives.mjs +16 -1
- package/src/batch/diagnosis-handoff-packet.mjs +74 -0
- package/src/batch/diagnosis-pending-lane.mjs +52 -1
- package/src/batch/diagnosis-review-infra.mjs +144 -0
- package/src/batch/diagnosis-suggested-command.mjs +9 -0
- package/src/batch/diagnosis.mjs +19 -20
- package/src/batch/engine-lanes/merge.mjs +0 -8
- package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
- package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
- package/src/batch/engine-lanes/review-code.mjs +1 -0
- package/src/batch/engine-lanes/review-final.mjs +83 -46
- package/src/batch/engine-lanes/review-plan.mjs +22 -2
- package/src/batch/engine-lanes/review-poll.mjs +51 -2
- package/src/batch/engine-lanes.mjs +6 -8
- package/src/batch/gate-posture-approve.mjs +154 -15
- package/src/batch/integrate-path-delete.mjs +85 -0
- package/src/batch/integrate-worktree.mjs +20 -27
- package/src/batch/journal.mjs +15 -0
- package/src/batch/metrics.mjs +13 -1
- package/src/batch/provider-quota.mjs +220 -0
- package/src/batch/quota-fallback.mjs +319 -0
- package/src/batch/reconcile-diagnosis-context.mjs +22 -0
- package/src/batch/reconcile-diagnosis.mjs +24 -77
- package/src/batch/resume-multi-queue.mjs +25 -10
- package/src/batch/review-artifacts.mjs +96 -17
- package/src/batch/review-level-effective.mjs +19 -0
- package/src/batch/review-spawn-retry.mjs +106 -0
- package/src/batch/review-spawn.mjs +60 -3
- package/src/batch/review-step-run.mjs +110 -8
- package/src/batch/reviewer-output.mjs +162 -0
- package/src/batch/reviewer-provider-error.mjs +153 -0
- package/src/batch/worker-host.mjs +49 -3
- package/src/batch/worker-prompt.mjs +5 -2
- package/src/config/cursor-rules/discover.mjs +40 -3
- package/src/config/cursor-rules/match-globs.mjs +6 -4
- package/src/config/env-overrides.mjs +41 -4
- package/src/config/settings-fields.mjs +11 -0
- package/src/config/spine-config-schema.mjs +62 -0
- package/src/doctor/pi-extension-hooks.mjs +322 -0
- package/src/doctor/quota-risk.mjs +45 -0
- package/src/doctor/run-doctor-checks.mjs +14 -1
- package/src/planner/file-scope.mjs +6 -6
- package/src/tasks/packet/validate-contract.mjs +3 -3
- package/src/tasks/packet/validate-prompt.mjs +11 -1
- package/src/tasks/validate-contract-warn.mjs +16 -0
- package/templates/spine-config.json +1 -1
|
@@ -9,9 +9,10 @@ import path from "node:path";
|
|
|
9
9
|
import { execFileSync } from "node:child_process";
|
|
10
10
|
import { gitExec } from "./git-exec.mjs";
|
|
11
11
|
import { resolveGitCommitEnv } from "./git-commit-env.mjs";
|
|
12
|
-
import {
|
|
12
|
+
import { tryAutoResolveMergeConflicts } from "./engine-lanes/merge.mjs";
|
|
13
13
|
import { appendJournalEvent } from "./journal.mjs";
|
|
14
14
|
import { listIntegrateDirtyPaths } from "./rules-manifest-drift.mjs";
|
|
15
|
+
import { isTimeoutError, removeMergeDeletedPath } from "./integrate-path-delete.mjs";
|
|
15
16
|
|
|
16
17
|
export const DEFAULT_SYNC_TIMEOUT_MS = 60_000;
|
|
17
18
|
|
|
@@ -215,13 +216,9 @@ export function plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch,
|
|
|
215
216
|
return { ok: true, mergeCommit, mode: "plumbing" };
|
|
216
217
|
}
|
|
217
218
|
|
|
218
|
-
/**
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
*/
|
|
222
|
-
function isTimeoutError(err) {
|
|
223
|
-
if (!err || typeof err !== "object") return false;
|
|
224
|
-
return /** @type {any} */ (err).killed === true || /** @type {any} */ (err).code === "ETIMEDOUT";
|
|
219
|
+
/** Shared timed-out result for the sync loop's git calls. */
|
|
220
|
+
function timeoutSyncResult(error, processedCount, totalPaths) {
|
|
221
|
+
return { ok: false, timedOut: true, error, processedPaths: processedCount, totalPaths: totalPaths };
|
|
225
222
|
}
|
|
226
223
|
|
|
227
224
|
/**
|
|
@@ -289,10 +286,10 @@ function pathExistsInTree(cwd, treeRef, filePath, { timeoutMs } = {}) {
|
|
|
289
286
|
* @param {string} projectRoot
|
|
290
287
|
* @param {string} baseSha
|
|
291
288
|
* @param {string} mergeCommit
|
|
292
|
-
* @param {{ timeoutMs?: number, dirtyPaths?: string[] }} [options]
|
|
289
|
+
* @param {{ timeoutMs?: number, dirtyPaths?: string[], applyDeletions?: boolean }} [options]
|
|
293
290
|
* @returns {{ ok: boolean, timedOut?: boolean, error?: string, processedPaths?: number, totalPaths?: number, skippedDirtyPaths?: string[] }}
|
|
294
291
|
*/
|
|
295
|
-
export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, { timeoutMs = DEFAULT_SYNC_TIMEOUT_MS, dirtyPaths } = {}) {
|
|
292
|
+
export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, { timeoutMs = DEFAULT_SYNC_TIMEOUT_MS, dirtyPaths, applyDeletions } = {}) {
|
|
296
293
|
const envTimeoutMs = process.env.SPINE_SYNC_TIMEOUT_MS
|
|
297
294
|
? Number(process.env.SPINE_SYNC_TIMEOUT_MS)
|
|
298
295
|
: null;
|
|
@@ -329,18 +326,20 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
|
|
|
329
326
|
pathExistsInTree(projectRoot, baseSha, filePath, { timeoutMs: effectiveTimeout });
|
|
330
327
|
} catch (err) {
|
|
331
328
|
if (isTimeoutError(err)) {
|
|
332
|
-
return {
|
|
333
|
-
ok: false,
|
|
334
|
-
timedOut: true,
|
|
335
|
-
error: `git cat-file timed out for ${filePath} after ${effectiveTimeout}ms`,
|
|
336
|
-
processedPaths: processedCount,
|
|
337
|
-
totalPaths: paths.length,
|
|
338
|
-
};
|
|
329
|
+
return timeoutSyncResult(`git cat-file timed out for ${filePath} after ${effectiveTimeout}ms`, processedCount, paths.length);
|
|
339
330
|
}
|
|
340
331
|
existsInMerge = false;
|
|
341
332
|
}
|
|
342
333
|
|
|
343
334
|
if (!existsInMerge) {
|
|
335
|
+
if (applyDeletions) {
|
|
336
|
+
try {
|
|
337
|
+
if (removeMergeDeletedPath(projectRoot, baseSha, filePath, { timeoutMs: effectiveTimeout }).removed) processedCount++;
|
|
338
|
+
else if (dirtyPathSet.has(filePath) && operatorTouched) skippedDirtyPaths.push(filePath);
|
|
339
|
+
} catch (err) {
|
|
340
|
+
if (isTimeoutError(err)) return timeoutSyncResult(`git rm timed out for ${filePath} after ${effectiveTimeout}ms`, processedCount, paths.length);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
344
343
|
debugSyncLog(
|
|
345
344
|
`syncPlumbingMergePathsToWorktree: skip ${filePath} — not present in merge commit ${mergeCommit}`,
|
|
346
345
|
);
|
|
@@ -360,13 +359,7 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
|
|
|
360
359
|
);
|
|
361
360
|
} catch (err) {
|
|
362
361
|
if (isTimeoutError(err)) {
|
|
363
|
-
return {
|
|
364
|
-
ok: false,
|
|
365
|
-
timedOut: true,
|
|
366
|
-
error: `git restore timed out for ${filePath} after ${effectiveTimeout}ms`,
|
|
367
|
-
processedPaths: processedCount,
|
|
368
|
-
totalPaths: paths.length,
|
|
369
|
-
};
|
|
362
|
+
return timeoutSyncResult(`git restore timed out for ${filePath} after ${effectiveTimeout}ms`, processedCount, paths.length);
|
|
370
363
|
}
|
|
371
364
|
if (isPathspecMismatchError(err)) {
|
|
372
365
|
debugSyncLog(
|
|
@@ -404,11 +397,11 @@ export function syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha,
|
|
|
404
397
|
export function syncMergeResultToCheckedOutBase(projectRoot, baseBranch, mergeResult, options) {
|
|
405
398
|
const { mode, mergeCommit } = mergeResult;
|
|
406
399
|
if (mode === "fast-forward") {
|
|
407
|
-
return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, mergeResult.baseShaBefore, mergeCommit, options);
|
|
400
|
+
return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, mergeResult.baseShaBefore, mergeCommit, { ...options, applyDeletions: true });
|
|
408
401
|
}
|
|
409
402
|
if (mode === "plumbing") {
|
|
410
403
|
const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
|
|
411
|
-
return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha, mergeCommit, options);
|
|
404
|
+
return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha, mergeCommit, { ...options, applyDeletions: true });
|
|
412
405
|
}
|
|
413
406
|
return null;
|
|
414
407
|
}
|
|
@@ -429,7 +422,7 @@ function mergeInIntegrateWorktree({ projectRoot, worktreePath, baseBranch, orchB
|
|
|
429
422
|
try {
|
|
430
423
|
git(worktreePath, ["merge", "--no-ff", orchBranch, "-m", mergeMessage]);
|
|
431
424
|
} catch {
|
|
432
|
-
const autoResolved =
|
|
425
|
+
const autoResolved = tryAutoResolveMergeConflicts(worktreePath, {});
|
|
433
426
|
if (!autoResolved.ok) {
|
|
434
427
|
try {
|
|
435
428
|
execFileSync("git", ["merge", "--abort"], {
|
package/src/batch/journal.mjs
CHANGED
|
@@ -348,6 +348,17 @@ export function summarizeJournalEvent(event) {
|
|
|
348
348
|
if (payload.reason) parts.push(String(payload.reason));
|
|
349
349
|
if (payload.error) parts.push(String(payload.error).slice(0, 80));
|
|
350
350
|
if (payload.classification) parts.push(String(payload.classification));
|
|
351
|
+
// SP-810 (partial #329): quota-fallback fields operators act on.
|
|
352
|
+
if (payload.fromProfile && payload.toProfile) parts.push(`${payload.fromProfile} → ${payload.toProfile}`);
|
|
353
|
+
if (payload.poolId) parts.push(`pool ${payload.poolId}`);
|
|
354
|
+
if (Array.isArray(payload.exhaustedPools) && payload.exhaustedPools.length > 0) parts.push(`exhausted: ${payload.exhaustedPools.join(", ")}`);
|
|
355
|
+
const quotaReset = payload.resetAtRaw;
|
|
356
|
+
if (typeof quotaReset === "string" && quotaReset) {
|
|
357
|
+
parts.push(`resets ${quotaReset}`);
|
|
358
|
+
} else if (Array.isArray(quotaReset) && quotaReset.length > 0) {
|
|
359
|
+
parts.push(`resets ${quotaReset.map((reset) => reset ?? "unknown").join(" / ")}`);
|
|
360
|
+
}
|
|
361
|
+
if (Array.isArray(payload.taskIds) && payload.taskIds.length > 0) parts.push(`task(s): ${payload.taskIds.join(", ")}`);
|
|
351
362
|
if (payload.workerPhase) parts.push(`phase ${payload.workerPhase}`);
|
|
352
363
|
if (payload.dirtyPathCount != null && event.type === "lane.progress_snapshot") {
|
|
353
364
|
parts.push(`${payload.dirtyPathCount} dirty path(s)`);
|
|
@@ -428,6 +439,10 @@ export function extractJournalDiagnosisHints(events) {
|
|
|
428
439
|
"batch.merge_blocked",
|
|
429
440
|
"task.failed",
|
|
430
441
|
"matrix.task_failed",
|
|
442
|
+
// SP-810 (partial #329): quota events decide retry-vs-wait — rank with failures.
|
|
443
|
+
"batch.quota_fallback_applied",
|
|
444
|
+
"batch.quota_fallback_exhausted",
|
|
445
|
+
"worker.quota_exhausted",
|
|
431
446
|
"review.crash_recovered",
|
|
432
447
|
"review.skipped_fresh_artifact",
|
|
433
448
|
"review.resumed",
|
package/src/batch/metrics.mjs
CHANGED
|
@@ -133,7 +133,14 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
|
|
|
133
133
|
batchId,
|
|
134
134
|
taskId: task.taskId,
|
|
135
135
|
agentRole: "worker",
|
|
136
|
-
|
|
136
|
+
// SP-808 (#329): SP-809 pins task.workerModel to the model actually used
|
|
137
|
+
// (fallback profile after a hop); prefer it over the batch-start config.
|
|
138
|
+
model:
|
|
139
|
+
typeof task.workerModel === "string" && task.workerModel !== ""
|
|
140
|
+
? task.workerModel
|
|
141
|
+
: typeof worker.model === "string"
|
|
142
|
+
? worker.model
|
|
143
|
+
: "inherit",
|
|
137
144
|
thinking:
|
|
138
145
|
worker.thinking === "off" ||
|
|
139
146
|
worker.thinking === "low" ||
|
|
@@ -155,6 +162,11 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
|
|
|
155
162
|
if (task.exitReason) record.exitReason = task.exitReason;
|
|
156
163
|
if (task.exitReason === "contract_failed") record.failureKind = "contract";
|
|
157
164
|
if (task.exitReason === "review_exhausted") record.failureKind = "reviewer";
|
|
165
|
+
// SP-806 (#329): provider quota/overload exits carry their own failure kind
|
|
166
|
+
// so doctor quota-risk signals can fire on run-metrics without extra config.
|
|
167
|
+
if (task.exitReason === "provider_quota_exhausted" || task.exitReason === "provider_overloaded") {
|
|
168
|
+
record.failureKind = "quota";
|
|
169
|
+
}
|
|
158
170
|
if (reviewLevel > 0) record.reviewLevel = reviewLevel;
|
|
159
171
|
if (task.finalVerdict != null) record.finalVerdict = task.finalVerdict;
|
|
160
172
|
if (task.finalAttempts != null) record.finalAttempts = task.finalAttempts;
|
|
@@ -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
|
+
export 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
|
+
}
|