@defrex/autobuild 1.1.0 → 1.3.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 (157) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +249 -15
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +130 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +4 -1
  7. package/docs/architecture.md +224 -12
  8. package/docs/build-store.md +3 -41
  9. package/docs/builds.md +2 -0
  10. package/docs/cli.md +14 -0
  11. package/docs/configuration-overview.md +117 -0
  12. package/docs/configuration.md +266 -141
  13. package/docs/dispatcher-hosting.md +18 -33
  14. package/docs/intake.md +2 -0
  15. package/docs/integration-tree.md +16 -5
  16. package/docs/merge-policy.md +1 -3
  17. package/docs/operating.md +1 -2
  18. package/docs/operator-api.md +144 -53
  19. package/docs/operator-surfaces.md +32 -20
  20. package/docs/overview.md +1 -1
  21. package/docs/plugin-authoring.md +27 -1
  22. package/docs/remote-store-protocol.md +259 -91
  23. package/docs/remote-ticket-protocol.md +29 -49
  24. package/docs/restacking.md +45 -0
  25. package/docs/seams.md +8 -8
  26. package/docs/setup.md +34 -129
  27. package/docs/spec-standard.md +4 -2
  28. package/docs/ticket-dependencies.md +8 -0
  29. package/docs/ticket-sources.md +18 -0
  30. package/docs/troubleshooting.md +7 -11
  31. package/docs/upgrading.md +1 -1
  32. package/docs/workspaces.md +4 -4
  33. package/package.json +14 -5
  34. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  35. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  36. package/packages/core/src/accounts/local-credentials.ts +194 -0
  37. package/packages/core/src/accounts/local-inference.ts +106 -0
  38. package/packages/core/src/accounts/local-owner.ts +123 -0
  39. package/packages/core/src/accounts/sensitive.ts +2 -0
  40. package/packages/core/src/cli/accounts.ts +147 -0
  41. package/packages/core/src/cli/binary.ts +3 -1
  42. package/packages/core/src/cli/connect.ts +3 -3
  43. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  44. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  45. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  46. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  47. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  48. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  49. package/packages/core/src/cli/dispatch.ts +135 -27
  50. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  51. package/packages/core/src/cli/forge-clear.ts +30 -0
  52. package/packages/core/src/cli/help.ts +17 -0
  53. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  54. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  55. package/packages/core/src/cli/init-validation.ts +160 -18
  56. package/packages/core/src/cli/main.ts +72 -0
  57. package/packages/core/src/cli/publication-settlement.ts +4 -1
  58. package/packages/core/src/cli/secrets.ts +173 -0
  59. package/packages/core/src/cli/store-opening.ts +11 -1
  60. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  61. package/packages/core/src/cli/watch.ts +12 -14
  62. package/packages/core/src/config/accounts.ts +101 -0
  63. package/packages/core/src/config/live.ts +14 -1
  64. package/packages/core/src/config/roles.ts +54 -3
  65. package/packages/core/src/config/schema.ts +60 -0
  66. package/packages/core/src/events/catalog.ts +1 -0
  67. package/packages/core/src/events/compatibility.ts +2 -1
  68. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  69. package/packages/core/src/events/payloads.ts +13 -0
  70. package/packages/core/src/events/policy.ts +9 -0
  71. package/packages/core/src/events/repository.ts +75 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +278 -0
  73. package/packages/core/src/kernel/change-presence.ts +74 -8
  74. package/packages/core/src/kernel/engine.ts +8 -0
  75. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  76. package/packages/core/src/kernel/node-polling.ts +40 -7
  77. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  78. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  79. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  80. package/packages/core/src/kernel/read-facts.ts +6 -0
  81. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  82. package/packages/core/src/kernel/reducer.ts +4 -1
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +4 -0
  87. package/packages/core/src/operator/protocol.ts +6 -0
  88. package/packages/core/src/operator/registry.ts +42 -1
  89. package/packages/core/src/operator/tickets.ts +25 -4
  90. package/packages/core/src/plugins/manifest.ts +2 -1
  91. package/packages/core/src/ports/runner/account-env.ts +139 -0
  92. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  93. package/packages/core/src/ports/runner/claude.ts +70 -42
  94. package/packages/core/src/ports/runner/codex.ts +63 -31
  95. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  96. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  97. package/packages/core/src/ports/runner/routing.ts +35 -4
  98. package/packages/core/src/ports/tickets/contract.ts +58 -0
  99. package/packages/core/src/ports/tickets/tree.ts +1 -1
  100. package/packages/core/src/ports/types.ts +28 -7
  101. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  102. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  103. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  104. package/packages/core/src/ports/workspace/create.ts +2 -0
  105. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  106. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  107. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  108. package/packages/core/src/processes/build-runner.ts +32 -1
  109. package/packages/core/src/processes/dispatcher.ts +493 -121
  110. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  111. package/packages/core/src/processes/execution-settlement.ts +21 -3
  112. package/packages/core/src/processes/harvest-runner.ts +68 -8
  113. package/packages/core/src/processes/harvest.ts +11 -16
  114. package/packages/core/src/processes/repo-view.ts +3 -0
  115. package/packages/core/src/project-secrets.ts +105 -0
  116. package/packages/core/src/secret-name.ts +41 -0
  117. package/packages/core/src/store/account-redaction.ts +156 -0
  118. package/packages/core/src/store/artifact-meta.ts +7 -0
  119. package/packages/core/src/store/contract.ts +60 -1
  120. package/packages/core/src/store/memory.ts +4 -0
  121. package/packages/core/src/store/reducer-value-shapes.json +7389 -6647
  122. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  123. package/packages/core/src/store/remote/client.ts +85 -50
  124. package/packages/core/src/store/remote/compatibility.ts +57 -0
  125. package/packages/core/src/store/remote/index.ts +6 -0
  126. package/packages/core/src/store/remote/protocol.ts +8 -1
  127. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  128. package/packages/core/src/store/remote/version.ts +4 -0
  129. package/packages/core/src/store/repo-state-events.ts +4 -2
  130. package/packages/core/src/store/snapshots.ts +16 -3
  131. package/packages/core/src/store/types.ts +2 -0
  132. package/packages/core/src/testing/dispatch-read-budget.ts +266 -5
  133. package/packages/core/src/testing/index.ts +2 -1
  134. package/packages/core/src/testing/reduced-read-budget.ts +560 -5
  135. package/skills/guide/SKILL.md +164 -37
  136. package/skills/guide/references/accounts.md +130 -0
  137. package/skills/guide/references/integration-tree.md +16 -5
  138. package/skills/guide/references/merge-policy.md +1 -3
  139. package/skills/guide/references/operator-api.md +144 -53
  140. package/skills/guide/references/plugin-authoring.md +27 -1
  141. package/skills/guide/references/remote-store-protocol.md +259 -91
  142. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  143. package/skills/guide/references/restacking.md +45 -0
  144. package/skills/guide/references/setup.md +34 -129
  145. package/skills/guide/references/spec-standard.md +4 -2
  146. package/skills/guide/references/ticket-dependencies.md +8 -0
  147. package/skills/harvest/SKILL.md +3 -1
  148. package/skills/harvest-review/SKILL.md +3 -1
  149. package/skills/operate/SKILL.md +26 -11
  150. package/skills/reconcile/SKILL.md +6 -0
  151. package/skills/spec/SKILL.md +1 -1
  152. package/skills/tickets/SKILL.md +10 -5
  153. package/templates/hosted-service/package.json +2 -2
  154. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  155. package/docs/hosted-dispatcher.md +0 -278
  156. package/docs/hosted-service.md +0 -304
  157. package/docs/mcp.md +0 -150
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -90,6 +90,14 @@
90
90
  "./connection": {
91
91
  "types": "./packages/core/src/connection.ts",
92
92
  "import": "./packages/core/src/connection.ts"
93
+ },
94
+ "./project-secrets": {
95
+ "types": "./packages/core/src/project-secrets.ts",
96
+ "import": "./packages/core/src/project-secrets.ts"
97
+ },
98
+ "./secret-name": {
99
+ "types": "./packages/core/src/secret-name.ts",
100
+ "import": "./packages/core/src/secret-name.ts"
93
101
  }
