create-principles-disciple 1.150.2 → 1.150.3

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 (33) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/package.json +1 -1
  3. package/core/dist/runtime/activation/adaptive-selection-output.d.ts +35 -0
  4. package/core/dist/runtime/activation/adaptive-selection-output.d.ts.map +1 -0
  5. package/core/dist/runtime/activation/adaptive-selection-output.js +38 -0
  6. package/core/dist/runtime/activation/adaptive-selection-output.js.map +1 -0
  7. package/core/dist/runtime/adapter/artificer-l2-adapter.d.ts.map +1 -1
  8. package/core/dist/runtime/adapter/artificer-l2-adapter.js +89 -27
  9. package/core/dist/runtime/adapter/artificer-l2-adapter.js.map +1 -1
  10. package/core/dist/runtime/adapter/context-budget.d.ts +49 -0
  11. package/core/dist/runtime/adapter/context-budget.d.ts.map +1 -0
  12. package/core/dist/runtime/adapter/context-budget.js +127 -0
  13. package/core/dist/runtime/adapter/context-budget.js.map +1 -0
  14. package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
  15. package/core/dist/runtime/adapter/output-schema-registry.js +7 -0
  16. package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
  17. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts +30 -7
  18. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
  19. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +467 -206
  20. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
  21. package/core/dist/telemetry-event.d.ts +2 -2
  22. package/core/dist/telemetry-event.d.ts.map +1 -1
  23. package/core/dist/telemetry-event.js +5 -0
  24. package/core/dist/telemetry-event.js.map +1 -1
  25. package/core/package.json +1 -1
  26. package/host-runtime/dist/adaptive-selection.d.ts +3 -1
  27. package/host-runtime/dist/adaptive-selection.js +38 -9
  28. package/host-runtime/dist/production-rulehost-gate.js +21 -1
  29. package/package.json +2 -2
  30. package/plugin/dist/bundle.js +464 -508
  31. package/plugin/dist/hooks/gate.d.ts +1 -1
  32. package/plugin/dist/openclaw.plugin.json +1 -1
  33. package/release-manager/package.json +1 -1
@@ -33,6 +33,9 @@ import { formatValidationErrorEntry, safeStringifyPreview, stripLineageFields }
33
33
  import { buildSchemaToolDefinition } from './tools/diagnostician-tool.js';
34
34
  import { DefaultSchemaPromptAdapter } from './schema-prompt-adapter.js';
35
35
  import { mergeSystemPromptLayers } from '../system-prompt-merge.js';
36
+ // S4: pi-ai's own overflow-pattern authority + one shared budget derivation.
37
+ import { isContextOverflow } from '@earendil-works/pi-ai/utils/overflow';
38
+ import { estimateRequestTokens, resolveContextBudget } from './context-budget.js';
36
39
  /**
37
40
  * PRI-1011: ceiling pi-ai applies itself when no explicit max_tokens is sent
38
41
  * (`options.maxTokens ?? min(model.maxTokens, 32000)`). A downshift must start
@@ -54,6 +57,31 @@ const MIN_MAX_TOKENS_BUDGET = 4_096;
54
57
  * must keep their existing classification and must not trigger a downshift.
55
58
  */
56
59
  const MAX_TOKENS_REJECTED_PATTERN = /max[_ ]?tokens\b[^\n]{0,120}exceed|[Ee]xceeds the maximum output tokens/;
