crysk 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +2 -1
  2. package/package.json +3 -2
  3. package/skills/crysk-ci-setup/assets/workflow.yml +3 -0
  4. package/src/asset-manifest.ts +11 -0
  5. package/src/assets.ts +1 -1
  6. package/src/ci/credential-refresh.ts +524 -0
  7. package/src/ci/crysk-secrets.ts +20 -6
  8. package/src/ci/force-comment.ts +14 -1
  9. package/src/ci/gates.ts +64 -21
  10. package/src/ci/outcome.ts +165 -15
  11. package/src/ci/platform-estimate.ts +111 -0
  12. package/src/ci/platform-trace.ts +30 -0
  13. package/src/ci/platform.ts +183 -5
  14. package/src/ci/reporter.ts +14 -4
  15. package/src/ci/setup.ts +96 -6
  16. package/src/ci/trace-bundle.ts +231 -27
  17. package/src/ci/trace-transcripts.ts +65 -0
  18. package/src/ci/trigger.ts +20 -4
  19. package/src/commands/ci-setup.ts +12 -3
  20. package/src/commands/doctor.ts +25 -23
  21. package/src/diversity/identity.ts +11 -1
  22. package/src/diversity/pipeline-integration.ts +19 -6
  23. package/src/doctor.ts +133 -4
  24. package/src/execution/contracts.ts +15 -3
  25. package/src/harness/materiality-judge.ts +153 -0
  26. package/src/harness/pipeline-plan.ts +133 -0
  27. package/src/harness/replay-rows.ts +172 -0
  28. package/src/harness/route-runner.ts +288 -0
  29. package/src/harness/single-step.ts +153 -0
  30. package/src/index.ts +1 -1
  31. package/src/model/catalog.ts +10 -7
  32. package/src/model/model-name.ts +14 -0
  33. package/src/model/profiles/claude.ts +34 -0
  34. package/src/model/profiles/openai.ts +44 -0
  35. package/src/model/profiles.ts +213 -0
  36. package/src/model/routing.ts +155 -50
  37. package/src/pr/ci-admission-gate.ts +2 -0
  38. package/src/pr/discovery.ts +18 -0
  39. package/src/pr/plan.ts +41 -2
  40. package/src/pr/review-pr.ts +43 -6
  41. package/src/pr/target.ts +67 -15
  42. package/src/production-runtime.ts +100 -13
  43. package/src/review/pipeline.ts +193 -58
  44. package/src/review/preflight.ts +91 -9
  45. package/src/review/prompt-set.ts +68 -0
  46. package/src/review/report.ts +4 -0
  47. package/src/review/review.ts +21 -11
  48. package/src/review/route-preflight.ts +117 -67
  49. package/src/review/run.ts +50 -4
  50. package/src/security/credential-broker.ts +21 -9
  51. package/src/security/oauth-providers.ts +101 -0
  52. package/src/transport-registry.ts +33 -0
  53. package/src/transports/opencode-sdk.ts +33 -1
  54. package/src/ui/config-edit.ts +9 -0
  55. package/src/ui/config.ts +1 -0
  56. package/src/ui/menu.ts +9 -2
  57. package/src/ui/plan.ts +8 -3
  58. package/src/updater.ts +21 -13
  59. package/src/wizard.ts +23 -0
