@ossclip/core 0.1.26 → 0.1.28

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.
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod/v4";
2
2
  import { run } from "../exec";
3
+ import { attemptFactsLine } from "./failure";
3
4
  import type { LlmProvider } from "./provider";
4
5
  import { estimateTokens, type LlmUsage } from "./usage";
5
6
  // Shared fence-stripper for replies that wrap the JSON in prose/markdown.
@@ -24,6 +25,14 @@ export const AGY_PRINT_TIMEOUT = "10m";
24
25
  */
25
26
  export const MAX_AGY_PROMPT_BYTES = 700_000;
26
27
 
28
+ /**
29
+ * agy's `--effort` levels. Exposed after the §143 hang incident (2026-08-22):
30
+ * untested at real scale whether a lower effort moves the hang, but the knob
31
+ * existed and we passed nothing — every call ran at agy's default with no way
32
+ * to try anything else.
33
+ */
34
+ export type LlmEffort = "low" | "medium" | "high";
35
+
27
36
  /**
28
37
  * The argv for one `agy` print-mode call. Pure so the flag set is testable
29
38
  * without spawning anything. `--disable-slash-commands` because a transcript
@@ -31,7 +40,7 @@ export const MAX_AGY_PROMPT_BYTES = 700_000;
31
40
  */
