create-principles-disciple 1.150.2 → 1.150.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_release/product-identity.json +1 -1
- package/codex-adapter/dist/ingestion/admission.js +2 -0
- package/codex-adapter/dist/pd-hook.d.ts +7 -5
- package/codex-adapter/dist/pd-hook.js +18 -7
- package/codex-adapter/dist/tool-semantics.js +5 -1
- package/codex-adapter/dist/worker/workspace-worker.js +4 -2
- package/codex-adapter/package.json +1 -1
- package/console/dist/lib/utils.js +16 -1
- package/console/dist/web/assets/app.css +147 -46
- package/console/dist/web/assets/app.js +35 -32
- package/console/package.json +2 -0
- package/core/dist/runtime/activation/adaptive-selection-output.d.ts +35 -0
- package/core/dist/runtime/activation/adaptive-selection-output.d.ts.map +1 -0
- package/core/dist/runtime/activation/adaptive-selection-output.js +38 -0
- package/core/dist/runtime/activation/adaptive-selection-output.js.map +1 -0
- package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
- package/core/dist/runtime/activation-compatibility-read-model.js +2 -1
- package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
- package/core/dist/runtime/adapter/artificer-l2-adapter.d.ts.map +1 -1
- package/core/dist/runtime/adapter/artificer-l2-adapter.js +89 -27
- package/core/dist/runtime/adapter/artificer-l2-adapter.js.map +1 -1
- package/core/dist/runtime/adapter/context-budget.d.ts +49 -0
- package/core/dist/runtime/adapter/context-budget.d.ts.map +1 -0
- package/core/dist/runtime/adapter/context-budget.js +127 -0
- package/core/dist/runtime/adapter/context-budget.js.map +1 -0
- package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
- package/core/dist/runtime/adapter/output-schema-registry.js +7 -0
- package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
- package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts +30 -7
- package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
- package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +559 -211
- package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
- package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
- package/core/dist/runtime/candidate-audit.js +2 -1
- package/core/dist/runtime/candidate-audit.js.map +1 -1
- package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-effective.js +2 -0
- package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
- package/core/dist/runtime/config/pd-config-types.d.ts +52 -0
- package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-types.js.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.js +134 -0
- package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-contract.js +8 -0
- package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +24 -0
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
- package/core/dist/runtime/index.d.ts +2 -0
- package/core/dist/runtime/index.d.ts.map +1 -1
- package/core/dist/runtime/index.js +2 -0
- package/core/dist/runtime/index.js.map +1 -1
- package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +16 -0
- package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rule-host-input-builder.js +18 -0
- package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
- package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts +8 -0
- package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/split-diagnostician-runner.js +24 -2
- package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
- package/core/dist/runtime/internalization/tool-semantic-registry.d.ts +26 -0
- package/core/dist/runtime/internalization/tool-semantic-registry.d.ts.map +1 -1
- package/core/dist/runtime/internalization/tool-semantic-registry.js +55 -5
- package/core/dist/runtime/internalization/tool-semantic-registry.js.map +1 -1
- package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
- package/core/dist/runtime/internalization-chain-integrity-read-model.js +2 -2
- package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
- package/core/dist/runtime/internalization-integrity-remediation.d.ts.map +1 -1
- package/core/dist/runtime/internalization-integrity-remediation.js +2 -2
- package/core/dist/runtime/internalization-integrity-remediation.js.map +1 -1
- package/core/dist/runtime/operator-health-read-model.d.ts.map +1 -1
- package/core/dist/runtime/operator-health-read-model.js +2 -2
- package/core/dist/runtime/operator-health-read-model.js.map +1 -1
- package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
- package/core/dist/runtime/pain-recall-read-model.js +4 -3
- package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
- package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
- package/core/dist/runtime/pruning-read-model.js +3 -2
- package/core/dist/runtime/pruning-read-model.js.map +1 -1
- package/core/dist/runtime/risk/risk-calculator-policy.d.ts +12 -2
- package/core/dist/runtime/risk/risk-calculator-policy.d.ts.map +1 -1
- package/core/dist/runtime/risk/risk-calculator-policy.js +33 -22
- package/core/dist/runtime/risk/risk-calculator-policy.js.map +1 -1
- package/core/dist/runtime/schema-conformance-read-model.js +2 -2
- package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
- package/core/dist/runtime/store/sqlite-connection.d.ts +0 -5
- package/core/dist/runtime/store/sqlite-connection.d.ts.map +1 -1
- package/core/dist/runtime/store/sqlite-connection.js +4 -12
- package/core/dist/runtime/store/sqlite-connection.js.map +1 -1
- package/core/dist/runtime/store/storage-paths.d.ts +17 -0
- package/core/dist/runtime/store/storage-paths.d.ts.map +1 -0
- package/core/dist/runtime/store/storage-paths.js +52 -0
- package/core/dist/runtime/store/storage-paths.js.map +1 -0
- package/core/dist/runtime/trajectory-retention.d.ts +257 -0
- package/core/dist/runtime/trajectory-retention.d.ts.map +1 -0
- package/core/dist/runtime/trajectory-retention.js +598 -0
- package/core/dist/runtime/trajectory-retention.js.map +1 -0
- package/core/dist/telemetry-event.d.ts +2 -2
- package/core/dist/telemetry-event.d.ts.map +1 -1
- package/core/dist/telemetry-event.js +5 -0
- package/core/dist/telemetry-event.js.map +1 -1
- package/core/dist/trajectory-store.d.ts +9 -9
- package/core/dist/trajectory-store.d.ts.map +1 -1
- package/core/dist/trajectory-store.js +9 -12
- package/core/dist/trajectory-store.js.map +1 -1
- package/core/package.json +1 -1
- package/dist/installers/codex-host-installer.d.ts.map +1 -1
- package/dist/installers/codex-host-installer.js +92 -5
- package/dist/installers/codex-host-installer.js.map +1 -1
- package/dist/installers/mcp-binding-shape-mirror.d.ts +27 -0
- package/dist/installers/mcp-binding-shape-mirror.d.ts.map +1 -0
- package/dist/installers/mcp-binding-shape-mirror.js +105 -0
- package/dist/installers/mcp-binding-shape-mirror.js.map +1 -0
- package/dist/skill-catalog.d.ts +35 -0
- package/dist/skill-catalog.d.ts.map +1 -0
- package/dist/skill-catalog.js +85 -0
- package/dist/skill-catalog.js.map +1 -0
- package/dist/skill-delivery-parity.d.ts +22 -0
- package/dist/skill-delivery-parity.d.ts.map +1 -0
- package/dist/skill-delivery-parity.js +31 -0
- package/dist/skill-delivery-parity.js.map +1 -0
- package/host-runtime/dist/active-principle-prompt.d.ts +8 -0
- package/host-runtime/dist/active-principle-prompt.js +15 -5
- package/host-runtime/dist/adaptive-decision-protocol.d.ts +142 -0
- package/host-runtime/dist/adaptive-decision-protocol.js +190 -0
- package/host-runtime/dist/adaptive-priority-provider.d.ts +37 -13
- package/host-runtime/dist/adaptive-priority-provider.js +65 -62
- package/host-runtime/dist/adaptive-selection.d.ts +67 -62
- package/host-runtime/dist/adaptive-selection.js +218 -301
- package/host-runtime/dist/adaptive-skip-decision.d.ts +26 -14
- package/host-runtime/dist/adaptive-skip-decision.js +33 -29
- package/host-runtime/dist/codex-rule-context-provider.js +4 -1
- package/host-runtime/dist/governance-observation-store.d.ts +40 -1
- package/host-runtime/dist/governance-observation-store.js +188 -9
- package/host-runtime/dist/governance-signal-admission.d.ts +19 -3
- package/host-runtime/dist/governance-signal-admission.js +12 -4
- package/host-runtime/dist/host-tool-declaration.d.ts +18 -2
- package/host-runtime/dist/host-tool-declaration.js +67 -11
- package/host-runtime/dist/host-tool-semantic-resolver.d.ts +7 -0
- package/host-runtime/dist/host-tool-semantic-resolver.js +22 -2
- package/host-runtime/dist/index.d.ts +3 -0
- package/host-runtime/dist/index.js +14 -0
- package/host-runtime/dist/production-rulehost-gate.js +36 -4
- package/host-runtime/dist/trajectory-retention.d.ts +147 -0
- package/host-runtime/dist/trajectory-retention.js +907 -0
- package/host-runtime/package.json +1 -1
- package/install-layout/dist/index.d.ts +9 -2
- package/install-layout/dist/index.js +26 -9
- package/install-layout/dist/mcp-binding-contract.d.ts +91 -0
- package/install-layout/dist/mcp-binding-contract.js +230 -0
- package/install-layout/package.json +1 -1
- package/package.json +4 -4
- package/pd-cli/dist/commands/build-trajectory-evidence.d.ts.map +1 -1
- package/pd-cli/dist/commands/build-trajectory-evidence.js +17 -11
- package/pd-cli/dist/commands/build-trajectory-evidence.js.map +1 -1
- package/pd-cli/dist/commands/codex-reconcile.d.ts +7 -0
- package/pd-cli/dist/commands/codex-reconcile.d.ts.map +1 -1
- package/pd-cli/dist/commands/codex-reconcile.js +11 -2
- package/pd-cli/dist/commands/codex-reconcile.js.map +1 -1
- package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
- package/pd-cli/dist/commands/codex-worker.js +35 -0
- package/pd-cli/dist/commands/codex-worker.js.map +1 -1
- package/pd-cli/dist/commands/command-helpers.d.ts +1 -1
- package/pd-cli/dist/commands/command-helpers.js +1 -1
- package/pd-cli/dist/commands/errors-list.d.ts +1 -1
- package/pd-cli/dist/commands/errors-list.js +1 -1
- package/pd-cli/dist/commands/health-mcp.d.ts +23 -1
- package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
- package/pd-cli/dist/commands/health-mcp.js +81 -22
- package/pd-cli/dist/commands/health-mcp.js.map +1 -1
- package/pd-cli/dist/commands/health.d.ts +1 -1
- package/pd-cli/dist/commands/health.d.ts.map +1 -1
- package/pd-cli/dist/commands/health.js +12 -5
- package/pd-cli/dist/commands/health.js.map +1 -1
- package/pd-cli/dist/commands/principles-stats.d.ts +1 -1
- package/pd-cli/dist/commands/principles-stats.js +1 -1
- package/pd-cli/dist/commands/trajectory-retention.d.ts +23 -0
- package/pd-cli/dist/commands/trajectory-retention.d.ts.map +1 -0
- package/pd-cli/dist/commands/trajectory-retention.js +159 -0
- package/pd-cli/dist/commands/trajectory-retention.js.map +1 -0
- package/pd-cli/dist/commands/workbuddy-setup.d.ts +69 -0
- package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -0
- package/pd-cli/dist/commands/workbuddy-setup.js +379 -0
- package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -0
- package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
- package/pd-cli/dist/commands/workbuddy-worker.js +42 -6
- package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
- package/pd-cli/dist/index.d.ts +1 -7
- package/pd-cli/dist/index.d.ts.map +1 -1
- package/pd-cli/dist/index.js +15 -1201
- package/pd-cli/dist/index.js.map +1 -1
- package/pd-cli/dist/program.d.ts +17 -0
- package/pd-cli/dist/program.d.ts.map +1 -0
- package/pd-cli/dist/program.js +1263 -0
- package/pd-cli/dist/program.js.map +1 -0
- package/pd-cli/dist/services/delivery-surfaces.d.ts.map +1 -1
- package/pd-cli/dist/services/delivery-surfaces.js +7 -5
- package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
- package/pd-cli/dist/services/version-report.d.ts.map +1 -1
- package/pd-cli/dist/services/version-report.js +30 -4
- package/pd-cli/dist/services/version-report.js.map +1 -1
- package/pd-cli/package.json +1 -1
- package/pd-mcp-server/dist/version.d.ts +1 -1
- package/pd-mcp-server/dist/version.js +1 -1
- package/pd-mcp-server/package.json +3 -1
- package/plugin/dist/bundle.js +477 -471
- package/plugin/dist/constants/tools.d.ts +8 -1
- package/plugin/dist/core/trajectory-retention-trigger.d.ts +13 -0
- package/plugin/dist/core/trajectory.d.ts +14 -0
- package/plugin/dist/hooks/gate-block-helper.d.ts +17 -0
- package/plugin/dist/hooks/gate.d.ts +7 -2
- package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +1 -0
- package/plugin/dist/index.d.ts +5 -0
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/dist/rulehost-evidence.js +29 -23
- package/plugin/dist/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
- package/plugin/dist/templates/langs/en/skills/pd-control/SKILL.md +7 -6
- package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
- package/plugin/dist/templates/langs/en/skills/pd-review/SKILL.md +15 -1
- package/plugin/dist/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
- package/plugin/dist/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
- package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
- package/plugin/dist/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
- package/plugin/templates/langs/en/skills/pd-control/SKILL.md +7 -6
- package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
- package/plugin/templates/langs/en/skills/pd-review/SKILL.md +15 -1
- package/plugin/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
- package/plugin/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
- package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
- package/plugin/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
- package/release-manager/dist/installers/codex-host-installer.js +92 -5
- package/release-manager/dist/installers/mcp-binding-shape-mirror.js +105 -0
- package/release-manager/package.json +1 -1
- package/workbuddy-adapter/dist/codec/input-decoder.d.ts +10 -0
- package/workbuddy-adapter/dist/codec/input-decoder.js +62 -5
- package/workbuddy-adapter/dist/host-adapter.js +1 -0
- package/workbuddy-adapter/dist/index.d.ts +1 -0
- package/workbuddy-adapter/dist/index.js +1 -0
- package/workbuddy-adapter/dist/ingestion/catch-up.d.ts +25 -0
- package/workbuddy-adapter/dist/ingestion/catch-up.js +161 -0
- package/workbuddy-adapter/dist/ingestion/encode-cwd.d.ts +6 -0
- package/workbuddy-adapter/dist/ingestion/encode-cwd.js +39 -0
- package/workbuddy-adapter/dist/ingestion/index.d.ts +13 -0
- package/workbuddy-adapter/dist/ingestion/index.js +13 -0
- package/workbuddy-adapter/dist/ingestion/ingestion.d.ts +46 -0
- package/workbuddy-adapter/dist/ingestion/ingestion.js +135 -0
- package/workbuddy-adapter/dist/ingestion/transcript-decoder.d.ts +70 -0
- package/workbuddy-adapter/dist/ingestion/transcript-decoder.js +554 -0
- package/workbuddy-adapter/dist/ingestion/transcript-path.d.ts +39 -0
- package/workbuddy-adapter/dist/ingestion/transcript-path.js +117 -0
- package/workbuddy-adapter/dist/ingestion/transcript-source.d.ts +15 -0
- package/workbuddy-adapter/dist/ingestion/transcript-source.js +152 -0
- package/workbuddy-adapter/dist/pd-hook.d.ts +8 -0
- package/workbuddy-adapter/dist/pd-hook.js +59 -2
- package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -0
- package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -17
- package/workbuddy-adapter/package.json +1 -1
- package/workbuddy-adapter/plugin/hooks/hooks.json +11 -0
- package/workbuddy-adapter/plugin/skills/pd-cli-operator/SKILL.md +57 -19
- package/workbuddy-adapter/plugin/skills/pd-control/SKILL.md +21 -9
- package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +72 -61
- package/workbuddy-adapter/plugin/skills/pd-review/SKILL.md +27 -12
|
@@ -27,12 +27,15 @@ import { PDRuntimeError } from '../error-categories.js';
|
|
|
27
27
|
import { extractJsonObject, extractJsonObjectForSchema, extractJsonObjects, selectBestJsonObject } from './json-extractor.js';
|
|
28
28
|
import { resolveOutputSchema } from './output-schema-registry.js';
|
|
29
29
|
import { storeEmitter } from '../store/event-emitter.js';
|
|
30
|
-
import { attemptStructuredOutputRepair, deriveSchemaSummary } from './structured-output-repair.js';
|
|
30
|
+
import { attemptStructuredOutputRepair, DEFAULT_REPAIR_CONFIG, deriveSchemaSummary } from './structured-output-repair.js';
|
|
31
31
|
import { typeboxToOpenAIJsonSchema, sanitizeSchemaName } from './schema-json-converter.js';
|
|
32
32
|
import { formatValidationErrorEntry, safeStringifyPreview, stripLineageFields } from './output-repair-contract.js';
|
|
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,50 @@ 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
|
+
* S6: one request budget per logical run. A run may attempt at most this many
|
|
80
|
+
* provider requests in total, across the three output paths, the PRI-1011
|
|
81
|
+
* downshift retries and the schema repair loop. pi-ai's own transport retries
|
|
82
|
+
* (S2) happen inside a single PD request and are deliberately not counted —
|
|
83
|
+
* they are not requests PD decided to send.
|
|
84
|
+
*
|
|
85
|
+
* The budget lives in startRun's local scope: no adapter config key, no new
|
|
86
|
+
* public interface. Reverting the change restores the previous unbounded
|
|
87
|
+
* worst case.
|
|
88
|
+
*/
|
|
89
|
+
const RUN_REQUEST_BUDGET = 3;
|
|
90
|
+
/** S6: claim one request from the run budget, or report exhaustion. */
|
|
91
|
+
function consumeRunRequest(budget) {
|
|
92
|
+
if (budget.requestsLeft <= 0)
|
|
93
|
+
return false;
|
|
94
|
+
budget.requestsLeft -= 1;
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* S2: cap on the wait pi-ai may take between its own transport retries.
|
|
99
|
+
* pi-ai defaults to 60s per wait; 30s keeps the worst-case wait no worse than
|
|
100
|
+
* PD's previous capped backoff. A provider that asks for longer fails fast
|
|
101
|
+
* with its original message instead of parking the run.
|
|
102
|
+
*/
|
|
103
|
+
const PI_AI_MAX_RETRY_DELAY_MS = 30_000;
|
|
57
104
|
/** PRI-966 G2 P1-03: bounded usage summary from an AssistantMessage. Fields
|
|
58
105
|
* stay null when the provider did not surface a count — never guessed. An
|
|
59
106
|
* all-zero usage object is pi-ai's "provider surfaced nothing" placeholder
|
|
@@ -204,6 +251,65 @@ function isAbortError(err, signal) {
|
|
|
204
251
|
return true;
|
|
205
252
|
return false;
|
|
206
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* S1: true only when the run was aborted by an explicit caller cancel, never
|
|
256
|
+
* when the run's own time budget expired. Both leave `signal.aborted === true`,
|
|
257
|
+
* so the abort reason is the only reliable discriminator.
|
|
258
|
+
*/
|
|
259
|
+
function isCancelledSignal(signal) {
|
|
260
|
+
return signal?.aborted === true && signal.reason === CANCEL_ABORT_REASON;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* S3: recover the HTTP status from pi-ai's composed provider error message.
|
|
264
|
+
*
|
|
265
|
+
* pi-ai stops carrying the structured status once a failure becomes
|
|
266
|
+
* `AssistantMessage{stopReason:'error'}`, but `formatProviderError` builds the
|
|
267
|
+
* message as `<status>: <body>` (or `<prefix> (<status>): <body>`), so the
|
|
268
|
+
* status is still available without wrapping `fetch` and without inventing a
|
|
269
|
+
* second HTTP observation channel.
|
|
270
|
+
*/
|
|
271
|
+
export function extractProviderHttpStatus(rawMessage) {
|
|
272
|
+
const leading = /^\s*(\d{3})(?:\s|:|$)/.exec(rawMessage);
|
|
273
|
+
// Only `<prefix> (<status>): <body>` carries a status in parentheses; an
|
|
274
|
+
// arbitrary `(123)` in a message with no such shape is free-form text, not a
|
|
275
|
+
// provider status (rc-2: do not present a guess as authoritative evidence).
|
|
276
|
+
const parenthesized = /^[^:]*?\((\d{3})\)\s*:/.exec(rawMessage);
|
|
277
|
+
const status = Number(leading?.[1] ?? parenthesized?.[1]);
|
|
278
|
+
if (!Number.isInteger(status) || status < 100 || status > 599)
|
|
279
|
+
return undefined;
|
|
280
|
+
return status;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* S3: status-code-first classification. Returns `undefined` for codes PD has no
|
|
284
|
+
* specific meaning for (404, 409, …) so the caller keeps the text fallback and
|
|
285
|
+
* can mark the evidence `status_unknown`/`text_fallback` instead of guessing.
|
|
286
|
+
*/
|
|
287
|
+
function classifyProviderHttpStatus(status) {
|
|
288
|
+
if (status === 401 || status === 403)
|
|
289
|
+
return { category: 'input_invalid', label: 'provider_auth' };
|
|
290
|
+
if (status === 400 || status === 422)
|
|
291
|
+
return { category: 'input_invalid', label: 'provider_request' };
|
|
292
|
+
if (status === 408)
|
|
293
|
+
return { category: 'timeout', label: 'provider_timeout' };
|
|
294
|
+
if (status === 429)
|
|
295
|
+
return { category: 'rate_limit', label: 'provider_rate_limit' };
|
|
296
|
+
if (status >= 500 && status <= 599)
|
|
297
|
+
return { category: 'execution_failed', label: 'provider_upstream' };
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
/** S3: evidence attached to every provider failure so the classification is auditable. */
|
|
301
|
+
function providerStatusEvidence(rawMessage) {
|
|
302
|
+
const httpStatus = extractProviderHttpStatus(rawMessage);
|
|
303
|
+
const classification = httpStatus === undefined ? undefined : classifyProviderHttpStatus(httpStatus);
|
|
304
|
+
if (httpStatus === undefined) {
|
|
305
|
+
return { errorClassificationSource: 'text_fallback', statusUnknown: true };
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
httpStatus,
|
|
309
|
+
errorClassificationSource: classification ? 'status_code' : 'text_fallback',
|
|
310
|
+
...(classification ? { providerErrorClass: classification.label } : {}),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
207
313
|
function classifyFailure(err, signal) {
|
|
208
314
|
if (signal?.aborted) {
|
|
209
315
|
return {
|
|
@@ -257,11 +363,12 @@ function classifyFailure(err, signal) {
|
|
|
257
363
|
* so downstream code never sees a "successful" response that is actually broken.
|
|
258
364
|
*
|
|
259
365
|
* Error classification:
|
|
260
|
-
*
|
|
261
|
-
* stopReason:'
|
|
262
|
-
* stopReason:'error' +
|
|
263
|
-
* stopReason:'
|
|
264
|
-
*
|
|
366
|
+
* recovered HTTP status → S3 status-code mapping
|
|
367
|
+
* stopReason:'aborted' → timeout
|
|
368
|
+
* stopReason:'error' + timeout/abort in message → timeout
|
|
369
|
+
* stopReason:'error' + other → execution_failed
|
|
370
|
+
* stopReason:'length' + no extractable content → output_invalid (truncated)
|
|
371
|
+
* no text or thinking content block → output_invalid
|
|
265
372
|
*
|
|
266
373
|
* Reasoning-model fallback (BUG-007a):
|
|
267
374
|
* When all content blocks have empty text (common with reasoning models that
|
|
@@ -275,13 +382,25 @@ function extractAssistantTextOrThrow(response, signal) {
|
|
|
275
382
|
const rawMessage = response.errorMessage ?? 'unknown provider error';
|
|
276
383
|
// Truncate to 300 chars to avoid leaking huge payloads into logs/telemetry
|
|
277
384
|
const boundedMessage = rawMessage.length > 300 ? rawMessage.substring(0, 300) + '...' : rawMessage;
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
385
|
+
// S3: status code first; text heuristics only when no status is recoverable.
|
|
386
|
+
const statusClassification = classifyProviderHttpStatus(extractProviderHttpStatus(rawMessage) ?? -1);
|
|
387
|
+
const isTimeout = statusClassification
|
|
388
|
+
? statusClassification.category === 'timeout'
|
|
389
|
+
: response.stopReason === 'aborted'
|
|
390
|
+
|| signal?.aborted
|
|
391
|
+
|| /timeout|timed\s*out/i.test(rawMessage)
|
|
392
|
+
|| /abort/i.test(rawMessage);
|
|
393
|
+
const category = statusClassification && statusClassification.category !== 'timeout'
|
|
394
|
+
? statusClassification.category
|
|
395
|
+
: isTimeout
|
|
396
|
+
? 'timeout'
|
|
397
|
+
: 'execution_failed';
|
|
398
|
+
throw new PDRuntimeError(category, isTimeout
|
|
283
399
|
? `LLM request timed out: ${boundedMessage}`
|
|
284
|
-
: `LLM execution failed: ${boundedMessage}
|
|
400
|
+
: `LLM execution failed: ${boundedMessage}`, {
|
|
401
|
+
...(isTimeout ? { timeoutClassification: 'provider_transient_timeout' } : {}),
|
|
402
|
+
...providerStatusEvidence(rawMessage),
|
|
403
|
+
});
|
|
285
404
|
}
|
|
286
405
|
// Find text content (may be mixed with thinking content from reasoning-enabled models)
|
|
287
406
|
const textContent = response.content.find(c => c.type === 'text' && c.text && c.text.trim().length > 0);
|
|
@@ -314,6 +433,11 @@ function extractAssistantTextOrThrow(response, signal) {
|
|
|
314
433
|
export class PiAiRuntimeAdapter {
|
|
315
434
|
config;
|
|
316
435
|
runs = new Map();
|
|
436
|
+
/**
|
|
437
|
+
* S1: one controller per in-flight run. cancelRun() aborts it; startRun()
|
|
438
|
+
* clears it in `finally` so a finished run can never be aborted afterwards.
|
|
439
|
+
*/
|
|
440
|
+
abortControllers = new Map();
|
|
317
441
|
eventEmitter;
|
|
318
442
|
runtimeKind = 'pi-ai';
|
|
319
443
|
defaultCapabilities = {
|
|
@@ -503,62 +627,101 @@ export class PiAiRuntimeAdapter {
|
|
|
503
627
|
status: 'failed', // default until succeeded
|
|
504
628
|
};
|
|
505
629
|
this.runs.set(runId, runState);
|
|
630
|
+
// S6: every provider request this run sends draws from one local budget.
|
|
631
|
+
const requestBudget = { requestsLeft: RUN_REQUEST_BUDGET };
|
|
506
632
|
// AbortSignal.timeout for clean timeout control
|
|
507
633
|
// Priority: input.timeoutMs (runner) > config.timeoutMs (workflows.yaml) > 300_000 (default)
|
|
508
634
|
const effectiveTimeoutMs = input.timeoutMs ?? this.config.timeoutMs ?? 300_000;
|
|
509
635
|
const timeoutSource = input.timeoutMs !== undefined ? 'runner_input'
|
|
510
636
|
: this.config.timeoutMs !== undefined ? 'adapter_config'
|
|
511
637
|
: '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
638
|
// PRI-633: layered system prompt — base layer from the run's prompt
|
|
523
639
|
// builder (input.systemPrompt: agent role + protocol) + append layer from
|
|
524
640
|
// the profile config (this.config.systemPrompt). When both are absent the
|
|
525
641
|
// Context keeps its pre-PRI-633 shape (no systemPrompt field).
|
|
642
|
+
// Declared outside the try because the run handle returned afterwards
|
|
643
|
+
// reports its digest (PRI-1146 P1-02).
|
|
526
644
|
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
645
|
const systemPromptDigest = systemPrompt === undefined
|
|
531
646
|
? undefined
|
|
532
647
|
: createHash('sha256').update(systemPrompt, 'utf8').digest('hex');
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
//
|
|
538
|
-
|
|
539
|
-
//
|
|
540
|
-
//
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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
|
-
});
|
|
648
|
+
// S1: one AbortController per run, owning BOTH stop paths:
|
|
649
|
+
// - cancelRun() aborts it with CANCEL_ABORT_REASON;
|
|
650
|
+
// - the timer below aborts it when the run's time budget expires.
|
|
651
|
+
// A single controller means every request in the run (all three output
|
|
652
|
+
// paths + repair calls) shares one deadline, and a real cancel propagates
|
|
653
|
+
// to the in-flight HTTP request instead of being a documented no-op.
|
|
654
|
+
// Registered immediately before the first await so the cleanup in `finally`
|
|
655
|
+
// always pairs with it.
|
|
656
|
+
const abortController = new AbortController();
|
|
657
|
+
this.abortControllers.set(runId, abortController);
|
|
658
|
+
const { signal } = abortController;
|
|
659
|
+
const runDeadlineAt = Date.now() + effectiveTimeoutMs;
|
|
660
|
+
const budgetTimer = setTimeout(() => {
|
|
661
|
+
if (!signal.aborted)
|
|
662
|
+
abortController.abort();
|
|
663
|
+
}, effectiveTimeoutMs);
|
|
561
664
|
try {
|
|
665
|
+
const messageContent = typeof input.inputPayload === 'string'
|
|
666
|
+
? input.inputPayload
|
|
667
|
+
: JSON.stringify(input.inputPayload);
|
|
668
|
+
const userMessage = {
|
|
669
|
+
role: 'user',
|
|
670
|
+
content: messageContent,
|
|
671
|
+
timestamp: Date.now(),
|
|
672
|
+
};
|
|
673
|
+
// PRI-633: layered system prompt — base layer from the run's prompt
|
|
674
|
+
// builder (input.systemPrompt: agent role + protocol) + append layer from
|
|
675
|
+
// the profile config (this.config.systemPrompt). When both are absent the
|
|
676
|
+
// Context keeps its pre-PRI-633 shape (no systemPrompt field).
|
|
677
|
+
const context = {
|
|
678
|
+
messages: [userMessage],
|
|
679
|
+
...(systemPrompt ? { systemPrompt } : {}),
|
|
680
|
+
};
|
|
681
|
+
// Get model
|
|
682
|
+
const model = resolveModel(this.config.provider, this.config.model, this.config.baseUrl);
|
|
683
|
+
// Per-run output budget: each output path below resolves it through
|
|
684
|
+
// resolveEffectiveMaxTokens(input, model) — validating an explicit
|
|
685
|
+
// per-request budget BEFORE its first request is built, and applying the
|
|
686
|
+
// min(per-request, profile, model-ceiling) hard cap.
|
|
687
|
+
// Emit runtime_invocation_started telemetry
|
|
688
|
+
this.eventEmitter.emitTelemetry({
|
|
689
|
+
eventType: 'runtime_invocation_started',
|
|
690
|
+
traceId: input.taskRef?.taskId ?? runId,
|
|
691
|
+
timestamp: startedAt,
|
|
692
|
+
sessionId: 'pi-ai-adapter',
|
|
693
|
+
agentId: 'pi-ai-adapter',
|
|
694
|
+
payload: {
|
|
695
|
+
runId,
|
|
696
|
+
runtimeKind: 'pi-ai',
|
|
697
|
+
runnerKind: input.agentSpec.agentId,
|
|
698
|
+
provider: this.config.provider,
|
|
699
|
+
model: this.config.model,
|
|
700
|
+
timeoutMs: effectiveTimeoutMs,
|
|
701
|
+
timeoutSource,
|
|
702
|
+
outputSchemaRef: input.outputSchemaRef ?? 'unknown',
|
|
703
|
+
},
|
|
704
|
+
});
|
|
705
|
+
// S4: estimate the assembled request against the model's own context
|
|
706
|
+
// window before spending a request. An oversized request fails loud with a
|
|
707
|
+
// structured overflow reason (and a next action) rather than being sent,
|
|
708
|
+
// rejected by the provider, and reported as a generic failure.
|
|
709
|
+
const contextBudget = resolveContextBudget(model.contextWindow, this.resolveEffectiveMaxTokens(input, model) ?? 0);
|
|
710
|
+
const estimatedInputTokens = estimateRequestTokens({
|
|
711
|
+
systemPrompt,
|
|
712
|
+
texts: [messageContent],
|
|
713
|
+
});
|
|
714
|
+
if (estimatedInputTokens > contextBudget.budgetTokens) {
|
|
715
|
+
throw new PDRuntimeError('input_invalid', `LLM context overflow (pre-flight estimate): ~${estimatedInputTokens} input tokens > ${contextBudget.budgetTokens} budget`, {
|
|
716
|
+
contextOverflow: true,
|
|
717
|
+
contextWindowTokens: contextBudget.contextWindowTokens,
|
|
718
|
+
budgetTokens: contextBudget.budgetTokens,
|
|
719
|
+
reserveOutputTokens: contextBudget.reserveOutputTokens,
|
|
720
|
+
estimatedInputTokens,
|
|
721
|
+
nextAction: 'reduce_context',
|
|
722
|
+
finalFailureReason: 'context_overflow',
|
|
723
|
+
});
|
|
724
|
+
}
|
|
562
725
|
// PRI-271 B3: Three-path fallback chain for structured output
|
|
563
726
|
const schemaRef = input.outputSchemaRef;
|
|
564
727
|
const schema = resolveOutputSchema(schemaRef);
|
|
@@ -591,7 +754,7 @@ export class PiAiRuntimeAdapter {
|
|
|
591
754
|
}
|
|
592
755
|
// ── Path 1: Tool calling (PRI-271 B2) ──
|
|
593
756
|
if (strategy === 'tool_call_first' && schema && schemaRef) {
|
|
594
|
-
const toolResult = await this.tryToolCallPath({ model, baseContext: context, schemaRef, schema, signal, apiKey, effectiveTimeoutMs, input, runId });
|
|
757
|
+
const toolResult = await this.tryToolCallPath({ model, baseContext: context, schemaRef, schema, signal, apiKey, effectiveTimeoutMs, input, runId, requestBudget });
|
|
595
758
|
if (toolResult.success && toolResult.output !== undefined) {
|
|
596
759
|
validatedOutput = toolResult.output;
|
|
597
760
|
responseUsage = toolResult.usage ?? null;
|
|
@@ -603,7 +766,7 @@ export class PiAiRuntimeAdapter {
|
|
|
603
766
|
}
|
|
604
767
|
// ── Path 2: JSON mode (PRI-271 B1) ──
|
|
605
768
|
if (!validatedOutput && (strategy === 'tool_call_first' || strategy === 'json_mode_first') && schema && schemaRef) {
|
|
606
|
-
const jsonResult = await this.tryJsonModePath({ model, baseContext: context, schemaRef, schema, signal, apiKey, effectiveTimeoutMs, input, runId });
|
|
769
|
+
const jsonResult = await this.tryJsonModePath({ model, baseContext: context, schemaRef, schema, signal, apiKey, effectiveTimeoutMs, input, runId, requestBudget });
|
|
607
770
|
if (jsonResult.success && jsonResult.output !== undefined) {
|
|
608
771
|
validatedOutput = jsonResult.output;
|
|
609
772
|
responseUsage = jsonResult.usage ?? null;
|
|
@@ -615,7 +778,7 @@ export class PiAiRuntimeAdapter {
|
|
|
615
778
|
}
|
|
616
779
|
// ── Path 3: Free-form + repair (current behavior, enhanced) ──
|
|
617
780
|
if (!validatedOutput) {
|
|
618
|
-
const response = await this.completeWithRetry(model, context, { signal, apiKey, effectiveTimeoutMs, timeoutSource, input, runId });
|
|
781
|
+
const response = await this.completeWithRetry(model, context, { signal, apiKey, effectiveTimeoutMs, timeoutSource, input, runId, requestBudget });
|
|
619
782
|
const text = extractAssistantTextOrThrow(response, signal);
|
|
620
783
|
// PRI-707: preserve what the provider actually told us about how the
|
|
621
784
|
// response ended. Before this, finish metadata (stopReason/usage) was
|
|
@@ -701,8 +864,30 @@ export class PiAiRuntimeAdapter {
|
|
|
701
864
|
const originalOutput = typeof parsedOutput === 'object'
|
|
702
865
|
? parsedOutput
|
|
703
866
|
: undefined;
|
|
867
|
+
// S1: a repair attempt costs another round trip. When the run budget
|
|
868
|
+
// is almost gone it can only be aborted mid-flight, replacing a
|
|
869
|
+
// precise schema error with a vague timeout — so skip it and report
|
|
870
|
+
// the schema error we already have. attemptsUsed=0 in the telemetry
|
|
871
|
+
// below is the observable record of the skip.
|
|
872
|
+
const repairBudgetExhausted = runDeadlineAt - Date.now() < MIN_REPAIR_BUDGET_MS;
|
|
873
|
+
// S6: repair attempts are provider requests too, so they draw from the
|
|
874
|
+
// same run budget. When the three output paths already spent it, the
|
|
875
|
+
// schema error we have is returned instead of starting a repair loop
|
|
876
|
+
// that cannot send anything.
|
|
877
|
+
const configuredRepairAttempts = this.config.maxRepairAttempts ?? DEFAULT_REPAIR_CONFIG.maxRepairAttempts;
|
|
878
|
+
const repairAttemptsAllowed = Math.min(configuredRepairAttempts, Math.max(0, requestBudget.requestsLeft));
|
|
879
|
+
// S1: time-budget skip is decided before the loop (a repair that
|
|
880
|
+
// cannot finish inside the deadline is not started at all).
|
|
881
|
+
const repairTimeBudgetSkipEvidence = repairBudgetExhausted
|
|
882
|
+
? { repairSkipped: true, repairSkipReason: 'budget_exhausted', remainingBudgetMs: Math.max(0, runDeadlineAt - Date.now()) }
|
|
883
|
+
: {};
|
|
704
884
|
const repairResult = await attemptStructuredOutputRepair(parsedOutput, schemaErrors, {
|
|
705
|
-
llmCaller: (prompt) =>
|
|
885
|
+
llmCaller: (prompt) => {
|
|
886
|
+
// S6: maxRepairAttempts is already capped by the remaining run
|
|
887
|
+
// budget, so every repair attempt is guaranteed one request.
|
|
888
|
+
consumeRunRequest(requestBudget);
|
|
889
|
+
return this.repairLLMCall(model, prompt, { signal, apiKey, systemPrompt, input, runDeadlineAt });
|
|
890
|
+
},
|
|
706
891
|
schemaCheck: (value) => Value.Check(schema, value),
|
|
707
892
|
schemaErrors: (value) => [...Value.Errors(schema, value)].map(e => ({ path: e.path, message: e.message, value: e.value })),
|
|
708
893
|
}, {
|
|
@@ -711,7 +896,7 @@ export class PiAiRuntimeAdapter {
|
|
|
711
896
|
schemaSummary,
|
|
712
897
|
schemaJson,
|
|
713
898
|
requiredKeys,
|
|
714
|
-
maxRepairAttempts:
|
|
899
|
+
maxRepairAttempts: repairBudgetExhausted ? 0 : repairAttemptsAllowed,
|
|
715
900
|
// PRI-707: when finish metadata proves the output was cut by the
|
|
716
901
|
// token limit, the repair LLM must know — repairing a truncated
|
|
717
902
|
// fragment like a schema misunderstanding produced blind fixes.
|
|
@@ -719,6 +904,29 @@ export class PiAiRuntimeAdapter {
|
|
|
719
904
|
? `The previous output was cut off by the token limit (finish_reason=length${finishOutputTokens !== undefined ? `, ${finishOutputTokens} output tokens` : ''}). It is incomplete, not misunderstood. Do NOT invent missing content beyond the schema; produce the SHORTEST complete JSON object that satisfies the schema.`
|
|
720
905
|
: undefined,
|
|
721
906
|
});
|
|
907
|
+
// S6: the run budget can run out *during* the repair loop, not only
|
|
908
|
+
// before it. The loop can start at most `repairAttemptsAllowed`
|
|
909
|
+
// attempts, so every configured attempt above that cap had no request
|
|
910
|
+
// left. Report them by count — otherwise a partially truncated repair
|
|
911
|
+
// (configured 3, budget 3, 1 path spent → only 2 repair attempts) looks
|
|
912
|
+
// identical to a loop that simply used everything it was given.
|
|
913
|
+
// A successful repair ended the loop deliberately and skipped nothing.
|
|
914
|
+
const repairAttemptsSkippedByRequestBudget = !repairBudgetExhausted && !repairResult.repaired
|
|
915
|
+
? Math.max(0, configuredRepairAttempts - repairAttemptsAllowed)
|
|
916
|
+
: 0;
|
|
917
|
+
const repairRequestBudgetSkipEvidence = repairAttemptsSkippedByRequestBudget > 0
|
|
918
|
+
? {
|
|
919
|
+
// `repairSkipped` keeps its S1 meaning: the loop never ran.
|
|
920
|
+
...(repairAttemptsAllowed === 0 ? { repairSkipped: true } : {}),
|
|
921
|
+
repairSkipReason: 'request_budget_exhausted',
|
|
922
|
+
repairAttemptsConfigured: configuredRepairAttempts,
|
|
923
|
+
repairAttemptsSkippedByRequestBudget,
|
|
924
|
+
}
|
|
925
|
+
: {};
|
|
926
|
+
const repairSkipEvidence = {
|
|
927
|
+
...repairTimeBudgetSkipEvidence,
|
|
928
|
+
...repairRequestBudgetSkipEvidence,
|
|
929
|
+
};
|
|
722
930
|
this.eventEmitter.emitTelemetry({
|
|
723
931
|
eventType: 'output_repair_attempted',
|
|
724
932
|
traceId: input.taskRef?.taskId ?? runId,
|
|
@@ -734,8 +942,26 @@ export class PiAiRuntimeAdapter {
|
|
|
734
942
|
repairSummary: repairResult.repairSummary,
|
|
735
943
|
repairAttempts: repairResult.repairAttempts,
|
|
736
944
|
outputPath: 'free_form_with_repair',
|
|
945
|
+
// S1/S6: never truncate silently — when repair was skipped
|
|
946
|
+
// because the time budget or the run's request budget was spent,
|
|
947
|
+
// say which one in the event.
|
|
948
|
+
...repairSkipEvidence,
|
|
737
949
|
},
|
|
738
950
|
});
|
|
951
|
+
// S1: an abort during repair must surface as the real stop reason
|
|
952
|
+
// (caller cancel or budget expiry). The repair loop treats a throwing
|
|
953
|
+
// llmCaller as "attempt failed", which would otherwise disguise a
|
|
954
|
+
// stopped run as a schema mismatch.
|
|
955
|
+
if (isCancelledSignal(signal)) {
|
|
956
|
+
throw new PDRuntimeError('cancelled', 'LLM run cancelled by caller during output repair', {
|
|
957
|
+
cancelled: true,
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
if (signal.aborted) {
|
|
961
|
+
throw new PDRuntimeError('timeout', 'LLM run budget exhausted during output repair', {
|
|
962
|
+
timeoutClassification: 'client_timeout_budget_exhausted',
|
|
963
|
+
});
|
|
964
|
+
}
|
|
739
965
|
if (repairResult.repaired && repairResult.output) {
|
|
740
966
|
parsedOutput = repairResult.output;
|
|
741
967
|
}
|
|
@@ -775,6 +1001,7 @@ export class PiAiRuntimeAdapter {
|
|
|
775
1001
|
validationErrors: validationErrorEntries,
|
|
776
1002
|
repairAttempts: evidencePack.repairAttempts,
|
|
777
1003
|
finalFailureReason: evidencePack.finalFailureReason,
|
|
1004
|
+
...repairSkipEvidence,
|
|
778
1005
|
// PRI-707: keep the terminal repair-exhausted event able to
|
|
779
1006
|
// distinguish a token-limit cut from an ordinary schema
|
|
780
1007
|
// failure — mirror the evidencePack finish metadata (PR #1574
|
|
@@ -831,6 +1058,10 @@ export class PiAiRuntimeAdapter {
|
|
|
831
1058
|
let timeoutClassification = 'not_applicable';
|
|
832
1059
|
let providerEvidence = '';
|
|
833
1060
|
let retryAttempt = 0;
|
|
1061
|
+
// S3: carry the status-code evidence into the terminal failure event so
|
|
1062
|
+
// "why was this classified this way" stays auditable.
|
|
1063
|
+
let httpStatus;
|
|
1064
|
+
let errorClassificationSource;
|
|
834
1065
|
if (err instanceof PDRuntimeError && err.details) {
|
|
835
1066
|
const { details } = err;
|
|
836
1067
|
if (isObjectWithKey(details, 'timeoutClassification')) {
|
|
@@ -848,8 +1079,29 @@ export class PiAiRuntimeAdapter {
|
|
|
848
1079
|
if (typeof ra === 'number')
|
|
849
1080
|
retryAttempt = ra;
|
|
850
1081
|
}
|
|
1082
|
+
if (isObjectWithKey(details, 'httpStatus')) {
|
|
1083
|
+
const { httpStatus: hs } = details;
|
|
1084
|
+
if (typeof hs === 'number')
|
|
1085
|
+
httpStatus = hs;
|
|
1086
|
+
}
|
|
1087
|
+
if (isObjectWithKey(details, 'errorClassificationSource')) {
|
|
1088
|
+
const { errorClassificationSource: ecs } = details;
|
|
1089
|
+
if (typeof ecs === 'string')
|
|
1090
|
+
errorClassificationSource = ecs;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
if (isCancelledSignal(signal)) {
|
|
1094
|
+
// S1: a caller cancel is terminal and must never be retried, wrapped
|
|
1095
|
+
// as a generic failure, or reported as a timeout — the run did not run
|
|
1096
|
+
// out of time, the Owner withdrew it.
|
|
1097
|
+
runState.status = 'cancelled';
|
|
1098
|
+
runState.reason = 'cancelled: run stopped by caller';
|
|
1099
|
+
timeoutClassification = 'cancelled';
|
|
1100
|
+
if (!providerEvidence) {
|
|
1101
|
+
providerEvidence = safeStringifyPreview(err, 300);
|
|
1102
|
+
}
|
|
851
1103
|
}
|
|
852
|
-
if (isAbortError(err, signal)) {
|
|
1104
|
+
else if (isAbortError(err, signal)) {
|
|
853
1105
|
runState.status = 'timed_out';
|
|
854
1106
|
runState.reason = `[timeout] LLM request timed out after ${effectiveTimeoutMs}ms (timeoutSource=${timeoutSource})`;
|
|
855
1107
|
if (timeoutClassification === 'not_applicable') {
|
|
@@ -901,8 +1153,20 @@ export class PiAiRuntimeAdapter {
|
|
|
901
1153
|
errorMessage: runState.reason,
|
|
902
1154
|
errorCategory,
|
|
903
1155
|
finalFailure: true,
|
|
1156
|
+
...(httpStatus !== undefined ? { httpStatus } : {}),
|
|
1157
|
+
...(errorClassificationSource ? { errorClassificationSource } : {}),
|
|
904
1158
|
},
|
|
905
1159
|
});
|
|
1160
|
+
// S1: cancellation wins over the generic wrapping below — the category
|
|
1161
|
+
// must be `cancelled` whether the abort surfaced as a thrown AbortError,
|
|
1162
|
+
// a PDRuntimeError from a lower layer, or a provider "aborted" result.
|
|
1163
|
+
if (isCancelledSignal(signal)) {
|
|
1164
|
+
throw new PDRuntimeError('cancelled', 'LLM run cancelled by caller', {
|
|
1165
|
+
elapsedMs,
|
|
1166
|
+
cancelled: true,
|
|
1167
|
+
providerEvidence,
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
906
1170
|
// Re-throw PDRuntimeError as-is, wrap others
|
|
907
1171
|
if (err instanceof PDRuntimeError) {
|
|
908
1172
|
throw err;
|
|
@@ -912,6 +1176,13 @@ export class PiAiRuntimeAdapter {
|
|
|
912
1176
|
providerEvidence,
|
|
913
1177
|
});
|
|
914
1178
|
}
|
|
1179
|
+
finally {
|
|
1180
|
+
// S1: the run is terminal — release the abort handle and the budget timer
|
|
1181
|
+
// so a finished run can never be aborted and the timer cannot keep the
|
|
1182
|
+
// process alive.
|
|
1183
|
+
clearTimeout(budgetTimer);
|
|
1184
|
+
this.abortControllers.delete(runId);
|
|
1185
|
+
}
|
|
915
1186
|
return { runId, runtimeKind: 'pi-ai', startedAt, ...(systemPromptDigest === undefined ? {} : { systemPromptDigest }) };
|
|
916
1187
|
}
|
|
917
1188
|
async pollRun(runId) {
|
|
@@ -928,12 +1199,23 @@ export class PiAiRuntimeAdapter {
|
|
|
928
1199
|
};
|
|
929
1200
|
}
|
|
930
1201
|
async cancelRun(runId) {
|
|
931
|
-
//
|
|
932
|
-
//
|
|
933
|
-
const
|
|
934
|
-
if (
|
|
1202
|
+
// S1: abort the in-flight request. The abort reason is what lets the run
|
|
1203
|
+
// be classified as `cancelled` instead of `timeout` downstream.
|
|
1204
|
+
const controller = this.abortControllers.get(runId);
|
|
1205
|
+
if (!controller) {
|
|
1206
|
+
// Terminal or unknown run: nothing is in flight to stop.
|
|
935
1207
|
return;
|
|
936
1208
|
}
|
|
1209
|
+
if (!controller.signal.aborted) {
|
|
1210
|
+
controller.abort(CANCEL_ABORT_REASON);
|
|
1211
|
+
}
|
|
1212
|
+
// The run's catch block performs the authoritative status transition; this
|
|
1213
|
+
// keeps pollRun() truthful even if the provider ignores the abort.
|
|
1214
|
+
const state = this.runs.get(runId);
|
|
1215
|
+
if (state && state.status !== 'succeeded') {
|
|
1216
|
+
state.status = 'cancelled';
|
|
1217
|
+
state.reason = 'cancelled: run stopped by caller';
|
|
1218
|
+
}
|
|
937
1219
|
}
|
|
938
1220
|
async fetchOutput(runId) {
|
|
939
1221
|
const state = this.runs.get(runId);
|
|
@@ -970,6 +1252,12 @@ export class PiAiRuntimeAdapter {
|
|
|
970
1252
|
...params.baseContext,
|
|
971
1253
|
tools: [buildSchemaToolDefinition(params.schemaRef, params.schema, new DefaultSchemaPromptAdapter())],
|
|
972
1254
|
};
|
|
1255
|
+
// S6: spend from the run's shared budget. The tool path is always the
|
|
1256
|
+
// first of the three budgeted output paths, so with the budget set to
|
|
1257
|
+
// the path count it cannot find itself exhausted; the checks that can
|
|
1258
|
+
// actually fire live in completeWithRetry's downshift loop and in the
|
|
1259
|
+
// repair loop.
|
|
1260
|
+
consumeRunRequest(params.requestBudget);
|
|
973
1261
|
const completeOptions = {
|
|
974
1262
|
signal: params.signal,
|
|
975
1263
|
apiKey: params.apiKey,
|
|
@@ -1028,6 +1316,11 @@ export class PiAiRuntimeAdapter {
|
|
|
1028
1316
|
*/
|
|
1029
1317
|
async tryJsonModePath(params) {
|
|
1030
1318
|
try {
|
|
1319
|
+
// S6: spend from the run's shared budget. The JSON path is at most the
|
|
1320
|
+
// second of the three budgeted output paths, so it cannot find itself
|
|
1321
|
+
// exhausted; the checks that can fire live in completeWithRetry's
|
|
1322
|
+
// downshift loop and in the repair loop.
|
|
1323
|
+
consumeRunRequest(params.requestBudget);
|
|
1031
1324
|
const completeOptions = {
|
|
1032
1325
|
signal: params.signal,
|
|
1033
1326
|
apiKey: params.apiKey,
|
|
@@ -1112,13 +1405,19 @@ export class PiAiRuntimeAdapter {
|
|
|
1112
1405
|
* Returns extracted text response or null if no content.
|
|
1113
1406
|
* Reuses same provider/model/apiKey as the original call.
|
|
1114
1407
|
*
|
|
1115
|
-
*
|
|
1116
|
-
*
|
|
1117
|
-
*
|
|
1408
|
+
* S1: the repair call inherits the run's REMAINING time budget instead of a
|
|
1409
|
+
* fresh fixed 60s allowance. Before this, a repair request could outlive the
|
|
1410
|
+
* run's own deadline by up to a minute, so the run "timed out" long after the
|
|
1411
|
+
* caller stopped waiting for it.
|
|
1118
1412
|
*/
|
|
1119
1413
|
async repairLLMCall(model, prompt, options) {
|
|
1120
|
-
const
|
|
1121
|
-
|
|
1414
|
+
const remainingMs = options.runDeadlineAt - Date.now();
|
|
1415
|
+
// Defensive: the call site already skips repair when the budget is nearly
|
|
1416
|
+
// spent. If it still happens (clock skew between the two checks), do not
|
|
1417
|
+
// send a request that cannot finish.
|
|
1418
|
+
if (remainingMs < MIN_REPAIR_BUDGET_MS)
|
|
1419
|
+
return null;
|
|
1420
|
+
const repairTimeoutMs = Math.min(REPAIR_TIMEOUT_MS_CEILING, remainingMs);
|
|
1122
1421
|
const repairMessage = {
|
|
1123
1422
|
role: 'user',
|
|
1124
1423
|
content: prompt,
|
|
@@ -1131,9 +1430,11 @@ export class PiAiRuntimeAdapter {
|
|
|
1131
1430
|
...(options.systemPrompt ? { systemPrompt: options.systemPrompt } : {}),
|
|
1132
1431
|
};
|
|
1133
1432
|
const response = await completeSimple(model, repairContext, {
|
|
1134
|
-
signal
|
|
1433
|
+
// The run signal already carries the shared deadline (and any caller
|
|
1434
|
+
// cancel); the per-attempt timeout mirrors what is left of it.
|
|
1435
|
+
signal: options.signal,
|
|
1135
1436
|
apiKey: options.apiKey,
|
|
1136
|
-
timeoutMs:
|
|
1437
|
+
timeoutMs: repairTimeoutMs,
|
|
1137
1438
|
maxRetries: 0,
|
|
1138
1439
|
maxTokens: this.resolveEffectiveMaxTokens(options.input, model),
|
|
1139
1440
|
// PRI-683 transport ownership: repair calls ride the same dedicated PD
|
|
@@ -1160,13 +1461,23 @@ export class PiAiRuntimeAdapter {
|
|
|
1160
1461
|
}
|
|
1161
1462
|
}
|
|
1162
1463
|
/**
|
|
1163
|
-
* Call pi-ai complete()
|
|
1164
|
-
*
|
|
1464
|
+
* Call pi-ai complete().
|
|
1465
|
+
*
|
|
1466
|
+
* S2: transport retries belong to pi-ai. It already knows which failures are
|
|
1467
|
+
* retryable (408/409/429/5xx, `x-should-retry`, `retry-after`) and how long
|
|
1468
|
+
* to wait, and its wait is abortable. PD therefore passes `maxRetries` /
|
|
1469
|
+
* `maxRetryDelayMs` instead of running its own loop, so one logical failure
|
|
1470
|
+
* can no longer cost both layers' retries.
|
|
1471
|
+
*
|
|
1472
|
+
* The only PD-side retry left is the PRI-1011 output-budget downshift: that
|
|
1473
|
+
* is a parameter fix pi-ai cannot infer, and each step strictly shrinks the
|
|
1474
|
+
* budget, so the ladder terminates by construction.
|
|
1165
1475
|
*/
|
|
1166
1476
|
async completeWithRetry(model, context, options) {
|
|
1167
|
-
const
|
|
1168
|
-
|
|
1169
|
-
|
|
1477
|
+
const { effectiveTimeoutMs = this.config.timeoutMs ?? 300_000, timeoutSource = 'default', input, runId = crypto.randomUUID(), requestBudget, } = options;
|
|
1478
|
+
// S2: the retry budget handed to pi-ai. It is recorded on every failure so
|
|
1479
|
+
// the final reason is auditable ("who retried, how many times").
|
|
1480
|
+
const transportMaxRetries = this.config.maxRetries ?? 2;
|
|
1170
1481
|
const overallStartTime = Date.now();
|
|
1171
1482
|
// PRI-1011: the output budget actually sent for THIS invocation. It starts at
|
|
1172
1483
|
// the per-run effective value (min of the per-request StartRunInput.maxTokens,
|
|
@@ -1176,12 +1487,15 @@ export class PiAiRuntimeAdapter {
|
|
|
1176
1487
|
let maxTokensBudget = input !== undefined
|
|
1177
1488
|
? this.resolveEffectiveMaxTokens(input, model)
|
|
1178
1489
|
: this.resolveMaxTokens();
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1490
|
+
// Number of requests PD itself sent for this logical call. Transport
|
|
1491
|
+
// retries inside pi-ai are invisible here by design (they are pi-ai's).
|
|
1492
|
+
let attemptsSent = 0;
|
|
1493
|
+
// S6: evidence from the previous attempt, carried into the error raised
|
|
1494
|
+
// when the run's shared budget cannot fund another attempt.
|
|
1495
|
+
let lastFailureEvidence;
|
|
1496
|
+
while (true) {
|
|
1497
|
+
attemptsSent += 1;
|
|
1498
|
+
const attempt = attemptsSent - 1;
|
|
1185
1499
|
const elapsedMs = Date.now() - overallStartTime;
|
|
1186
1500
|
const remainingMs = effectiveTimeoutMs - elapsedMs;
|
|
1187
1501
|
// Fail fast if overall budget signal is aborted, or if we have already run out of budget time
|
|
@@ -1192,7 +1506,8 @@ export class PiAiRuntimeAdapter {
|
|
|
1192
1506
|
timeoutSource,
|
|
1193
1507
|
elapsedMs,
|
|
1194
1508
|
retryAttempt: attempt,
|
|
1195
|
-
|
|
1509
|
+
transportMaxRetries,
|
|
1510
|
+
retryOwnership: 'pi-ai',
|
|
1196
1511
|
providerEvidence: options.signal?.aborted
|
|
1197
1512
|
? 'Client budget signal aborted'
|
|
1198
1513
|
: `Overall timeout budget exhausted (elapsed ${elapsedMs}ms of ${effectiveTimeoutMs}ms)`,
|
|
@@ -1206,219 +1521,252 @@ export class PiAiRuntimeAdapter {
|
|
|
1206
1521
|
signal: options.signal,
|
|
1207
1522
|
apiKey: options.apiKey,
|
|
1208
1523
|
timeoutMs: currentTimeoutMs,
|
|
1209
|
-
|
|
1524
|
+
// S2: pi-ai owns transport retry/backoff (it knows retryable status
|
|
1525
|
+
// codes, honors retry-after, and its sleep is abortable). Keeping this
|
|
1526
|
+
// at 0 would silently disable every transient retry.
|
|
1527
|
+
maxRetries: transportMaxRetries,
|
|
1528
|
+
// Locked at 30s so the worst-case single wait never grows past what
|
|
1529
|
+
// PD's own capped backoff allowed; a provider asking for longer fails
|
|
1530
|
+
// immediately and PD records the original message.
|
|
1531
|
+
maxRetryDelayMs: PI_AI_MAX_RETRY_DELAY_MS,
|
|
1210
1532
|
maxTokens: maxTokensBudget, // PRI-621: undefined = pi-ai native model ceiling; PRI-1011: shrinks on rejection
|
|
1211
1533
|
fetch: this.config.fetch ?? getPiAiFetchForApi(model.api),
|
|
1212
1534
|
};
|
|
1213
1535
|
if (this.config.reasoning !== undefined && this.config.reasoning !== false) {
|
|
1214
1536
|
completeOptions.reasoning = this.config.reasoning;
|
|
1215
1537
|
}
|
|
1538
|
+
// S6: no attempt may exceed the run's shared request budget. This also
|
|
1539
|
+
// bounds the PRI-1011 downshift ladder, which is the only reason this
|
|
1540
|
+
// loop can iterate after S2 moved transport retries into pi-ai.
|
|
1541
|
+
if (!consumeRunRequest(requestBudget)) {
|
|
1542
|
+
const requestsSent = RUN_REQUEST_BUDGET - requestBudget.requestsLeft;
|
|
1543
|
+
throw new PDRuntimeError('execution_failed', `LLM request budget exhausted after ${requestsSent}/${RUN_REQUEST_BUDGET} requests for this run`, {
|
|
1544
|
+
finalFailureReason: 'request_budget_exhausted',
|
|
1545
|
+
requestBudget: RUN_REQUEST_BUDGET,
|
|
1546
|
+
requestsSent,
|
|
1547
|
+
retryAttempt: attempt,
|
|
1548
|
+
transportMaxRetries,
|
|
1549
|
+
retryOwnership: 'pi-ai',
|
|
1550
|
+
...(lastFailureEvidence !== undefined
|
|
1551
|
+
? { providerEvidence: lastFailureEvidence }
|
|
1552
|
+
: {}),
|
|
1553
|
+
nextAction: 'The run already spent its request budget on other output paths; inspect the earlier output_path_fallback events before increasing it.',
|
|
1554
|
+
});
|
|
1555
|
+
}
|
|
1216
1556
|
const response = await completeSimple(model, context, completeOptions);
|
|
1217
|
-
// If provider resolved with an error response, classify and
|
|
1557
|
+
// If provider resolved with an error response, classify and decide.
|
|
1558
|
+
// S2: no transport retry happens here — pi-ai already retried every
|
|
1559
|
+
// failure it considers retryable before handing this back.
|
|
1218
1560
|
if (response.stopReason === 'error' || response.stopReason === 'aborted') {
|
|
1219
1561
|
const rawMessage = response.errorMessage ?? 'unknown provider error';
|
|
1220
1562
|
const elapsedMsAfter = Date.now() - overallStartTime;
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1563
|
+
// S3: a recovered HTTP status is authoritative; only the codes PD has
|
|
1564
|
+
// no specific meaning for fall back to the legacy text heuristics.
|
|
1565
|
+
const statusClassification = classifyProviderHttpStatus(extractProviderHttpStatus(rawMessage) ?? -1);
|
|
1566
|
+
const statusEvidence = providerStatusEvidence(rawMessage);
|
|
1567
|
+
const isTimeout = statusClassification
|
|
1568
|
+
? statusClassification.category === 'timeout'
|
|
1569
|
+
: response.stopReason === 'aborted'
|
|
1570
|
+
|| options.signal?.aborted
|
|
1571
|
+
|| /timeout|timed\s*out/i.test(rawMessage)
|
|
1572
|
+
|| /abort/i.test(rawMessage);
|
|
1225
1573
|
const classification = (options.signal?.aborted || elapsedMsAfter >= effectiveTimeoutMs)
|
|
1226
1574
|
? 'client_timeout_budget_exhausted'
|
|
1227
1575
|
: isTimeout
|
|
1228
1576
|
? 'provider_transient_timeout'
|
|
1229
1577
|
: 'not_applicable';
|
|
1230
1578
|
if (isTimeout) {
|
|
1231
|
-
|
|
1579
|
+
throw new PDRuntimeError('timeout', `[timeout] LLM request timed out after ${effectiveTimeoutMs}ms (timeoutSource=provider_request)`, {
|
|
1232
1580
|
timeoutClassification: classification,
|
|
1233
1581
|
effectiveTimeoutMs,
|
|
1234
1582
|
timeoutSource,
|
|
1235
1583
|
elapsedMs: elapsedMsAfter,
|
|
1236
1584
|
retryAttempt: attempt,
|
|
1237
|
-
|
|
1585
|
+
transportMaxRetries,
|
|
1586
|
+
retryOwnership: 'pi-ai',
|
|
1238
1587
|
providerEvidence: safeStringifyPreview(rawMessage, 300),
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1588
|
+
...statusEvidence,
|
|
1589
|
+
});
|
|
1590
|
+
}
|
|
1591
|
+
// S4: a context overflow is an input-size problem, not a transient or
|
|
1592
|
+
// upstream one. pi-ai owns the provider-specific overflow patterns, so
|
|
1593
|
+
// reuse them instead of letting a "prompt is too long" rejection fall
|
|
1594
|
+
// through to rate_limit/execution_failed.
|
|
1595
|
+
if (isContextOverflow(response, model.contextWindow)) {
|
|
1596
|
+
throw new PDRuntimeError('input_invalid', `LLM context overflow: ${rawMessage.substring(0, 300)}`, {
|
|
1597
|
+
contextOverflow: true,
|
|
1598
|
+
contextWindowTokens: model.contextWindow,
|
|
1599
|
+
nextAction: 'reduce_context',
|
|
1600
|
+
retryAttempt: attempt,
|
|
1601
|
+
transportMaxRetries,
|
|
1602
|
+
retryOwnership: 'pi-ai',
|
|
1603
|
+
elapsedMs: elapsedMsAfter,
|
|
1604
|
+
providerEvidence: safeStringifyPreview(rawMessage, 300),
|
|
1605
|
+
finalFailureReason: 'context_overflow',
|
|
1606
|
+
...statusEvidence,
|
|
1607
|
+
});
|
|
1608
|
+
}
|
|
1609
|
+
// ADR-0019: rate-limit signatures stay a distinct category so
|
|
1610
|
+
// downstream degradation can recognise them.
|
|
1611
|
+
const isRateLimit = statusClassification
|
|
1612
|
+
? statusClassification.category === 'rate_limit'
|
|
1613
|
+
: /rate.?limit|429|quota|too many requests/i.test(rawMessage);
|
|
1614
|
+
// PRI-1011: a rejected output budget is a parameter problem, not a
|
|
1615
|
+
// transport one — resending the identical rejected value can only fail
|
|
1616
|
+
// the same way, so the next attempt goes out with a smaller budget.
|
|
1617
|
+
const isBudgetRejection = !isRateLimit && MAX_TOKENS_REJECTED_PATTERN.test(rawMessage);
|
|
1618
|
+
if (isBudgetRejection) {
|
|
1619
|
+
const next = this.downshiftMaxTokensBudget({
|
|
1620
|
+
model,
|
|
1621
|
+
currentMaxTokens: maxTokensBudget,
|
|
1622
|
+
providerEvidence: rawMessage,
|
|
1623
|
+
input,
|
|
1624
|
+
runId,
|
|
1625
|
+
attempt,
|
|
1626
|
+
});
|
|
1627
|
+
if (next !== undefined) {
|
|
1243
1628
|
if (input) {
|
|
1244
1629
|
this.emitAttemptTelemetry({
|
|
1245
1630
|
input,
|
|
1246
1631
|
runId,
|
|
1247
1632
|
attempt,
|
|
1248
|
-
maxRetries,
|
|
1249
|
-
err:
|
|
1633
|
+
maxRetries: transportMaxRetries,
|
|
1634
|
+
err: new PDRuntimeError('output_invalid', 'output budget rejected by provider', {
|
|
1635
|
+
providerEvidence: safeStringifyPreview(rawMessage, 300),
|
|
1636
|
+
}),
|
|
1250
1637
|
elapsedMs: elapsedMsAfter,
|
|
1251
1638
|
timeoutSource,
|
|
1252
1639
|
effectiveTimeoutMs,
|
|
1253
1640
|
});
|
|
1254
1641
|
}
|
|
1255
|
-
|
|
1256
|
-
|
|
1642
|
+
maxTokensBudget = next;
|
|
1643
|
+
lastFailureEvidence = safeStringifyPreview(rawMessage, 300);
|
|
1257
1644
|
continue;
|
|
1258
1645
|
}
|
|
1259
|
-
throw pdErr;
|
|
1260
1646
|
}
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
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)}`, {
|
|
1647
|
+
const errorCategory = statusClassification && statusClassification.category !== 'rate_limit'
|
|
1648
|
+
? statusClassification.category
|
|
1649
|
+
: isRateLimit
|
|
1650
|
+
? 'rate_limit'
|
|
1651
|
+
: 'execution_failed';
|
|
1652
|
+
throw new PDRuntimeError(errorCategory, `${isRateLimit ? 'LLM rate limit hit' : 'LLM execution failed'}: ${rawMessage.substring(0, 300)}`, {
|
|
1271
1653
|
retryAttempt: attempt,
|
|
1272
|
-
|
|
1654
|
+
transportMaxRetries,
|
|
1655
|
+
retryOwnership: 'pi-ai',
|
|
1273
1656
|
elapsedMs: elapsedMsAfter,
|
|
1274
1657
|
providerEvidence: safeStringifyPreview(rawMessage, 300),
|
|
1658
|
+
finalFailureReason: 'pi_ai_retries_exhausted',
|
|
1659
|
+
...statusEvidence,
|
|
1275
1660
|
});
|
|
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
1661
|
}
|
|
1311
1662
|
return response;
|
|
1312
1663
|
}
|
|
1313
1664
|
catch (err) {
|
|
1314
1665
|
const elapsedMsAfter = Date.now() - overallStartTime;
|
|
1666
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
1667
|
+
// An error that left this function's try block as a PDRuntimeError has
|
|
1668
|
+
// already been classified (status code, context overflow, timeout
|
|
1669
|
+
// budget). Re-running `classifyFailure`'s text heuristics over its
|
|
1670
|
+
// composed message would overwrite that category — e.g. a 400 whose
|
|
1671
|
+
// body says "invalid parameter: timeout" would become `timeout`.
|
|
1672
|
+
if (err instanceof PDRuntimeError) {
|
|
1673
|
+
throw err;
|
|
1674
|
+
}
|
|
1675
|
+
// S3: a recovered HTTP status is authoritative; text heuristics only
|
|
1676
|
+
// apply when the status is absent or has no PD-specific meaning.
|
|
1677
|
+
const statusClassification = classifyProviderHttpStatus(extractProviderHttpStatus(errMsg) ?? -1);
|
|
1678
|
+
const statusEvidence = providerStatusEvidence(errMsg);
|
|
1315
1679
|
let classificationResult = classifyFailure(err, options.signal);
|
|
1680
|
+
if (statusClassification?.category === 'timeout') {
|
|
1681
|
+
classificationResult = { category: 'timeout', classification: 'provider_transient_timeout' };
|
|
1682
|
+
}
|
|
1316
1683
|
if (options.signal?.aborted || elapsedMsAfter >= effectiveTimeoutMs) {
|
|
1317
1684
|
classificationResult = {
|
|
1318
1685
|
category: 'timeout',
|
|
1319
1686
|
classification: 'client_timeout_budget_exhausted',
|
|
1320
1687
|
};
|
|
1321
1688
|
}
|
|
1322
|
-
//
|
|
1689
|
+
// The run's own deadline is authoritative: stop immediately.
|
|
1323
1690
|
if (classificationResult.classification === 'client_timeout_budget_exhausted') {
|
|
1324
|
-
|
|
1691
|
+
throw new PDRuntimeError('timeout', `LLM request timed out after ${effectiveTimeoutMs}ms`, {
|
|
1325
1692
|
timeoutClassification: 'client_timeout_budget_exhausted',
|
|
1326
1693
|
effectiveTimeoutMs,
|
|
1327
1694
|
timeoutSource,
|
|
1328
1695
|
elapsedMs: elapsedMsAfter,
|
|
1329
1696
|
retryAttempt: attempt,
|
|
1330
|
-
|
|
1697
|
+
transportMaxRetries,
|
|
1698
|
+
retryOwnership: 'pi-ai',
|
|
1331
1699
|
providerEvidence: safeStringifyPreview(err, 300),
|
|
1332
|
-
|
|
1333
|
-
|
|
1700
|
+
...statusEvidence,
|
|
1701
|
+
});
|
|
1334
1702
|
}
|
|
1335
1703
|
if (classificationResult.category === 'timeout') {
|
|
1336
|
-
|
|
1704
|
+
// S2: a transient provider timeout is no longer retried here — pi-ai
|
|
1705
|
+
// already spent its retry budget before surfacing it.
|
|
1706
|
+
throw new PDRuntimeError('timeout', `LLM request timed out after ${effectiveTimeoutMs}ms`, {
|
|
1337
1707
|
timeoutClassification: 'provider_transient_timeout',
|
|
1338
1708
|
effectiveTimeoutMs,
|
|
1339
1709
|
timeoutSource,
|
|
1340
1710
|
elapsedMs: elapsedMsAfter,
|
|
1341
1711
|
retryAttempt: attempt,
|
|
1342
|
-
|
|
1712
|
+
transportMaxRetries,
|
|
1713
|
+
retryOwnership: 'pi-ai',
|
|
1343
1714
|
providerEvidence: safeStringifyPreview(err, 300),
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1715
|
+
finalFailureReason: 'pi_ai_retries_exhausted',
|
|
1716
|
+
...statusEvidence,
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
// ADR-0019: keep rate-limit signatures a distinct category.
|
|
1720
|
+
const isRateLimitCatch = statusClassification
|
|
1721
|
+
? statusClassification.category === 'rate_limit'
|
|
1722
|
+
: /rate.?limit|429|quota|too many requests/i.test(errMsg);
|
|
1723
|
+
// PRI-1011: SDKs may throw the budget rejection instead of resolving it.
|
|
1724
|
+
const isBudgetRejectionCatch = !isRateLimitCatch && MAX_TOKENS_REJECTED_PATTERN.test(errMsg);
|
|
1725
|
+
if (isBudgetRejectionCatch) {
|
|
1726
|
+
const next = this.downshiftMaxTokensBudget({
|
|
1727
|
+
model,
|
|
1728
|
+
currentMaxTokens: maxTokensBudget,
|
|
1729
|
+
providerEvidence: errMsg,
|
|
1730
|
+
input,
|
|
1731
|
+
runId,
|
|
1732
|
+
attempt,
|
|
1733
|
+
});
|
|
1734
|
+
if (next !== undefined) {
|
|
1348
1735
|
if (input) {
|
|
1349
1736
|
this.emitAttemptTelemetry({
|
|
1350
1737
|
input,
|
|
1351
1738
|
runId,
|
|
1352
1739
|
attempt,
|
|
1353
|
-
maxRetries,
|
|
1354
|
-
err:
|
|
1740
|
+
maxRetries: transportMaxRetries,
|
|
1741
|
+
err: new PDRuntimeError('output_invalid', 'output budget rejected by provider', {
|
|
1742
|
+
providerEvidence: safeStringifyPreview(errMsg, 300),
|
|
1743
|
+
}),
|
|
1355
1744
|
elapsedMs: elapsedMsAfter,
|
|
1356
1745
|
timeoutSource,
|
|
1357
1746
|
effectiveTimeoutMs,
|
|
1358
1747
|
});
|
|
1359
1748
|
}
|
|
1360
|
-
|
|
1361
|
-
|
|
1749
|
+
maxTokensBudget = next;
|
|
1750
|
+
lastFailureEvidence = safeStringifyPreview(errMsg, 300);
|
|
1362
1751
|
continue;
|
|
1363
1752
|
}
|
|
1364
|
-
throw pdErr;
|
|
1365
1753
|
}
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
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 = {
|
|
1754
|
+
const catchCategory = statusClassification && statusClassification.category !== 'rate_limit'
|
|
1755
|
+
? statusClassification.category
|
|
1756
|
+
: isRateLimitCatch
|
|
1757
|
+
? 'rate_limit'
|
|
1758
|
+
: 'execution_failed';
|
|
1759
|
+
throw new PDRuntimeError(catchCategory, `${isRateLimitCatch ? 'LLM rate limit hit' : 'LLM completion failed'}: ${errMsg.substring(0, 300)}`, {
|
|
1377
1760
|
retryAttempt: attempt,
|
|
1378
|
-
|
|
1761
|
+
transportMaxRetries,
|
|
1762
|
+
retryOwnership: 'pi-ai',
|
|
1379
1763
|
elapsedMs: elapsedMsAfter,
|
|
1380
1764
|
providerEvidence: safeStringifyPreview(err, 300),
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
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
|
-
}
|
|
1765
|
+
finalFailureReason: 'pi_ai_retries_exhausted',
|
|
1766
|
+
...statusEvidence,
|
|
1767
|
+
});
|
|
1415
1768
|
}
|
|
1416
1769
|
}
|
|
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
1770
|
}
|
|
1423
1771
|
/**
|
|
1424
1772
|
* PRI-1011: move one step down the output-budget ladder and record it.
|