@commonlyai/cli 0.1.173 → 0.1.175

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 (29) hide show
  1. package/node_modules/@commonlyai/seats/README.md +11 -0
  2. package/node_modules/@commonlyai/seats/package.json +22 -0
  3. package/node_modules/@commonlyai/seats/src/adapters/hermes.js +206 -0
  4. package/node_modules/@commonlyai/seats/src/adapters/stub.js +24 -0
  5. package/node_modules/@commonlyai/seats/src/contract.js +48 -0
  6. package/node_modules/@commonlyai/seats/src/failures.js +38 -0
  7. package/node_modules/@commonlyai/seats/src/index.js +22 -0
  8. package/node_modules/@commonlyai/seats/src/process-group.js +261 -0
  9. package/node_modules/@commonlyai/seats/src/record/format.js +635 -0
  10. package/node_modules/@commonlyai/seats/src/record/otel.js +238 -0
  11. package/node_modules/@commonlyai/seats/src/runtime-observation.js +29 -0
  12. package/node_modules/@commonlyai/seats/src/seat-model.js +17 -0
  13. package/node_modules/@commonlyai/seats/src/supervisor.js +308 -0
  14. package/node_modules/@commonlyai/seats/src/trace/events.js +45 -0
  15. package/node_modules/@commonlyai/seats/src/trace/store.js +276 -0
  16. package/node_modules/@commonlyai/seats/src/upstream-refusal.js +362 -0
  17. package/node_modules/@commonlyai/seats/src/valet/env.js +164 -0
  18. package/node_modules/@commonlyai/seats/src/valet/grant.js +118 -0
  19. package/node_modules/@commonlyai/seats/src/valet/permissions.js +213 -0
  20. package/package.json +6 -1
  21. package/src/commands/agent.js +21 -3
  22. package/src/lib/adapters/claude.js +8 -3
  23. package/src/lib/adapters/codex.js +5 -2
  24. package/src/lib/adapters/hermes.js +13 -194
  25. package/src/lib/adapters/seat-model.js +5 -12
  26. package/src/lib/adapters/stub.js +1 -24
  27. package/src/lib/runtime-observation.js +3 -27
  28. package/src/lib/seat-stop.js +96 -0
  29. package/src/lib/upstream-refusal.js +1 -354