@@ -42,6 +42,7 @@ import {
42
42
  import { PLATFORM_API_URL } from "./platform";
43
43
  import { decidePublication } from "./publish";
44
44
  import {
45
+ type AttemptStart,
45
46
  encodeTrace,
46
47
  type TraceAttemptInput,
47
48
  type TraceOutcome,
@@ -134,6 +135,7 @@ export function locateRunDir(
134
135
  const EVIDENCE = /^evidence\.(.+)\.attempt(\d+)\.json$/;
135
136
  const CAPTURE = /^evidence\.(.+)\.attempt(\d+)\.capture\.json$/;
136
137
  const TRANSCRIPT = /^trace\.(.+)\.attempt(\d+)\.jsonl$/;
138
+ const REQUEST = /^evidence\.(.+)\.attempt(\d+)\.request\.json$/;
137
139
 
138
140
  // Every step the run directory holds files for: pipeline.json's steps, and any
139
141
  // step whose evidence or transcript exists without a pipeline row (a run that
@@ -185,6 +187,16 @@ export function readRunSteps(
185
187
  }
186
188
  continue;
187
189
  }
190
+ // #511: the plan an attempt freezes at spawn, the one file a hunter still
191
+ // running at a cancel has written.
192
+ const request = REQUEST.exec(name);
193
+ if (request?.[1] !== undefined) {
194
+ const started = attemptStart(file);
195
+ if (started !== undefined) {
196
+ attemptOf(request[1], Number(request[2])).started = started;
197
+ }
198
+ continue;
199
+ }
188
200
  const evidence = EVIDENCE.exec(name);
189
201
  if (evidence?.[1] !== undefined) {
190
202
  const parsed = readJson(file);
@@ -252,6 +264,24 @@ export function readRunSteps(
252
264
  });
253
265
  }
254
266
 
267
+ // What a frozen request plan says of its attempt: its route's model and
268
+ // provider, and the file's time as the spawn's.
269
+ function attemptStart(file: string): AttemptStart | undefined {
270
+ const plan = readJson(file);
271
+ if (!isRecord(plan)) return undefined;
272
+ const route = isRecord(plan.route) ? plan.route : {};
273
+ const started: AttemptStart = {};
274
+ const atMs = mtimeMs(file);
275
+ if (atMs !== undefined) started.atMs = atMs;
276
+ if (typeof route.modelSnapshot === "string" && route.modelSnapshot !== "") {
277
+ started.model = route.modelSnapshot;
278
+ }
279
+ if (typeof route.provider === "string" && route.provider !== "") {
280
+ started.provider = route.provider;
281
+ }
282
+ return started;
283
+ }
284
+
255
285
  // An OpenCode capture's metadata: its conversation without content. The text
256
286
  // and the parsed capture are dropped on return.
257
287
  function captureMetadata(file: string): Conversation | undefined {
@@ -19,11 +19,46 @@
19
19
  // WHY ONLY BUILTINS: like the trigger, this runs before `bun install`. Keep
20
20
  // every import `node:` or `bun`, and `fetch` is the runtime's own.
21
21
 
22
- import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
22
+ import {
23
+ appendFileSync,
24
+ existsSync,
25
+ mkdirSync,
26
+ readFileSync,
27
+ writeFileSync,
28
+ } from "node:fs";
23
29
  import path from "node:path";
30
+ // Import-free, like the registry below.
31
+ import { readBrandEnv } from "../brand";
32
+ // The profile registry: data modules with no runtime imports of their own
33
+ // (test/architecture/profile-registry.test.ts), so the builtins-only rule still
34
+ // holds, and the step reads the same profiles the review runs.
35
+ import {
36
+ FALLBACK_PROFILE_ID,
37
+ MODEL_PROFILES,
38
+ profileModels,
39
+ } from "../model/profiles";
40
+ // A sibling with no imports of its own, so the builtins-only rule still holds.
41
+ import {
42
+ PLATFORM_ESTIMATE_CAPABILITY,
43
+ type PlatformEstimate,
44
+ parsePlatformEstimate,
45
+ serializePlatformEstimate,
46
+ } from "./platform-estimate";
24
47
 
25
48
  export const PLATFORM_API_URL = "https://api.crysk.dev";
26
49
 
50
+ // The engine accepts the person config's `profile` key (openai-profile S7). An
51
+ // engine without it refuses the key as unknown, so the platform sends a
52
+ // profile only to a run that names this capability.
53
+ export const PLATFORM_PROFILE_CAPABILITY = "profile";
54
+
55
+ // What this engine reads from the `/runs/token` response, as the platform's
56
+ // comma-separated `X-Crysk-Capabilities` list.
57
+ export const PLATFORM_CAPABILITIES = [
58
+ PLATFORM_ESTIMATE_CAPABILITY,
59
+ PLATFORM_PROFILE_CAPABILITY,
60
+ ].join(",");
61
+
27
62
  // The audience the platform verifies. An OIDC token minted for any other
28
63
  // audience is refused with a 401.
29
64
  const OIDC_AUDIENCE = "crysk";
@@ -106,6 +141,8 @@ export type PlatformTokenResult =
106
141
  // `full` or `metadata_only`; the connect step reads absence as metadata_only.
107
142
  // `traceContent` is present, and true, only when the platform sent exactly
108
143
  // `true`; the connect step reads absence as false.
144
+ // `estimate` is present only for the first connect step (refresh steps do not
145
+ // ask for one) and only when the platform sent a usable range.
109
146
  | {
110
147
  ok: true;
111
148
  githubToken: string;
@@ -114,6 +151,7 @@ export type PlatformTokenResult =
114
151
  dataMode?: PlatformDataMode;
115
152
  traceContent?: true;
116
153
  config?: PlatformConfig;
154
+ estimate?: PlatformEstimate;
117
155
  }
118
156
  // `message` names the HTTP status and the API's own `message` when there was
119
157
  // one. It never carries a token.
@@ -235,6 +273,12 @@ export async function exchangePlatformToken(
235
273
  headers: {
236
274
  Authorization: `Bearer ${oidc}`,
237
275
  "X-Crysk-Dispatch-Id": dispatchId,
276
+ // Only the first connect step asks: its estimate is the one the budget
277
+ // gate reads, the platform records each estimate it sends, and only
278
+ // that step reads the config a profile arrives in.
279
+ ...(deps.ignoreConfig === true
280
+ ? {}
281
+ : { "X-Crysk-Capabilities": PLATFORM_CAPABILITIES }),
238
282
  },
239
283
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
240
284
  });
@@ -252,6 +296,7 @@ export async function exchangePlatformToken(
252
296
  data_mode?: unknown;
253
297
  trace_content?: unknown;
254
298
  config?: unknown;
299
+ estimate?: unknown;
255
300
  };
256
301
  const {
257
302
  github_token: githubToken,
@@ -285,6 +330,12 @@ export async function exchangePlatformToken(
285
330
  [...secrets, githubToken, runToken],
286
331
  );
287
332
  }
333
+ // An estimate is advice: one that does not parse is dropped and the
334
+ // engine's own band decides, never a failed exchange.
335
+ const estimate =
336
+ deps.ignoreConfig === true
337
+ ? undefined
338
+ : parsePlatformEstimate(body.estimate);
288
339
  return {
289
340
  ok: true,
290
341
  githubToken,
@@ -300,6 +351,7 @@ export async function exchangePlatformToken(
300
351
  // an absent or malformed value sends metadata only.
301
352
  ...(body.trace_content === true ? { traceContent: true as const } : {}),
302
353
  ...(config.config === undefined ? {} : { config: config.config }),
354
+ ...(estimate === undefined ? {} : { estimate }),
303
355
  };
304
356
  } catch (error) {
305
357
  const detail = error instanceof Error ? error.message : String(error);
@@ -402,6 +454,13 @@ export async function runPlatformConnect(
402
454
  if (result.githubActor !== undefined) {
403
455
  deps.appendOutput(`github-actor=${result.githubActor}\n`);
404
456
  }
457
+ // Not a secret: two validated numbers and a basis. The run step's budget
458
+ // gate reads it as CRYSK_PLATFORM_ESTIMATE in place of the engine's band.
459
+ if (result.estimate !== undefined) {
460
+ deps.appendOutput(
461
+ `estimate=${serializePlatformEstimate(result.estimate)}\n`,
462
+ );
463
+ }
405
464
  // Present only when there is configuration to apply: the setup step and the
406
465
  // run step are gated on it, so a standalone run (no platform step, no
407
466
  // output) and an empty config both skip everything.
@@ -419,10 +478,21 @@ export async function runPlatformConnect(
419
478
  // platform `routing` is refused by the setup step's person parser.
420
479
  const person = result.config?.person ?? {};
421
480
  if (Object.keys(person).length > 0) {
422
- const models = person.models;
423
- const opencode =
424
- models !== undefined && JSON.stringify(models).includes('"opencode:');
425
- deps.appendOutput(`routing-opencode=${opencode}\n`);
481
+ const customAgents = customAgentsMayApply(
482
+ person,
483
+ result.config?.repo ?? {},
484
+ deps.env,
485
+ );
486
+ deps.appendOutput(
487
+ `routing-opencode=${personMayNeedOpenCode(person)}\n`,
488
+ );
489
+ // Whether any step may run on the Claude CLI (model-profiles S6). The
490
+ // Install Claude Code CLI step skips only on exactly `false`, so an
491
+ // absent output (a standalone run, an empty person layer, an older
492
+ // engine) installs it, as every run always did.
493
+ deps.appendOutput(
494
+ `routing-claude=${personMayNeedClaude(person, { customAgents })}\n`,
495
+ );
426
496
  }
427
497
  }
428
498
  } catch (error) {
@@ -435,6 +505,114 @@ export async function runPlatformConnect(
435
505
  return 0;
436
506
  }
437
507
 
508
+ // Whether the person layer's `models` may send any step to the Claude CLI.
509
+ // `false` only when it is proven not to: a `default` list, so no role falls
510
+ // through to the `claude` profile, and every entry of every role, fallbacks and
511
+ // the judge included, an `opencode:` model. With no `models.judge` the judge
512
+ // joins a plan only beside a step on its own backend (routing.ts), so it stays
513
+ // off Claude here whatever `materiality_gate` says. Anything else, a shape this
514
+ // walk does not know included, is `true`: the engine's parser stays the
515
+ // authority (this step cannot import it), and a wrong `false` would leave a
516
+ // Claude run without its CLI. src/doctor.ts reviewNeedsClaude answers the same
517
+ // question from the real route plan; test/ci/platform.test.ts holds both to
518
+ // one table.
519
+ //
520
+ // A role `models` does not set runs the person's `profile` (openai-profile S6),
521
+ // so with no `models.default` the answer is the profile's: `false` only for a
522
+ // registered profile whose every route is OpenCode. No profile is the fallback
523
+ // profile, `claude`; an unknown one is `true`, and the engine refuses it.
524
+ export function personModelsMayNeedClaude(
525
+ models: unknown,
526
+ profile?: unknown,
527
+ ): boolean {
528
+ if (models !== undefined) {
529
+ if (!isPlainObject(models)) return true;
530
+ for (const list of Object.values(models)) {
531
+ if (!Array.isArray(list) || list.length === 0) return true;
532
+ for (const entry of list) {
533
+ const name = isPlainObject(entry) ? entry.model : entry;
534
+ if (typeof name !== "string" || !name.startsWith("opencode:")) {
535
+ return true;
536
+ }
537
+ }
538
+ }
539
+ if (Array.isArray(models.default)) return false;
540
+ }
541
+ const routes = profileRouteModels(profile);
542
+ return routes === undefined || routes.some((m) => !m.startsWith("opencode:"));
543
+ }
544
+
545
+ // Whether the models in effect run any step on OpenCode: an `opencode:` model
546
+ // in `models`, or, for a role `models` does not set, in the profile's routes.
547
+ export function personMayNeedOpenCode(
548
+ person: Record<string, unknown>,
549
+ ): boolean {
550
+ const models = person.models;
551
+ if (models !== undefined && JSON.stringify(models).includes('"opencode:')) {
552
+ return true;
553
+ }
554
+ if (isPlainObject(models) && Array.isArray(models.default)) return false;
555
+ return (profileRouteModels(person.profile) ?? []).some((m) =>
556
+ m.startsWith("opencode:"),
557
+ );
558
+ }
559
+
560
+ // The registered profile's route models, or undefined for one this step does
561
+ // not know (the engine's parser refuses it).
562
+ function profileRouteModels(profile: unknown): string[] | undefined {
563
+ const id = profile ?? FALLBACK_PROFILE_ID;
564
+ if (typeof id !== "string" || !Object.hasOwn(MODEL_PROFILES, id)) {
565
+ return undefined;
566
+ }
567
+ const registered = MODEL_PROFILES[id];
568
+ return registered === undefined ? undefined : profileModels(registered);
569
+ }
570
+
571
+ // The person layer's answer: its `models`, plus the one other way a person
572
+ // layer names a model. A legacy `summary.model` (only "haiku" parses) becomes
573
+ // `models.summary: claude:haiku-latest` when `models.summary` is absent
574
+ // (preflight.ts parseSummaryConfig), so any `summary.model` keeps the CLI.
575
+ //
576
+ // `customAgents` (PR #521 R003): a custom agents_dir's frontmatter outranks
577
+ // the profile's seat (routing.ts resolveStepChoices), and this step cannot
578
+ // read those prompts, so with no `models.default` the CLI stays required.
579
+ export function personMayNeedClaude(
580
+ person: Record<string, unknown>,
581
+ context: { customAgents?: boolean } = {},
582
+ ): boolean {
583
+ if (isPlainObject(person.summary) && "model" in person.summary) return true;
584
+ const coversEveryRole =
585
+ isPlainObject(person.models) && Array.isArray(person.models.default);
586
+ if (context.customAgents === true && !coversEveryRole) return true;
587
+ return personModelsMayNeedClaude(person.models, person.profile);
588
+ }
589
+
590
+ // Whether a custom agents_dir may apply to this run: named in the platform's
591
+ // person or repo layer, in the checkout's own repo config (read raw, since this
592
+ // step runs before `bun install`), or in the AGENTS_DIR env. A repo config this
593
+ // step cannot read counts as one: the answer must never be a wrong `false`.
594
+ export function customAgentsMayApply(
595
+ person: Record<string, unknown>,
596
+ repo: Record<string, unknown>,
597
+ env: Readonly<Record<string, string | undefined>>,
598
+ ): boolean {
599
+ if ("agents_dir" in person || "agents_dir" in repo) return true;
600
+ if ((readBrandEnv(env, "AGENTS_DIR")?.value ?? "") !== "") return true;
601
+ const workspace = env.GITHUB_WORKSPACE ?? "";
602
+ if (workspace === "") return false;
603
+ for (const dir of [".crysk", ".prhero"]) {
604
+ const file = path.join(workspace, dir, "config.json");
605
+ if (!existsSync(file)) continue;
606
+ try {
607
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
608
+ return !isPlainObject(parsed) || "agents_dir" in parsed;
609
+ } catch {
610
+ return true;
611
+ }
612
+ }
613
+ return false;
614
+ }
615
+
438
616
  // Appends to the file the runner named in GITHUB_OUTPUT. Unset or empty is an
439
617
  // error, not a no-op: see runPlatformConnect.
440
618
  export function appendGithubOutput(
@@ -150,6 +150,9 @@ interface CiSkipSizeSummary {
150
150
  changedFiles: number;
151
151
  maxChangedLines: number;
152
152
  maxChangedFiles: number;
153
+ // A platform-connected run: the limits live in the Crysk dashboard, not in
154
+ // workflow inputs, so the summary says so like the comment does.
155
+ platformConnected?: true;
153
156
  }
154
157
 
155
158
  interface CiSkipBudgetSummary {
@@ -157,6 +160,8 @@ interface CiSkipBudgetSummary {
157
160
  prNumber: number;
158
161
  estimatedCostUsd: number;
159
162
  budgetUsd: number;
163
+ // A platform repository has no `--budget-usd` to raise (cryskai/platform#12).
164
+ platformConnected?: true;
160
165
  }
161
166
 
162
167
  interface CiSkipExcludedSummary {
@@ -327,8 +332,11 @@ function skipSizeLines(data: CiSkipSizeSummary): string[] {
327
332
  `| Changed lines | ${data.changedLines} (${sizeLimitText(data.maxChangedLines)}) |`,
328
333
  `| Changed files | ${data.changedFiles} (${sizeLimitText(data.maxChangedFiles)}) |`,
329
334
  "",
330
- "Crysk did not run to avoid reviewing an unbounded diff. Split the " +
331
- "PR or raise `max-changed-lines` / `max-changed-files`.",
335
+ data.platformConnected === true
336
+ ? "Crysk did not run to avoid reviewing an unbounded diff. Split the " +
337
+ "PR or raise the size limits in the Crysk dashboard."
338
+ : "Crysk did not run to avoid reviewing an unbounded diff. Split the " +
339
+ "PR or raise `max-changed-lines` / `max-changed-files`.",
332
340
  ];
333
341
  }
334
342
 
@@ -342,8 +350,10 @@ function skipBudgetLines(data: CiSkipBudgetSummary): string[] {
342
350
  "| --- | --- |",
343
351
  `| Estimated cost | ${usd(data.estimatedCostUsd)} (budget ${usd(data.budgetUsd)}) |`,
344
352
  "",
345
- "Crysk did not run to stay within the configured `--budget-usd` " +
346
- "ceiling.",
353
+ data.platformConnected === true
354
+ ? "To change what reviews cost, change the model setup in the Crysk dashboard."
355
+ : "Crysk did not run to stay within the configured `--budget-usd` " +
356
+ "ceiling.",
347
357
  ];
348
358
  }
349
359
 
package/src/ci/setup.ts CHANGED
@@ -51,6 +51,7 @@ import {
51
51
  CREDENTIALS_INPUT_LINE,
52
52
  type ErrorClass,
53
53
  MODELS_INPUT_LINE,
54
+ PROFILE_INPUT_LINE,
54
55
  type SetupRecord,
55
56
  } from "#ci/outcome";
56
57
  import { appendGithubOutput } from "#ci/platform";
@@ -74,6 +75,7 @@ import {
74
75
  parseModelName,
75
76
  parseModelsConfig,
76
77
  } from "#model/model-name";
78
+ import { MODEL_PROFILES, profileModels } from "#model/profiles";
77
79
  import { parseGlobalConfig, parseLocalConfig } from "#review/preflight";
78
80
  import { commandForms } from "../brand";
79
81
  import {
@@ -87,6 +89,7 @@ import {
87
89
  import { CliError } from "../errors";
88
90
  import { prheroLayout } from "../home-preflight";
89
91
  import { parseIgnoreFile } from "../ignore-file";
92
+ import { credentialKindForRoute } from "../runner-authority";
90
93
  import { resolveOpenCodeAuthPath } from "../security/credential-broker";
91
94
  import {
92
95
  type OpenCodeSecretManifestEntry,
@@ -280,7 +283,10 @@ ${lines}
280
283
  # repository variables. Unset, every role runs the default Claude model
281
284
  # and the subscription is tried first.
282
285
  ${MODELS_INPUT_LINE}
283
- ${CREDENTIALS_INPUT_LINE}`;
286
+ ${CREDENTIALS_INPUT_LINE}
287
+ # The model profile (claude or openai) from a repository variable.
288
+ # Unset, the claude profile. models still wins role by role.
289
+ ${PROFILE_INPUT_LINE}`;
284
290
  }
285
291
 
286
292
  export function generateCiWorkflowTemplate(
@@ -748,6 +754,9 @@ export interface MaterializeCiOpenCodeDataOptions {
748
754
  // unless a platform person layer exists, which wins whole.
749
755
  modelsInput?: string;
750
756
  credentialsInput?: string;
757
+ // The `profile` input (openai-profile S6), a profile id from
758
+ // vars.CRYSK_PROFILE, written beside them. The platform's layer wins whole.
759
+ profileInput?: string;
751
760
  home?: string;
752
761
  env?: Readonly<Record<string, string | undefined>>;
753
762
  // Platform mode: the person layer the Crysk platform returned (`{}` when it
@@ -795,8 +804,12 @@ const INPUT_CLASS: Record<"models" | "credentials", ErrorClass> = {
795
804
  models: { kind: "config-parse", source: "models-input" },
796
805
  credentials: { kind: "config-parse", source: "credentials-input" },
797
806
  };
807
+ const PROFILE_INPUT_CLASS: ErrorClass = {
808
+ kind: "config-parse",
809
+ source: "profile-input",
810
+ };
798
811
  const INPUTS_IGNORED_WARNING =
799
- "The models and credentials inputs are ignored: this repository is connected to the Crysk platform, whose model settings apply.";
812
+ "The models, credentials and profile inputs are ignored: this repository is connected to the Crysk platform, whose model settings apply.";
800
813
 
801
814
  // A crysk-secrets, models or credentials input the user configured wrongly. `message` is the
802
815
  // line stderr has always printed; `cls` and `detail` are what the record carries.
@@ -852,6 +865,61 @@ export function openCodeProvidersOfModels(models: unknown): string[] {
852
865
  return [...providers].sort();
853
866
  }
854
867
 
868
+ // The OpenCode providers the person layer's routing runs on (openai-profile
869
+ // S6): its models', plus, for the roles `models` does not set (no `default`),
870
+ // its `profile`'s. A profile the parser refused never reaches here.
871
+ export function openCodeProvidersOfPerson(person: {
872
+ models?: unknown;
873
+ profile?: unknown;
874
+ }): string[] {
875
+ const providers = new Set(openCodeProvidersOfModels(person.models));
876
+ const models = person.models as Record<string, unknown> | undefined;
877
+ const coversEveryRole = models !== undefined && models.default !== undefined;
878
+ const profile =
879
+ typeof person.profile === "string" &&
880
+ Object.hasOwn(MODEL_PROFILES, person.profile)
881
+ ? MODEL_PROFILES[person.profile]
882
+ : undefined;
883
+ if (!coversEveryRole && profile !== undefined) {
884
+ for (const model of profileModels(profile)) {
885
+ const parsed = parseModelName(model);
886
+ if (parsed.backend === "opencode") providers.add(parsed.provider);
887
+ }
888
+ }
889
+ return [...providers].sort();
890
+ }
891
+
892
+ // Whether an OpenCode route this run takes bills per token (cryskai/platform#12
893
+ // item 5): an auth file exists AND some OpenCode provider among the run's
894
+ // resolved routes, any step or fallback, binds an API key, by the same rule the
895
+ // run binds it with (credentialKindForRoute over the secret manifest's names, the
896
+ // provider literal without one). `providers` comes from the run's own route plan,
897
+ // so every source routing reads counts (`models`, `--model`, `--scout-model`, a
898
+ // spec model, a prompt's frontmatter, the engine's defaults). Undefined means the
899
+ // routes could not be resolved here: the auth file decides, the old rule, which
900
+ // keeps the ceiling. The file alone is not enough otherwise: it also exists for a
901
+ // ChatGPT subscription, after an earlier run on a runner whose HOME persists, or
902
+ // from a local `opencode auth login`. And no file means no credential for a
903
+ // per-token route, as before: a free `opencode/*` model stays unmetered.
904
+ export function openCodeRoutesBillMetered(input: {
905
+ providers: readonly string[] | undefined;
906
+ authFilePresent: boolean;
907
+ openCodeSecretNames: readonly string[] | undefined;
908
+ }): boolean {
909
+ if (!input.authFilePresent) return false;
910
+ if (input.providers === undefined) return true;
911
+ return input.providers.some(
912
+ (provider) =>
913
+ credentialKindForRoute(
914
+ "opencode",
915
+ provider,
916
+ {},
917
+ false,
918
+ input.openCodeSecretNames,
919
+ ) === "provider_api_token",
920
+ );
921
+ }
922
+
855
923
  interface OpenCodeAuthAssembly {
856
924
  // provider id -> its auth.json record.
857
925
  readonly records: Record<string, Record<string, unknown>>;
@@ -921,6 +989,23 @@ function assembleOpenCodeAuth(
921
989
  return { records, manifest, notices, problems };
922
990
  }
923
991
 
992
+ // The `profile` input: a bare id, not JSON, checked by the person parser like
993
+ // the key in ~/.crysk/config.json. Returns undefined for an empty input.
994
+ function readProfileInput(raw: string | undefined): string | undefined {
995
+ if (raw === undefined || raw.trim() === "") return undefined;
996
+ const profile = raw.trim();
997
+ try {
998
+ parseGlobalConfig(JSON.stringify({ profile }), "the profile input");
999
+ } catch (error) {
1000
+ throw new SetupInputError(
1001
+ PROFILE_INPUT_CLASS,
1002
+ "the profile input is not a known profile (the setup step's log names the known ones)",
1003
+ messageOf(error),
1004
+ );
1005
+ }
1006
+ return profile;
1007
+ }
1008
+
924
1009
  // One of the two inputs (D1), read the way the person parser reads that key in
925
1010
  // ~/.crysk/config.json: the value is the key's own object, checked under that
926
1011
  // key alone. Returns undefined for an empty input.
@@ -992,9 +1077,11 @@ export async function materializeCiOpenCodeData(
992
1077
  personBody = { ...platformPerson };
993
1078
  // The inputs are not even read: a value the platform overrides is not this
994
1079
  // run's configuration, so a malformed one must not fail it.
995
- const inputGiven = [options.modelsInput, options.credentialsInput].some(
996
- (raw) => raw !== undefined && raw.trim() !== "",
997
- );
1080
+ const inputGiven = [
1081
+ options.modelsInput,
1082
+ options.credentialsInput,
1083
+ options.profileInput,
1084
+ ].some((raw) => raw !== undefined && raw.trim() !== "");
998
1085
  if (inputGiven) warnings.push(INPUTS_IGNORED_WARNING);
999
1086
  } else {
1000
1087
  const models = readConfigInput(options.modelsInput, "models");
@@ -1002,13 +1089,15 @@ export async function materializeCiOpenCodeData(
1002
1089
  options.credentialsInput,
1003
1090
  "credentials",
1004
1091
  );
1092
+ const profile = readProfileInput(options.profileInput);
1005
1093
  personBody = {
1006
1094
  ...(models === undefined ? {} : { models }),
1007
1095
  ...(credentials === undefined ? {} : { credentials }),
1096
+ ...(profile === undefined ? {} : { profile }),
1008
1097
  };
1009
1098
  }
1010
1099
 
1011
- const providers = openCodeProvidersOfModels(personBody.models);
1100
+ const providers = openCodeProvidersOfPerson(personBody);
1012
1101
  const notices: string[] = [];
1013
1102
  const assembly =
1014
1103
  options.cryskSecrets === undefined
@@ -1194,6 +1283,7 @@ async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
1194
1283
  env: deps.env,
1195
1284
  modelsInput: deps.env.MODELS_INPUT ?? "",
1196
1285
  credentialsInput: deps.env.CREDENTIALS_INPUT ?? "",
1286
+ profileInput: deps.env.PROFILE_INPUT ?? "",
1197
1287
  ...(platformMode ? { platformPerson: platform?.person ?? {} } : {}),
1198
1288
  ...(cryskSecrets === undefined ? {} : { cryskSecrets }),
1199
1289
  });