@defrex/autobuild 1.1.0 → 1.2.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 (114) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +140 -10
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +119 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/architecture.md +107 -8
  7. package/docs/build-store.md +3 -41
  8. package/docs/cli.md +14 -0
  9. package/docs/configuration-overview.md +111 -0
  10. package/docs/configuration.md +260 -141
  11. package/docs/dispatcher-hosting.md +18 -33
  12. package/docs/intake.md +2 -0
  13. package/docs/merge-policy.md +1 -3
  14. package/docs/operating.md +1 -2
  15. package/docs/operator-api.md +100 -47
  16. package/docs/operator-surfaces.md +3 -20
  17. package/docs/overview.md +1 -1
  18. package/docs/plugin-authoring.md +21 -0
  19. package/docs/remote-store-protocol.md +198 -89
  20. package/docs/remote-ticket-protocol.md +29 -49
  21. package/docs/seams.md +8 -8
  22. package/docs/setup.md +34 -129
  23. package/docs/ticket-sources.md +18 -0
  24. package/docs/troubleshooting.md +7 -11
  25. package/docs/upgrading.md +1 -1
  26. package/docs/workspaces.md +4 -4
  27. package/package.json +14 -5
  28. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  29. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  30. package/packages/core/src/accounts/local-credentials.ts +194 -0
  31. package/packages/core/src/accounts/local-inference.ts +106 -0
  32. package/packages/core/src/accounts/local-owner.ts +123 -0
  33. package/packages/core/src/accounts/sensitive.ts +2 -0
  34. package/packages/core/src/cli/accounts.ts +147 -0
  35. package/packages/core/src/cli/binary.ts +3 -1
  36. package/packages/core/src/cli/connect.ts +3 -3
  37. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  38. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  39. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  40. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  41. package/packages/core/src/cli/dispatch.ts +71 -2
  42. package/packages/core/src/cli/help.ts +16 -0
  43. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  44. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  45. package/packages/core/src/cli/init-validation.ts +160 -18
  46. package/packages/core/src/cli/main.ts +44 -0
  47. package/packages/core/src/cli/publication-settlement.ts +4 -1
  48. package/packages/core/src/cli/secrets.ts +173 -0
  49. package/packages/core/src/cli/store-opening.ts +11 -1
  50. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  51. package/packages/core/src/cli/watch.ts +3 -1
  52. package/packages/core/src/config/accounts.ts +101 -0
  53. package/packages/core/src/config/live.ts +14 -1
  54. package/packages/core/src/config/roles.ts +54 -3
  55. package/packages/core/src/config/schema.ts +60 -0
  56. package/packages/core/src/events/compatibility.ts +2 -1
  57. package/packages/core/src/events/payloads.ts +3 -0
  58. package/packages/core/src/events/repository.ts +2 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +3 -0
  60. package/packages/core/src/kernel/reducer.ts +4 -1
  61. package/packages/core/src/operator/index.ts +2 -0
  62. package/packages/core/src/operator/protocol.ts +6 -0
  63. package/packages/core/src/operator/registry.ts +22 -1
  64. package/packages/core/src/operator/tickets.ts +25 -4
  65. package/packages/core/src/plugins/manifest.ts +2 -1
  66. package/packages/core/src/ports/runner/account-env.ts +88 -0
  67. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  68. package/packages/core/src/ports/runner/claude.ts +26 -2
  69. package/packages/core/src/ports/runner/codex.ts +63 -31
  70. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  71. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  72. package/packages/core/src/ports/runner/routing.ts +35 -4
  73. package/packages/core/src/ports/tickets/contract.ts +58 -0
  74. package/packages/core/src/ports/tickets/tree.ts +1 -1
  75. package/packages/core/src/ports/types.ts +28 -7
  76. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  77. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  78. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  79. package/packages/core/src/ports/workspace/create.ts +2 -0
  80. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  81. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  82. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  83. package/packages/core/src/processes/build-runner.ts +32 -1
  84. package/packages/core/src/processes/dispatcher.ts +23 -0
  85. package/packages/core/src/processes/execution-settlement.ts +21 -3
  86. package/packages/core/src/processes/harvest-runner.ts +68 -8
  87. package/packages/core/src/project-secrets.ts +105 -0
  88. package/packages/core/src/secret-name.ts +41 -0
  89. package/packages/core/src/store/account-redaction.ts +156 -0
  90. package/packages/core/src/store/contract.ts +3 -1
  91. package/packages/core/src/store/reducer-value-shapes.json +2889 -2781
  92. package/packages/core/src/store/remote/client.ts +42 -47
  93. package/packages/core/src/store/remote/compatibility.ts +18 -0
  94. package/packages/core/src/testing/dispatch-read-budget.ts +122 -0
  95. package/packages/core/src/testing/index.ts +1 -0
  96. package/packages/core/src/testing/reduced-read-budget.ts +47 -0
  97. package/skills/guide/SKILL.md +120 -30
  98. package/skills/guide/references/accounts.md +119 -0
  99. package/skills/guide/references/merge-policy.md +1 -3
  100. package/skills/guide/references/operator-api.md +100 -47
  101. package/skills/guide/references/plugin-authoring.md +21 -0
  102. package/skills/guide/references/remote-store-protocol.md +198 -89
  103. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  104. package/skills/guide/references/setup.md +34 -129
  105. package/skills/harvest/SKILL.md +3 -1
  106. package/skills/harvest-review/SKILL.md +3 -1
  107. package/skills/operate/SKILL.md +5 -6
  108. package/skills/spec/SKILL.md +1 -1
  109. package/skills/tickets/SKILL.md +3 -2
  110. package/templates/hosted-service/package.json +2 -2
  111. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  112. package/docs/hosted-dispatcher.md +0 -278
  113. package/docs/hosted-service.md +0 -304
  114. package/docs/mcp.md +0 -150