94
102
  },
95
103
  "files": [
@@ -127,13 +135,13 @@
127
135
  "release": "bun tools/release.ts",
128
136
  "postgres:migrate": "bun packages/postgres-store/src/bin.ts migrate",
129
137
  "docs:configuration": "bun tools/configuration-reference.ts --write",
130
- "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
138
+ "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/reducer-value-shapes.ts --check && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
131
139
  "check:build": "bun tools/workspace-manifest-check.ts && bun tools/bin-mode-check.ts && bun tools/publish-contents-check.ts && bun tools/publish-imports-check.ts",
132
140
  "format:staged": "git-format-staged --formatter './node_modules/.bin/biome format --stdin-file-path {}' '*.js' '*.jsx' '*.ts' '*.tsx' '*.json' '*.jsonc' '*.css' '*.graphql' '*.gql'",
133
141
  "prepare": "husky",
134
142
  "test": "bun tools/test-temp-leaks.ts unit",
135
143
  "test:integration": "bun tools/test-temp-leaks.ts integration",
136
- "typecheck": "tsc --noEmit"
144
+ "typecheck": "node --max-old-space-size=4096 ./node_modules/typescript/bin/tsc --noEmit"
137
145
  },
138
146
  "dependencies": {
139
147
  "@ai-sdk/gateway": "4.0.82",
@@ -141,14 +149,15 @@
141
149
  "@vercel/sandbox": "^3.1.0",
142
150
  "ai": "^7.0.101",
143
151
  "drizzle-orm": "^0.45.2",
152
+ "jose": "^6.2.13",
144
153
  "semver": "^7.7.4",
145
154
  "smol-toml": "^1.7.0",
146
155
  "zod": "^4.4.3"
147
156
  },
