Open History to see the last commit
1/**
2 * Tools bridged into the sandbox harness for the triage demo.
3 *
4 * The point of these is to exercise the **sandbox tool bridge**: the harness
5 * (Claude Code / Codex / OpenCode) runs INSIDE the sandbox, but these tools
6 * execute on the HOST and their results are relayed back. If a run shows both
7 * tool calls firing and returning data, the bridge round-trips correctly.
8 *
9 * Two flavours, on purpose:
10 * - `fetchIssueComments` — a NORMAL server tool the harness calls directly.
11 * - `searchRelatedIssues` — a CODE-MODE tool: the harness calls
12 * `execute_typescript` and the generated code invokes it as the bound
13 * function `external_searchRelatedIssues(...)` (host-run code mode).
14 *
15 * Both are bound to the run's repo/issue so the model can't pass the wrong
16 * target — a more reliable bridge check.
17 */
18import { toolDefinition } from '@tanstack/ai'
19import { createCodeMode } from '@tanstack/ai-code-mode'
20import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
21import { z } from 'zod'
22
23function githubHeaders(): Record<string, string> {
24 const headers: Record<string, string> = {
25 Accept: 'application/vnd.github+json',
26 'User-Agent': 'tanstack-ai-sandbox-triage',
27 }
28 if (process.env.GITHUB_TOKEN) {
29 headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`
30 }
31 return headers
32}
33
34/**
35 * Build the bridged tools + code-mode setup + system mandate for one triage run.
36 * `repo`/`issueNumber` are captured so the tools take minimal (or no) model
37 * input — the bridge test doesn't hinge on the model echoing the right target.
38 */
39export function createTriageTools(repo: string, issueNumber: number) {
40 // ── Normal bridged tool: host fetches the issue's comment thread ──────────
41 const fetchIssueComments = toolDefinition({
42 name: 'fetchIssueComments',
43 description:
44 `Fetch the human discussion thread on issue #${issueNumber} of ${repo} ` +
45 'from the host. Comments often hold reproduction steps, stack traces, and ' +
46 'maintainer hints that are not in the issue body. Takes no arguments.',
47 inputSchema: z.object({}),
48 outputSchema: z.object({
49 count: z.number(),
50 comments: z.array(
51 z.object({
52 author: z.string(),
53 body: z.string(),
54 createdAt: z.string(),
55 }),
56 ),
57 }),
58 }).server(async () => {
59 const res = await fetch(
60 `https://api.github.com/repos/${repo}/issues/${issueNumber}/comments?per_page=20`,
61 { headers: githubHeaders() },
62 )
63 if (!res.ok) {
64 throw new Error(
65 `GitHub comments fetch failed: ${res.status} ${res.statusText}`,
66 )
67 }
68 const data = (await res.json()) as Array<{
69 user?: { login?: string }
70 body?: string
71 created_at?: string
72 }>
73 const comments = data.map((comment) => ({
74 author: comment.user?.login ?? 'unknown',
75 body: comment.body ?? '',
76 createdAt: comment.created_at ?? '',
77 }))
78 return { count: comments.length, comments }
79 })
80
81 // ── Code-mode bound tool: host searches the repo for related issues ───────
82 const searchRelatedIssues = toolDefinition({
83 name: 'searchRelatedIssues',
84 description:
85 `Search ${repo} for issues matching a free-text query. Use it to find ` +
86 'duplicates or related reports for the issue under triage.',
87 inputSchema: z.object({
88 query: z.string().describe('Free-text search terms.'),
89 }),
90 outputSchema: z.object({
91 issues: z.array(
92 z.object({
93 number: z.number(),
94 title: z.string(),
95 state: z.string(),
96 url: z.string(),
97 }),
98 ),
99 }),
100 }).server(async ({ query }) => {
101 const q = encodeURIComponent(`repo:${repo} is:issue ${query}`)
102 const res = await fetch(
103 `https://api.github.com/search/issues?q=${q}&per_page=5`,
104 { headers: githubHeaders() },
105 )
106 if (!res.ok) {
107 throw new Error(`GitHub search failed: ${res.status} ${res.statusText}`)
108 }
109 const data = (await res.json()) as {
110 items?: Array<{
111 number: number
112 title: string
113 state: string
114 html_url: string
115 }>
116 }
117 const issues = (data.items ?? []).map((issue) => ({
118 number: issue.number,
119 title: issue.title,
120 state: issue.state,
121 url: issue.html_url,
122 }))
123 return { issues }
124 })
125
126 // Code mode runs the agent's generated TypeScript on the host; the bound
127 // tool is exposed to that code as `external_searchRelatedIssues(...)`.
128 const codeMode = createCodeMode({
129 driver: createNodeIsolateDriver(),
130 tools: [searchRelatedIssues],
131 timeout: 60_000,
132 memoryLimit: 128,
133 })
134
135 // System instruction: force BOTH bridged tools before any repo work, so a
136 // broken bridge is immediately obvious (the run can't get past step 2).
137 const mandate = [
138 'Before you read, clone, or analyze ANY repository files, you MUST complete',
139 'these two steps, in order:',
140 '',
141 '1. Call the `fetchIssueComments` tool (no arguments) to load the issue',
142 ' discussion thread from the host.',
143 '2. Call the `execute_typescript` tool with a short script that calls',
144 ' `external_searchRelatedIssues({ query })` with a query derived from the',
145 ' issue title, and returns its result. This runs your code on the host via',
146 ' code mode.',
147 '',
148 'Only AFTER both tool calls have returned may you inspect the repository and',
149 'produce your triage verdict. These tools execute on the host through the',
150 'sandbox tool bridge — calling them confirms the bridge works end to end.',
151 ].join('\n')
152
153 return {
154 /** The normal tool + the code-mode tools (`execute_typescript`, …). */
155 tools: [fetchIssueComments, ...codeMode.tools],
156 /** Code mode's own system prompt (explains `execute_typescript` usage). */
157 codeModeSystemPrompt: codeMode.systemPrompt,
158 /** Our mandate forcing both tools first. */
159 mandate,
160 }
161}