@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,4 @@
1
+ import type { SelectedAccount } from '../config/accounts'
1
2
  import {
2
3
  advanceVerifyStage,
3
4
  initialVerifyStageState,
@@ -118,6 +119,7 @@ export interface OpenSession {
118
119
  nativeHandle?: NativeSessionHandle
119
120
  continuation?: EventPayload<'session.started'>['continuation']
120
121
  budgetMs?: number
122
+ account?: SelectedAccount
121
123
  args?: string[]
122
124
  startedAt: string
123
125
  nativeResumeFallback?: boolean
@@ -463,7 +465,7 @@ export interface BuildAcc {
463
465
  }
464
466
 
465
467
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
466
- export const BUILD_REDUCER_VERSION = 24
468
+ export const BUILD_REDUCER_VERSION = 25
467
469
 
468
470
  function initialBuildAcc(): BuildAcc {
469
471
  return {
@@ -865,6 +867,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
865
867
  continuation: event.payload.continuation,
866
868
  budgetMs: event.payload.budgetMs,
867
869
  args: event.payload.args,
870
+ account: event.payload.account,
868
871
  startedAt: event.ts,
869
872
  nativeHandle: event.payload.continuation?.handle,
870
873
  session: event.payload.session,
@@ -17,6 +17,7 @@ export {
17
17
  ticketBlockerRequestSchema,
18
18
  ticketCreateRequestSchema,
19
19
  ticketMoveRequestSchema,
20
+ ticketPageSchema,
20
21
  ticketUpdateRequestSchema,
21
22
  } from './protocol'
22
23
  export type {
@@ -83,6 +84,7 @@ export type {
83
84
  OperatorTicketBuild,
84
85
  OperatorTicketContext,
85
86
  OperatorTicketDetail,
87
+ OperatorTicketPage,
86
88
  OperatorTicketQueue,
87
89
  } from './tickets'
88
90
  export {
@@ -79,6 +79,12 @@ export const ticketUpdateRequestSchema = z
79
79
  value.target !== undefined,
80
80
  'update must name at least one field',
81
81
  )
82
+ /** A window over a ticket listing; see `OperatorTicketPage`. */
83
+ export const ticketPageSchema = z.strictObject({
84
+ limit: z.number().int().min(0).max(200),
85
+ offset: z.number().int().min(0).optional(),
86
+ order: z.enum(['oldest', 'newest']).optional(),
87
+ })
82
88
  export const ticketMoveRequestSchema = z.strictObject({
83
89
  expectedRevision: expectedRevisionSchema,
84
90
  state: z.string().min(1),
@@ -311,6 +311,18 @@ const ticketsListInput = z.strictObject({
311
311
  .array(z.string().min(1))
312
312
  .optional()
313
313
  .describe('Narrow the list to tickets carrying every named label.'),
314
+ limit: z
315
+ .number()
316
+ .int()
317
+ .min(0)
318
+ .max(200)
319
+ .optional()
320
+ .describe('Return at most this many tickets; `total` still counts every match.'),
321
+ offset: z.number().int().min(0).optional().describe('Skip this many tickets first.'),
322
+ order: z
323
+ .enum(['oldest', 'newest'])
324
+ .optional()
325
+ .describe('Oldest first (the source order, the default) or newest first.'),
314
326
  })
315
327
 
316
328
  const ticketsCreateInput = ticketCreateRequestSchema.extend({ repo: repoField })
@@ -783,7 +795,7 @@ export const TOOLS: readonly ToolEntry[] = [
783
795
  'tickets.list',
784
796
  'List the repository’s ticket grooming queue from the configured ticket source.',
785
797
  ticketsListInput,
786
- '{states, tickets, diagnostics, criteria, triageState, readyState}: the queue listing, the effective lifecycle names, and the criteria actually applied.',
798
+ '{states, tickets, diagnostics, criteria, triageState, readyState, doneState, total}: the queue listing (one page when `limit` is set), the effective lifecycle names, the criteria actually applied, and the match count before paging.',
787
799
  async (raw, ctx) => {
788
800
  const input = raw as z.infer<typeof ticketsListInput>
789
801
  return listOperatorTickets({
@@ -792,6 +804,15 @@ export const TOOLS: readonly ToolEntry[] = [
792
804
  backend: ticketsOf(ctx),
793
805
  ...(input.state !== undefined ? { state: input.state } : {}),
794
806
  ...(input.labels !== undefined ? { labels: input.labels } : {}),
807
+ ...(input.limit !== undefined
808
+ ? {
809
+ page: {
810
+ limit: input.limit,
811
+ ...(input.offset !== undefined ? { offset: input.offset } : {}),
812
+ ...(input.order !== undefined ? { order: input.order } : {}),
813
+ },
814
+ }
815
+ : {}),
795
816
  })
796
817
  },
797
818
  ),
@@ -17,7 +17,14 @@ import {
17
17
  requireTicket,
18
18
  updateTicket,
19
19
  } from '../ports/tickets/operations'
20
- import type { DependencyState, Ticket, TicketSource, TicketUpdate } from '../ports/types'
20
+ import type {
21
+ DependencyState,
22
+ Ticket,
23
+ TicketSource,
24
+ TicketUpdate,
25
+ TicketPage,
26
+ TicketPageListing,
27
+ } from '../ports/types'
21
28
  import type { BuildStore } from '../store/types'
22
29
  import { ticketLifecycle } from '../ports/tickets/lifecycle'
23
30
  import { effectiveConfig } from './query'
@@ -47,8 +54,14 @@ export interface OperatorTicketQueue {
47
54
  /** Effective repository lifecycle names; clients must not invent provider states. */
48
55
  triageState: string
49
56
  readyState: string
57
+ doneState: string
58
+ /** Tickets matching the criteria before `page` sliced them. */
59
+ total: number
50
60
  }
51
61
 
62
+ /** A window over a listing. `newest` reverses the source's oldest-first order. */
63
+ export type OperatorTicketPage = TicketPage
64
+
52
65
  export interface OperatorTicketBuild {
53
66
  slug: string
54
67
  status: string
@@ -91,9 +104,11 @@ export async function listOperatorTickets(opts: {
91
104
  backend: OperatorTicketBackend
92
105
  state?: string
93
106
  labels?: string[]
107
+ page?: OperatorTicketPage
94
108
  }): Promise<OperatorTicketQueue> {
95
109
  const { context, source } = await openOperatorTickets(opts)
96
- const triageState = ticketLifecycle(context.tickets).triage
110
+ const lifecycle = ticketLifecycle(context.tickets)
111
+ const triageState = lifecycle.triage
97
112
  const readyState = context.tickets.readyState
98
113
  // The operator surface is a grooming queue. Unlike the CLI's ticket list,
99
114
  // labels narrow the default state instead of replacing its lifecycle gate.
@@ -101,17 +116,23 @@ export async function listOperatorTickets(opts: {
101
116
  state: opts.state ?? triageState,
102
117
  ...(opts.labels !== undefined ? { labels: opts.labels } : {}),
103
118
  }
119
+ const nativePage = opts.page !== undefined && source.listPage !== undefined
104
120
  const [listing, states] = await Promise.all([
105
- source.listReady(criteria),
121
+ nativePage ? source.listPage!(criteria, opts.page!) : source.listReady(criteria),
106
122
  opts.backend.statesFor(context, source),
107
123
  ])
124
+ const ordered =
125
+ !nativePage && opts.page?.order === 'newest' ? [...listing.tickets].reverse() : listing.tickets
126
+ const offset = opts.page?.offset ?? 0
108
127
  return {
109
128
  states,
110
- tickets: listing.tickets,
129
+ tickets: opts.page && !nativePage ? ordered.slice(offset, offset + opts.page.limit) : ordered,
111
130
  diagnostics: listing.diagnostics,
112
131
  criteria,
113
132
  triageState,
114
133
  readyState,
134
+ doneState: lifecycle.done,
135
+ total: nativePage ? (listing as TicketPageListing).total : listing.tickets.length,
115
136
  }
116
137
  }
117
138
 
@@ -15,7 +15,7 @@ import type {
15
15
  } from '../ports/workspace/provider-capabilities'
16
16
 
17
17
  /** Version of the in-process plugin contract exposed by `@defrex/autobuild/plugin-sdk`. */
18
- export const PLUGIN_API_VERSION = '1.8.0' as const
18
+ export const PLUGIN_API_VERSION = '1.9.0' as const
19
19
 
20
20
  /** Context supplied when a registered adapter or contract fixture is selected. */
21
21
  export interface PluginFactoryContext<Config = Record<string, unknown>> {
@@ -59,6 +59,7 @@ export interface WorkspaceProviderPluginFactoryContext<Config = Record<string, u
59
59
  /** Host-derived effective runtime routes (the referenced runtimes and their
60
60
  * selection provenance). Absent at call sites that reference no runtimes
61
61
  * (for example the MCP server), which never construct a workspace. */
62
+ accounts?: () => import('../config/accounts').Accounts
62
63
  runtimeReferences?: RuntimeReferencesSource
63
64
  /** Checkout-less seam: the repository's HTTPS origin. When absent the
64
65
  * provider falls back to host `git` from `repoRoot` — the same default the
@@ -0,0 +1,88 @@
1
+ import {
2
+ accountRemedy,
3
+ accountPlaceholder,
4
+ kimiEndpoint,
5
+ type SelectedAccount,
6
+ } from '../../config/accounts'
7
+
8
+ const ROUTING_KEYS = [
9
+ 'ANTHROPIC_CUSTOM_HEADERS',
10
+ 'CLAUDE_CODE_OAUTH_TOKEN',
11
+ 'ANTHROPIC_API_KEY',
12
+ 'ANTHROPIC_AUTH_TOKEN',
13
+ 'ANTHROPIC_DEFAULT_FABLE_MODEL',
14
+ 'ANTHROPIC_SMALL_FAST_MODEL',
15
+ 'ANTHROPIC_BASE_URL',
16
+ 'ANTHROPIC_MODEL',
17
+ 'ANTHROPIC_DEFAULT_HAIKU_MODEL',
18
+ 'ANTHROPIC_DEFAULT_SONNET_MODEL',
19
+ 'ANTHROPIC_DEFAULT_OPUS_MODEL',
20
+ 'CLAUDE_CODE_SUBAGENT_MODEL',
21
+ 'CLAUDE_CODE_USE_BEDROCK',
22
+ 'CLAUDE_CODE_USE_VERTEX',
23
+ 'CLAUDE_CODE_USE_FOUNDRY',
24
+ ] as const
25
+
26
+ /** Existing environment-owned launch metadata also covers a runner that
27
+ * started before its first account was declared by a live configuration reload. */
28
+ function usesPlaceholders(env: Readonly<Record<string, string>>): boolean {
29
+ if (env.AB_ACCOUNT_PLACEHOLDERS === '1') return true
30
+ return [env.AB_BUILD_RUNNER_OPTIONS, env.AB_HARVEST_RUNNER_OPTIONS].some((raw) => {
31
+ if (!raw) return false
32
+ try {
33
+ const launch = JSON.parse(raw) as { supervision?: { kind?: unknown } } | null
34
+ return launch?.supervision?.kind === 'environment'
35
+ } catch {
36
+ return false
37
+ }
38
+ })
39
+ }
40
+
41
+ /** Apply after ambient merging. Inputs and process.env remain untouched. */
42
+ export function accountEnvironment(
43
+ ambient: Readonly<Record<string, string>>,
44
+ account?: SelectedAccount,
45
+ model?: string,
46
+ ): Record<string, string> {
47
+ if (account === undefined) return { ...ambient }
48
+ const env = { ...ambient }
49
+ const remote = usesPlaceholders(env)
50
+ const originalCredential = env[account.descriptor.credentialEnv]
51
+ const credential = remote ? accountPlaceholder(account.name) : originalCredential
52
+ if (remote && originalCredential)
53
+ for (const [key, value] of Object.entries(env))
54
+ if (value.includes(originalCredential)) delete env[key]
55
+ for (const key of ROUTING_KEYS) delete env[key]
56
+ if (remote && !ROUTING_KEYS.some((key) => key === account.descriptor.credentialEnv))
57
+ env[account.descriptor.credentialEnv] = credential!
58
+ if (account.descriptor.kind === 'kimi-code') {
59
+ if (!credential) throw new Error(`Missing credential: ${accountRemedy(account)}`)
60
+ const selectedModel = model ?? 'kimi-for-coding'
61
+ Object.assign(env, {
62
+ ANTHROPIC_API_KEY: credential,
63
+ ANTHROPIC_BASE_URL: kimiEndpoint(account.descriptor.region).baseUrl,
64
+ ANTHROPIC_MODEL: selectedModel,
65
+ ANTHROPIC_DEFAULT_FABLE_MODEL: selectedModel,
66
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: selectedModel,
67
+ ANTHROPIC_DEFAULT_SONNET_MODEL: selectedModel,
68
+ ANTHROPIC_DEFAULT_OPUS_MODEL: selectedModel,
69
+ CLAUDE_CODE_SUBAGENT_MODEL: selectedModel,
70
+ })
71
+ } else if (credential) env.CLAUDE_CODE_OAUTH_TOKEN = credential
72
+ else if (env.AB_WORKSPACE_PROVIDER === 'vercel-sandbox')
73
+ throw new Error(`Missing credential: ${accountRemedy(account)}`)
74
+ return env
75
+ }
76
+
77
+ /** CLI settings outrank user/project settings.env. Empty competing values also
78
+ * override saved values, without editing the user's files. */
79
+ export function accountSettings(env: Record<string, string>, account?: SelectedAccount): string[] {
80
+ if (account === undefined) return []
81
+ return [
82
+ '--settings',
83
+ JSON.stringify({
84
+ apiKeyHelper: '',
85
+ env: Object.fromEntries(ROUTING_KEYS.map((key) => [key, env[key] ?? ''])),
86
+ }),
87
+ ]
88
+ }
@@ -0,0 +1,85 @@
1
+ import { sensitiveAccountValues } from '../../accounts/sensitive'
2
+ import { LocalCredentials } from '../../accounts/local-credentials'
3
+ import { localInference } from '../../accounts/local-inference'
4
+ import { resolveMainRepo } from '../../cli/main-checkout'
5
+ import { spawnExec } from '../workspace/git-worktree'
6
+ import { mkdirSync, lstatSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import type { SelectedAccount } from '../../config/accounts'
9
+ import { accountPlaceholder } from '../../config/accounts'
10
+
11
+ /** A selected account owns provider routing even when callers supply config flags. */
12
+ export async function chatgptProvider(
13
+ account: SelectedAccount | undefined,
14
+ env: Record<string, string>,
15
+ cwd: string,
16
+ ): Promise<{ env: Record<string, string>; args: string[]; close: () => Promise<void> }> {
17
+ if (account?.descriptor.kind !== 'chatgpt-subscription')
18
+ return { env, args: [], close: async () => {} }
19
+ const originalCredential = env[account.descriptor.credentialEnv]
20
+ if (originalCredential && originalCredential !== accountPlaceholder(account.name))
21
+ sensitiveAccountValues.add(originalCredential)
22
+ const selected = { ...env }
23
+ for (const key of [
24
+ 'OPENAI_API_KEY',
25
+ 'OPENAI_BASE_URL',
26
+ 'OPENAI_ORG_ID',
27
+ 'OPENAI_ORGANIZATION',
28
+ 'OPENAI_PROJECT_ID',
29
+ 'CODEX_API_KEY',
30
+ account.descriptor.credentialEnv,
31
+ ])
32
+ delete selected[key]
33
+ const scratch = join(cwd, '.ab')
34
+ mkdirSync(scratch, { recursive: true, mode: 0o700 })
35
+ const scratchInfo = lstatSync(scratch)
36
+ if (!scratchInfo.isDirectory() || scratchInfo.isSymbolicLink())
37
+ throw new Error('Unsafe isolated Codex state directory')
38
+ const home = join(scratch, 'codex-chatgpt')
39
+ mkdirSync(home, { recursive: true, mode: 0o700 })
40
+ const homeInfo = lstatSync(home)
41
+ if (
42
+ !homeInfo.isDirectory() ||
43
+ homeInfo.isSymbolicLink() ||
44
+ (homeInfo.mode & 0o777) !== 0o700 ||
45
+ homeInfo.uid !== process.getuid?.()
46
+ )
47
+ throw new Error('Unsafe isolated Codex state directory')
48
+ const remote = env.AB_ACCOUNT_PLACEHOLDERS === '1'
49
+ const transport = remote
50
+ ? undefined
51
+ : localInference(
52
+ new LocalCredentials(join(await resolveMainRepo(cwd, spawnExec), '.autobuild')),
53
+ account.name,
54
+ )
55
+ const base = remote ? 'https://api.openai.com/v1' : transport!.baseUrl
56
+ const credential = remote ? accountPlaceholder(account.name) : transport!.capability
57
+ if (!base || !credential || (!remote && !/^http:\/\/127\.0\.0\.1:\d+\/v1$/.test(base)))
58
+ throw new Error(
59
+ `ChatGPT account ${JSON.stringify(account.name)} requires its dispatcher inference transport; sign in again`,
60
+ )
61
+ for (const [key, value] of Object.entries(selected))
62
+ if ([...sensitiveAccountValues].some((secret) => value.includes(secret))) delete selected[key]
63
+ selected.CODEX_HOME = home
64
+ selected.AUTOBUILD_CHATGPT_BEARER = credential
65
+ const provider = 'model_providers.autobuild_chatgpt.'
66
+ const settings: Record<string, string | boolean> = {
67
+ model_provider: 'autobuild_chatgpt',
68
+ [`${provider}name`]: 'ChatGPT plan',
69
+ [`${provider}base_url`]: base,
70
+ [`${provider}env_key`]: 'AUTOBUILD_CHATGPT_BEARER',
71
+ [`${provider}wire_api`]: 'responses',
72
+ [`${provider}requires_openai_auth`]: false,
73
+ [`${provider}supports_websockets`]: false,
74
+ }
75
+ return {
76
+ env: selected,
77
+ close: async () => {
78
+ await transport?.close()
79
+ },
80
+ args: [
81
+ '--ignore-user-config',
82
+ ...Object.entries(settings).flatMap(([k, v]) => ['-c', `${k}=${JSON.stringify(v)}`]),
83
+ ],
84
+ }
85
+ }
@@ -1,3 +1,5 @@
1
+ import { accountRemedy } from '../../config/accounts'
2
+ import { accountEnvironment, accountSettings } from './account-env'
1
3
  import { hostname } from 'node:os'
2
4
  import {
3
5
  guardNativeHandle,
@@ -228,7 +230,9 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
228
230
  * resumable session persistence. With no built-in or MCP tools, the single
229
231
  * print-mode prompt cannot enter a tool-result loop. */
230
232
  async complete(input: OneShotCompletionInput): Promise<OneShotCompletionResult> {
233
+ const env = accountEnvironment(sessionEnv(input.env), input.account, input.model)
231
234
  const args = this.baseArgs()
235
+ args.push(...accountSettings(env, input.account))
232
236
  args.push('--tools', '', '--disallowedTools', 'mcp__*', '--no-session-persistence')
233
237
  if (input.model !== undefined) args.push(CLAUDE_MODEL_ARG, input.model)
234
238
  args.push(...(input.args ?? []), CLAUDE_PROMPT_BOUNDARY, input.prompt)
@@ -236,7 +240,7 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
236
240
  const turn = await this.runPrompt({
237
241
  args,
238
242
  cwd: input.cwd,
239
- env: sessionEnv(input.env),
243
+ env,
240
244
  ...(input.signal !== undefined ? { signal: input.signal } : {}),
241
245
  })
242
246
  if (turn.failure !== undefined) throw new Error(turn.failure.message)
@@ -382,6 +386,24 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
382
386
  }
383
387
 
384
388
  private async runTurn(
389
+ prompt: string,
390
+ opts: AgentStartOpts,
391
+ session: { sessionId: string } | { resume: string },
392
+ signal = opts.signal,
393
+ ): Promise<ClaudeTurn> {
394
+ let turn: ClaudeTurn
395
+ try {
396
+ turn = await this.runAuthenticatedTurn(prompt, opts, session, signal)
397
+ } catch (error) {
398
+ if (!opts.account) throw error
399
+ turn = launchFailure(error)
400
+ }
401
+ if (opts.account && turn.failure?.cause === 'credentials')
402
+ turn.failure.message += `; ${accountRemedy(opts.account)}`
403
+ return turn
404
+ }
405
+
406
+ private async runAuthenticatedTurn(
385
407
  prompt: string,
386
408
  opts: AgentStartOpts,
387
409
  session: { sessionId: string } | { resume: string },
@@ -418,10 +440,12 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
418
440
  if (opts.stream !== undefined) args.push(CLAUDE_INCLUDE_PARTIAL_ARG)
419
441
  args.push(...(opts.args ?? []), CLAUDE_PROMPT_BOUNDARY, prompt)
420
442
 
443
+ const env = accountEnvironment(sessionEnv(opts.env), opts.account, opts.model)
444
+ args.unshift(...accountSettings(env, opts.account))
421
445
  const invocation: ClaudeCliInvocation = {
422
446
  args,
423
447
  cwd: opts.workspacePath,
424
- env: sessionEnv(opts.env),
448
+ env,
425
449
  ...(signal !== undefined ? { signal } : {}),
426
450
  }
427
451
  if (opts.stream === undefined && opts.onNativeSession === undefined)
@@ -1,3 +1,5 @@
1
+ import { accountRemedy, type SelectedAccount } from '../../config/accounts'
2
+ import { chatgptProvider } from './chatgpt-provider'
1
3
  import { hostname } from 'node:os'
2
4
  import {
3
5
  guardNativeHandle,
@@ -53,6 +55,7 @@ import type { RuntimeUsabilityInput, RuntimeUsabilityResult } from './runtime'
53
55
  import { sessionEnv } from './session-env'
54
56
 
55
57
  export interface CodexCliInvocation {
58
+ account?: SelectedAccount
56
59
  /** Arguments after the `codex` executable. */
57
60
  args: string[]
58
61
  cwd: string
@@ -251,14 +254,21 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
251
254
  ]
252
255
  for (const feature of ONE_SHOT_DISABLED_FEATURES) args.push('--disable', feature)
253
256
  if (input.model !== undefined) args.push(CODEX_MODEL_ARG, input.model)
254
- args.push(...(input.args ?? []), CODEX_PROMPT_BOUNDARY, input.prompt)
257
+ const provider = await chatgptProvider(input.account, sessionEnv(input.env), input.cwd)
258
+ args.push(
259
+ ...(input.args ?? []),
260
+ ...provider.args.filter((arg) => arg !== '--ignore-user-config'),
261
+ CODEX_PROMPT_BOUNDARY,
262
+ input.prompt,
263
+ )
255
264
 
256
265
  const turn = await this.runPrompt({
257
266
  args,
258
267
  cwd: input.cwd,
259
- env: sessionEnv(input.env),
268
+ account: input.account,
269
+ env: provider.env,
260
270
  ...(input.signal !== undefined ? { signal: input.signal } : {}),
261
- })
271
+ }).finally(provider.close)
262
272
  if (turn.failure !== undefined) throw new Error(turn.failure.message)
263
273
  if (turn.toolItems.length > 0) {
264
274
  throw new Error(
@@ -445,40 +455,49 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
445
455
  SHELL_ENV_INHERIT,
446
456
  )
447
457
  if (opts.model !== undefined) args.push(CODEX_MODEL_ARG, opts.model)
448
- args.push(...(opts.args ?? []))
458
+ const provider =
459
+ opts.account?.descriptor.kind === 'chatgpt-subscription'
460
+ ? await chatgptProvider(opts.account, sessionEnv(opts.env), opts.workspacePath)
461
+ : { env: sessionEnv(opts.env), args: [] as string[], close: async () => {} }
462
+ args.push(...(opts.args ?? []), ...provider.args)
449
463
  if (resume !== undefined) args.push(resume)
450
464
  args.push(CODEX_PROMPT_BOUNDARY, prompt)
451
465
  const invocation: CodexCliInvocation = {
452
466
  args,
453
467
  cwd: opts.workspacePath,
454
- env: sessionEnv(opts.env),
468
+ account: opts.account,
469
+ env: provider.env,
455
470
  ...(signal !== undefined ? { signal } : {}),
456
471
  }
457
- if (opts.stream === undefined && opts.onNativeSession === undefined)
458
- return this.runPrompt(invocation)
459
- if (opts.stream === undefined) {
460
- if (this.runCliStream !== undefined)
461
- return this.runStreamingPrompt(invocation, undefined, observe)
462
- const turn = await this.runPrompt(invocation)
463
- for (const event of turn.events) await observeEvent(event)
472
+ try {
473
+ if (opts.stream === undefined && opts.onNativeSession === undefined)
474
+ return await this.runPrompt(invocation)
475
+ if (opts.stream === undefined) {
476
+ if (this.runCliStream !== undefined)
477
+ return await this.runStreamingPrompt(invocation, undefined, observe)
478
+ const turn = await this.runPrompt(invocation)
479
+ for (const event of turn.events) await observeEvent(event)
480
+ return turn
481
+ }
482
+
483
+ // Streaming turn: translate while the CLI runs. Without an injected
484
+ // streaming boundary (offline fakes), the buffered path still translates
485
+ // after completion — degraded latency, same content.
486
+ const emitter = opts.stream
487
+ emitter.append([promptPart(prompt), startPart(crypto.randomUUID())])
488
+ let turn: CodexTurn
489
+ if (this.runCliStream !== undefined) {
490
+ turn = await this.runStreamingPrompt(invocation, emitter, observe)
491
+ } else {
492
+ turn = await this.runPrompt(invocation)
493
+ for (const event of turn.events) await observeEvent(event)
494
+ translateBufferedCodexTurn(turn, (parts) => emitter?.append(parts))
495
+ }
496
+ this.emitTurnEnd(turn, emitter, signal)
464
497
  return turn
498
+ } finally {
499
+ await provider.close()
465
500
  }
466
-
467
- // Streaming turn: translate while the CLI runs. Without an injected
468
- // streaming boundary (offline fakes), the buffered path still translates
469
- // after completion — degraded latency, same content.
470
- const emitter = opts.stream
471
- emitter.append([promptPart(prompt), startPart(crypto.randomUUID())])
472
- let turn: CodexTurn
473
- if (this.runCliStream !== undefined) {
474
- turn = await this.runStreamingPrompt(invocation, emitter, observe)
475
- } else {
476
- turn = await this.runPrompt(invocation)
477
- for (const event of turn.events) await observeEvent(event)
478
- translateBufferedCodexTurn(turn, (parts) => emitter?.append(parts))
479
- }
480
- this.emitTurnEnd(turn, emitter, signal)
481
- return turn
482
501
  }
483
502
 
484
503
  /** Completed-turn, failed-turn, and cancelled-turn closing parts. */
@@ -550,7 +569,7 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
550
569
  // The result promise below still carries the CLI's exit and stderr.
551
570
  }
552
571
  const cli = await handle.result
553
- return this.finishTurn(cli, acc.snapshot())
572
+ return this.finishTurn(cli, acc.snapshot(), invocation.account)
554
573
  }
555
574
 
556
575
  private async runPrompt(invocation: CodexCliInvocation): Promise<CodexTurn> {
@@ -560,11 +579,15 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
560
579
  } catch (error) {
561
580
  return launchFailure(error)
562
581
  }
563
- return this.finishTurn(cli, parseCodexOutput(cli.stdout))
582
+ return this.finishTurn(cli, parseCodexOutput(cli.stdout), invocation.account)
564
583
  }
565
584
 
566
585
  /** Shared post-processing of a completed CLI run. */
567
- private finishTurn(cli: CodexCliResult, parsed: ParsedCodexOutput): CodexTurn {
586
+ private finishTurn(
587
+ cli: CodexCliResult,
588
+ parsed: ParsedCodexOutput,
589
+ account?: SelectedAccount,
590
+ ): CodexTurn {
568
591
  const text = parsed.assistantText.join('\n')
569
592
  let failureMessage: string | undefined
570
593
  let loggedOut = false
@@ -588,6 +611,15 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
588
611
  failureMessage = `${this.name} runtime: Codex CLI stream ended without a turn.completed event`
589
612
  }
590
613
 
614
+ if (
615
+ failureMessage &&
616
+ account?.descriptor.kind === 'chatgpt-subscription' &&
617
+ classifyProviderError(failureMessage, { status: parsed.statuses[0], codes: parsed.codes })
618
+ .cause === 'credentials'
619
+ ) {
620
+ failureMessage = accountRemedy(account)
621
+ loggedOut = true
622
+ }
591
623
  return {
592
624
  text,
593
625
  usage: parsed.usage,
@@ -1,3 +1,4 @@
1
+ import type { SelectedAccount } from '../../config/accounts'
1
2
  /**
2
3
  * A narrow, tool-free, non-phase judgment capability. Unlike AgentRunner,
3
4
  * one-shot completions have no resumable session, skill invocation,
@@ -6,6 +7,7 @@
6
7
  */
7
8
 
8
9
  export interface OneShotCompletionInput {
10
+ account?: SelectedAccount
9
11
  prompt: string
10
12
  /** Working directory used for project context and runtime resolution. */
11
13
  cwd: string
@@ -10,12 +10,14 @@ export interface ProviderErrorHints {
10
10
  }
11
11
 
12
12
  const EXHAUSTION_CODE_PATTERNS = [
13
+ /^subscription_sharing_usage_(?:limit_exceeded|unavailable)$/,
13
14
  /(?:^|[_-])(?:billing|payment|quota|credit|balance|budget)(?:[_-]|$)/,
14
15
  /^(?:insufficient|out_of)_(?:quota|credits?|balance|funds)$/,
15
16
  /^usage_(?:limit|quota)(?:_|$)/,
16
17
  ] as const
17
18
 
18
19
  const CREDENTIAL_CODE_PATTERNS = [
20
+ /^(?:invalid_grant|refresh_token_invalidated|subscription_sharing_user_not_eligible)$/,
19
21
  /^(?:auth|authentication|authorization)(?:_|-)/,
20
22
  /^(?:unauthorized|forbidden)$/,
21
23
  /^(?:invalid|expired|missing|revoked)_(?:api_)?(?:key|token|credential)s?$/,
@@ -24,6 +26,7 @@ const CREDENTIAL_CODE_PATTERNS = [
24
26
  ] as const
25
27
 
26
28
  const EXHAUSTION_TEXT_PATTERNS = [
29
+ /subscription_sharing_usage_(?:limit_exceeded|unavailable)/i,
27
30
  /(?:^|[^a-z0-9])(?:quota(?:[_ -](?:exceeded|exhausted|depleted|refreshes?))?|(?:insufficient|exhausted|depleted)[_ -]quota)(?:$|[^a-z0-9])/i,
28
31
  /\busage[_ -]?(?:limit|quota)\b/i,
29
32
  /\b(?:billing|spending|monthly)\s+(?:limit|cap|cycle)\b/i,
@@ -36,6 +39,8 @@ const EXHAUSTION_TEXT_PATTERNS = [
36
39
  ] as const
37
40
 
38
41
  const CREDENTIAL_TEXT_PATTERNS = [
42
+ /\b(?:invalid|expired|revoked)\s+(?:oauth\s+access|bearer)\s+token\b/i,
43
+ /\bfailed to authenticate\b/i,
39
44
  /\b(?:authentication|authorization)[_ -](?:failed|required|error|invalid)\b/i,
40
45
  /\bunauthori[sz]ed\b/i,
41
46
  /\bforbidden\b/i,