crysk 0.0.0 → 0.3.1
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/LICENSE +176 -0
- package/README.md +611 -3
- package/bin/pr-hero.js +166 -0
- package/config/models/anthropic.json +5 -0
- package/dist/SKILL-7e3725zn.md +496 -0
- package/dist/SKILL-7q35wcaz.md +66 -0
- package/dist/SKILL-9at22381.md +74 -0
- package/dist/SKILL-ex2hxxh3.md +134 -0
- package/dist/SKILL-y8rv8msh.md +134 -0
- package/dist/SKILL-ygka1bs0.md +515 -0
- package/dist/adjudicator-dtg2axnh.md +86 -0
- package/dist/admission-config.example-a9vqmmad.json +9 -0
- package/dist/ci-admission-camfbx2b.md +122 -0
- package/dist/ci-admission-qk9r9taq.md +124 -0
- package/dist/cli.js +42501 -0
- package/dist/consolidate-ac0mnfyj.md +24 -0
- package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
- package/dist/deep-review-logic-a6b1gczf.md +156 -0
- package/dist/deep-review-parity-0ec904db.md +120 -0
- package/dist/deep-review-reliability-qyakbjb9.md +125 -0
- package/dist/deep-review-resilience-3tz8y26e.md +118 -0
- package/dist/index.js +20190 -0
- package/dist/opencode-ci-7b0be64p.md +141 -0
- package/dist/review-refuter-j4e9gezy.md +71 -0
- package/dist/scout-yvp153q7.md +140 -0
- package/dist/summarizer-zca44nxa.md +18 -0
- package/dist/workflow-w1g9szna.yml +151 -0
- package/package.json +81 -4
- package/prompts/consolidate.md +24 -0
- package/prompts/default/PROVENANCE.md +18 -0
- package/prompts/default/deep-review-lifecycle.md +362 -0
- package/prompts/default/deep-review-logic.md +156 -0
- package/prompts/default/deep-review-parity.md +120 -0
- package/prompts/default/deep-review-reliability.md +125 -0
- package/prompts/default/deep-review-resilience.md +118 -0
- package/prompts/default/review-refuter.md +71 -0
- package/prompts/scout.md +140 -0
- package/prompts/summarizer.md +18 -0
- package/skills/crysk/SKILL.md +74 -0
- package/skills/crysk-ci-setup/SKILL.md +134 -0
- package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
- package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
- package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
- package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
- package/skills/crysk-loop/SKILL.md +515 -0
- package/skills/crysk-loop/adjudicator.md +86 -0
- package/skills/crysk-pr/SKILL.md +66 -0
- package/src/agent-env.ts +1084 -0
- package/src/asset-manifest.ts +83 -0
- package/src/assets.d.ts +6 -0
- package/src/assets.ts +183 -0
- package/src/brand-paths.ts +155 -0
- package/src/brand.ts +255 -0
- package/src/ci/admission-ledger.ts +350 -0
- package/src/ci/classify-error.ts +73 -0
- package/src/ci/cli-record.ts +271 -0
- package/src/ci/force-comment.ts +39 -0
- package/src/ci/gates.ts +945 -0
- package/src/ci/outcome.ts +2181 -0
- package/src/ci/override.ts +187 -0
- package/src/ci/publish.ts +1639 -0
- package/src/ci/reporter.ts +626 -0
- package/src/ci/review-admission.ts +910 -0
- package/src/ci/review-levels.ts +310 -0
- package/src/ci/review-policy.ts +18 -0
- package/src/ci/review-risk.ts +184 -0
- package/src/ci/setup.ts +844 -0
- package/src/ci/trigger.ts +1353 -0
- package/src/cli.ts +348 -0
- package/src/commands/activity.ts +67 -0
- package/src/commands/ci-setup-questions.ts +397 -0
- package/src/commands/ci-setup.ts +381 -0
- package/src/commands/config.ts +99 -0
- package/src/commands/doctor.ts +108 -0
- package/src/commands/init.ts +139 -0
- package/src/commands/mcp.ts +10 -0
- package/src/commands/menu.ts +129 -0
- package/src/commands/post.ts +302 -0
- package/src/commands/skills.ts +83 -0
- package/src/commands/status.ts +173 -0
- package/src/commands/triage.ts +342 -0
- package/src/commands/uninstall.ts +37 -0
- package/src/commands/upgrade.ts +214 -0
- package/src/commands/usage.ts +98 -0
- package/src/compare/compare.ts +28 -0
- package/src/compare/floor-test.ts +471 -0
- package/src/compare/martian-adapter.ts +80 -0
- package/src/config/config.ts +267 -0
- package/src/corpus/corpus.ts +1094 -0
- package/src/corpus/preflight.ts +1789 -0
- package/src/diversity/accounting.ts +90 -0
- package/src/diversity/adjudication.ts +145 -0
- package/src/diversity/admission.ts +60 -0
- package/src/diversity/benchmark.ts +195 -0
- package/src/diversity/clustering.ts +285 -0
- package/src/diversity/errors.ts +7 -0
- package/src/diversity/identity.ts +285 -0
- package/src/diversity/index.ts +11 -0
- package/src/diversity/pipeline-integration.ts +448 -0
- package/src/diversity/projection.ts +57 -0
- package/src/diversity/self-contained.ts +68 -0
- package/src/diversity/target-validation.ts +179 -0
- package/src/doctor-migration.ts +209 -0
- package/src/doctor.ts +723 -0
- package/src/errors.ts +83 -0
- package/src/execution/admission.ts +75 -0
- package/src/execution/atomic-write.ts +35 -0
- package/src/execution/attempt-evidence.ts +415 -0
- package/src/execution/bucket-id.ts +136 -0
- package/src/execution/concurrency-limiter.ts +175 -0
- package/src/execution/contracts.ts +443 -0
- package/src/execution/failure-classification.ts +42 -0
- package/src/execution/failure-policy.ts +240 -0
- package/src/execution/harness.ts +2548 -0
- package/src/execution/settlement.ts +348 -0
- package/src/execution/spawned-process.ts +66 -0
- package/src/execution/spend-limiter.ts +424 -0
- package/src/execution/step-artifacts.ts +55 -0
- package/src/execution/usage-normalized.ts +469 -0
- package/src/git/git.ts +396 -0
- package/src/git/identity.ts +64 -0
- package/src/git/refs.ts +140 -0
- package/src/home-preflight.ts +443 -0
- package/src/home.ts +243 -0
- package/src/ignore-file.ts +336 -0
- package/src/ignore-read.ts +118 -0
- package/src/index.ts +34 -0
- package/src/legacy-launchd.ts +29 -0
- package/src/mcp/mcp.ts +150 -0
- package/src/mcp/preflight.ts +407 -0
- package/src/menu-context.ts +192 -0
- package/src/model/catalog.ts +251 -0
- package/src/model/exec-snapshots.ts +390 -0
- package/src/model/free-discovery.ts +302 -0
- package/src/model/provider-capabilities.ts +814 -0
- package/src/model/routing.ts +600 -0
- package/src/pr/admission.ts +984 -0
- package/src/pr/answered-findings.ts +169 -0
- package/src/pr/ci-admission-gate.ts +743 -0
- package/src/pr/ci-publish.ts +76 -0
- package/src/pr/discovery.ts +432 -0
- package/src/pr/inline.ts +507 -0
- package/src/pr/plan.ts +366 -0
- package/src/pr/posting.ts +115 -0
- package/src/pr/pr-status.ts +845 -0
- package/src/pr/pr.ts +3642 -0
- package/src/pr/preflight.ts +1031 -0
- package/src/pr/publish-outcome.ts +361 -0
- package/src/pr/range.ts +119 -0
- package/src/pr/reverts-preflight.ts +606 -0
- package/src/pr/reverts.ts +377 -0
- package/src/pr/review-pr.ts +927 -0
- package/src/pr/status.ts +154 -0
- package/src/pr/target.ts +388 -0
- package/src/pr/teardown.ts +437 -0
- package/src/pr/worktree-setup.ts +60 -0
- package/src/production-runtime.ts +1877 -0
- package/src/progress.ts +487 -0
- package/src/rereview/adjudicate.ts +89 -0
- package/src/rereview/classify.ts +362 -0
- package/src/rereview/identity.ts +211 -0
- package/src/rereview/plan.ts +308 -0
- package/src/rereview/prepare.ts +1025 -0
- package/src/rereview/state.ts +767 -0
- package/src/rereview/verify.ts +241 -0
- package/src/review/boundary.ts +105 -0
- package/src/review/consolidate.ts +246 -0
- package/src/review/dedupe.ts +368 -0
- package/src/review/drafts.ts +448 -0
- package/src/review/findings-conformance.ts +120 -0
- package/src/review/findings.ts +714 -0
- package/src/review/pipeline.ts +3977 -0
- package/src/review/preflight.ts +3575 -0
- package/src/review/prompt-set.ts +177 -0
- package/src/review/proof-refs.ts +187 -0
- package/src/review/report.ts +1821 -0
- package/src/review/review.ts +490 -0
- package/src/review/root-cause.ts +120 -0
- package/src/review/route-preflight.ts +289 -0
- package/src/review/run.ts +601 -0
- package/src/review/scout.ts +323 -0
- package/src/review/size-gate.ts +595 -0
- package/src/review/spec.ts +235 -0
- package/src/review/step-runner.ts +233 -0
- package/src/runner-authority.ts +596 -0
- package/src/security/binding-policy.ts +115 -0
- package/src/security/credential-broker.ts +773 -0
- package/src/security/evidence-redaction.ts +62 -0
- package/src/security/execution-authority.ts +27 -0
- package/src/security/redact.ts +71 -0
- package/src/security/workspace-read-broker.ts +466 -0
- package/src/server/client.ts +190 -0
- package/src/server/preflight.ts +217 -0
- package/src/server/server.ts +327 -0
- package/src/signal-handler.ts +50 -0
- package/src/store/activity.ts +413 -0
- package/src/store/backfill-preflight.ts +49 -0
- package/src/store/backfill.ts +141 -0
- package/src/store/gc-preflight.ts +206 -0
- package/src/store/gc.ts +424 -0
- package/src/store/metrics-preflight.ts +229 -0
- package/src/store/metrics.ts +236 -0
- package/src/store/preflight.ts +748 -0
- package/src/store/store.ts +693 -0
- package/src/system-tools.ts +355 -0
- package/src/transport-registry.ts +1124 -0
- package/src/transports/claude-code-cli.ts +1348 -0
- package/src/transports/opencode-admission.ts +515 -0
- package/src/transports/opencode-client.ts +3328 -0
- package/src/transports/opencode-evidence.ts +557 -0
- package/src/transports/opencode-mcp.ts +248 -0
- package/src/transports/opencode-sdk.ts +2294 -0
- package/src/transports/opencode-server.ts +535 -0
- package/src/triage/adjudication.ts +113 -0
- package/src/triage/reply.ts +125 -0
- package/src/triage/triage.ts +255 -0
- package/src/ui/activity.ts +173 -0
- package/src/ui/config-edit.ts +816 -0
- package/src/ui/config.ts +462 -0
- package/src/ui/menu.ts +1325 -0
- package/src/ui/plan.ts +1039 -0
- package/src/ui/primitives.ts +300 -0
- package/src/ui/progress.ts +298 -0
- package/src/ui/result.ts +552 -0
- package/src/ui/review-menu.ts +312 -0
- package/src/ui/select.ts +528 -0
- package/src/ui/tree.ts +178 -0
- package/src/uninstaller.ts +479 -0
- package/src/updater.ts +836 -0
- package/src/usage.ts +77 -0
- package/src/watch/preflight.ts +1389 -0
- package/src/watch/watch.ts +1235 -0
- package/src/wizard.ts +877 -0
|
@@ -0,0 +1,2294 @@
|
|
|
1
|
+
import type { BucketScope } from "../execution/bucket-id";
|
|
2
|
+
import { deriveBucketId } from "../execution/bucket-id";
|
|
3
|
+
import type {
|
|
4
|
+
AsyncEventSink,
|
|
5
|
+
ProviderCapabilityReport,
|
|
6
|
+
ProviderEvent,
|
|
7
|
+
ProviderEventBase,
|
|
8
|
+
ProviderTerminalProof,
|
|
9
|
+
ProviderTransport,
|
|
10
|
+
ResolvedModelRoute,
|
|
11
|
+
TransportFailureCause,
|
|
12
|
+
TransportOutcome,
|
|
13
|
+
TransportRequest,
|
|
14
|
+
} from "../execution/contracts";
|
|
15
|
+
import type {
|
|
16
|
+
NormalizedTokens,
|
|
17
|
+
NormalizedUsage,
|
|
18
|
+
UsageBillingMode,
|
|
19
|
+
UsageModeState,
|
|
20
|
+
} from "../execution/usage-normalized";
|
|
21
|
+
import {
|
|
22
|
+
applyUsageUpdate,
|
|
23
|
+
normalizeUnavailableUsage,
|
|
24
|
+
UsageModeMismatchError,
|
|
25
|
+
} from "../execution/usage-normalized";
|
|
26
|
+
import { CredentialProjectionError } from "../security/credential-broker";
|
|
27
|
+
import { redactDiagnostic } from "../security/redact";
|
|
28
|
+
|
|
29
|
+
// WHY there is no @opencode-ai dependency here: production enablement over the
|
|
30
|
+
// real SDK is deliberately deferred to D1-11 (§12 D1-06 vs D1-11). This slice
|
|
31
|
+
// ships the full §3.2/§4/§5.2 transport mechanics against a narrow injectable
|
|
32
|
+
// client (OpenCodeClientLike) so every deadline, bound, and arbitration rule is
|
|
33
|
+
// offline-conformance-testable; the D1-11 adapter wraps the actual SDK in
|
|
34
|
+
// exactly this interface.
|
|
35
|
+
|
|
36
|
+
// WHY the known sums: OpenCode's token leaves are disjoint-additive
|
|
37
|
+
// (packages/schema/src/token-usage.ts: total = input + output + reasoning +
|
|
38
|
+
// cache.read + cache.write), so the aggregate input is uncached + cache read +
|
|
39
|
+
// cache write, and the output is visible + reasoning. Undefined leaves stay out
|
|
40
|
+
// of the sum; with only input/output reported the result equals the old
|
|
41
|
+
// `inputUncached`/`outputVisible` values exactly. The terminal-usage fallback
|
|
42
|
+
// is kept for a stream that delivered no usage event.
|
|
43
|
+
function sumDefinedLeaves(
|
|
44
|
+
...values: readonly (number | undefined)[]
|
|
45
|
+
): number | undefined {
|
|
46
|
+
let sum: number | undefined;
|
|
47
|
+
for (const value of values) {
|
|
48
|
+
if (value !== undefined) sum = (sum ?? 0) + value;
|
|
49
|
+
}
|
|
50
|
+
return sum;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// The reconciled message usage a poll terminal carries: the same leaves the
|
|
54
|
+
// stream's usage events report (opencode-client.ts StepUsage).
|
|
55
|
+
interface TerminalUsage {
|
|
56
|
+
readonly inputTokens?: number;
|
|
57
|
+
readonly outputTokens?: number;
|
|
58
|
+
readonly costUsd?: number;
|
|
59
|
+
readonly cacheReadTokens?: number;
|
|
60
|
+
readonly cacheWriteTokens?: number;
|
|
61
|
+
readonly reasoningTokens?: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The token leaves of a poll-only terminal, for a stream that delivered no
|
|
65
|
+
// usage event: without them a poll-settled attempt would report its cache use
|
|
66
|
+
// as absent and its input as the uncached count alone.
|
|
67
|
+
function terminalLeaves(
|
|
68
|
+
terminal: TerminalUsage | undefined,
|
|
69
|
+
): Partial<NormalizedTokens> {
|
|
70
|
+
if (terminal === undefined) return {};
|
|
71
|
+
return {
|
|
72
|
+
...(terminal.inputTokens !== undefined
|
|
73
|
+
? { inputUncached: terminal.inputTokens }
|
|
74
|
+
: {}),
|
|
75
|
+
...(terminal.cacheReadTokens !== undefined
|
|
76
|
+
? { inputCacheRead: terminal.cacheReadTokens }
|
|
77
|
+
: {}),
|
|
78
|
+
...(terminal.cacheWriteTokens !== undefined
|
|
79
|
+
? { inputCacheWrite: terminal.cacheWriteTokens }
|
|
80
|
+
: {}),
|
|
81
|
+
...(terminal.outputTokens !== undefined
|
|
82
|
+
? { outputVisible: terminal.outputTokens }
|
|
83
|
+
: {}),
|
|
84
|
+
...(terminal.reasoningTokens !== undefined
|
|
85
|
+
? { outputReasoning: terminal.reasoningTokens }
|
|
86
|
+
: {}),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function knownUsageSums(
|
|
91
|
+
streamed: Partial<NormalizedTokens> | undefined,
|
|
92
|
+
terminal: TerminalUsage | undefined,
|
|
93
|
+
): {
|
|
94
|
+
inputKnown: number | undefined;
|
|
95
|
+
outputKnown: number | undefined;
|
|
96
|
+
totalKnown: number | undefined;
|
|
97
|
+
} {
|
|
98
|
+
const fallback = terminalLeaves(terminal);
|
|
99
|
+
const inputKnown =
|
|
100
|
+
sumDefinedLeaves(
|
|
101
|
+
streamed?.inputUncached,
|
|
102
|
+
streamed?.inputCacheRead,
|
|
103
|
+
streamed?.inputCacheWrite,
|
|
104
|
+
) ??
|
|
105
|
+
sumDefinedLeaves(
|
|
106
|
+
fallback.inputUncached,
|
|
107
|
+
fallback.inputCacheRead,
|
|
108
|
+
fallback.inputCacheWrite,
|
|
109
|
+
);
|
|
110
|
+
const outputKnown =
|
|
111
|
+
sumDefinedLeaves(streamed?.outputVisible, streamed?.outputReasoning) ??
|
|
112
|
+
sumDefinedLeaves(fallback.outputVisible, fallback.outputReasoning);
|
|
113
|
+
const totalKnown =
|
|
114
|
+
inputKnown !== undefined || outputKnown !== undefined
|
|
115
|
+
? (inputKnown ?? 0) + (outputKnown ?? 0)
|
|
116
|
+
: undefined;
|
|
117
|
+
return { inputKnown, outputKnown, totalKnown };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// §4.2 line 191 hard content bounds: one delta ≤ 64 KiB, aggregate finalText
|
|
121
|
+
// ≤ 1 MiB, stderr tail ≤ 64 KiB. Exceeding a bound TERMINATES the attempt —
|
|
122
|
+
// content is never silently truncated and parsed.
|
|
123
|
+
const MAX_DELTA_BYTES = 64 * 1024;
|
|
124
|
+
const MAX_FINAL_TEXT_BYTES = 1024 * 1024;
|
|
125
|
+
const MAX_STDERR_TAIL_BYTES = 64 * 1024;
|
|
126
|
+
|
|
127
|
+
// §4.2 line 189: backpressure beyond "the transport's declared stall deadline"
|
|
128
|
+
// aborts the attempt as protocol_overflow. The spec fixes no number; 10 s is
|
|
129
|
+
// the declared production default (injectable for offline tests).
|
|
130
|
+
const DEFAULT_STALL_DEADLINE_MS = 10_000;
|
|
131
|
+
|
|
132
|
+
// The setup deadline covers launch, qualification, mcp.status and
|
|
133
|
+
// session.create, so it must outlast the layers it wraps or it fires first and
|
|
134
|
+
// turns a recoverable slow start into a failure. Launch can take the server's
|
|
135
|
+
// own 15 s startup timeout (opencode-server.ts), and qualification's worst case
|
|
136
|
+
// is 19.5 s: health 3 x 2 s + /doc 3 x 4 s + 250 ms and 500 ms backoff. That
|
|
137
|
+
// is 34.5 s before mcp.status and session.create. 45 s keeps headroom above it.
|
|
138
|
+
const DEFAULT_SETUP_DEADLINE_MS = 45_000;
|
|
139
|
+
|
|
140
|
+
// §5.2 line 272 (SDK row): session.abort() → provider-specific terminal
|
|
141
|
+
// confirmation up to 5,000 ms → local cleanup up to 1,000 ms; the harness
|
|
142
|
+
// deadline is 6,500 ms including margin and is declared via capabilities().
|
|
143
|
+
const SDK_ABORT_CONFIRM_MS = 5000;
|
|
144
|
+
const SDK_CLEANUP_MS = 1000;
|
|
145
|
+
|
|
146
|
+
// §9.2 non-secret provider label: this credential kind is opencode_chatgpt_
|
|
147
|
+
// oauth (ChatGPT), so "openai" is the correct HMAC input regardless of
|
|
148
|
+
// which model family a given step later routes to over the SDK — bucket
|
|
149
|
+
// identity is about the CREDENTIAL's rate-limit pool, not the model.
|
|
150
|
+
const BUCKET_IDENTITY_PROVIDER = "openai";
|
|
151
|
+
|
|
152
|
+
// D1-08 PR3 (§9.2): same optional-input shape as ClaudeCliCapabilitiesInput
|
|
153
|
+
// — omitted by every existing call site, so capabilities() stays
|
|
154
|
+
// byte-identical to pre-PR3 behavior until PR5a's harness wiring supplies a
|
|
155
|
+
// real credential's resolved scope.
|
|
156
|
+
export interface OpenCodeCapabilitiesInput {
|
|
157
|
+
readonly credentialFingerprint: string;
|
|
158
|
+
readonly bucketScope?: BucketScope;
|
|
159
|
+
readonly localKey: Uint8Array;
|
|
160
|
+
}
|
|
161
|
+
// The margin the §5.2 row folds in on top of confirm+cleanup. Declared as a
|
|
162
|
+
// term rather than a literal total because harness.ts:425 TRUSTS the number
|
|
163
|
+
// capabilities() reports as the real bound: a constant would let an instance
|
|
164
|
+
// configured with larger budgets promise less time than it needs, and the
|
|
165
|
+
// harness would call a still-in-budget cancellation unconfirmed.
|
|
166
|
+
const SDK_DEADLINE_MARGIN_MS = 500;
|
|
167
|
+
|
|
168
|
+
// §197 names stream/poll arbitration without fixing numbers: the poll cadence
|
|
169
|
+
// and the per-round timeout are transport-declared defaults. A poll round that
|
|
170
|
+
// times out is an observation failure and can never win the terminal slot.
|
|
171
|
+
const DEFAULT_POLL_INTERVAL_MS = 250;
|
|
172
|
+
const DEFAULT_POLL_ROUND_MS = 2000;
|
|
173
|
+
|
|
174
|
+
// #132: how many consecutive post-win windows may be extended by a stream that
|
|
175
|
+
// keeps delivering. Each cycle is one `cleanupMs`, so this bounds the hold at
|
|
176
|
+
// maxDrainCycles x cleanupMs of SUSTAINED delivery — a whole answer draining in
|
|
177
|
+
// microseconds costs one cycle and never approaches the budget. It exists so a
|
|
178
|
+
// provider that will not stop cannot hold the attempt open until the step
|
|
179
|
+
// watchdog fires: exhausting it is an explicit `truncated` outcome, which is a
|
|
180
|
+
// louder and more actionable end than a watchdog timeout over a won terminal.
|
|
181
|
+
const DEFAULT_MAX_DRAIN_CYCLES = 4;
|
|
182
|
+
|
|
183
|
+
// Useful progress is a monotonic deadline, independent of poll latency. The
|
|
184
|
+
// optional round cap remains a deterministic test/backward-compatibility seam;
|
|
185
|
+
// production does not use rounds as a substitute for elapsed time.
|
|
186
|
+
const DEFAULT_USEFUL_PROGRESS_MS = 150_000;
|
|
187
|
+
|
|
188
|
+
export interface OpenCodeClientSession {
|
|
189
|
+
readonly id: string;
|
|
190
|
+
// The tool allow map the client actually sent, resolved against the
|
|
191
|
+
// provider's enumerated surface. Optional because `OpenCodeClientLike` is an
|
|
192
|
+
// injectable contract and a client that cannot express a tool gate has
|
|
193
|
+
// nothing to report — a client that CAN must report it, so the enforcement
|
|
194
|
+
// is provable from the attempt's artifacts instead of assumed from source.
|
|
195
|
+
readonly toolMap?: Readonly<Record<string, boolean>>;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export interface OpenCodeCreateSessionInput {
|
|
199
|
+
readonly correlation?: { sessionId: string; attempt: number };
|
|
200
|
+
readonly signal?: AbortSignal;
|
|
201
|
+
readonly cwd: string;
|
|
202
|
+
readonly userPrompt: string;
|
|
203
|
+
readonly systemPromptPath: string;
|
|
204
|
+
readonly tools: readonly string[];
|
|
205
|
+
readonly mcpConfigPath?: string;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export type OpenCodeClientEvent =
|
|
209
|
+
| { readonly kind: "delta"; readonly text: string }
|
|
210
|
+
| {
|
|
211
|
+
readonly kind: "usage";
|
|
212
|
+
readonly id?: string;
|
|
213
|
+
readonly mode: "snapshot" | "delta";
|
|
214
|
+
readonly final?: boolean;
|
|
215
|
+
readonly inputTokens?: number;
|
|
216
|
+
readonly outputTokens?: number;
|
|
217
|
+
readonly costUsd?: number;
|
|
218
|
+
// OpenCode's disjoint-additive token leaves (see opencode-client.ts
|
|
219
|
+
// StepUsage). Optional: a route that reports only input/output omits them.
|
|
220
|
+
readonly cacheReadTokens?: number;
|
|
221
|
+
readonly cacheWriteTokens?: number;
|
|
222
|
+
readonly reasoningTokens?: number;
|
|
223
|
+
readonly incomplete?: boolean;
|
|
224
|
+
}
|
|
225
|
+
| {
|
|
226
|
+
readonly kind: "diagnostic";
|
|
227
|
+
readonly level: "info" | "warn" | "error";
|
|
228
|
+
readonly message: string;
|
|
229
|
+
}
|
|
230
|
+
| { readonly kind: "heartbeat" }
|
|
231
|
+
// #124: a reasoning delta the mapper DISCARDED. Deliberately carries no
|
|
232
|
+
// payload — not the text, not even its length. The text is not the answer
|
|
233
|
+
// and must not spend the answer's content budget; and nothing derived from
|
|
234
|
+
// it may reach `notes`, which is classifyFailure's witness (see the note
|
|
235
|
+
// this event ends up producing for what a bare number does there). What
|
|
236
|
+
// survives the boundary is the bare fact that the model thought, which is
|
|
237
|
+
// all the transport needs to tell a turn that reasoned and never answered
|
|
238
|
+
// apart from one that produced nothing at all.
|
|
239
|
+
| { readonly kind: "reasoning"; readonly progress?: boolean }
|
|
240
|
+
// A tool part's status actually CHANGED (a novel pending/running/
|
|
241
|
+
// completed/error transition the client observed at most once — see
|
|
242
|
+
// opencode-client.ts's `handlePartUpdated`). Deliberately carries no
|
|
243
|
+
// payload, same reasoning as the bare "reasoning" marker above: the tool's
|
|
244
|
+
// input/output is not the answer and must not spend any content budget.
|
|
245
|
+
// Distinct from "reasoning" on purpose — the SDK uses reasoning events for
|
|
246
|
+
// its own "reasoning parts were received and discarded" diagnostics, and
|
|
247
|
+
// conflating tool execution into that would corrupt them.
|
|
248
|
+
| { readonly kind: "activity" }
|
|
249
|
+
// #214 (merged with #228's toolActivityRank): a COMPLETED tool-call part,
|
|
250
|
+
// emitted alongside "activity" at most once per callID — see
|
|
251
|
+
// opencode-client.ts's `handlePartUpdated`, which gates this on the SAME
|
|
252
|
+
// stream-owned `toolActivityRank` forward-rank check "activity" uses, never
|
|
253
|
+
// on `toolStates` (which the poll readback also writes and can race ahead
|
|
254
|
+
// of the stream). Pending/running/error restatements are dropped —
|
|
255
|
+
// announcing Read is not looking, and an errored call is excluded on
|
|
256
|
+
// purpose: it produced no signal to reason from, and no test has asked for
|
|
257
|
+
// it to count. `tool` is the provider id (`read`, `grep`, …), never
|
|
258
|
+
// arguments or output: those are model-adjacent and must not reach `notes`.
|
|
259
|
+
// `callId` (pr-hero review F001/F002 on #214): the SAME identity
|
|
260
|
+
// `handlePartUpdated` tracks in `toolStates`/`toolActivityRank` — required
|
|
261
|
+
// so the transport can union this observation with the poll's by identity
|
|
262
|
+
// rather than combine two disjoint counts. Optional only because hand-
|
|
263
|
+
// written test doubles construct this event without a real client behind
|
|
264
|
+
// it; the transport falls back to a synthetic per-event id in that case so
|
|
265
|
+
// those fixtures keep counting one event as one invocation.
|
|
266
|
+
| { readonly kind: "tool"; readonly tool?: string; readonly callId?: string }
|
|
267
|
+
// #157: our own session's status named an account/usage limit (a `retry`
|
|
268
|
+
// status whose `action.reason` is one opencode-client.ts's
|
|
269
|
+
// providerLimitFromStatus recognises). Carries the provider's reason and
|
|
270
|
+
// message VERBATIM — nothing is summarized or reworded — because the
|
|
271
|
+
// classification witness has to be the provider's own fact, not this
|
|
272
|
+
// transport's paraphrase of it.
|
|
273
|
+
| {
|
|
274
|
+
readonly kind: "provider_limit";
|
|
275
|
+
readonly reason: string;
|
|
276
|
+
readonly message: string;
|
|
277
|
+
}
|
|
278
|
+
// #213: the bus event `session.error` (SDK EventSessionError). The model
|
|
279
|
+
// never ran — a 403 DataPolicyError arrives here with isRetryable false —
|
|
280
|
+
// and dropping it left an empty turn that the harness filed as
|
|
281
|
+
// format_violation. Carries the provider's name, status, retry flag, and
|
|
282
|
+
// message. responseBody stays off this event: it is not the witness, and
|
|
283
|
+
// it is where a provider pastes request echoes.
|
|
284
|
+
| {
|
|
285
|
+
readonly kind: "provider_refusal";
|
|
286
|
+
readonly name: string;
|
|
287
|
+
readonly statusCode?: number;
|
|
288
|
+
readonly retryable?: boolean;
|
|
289
|
+
readonly message: string;
|
|
290
|
+
}
|
|
291
|
+
| { readonly kind: "terminal"; readonly proof: ProviderTerminalProof };
|
|
292
|
+
|
|
293
|
+
export type OpenCodePollResult =
|
|
294
|
+
| { readonly kind: "pending" }
|
|
295
|
+
| {
|
|
296
|
+
readonly kind: "terminal";
|
|
297
|
+
readonly proof: ProviderTerminalProof;
|
|
298
|
+
readonly finalText?: string;
|
|
299
|
+
readonly usage?: TerminalUsage;
|
|
300
|
+
readonly usageIncomplete?: boolean;
|
|
301
|
+
// #214, reshaped by pr-hero review F001: the callIDs this observer has
|
|
302
|
+
// EVER seen reach "completed", read off opencode-client.ts's
|
|
303
|
+
// `OpenCodeTurnState.completedToolCallIds` — a set that only grows, so
|
|
304
|
+
// a LATER readback reporting the same callID as "error" (or anything
|
|
305
|
+
// else) can never make it vanish from this list. The previous shape
|
|
306
|
+
// (`toolInvocations: number`, recomputed fresh from `toolStates` on
|
|
307
|
+
// every poll) went DOWN exactly that way: `toolStates` stores the
|
|
308
|
+
// provider's raw last-known status and a later "error" for an
|
|
309
|
+
// earlier-"completed" call shrank the recount. Absent whenever this
|
|
310
|
+
// poll produced no terminal at all; present on EVERY terminal this
|
|
311
|
+
// poll reports, whether or not it goes on to win §197's slot — the
|
|
312
|
+
// transport, not this observer, decides that. A poll-won turn is a
|
|
313
|
+
// supported delivery path (`terminalFinalText` already mirrors it for
|
|
314
|
+
// the answer text): the stream's own "tool" events only fire for a
|
|
315
|
+
// completion the STREAM itself watched happen, so a hunter whose only
|
|
316
|
+
// observer of a completed tool call was this poll readback would
|
|
317
|
+
// otherwise be undercounted as zero and read as a hunt that never
|
|
318
|
+
// looked. Real callIDs, not a count, so the transport can union this
|
|
319
|
+
// with the stream's own observations by identity (F002) instead of
|
|
320
|
+
// combining two disjoint counts.
|
|
321
|
+
readonly completedToolCallIds?: readonly string[];
|
|
322
|
+
}
|
|
323
|
+
// The session itself failed, so no turn will ever produce a terminal. It is
|
|
324
|
+
// NOT a terminal — the transport issues no proof of its own — and it is not
|
|
325
|
+
// a failed observation either: it is a successful observation of a fact that
|
|
326
|
+
// ends the attempt. The distinction is load-bearing. A poll that THROWS is
|
|
327
|
+
// counted (`pollTimeouts += 1; continue`) and the loop runs on forever, so
|
|
328
|
+
// reporting this by throwing would have swapped one silent hang for another.
|
|
329
|
+
| { readonly kind: "failed"; readonly detail: string };
|
|
330
|
+
|
|
331
|
+
// Narrow injectable client shaped ONLY from what §197 (stream + poll
|
|
332
|
+
// arbitration) and §290 (abort without provider confirmation) require. No
|
|
333
|
+
// assumption about the real SDK's API is encoded here.
|
|
334
|
+
export interface OpenCodeClientLike {
|
|
335
|
+
takeEvidence?(
|
|
336
|
+
sessionId: string,
|
|
337
|
+
attempt: number,
|
|
338
|
+
): import("../execution/contracts").DiagnosticEvidence | undefined;
|
|
339
|
+
createSession(
|
|
340
|
+
input: OpenCodeCreateSessionInput,
|
|
341
|
+
): Promise<OpenCodeClientSession>;
|
|
342
|
+
streamEvents(
|
|
343
|
+
session: OpenCodeClientSession,
|
|
344
|
+
): AsyncIterable<OpenCodeClientEvent>;
|
|
345
|
+
pollStatus(
|
|
346
|
+
session: OpenCodeClientSession,
|
|
347
|
+
signal?: AbortSignal,
|
|
348
|
+
): Promise<OpenCodePollResult>;
|
|
349
|
+
abort(session: OpenCodeClientSession): Promise<void>;
|
|
350
|
+
close?(): Promise<void>;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Injectable clock so conformance tests fire every deadline by hand and never
|
|
354
|
+
// sleep a real one (§13 line 746).
|
|
355
|
+
export interface OpenCodeTransportClock {
|
|
356
|
+
nowMs?(): number;
|
|
357
|
+
schedule(ms: number, fn: () => void): () => void;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const systemClock: OpenCodeTransportClock = {
|
|
361
|
+
nowMs: () => performance.now(),
|
|
362
|
+
schedule(ms, fn) {
|
|
363
|
+
const timer = setTimeout(fn, ms);
|
|
364
|
+
return () => clearTimeout(timer);
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
export interface OpenCodeSdkTransportOptions {
|
|
369
|
+
readonly client: OpenCodeClientLike;
|
|
370
|
+
readonly stallDeadlineMs?: number;
|
|
371
|
+
readonly abortConfirmMs?: number;
|
|
372
|
+
readonly cleanupMs?: number;
|
|
373
|
+
readonly maxDeltaBytes?: number;
|
|
374
|
+
readonly maxFinalTextBytes?: number;
|
|
375
|
+
readonly pollIntervalMs?: number;
|
|
376
|
+
readonly pollRoundMs?: number;
|
|
377
|
+
readonly maxDrainCycles?: number;
|
|
378
|
+
// Optional legacy test tripwire; production uses usefulProgressMs.
|
|
379
|
+
readonly maxQuietRounds?: number;
|
|
380
|
+
readonly usefulProgressMs?: number;
|
|
381
|
+
readonly setupDeadlineMs?: number;
|
|
382
|
+
readonly clock?: OpenCodeTransportClock;
|
|
383
|
+
readonly nowIso?: () => string;
|
|
384
|
+
// 2026-09-02: how the ROUTE this transport serves bills, stamped onto every
|
|
385
|
+
// usage record it emits. Derived by the registry factory from the
|
|
386
|
+
// credential kind the authority resolved (`credentialKindBillsMetered`,
|
|
387
|
+
// runner-authority.ts) — the transport cannot derive it, holding no
|
|
388
|
+
// credential and, since #137's note, no route.
|
|
389
|
+
//
|
|
390
|
+
// Defaults to "subscription" rather than "unknown" so an unconfigured
|
|
391
|
+
// construction is byte-identical to what this file hardcoded before, and
|
|
392
|
+
// because the factory branch that omits the kind is the SAME branch that
|
|
393
|
+
// defaults the route to `openai/gpt-4o` — an OAuth, subscription-billed
|
|
394
|
+
// route. A default of "unknown" would make the two disagree.
|
|
395
|
+
//
|
|
396
|
+
// That "SAME branch" is a guarantee only since 2026-09-02, and it was
|
|
397
|
+
// written here before it was true: `FrozenRuntimeBinding.acquire()` used to
|
|
398
|
+
// forward the route without the kind, so a registry built without a
|
|
399
|
+
// construction-time `credentialKind` served a real metered route while this
|
|
400
|
+
// default stamped it "subscription". `acquire()` now forwards the pair, so
|
|
401
|
+
// through it — the only production caller that names a route — omitting the
|
|
402
|
+
// kind really does mean omitting the route, and this default only ever
|
|
403
|
+
// describes a caller holding no binding at all. `StepExecutionHarness`'s own
|
|
404
|
+
// registry branch still passes a route without a kind, but no composition in
|
|
405
|
+
// src/ reaches it: both harness constructions supply an explicit transport.
|
|
406
|
+
readonly billingMode?: UsageBillingMode;
|
|
407
|
+
readonly admissionIdentity?: {
|
|
408
|
+
readonly executable: string;
|
|
409
|
+
readonly provider: string;
|
|
410
|
+
};
|
|
411
|
+
readonly defaultRoute?: ResolvedModelRoute;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const MARKER_ABORT_UNCONFIRMED =
|
|
415
|
+
"[pr-hero] opencode sdk: abort requested but the provider supplied no terminal proof within the confirmation window; remote state unknown_may_continue";
|
|
416
|
+
const MARKER_STALL =
|
|
417
|
+
"[pr-hero] opencode sdk: event sink push stalled past the declared stall deadline";
|
|
418
|
+
const MARKER_BOUND_DELTA =
|
|
419
|
+
"[pr-hero] opencode sdk: delta exceeded the hard per-delta content bound";
|
|
420
|
+
const MARKER_BOUND_AGGREGATE =
|
|
421
|
+
"[pr-hero] opencode sdk: aggregate finalText exceeded the hard aggregate content bound";
|
|
422
|
+
const MARKER_USAGE_FLIP =
|
|
423
|
+
"[pr-hero] opencode sdk: usage aggregation mode changed after the first usage event fixed it";
|
|
424
|
+
|
|
425
|
+
const MARKER_CONFLICT =
|
|
426
|
+
"[pr-hero] opencode sdk: conflicting provider terminal observed after the compare-and-set slot was won";
|
|
427
|
+
// Already the literal prefix of the stderrTail this transport writes when
|
|
428
|
+
// createSession throws; naming it here makes it a classification witness too.
|
|
429
|
+
const MARKER_SESSION_CREATE = "[pr-hero] opencode sdk: session creation failed";
|
|
430
|
+
// Already the literal text the client puts on the error it hands the stream
|
|
431
|
+
// when session.prompt is refused (opencode-client.ts, via unwrap); naming it
|
|
432
|
+
// here makes it a classification witness too. The coupling is pinned by an
|
|
433
|
+
// end-to-end test rather than by this constant —
|
|
434
|
+
// test/conformance/opencode-resolved-error-arm.test.ts drives a refusal
|
|
435
|
+
// through the real client and asserts what comes out here.
|
|
436
|
+
const MARKER_PROMPT_REFUSED = "opencode session.prompt failed";
|
|
437
|
+
// #132, and #124's sibling in CAUSE rather than in fact: that one says the
|
|
438
|
+
// turn reasoned and never opened a text part, this one says it opened one and
|
|
439
|
+
// was cut off mid-delivery. Both map to `protocol_truncation` because a FRESH
|
|
440
|
+
// attempt is the only remedy that can work on either.
|
|
441
|
+
//
|
|
442
|
+
// Deliberately digit-free and worded clear of every classifier pattern: it
|
|
443
|
+
// shares the witness with the provider's own text, so a marker that reads like
|
|
444
|
+
// a rate limit or a socket error would decide the cause instead of reporting
|
|
445
|
+
// the fact (#126).
|
|
446
|
+
const MARKER_UNDELIVERED_CONTENT =
|
|
447
|
+
"[pr-hero] opencode sdk: the drain budget expired while the stream was still delivering; the answer is incomplete";
|
|
448
|
+
// #124. Distinct from an empty answer in general: this says the turn REASONED
|
|
449
|
+
// and never opened a text part, so there is no malformed output to reformat
|
|
450
|
+
// and the format-reminder budget would be spent on nothing — the same argument
|
|
451
|
+
// that made a turn which never started `runtime_unavailable` (#121, #123).
|
|
452
|
+
// The cause it maps to differs, though, and deliberately: the runtime WAS
|
|
453
|
+
// available and the model DID run, so the honest fact is that the answer
|
|
454
|
+
// channel delivered no content. See classifyFailure.
|
|
455
|
+
const MARKER_REASONING_ONLY =
|
|
456
|
+
"[pr-hero] opencode sdk: the turn completed with reasoning parts only and no answer text part";
|
|
457
|
+
// Martian `opencode` arm, 2026-09-10: the provider-silence tripwire below.
|
|
458
|
+
// Maps to `protocol_truncation` beside the undelivered-content marker: the
|
|
459
|
+
// channel went quiet mid-delivery (or before any delivery), and a FRESH
|
|
460
|
+
// attempt on the transient budget is the only remedy that can work.
|
|
461
|
+
//
|
|
462
|
+
// Deliberately digit-free per #126 (shares the witness with provider text).
|
|
463
|
+
const MARKER_SILENCE =
|
|
464
|
+
"[pr-hero] opencode sdk: the provider stream delivered no content event for the whole quiet-round budget; the answer is incomplete";
|
|
465
|
+
// #157: pr-157-8df2fca3-4's complete capture — OpenCode reported an
|
|
466
|
+
// account_rate_limit retry status (`5 hour usage limit reached...`) for our
|
|
467
|
+
// own session ~3.8s into the attempt, kept retrying internally, and never
|
|
468
|
+
// delivered another reasoning/text/usage event. The attempt sat quiet for
|
|
469
|
+
// the whole usefulProgressMs budget before the silence tripwire settled it
|
|
470
|
+
// $0/transient — the user saw "silence", never the account limit the
|
|
471
|
+
// provider had already named. A spent quota cannot be outrun by a fresh
|
|
472
|
+
// attempt, unlike silence or a transient stall, so this is fail-fast.
|
|
473
|
+
//
|
|
474
|
+
// Digit-free per #126 (the marker shares its witness with the provider's own
|
|
475
|
+
// text, appended verbatim by formatProviderLimitDetail below): a prefix that
|
|
476
|
+
// read like a rate limit or a socket error would let classifyFailure's
|
|
477
|
+
// generic patterns decide the cause instead of this fact.
|
|
478
|
+
const MARKER_PROVIDER_LIMIT =
|
|
479
|
+
"[pr-hero] opencode sdk: provider usage limit reached";
|
|
480
|
+
|
|
481
|
+
// Shared by both observers of this fact — opencode-client.ts's stream
|
|
482
|
+
// mapping (a `provider_limit` OpenCodeClientEvent) and its status poll (a
|
|
483
|
+
// `{kind:"failed"}` OpenCodePollResult) — so the exact classification witness
|
|
484
|
+
// is defined once rather than duplicated as a literal in two files.
|
|
485
|
+
export function formatProviderLimitDetail(
|
|
486
|
+
reason: string,
|
|
487
|
+
message: string,
|
|
488
|
+
): string {
|
|
489
|
+
return `${MARKER_PROVIDER_LIMIT} (${reason}): ${message}`;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// #213. Digit-free prefix, same rule as MARKER_PROVIDER_LIMIT: the provider's
|
|
493
|
+
// own message is appended after it, and a prefix that read like a rate limit
|
|
494
|
+
// or a socket error would let the generic patterns decide the cause.
|
|
495
|
+
const MARKER_PROVIDER_REFUSAL =
|
|
496
|
+
"[pr-hero] opencode sdk: provider refused the turn";
|
|
497
|
+
|
|
498
|
+
// The message is the operator's only copy of the opt-in sentence. URLs stay
|
|
499
|
+
// (that sentence IS a URL). Credentials do not: redactDiagnostic runs before
|
|
500
|
+
// the line is a witness. Capped so a provider that pastes a body into
|
|
501
|
+
// `data.message` cannot fill the stderr tail by itself.
|
|
502
|
+
const PROVIDER_REFUSAL_MESSAGE_MAX = 500;
|
|
503
|
+
|
|
504
|
+
export function formatProviderRefusalDetail(input: {
|
|
505
|
+
readonly name: string;
|
|
506
|
+
readonly statusCode?: number;
|
|
507
|
+
readonly retryable?: boolean;
|
|
508
|
+
readonly message: string;
|
|
509
|
+
}): string {
|
|
510
|
+
const status =
|
|
511
|
+
input.statusCode === undefined ? "unknown" : String(input.statusCode);
|
|
512
|
+
// The flag is the first token after the marker, before any provider-owned
|
|
513
|
+
// field. classifyFailure reads only that token. `name` and `message` are
|
|
514
|
+
// the provider's, and a message that happens to say "isRetryable: true"
|
|
515
|
+
// must not flip a terminal refusal into a retry.
|
|
516
|
+
const retryable = input.retryable === true ? "yes" : "no";
|
|
517
|
+
const message = redactDiagnostic(input.message).slice(
|
|
518
|
+
0,
|
|
519
|
+
PROVIDER_REFUSAL_MESSAGE_MAX,
|
|
520
|
+
);
|
|
521
|
+
return `${MARKER_PROVIDER_REFUSAL} retryable=${retryable} (${input.name} status=${status}): ${message}`;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// The flag occupies a fixed slot immediately after the marker. Reading
|
|
525
|
+
// anywhere else in the witness would let the provider's own message decide
|
|
526
|
+
// the disposition (#213 review).
|
|
527
|
+
function providerRefusalRetries(witness: string): boolean | undefined {
|
|
528
|
+
const at = witness.indexOf(MARKER_PROVIDER_REFUSAL);
|
|
529
|
+
if (at < 0) return undefined;
|
|
530
|
+
const rest = witness.slice(at + MARKER_PROVIDER_REFUSAL.length);
|
|
531
|
+
if (rest.startsWith(" retryable=yes")) return true;
|
|
532
|
+
if (rest.startsWith(" retryable=no")) return false;
|
|
533
|
+
return undefined;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// The provider's HTTP status, read from the fixed `status=` slot inside the
|
|
537
|
+
// `(<name> status=<code>)` group that follows the retryable flag. The name is
|
|
538
|
+
// the provider's own text, so the match is anchored right after the flag and
|
|
539
|
+
// stops at the group's close paren: a message that says "status=404" cannot
|
|
540
|
+
// reach this slot. "unknown" (no status was reported) returns undefined.
|
|
541
|
+
function providerRefusalStatus(witness: string): string | undefined {
|
|
542
|
+
const at = witness.indexOf(MARKER_PROVIDER_REFUSAL);
|
|
543
|
+
if (at < 0) return undefined;
|
|
544
|
+
const rest = witness.slice(at + MARKER_PROVIDER_REFUSAL.length);
|
|
545
|
+
const slot = rest.match(
|
|
546
|
+
/^ retryable=(?:yes|no) \([^()]* status=(\d+|unknown)\): /,
|
|
547
|
+
);
|
|
548
|
+
return slot?.[1] === "unknown" ? undefined : slot?.[1];
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// #157 (pr-157-8df2fca3-6): a hunter's tool call for a path OUTSIDE the
|
|
552
|
+
// reviewed worktree tripped `permission.asked` for `external_directory`
|
|
553
|
+
// twice in one run, and pr-hero never answered OpenCode's permission prompt
|
|
554
|
+
// — the tool call sat blocked until the silence tripwire killed the attempt
|
|
555
|
+
// 150s later at $0. opencode-client.ts rejects any own-session permission
|
|
556
|
+
// prompt as defense in depth beside the server-side `deny` config
|
|
557
|
+
// (opencode-server.ts); THIS marker fires only when that reject itself could
|
|
558
|
+
// not be delivered — the one case the config cannot cover, since it needs a
|
|
559
|
+
// working SDK call to answer the prompt at all. No retry can fix a control
|
|
560
|
+
// that failed to execute, so this is terminal, not `protocol_truncation`.
|
|
561
|
+
const MARKER_PERMISSION_REJECT_FAILED =
|
|
562
|
+
"[pr-hero] opencode sdk: failed to reject an OpenCode permission request";
|
|
563
|
+
|
|
564
|
+
export function formatPermissionRejectFailureDetail(
|
|
565
|
+
permission: string,
|
|
566
|
+
patterns: readonly string[],
|
|
567
|
+
errorMessage: string,
|
|
568
|
+
): string {
|
|
569
|
+
return `${MARKER_PERMISSION_REJECT_FAILED} (${permission} ${JSON.stringify(patterns)}): ${errorMessage}`;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
type SettleReason =
|
|
573
|
+
// #132: `drained` records whether the stream had gone QUIET when the
|
|
574
|
+
// post-win window closed. False means the drain budget ran out with content
|
|
575
|
+
// still arriving — a provider terminal over an unfinished delivery, which is
|
|
576
|
+
// the one shape of this reason that must never report success.
|
|
577
|
+
| { readonly kind: "provider_terminal"; readonly drained: boolean }
|
|
578
|
+
| { readonly kind: "conflict"; readonly detail: string }
|
|
579
|
+
| { readonly kind: "usage_flip"; readonly detail: string }
|
|
580
|
+
| { readonly kind: "bound"; readonly target: "delta" | "aggregate" }
|
|
581
|
+
| { readonly kind: "stall" }
|
|
582
|
+
| { readonly kind: "silence" }
|
|
583
|
+
| { readonly kind: "stream_error"; readonly detail: string }
|
|
584
|
+
| { readonly kind: "session_failed"; readonly detail: string }
|
|
585
|
+
| { readonly kind: "abort_confirmed" }
|
|
586
|
+
| { readonly kind: "abort_unconfirmed" };
|
|
587
|
+
|
|
588
|
+
type PushResult = "accepted" | "closed" | "stalled";
|
|
589
|
+
|
|
590
|
+
// Sentinel for the stream watcher's race against settlement.
|
|
591
|
+
const STREAM_SETTLED = "stream_settled" as const;
|
|
592
|
+
|
|
593
|
+
function utf8Bytes(text: string): number {
|
|
594
|
+
return new TextEncoder().encode(text).length;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// The tail bound is declared in BYTES, so it is enforced in bytes. String
|
|
598
|
+
// .slice counts UTF-16 code units, which lets multi-byte provider text run
|
|
599
|
+
// past the bound the transport claims.
|
|
600
|
+
//
|
|
601
|
+
// Keeping the last maxBytes bytes can tear a multi-byte sequence at the head,
|
|
602
|
+
// and decoding that orphan does not merely lose a character — it GROWS the
|
|
603
|
+
// result: every stray continuation byte becomes a U+FFFD, which is three
|
|
604
|
+
// bytes in UTF-8, so a byte-exact cut can come back over the bound. The head
|
|
605
|
+
// is therefore advanced past any continuation bytes (0b10xxxxxx) to land on a
|
|
606
|
+
// real character boundary, which can only shorten the tail.
|
|
607
|
+
function boundTailBytes(text: string, maxBytes: number): string {
|
|
608
|
+
const bytes = new TextEncoder().encode(text);
|
|
609
|
+
if (bytes.length <= maxBytes) return text;
|
|
610
|
+
let start = bytes.length - maxBytes;
|
|
611
|
+
while (start < bytes.length && (bytes[start] & 0b1100_0000) === 0b1000_0000) {
|
|
612
|
+
start += 1;
|
|
613
|
+
}
|
|
614
|
+
return new TextDecoder().decode(bytes.slice(start));
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function errorMessage(error: unknown): string {
|
|
618
|
+
return error instanceof Error ? error.message : String(error);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// Session creation failing means no attempt ever reached the provider —
|
|
622
|
+
// genuine zero cost, not "unavailable" (which would misfile a $0 refusal as
|
|
623
|
+
// an unresolved spend now that PR5b's spend ledger does read completeness).
|
|
624
|
+
//
|
|
625
|
+
// 2026-09-02: it carries the ROUTE's billing mode like every other usage
|
|
626
|
+
// record here, metered included. That is safe precisely because `tokens` is
|
|
627
|
+
// empty — `settlementFromUsage`'s metered-zero rule gates on output tokens,
|
|
628
|
+
// so this stays settleable at 0 while a metered attempt that actually
|
|
629
|
+
// produced output does not.
|
|
630
|
+
function noSessionUsage(
|
|
631
|
+
wallMs: number,
|
|
632
|
+
billingMode: UsageBillingMode,
|
|
633
|
+
): NormalizedUsage {
|
|
634
|
+
return {
|
|
635
|
+
wallMs,
|
|
636
|
+
tokens: {},
|
|
637
|
+
completeness: "complete",
|
|
638
|
+
billingMode,
|
|
639
|
+
costSource: "provider",
|
|
640
|
+
cashCostUsd: 0,
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// A prompt refusal that arrived before any provider event: the failure
|
|
645
|
+
// detail IS the refusal (session.prompt rejected at call time —
|
|
646
|
+
// opencode-client.ts: a refused prompt creates no message and therefore no
|
|
647
|
+
// events), and not a single delta, reasoning part, tool invocation, or usage
|
|
648
|
+
// event was ever observed. The model provably never started, so the
|
|
649
|
+
// noSessionUsage assertion holds exactly as it does for session-creation
|
|
650
|
+
// failure. Anything else — a refusal after partial delivery, a non-refusal
|
|
651
|
+
// stream death, a poll-observed failure with no refusal text — keeps the
|
|
652
|
+
// fail-closed "unavailable".
|
|
653
|
+
function promptRefusedBeforeStart(
|
|
654
|
+
reason: SettleReason,
|
|
655
|
+
finalPartsLength: number,
|
|
656
|
+
sawReasoning: boolean,
|
|
657
|
+
sawContentEvent: boolean,
|
|
658
|
+
): boolean {
|
|
659
|
+
if (reason.kind !== "stream_error" && reason.kind !== "session_failed") {
|
|
660
|
+
return false;
|
|
661
|
+
}
|
|
662
|
+
if (!reason.detail.includes(MARKER_PROMPT_REFUSED)) {
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
665
|
+
if (finalPartsLength !== 0 || sawReasoning || sawContentEvent) {
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
// A dispatched request may fail after provider work began. Text (including
|
|
669
|
+
// incidental HTTP-looking numbers) is not authoritative nonexecution proof.
|
|
670
|
+
return false;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Matching means the poll observes the SAME terminal identity the slot already
|
|
674
|
+
// holds: identical eventId AND providerStatus. Anything else is a conflicting
|
|
675
|
+
// terminal, which §197 says makes the outcome malformed rather than being
|
|
676
|
+
// selected by arrival order.
|
|
677
|
+
function sameTerminal(
|
|
678
|
+
a: ProviderTerminalProof,
|
|
679
|
+
b: ProviderTerminalProof,
|
|
680
|
+
): boolean {
|
|
681
|
+
return a.eventId === b.eventId && a.providerStatus === b.providerStatus;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// §197: only a VALID provider terminal proof may win the slot.
|
|
685
|
+
function isValidProof(proof: ProviderTerminalProof): boolean {
|
|
686
|
+
return (
|
|
687
|
+
proof.eventId.length > 0 &&
|
|
688
|
+
proof.providerStatus.length > 0 &&
|
|
689
|
+
proof.providerObservedAt.length > 0
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
export class OpenCodeSdkTransport implements ProviderTransport {
|
|
694
|
+
readonly backend = "opencode" as const;
|
|
695
|
+
readonly admissionIdentity: {
|
|
696
|
+
readonly executable: string;
|
|
697
|
+
readonly provider: string;
|
|
698
|
+
};
|
|
699
|
+
readonly cancellationSemantics = "provider-proof" as const;
|
|
700
|
+
// #150: this transport never reads `TransportRequest.isolation` — its
|
|
701
|
+
// server owns ONE credential projection for the server's whole lifetime
|
|
702
|
+
// (#149, brokered by `OpenCodeAuthBroker`/`OpenCodeFreeBroker` before the
|
|
703
|
+
// server ever launches), not a fresh one per step. Declaring
|
|
704
|
+
// "server-lifetime" tells `StepExecutionHarness.run` to skip the per-step
|
|
705
|
+
// broker call for every attempt this transport executes — no auth file
|
|
706
|
+
// materialized and destroyed for nothing, no false
|
|
707
|
+
// `missing_subscription_record` degrade for a projection that was never
|
|
708
|
+
// attempted.
|
|
709
|
+
readonly credentialProjection = "server-lifetime" as const;
|
|
710
|
+
readonly defaultRoute?: ResolvedModelRoute;
|
|
711
|
+
private readonly client: OpenCodeClientLike;
|
|
712
|
+
private readonly stallDeadlineMs: number;
|
|
713
|
+
private readonly abortConfirmMs: number;
|
|
714
|
+
private readonly cleanupMs: number;
|
|
715
|
+
private readonly maxDeltaBytes: number;
|
|
716
|
+
private readonly maxFinalTextBytes: number;
|
|
717
|
+
private readonly pollIntervalMs: number;
|
|
718
|
+
private readonly pollRoundMs: number;
|
|
719
|
+
private readonly maxDrainCycles: number;
|
|
720
|
+
private readonly maxQuietRounds: number;
|
|
721
|
+
private readonly usefulProgressMs: number;
|
|
722
|
+
private readonly setupDeadlineMs: number;
|
|
723
|
+
private readonly clock: OpenCodeTransportClock;
|
|
724
|
+
private readonly nowIso: () => string;
|
|
725
|
+
// Public and readonly on purpose. #149's forwarding "guarantee" shipped
|
|
726
|
+
// dead twice because nothing outside the registry could observe it, and a
|
|
727
|
+
// billing mode derived from a credential kind inside a factory has exactly
|
|
728
|
+
// that shape. Reading it is how `test/route-admission.test.ts` proves the
|
|
729
|
+
// factory wired the kind through, without driving a whole attempt.
|
|
730
|
+
readonly usageBillingMode: UsageBillingMode;
|
|
731
|
+
get billingMode(): UsageBillingMode {
|
|
732
|
+
return this.usageBillingMode;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
constructor(options: OpenCodeSdkTransportOptions) {
|
|
736
|
+
this.admissionIdentity = options.admissionIdentity ?? {
|
|
737
|
+
executable: "opencode",
|
|
738
|
+
provider: "opencode",
|
|
739
|
+
};
|
|
740
|
+
this.cancellationSemantics = "provider-proof";
|
|
741
|
+
this.defaultRoute = options.defaultRoute;
|
|
742
|
+
this.client = options.client;
|
|
743
|
+
this.stallDeadlineMs = options.stallDeadlineMs ?? DEFAULT_STALL_DEADLINE_MS;
|
|
744
|
+
this.abortConfirmMs = options.abortConfirmMs ?? SDK_ABORT_CONFIRM_MS;
|
|
745
|
+
this.cleanupMs = options.cleanupMs ?? SDK_CLEANUP_MS;
|
|
746
|
+
this.maxDeltaBytes = options.maxDeltaBytes ?? MAX_DELTA_BYTES;
|
|
747
|
+
this.maxFinalTextBytes = options.maxFinalTextBytes ?? MAX_FINAL_TEXT_BYTES;
|
|
748
|
+
this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
749
|
+
this.pollRoundMs = options.pollRoundMs ?? DEFAULT_POLL_ROUND_MS;
|
|
750
|
+
this.maxDrainCycles = options.maxDrainCycles ?? DEFAULT_MAX_DRAIN_CYCLES;
|
|
751
|
+
this.maxQuietRounds = options.maxQuietRounds ?? Number.POSITIVE_INFINITY;
|
|
752
|
+
this.clock = options.clock ?? systemClock;
|
|
753
|
+
this.usefulProgressMs =
|
|
754
|
+
options.usefulProgressMs ?? DEFAULT_USEFUL_PROGRESS_MS;
|
|
755
|
+
this.setupDeadlineMs = options.setupDeadlineMs ?? DEFAULT_SETUP_DEADLINE_MS;
|
|
756
|
+
this.nowIso = options.nowIso ?? (() => new Date().toISOString());
|
|
757
|
+
this.usageBillingMode = options.billingMode ?? "subscription";
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// §11/D1-09 honesty: every unimplemented feature is claimed false with a
|
|
761
|
+
// non-blocking issue, never assumed green — hence status "degraded", not
|
|
762
|
+
// "ready". The real adapter, credential route, and pricing table are D1-11.
|
|
763
|
+
async capabilities(
|
|
764
|
+
input?: OpenCodeCapabilitiesInput,
|
|
765
|
+
): Promise<ProviderCapabilityReport> {
|
|
766
|
+
return {
|
|
767
|
+
backend: "opencode",
|
|
768
|
+
status: "degraded",
|
|
769
|
+
auth: {
|
|
770
|
+
kind: "opencode_chatgpt_oauth",
|
|
771
|
+
projectionReady: true,
|
|
772
|
+
probe: "passed",
|
|
773
|
+
},
|
|
774
|
+
isolation: {
|
|
775
|
+
syntheticHome: true,
|
|
776
|
+
workspaceReadBroker: true,
|
|
777
|
+
codegraphPolicy: false,
|
|
778
|
+
},
|
|
779
|
+
protocol: {
|
|
780
|
+
terminalProof: true,
|
|
781
|
+
boundedEvents: true,
|
|
782
|
+
usageMode: "none",
|
|
783
|
+
},
|
|
784
|
+
cancellation: {
|
|
785
|
+
deadlineMs:
|
|
786
|
+
this.abortConfirmMs + this.cleanupMs + SDK_DEADLINE_MARGIN_MS,
|
|
787
|
+
conformance: "passed",
|
|
788
|
+
},
|
|
789
|
+
billing: {
|
|
790
|
+
mode: "subscription",
|
|
791
|
+
// 2026-09-02: `true`, because this transport reports PROVIDER COST.
|
|
792
|
+
//
|
|
793
|
+
// The design's metered rule (§8, docs/multi-runtime-model-diversity-
|
|
794
|
+
// design.md line 461) is a disjunction and its order is the point:
|
|
795
|
+
// "Metered routes require provider cost or a versioned rate-table
|
|
796
|
+
// calculation." Provider cost is named FIRST — it is the primary
|
|
797
|
+
// path; the rate table is the fallback for a transport that reports
|
|
798
|
+
// nothing. `tokenPricingAvailable` in production-runtime.ts has read
|
|
799
|
+
// both disjuncts since #137.
|
|
800
|
+
//
|
|
801
|
+
// This transport satisfies the first one. The OpenCode SDK's
|
|
802
|
+
// `AssistantMessage` carries a NON-OPTIONAL `cost: number` (and so
|
|
803
|
+
// does `StepFinishPart`); `opencode-client.ts` reads it off every
|
|
804
|
+
// assistant message, this file accumulates it across the turn, and
|
|
805
|
+
// the outcome's usage carries it as `cashCostUsd` with
|
|
806
|
+
// `costSource: "provider"`. That is a provider-reported cost for
|
|
807
|
+
// whatever model the route named, with no table involved — which is
|
|
808
|
+
// why it holds for all of models.dev, not the two providers we bundle
|
|
809
|
+
// a table for, and why it does not expire.
|
|
810
|
+
//
|
|
811
|
+
// What this REPLACES, because the old reasoning was not wrong so much
|
|
812
|
+
// as aimed at the wrong disjunct: it argued that no model id is in
|
|
813
|
+
// scope here, that the factory hands this transport only `{ client }`,
|
|
814
|
+
// and that an Anthropic catalogue would not cover `openai/gpt-4o`
|
|
815
|
+
// anyway. Every clause of that is true OF THE RATE TABLE, which this
|
|
816
|
+
// transport genuinely cannot consult — and none of it bears on
|
|
817
|
+
// provider cost, which needs no model id because the provider prices
|
|
818
|
+
// its own call. Applying a table's limitation to the cost path left
|
|
819
|
+
// the design's primary source unconnected, so a metered route on any
|
|
820
|
+
// model outside the two bundled catalogues was refused as unpriceable
|
|
821
|
+
// while the provider was reporting its price on every message.
|
|
822
|
+
//
|
|
823
|
+
// #197: the claim is no longer scoped to this transport. The
|
|
824
|
+
// claude-code CLI reports `total_cost_usd`, so its transport and its
|
|
825
|
+
// backend-wide producer now answer `true` for the same reason this
|
|
826
|
+
// one does. The remaining `false` is transport-registry.ts's
|
|
827
|
+
// synthetic report for a backend whose transport could not be
|
|
828
|
+
// CONSTRUCTED — no transport, so no claim.
|
|
829
|
+
pricingReady: true,
|
|
830
|
+
},
|
|
831
|
+
...(input !== undefined
|
|
832
|
+
? {
|
|
833
|
+
rateLimitBucketId: deriveBucketId(
|
|
834
|
+
{
|
|
835
|
+
provider: BUCKET_IDENTITY_PROVIDER,
|
|
836
|
+
credentialFingerprint: input.credentialFingerprint,
|
|
837
|
+
scope: input.bucketScope,
|
|
838
|
+
},
|
|
839
|
+
input.localKey,
|
|
840
|
+
),
|
|
841
|
+
}
|
|
842
|
+
: {}),
|
|
843
|
+
issues: [
|
|
844
|
+
{
|
|
845
|
+
code: "codegraph_policy_unenforced",
|
|
846
|
+
message:
|
|
847
|
+
"no dedicated codegraph sensitive-file policy is enforced for this backend yet",
|
|
848
|
+
blocking: false,
|
|
849
|
+
},
|
|
850
|
+
{
|
|
851
|
+
code: "usage_mode_client_reported",
|
|
852
|
+
message:
|
|
853
|
+
"usage aggregation mode (§4.2 line 195) is fixed at runtime by the first client usage event, so no static snapshot/delta claim can be defended; usageMode is 'none'",
|
|
854
|
+
blocking: false,
|
|
855
|
+
},
|
|
856
|
+
{
|
|
857
|
+
// NOTIONAL cost, a different fact from the cash cost above: what a
|
|
858
|
+
// subscription attempt WOULD have cost metered. No route is in
|
|
859
|
+
// scope here to name a model, and since #197 there is no bundled
|
|
860
|
+
// table to look one up in either — a subscription attempt's
|
|
861
|
+
// notional figure now comes from whatever the transport reports for
|
|
862
|
+
// the attempt, not from this report.
|
|
863
|
+
//
|
|
864
|
+
// #197 removed this list's OTHER `pricing_table_missing` entry,
|
|
865
|
+
// which said no bundled table could be consulted from here: both
|
|
866
|
+
// halves of it died with the tables, and a "missing table" issue
|
|
867
|
+
// beside `pricingReady: true` read as a contradiction.
|
|
868
|
+
code: "pricing_table_missing",
|
|
869
|
+
message:
|
|
870
|
+
"no route is in scope here, so notional cost cannot be derived for this backend's models; subscription cash cost stays 0",
|
|
871
|
+
blocking: false,
|
|
872
|
+
},
|
|
873
|
+
],
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
async execute(
|
|
878
|
+
request: TransportRequest,
|
|
879
|
+
context: { readonly signal: AbortSignal; readonly events: AsyncEventSink },
|
|
880
|
+
): Promise<TransportOutcome> {
|
|
881
|
+
const outcome = await this.executeAttempt(request, context);
|
|
882
|
+
try {
|
|
883
|
+
const diagnosticEvidence = this.client.takeEvidence?.(
|
|
884
|
+
request.sessionId,
|
|
885
|
+
request.attempt,
|
|
886
|
+
);
|
|
887
|
+
return diagnosticEvidence ? { ...outcome, diagnosticEvidence } : outcome;
|
|
888
|
+
} catch {
|
|
889
|
+
return outcome;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
private async executeAttempt(
|
|
894
|
+
request: TransportRequest,
|
|
895
|
+
context: { readonly signal: AbortSignal; readonly events: AsyncEventSink },
|
|
896
|
+
): Promise<TransportOutcome> {
|
|
897
|
+
// `notes` becomes stderrTail, which is the classification WITNESS: the
|
|
898
|
+
// markers this transport stamps, plus the provider's own words verbatim.
|
|
899
|
+
// Nothing else belongs in it.
|
|
900
|
+
const notes: string[] = [];
|
|
901
|
+
// #126: our own observation tallies. Same attempt log, different channel,
|
|
902
|
+
// and NO classifier reads this one — see TransportOutcome.diagnosticsTail
|
|
903
|
+
// for the measured collisions that made the separation necessary.
|
|
904
|
+
const diagnostics: string[] = [];
|
|
905
|
+
const startedWall = Date.now();
|
|
906
|
+
let seq = 0;
|
|
907
|
+
const nextSeq = () => {
|
|
908
|
+
const value = seq;
|
|
909
|
+
seq += 1;
|
|
910
|
+
return value;
|
|
911
|
+
};
|
|
912
|
+
const base = (): ProviderEventBase => ({
|
|
913
|
+
sessionId: request.sessionId,
|
|
914
|
+
attempt: request.attempt,
|
|
915
|
+
seq: nextSeq(),
|
|
916
|
+
observedAt: this.nowIso(),
|
|
917
|
+
});
|
|
918
|
+
|
|
919
|
+
let settled = false;
|
|
920
|
+
let resolveDone!: (reason: SettleReason) => void;
|
|
921
|
+
const done = new Promise<SettleReason>((resolve) => {
|
|
922
|
+
resolveDone = resolve;
|
|
923
|
+
});
|
|
924
|
+
const settle = (reason: SettleReason): void => {
|
|
925
|
+
if (settled) return;
|
|
926
|
+
settled = true;
|
|
927
|
+
resolveDone(reason);
|
|
928
|
+
};
|
|
929
|
+
|
|
930
|
+
const cancellers = new Set<() => void>();
|
|
931
|
+
const scheduleTracked = (ms: number, fn: () => void): void => {
|
|
932
|
+
const cancel = this.clock.schedule(ms, () => {
|
|
933
|
+
cancellers.delete(cancel);
|
|
934
|
+
fn();
|
|
935
|
+
});
|
|
936
|
+
cancellers.add(cancel);
|
|
937
|
+
};
|
|
938
|
+
const delay = (ms: number): Promise<void> =>
|
|
939
|
+
new Promise<void>((resolve) => {
|
|
940
|
+
scheduleTracked(ms, resolve);
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
// §4.2 line 188: producers await every push — no fire-and-forget. Each
|
|
944
|
+
// push races the declared stall deadline; losing the race is the
|
|
945
|
+
// §4.2 line 189 protocol_overflow abort.
|
|
946
|
+
const pushGuarded = async (event: ProviderEvent): Promise<PushResult> => {
|
|
947
|
+
let cancelStall: (() => void) | undefined;
|
|
948
|
+
try {
|
|
949
|
+
const stalled = new Promise<"stalled">((resolve) => {
|
|
950
|
+
cancelStall = this.clock.schedule(this.stallDeadlineMs, () =>
|
|
951
|
+
resolve("stalled"),
|
|
952
|
+
);
|
|
953
|
+
});
|
|
954
|
+
// A sink that throws (or rejects after the race decided) is treated as
|
|
955
|
+
// closed: stop feeding it rather than crash a paid attempt.
|
|
956
|
+
const pushed = context.events
|
|
957
|
+
.push(event)
|
|
958
|
+
.catch(() => "closed" as const);
|
|
959
|
+
return await Promise.race([pushed, stalled]);
|
|
960
|
+
} finally {
|
|
961
|
+
cancelStall?.();
|
|
962
|
+
}
|
|
963
|
+
};
|
|
964
|
+
|
|
965
|
+
// ---- #132 post-win drain window ---------------------------------------
|
|
966
|
+
// `deltaSinceArm` is the whole delivery signal: set when a delta is picked
|
|
967
|
+
// up by the stream watcher and cleared every time the window re-arms, so a
|
|
968
|
+
// window that closes with it false saw a stream that said nothing for a
|
|
969
|
+
// full cleanup budget. In real time that is decisive — the client hands
|
|
970
|
+
// events over through an in-process queue, so a buffered delta reaches the
|
|
971
|
+
// watcher within a microtask, never a timer.
|
|
972
|
+
let deltaSinceArm = false;
|
|
973
|
+
let drainCyclesLeft = 0;
|
|
974
|
+
const armDrainWindow = (): void => {
|
|
975
|
+
deltaSinceArm = false;
|
|
976
|
+
scheduleTracked(this.cleanupMs, () => {
|
|
977
|
+
if (settled) return;
|
|
978
|
+
if (!deltaSinceArm) {
|
|
979
|
+
settle({ kind: "provider_terminal", drained: true });
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
if (drainCyclesLeft <= 0) {
|
|
983
|
+
settle({ kind: "provider_terminal", drained: false });
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
drainCyclesLeft -= 1;
|
|
987
|
+
armDrainWindow();
|
|
988
|
+
});
|
|
989
|
+
};
|
|
990
|
+
|
|
991
|
+
// ---- provider-silence tripwire (Martian `opencode` arm, 2026-09-10) ----
|
|
992
|
+
// Counts consecutive poll rounds with no content event; heartbeats do not
|
|
993
|
+
// reset — a keepalive-only session is the hung shape. Tripping settles
|
|
994
|
+
// `silence` (fresh transient attempt), capping a hung provider well under
|
|
995
|
+
// the 30-min harness watchdog. A timed-out round counts: an unobservable
|
|
996
|
+
// server beside a silent stream is the same hung shape, and the remedy
|
|
997
|
+
// (bounded retry) is the same.
|
|
998
|
+
let quietRounds = 0;
|
|
999
|
+
let contentSinceRound = false;
|
|
1000
|
+
const nowMs = () => this.clock.nowMs?.() ?? performance.now();
|
|
1001
|
+
let lastUsefulProgressWall = nowMs();
|
|
1002
|
+
const noteContentEvent = (): void => {
|
|
1003
|
+
contentSinceRound = true;
|
|
1004
|
+
lastUsefulProgressWall = nowMs();
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
// ---- §197 terminal compare-and-set slot -------------------------------
|
|
1008
|
+
let slotProof: ProviderTerminalProof | undefined;
|
|
1009
|
+
let pollConfirmations = 0;
|
|
1010
|
+
let invalidProofs = 0;
|
|
1011
|
+
let terminalFinalText: string | undefined;
|
|
1012
|
+
let terminalUsage: TerminalUsage | undefined;
|
|
1013
|
+
let terminalUsageIncomplete = false;
|
|
1014
|
+
|
|
1015
|
+
const onProviderTerminalCandidate = (
|
|
1016
|
+
proof: ProviderTerminalProof,
|
|
1017
|
+
source: "stream" | "poll",
|
|
1018
|
+
finalText?: string,
|
|
1019
|
+
usage?: TerminalUsage,
|
|
1020
|
+
incompleteUsage?: boolean,
|
|
1021
|
+
polledCompletedCallIds?: readonly string[],
|
|
1022
|
+
): void => {
|
|
1023
|
+
if (settled) return;
|
|
1024
|
+
if (!isValidProof(proof)) {
|
|
1025
|
+
invalidProofs += 1;
|
|
1026
|
+
diagnostics.push(
|
|
1027
|
+
`[pr-hero] opencode sdk: ignored invalid ${source} terminal proof (missing identity fields); it could not win the slot`,
|
|
1028
|
+
);
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
if (finalText !== undefined) {
|
|
1032
|
+
terminalFinalText = finalText;
|
|
1033
|
+
}
|
|
1034
|
+
if (usage !== undefined) {
|
|
1035
|
+
terminalUsage = usage;
|
|
1036
|
+
}
|
|
1037
|
+
if (incompleteUsage === true) {
|
|
1038
|
+
terminalUsageIncomplete = true;
|
|
1039
|
+
}
|
|
1040
|
+
// pr-hero review F001: UNION, never overwrite. `completedCallIds` (the
|
|
1041
|
+
// one canonical per-attempt tally, declared below with the stream's own
|
|
1042
|
+
// writer) only ever grows — a CONFIRMING poll of an already-won
|
|
1043
|
+
// terminal (reachable right here, on the `sameTerminal` branch further
|
|
1044
|
+
// down, not just on the first win) used to overwrite the running total
|
|
1045
|
+
// with whatever this specific readback's fresh recount said, and a
|
|
1046
|
+
// recount can be smaller than an earlier one for the same set of real
|
|
1047
|
+
// completions. Adding to the set instead means a later, poorer
|
|
1048
|
+
// observation can only ever be a no-op, never a regression.
|
|
1049
|
+
if (polledCompletedCallIds !== undefined) {
|
|
1050
|
+
for (const id of polledCompletedCallIds) completedCallIds.add(id);
|
|
1051
|
+
}
|
|
1052
|
+
if (slotProof === undefined) {
|
|
1053
|
+
slotProof = proof;
|
|
1054
|
+
if (abortSequenceStarted) {
|
|
1055
|
+
// §5.2 line 272: the provider confirmed the abort inside the
|
|
1056
|
+
// confirmation window. Settle at once — adding the normal drain
|
|
1057
|
+
// window here would overrun the 6,500 ms harness deadline.
|
|
1058
|
+
settle({ kind: "abort_confirmed" });
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
// Post-win window, with TWO purposes now.
|
|
1062
|
+
//
|
|
1063
|
+
// §197's, which came first: a later conflicting terminal must be able
|
|
1064
|
+
// to flip the outcome malformed, so settlement is held open for one
|
|
1065
|
+
// cleanup budget before the win is recorded.
|
|
1066
|
+
//
|
|
1067
|
+
// #132's: the other observer may still be delivering this turn's
|
|
1068
|
+
// answer. The poll reaches the boundary from `/session/status` while
|
|
1069
|
+
// the stream is mid-delivery, and a window that simply expired
|
|
1070
|
+
// reported success over a truncated finalText — silently, since the
|
|
1071
|
+
// proof is valid and the completion is real. So the window now asks
|
|
1072
|
+
// whether the stream went quiet, and re-arms while it has not.
|
|
1073
|
+
//
|
|
1074
|
+
// This does NOT couple the observers. What §197 keeps independent is
|
|
1075
|
+
// the EVIDENCE — `observedActive` is owned by the poll and is never
|
|
1076
|
+
// armed from the stream (opencode-client.ts), because two observers of
|
|
1077
|
+
// one derived fact are not two observers. "Have you finished
|
|
1078
|
+
// delivering?" is a question about DELIVERY, and the answer changes no
|
|
1079
|
+
// observer's verdict about when the turn ended.
|
|
1080
|
+
drainCyclesLeft = this.maxDrainCycles;
|
|
1081
|
+
armDrainWindow();
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
if (sameTerminal(slotProof, proof)) {
|
|
1085
|
+
// §197: polling may confirm a matching terminal but never creates a
|
|
1086
|
+
// second one.
|
|
1087
|
+
pollConfirmations += 1;
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1090
|
+
settle({
|
|
1091
|
+
kind: "conflict",
|
|
1092
|
+
detail: `${source} terminal ${proof.eventId}/${proof.providerStatus} conflicts with ${slotProof.eventId}/${slotProof.providerStatus}`,
|
|
1093
|
+
});
|
|
1094
|
+
};
|
|
1095
|
+
|
|
1096
|
+
// ---- session -----------------------------------------------------------
|
|
1097
|
+
if (context.signal.aborted) {
|
|
1098
|
+
return {
|
|
1099
|
+
completion: "cancelled",
|
|
1100
|
+
protocolIntegrity: "unverified",
|
|
1101
|
+
finalText: "",
|
|
1102
|
+
usage: noSessionUsage(Date.now() - startedWall, this.usageBillingMode),
|
|
1103
|
+
stderrTail: "[pr-hero] opencode sdk: cancelled before session creation",
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
let session: OpenCodeClientSession;
|
|
1108
|
+
let removeAbort: (() => void) | undefined;
|
|
1109
|
+
let cancelSetup: (() => void) | undefined;
|
|
1110
|
+
let setupTimedOut = false;
|
|
1111
|
+
const operation = new AbortController();
|
|
1112
|
+
const cancelOperation = () => operation.abort();
|
|
1113
|
+
context.signal.addEventListener("abort", cancelOperation, { once: true });
|
|
1114
|
+
let createPromise: Promise<OpenCodeClientSession> | undefined;
|
|
1115
|
+
try {
|
|
1116
|
+
const abortPromise = new Promise<never>((_, reject) => {
|
|
1117
|
+
const onAbort = () => {
|
|
1118
|
+
reject(new DOMException("The operation was aborted", "AbortError"));
|
|
1119
|
+
};
|
|
1120
|
+
context.signal.addEventListener("abort", onAbort, { once: true });
|
|
1121
|
+
removeAbort = () => {
|
|
1122
|
+
context.signal.removeEventListener("abort", onAbort);
|
|
1123
|
+
};
|
|
1124
|
+
});
|
|
1125
|
+
|
|
1126
|
+
const setupTimeoutPromise = new Promise<never>((_, reject) => {
|
|
1127
|
+
cancelSetup = this.clock.schedule(this.setupDeadlineMs, () => {
|
|
1128
|
+
setupTimedOut = true;
|
|
1129
|
+
operation.abort();
|
|
1130
|
+
reject(new Error("opencode sdk: session creation deadline exceeded"));
|
|
1131
|
+
});
|
|
1132
|
+
});
|
|
1133
|
+
|
|
1134
|
+
// `request.effort` is deliberately NOT forwarded. Effort is a Claude Code
|
|
1135
|
+
// CLI control (`claude --effort`, #299); OpenCode's closest equivalent is
|
|
1136
|
+
// per-model reasoning variants, whose levels differ by provider and are
|
|
1137
|
+
// not the same scale, so mapping one onto the other here would invent a
|
|
1138
|
+
// meaning. That is a separate decision. What this backend does instead is
|
|
1139
|
+
// honest about it: the request plan still records the level the engine
|
|
1140
|
+
// asked for, with `effortApplied: false` (attempt-evidence.ts), and
|
|
1141
|
+
// pipeline.json says `effort_applied: false`.
|
|
1142
|
+
createPromise = this.client.createSession({
|
|
1143
|
+
correlation: { sessionId: request.sessionId, attempt: request.attempt },
|
|
1144
|
+
signal: operation.signal,
|
|
1145
|
+
cwd: request.cwd,
|
|
1146
|
+
userPrompt: request.userPrompt,
|
|
1147
|
+
systemPromptPath: request.systemPromptPath,
|
|
1148
|
+
tools: request.tools,
|
|
1149
|
+
...(request.mcpConfigPath !== undefined
|
|
1150
|
+
? { mcpConfigPath: request.mcpConfigPath }
|
|
1151
|
+
: {}),
|
|
1152
|
+
});
|
|
1153
|
+
|
|
1154
|
+
session = await Promise.race([
|
|
1155
|
+
createPromise,
|
|
1156
|
+
abortPromise,
|
|
1157
|
+
setupTimeoutPromise,
|
|
1158
|
+
]);
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
operation.abort();
|
|
1161
|
+
context.signal.removeEventListener("abort", cancelOperation);
|
|
1162
|
+
if (createPromise !== undefined) {
|
|
1163
|
+
void createPromise
|
|
1164
|
+
.then((s) => void this.client.abort(s))
|
|
1165
|
+
.catch(() => {});
|
|
1166
|
+
}
|
|
1167
|
+
if (
|
|
1168
|
+
context.signal.aborted ||
|
|
1169
|
+
(error instanceof DOMException && error.name === "AbortError")
|
|
1170
|
+
) {
|
|
1171
|
+
return {
|
|
1172
|
+
completion: "cancelled",
|
|
1173
|
+
protocolIntegrity: "unverified",
|
|
1174
|
+
finalText: "",
|
|
1175
|
+
usage: normalizeUnavailableUsage({
|
|
1176
|
+
wallMs: Date.now() - startedWall,
|
|
1177
|
+
billingMode: this.usageBillingMode,
|
|
1178
|
+
}),
|
|
1179
|
+
stderrTail:
|
|
1180
|
+
"[pr-hero] opencode sdk: cancelled during session creation",
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
// Redaction of any provider text happens harness-side before persistence;
|
|
1184
|
+
// here the message is only classification witness (§6.3).
|
|
1185
|
+
return {
|
|
1186
|
+
completion: "failed",
|
|
1187
|
+
protocolIntegrity: "unverified",
|
|
1188
|
+
finalText: "",
|
|
1189
|
+
usage: setupTimedOut
|
|
1190
|
+
? normalizeUnavailableUsage({
|
|
1191
|
+
wallMs: Date.now() - startedWall,
|
|
1192
|
+
billingMode: this.usageBillingMode,
|
|
1193
|
+
})
|
|
1194
|
+
: noSessionUsage(Date.now() - startedWall, this.usageBillingMode),
|
|
1195
|
+
stderrTail: `[pr-hero] opencode sdk: session creation failed: ${errorMessage(error)}`,
|
|
1196
|
+
// WHY the typed error, not the message: the server launch projects the route's
|
|
1197
|
+
// credential, and a provider with no record in the auth store is a typed broker
|
|
1198
|
+
// refusal. Its witness text would classify as runtime_unavailable, the generic
|
|
1199
|
+
// cause, so the instance carries the one class this transport can name.
|
|
1200
|
+
...(error instanceof CredentialProjectionError &&
|
|
1201
|
+
error.failureClass === "missing_provider_record"
|
|
1202
|
+
? { failureCause: "missing_provider_record" as const }
|
|
1203
|
+
: {}),
|
|
1204
|
+
};
|
|
1205
|
+
} finally {
|
|
1206
|
+
removeAbort?.();
|
|
1207
|
+
cancelSetup?.();
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// ONE line per attempt (#122), so the tools/MCP axis is provable by
|
|
1211
|
+
// reading the artifact rather than trusting `allowMapEnforced: true`.
|
|
1212
|
+
// Keys are sorted so the line is byte-stable across runs.
|
|
1213
|
+
//
|
|
1214
|
+
// On the diagnostics channel, not the witness (#126). This line records
|
|
1215
|
+
// what WE resolved, and it interpolates a provider-supplied id vocabulary
|
|
1216
|
+
// we do not control — the two properties that make a witness lie. It used
|
|
1217
|
+
// to sit in `notes` under a caveat asking every future author to check
|
|
1218
|
+
// that no new id trips a classifyFailure pattern ("invalid" alone does not
|
|
1219
|
+
// match `invalid api key`, nothing here looks like a rate limit or a
|
|
1220
|
+
// socket error). That caveat is now unnecessary rather than merely
|
|
1221
|
+
// satisfied: no classifier reads this channel, so no id CAN misclassify an
|
|
1222
|
+
// attempt, and the line is free to widen.
|
|
1223
|
+
if (session.toolMap !== undefined) {
|
|
1224
|
+
const rendered = Object.keys(session.toolMap)
|
|
1225
|
+
.sort()
|
|
1226
|
+
.map((id) => `${id}=${session.toolMap?.[id] === true}`)
|
|
1227
|
+
.join(",");
|
|
1228
|
+
diagnostics.push(
|
|
1229
|
+
`[pr-hero] opencode sdk: resolved tool map: ${rendered}`,
|
|
1230
|
+
);
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// ---- mutable attempt state --------------------------------------------
|
|
1234
|
+
const finalParts: string[] = [];
|
|
1235
|
+
let aggregateBytes = 0;
|
|
1236
|
+
// #124: the bare fact, not a volume. Nothing about reasoning is added to
|
|
1237
|
+
// `aggregateBytes` either — reasoning is not the answer, so it must not
|
|
1238
|
+
// consume the answer's §4.2 content budget.
|
|
1239
|
+
let sawReasoning = false;
|
|
1240
|
+
// #214: always stamped, including 0 — see the "tool" case below and the
|
|
1241
|
+
// outcome construction further down.
|
|
1242
|
+
//
|
|
1243
|
+
// pr-hero review F001/F002: ONE canonical per-attempt set, keyed by the
|
|
1244
|
+
// provider's callID, that BOTH the stream ("tool" events below) and the
|
|
1245
|
+
// poll (`onProviderTerminalCandidate`'s `polledCompletedCallIds` above)
|
|
1246
|
+
// add to. It only ever grows: no overwrite (F001 — a later, poorer
|
|
1247
|
+
// observation cannot erase an earlier real completion) and no separate
|
|
1248
|
+
// counts combined by `Math.max` (F002 — two different calls, one per
|
|
1249
|
+
// observer, must both count, which a size comparison cannot tell apart
|
|
1250
|
+
// from the same call counted twice). `toolInvocations` is this set's
|
|
1251
|
+
// size, read once at settlement. Bounded transitively: every id here (a)
|
|
1252
|
+
// stream events carry the id `handlePartUpdated` computed off `part
|
|
1253
|
+
// .callID`/`partId`, already capped by opencode-client.ts's
|
|
1254
|
+
// MAX_TRACKED_PARTS via `toolStates`, and (b) poll reports are `Array
|
|
1255
|
+
// .from` of that same client-side capped set — this map never receives
|
|
1256
|
+
// an id from an unbounded source, so it needs no cap of its own.
|
|
1257
|
+
const completedCallIds = new Set<string>();
|
|
1258
|
+
// Hand-written test doubles script a bare `{kind:"tool"}` with no
|
|
1259
|
+
// `callId` (there is no real client behind them to compute one) — a
|
|
1260
|
+
// per-event counter keeps each such event counting as one distinct
|
|
1261
|
+
// invocation, exactly as it did before identity tracking existed.
|
|
1262
|
+
let syntheticToolEventId = 0;
|
|
1263
|
+
const completedToolIds: string[] = [];
|
|
1264
|
+
let sawContentEvent = false;
|
|
1265
|
+
const seenUsageIds = new Set<string>();
|
|
1266
|
+
let usageIncomplete = false;
|
|
1267
|
+
// §4.1/§8: the first usage event fixes the attempt's aggregation mode;
|
|
1268
|
+
// `applyUsageUpdate` is the pure snapshot-replaces/delta-accumulates state
|
|
1269
|
+
// machine, shared with every other transport that folds a usage stream.
|
|
1270
|
+
let usageState: UsageModeState | undefined;
|
|
1271
|
+
let cashCostUsd: number | undefined;
|
|
1272
|
+
let sinkClosed = false;
|
|
1273
|
+
let closedDataPlaneEvents = 0;
|
|
1274
|
+
let pollTimeouts = 0;
|
|
1275
|
+
let abortSequenceStarted = false;
|
|
1276
|
+
|
|
1277
|
+
// Single-delivery guarantee for abort(): gated by abortSequenceStarted,
|
|
1278
|
+
// which both the signal path and the local-termination path consult.
|
|
1279
|
+
const callAbortOnce = async (): Promise<void> => {
|
|
1280
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1281
|
+
try {
|
|
1282
|
+
const timeoutPromise = new Promise<void>((resolve) => {
|
|
1283
|
+
timer = setTimeout(resolve, this.cleanupMs);
|
|
1284
|
+
});
|
|
1285
|
+
await Promise.race([this.client.abort(session), timeoutPromise]);
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
notes.push(
|
|
1288
|
+
`[pr-hero] opencode sdk: abort call failed: ${errorMessage(error)}`,
|
|
1289
|
+
);
|
|
1290
|
+
} finally {
|
|
1291
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
|
|
1295
|
+
// §5.2 line 272 abort sequence: abort() once, then wait up to
|
|
1296
|
+
// abortConfirmMs for a PROVIDER terminal proof. The abort request itself
|
|
1297
|
+
// can never win the §197 slot; only the provider's own proof can.
|
|
1298
|
+
const runAbortSequence = (): void => {
|
|
1299
|
+
if (abortSequenceStarted || settled) return;
|
|
1300
|
+
abortSequenceStarted = true;
|
|
1301
|
+
notes.push("[pr-hero] opencode sdk: abort requested");
|
|
1302
|
+
void callAbortOnce();
|
|
1303
|
+
if (slotProof !== undefined) {
|
|
1304
|
+
settle({ kind: "abort_confirmed" });
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
scheduleTracked(this.abortConfirmMs, () =>
|
|
1308
|
+
settle({ kind: "abort_unconfirmed" }),
|
|
1309
|
+
);
|
|
1310
|
+
};
|
|
1311
|
+
const onAbortSignal = (): void => {
|
|
1312
|
+
runAbortSequence();
|
|
1313
|
+
};
|
|
1314
|
+
if (context.signal.aborted) {
|
|
1315
|
+
runAbortSequence();
|
|
1316
|
+
} else {
|
|
1317
|
+
context.signal.addEventListener("abort", onAbortSignal, { once: true });
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// Per-attempt step timeout is harness-owned (StepSpec.timeoutMs → watchdog
|
|
1321
|
+
// → AbortSignal). This transport reacts to the supplied signal only; it
|
|
1322
|
+
// does not arm its own attempt deadline from the request.
|
|
1323
|
+
|
|
1324
|
+
// ---- stream watcher ----------------------------------------------------
|
|
1325
|
+
let streamIterator: AsyncIterator<OpenCodeClientEvent> | undefined;
|
|
1326
|
+
const runStream = async (): Promise<void> => {
|
|
1327
|
+
// NOT `for await`. execute() awaits `done`, never the watchers, so when
|
|
1328
|
+
// settlement is decided by the poll watcher or the attempt watchdog this
|
|
1329
|
+
// loop is parked inside next() — and its `if (settled)` guard only runs
|
|
1330
|
+
// once an event arrives. A provider that then goes quiet leaves the
|
|
1331
|
+
// subscription open forever. The poll watcher escapes because it wakes
|
|
1332
|
+
// on its own delay(); the stream watcher has no timer of its own, so it
|
|
1333
|
+
// is given one thing to race: settlement itself.
|
|
1334
|
+
//
|
|
1335
|
+
// Calling .return() from the outside would not have fixed it either —
|
|
1336
|
+
// on an async generator it queues BEHIND the pending next(), so a parked
|
|
1337
|
+
// watcher stays parked. Racing next() is what actually releases it.
|
|
1338
|
+
const iterator = this.client
|
|
1339
|
+
.streamEvents(session)
|
|
1340
|
+
[Symbol.asyncIterator]();
|
|
1341
|
+
streamIterator = iterator;
|
|
1342
|
+
// Attached ONCE: a per-iteration `done.then(...)` would pile a handler
|
|
1343
|
+
// onto `done` for every event a long stream delivers.
|
|
1344
|
+
const settledSignal = done.then(() => STREAM_SETTLED);
|
|
1345
|
+
let lastKnownTokens = 0;
|
|
1346
|
+
let lastKnownCost = 0;
|
|
1347
|
+
try {
|
|
1348
|
+
for (;;) {
|
|
1349
|
+
const step = await Promise.race([iterator.next(), settledSignal]);
|
|
1350
|
+
if (step === STREAM_SETTLED) return;
|
|
1351
|
+
if (step.done === true) break;
|
|
1352
|
+
const event = step.value;
|
|
1353
|
+
if (settled) return;
|
|
1354
|
+
// Provider-silence tripwire accounting: advance progress only on novel
|
|
1355
|
+
// delta text or strictly advanced usage tokens/cost. Heartbeats and
|
|
1356
|
+
// duplicate identical usage are keepalives, not signs of real delivery.
|
|
1357
|
+
let advancedProgress = false;
|
|
1358
|
+
if (event.kind === "delta") {
|
|
1359
|
+
if (event.text.length > 0) {
|
|
1360
|
+
advancedProgress = true;
|
|
1361
|
+
}
|
|
1362
|
+
} else if (event.kind === "reasoning" && event.progress === true) {
|
|
1363
|
+
advancedProgress = true;
|
|
1364
|
+
} else if (event.kind === "activity") {
|
|
1365
|
+
advancedProgress = true;
|
|
1366
|
+
} else if (event.kind === "usage") {
|
|
1367
|
+
const totalTokens =
|
|
1368
|
+
(event.inputTokens ?? 0) + (event.outputTokens ?? 0);
|
|
1369
|
+
const cost = event.costUsd ?? 0;
|
|
1370
|
+
if (totalTokens > lastKnownTokens || cost > lastKnownCost) {
|
|
1371
|
+
advancedProgress = true;
|
|
1372
|
+
if (totalTokens > lastKnownTokens) lastKnownTokens = totalTokens;
|
|
1373
|
+
if (cost > lastKnownCost) lastKnownCost = cost;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
if (advancedProgress) {
|
|
1377
|
+
noteContentEvent();
|
|
1378
|
+
sawContentEvent = true;
|
|
1379
|
+
}
|
|
1380
|
+
switch (event.kind) {
|
|
1381
|
+
case "delta": {
|
|
1382
|
+
// #132: set BEFORE the push, not after it. The window must count
|
|
1383
|
+
// a delta the watcher is still handing to the sink, or a slow
|
|
1384
|
+
// consumer turns the one delta in flight into the one delta
|
|
1385
|
+
// lost — the same gap that let `finalParts.push` below run after
|
|
1386
|
+
// settlement had already frozen the answer.
|
|
1387
|
+
deltaSinceArm = true;
|
|
1388
|
+
const bytes = utf8Bytes(event.text);
|
|
1389
|
+
if (bytes > this.maxDeltaBytes) {
|
|
1390
|
+
// §4.2 line 191: the offending delta is dropped WHOLE — it is
|
|
1391
|
+
// never truncated into something parseable.
|
|
1392
|
+
settle({ kind: "bound", target: "delta" });
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
if (aggregateBytes + bytes > this.maxFinalTextBytes) {
|
|
1396
|
+
settle({ kind: "bound", target: "aggregate" });
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
const pushed = await pushGuarded({
|
|
1400
|
+
...base(),
|
|
1401
|
+
type: "delta",
|
|
1402
|
+
text: event.text,
|
|
1403
|
+
});
|
|
1404
|
+
if (pushed === "stalled") {
|
|
1405
|
+
settle({ kind: "stall" });
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
if (pushed === "closed") {
|
|
1409
|
+
sinkClosed = true;
|
|
1410
|
+
closedDataPlaneEvents += 1;
|
|
1411
|
+
}
|
|
1412
|
+
if (settled) return;
|
|
1413
|
+
finalParts.push(event.text);
|
|
1414
|
+
aggregateBytes += bytes;
|
|
1415
|
+
break;
|
|
1416
|
+
}
|
|
1417
|
+
case "usage": {
|
|
1418
|
+
if (event.incomplete) {
|
|
1419
|
+
usageIncomplete = true;
|
|
1420
|
+
}
|
|
1421
|
+
if (event.id !== undefined) {
|
|
1422
|
+
if (seenUsageIds.has(event.id)) {
|
|
1423
|
+
if (event.mode === "delta") {
|
|
1424
|
+
break;
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
seenUsageIds.add(event.id);
|
|
1428
|
+
}
|
|
1429
|
+
// §4.2 line 195: the first usage event fixes the attempt's
|
|
1430
|
+
// aggregation mode; a later flip throws rather than silently
|
|
1431
|
+
// mixing snapshot and delta semantics.
|
|
1432
|
+
try {
|
|
1433
|
+
usageState = applyUsageUpdate(usageState, event.mode, {
|
|
1434
|
+
...(event.inputTokens !== undefined
|
|
1435
|
+
? { inputUncached: event.inputTokens }
|
|
1436
|
+
: {}),
|
|
1437
|
+
...(event.outputTokens !== undefined
|
|
1438
|
+
? { outputVisible: event.outputTokens }
|
|
1439
|
+
: {}),
|
|
1440
|
+
...(event.cacheReadTokens !== undefined
|
|
1441
|
+
? { inputCacheRead: event.cacheReadTokens }
|
|
1442
|
+
: {}),
|
|
1443
|
+
...(event.cacheWriteTokens !== undefined
|
|
1444
|
+
? { inputCacheWrite: event.cacheWriteTokens }
|
|
1445
|
+
: {}),
|
|
1446
|
+
...(event.reasoningTokens !== undefined
|
|
1447
|
+
? { outputReasoning: event.reasoningTokens }
|
|
1448
|
+
: {}),
|
|
1449
|
+
});
|
|
1450
|
+
} catch (error) {
|
|
1451
|
+
if (error instanceof UsageModeMismatchError) {
|
|
1452
|
+
settle({ kind: "usage_flip", detail: error.message });
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
throw error;
|
|
1456
|
+
}
|
|
1457
|
+
if (event.costUsd !== undefined) {
|
|
1458
|
+
cashCostUsd =
|
|
1459
|
+
event.mode === "snapshot"
|
|
1460
|
+
? event.costUsd
|
|
1461
|
+
: (cashCostUsd ?? 0) + event.costUsd;
|
|
1462
|
+
}
|
|
1463
|
+
const usage: Partial<NormalizedTokens> & {
|
|
1464
|
+
cashCostUsd?: number;
|
|
1465
|
+
} = {
|
|
1466
|
+
...(event.inputTokens !== undefined
|
|
1467
|
+
? { inputUncached: event.inputTokens }
|
|
1468
|
+
: {}),
|
|
1469
|
+
...(event.outputTokens !== undefined
|
|
1470
|
+
? { outputVisible: event.outputTokens }
|
|
1471
|
+
: {}),
|
|
1472
|
+
...(event.cacheReadTokens !== undefined
|
|
1473
|
+
? { inputCacheRead: event.cacheReadTokens }
|
|
1474
|
+
: {}),
|
|
1475
|
+
...(event.cacheWriteTokens !== undefined
|
|
1476
|
+
? { inputCacheWrite: event.cacheWriteTokens }
|
|
1477
|
+
: {}),
|
|
1478
|
+
...(event.reasoningTokens !== undefined
|
|
1479
|
+
? { outputReasoning: event.reasoningTokens }
|
|
1480
|
+
: {}),
|
|
1481
|
+
...(event.costUsd !== undefined
|
|
1482
|
+
? { cashCostUsd: event.costUsd }
|
|
1483
|
+
: {}),
|
|
1484
|
+
};
|
|
1485
|
+
const pushed = await pushGuarded({
|
|
1486
|
+
...base(),
|
|
1487
|
+
type: "usage",
|
|
1488
|
+
mode: event.mode,
|
|
1489
|
+
final: event.final ?? false,
|
|
1490
|
+
usage,
|
|
1491
|
+
});
|
|
1492
|
+
if (pushed === "stalled") {
|
|
1493
|
+
settle({ kind: "stall" });
|
|
1494
|
+
return;
|
|
1495
|
+
}
|
|
1496
|
+
if (pushed === "closed") {
|
|
1497
|
+
sinkClosed = true;
|
|
1498
|
+
closedDataPlaneEvents += 1;
|
|
1499
|
+
}
|
|
1500
|
+
if (settled) return;
|
|
1501
|
+
break;
|
|
1502
|
+
}
|
|
1503
|
+
case "diagnostic": {
|
|
1504
|
+
const pushed = await pushGuarded({
|
|
1505
|
+
...base(),
|
|
1506
|
+
type: "diagnostic",
|
|
1507
|
+
level: event.level,
|
|
1508
|
+
message: event.message,
|
|
1509
|
+
});
|
|
1510
|
+
if (pushed === "stalled") {
|
|
1511
|
+
settle({ kind: "stall" });
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
if (pushed === "closed") {
|
|
1515
|
+
sinkClosed = true;
|
|
1516
|
+
closedDataPlaneEvents += 1;
|
|
1517
|
+
}
|
|
1518
|
+
if (settled) return;
|
|
1519
|
+
break;
|
|
1520
|
+
}
|
|
1521
|
+
case "reasoning": {
|
|
1522
|
+
// Recorded, never forwarded. There is no sink push and no bound
|
|
1523
|
+
// check: nothing is being delivered and nothing is being spent —
|
|
1524
|
+
// the content was dropped at the client boundary and only this
|
|
1525
|
+
// one bit survives it.
|
|
1526
|
+
sawReasoning = true;
|
|
1527
|
+
break;
|
|
1528
|
+
}
|
|
1529
|
+
case "tool": {
|
|
1530
|
+
// Completed invocations only — the mapper dropped pending/error
|
|
1531
|
+
// and already dedupes by callID. Never a witness: tool ids ride
|
|
1532
|
+
// diagnosticsTail with the count, never `notes`.
|
|
1533
|
+
completedCallIds.add(
|
|
1534
|
+
event.callId ?? `synthetic-${syntheticToolEventId++}`,
|
|
1535
|
+
);
|
|
1536
|
+
if (event.tool !== undefined && event.tool.length > 0) {
|
|
1537
|
+
completedToolIds.push(event.tool);
|
|
1538
|
+
}
|
|
1539
|
+
break;
|
|
1540
|
+
}
|
|
1541
|
+
case "activity": {
|
|
1542
|
+
// Same shape as "reasoning" above: nothing to forward, nothing
|
|
1543
|
+
// to bound. The useful-progress credit was already taken above,
|
|
1544
|
+
// before this switch — there is nothing left to do here.
|
|
1545
|
+
break;
|
|
1546
|
+
}
|
|
1547
|
+
case "heartbeat": {
|
|
1548
|
+
const pushed = await pushGuarded({
|
|
1549
|
+
...base(),
|
|
1550
|
+
type: "heartbeat",
|
|
1551
|
+
});
|
|
1552
|
+
if (pushed === "stalled") {
|
|
1553
|
+
settle({ kind: "stall" });
|
|
1554
|
+
return;
|
|
1555
|
+
}
|
|
1556
|
+
if (pushed === "closed") {
|
|
1557
|
+
sinkClosed = true;
|
|
1558
|
+
closedDataPlaneEvents += 1;
|
|
1559
|
+
}
|
|
1560
|
+
if (settled) return;
|
|
1561
|
+
break;
|
|
1562
|
+
}
|
|
1563
|
+
case "terminal": {
|
|
1564
|
+
onProviderTerminalCandidate(event.proof, "stream");
|
|
1565
|
+
if (settled) return;
|
|
1566
|
+
break;
|
|
1567
|
+
}
|
|
1568
|
+
case "provider_limit": {
|
|
1569
|
+
// #157: fail fast — no fresh attempt can outrun a spent quota,
|
|
1570
|
+
// unlike an ordinary stall or silence. Reuses `stream_error`
|
|
1571
|
+
// rather than a new SettleReason: the abort-trigger set and the
|
|
1572
|
+
// completion/protocolIntegrity mapping already give this exact
|
|
1573
|
+
// shape (failed, unverified, best-effort abort), and the
|
|
1574
|
+
// classification-critical text just needs to survive inside
|
|
1575
|
+
// `detail` for classifyFailure's substring match below.
|
|
1576
|
+
settle({
|
|
1577
|
+
kind: "stream_error",
|
|
1578
|
+
detail: formatProviderLimitDetail(event.reason, event.message),
|
|
1579
|
+
});
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
case "provider_refusal": {
|
|
1583
|
+
// #213: same settlement as the limit above, and for the same
|
|
1584
|
+
// reason. A provider that already refused the turn (403,
|
|
1585
|
+
// isRetryable false) must not sit until the silence tripwire
|
|
1586
|
+
// and must not be parsed as an empty draft. The drain window
|
|
1587
|
+
// is still open when this arrives after session.idle, and
|
|
1588
|
+
// settle() is first-write-wins — so this still beats an empty
|
|
1589
|
+
// terminal that has not closed yet.
|
|
1590
|
+
settle({
|
|
1591
|
+
kind: "stream_error",
|
|
1592
|
+
detail: formatProviderRefusalDetail(event),
|
|
1593
|
+
});
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
if (settled) return;
|
|
1598
|
+
}
|
|
1599
|
+
// §197: a stream EOF is not a terminal proof and cannot win the slot.
|
|
1600
|
+
// Polling keeps running so the provider can still terminate the
|
|
1601
|
+
// attempt through the slot.
|
|
1602
|
+
notes.push(
|
|
1603
|
+
"[pr-hero] opencode sdk: stream EOF observed; EOF is not a terminal proof and cannot win the slot",
|
|
1604
|
+
);
|
|
1605
|
+
} catch (error) {
|
|
1606
|
+
settle({ kind: "stream_error", detail: errorMessage(error) });
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
|
|
1610
|
+
// ---- poll watcher ------------------------------------------------------
|
|
1611
|
+
let inFlightPoll: Promise<OpenCodePollResult | "round_timeout"> | undefined;
|
|
1612
|
+
const pollScriptRound = async (): Promise<
|
|
1613
|
+
OpenCodePollResult | "round_timeout"
|
|
1614
|
+
> => {
|
|
1615
|
+
let cancelRound: (() => void) | undefined;
|
|
1616
|
+
const roundController = new AbortController();
|
|
1617
|
+
const abortRound = () => roundController.abort();
|
|
1618
|
+
context.signal.addEventListener("abort", abortRound, { once: true });
|
|
1619
|
+
// After cancellation, fresh bounded polls may still confirm cessation.
|
|
1620
|
+
// Only the request in flight when cancellation arrives is interrupted.
|
|
1621
|
+
try {
|
|
1622
|
+
const timedOut = new Promise<"round_timeout">((resolve) => {
|
|
1623
|
+
cancelRound = this.clock.schedule(this.pollRoundMs, () =>
|
|
1624
|
+
resolve("round_timeout"),
|
|
1625
|
+
);
|
|
1626
|
+
});
|
|
1627
|
+
// A poll that throws is a failed observation, not a terminal.
|
|
1628
|
+
// A client ignoring AbortSignal must not accumulate requests. Keep its
|
|
1629
|
+
// promise occupying the slot until it actually settles.
|
|
1630
|
+
if (inFlightPoll === undefined) {
|
|
1631
|
+
inFlightPoll = this.client
|
|
1632
|
+
.pollStatus(session, roundController.signal)
|
|
1633
|
+
.catch(() => "round_timeout" as const)
|
|
1634
|
+
.finally(() => {
|
|
1635
|
+
inFlightPoll = undefined;
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1638
|
+
return await Promise.race([
|
|
1639
|
+
inFlightPoll,
|
|
1640
|
+
timedOut,
|
|
1641
|
+
done.then(() => "round_timeout" as const),
|
|
1642
|
+
]);
|
|
1643
|
+
} finally {
|
|
1644
|
+
cancelRound?.();
|
|
1645
|
+
roundController.abort();
|
|
1646
|
+
context.signal.removeEventListener("abort", abortRound);
|
|
1647
|
+
}
|
|
1648
|
+
};
|
|
1649
|
+
// Observe FIRST, delay BETWEEN rounds — never before the first one. The
|
|
1650
|
+
// poll observer can only read absence as a boundary once it has seen the
|
|
1651
|
+
// provider name this session through its own endpoint, and a full
|
|
1652
|
+
// pollIntervalMs of blindness at the start meant a turn finishing inside
|
|
1653
|
+
// that first interval was never observed working at all. Absence was then
|
|
1654
|
+
// all it ever saw, absence alone proves nothing (it is also what a wrong
|
|
1655
|
+
// status scope looks like), and the fallback that exists precisely for a
|
|
1656
|
+
// stream EOF without `session.idle` had no path to a terminal — the
|
|
1657
|
+
// attempt ran to the harness watchdog over a turn already sitting
|
|
1658
|
+
// completed in session.messages().
|
|
1659
|
+
//
|
|
1660
|
+
// This NARROWS that window to the provider's own busy-registration
|
|
1661
|
+
// latency, it does not close it: the prompt is fired-not-awaited, so a
|
|
1662
|
+
// first poll can still land before the server marks the session busy. No
|
|
1663
|
+
// sampling observer can do better without arming from the STREAM, and
|
|
1664
|
+
// that is forbidden by design (see SessionState.observedActive) — a status
|
|
1665
|
+
// scope that cannot see the session would then read step 1's completion as
|
|
1666
|
+
// the turn's terminal and reopen #127, trading a loud hang for a silent
|
|
1667
|
+
// truncation.
|
|
1668
|
+
//
|
|
1669
|
+
// The delay MOVED rather than being dropped, so every `continue` above it
|
|
1670
|
+
// had to go: a `continue` that now skips the delay is a busy loop.
|
|
1671
|
+
const runPoll = async (): Promise<void> => {
|
|
1672
|
+
for (;;) {
|
|
1673
|
+
if (settled) return;
|
|
1674
|
+
const result = await pollScriptRound();
|
|
1675
|
+
if (settled) return;
|
|
1676
|
+
if (result === "round_timeout") {
|
|
1677
|
+
// §197: a poll timeout cannot win the slot; it is only counted.
|
|
1678
|
+
pollTimeouts += 1;
|
|
1679
|
+
} else if (result.kind === "failed") {
|
|
1680
|
+
// §197's second observer, seeing the SAME fact the stream carries
|
|
1681
|
+
// when it is still alive to carry it. Settled, not counted: the
|
|
1682
|
+
// session cannot produce a terminal any more, so continuing to poll
|
|
1683
|
+
// for one would only wait out the harness watchdog.
|
|
1684
|
+
settle({ kind: "session_failed", detail: result.detail });
|
|
1685
|
+
return;
|
|
1686
|
+
} else if (result.kind === "terminal") {
|
|
1687
|
+
onProviderTerminalCandidate(
|
|
1688
|
+
result.proof,
|
|
1689
|
+
"poll",
|
|
1690
|
+
result.finalText,
|
|
1691
|
+
result.usage,
|
|
1692
|
+
result.usageIncomplete,
|
|
1693
|
+
result.completedToolCallIds,
|
|
1694
|
+
);
|
|
1695
|
+
if (settled) return;
|
|
1696
|
+
}
|
|
1697
|
+
if (settled) return;
|
|
1698
|
+
// Provider-silence tripwire accounting, closed here: one completed
|
|
1699
|
+
// round with no content event since the last one. A timed-out round
|
|
1700
|
+
// counts — §197 already says it proves nothing either way, and beside
|
|
1701
|
+
// a silent stream it is the same hung shape.
|
|
1702
|
+
if (contentSinceRound) {
|
|
1703
|
+
quietRounds = 0;
|
|
1704
|
+
contentSinceRound = false;
|
|
1705
|
+
} else {
|
|
1706
|
+
quietRounds += 1;
|
|
1707
|
+
const elapsedQuietMs = nowMs() - lastUsefulProgressWall;
|
|
1708
|
+
if (
|
|
1709
|
+
quietRounds >= this.maxQuietRounds ||
|
|
1710
|
+
elapsedQuietMs >= this.usefulProgressMs
|
|
1711
|
+
) {
|
|
1712
|
+
settle({ kind: "silence" });
|
|
1713
|
+
return;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
if (settled) return;
|
|
1717
|
+
await delay(this.pollIntervalMs);
|
|
1718
|
+
}
|
|
1719
|
+
};
|
|
1720
|
+
|
|
1721
|
+
// Re-arm against an absolute monotonic deadline, not a count of polls.
|
|
1722
|
+
const checkUsefulDeadline = (): void => {
|
|
1723
|
+
if (settled || slotProof !== undefined || abortSequenceStarted) return;
|
|
1724
|
+
const remaining =
|
|
1725
|
+
this.usefulProgressMs - (nowMs() - lastUsefulProgressWall);
|
|
1726
|
+
if (remaining <= 0) settle({ kind: "silence" });
|
|
1727
|
+
else scheduleTracked(remaining, checkUsefulDeadline);
|
|
1728
|
+
};
|
|
1729
|
+
lastUsefulProgressWall = nowMs();
|
|
1730
|
+
// Legacy timeless conformance clocks cannot drive elapsed-time alarms;
|
|
1731
|
+
// production and advancing-clock tests always supply monotonic nowMs.
|
|
1732
|
+
if (this.clock.nowMs !== undefined) {
|
|
1733
|
+
scheduleTracked(this.usefulProgressMs, checkUsefulDeadline);
|
|
1734
|
+
}
|
|
1735
|
+
const streamWatcher = runStream();
|
|
1736
|
+
const pollWatcher = runPoll();
|
|
1737
|
+
|
|
1738
|
+
let outcome: TransportOutcome;
|
|
1739
|
+
try {
|
|
1740
|
+
const reason = await done;
|
|
1741
|
+
operation.abort();
|
|
1742
|
+
context.signal.removeEventListener("abort", cancelOperation);
|
|
1743
|
+
for (const cancel of [...cancellers]) cancel();
|
|
1744
|
+
cancellers.clear();
|
|
1745
|
+
context.signal.removeEventListener("abort", onAbortSignal);
|
|
1746
|
+
|
|
1747
|
+
// Local terminations where the remote may still be producing: best-effort
|
|
1748
|
+
// abort so paid remote work is not abandoned silently. Confirmation is NOT
|
|
1749
|
+
// claimed unless a provider proof actually arrived.
|
|
1750
|
+
if (
|
|
1751
|
+
(reason.kind === "bound" ||
|
|
1752
|
+
reason.kind === "stall" ||
|
|
1753
|
+
reason.kind === "silence" ||
|
|
1754
|
+
reason.kind === "stream_error" ||
|
|
1755
|
+
reason.kind === "session_failed" ||
|
|
1756
|
+
reason.kind === "usage_flip") &&
|
|
1757
|
+
!abortSequenceStarted
|
|
1758
|
+
) {
|
|
1759
|
+
abortSequenceStarted = true;
|
|
1760
|
+
await callAbortOnce();
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
if (reason.kind === "conflict")
|
|
1764
|
+
notes.push(`${MARKER_CONFLICT}: ${reason.detail}`);
|
|
1765
|
+
if (reason.kind === "usage_flip")
|
|
1766
|
+
notes.push(`${MARKER_USAGE_FLIP}: ${reason.detail}`);
|
|
1767
|
+
if (reason.kind === "bound") {
|
|
1768
|
+
notes.push(
|
|
1769
|
+
reason.target === "delta"
|
|
1770
|
+
? `${MARKER_BOUND_DELTA}; attempt terminated, offending delta dropped whole`
|
|
1771
|
+
: `${MARKER_BOUND_AGGREGATE}; attempt terminated, offending delta dropped whole`,
|
|
1772
|
+
);
|
|
1773
|
+
}
|
|
1774
|
+
if (reason.kind === "stall") notes.push(MARKER_STALL);
|
|
1775
|
+
if (reason.kind === "stream_error") {
|
|
1776
|
+
notes.push(`[pr-hero] opencode sdk: stream errored: ${reason.detail}`);
|
|
1777
|
+
}
|
|
1778
|
+
if (reason.kind === "session_failed") {
|
|
1779
|
+
// Carries the provider's own words verbatim, which is what makes the
|
|
1780
|
+
// poll path classify exactly like the stream path — classifyFailure
|
|
1781
|
+
// substring-matches MARKER_PROMPT_REFUSED inside this detail rather
|
|
1782
|
+
// than pattern-matching this note's own wording.
|
|
1783
|
+
notes.push(
|
|
1784
|
+
`[pr-hero] opencode sdk: poll observed a session failure: ${reason.detail}`,
|
|
1785
|
+
);
|
|
1786
|
+
}
|
|
1787
|
+
if (reason.kind === "silence") notes.push(MARKER_SILENCE);
|
|
1788
|
+
if (reason.kind === "abort_unconfirmed")
|
|
1789
|
+
notes.push(MARKER_ABORT_UNCONFIRMED);
|
|
1790
|
+
if (
|
|
1791
|
+
reason.kind === "abort_confirmed" ||
|
|
1792
|
+
(abortSequenceStarted &&
|
|
1793
|
+
slotProof !== undefined &&
|
|
1794
|
+
!notes.includes(
|
|
1795
|
+
"[pr-hero] opencode sdk: provider terminal proof confirmed the abort inside the confirmation window",
|
|
1796
|
+
))
|
|
1797
|
+
) {
|
|
1798
|
+
notes.push(
|
|
1799
|
+
"[pr-hero] opencode sdk: provider terminal proof confirmed the abort inside the confirmation window",
|
|
1800
|
+
);
|
|
1801
|
+
}
|
|
1802
|
+
// #132: gated on `completed`, and the gate is the whole rationale.
|
|
1803
|
+
// Truncation-as-failure exists because SUCCESS is the one verdict that
|
|
1804
|
+
// hides a short answer. A terminal whose status is `cancelled` or
|
|
1805
|
+
// `failed` was never going to report success, and its answer is
|
|
1806
|
+
// incomplete by definition — so the drain budget has nothing to add
|
|
1807
|
+
// there, while stamping the marker would hand `protocol_truncation` a
|
|
1808
|
+
// fresh transient attempt to re-run a turn the provider already ended.
|
|
1809
|
+
const drainTruncated =
|
|
1810
|
+
reason.kind === "provider_terminal" &&
|
|
1811
|
+
!reason.drained &&
|
|
1812
|
+
(slotProof?.providerStatus ?? "").toLowerCase() === "completed";
|
|
1813
|
+
if (drainTruncated) {
|
|
1814
|
+
notes.push(MARKER_UNDELIVERED_CONTENT);
|
|
1815
|
+
}
|
|
1816
|
+
if (sawReasoning) {
|
|
1817
|
+
// A FIXED string: no model prose, and no free-form numbers either.
|
|
1818
|
+
//
|
|
1819
|
+
// `notes` becomes stderrTail, which is classifyFailure's whole
|
|
1820
|
+
// witness. Prose is the obvious hazard — reasoning is model-generated
|
|
1821
|
+
// text about the very failure modes those patterns name, which is
|
|
1822
|
+
// exactly why finalText is excluded from the witness and reasoning is
|
|
1823
|
+
// finalText's sibling. The counts are the SUBTLE one, and they were
|
|
1824
|
+
// measured, not guessed: the witness patterns include `\b429\b` and
|
|
1825
|
+
// `\b(?:502|503|504)\b`, so a reasoning stream of exactly 429 bytes
|
|
1826
|
+
// would have classified its own attempt `rate_limit`, and one of 503
|
|
1827
|
+
// bytes `network_transient`. A byte count lands in that range often.
|
|
1828
|
+
// The volume is not worth a note that can lie about why an attempt
|
|
1829
|
+
// failed, and the fact that matters — reasoning and no answer — is
|
|
1830
|
+
// stated below without a single digit.
|
|
1831
|
+
notes.push(
|
|
1832
|
+
"[pr-hero] opencode sdk: reasoning parts were received and discarded; reasoning is not the answer",
|
|
1833
|
+
);
|
|
1834
|
+
}
|
|
1835
|
+
// Only on a turn the provider actually finished. An aborted or errored
|
|
1836
|
+
// turn legitimately has no answer text, and saying otherwise would put a
|
|
1837
|
+
// second, competing diagnosis on an attempt that already has one.
|
|
1838
|
+
if (
|
|
1839
|
+
reason.kind === "provider_terminal" &&
|
|
1840
|
+
sawReasoning &&
|
|
1841
|
+
finalParts.length === 0
|
|
1842
|
+
) {
|
|
1843
|
+
notes.push(MARKER_REASONING_ONLY);
|
|
1844
|
+
}
|
|
1845
|
+
// #126: the four tallies below go to `diagnostics`, never `notes`. They
|
|
1846
|
+
// interpolate raw counts, and a count is a number we chose — landing it
|
|
1847
|
+
// in the witness lets our own bookkeeping answer a question only the
|
|
1848
|
+
// provider may answer. `429` poll timeouts filed as `rate_limit`, `503`
|
|
1849
|
+
// as `network_transient`, and — the leak that needs no rare number at
|
|
1850
|
+
// all — "poll round(s) timed out" carries the literal words `timed out`,
|
|
1851
|
+
// which the legacy classifier reads as transient at EVERY count.
|
|
1852
|
+
if (sinkClosed) {
|
|
1853
|
+
diagnostics.push(
|
|
1854
|
+
`[pr-hero] opencode sdk: sink closed early; ${closedDataPlaneEvents} data-plane event(s) not delivered`,
|
|
1855
|
+
);
|
|
1856
|
+
}
|
|
1857
|
+
if (pollTimeouts > 0) {
|
|
1858
|
+
diagnostics.push(
|
|
1859
|
+
`[pr-hero] opencode sdk: ${pollTimeouts} poll round(s) timed out; timeouts cannot win the terminal slot`,
|
|
1860
|
+
);
|
|
1861
|
+
}
|
|
1862
|
+
if (pollConfirmations > 0) {
|
|
1863
|
+
diagnostics.push(
|
|
1864
|
+
`[pr-hero] opencode sdk: poll confirmed the winning terminal ${pollConfirmations} time(s) without creating a second terminal`,
|
|
1865
|
+
);
|
|
1866
|
+
}
|
|
1867
|
+
if (invalidProofs > 0) {
|
|
1868
|
+
diagnostics.push(
|
|
1869
|
+
`[pr-hero] opencode sdk: ${invalidProofs} invalid terminal proof(s) ignored`,
|
|
1870
|
+
);
|
|
1871
|
+
}
|
|
1872
|
+
// #214: always, including 0. 0 is the claim "this session issued no
|
|
1873
|
+
// tool-call parts", and the live hunt that posted a clean bill could
|
|
1874
|
+
// not even prove that fact. Session-creation failure never reaches
|
|
1875
|
+
// here, so it correctly omits the count.
|
|
1876
|
+
//
|
|
1877
|
+
// pr-hero review F001/F002: the size of `completedCallIds` — see its
|
|
1878
|
+
// declaration above. Neither `Math.max` nor an overwrite is needed
|
|
1879
|
+
// anymore: the set itself is the union, built once, correctly, as each
|
|
1880
|
+
// observation arrives.
|
|
1881
|
+
const effectiveToolInvocations = completedCallIds.size;
|
|
1882
|
+
const toolIds =
|
|
1883
|
+
completedToolIds.length === 0
|
|
1884
|
+
? ""
|
|
1885
|
+
: ` (${completedToolIds.join(", ")})`;
|
|
1886
|
+
diagnostics.push(
|
|
1887
|
+
`[pr-hero] opencode sdk: observed ${effectiveToolInvocations} completed tool invocation(s)${toolIds}`,
|
|
1888
|
+
);
|
|
1889
|
+
|
|
1890
|
+
let completion: TransportOutcome["completion"];
|
|
1891
|
+
let protocolIntegrity: TransportOutcome["protocolIntegrity"];
|
|
1892
|
+
switch (reason.kind) {
|
|
1893
|
+
case "provider_terminal":
|
|
1894
|
+
case "abort_confirmed": {
|
|
1895
|
+
// #132: a won terminal over a delivery that never finished. The
|
|
1896
|
+
// proof is real and stays attached as EVIDENCE — the same rule the
|
|
1897
|
+
// conflict arm follows — but §4.2 line 191 forbids reporting a
|
|
1898
|
+
// truncated answer as anything but truncated, and success is the one
|
|
1899
|
+
// verdict that would hide it. Only the completed status can reach
|
|
1900
|
+
// here; see `drainTruncated` above for why the others must not.
|
|
1901
|
+
if (drainTruncated) {
|
|
1902
|
+
completion = "failed";
|
|
1903
|
+
protocolIntegrity = "truncated";
|
|
1904
|
+
break;
|
|
1905
|
+
}
|
|
1906
|
+
protocolIntegrity = "verified";
|
|
1907
|
+
const status = (slotProof?.providerStatus ?? "").toLowerCase();
|
|
1908
|
+
if (abortSequenceStarted || context.signal.aborted) {
|
|
1909
|
+
// BE1a: Cancellation/deadline admitted before settlement fences
|
|
1910
|
+
// success deterministically. The verified terminal proof stays
|
|
1911
|
+
// attached as evidence of remote completion.
|
|
1912
|
+
completion = status === "failed" ? "failed" : "cancelled";
|
|
1913
|
+
} else if (status === "completed") {
|
|
1914
|
+
// §3.2 requires a VERIFIED proof and a BOUNDED finalText for
|
|
1915
|
+
// success — bounded, not non-empty: whether empty text is usable
|
|
1916
|
+
// output is the harness's format decision (§7), never ours.
|
|
1917
|
+
completion = "success";
|
|
1918
|
+
} else if (status === "cancelled") {
|
|
1919
|
+
completion = "cancelled";
|
|
1920
|
+
} else {
|
|
1921
|
+
completion = "failed";
|
|
1922
|
+
}
|
|
1923
|
+
break;
|
|
1924
|
+
}
|
|
1925
|
+
case "silence":
|
|
1926
|
+
// The answer channel went quiet with the delivery unfinished (or
|
|
1927
|
+
// never started) — failed/truncated, never success. The marker
|
|
1928
|
+
// above carries the cause to `protocol_truncation`.
|
|
1929
|
+
completion = "failed";
|
|
1930
|
+
protocolIntegrity = "truncated";
|
|
1931
|
+
break;
|
|
1932
|
+
case "conflict":
|
|
1933
|
+
case "usage_flip":
|
|
1934
|
+
// §197 / §4.2 line 195: a contradiction makes the outcome malformed;
|
|
1935
|
+
// the first valid proof stays attached as evidence, never as success.
|
|
1936
|
+
completion = "failed";
|
|
1937
|
+
protocolIntegrity = "malformed";
|
|
1938
|
+
break;
|
|
1939
|
+
case "bound":
|
|
1940
|
+
case "stall":
|
|
1941
|
+
completion = "failed";
|
|
1942
|
+
protocolIntegrity = "overflow";
|
|
1943
|
+
break;
|
|
1944
|
+
case "stream_error":
|
|
1945
|
+
case "session_failed":
|
|
1946
|
+
// Unverified, never malformed: nothing contradicted anything. The
|
|
1947
|
+
// provider simply never opened a turn, and the transport refuses to
|
|
1948
|
+
// manufacture a proof for the one it did not run.
|
|
1949
|
+
completion = "failed";
|
|
1950
|
+
protocolIntegrity = "unverified";
|
|
1951
|
+
break;
|
|
1952
|
+
case "abort_unconfirmed":
|
|
1953
|
+
// §5.3 line 290: the transport surfaces an unconfirmed abort honestly
|
|
1954
|
+
// — cancelled locally, integrity unverified, NO terminalProof, and
|
|
1955
|
+
// never a claim that remote execution or cost ended.
|
|
1956
|
+
completion = "cancelled";
|
|
1957
|
+
protocolIntegrity = "unverified";
|
|
1958
|
+
break;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
const effectiveFinalText =
|
|
1962
|
+
terminalFinalText !== undefined
|
|
1963
|
+
? terminalFinalText
|
|
1964
|
+
: finalParts.join("");
|
|
1965
|
+
|
|
1966
|
+
const effectiveIncomplete = usageIncomplete || terminalUsageIncomplete;
|
|
1967
|
+
|
|
1968
|
+
const effectiveCostUsd =
|
|
1969
|
+
terminalUsage?.costUsd !== undefined
|
|
1970
|
+
? Math.max(cashCostUsd ?? 0, terminalUsage.costUsd)
|
|
1971
|
+
: cashCostUsd;
|
|
1972
|
+
|
|
1973
|
+
const hasObservedUsage =
|
|
1974
|
+
usageState !== undefined ||
|
|
1975
|
+
(terminalUsage !== undefined &&
|
|
1976
|
+
(terminalUsage.costUsd !== undefined ||
|
|
1977
|
+
terminalUsage.inputTokens !== undefined ||
|
|
1978
|
+
terminalUsage.outputTokens !== undefined));
|
|
1979
|
+
|
|
1980
|
+
outcome = {
|
|
1981
|
+
completion,
|
|
1982
|
+
protocolIntegrity,
|
|
1983
|
+
...(slotProof !== undefined &&
|
|
1984
|
+
reason.kind !== "abort_unconfirmed" &&
|
|
1985
|
+
(reason.kind === "provider_terminal" ||
|
|
1986
|
+
reason.kind === "abort_confirmed" ||
|
|
1987
|
+
reason.kind === "conflict" ||
|
|
1988
|
+
reason.kind === "usage_flip")
|
|
1989
|
+
? { terminalProof: slotProof }
|
|
1990
|
+
: {}),
|
|
1991
|
+
finalText: effectiveFinalText,
|
|
1992
|
+
// §8: no usage event ever arriving is not a proven zero —
|
|
1993
|
+
// "unavailable" says honestly that the cost is unknown rather than
|
|
1994
|
+
// fabricating a $0 for a session that DID run. `usageState` defined
|
|
1995
|
+
// means at least one usage event landed and fixed a mode, so the
|
|
1996
|
+
// leaves it accumulated are trustworthy.
|
|
1997
|
+
//
|
|
1998
|
+
// 2026-09-02: the parenthetical here used to read "capabilities().
|
|
1999
|
+
// protocol.usageMode is 'none' until D1-11's real SDK adapter", which
|
|
2000
|
+
// misattributed that field. `usageMode: "none"` is not a gap waiting
|
|
2001
|
+
// on an adapter — it is the honest static answer to a RUNTIME
|
|
2002
|
+
// question, because the aggregation mode is fixed by the first usage
|
|
2003
|
+
// event (§4.2 line 195) and no static snapshot/delta claim can be
|
|
2004
|
+
// defended before one arrives. The transport's own
|
|
2005
|
+
// `usage_mode_client_reported` issue says exactly that. Reading the
|
|
2006
|
+
// old wording as "usage does not arrive yet" is what made
|
|
2007
|
+
// `pricingReady: false` look consistent with a client that has been
|
|
2008
|
+
// reading the provider's cost off every assistant message.
|
|
2009
|
+
usage: !hasObservedUsage
|
|
2010
|
+
? promptRefusedBeforeStart(
|
|
2011
|
+
reason,
|
|
2012
|
+
finalParts.length,
|
|
2013
|
+
sawReasoning,
|
|
2014
|
+
sawContentEvent,
|
|
2015
|
+
)
|
|
2016
|
+
? noSessionUsage(Date.now() - startedWall, this.usageBillingMode)
|
|
2017
|
+
: normalizeUnavailableUsage({
|
|
2018
|
+
wallMs: Date.now() - startedWall,
|
|
2019
|
+
billingMode: this.usageBillingMode,
|
|
2020
|
+
})
|
|
2021
|
+
: {
|
|
2022
|
+
wallMs: Date.now() - startedWall,
|
|
2023
|
+
tokens: {
|
|
2024
|
+
...(usageState?.tokens ?? terminalLeaves(terminalUsage)),
|
|
2025
|
+
...knownUsageSums(usageState?.tokens, terminalUsage),
|
|
2026
|
+
},
|
|
2027
|
+
completeness:
|
|
2028
|
+
effectiveIncomplete ||
|
|
2029
|
+
reason.kind === "abort_unconfirmed" ||
|
|
2030
|
+
reason.kind === "usage_flip" ||
|
|
2031
|
+
reason.kind === "conflict" ||
|
|
2032
|
+
reason.kind === "silence" ||
|
|
2033
|
+
reason.kind === "stream_error" ||
|
|
2034
|
+
reason.kind === "session_failed" ||
|
|
2035
|
+
reason.kind === "stall" ||
|
|
2036
|
+
reason.kind === "bound"
|
|
2037
|
+
? "partial"
|
|
2038
|
+
: "complete",
|
|
2039
|
+
// 2026-09-02: the ROUTE's mode, not a hardcoded
|
|
2040
|
+
// "subscription". #133 established that an OpenCode route on
|
|
2041
|
+
// any provider but `openai` runs on a `provider_api_token`
|
|
2042
|
+
// and therefore bills METERED, and the exact-binding
|
|
2043
|
+
// capability report has said so since. This record used to
|
|
2044
|
+
// contradict it — and the contradiction is exploitable, not
|
|
2045
|
+
// cosmetic: `settlementFromUsage`'s metered-zero rule reads
|
|
2046
|
+
// THIS field, so a metered attempt wearing a subscription
|
|
2047
|
+
// badge settles a provider-reported $0 as truthful.
|
|
2048
|
+
billingMode: this.usageBillingMode,
|
|
2049
|
+
costSource:
|
|
2050
|
+
effectiveCostUsd !== undefined ? "provider" : "unknown",
|
|
2051
|
+
...(effectiveCostUsd !== undefined
|
|
2052
|
+
? { cashCostUsd: effectiveCostUsd }
|
|
2053
|
+
: {}),
|
|
2054
|
+
},
|
|
2055
|
+
// D1-07 bridge recovers watchdog_timeout from harness-set timedOut on
|
|
2056
|
+
// the outcome, not from transport notes.
|
|
2057
|
+
stderrTail: boundTailBytes(notes.join("\n"), MAX_STDERR_TAIL_BYTES),
|
|
2058
|
+
// Bounded like the witness (§4.2 line 191) because it lands on disk
|
|
2059
|
+
// through the same attempt log and the same redaction.
|
|
2060
|
+
diagnosticsTail: boundTailBytes(
|
|
2061
|
+
diagnostics.join("\n"),
|
|
2062
|
+
MAX_STDERR_TAIL_BYTES,
|
|
2063
|
+
),
|
|
2064
|
+
// #214: stamped after a session ran, including 0. Absence is reserved
|
|
2065
|
+
// for transports that cannot observe tools (and for this transport's
|
|
2066
|
+
// own session-creation failure, which never opened a turn).
|
|
2067
|
+
toolInvocations: effectiveToolInvocations,
|
|
2068
|
+
};
|
|
2069
|
+
|
|
2070
|
+
// §4.1: the transport normally supplies the attempt's ONE terminal event.
|
|
2071
|
+
// The push is awaited but raced against the cleanup budget so a wedged
|
|
2072
|
+
// sink cannot hang the return; the harness owns the slot and the sink.
|
|
2073
|
+
let cancelTerminalPush: (() => void) | undefined;
|
|
2074
|
+
try {
|
|
2075
|
+
const status =
|
|
2076
|
+
completion === "success"
|
|
2077
|
+
? "completed"
|
|
2078
|
+
: completion === "failed"
|
|
2079
|
+
? "failed"
|
|
2080
|
+
: "cancelled";
|
|
2081
|
+
const origin =
|
|
2082
|
+
outcome.terminalProof !== undefined ? "provider" : "transport";
|
|
2083
|
+
const terminalEvent: ProviderEvent = {
|
|
2084
|
+
...base(),
|
|
2085
|
+
type: "terminal",
|
|
2086
|
+
origin,
|
|
2087
|
+
status,
|
|
2088
|
+
...(outcome.terminalProof !== undefined
|
|
2089
|
+
? { proof: outcome.terminalProof }
|
|
2090
|
+
: {}),
|
|
2091
|
+
integrity: protocolIntegrity,
|
|
2092
|
+
};
|
|
2093
|
+
const pushPromise = context.events
|
|
2094
|
+
.push(terminalEvent)
|
|
2095
|
+
.catch(() => "closed" as const);
|
|
2096
|
+
const pushWindow = new Promise<"window_expired">((resolve) => {
|
|
2097
|
+
cancelTerminalPush = this.clock.schedule(this.cleanupMs, () =>
|
|
2098
|
+
resolve("window_expired"),
|
|
2099
|
+
);
|
|
2100
|
+
});
|
|
2101
|
+
await Promise.race([pushPromise, pushWindow]);
|
|
2102
|
+
} finally {
|
|
2103
|
+
cancelTerminalPush?.();
|
|
2104
|
+
}
|
|
2105
|
+
|
|
2106
|
+
// Watchers observe `settled` and stop on their own; keep references so a
|
|
2107
|
+
// rejection inside a watcher after settlement is never unhandled.
|
|
2108
|
+
void streamWatcher.catch(() => {});
|
|
2109
|
+
void pollWatcher.catch(() => {});
|
|
2110
|
+
|
|
2111
|
+
return outcome;
|
|
2112
|
+
} finally {
|
|
2113
|
+
if (streamIterator !== undefined) {
|
|
2114
|
+
let returnTimer: ReturnType<typeof setTimeout> | undefined;
|
|
2115
|
+
try {
|
|
2116
|
+
const returnTimeout = new Promise<void>((resolve) => {
|
|
2117
|
+
returnTimer = setTimeout(resolve, this.cleanupMs);
|
|
2118
|
+
});
|
|
2119
|
+
await Promise.race([
|
|
2120
|
+
streamIterator.return?.() ??
|
|
2121
|
+
Promise.resolve({ done: true as const, value: undefined }),
|
|
2122
|
+
returnTimeout,
|
|
2123
|
+
]).catch(() => {});
|
|
2124
|
+
} finally {
|
|
2125
|
+
if (returnTimer !== undefined) clearTimeout(returnTimer);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
// Lease teardown only: execute() must not close the shared client because
|
|
2132
|
+
// the cached transport instance is reused across retries and concurrent steps
|
|
2133
|
+
// on the same routeFingerprint until registry.release() evicts it.
|
|
2134
|
+
async dispose(): Promise<void> {
|
|
2135
|
+
await this.client.close?.().catch(() => {});
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
// Marker-based mapping: the transport stamps the §4.2/§197/§290 violations
|
|
2139
|
+
// into its own stderr notes, and this function turns exactly those stamped
|
|
2140
|
+
// facts into TransportFailureCause values — plus provider auth/network text.
|
|
2141
|
+
// It can never return a harness cause (format_violation is harness-only, §7).
|
|
2142
|
+
classifyFailure(
|
|
2143
|
+
outcome: TransportOutcome,
|
|
2144
|
+
): TransportFailureCause | undefined {
|
|
2145
|
+
// finalText is deliberately NOT part of the witness. It is model-generated
|
|
2146
|
+
// review prose, and pr-hero reviews code for exactly the failure modes
|
|
2147
|
+
// these patterns name — "no rate limit on this endpoint", "unauthorized
|
|
2148
|
+
// access is possible" — so including it makes the tool's own subject
|
|
2149
|
+
// matter look like provider diagnostics. Every violation this transport
|
|
2150
|
+
// detects is stamped into `notes`, and the provider's own stream error is
|
|
2151
|
+
// recorded there too, so stderrTail is the complete diagnostics channel.
|
|
2152
|
+
const witness = outcome.stderrTail;
|
|
2153
|
+
if (witness.includes(MARKER_ABORT_UNCONFIRMED)) {
|
|
2154
|
+
return "remote_abort_unconfirmed";
|
|
2155
|
+
}
|
|
2156
|
+
// #157: FIRST among the provider-text patterns, deliberately. The
|
|
2157
|
+
// provider's own message is appended verbatim after this marker (see
|
|
2158
|
+
// formatProviderLimitDetail), and a message that happens to say "rate
|
|
2159
|
+
// limit" or "quota exceeded" must not let the generic patterns below
|
|
2160
|
+
// decide the cause instead of the fact pr-hero actually observed.
|
|
2161
|
+
// `quota_exhausted` is the one §7 cause whose retry disposition is
|
|
2162
|
+
// already terminal (decideRetryDisposition's default arm) — exactly
|
|
2163
|
+
// right, since a fresh attempt cannot outrun quota that is already spent.
|
|
2164
|
+
if (witness.includes(MARKER_PROVIDER_LIMIT)) {
|
|
2165
|
+
return "quota_exhausted";
|
|
2166
|
+
}
|
|
2167
|
+
// #157: same ordering rule as the marker above — checked before any
|
|
2168
|
+
// generic provider-text pattern so the underlying reply-failure message
|
|
2169
|
+
// (network error, 4xx body, whatever the SDK call actually failed with)
|
|
2170
|
+
// cannot steer this into rate_limit/network_transient/auth_invalid
|
|
2171
|
+
// instead of the fact that pr-hero's own permission control failed to
|
|
2172
|
+
// run.
|
|
2173
|
+
if (witness.includes(MARKER_PERMISSION_REJECT_FAILED)) {
|
|
2174
|
+
return "runtime_unavailable";
|
|
2175
|
+
}
|
|
2176
|
+
if (
|
|
2177
|
+
witness.includes(MARKER_CONFLICT) ||
|
|
2178
|
+
witness.includes(MARKER_USAGE_FLIP)
|
|
2179
|
+
) {
|
|
2180
|
+
return "protocol_mismatch";
|
|
2181
|
+
}
|
|
2182
|
+
if (witness.includes(MARKER_STALL)) {
|
|
2183
|
+
return "protocol_overflow";
|
|
2184
|
+
}
|
|
2185
|
+
if (
|
|
2186
|
+
witness.includes(MARKER_BOUND_DELTA) ||
|
|
2187
|
+
witness.includes(MARKER_BOUND_AGGREGATE)
|
|
2188
|
+
) {
|
|
2189
|
+
return "output_limit_exceeded";
|
|
2190
|
+
}
|
|
2191
|
+
if (
|
|
2192
|
+
/unauthorized|invalid[ _-]?api[ _-]?key|not authenticated|authentication (required|failed)|please (log ?in|sign ?in|authenticate)|chatgpt (login|auth)|opencode.*(log ?in|auth)/i.test(
|
|
2193
|
+
witness,
|
|
2194
|
+
)
|
|
2195
|
+
) {
|
|
2196
|
+
return "auth_invalid";
|
|
2197
|
+
}
|
|
2198
|
+
if (/\b429\b|rate limit|quota exceeded/i.test(witness)) {
|
|
2199
|
+
return "rate_limit";
|
|
2200
|
+
}
|
|
2201
|
+
if (
|
|
2202
|
+
/ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|socket hang up|fetch failed|network (error|failure)|\b(?:502|503|504)\b|overloaded/i.test(
|
|
2203
|
+
witness,
|
|
2204
|
+
)
|
|
2205
|
+
) {
|
|
2206
|
+
return "network_transient";
|
|
2207
|
+
}
|
|
2208
|
+
// The gateway's 500 surfacing as a refused prompt (Martian `opencode`
|
|
2209
|
+
// arm, 2026-09-10: `opencode session.prompt failed:
|
|
2210
|
+
// {"name":"UnknownError","data":{"message":"Unexpected server error…"}}`
|
|
2211
|
+
// killed 7/10 PRs with no retry, while the same route self-healed within
|
|
2212
|
+
// seconds hours later). A refused prompt whose text IS the provider's own
|
|
2213
|
+
// 500 is a transient gateway failure, not the runtime being unavailable —
|
|
2214
|
+
// the terminal marker below must not swallow it. Placed beside the
|
|
2215
|
+
// network patterns under the same ordering rule: auth/rate-limit above
|
|
2216
|
+
// still win, and a local TypeError with no provider-500 text still falls
|
|
2217
|
+
// through to the terminal marker.
|
|
2218
|
+
if (
|
|
2219
|
+
/unexpected server error|internal server error|\b500\b/i.test(witness)
|
|
2220
|
+
) {
|
|
2221
|
+
return "network_transient";
|
|
2222
|
+
}
|
|
2223
|
+
// LAST, and the position is the point. A session that never opened — or a
|
|
2224
|
+
// TURN that never started, which is the same fact one call later: the
|
|
2225
|
+
// provider refused the prompt, so no message exists and the model never
|
|
2226
|
+
// saw the request — is the runtime being unavailable. §7 makes that
|
|
2227
|
+
// terminal, so it stops instead
|
|
2228
|
+
// of spending the format-reminder budget on an attempt the model never
|
|
2229
|
+
// saw. That is what went wrong in issue #121: `sdk.createClient is not a
|
|
2230
|
+
// function` reached the harness with no mapped witness, fell through to
|
|
2231
|
+
// the legacy classifier, and was filed as `format_violation` — a
|
|
2232
|
+
// TypeError in our own transport recorded in the bucket reserved for
|
|
2233
|
+
// model misbehaviour, burning a retry on the way.
|
|
2234
|
+
//
|
|
2235
|
+
// Checked after the auth/rate-limit/network patterns because both
|
|
2236
|
+
// messages CARRY the provider's own text: "session creation failed:
|
|
2237
|
+
// fetch failed" is a transient network failure that keeps its retry, and
|
|
2238
|
+
// a refused prompt is if anything more likely to be a 429 or a 401. A
|
|
2239
|
+
// marker check above them would silently delete those paths.
|
|
2240
|
+
// #213: after the auth/rate/network/500 patterns, same ordering rule as
|
|
2241
|
+
// MARKER_PROMPT_REFUSED. A refusal whose own text is a 401 or a 500 keeps
|
|
2242
|
+
// that cause. What remains is a turn the provider refused and the model
|
|
2243
|
+
// never saw — runtime_unavailable, which is terminal, so the harness does
|
|
2244
|
+
// not spend the format-reminder budget on an empty draft. isRetryable
|
|
2245
|
+
// true is the provider asking for another attempt; that is the transient
|
|
2246
|
+
// budget, never the format one.
|
|
2247
|
+
// A refusal whose slot reports HTTP 404 names a model the provider does not
|
|
2248
|
+
// serve: no retry can make it exist, and PRH-MODEL-UNAVAILABLE says so with
|
|
2249
|
+
// the provider's name. Only the status slot decides, never the message.
|
|
2250
|
+
if (
|
|
2251
|
+
witness.includes(MARKER_PROVIDER_REFUSAL) &&
|
|
2252
|
+
providerRefusalStatus(witness) === "404"
|
|
2253
|
+
) {
|
|
2254
|
+
return "model_unavailable";
|
|
2255
|
+
}
|
|
2256
|
+
if (witness.includes(MARKER_PROVIDER_REFUSAL)) {
|
|
2257
|
+
return providerRefusalRetries(witness) === true
|
|
2258
|
+
? "network_transient"
|
|
2259
|
+
: "runtime_unavailable";
|
|
2260
|
+
}
|
|
2261
|
+
if (
|
|
2262
|
+
witness.includes(MARKER_SESSION_CREATE) ||
|
|
2263
|
+
witness.includes(MARKER_PROMPT_REFUSED)
|
|
2264
|
+
) {
|
|
2265
|
+
return "runtime_unavailable";
|
|
2266
|
+
}
|
|
2267
|
+
// LAST, under the same ordering rule as the two markers above and for the
|
|
2268
|
+
// same reason: this note sits beside the provider's own text in the same
|
|
2269
|
+
// witness, so a 429 or a 401 recorded on the same attempt must still win.
|
|
2270
|
+
//
|
|
2271
|
+
// `protocol_truncation`, not `runtime_unavailable` and not
|
|
2272
|
+
// `format_violation`. §7 freezes the cause vocabulary, so the choice is
|
|
2273
|
+
// between existing members: the runtime WAS available and the model DID
|
|
2274
|
+
// run, which rules out the first; nothing malformed was written, which
|
|
2275
|
+
// rules out the second — a format reminder would spend that budget telling
|
|
2276
|
+
// the model to reformat an answer it never produced. What actually
|
|
2277
|
+
// happened is that the answer channel delivered no content, and
|
|
2278
|
+
// truncation's disposition is the remedy that can work: a FRESH attempt on
|
|
2279
|
+
// the transient budget, bounded at 3, never the format budget.
|
|
2280
|
+
// #132, and LAST for the same reason as the markers above: this note sits
|
|
2281
|
+
// beside the provider's own text in one witness, so a 429 or a 401
|
|
2282
|
+
// recorded on the same attempt must still win. `protocol_truncation` is
|
|
2283
|
+
// the literal fact — the answer channel was cut short — and its
|
|
2284
|
+
// disposition is the remedy that can work: a FRESH attempt on the
|
|
2285
|
+
// transient budget, never the format budget, which would spend a reminder
|
|
2286
|
+
// telling the model to reformat text it did finish writing.
|
|
2287
|
+
if (witness.includes(MARKER_UNDELIVERED_CONTENT)) {
|
|
2288
|
+
return "protocol_truncation";
|
|
2289
|
+
}
|
|
2290
|
+
if (witness.includes(MARKER_SILENCE)) return "protocol_truncation";
|
|
2291
|
+
if (witness.includes(MARKER_REASONING_ONLY)) return "protocol_truncation";
|
|
2292
|
+
return undefined;
|
|
2293
|
+
}
|
|
2294
|
+
}
|