60
+ /**
61
+ * S1: abort reason set by cancelRun(). Node surfaces it through
62
+ * `AbortSignal.reason`, which lets every classification site tell a caller
63
+ * cancellation apart from the run's own time budget expiring — both leave
64
+ * `signal.aborted === true`, so `aborted` alone cannot distinguish them.
65
+ */
66
+ const CANCEL_ABORT_REASON = 'pd_cancelled_by_caller';
67
+ /**
68
+ * S1: upper bound for one repair call. The repair call now inherits the run's
69
+ * remaining budget (see repairLLMCall) instead of always getting this much.
70
+ */
71
+ const REPAIR_TIMEOUT_MS_CEILING = 60_000;
72
+ /**
73
+ * S1: a repair call is pointless when less than this remains in the run's
74
+ * budget — the attempt would be aborted mid-flight. Skipping it keeps the
75
+ * already-obtained schema error instead of turning it into a timeout.
76
+ */
77
+ const MIN_REPAIR_BUDGET_MS = 1_000;
78
+ /**
79
+ * S2: cap on the wait pi-ai may take between its own transport retries.
80
+ * pi-ai defaults to 60s per wait; 30s keeps the worst-case wait no worse than
81
+ * PD's previous capped backoff. A provider that asks for longer fails fast
82
+ * with its original message instead of parking the run.
83
+ */
84
+ const PI_AI_MAX_RETRY_DELAY_MS = 30_000;
57
85
  /** PRI-966 G2 P1-03: bounded usage summary from an AssistantMessage. Fields
58
86
  * stay null when the provider did not surface a count — never guessed. An
59
87
  * all-zero usage object is pi-ai's "provider surfaced nothing" placeholder
@@ -204,6 +232,65 @@ function isAbortError(err, signal) {
204
232
  return true;
205
233
  return false;
206
234
  }
235
+ /**
236
+ * S1: true only when the run was aborted by an explicit caller cancel, never
237
+ * when the run's own time budget expired. Both leave `signal.aborted === true`,
238
+ * so the abort reason is the only reliable discriminator.
239
+ */
240
+ function isCancelledSignal(signal) {
241
+ return signal?.aborted === true && signal.reason === CANCEL_ABORT_REASON;
242
+ }
243
+ /**
244
+ * S3: recover the HTTP status from pi-ai's composed provider error message.
245
+ *
246
+ * pi-ai stops carrying the structured status once a failure becomes
247
+ * `AssistantMessage{stopReason:'error'}`, but `formatProviderError` builds the
248
+ * message as `<status>: <body>` (or `<prefix> (<status>): <body>`), so the
249
+ * status is still available without wrapping `fetch` and without inventing a
250
+ * second HTTP observation channel.
251
+ */
252
+ export function extractProviderHttpStatus(rawMessage) {
253
+ const leading = /^\s*(\d{3})(?:\s|:|$)/.exec(rawMessage);
254
+ // Only `<prefix> (<status>): <body>` carries a status in parentheses; an
255
+ // arbitrary `(123)` in a message with no such shape is free-form text, not a
256
+ // provider status (rc-2: do not present a guess as authoritative evidence).
257
+ const parenthesized = /^[^:]*?\((\d{3})\)\s*:/.exec(rawMessage);
258
+ const status = Number(leading?.[1] ?? parenthesized?.[1]);
259
+ if (!Number.isInteger(status) || status < 100 || status > 599)
260
+ return undefined;
261
+ return status;
262
+ }
263
+ /**
264
+ * S3: status-code-first classification. Returns `undefined` for codes PD has no
265
+ * specific meaning for (404, 409, …) so the caller keeps the text fallback and
266
+ * can mark the evidence `status_unknown`/`text_fallback` instead of guessing.
267
+ */
268
+ function classifyProviderHttpStatus(status) {
269
+ if (status === 401 || status === 403)
270
+ return { category: 'input_invalid', label: 'provider_auth' };
271
+ if (status === 400 || status === 422)
272
+ return { category: 'input_invalid', label: 'provider_request' };
273
+ if (status === 408)
274
+ return { category: 'timeout', label: 'provider_timeout' };
275
+ if (status === 429)
276
+ return { category: 'rate_limit', label: 'provider_rate_limit' };
277
+ if (status >= 500 && status <= 599)
278
+ return { category: 'execution_failed', label: 'provider_upstream' };
279
+ return undefined;
280
+ }
281
+ /** S3: evidence attached to every provider failure so the classification is auditable. */
282
+ function providerStatusEvidence(rawMessage) {
283
+ const httpStatus = extractProviderHttpStatus(rawMessage);
284
+ const classification = httpStatus === undefined ? undefined : classifyProviderHttpStatus(httpStatus);
285
+ if (httpStatus === undefined) {
286
+ return { errorClassificationSource: 'text_fallback', statusUnknown: true };
287
+ }
288
+ return {
289
+ httpStatus,
290
+ errorClassificationSource: classification ? 'status_code' : 'text_fallback',
291
+ ...(classification ? { providerErrorClass: classification.label } : {}),
292
+ };
293
+ }
207
294
  function classifyFailure(err, signal) {
208
295
  if (signal?.aborted) {
209
296
  return {
@@ -257,11 +344,12 @@ function classifyFailure(err, signal) {
257
344
  * so downstream code never sees a "successful" response that is actually broken.
258
345
  *
259
346
  * Error classification:
260
- * stopReason:'aborted' → timeout
261
- * stopReason:'error' + timeout/abort in errorMessage → timeout
262
- * stopReason:'error' + other → execution_failed
263
- * stopReason:'length' + no extractable content → output_invalid (truncated)
264
- * no text or thinking content block → output_invalid
347
+ * recovered HTTP status → S3 status-code mapping
348
+ * stopReason:'aborted' → timeout
349
+ * stopReason:'error' + timeout/abort in message → timeout
350
+ * stopReason:'error' + other → execution_failed
351
+ * stopReason:'length' + no extractable content → output_invalid (truncated)
352
+ * no text or thinking content block → output_invalid
265
353
  *
266
354
  * Reasoning-model fallback (BUG-007a):
267
355
  * When all content blocks have empty text (common with reasoning models that
@@ -275,13 +363,25 @@ function extractAssistantTextOrThrow(response, signal) {
275
363
  const rawMessage = response.errorMessage ?? 'unknown provider error';
276
364
  // Truncate to 300 chars to avoid leaking huge payloads into logs/telemetry
277
365
  const boundedMessage = rawMessage.length > 300 ? rawMessage.substring(0, 300) + '...' : rawMessage;
278
- const isTimeout = response.stopReason === 'aborted'
279
- || signal?.aborted
280
- || /timeout|timed\s*out/i.test(rawMessage)
281
- || /abort/i.test(rawMessage);
282
- throw new PDRuntimeError(isTimeout ? 'timeout' : 'execution_failed', isTimeout
366
+ // S3: status code first; text heuristics only when no status is recoverable.
367
+ const statusClassification = classifyProviderHttpStatus(extractProviderHttpStatus(rawMessage) ?? -1);
368
+ const isTimeout = statusClassification
369
+ ? statusClassification.category === 'timeout'
370
+ : response.stopReason === 'aborted'
371
+ || signal?.aborted
372
+ || /timeout|timed\s*out/i.test(rawMessage)
373
+ || /abort/i.test(rawMessage);
374
+ const category = statusClassification && statusClassification.category !== 'timeout'
375
+ ? statusClassification.category
376
+ : isTimeout
377
+ ? 'timeout'
378
+ : 'execution_failed';
379
+ throw new PDRuntimeError(category, isTimeout
283
380
  ? `LLM request timed out: ${boundedMessage}`
284
- : `LLM execution failed: ${boundedMessage}`);
381
+ : `LLM execution failed: ${boundedMessage}`, {
382
+ ...(isTimeout ? { timeoutClassification: 'provider_transient_timeout' } : {}),
383
+ ...providerStatusEvidence(rawMessage),
384
+ });
285
385
  }
286
386
  // Find text content (may be mixed with thinking content from reasoning-enabled models)
287
387
  const textContent = response.content.find(c => c.type === 'text' && c.text && c.text.trim().length > 0);
@@ -314,6 +414,11 @@ function extractAssistantTextOrThrow(response, signal) {
314
414
  export class PiAiRuntimeAdapter {
315
415
  config;
316
416
  runs = new Map();
417
+ /**
418
+ * S1: one controller per in-flight run. cancelRun() aborts it; startRun()
419
+ * clears it in `finally` so a finished run can never be aborted afterwards.
420
+ */
421
+ abortControllers = new Map();
317
422
  eventEmitter;
318
423
  runtimeKind = 'pi-ai';
319
424
  defaultCapabilities = {
@@ -509,56 +614,93 @@ export class PiAiRuntimeAdapter {
509
614
  const timeoutSource = input.timeoutMs !== undefined ? 'runner_input'
510
615
  : this.config.timeoutMs !== undefined ? 'adapter_config'
511
616
  : 'default';
512
- const signal = AbortSignal.timeout(effectiveTimeoutMs);
513
- // Build pi-ai Context from inputPayload
514
- const messageContent = typeof input.inputPayload === 'string'
515
- ? input.inputPayload
516
- : JSON.stringify(input.inputPayload);
517
- const userMessage = {
518
- role: 'user',
519
- content: messageContent,
520
- timestamp: Date.now(),
521
- };
522
617
  // PRI-633: layered system prompt — base layer from the run's prompt
523
618
  // builder (input.systemPrompt: agent role + protocol) + append layer from
524
619
  // the profile config (this.config.systemPrompt). When both are absent the
525
620
  // Context keeps its pre-PRI-633 shape (no systemPrompt field).
621
+ // Declared outside the try because the run handle returned afterwards
622
+ // reports its digest (PRI-1146 P1-02).
526
623
  const systemPrompt = mergeSystemPromptLayers(input.systemPrompt, this.config.systemPrompt);
527
- // PRI-1146 P1-02: this merged string is exactly what the provider receives
528
- // below (and on repair). Reporting its digest lets the receipt bind the
529
- // REAL provider prompt instead of a base layer that was never sent.
530
624
  const systemPromptDigest = systemPrompt === undefined
531
625
  ? undefined
532
626
  : createHash('sha256').update(systemPrompt, 'utf8').digest('hex');
533
- const context = {
534
- messages: [userMessage],
535
- ...(systemPrompt ? { systemPrompt } : {}),
536
- };
537
- // Get model
538
- const model = resolveModel(this.config.provider, this.config.model, this.config.baseUrl);
539
- // Per-run output budget: each output path below resolves it through
540
- // resolveEffectiveMaxTokens(input, model) — validating an explicit
541
- // per-request budget BEFORE its first request is built, and applying the
542
- // min(per-request, profile, model-ceiling) hard cap.
543
- // Emit runtime_invocation_started telemetry
544
- this.eventEmitter.emitTelemetry({
545
- eventType: 'runtime_invocation_started',
546
- traceId: input.taskRef?.taskId ?? runId,
547
- timestamp: startedAt,
548
- sessionId: 'pi-ai-adapter',
549
- agentId: 'pi-ai-adapter',
550
- payload: {
551
- runId,
552
- runtimeKind: 'pi-ai',
553
- runnerKind: input.agentSpec.agentId,
554
- provider: this.config.provider,
555
- model: this.config.model,
556
- timeoutMs: effectiveTimeoutMs,
557
- timeoutSource,
558
- outputSchemaRef: input.outputSchemaRef ?? 'unknown',
559
- },
560
- });
627
+ // S1: one AbortController per run, owning BOTH stop paths:
628
+ // - cancelRun() aborts it with CANCEL_ABORT_REASON;
629
+ // - the timer below aborts it when the run's time budget expires.
630
+ // A single controller means every request in the run (all three output
631
+ // paths + repair calls) shares one deadline, and a real cancel propagates
632
+ // to the in-flight HTTP request instead of being a documented no-op.
633
+ // Registered immediately before the first await so the cleanup in `finally`
634
+ // always pairs with it.
635
+ const abortController = new AbortController();
636
+ this.abortControllers.set(runId, abortController);
637
+ const { signal } = abortController;
638
+ const runDeadlineAt = Date.now() + effectiveTimeoutMs;
639
+ const budgetTimer = setTimeout(() => {
640
+ if (!signal.aborted)
641
+ abortController.abort();
642
+ }, effectiveTimeoutMs);
561
643
  try {
644
+ const messageContent = typeof input.inputPayload === 'string'
645
+ ? input.inputPayload
646
+ : JSON.stringify(input.inputPayload);
647
+ const userMessage = {
648
+ role: 'user',
649
+ content: messageContent,
650
+ timestamp: Date.now(),
651
+ };
652
+ // PRI-633: layered system prompt — base layer from the run's prompt
653
+ // builder (input.systemPrompt: agent role + protocol) + append layer from
654
+ // the profile config (this.config.systemPrompt). When both are absent the
655
+ // Context keeps its pre-PRI-633 shape (no systemPrompt field).
656
+ const context = {
657
+ messages: [userMessage],
658
+ ...(systemPrompt ? { systemPrompt } : {}),
659
+ };
660
+ // Get model
661
+ const model = resolveModel(this.config.provider, this.config.model, this.config.baseUrl);
662
+ // Per-run output budget: each output path below resolves it through
663
+ // resolveEffectiveMaxTokens(input, model) — validating an explicit
664
+ // per-request budget BEFORE its first request is built, and applying the
665
+ // min(per-request, profile, model-ceiling) hard cap.
666
+ // Emit runtime_invocation_started telemetry
667
+ this.eventEmitter.emitTelemetry({
668
+ eventType: 'runtime_invocation_started',
669
+ traceId: input.taskRef?.taskId ?? runId,
670
+ timestamp: startedAt,
671
+ sessionId: 'pi-ai-adapter',
672
+ agentId: 'pi-ai-adapter',
673
+ payload: {
674
+ runId,
675
+ runtimeKind: 'pi-ai',
676
+ runnerKind: input.agentSpec.agentId,
677
+ provider: this.config.provider,
678
+ model: this.config.model,
679
+ timeoutMs: effectiveTimeoutMs,
680
+ timeoutSource,
681
+ outputSchemaRef: input.outputSchemaRef ?? 'unknown',
682
+ },
683
+ });
684
+ // S4: estimate the assembled request against the model's own context
685
+ // window before spending a request. An oversized request fails loud with a
686
+ // structured overflow reason (and a next action) rather than being sent,
687
+ // rejected by the provider, and reported as a generic failure.
688
+ const contextBudget = resolveContextBudget(model.contextWindow, this.resolveEffectiveMaxTokens(input, model) ?? 0);
689
+ const estimatedInputTokens = estimateRequestTokens({
690
+ systemPrompt,
691
+ texts: [messageContent],
692
+ });
693
+ if (estimatedInputTokens > contextBudget.budgetTokens) {
694
+ throw new PDRuntimeError('input_invalid', `LLM context overflow (pre-flight estimate): ~${estimatedInputTokens} input tokens > ${contextBudget.budgetTokens} budget`, {
695
+ contextOverflow: true,
696
+ contextWindowTokens: contextBudget.contextWindowTokens,
697
+ budgetTokens: contextBudget.budgetTokens,
698
+ reserveOutputTokens: contextBudget.reserveOutputTokens,
699
+ estimatedInputTokens,
700
+ nextAction: 'reduce_context',
701
+ finalFailureReason: 'context_overflow',
702
+ });
703
+ }
562
704
  // PRI-271 B3: Three-path fallback chain for structured output
563
705
  const schemaRef = input.outputSchemaRef;
564
706
  const schema = resolveOutputSchema(schemaRef);
@@ -701,8 +843,14 @@ export class PiAiRuntimeAdapter {
701
843
  const originalOutput = typeof parsedOutput === 'object'
702
844
  ? parsedOutput
703
845
  : undefined;
846
+ // S1: a repair attempt costs another round trip. When the run budget
847
+ // is almost gone it can only be aborted mid-flight, replacing a
848
+ // precise schema error with a vague timeout — so skip it and report
849
+ // the schema error we already have. attemptsUsed=0 in the telemetry
850
+ // below is the observable record of the skip.
851
+ const repairBudgetExhausted = runDeadlineAt - Date.now() < MIN_REPAIR_BUDGET_MS;
704
852
  const repairResult = await attemptStructuredOutputRepair(parsedOutput, schemaErrors, {
705
- llmCaller: (prompt) => this.repairLLMCall(model, prompt, { signal, apiKey, systemPrompt, input }),
853
+ llmCaller: (prompt) => this.repairLLMCall(model, prompt, { signal, apiKey, systemPrompt, input, runDeadlineAt }),
706
854
  schemaCheck: (value) => Value.Check(schema, value),
707
855
  schemaErrors: (value) => [...Value.Errors(schema, value)].map(e => ({ path: e.path, message: e.message, value: e.value })),
708
856
  }, {
@@ -711,7 +859,7 @@ export class PiAiRuntimeAdapter {
711
859
  schemaSummary,
712
860
  schemaJson,
713
861
  requiredKeys,
714
- maxRepairAttempts: this.config.maxRepairAttempts,
862
+ maxRepairAttempts: repairBudgetExhausted ? 0 : this.config.maxRepairAttempts,
715
863
  // PRI-707: when finish metadata proves the output was cut by the
716
864
  // token limit, the repair LLM must know — repairing a truncated
717
865
  // fragment like a schema misunderstanding produced blind fixes.
@@ -734,8 +882,31 @@ export class PiAiRuntimeAdapter {
734
882
  repairSummary: repairResult.repairSummary,
735
883
  repairAttempts: repairResult.repairAttempts,
736
884
  outputPath: 'free_form_with_repair',
885
+ // S1: never truncate silently — when repair was skipped because
886
+ // the run budget was nearly spent, say so in the event.
887
+ ...(repairBudgetExhausted
888
+ ? {
889
+ repairSkipped: true,
890
+ repairSkipReason: 'budget_exhausted',
891
+ remainingBudgetMs: Math.max(0, runDeadlineAt - Date.now()),
892
+ }
893
+ : {}),
737
894
  },
738
895
  });
896
+ // S1: an abort during repair must surface as the real stop reason
897
+ // (caller cancel or budget expiry). The repair loop treats a throwing
898
+ // llmCaller as "attempt failed", which would otherwise disguise a
899
+ // stopped run as a schema mismatch.
900
+ if (isCancelledSignal(signal)) {
901
+ throw new PDRuntimeError('cancelled', 'LLM run cancelled by caller during output repair', {
902
+ cancelled: true,
903
+ });
904
+ }
905
+ if (signal.aborted) {
906
+ throw new PDRuntimeError('timeout', 'LLM run budget exhausted during output repair', {
907
+ timeoutClassification: 'client_timeout_budget_exhausted',
908
+ });
909
+ }
739
910
  if (repairResult.repaired && repairResult.output) {
740
911
  parsedOutput = repairResult.output;
741
912
  }
@@ -775,6 +946,9 @@ export class PiAiRuntimeAdapter {
775
946
  validationErrors: validationErrorEntries,
776
947
  repairAttempts: evidencePack.repairAttempts,
777
948
  finalFailureReason: evidencePack.finalFailureReason,
949
+ ...(repairBudgetExhausted
950
+ ? { repairSkipped: true, repairSkipReason: 'budget_exhausted' }
951
+ : {}),
778
952
  // PRI-707: keep the terminal repair-exhausted event able to
779
953
  // distinguish a token-limit cut from an ordinary schema
780
954
  // failure — mirror the evidencePack finish metadata (PR #1574
@@ -831,6 +1005,10 @@ export class PiAiRuntimeAdapter {
831
1005
  let timeoutClassification = 'not_applicable';
832
1006
  let providerEvidence = '';
833
1007
  let retryAttempt = 0;
1008
+ // S3: carry the status-code evidence into the terminal failure event so
1009
+ // "why was this classified this way" stays auditable.
1010
+ let httpStatus;
1011
+ let errorClassificationSource;
834
1012
  if (err instanceof PDRuntimeError && err.details) {
835
1013
  const { details } = err;
836
1014
  if (isObjectWithKey(details, 'timeoutClassification')) {
@@ -848,8 +1026,29 @@ export class PiAiRuntimeAdapter {
848
1026
  if (typeof ra === 'number')
849
1027
  retryAttempt = ra;
850
1028
  }
1029
+ if (isObjectWithKey(details, 'httpStatus')) {
1030
+ const { httpStatus: hs } = details;
1031
+ if (typeof hs === 'number')
1032
+ httpStatus = hs;
1033
+ }
1034
+ if (isObjectWithKey(details, 'errorClassificationSource')) {
1035
+ const { errorClassificationSource: ecs } = details;
1036
+ if (typeof ecs === 'string')
1037
+ errorClassificationSource = ecs;
1038
+ }
851
1039
  }
852
- if (isAbortError(err, signal)) {
1040
+ if (isCancelledSignal(signal)) {
1041
+ // S1: a caller cancel is terminal and must never be retried, wrapped
1042
+ // as a generic failure, or reported as a timeout — the run did not run
1043
+ // out of time, the Owner withdrew it.
1044
+ runState.status = 'cancelled';
1045
+ runState.reason = 'cancelled: run stopped by caller';
1046
+ timeoutClassification = 'cancelled';
1047
+ if (!providerEvidence) {
1048
+ providerEvidence = safeStringifyPreview(err, 300);
1049
+ }
1050
+ }
1051
+ else if (isAbortError(err, signal)) {
853
1052
  runState.status = 'timed_out';
854
1053
  runState.reason = `[timeout] LLM request timed out after ${effectiveTimeoutMs}ms (timeoutSource=${timeoutSource})`;
855
1054
  if (timeoutClassification === 'not_applicable') {
@@ -901,8 +1100,20 @@ export class PiAiRuntimeAdapter {
901
1100
  errorMessage: runState.reason,
902
1101
  errorCategory,
903
1102
  finalFailure: true,
1103
+ ...(httpStatus !== undefined ? { httpStatus } : {}),
1104
+ ...(errorClassificationSource ? { errorClassificationSource } : {}),
904
1105
  },
905
1106
  });
1107
+ // S1: cancellation wins over the generic wrapping below — the category
1108
+ // must be `cancelled` whether the abort surfaced as a thrown AbortError,
1109
+ // a PDRuntimeError from a lower layer, or a provider "aborted" result.
1110
+ if (isCancelledSignal(signal)) {
1111
+ throw new PDRuntimeError('cancelled', 'LLM run cancelled by caller', {
1112
+ elapsedMs,
1113
+ cancelled: true,
1114
+ providerEvidence,
1115
+ });
1116
+ }
906
1117
  // Re-throw PDRuntimeError as-is, wrap others
907
1118
  if (err instanceof PDRuntimeError) {
908
1119
  throw err;
@@ -912,6 +1123,13 @@ export class PiAiRuntimeAdapter {
912
1123
  providerEvidence,
913
1124
  });
914
1125
  }
1126
+ finally {
1127
+ // S1: the run is terminal — release the abort handle and the budget timer
1128
+ // so a finished run can never be aborted and the timer cannot keep the
1129
+ // process alive.
1130
+ clearTimeout(budgetTimer);
1131
+ this.abortControllers.delete(runId);
1132
+ }
915
1133
  return { runId, runtimeKind: 'pi-ai', startedAt, ...(systemPromptDigest === undefined ? {} : { systemPromptDigest }) };
916
1134
  }
917
1135
  async pollRun(runId) {
@@ -928,12 +1146,23 @@ export class PiAiRuntimeAdapter {
928
1146
  };
929
1147
  }
930
1148
  async cancelRun(runId) {
931
- // One-shot mode: startRun() blocks until LLM responds, so cancel is always a no-op.
932
- // The run is already terminal by the time cancelRun could be called.
933
- const state = this.runs.get(runId);
934
- if (state && state.status === 'succeeded') {
1149
+ // S1: abort the in-flight request. The abort reason is what lets the run
1150
+ // be classified as `cancelled` instead of `timeout` downstream.
1151
+ const controller = this.abortControllers.get(runId);
1152
+ if (!controller) {
1153
+ // Terminal or unknown run: nothing is in flight to stop.
935
1154
  return;
936
1155
  }
1156
+ if (!controller.signal.aborted) {
1157
+ controller.abort(CANCEL_ABORT_REASON);
1158
+ }
1159
+ // The run's catch block performs the authoritative status transition; this
1160
+ // keeps pollRun() truthful even if the provider ignores the abort.
1161
+ const state = this.runs.get(runId);
1162
+ if (state && state.status !== 'succeeded') {
1163
+ state.status = 'cancelled';
1164
+ state.reason = 'cancelled: run stopped by caller';
1165
+ }
937
1166
  }
938
1167
  async fetchOutput(runId) {
939
1168
  const state = this.runs.get(runId);
@@ -1112,13 +1341,19 @@ export class PiAiRuntimeAdapter {
1112
1341
  * Returns extracted text response or null if no content.
1113
1342
  * Reuses same provider/model/apiKey as the original call.
1114
1343
  *
1115
- * Uses an independent AbortSignal (fixed 60s timeout) to avoid the repair
1116
- * call immediately timing out when the original call consumed most of the
1117
- * original timeout budget (e.g., 5min original → 4m50s elapsed → 10s left).
1344
+ * S1: the repair call inherits the run's REMAINING time budget instead of a
1345
+ * fresh fixed 60s allowance. Before this, a repair request could outlive the
1346
+ * run's own deadline by up to a minute, so the run "timed out" long after the
1347
+ * caller stopped waiting for it.
1118
1348
  */
1119
1349
  async repairLLMCall(model, prompt, options) {
1120
- const REPAIR_TIMEOUT_MS = 60_000;
1121
- const repairSignal = AbortSignal.timeout(REPAIR_TIMEOUT_MS);
1350
+ const remainingMs = options.runDeadlineAt - Date.now();
1351
+ // Defensive: the call site already skips repair when the budget is nearly
1352
+ // spent. If it still happens (clock skew between the two checks), do not
1353
+ // send a request that cannot finish.
1354
+ if (remainingMs < MIN_REPAIR_BUDGET_MS)
1355
+ return null;
1356
+ const repairTimeoutMs = Math.min(REPAIR_TIMEOUT_MS_CEILING, remainingMs);
1122
1357
  const repairMessage = {
1123
1358
  role: 'user',
1124
1359
  content: prompt,
@@ -1131,9 +1366,11 @@ export class PiAiRuntimeAdapter {
1131
1366
  ...(options.systemPrompt ? { systemPrompt: options.systemPrompt } : {}),
1132
1367
  };
1133
1368
  const response = await completeSimple(model, repairContext, {
1134
- signal: repairSignal,
1369
+ // The run signal already carries the shared deadline (and any caller
1370
+ // cancel); the per-attempt timeout mirrors what is left of it.
1371
+ signal: options.signal,
1135
1372
  apiKey: options.apiKey,
1136
- timeoutMs: REPAIR_TIMEOUT_MS,
1373
+ timeoutMs: repairTimeoutMs,
1137
1374
  maxRetries: 0,
1138
1375
  maxTokens: this.resolveEffectiveMaxTokens(options.input, model),
1139
1376
  // PRI-683 transport ownership: repair calls ride the same dedicated PD
@@ -1160,13 +1397,23 @@ export class PiAiRuntimeAdapter {
1160
1397
  }
1161
1398
  }
1162
1399
  /**
1163
- * Call pi-ai complete() with retry and exponential backoff.
1164
- * Disables pi-ai built-in retry (maxRetries: 0) to avoid double-retry.
1400
+ * Call pi-ai complete().
1401
+ *
1402
+ * S2: transport retries belong to pi-ai. It already knows which failures are
1403
+ * retryable (408/409/429/5xx, `x-should-retry`, `retry-after`) and how long
1404
+ * to wait, and its wait is abortable. PD therefore passes `maxRetries` /
1405
+ * `maxRetryDelayMs` instead of running its own loop, so one logical failure
1406
+ * can no longer cost both layers' retries.
1407
+ *
1408
+ * The only PD-side retry left is the PRI-1011 output-budget downshift: that
1409
+ * is a parameter fix pi-ai cannot infer, and each step strictly shrinks the
1410
+ * budget, so the ladder terminates by construction.
1165
1411
  */
1166
1412
  async completeWithRetry(model, context, options) {
1167
- const maxRetries = this.config.maxRetries ?? 2;
1168
1413
  const { effectiveTimeoutMs = this.config.timeoutMs ?? 300_000, timeoutSource = 'default', input, runId = crypto.randomUUID(), } = options;
1169
- let lastError = undefined;
1414
+ // S2: the retry budget handed to pi-ai. It is recorded on every failure so
1415
+ // the final reason is auditable ("who retried, how many times").
1416
+ const transportMaxRetries = this.config.maxRetries ?? 2;
1170
1417
  const overallStartTime = Date.now();
1171
1418
  // PRI-1011: the output budget actually sent for THIS invocation. It starts at
1172
1419
  // the per-run effective value (min of the per-request StartRunInput.maxTokens,
@@ -1176,12 +1423,12 @@ export class PiAiRuntimeAdapter {
1176
1423
  let maxTokensBudget = input !== undefined
1177
1424
  ? this.resolveEffectiveMaxTokens(input, model)
1178
1425
  : this.resolveMaxTokens();
1179
- const getDelay = (attemptIndex) => {
1180
- return this.config._testBackoffDelayMs !== undefined
1181
- ? this.config._testBackoffDelayMs
1182
- : Math.min(1000 * Math.pow(2, attemptIndex), 30_000);
1183
- };
1184
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1426
+ // Number of requests PD itself sent for this logical call. Transport
1427
+ // retries inside pi-ai are invisible here by design (they are pi-ai's).
1428
+ let attemptsSent = 0;
1429
+ while (true) {
1430
+ attemptsSent += 1;
1431
+ const attempt = attemptsSent - 1;
1185
1432
  const elapsedMs = Date.now() - overallStartTime;
1186
1433
  const remainingMs = effectiveTimeoutMs - elapsedMs;
1187
1434
  // Fail fast if overall budget signal is aborted, or if we have already run out of budget time
@@ -1192,7 +1439,8 @@ export class PiAiRuntimeAdapter {
1192
1439
  timeoutSource,
1193
1440
  elapsedMs,
1194
1441
  retryAttempt: attempt,
1195
- maxRetries,
1442
+ transportMaxRetries,
1443
+ retryOwnership: 'pi-ai',
1196
1444
  providerEvidence: options.signal?.aborted
1197
1445
  ? 'Client budget signal aborted'
1198
1446
  : `Overall timeout budget exhausted (elapsed ${elapsedMs}ms of ${effectiveTimeoutMs}ms)`,
@@ -1206,7 +1454,14 @@ export class PiAiRuntimeAdapter {
1206
1454
  signal: options.signal,
1207
1455
  apiKey: options.apiKey,
1208
1456
  timeoutMs: currentTimeoutMs,
1209
- maxRetries: 0, // disable pi-ai built-in retry to avoid double-retry
1457
+ // S2: pi-ai owns transport retry/backoff (it knows retryable status
1458
+ // codes, honors retry-after, and its sleep is abortable). Keeping this
1459
+ // at 0 would silently disable every transient retry.
1460
+ maxRetries: transportMaxRetries,
1461
+ // Locked at 30s so the worst-case single wait never grows past what
1462
+ // PD's own capped backoff allowed; a provider asking for longer fails
1463
+ // immediately and PD records the original message.
1464
+ maxRetryDelayMs: PI_AI_MAX_RETRY_DELAY_MS,
1210
1465
  maxTokens: maxTokensBudget, // PRI-621: undefined = pi-ai native model ceiling; PRI-1011: shrinks on rejection
1211
1466
  fetch: this.config.fetch ?? getPiAiFetchForApi(model.api),
1212
1467
  };
@@ -1214,211 +1469,217 @@ export class PiAiRuntimeAdapter {
1214
1469
  completeOptions.reasoning = this.config.reasoning;
1215
1470
  }
1216
1471
  const response = await completeSimple(model, context, completeOptions);
1217
- // If provider resolved with an error response, classify and potentially retry.
1472
+ // If provider resolved with an error response, classify and decide.
1473
+ // S2: no transport retry happens here — pi-ai already retried every
1474
+ // failure it considers retryable before handing this back.
1218
1475
  if (response.stopReason === 'error' || response.stopReason === 'aborted') {
1219
1476
  const rawMessage = response.errorMessage ?? 'unknown provider error';
1220
1477
  const elapsedMsAfter = Date.now() - overallStartTime;
1221
- const isTimeout = response.stopReason === 'aborted'
1222
- || options.signal?.aborted
1223
- || /timeout|timed\s*out/i.test(rawMessage)
1224
- || /abort/i.test(rawMessage);
1478
+ // S3: a recovered HTTP status is authoritative; only the codes PD has
1479
+ // no specific meaning for fall back to the legacy text heuristics.
1480
+ const statusClassification = classifyProviderHttpStatus(extractProviderHttpStatus(rawMessage) ?? -1);
1481
+ const statusEvidence = providerStatusEvidence(rawMessage);
1482
+ const isTimeout = statusClassification
1483
+ ? statusClassification.category === 'timeout'
1484
+ : response.stopReason === 'aborted'
1485
+ || options.signal?.aborted
1486
+ || /timeout|timed\s*out/i.test(rawMessage)
1487
+ || /abort/i.test(rawMessage);
1225
1488
  const classification = (options.signal?.aborted || elapsedMsAfter >= effectiveTimeoutMs)
1226
1489
  ? 'client_timeout_budget_exhausted'
1227
1490
  : isTimeout
1228
1491
  ? 'provider_transient_timeout'
1229
1492
  : 'not_applicable';
1230
1493
  if (isTimeout) {
1231
- const errorDetails = {
1494
+ throw new PDRuntimeError('timeout', `[timeout] LLM request timed out after ${effectiveTimeoutMs}ms (timeoutSource=provider_request)`, {
1232
1495
  timeoutClassification: classification,
1233
1496
  effectiveTimeoutMs,
1234
1497
  timeoutSource,
1235
1498
  elapsedMs: elapsedMsAfter,
1236
1499
  retryAttempt: attempt,
1237
- maxRetries,
1500
+ transportMaxRetries,
1501
+ retryOwnership: 'pi-ai',
1238
1502
  providerEvidence: safeStringifyPreview(rawMessage, 300),
1239
- };
1240
- const pdErr = new PDRuntimeError('timeout', `[timeout] LLM request timed out after ${effectiveTimeoutMs}ms (timeoutSource=provider_request)`, errorDetails);
1241
- lastError = pdErr;
1242
- if (classification === 'provider_transient_timeout' && attempt < maxRetries) {
1503
+ ...statusEvidence,
1504
+ });
1505
+ }
1506
+ // S4: a context overflow is an input-size problem, not a transient or
1507
+ // upstream one. pi-ai owns the provider-specific overflow patterns, so
1508
+ // reuse them instead of letting a "prompt is too long" rejection fall
1509
+ // through to rate_limit/execution_failed.
1510
+ if (isContextOverflow(response, model.contextWindow)) {
1511
+ throw new PDRuntimeError('input_invalid', `LLM context overflow: ${rawMessage.substring(0, 300)}`, {
1512
+ contextOverflow: true,
1513
+ contextWindowTokens: model.contextWindow,
1514
+ nextAction: 'reduce_context',
1515
+ retryAttempt: attempt,
1516
+ transportMaxRetries,
1517
+ retryOwnership: 'pi-ai',
1518
+ elapsedMs: elapsedMsAfter,
1519
+ providerEvidence: safeStringifyPreview(rawMessage, 300),
1520
+ finalFailureReason: 'context_overflow',
1521
+ ...statusEvidence,
1522
+ });
1523
+ }
1524
+ // ADR-0019: rate-limit signatures stay a distinct category so
1525
+ // downstream degradation can recognise them.
1526
+ const isRateLimit = statusClassification
1527
+ ? statusClassification.category === 'rate_limit'
1528
+ : /rate.?limit|429|quota|too many requests/i.test(rawMessage);
1529
+ // PRI-1011: a rejected output budget is a parameter problem, not a
1530
+ // transport one — resending the identical rejected value can only fail
1531
+ // the same way, so the next attempt goes out with a smaller budget.
1532
+ const isBudgetRejection = !isRateLimit && MAX_TOKENS_REJECTED_PATTERN.test(rawMessage);
1533
+ if (isBudgetRejection) {
1534
+ const next = this.downshiftMaxTokensBudget({
1535
+ model,
1536
+ currentMaxTokens: maxTokensBudget,
1537
+ providerEvidence: rawMessage,
1538
+ input,
1539
+ runId,
1540
+ attempt,
1541
+ });
1542
+ if (next !== undefined) {
1243
1543
  if (input) {
1244
1544
  this.emitAttemptTelemetry({
1245
1545
  input,
1246
1546
  runId,
1247
1547
  attempt,
1248
- maxRetries,
1249
- err: pdErr,
1548
+ maxRetries: transportMaxRetries,
1549
+ err: new PDRuntimeError('output_invalid', 'output budget rejected by provider', {
1550
+ providerEvidence: safeStringifyPreview(rawMessage, 300),
1551
+ }),
1250
1552
  elapsedMs: elapsedMsAfter,
1251
1553
  timeoutSource,
1252
1554
  effectiveTimeoutMs,
1253
1555
  });
1254
1556
  }
1255
- const delay = getDelay(attempt);
1256
- await new Promise(r => setTimeout(r, delay));
1557
+ maxTokensBudget = next;
1257
1558
  continue;
1258
1559
  }
1259
- throw pdErr;
1260
1560
  }
1261
- // execution_failed — retryable if attempts remain
1262
- // ADR-0019: detect rate-limit signatures first and classify as rate_limit
1263
- // (distinct from execution_failed) so downstream retryOrFail can degrade.
1264
- const isRateLimit = /rate.?limit|429|quota|too many requests/i.test(rawMessage);
1265
- // PRI-1011: a rejected output budget is a parameter problem, not a
1266
- // transport one — resending the identical rejected value can only fail
1267
- // the same way, so the next attempt goes out with a smaller budget.
1268
- const isBudgetRejection = !isRateLimit && MAX_TOKENS_REJECTED_PATTERN.test(rawMessage);
1269
- const errorCategory = isRateLimit ? 'rate_limit' : 'execution_failed';
1270
- const pdErr = new PDRuntimeError(errorCategory, `${isRateLimit ? 'LLM rate limit hit' : 'LLM execution failed'}: ${rawMessage.substring(0, 300)}`, {
1561
+ const errorCategory = statusClassification && statusClassification.category !== 'rate_limit'
1562
+ ? statusClassification.category
1563
+ : isRateLimit
1564
+ ? 'rate_limit'
1565
+ : 'execution_failed';
1566
+ throw new PDRuntimeError(errorCategory, `${isRateLimit ? 'LLM rate limit hit' : 'LLM execution failed'}: ${rawMessage.substring(0, 300)}`, {
1271
1567
  retryAttempt: attempt,
1272
- maxRetries,
1568
+ transportMaxRetries,
1569
+ retryOwnership: 'pi-ai',
1273
1570
  elapsedMs: elapsedMsAfter,
1274
1571
  providerEvidence: safeStringifyPreview(rawMessage, 300),
1572
+ finalFailureReason: 'pi_ai_retries_exhausted',
1573
+ ...statusEvidence,
1275
1574
  });
1276
- lastError = pdErr;
1277
- if (attempt < maxRetries) {
1278
- if (input) {
1279
- this.emitAttemptTelemetry({
1280
- input,
1281
- runId,
1282
- attempt,
1283
- maxRetries,
1284
- err: pdErr,
1285
- elapsedMs: elapsedMsAfter,
1286
- timeoutSource,
1287
- effectiveTimeoutMs,
1288
- });
1289
- }
1290
- // PRI-1011: downshift BEFORE the next request goes out, so a rejected
1291
- // budget is never resent unchanged.
1292
- if (isBudgetRejection) {
1293
- const next = this.downshiftMaxTokensBudget({
1294
- model,
1295
- currentMaxTokens: maxTokensBudget,
1296
- providerEvidence: rawMessage,
1297
- input,
1298
- runId,
1299
- attempt,
1300
- });
1301
- if (next !== undefined)
1302
- maxTokensBudget = next;
1303
- }
1304
- // ADR-0019: rate-limit uses 2× backoff since limits need more time to clear
1305
- const delay = isRateLimit ? getDelay(attempt) * 2 : getDelay(attempt);
1306
- await new Promise(r => setTimeout(r, delay));
1307
- continue;
1308
- }
1309
- throw pdErr;
1310
1575
  }
1311
1576
  return response;
1312
1577
  }
1313
1578
  catch (err) {
1314
1579
  const elapsedMsAfter = Date.now() - overallStartTime;
1580
+ const errMsg = err instanceof Error ? err.message : String(err);
1581
+ // An error that left this function's try block as a PDRuntimeError has
1582
+ // already been classified (status code, context overflow, timeout
1583
+ // budget). Re-running `classifyFailure`'s text heuristics over its
1584
+ // composed message would overwrite that category — e.g. a 400 whose
1585
+ // body says "invalid parameter: timeout" would become `timeout`.
1586
+ if (err instanceof PDRuntimeError) {
1587
+ throw err;
1588
+ }
1589
+ // S3: a recovered HTTP status is authoritative; text heuristics only
1590
+ // apply when the status is absent or has no PD-specific meaning.
1591
+ const statusClassification = classifyProviderHttpStatus(extractProviderHttpStatus(errMsg) ?? -1);
1592
+ const statusEvidence = providerStatusEvidence(errMsg);
1315
1593
  let classificationResult = classifyFailure(err, options.signal);
1594
+ if (statusClassification?.category === 'timeout') {
1595
+ classificationResult = { category: 'timeout', classification: 'provider_transient_timeout' };
1596
+ }
1316
1597
  if (options.signal?.aborted || elapsedMsAfter >= effectiveTimeoutMs) {
1317
1598
  classificationResult = {
1318
1599
  category: 'timeout',
1319
1600
  classification: 'client_timeout_budget_exhausted',
1320
1601
  };
1321
1602
  }
1322
- // If it's a client budget exhaustion, throw immediately (no retry)
1603
+ // The run's own deadline is authoritative: stop immediately.
1323
1604
  if (classificationResult.classification === 'client_timeout_budget_exhausted') {
1324
- const errorDetails = {
1605
+ throw new PDRuntimeError('timeout', `LLM request timed out after ${effectiveTimeoutMs}ms`, {
1325
1606
  timeoutClassification: 'client_timeout_budget_exhausted',
1326
1607
  effectiveTimeoutMs,
1327
1608
  timeoutSource,
1328
1609
  elapsedMs: elapsedMsAfter,
1329
1610
  retryAttempt: attempt,
1330
- maxRetries,
1611
+ transportMaxRetries,
1612
+ retryOwnership: 'pi-ai',
1331
1613
  providerEvidence: safeStringifyPreview(err, 300),
1332
- };
1333
- throw new PDRuntimeError('timeout', `LLM request timed out after ${effectiveTimeoutMs}ms`, errorDetails);
1614
+ ...statusEvidence,
1615
+ });
1334
1616
  }
1335
1617
  if (classificationResult.category === 'timeout') {
1336
- const errorDetails = {
1618
+ // S2: a transient provider timeout is no longer retried here — pi-ai
1619
+ // already spent its retry budget before surfacing it.
1620
+ throw new PDRuntimeError('timeout', `LLM request timed out after ${effectiveTimeoutMs}ms`, {
1337
1621
  timeoutClassification: 'provider_transient_timeout',
1338
1622
  effectiveTimeoutMs,
1339
1623
  timeoutSource,
1340
1624
  elapsedMs: elapsedMsAfter,
1341
1625
  retryAttempt: attempt,
1342
- maxRetries,
1626
+ transportMaxRetries,
1627
+ retryOwnership: 'pi-ai',
1343
1628
  providerEvidence: safeStringifyPreview(err, 300),
1344
- };
1345
- const pdErr = new PDRuntimeError('timeout', `LLM request timed out after ${effectiveTimeoutMs}ms`, errorDetails);
1346
- lastError = pdErr;
1347
- if (attempt < maxRetries) {
1629
+ finalFailureReason: 'pi_ai_retries_exhausted',
1630
+ ...statusEvidence,
1631
+ });
1632
+ }
1633
+ // ADR-0019: keep rate-limit signatures a distinct category.
1634
+ const isRateLimitCatch = statusClassification
1635
+ ? statusClassification.category === 'rate_limit'
1636
+ : /rate.?limit|429|quota|too many requests/i.test(errMsg);
1637
+ // PRI-1011: SDKs may throw the budget rejection instead of resolving it.
1638
+ const isBudgetRejectionCatch = !isRateLimitCatch && MAX_TOKENS_REJECTED_PATTERN.test(errMsg);
1639
+ if (isBudgetRejectionCatch) {
1640
+ const next = this.downshiftMaxTokensBudget({
1641
+ model,
1642
+ currentMaxTokens: maxTokensBudget,
1643
+ providerEvidence: errMsg,
1644
+ input,
1645
+ runId,
1646
+ attempt,
1647
+ });
1648
+ if (next !== undefined) {
1348
1649
  if (input) {
1349
1650
  this.emitAttemptTelemetry({
1350
1651
  input,
1351
1652
  runId,
1352
1653
  attempt,
1353
- maxRetries,
1354
- err: pdErr,
1654
+ maxRetries: transportMaxRetries,
1655
+ err: new PDRuntimeError('output_invalid', 'output budget rejected by provider', {
1656
+ providerEvidence: safeStringifyPreview(errMsg, 300),
1657
+ }),
1355
1658
  elapsedMs: elapsedMsAfter,
1356
1659
  timeoutSource,
1357
1660
  effectiveTimeoutMs,
1358
1661
  });
1359
1662
  }
1360
- const delay = getDelay(attempt);
1361
- await new Promise(r => setTimeout(r, delay));
1663
+ maxTokensBudget = next;
1362
1664
  continue;
1363
1665
  }
1364
- throw pdErr;
1365
1666
  }
1366
- if (err instanceof PDRuntimeError) {
1367
- throw err; // don't retry standard PDRuntimeError if it is permanent or already handled
1368
- }
1369
- // It is an execution_failed (network, etc.)
1370
- // ADR-0019: detect rate-limit signatures in thrown errors too (SDK may throw 429)
1371
- const errMsg = err instanceof Error ? err.message : String(err);
1372
- const isRateLimitCatch = /rate.?limit|429|quota|too many requests/i.test(errMsg);
1373
- // PRI-1011: SDKs may throw the budget rejection instead of resolving it.
1374
- const isBudgetRejectionCatch = !isRateLimitCatch && MAX_TOKENS_REJECTED_PATTERN.test(errMsg);
1375
- const catchCategory = isRateLimitCatch ? 'rate_limit' : 'execution_failed';
1376
- const errorDetails = {
1667
+ const catchCategory = statusClassification && statusClassification.category !== 'rate_limit'
1668
+ ? statusClassification.category
1669
+ : isRateLimitCatch
1670
+ ? 'rate_limit'
1671
+ : 'execution_failed';
1672
+ throw new PDRuntimeError(catchCategory, `${isRateLimitCatch ? 'LLM rate limit hit' : 'LLM completion failed'}: ${errMsg.substring(0, 300)}`, {
1377
1673
  retryAttempt: attempt,
1378
- maxRetries,
1674
+ transportMaxRetries,
1675
+ retryOwnership: 'pi-ai',
1379
1676
  elapsedMs: elapsedMsAfter,
1380
1677
  providerEvidence: safeStringifyPreview(err, 300),
1381
- };
1382
- const pdErr = new PDRuntimeError(catchCategory, `${isRateLimitCatch ? 'LLM rate limit hit' : 'LLM completion failed'}: ${errMsg.substring(0, 300)}`, errorDetails);
1383
- lastError = pdErr;
1384
- if (attempt < maxRetries) {
1385
- if (input) {
1386
- this.emitAttemptTelemetry({
1387
- input,
1388
- runId,
1389
- attempt,
1390
- maxRetries,
1391
- err: pdErr,
1392
- elapsedMs: elapsedMsAfter,
1393
- timeoutSource,
1394
- effectiveTimeoutMs,
1395
- });
1396
- }
1397
- // PRI-1011: downshift BEFORE the next request goes out, so a rejected
1398
- // budget is never resent unchanged.
1399
- if (isBudgetRejectionCatch) {
1400
- const next = this.downshiftMaxTokensBudget({
1401
- model,
1402
- currentMaxTokens: maxTokensBudget,
1403
- providerEvidence: errMsg,
1404
- input,
1405
- runId,
1406
- attempt,
1407
- });
1408
- if (next !== undefined)
1409
- maxTokensBudget = next;
1410
- }
1411
- // ADR-0019: rate-limit uses 2× backoff
1412
- const delay = isRateLimitCatch ? getDelay(attempt) * 2 : getDelay(attempt);
1413
- await new Promise(r => setTimeout(r, delay));
1414
- }
1678
+ finalFailureReason: 'pi_ai_retries_exhausted',
1679
+ ...statusEvidence,
1680
+ });
1415
1681
  }
1416
1682
  }
1417
- // If lastError is already a PDRuntimeError, re-throw it; otherwise wrap it
1418
- if (lastError instanceof PDRuntimeError) {
1419
- throw lastError;
1420
- }
1421
- throw new PDRuntimeError('execution_failed', `LLM completion failed after ${maxRetries + 1} attempts: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
1422
1683
  }
1423
1684
  /**
1424
1685
  * PRI-1011: move one step down the output-budget ladder and record it.