@abide/bridge 0.0.0-stage → 0.1.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/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
- "name": "@abide/bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@abide/bridge",
3
+ "version": "0.1.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.3.0"
31
+ },
32
+ "devDependencies": {
33
+ "@abide/abide": "workspace:*"
34
+ },
35
+ "scripts": {
36
+ "typecheck": "tsc -p tsconfig.json"
37
+ }
38
+ }
package/src/bridge.ts ADDED
@@ -0,0 +1,179 @@
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
+
20
+ type SiteFrame =
21
+ | { type: 'paired'; token: string }
22
+ | ({ type: 'turn' } & TurnRequest)
23
+ | {
24
+ type: 'reply'
25
+ turn: string
26
+ id: number
27
+ reply: Record<string, unknown>
28
+ }
29
+ | { type: 'cancel'; turn: string }
30
+ | { type: 'bye' }
31
+
32
+ type Report =
33
+ | { type: 'event'; turn: string; event: AssistantEvent }
34
+ | {
35
+ type: 'mcp'
36
+ turn: string
37
+ id: number
38
+ method: string
39
+ params: unknown
40
+ }
41
+ | { type: 'end'; turn: string }
42
+ | { type: 'fail'; turn: string; message: string }
43
+
44
+ /** Pairs with `site` by `code`, and serves its turns until the site or the stream ends it. */
45
+ export async function bridge(options: {
46
+ site: string
47
+ code: string
48
+ claude?: string
49
+ say?: (line: string) => void
50
+ }): Promise<void> {
51
+ const site = options.site.replace(/\/+$/, '')
52
+ const say = options.say ?? ((line: string) => console.error(line))
53
+ const paired = await fetch(
54
+ `${site}${BRIDGE_PATH}?code=${encodeURIComponent(options.code)}`,
55
+ { headers: { accept: 'text/event-stream' } },
56
+ )
57
+ if (!paired.ok || paired.body === null)
58
+ throw new Error(
59
+ `${site} refused the pairing (${paired.status}): ${await paired.text()}`,
60
+ )
61
+
62
+ let token = ''
63
+ const outbox: string[] = []
64
+ let flushing: Promise<void> = Promise.resolve()
65
+ let scheduled = false
66
+ const flush = async (): Promise<void> => {
67
+ scheduled = false
68
+ const body = outbox.splice(0).join('\n')
69
+ if (body === '') return
70
+ await fetch(`${site}${BRIDGE_PATH}`, {
71
+ method: 'POST',
72
+ headers: {
73
+ authorization: `Bearer ${token}`,
74
+ 'content-type': 'application/jsonl',
75
+ },
76
+ body,
77
+ }).catch(() => {})
78
+ }
79
+ // One post at a time, in order: a turn's `end` never overtakes its last event.
80
+ const report = (item: Report): void => {
81
+ outbox.push(JSON.stringify(item))
82
+ if (scheduled) return
83
+ scheduled = true
84
+ setTimeout(() => {
85
+ flushing = flushing.then(flush)
86
+ }, BATCH_MILLISECONDS)
87
+ }
88
+
89
+ const turns = new Map<string, AbortController>()
90
+ const waiting = new Map<number, (reply: Record<string, unknown>) => void>()
91
+ let asked = 0
92
+ const secret = crypto.randomUUID()
93
+ const shim = Bun.serve({
94
+ hostname: '127.0.0.1',
95
+ port: 0,
96
+ async fetch(request) {
97
+ const [, given, turn] = new URL(request.url).pathname.split('/')
98
+ if (given !== secret || turn === undefined || !turns.has(turn))
99
+ return new Response(null, { status: 404 })
100
+ if (request.method !== 'POST')
101
+ return new Response(null, {
102
+ status: 405,
103
+ headers: { allow: 'POST' },
104
+ })
105
+ const message = (await request.json()) as {
106
+ id?: number | string
107
+ method: string
108
+ params?: unknown
109
+ }
110
+ // A notification is acknowledged here; there is nothing for the site to answer.
111
+ if (message.id === undefined)
112
+ return new Response(null, { status: 202 })
113
+ const id = ++asked
114
+ const reply = new Promise<Record<string, unknown>>((done) => {
115
+ waiting.set(id, done)
116
+ })
117
+ report({
118
+ type: 'mcp',
119
+ turn,
120
+ id,
121
+ method: message.method,
122
+ params: message.params,
123
+ })
124
+ return Response.json({
125
+ jsonrpc: '2.0',
126
+ id: message.id,
127
+ ...(await reply),
128
+ })
129
+ },
130
+ })
131
+
132
+ const run = async (turn: TurnRequest): Promise<void> => {
133
+ const controller = new AbortController()
134
+ turns.set(turn.id, controller)
135
+ try {
136
+ await claudeTurn(turn, {
137
+ claude: options.claude ?? 'claude',
138
+ mcpUrl: `http://127.0.0.1:${shim.port}/${secret}/${turn.id}`,
139
+ signal: controller.signal,
140
+ report: (event) =>
141
+ report({ type: 'event', turn: turn.id, event }),
142
+ })
143
+ report({ type: 'end', turn: turn.id })
144
+ } catch (thrown) {
145
+ report({
146
+ type: 'fail',
147
+ turn: turn.id,
148
+ message:
149
+ thrown instanceof Error ? thrown.message : String(thrown),
150
+ })
151
+ } finally {
152
+ turns.delete(turn.id)
153
+ }
154
+ }
155
+
156
+ try {
157
+ for await (const line of readLines(paired.body)) {
158
+ if (!line.startsWith('data: ')) continue
159
+ const frame = JSON.parse(line.slice('data: '.length)) as SiteFrame
160
+ if (frame.type === 'paired') {
161
+ token = frame.token
162
+ say(
163
+ `Connected to ${site}. Keep this running while you chat; it ends when you close the page.`,
164
+ )
165
+ } else if (frame.type === 'turn') void run(frame)
166
+ else if (frame.type === 'reply') {
167
+ waiting.get(frame.id)?.(frame.reply)
168
+ waiting.delete(frame.id)
169
+ } else if (frame.type === 'cancel') turns.get(frame.turn)?.abort()
170
+ else if (frame.type === 'bye') break
171
+ }
172
+ } finally {
173
+ for (const controller of turns.values()) controller.abort()
174
+ await flushing
175
+ await flush()
176
+ shim.stop(true)
177
+ say(`Disconnected from ${site}.`)
178
+ }
179
+ }
@@ -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
+ }
@@ -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
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.