Open History to see the last commit
1import { acpCompatibleText } from '@tanstack/ai-acp'
2import { claudeCodeText } from '@tanstack/ai-claude-code'
3import { codexText } from '@tanstack/ai-codex'
4import {
5 GROK_CLI_INSTALL_COMMAND,
6 grokBuildText,
7} from '@tanstack/ai-grok-build'
8import { opencodeText } from '@tanstack/ai-opencode'
9import {
10 createSecrets,
11 defineSandbox,
12 defineWorkspace,
13 githubRepo,
14} from '@tanstack/ai-sandbox'
15import { daytonaSandbox } from '@tanstack/ai-sandbox-daytona'
16import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
17import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
18import { railwaySandbox } from '@tanstack/ai-sandbox-railway'
19import { vercelSandbox } from '@tanstack/ai-sandbox-vercel'
20import { parseVerdict } from './sandbox-triage-options'
21import type {
22 GrokBuildModel,
23 GrokBuildProtocol,
24 GrokTransport,
25 HarnessName,
26 ProviderName,
27 Verdict,
28} from './sandbox-triage-options'
29import type { AnyTextAdapter } from '@tanstack/ai'
30import type { SandboxDefinition, SandboxProvider } from '@tanstack/ai-sandbox'
31
32export { parseVerdict }
33export type { Verdict, HarnessName, ProviderName }
34
35/** GitHub issue URL → repo + issue number. Throws on anything that isn't an issue URL. */
36export function parseIssueUrl(url: string): {
37 repo: string
38 issueNumber: number
39} {
40 const match = url
41 .trim()
42 .match(
43 /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)(?:[/?#].*)?$/i,
44 )
45 if (!match) {
46 throw new Error(
47 'Enter a GitHub issue URL like https://github.com/owner/repo/issues/123',
48 )
49 }
50 return { repo: `${match[1]}/${match[2]}`, issueNumber: Number(match[3]) }
51}
52
53const WORKDIR = '/workspace'
54const SANDBOX_IMAGE = process.env.SANDBOX_IMAGE ?? 'node:22'
55
56export interface HarnessSpec {
57 label: string
58 /** Build the adapter; receives the chosen provider so it can adapt (e.g. codex
59 * can't use OS sandboxing on local-process / Windows). */
60 makeAdapter: (provider: ProviderName) => AnyTextAdapter
61 /**
62 * The COMPLETE shell command that installs AND verifies the CLI, run once on
63 * first create (sandboxed providers only); null = nothing to install. Each
64 * harness owns its own retry strategy — npm-based ones use
65 * {@link npmGlobalCli}, grok runs its own installer script. The runner passes
66 * this string to `sh -c` verbatim and never wraps it, because splicing a
67 * command that starts with `(` into another command (`… || sudo … <cmd>`) is a
68 * SHELL SYNTAX ERROR (`sh: syntax error: unexpected "("` → exit 2) that aborts
69 * setup before anything runs.
70 */
71 installCommand: string | null
72 /** Env vars the in-sandbox CLI needs; any that are set are injected as secrets. */
73 requiredEnv: Array<string>
74 /**
75 * Optional custom check (overrides `requiredEnv` for validation) for harnesses
76 * with either/or auth — returns the missing env vars, or `[]` if satisfied.
77 */
78 envCheck?: () => Array<string>
79 /**
80 * Optional secrets to inject into a SANDBOXED run (overrides the default
81 * requiredEnv-based injection for this harness). Use when the in-sandbox CLI
82 * reads a differently-named var — e.g. `codex exec` authenticates via
83 * `CODEX_API_KEY`, not `OPENAI_API_KEY` (the latter hits its OAuth/WS path → 401).
84 */
85 sandboxSecrets?: () => Record<string, string>
86 /** Port the in-sandbox CLI listens on that the host must reach (e.g. opencode's
87 * `opencode serve`). Sandboxed providers publish/expose it; undefined = none. */
88 exposePort?: number
89}
90
91/**
92 * A global npm install of a CLI, hardened for sandbox images, as ONE `sh` command:
93 *
94 * - `--include=optional`: these CLIs ship their native binary as a
95 * platform-specific OPTIONAL dep (`@openai/codex-linux-x64`, …); an npm
96 * configured to omit optional deps installs a broken CLI.
97 * - sudo fallback: some images (Daytona) run as a non-root user with a root-owned
98 * global npm prefix → `-g` fails EACCES. `sudo -n` never prompts, and keeping
99 * `PATH` lets nvm's node/npm still resolve. Docker runs as root, so the direct
100 * install succeeds and sudo never runs.
101 * - `verify` + one retry: npm treats optional deps as BEST-EFFORT — a transient
102 * failure fetching the platform binary is not an install error, so npm exits 0
103 * and leaves a CLI that dies at run time with "Missing optional dependency".
104 * Running the CLI here turns that into a loud setup failure, and retrying the
105 * whole attempt absorbs the transient case.
106 */
107function npmGlobalCli(spec: string, verify: string): string {
108 const install = `npm install -g ${spec} --include=optional`
109 const attempt = `{ ${install} || sudo -n env "PATH=$PATH" ${install} ; } && ${verify}`
110 return `${attempt} || { ${attempt} ; }`
111}
112
113export const HARNESSES: Record<HarnessName, HarnessSpec> = {
114 'claude-code': {
115 label: 'Claude Code',
116 // Headless `-p` cannot answer permission prompts. Isolated sandboxes and
117 // this trusted local demo both need bypassPermissions, same as Codex
118 // `danger-full-access`. Do not set CLAUDE_CODE_SANDBOXED here: that marker
119 // is only for a real isolation boundary, which the adapter sets itself.
120 makeAdapter: () =>
121 claudeCodeText('sonnet', {
122 permissionMode: 'bypassPermissions',
123 }),
124 installCommand: npmGlobalCli(
125 '@anthropic-ai/claude-code',
126 'claude --version',
127 ),
128 requiredEnv: ['ANTHROPIC_API_KEY'],
129 },
130 codex: {
131 label: 'Codex',
132 // Always run codex with its OWN OS sandbox disabled (`danger-full-access`):
133 // it already runs inside an isolated sandbox (Docker/Vercel/Daytona) or on a
134 // trusted host (local-process), so codex's inner Landlock/seccomp sandbox is
135 // redundant — and it's unsupported on Windows and on some Linux images
136 // (Daytona), where it fails with "os error 2". The outer sandbox is the
137 // real boundary; the read-only triage prompt constrains behavior.
138 makeAdapter: () =>
139 codexText('gpt-5.5', { sandboxMode: 'danger-full-access' }),
140 installCommand: npmGlobalCli('@openai/codex', 'codex --version'),
141 // `codex exec` authenticates headlessly via CODEX_API_KEY (a bare
142 // OPENAI_API_KEY makes it try the OAuth WebSocket transport → 401). Accept
143 // either env var; inject the value AS CODEX_API_KEY into the sandbox. On
144 // local-process it uses the host `codex login` instead, so nothing is needed.
145 requiredEnv: ['CODEX_API_KEY'],
146 envCheck: () =>
147 process.env.CODEX_API_KEY || process.env.OPENAI_API_KEY
148 ? []
149 : ['CODEX_API_KEY (or OPENAI_API_KEY)'],
150 sandboxSecrets: (): Record<string, string> => {
151 const key = process.env.CODEX_API_KEY ?? process.env.OPENAI_API_KEY
152 return key ? { CODEX_API_KEY: key } : {}
153 },
154 },
155 opencode: {
156 label: 'OpenCode',
157 makeAdapter: () =>
158 opencodeText('openai/gpt-5.1-codex', {
159 directory: WORKDIR,
160 permissionMode: 'bypassPermissions',
161 }),
162 installCommand: npmGlobalCli('opencode-ai', 'opencode --version'),
163 requiredEnv: ['OPENAI_API_KEY'],
164 // `opencode serve` listens on this port inside the sandbox; the host reaches
165 // it over HTTP, so sandboxed providers must publish/expose it (Docker
166 // `publishPorts`, Vercel `ports`). Local/Daytona need nothing (localhost /
167 // auto-exposed). Matches the opencode adapter's DEFAULT_PORT.
168 exposePort: 4096,
169 },
170 grok: {
171 label: 'Grok Build',
172 makeAdapter: () => grokBuildText('composer-2.5'),
173 installCommand: GROK_CLI_INSTALL_COMMAND,
174 requiredEnv: ['XAI_API_KEY'],
175 envCheck: () =>
176 process.env.XAI_API_KEY || process.env.GROK_API_KEY
177 ? []
178 : ['XAI_API_KEY (or GROK_API_KEY)'],
179 sandboxSecrets: (): Record<string, string> => {
180 const key = process.env.XAI_API_KEY ?? process.env.GROK_API_KEY
181 return key ? { XAI_API_KEY: key } : {}
182 },
183 exposePort: 2419,
184 },
185 acp: {
186 label: 'ACP compatible (Grok)',
187 makeAdapter: () =>
188 acpCompatibleText('composer-2.5', {
189 name: 'acp',
190 command: ({ model }) =>
191 `grok agent -m '${model}' --always-approve stdio`,
192 permissionMode: 'bypassPermissions',
193 }),
194 installCommand: GROK_CLI_INSTALL_COMMAND,
195 requiredEnv: ['XAI_API_KEY'],
196 envCheck: () =>
197 process.env.XAI_API_KEY || process.env.GROK_API_KEY
198 ? []
199 : ['XAI_API_KEY (or GROK_API_KEY)'],
200 sandboxSecrets: (): Record<string, string> => {
201 const key = process.env.XAI_API_KEY ?? process.env.GROK_API_KEY
202 return key ? { XAI_API_KEY: key } : {}
203 },
204 },
205}
206
207export type HarnessAuthMode = 'host' | 'api-key'
208
209export interface GrokHarnessOptions {
210 model?: GrokBuildModel
211 protocol?: GrokBuildProtocol
212 transport?: GrokTransport
213 authMode?: HarnessAuthMode
214}
215
216function harnessAuthKeys(harness: HarnessName): Array<string> {
217 switch (harness) {
218 case 'grok':
219 case 'acp':
220 return ['XAI_API_KEY', 'GROK_API_KEY']
221 case 'claude-code':
222 return ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']
223 case 'codex':
224 return ['CODEX_API_KEY']
225 case 'opencode':
226 return ['OPENAI_API_KEY']
227 }
228}
229
230/** Build the adapter for a harness run, including per-run Grok protocol options. */
231export function buildHarnessAdapter(
232 harness: HarnessName,
233 provider: ProviderName,
234 grokOptions?: GrokHarnessOptions,
235): AnyTextAdapter {
236 const authMode = grokOptions?.authMode
237 if (harness === 'grok') {
238 return grokBuildText(grokOptions?.model ?? 'composer-2.5', {
239 protocol: grokOptions?.protocol ?? 'acp',
240 transport: grokOptions?.transport ?? 'auto',
241 ...(authMode !== undefined && { authMode }),
242 })
243 }
244 if (harness === 'acp') {
245 return acpCompatibleText('composer-2.5', {
246 name: 'acp',
247 command: ({ model }) => `grok agent -m '${model}' --always-approve stdio`,
248 permissionMode: 'bypassPermissions',
249 ...(authMode !== undefined && { authMode }),
250 ...(authMode === 'api-key' && { authMethodId: 'xai.api_key' }),
251 })
252 }
253 if (harness === 'claude-code') {
254 return claudeCodeText('sonnet', {
255 permissionMode: 'bypassPermissions',
256 ...(authMode !== undefined && { authMode }),
257 })
258 }
259 if (harness === 'codex') {
260 return codexText('gpt-5.5', {
261 sandboxMode: 'danger-full-access',
262 ...(authMode !== undefined && { authMode }),
263 })
264 }
265 return HARNESSES[harness].makeAdapter(provider)
266}
267
268export interface ProviderSpec {
269 label: string
270 /** `ports` are host-reachable ports the harness needs exposed (e.g. opencode's). */
271 make: (ports: Array<number>) => SandboxProvider
272 requiredEnv: Array<string>
273 /**
274 * Optional custom env check (overrides `requiredEnv`) for providers with
275 * either/or auth — returns the list of missing env vars, or `[]` if satisfied.
276 */
277 envCheck?: () => Array<string>
278 /**
279 * Whether the host tool bridge is reachable from inside this provider's
280 * sandbox. The bridge is a `localhost` HTTP server, so only same-machine
281 * providers (local, docker via `host.docker.internal`) can reach it. Remote
282 * cloud sandboxes (daytona, vercel) can't reach the host without a public
283 * tunnel, so chat()-provided tools / code mode can't be bridged there.
284 */
285 toolBridge: boolean
286}
287
288export const PROVIDERS: Record<ProviderName, ProviderSpec> = {
289 docker: {
290 label: 'Docker',
291 make: (ports) =>
292 dockerSandbox({
293 image: SANDBOX_IMAGE,
294 ...(ports.length ? { publishPorts: ports } : {}),
295 }),
296 requiredEnv: [],
297 toolBridge: true,
298 },
299 local: {
300 label: 'Local process',
301 make: () => localProcessSandbox(),
302 requiredEnv: [],
303 toolBridge: true,
304 },
305 vercel: {
306 label: 'Vercel',
307 make: (ports) => vercelSandbox(ports.length ? { ports } : {}),
308 toolBridge: false,
309 // Either a self-contained OIDC token (`vercel env pull` → VERCEL_OIDC_TOKEN),
310 // OR token + team + project (off-Vercel, no OIDC). With only VERCEL_TOKEN the
311 // SDK falls back to OIDC and fails.
312 requiredEnv: ['VERCEL_TOKEN', 'VERCEL_TEAM_ID', 'VERCEL_PROJECT_ID'],
313 envCheck: () =>
314 process.env.VERCEL_OIDC_TOKEN
315 ? []
316 : ['VERCEL_TOKEN', 'VERCEL_TEAM_ID', 'VERCEL_PROJECT_ID'].filter(
317 (key) => !process.env[key],
318 ),
319 },
320 daytona: {
321 label: 'Daytona',
322 // Daytona auto-exposes ports via preview URLs, so it ignores `ports`.
323 make: () => daytonaSandbox(),
324 requiredEnv: ['DAYTONA_API_KEY'],
325 toolBridge: false,
326 },
327 railway: {
328 label: 'Railway',
329 // Railway publishes sandbox domains only on the environment's private
330 // network, so preview ports opt into PRIVATE isolation; without ports the
331 // sandbox stays ISOLATED.
332 make: (ports) =>
333 railwaySandbox(
334 ports.length ? { ports, networkIsolation: 'PRIVATE' } : {},
335 ),
336 // Either a project token (RAILWAY_TOKEN) or an account/workspace token
337 // (RAILWAY_API_TOKEN), plus the environment the sandboxes run in.
338 requiredEnv: ['RAILWAY_API_TOKEN', 'RAILWAY_ENVIRONMENT_ID'],
339 envCheck: () => [
340 ...(!process.env.RAILWAY_TOKEN && !process.env.RAILWAY_API_TOKEN
341 ? ['RAILWAY_API_TOKEN (or RAILWAY_TOKEN)']
342 : []),
343 ...(!process.env.RAILWAY_ENVIRONMENT_ID
344 ? ['RAILWAY_ENVIRONMENT_ID']
345 : []),
346 ],
347 toolBridge: false,
348 },
349}
350
351export function isHarness(value: unknown): value is HarnessName {
352 return typeof value === 'string' && value in HARNESSES
353}
354
355export function isProvider(value: unknown): value is ProviderName {
356 return typeof value === 'string' && value in PROVIDERS
357}
358
359/**
360 * Whether to use the host's logged-in Claude Code subscription instead of an API
361 * key (no API billing). Only valid for Claude Code on the local-process provider,
362 * which runs *your* host `claude`; sandboxes have no host login.
363 */
364export function usesSubscription(
365 harness: HarnessName,
366 provider: ProviderName,
367 useSubscription: boolean | undefined,
368): boolean {
369 return !!useSubscription && provider === 'local' && harness === 'claude-code'
370}
371
372/** Required env vars (harness + provider) that are not set in process.env. */
373export function missingEnv(
374 harness: HarnessName,
375 provider: ProviderName,
376 authMode?: HarnessAuthMode,
377): Array<string> {
378 const harnessSpec = HARNESSES[harness]
379 const hostAuth = authMode === 'host'
380 const harnessMissing = hostAuth
381 ? []
382 : harnessSpec.envCheck
383 ? harnessSpec.envCheck()
384 : harnessSpec.requiredEnv.filter((key) => !process.env[key])
385 const spec = PROVIDERS[provider]
386 const providerMissing = spec.envCheck
387 ? spec.envCheck()
388 : spec.requiredEnv.filter((key) => !process.env[key])
389 return [...harnessMissing, ...providerMissing]
390}
391
392export interface GitHubIssue {
393 number: number
394 title: string
395 body: string
396 url: string
397}
398
399/** Fetch one issue. Uses GITHUB_TOKEN when set (private repos / rate limits). */
400export async function fetchIssue(
401 repo: string,
402 issueNumber: number,
403): Promise<GitHubIssue> {
404 const headers: Record<string, string> = {
405 Accept: 'application/vnd.github+json',
406 'User-Agent': 'tanstack-ai-sandbox-triage',
407 }
408 if (process.env.GITHUB_TOKEN) {
409 headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`
410 }
411 const res = await fetch(
412 `https://api.github.com/repos/${repo}/issues/${issueNumber}`,
413 { headers },
414 )
415 if (!res.ok) {
416 throw new Error(
417 `GitHub API ${res.status} ${res.statusText}: ${await res.text()}`,
418 )
419 }
420 const issue = (await res.json()) as {
421 number: number
422 title: string
423 body: string | null
424 html_url: string
425 pull_request?: unknown
426 }
427 if (issue.pull_request !== undefined) {
428 throw new Error(`${repo}#${issueNumber} is a pull request, not an issue.`)
429 }
430 return {
431 number: issue.number,
432 title: issue.title,
433 body: issue.body ?? '',
434 url: issue.html_url,
435 }
436}
437
438export function buildTriagePrompt(issue: GitHubIssue, repo: string): string {
439 return [
440 `You are triaging a GitHub issue in the ${repo} repository, which is checked`,
441 `out in your current working directory.`,
442 '',
443 `Issue #${issue.number}: ${issue.title}`,
444 `URL: ${issue.url}`,
445 '',
446 'Issue body:',
447 issue.body || '(no description provided)',
448 '',
449 'Investigate the repository to understand and triage this issue. Do NOT',
450 'change any source code — this is analysis only. Determine whether the bug',
451 'is still RELEVANT to the current code and find its root cause.',
452 '',
453 'Reply with Markdown. The VERY FIRST line MUST be exactly one of:',
454 ' VERDICT: relevant | not-relevant | uncertain',
455 'Then these sections:',
456 '## Summary',
457 '## Root cause / analysis',
458 '## Affected files',
459 '## Confidence',
460 ].join('\n')
461}
462
463/** One sandbox per (harness, provider, thread): switching a picker → fresh sandbox. */
464export function buildSandbox(opts: {
465 harness: HarnessName
466 provider: ProviderName
467 repo: string
468 threadId: string
469 /** Keep the sandbox alive after the run instead of destroying it (default: destroy). */
470 keepAlive?: boolean
471 /** Local Claude Code only: use the host's subscription login instead of an API key. */
472 useSubscription?: boolean
473 /** Host login vs API key. Not inferred from the sandbox provider. */
474 authMode?: HarnessAuthMode
475}): SandboxDefinition {
476 const harness = HARNESSES[opts.harness]
477 const authMode =
478 opts.authMode ??
479 (usesSubscription(opts.harness, opts.provider, opts.useSubscription)
480 ? 'host'
481 : 'api-key')
482 const hostAuth = authMode === 'host'
483
484 const ports = harness.exposePort !== undefined ? [harness.exposePort] : []
485 const provider =
486 hostAuth && opts.provider === 'local'
487 ? localProcessSandbox({ scrubEnv: harnessAuthKeys(opts.harness) })
488 : PROVIDERS[opts.provider].make(ports)
489
490 const secretEnv: Record<string, string> = {}
491 if (!hostAuth) {
492 if (harness.sandboxSecrets) {
493 Object.assign(secretEnv, harness.sandboxSecrets())
494 } else {
495 for (const key of harness.requiredEnv) {
496 const value = process.env[key]
497 if (value) secretEnv[key] = value
498 }
499 }
500 }
501 if (opts.provider !== 'local') {
502 // Provider auth (e.g. DAYTONA_API_KEY) — used host-side, harmless in-sandbox.
503 for (const key of PROVIDERS[opts.provider].requiredEnv) {
504 const value = process.env[key]
505 if (value) secretEnv[key] = value
506 }
507 }
508 return defineSandbox({
509 id: `triage-${opts.harness}-${opts.provider}-${opts.threadId}`,
510 provider,
511 workspace: defineWorkspace({
512 source: githubRepo({ repo: opts.repo }),
513 setup: ({ serial }) => {
514 // Install the harness CLI into the fresh sandbox for every provider
515 // EXCEPT local-process, which uses the host's CLI already on PATH.
516 // Remote/container images (docker/vercel/daytona) don't ship it.
517 // Run the harness command AS-IS. Never splice it into a larger shell
518 // command here: grok's installer starts with `(`, and `… || sudo … (curl
519 // …)` is a syntax error that aborts setup with exit 2. Retries and
520 // privilege fallbacks belong INSIDE each `installCommand`.
521 if (opts.provider !== 'local' && harness.installCommand) {
522 serial(harness.installCommand)
523 }
524 },
525 instructions:
526 'Investigate read-only; do not modify source files unless explicitly asked.',
527 secrets: createSecrets(secretEnv),
528 }),
529 // Tear down after the run so a container/VM is never left running. On
530 // success/error `withSandbox` honors `destroyOnComplete`; on an explicit
531 // abort it ALWAYS destroys (killing the agent's token drain), so keepAlive
532 // only preserves the sandbox after a successful run.
533 lifecycle: { reuse: 'thread', destroyOnComplete: !opts.keepAlive },
534 })
535}