@sensigo/realm-cli 0.38.0 → 0.40.0

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 (99) hide show
  1. package/dist/agent/drive-failure.d.ts +62 -0
  2. package/dist/agent/drive-failure.d.ts.map +1 -0
  3. package/dist/agent/drive-failure.js +241 -0
  4. package/dist/agent/drive-failure.js.map +1 -0
  5. package/dist/agent/providers/agent-utils.d.ts +132 -0
  6. package/dist/agent/providers/agent-utils.d.ts.map +1 -1
  7. package/dist/agent/providers/agent-utils.js +348 -1
  8. package/dist/agent/providers/agent-utils.js.map +1 -1
  9. package/dist/agent/providers/anthropic-provider.d.ts +51 -1
  10. package/dist/agent/providers/anthropic-provider.d.ts.map +1 -1
  11. package/dist/agent/providers/anthropic-provider.js +109 -30
  12. package/dist/agent/providers/anthropic-provider.js.map +1 -1
  13. package/dist/agent/providers/llm-provider.d.ts +13 -1
  14. package/dist/agent/providers/llm-provider.d.ts.map +1 -1
  15. package/dist/agent/providers/llm-provider.js +8 -4
  16. package/dist/agent/providers/llm-provider.js.map +1 -1
  17. package/dist/agent/providers/openai-provider.d.ts +6 -1
  18. package/dist/agent/providers/openai-provider.d.ts.map +1 -1
  19. package/dist/agent/providers/openai-provider.js +75 -20
  20. package/dist/agent/providers/openai-provider.js.map +1 -1
  21. package/dist/agent/providers/openai-reasoning-provider.d.ts +4 -1
  22. package/dist/agent/providers/openai-reasoning-provider.d.ts.map +1 -1
  23. package/dist/agent/providers/openai-reasoning-provider.js +21 -6
  24. package/dist/agent/providers/openai-reasoning-provider.js.map +1 -1
  25. package/dist/agent/run-agent.d.ts +9 -0
  26. package/dist/agent/run-agent.d.ts.map +1 -1
  27. package/dist/agent/run-agent.js +775 -680
  28. package/dist/agent/run-agent.js.map +1 -1
  29. package/dist/agent/run-attach.d.ts.map +1 -1
  30. package/dist/agent/run-attach.js +58 -11
  31. package/dist/agent/run-attach.js.map +1 -1
  32. package/dist/agent/test-support/anthropic-stub.d.ts +45 -0
  33. package/dist/agent/test-support/anthropic-stub.d.ts.map +1 -0
  34. package/dist/agent/test-support/anthropic-stub.js +146 -0
  35. package/dist/agent/test-support/anthropic-stub.js.map +1 -0
  36. package/dist/agent/test-support/composed-journey.d.ts +40 -0
  37. package/dist/agent/test-support/composed-journey.d.ts.map +1 -0
  38. package/dist/agent/test-support/composed-journey.js +104 -0
  39. package/dist/agent/test-support/composed-journey.js.map +1 -0
  40. package/dist/agent/test-support/mcp-server-entry.d.ts +20 -0
  41. package/dist/agent/test-support/mcp-server-entry.d.ts.map +1 -0
  42. package/dist/agent/test-support/mcp-server-entry.js +39 -0
  43. package/dist/agent/test-support/mcp-server-entry.js.map +1 -0
  44. package/dist/agent/test-support/openai-stub.d.ts +47 -0
  45. package/dist/agent/test-support/openai-stub.d.ts.map +1 -0
  46. package/dist/agent/test-support/openai-stub.js +115 -0
  47. package/dist/agent/test-support/openai-stub.js.map +1 -0
  48. package/dist/commands/abandon.d.ts.map +1 -1
  49. package/dist/commands/abandon.js +8 -1
  50. package/dist/commands/abandon.js.map +1 -1
  51. package/dist/commands/agent.d.ts.map +1 -1
  52. package/dist/commands/agent.js +17 -0
  53. package/dist/commands/agent.js.map +1 -1
  54. package/dist/commands/cleanup.d.ts.map +1 -1
  55. package/dist/commands/cleanup.js +21 -9
  56. package/dist/commands/cleanup.js.map +1 -1
  57. package/dist/commands/export.d.ts +5 -2
  58. package/dist/commands/export.d.ts.map +1 -1
  59. package/dist/commands/export.js +1 -1
  60. package/dist/commands/export.js.map +1 -1
  61. package/dist/commands/gc.d.ts +1 -1
  62. package/dist/commands/gc.d.ts.map +1 -1
  63. package/dist/commands/gc.js +29 -4
  64. package/dist/commands/gc.js.map +1 -1
  65. package/dist/commands/inspect.d.ts.map +1 -1
  66. package/dist/commands/inspect.js +86 -1
  67. package/dist/commands/inspect.js.map +1 -1
  68. package/dist/commands/list.d.ts.map +1 -1
  69. package/dist/commands/list.js +35 -0
  70. package/dist/commands/list.js.map +1 -1
  71. package/dist/commands/listen.d.ts.map +1 -1
  72. package/dist/commands/listen.js +9 -5
  73. package/dist/commands/listen.js.map +1 -1
  74. package/dist/commands/purge.d.ts +22 -1
  75. package/dist/commands/purge.d.ts.map +1 -1
  76. package/dist/commands/purge.js +70 -42
  77. package/dist/commands/purge.js.map +1 -1
  78. package/dist/commands/register.d.ts.map +1 -1
  79. package/dist/commands/register.js +3 -1
  80. package/dist/commands/register.js.map +1 -1
  81. package/dist/commands/run-migrate.d.ts +83 -0
  82. package/dist/commands/run-migrate.d.ts.map +1 -0
  83. package/dist/commands/run-migrate.js +303 -0
  84. package/dist/commands/run-migrate.js.map +1 -0
  85. package/dist/commands/validate.d.ts.map +1 -1
  86. package/dist/commands/validate.js +7 -5
  87. package/dist/commands/validate.js.map +1 -1
  88. package/dist/commands/watch.d.ts.map +1 -1
  89. package/dist/commands/watch.js +6 -4
  90. package/dist/commands/watch.js.map +1 -1
  91. package/dist/commands-registry.d.ts.map +1 -1
  92. package/dist/commands-registry.js +4 -0
  93. package/dist/commands-registry.js.map +1 -1
  94. package/dist/index.js +1 -1
  95. package/dist/lib/loader-warnings.d.ts +22 -1
  96. package/dist/lib/loader-warnings.d.ts.map +1 -1
  97. package/dist/lib/loader-warnings.js +42 -2
  98. package/dist/lib/loader-warnings.js.map +1 -1
  99. package/package.json +5 -4