@@ -1,354 +1 @@
1
- /**
2
- * TASK-096 — name a refused model route, instead of reporting the silence it
3
- * causes.
4
- *
5
- * Measured 2026-09-22 against pi 0.84.1 with a route answering 429 (the shape
6
- * that made a seat look broken for two and a half days): pi runs its own retry
7
- * ladder, reports the refusal on `message_end`/`auto_retry_end` JSON events, and
8
- * EXITS 0 with no assistant text. `extractReply` in the pi adapter collected only
9
- * `type: "error"` events — of which this produces none — so the wrapper logged
10
- * `no wrapper-post (empty output)` and the cause sat unread in the stream.
11
- *
12
- * Two rules govern the text that reaches a seat log:
13
- *
14
- * 1. KEEP-LIST, not strip-list (Vera 70876, Wren 70877). A strip-list removes
15
- * only the shapes we thought of, and a 401 can echo the key back. So a body
16
- * contributes one NAMED field or nothing at all.
17
- * 2. Exact-match refusal for credentials. If the kept text contains a value
18
- * this spawn was handed, the text is dropped — a known value, not a guessed
19
- * shape (Wren 70877).
20
- *
21
- * Two limits follow from rule 2. They are the accepted cost of refusing guessed
22
- * shapes, named here so they are not rediscovered as defects later (Vera 71082):
23
- *
24
- * a. The match is exact and against THIS spawn's values only, so a credential
25
- * that arrives transformed — base64 inside a proxy error, percent-encoded in
26
- * a URL echo — does not match and the text is kept. Matching transformed
27
- * shapes instead would reintroduce the class rule 1 exists to avoid.
28
- * b. The keep-list can still surface someone ELSE's secret. A third party's key
29
- * relayed in an upstream error is not detectable here, because the one
30
- * inventory this module has is the set of values it was itself handed.
31
- *
32
- * Scope: this reader was wired into the pi adapter only. TASK-103 extended it
33
- * to codex and claude, which are NOT silent the way pi was: the claude adapter
34
- * rejects on a non-zero exit and deliberately reports stdout with it, because a
35
- * `-p` run writes quota conditions there; the codex adapter rejects on
36
- * `turnFailedMessage` even at exit 0. Their gap was the opposite one — the text
37
- * they raised was the raw tail, unscrubbed by the rules above, and carried no
38
- * HTTP status for the run loop to classify on. `scrubAdapterFailure` below is
39
- * the shared reader they now both go through, so the two rules cannot drift
40
- * apart between three adapters.
41
- */
42
-
43
- /** The kept detail is truncated, ellipsis included, to this many characters. */
44
- export const MAX_REFUSAL_DETAIL = 256;
45
-
46
- /**
47
- * The status an adapter prefixes to its error text: `"429: {…}"` -> `429`.
48
- * Null for anything that is not a 4xx/5xx, so a message that merely starts with
49
- * a number ("4040 tokens over budget") is not read as a status.
50
- *
51
- * The separator pi uses is NOT fixed — measured 2026-09-22, the same pi 0.84.1
52
- * emits `"429: {"message":…}"` for a JSON body and `"502 <html>…"` for an
53
- * HTML one. Both forms are matched here; a parser that required the colon would
54
- * have kept `502 <html>…` as the whole "body" and then dropped it as non-JSON,
55
- * reporting the status alone with no sign that the body was never read.
56
- */
57
- const STATUS_PREFIX = /^\s*(\d{3})(?!\d)\s*:?\s*/;
58
-
59
- export const statusFromError = (value) => {
60
- const match = STATUS_PREFIX.exec(String(value ?? ''));
61
- if (!match) return null;
62
- const status = Number(match[1]);
63
- return status >= 400 && status <= 599 ? status : null;
64
- };
65
-
66
- /**
67
- * The body the adapter carried after its status prefix, or the whole text when
68
- * there is no status to strip. `"429: {"message":"a: b"}"` -> `{"message":"a: b"}`;
69
- * `"502 <html>"` -> `<html>`.
70
- */
71
- export const bodyFromError = (value) => {
72
- const text = String(value ?? '');
73
- if (statusFromError(text) === null) return text.trim();
74
- return text.replace(STATUS_PREFIX, '').trim();
75
- };
76
-
77
- /**
78
- * Replace credential values this spawn was handed with a marker.
79
- *
80
- * This is the exact-match half, for text that is kept for its whole shape rather
81
- * than filtered to one field — an adapter's stderr tail, say, whose diagnostic
82
- * value is in the lines around the secret. Values shorter than eight characters
83
- * are ignored: redacting a one-character "credential" would corrupt ordinary
84
- * prose, and no issued credential is that short.
85
- */
86
- export const redactKnownCredentials = (text, credentials = []) => {
87
- let out = String(text ?? '');
88
- for (const value of credentials) {
89
- if (typeof value !== 'string' || value.length < 8) continue;
90
- out = out.split(value).join('[redacted]');
91
- }
92
- return out;
93
- };
94
-
95
- /**
96
- * The keep-list. Given the raw body an adapter captured, keep at most one named
97
- * field of it and only when that field is a string:
98
- *
99
- * `error.message` first (the OpenAI-shaped error), then a top-level `message`
100
- * (which is the shape LiteLLM's budget refusal actually uses — the motivating
101
- * case; a keep-list that kept only `error.message` would name the status and
102
- * still hide the budget line that started this row).
103
- *
104
- * Everything else — HTML, a non-JSON body, a JSON body with neither field, a
105
- * body echoing a known credential — contributes nothing. Returns null rather
106
- * than a partial guess.
107
- */
108
- export const keptRefusalDetail = (raw, { credentials = [] } = {}) => {
109
- let parsed;
110
- try {
111
- parsed = JSON.parse(String(raw ?? ''));
112
- } catch {
113
- return null;
114
- }
115
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
116
-
117
- const candidate = parsed?.error?.message ?? parsed?.message;
118
- if (typeof candidate !== 'string') return null;
119
-
120
- const text = candidate.replace(/\s+/g, ' ').trim();
121
- if (!text) return null;
122
-
123
- const redacted = redactKnownCredentials(text, credentials);
124
- // `[redacted]` appearing is the signal that the body echoed something this
125
- // spawn was handed. The status is still worth keeping; the text is not.
126
- if (redacted !== text) return null;
127
-
128
- return text.length > MAX_REFUSAL_DETAIL
129
- ? `${text.slice(0, MAX_REFUSAL_DETAIL - 1)}…`
130
- : text;
131
- };
132
-
133
- /**
134
- * Read a pi JSON stream and return the refusal it ended on, or null.
135
- *
136
- * `auto_retry_end` is the terminal word — it names the status and the body after
137
- * the ladder has finished — so it wins over the per-attempt `message_end`
138
- * events that precede it. A run that refused on its first attempt and never
139
- * retried still reports through `message_end`.
140
- */
141
- export const readUpstreamRefusal = (stdout, { credentials = [] } = {}) => {
142
- let status = null;
143
- let raw = null;
144
-
145
- for (const line of String(stdout ?? '').split('\n')) {
146
- if (!line.trim()) continue;
147
- let event;
148
- try {
149
- event = JSON.parse(line);
150
- } catch {
151
- continue;
152
- }
153
-
154
- if (event?.type === 'auto_retry_end' && event.success === false) {
155
- const candidate = event.finalError ?? event.errorMessage;
156
- const attemptStatus = statusFromError(candidate);
157
- if (attemptStatus) {
158
- status = attemptStatus;
159
- raw = bodyFromError(candidate);
160
- }
161
- continue;
162
- }
163
-
164
- const message = event?.message;
165
- if (
166
- event?.type === 'message_end'
167
- && message?.role === 'assistant'
168
- && message.stopReason === 'error'
169
- && status === null
170
- ) {
171
- const attemptStatus = statusFromError(message.errorMessage);
172
- if (attemptStatus) {
173
- status = attemptStatus;
174
- raw = bodyFromError(message.errorMessage);
175
- }
176
- }
177
- }
178
-
179
- if (status === null) return null;
180
- return { status, detail: keptRefusalDetail(raw, { credentials }) };
181
- };
182
-
183
- /**
184
- * Is this text STRUCTURED upstream data — a JSON object or an array? The gate for
185
- * the whole-tail fallback below, deliberately NOT `kept === null`, which is true
186
- * for five different reasons (Vera 71350).
187
- *
188
- * An array counts, and that is a correction (Vera 71360, measured): `[{...}]` is
189
- * structured data with fields this code does not know, which is exactly what rule
190
- * 1 exists for, and treating it as prose shipped the whole body under exact-match
191
- * alone. A JSON *string* is the opposite case and does NOT count — `"Too many
192
- * requests"` is a whole-shape text with no fields to reduce, so it keeps its
193
- * wording like any other prose.
194
- */
195
- const isStructuredBody = (raw) => {
196
- try {
197
- const parsed = JSON.parse(String(raw ?? ''));
198
- return parsed !== null && typeof parsed === 'object';
199
- } catch {
200
- return false;
201
- }
202
- };
203
-
204
- /**
205
- * A 3-digit number is read as a status only when the tail NAMES it as one:
206
- * `status 429`, `HTTP 429`, `code: "429"` — or when it opens the tail or a ` | `
207
- * segment followed by a colon, which is the shape claude's `stderr | stdout`
208
- * join produces for a body that leads with its status.
209
- *
210
- * A bare `\b(\d{3})\b` scan is not enough, and the false positives are not
211
- * hypothetical: `500 tokens`, `"max_tokens": 500` and `retry in 500 seconds`
212
- * all read as 500, and `classifySpawnFailure` tests the status FIELD before the
213
- * message — so a count misread as a status stands the fleet down on a refusal
214
- * that never happened, which is worse than no status at all (Vera 71352).
215
- */
216
- const STATUS_NAMED = /\b(?:status(?:_?code)?|code|http)\b\W{0,4}(\d{3})(?!\d)/gi;
217
- // `HTTP/1.1 429 Too Many Requests` is the most canonical refusal shape there is,
218
- // and the `\W{0,4}` gap above handles `HTTP 429` but cannot reach a VERSIONED
219
- // line: the `1` in `/1.1` is a
220
- // WORD character, so `HTTP` and `429` are not within four non-word characters of
221
- // each other. It read as `status: null` — an unclassified runtime failure on the
222
- // single most recognisable shape, which is the misclassification this row exists
223
- // to remove (Vera 71359). Its own pattern, not a looser gap: widening the gap
224
- // would start reading `/v1/models 500` as a status.
225
- const STATUS_LINE = /\bHTTP\/\d(?:\.\d)?\s+(\d{3})(?!\d)/gi;
226
- const STATUS_COLON = /(?:^|\|\s*)(\d{3})(?!\d)\s*:/g;
227
-
228
- /** The first 4xx/5xx one of those shapes names, or null. */
229
- const scanStatuses = (text, pattern) => {
230
- for (const match of String(text ?? '').matchAll(pattern)) {
231
- const value = Number(match[1]);
232
- if (value >= 400 && value <= 599) return value;
233
- }
234
- return null;
235
- };
236
-
237
- /**
238
- * Find the status AND the body boundary, because they are the same question.
239
- *
240
- * Anchoring the status to a ` | ` segment start is not enough on its own: the
241
- * body has to be taken from just past that status too, or a mid-tail read
242
- * isolates the status and then hands the WHOLE joined tail to the body rules,
243
- * which no longer look like a JSON body and so fall through to "keep it all".
244
- * That is the difference between dropping a credential-echoing body and shipping
245
- * the part of it that exact-match cannot see.
246
- *
247
- * `STATUS_COLON` is the only shape that moves the boundary, because it is the
248
- * same shape as the anchored prefix (`429: {body}`), just found at a segment
249
- * boundary — claude's `stderr | stdout` join. A status that appears inside a
250
- * body (`{"error":{"code":"429"}}`) or as prose (`HTTP 503`) names the status
251
- * (`HTTP/1.1 429`) but marks no boundary, so the whole text stays the body.
252
- */
253
- const readStatusAndBody = (text) => {
254
- const raw = String(text ?? '');
255
- const prefixed = statusFromError(raw);
256
- if (prefixed !== null) return { status: prefixed, body: bodyFromError(raw) };
257
- // Only the colon shape moves the boundary — see the note above. A status LINE
258
- // names the status but its reason phrase is prose, so the body stays the whole
259
- // text and the exact-match rule protects it.
260
- for (const match of raw.matchAll(STATUS_COLON)) {
261
- const value = Number(match[1]);
262
- if (value >= 400 && value <= 599) {
263
- return { status: value, body: raw.slice(match.index + match[0].length).replace(/^\s*:?\s*/, '') };
264
- }
265
- }
266
- const named = scanStatuses(raw, STATUS_NAMED);
267
- return { status: named ?? scanStatuses(raw, STATUS_LINE), body: raw };
268
- };
269
-
270
- /**
271
- * The shared reader for an adapter's own failure tail (TASK-103).
272
- *
273
- * The two rules above are about a body an adapter captured, and they apply here
274
- * too — but the tail is a different shape from pi's refusal, and the difference
275
- * decides how each rule lands:
276
- *
277
- * - The tail is often NOT structured. Claude's `-p` mode writes its terminal
278
- * condition as prose (`Claude usage limit reached. Your limit will reset at
279
- * 11:40pm.`), and that line is the whole diagnostic value of reporting
280
- * stdout at all — 361 consecutive failures on 2026-08-03 carried no reason
281
- * because of it. So the keep-list applies only when the tail parses as a
282
- * body; when it does not, the text is KEPT as a whole shape and the
283
- * exact-match rule is what protects it (`redactKnownCredentials`, which
284
- * substitutes rather than drops, precisely because a whole-shape text has no
285
- * second field to fall back to).
286
- *
287
- * - A body that IS structured (a JSON object or array) is reduced to one named
288
- * field, and a body whose field echoed a value this spawn was handed is
289
- * DROPPED WHOLE — the same trade rule 2 makes everywhere. The fallback to the
290
- * whole tail is gated on the SHAPE (is it structured at all), never on
291
- * "the keep-list returned null": that null has
292
- * four other causes, and one of them is the credential echo this line exists
293
- * to drop. Gating on `kept === null` would emit the whole body for that case,
294
- * which is precisely what rule 2 forbids — and exact-match cannot see a
295
- * transformed shape (limit (a) in the header), so a key that arrived
296
- * base64'd or percent-encoded would ship (Vera 71350/71351).
297
- *
298
- * Returns `{ status, detail }`: `status` is the 4xx/5xx the tail named, or null.
299
- * The caller decides where the status goes; `classifySpawnFailure` reads it off
300
- * `error.status` or out of the message text, so both a leading `429: …` prefix
301
- * and an attached field classify the same way. `detail` is `''` when nothing of
302
- * the body may be shown — the status is then the whole diagnostic.
303
- */
304
- export const scrubAdapterFailure = (text, { credentials = [], limit = MAX_REFUSAL_DETAIL } = {}) => {
305
- const raw = String(text ?? '').trim();
306
- const { status, body } = readStatusAndBody(raw);
307
- const kept = keptRefusalDetail(body, { credentials });
308
- const detail = kept ?? (isStructuredBody(body) ? '' : redactKnownCredentials(body, credentials));
309
- return { status, detail: detail.slice(0, limit) };
310
- };
311
-
312
- /**
313
- * The Error an adapter raises, built from its own failure tail.
314
- *
315
- * `status` is attached as a field, not only written into the text: the run
316
- * loop's classifier tests `error.status === 429` before it looks at the
317
- * message, and a refusal that is only readable by regex is one wording away
318
- * from the misclassification that cost an hour on 2026-08-18 (see
319
- * spawn-retry.js). The message still names the status so a human log says the
320
- * same thing as the classifier's decision.
321
- */
322
- export const adapterFailure = (label, text, { credentials = [], exitCode = null, limit } = {}) => {
323
- const { status, detail } = scrubAdapterFailure(text, { credentials, limit });
324
- const code = exitCode === null ? '' : ` exited with code ${exitCode}`;
325
- const named = status === null ? '' : ` (upstream ${status})`;
326
- const error = new Error(`${label}${code}${named}${detail ? `: ${detail}` : ''}`);
327
- if (status !== null) error.status = status;
328
- return error;
329
- };
330
-
331
- /**
332
- * The seat-log clause. The status is always present; the detail only when the
333
- * keep-list kept one. `grep 'upstream refused'` finds every refusal, which is
334
- * the property the old `no wrapper-post (empty output)` line did not have.
335
- */
336
- export const describeUpstreamRefusal = (refusal) => {
337
- if (!refusal || typeof refusal.status !== 'number') return null;
338
- return refusal.detail
339
- ? `upstream refused ${refusal.status}: ${refusal.detail}`
340
- : `upstream refused ${refusal.status}`;
341
- };
342
-
343
- /**
344
- * The credential values this spawn was handed, for the exact-match check in
345
- * `redactKnownCredentials`. `envNames` are the adapter's own provider keys; the
346
- * caller supplies them because only the adapter knows which key its route uses.
347
- */
348
- export const spawnCredentials = (ctx = {}, envNames = []) => {
349
- const env = ctx.env || process.env || {};
350
- return [
351
- ctx.runtimeToken,
352
- ...envNames.map((name) => env[name]),
353
- ].filter((value) => typeof value === 'string' && value.length >= 8);
354
- };
1
+ export * from '@commonlyai/seats/upstream-refusal';