Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

sandbox-triage.ts

512 lines18.4 KB

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