@@ -1,3 +1,6 @@
1
+ import { LocalCredentials } from '../accounts/local-credentials'
2
+ import { LocalAccountOwner, renewLocalAccounts } from '../accounts/local-owner'
3
+ import { accountRedactor, redactAccountStore } from '../store/account-redaction'
1
4
  import { capturedBuildConfig } from '../processes/verify-cycle-config'
2
5
  import { ForgeRequestDeferred } from '../ports/forge-request-context'
3
6
  import { migrationIdentity } from '../kernel/ticket-migrations'
@@ -249,7 +252,10 @@ export function slugNamingPrompt(spec: string): string {
249
252
  function definedEnv(env: Record<string, string | undefined>): Record<string, string> {
250
253
  const defined: Record<string, string> = {}
251
254
  for (const [key, value] of Object.entries(env)) {
252
- if (value !== undefined && !['AB_TOKEN', 'AB_TICKET_TOKEN', 'AB_TICKET_URL'].includes(key))
255
+ if (
256
+ value !== undefined &&
257
+ !['AB_TOKEN', 'AB_TICKET_TOKEN', 'AB_TICKET_URL', 'AB_PROJECT_SECRETS_KEY'].includes(key)
258
+ )
253
259
  defined[key] = value
254
260
  }
255
261
  return defined
@@ -294,6 +300,9 @@ interface ResumePrompt {
294
300
  /** The real adapters the loop drives — resolved by `wire` (default: the
295
301
  * production ports; tests inject fakes). */
296
302
  export interface DispatchWiring {
303
+ renewAccounts?: (authority: { repo: string; run: string }) => Promise<void>
304
+ releaseAccounts?: () => Promise<void>
305
+
297
306
  credentialIssuer?: typeof delegateCredential
298
307
  store: BuildStore
299
308
  tickets: TicketSource
@@ -517,8 +526,12 @@ async function defaultWire(
517
526
  remoteBranchHead: async (branch: string): Promise<string | undefined> => {
518
527
  const remoteBranchSha = forge.remoteBranchSha
519
528
  if (remoteBranchSha === undefined) return undefined
529
+ // The provider pushes through the guest, bypassing the forge's read
530
+ // invalidation, so each head read takes a fresh scope: a post-push
531
+ // readback must never replay the tick's pre-push answer.
532
+ const read = () => remoteBranchSha.call(forge, branch)
520
533
  try {
521
- return await remoteBranchSha.call(forge, branch)
534
+ return await (forge.withReadScope ? forge.withReadScope(read) : read())
522
535
  } catch (error) {
523
536
  if (error instanceof GitHubApiError && error.status === 404) return undefined
524
537
  throw error
@@ -536,6 +549,51 @@ async function defaultWire(
536
549
  plugins,
537
550
  )
538
551
  const { runtimes } = createProductionRuntimes()
552
+ if (opts.env.AB_PROJECT_SECRETS_FAILED === '1')
553
+ for (const name of JSON.parse(opts.env.AB_PROJECT_SECRETS_UNAVAILABLE ?? '[]') as string[])
554
+ delete opts.env[name]
555
+ let accounts = config.accounts
556
+ const credentials = new LocalCredentials(join(state.checkout, '.autobuild'))
557
+ const owner = new LocalAccountOwner(credentials)
558
+ const claimed = new Set<string>()
559
+ let renewal: Promise<void> | undefined
560
+ let accountTimer: ReturnType<typeof setInterval> | undefined
561
+ const renewAccounts = async (authority: { repo: string; run: string }) => {
562
+ if (opts.repository || !Object.values(accounts).some((a) => a.kind === 'chatgpt-subscription'))
563
+ return
564
+ if (!accountTimer) {
565
+ accountTimer = setInterval(() => {
566
+ void (async () => {
567
+ const held = await opened.store.getRepo(authority.repo)
568
+ if (
569
+ held?.lease?.holder !== authority.run ||
570
+ Date.parse(held.lease.expiresAt) <= Date.now()
571
+ ) {
572
+ await releaseAccounts()
573
+ return
574
+ }
575
+ await renewAccounts(authority)
576
+ })().catch(() => {})
577
+ }, 15000)
578
+ accountTimer.unref()
579
+ }
580
+ if (renewal) return renewal
581
+ renewal = renewLocalAccounts(owner, accounts, opts.env, claimed).finally(() => {
582
+ renewal = undefined
583
+ })
584
+ return renewal
585
+ }
586
+ const releaseAccounts = async () => {
587
+ if (accountTimer) clearInterval(accountTimer)
588
+ accountTimer = undefined
589
+ await renewal
590
+ for (const name of claimed) owner.release(name)
591
+ claimed.clear()
592
+ }
593
+ opened.store = redactAccountStore(
594
+ opened.store,
595
+ accountRedactor(() => accounts, opts.env),
596
+ )
539
597
  let runtimeReferences = effectiveRuntimeReferences(config)
540
598
  // A local override relocates the whole tree. Remote stores still need local
541
599
  // scratch beneath the repository default. Plugin factories receive only
@@ -549,6 +607,7 @@ async function defaultWire(
549
607
  env: opts.env,
550
608
  storeRef: opened.storeRef,
551
609
  runtimeReferences: () => runtimeReferences,
610
+ accounts: () => accounts,
552
611
  sandboxSetupCommand: config.commands.setup,
553
612
  sandboxRoot: resolve(join(opened.localStateRoot, 'orchestrator-sandboxes')),
554
613
  sandboxEnvironmentVariables: config.orchestrator.sandbox.environmentVariables,
@@ -571,6 +630,8 @@ async function defaultWire(
571
630
 
572
631
  return {
573
632
  store: opened.store,
633
+ renewAccounts,
634
+ releaseAccounts,
574
635
  tickets,
575
636
  forge,
576
637
  workspaces: workspaceRuntime.provider,
@@ -586,6 +647,7 @@ async function defaultWire(
586
647
  clock: systemClock,
587
648
  plugins,
588
649
  updateRuntimeReferences: (effectiveConfig) => {
650
+ accounts = effectiveConfig.accounts
589
651
  runtimeReferences = effectiveRuntimeReferences(effectiveConfig)
590
652
  },
591
653
  }
@@ -810,6 +872,7 @@ class DispatchLoop {
810
872
  signal,
811
873
  ...(resolvedSlug.model !== undefined ? { model: resolvedSlug.model } : {}),
812
874
  args: resolvedSlug.args,
875
+ account: resolvedSlug.account,
813
876
  })
814
877
  return result.text
815
878
  }
@@ -1206,10 +1269,12 @@ class DispatchLoop {
1206
1269
  settings.intake || (!this.dashboard && this.opts.kernelRunId === undefined)
1207
1270
  ? undefined
1208
1271
  : await this.dispatcher.observeReady({ viewRefreshed: true })
1272
+ await this.wiring.renewAccounts?.({ repo: this.repoIdentity, run: this.runId })
1209
1273
  const report = await this.dispatcher.tick({
1210
1274
  resumeCurrent,
1211
1275
  viewRefreshed: true,
1212
1276
  acceptNewWork: settings.intake,
1277
+ observationOnly: this.opts.env.AB_PROJECT_SECRETS_FAILED === '1',
1213
1278
  defaultAutoMerge: settings.defaultAutoMerge,
1214
1279
  autoMergeUser: buildControlUser(this.opts.env),
1215
1280
  // Invocation bound forwarded into the tick: per-item loops inside the
@@ -3080,6 +3145,7 @@ class DispatchLoop {
3080
3145
  publication: this.wiring.workspaces.publication,
3081
3146
  forge: this.wiring.forge,
3082
3147
  workspacePath: this.opts.targetRepo,
3148
+ checkoutless: this.opts.repository !== undefined,
3083
3149
  exec: this.opts.exec,
3084
3150
  ids: this.wiring.ids,
3085
3151
  runId: this.runId,
@@ -4184,6 +4250,7 @@ class DispatchLoop {
4184
4250
  cacheId: request.cacheId,
4185
4251
  target: request.target,
4186
4252
  }
4253
+ await this.wiring.releaseAccounts?.()
4187
4254
  let acceptanceError: unknown
4188
4255
  try {
4189
4256
  await this.repoView.appendRepo(this.repoIdentity, {
@@ -4364,6 +4431,7 @@ class DispatchLoop {
4364
4431
  this.wiring.runtimes,
4365
4432
  config.roles,
4366
4433
  config.policy.sessionBudgetSeconds,
4434
+ config.accounts,
4367
4435
  )
4368
4436
  const deadline = new Date(
4369
4437
  Date.parse(retirement.startedAt) + config.policy.upgradeDrainSeconds * 1000,
@@ -5149,6 +5217,7 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
5149
5217
  // view; leave the reduced state behind so the next cold process reads
5150
5218
  // only what is newer than it.
5151
5219
 
5220
+ await wiring.releaseAccounts?.()
5152
5221
  if (resolvedOpts.wire === undefined) await wiring.store.close()
5153
5222
  }
5154
5223
  }
@@ -71,6 +71,22 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
71
71
  'locally. --validate cannot be combined with --force.',
72
72
  ]),
73
73
  },
74
+ {
75
+ name: 'accounts',
76
+ summary: 'Sign in with ChatGPT for a Codex billing account',
77
+ audience: 'human',
78
+ detail: page([
79
+ 'Usage: ab accounts login NAME [--local|--project]',
80
+ 'Runs outside sessions. Local stores protected repository credentials for the dispatcher. Project transfers credentials to the connected refreshing secret and retains none locally. The browser completes OpenAI authorization; tokens are never printed.',
81
+ ]),
82
+ },
83
+ {
84
+ name: 'secrets',
85
+ summary: 'Manage write-only secrets for a connected project',
86
+ audience: 'human',
87
+ detail:
88
+ 'Usage: ab secrets list [--json] | ab secrets set NAME | ab secrets remove NAME. Uses the saved owner credential from ab connect. Set reads hidden terminal input or redirected stdin; values are never returned. List reports owner, set time, fingerprint, status and last supply time. Runs outside sessions.',
89
+ },
74
90
  {
75
91
  name: 'connect',
76
92
  audience: 'human',
@@ -17,6 +17,21 @@ export async function validateRemoteReadiness(
17
17
  ctx: WorkspaceReadinessContext,
18
18
  ): Promise<InitValidationReport> {
19
19
  const vercel = ctx.providerConfig as VercelSandboxConfig
20
+ const hostChecks = Object.entries(ctx.accounts ?? {}).map(([name, descriptor]) => ({
21
+ name: `host account ${JSON.stringify(name)}`,
22
+ status: ctx.env[descriptor.credentialEnv] ? ('pass' as const) : ('fail' as const),
23
+ detail: ctx.env[descriptor.credentialEnv]
24
+ ? `${descriptor.credentialEnv} is present`
25
+ : `${descriptor.credentialEnv} is missing; ${descriptor.kind === 'claude-subscription' ? 'run claude setup-token and set the dispatcher variable' : 'provision the Kimi membership key'}`,
26
+ }))
27
+ if (hostChecks.some((check) => check.status === 'fail'))
28
+ return {
29
+ provider: 'vercel-sandbox',
30
+ context: 'Vercel Sandbox',
31
+ checks: hostChecks,
32
+ exitCode: 1,
33
+ }
34
+
20
35
  const remoteLine = await gitText(
21
36
  ctx.exec,
22
37
  ctx.repo,
@@ -69,6 +84,7 @@ export async function validateRemoteReadiness(
69
84
  exec: ctx.exec,
70
85
  ...(ctx.packageArchive !== undefined ? { packageArchive: ctx.packageArchive } : {}),
71
86
  runtimeReferences: [...ctx.runtimeReferences],
87
+ accounts: ctx.accounts,
72
88
  ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
73
89
  onSandbox: (name) => ctx.stdout(`Disposable Vercel Sandbox: ${name} (active)`),
74
90
  })
@@ -103,8 +119,13 @@ export async function validateRemoteReadiness(
103
119
  ? 'no workspace.config.provisioning steps declared'
104
120
  : `completed: ${remote.provisioning.join(', ')}`,
105
121
  },
122
+ ...hostChecks,
106
123
  ...guest.checks,
107
124
  ],
108
- exitCode: guest.checks.some((check) => check.status === 'fail') ? 1 : 0,
125
+ exitCode:
126
+ guest.checks.some((check) => check.status === 'fail') ||
127
+ Object.values(ctx.accounts ?? {}).some((account) => !ctx.env[account.credentialEnv])
128
+ ? 1
129
+ : 0,
109
130
  }
110
131
  }
@@ -1,3 +1,4 @@
1
+ import { sensitiveAccountValues } from '../accounts/sensitive'
1
2
  /**
2
3
  * Readiness-probe helpers shared by the local-worktree and remote validation
3
4
  * paths (AUT-516). Moved out of `cli/init-validation.ts` so the remote
@@ -39,7 +40,10 @@ export function createReadinessRedactor(
39
40
  ].sort((left, right) => right.length - left.length)
40
41
  return (value) => {
41
42
  let text = message(value)
42
- for (const secret of secrets) text = text.split(secret).join('[REDACTED]')
43
+ for (const secret of [...sensitiveAccountValues, ...secrets].sort(
44
+ (a, b) => b.length - a.length,
45
+ ))
46
+ text = text.split(secret).join('[REDACTED]')
43
47
  return text
44
48
  }
45
49
  }
@@ -1,3 +1,8 @@
1
+ import { LocalCredentials } from '../accounts/local-credentials'
2
+ import { LocalAccountOwner } from '../accounts/local-owner'
3
+ import { abSecrets } from './secrets'
4
+ import type { ProjectSecretMetadata } from '../project-secrets'
5
+ import { accountRemedy } from '../config/accounts'
1
6
  import { createForge } from '../ports/forge/create'
2
7
  import {
3
8
  inspectForgeReadiness,
@@ -73,15 +78,17 @@ function effectiveTargets(
73
78
  ): Array<{ runtime: string; models: string[] }> {
74
79
  // Preserve eager registry/model/argument validation, but probe only routes
75
80
  // the pipeline can consume rather than every declared role table.
76
- createRuntimeResolver(runtimes, config.roles, config.policy.sessionBudgetSeconds)
77
- return effectiveRuntimeReferences(config).map((group) => {
81
+ createRuntimeResolver(runtimes, config.roles, config.policy.sessionBudgetSeconds, config.accounts)
82
+ return effectiveRuntimeReferences(config).flatMap((group) => {
83
+ const selected = Object.keys(config.accounts).length ? group.legacyAuthentication : group
84
+ if (selected === undefined) return []
78
85
  const defaultModel = runtimes[group.runtime]?.defaultModel
79
86
  return {
80
87
  runtime: group.runtime,
81
88
  models: [
82
89
  ...new Set([
83
- ...group.models,
84
- ...(group.usesRuntimeDefaultModel && defaultModel !== undefined ? [defaultModel] : []),
90
+ ...selected.models,
91
+ ...(selected.usesRuntimeDefaultModel && defaultModel !== undefined ? [defaultModel] : []),
85
92
  ]),
86
93
  ].sort(),
87
94
  }
@@ -124,10 +131,10 @@ export async function runGuestReadinessProbe(opts: {
124
131
  // check detail now see `[REDACTED]` there. Providers without a
125
132
  // `guestEnvNames`/`configSchema` declaration fall back to the name-heuristic
126
133
  // redaction only.
127
- const redact = createReadinessRedactor(
128
- opts.env,
129
- providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : [],
130
- )
134
+ const redact = createReadinessRedactor(opts.env, [
135
+ ...(providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : []),
136
+ ...Object.values(config.accounts).map((account) => account.credentialEnv),
137
+ ])
131
138
  try {
132
139
  const setup = config.commands.setup
133
140
  if (opts.signal?.aborted) throw opts.signal.reason ?? new Error('validation cancelled')
@@ -221,6 +228,57 @@ export async function runGuestReadinessProbe(opts: {
221
228
  : `fix workspace.config.runtimeProvisioning.${runtime}${preflightOnly ? '.preflight' : ''} and expose API credential names in workspace.config.environmentVariables`
222
229
 
223
230
  try {
231
+ for (const [name, descriptor] of Object.entries(config.accounts)) {
232
+ checks.push({
233
+ name: `credential ${JSON.stringify(name)}`,
234
+ status: opts.env[descriptor.credentialEnv] ? 'pass' : 'warning',
235
+ detail: `${descriptor.credentialEnv} is ${opts.env[descriptor.credentialEnv] ? 'present' : 'absent'}${!opts.env[descriptor.credentialEnv] && descriptor.kind === 'claude-subscription' ? '; run claude setup-token for remote use' : ''}`,
236
+ })
237
+ const account = { name, descriptor }
238
+ const runtime = descriptor.kind === 'chatgpt-subscription' ? 'codex' : 'claude'
239
+ if (
240
+ descriptor.kind === 'chatgpt-subscription' &&
241
+ (JSON.parse(opts.env.AB_CHATGPT_HOSTED_READINESS ?? '[]') as string[]).includes(name)
242
+ ) {
243
+ checks.push({
244
+ name: `account ${JSON.stringify(name)}`,
245
+ status: 'pass',
246
+ detail: 'Hosted metadata readiness only; the first hosted build is the live check',
247
+ })
248
+ continue
249
+ }
250
+ const completion = runtimes[runtime]?.oneShot
251
+ try {
252
+ if (!completion) throw new Error(`${runtime} runtime has no model probe capability`)
253
+ await completion.complete({
254
+ prompt: 'Reply only OK.',
255
+ cwd: opts.repo,
256
+ env: Object.fromEntries(
257
+ Object.entries(opts.env).filter(
258
+ (entry): entry is [string, string] => entry[1] !== undefined,
259
+ ),
260
+ ),
261
+ account,
262
+ model:
263
+ descriptor.kind === 'kimi-code' ? 'kimi-for-coding' : runtimes[runtime]?.defaultModel,
264
+ signal: AbortSignal.any([
265
+ AbortSignal.timeout(30_000),
266
+ ...(opts.signal ? [opts.signal] : []),
267
+ ]),
268
+ })
269
+ checks.push({
270
+ name: `account ${JSON.stringify(name)}`,
271
+ status: 'pass',
272
+ detail: `minimal ${runtime} model request succeeded`,
273
+ })
274
+ } catch (error) {
275
+ checks.push({
276
+ name: `account ${JSON.stringify(name)}`,
277
+ status: 'fail',
278
+ detail: `${redact(error)}; ${accountRemedy(account)}`,
279
+ })
280
+ }
281
+ }
224
282
  for (const target of effectiveTargets(config, runtimes)) {
225
283
  if (opts.signal?.aborted) throw opts.signal.reason ?? new Error('validation cancelled')
226
284
  const probe = runtimes[target.runtime]?.initUsable
@@ -378,7 +436,8 @@ function hostPreflight(config: Config, env: Record<string, string | undefined>):
378
436
  throw new Error('ticket source "linear" requires LINEAR_API_KEY')
379
437
  }
380
438
 
381
- export async function validateInitReadiness(opts: {
439
+ async function validateInitReadinessInner(opts: {
440
+ resolvedRepo?: string
382
441
  targetRepo: string
383
442
  env: Record<string, string | undefined>
384
443
  /** The raw launcher process environment, alongside the dotenv-augmented
@@ -396,7 +455,7 @@ export async function validateInitReadiness(opts: {
396
455
  }): Promise<InitValidationReport> {
397
456
  const exec = opts.exec ?? spawnExec
398
457
  if (opts.signal?.aborted) throw opts.signal.reason ?? new Error('validation cancelled')
399
- const repo = await resolveMainRepo(opts.targetRepo, exec)
458
+ const repo = opts.resolvedRepo ?? (await resolveMainRepo(opts.targetRepo, exec))
400
459
  const configPath = join(repo, 'autobuild.toml')
401
460
  const configBytes = await readFile(configPath, 'utf8')
402
461
  const config = await loadConfig(configPath)
@@ -432,10 +491,10 @@ export async function validateInitReadiness(opts: {
432
491
  builtinCaps?.configSchema !== undefined
433
492
  ? builtinCaps.configSchema.parse(config.workspace.config)
434
493
  : undefined
435
- let redact = createReadinessRedactor(
436
- opts.env,
437
- providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : [],
438
- )
494
+ let redact = createReadinessRedactor(opts.env, [
495
+ ...(providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : []),
496
+ ...Object.values(config.accounts).map((account) => account.credentialEnv),
497
+ ])
439
498
  let caps: WorkspaceProviderCapabilities | undefined
440
499
  let assigneeLine: string | undefined
441
500
  let forgeChecks: ForgeReadinessCheck[] = readinessChecks(
@@ -480,10 +539,12 @@ export async function validateInitReadiness(opts: {
480
539
  if (caps?.configSchema !== undefined)
481
540
  providerConfig = caps.configSchema.parse(config.workspace.config)
482
541
  if (caps?.guestEnvNames !== undefined)
483
- redact = createReadinessRedactor(
484
- opts.env,
485
- caps.guestEnvNames(providerConfig !== undefined ? providerConfig : config.workspace.config),
486
- )
542
+ redact = createReadinessRedactor(opts.env, [
543
+ ...caps.guestEnvNames(
544
+ providerConfig !== undefined ? providerConfig : config.workspace.config,
545
+ ),
546
+ ...Object.values(config.accounts).map((account) => account.credentialEnv),
547
+ ])
487
548
  // Registry-aware process-env-only check: a declared name present in the
488
549
  // dotenv-augmented `env` but absent from the raw launcher map fails here,
489
550
  // so plugin-declared requirements and non-CLI callers are covered too
@@ -635,6 +696,7 @@ export async function validateInitReadiness(opts: {
635
696
  exec,
636
697
  redact,
637
698
  runtimeReferences: effectiveRuntimeReferences(config),
699
+ accounts: config.accounts,
638
700
  stdout: opts.stdout ?? (() => {}),
639
701
  ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
640
702
  ...(opts.vercelFacade !== undefined ? { facade: opts.vercelFacade } : {}),
@@ -691,3 +753,83 @@ export async function validateInitReadiness(opts: {
691
753
  })),
692
754
  }
693
755
  }
756
+
757
+ /** Validation consumes the current owner's access value, never its refresh token. */
758
+ export async function validateInitReadiness(
759
+ opts: Parameters<typeof validateInitReadinessInner>[0],
760
+ ): Promise<InitValidationReport> {
761
+ const exec = opts.exec ?? spawnExec
762
+ const repo = await resolveMainRepo(opts.targetRepo, exec)
763
+ const config = await loadConfig(join(repo, 'autobuild.toml'))
764
+ const accounts = Object.entries(config.accounts).filter(
765
+ ([, a]) => a.kind === 'chatgpt-subscription',
766
+ )
767
+ if (!accounts.length) return validateInitReadinessInner({ ...opts, resolvedRepo: repo })
768
+ const credentials = new LocalCredentials(join(repo, '.autobuild'))
769
+ const owner = new LocalAccountOwner(credentials)
770
+ const claimed: string[] = []
771
+ const env = { ...opts.env }
772
+ const checks: InitValidationReport['checks'] = []
773
+ try {
774
+ const service = opts.env.AB_STORE?.trim() || config.store?.url
775
+ let metadata: ProjectSecretMetadata[] | undefined
776
+ if (
777
+ service &&
778
+ isRemoteStoreRef(service) &&
779
+ accounts.some(([name]) => !credentials.load(name))
780
+ ) {
781
+ await abSecrets('list', undefined, {
782
+ cwd: repo,
783
+ env: opts.env,
784
+ exec,
785
+ json: true,
786
+ print: (text) => {
787
+ metadata = JSON.parse(text).secrets
788
+ },
789
+ })
790
+ }
791
+ for (const [name, descriptor] of accounts) {
792
+ const record = credentials.load(name)
793
+ if (record) {
794
+ if (!record.owner) {
795
+ owner.claim(name)
796
+ claimed.push(name)
797
+ await owner.tick({ [name]: descriptor })
798
+ }
799
+ const current = credentials.load(name)!
800
+ if (current.status !== 'ready' || current.state.expiresAt <= Date.now())
801
+ throw new Error(`account ${JSON.stringify(name)}: sign in again with ab accounts login`)
802
+ env[descriptor.credentialEnv] = current.state.accessToken
803
+ } else {
804
+ const entry = metadata?.find(
805
+ (s) => s.name === descriptor.credentialEnv && s.kind === 'chatgpt-subscription',
806
+ )
807
+ const ready = entry?.status === 'ready' && entry.failureCode === null
808
+ checks.push({
809
+ name: `account ${JSON.stringify(name)}`,
810
+ status: ready ? 'pass' : 'fail',
811
+ detail: entry
812
+ ? `Hosted credential ${entry.status}; owner ${entry.owner}; set ${entry.setAt}; ${entry.warnings?.join(', ') || 'no refresh-window warning'}. The first hosted build is the live check.`
813
+ : `Credential absent; run ab accounts login ${JSON.stringify(name)} ${service && isRemoteStoreRef(service) ? '--project' : '--local'}`,
814
+ })
815
+ if (!ready)
816
+ return {
817
+ provider: config.workspace.provider,
818
+ context:
819
+ config.workspace.provider === 'git-worktree' ? 'local worktree' : 'Vercel Sandbox',
820
+ checks,
821
+ exitCode: 1,
822
+ }
823
+ env.AB_CHATGPT_HOSTED_READINESS = JSON.stringify([
824
+ ...(JSON.parse(env.AB_CHATGPT_HOSTED_READINESS ?? '[]') as string[]),
825
+ name,
826
+ ])
827
+ env[descriptor.credentialEnv] = 'autobuild-hosted-metadata-only'
828
+ }
829
+ }
830
+ const report = await validateInitReadinessInner({ ...opts, env, resolvedRepo: repo })
831
+ return { ...report, checks: [...checks, ...report.checks] }
832
+ } finally {
833
+ for (const name of claimed) owner.release(name)
834
+ }
835
+ }
@@ -1,3 +1,5 @@
1
+ import { abAccountsLogin } from './accounts'
2
+ import { abSecrets } from './secrets'
1
3
  import { currentTicketRef } from '../kernel/ticket-migrations'
2
4
  import { upgradeFollowup } from './upgrade-followup'
3
5
  import { parseDispatchArgs } from './dispatch-args'
@@ -106,6 +108,8 @@ export const SESSIONLESS_COMMANDS = new Set([
106
108
  'init',
107
109
  'connect',
108
110
  'disconnect',
111
+ 'secrets',
112
+ 'accounts',
109
113
  'upgrade',
110
114
  'update',
111
115
  'ticket',
@@ -488,6 +492,46 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
488
492
 
489
493
  // init and upgrade run OUTSIDE build sessions (§16.3): they operate on a
490
494
  // repo, not a build, so they route before any store/env requirement.
495
+ case 'accounts': {
496
+ const usage = 'usage: ab accounts login NAME [--local|--project]'
497
+ const parsed = parseArgs(rest, { local: 'boolean', project: 'boolean' }, usage)
498
+ if (
499
+ parsed.positionals.length !== 2 ||
500
+ parsed.positionals[0] !== 'login' ||
501
+ (parsed.flags.get('local') && parsed.flags.get('project'))
502
+ )
503
+ throw new Error(usage)
504
+ await abAccountsLogin(parsed.positionals[1]!, {
505
+ cwd: deps.workspacePath,
506
+ env: deps.processEnv ?? process.env,
507
+ exec: deps.exec ?? spawnExec,
508
+ print: stdout,
509
+ ...(deps.signal ? { signal: deps.signal } : {}),
510
+ ...(parsed.flags.get('local')
511
+ ? { destination: 'local' as const }
512
+ : parsed.flags.get('project')
513
+ ? { destination: 'project' as const }
514
+ : {}),
515
+ })
516
+ return 0
517
+ }
518
+ case 'secrets': {
519
+ const parsed = parseArgs(
520
+ rest,
521
+ { json: 'boolean' },
522
+ 'usage: ab secrets list [--json] | set NAME | remove NAME',
523
+ )
524
+ if (parsed.positionals.length > 2)
525
+ throw new Error('Secrets values must be supplied through stdin')
526
+ await abSecrets(parsed.positionals[0], parsed.positionals[1], {
527
+ cwd: deps.workspacePath,
528
+ env: deps.processEnv ?? process.env,
529
+ exec: deps.exec ?? spawnExec,
530
+ print: stdout,
531
+ json: parsed.flags.get('json') === true,
532
+ })
533
+ return 0
534
+ }
491
535
  case 'connect':
492
536
  case 'disconnect': {
493
537
  const usage = command === 'connect' ? 'usage: ab connect [url]' : 'usage: ab disconnect'
@@ -18,6 +18,9 @@ export interface PublicationSettlementDeps {
18
18
  publication?: WorkspacePublication
19
19
  forge: Forge
20
20
  workspacePath: string
21
+ /** Origin-mode dispatchers have no checkout, and possibly no host git:
22
+ * their `workspacePath` is a scratch root, never a ref cache to confirm. */
23
+ checkoutless?: boolean
21
24
  exec: Exec
22
25
  ids: IdSource
23
26
  runId: string
@@ -34,7 +37,7 @@ async function confirmDispatcherCache(
34
37
  branch: string,
35
38
  sha: string,
36
39
  ) {
37
- if (!deps.forge.confirmPublication) return
40
+ if (deps.checkoutless || !deps.forge.confirmPublication) return
38
41
  try {
39
42
  if (!(await stat(deps.workspacePath)).isDirectory()) return
40
43
  } catch (error) {