@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
@@ -0,0 +1,173 @@
1
+ import { SECRET_NAME_EXPLANATION } from '../secret-name'
2
+ import { connectedProject } from './connect'
3
+ import { ProjectCredentials } from './project-credentials'
4
+ import type { Exec } from '../ports/workspace/git-worktree'
5
+ import { decodeSecretMetadata, validateSecretName, validateSecretValue } from '../project-secrets'
6
+ import {
7
+ AUTOBUILD_VERSION,
8
+ AUTOBUILD_VERSION_HEADER,
9
+ REMOTE_STORE_PROTOCOL_VERSION,
10
+ REMOTE_STORE_PROTOCOL_VERSION_HEADER,
11
+ } from '../store/remote/version'
12
+ /** Raw mode disables terminal echo before listening. Restore the exact prior state on every exit. */
13
+ export async function readSecretInput(
14
+ input: NodeJS.ReadStream = process.stdin,
15
+ prompt: (s: string) => void = (s) => {
16
+ process.stderr.write(s)
17
+ },
18
+ ): Promise<string> {
19
+ if (!input.isTTY) {
20
+ const chunks: Buffer[] = []
21
+ let size = 0
22
+ for await (const chunk of input) {
23
+ const b = Buffer.from(chunk)
24
+ size += b.length
25
+ if (size > 65538) throw new Error('Secret input too large')
26
+ chunks.push(b)
27
+ }
28
+ return Buffer.concat(chunks)
29
+ .toString()
30
+ .replace(/\r?\n$/, '')
31
+ }
32
+ const wasPaused = input.isPaused()
33
+ const wasRaw = input.isRaw
34
+ input.setRawMode(true)
35
+ try {
36
+ prompt('Secret value: ')
37
+ } catch {
38
+ input.setRawMode(wasRaw)
39
+ throw new Error('Secret input failed')
40
+ }
41
+ return new Promise((resolve, reject) => {
42
+ let value = ''
43
+ const finish = (error?: Error) => {
44
+ input.off('data', data)
45
+ input.off('end', end)
46
+ input.off('error', failed)
47
+ process.off('SIGINT', cancel)
48
+ input.setRawMode(wasRaw)
49
+ if (wasPaused) input.pause()
50
+ else input.resume()
51
+ prompt('\n')
52
+ if (error) reject(error)
53
+ else resolve(value)
54
+ }
55
+ const cancel = () => finish(new Error('Secret input cancelled'))
56
+ const end = () => finish(new Error('Secret input ended'))
57
+ const failed = () => finish(new Error('Secret input failed'))
58
+ const data = (chunk: Buffer) => {
59
+ for (const c of chunk.toString()) {
60
+ if (c === '\x03') {
61
+ cancel()
62
+ return
63
+ }
64
+ if (c === '\x04') {
65
+ end()
66
+ return
67
+ }
68
+ if (c === '\r' || c === '\n') {
69
+ finish()
70
+ return
71
+ }
72
+ if (c === '\x7f' || c === '\b') value = value.slice(0, -1)
73
+ else value += c
74
+ if (Buffer.byteLength(value) > 65536) {
75
+ finish(new Error('Secret input too large'))
76
+ return
77
+ }
78
+ }
79
+ }
80
+ input.on('data', data)
81
+ input.once('end', end)
82
+ input.once('error', failed)
83
+ process.once('SIGINT', cancel)
84
+ input.resume()
85
+ })
86
+ }
87
+ export async function abSecrets(
88
+ operation: string | undefined,
89
+ name: string | undefined,
90
+ opts: {
91
+ cwd: string
92
+ env: Record<string, string | undefined>
93
+ exec: Exec
94
+ print: (s: string) => void
95
+ json?: boolean
96
+ readValue?: () => Promise<string>
97
+ fetch?: (input: string, init?: RequestInit) => Promise<Response>
98
+ },
99
+ ): Promise<void> {
100
+ if (
101
+ !['list', 'set', 'remove'].includes(operation ?? '') ||
102
+ (operation === 'list' ? name !== undefined : name === undefined)
103
+ )
104
+ throw new Error('usage: ab secrets list [--json] | set NAME | remove NAME')
105
+ if (name !== undefined) {
106
+ try {
107
+ validateSecretName(name)
108
+ } catch {
109
+ throw new Error(SECRET_NAME_EXPLANATION)
110
+ }
111
+ }
112
+ const project = await connectedProject(opts)
113
+ if (!project.service) throw new Error('No connected build service; run ab connect <url>')
114
+ const credential = new ProjectCredentials(opts.env).load(project.service, project.repo)
115
+ if (!credential) throw new Error('Missing saved project credential; run ab connect')
116
+ const body: Record<string, unknown> = { version: 1, repo: project.repo, name }
117
+ if (operation === 'set') {
118
+ const value = await (opts.readValue ?? readSecretInput)()
119
+ validateSecretValue(value)
120
+ body.value = value
121
+ }
122
+ let response: Response
123
+ try {
124
+ response = await (opts.fetch ?? fetch)(
125
+ `${project.service}/secrets/v1/${operation}${operation === 'list' ? `?repo=${encodeURIComponent(project.repo)}` : ''}`,
126
+ {
127
+ method: operation === 'list' ? 'GET' : 'POST',
128
+ headers: {
129
+ 'content-type': 'application/json',
130
+ authorization: `Bearer ${credential.token}`,
131
+ [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
132
+ [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
133
+ },
134
+ ...(operation === 'list' ? {} : { body: JSON.stringify(body) }),
135
+ signal: AbortSignal.timeout(15000),
136
+ redirect: 'error',
137
+ },
138
+ )
139
+ } catch {
140
+ throw new Error('Project secrets request failed')
141
+ }
142
+ if (!response.ok) throw new Error(`Project secrets request refused (${response.status})`)
143
+ try {
144
+ const result = await response.json()
145
+ if (
146
+ !result ||
147
+ typeof result !== 'object' ||
148
+ Object.keys(result).length !== 2 ||
149
+ result.version !== 1
150
+ )
151
+ throw new Error()
152
+ if (operation === 'list') {
153
+ if (!Array.isArray(result.secrets)) throw new Error()
154
+ const secrets: ReturnType<typeof decodeSecretMetadata>[] =
155
+ result.secrets.map(decodeSecretMetadata)
156
+ opts.print(
157
+ opts.json
158
+ ? JSON.stringify({ version: 1, secrets })
159
+ : secrets
160
+ .map(
161
+ (s) =>
162
+ `${s.name}\t${s.status}\t${s.owner}\t${s.setAt}\t${s.fingerprint}\t${s.lastSuppliedAt ?? 'never supplied'}${s.warnings?.length ? `\t${s.warnings.join(', ')}` : ''}`,
163
+ )
164
+ .join('\n') || 'No project secrets.',
165
+ )
166
+ } else {
167
+ if (result.ok !== true) throw new Error()
168
+ opts.print(`Secret ${operation === 'set' ? 'saved' : 'removed'}.`)
169
+ }
170
+ } catch {
171
+ throw new Error('Invalid project secrets response')
172
+ }
173
+ }
@@ -1,3 +1,4 @@
1
+ import { AccountRedactor, redactAccountStore } from '../store/account-redaction'
1
2
  import { untilDeadline } from './watch-lifetime'
2
3
  /**
3
4
  * Production BuildStore composition for CLI commands.
@@ -35,10 +36,19 @@ function optionalToken(value: string | undefined): string | undefined {
35
36
  * and does not import the HTTP adapter. */
36
37
  export const openProductionStore: StoreOpener = (ref, token) => {
37
38
  const forwardedToken = optionalToken(token)
38
- return resolveStore(ref, {
39
+ const store = resolveStore(ref, {
39
40
  remoteFactory: (url, remoteToken) => new RemoteBuildStore({ url, token: remoteToken }),
40
41
  ...(forwardedToken !== undefined ? { token: forwardedToken } : {}),
41
42
  })
43
+ const raw = process.env.AB_ACCOUNT_CREDENTIAL_ENVS
44
+ if (!raw) return store
45
+ const names: unknown = JSON.parse(raw)
46
+ if (!Array.isArray(names) || !names.every((name) => typeof name === 'string'))
47
+ throw new Error('Invalid account credential variable inventory')
48
+ return redactAccountStore(
49
+ store,
50
+ new AccountRedactor(() => names.map((name) => process.env[name])),
51
+ )
42
52
  }
43
53
 
44
54
  /** Apply validated ambient authority to a selected Store handle. Remote
@@ -87,6 +87,7 @@ export function upgradeConflictPrompt(input: {
87
87
  }
88
88
 
89
89
  interface ResolvedCompletion {
90
+ account?: import('../config/accounts').SelectedAccount
90
91
  oneShot: OneShotCompletion
91
92
  model?: string
92
93
  args: readonly string[]
@@ -110,7 +111,12 @@ export function createUpgradeAgentResolver(opts: UpgradeAgentResolverOpts): Reso
110
111
  repoRoot: opts.targetRepo,
111
112
  env: opts.env,
112
113
  })
113
- const selected = createRuntimeResolver(runtimes, config.roles).resolve(UPGRADE_ROLE)
114
+ const selected = createRuntimeResolver(
115
+ runtimes,
116
+ config.roles,
117
+ config.policy.sessionBudgetSeconds,
118
+ config.accounts,
119
+ ).resolve(UPGRADE_ROLE)
114
120
  const oneShot = runtimes[selected.runtime]?.oneShot
115
121
  if (oneShot === undefined) {
116
122
  throw new Error(
@@ -122,6 +128,7 @@ export function createUpgradeAgentResolver(opts: UpgradeAgentResolverOpts): Reso
122
128
  oneShot,
123
129
  ...(selected.model !== undefined ? { model: selected.model } : {}),
124
130
  args: selected.args,
131
+ account: selected.account,
125
132
  }
126
133
  })()
127
134
  return resolved
@@ -167,6 +174,7 @@ export function createUpgradeAgentResolver(opts: UpgradeAgentResolverOpts): Reso
167
174
  signal: controller.signal,
168
175
  ...(selected.model !== undefined ? { model: selected.model } : {}),
169
176
  args: selected.args,
177
+ account: selected.account,
170
178
  }),
171
179
  stopped,
172
180
  ])
@@ -1,3 +1,4 @@
1
+ import { ReducerValueIncompatibilityError } from '../store/remote/compatibility'
1
2
  import { WatchLifetime } from './watch-lifetime'
2
3
  import { hostname } from 'node:os'
3
4
  import { randomUUID } from 'node:crypto'
@@ -1038,7 +1039,8 @@ export async function abWatch(opts: AbWatchOpts): Promise<void> {
1038
1039
  if (!stop) checkPersistence()
1039
1040
  } else attentionInitialized = true
1040
1041
  return true
1041
- } catch {
1042
+ } catch (error) {
1043
+ if (error instanceof ReducerValueIncompatibilityError) throw error
1042
1044
  return false
1043
1045
  }
1044
1046
  }
@@ -0,0 +1,101 @@
1
+ import { z } from 'zod'
2
+ import { documentSchema, documentFields } from './reference-metadata'
3
+
4
+ const accountCredentialEnvSchema = z
5
+ .string()
6
+ .regex(/^[A-Za-z_][A-Za-z0-9_]*$/)
7
+ .refine(
8
+ (name) => !name.startsWith('AB_'),
9
+ 'Autobuild control variables cannot hold account credentials',
10
+ )
11
+ export const accountSchema = z.discriminatedUnion('kind', [
12
+ z.strictObject({
13
+ kind: z.literal('chatgpt-subscription'),
14
+ credentialEnv: accountCredentialEnvSchema,
15
+ }),
16
+ z.strictObject({
17
+ kind: z.literal('claude-subscription'),
18
+ credentialEnv: accountCredentialEnvSchema,
19
+ }),
20
+ z.strictObject({
21
+ kind: z.literal('kimi-code'),
22
+ credentialEnv: accountCredentialEnvSchema,
23
+ region: z.enum(['overseas', 'china']).default('overseas'),
24
+ }),
25
+ ])
26
+
27
+ documentSchema(accountSchema, { description: 'Named nonsecret billing account descriptor.' })
28
+ documentSchema(accountCredentialEnvSchema, {
29
+ constraints: 'Portable environment variable identifier; AB_ control variables are reserved.',
30
+ })
31
+ for (const branch of accountSchema.options)
32
+ documentFields(branch, {
33
+ kind: 'Claude subscription, Kimi Code membership, or ChatGPT subscription (Codex only).',
34
+ credentialEnv:
35
+ 'Host credential variable name; ChatGPT names a host-resolved access-token slot, never a credential value.',
36
+ ...(branch.shape.kind.value === 'kimi-code'
37
+ ? {
38
+ region:
39
+ 'Membership region: overseas (default) or china. Selects the base URL and exact egress host together.',
40
+ }
41
+ : {}),
42
+ })
43
+
44
+ /** Nonsecret billing descriptors. Credential values are resolved only at execution boundaries. */
45
+ export type Account =
46
+ | { kind: 'claude-subscription'; credentialEnv: string }
47
+ | { kind: 'chatgpt-subscription'; credentialEnv: string }
48
+ | { kind: 'kimi-code'; credentialEnv: string; region: 'overseas' | 'china' }
49
+ export type Accounts = Readonly<Record<string, Account>>
50
+ export const selectedAccountSchema = z.strictObject({
51
+ name: z.string().min(1),
52
+ descriptor: accountSchema,
53
+ })
54
+ export type SelectedAccount = z.infer<typeof selectedAccountSchema>
55
+
56
+ export function kimiEndpoint(region: 'overseas' | 'china'): { baseUrl: string; host: string } {
57
+ return region === 'china'
58
+ ? { baseUrl: 'https://api.kimi.com/coding/', host: 'api.kimi.com' }
59
+ : { baseUrl: 'https://api.kimi.ai/coding/', host: 'api.kimi.ai' }
60
+ }
61
+
62
+ export function selectAccount(
63
+ accounts: Accounts,
64
+ runtime: string | undefined,
65
+ name: string | undefined,
66
+ label: string,
67
+ ): SelectedAccount | undefined {
68
+ if (name === undefined && runtime === 'claude') {
69
+ const defaults = Object.entries(accounts).filter(
70
+ ([, account]) => account.kind === 'claude-subscription',
71
+ )
72
+ if (defaults.length > 1)
73
+ throw new Error(`${label}: ambiguous Claude subscription account; select account explicitly`)
74
+ name = defaults[0]?.[0]
75
+ }
76
+ if (name === undefined) return undefined
77
+ if (!Object.hasOwn(accounts, name))
78
+ throw new Error(`${label}: unknown account ${JSON.stringify(name)}`)
79
+ const requiredRuntime = accounts[name]!.kind === 'chatgpt-subscription' ? 'codex' : 'claude'
80
+ if (runtime !== requiredRuntime)
81
+ throw new Error(
82
+ `${label}: account ${JSON.stringify(name)} requires runtime "${requiredRuntime}"`,
83
+ )
84
+ return { name, descriptor: accounts[name]! }
85
+ }
86
+
87
+ export function accountRemedy(account: SelectedAccount): string {
88
+ return (
89
+ `account ${JSON.stringify(account.name)} (${account.descriptor.credentialEnv}): ` +
90
+ (account.descriptor.kind === 'chatgpt-subscription'
91
+ ? `sign in again with ab accounts login ${JSON.stringify(account.name)} (--local for the local dispatcher or --project for the connected project)`
92
+ : account.descriptor.kind === 'claude-subscription'
93
+ ? 'renew with claude setup-token and set the dispatcher credential variable'
94
+ : 'replace the Kimi Code membership key in the dispatcher credential variable')
95
+ )
96
+ }
97
+
98
+ /** Encodes arbitrary names injectively; never a credential. */
99
+ export function accountPlaceholder(name: string): string {
100
+ return `autobuild-account-${Buffer.from(name).toString('hex')}`
101
+ }
@@ -29,6 +29,7 @@ export const CONFIG_RELOAD_CLASSIFICATION = {
29
29
  verify: 'hot',
30
30
  finalize: 'hot',
31
31
  roles: 'hot',
32
+ accounts: 'hot',
32
33
  policy: 'hot',
33
34
  orchestrator: 'restart',
34
35
  tickets: {
@@ -184,7 +185,12 @@ export class LiveConfig {
184
185
  this.acceptedContent = startupContent
185
186
  this.snapshot = {
186
187
  config: startup,
187
- resolver: createRuntimeResolver(runtimes, startup.roles, startup.policy.sessionBudgetSeconds),
188
+ resolver: createRuntimeResolver(
189
+ runtimes,
190
+ startup.roles,
191
+ startup.policy.sessionBudgetSeconds,
192
+ startup.accounts,
193
+ ),
188
194
  revision: 0,
189
195
  }
190
196
  }
@@ -244,10 +250,17 @@ export class LiveConfig {
244
250
  const config = composeReloadedConfig(this.startup, candidate)
245
251
  let resolver: RuntimeResolver
246
252
  try {
253
+ for (const [name, account] of Object.entries(this.snapshot.config.accounts)) {
254
+ if (account.kind === 'chatgpt-subscription' && !same(account, config.accounts[name]))
255
+ throw new Error(
256
+ `ChatGPT account ${JSON.stringify(name)} cannot change while dispatch is active; stop dispatch before replacing its descriptor`,
257
+ )
258
+ }
247
259
  resolver = createRuntimeResolver(
248
260
  this.runtimes,
249
261
  config.roles,
250
262
  config.policy.sessionBudgetSeconds,
263
+ config.accounts,
251
264
  )
252
265
  } catch (error) {
253
266
  const message = error instanceof Error ? error.message : String(error)
@@ -1,3 +1,4 @@
1
+ import { selectAccount, type SelectedAccount } from './accounts'
1
2
  /**
2
3
  * Role-key consumability diagnostics (SPEC §9).
3
4
  *
@@ -79,6 +80,9 @@ export interface RoleKeyDiagnostics {
79
80
  type StepTable = { kind: 'check' } | { kind: 'agent'; skill: string }
80
81
 
81
82
  export interface RuntimeReferenceGroup {
83
+ /** Account-free routes, retained separately when accounts are declared. */
84
+ legacyAuthentication?: { models: string[]; usesRuntimeDefaultModel: boolean }
85
+ accountTargets?: Array<{ account: SelectedAccount; model?: string; references: string[] }>
82
86
  runtime: string
83
87
  /** Human-readable routes selecting this runtime, including alternates. */
84
88
  references: string[]
@@ -95,7 +99,7 @@ export interface RuntimeReferenceGroup {
95
99
  * bootstrap share one source of truth.
96
100
  */
97
101
  export function effectiveRuntimeReferences(
98
- config: Pick<Config, 'roles' | 'verify' | 'finalize'>,
102
+ config: Pick<Config, 'roles' | 'verify' | 'finalize'> & Partial<Pick<Config, 'accounts'>>,
99
103
  ): RuntimeReferenceGroup[] {
100
104
  const defaultSpec = config.roles.default ?? {}
101
105
  const routes: Array<{ role: string; aliases?: string[]; label: string }> = [
@@ -112,6 +116,14 @@ export function effectiveRuntimeReferences(
112
116
  })),
113
117
  ]
114
118
 
119
+ const legacyAuthentication = new Map<
120
+ string,
121
+ { models: Set<string>; usesRuntimeDefaultModel: boolean }
122
+ >()
123
+ const accountTargets = new Map<
124
+ string,
125
+ Array<{ account: SelectedAccount; model?: string; references: string[] }>
126
+ >()
115
127
  const grouped = new Map<
116
128
  string,
117
129
  { references: Set<string>; models: Set<string>; usesRuntimeDefaultModel: boolean }
@@ -123,8 +135,28 @@ export function effectiveRuntimeReferences(
123
135
  }
124
136
  return defaultSpec
125
137
  }
126
- const add = (runtime: string | undefined, model: string | undefined, reference: string) => {
138
+ const add = (
139
+ runtime: string | undefined,
140
+ model: string | undefined,
141
+ reference: string,
142
+ accountName?: string,
143
+ ) => {
144
+ const account = selectAccount(config.accounts ?? {}, runtime, accountName, reference)
145
+ if (account && runtime) {
146
+ const targets = accountTargets.get(runtime) ?? []
147
+ targets.push({ account, ...(model === undefined ? {} : { model }), references: [reference] })
148
+ accountTargets.set(runtime, targets)
149
+ }
127
150
  if (runtime === undefined || runtime.trim() === '') return
151
+ if (!account) {
152
+ const legacy = legacyAuthentication.get(runtime) ?? {
153
+ models: new Set<string>(),
154
+ usesRuntimeDefaultModel: false,
155
+ }
156
+ if (model === undefined) legacy.usesRuntimeDefaultModel = true
157
+ else legacy.models.add(model)
158
+ legacyAuthentication.set(runtime, legacy)
159
+ }
128
160
  const group = grouped.get(runtime) ?? {
129
161
  references: new Set(),
130
162
  models: new Set(),
@@ -140,21 +172,40 @@ export function effectiveRuntimeReferences(
140
172
  const spec = declaredSpec(route.role, route.aliases)
141
173
  const runtime = spec.runtime ?? defaultSpec.runtime
142
174
  const model = spec.model ?? defaultSpec.model
143
- add(runtime, model, `${route.label} primary`)
175
+ add(runtime, model, `${route.label} primary`, spec.account ?? defaultSpec.account)
144
176
  const alternates = spec.alternates ?? defaultSpec.alternates ?? []
145
177
  alternates.forEach((alternate, index) => {
146
178
  add(
147
179
  alternate.runtime ?? runtime,
148
180
  alternate.model ?? model,
149
181
  `${route.label} alternate[${index}]`,
182
+ alternate.account ?? spec.account ?? defaultSpec.account,
150
183
  )
151
184
  })
152
185
  }
153
186
 
187
+ // Unused accounts still require their actual runtime for readiness.
188
+ for (const [name, descriptor] of Object.entries(config.accounts ?? {}))
189
+ add(
190
+ descriptor.kind === 'chatgpt-subscription' ? 'codex' : 'claude',
191
+ descriptor.kind === 'kimi-code' ? 'kimi-for-coding' : undefined,
192
+ `account ${displayName(name)} readiness`,
193
+ name,
194
+ )
195
+
154
196
  return [...grouped.entries()]
155
197
  .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
156
198
  .map(([runtime, group]) => ({
157
199
  runtime,
200
+ ...(Object.keys(config.accounts ?? {}).length && legacyAuthentication.has(runtime)
201
+ ? {
202
+ legacyAuthentication: {
203
+ models: [...legacyAuthentication.get(runtime)!.models].sort(),
204
+ usesRuntimeDefaultModel: legacyAuthentication.get(runtime)!.usesRuntimeDefaultModel,
205
+ },
206
+ }
207
+ : {}),
208
+ ...(accountTargets.has(runtime) ? { accountTargets: accountTargets.get(runtime)! } : {}),
158
209
  references: [...group.references].sort(),
159
210
  models: [...group.models].sort(),
160
211
  usesRuntimeDefaultModel: group.usesRuntimeDefaultModel,
@@ -1,3 +1,4 @@
1
+ import { accountSchema, selectAccount } from './accounts'
1
2
  import { isSafeStepName } from '../context-directory'
2
3
  /**
3
4
  * autobuild.toml schema (SPEC §16.1, D9): the one declarative per-repo config
@@ -645,6 +646,7 @@ export const finalizeSectionSchema = stepSection(
645
646
  const roleArgsSchema = z.array(z.string().min(1))
646
647
 
647
648
  const runtimeAxesSchema = z.strictObject({
649
+ account: z.string().min(1).regex(/\S/).optional(),
648
650
  runtime: z.string().min(1).optional(),
649
651
  model: z.string().min(1).optional(),
650
652
  args: roleArgsSchema.optional(),
@@ -653,6 +655,8 @@ const runtimeAxesSchema = z.strictObject({
653
655
  })
654
656
 
655
657
  documentFields(runtimeAxesSchema, {
658
+ account:
659
+ 'Named billing account; inherits independently. Claude selects the sole subscription account when omitted.',
656
660
  runtime: 'Select an agent adapter.',
657
661
  model: 'Select the exact model. Codex uses unqualified `gpt-*`; Pi ids are provider-qualified.',
658
662
  args: 'Ordered extra CLI argv tokens applied to every phase and tool-free one-shot invocation. A supplied list replaces, rather than unions with, the inherited list.',
@@ -679,6 +683,8 @@ export const roleSchema = runtimeAxesSchema.extend({
679
683
  })
680
684
 
681
685
  documentFields(roleSchema, {
686
+ account:
687
+ 'Named billing account; inherits independently. Claude selects the sole subscription account when omitted.',
682
688
  runtime: 'Select an agent adapter.',
683
689
  model: 'Select the exact model. Codex uses unqualified `gpt-*`; Pi ids are provider-qualified.',
684
690
  args: 'Ordered extra CLI argv tokens applied to every phase and tool-free one-shot invocation. A supplied list replaces, rather than unions with, the inherited list.',
@@ -1069,6 +1075,7 @@ export const configRootSchema = z.strictObject({
1069
1075
  // disappear ahead of both eager resolution and the unconsumed-key warning;
1070
1076
  // the registry-aware eager resolver requires default.runtime and can
1071
1077
  // therefore include the complete materialized runtime list in its diagnostic.
1078
+ accounts: openMap('[accounts]', accountSchema).default({}),
1072
1079
  roles: openMap('[roles]', roleSchema),
1073
1080
  policy: policySchema.prefault({}),
1074
1081
  orchestrator: orchestratorSchema.prefault({}),
@@ -1103,6 +1110,8 @@ documentFields(configRootSchema, {
1103
1110
  'Ordered verification steps and applicability rules. Step names use ASCII letters, digits, ., _ and -; exactly . and .. are forbidden.',
1104
1111
  finalize:
1105
1112
  'Ordered post-PR steps. Failures are recorded without blocking the PR. Step names use ASCII letters, digits, ., _ and -; exactly . and .. are forbidden.',
1113
+ accounts:
1114
+ 'Named Claude subscription, Kimi Code, or ChatGPT subscription billing accounts. Descriptors contain credential variable names only.',
1106
1115
  roles: 'Named agent roles. The reserved default role provides inherited runtime axes.',
1107
1116
  policy: 'Lifecycle budgets, retries, convergence and harvest limits.',
1108
1117
  orchestrator:
@@ -1149,6 +1158,57 @@ const normalizedConfigSchema = configRootSchema.transform((input, ctx) => {
1149
1158
  })
1150
1159
 
1151
1160
  export const configSchema = normalizedConfigSchema.superRefine((config, ctx) => {
1161
+ for (const [name, account] of Object.entries(config.accounts)) {
1162
+ if (account.kind !== 'chatgpt-subscription') continue
1163
+ if (
1164
+ Object.entries(config.accounts).some(
1165
+ ([other, a]) => other !== name && a.credentialEnv === account.credentialEnv,
1166
+ )
1167
+ )
1168
+ ctx.addIssue({
1169
+ code: 'custom',
1170
+ path: ['accounts', name],
1171
+ message: 'ChatGPT accounts require distinct credentialEnv slots',
1172
+ })
1173
+ }
1174
+
1175
+ const accountVariables = new Set(
1176
+ Object.values(config.accounts).map((account) => account.credentialEnv),
1177
+ )
1178
+ for (const name of config.orchestrator.sandbox.environmentVariables)
1179
+ if (accountVariables.has(name))
1180
+ ctx.addIssue({
1181
+ code: 'custom',
1182
+ path: ['orchestrator', 'sandbox', 'environmentVariables'],
1183
+ message: `Account credential variable ${JSON.stringify(name)} cannot enter an operator sandbox`,
1184
+ })
1185
+ const defaults = config.roles.default ?? {}
1186
+ for (const [role, spec] of Object.entries(config.roles)) {
1187
+ const primary = {
1188
+ runtime: spec.runtime ?? defaults.runtime,
1189
+ account: spec.account ?? defaults.account,
1190
+ }
1191
+ const targets = [
1192
+ primary,
1193
+ ...(spec.alternates ?? defaults.alternates ?? []).map((alt) => ({
1194
+ runtime: alt.runtime ?? primary.runtime,
1195
+ account: alt.account ?? primary.account,
1196
+ })),
1197
+ ]
1198
+ targets.forEach((target, index) => {
1199
+ try {
1200
+ selectAccount(
1201
+ config.accounts,
1202
+ target.runtime,
1203
+ target.account,
1204
+ `role ${JSON.stringify(role)}${index ? ` alternate[${index - 1}]` : ''}`,
1205
+ )
1206
+ } catch (error) {
1207
+ ctx.addIssue({ code: 'custom', path: ['roles', role], message: (error as Error).message })
1208
+ }
1209
+ })
1210
+ }
1211
+
1152
1212
  for (const kind of ['verify', 'finalize'] as const) {
1153
1213
  const section = config[kind]
1154
1214
  if (!section) continue
@@ -23,7 +23,8 @@ export interface StoredEvent {
23
23
  }
24
24
 
25
25
  /** Change this revision whenever projection semantics change without new types. */
26
- export const READ_DECODER_REVISION = 2
26
+ // Revision 3 retains optional billing-account descriptors in session/attempt projections.
27
+ export const READ_DECODER_REVISION = 3
27
28
  export function catalogIdentity(
28
29
  build: Record<string, string> = buildEventPolicy,
29
30
  repository: Record<string, string> = repositoryEventPolicy,
@@ -1,3 +1,4 @@
1
+ import { selectedAccountSchema } from '../config/accounts'
1
2
  import { runtimeIdentitySchema } from './runtime'
2
3
  import { viaSchema } from './envelope'
3
4
  import { nativeSessionHandleSchema } from './native-session'
@@ -141,6 +142,7 @@ export const agentFailureCauseSchema = z.enum([
141
142
 
142
143
  /** One configured execution target that failed within a single phase attempt. */
143
144
  export const providerAttemptSchema = z.strictObject({
145
+ account: selectedAccountSchema.optional(),
144
146
  index: z.number().int().nonnegative(),
145
147
  session: z.string().min(1),
146
148
  runner: z.string().min(1),
@@ -846,6 +848,7 @@ export const eventPayloadSchemas = {
846
848
  model: z.string().optional(),
847
849
  /** Optional only so historical events replay without migration. */
848
850
  args: z.array(z.string()).optional(),
851
+ account: selectedAccountSchema.optional(),
849
852
  phase: phaseSchema,
850
853
  round: round.optional(),
851
854
  /** Stream id this session's live view writes to (SPEC §9, session
@@ -1,3 +1,4 @@
1
+ import { selectedAccountSchema } from '../config/accounts'
1
2
  import { nativeSessionHandleSchema } from './native-session'
2
3
  import { runtimeIdentitySchema } from './runtime'
3
4
  import { stampCompatibility, type CompatibilityMetadata, repositoryEventPolicy } from './policy'
@@ -278,6 +279,7 @@ export const harvestEventPayloadSchemas = {
278
279
  model: z.string().optional(),
279
280
  /** Optional only so historical repository journals replay without migration. */
280
281
  args: z.array(z.string()).optional(),
282
+ account: selectedAccountSchema.optional(),
281
283
  step: z.enum(['synthesize', 'review']),
282
284
  round,
283
285
  /** Stream id this session's live view writes to (SPEC §9, session
@@ -2356,6 +2356,7 @@
2356
2356
  "$.build.openEscalations[].source: string",
2357
2357
  "$.build.openEscalations[]: object",
2358
2358
  "$.build.openSessions: array",
2359
+ "$.build.openSessions[].account: undefined",
2359
2360
  "$.build.openSessions[].args: undefined",
2360
2361
  "$.build.openSessions[].budgetMs: undefined",
2361
2362
  "$.build.openSessions[].continuation: undefined",
@@ -3417,6 +3418,7 @@
3417
3418
  "$.build.openEscalations[].source: string",
3418
3419
  "$.build.openEscalations[]: object",
3419
3420
  "$.build.openSessions: array",
3421
+ "$.build.openSessions[].account: undefined",
3420
3422
  "$.build.openSessions[].args: undefined",
3421
3423
  "$.build.openSessions[].budgetMs: undefined",
3422
3424
  "$.build.openSessions[].continuation: undefined",
@@ -6055,6 +6057,7 @@
6055
6057
  "$.openEscalations[].source: string",
6056
6058
  "$.openEscalations[]: object",
6057
6059
  "$.openSessions: array",
6060
+ "$.openSessions[].account: undefined",
6058
6061
  "$.openSessions[].args: undefined",
6059
6062
  "$.openSessions[].budgetMs: undefined",
6060
6063
  "$.openSessions[].continuation: undefined",