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.
- package/bin/spine-batch.mjs +46 -4
- package/bin/spine-cli/cli-args.mjs +117 -0
- package/bin/spine-gate.mjs +28 -21
- package/bin/spine-integrate.mjs +28 -7
- package/bin/spine-issue.mjs +2 -1
- package/bin/spine-settings.mjs +7 -9
- package/bin/spine-tasks.mjs +1 -0
- package/bin/spine-worker-runner.mjs +21 -8
- package/bin/spine.mjs +10 -3
- package/package.json +1 -1
- package/skills/create-spine-tasks/references/prompt-template.md +5 -0
- package/skills/spine-release-operator/SKILL.md +14 -2
- package/src/batch/contract-exec.mjs +2 -3
- package/src/batch/contract-task-start.mjs +23 -1
- package/src/batch/diagnosis-handoff-packet.mjs +18 -0
- package/src/batch/diagnosis-primary-failure.mjs +35 -0
- package/src/batch/engine-lanes/matrix-run.mjs +2 -0
- package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
- package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
- package/src/batch/engine-lanes/review-code.mjs +20 -0
- package/src/batch/engine-lanes/review-final.mjs +10 -2
- package/src/batch/engine-lanes/review-poll.mjs +33 -0
- package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
- package/src/batch/engine-lanes.mjs +18 -17
- package/src/batch/evidence-command.mjs +18 -21
- package/src/batch/evidence-exec.mjs +79 -0
- package/src/batch/journal.mjs +5 -3
- package/src/batch/metrics-rollup.mjs +98 -4
- package/src/batch/metrics.mjs +134 -9
- package/src/batch/provider-quota.mjs +174 -6
- package/src/batch/quota-fallback.mjs +87 -6
- package/src/batch/reconcile-classify.mjs +28 -1
- package/src/batch/reconcile-diagnosis-context.mjs +2 -0
- package/src/batch/resume-lane-reviews.mjs +11 -10
- package/src/batch/retry-profile.mjs +77 -0
- package/src/batch/retry.mjs +32 -1
- package/src/batch/review-step-run.mjs +4 -0
- package/src/batch/review-step.mjs +1 -0
- package/src/batch/sequence-wait.mjs +7 -5
- package/src/batch/state-io.mjs +29 -3
- package/src/batch/worker-heartbeat.mjs +10 -2
- package/src/batch/worker-host.mjs +1 -1
- package/src/batch/worker-prompt.mjs +4 -5
- package/src/cli/deps.mjs +3 -2
- package/src/config/agent-model-resolve.mjs +144 -8
- package/src/config/contract.mjs +20 -0
- package/src/config/model-family.mjs +60 -0
- package/src/config/preflight/discovery.mjs +1 -0
- package/src/config/settings-fields.mjs +15 -0
- package/src/config/spine-config-schema.mjs +49 -0
- package/src/doctor/agent-model-inherit.mjs +78 -1
- package/src/doctor/agent-template-drift.mjs +65 -0
- package/src/doctor/run-doctor-checks.mjs +8 -1
- package/src/doctor/stet-capacity.mjs +171 -0
- package/src/metrics/quota-cli.mjs +16 -0
- package/src/metrics/quota-probes.mjs +228 -31
- package/src/metrics/quota-snapshot.mjs +21 -2
- package/src/planner/graph.mjs +7 -5
- package/src/planner/pending.mjs +2 -2
- package/src/planner/scope.mjs +3 -3
- package/src/tasks/packet/parse-prompt.mjs +47 -0
- package/src/tasks/packet/validate-prompt.mjs +156 -1
- package/templates/agents/reviewer.md +3 -1
- package/templates/agents/worker.md +15 -19
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Advisory host-capacity preflight for stet-backed contract review. Local LLM
|
|
3
|
+
* review competes with batch workers for RAM; the v2.28 release stalled when a
|
|
4
|
+
* second stet session and a 16 GB model ran with swap nearly exhausted.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { execFileSync } from "node:child_process";
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
|
|
11
|
+
const PROBE_TIMEOUT_MS = 3000;
|
|
12
|
+
const BYTES_PER_MIB = 1024 * 1024;
|
|
13
|
+
export const SWAP_FREE_WARN_BYTES = 2 * 1024 * BYTES_PER_MIB;
|
|
14
|
+
/** Loaded local-model bytes above this share of physical RAM leave too little for lanes. */
|
|
15
|
+
export const LOADED_MODEL_RAM_SHARE_WARN = 0.5;
|
|
16
|
+
|
|
17
|
+
const STET_SESSION_PATTERN = "stet (start|run|rerun)( |$)";
|
|
18
|
+
const SPINE_BATCH_PATTERN = "spine(\\.mjs)? batch (start|resume)";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {string} file
|
|
22
|
+
* @param {string[]} args
|
|
23
|
+
* @param {number|null} [emptyExitStatus] Exit status meaning "ran fine, no results".
|
|
24
|
+
* @returns {string|null} stdout, or null when the probe is unavailable.
|
|
25
|
+
*/
|
|
26
|
+
function tryExec(file, args, emptyExitStatus = null) {
|
|
27
|
+
try {
|
|
28
|
+
return execFileSync(file, args, {
|
|
29
|
+
encoding: "utf-8",
|
|
30
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
31
|
+
timeout: PROBE_TIMEOUT_MS,
|
|
32
|
+
});
|
|
33
|
+
} catch (err) {
|
|
34
|
+
const status = err && typeof err === "object" && "status" in err ? err.status : null;
|
|
35
|
+
return emptyExitStatus !== null && status === emptyExitStatus ? "" : null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @param {string} pattern @returns {number[]|null} */
|
|
40
|
+
function pgrepPids(pattern) {
|
|
41
|
+
const PGREP_NO_MATCH_STATUS = 1;
|
|
42
|
+
const out = tryExec("pgrep", ["-f", pattern], PGREP_NO_MATCH_STATUS);
|
|
43
|
+
if (out === null) return null;
|
|
44
|
+
return out
|
|
45
|
+
.split("\n")
|
|
46
|
+
.map((line) => Number.parseInt(line, 10))
|
|
47
|
+
.filter((pid) => Number.isInteger(pid) && pid !== process.pid);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {string} text `sysctl vm.swapusage` output
|
|
52
|
+
* @returns {number|null}
|
|
53
|
+
*/
|
|
54
|
+
export function parseDarwinSwapFreeBytes(text) {
|
|
55
|
+
const match = /free\s*=\s*([\d.]+)M/.exec(text);
|
|
56
|
+
return match ? Math.round(Number.parseFloat(match[1]) * BYTES_PER_MIB) : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {string} text /proc/meminfo contents
|
|
61
|
+
* @returns {number|null} null when the host has no swap configured.
|
|
62
|
+
*/
|
|
63
|
+
export function parseLinuxSwapFreeBytes(text) {
|
|
64
|
+
const total = /^SwapTotal:\s+(\d+) kB/m.exec(text);
|
|
65
|
+
const free = /^SwapFree:\s+(\d+) kB/m.exec(text);
|
|
66
|
+
if (!total || !free || Number(total[1]) === 0) return null;
|
|
67
|
+
return Number(free[1]) * 1024;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @returns {number|null} */
|
|
71
|
+
function probeSwapFreeBytes() {
|
|
72
|
+
if (process.platform === "darwin") {
|
|
73
|
+
const out = tryExec("sysctl", ["vm.swapusage"]);
|
|
74
|
+
return out === null ? null : parseDarwinSwapFreeBytes(out);
|
|
75
|
+
}
|
|
76
|
+
if (process.platform === "linux") {
|
|
77
|
+
try {
|
|
78
|
+
return parseLinuxSwapFreeBytes(fs.readFileSync("/proc/meminfo", "utf-8"));
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @param {string} text `lms ps --json` output
|
|
88
|
+
* @returns {{ id: string, sizeBytes: number }[]|null}
|
|
89
|
+
*/
|
|
90
|
+
export function parseLmsLoadedModels(text) {
|
|
91
|
+
try {
|
|
92
|
+
const parsed = JSON.parse(text);
|
|
93
|
+
if (!Array.isArray(parsed)) return null;
|
|
94
|
+
return parsed
|
|
95
|
+
.filter((m) => m && typeof m.sizeBytes === "number")
|
|
96
|
+
.map((m) => ({ id: String(m.identifier ?? m.modelKey ?? "unknown"), sizeBytes: m.sizeBytes }));
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @returns {{ id: string, sizeBytes: number }[]|null} */
|
|
103
|
+
function probeLoadedModels() {
|
|
104
|
+
const out = tryExec("lms", ["ps", "--json"]);
|
|
105
|
+
return out === null ? null : parseLmsLoadedModels(out);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const DEFAULT_STET_CAPACITY_PROBES = {
|
|
109
|
+
stetOnPath: () => tryExec("stet", ["--version"]) !== null,
|
|
110
|
+
stetSessionPids: () => pgrepPids(STET_SESSION_PATTERN),
|
|
111
|
+
spineBatchPids: () => pgrepPids(SPINE_BATCH_PATTERN),
|
|
112
|
+
swapFreeBytes: probeSwapFreeBytes,
|
|
113
|
+
loadedModels: probeLoadedModels,
|
|
114
|
+
totalMemBytes: () => os.totalmem(),
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/** @param {number} bytes */
|
|
118
|
+
const gib = (bytes) => `${(bytes / (1024 * BYTES_PER_MIB)).toFixed(1)} GiB`;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* @param {{ probes?: Partial<typeof DEFAULT_STET_CAPACITY_PROBES> }} [opts]
|
|
122
|
+
*/
|
|
123
|
+
export function buildStetCapacityDoctorCheck(opts = {}) {
|
|
124
|
+
const probes = { ...DEFAULT_STET_CAPACITY_PROBES, ...opts.probes };
|
|
125
|
+
const label = "stet review capacity";
|
|
126
|
+
if (!probes.stetOnPath()) {
|
|
127
|
+
return { label, ok: true, detail: "stet not on PATH (skipped)" };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** @type {string[]} */
|
|
131
|
+
const warnings = [];
|
|
132
|
+
/** @type {string[]} */
|
|
133
|
+
const unknown = [];
|
|
134
|
+
|
|
135
|
+
const stetPids = probes.stetSessionPids();
|
|
136
|
+
if (stetPids === null) unknown.push("stet processes");
|
|
137
|
+
else if (stetPids.length > 0) warnings.push(`stet review already running (pid ${stetPids.join(", ")})`);
|
|
138
|
+
|
|
139
|
+
const batchPids = probes.spineBatchPids();
|
|
140
|
+
if (batchPids === null) unknown.push("spine batches");
|
|
141
|
+
else if (batchPids.length > 0) warnings.push(`other spine batch running (pid ${batchPids.join(", ")})`);
|
|
142
|
+
|
|
143
|
+
const swapFree = probes.swapFreeBytes();
|
|
144
|
+
if (swapFree !== null && swapFree < SWAP_FREE_WARN_BYTES) {
|
|
145
|
+
warnings.push(`swap nearly exhausted (${gib(swapFree)} free)`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const models = probes.loadedModels();
|
|
149
|
+
if (models === null) {
|
|
150
|
+
unknown.push("LM Studio models");
|
|
151
|
+
} else {
|
|
152
|
+
const loadedBytes = models.reduce((sum, m) => sum + m.sizeBytes, 0);
|
|
153
|
+
const totalMem = probes.totalMemBytes();
|
|
154
|
+
if (loadedBytes > totalMem * LOADED_MODEL_RAM_SHARE_WARN) {
|
|
155
|
+
const ids = models.map((m) => m.id).join(", ");
|
|
156
|
+
warnings.push(`LM Studio models use ${gib(loadedBytes)} of ${gib(totalMem)} RAM (${ids})`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const unknownNote = unknown.length > 0 ? `; not probed: ${unknown.join(", ")}` : "";
|
|
161
|
+
if (warnings.length === 0) {
|
|
162
|
+
return { label, ok: true, detail: `host has headroom for stet review${unknownNote}` };
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
label,
|
|
166
|
+
ok: true,
|
|
167
|
+
warning: true,
|
|
168
|
+
detail: `${warnings.join("; ")}${unknownNote}`,
|
|
169
|
+
suggestedCommand: "lms unload --all # or wait for the other stet/spine run to finish",
|
|
170
|
+
};
|
|
171
|
+
}
|
|
@@ -32,6 +32,18 @@ function formatReportFilename(now) {
|
|
|
32
32
|
return `quota-snapshot-${iso}.json`;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Format one quota window as `5h 63% (resets 2026-10-15T06:28:41Z)`.
|
|
37
|
+
*
|
|
38
|
+
* @param {import("./quota-probes.mjs").QuotaWindow} win
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
function formatWindow(win) {
|
|
42
|
+
let text = `${win.window} ${Math.round(win.percentUsed)}%`;
|
|
43
|
+
if (win.resetAt) text += ` (resets ${win.resetAt.replace(/\.\d+Z$/, "Z")})`;
|
|
44
|
+
return text;
|
|
45
|
+
}
|
|
46
|
+
|
|
35
47
|
/**
|
|
36
48
|
* Format a short human-readable summary of the snapshot.
|
|
37
49
|
*
|
|
@@ -55,11 +67,15 @@ function formatHumanSummary(snapshot, reportPath) {
|
|
|
55
67
|
for (const pool of pools) {
|
|
56
68
|
const usage = pool.usage;
|
|
57
69
|
const parts = [`${pool.poolId}: ${usage.taskCount} tasks`];
|
|
70
|
+
if (usage.reviewCount) parts.push(`${usage.reviewCount} reviews`);
|
|
58
71
|
if (usage.durationMs > 0) parts.push(`${usage.durationMs}ms`);
|
|
59
72
|
if (usage.tokensIn) parts.push(`${usage.tokensIn} in-tokens`);
|
|
60
73
|
if (usage.tokensOut) parts.push(`${usage.tokensOut} out-tokens`);
|
|
61
74
|
if (usage.estimatedUsd) parts.push(`$${usage.estimatedUsd.toFixed(4)} est`);
|
|
62
75
|
lines.push(` ${parts.join(", ")}`);
|
|
76
|
+
for (const win of pool.windows ?? []) {
|
|
77
|
+
lines.push(` ${formatWindow(win)}`);
|
|
78
|
+
}
|
|
63
79
|
}
|
|
64
80
|
|
|
65
81
|
if (reportPath) {
|
|
@@ -35,7 +35,7 @@ const DEFAULT_AUTH_PATH = path.join(os.homedir(), ".pi", "agent", "auth.json");
|
|
|
35
35
|
|
|
36
36
|
const PROBE_URLS = {
|
|
37
37
|
zai: "https://api.z.ai/api/monitor/usage/quota/limit",
|
|
38
|
-
"kimi-coding": "https://api.
|
|
38
|
+
"kimi-coding": "https://api.kimi.com/coding/v1/usages",
|
|
39
39
|
cursor: "https://api.cursor.com/teams/daily-usage-data",
|
|
40
40
|
anthropic: "https://api.anthropic.com/v1/organizations/usage_report/messages",
|
|
41
41
|
};
|
|
@@ -61,14 +61,34 @@ export const PROBE_POOLS = {
|
|
|
61
61
|
*/
|
|
62
62
|
|
|
63
63
|
/**
|
|
64
|
+
* One quota window reported by a provider (for example the 5-hour or weekly
|
|
65
|
+
* window). `percentUsed` is 0-100 and is only set from provider-reported data.
|
|
66
|
+
*
|
|
67
|
+
* @typedef {object} QuotaWindow
|
|
68
|
+
* @property {string} window Window id: `"5h"`, `"weekly"`, or `"monthly_tool_calls"`.
|
|
69
|
+
* @property {number} percentUsed
|
|
70
|
+
* @property {number} [used]
|
|
71
|
+
* @property {number} [limit]
|
|
72
|
+
* @property {string} [resetAt] ISO 8601 reset time.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* `source` is `"live"` only when at least one window or usage value was
|
|
77
|
+
* parsed. A successful HTTP response with no recognised quota fields is
|
|
78
|
+
* `"unparsed"`; missing credentials, non-2xx responses, and network errors are
|
|
79
|
+
* `"absent"`.
|
|
80
|
+
*
|
|
64
81
|
* @typedef {object} ProbeResult
|
|
65
82
|
* @property {string} poolId
|
|
66
|
-
* @property {"live" | "absent"} source
|
|
83
|
+
* @property {"live" | "absent" | "unparsed"} source
|
|
67
84
|
* @property {PoolUsage} [usage]
|
|
68
85
|
* @property {number} [limit]
|
|
69
|
-
* @property {
|
|
86
|
+
* @property {QuotaWindow[]} [windows]
|
|
87
|
+
* @property {Error | string} [error]
|
|
70
88
|
*/
|
|
71
89
|
|
|
90
|
+
const UNPARSED_ERROR = "HTTP 200 but no quota fields recognised";
|
|
91
|
+
|
|
72
92
|
/**
|
|
73
93
|
* Read and parse the pi agent auth file, returning `null` when it is missing
|
|
74
94
|
* or unreadable so callers fail closed.
|
|
@@ -197,6 +217,24 @@ async function fetchJsonWithBearer(url, key, fetch) {
|
|
|
197
217
|
return fetchJsonWithHeaders(url, { Authorization: `Bearer ${key}` }, fetch);
|
|
198
218
|
}
|
|
199
219
|
|
|
220
|
+
/**
|
|
221
|
+
* Coerce a provider value to a finite non-negative number. Numeric strings
|
|
222
|
+
* (`"63"`) are accepted because some providers serialise counters as strings.
|
|
223
|
+
*
|
|
224
|
+
* @param {unknown} value
|
|
225
|
+
* @returns {number | undefined}
|
|
226
|
+
*/
|
|
227
|
+
function toNonNegativeNumber(value) {
|
|
228
|
+
if (typeof value === "number") {
|
|
229
|
+
return Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
230
|
+
}
|
|
231
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
232
|
+
const parsed = Number(value);
|
|
233
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
|
|
234
|
+
}
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
200
238
|
/**
|
|
201
239
|
* Extract a numeric limit from a provider response when it is explicitly
|
|
202
240
|
* present; otherwise return `undefined` so the snapshot does not invent one.
|
|
@@ -208,8 +246,8 @@ async function fetchJsonWithBearer(url, key, fetch) {
|
|
|
208
246
|
function extractLimit(data, fields) {
|
|
209
247
|
if (!data || typeof data !== "object") return undefined;
|
|
210
248
|
for (const field of fields) {
|
|
211
|
-
const value = data[field];
|
|
212
|
-
if (
|
|
249
|
+
const value = toNonNegativeNumber(data[field]);
|
|
250
|
+
if (value !== undefined) return value;
|
|
213
251
|
}
|
|
214
252
|
return undefined;
|
|
215
253
|
}
|
|
@@ -223,19 +261,183 @@ function extractLimit(data, fields) {
|
|
|
223
261
|
* @returns {number | undefined}
|
|
224
262
|
*/
|
|
225
263
|
function extractNumber(data, fields) {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
264
|
+
return extractLimit(data, fields);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Round a percentage to two decimals so float noise (62.74999999999999) does
|
|
269
|
+
* not reach reports.
|
|
270
|
+
*
|
|
271
|
+
* @param {number} value
|
|
272
|
+
* @returns {number}
|
|
273
|
+
*/
|
|
274
|
+
function roundPercent(value) {
|
|
275
|
+
return Math.round(value * 100) / 100;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Normalise a reset time (epoch milliseconds as number or numeric string, or
|
|
280
|
+
* an ISO 8601 string) to an ISO string. Returns `undefined` when unparseable.
|
|
281
|
+
*
|
|
282
|
+
* @param {unknown} value
|
|
283
|
+
* @returns {string | undefined}
|
|
284
|
+
*/
|
|
285
|
+
function toIsoTime(value) {
|
|
286
|
+
if (value === undefined || value === null || value === "") return undefined;
|
|
287
|
+
const epoch = toNonNegativeNumber(value);
|
|
288
|
+
const date = new Date(epoch !== undefined ? epoch : /** @type {string} */ (value));
|
|
289
|
+
if (Number.isNaN(date.getTime())) return undefined;
|
|
290
|
+
return date.toISOString();
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Build a window entry, omitting fields the provider did not report.
|
|
295
|
+
*
|
|
296
|
+
* @param {string} window
|
|
297
|
+
* @param {number | undefined} percentUsed
|
|
298
|
+
* @param {{ used?: number, limit?: number, resetAt?: string }} [extra]
|
|
299
|
+
* @returns {QuotaWindow | undefined}
|
|
300
|
+
*/
|
|
301
|
+
function makeWindow(window, percentUsed, extra = {}) {
|
|
302
|
+
if (percentUsed === undefined) return undefined;
|
|
303
|
+
/** @type {QuotaWindow} */
|
|
304
|
+
const entry = { window, percentUsed: roundPercent(percentUsed) };
|
|
305
|
+
if (extra.used !== undefined) entry.used = extra.used;
|
|
306
|
+
if (extra.limit !== undefined) entry.limit = extra.limit;
|
|
307
|
+
if (extra.resetAt !== undefined) entry.resetAt = extra.resetAt;
|
|
308
|
+
return entry;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Percentage from explicit `used` / `limit` counters; `undefined` when the
|
|
313
|
+
* limit is missing or zero.
|
|
314
|
+
*
|
|
315
|
+
* @param {number | undefined} used
|
|
316
|
+
* @param {number | undefined} limit
|
|
317
|
+
* @returns {number | undefined}
|
|
318
|
+
*/
|
|
319
|
+
function percentFromCounts(used, limit) {
|
|
320
|
+
if (used === undefined || limit === undefined || limit <= 0) return undefined;
|
|
321
|
+
return (used / limit) * 100;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Parse Z.ai `data.limits[]` into quota windows. `TOKENS_LIMIT` entries map by
|
|
326
|
+
* `unit`/`number` (3/5 = 5-hour, 6/1 = weekly); `TIME_LIMIT` is the monthly
|
|
327
|
+
* tool-call allowance. Unknown entries are skipped, never guessed.
|
|
328
|
+
*
|
|
329
|
+
* @param {unknown} limits
|
|
330
|
+
* @returns {QuotaWindow[]}
|
|
331
|
+
*/
|
|
332
|
+
function parseZaiWindows(limits) {
|
|
333
|
+
if (!Array.isArray(limits)) return [];
|
|
334
|
+
/** @type {QuotaWindow[]} */
|
|
335
|
+
const windows = [];
|
|
336
|
+
const seen = new Set();
|
|
337
|
+
for (const item of limits) {
|
|
338
|
+
if (!item || typeof item !== "object") continue;
|
|
339
|
+
let id;
|
|
340
|
+
if (item.type === "TOKENS_LIMIT") {
|
|
341
|
+
const unit = toNonNegativeNumber(item.unit);
|
|
342
|
+
const number = toNonNegativeNumber(item.number);
|
|
343
|
+
if (unit === 3 && number === 5) id = "5h";
|
|
344
|
+
else if (unit === 6 && number === 1) id = "weekly";
|
|
345
|
+
} else if (item.type === "TIME_LIMIT") {
|
|
346
|
+
id = "monthly_tool_calls";
|
|
347
|
+
}
|
|
348
|
+
if (!id || seen.has(id)) continue;
|
|
349
|
+
|
|
350
|
+
// For TIME_LIMIT, `usage` is the allowance and `currentValue` the count used.
|
|
351
|
+
const limit = id === "monthly_tool_calls" ? toNonNegativeNumber(item.usage) : undefined;
|
|
352
|
+
const used = id === "monthly_tool_calls" ? toNonNegativeNumber(item.currentValue) : undefined;
|
|
353
|
+
const percent = toNonNegativeNumber(item.percentage) ?? percentFromCounts(used, limit);
|
|
354
|
+
const entry = makeWindow(id, percent, { used, limit, resetAt: toIsoTime(item.nextResetTime) });
|
|
355
|
+
if (!entry) continue;
|
|
356
|
+
seen.add(id);
|
|
357
|
+
windows.push(entry);
|
|
230
358
|
}
|
|
231
|
-
return
|
|
359
|
+
return windows;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* True when a Kimi `limits[]` window descriptor is the 5-hour window
|
|
364
|
+
* (300 minutes or 5 hours).
|
|
365
|
+
*
|
|
366
|
+
* @param {object | undefined} win
|
|
367
|
+
* @returns {boolean}
|
|
368
|
+
*/
|
|
369
|
+
function isKimiFiveHourWindow(win) {
|
|
370
|
+
if (!win || typeof win !== "object") return false;
|
|
371
|
+
const duration = toNonNegativeNumber(win.duration);
|
|
372
|
+
if (duration === undefined) return false;
|
|
373
|
+
if (win.timeUnit === "TIME_UNIT_MINUTE") return duration === 300;
|
|
374
|
+
if (win.timeUnit === "TIME_UNIT_HOUR") return duration === 5;
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Build a window from a Kimi `{ used, limit, resetTime }` counter block.
|
|
380
|
+
*
|
|
381
|
+
* @param {string} id
|
|
382
|
+
* @param {object | undefined} block
|
|
383
|
+
* @returns {QuotaWindow | undefined}
|
|
384
|
+
*/
|
|
385
|
+
function kimiCounterWindow(id, block) {
|
|
386
|
+
if (!block || typeof block !== "object") return undefined;
|
|
387
|
+
const used = toNonNegativeNumber(block.used);
|
|
388
|
+
const limit = toNonNegativeNumber(block.limit);
|
|
389
|
+
return makeWindow(id, percentFromCounts(used, limit), {
|
|
390
|
+
used,
|
|
391
|
+
limit,
|
|
392
|
+
resetAt: toIsoTime(block.resetTime),
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Parse the Kimi Coding `/coding/v1/usages` response. `usages.limit_5h` and
|
|
398
|
+
* `usages.limit_7d` (`used_ratio`, `reset_time`) are preferred; `limits[]`
|
|
399
|
+
* detail (5-hour) and top-level `usage` (weekly) are fallbacks.
|
|
400
|
+
*
|
|
401
|
+
* @param {object} data
|
|
402
|
+
* @returns {QuotaWindow[]}
|
|
403
|
+
*/
|
|
404
|
+
function parseKimiWindows(data) {
|
|
405
|
+
/** @type {QuotaWindow[]} */
|
|
406
|
+
const windows = [];
|
|
407
|
+
const usages = data.usages && typeof data.usages === "object" ? data.usages : {};
|
|
408
|
+
|
|
409
|
+
const ratioWindow = (id, block) => {
|
|
410
|
+
if (!block || typeof block !== "object") return undefined;
|
|
411
|
+
const ratio = toNonNegativeNumber(block.used_ratio);
|
|
412
|
+
return makeWindow(id, ratio === undefined ? undefined : ratio * 100, {
|
|
413
|
+
resetAt: toIsoTime(block.reset_time),
|
|
414
|
+
});
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
let fiveHour = ratioWindow("5h", usages.limit_5h);
|
|
418
|
+
if (!fiveHour && Array.isArray(data.limits)) {
|
|
419
|
+
for (const item of data.limits) {
|
|
420
|
+
if (!item || typeof item !== "object" || !isKimiFiveHourWindow(item.window)) continue;
|
|
421
|
+
fiveHour = kimiCounterWindow("5h", item.detail);
|
|
422
|
+
if (fiveHour) break;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
if (fiveHour) windows.push(fiveHour);
|
|
426
|
+
|
|
427
|
+
const weekly = ratioWindow("weekly", usages.limit_7d) ?? kimiCounterWindow("weekly", data.usage);
|
|
428
|
+
if (weekly) windows.push(weekly);
|
|
429
|
+
|
|
430
|
+
return windows;
|
|
232
431
|
}
|
|
233
432
|
|
|
234
433
|
/**
|
|
235
434
|
* Z.ai probe — uses the bearer key from `auth.json` to request the quota
|
|
236
435
|
* monitor endpoint.
|
|
237
436
|
*
|
|
238
|
-
*
|
|
437
|
+
* Real shape: `{ data: { limits: [{ type, unit, number, percentage,
|
|
438
|
+
* nextResetTime }] } }` (see #351). Flat `{ used, total }` bodies are still
|
|
439
|
+
* read when present. A 2xx response with nothing recognised is `"unparsed"`,
|
|
440
|
+
* never `"live"`.
|
|
239
441
|
*
|
|
240
442
|
* @param {object | null} auth
|
|
241
443
|
* @param {typeof globalThis.fetch} fetch
|
|
@@ -259,8 +461,14 @@ async function probeZai(auth, fetch) {
|
|
|
259
461
|
extractLimit(data, ["total", "total_tokens", "limit"]) ??
|
|
260
462
|
extractLimit(data.data, ["total", "total_tokens", "limit"]);
|
|
261
463
|
|
|
464
|
+
const windows = parseZaiWindows(data.data?.limits);
|
|
465
|
+
|
|
466
|
+
if (used === undefined && windows.length === 0) {
|
|
467
|
+
return { poolId: "zai", source: "unparsed", error: UNPARSED_ERROR };
|
|
468
|
+
}
|
|
262
469
|
const result = { poolId: "zai", source: "live", usage };
|
|
263
470
|
if (limit !== undefined) result.limit = limit;
|
|
471
|
+
if (windows.length > 0) result.windows = windows;
|
|
264
472
|
return result;
|
|
265
473
|
} catch (error) {
|
|
266
474
|
return { poolId: "zai", source: "absent", error };
|
|
@@ -268,10 +476,10 @@ async function probeZai(auth, fetch) {
|
|
|
268
476
|
}
|
|
269
477
|
|
|
270
478
|
/**
|
|
271
|
-
* Kimi
|
|
272
|
-
* balance endpoint
|
|
273
|
-
*
|
|
274
|
-
*
|
|
479
|
+
* Kimi Coding probe — uses the bearer key from `auth.json` to request the
|
|
480
|
+
* `/coding/v1/usages` endpoint (the Moonshot platform balance endpoint rejects
|
|
481
|
+
* Kimi Coding plan keys). Numbers arrive as strings. A 2xx response with
|
|
482
|
+
* nothing recognised is `"unparsed"`, never `"live"`.
|
|
275
483
|
*
|
|
276
484
|
* @param {object | null} auth
|
|
277
485
|
* @param {typeof globalThis.fetch} fetch
|
|
@@ -285,24 +493,13 @@ async function probeKimi(auth, fetch) {
|
|
|
285
493
|
const data = await fetchJsonWithBearer(PROBE_URLS["kimi-coding"], key, fetch);
|
|
286
494
|
if (!data) return { poolId: "kimi-coding", source: "absent" };
|
|
287
495
|
|
|
496
|
+
const windows = parseKimiWindows(data);
|
|
497
|
+
if (windows.length === 0) {
|
|
498
|
+
return { poolId: "kimi-coding", source: "unparsed", error: UNPARSED_ERROR };
|
|
499
|
+
}
|
|
288
500
|
/** @type {PoolUsage} */
|
|
289
501
|
const usage = { taskCount: 0, durationMs: 0 };
|
|
290
|
-
|
|
291
|
-
?? extractNumber(data.data, ["used", "used_tokens"]);
|
|
292
|
-
if (used !== undefined) usage.tokensOut = used;
|
|
293
|
-
|
|
294
|
-
const balance =
|
|
295
|
-
extractNumber(data, ["balance", "cash"]) ??
|
|
296
|
-
extractNumber(data.data, ["balance", "cash"]);
|
|
297
|
-
if (balance !== undefined) usage.estimatedUsd = balance;
|
|
298
|
-
|
|
299
|
-
const limit =
|
|
300
|
-
extractLimit(data, ["total", "total_tokens", "limit"]) ??
|
|
301
|
-
extractLimit(data.data, ["total", "total_tokens", "limit"]);
|
|
302
|
-
|
|
303
|
-
const result = { poolId: "kimi-coding", source: "live", usage };
|
|
304
|
-
if (limit !== undefined) result.limit = limit;
|
|
305
|
-
return result;
|
|
502
|
+
return { poolId: "kimi-coding", source: "live", usage, windows };
|
|
306
503
|
} catch (error) {
|
|
307
504
|
return { poolId: "kimi-coding", source: "absent", error };
|
|
308
505
|
}
|
|
@@ -93,6 +93,7 @@ export function collectExpectedModels(config) {
|
|
|
93
93
|
/**
|
|
94
94
|
* @typedef {object} PoolUsage
|
|
95
95
|
* @property {number} taskCount
|
|
96
|
+
* @property {number} [reviewCount] Reviewer rows (SP-837); present only when > 0, not part of `taskCount`.
|
|
96
97
|
* @property {number} durationMs
|
|
97
98
|
* @property {number} [tokensIn]
|
|
98
99
|
* @property {number} [tokensOut]
|
|
@@ -118,7 +119,11 @@ export function aggregatePoolUsage(records) {
|
|
|
118
119
|
|
|
119
120
|
for (const record of records) {
|
|
120
121
|
if (!record || typeof record !== "object") continue;
|
|
121
|
-
|
|
122
|
+
if (record.recordType === "review") {
|
|
123
|
+
usage.reviewCount = (usage.reviewCount ?? 0) + 1;
|
|
124
|
+
} else {
|
|
125
|
+
usage.taskCount += 1;
|
|
126
|
+
}
|
|
122
127
|
if (Number.isFinite(record.durationMs)) {
|
|
123
128
|
usage.durationMs += Math.max(0, record.durationMs);
|
|
124
129
|
}
|
|
@@ -166,6 +171,7 @@ function buildPoolDrift(expectedModels, observedModels) {
|
|
|
166
171
|
* @property {string[]} observedModels
|
|
167
172
|
* @property {PoolUsage} usage
|
|
168
173
|
* @property {number} [limit]
|
|
174
|
+
* @property {import("./quota-probes.mjs").QuotaWindow[]} [windows] Per-window percent/reset from a live probe.
|
|
169
175
|
* @property {{unexpectedModels: string[], missingModels: string[]}} drift
|
|
170
176
|
*/
|
|
171
177
|
|
|
@@ -195,8 +201,11 @@ export function buildQuotaSnapshot({ projectRoot, config, metricsLines, probeRes
|
|
|
195
201
|
const filePath = metricsFilePath(projectRoot, config);
|
|
196
202
|
lines = readMetricsLines(filePath);
|
|
197
203
|
}
|
|
204
|
+
// SP-837 (#325): reviewer rows count toward observed models and pool usage;
|
|
205
|
+
// aggregatePoolUsage keeps them out of taskCount.
|
|
198
206
|
const taskRecords = (lines ?? []).filter(
|
|
199
|
-
(line) =>
|
|
207
|
+
(line) =>
|
|
208
|
+
line && typeof line === "object" && (line.recordType === "task" || line.recordType === "review"),
|
|
200
209
|
);
|
|
201
210
|
|
|
202
211
|
const expectedModels = collectExpectedModels(config);
|
|
@@ -239,11 +248,20 @@ export function buildQuotaSnapshot({ projectRoot, config, metricsLines, probeRes
|
|
|
239
248
|
/** @type {PoolUsage} */
|
|
240
249
|
let usage = aggregatePoolUsage(observedRecords);
|
|
241
250
|
let limit;
|
|
251
|
+
let windows;
|
|
242
252
|
|
|
253
|
+
// Only a "live" probe enriches the pool. "unparsed" (HTTP 200 with no
|
|
254
|
+
// recognised quota fields) and "absent" both fall back to the estimate.
|
|
243
255
|
if (probe?.source === "live") {
|
|
244
256
|
source = "live";
|
|
245
257
|
usage = probe.usage && typeof probe.usage === "object" ? probe.usage : usage;
|
|
246
258
|
if (Number.isFinite(probe.limit) && probe.limit >= 0) limit = probe.limit;
|
|
259
|
+
if (Array.isArray(probe.windows)) {
|
|
260
|
+
const valid = probe.windows.filter(
|
|
261
|
+
(w) => w && typeof w.window === "string" && Number.isFinite(w.percentUsed),
|
|
262
|
+
);
|
|
263
|
+
if (valid.length > 0) windows = valid;
|
|
264
|
+
}
|
|
247
265
|
}
|
|
248
266
|
|
|
249
267
|
if (source === "live") overallHasLive = true;
|
|
@@ -259,6 +277,7 @@ export function buildQuotaSnapshot({ projectRoot, config, metricsLines, probeRes
|
|
|
259
277
|
drift: buildPoolDrift([...expectedSet], [...observedSet]),
|
|
260
278
|
};
|
|
261
279
|
if (limit !== undefined) pool.limit = limit;
|
|
280
|
+
if (windows !== undefined) pool.windows = windows;
|
|
262
281
|
pools[poolId] = pool;
|
|
263
282
|
}
|
|
264
283
|
|
package/src/planner/graph.mjs
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* included in the graph.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import { compareTaskIds } from '../tasks/packet/discover.mjs';
|
|
14
|
+
|
|
13
15
|
/**
|
|
14
16
|
* @param {Record<string, string[]>} depsByTask
|
|
15
17
|
* @returns {{ nodes: string[], depsByTask: Record<string, string[]>, dependentsByTask: Record<string, string[]> }}
|
|
@@ -37,9 +39,9 @@ export function buildGraph(depsByTask) {
|
|
|
37
39
|
if (!dependentsByTask[id]) dependentsByTask[id] = [];
|
|
38
40
|
}
|
|
39
41
|
|
|
40
|
-
const nodes = Array.from(nodesSet).sort();
|
|
42
|
+
const nodes = Array.from(nodesSet).sort(compareTaskIds);
|
|
41
43
|
for (const id of Object.keys(dependentsByTask)) {
|
|
42
|
-
dependentsByTask[id].sort();
|
|
44
|
+
dependentsByTask[id].sort(compareTaskIds);
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
return { nodes, depsByTask: normalized, dependentsByTask };
|
|
@@ -69,7 +71,7 @@ export function topoWaves(graph) {
|
|
|
69
71
|
const zero = Array.from(indegree.entries())
|
|
70
72
|
.filter(([, deg]) => deg === 0)
|
|
71
73
|
.map(([id]) => id)
|
|
72
|
-
.sort();
|
|
74
|
+
.sort(compareTaskIds);
|
|
73
75
|
|
|
74
76
|
const waves = [];
|
|
75
77
|
let current = zero;
|
|
@@ -88,13 +90,13 @@ export function topoWaves(graph) {
|
|
|
88
90
|
}
|
|
89
91
|
}
|
|
90
92
|
|
|
91
|
-
current = next.sort();
|
|
93
|
+
current = next.sort(compareTaskIds);
|
|
92
94
|
}
|
|
93
95
|
|
|
94
96
|
const remainingWithDeps = Array.from(indegree.entries())
|
|
95
97
|
.filter(([, deg]) => deg > 0)
|
|
96
98
|
.map(([id]) => id)
|
|
97
|
-
.sort();
|
|
99
|
+
.sort(compareTaskIds);
|
|
98
100
|
|
|
99
101
|
return { waves, remainingWithDeps };
|
|
100
102
|
}
|
package/src/planner/pending.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import fs from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
|
-
import { TASK_ID_RE } from "
|
|
7
|
+
import { TASK_ID_RE, compareTaskIds } from "../tasks/packet/discover.mjs";
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* @param {Array<{ taskId: string, folderPath: string }>} discoveredTasks
|
|
@@ -23,7 +23,7 @@ export function filterPendingTaskIds(discoveredTasks, tasksRoot) {
|
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
return pending.sort();
|
|
26
|
+
return pending.sort(compareTaskIds);
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/**
|