crysk 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +176 -0
- package/README.md +610 -2
- 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/adjudicator-dtg2axnh.md +86 -0
- package/dist/admission-config.example-a9vqmmad.json +9 -0
- package/dist/ci-admission-camfbx2b.md +122 -0
- package/dist/cli.js +42292 -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 +82 -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 +122 -0
- package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
- package/skills/crysk-loop/SKILL.md +496 -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 +923 -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 +901 -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 +847 -0
- package/src/pr/ci-admission-gate.ts +665 -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 +787 -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,515 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
|
|
4
|
+
export interface OpenCodeObservedIdentity {
|
|
5
|
+
readonly sdkVersion: string;
|
|
6
|
+
readonly serverVersion: string;
|
|
7
|
+
readonly executablePath: string;
|
|
8
|
+
readonly executableSha256: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Absence and mismatch are different FACTS with different consequences, so
|
|
12
|
+
// they get different error identities. A mismatch (both versions present,
|
|
13
|
+
// either one wrong) is an admission-policy violation: the exact-version gate
|
|
14
|
+
// is a threat model (CLAUDE.md rule 4), and admitOpenCodeVersionPair keeps
|
|
15
|
+
// refusing it exactly as before. Absence (no `@opencode-ai/sdk` resolvable at
|
|
16
|
+
// all — e.g. a `bun build --compile` binary run from a directory with no
|
|
17
|
+
// node_modules, which is every real user's repo) is not a policy violation:
|
|
18
|
+
// there is nothing to admit or refuse, the OpenCode route is simply
|
|
19
|
+
// unavailable here, and Claude-only routes are unaffected. Collapsing the two
|
|
20
|
+
// into one "Unsupported observed OpenCode pair: undefined/x.y.z" message is
|
|
21
|
+
// what made doctor report a Claude-only setup as blocking (see
|
|
22
|
+
// OpenCodeSdkUnavailableError's doctor-side handling).
|
|
23
|
+
export class OpenCodeSdkUnavailableError extends Error {
|
|
24
|
+
constructor(message: string) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "OpenCodeSdkUnavailableError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ONE sentence for every "the SDK is not resolvable" throw: the loader and
|
|
31
|
+
// the admission absence check. A version literal, not an interpolated
|
|
32
|
+
// missing value — the operator-facing text must name the pin and must not
|
|
33
|
+
// print the word "undefined". The transport test locks this sentence to
|
|
34
|
+
// SUPPORTED_OPENCODE_SDK_VERSION so the two pins cannot drift.
|
|
35
|
+
export function openCodeSdkUnavailableMessage(): string {
|
|
36
|
+
return (
|
|
37
|
+
"@opencode-ai/sdk@1.18.25 is not installed under ~/.crysk/node_modules " +
|
|
38
|
+
"(~/.prhero/node_modules on an install not yet migrated). " +
|
|
39
|
+
"Run crysk upgrade --reconcile to install it."
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The counterpart for "installed but the import itself failed" — a
|
|
44
|
+
// DIFFERENT fact from openCodeSdkUnavailableMessage above, which by this
|
|
45
|
+
// point in loadOpenCodeSdk is already known to be false (the version check
|
|
46
|
+
// just passed, so the package IS installed). Collapsing an import failure
|
|
47
|
+
// into "not installed" is what shipped a compiled binary reporting
|
|
48
|
+
// "@opencode-ai/sdk@1.18.25 is not installed" while it plainly was — the real
|
|
49
|
+
// cause, a `ResolveMessage: Cannot find package 'which'` from cross-spawn
|
|
50
|
+
// (nested inside the SDK's full /v2 index), was thrown away. This one
|
|
51
|
+
// interpolates the failed specifier and the caught error's own name+message
|
|
52
|
+
// on purpose: they are the only place the real cause still lives once this
|
|
53
|
+
// throws. It names no install location: the specifier already carries the
|
|
54
|
+
// real one, and ~/.crysk/node_modules (or a legacy ~/.prhero) is only where a COMPILED binary looks.
|
|
55
|
+
// The version is a literal for the same reason as the sentence above, and
|
|
56
|
+
// its transport test locks it to SUPPORTED_OPENCODE_SDK_VERSION the same way.
|
|
57
|
+
export function openCodeSdkLoadFailedMessage(
|
|
58
|
+
specifier: string,
|
|
59
|
+
error: unknown,
|
|
60
|
+
): string {
|
|
61
|
+
const detail =
|
|
62
|
+
error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
63
|
+
return (
|
|
64
|
+
`@opencode-ai/sdk@1.18.25 is installed but failed to load "${specifier}": ` +
|
|
65
|
+
`${detail}. This is a load failure, not a missing install — that error ` +
|
|
66
|
+
"is the real cause."
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
export interface OpenCodeExecutableIdentity {
|
|
70
|
+
readonly absolutePath: string;
|
|
71
|
+
readonly verifiedExecutionPath: string;
|
|
72
|
+
readonly sha256: string;
|
|
73
|
+
}
|
|
74
|
+
export type OpenCodeIdentityObserver = (
|
|
75
|
+
executable: OpenCodeExecutableIdentity,
|
|
76
|
+
signal?: AbortSignal,
|
|
77
|
+
) => Promise<OpenCodeObservedIdentity>;
|
|
78
|
+
|
|
79
|
+
// Independently derived from anomalyco/opencode tag v1.18.30, commit
|
|
80
|
+
// 3104c1428ec91f809e5ab86631300de41eb6952e, packages/sdk/openapi.json.
|
|
81
|
+
// Source SHA256 00502bd13e9c86f3ca9e765e99a57e06fa9f434ca16f2a714766d1444f8d37f3.
|
|
82
|
+
// Same consumed projection independently matches SDK 1.18.25. This is a
|
|
83
|
+
// qualification policy, never a digest manufactured from the running server.
|
|
84
|
+
export const OPENCODE_CONSUMED_CONTRACT_SHA256 =
|
|
85
|
+
"0126721f557bfb0fcbeed3567392416394921d0c5d38798392608ffd8f63e95d";
|
|
86
|
+
const operations: Record<string, readonly string[]> = {
|
|
87
|
+
"/global/health": ["get"],
|
|
88
|
+
"/session": ["post"],
|
|
89
|
+
"/session/{sessionID}/message": ["get", "post"],
|
|
90
|
+
"/session/status": ["get"],
|
|
91
|
+
"/session/{sessionID}/abort": ["post"],
|
|
92
|
+
"/experimental/tool/ids": ["get"],
|
|
93
|
+
"/mcp": ["get"],
|
|
94
|
+
"/event": ["get"],
|
|
95
|
+
};
|
|
96
|
+
const events = [
|
|
97
|
+
"EventMessageUpdated",
|
|
98
|
+
"EventMessageRemoved",
|
|
99
|
+
"EventMessagePartUpdated",
|
|
100
|
+
"EventMessagePartRemoved",
|
|
101
|
+
"EventMessagePartDelta",
|
|
102
|
+
"EventSessionError",
|
|
103
|
+
"EventSessionStatus",
|
|
104
|
+
"EventSessionIdle",
|
|
105
|
+
"EventServerConnected",
|
|
106
|
+
];
|
|
107
|
+
const annotations = new Set([
|
|
108
|
+
"description",
|
|
109
|
+
"summary",
|
|
110
|
+
"title",
|
|
111
|
+
"examples",
|
|
112
|
+
"example",
|
|
113
|
+
"x-codeSamples",
|
|
114
|
+
"tags",
|
|
115
|
+
]);
|
|
116
|
+
function record(value: unknown): Record<string, unknown> {
|
|
117
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
118
|
+
throw new Error("OpenCode contract object missing");
|
|
119
|
+
return value as Record<string, unknown>;
|
|
120
|
+
}
|
|
121
|
+
function normalize(value: unknown, key = ""): unknown {
|
|
122
|
+
if (Array.isArray(value)) {
|
|
123
|
+
const values = value.map((item) => normalize(item));
|
|
124
|
+
return [
|
|
125
|
+
"required",
|
|
126
|
+
"enum",
|
|
127
|
+
"anyOf",
|
|
128
|
+
"oneOf",
|
|
129
|
+
"allOf",
|
|
130
|
+
"parameters",
|
|
131
|
+
].includes(key)
|
|
132
|
+
? values.sort((a, b) =>
|
|
133
|
+
JSON.stringify(a) < JSON.stringify(b)
|
|
134
|
+
? -1
|
|
135
|
+
: JSON.stringify(a) > JSON.stringify(b)
|
|
136
|
+
? 1
|
|
137
|
+
: 0,
|
|
138
|
+
)
|
|
139
|
+
: values;
|
|
140
|
+
}
|
|
141
|
+
if (value !== null && typeof value === "object") {
|
|
142
|
+
return Object.fromEntries(
|
|
143
|
+
Object.entries(record(value))
|
|
144
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
145
|
+
.filter(([name]) => key === "properties" || !annotations.has(name))
|
|
146
|
+
.map(([name, item]) => [name, normalize(item, name)]),
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
return value;
|
|
150
|
+
}
|
|
151
|
+
export function consumedOpenCodeContractDigest(document: unknown): string {
|
|
152
|
+
const root = record(document);
|
|
153
|
+
const allPaths = record(root.paths);
|
|
154
|
+
const sourceSchemas = record(record(root.components).schemas);
|
|
155
|
+
const paths: Record<string, unknown> = {};
|
|
156
|
+
const schemas: Record<string, unknown> = {};
|
|
157
|
+
for (const [path, methods] of Object.entries(operations)) {
|
|
158
|
+
paths[path] = Object.fromEntries(
|
|
159
|
+
methods.map((method) => {
|
|
160
|
+
const operation = record(allPaths[path])[method];
|
|
161
|
+
if (operation === undefined)
|
|
162
|
+
throw new Error(`OpenCode contract lacks ${method} ${path}`);
|
|
163
|
+
return [method, operation];
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
const visit = (value: unknown): void => {
|
|
168
|
+
if (Array.isArray(value)) {
|
|
169
|
+
for (const item of value) visit(item);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (value === null || typeof value !== "object") return;
|
|
173
|
+
const node = record(value);
|
|
174
|
+
if (typeof node.$ref === "string") {
|
|
175
|
+
if (!node.$ref.startsWith("#/components/schemas/"))
|
|
176
|
+
throw new Error("Unsupported OpenCode contract reference");
|
|
177
|
+
const name = node.$ref.slice("#/components/schemas/".length);
|
|
178
|
+
if (name in schemas) return;
|
|
179
|
+
let schema = record(sourceSchemas[name]);
|
|
180
|
+
if (name === "Event") {
|
|
181
|
+
const branches = schema.anyOf;
|
|
182
|
+
if (!Array.isArray(branches))
|
|
183
|
+
throw new Error("OpenCode Event union unavailable");
|
|
184
|
+
const refs = new Set(branches.map((branch) => record(branch).$ref));
|
|
185
|
+
if (events.some((event) => !refs.has(`#/components/schemas/${event}`)))
|
|
186
|
+
throw new Error("OpenCode consumed Event branch missing");
|
|
187
|
+
schema = {
|
|
188
|
+
anyOf: events.map((event) => ({
|
|
189
|
+
$ref: `#/components/schemas/${event}`,
|
|
190
|
+
})),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
schemas[name] = schema;
|
|
194
|
+
visit(schema);
|
|
195
|
+
} else for (const item of Object.values(node)) visit(item);
|
|
196
|
+
};
|
|
197
|
+
visit(paths);
|
|
198
|
+
return createHash("sha256")
|
|
199
|
+
.update(JSON.stringify(normalize({ paths, components: { schemas } })))
|
|
200
|
+
.digest("hex");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function withAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
204
|
+
// The promise may have been constructed by the caller before cancellation.
|
|
205
|
+
// Observe its rejection even when the pre-aborted branch wins immediately.
|
|
206
|
+
void work.catch(() => {});
|
|
207
|
+
signal.throwIfAborted();
|
|
208
|
+
let abort: () => void = () => {};
|
|
209
|
+
try {
|
|
210
|
+
return await Promise.race([
|
|
211
|
+
work,
|
|
212
|
+
new Promise<never>((_, reject) => {
|
|
213
|
+
abort = () =>
|
|
214
|
+
reject(signal.reason ?? new Error("OpenCode observation aborted"));
|
|
215
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
216
|
+
}),
|
|
217
|
+
]);
|
|
218
|
+
} finally {
|
|
219
|
+
signal.removeEventListener("abort", abort);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function boundedText(
|
|
224
|
+
stream: ReadableStream<Uint8Array>,
|
|
225
|
+
maxBytes: number,
|
|
226
|
+
signal: AbortSignal,
|
|
227
|
+
): Promise<string> {
|
|
228
|
+
const reader = stream.getReader();
|
|
229
|
+
const chunks: Uint8Array[] = [];
|
|
230
|
+
let size = 0;
|
|
231
|
+
const abort = () => {
|
|
232
|
+
void reader.cancel().catch(() => {});
|
|
233
|
+
};
|
|
234
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
235
|
+
try {
|
|
236
|
+
for (;;) {
|
|
237
|
+
signal.throwIfAborted();
|
|
238
|
+
const { done, value } = await withAbort(reader.read(), signal);
|
|
239
|
+
signal.throwIfAborted();
|
|
240
|
+
if (done) break;
|
|
241
|
+
size += value.byteLength;
|
|
242
|
+
if (size > maxBytes)
|
|
243
|
+
throw new Error("OpenCode observation byte limit exceeded");
|
|
244
|
+
chunks.push(value);
|
|
245
|
+
}
|
|
246
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
247
|
+
} finally {
|
|
248
|
+
signal.removeEventListener("abort", abort);
|
|
249
|
+
void reader.cancel().catch(() => {});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export async function observeOpenCodeExecutable(
|
|
254
|
+
executable: OpenCodeExecutableIdentity,
|
|
255
|
+
signal?: AbortSignal,
|
|
256
|
+
dependencies: {
|
|
257
|
+
spawn?: typeof Bun.spawn;
|
|
258
|
+
sdkVersion?: () => Promise<string | undefined>;
|
|
259
|
+
timeoutMs?: number;
|
|
260
|
+
} = {},
|
|
261
|
+
): Promise<OpenCodeObservedIdentity> {
|
|
262
|
+
signal?.throwIfAborted();
|
|
263
|
+
const controller = new AbortController();
|
|
264
|
+
const abort = () => controller.abort(signal?.reason);
|
|
265
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
266
|
+
const timer = setTimeout(
|
|
267
|
+
() => controller.abort(new Error("OpenCode version observation deadline")),
|
|
268
|
+
dependencies.timeoutMs ?? 2_000,
|
|
269
|
+
);
|
|
270
|
+
let proc: ReturnType<typeof Bun.spawn> | undefined;
|
|
271
|
+
const kill = () => {
|
|
272
|
+
try {
|
|
273
|
+
proc?.kill("SIGKILL");
|
|
274
|
+
} catch {}
|
|
275
|
+
};
|
|
276
|
+
controller.signal.addEventListener("abort", kill, { once: true });
|
|
277
|
+
try {
|
|
278
|
+
const bytes = await withAbort(
|
|
279
|
+
readFile(executable.absolutePath, { signal: controller.signal }),
|
|
280
|
+
controller.signal,
|
|
281
|
+
);
|
|
282
|
+
if (createHash("sha256").update(bytes).digest("hex") !== executable.sha256)
|
|
283
|
+
throw new Error("OpenCode executable changed before version observation");
|
|
284
|
+
controller.signal.throwIfAborted();
|
|
285
|
+
proc = (dependencies.spawn ?? Bun.spawn)(
|
|
286
|
+
[executable.verifiedExecutionPath, "--version"],
|
|
287
|
+
{ stdin: "ignore", stdout: "pipe", stderr: "pipe", env: {} },
|
|
288
|
+
);
|
|
289
|
+
const [stdout, , code] = await withAbort(
|
|
290
|
+
Promise.all([
|
|
291
|
+
boundedText(
|
|
292
|
+
proc.stdout as ReadableStream<Uint8Array>,
|
|
293
|
+
4096,
|
|
294
|
+
controller.signal,
|
|
295
|
+
),
|
|
296
|
+
boundedText(
|
|
297
|
+
proc.stderr as ReadableStream<Uint8Array>,
|
|
298
|
+
4096,
|
|
299
|
+
controller.signal,
|
|
300
|
+
),
|
|
301
|
+
proc.exited,
|
|
302
|
+
]),
|
|
303
|
+
controller.signal,
|
|
304
|
+
);
|
|
305
|
+
controller.signal.throwIfAborted();
|
|
306
|
+
const serverVersion = stdout.trim();
|
|
307
|
+
if (code !== 0 || !/^\d+\.\d+\.\d+$/.test(serverVersion))
|
|
308
|
+
throw new Error("OpenCode version observation malformed");
|
|
309
|
+
const sdkVersion = await withAbort(
|
|
310
|
+
Promise.resolve(dependencies.sdkVersion?.()),
|
|
311
|
+
controller.signal,
|
|
312
|
+
);
|
|
313
|
+
// Absence check FIRST, and separate from the mismatch check below: a
|
|
314
|
+
// missing/blank SDK version means "not resolvable here" (see
|
|
315
|
+
// OpenCodeSdkUnavailableError above), not "resolvable but wrong". Folding
|
|
316
|
+
// this into the mismatch branch is exactly what produced
|
|
317
|
+
// "Unsupported observed OpenCode pair: undefined/1.18.30" for every
|
|
318
|
+
// compiled-binary install and made doctor report it as blocking.
|
|
319
|
+
if (typeof sdkVersion !== "string" || sdkVersion.trim() === "")
|
|
320
|
+
throw new OpenCodeSdkUnavailableError(openCodeSdkUnavailableMessage());
|
|
321
|
+
if (sdkVersion !== "1.18.25" || serverVersion !== "1.18.30")
|
|
322
|
+
throw new Error(
|
|
323
|
+
`Unsupported observed OpenCode pair: ${sdkVersion}/${serverVersion}`,
|
|
324
|
+
);
|
|
325
|
+
return Object.freeze({
|
|
326
|
+
sdkVersion,
|
|
327
|
+
serverVersion,
|
|
328
|
+
executablePath: executable.absolutePath,
|
|
329
|
+
executableSha256: executable.sha256,
|
|
330
|
+
});
|
|
331
|
+
} finally {
|
|
332
|
+
clearTimeout(timer);
|
|
333
|
+
signal?.removeEventListener("abort", abort);
|
|
334
|
+
controller.signal.removeEventListener("abort", kill);
|
|
335
|
+
controller.abort();
|
|
336
|
+
kill();
|
|
337
|
+
if (proc !== undefined) {
|
|
338
|
+
let reapTimer: ReturnType<typeof setTimeout> | undefined;
|
|
339
|
+
try {
|
|
340
|
+
await Promise.race([
|
|
341
|
+
proc.exited.catch(() => {}),
|
|
342
|
+
new Promise<void>((resolve) => {
|
|
343
|
+
reapTimer = setTimeout(resolve, 100);
|
|
344
|
+
}),
|
|
345
|
+
]);
|
|
346
|
+
} finally {
|
|
347
|
+
if (reapTimer !== undefined) clearTimeout(reapTimer);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Qualification runs right after the server's "listening" line, on a runner
|
|
354
|
+
// that may be cold or CPU-contended, so a single shared deadline turned a slow
|
|
355
|
+
// but healthy server into a failed session (~10 s in). Each request gets its
|
|
356
|
+
// own deadline, and only transport-level failures are retried.
|
|
357
|
+
const QUALIFY_HEALTH_DEADLINE_MS = 2_000;
|
|
358
|
+
const QUALIFY_DOC_DEADLINE_MS = 4_000;
|
|
359
|
+
const QUALIFY_ATTEMPTS = 3;
|
|
360
|
+
const QUALIFY_BACKOFF_MS = [250, 500] as const;
|
|
361
|
+
const QUALIFY_DEADLINE_MESSAGE = "OpenCode health/doc deadline";
|
|
362
|
+
const BYTE_LIMIT_MESSAGE = "OpenCode observation byte limit exceeded";
|
|
363
|
+
|
|
364
|
+
// The only error class qualification retries: a request deadline, a
|
|
365
|
+
// fetch/connection failure while sending or reading, or an HTTP status >= 500.
|
|
366
|
+
// Everything else (an unhealthy body, a version or contract mismatch, a 4xx,
|
|
367
|
+
// malformed JSON, the byte limit) is NOT transport and is never retried: those
|
|
368
|
+
// are the identity and contract facts the guard exists to refuse, and a retry
|
|
369
|
+
// would only re-ask a server that already answered.
|
|
370
|
+
class OpenCodeQualificationTransportError extends Error {
|
|
371
|
+
override readonly name = "OpenCodeQualificationTransportError";
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export interface OpenCodeQualificationOptions {
|
|
375
|
+
readonly healthDeadlineMs?: number;
|
|
376
|
+
readonly docDeadlineMs?: number;
|
|
377
|
+
readonly backoffMs?: readonly number[];
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export async function qualifyOpenCodeServer(
|
|
381
|
+
url: string,
|
|
382
|
+
expected: OpenCodeObservedIdentity,
|
|
383
|
+
signal?: AbortSignal,
|
|
384
|
+
fetcher: typeof fetch = fetch,
|
|
385
|
+
options: OpenCodeQualificationOptions = {},
|
|
386
|
+
): Promise<{
|
|
387
|
+
serverVersion: string;
|
|
388
|
+
consumedContractSha256: string;
|
|
389
|
+
openApiDocumentSha256: string;
|
|
390
|
+
}> {
|
|
391
|
+
signal?.throwIfAborted();
|
|
392
|
+
const backoffMs = options.backoffMs ?? QUALIFY_BACKOFF_MS;
|
|
393
|
+
|
|
394
|
+
// One request, one deadline. The deadline covers the body read too, because
|
|
395
|
+
// a server that sends headers and then stalls is the same failure as one
|
|
396
|
+
// that never answers.
|
|
397
|
+
const attempt = async (
|
|
398
|
+
path: string,
|
|
399
|
+
deadlineMs: number,
|
|
400
|
+
): Promise<unknown> => {
|
|
401
|
+
const controller = new AbortController();
|
|
402
|
+
const abort = () => controller.abort(signal?.reason);
|
|
403
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
404
|
+
let deadlineHit = false;
|
|
405
|
+
const timer = setTimeout(() => {
|
|
406
|
+
deadlineHit = true;
|
|
407
|
+
controller.abort(new Error(QUALIFY_DEADLINE_MESSAGE));
|
|
408
|
+
}, deadlineMs);
|
|
409
|
+
// A caller abort is never a transport failure: rethrow it so the retry
|
|
410
|
+
// loop stops. A deadline or a connection error is retryable.
|
|
411
|
+
const transport = (error: unknown): unknown => {
|
|
412
|
+
if (signal?.aborted) return error;
|
|
413
|
+
if (deadlineHit)
|
|
414
|
+
return new OpenCodeQualificationTransportError(
|
|
415
|
+
QUALIFY_DEADLINE_MESSAGE,
|
|
416
|
+
);
|
|
417
|
+
if (error instanceof Error && error.message === BYTE_LIMIT_MESSAGE)
|
|
418
|
+
return error;
|
|
419
|
+
return new OpenCodeQualificationTransportError(
|
|
420
|
+
error instanceof Error ? error.message : String(error),
|
|
421
|
+
);
|
|
422
|
+
};
|
|
423
|
+
try {
|
|
424
|
+
let response: Response;
|
|
425
|
+
try {
|
|
426
|
+
response = await withAbort(
|
|
427
|
+
fetcher(new URL(path, url), { signal: controller.signal }),
|
|
428
|
+
controller.signal,
|
|
429
|
+
);
|
|
430
|
+
} catch (error) {
|
|
431
|
+
throw transport(error);
|
|
432
|
+
}
|
|
433
|
+
if (!response.ok || response.body === null) {
|
|
434
|
+
const message = `OpenCode qualification unavailable: ${path}`;
|
|
435
|
+
throw response.status >= 500
|
|
436
|
+
? new OpenCodeQualificationTransportError(message)
|
|
437
|
+
: new Error(message);
|
|
438
|
+
}
|
|
439
|
+
let text: string;
|
|
440
|
+
try {
|
|
441
|
+
text = await boundedText(
|
|
442
|
+
response.body,
|
|
443
|
+
2 * 1024 * 1024,
|
|
444
|
+
controller.signal,
|
|
445
|
+
);
|
|
446
|
+
} catch (error) {
|
|
447
|
+
throw transport(error);
|
|
448
|
+
}
|
|
449
|
+
return JSON.parse(text);
|
|
450
|
+
} finally {
|
|
451
|
+
clearTimeout(timer);
|
|
452
|
+
signal?.removeEventListener("abort", abort);
|
|
453
|
+
controller.abort();
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
const get = async (path: string, deadlineMs: number): Promise<unknown> => {
|
|
458
|
+
for (let n = 1; ; n++) {
|
|
459
|
+
try {
|
|
460
|
+
return await attempt(path, deadlineMs);
|
|
461
|
+
} catch (error) {
|
|
462
|
+
if (
|
|
463
|
+
signal?.aborted ||
|
|
464
|
+
!(error instanceof OpenCodeQualificationTransportError) ||
|
|
465
|
+
n >= QUALIFY_ATTEMPTS
|
|
466
|
+
)
|
|
467
|
+
throw error;
|
|
468
|
+
// The backoff listens to the caller too: an abort ends the wait at
|
|
469
|
+
// once instead of after the sleep.
|
|
470
|
+
await new Promise<void>((resolve) => {
|
|
471
|
+
const done = () => {
|
|
472
|
+
clearTimeout(sleep);
|
|
473
|
+
signal?.removeEventListener("abort", done);
|
|
474
|
+
resolve();
|
|
475
|
+
};
|
|
476
|
+
const sleep = setTimeout(
|
|
477
|
+
done,
|
|
478
|
+
backoffMs[n - 1] ?? backoffMs.at(-1) ?? 0,
|
|
479
|
+
);
|
|
480
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
481
|
+
});
|
|
482
|
+
signal?.throwIfAborted();
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
const health = record(
|
|
488
|
+
await get(
|
|
489
|
+
"/global/health",
|
|
490
|
+
options.healthDeadlineMs ?? QUALIFY_HEALTH_DEADLINE_MS,
|
|
491
|
+
),
|
|
492
|
+
);
|
|
493
|
+
if (health.healthy !== true || health.version !== expected.serverVersion)
|
|
494
|
+
throw new Error(
|
|
495
|
+
"OpenCode serving version differs from observed executable",
|
|
496
|
+
);
|
|
497
|
+
const document = await get(
|
|
498
|
+
"/doc",
|
|
499
|
+
options.docDeadlineMs ?? QUALIFY_DOC_DEADLINE_MS,
|
|
500
|
+
);
|
|
501
|
+
const consumedContractSha256 = consumedOpenCodeContractDigest(document);
|
|
502
|
+
if (
|
|
503
|
+
expected.sdkVersion !== "1.18.25" ||
|
|
504
|
+
expected.serverVersion !== "1.18.30" ||
|
|
505
|
+
consumedContractSha256 !== OPENCODE_CONSUMED_CONTRACT_SHA256
|
|
506
|
+
)
|
|
507
|
+
throw new Error("OpenCode served contract is not qualified");
|
|
508
|
+
return {
|
|
509
|
+
serverVersion: String(health.version),
|
|
510
|
+
consumedContractSha256,
|
|
511
|
+
openApiDocumentSha256: createHash("sha256")
|
|
512
|
+
.update(JSON.stringify(document))
|
|
513
|
+
.digest("hex"),
|
|
514
|
+
};
|
|
515
|
+
}
|