@abide/bridge 0.0.0-stage → 0.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.
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/bin/abideBridge.ts +31 -0
- package/package.json +37 -5
- package/src/bridge.ts +325 -0
- package/src/claudeTurn.ts +206 -0
- package/src/readLines.ts +33 -0
- package/README.md +0 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# @abide/bridge
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 9aa03a5: socket mux bounds, request ceilings, stop timeout, scroll restore, numeric and composed bind:value, and keyed rows kept across patches (16.78, 18.28-18.32, 30.29-30.31, 32.58-32.62, 32.66, 32.67, 42.17) ([`301bf47`](https://github.com/briancray/abide/commit/301bf47adf5059271b439fe3c129963861dd1c72))
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Brian Cray
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// `abide-bridge <site> <code>` — the command an abide site shows you to connect your Claude Code to its
|
|
3
|
+
// assistant. `--claude <path>` names the executable where `claude` is not on PATH.
|
|
4
|
+
|
|
5
|
+
import { bridge } from '../src/bridge.ts'
|
|
6
|
+
|
|
7
|
+
const args = process.argv.slice(2)
|
|
8
|
+
const flag = args.indexOf('--claude')
|
|
9
|
+
const claude = flag === -1 ? undefined : args[flag + 1]
|
|
10
|
+
const [site, code] = args.filter(
|
|
11
|
+
(_arg, index) => flag === -1 || (index !== flag && index !== flag + 1),
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
if (site === undefined || code === undefined) {
|
|
15
|
+
console.error('usage: abide-bridge <site> <code> [--claude <path>]')
|
|
16
|
+
process.exit(2)
|
|
17
|
+
}
|
|
18
|
+
if (claude === undefined && Bun.which('claude') === null) {
|
|
19
|
+
console.error(
|
|
20
|
+
'Claude Code is not installed here: `claude` is not on PATH. Install it, sign in, and run this again.',
|
|
21
|
+
)
|
|
22
|
+
process.exit(1)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
await bridge({ site, code, ...(claude === undefined ? {} : { claude }) })
|
|
27
|
+
process.exit(0)
|
|
28
|
+
} catch (thrown) {
|
|
29
|
+
console.error(thrown instanceof Error ? thrown.message : String(thrown))
|
|
30
|
+
process.exit(1)
|
|
31
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@abide/bridge",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Connects the Claude Code on your machine to the assistant on an abide site",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Brian Cray",
|
|
8
|
+
"homepage": "https://github.com/briancray/abide#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/briancray/abide.git",
|
|
12
|
+
"directory": "packages/bridge"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/briancray/abide/issues"
|
|
16
|
+
},
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public",
|
|
19
|
+
"provenance": true
|
|
20
|
+
},
|
|
21
|
+
"bin": {
|
|
22
|
+
"abide-bridge": "./bin/abideBridge.ts"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"bin",
|
|
26
|
+
"src",
|
|
27
|
+
"CHANGELOG.md"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"bun": ">=1.4.3"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@abide/abide": "workspace:*"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"typecheck": "bun check"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/bridge.ts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// THE BRIDGE: this machine's Claude Code, lent to one browser on one abide site. It dials OUT — a page
|
|
2
|
+
// cannot reach a process on its own machine from https — and holds a server-sent stream open to the
|
|
3
|
+
// site, which sends it turns; what it reports goes back as posts.
|
|
4
|
+
//
|
|
5
|
+
// TOOLS ARE RELAYED, NEVER CALLED FROM HERE. Claude Code is handed an MCP server on loopback, behind a
|
|
6
|
+
// path no other process is told; each request it makes there is posted to the site, which answers it
|
|
7
|
+
// inside the page's own request, as the person at the page. No credential of theirs reaches this
|
|
8
|
+
// machine, and none of this machine's reaches the site.
|
|
9
|
+
|
|
10
|
+
import type { AssistantEvent } from '@abide/abide/server'
|
|
11
|
+
import { claudeTurn, type TurnRequest } from './claudeTurn.ts'
|
|
12
|
+
import { readLines } from './readLines.ts'
|
|
13
|
+
|
|
14
|
+
// abide's `BRIDGE_ADDRESS`, spelled out because the bridge carries no abide at run time — a test
|
|
15
|
+
// holds the two equal.
|
|
16
|
+
export const BRIDGE_PATH = '/__abide/bridge'
|
|
17
|
+
// How long reports gather before they are posted, so a streamed reply is not a post per token.
|
|
18
|
+
const BATCH_MILLISECONDS = 15
|
|
19
|
+
// 44.24 — how long a relayed MCP request waits for the site's reply.
|
|
20
|
+
const REPLY_MILLISECONDS = 120_000
|
|
21
|
+
// 44.25 — the first wait before redialing a dropped stream, doubled per failed dial up to the last.
|
|
22
|
+
const FIRST_REDIAL_MILLISECONDS = 250
|
|
23
|
+
const LAST_REDIAL_MILLISECONDS = 8_000
|
|
24
|
+
// abide's `RESUME_MILLISECONDS`, spelled out for `BRIDGE_PATH`'s reason: past it the site no longer
|
|
25
|
+
// holds the pairing, and a redial is refused.
|
|
26
|
+
export const RESUME_MILLISECONDS = 30_000
|
|
27
|
+
// abide's `HEARTBEAT_MILLISECONDS`, spelled out for `BRIDGE_PATH`'s reason.
|
|
28
|
+
export const HEARTBEAT_MILLISECONDS = 15_000
|
|
29
|
+
// 44.28 — how long the stream may go without a line before it is taken for dropped.
|
|
30
|
+
const SILENCE_MILLISECONDS = 3 * HEARTBEAT_MILLISECONDS
|
|
31
|
+
|
|
32
|
+
type SiteFrame =
|
|
33
|
+
| { type: 'paired'; token: string }
|
|
34
|
+
| ({ type: 'turn' } & TurnRequest)
|
|
35
|
+
| {
|
|
36
|
+
type: 'reply'
|
|
37
|
+
turn: string
|
|
38
|
+
id: number
|
|
39
|
+
reply: Record<string, unknown>
|
|
40
|
+
}
|
|
41
|
+
| { type: 'cancel'; turn: string }
|
|
42
|
+
| { type: 'bye' }
|
|
43
|
+
|
|
44
|
+
type Report =
|
|
45
|
+
| { type: 'event'; turn: string; event: AssistantEvent }
|
|
46
|
+
| {
|
|
47
|
+
type: 'mcp'
|
|
48
|
+
turn: string
|
|
49
|
+
id: number
|
|
50
|
+
method: string
|
|
51
|
+
params: unknown
|
|
52
|
+
}
|
|
53
|
+
| { type: 'end'; turn: string }
|
|
54
|
+
| { type: 'fail'; turn: string; message: string }
|
|
55
|
+
|
|
56
|
+
/** A relayed MCP request the site has yet to reply to. */
|
|
57
|
+
type Waiting = {
|
|
58
|
+
turn: string
|
|
59
|
+
method: string
|
|
60
|
+
answer: (reply: Record<string, unknown>) => void
|
|
61
|
+
deadline: ReturnType<typeof setTimeout>
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** What Claude Code is answered where the site never replied: a failed call, or a JSON-RPC error. */
|
|
65
|
+
function unanswered(method: string, message: string): Record<string, unknown> {
|
|
66
|
+
return method === 'tools/call'
|
|
67
|
+
? {
|
|
68
|
+
result: {
|
|
69
|
+
content: [{ type: 'text', text: message }],
|
|
70
|
+
isError: true,
|
|
71
|
+
},
|
|
72
|
+
}
|
|
73
|
+
: { error: { code: -32603, message } }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Pairs with `site` by `code`, and serves its turns until the site or the stream ends it. */
|
|
77
|
+
export async function bridge(options: {
|
|
78
|
+
site: string
|
|
79
|
+
code: string
|
|
80
|
+
claude?: string
|
|
81
|
+
say?: (line: string) => void
|
|
82
|
+
replyMilliseconds?: number
|
|
83
|
+
silenceMilliseconds?: number
|
|
84
|
+
}): Promise<void> {
|
|
85
|
+
const site = options.site.replace(/\/+$/, '')
|
|
86
|
+
const say = options.say ?? ((line: string) => console.error(line))
|
|
87
|
+
const replyMilliseconds = options.replyMilliseconds ?? REPLY_MILLISECONDS
|
|
88
|
+
const silenceMilliseconds =
|
|
89
|
+
options.silenceMilliseconds ?? SILENCE_MILLISECONDS
|
|
90
|
+
// What cuts the stream being read, where it went silent.
|
|
91
|
+
let dialed = new AbortController()
|
|
92
|
+
let stream = await fetch(
|
|
93
|
+
`${site}${BRIDGE_PATH}?code=${encodeURIComponent(options.code)}`,
|
|
94
|
+
{
|
|
95
|
+
headers: { accept: 'text/event-stream' },
|
|
96
|
+
signal: dialed.signal,
|
|
97
|
+
},
|
|
98
|
+
)
|
|
99
|
+
if (!stream.ok || stream.body === null)
|
|
100
|
+
throw new Error(
|
|
101
|
+
`${site} refused the pairing (${stream.status}): ${await stream.text()}`,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
let token = ''
|
|
105
|
+
const waiting = new Map<number, Waiting>()
|
|
106
|
+
const answer = (id: number, reply: Record<string, unknown>): void => {
|
|
107
|
+
const waiter = waiting.get(id)
|
|
108
|
+
if (waiter === undefined) return
|
|
109
|
+
waiting.delete(id)
|
|
110
|
+
clearTimeout(waiter.deadline)
|
|
111
|
+
waiter.answer(reply)
|
|
112
|
+
}
|
|
113
|
+
const outbox: Report[] = []
|
|
114
|
+
let flushing: Promise<void> = Promise.resolve()
|
|
115
|
+
let scheduled = false
|
|
116
|
+
const flush = async (): Promise<void> => {
|
|
117
|
+
scheduled = false
|
|
118
|
+
const batch = outbox.splice(0)
|
|
119
|
+
if (batch.length === 0) return
|
|
120
|
+
const lines: string[] = []
|
|
121
|
+
for (const item of batch) lines.push(JSON.stringify(item))
|
|
122
|
+
let failure: string | undefined
|
|
123
|
+
try {
|
|
124
|
+
const posted = await fetch(`${site}${BRIDGE_PATH}`, {
|
|
125
|
+
method: 'POST',
|
|
126
|
+
headers: {
|
|
127
|
+
authorization: `Bearer ${token}`,
|
|
128
|
+
'content-type': 'application/jsonl',
|
|
129
|
+
},
|
|
130
|
+
body: lines.join('\n'),
|
|
131
|
+
})
|
|
132
|
+
if (!posted.ok)
|
|
133
|
+
failure = `${site} refused a report (${posted.status}): ${await posted.text()}`
|
|
134
|
+
else await posted.body?.cancel()
|
|
135
|
+
} catch (thrown) {
|
|
136
|
+
failure = `${site} could not be reached: ${thrown instanceof Error ? thrown.message : String(thrown)}`
|
|
137
|
+
}
|
|
138
|
+
if (failure === undefined) return
|
|
139
|
+
say(failure)
|
|
140
|
+
// 44.24 — a request the site never heard of is answered failed rather than waited on.
|
|
141
|
+
for (const item of batch)
|
|
142
|
+
if (item.type === 'mcp')
|
|
143
|
+
answer(item.id, unanswered(item.method, failure))
|
|
144
|
+
}
|
|
145
|
+
// One post at a time, in order: a turn's `end` never overtakes its last event.
|
|
146
|
+
const report = (item: Report): void => {
|
|
147
|
+
outbox.push(item)
|
|
148
|
+
if (scheduled) return
|
|
149
|
+
scheduled = true
|
|
150
|
+
setTimeout(() => {
|
|
151
|
+
flushing = flushing.then(flush)
|
|
152
|
+
}, BATCH_MILLISECONDS)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const turns = new Map<string, AbortController>()
|
|
156
|
+
let asked = 0
|
|
157
|
+
const secret = crypto.randomUUID()
|
|
158
|
+
const shim = Bun.serve({
|
|
159
|
+
hostname: '127.0.0.1',
|
|
160
|
+
port: 0,
|
|
161
|
+
// A tool call takes as long as its handler does: the reply deadline (44.24) bounds the wait,
|
|
162
|
+
// where bun's own idle timeout would cut every call past 10 seconds.
|
|
163
|
+
idleTimeout: 0,
|
|
164
|
+
async fetch(request) {
|
|
165
|
+
const [, given, turn] = new URL(request.url).pathname.split('/')
|
|
166
|
+
if (given !== secret || turn === undefined || !turns.has(turn))
|
|
167
|
+
return new Response(null, { status: 404 })
|
|
168
|
+
if (request.method !== 'POST')
|
|
169
|
+
return new Response(null, {
|
|
170
|
+
status: 405,
|
|
171
|
+
headers: { allow: 'POST' },
|
|
172
|
+
})
|
|
173
|
+
const message = (await request.json()) as {
|
|
174
|
+
id?: number | string
|
|
175
|
+
method: string
|
|
176
|
+
params?: unknown
|
|
177
|
+
}
|
|
178
|
+
// A notification is acknowledged here; there is nothing for the site to answer.
|
|
179
|
+
if (message.id === undefined)
|
|
180
|
+
return new Response(null, { status: 202 })
|
|
181
|
+
const id = ++asked
|
|
182
|
+
const method = message.method
|
|
183
|
+
const reply = new Promise<Record<string, unknown>>((done) => {
|
|
184
|
+
waiting.set(id, {
|
|
185
|
+
turn,
|
|
186
|
+
method,
|
|
187
|
+
answer: done,
|
|
188
|
+
// 44.24 — a reply lost on the way is a failure Claude Code is told of.
|
|
189
|
+
deadline: setTimeout(
|
|
190
|
+
() =>
|
|
191
|
+
answer(
|
|
192
|
+
id,
|
|
193
|
+
unanswered(
|
|
194
|
+
method,
|
|
195
|
+
`${site} sent no reply within ${replyMilliseconds} ms.`,
|
|
196
|
+
),
|
|
197
|
+
),
|
|
198
|
+
replyMilliseconds,
|
|
199
|
+
),
|
|
200
|
+
})
|
|
201
|
+
})
|
|
202
|
+
report({
|
|
203
|
+
type: 'mcp',
|
|
204
|
+
turn,
|
|
205
|
+
id,
|
|
206
|
+
method: message.method,
|
|
207
|
+
params: message.params,
|
|
208
|
+
})
|
|
209
|
+
return Response.json({
|
|
210
|
+
jsonrpc: '2.0',
|
|
211
|
+
id: message.id,
|
|
212
|
+
...(await reply),
|
|
213
|
+
})
|
|
214
|
+
},
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
const run = async (turn: TurnRequest): Promise<void> => {
|
|
218
|
+
const controller = new AbortController()
|
|
219
|
+
turns.set(turn.id, controller)
|
|
220
|
+
try {
|
|
221
|
+
await claudeTurn(turn, {
|
|
222
|
+
claude: options.claude ?? 'claude',
|
|
223
|
+
mcpUrl: `http://127.0.0.1:${shim.port}/${secret}/${turn.id}`,
|
|
224
|
+
signal: controller.signal,
|
|
225
|
+
report: (event) =>
|
|
226
|
+
report({ type: 'event', turn: turn.id, event }),
|
|
227
|
+
})
|
|
228
|
+
report({ type: 'end', turn: turn.id })
|
|
229
|
+
} catch (thrown) {
|
|
230
|
+
report({
|
|
231
|
+
type: 'fail',
|
|
232
|
+
turn: turn.id,
|
|
233
|
+
message:
|
|
234
|
+
thrown instanceof Error ? thrown.message : String(thrown),
|
|
235
|
+
})
|
|
236
|
+
} finally {
|
|
237
|
+
turns.delete(turn.id)
|
|
238
|
+
for (const [id, waiter] of waiting)
|
|
239
|
+
if (waiter.turn === turn.id)
|
|
240
|
+
answer(id, unanswered(waiter.method, 'The turn ended.'))
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// 44.25 — THE STREAM REDIALED BY ITS TOKEN, each wait twice the last, until the site refuses it or
|
|
245
|
+
// stops holding the pairing.
|
|
246
|
+
const redial = async (): Promise<Response | undefined> => {
|
|
247
|
+
if (token === '') return undefined
|
|
248
|
+
say(`Lost ${site}; reconnecting.`)
|
|
249
|
+
const until = Date.now() + RESUME_MILLISECONDS
|
|
250
|
+
let delay = FIRST_REDIAL_MILLISECONDS
|
|
251
|
+
while (Date.now() < until) {
|
|
252
|
+
await Bun.sleep(delay)
|
|
253
|
+
delay = Math.min(delay * 2, LAST_REDIAL_MILLISECONDS)
|
|
254
|
+
try {
|
|
255
|
+
dialed = new AbortController()
|
|
256
|
+
const resumed = await fetch(`${site}${BRIDGE_PATH}`, {
|
|
257
|
+
headers: {
|
|
258
|
+
accept: 'text/event-stream',
|
|
259
|
+
authorization: `Bearer ${token}`,
|
|
260
|
+
},
|
|
261
|
+
signal: dialed.signal,
|
|
262
|
+
})
|
|
263
|
+
if (resumed.ok && resumed.body !== null) {
|
|
264
|
+
say(`Reconnected to ${site}.`)
|
|
265
|
+
return resumed
|
|
266
|
+
}
|
|
267
|
+
await resumed.body?.cancel()
|
|
268
|
+
if (resumed.status < 500) return undefined
|
|
269
|
+
} catch {
|
|
270
|
+
// Unreachable for now: the next dial is the retry.
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return undefined
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
try {
|
|
277
|
+
let bye = false
|
|
278
|
+
for (;;) {
|
|
279
|
+
// 44.28 — a stream silent past the bound is cut, and redialed as one that dropped.
|
|
280
|
+
const silence = setTimeout(
|
|
281
|
+
() => dialed.abort(),
|
|
282
|
+
silenceMilliseconds,
|
|
283
|
+
)
|
|
284
|
+
try {
|
|
285
|
+
for await (const line of readLines(
|
|
286
|
+
stream.body as ReadableStream<Uint8Array>,
|
|
287
|
+
)) {
|
|
288
|
+
silence.refresh()
|
|
289
|
+
if (!line.startsWith('data: ')) continue
|
|
290
|
+
const frame = JSON.parse(
|
|
291
|
+
line.slice('data: '.length),
|
|
292
|
+
) as SiteFrame
|
|
293
|
+
if (frame.type === 'paired') {
|
|
294
|
+
token = frame.token
|
|
295
|
+
say(
|
|
296
|
+
`Connected to ${site}. Keep this running while you chat; it ends when you close the page.`,
|
|
297
|
+
)
|
|
298
|
+
} else if (frame.type === 'turn') void run(frame)
|
|
299
|
+
else if (frame.type === 'reply')
|
|
300
|
+
answer(frame.id, frame.reply)
|
|
301
|
+
else if (frame.type === 'cancel')
|
|
302
|
+
turns.get(frame.turn)?.abort()
|
|
303
|
+
else if (frame.type === 'bye') {
|
|
304
|
+
bye = true
|
|
305
|
+
break
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
} catch {
|
|
309
|
+
// A stream cut mid-read is a drop like one that ended.
|
|
310
|
+
} finally {
|
|
311
|
+
clearTimeout(silence)
|
|
312
|
+
}
|
|
313
|
+
if (bye) break
|
|
314
|
+
const resumed = await redial()
|
|
315
|
+
if (resumed === undefined) break
|
|
316
|
+
stream = resumed
|
|
317
|
+
}
|
|
318
|
+
} finally {
|
|
319
|
+
for (const controller of turns.values()) controller.abort()
|
|
320
|
+
await flushing
|
|
321
|
+
await flush()
|
|
322
|
+
shim.stop(true)
|
|
323
|
+
say(`Disconnected from ${site}.`)
|
|
324
|
+
}
|
|
325
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// ONE TURN OF THE CLAUDE CODE ON THIS MACHINE, run for a site and translated into the events abide's
|
|
2
|
+
// `assistant` yields. Claude Code runs its own loop; its tools are the site's, reached through the MCP
|
|
3
|
+
// server this bridge runs on loopback, and nothing else.
|
|
4
|
+
//
|
|
5
|
+
// ITS OWN TOOLS OFF, NO SETTINGS READ, NO MCP SERVER BUT THE BRIDGE'S, IN AN EMPTY DIRECTORY: the site
|
|
6
|
+
// chose the prompt, and nothing of this machine — a user's settings, a project's CLAUDE.md, the files
|
|
7
|
+
// around it, its shell — is the site's to reach. None of that is something the site can ask for.
|
|
8
|
+
|
|
9
|
+
import { mkdtemp, rm } from 'node:fs/promises' // bun has no temporary directory or recursive remove of its own
|
|
10
|
+
import { tmpdir } from 'node:os' // bun exposes no temporary directory of its own
|
|
11
|
+
import type { AssistantEvent, ClaudeCodeConfig } from '@abide/abide/server'
|
|
12
|
+
import { readLines } from './readLines.ts'
|
|
13
|
+
|
|
14
|
+
// What Claude Code names the one MCP server it is handed, and so the prefix on each tool it calls.
|
|
15
|
+
const SERVER_NAME = 'app'
|
|
16
|
+
const TOOL_PREFIX = `mcp__${SERVER_NAME}__`
|
|
17
|
+
|
|
18
|
+
/** What the site asks of one turn. */
|
|
19
|
+
export type TurnRequest = {
|
|
20
|
+
id: string
|
|
21
|
+
prompt: string
|
|
22
|
+
config: ClaudeCodeConfig
|
|
23
|
+
maxTurns: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Usage = {
|
|
27
|
+
input_tokens?: number
|
|
28
|
+
cache_creation_input_tokens?: number
|
|
29
|
+
cache_read_input_tokens?: number
|
|
30
|
+
output_tokens?: number
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type McpContent = { type: string; text?: string }
|
|
34
|
+
|
|
35
|
+
type CodeLine = {
|
|
36
|
+
type: string
|
|
37
|
+
subtype?: string
|
|
38
|
+
event?: { type: string; delta?: { type: string; text?: string } }
|
|
39
|
+
message?: {
|
|
40
|
+
content:
|
|
41
|
+
| string
|
|
42
|
+
| {
|
|
43
|
+
type: string
|
|
44
|
+
id?: string
|
|
45
|
+
name?: string
|
|
46
|
+
input?: unknown
|
|
47
|
+
tool_use_id?: string
|
|
48
|
+
content?: McpContent[] | string
|
|
49
|
+
is_error?: boolean
|
|
50
|
+
}[]
|
|
51
|
+
}
|
|
52
|
+
stop_reason?: string | null
|
|
53
|
+
is_error?: boolean
|
|
54
|
+
result?: string
|
|
55
|
+
usage?: Usage
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The flags that carry what a site may set, in Claude Code's own spelling. */
|
|
59
|
+
function configFlags(config: ClaudeCodeConfig): string[] {
|
|
60
|
+
const flags: string[] = []
|
|
61
|
+
if (config.model !== undefined) flags.push('--model', config.model)
|
|
62
|
+
if (config.fallbackModel !== undefined)
|
|
63
|
+
flags.push('--fallback-model', config.fallbackModel)
|
|
64
|
+
if (config.systemPrompt !== undefined)
|
|
65
|
+
flags.push('--system-prompt', config.systemPrompt)
|
|
66
|
+
if (config.appendSystemPrompt !== undefined)
|
|
67
|
+
flags.push('--append-system-prompt', config.appendSystemPrompt)
|
|
68
|
+
if (config.effort !== undefined) flags.push('--effort', config.effort)
|
|
69
|
+
return flags
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function textOf(content: McpContent[] | string | undefined): string {
|
|
73
|
+
if (typeof content === 'string') return content
|
|
74
|
+
let text = ''
|
|
75
|
+
for (const part of content ?? [])
|
|
76
|
+
if (part.text !== undefined) text += part.text
|
|
77
|
+
return text
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function done(stop: string, usage: Usage | undefined): AssistantEvent {
|
|
81
|
+
return {
|
|
82
|
+
type: 'done',
|
|
83
|
+
stop,
|
|
84
|
+
usage: {
|
|
85
|
+
input:
|
|
86
|
+
(usage?.input_tokens ?? 0) +
|
|
87
|
+
(usage?.cache_creation_input_tokens ?? 0) +
|
|
88
|
+
(usage?.cache_read_input_tokens ?? 0),
|
|
89
|
+
output: usage?.output_tokens ?? 0,
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Runs `turn` with `claude`, reporting each event, until Claude Code ends it or `signal` does.
|
|
96
|
+
*
|
|
97
|
+
* Throws where Claude Code fails, with what it said.
|
|
98
|
+
*/
|
|
99
|
+
export async function claudeTurn(
|
|
100
|
+
turn: TurnRequest,
|
|
101
|
+
options: {
|
|
102
|
+
claude: string
|
|
103
|
+
mcpUrl: string
|
|
104
|
+
signal: AbortSignal
|
|
105
|
+
report: (event: AssistantEvent) => void
|
|
106
|
+
},
|
|
107
|
+
): Promise<void> {
|
|
108
|
+
const directory = await mkdtemp(`${tmpdir()}/abide-bridge-`)
|
|
109
|
+
const config = `${directory}/mcp.json`
|
|
110
|
+
await Bun.write(
|
|
111
|
+
config,
|
|
112
|
+
JSON.stringify({
|
|
113
|
+
mcpServers: {
|
|
114
|
+
[SERVER_NAME]: { type: 'http', url: options.mcpUrl },
|
|
115
|
+
},
|
|
116
|
+
}),
|
|
117
|
+
)
|
|
118
|
+
const child = Bun.spawn({
|
|
119
|
+
cmd: [
|
|
120
|
+
options.claude,
|
|
121
|
+
'-p',
|
|
122
|
+
'--input-format',
|
|
123
|
+
'stream-json',
|
|
124
|
+
'--output-format',
|
|
125
|
+
'stream-json',
|
|
126
|
+
'--verbose',
|
|
127
|
+
'--include-partial-messages',
|
|
128
|
+
'--no-session-persistence',
|
|
129
|
+
'--tools',
|
|
130
|
+
'',
|
|
131
|
+
'--setting-sources',
|
|
132
|
+
'',
|
|
133
|
+
'--strict-mcp-config',
|
|
134
|
+
'--mcp-config',
|
|
135
|
+
config,
|
|
136
|
+
'--allowedTools',
|
|
137
|
+
TOOL_PREFIX.slice(0, -2),
|
|
138
|
+
'--max-turns',
|
|
139
|
+
String(turn.maxTurns),
|
|
140
|
+
...configFlags(turn.config),
|
|
141
|
+
],
|
|
142
|
+
cwd: directory,
|
|
143
|
+
stdin: 'pipe',
|
|
144
|
+
stdout: 'pipe',
|
|
145
|
+
stderr: 'pipe',
|
|
146
|
+
signal: options.signal,
|
|
147
|
+
})
|
|
148
|
+
child.stdin.write(
|
|
149
|
+
`${JSON.stringify({ type: 'user', message: { role: 'user', content: turn.prompt } })}\n`,
|
|
150
|
+
)
|
|
151
|
+
child.stdin.end()
|
|
152
|
+
const stderr = new Response(child.stderr).text()
|
|
153
|
+
try {
|
|
154
|
+
for await (const text of readLines(child.stdout)) {
|
|
155
|
+
if (text === '') continue
|
|
156
|
+
const line = JSON.parse(text) as CodeLine
|
|
157
|
+
if (line.type === 'stream_event') {
|
|
158
|
+
const delta = line.event?.delta
|
|
159
|
+
if (
|
|
160
|
+
line.event?.type === 'content_block_delta' &&
|
|
161
|
+
delta?.type === 'text_delta'
|
|
162
|
+
)
|
|
163
|
+
options.report({ type: 'text', text: delta.text as string })
|
|
164
|
+
} else if (
|
|
165
|
+
(line.type === 'assistant' || line.type === 'user') &&
|
|
166
|
+
Array.isArray(line.message?.content)
|
|
167
|
+
) {
|
|
168
|
+
for (const block of line.message.content)
|
|
169
|
+
if (block.type === 'tool_use')
|
|
170
|
+
options.report({
|
|
171
|
+
type: 'tool',
|
|
172
|
+
id: block.id as string,
|
|
173
|
+
name: (block.name as string).replace(
|
|
174
|
+
TOOL_PREFIX,
|
|
175
|
+
'',
|
|
176
|
+
),
|
|
177
|
+
input: block.input,
|
|
178
|
+
})
|
|
179
|
+
else if (block.type === 'tool_result')
|
|
180
|
+
options.report({
|
|
181
|
+
type: 'result',
|
|
182
|
+
id: block.tool_use_id as string,
|
|
183
|
+
text: textOf(block.content),
|
|
184
|
+
failed: block.is_error === true,
|
|
185
|
+
})
|
|
186
|
+
} else if (line.type === 'result') {
|
|
187
|
+
// The turn cap is one stop, whichever provider reached it.
|
|
188
|
+
if (line.subtype === 'error_max_turns') {
|
|
189
|
+
options.report(done('max_turns', line.usage))
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
if (line.is_error === true)
|
|
193
|
+
throw new Error(line.result ?? line.subtype ?? 'failed')
|
|
194
|
+
options.report(done(line.stop_reason ?? 'end_turn', line.usage))
|
|
195
|
+
return
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (options.signal.aborted) return
|
|
199
|
+
throw new Error(
|
|
200
|
+
`claude exited ${await child.exited} with no result\n${(await stderr).slice(-2000)}`,
|
|
201
|
+
)
|
|
202
|
+
} finally {
|
|
203
|
+
child.kill()
|
|
204
|
+
await rm(directory, { recursive: true, force: true })
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/readLines.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lines `body` carries, each as it lands, the last one whether or not a newline ends it.
|
|
3
|
+
*
|
|
4
|
+
* The relay's pairing stream and the claude child's stdout. Its own rather than the docs app's
|
|
5
|
+
* `linesOf`: this CLI ships without the docs app, and abide exports no line reader of its own.
|
|
6
|
+
*/
|
|
7
|
+
export async function* readLines(
|
|
8
|
+
body: ReadableStream<Uint8Array>,
|
|
9
|
+
): AsyncGenerator<string> {
|
|
10
|
+
const reader = body.getReader()
|
|
11
|
+
const decoder = new TextDecoder()
|
|
12
|
+
let buffered = ''
|
|
13
|
+
try {
|
|
14
|
+
for (;;) {
|
|
15
|
+
const { done, value } = await reader.read()
|
|
16
|
+
buffered += done
|
|
17
|
+
? decoder.decode()
|
|
18
|
+
: decoder.decode(value, { stream: true })
|
|
19
|
+
let newline = buffered.indexOf('\n')
|
|
20
|
+
while (newline !== -1) {
|
|
21
|
+
yield buffered.slice(0, newline)
|
|
22
|
+
buffered = buffered.slice(newline + 1)
|
|
23
|
+
newline = buffered.indexOf('\n')
|
|
24
|
+
}
|
|
25
|
+
if (done) {
|
|
26
|
+
if (buffered !== '') yield buffered
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
} finally {
|
|
31
|
+
void reader.cancel().catch(() => {})
|
|
32
|
+
}
|
|
33
|
+
}
|
package/README.md
DELETED