32
41
  export function buildAgyArgs(
33
42
  prompt: string,
34
- opts: { model?: string; schemaJson: string },
43
+ opts: { model?: string; effort?: LlmEffort; schemaJson: string },
35
44
  ): string[] {
36
45
  return [
37
46
  "-p",
@@ -44,6 +53,9 @@ export function buildAgyArgs(
44
53
  "--print-timeout",
45
54
  AGY_PRINT_TIMEOUT,
46
55
  ...(opts.model ? ["--model", opts.model] : []),
56
+ // Omitted entirely when unset — agy's own default stands, exactly as it
57
+ // did before the knob existed (§143).
58
+ ...(opts.effort ? ["--effort", opts.effort] : []),
47
59
  ];
48
60
  }
49
61
 
@@ -107,11 +119,159 @@ export function parseAgyEnvelope(stdout: string): {
107
119
  * Failures a retry cannot fix: missing auth and a bad model slug are
108
120
  * deterministic, and each retry burns another ~24k-token baseline call (agy's
109
121
  * own agent context) for nothing (FINDINGS §132, antigravity provider).
122
+ *
123
+ * The patterns were always right; the INPUT was wrong. Until 2026-08-22 this
124
+ * was handed `run()`'s rejection, and the contract §132 claimed for it — "the
125
+ * stderr tail is embedded, so auth/bad-slug are matchable here" — is false for
126
+ * real agy: a bad slug exits 1 with `invalid model selection …` in the STDOUT
127
+ * envelope and NOTHING on stderr (measured, 1.1.18). So the message this saw
128
+ * was our own echoed argv, which contains the slug but never the words
129
+ * "invalid model", and the documented fail-fast has never once fired in the
130
+ * field. It is now given `agyErrorText()` — the envelope's own error — which
131
+ * matches the shipped patterns as measured, with no pattern change at all.
132
+ *
133
+ * That is a real behaviour change (a bad slug now costs one call, not two),
134
+ * taken deliberately: it makes the code do what this comment has always said
135
+ * it does, rather than changing what it should do.
110
136
  */
111
137
  export function isNonRetryableAgyFailure(message: string): boolean {
112
138
  return /authentication|not logged in|login|unknown model|invalid model/i.test(message);
113
139
  }
114
140
 
141
+ /**
142
+ * What actually went wrong, out of the two surfaces agy uses — measured
143
+ * against agy 1.1.18 on 2026-08-22, because none of it is documented:
144
+ *
145
+ * print timeout fires exit 1 stdout `{"status":"ERROR","error":"timeout
146
+ * waiting for response",…}` stderr empty
147
+ * unknown model slug exit 1 stdout `{"status":"ERROR","error":"invalid
148
+ * model selection (--model …)…"}` stderr empty
149
+ * bad flag / usage exit 2 stdout empty stderr usage text
150
+ *
151
+ * So the operational failures speak through the ENVELOPE and the process-level
152
+ * ones through stderr, and a reader of only one surface is blind to half of
153
+ * them. Preference order follows that: the envelope's own `error` first (it is
154
+ * agy's sentence about its own failure), then stderr for the exits that never
155
+ * reached the envelope, then the bare status, then whatever stdout held.
156
+ *
157
+ * Pure, and exported so the surfaces are testable without spawning agy. agy's
158
+ * wording is not a contract we control — only the two surfaces are — which is
159
+ * why callers classify loosely and print the raw text either way.
160
+ */
161
+ export function agyErrorText(stdout: string, stderr: string): string {
162
+ const env = parseAgyEnvelope(stdout);
163
+ if (env.error?.trim()) return env.error.trim();
164
+ if (stderr.trim()) return stderr.trim().slice(-2000);
165
+ if (env.status) return `agy reported status ${env.status}`;
166
+ if (stdout.trim()) return `agy replied with no envelope: ${stdout.trim().slice(0, 300)}`;
167
+ return "agy printed nothing";
168
+ }
169
+
170
+ /** What the failure text says actually went wrong. See `classifyAgyFailure`. */
171
+ export type AgyFailureClass = "auth" | "model" | "timeout" | "schema" | "unknown";
172
+
173
+ /**
174
+ * Classify a failure so the error can say what happened instead of guessing.
175
+ * Pure and exported so every class is assertable without spawning agy. The
176
+ * input is `agyErrorText()` — agy's own sentence — not `run()`'s rejection.
177
+ *
178
+ * The incident (2026-08-22, FINDINGS §132): a `--produce --aspect 16:9` run on
179
+ * an 11-minute take timed out twice at AGY_PRINT_TIMEOUT — 10m each, 25
180
+ * minutes burned — and then died with "Is Antigravity installed and logged
181
+ * in?", while agy was installed, logged in and working. The hint was appended
182
+ * unconditionally, so every failure was reported as an auth failure and this
183
+ * one sent the user to debug auth after a 25-minute wait.
184
+ *
185
+ * Anchors, and how much each is worth:
186
+ * - `timeout` and `model` are MEASURED (agy 1.1.18): "timeout waiting for
187
+ * response" and "invalid model selection (--model …)". The looser
188
+ * alternatives stay beside them because the exact strings are agy's to
189
+ * change without telling us — and because an externally killed agy (a
190
+ * signal, not agy's own clock) surfaces differently again.
191
+ * - `auth` is INFERRED, not measured: establishing it would mean signing the
192
+ * user out. Its patterns are exactly the ones `isNonRetryableAgyFailure`
193
+ * has always used, so an auth failure can never classify worse than it did
194
+ * before this change, and both measured samples put operational reasons in
195
+ * the same envelope field, so there is no reason to expect auth elsewhere.
196
+ * - `schema` matches what OUR OWN code leaves in `lastError` — `extractJson-
197
+ * Object`'s message, JSON.parse's, and zod's issue array.
198
+ *
199
+ * A miss costs the headline and the class-gated advice, never the facts: the
200
+ * attempt line below prints for every class, and it is what actually
201
+ * self-diagnoses a hang.
202
+ */
203
+ export function classifyAgyFailure(message: string): AgyFailureClass {
204
+ if (/authentication|not logged in|login/i.test(message)) return "auth";
205
+ if (/unknown model|invalid model/i.test(message)) return "model";
206
+ if (/timed? ?out|ETIMEDOUT|SIGTERM|SIGKILL/i.test(message)) return "timeout";
207
+ const schemaish = /no JSON object in reply|is not valid JSON|Unexpected (token|end of)|"code":\s*"/i;
208
+ if (schemaish.test(message)) return "schema";
209
+ return "unknown";
210
+ }
211
+
212
+ /**
213
+ * The error thrown when every attempt failed. Pure so the wording is testable
214
+ * without spawning agy, and built around one rule learned from the 2026-08-22
215
+ * incident: the ATTEMPT FACTS print for every class, because they self-diagnose
216
+ * regardless of what the classifier decided. "2 attempts, 10m0s and 10m0s,
217
+ * --print-timeout 10m" tells a user the call hung better than any guess we
218
+ * could make, and it stays true when the guess is wrong.
219
+ *
220
+ * Guidance, by contrast, is class-gated: the sign-in hint only for `auth`, and
221
+ * for `timeout` the actual escape hatch — another provider, or no planner at
222
+ * all — named the way the oversized-prompt error above names them.
223
+ */
224
+ export function agyFailureMessage(parts: {
225
+ bin: string;
226
+ schemaName: string;
227
+ lastError: string;
228
+ /** Wall time of every attempt that ran, in order. */
229
+ attemptMs: readonly number[];
230
+ printTimeout: string;
231
+ }): string {
232
+ const cls = classifyAgyFailure(parts.lastError);
233
+ const headline =
234
+ cls === "timeout"
235
+ ? " — the call timed out"
236
+ : cls === "schema"
237
+ ? " — the reply never matched the schema"
238
+ : "";
239
+ const detail = parts.lastError.trim().slice(0, 400) || "agy printed nothing";
240
+ const lines = [
241
+ `agy CLI ('${parts.bin}') did not produce valid ${parts.schemaName} JSON${headline}: ${detail}`,
242
+ attemptFactsLine(parts.attemptMs, `--print-timeout ${parts.printTimeout}`),
243
+ ];
244
+ if (cls === "auth") {
245
+ lines.push(
246
+ `Is Antigravity installed and logged in? (https://antigravity.google — run 'agy' once interactively to sign in)`,
247
+ );
248
+ }
249
+ if (cls === "timeout") {
250
+ lines.push(
251
+ `A long take can outrun agy's ${parts.printTimeout} print timeout. ` +
252
+ `Use --llm claude-cli (a logged-in Claude Code subscription) or --llm gemini (needs GEMINI_API_KEY), ` +
253
+ `or drop --produce to cut and caption without a planner.`,
254
+ );
255
+ }
256
+ return lines.join("\n");
257
+ }
258
+
259
+ /**
260
+ * The provider's terminal error, carrying the failure class as DATA. The
261
+ * message is written for humans and free to reword; a provider-fallback
262
+ * decorator that branches on what failed must read `failureClass`, never
263
+ * re-parse the prose.
264
+ */
265
+ export class AgyError extends Error {
266
+ constructor(
267
+ message: string,
268
+ readonly failureClass: AgyFailureClass,
269
+ ) {
270
+ super(message);
271
+ this.name = "AgyError";
272
+ }
273
+ }
274
+
115
275
  /**
116
276
  * Google Antigravity via the locally installed `agy` CLI. Uses whatever auth
117
277
  * the CLI holds — a logged-in subscription, so producing a video consumes
@@ -131,9 +291,12 @@ export class AntigravityProvider implements LlmProvider {
131
291
  readonly name = "antigravity";
132
292
  readonly usage: LlmUsage[] = [];
133
293
 
294
+ // A trailing options bag rather than a fourth positional: every existing
295
+ // `new AntigravityProvider(model, bin)` call site keeps compiling unchanged.
134
296
  constructor(
135
297
  private model?: string,
136
298
  private bin: string = process.env.OSSCLIP_AGY_BIN ?? "agy",
299
+ private opts: { effort?: LlmEffort } = {},
137
300
  ) {}
138
301
 
139
302
  async complete<T>(req: {
@@ -149,6 +312,11 @@ export class AntigravityProvider implements LlmProvider {
149
312
  `No markdown fences, no commentary, no tool use — just the JSON:\n${schemaText}`;
150
313
 
151
314
  let lastError = "";
315
+ // Wall time of every attempt that FAILED, in order — the facts the final
316
+ // error reports. Kept separately from `usage`, which only records attempts
317
+ // that got as far as an envelope: a call killed by --print-timeout never
318
+ // does, and a 10-minute hang is exactly the attempt a user needs to see.
319
+ const attemptMs: number[] = [];
152
320
  for (let attempt = 0; attempt < 2; attempt++) {
153
321
  const prompt =
154
322
  attempt === 0
@@ -164,41 +332,78 @@ export class AntigravityProvider implements LlmProvider {
164
332
  }
165
333
  const started = Date.now();
166
334
  let stdout = "";
335
+ let stderr = "";
167
336
  try {
168
- ({ stdout } = await run(
337
+ // allowNonZero, and it is load-bearing: agy reports its operational
338
+ // failures as exit 1 with the reason in the STDOUT envelope and
339
+ // nothing on stderr (measured 1.1.18 — see `agyErrorText`). run()'s
340
+ // default reject path keeps only the stderr tail, so it threw away
341
+ // every one of those reasons and handed this loop our own echoed
342
+ // argv instead. Resolving non-zero exits and reading the envelope is
343
+ // what makes both the message AND the fail-fast work.
344
+ ({ stdout, stderr } = await run(
169
345
  this.bin,
170
- buildAgyArgs(prompt, { model: this.model, schemaJson: schemaText }),
346
+ buildAgyArgs(prompt, {
347
+ model: this.model,
348
+ effort: this.opts.effort,
349
+ schemaJson: schemaText,
350
+ }),
351
+ { allowNonZero: true },
171
352
  ));
172
353
  } catch (err) {
354
+ // Only a spawn failure reaches here now: agy not on PATH, or not
355
+ // executable. Nothing was spent, and no retry can install it.
356
+ attemptMs.push(Date.now() - started);
173
357
  lastError = err instanceof Error ? err.message : String(err);
174
- // run() embeds the stderr tail in its rejection, so auth/bad-slug
175
- // failures are matchable here and fail fast instead of re-spending.
176
358
  if (isNonRetryableAgyFailure(lastError)) break;
359
+ // An externally killed spawn (SIGTERM/SIGKILL) classifies as timeout,
360
+ // and is as persistent as an expired --print-timeout — same fail-fast
361
+ // as the envelope path below.
362
+ if (classifyAgyFailure(lastError) === "timeout") break;
177
363
  continue;
178
364
  }
365
+ const elapsed = Date.now() - started;
179
366
  // Recorded per ATTEMPT, before validation: a reply that failed the
180
367
  // schema still spent the tokens, and a retry is exactly the cost a user
181
368
  // would want to see rather than have quietly absorbed.
182
369
  const envelope = parseAgyEnvelope(stdout);
183
- this.usage.push({
184
- provider: this.name,
185
- // The envelope names no model, so record what was asked for — or the
186
- // honest placeholder, which the cost report declines to price.
187
- model: this.model ?? "antigravity-default",
188
- schemaName: req.schemaName,
189
- inputTokens: envelope.inputTokens ?? estimateTokens(prompt),
190
- outputTokens: envelope.outputTokens ?? estimateTokens(envelope.response ?? stdout),
191
- cachedInputTokens: envelope.cachedInputTokens,
192
- exact: envelope.inputTokens !== undefined,
193
- // The whole point of this provider: agy's cached sign-in means the
194
- // subscription pays, not a card, and agy reports no cost to forward.
195
- billed: false,
196
- ms: Date.now() - started,
197
- });
370
+ // Gated on stdout now that non-zero exits resolve: a call that printed
371
+ // NOTHING never reached the model (exit 2, a usage error) and must not
372
+ // be booked as an estimated ~24k-token call. Anything that did reply —
373
+ // including an ERROR envelope reporting zeros — is still recorded.
374
+ if (stdout.trim()) {
375
+ this.usage.push({
376
+ provider: this.name,
377
+ // The envelope names no model, so record what was asked for — or the
378
+ // honest placeholder, which the cost report declines to price.
379
+ model: this.model ?? "antigravity-default",
380
+ schemaName: req.schemaName,
381
+ inputTokens: envelope.inputTokens ?? estimateTokens(prompt),
382
+ outputTokens: envelope.outputTokens ?? estimateTokens(envelope.response ?? stdout),
383
+ cachedInputTokens: envelope.cachedInputTokens,
384
+ exact: envelope.inputTokens !== undefined,
385
+ // The whole point of this provider: agy's cached sign-in means the
386
+ // subscription pays, not a card, and agy reports no cost to forward.
387
+ billed: false,
388
+ ms: elapsed,
389
+ // The envelope's own verdict (§143): a failed attempt's cost stays
390
+ // visible, but attribution (the production.json stamp) skips it.
391
+ failed: envelope.status !== "SUCCESS" || undefined,
392
+ });
393
+ }
394
+ // SUCCESS is the envelope's own word for "this worked" (§132 lists the
395
+ // status enum), and with non-zero exits resolving it is now the ONLY
396
+ // success test — an exit code we no longer see cannot be one.
198
397
  if (envelope.status !== "SUCCESS") {
199
- lastError =
200
- envelope.error ?? `agy reported status ${envelope.status ?? "unknown"}: ${stdout.slice(0, 300)}`;
398
+ attemptMs.push(elapsed);
399
+ lastError = agyErrorText(stdout, stderr);
201
400
  if (isNonRetryableAgyFailure(lastError)) break;
401
+ // A timed-out call never succeeds on retry at this call size —
402
+ // measured 2026-08-22: a ~63k-token beat-sheet call expired at the
403
+ // 10m --print-timeout twice in a row, so the second attempt only
404
+ // doubled the wall clock to 20 minutes. Fail fast; the escape hatch
405
+ // is another provider, not the same call again.
406
+ if (classifyAgyFailure(lastError) === "timeout") break;
202
407
  continue;
203
408
  }
204
409
  try {
@@ -209,12 +414,19 @@ export class AntigravityProvider implements LlmProvider {
209
414
  }
210
415
  return req.schema.parse(JSON.parse(extractJsonObject(envelope.response ?? stdout)));
211
416
  } catch (err) {
417
+ attemptMs.push(elapsed);
212
418
  lastError = err instanceof Error ? err.message : String(err);
213
419
  }
214
420
  }
215
- throw new Error(
216
- `agy CLI ('${this.bin}') did not produce valid ${req.schemaName} JSON: ${lastError.slice(0, 400)}\n` +
217
- `Is Antigravity installed and logged in? (https://antigravity.google — run 'agy' once interactively to sign in)`,
421
+ throw new AgyError(
422
+ agyFailureMessage({
423
+ bin: this.bin,
424
+ schemaName: req.schemaName,
425
+ lastError,
426
+ attemptMs,
427
+ printTimeout: AGY_PRINT_TIMEOUT,
428
+ }),
429
+ classifyAgyFailure(lastError),
218
430
  );
219
431
  }
220
432
  }
@@ -99,7 +99,37 @@ export const ClipBeatSheetSchema = BeatSheetSchema.extend({
99
99
  ),
100
100
  });
101
101
 
102
- export const PRODUCER_SYSTEM = `You are the producer for a short-form vertical video (Reels/Shorts/TikTok). You receive a word-indexed transcript of a talking-head take that has already been cut. Your job is EDITORIAL: segment the take into moments, pick which moments deserve a graphic scene, and write the on-screen copy.
102
+ /**
103
+ * Bump whenever `producerSystem`/`buildBeatsUserPrompt` change what they ask
104
+ * for: a prompt change changes the answer, so the beat-sheet/scenes cache key
105
+ * carries this (the §78 cache-key posture, same role as
106
+ * YOUTUBE_PROMPT_VERSION) — an old cached sheet must not survive a new prompt.
107
+ *
108
+ * v2: the system prompt stopped calling every output "vertical" (see
109
+ * `producerSystem`).
110
+ */
111
+ export const PRODUCER_PROMPT_VERSION = "v2";
112
+
113
+ /**
114
+ * The editorial system prompt, in the shape the output actually has.
115
+ *
116
+ * The opening sentence used to hardcode "short-form vertical video
117
+ * (Reels/Shorts/TikTok)" for every run, while `buildBeatsUserPrompt` has told
118
+ * 16:9 runs "Output frame: LANDSCAPE 16:9" since R21 §101 — so a landscape
119
+ * produce handed the model two contradictory descriptions of the same frame
120
+ * and left it to reconcile them (confirmed on a live 16:9 run, 2026-08).
121
+ *
122
+ * ONLY that sentence varies. Everything below it is the tuned 9:16 wording,
123
+ * byte-identical, and the portrait default must stay byte-identical to what
124
+ * shipped — the virality grammar was tuned against real runs of it, and a
125
+ * silent reword is a silent re-tune.
126
+ */
127
+ export function producerSystem(aspect?: "9:16" | "16:9"): string {
128
+ const shape =
129
+ aspect === "16:9"
130
+ ? "a landscape video (YouTube)"
131
+ : "a short-form vertical video (Reels/Shorts/TikTok)";
132
+ return `You are the producer for ${shape}. You receive a word-indexed transcript of a talking-head take that has already been cut. Your job is EDITORIAL: segment the take into moments, pick which moments deserve a graphic scene, and write the on-screen copy.
103
133
 
104
134
  Virality grammar — follow these as hard policies:
105
135
  - The first moment is the hook: the strongest claim or number anywhere in the take, on screen within 2 seconds.
@@ -115,10 +145,19 @@ Virality grammar — follow these as hard policies:
115
145
  - The transcript is ASR output and may contain mishearings: an unfamiliar proper noun is more likely a mistranscription of a common phrase than a real entity — write on-screen copy with the common-sense reading, never a suspected mishearing.
116
146
  - FRAMING: when the prompt carries a "Camera framing" brief, it is measured from the footage and is a HARD constraint: on words marked CLOSE, never choose a layout listed as UNAVAILABLE there — pick a \`layout\` that keeps the whole head in frame (pip-bubble, graphic-only, full-bleed) or leave the moment as "none". You may set \`layout\` on any moment; omit it to accept the component's default.
117
147
  - COVER: also write \`coverText\` — the hook compressed to a thumbnail headline, AT MOST ${COVER_MAX_WORDS} WORDS. It is read at a glance in a profile grid, so it must stand alone without the video: the claim or the number, no lead-in, no ellipsis.`;
148
+ }
149
+
150
+ /**
151
+ * The portrait prompt, kept as a named export because it is part of
152
+ * @ossclip/core's public surface (`export * from "./producer/beats"`) and
153
+ * removing it would break an importer for nothing. Equal to
154
+ * `producerSystem()` by construction — never a second copy of the text.
155
+ */
156
+ export const PRODUCER_SYSTEM = producerSystem();
118
157
 
119
158
  /**
120
159
  * The `--clip` request, appended to the USER prompt (R19 §93d). The tuned
121
- * PRODUCER_SYSTEM stays untouched — this adds the window request without
160
+ * system prompt stays untouched — this adds the window request without
122
161
  * rewriting the editorial instructions the beat sheet already follows.
123
162
  */
124
163
  export function buildClipAddendum(targetSec: number): string {
@@ -508,7 +547,9 @@ export async function generateBeatSheet(
508
547
  // Same editorial call, extended schema (R19 §93d) — the highlight and the
509
548
  // beat sheet come from ONE judgement, so they cannot disagree.
510
549
  const raw = await provider.complete({
511
- system: PRODUCER_SYSTEM,
550
+ // Same aspect the user prompt was built with — the two halves of one
551
+ // call must describe the same frame.
552
+ system: producerSystem(aspect),
512
553
  user,
513
554
  schema: ClipBeatSheetSchema,
514
555
  schemaName: "clip_beat_sheet",
@@ -517,7 +558,7 @@ export async function generateBeatSheet(
517
558
  return { ...normalizeBeatSheet(raw, transcript, null), asked, highlight: raw.highlight };
518
559
  }
519
560
  const raw = await provider.complete({
520
- system: PRODUCER_SYSTEM,
561
+ system: producerSystem(aspect),
521
562
  user,
522
563
  schema: BeatSheetSchema,
523
564
  schemaName: "beat_sheet",
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod/v4";
2
2
  import { run } from "../exec";
3
+ import { attemptFactsLine } from "./failure";
3
4
  import type { LlmProvider } from "./provider";
4
5
  import { estimateTokens, type LlmUsage } from "./usage";
5
6
 
@@ -38,6 +39,8 @@ export class ClaudeCliProvider implements LlmProvider {
38
39
  `No markdown fences, no commentary, no tool use — just the JSON:\n${schemaText}`;
39
40
 
40
41
  let lastError = "";
42
+ /** Wall time of every failed attempt — see `claudeCliFailureMessage`. */
43
+ const attemptMs: number[] = [];
41
44
  for (let attempt = 0; attempt < 2; attempt++) {
42
45
  const prompt =
43
46
  attempt === 0
@@ -50,6 +53,7 @@ export class ClaudeCliProvider implements LlmProvider {
50
53
  try {
51
54
  ({ stdout } = await run(this.bin, args, { stdin: prompt }));
52
55
  } catch (err) {
56
+ attemptMs.push(Date.now() - started);
53
57
  lastError = err instanceof Error ? err.message : String(err);
54
58
  continue;
55
59
  }
@@ -75,16 +79,92 @@ export class ClaudeCliProvider implements LlmProvider {
75
79
  try {
76
80
  return req.schema.parse(JSON.parse(extractJsonObject(unwrapCliEnvelope(stdout))));
77
81
  } catch (err) {
82
+ attemptMs.push(Date.now() - started);
78
83
  lastError = err instanceof Error ? err.message : String(err);
79
84
  }
80
85
  }
81
86
  throw new Error(
82
- `claude CLI ('${this.bin}') did not produce valid ${req.schemaName} JSON: ${lastError.slice(0, 400)}\n` +
83
- `Is Claude Code installed and logged in? (npm i -g @anthropic-ai/claude-code; run 'claude' once to /login)`,
87
+ claudeCliFailureMessage({ bin: this.bin, schemaName: req.schemaName, lastError, attemptMs }),
84
88
  );
85
89
  }
86
90
  }
87
91
 
92
+ /** What the failure text says went wrong. See `classifyClaudeCliFailure`. */
93
+ export type ClaudeCliFailureClass = "auth" | "model" | "timeout" | "schema" | "unknown";
94
+
95
+ /**
96
+ * Classify a `claude -p` failure. Pure, and exported so each class is
97
+ * assertable without spawning the CLI.
98
+ *
99
+ * Same disease as agy's (FINDINGS §132): the sign-in hint below used to be
100
+ * appended to EVERY failure, so a bad model slug or a schema-repair loop told
101
+ * the user to check a login that was fine. Same cure — classify, print the
102
+ * attempt facts unconditionally, gate the advice.
103
+ *
104
+ * The surfaces are NOT the same, and this one was measured too (Claude Code,
105
+ * 2026-08-22, a bad `--model` slug): exit 1, a machine-readable
106
+ * `[claude-code:unrecognized_model] {…}` on STDERR, and a human sentence in
107
+ * the stdout envelope's `result`. Because it uses stderr — and because the
108
+ * prompt rides STDIN here, so `run()`'s rejection echoes a short argv rather
109
+ * than the whole transcript — the rejection message this receives already
110
+ * carries the reason, and no `allowNonZero` change is needed to see it.
111
+ *
112
+ * `auth` is inferred, not measured: establishing it would mean signing the
113
+ * user out. Its patterns are widened only to things that cannot mean anything
114
+ * else, so a real auth failure still gets the hint it always got.
115
+ */
116
+ export function classifyClaudeCliFailure(message: string): ClaudeCliFailureClass {
117
+ if (/invalid api key|authentication|not logged in|\/login|unauthorized|oauth/i.test(message))
118
+ return "auth";
119
+ if (/unrecognized_model|unknown model|invalid model|model .* not (found|recognized)/i.test(message))
120
+ return "model";
121
+ if (/timed? ?out|ETIMEDOUT|SIGTERM|SIGKILL/i.test(message)) return "timeout";
122
+ const schemaish = /no JSON object in reply|is not valid JSON|Unexpected (token|end of)|"code":\s*"/i;
123
+ if (schemaish.test(message)) return "schema";
124
+ return "unknown";
125
+ }
126
+
127
+ /**
128
+ * The error thrown when both attempts failed. The attempt facts print for
129
+ * every class because they self-diagnose regardless of the classification
130
+ * (§132); the sign-in hint is gated to `auth`, and a model failure points at
131
+ * the flag that actually caused it.
132
+ */
133
+ export function claudeCliFailureMessage(parts: {
134
+ bin: string;
135
+ schemaName: string;
136
+ lastError: string;
137
+ attemptMs: readonly number[];
138
+ }): string {
139
+ const cls = classifyClaudeCliFailure(parts.lastError);
140
+ const headline =
141
+ cls === "timeout"
142
+ ? " — the call timed out"
143
+ : cls === "schema"
144
+ ? " — the reply never matched the schema"
145
+ : "";
146
+ const lines = [
147
+ `claude CLI ('${parts.bin}') did not produce valid ${parts.schemaName} JSON${headline}: ` +
148
+ (parts.lastError.trim().slice(0, 400) || "claude printed nothing"),
149
+ attemptFactsLine(parts.attemptMs),
150
+ ];
151
+ if (cls === "auth") {
152
+ lines.push(
153
+ `Is Claude Code installed and logged in? (npm i -g @anthropic-ai/claude-code; run 'claude' once to /login)`,
154
+ );
155
+ }
156
+ if (cls === "model") {
157
+ lines.push(`Check the --llm-model slug, or drop it to use the CLI's own default model.`);
158
+ }
159
+ if (cls === "timeout") {
160
+ lines.push(
161
+ `Use --llm antigravity (a logged-in Antigravity subscription) or --llm gemini (needs GEMINI_API_KEY), ` +
162
+ `or drop --produce to cut and caption without a planner.`,
163
+ );
164
+ }
165
+ return lines.join("\n");
166
+ }
167
+
88
168
  /**
89
169
  * The accounting half of the same envelope: tokens, cost and model, all
90
170
  * optional because the CLI's envelope shape is not ours to depend on. Every
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The facts every failed LLM call can state without guessing why it failed.
3
+ *
4
+ * From the 2026-08-22 incident (FINDINGS §132): a `--produce --aspect 16:9`
5
+ * run on an 11-minute take timed out twice at agy's print timeout — 10m each,
6
+ * 25 minutes burned — and died with "Is Antigravity installed and logged in?"
7
+ * on an agy that was installed, logged in and working. What that user needed
8
+ * was not a better guess, it was the shape of the wait: two attempts, ten
9
+ * minutes each. Attempt facts self-diagnose a hang, and they stay true when
10
+ * the classification is wrong — so both CLI providers print them for EVERY
11
+ * failure class, and gate only the advice.
12
+ *
13
+ * Pure, and shared so the two providers cannot drift into two formats for the
14
+ * same sentence.
15
+ */
16
+
17
+ /** `600_000 → "10m0s"`, `1_500 → "1.5s"` — an at-a-glance wall time. */
18
+ export function formatElapsed(ms: number): string {
19
+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
20
+ // Floored, not rounded: 1m59.6s must not print as "1m60s".
21
+ return `${Math.floor(ms / 60_000)}m${Math.floor((ms % 60_000) / 1000)}s`;
22
+ }
23
+
24
+ /**
25
+ * "2 attempts, 10m0s and 10m0s" — how many calls ran and how long each took,
26
+ * with `extra` appended for a provider that has a clock worth naming (agy's
27
+ * `--print-timeout`). An empty list still says "0 attempts": a call that never
28
+ * spawned is itself the diagnosis.
29
+ */
30
+ export function attemptFactsLine(attemptMs: readonly number[], extra?: string): string {
31
+ const times = attemptMs.map(formatElapsed);
32
+ const listed =
33
+ times.length > 1
34
+ ? `${times.slice(0, -1).join(", ")} and ${times[times.length - 1]}`
35
+ : (times[0] ?? "");
36
+ return (
37
+ `${attemptMs.length} attempt${attemptMs.length === 1 ? "" : "s"}` +
38
+ `${listed ? `, ${listed}` : ""}${extra ? `, ${extra}` : ""}.`
39
+ );
40
+ }