@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,41 @@
1
+ import { sensitiveAccountValues } from './sensitive'
2
+ import { z } from 'zod'
3
+
4
+ const token = z
5
+ .string()
6
+ .min(1)
7
+ .max(65536)
8
+ .refine((s) => !s.includes('\0'))
9
+ export const chatgptStateSchema = z.strictObject({
10
+ version: z.literal(1),
11
+ hostId: z
12
+ .string()
13
+ .regex(/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),
14
+ clientId: z
15
+ .string()
16
+ .min(1)
17
+ .refine((s) => s !== 'dynamic_agent_client'),
18
+ subject: z.string().min(1),
19
+ scopes: z
20
+ .array(z.string())
21
+ .refine((s) => s.includes('chatgpt.tokens.use.direct') && s.includes('offline_access')),
22
+ accessToken: token,
23
+ refreshToken: token,
24
+ idToken: token,
25
+ expiresAt: z.number().finite(),
26
+ earliestRefreshAt: z.number().finite().optional(),
27
+ })
28
+ export type ChatGPTState = z.infer<typeof chatgptStateSchema>
29
+ export function credentialValues(state: ChatGPTState): string[] {
30
+ const values = [state.accessToken, state.refreshToken, state.idToken]
31
+ values.forEach((v) => {
32
+ sensitiveAccountValues.add(v)
33
+ })
34
+ return values
35
+ }
36
+ /** Provider uses absolute Unix seconds for numbers and absolute dates for strings. */
37
+ export function earliestRefreshAt(value: unknown): number | undefined {
38
+ const n =
39
+ typeof value === 'number' ? value * 1000 : typeof value === 'string' ? Date.parse(value) : NaN
40
+ return Number.isFinite(n) ? n : undefined
41
+ }
@@ -0,0 +1,194 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { sensitiveAccountValues } from './sensitive'
3
+ import {
4
+ constants,
5
+ closeSync,
6
+ fstatSync,
7
+ fsyncSync,
8
+ lstatSync,
9
+ mkdirSync,
10
+ openSync,
11
+ readFileSync,
12
+ renameSync,
13
+ unlinkSync,
14
+ writeFileSync,
15
+ } from 'node:fs'
16
+ import { dirname, join } from 'node:path'
17
+ import { randomUUID } from 'node:crypto'
18
+ import type { Account } from '../config/accounts'
19
+ import { chatgptStateSchema, credentialValues, type ChatGPTState } from './chatgpt-state'
20
+
21
+ export interface LocalCredential {
22
+ version: 1
23
+ generation: string
24
+ descriptor: Account
25
+ state: ChatGPTState
26
+ status: 'ready' | 'refreshing' | 'failed'
27
+ owner?: string
28
+ ownerPid?: number
29
+ }
30
+ const error = () =>
31
+ new Error('ChatGPT credential storage unavailable; check permissions and sign in again')
32
+ /** Shared main-checkout state. All operations fail closed on unsafe existing files. */
33
+ export class LocalCredentials {
34
+ readonly directory: string
35
+ readonly sensitive = new Set<string>()
36
+ constructor(stateRoot: string) {
37
+ this.directory = join(stateRoot, 'accounts')
38
+ }
39
+ private prepare() {
40
+ mkdirSync(dirname(this.directory), { recursive: true, mode: 0o700 })
41
+ const parent = lstatSync(dirname(this.directory))
42
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.())
43
+ throw error()
44
+ mkdirSync(this.directory, { mode: 0o700, recursive: true })
45
+ const info = lstatSync(this.directory)
46
+ if (
47
+ !info.isDirectory() ||
48
+ info.isSymbolicLink() ||
49
+ (info.mode & 0o777) !== 0o700 ||
50
+ info.uid !== process.getuid?.()
51
+ )
52
+ throw error()
53
+ }
54
+ private path(name: string) {
55
+ return join(this.directory, `${Buffer.from(name).toString('hex')}.json`)
56
+ }
57
+ private read<T>(path: string): T | undefined {
58
+ this.prepare()
59
+ let fd: number
60
+ try {
61
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW)
62
+ } catch (e) {
63
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return undefined
64
+ throw error()
65
+ }
66
+ try {
67
+ const info = fstatSync(fd)
68
+ if (
69
+ !info.isFile() ||
70
+ (info.mode & 0o777) !== 0o600 ||
71
+ info.uid !== process.getuid?.() ||
72
+ info.size > 300000
73
+ )
74
+ throw error()
75
+ return JSON.parse(readFileSync(fd, 'utf8')) as T
76
+ } catch {
77
+ throw error()
78
+ } finally {
79
+ closeSync(fd)
80
+ }
81
+ }
82
+ private write(path: string, value: unknown) {
83
+ this.prepare()
84
+ this.read(path)
85
+ const temporary = `${path}.${randomUUID()}`
86
+ const fd = openSync(temporary, 'wx', 0o600)
87
+ try {
88
+ writeFileSync(fd, JSON.stringify(value))
89
+ fsyncSync(fd)
90
+ } finally {
91
+ closeSync(fd)
92
+ }
93
+ try {
94
+ renameSync(temporary, path)
95
+ } finally {
96
+ try {
97
+ unlinkSync(temporary)
98
+ } catch {
99
+ /* moved */
100
+ }
101
+ }
102
+ const directory = openSync(this.directory, constants.O_RDONLY)
103
+ try {
104
+ fsyncSync(directory)
105
+ } finally {
106
+ closeSync(directory)
107
+ }
108
+ }
109
+ /** SQLite's filesystem lock is released by the OS on process death.
110
+ * Only locking lives here; the protected atomic records remain authoritative. */
111
+ locked<T>(_name: string, operation: () => T): T {
112
+ this.prepare()
113
+ const path = join(this.directory, 'locks.sqlite')
114
+ try {
115
+ const fd = openSync(path, 'wx', 0o600)
116
+ closeSync(fd)
117
+ } catch (e) {
118
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw error()
119
+ }
120
+ const info = lstatSync(path)
121
+ if (
122
+ !info.isFile() ||
123
+ info.isSymbolicLink() ||
124
+ (info.mode & 0o777) !== 0o600 ||
125
+ info.uid !== process.getuid?.()
126
+ )
127
+ throw error()
128
+ const db = new Database(path)
129
+ try {
130
+ db.exec('PRAGMA busy_timeout=1000')
131
+ db.exec('BEGIN IMMEDIATE')
132
+ try {
133
+ const result = operation()
134
+ db.exec('COMMIT')
135
+ return result
136
+ } catch (e) {
137
+ db.exec('ROLLBACK')
138
+ throw e
139
+ }
140
+ } finally {
141
+ db.close()
142
+ }
143
+ }
144
+ hostId(): string {
145
+ return this.locked('__host', () => {
146
+ const path = join(this.directory, 'host.json')
147
+ const old = this.read<{ id: string }>(path)
148
+ if (old) {
149
+ if (!/^urn:uuid:[0-9a-f-]{36}$/.test(old.id)) throw error()
150
+ return old.id
151
+ }
152
+ const id = `urn:uuid:${randomUUID()}`
153
+ this.write(path, { id })
154
+ return id
155
+ })
156
+ }
157
+ load(name: string): LocalCredential | undefined {
158
+ const record = this.read<LocalCredential>(this.path(name))
159
+ if (!record) return undefined
160
+ if (
161
+ record.version !== 1 ||
162
+ typeof record.generation !== 'string' ||
163
+ !['ready', 'refreshing', 'failed'].includes(record.status) ||
164
+ record.descriptor.kind !== 'chatgpt-subscription'
165
+ )
166
+ throw error()
167
+ record.state = chatgptStateSchema.parse(record.state)
168
+ credentialValues(record.state).forEach((v) => {
169
+ this.sensitive.add(v)
170
+ sensitiveAccountValues.add(v)
171
+ })
172
+ return record
173
+ }
174
+ save(name: string, record: LocalCredential): void {
175
+ credentialValues(record.state).forEach((v) => {
176
+ this.sensitive.add(v)
177
+ sensitiveAccountValues.add(v)
178
+ })
179
+ this.write(this.path(name), record)
180
+ }
181
+ install(name: string, descriptor: Account, state: ChatGPTState): void {
182
+ this.locked(name, () => {
183
+ const old = this.load(name)
184
+ this.save(name, {
185
+ version: 1,
186
+ generation: randomUUID(),
187
+ descriptor,
188
+ state,
189
+ status: 'ready',
190
+ ...(old?.owner ? { owner: old.owner, ownerPid: old.ownerPid } : {}),
191
+ })
192
+ })
193
+ }
194
+ }
@@ -0,0 +1,106 @@
1
+ import { sensitiveAccountValues } from './sensitive'
2
+ import { randomBytes } from 'node:crypto'
3
+ import type { LocalCredentials } from './local-credentials'
4
+
5
+ /** A per-launch capability gates a fixed Responses endpoint. It never refreshes. */
6
+ export function localInference(
7
+ credentials: LocalCredentials,
8
+ name: string,
9
+ fetcher: (input: string, init?: RequestInit) => Promise<Response> = fetch,
10
+ ) {
11
+ credentials.load(name)
12
+ const capability = randomBytes(32).toString('hex')
13
+ credentials.sensitive.add(capability)
14
+ sensitiveAccountValues.add(capability)
15
+ const server = Bun.serve({
16
+ hostname: '127.0.0.1',
17
+ port: 0,
18
+ maxRequestBodySize: 16000000,
19
+ async fetch(request) {
20
+ const url = new URL(request.url)
21
+ if (
22
+ request.method !== 'POST' ||
23
+ url.pathname !== '/v1/responses' ||
24
+ url.search ||
25
+ request.headers.get('authorization') !== `Bearer ${capability}`
26
+ )
27
+ return new Response(null, { status: 403 })
28
+ try {
29
+ const record = credentials.load(name)
30
+ if (!record || record.status === 'failed' || record.state.expiresAt <= Date.now())
31
+ return new Response(null, { status: 401 })
32
+ const body = await request.text()
33
+ if (body.length > 16000000) return new Response(null, { status: 413 })
34
+ const response = await fetcher('https://api.openai.com/v1/responses', {
35
+ method: 'POST',
36
+ redirect: 'error',
37
+ signal: request.signal,
38
+ headers: {
39
+ authorization: `Bearer ${record.state.accessToken}`,
40
+ 'content-type': 'application/json',
41
+ },
42
+ body,
43
+ })
44
+ if (response.status === 401) {
45
+ await response.body?.cancel()
46
+ credentials.locked(name, () => {
47
+ const current = credentials.load(name)
48
+ if (
49
+ current?.generation === record.generation &&
50
+ current.state.accessToken === record.state.accessToken
51
+ )
52
+ credentials.save(name, { ...current, status: 'failed' })
53
+ })
54
+ return Response.json(
55
+ {
56
+ error: { code: 'invalid_token', message: 'ChatGPT account rejected; sign in again' },
57
+ },
58
+ { status: 401 },
59
+ )
60
+ }
61
+ // Never relay a provider diagnostic containing the host bearer into the child.
62
+ const decoder = new TextDecoder()
63
+ let pending = ''
64
+ const needles = () =>
65
+ [...credentials.sensitive]
66
+ .flatMap((s) => [s, JSON.stringify(s).slice(1, -1)])
67
+ .sort((a, b) => b.length - a.length)
68
+ const clean = (value: string) => {
69
+ for (const secret of needles()) value = value.split(secret).join('[REDACTED]')
70
+ return value
71
+ }
72
+ const filtered = response.body?.pipeThrough(
73
+ new TransformStream<Uint8Array, Uint8Array>({
74
+ transform(chunk, controller) {
75
+ pending = clean(pending + decoder.decode(chunk, { stream: true }))
76
+ let retained = 0
77
+ for (const secret of needles())
78
+ for (let n = 1; n < secret.length && n <= pending.length; n++)
79
+ if (pending.endsWith(secret.slice(0, n))) retained = Math.max(retained, n)
80
+ const output = retained ? pending.slice(0, -retained) : pending
81
+ if (output) controller.enqueue(new TextEncoder().encode(output))
82
+ pending = retained ? pending.slice(-retained) : ''
83
+ },
84
+ flush(controller) {
85
+ controller.enqueue(new TextEncoder().encode(clean(pending + decoder.decode())))
86
+ },
87
+ }),
88
+ )
89
+ return new Response(filtered, {
90
+ status: response.status,
91
+ headers: {
92
+ 'content-type': response.headers.get('content-type') ?? 'text/event-stream',
93
+ 'cache-control': 'no-store',
94
+ },
95
+ })
96
+ } catch {
97
+ return new Response(null, { status: 401 })
98
+ }
99
+ },
100
+ })
101
+ return {
102
+ baseUrl: `http://127.0.0.1:${server.port}/v1`,
103
+ capability,
104
+ close: () => server.stop(true),
105
+ }
106
+ }
@@ -0,0 +1,123 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { Accounts } from '../config/accounts'
3
+ import { refreshChatGPT } from './chatgpt-oauth'
4
+ import type { LocalCredentials } from './local-credentials'
5
+ import type { ChatGPTState } from './chatgpt-state'
6
+
7
+ /** One claimed dispatcher/validator owns renewal. Durable refreshing state is
8
+ * written before HTTP, and uncertain completion is terminal for that generation. */
9
+ export class LocalAccountOwner {
10
+ readonly id = randomUUID()
11
+ constructor(
12
+ readonly credentials: LocalCredentials,
13
+ private readonly refresh = refreshChatGPT,
14
+ ) {}
15
+ claim(name: string): void {
16
+ this.credentials.locked(name, () => {
17
+ const r = this.credentials.load(name)
18
+ if (!r || (r.owner && r.owner !== this.id && !ownerProcessEnded(r.ownerPid)))
19
+ throw new Error('ChatGPT account already owned or missing')
20
+ if (r.status === 'refreshing') r.status = 'failed'
21
+ this.credentials.save(name, { ...r, owner: this.id, ownerPid: process.pid })
22
+ })
23
+ }
24
+ release(name: string): void {
25
+ this.credentials.locked(name, () => {
26
+ const r = this.credentials.load(name)
27
+ if (r?.owner === this.id) {
28
+ delete r.owner
29
+ delete r.ownerPid
30
+ this.credentials.save(name, r)
31
+ }
32
+ })
33
+ }
34
+ async tick(accounts: Accounts, now = Date.now()): Promise<Record<string, string>> {
35
+ const env: Record<string, string> = {}
36
+ for (const [name, descriptor] of Object.entries(accounts)) {
37
+ if (descriptor.kind !== 'chatgpt-subscription') continue
38
+ let r = this.credentials.load(name)
39
+ if (!r || r.owner !== this.id || JSON.stringify(r.descriptor) !== JSON.stringify(descriptor))
40
+ throw new Error('ChatGPT account ownership or descriptor changed; sign in again')
41
+ if (r.status !== 'ready') throw new Error('ChatGPT account failed; sign in again')
42
+ if (now >= Math.max(r.state.earliestRefreshAt ?? 0, r.state.expiresAt - 60000)) {
43
+ const claim = this.credentials.locked(name, () => {
44
+ const current = this.credentials.load(name)
45
+ if (
46
+ !current ||
47
+ current.owner !== this.id ||
48
+ current.generation !== r!.generation ||
49
+ current.status !== 'ready'
50
+ )
51
+ throw new Error('ChatGPT account changed')
52
+ this.credentials.save(name, { ...current, status: 'refreshing' })
53
+ return current
54
+ })
55
+ try {
56
+ const state: ChatGPTState = await this.refresh(claim.state, AbortSignal.timeout(15000))
57
+ this.credentials.locked(name, () => {
58
+ const current = this.credentials.load(name)
59
+ if (
60
+ current?.generation === claim.generation &&
61
+ current.owner === this.id &&
62
+ current.status === 'refreshing'
63
+ )
64
+ this.credentials.save(name, { ...current, state, status: 'ready' })
65
+ })
66
+ } catch {
67
+ this.credentials.locked(name, () => {
68
+ const current = this.credentials.load(name)
69
+ if (current?.generation === claim.generation && current.status === 'refreshing')
70
+ this.credentials.save(name, { ...current, status: 'failed' })
71
+ })
72
+ throw new Error('ChatGPT refresh failed; sign in again')
73
+ }
74
+ r = this.credentials.load(name)!
75
+ }
76
+ if (r.status !== 'ready' || r.state.expiresAt <= now)
77
+ throw new Error('ChatGPT account expired; sign in again')
78
+ env[descriptor.credentialEnv] = r.state.accessToken
79
+ }
80
+ return env
81
+ }
82
+ }
83
+
84
+ /** Unknown ownership and permission errors remain live; only OS proof of exit
85
+ * permits reclaiming a record. An abandoned rotating attempt still fails closed. */
86
+ function ownerProcessEnded(pid: number | undefined): boolean {
87
+ if (!Number.isSafeInteger(pid) || pid! <= 0) return false
88
+ try {
89
+ process.kill(pid!, 0)
90
+ return false
91
+ } catch (error) {
92
+ return (error as NodeJS.ErrnoException).code === 'ESRCH'
93
+ }
94
+ }
95
+
96
+ /** Dispatcher renewal also recovers ready credentials after sleep or downtime.
97
+ * Access expiry is not refresh failure; only the owner may consume refresh state. */
98
+ export async function renewLocalAccounts(
99
+ owner: LocalAccountOwner,
100
+ accounts: Accounts,
101
+ env: Record<string, string | undefined>,
102
+ claimed: Set<string>,
103
+ now = Date.now(),
104
+ ): Promise<void> {
105
+ for (const [name, descriptor] of Object.entries(accounts)) {
106
+ if (descriptor.kind !== 'chatgpt-subscription') continue
107
+ try {
108
+ const record = owner.credentials.load(name)
109
+ if (!record || record.status === 'failed') {
110
+ delete env[descriptor.credentialEnv]
111
+ continue
112
+ }
113
+ owner.claim(name)
114
+ claimed.add(name)
115
+ // Only expose a still-valid access value during the rotating HTTP call.
116
+ if (record.state.expiresAt > now) env[descriptor.credentialEnv] = record.state.accessToken
117
+ else delete env[descriptor.credentialEnv]
118
+ Object.assign(env, await owner.tick({ [name]: descriptor }, now))
119
+ } catch {
120
+ delete env[descriptor.credentialEnv]
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,2 @@
1
+ /** Host-only registry: retain previous generations until process exit. */
2
+ export const sensitiveAccountValues = new Set<string>()
@@ -0,0 +1,147 @@
1
+ import { join } from 'node:path'
2
+ import { connectedProject } from './connect'
3
+ import { parseConfig } from '../config/load'
4
+ import { ProjectCredentials } from './project-credentials'
5
+ import { LocalCredentials } from '../accounts/local-credentials'
6
+ import { transaction, authorizationUrl, exchangeCode } from '../accounts/chatgpt-oauth'
7
+ import type { Exec } from '../ports/workspace/git-worktree'
8
+ import {
9
+ AUTOBUILD_VERSION,
10
+ AUTOBUILD_VERSION_HEADER,
11
+ REMOTE_STORE_PROTOCOL_VERSION,
12
+ REMOTE_STORE_PROTOCOL_VERSION_HEADER,
13
+ } from '../store/remote/version'
14
+
15
+ export async function abAccountsLogin(
16
+ name: string,
17
+ opts: {
18
+ cwd: string
19
+ env: Record<string, string | undefined>
20
+ exec: Exec
21
+ print: (s: string) => void
22
+ destination?: 'local' | 'project'
23
+ signal?: AbortSignal
24
+ browser?: (url: string) => Promise<void>
25
+ },
26
+ ): Promise<void> {
27
+ const project = await connectedProject(opts)
28
+ const account = parseConfig(project.text).accounts[name]
29
+ if (account?.kind !== 'chatgpt-subscription')
30
+ throw new Error('Select a declared ChatGPT subscription account')
31
+ const destination = opts.destination ?? (project.service ? 'project' : 'local')
32
+ if (destination === 'project' && !project.service)
33
+ throw new Error('Project login requires ab connect')
34
+ const credential =
35
+ destination === 'project'
36
+ ? new ProjectCredentials(opts.env).load(project.service!, project.repo)
37
+ : undefined
38
+ if (destination === 'project' && !credential)
39
+ throw new Error('Missing project credential; run ab connect')
40
+ const local = new LocalCredentials(join(project.checkout, '.autobuild'))
41
+ // Host identity is nonsecret. Project credentials themselves are never written here.
42
+ let hostId: string
43
+ if (destination === 'project') {
44
+ if (local.load(name))
45
+ throw new Error(
46
+ 'A local credential already owns this account; use a separate account for the project',
47
+ )
48
+ const response = await fetch(
49
+ `${project.service}/secrets/v1/chatgpt-host?repo=${encodeURIComponent(project.repo)}`,
50
+ {
51
+ headers: {
52
+ authorization: `Bearer ${credential!.token}`,
53
+ [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
54
+ [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
55
+ },
56
+ signal: AbortSignal.timeout(15000),
57
+ redirect: 'error',
58
+ },
59
+ )
60
+ if (!response.ok) throw new Error('Project host identity unavailable')
61
+ const result = await response.json()
62
+ if (
63
+ result?.version !== 1 ||
64
+ typeof result.hostId !== 'string' ||
65
+ !/^urn:uuid:[0-9a-f-]{36}$/.test(result.hostId)
66
+ )
67
+ throw new Error('Invalid project host identity')
68
+ hostId = result.hostId
69
+ } else hostId = local.hostId()
70
+ const previous = destination === 'local' ? local.load(name)?.state : undefined
71
+ opts.print(
72
+ `Continue with ChatGPT: account ${JSON.stringify(name)}, destination ${destination === 'local' ? 'local dispatcher' : 'connected project'}.`,
73
+ )
74
+ const signal = AbortSignal.any([
75
+ AbortSignal.timeout(300000),
76
+ ...(opts.signal ? [opts.signal] : []),
77
+ ])
78
+ let resolveCallback!: (url: URL) => void
79
+ let rejectCallback!: (error: Error) => void
80
+ const received = new Promise<URL>((resolve, reject) => {
81
+ resolveCallback = resolve
82
+ rejectCallback = reject
83
+ })
84
+ void received.catch(() => {})
85
+ const server = Bun.serve({
86
+ hostname: '127.0.0.1',
87
+ port: 0,
88
+ fetch(request) {
89
+ const url = new URL(request.url)
90
+ if (url.pathname !== '/auth/callback') return new Response('Not found', { status: 404 })
91
+ resolveCallback(url)
92
+ return new Response('Return to the terminal to complete sign-in.', {
93
+ headers: { 'cache-control': 'no-store' },
94
+ })
95
+ },
96
+ })
97
+ const abort = () => rejectCallback(new Error('ChatGPT sign-in cancelled or timed out'))
98
+ signal.addEventListener('abort', abort, { once: true })
99
+ try {
100
+ if (signal.aborted) throw new Error('Sign-in cancelled')
101
+ const t = transaction(`http://127.0.0.1:${server.port}/auth/callback`, hostId, previous)
102
+ const url = authorizationUrl(t)
103
+ const opening = (async () => {
104
+ if (opts.browser) await opts.browser(url)
105
+ else {
106
+ const command = process.platform === 'darwin' ? 'open' : 'xdg-open'
107
+ const result = await opts.exec([command, url], { cwd: opts.cwd })
108
+ if (result.exitCode !== 0) throw new Error('Unable to open system browser')
109
+ }
110
+ })()
111
+ void opening.catch(() => {})
112
+ await Promise.race([opening, received.then(() => {})])
113
+ const state = await exchangeCode(t, await received, signal)
114
+ if (destination === 'local') local.install(name, account, state)
115
+ else {
116
+ const response = await fetch(`${project.service}/secrets/v1/chatgpt`, {
117
+ method: 'POST',
118
+ redirect: 'error',
119
+ signal,
120
+ headers: {
121
+ 'content-type': 'application/json',
122
+ authorization: `Bearer ${credential!.token}`,
123
+ [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
124
+ [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
125
+ },
126
+ body: JSON.stringify({
127
+ version: 1,
128
+ repo: project.repo,
129
+ name: account.credentialEnv,
130
+ state,
131
+ }),
132
+ })
133
+ if (!response.ok) throw new Error('Project sign-in write failed')
134
+ const result = await response.json()
135
+ if (result?.version !== 1 || result?.ok !== true)
136
+ throw new Error('Project sign-in write not acknowledged')
137
+ }
138
+ opts.print(`ChatGPT account ${JSON.stringify(name)} saved for ${destination}.`)
139
+ } catch {
140
+ throw new Error(
141
+ `ChatGPT sign-in failed for account ${JSON.stringify(name)}; run ab accounts login again`,
142
+ )
143
+ } finally {
144
+ signal.removeEventListener('abort', abort)
145
+ await server.stop(true)
146
+ }
147
+ }
@@ -3,7 +3,7 @@ import type { DashboardRendererResolver } from './dashboard/render'
3
3
  import { loadDotEnv } from './dotenv'
4
4
  import { parseDispatchArgs } from './dispatch-args'
5
5
  import { launchDispatcher } from './dispatch-launcher'
6
- import { DISPATCH_GENERATION_ENV } from './dispatch-launch-contract'
6
+ import { DISPATCH_GENERATION_ENV, DISPATCH_CONDITIONAL_ENV } from './dispatch-launch-contract'
7
7
  export {
8
8
  usesGenericSessionlessSigintHandler,
9
9
  installSessionlessSigintHandler,
@@ -15,9 +15,11 @@ export async function runBinary(
15
15
  ): Promise<number> {
16
16
  delete process.env.AB_DISPATCH_LAUNCH_CONTEXT
17
17
  delete process.env[DISPATCH_GENERATION_ENV]
18
+ delete process.env[DISPATCH_CONDITIONAL_ENV]
18
19
  if (argv[0] !== '--version') loadDotEnv(join(process.cwd(), '.env'), process.env)
19
20
  delete process.env.AB_DISPATCH_LAUNCH_CONTEXT
20
21
  delete process.env[DISPATCH_GENERATION_ENV]
22
+ delete process.env[DISPATCH_CONDITIONAL_ENV]
21
23
  if (
22
24
  argv[0] === 'dispatch' &&
23
25
  !(argv.length === 2 && argv[1] === '--help') &&
@@ -37,7 +37,7 @@ function requireOperator(env: ConnectOptions['env']) {
37
37
  )
38
38
  throw new Error('connect and disconnect are unavailable inside build or harvest sessions')
39
39
  }
40
- async function project(opts: ConnectOptions) {
40
+ export async function connectedProject(opts: ConnectOptions) {
41
41
  requireOperator(opts.env)
42
42
  const checkout = await resolveMainRepo(opts.cwd, opts.exec)
43
43
  const remote = await opts.exec(['git', 'remote', 'get-url', 'origin'], { cwd: checkout })
@@ -97,7 +97,7 @@ async function atomicConfig(path: string, before: string, after: string) {
97
97
  }
98
98
  export async function abConnect(raw: string | undefined, opts: ConnectOptions): Promise<void> {
99
99
  if (opts.tickets && opts.builds) throw new Error('Choose --tickets or --builds')
100
- const p = await project(opts)
100
+ const p = await connectedProject(opts)
101
101
  if (opts.tickets && (p.table.tickets as { source?: string } | undefined)?.source !== 'hosted')
102
102
  throw new Error('ab connect --tickets requires [tickets] source = "hosted"')
103
103
  const credentials = new ProjectCredentials(opts.env)
@@ -309,7 +309,7 @@ export async function abConnect(raw: string | undefined, opts: ConnectOptions):
309
309
  }
310
310
  export async function abDisconnect(opts: ConnectOptions): Promise<void> {
311
311
  if (opts.tickets && opts.builds) throw new Error('Choose --tickets or --builds')
312
- const p = await project(opts)
312
+ const p = await connectedProject(opts)
313
313
  if (
314
314
  !opts.tickets &&
315
315
  !opts.builds &&