@@ -34,12 +34,31 @@ let additionalRedactionValues = [];
34
34
  export function setAdditionalRedactionValues(values) {
35
35
  additionalRedactionValues = values;
36
36
  }
37
+ /**
38
+ * npm's manifest metadata — public values copied out of package.json, not secrets. The negative
39
+ * lookahead keeps `npm_package_config_*` OUT of this exclusion (see sanitizeError's doc).
40
+ */
41
+ const NPM_MANIFEST_METADATA = /^npm_(package_(?!config_)|lifecycle_)/;
37
42
  /**
38
43
  * Converts an error value to a string and strips sensitive patterns: Bearer tokens,
39
44
  * query-string tokens, process.env values longer than 4 characters, and the additional
40
45
  * (manifest-secret) values. All literal values are redacted in ONE combined pass,
41
46
  * deduped and applied LONGEST-FIRST — a short value contained in a longer one can no
42
47
  * longer leave fragments of the longer value behind.
48
+ *
49
+ * EXCLUDED from the env sweep (issue #407): npm's own manifest metadata —
50
+ * `npm_package_*` (except `npm_package_config_*`) and `npm_lifecycle_*`. These are values npm
51
+ * copies OUT OF package.json, so treating them as secrets meant realm redacted its own name and
52
+ * version from its own error messages: under npm, `npm_package_name` is `"realm"`, and a message
53
+ * reading "realm agent requires…" shipped as "[REDACTED] agent requires…". Harmless while it was
54
+ * console-only; issue #401 persists these messages in the run record, which made the mangling
55
+ * durable evidence.
56
+ *
57
+ * `npm_package_config_*` deliberately STAYS redacted, and the lookahead that keeps it in is
58
+ * load-bearing: a package.json `config` block holds values the AUTHOR wrote, and npm exports them
59
+ * verbatim — a probe on this repo produced `npm_package_config_apitoken=SUPERSECRETVALUE123`.
60
+ * `npm_config_*` stays for the same reason. Widening this exclusion to all `npm_*` would leak
61
+ * exactly the values most likely to be secrets.
43
62
  */