148
157
  "devDependencies": {
149
158
  "@biomejs/biome": "2.5.5",
150
- "@defrex/autobuild-postgres-store": "1.1.0",
151
- "@defrex/autobuild-vercel-sandbox": "1.1.0",
159
+ "@defrex/autobuild-postgres-store": "1.3.0",
160
+ "@defrex/autobuild-vercel-sandbox": "1.3.0",
152
161
  "@resvg/resvg-js": "2.6.2",
153
162
  "@types/bun": "^1.3.14",
154
163
  "@types/node": "^24.0.0",
@@ -0,0 +1,216 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'
3
+ import { chatgptStateSchema, earliestRefreshAt, type ChatGPTState } from './chatgpt-state'
4
+
5
+ const issuer = 'https://auth.openai.com'
6
+ export const CHATGPT_RESOURCE = 'https://api.openai.com/v1'
7
+ const tokenEndpoint = `${issuer}/api/accounts/oauth/token`
8
+ const scopes = 'openid profile email offline_access resource.invoke chatgpt.tokens.use.direct'
9
+ const failure = () => new Error('ChatGPT authorization failed; sign in again')
10
+ type Fetch = typeof globalThis.fetch
11
+ export interface OAuthTransaction {
12
+ state: string
13
+ nonce: string
14
+ verifier: string
15
+ redirectUri: string
16
+ hostId: string
17
+ previous?: ChatGPTState
18
+ }
19
+ export function transaction(
20
+ redirectUri: string,
21
+ hostId: string,
22
+ previous?: ChatGPTState,
23
+ ): OAuthTransaction {
24
+ const random = () => randomBytes(32).toString('base64url')
25
+ return {
26
+ state: random(),
27
+ nonce: random(),
28
+ verifier: random(),
29
+ redirectUri,
30
+ hostId,
31
+ ...(previous ? { previous } : {}),
32
+ }
33
+ }
34
+ export function authorizationUrl(t: OAuthTransaction): string {
35
+ const url = new URL(`${issuer}/api/accounts/authorize`)
36
+ url.search = new URLSearchParams({
37
+ client_id: t.previous?.clientId ?? 'dynamic_agent_client',
38
+ ...(t.previous ? { id_token_hint: t.previous.idToken } : { agent_name_hint: 'autobuild' }),
39
+ ext_agent_host_id: t.hostId,
40
+ response_type: 'code',
41
+ redirect_uri: t.redirectUri,
42
+ resource: CHATGPT_RESOURCE,
43
+ scope: scopes,
44
+ state: t.state,
45
+ nonce: t.nonce,
46
+ code_challenge_method: 'S256',
47
+ code_challenge: createHash('sha256').update(t.verifier).digest('base64url'),
48
+ }).toString()
49
+ return url.href
50
+ }
51
+ export function callback(t: OAuthTransaction, url: URL): { code: string; clientId: string } {
52
+ if (
53
+ url.pathname !== '/auth/callback' ||
54
+ url.searchParams.getAll('state').length !== 1 ||
55
+ url.searchParams.get('state') !== t.state ||
56
+ url.searchParams.has('error')
57
+ )
58
+ throw failure()
59
+ const clientId = url.searchParams.get('client_id') ?? t.previous?.clientId
60
+ const code = url.searchParams.get('code')
61
+ if (
62
+ !code ||
63
+ !clientId ||
64
+ clientId === 'dynamic_agent_client' ||
65
+ (t.previous && clientId !== t.previous.clientId) ||
66
+ url.searchParams.getAll('code').length !== 1 ||
67
+ url.searchParams.getAll('client_id').length > 1
68
+ )
69
+ throw failure()
70
+ return { code, clientId }
71
+ }
72
+ const jwks = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), {
73
+ timeoutDuration: 15000,
74
+ })
75
+ export async function verifyIdentity(
76
+ idToken: string,
77
+ clientId: string,
78
+ nonce?: string,
79
+ keys: JWTVerifyGetKey = jwks,
80
+ ): Promise<string> {
81
+ const { payload } = await jwtVerify(idToken, keys, {
82
+ issuer,
83
+ audience: clientId,
84
+ requiredClaims: ['exp', 'sub', ...(nonce ? ['nonce'] : [])],
85
+ algorithms: ['RS256'],
86
+ clockTolerance: 5,
87
+ })
88
+ if (!payload.sub || (nonce !== undefined && payload.nonce !== nonce)) throw failure()
89
+ return payload.sub
90
+ }
91
+ async function request(
92
+ body: URLSearchParams,
93
+ signal: AbortSignal,
94
+ fetcher: Fetch,
95
+ ): Promise<Record<string, unknown>> {
96
+ try {
97
+ const response = await fetcher(tokenEndpoint, {
98
+ method: 'POST',
99
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
100
+ body,
101
+ signal,
102
+ redirect: 'error',
103
+ })
104
+ if (!response.ok) throw failure()
105
+ const text = await response.text()
106
+ if (text.length > 300000) throw failure()
107
+ const value: unknown = JSON.parse(text)
108
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw failure()
109
+ return value as Record<string, unknown>
110
+ } catch {
111
+ throw failure()
112
+ }
113
+ }
114
+ export async function parseTokens(
115
+ raw: Record<string, unknown>,
116
+ registration: {
117
+ hostId: string
118
+ clientId: string
119
+ subject?: string
120
+ nonce?: string
121
+ previous?: ChatGPTState
122
+ },
123
+ verify = verifyIdentity,
124
+ now = Date.now(),
125
+ ): Promise<ChatGPTState> {
126
+ try {
127
+ if (
128
+ typeof raw.access_token !== 'string' ||
129
+ typeof raw.refresh_token !== 'string' ||
130
+ typeof raw.expires_in !== 'number' ||
131
+ !Number.isFinite(raw.expires_in) ||
132
+ raw.expires_in <= 30 ||
133
+ typeof raw.token_type !== 'string' ||
134
+ raw.token_type.toLowerCase() !== 'bearer'
135
+ )
136
+ throw failure()
137
+ const idToken = raw.id_token === undefined ? registration.previous?.idToken : raw.id_token
138
+ if (typeof idToken !== 'string') throw failure()
139
+ const subject =
140
+ raw.id_token === undefined && registration.previous
141
+ ? registration.previous.subject
142
+ : await verify(idToken, registration.clientId, registration.nonce)
143
+ if (registration.subject !== undefined && registration.subject !== subject) throw failure()
144
+ const granted =
145
+ raw.scope === undefined && registration.previous
146
+ ? registration.previous.scopes
147
+ : typeof raw.scope === 'string'
148
+ ? raw.scope.split(/\s+/)
149
+ : []
150
+ const earliest = earliestRefreshAt(raw.earliest_refresh_at)
151
+ return chatgptStateSchema.parse({
152
+ version: 1,
153
+ hostId: registration.hostId,
154
+ clientId: registration.clientId,
155
+ subject,
156
+ scopes: granted,
157
+ accessToken: raw.access_token,
158
+ refreshToken: raw.refresh_token,
159
+ idToken,
160
+ expiresAt: now + raw.expires_in * 1000 - 5000,
161
+ ...(earliest === undefined ? {} : { earliestRefreshAt: earliest }),
162
+ })
163
+ } catch {
164
+ throw failure()
165
+ }
166
+ }
167
+ export async function exchangeCode(
168
+ t: OAuthTransaction,
169
+ url: URL,
170
+ signal: AbortSignal,
171
+ fetcher: Fetch = fetch,
172
+ ): Promise<ChatGPTState> {
173
+ const { code, clientId } = callback(t, url)
174
+ const raw = await request(
175
+ new URLSearchParams({
176
+ grant_type: 'authorization_code',
177
+ client_id: clientId,
178
+ code,
179
+ code_verifier: t.verifier,
180
+ redirect_uri: t.redirectUri,
181
+ resource: CHATGPT_RESOURCE,
182
+ }),
183
+ signal,
184
+ fetcher,
185
+ )
186
+ return parseTokens(raw, {
187
+ hostId: t.hostId,
188
+ clientId,
189
+ nonce: t.nonce,
190
+ subject: t.previous?.subject,
191
+ })
192
+ }
193
+ export async function refreshChatGPT(
194
+ state: ChatGPTState,
195
+ signal: AbortSignal,
196
+ fetcher: Fetch = fetch,
197
+ ): Promise<ChatGPTState> {
198
+ chatgptStateSchema.parse(state)
199
+ if ((state.earliestRefreshAt ?? 0) > Date.now()) throw failure()
200
+ const raw = await request(
201
+ new URLSearchParams({
202
+ grant_type: 'refresh_token',
203
+ client_id: state.clientId,
204
+ refresh_token: state.refreshToken,
205
+ resource: CHATGPT_RESOURCE,
206
+ }),
207
+ signal,
208
+ fetcher,
209
+ )
210
+ return parseTokens(raw, {
211
+ hostId: state.hostId,
212
+ clientId: state.clientId,
213
+ subject: state.subject,
214
+ previous: state,
215
+ })
216
+ }
@@ -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
+ }