44
63
  export function sanitizeError(err) {
45
64
  let text;
@@ -54,7 +73,10 @@ export function sanitizeError(err) {
54
73
  }
55
74
  text = text.replace(/Bearer [A-Za-z0-9._-]+/g, 'Bearer [REDACTED]');
56
75
  text = text.replace(/token=[A-Za-z0-9._-]+/g, 'token=[REDACTED]');
57
- const envValues = Object.values(process.env).filter((val) => val !== undefined && val.length > 4);
76
+ const envValues = Object.entries(process.env)
77
+ .filter(([key]) => !NPM_MANIFEST_METADATA.test(key))
78
+ .map(([, val]) => val)
79
+ .filter((val) => val !== undefined && val.length > 4);
58
80
  const combined = [...new Set([...envValues, ...additionalRedactionValues])].sort((a, b) => b.length - a.length);
59
81
  for (const val of combined) {
60
82
  text = text.split(val).join('[REDACTED]');
@@ -69,6 +91,60 @@ export function serializeToolResult(result) {
69
91
  const raw = typeof result === 'string' ? result : JSON.stringify(result);
70
92
  return sanitizeError(raw);
71
93
  }
94
+ /** The `error` text for a Class-B result whose content carries no readable text at all. */
95
+ export const CLASS_B_NO_TEXT_MARKER = 'tool returned isError with no text content';
96
+ /**
97
+ * Extracts the failure text from a POLITELY FAILED tool call — issue #345.
98
+ *
99
+ * MCP defines two ways a tool call fails. The transport can reject (Class A: an exception, which
100
+ * the providers' catch branch already records honestly), or the call can RETURN normally with
101
+ * `isError: true` inside the result (Class B: the polite failure the spec defines for a tool
102
+ * reporting its own error to the model). Class B used to be minted as a success — no `error`
103
+ * field, the failure text buried inside `result` — which made the record type's own doc contract
104
+ * false and made every tool-reliability count read failures as successes.
105
+ *
106
+ * Returns the sanitized failure text for a Class-B result, or `undefined` for anything else — so
107
+ * a caller writes `const err = classBError(raw)` and branches on presence.
108
+ *
109
+ * WHY `=== true` AND NOT TRUTHINESS. The SDK zod-validates every `callTool` response against
110
+ * `CallToolResultSchema`, where `isError` is `z.boolean().optional()`. A non-boolean `isError`
111
+ * fails that parse, the promise REJECTS, and the call lands in the catch branch as Class A —
112
+ * recorded WITH an `error` either way. So the spec-illegal world cannot reach this mint through
113
+ * the real transport, and a strict check cannot silently swallow a failure. (The fixture in the
114
+ * strict-boolean cell models a wire state that cannot occur; it exists to pin the choice, not a
115
+ * reachable case.) This premise breaks only if realm switches to
116
+ * `CompatibilityCallToolResultSchema` or talks to a raw transport that skips validation — if that
117
+ * ever happens, revisit this line first.
118
+ */
119
+ export function classBError(rawResult) {
120
+ if (typeof rawResult !== 'object' || rawResult === null)
121
+ return undefined;
122
+ const result = rawResult;
123
+ if (result.isError !== true)
124
+ return undefined;
125
+ const blocks = Array.isArray(result.content) ? result.content : [];
126
+ const text = blocks
127
+ .filter((b) => typeof b === 'object' &&
128
+ b !== null &&
129
+ b.type === 'text' &&
130
+ typeof b.text === 'string')
131
+ .map((b) => b.text)
132
+ // '\n' is specified rather than incidental: two providers mint this and a different join
133
+ // would make the same failure read differently depending on which one ran.
134
+ .join('\n');
135
+ // Empty JOINED text, not merely absent blocks — `text: ''` is transport-legal, and an empty
136
+ // `error` would be invisible to inspect's truthiness check, so a politely-failed call would
137
+ // render as unfailed. The marker is what stops that.
138
+ //
139
+ // Tested on the TRIMMED text, and that is not fussiness: TWO empty blocks join to `'\n'`, which
140
+ // is length 1 and would have sailed past a `length === 0` check — producing an `error` that is
141
+ // technically truthy and visually nothing, which is the same invisible failure wearing a
142
+ // different hat. (Found by the all-empty cell below, which is why it exists.) The returned text
143
+ // is never trimmed — only the emptiness question is.
144
+ if (text.trim().length === 0)
145
+ return CLASS_B_NO_TEXT_MARKER;
146
+ return sanitizeError(text);
147
+ }
72
148
  /** Splits "server_id:tool_name" into its components. Throws if the format is invalid. */
73
149
  export function parseNamespacedId(id) {
74
150
  const colonIdx = id.indexOf(':');
@@ -291,4 +367,275 @@ export function extractApiErrorFields(err) {
291
367
  out.api_code = typeof e.code === 'string' ? e.code : null;
292
368
  return out;
293
369
  }
370
+ // =================================================================================================
371
+ // issue #401 — the per-create budget: the counting fetch, the ceiling, and the attribution
372
+ //
373
+ // THE INVARIANT: no single model request can hold a drive hostage. The SDK's own `timeout` bounds
374
+ // one ATTEMPT; nothing bounded the whole create, so a server directing a two-hour Retry-After, or
375
+ // a connection that hung after headers, could park a drive indefinitely with nothing recorded.
376
+ //
377
+ // Scope, stated because the claim must not overreach: this bounds realm's IN-REPO providers, which
378
+ // consume the clock. A `--provider-module` provider still gets the RECORD when it fails — it just
379
+ // does not get the bound.
380
+ // =================================================================================================
381
+ /** Realm's own retry count, passed EXPLICITLY to every SDK client. */
382
+ export const MAX_RETRIES = 2;
383
+ /** The download allowance the derived ceiling adds on top of the retry budget. */
384
+ const DOWNLOAD_ALLOWANCE_MS = 60_000;
385
+ /**
386
+ * The largest delay a timer can hold. Past it `setTimeout` overflows and fires ~immediately,
387
+ * which would inVERT a huge budget into an instant abort (gate-expiry-timer.ts:24 clamps for the
388
+ * same reason). Both timers matter here: realm's own ceiling, and the `timeout` realm hands the
389
+ * SDK — an unclamped per-attempt value overflows one layer down and returns as a
390
+ * `connection_timeout` that has nothing to do with the connection.
391
+ */
392
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
393
+ /**
394
+ * Derives the whole-create ceiling from a per-attempt value.
395
+ *
396
+ * `perAttempt × (MAX_RETRIES + 1)` covers every attempt the SDK will make, plus the backoff it
397
+ * sleeps between them, plus a download allowance so a large-but-progressing response is never
398
+ * killed for being large. The backoff term is the SDK's OWN schedule summed as an UPPER bound —
399
+ * its jitter only ever reduces the wait, so budgeting the un-jittered sum cannot cut short a
400
+ * retry the SDK scheduled for itself.
401
+ *
402
+ * A SERVER-DIRECTED wait is a different thing and is deliberately NOT budgeted. A `Retry-After`
403
+ * can ask for hours; the ceiling outranks it on purpose, which is the point of the bound rather
404
+ * than a gap in it.
405
+ */
406
+ export function deriveLlmClock(perAttemptMs) {
407
+ let backoffMarginMs = 0;
408
+ for (let n = 0; n < MAX_RETRIES; n++)
409
+ backoffMarginMs += Math.min(0.5 * 2 ** n, 8) * 1000;
410
+ // Clamped BEFORE the arithmetic and again after it, because both numbers arm a real timer. The
411
+ // clamped per-attempt value is what gets recorded too — the record states what actually bounds
412
+ // the attempt, not what someone asked for. There is deliberately no validator upper bound: a
413
+ // huge value is not an authoring error, it is a request for "effectively no limit", and that is
414
+ // what it gets.
415
+ const perAttempt = Math.min(perAttemptMs, MAX_TIMEOUT_MS);
416
+ return {
417
+ ceilingMs: Math.min(perAttempt * (MAX_RETRIES + 1) + backoffMarginMs + DOWNLOAD_ALLOWANCE_MS, MAX_TIMEOUT_MS),
418
+ declaredPerAttemptMs: perAttempt,
419
+ };
420
+ }
421
+ /**
422
+ * Parses all three Retry-After forms into milliseconds: `retry-after-ms`, a numeric
423
+ * `Retry-After` in seconds, and an HTTP-date `Retry-After`. OBSERVED, never honored by realm.
424
+ *
425
+ * The date form is legal, the SDKs honor it, and a parser that only understood numbers dropped a
426
+ * whole header form on the floor — recording nothing for a rate limit that was clearly signalled.
427
+ * A date already in the past observes as 0 (the wait is over; a negative number would be a
428
+ * nonsense measurement), while a header nobody can parse observes as nothing at all — realm has
429
+ * no idea what was asked for and says so by omission rather than by inventing a zero.
430
+ */
431
+ function parseRetryAfterMs(headers) {
432
+ const ms = headers.get('retry-after-ms');
433
+ if (ms !== null && ms.trim() !== '' && Number.isFinite(Number(ms)))
434
+ return Number(ms);
435
+ const after = headers.get('retry-after');
436
+ if (after === null || after.trim() === '')
437
+ return undefined;
438
+ if (Number.isFinite(Number(after)))
439
+ return Number(after) * 1000;
440
+ // `Number`, deliberately, not `parseFloat`. RFC 9110 says a Retry-After is EITHER digits-only
441
+ // seconds or an HTTP-date; `parseFloat('7200abc')` would happily read 7200 out of a header that
442
+ // is neither, and record a measurement the server never sent. The strict parse falls through to
443
+ // the date arm and then to nothing, which is the truthful answer for a malformed header.
444
+ const at = Date.parse(after);
445
+ if (!Number.isFinite(at))
446
+ return undefined;
447
+ return Math.max(0, at - Date.now());
448
+ }
449
+ /**
450
+ * Wraps `fetch` so realm can SEE what the SDK's retry ladder did — how many attempts it made, the
451
+ * last status, and any Retry-After the server asked for, in all three of its legal forms
452
+ * (`retry-after-ms`, a numeric `Retry-After`, an HTTP-date `Retry-After`).
453
+ *
454
+ * Observation only. Realm never honors a Retry-After: acting on it would be a scheduling decision
455
+ * this layer does not make, and recording it is what lets an operator tell a rate limit apart from
456
+ * a hang. The inner fetch is injectable so the wrapper is unit-testable without a socket.
457
+ */
458
+ export function makeCountingFetch(counters, innerFetch = globalThis.fetch) {
459
+ return async (input, init) => {
460
+ try {
461
+ const res = await innerFetch(input, init);
462
+ counters.attempts++;
463
+ counters.lastStatus = res.status;
464
+ const retryAfter = parseRetryAfterMs(res.headers);
465
+ if (retryAfter !== undefined)
466
+ counters.lastRetryAfterMs = retryAfter;
467
+ return res;
468
+ }
469
+ catch (err) {
470
+ // A rejection is still an attempt — it just carries no status to observe.
471
+ counters.attempts++;
472
+ throw err;
473
+ }
474
+ };
475
+ }
476
+ /**
477
+ * Attaches a payload to an error, WITHOUT overwriting one that is already there.
478
+ *
479
+ * TOTAL. Both the probe and the assignment can throw on a value realm did not create — `in` runs
480
+ * a proxy's `has` trap, and assigning to a frozen object throws in strict mode. Either one would
481
+ * hand the caller the attacher's own TypeError in place of the failure it was trying to describe,
482
+ * which is the whole attribution chain defeated by the last link in it. An error that cannot be
483
+ * enriched still propagates, intact and unenriched; shape classification never needed the payload.
484
+ */
485
+ export function attachDriveCall(err, payload) {
486
+ if (typeof err !== 'object' || err === null)
487
+ return;
488
+ try {
489
+ if ('driveCall' in err)
490
+ return; // e.g. getClient's sdk_missing attach — never re-attributed
491
+ err.driveCall = payload;
492
+ }
493
+ catch {
494
+ /* enrichment never out-throws the error being attributed */
495
+ }
496
+ }
497
+ /**
498
+ * Converts any thrown value to display text, TOTALLY.
499
+ *
500
+ * The chokepoints interpolate the thrown value into their console line BEFORE recording it, so a
501
+ * poisoned `toString` used to out-throw at the print — replacing the operator's error with a
502
+ * secondary one before the (already hardened) mint could run.
503
+ */
504
+ export function safeErrorText(err) {
505
+ try {
506
+ return err instanceof Error ? err.message : String(err);
507
+ }
508
+ catch {
509
+ return 'unrenderable thrown value';
510
+ }
511
+ }
512
+ /**
513
+ * Classifies an SDK-raised error by shape, for the payload's `error_class`.
514
+ *
515
+ * BOTH `name` and `constructor.name` are checked, and the second is the one that works. Neither
516
+ * installed SDK sets `.name` on its error classes — a real `APIConnectionError` from either one
517
+ * reports `name === 'Error'` and carries its identity on the constructor — so a check on `.name`
518
+ * alone recorded every genuine connection failure and every genuine request timeout as `other`.
519
+ * `.name` is kept because a wrapper that re-throws with a copied name is a real shape too.
520
+ *
521
+ * The timeout arm sits first as a belt: under exact string equality a real timeout cannot match
522
+ * the connection arm anyway (its constructor name is the leaf), but a wrapper copying a parent
523
+ * `.name` onto a timeout instance could.
524
+ *
525
+ * TOTAL. This runs inside driveCreate's catch, where a throw would replace the operator's failure
526
+ * with realm's own — and reading `constructor` and `name` off a value realm did not create can
527
+ * throw. (That hole predates the constructor check: a poisoned `.name` getter out-threw here.)
528
+ */
529
+ function shapeClass(err) {
530
+ try {
531
+ const name = err?.name;
532
+ const ctor = err?.constructor?.name;
533
+ if (name === 'APIConnectionTimeoutError' || ctor === 'APIConnectionTimeoutError') {
534
+ return 'connection_timeout';
535
+ }
536
+ if (name === 'APIConnectionError' || ctor === 'APIConnectionError')
537
+ return 'connection_error';
538
+ if (extractHttpStatus(err) !== undefined)
539
+ return 'api_status';
540
+ return 'other';
541
+ }
542
+ catch {
543
+ return 'other';
544
+ }
545
+ }
546
+ /**
547
+ * Runs ONE model create under realm's ceiling.
548
+ *
549
+ * Two mechanisms, because one is not enough. The timer is what bounds the wall clock; the abort is
550
+ * what actually stops work — but only as far as the SDK will let it. The SDK's sleep primitive is
551
+ * signal-aware, yet its retry site passes no signal, so a raced-out backoff sleep runs to
552
+ * completion in the worker. That is the ceiling's known reach, not a bug in it: an SDK bump that
553
+ * threads the signal there would make the race leg partially redundant, and it would still be
554
+ * earning its keep on the post-header body hang.
555
+ *
556
+ * Wraps the CREATE only. Client construction stays outside — that is where a missing SDK attaches
557
+ * its own payload, and this must never re-attribute it.
558
+ */
559
+ export async function driveCreate(rawCreate, body, clock, counters) {
560
+ const before = { ...counters };
561
+ // The observations are cleared, the attempt total is not. `attempts` is a running count, so a
562
+ // delta is the right question for it; a status is an OBSERVATION, and asking "did it change?"
563
+ // means a second identical 429 reads as nothing observed at all — the discriminator vanishing
564
+ // exactly during the rate-limit storm it exists to describe. Cleared here, they are present in
565
+ // the payload if and only if THIS create saw them.
566
+ delete counters.lastStatus;
567
+ delete counters.lastRetryAfterMs;
568
+ const started = Date.now();
569
+ const controller = new AbortController();
570
+ let timer;
571
+ let fired = false;
572
+ const ceiling = new Promise((_, reject) => {
573
+ timer = setTimeout(() => {
574
+ fired = true;
575
+ reject(new Error('__realm_ceiling__'));
576
+ }, clock.ceilingMs);
577
+ });
578
+ // A race has a LOSER, and an unobserved rejected promise takes the process down on Node >= 15.
579
+ // DEFENSE IN DEPTH, stated precisely: `Promise.race` subscribes to every promise it is given,
580
+ // and that subscription counts as handling — so as long as the race below actually runs, neither
581
+ // loser can go unhandled, and probing this line away does NOT trip an unhandledRejection trap.
582
+ // What made the class real was the path where the race NEVER RAN: a create that threw
583
+ // synchronously escaped before `Promise.race`, leaving this timer to fire into nothing and kill
584
+ // the process. That path is closed structurally below; this line is the belt for a future
585
+ // refactor that stops racing, which is why it survives a probe showing it does nothing today.
586
+ void ceiling.catch(() => undefined);
587
+ // Declared out here so the fired path can observe the loser; ASSIGNED inside the try, because a
588
+ // provider whose create throws SYNCHRONOUSLY (a bad argument, a mocked double) would otherwise
589
+ // escape past both the classification and the `finally` — leaving the error unattributed and
590
+ // the timer running to fire into nothing.
591
+ let sdkCall;
592
+ try {
593
+ sdkCall = (async () => rawCreate(body, { signal: controller.signal }))();
594
+ return await Promise.race([sdkCall, ceiling]);
595
+ }
596
+ catch (err) {
597
+ // Present iff THIS create observed them — the fields were cleared at the top, so a stale
598
+ // status from a previous create cannot attach to this failure and tell a confident lie about
599
+ // what just happened.
600
+ const sawStatus = counters.lastStatus !== undefined;
601
+ const sawRetryAfter = counters.lastRetryAfterMs !== undefined;
602
+ const delta = {
603
+ attempts_sdk: counters.attempts - before.attempts,
604
+ elapsed_ms: Date.now() - started,
605
+ ...(sawStatus ? { last_observed_status: counters.lastStatus } : {}),
606
+ ...(sawRetryAfter ? { retry_after_observed_ms: counters.lastRetryAfterMs } : {}),
607
+ ...(clock.declaredPerAttemptMs !== undefined
608
+ ? { declared_per_attempt_ms: clock.declaredPerAttemptMs }
609
+ : {}),
610
+ derived_ceiling_ms: clock.ceilingMs,
611
+ };
612
+ if (fired) {
613
+ controller.abort();
614
+ // The loser's rejection still arrives — an APIUserAbortError, moments later. Same defense
615
+ // in depth as the timer's catch above, and the same honest caveat: the race is already
616
+ // subscribed, so this is insurance rather than the thing currently preventing a crash.
617
+ void sdkCall?.catch(() => undefined);
618
+ // The lever named is the one that is actually LIVE. Telling an operator to raise a flag
619
+ // that a step key is already overriding sends them to change something with no effect —
620
+ // so provenance decides which arm renders. With no provenance at all (a hand-built clock)
621
+ // both arms render, because either could be the live one.
622
+ const source = clock.perAttemptSource;
623
+ const stepArm = source === undefined || source === 'step';
624
+ const flagArm = source === undefined || source === 'flag' || source === 'default';
625
+ const levers = [
626
+ ...(stepArm ? ['raise llm_timeout_seconds on the step'] : []),
627
+ ...(flagArm ? ['pass a larger --llm-timeout'] : []),
628
+ ].join(' or ');
629
+ const aborted = new Error(`LLM create exceeded the per-create ceiling (${String(clock.ceilingMs)}ms) — ${levers}`);
630
+ attachDriveCall(aborted, { error_class: 'aborted_by_budget', ...delta });
631
+ throw aborted;
632
+ }
633
+ attachDriveCall(err, { error_class: shapeClass(err), ...delta });
634
+ throw err;
635
+ }
636
+ finally {
637
+ if (timer !== undefined)
638
+ clearTimeout(timer);
639
+ }
640
+ }
294
641
  //# sourceMappingURL=agent-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.js","sourceRoot":"","sources":["../../../src/agent/providers/agent-utils.ts"],"names":[],"mappings":"AAGA,MAAM,kBAAkB,GACtB,kEAAkE;IAClE,8FAA8F,CAAC;AAEjG,mGAAmG;AACnG,mGAAmG;AACnG,2GAA2G;AAC3G,MAAM,4BAA4B,GAChC,kEAAkE;IAClE,8FAA8F;IAC9F,wDAAwD,CAAC;AAE3D;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAC/B,WAAqC,EACrC,wBAAiC,EACjC,qBAA+B;IAE/B,MAAM,UAAU,GACd,qBAAqB,KAAK,IAAI,CAAC,CAAC,CAAC,4BAA4B,CAAC,CAAC,CAAC,kBAAkB,CAAC;IACrF,MAAM,IAAI,GACR,wBAAwB,KAAK,SAAS;QACpC,CAAC,CAAC,GAAG,wBAAwB,OAAO,UAAU,EAAE;QAChD,CAAC,CAAC,UAAU,CAAC;IACjB,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IAC3C,OAAO,GAAG,IAAI,2CAA2C,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC;A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M,KAAK,MAAM,IAAI,MAAM,KAAK,SAAS,CAAC;YAClF,MAAM,MAAM,GAAG;gBACb,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,uCAAuC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC7D,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;aACpD,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACf,MAAM,OAAO,GAAG,IAAI,KAAK,CACvB,+CAA+C,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,SAAS,MAAM,EAAE,CACxF,CAAC;YACF,eAAe,CAAC,OAAO,EAAE,EAAE,WAAW,EAAE,mBAAmB,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;YACzE,MAAM,OAAO,CAAC;QAChB,CAAC;QAED,eAAe,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;QACjE,MAAM,GAAG,CAAC;IACZ,CAAC;YAAS,CAAC;QACT,IAAI,KAAK,KAAK,SAAS;YAAE,YAAY,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;AACH,CAAC"}
@@ -1,6 +1,52 @@
1
1
  import { type StructuredOutputMeta } from '@sensigo/realm';
2
2
  import { ToolCapableLlmProvider, type ProviderCapabilities } from './llm-provider.js';
3
3
  import type { ToolDefinition, ToolExecutor, StepWithToolsResult } from '../mcp/mcp-extensions.js';
4
+ import { type LlmClock } from './agent-utils.js';
5
+ /**
6
+ * Returns the maximum output tokens for the given Anthropic model.
7
+ * The Anthropic Messages API requires max_tokens — this must always produce a valid value.
8
+ * Source: https://docs.anthropic.com/en/docs/about-claude/models/all-models
9
+ *
10
+ * Issue #309 fix (ratified per design-d4-final.md's ADDENDUM, the audit's 3.5-cap correction):
11
+ * the PRE-#309 regex (`claude-(3[-.]5|[a-z]+-4)`) was stale in a dangerous direction — it gave
12
+ * the claude-3.5 family's OWN hard output cap (8192; 16384 would 400 every call) to EVERY 4.x
13
+ * model too (claude-sonnet-4-5, claude-opus-4-1, …), silently under-budgeting them. Three
14
+ * buckets now, ordered most-specific-first:
15
+ * 1. claude-3.5 family (`claude-3-5-*` / `claude-3.5-*`) ⇒ 8192 — its OWN hard cap.
16
+ * 2. Bare legacy claude-3 generation (claude-3-opus/-sonnet/-haiku, NOT 3.5) ⇒ 4096 — original,
17
+ * unchanged fallback.
18
+ * 3. Everything else — 3.7, every 4.x/5.x model, and any UNKNOWN future model id — ⇒ 16384.
19
+ * Fail-forward (the stale-classifier lesson, #312 is the durable fix: an unrecognized model
20
+ * id is treated as AT LEAST as capable as today's models, never less; 16384 is
21
+ * non-streaming-safe and current models think by default, so 4096 would starve
22
+ * thinking+output on anything not explicitly bucketed above).
23
+ */
24
+ export declare function resolveMaxTokens(model: string): number;
25
+ /**
26
+ * The Anthropic SDK's own non-streaming coherence threshold. A single non-streaming request asking
27
+ * for more output tokens than this can legitimately outrun a ten-minute budget, and the SDK would
28
+ * rather you stream than have the request die on a timeout it cannot distinguish from a hang.
29
+ */
30
+ export declare const MAX_NONSTREAMING_TOKENS = 21333;
31
+ /**
32
+ * issue #401 — realm re-imposes the SDK's rule, because realm's own `timeout` DISABLES it.
33
+ * The SDK runs that check only when `!stream && timeout == null` (messages.js:29-33): the moment
34
+ * realm passes an explicit per-attempt timeout, the guard silently stops running. Re-imposing it
35
+ * here keeps behaviour identical to the pre-#401 client instead of trading a loud refusal for a
36
+ * confusing abort — so it fires ONLY when a clock was threaded (no clock ⇒ no realm timeout ⇒ the
37
+ * SDK's own guard is still live and will raise this itself).
38
+ *
39
+ * STREAMING FORK: realm's Anthropic path never sets `stream: true` on any request, so in practice
40
+ * this is unconditional. If a streaming path is ever added it must NOT call this — the rule is
41
+ * about non-streaming requests only, and inheriting it would refuse a request that is perfectly
42
+ * legal when streamed.
43
+ *
44
+ * Realm re-imposes the RATIO rule ONLY. The SDK additionally carries per-model
45
+ * MODEL_NONSTREAMING_TOKENS caps; those are deliberately not duplicated — a per-model table
46
+ * copied into a client goes stale on the next model release and starts refusing requests the
47
+ * server would have served.
48
+ */
49
+ export declare function assertMaxTokensCoherent(maxTokens: number, clock: LlmClock | undefined): void;
4
50
  /**
5
51
  * Thrown when the ladder's OWN drop-strict retry ALSO fails — design §4 [R2-7]: (a) carries the
6
52
  * `structuredOutput` meta so a catch site can still disclose the downgrade even though no result
@@ -42,11 +88,14 @@ export declare class AnthropicProvider extends ToolCapableLlmProvider {
42
88
  * THIS invocation — a step that never opted in gets no `structuredOutput` meta at all.
43
89
  */
44
90
  private callStepInternal;
45
- callStep(prompt: string, inputSchema?: Record<string, unknown>, agentProfileInstructions?: string): Promise<Record<string, unknown>>;
91
+ callStep(prompt: string, inputSchema?: Record<string, unknown>, agentProfileInstructions?: string, opts?: {
92
+ llmClock?: LlmClock;
93
+ }): Promise<Record<string, unknown>>;
46
94
  /** issue #236 override — the only provider in this codebase that actually honors
47
95
  * `opts.structuredOutputStrict`; the base class's default just wraps `callStep`. */
48
96
  callStepWithMeta(prompt: string, inputSchema?: Record<string, unknown>, agentProfileInstructions?: string, opts?: {
49
97
  structuredOutputStrict?: boolean;
98
+ llmClock?: LlmClock;
50
99
  }): Promise<{
51
100
  output: Record<string, unknown>;
52
101
  meta?: StructuredOutputMeta;
@@ -64,6 +113,7 @@ export declare class AnthropicProvider extends ToolCapableLlmProvider {
64
113
  maxFanOut?: number;
65
114
  toolTimeoutMs?: number;
66
115
  agentProfileInstructions?: string;
116
+ llmClock?: LlmClock;
67
117
  }): Promise<StepWithToolsResult>;
68
118
  }
69
119
  //# sourceMappingURL=anthropic-provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-provider.d.ts","sourceRoot":"","sources":["../../../src/agent/providers/anthropic-provider.ts"],"names":[],"mappings":"AAEA,OAAO,EAIL,KAAK,oBAAoB,EAC1B,MAAM,gBAAgB,CAAC;AACx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