@abide/bridge 0.8.3 → 0.9.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 CHANGED
@@ -1,5 +1,31 @@
1
1
  # @abide/bridge
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9206ce8: An assistant's answer streams as the Messages API streams it, and a conversation is held as the API holds it. `assistant` yields each run of the model event for event — `message_start`, `content_block_start`, `content_block_delta` (`text_delta`, `input_json_delta`, `citations_delta`, …), `content_block_stop`, `message_delta` with its `stop_reason` and `usage`, `message_stop` — through `provider.claudeApi` and `provider.claudeCode` alike, and between runs a `tool_result` event for each call, with its value (RULEBOOK 44.2, 44.11, 44.28, 44.49). `assistantMessage('assistant', events)` makes the messages an answer amounts to, accumulated as the API's own clients accumulate its stream (44.105), and `chat` holds `messages` — the API's own — folding an answer into them as it streams (53.24-53.32, 53.47). `resultsOf` reads a handler's results off those messages (44.51). `ToolAnswer` takes MCP's `isError`.
8
+
9
+ Migrating:
10
+
11
+ - Events: `text` → `content_block_delta` with a `text_delta`; `tool` → `content_block_start` with a `tool_use` block; `input` → that block's `input_json_delta`s; `result` → `tool_result` (`content` is the blocks the model was shown); `done` → each run's `message_delta` (`stop_reason`, `usage`) and `message_stop`. A call reaches the handler its `tool_use` names; events no longer carry `handler`.
12
+ - `transcript.turn` / `transcript.fold` / `transcript.messages`, `AssistantTurn` and `AssistantTurnPart` are gone: hold `AssistantMessage[]`, and turn a whole answer's events into messages with `assistantMessage('assistant', events)`.
13
+ - `chat({ turns })` → `chat({ messages })`; `talk.turns` → `talk.messages`; `talk.turn(turn, index)` → `talk.message(message, index)`, rendering its `blocks` where it is `shown`; a tool part → a `tool_use` block, `talk.tool(block)` carrying its `toolResult` and `answer`; permission prompts → `talk.permissions`; an answer's failure and stop → `talk.failed` and `talk.stop_reason`, on the root as `data-failed` and `data-stop`. `data-chat="turn"` → `data-chat="message"`. Show Ask again under a message that `ends` its answer.
14
+ - `resultsOf(events, handler)` → `resultsOf(assistantMessage('assistant', events), handler)`, or the messages a chat holds.
15
+ - `ToolAnswer.failed` → `isError`.
16
+ - A `Provider` an app wrote yields each run as the API streams it — `message_start` first — and a `tool_result` event between runs.
17
+ - A stored conversation is the API's own messages; one stored as turns has no reader and is rewritten once.
18
+ - Pair with a bridge of this release: an older bridge reports events in the old shapes.
19
+
20
+ ### Patch Changes
21
+
22
+ - edb7aae: a refused call is answered through served() like every other report ([`604a78c`](https://github.com/briancray/abide/commit/604a78cd7b05e838d48d4926693426d7444310a2))
23
+ - edb7aae: the bench reads webkit for shared and shapes alone, as skipWebkitClock skips the rest everywhere ([`9a85615`](https://github.com/briancray/abide/commit/9a85615f1ddcc931404b69fafb9f55b1ac4cd3fd))
24
+ - edb7aae: grantFor hands back the args a caller uses, one APP_NAME, the icon in a scratch directory ([`acfe9c2`](https://github.com/briancray/abide/commit/acfe9c2ad9845cef125d57eb0cdb9010e1c0e68e))
25
+ - edb7aae: callTool names its configuration parameter, one XDG directory rule, Bun.env for headersHelper ([`bf58b29`](https://github.com/briancray/abide/commit/bf58b29ce68f2175a20442d2d7b7debffcab8787))
26
+ - edb7aae: a direct call to an http MCP server sends what its headersHelper writes, over its headers, as Claude Code does — 44.95 ([`c75e1bf`](https://github.com/briancray/abide/commit/c75e1bfeaef80545ee8f58c5f746cd42490cf746))
27
+ - 5c6d6da: A turn whose readying fails is reported failed, as a call's already was, rather than left running with nothing reported.
28
+
3
29
  ## 0.8.3
4
30
 
5
31
  ### Patch Changes
@@ -22,6 +22,7 @@ import {
22
22
  installDirectory,
23
23
  uninstall,
24
24
  } from '../src/install.ts'
25
+ import { messageOf } from '../src/messageOf.ts'
25
26
 
26
27
  const USAGE =
27
28
  'usage: abide-bridge <site> <code> [--full] [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge install [--full] [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge uninstall\n abide-bridge forget [<site>]'
@@ -116,6 +117,6 @@ try {
116
117
  }
117
118
  process.exit(0)
118
119
  } catch (thrown) {
119
- console.error(thrown instanceof Error ? thrown.message : String(thrown))
120
+ console.error(messageOf(thrown))
120
121
  process.exit(1)
121
122
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abide/bridge",
3
- "version": "0.8.3",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Connects the Claude Code on your machine to the assistant on an abide site",
6
6
  "license": "MIT",
@@ -0,0 +1,2 @@
1
+ /** The name the visitor knows the bridge's handler by: its app, its desktop entry and its notifications. */
2
+ export const APP_NAME = 'abide bridge'
package/src/bridge.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  import { BRIDGE_PATH } from './BRIDGE_PATH.ts'
11
11
  import { grantFor, withheldNotices } from './grant.ts'
12
12
  import { HEARTBEAT_MILLISECONDS } from './HEARTBEAT_MILLISECONDS.ts'
13
+ import { messageOf } from './messageOf.ts'
13
14
  import { siteOf } from './pairingLink.ts'
14
15
  import { readLines } from './readLines.ts'
15
16
  import { RESUME_MILLISECONDS } from './RESUME_MILLISECONDS.ts'
@@ -53,14 +54,21 @@ export async function bridge(options: {
53
54
  options.silenceMilliseconds ?? SILENCE_MILLISECONDS
54
55
  // What cuts the stream being read, where it went silent.
55
56
  let dialed = new AbortController()
56
- // 44.96 — `calls` says, as it pairs, that this bridge makes a call of one tool with no model.
57
- let stream = await fetch(
58
- `${site}${BRIDGE_PATH}?code=${encodeURIComponent(options.code)}&calls=1`,
59
- {
60
- headers: { accept: 'text/event-stream' },
57
+ const dial = (
58
+ query: string,
59
+ headers: Record<string, string>,
60
+ ): Promise<Response> => {
61
+ dialed = new AbortController()
62
+ return fetch(`${site}${BRIDGE_PATH}${query}`, {
63
+ headers: { accept: 'text/event-stream', ...headers },
61
64
  signal: dialed.signal,
62
65
  tls,
63
- },
66
+ })
67
+ }
68
+ // 44.96 — `calls` says, as it pairs, that this bridge makes a call of one tool with no model.
69
+ let stream = await dial(
70
+ `?code=${encodeURIComponent(options.code)}&calls=1`,
71
+ {},
64
72
  )
65
73
  if (!stream.ok || stream.body === null)
66
74
  throw new Error(
@@ -97,7 +105,7 @@ export async function bridge(options: {
97
105
  notice = `${host} didn’t take Claude Code’s reply (${posted.status}), so it stopped.`
98
106
  } else await posted.body?.cancel()
99
107
  } catch (thrown) {
100
- failure = `${site} could not be reached: ${thrown instanceof Error ? thrown.message : String(thrown)}`
108
+ failure = `${site} could not be reached: ${messageOf(thrown)}`
101
109
  notice = `Can’t reach ${host}, so Claude Code stopped its reply.`
102
110
  }
103
111
  if (failure === undefined) {
@@ -190,14 +198,8 @@ export async function bridge(options: {
190
198
  await Bun.sleep(delay)
191
199
  delay = Math.min(delay * 2, LAST_REDIAL_MILLISECONDS)
192
200
  try {
193
- dialed = new AbortController()
194
- const resumed = await fetch(`${site}${BRIDGE_PATH}`, {
195
- headers: {
196
- accept: 'text/event-stream',
197
- authorization: `Bearer ${token}`,
198
- },
199
- signal: dialed.signal,
200
- tls,
201
+ const resumed = await dial('', {
202
+ authorization: `Bearer ${token}`,
201
203
  })
202
204
  if (resumed.ok && resumed.body !== null) {
203
205
  say(`Reconnected to ${host}.`)
package/src/callTool.ts CHANGED
@@ -2,14 +2,15 @@
2
2
  // server itself — the server as 44.58 finds it, started as Claude Code would start it — and hands back
3
3
  // what the tool answered. A server is started for the one call and ended with it.
4
4
 
5
- import { mkdtemp, rm } from 'node:fs/promises' // bun has no temporary directory or recursive remove of its own
6
- import { tmpdir } from 'node:os' // bun exposes no temporary directory of its own
7
-
8
- import type { AssistantContent, ToolAnswer } from '@abide/abide/server'
5
+ import type { ToolAnswer } from '@abide/abide/server'
9
6
 
7
+ import { messageOf } from './messageOf.ts'
10
8
  import { readLines } from './readLines.ts'
9
+ import { scratchDirectory } from './scratchDirectory.ts'
11
10
 
12
11
  const PROTOCOL_VERSION = '2025-06-18'
12
+ /** How long a `headersHelper` has to write its headers, as Claude Code gives one. */
13
+ const HEADERS_HELPER_MILLISECONDS = 10_000
13
14
 
14
15
  /** A server as an MCP config's `mcpServers` holds it: a command run over stdio, or an http address. */
15
16
  type ServerConfiguration = {
@@ -19,6 +20,8 @@ type ServerConfiguration = {
19
20
  env?: Record<string, string>
20
21
  url?: string
21
22
  headers?: Record<string, string>
23
+ /** A shell command writing a JSON object of headers, run for every call, over `headers`. */
24
+ headersHelper?: string
22
25
  }
23
26
 
24
27
  type RpcMessage = {
@@ -38,27 +41,19 @@ type Session = {
38
41
  close(): Promise<void>
39
42
  }
40
43
 
41
- type McpPiece = {
42
- type: string
43
- text?: string
44
- data?: string
45
- mimeType?: string
46
- resource?: { text?: string }
47
- }
48
-
49
44
  /**
50
- * What `tool` of `server` answered `input`, its server named `name` in what it says.
45
+ * What `tool` of the server named `name`, run as `configured`, answered `input`.
51
46
  *
52
47
  * Throws where the server cannot be started or reached, or fails the protocol before the call.
53
48
  */
54
49
  export async function callTool(
55
50
  name: string,
56
- server: unknown,
51
+ configured: unknown,
57
52
  tool: string,
58
53
  input: unknown,
59
54
  signal: AbortSignal,
60
55
  ): Promise<ToolAnswer> {
61
- const configuration = server as ServerConfiguration
56
+ const configuration = configured as ServerConfiguration
62
57
  const type =
63
58
  configuration.type ??
64
59
  (configuration.command === undefined ? undefined : 'stdio')
@@ -66,7 +61,15 @@ export async function callTool(
66
61
  if (type === 'stdio' && configuration.command !== undefined)
67
62
  session = await stdioSession(name, configuration, signal)
68
63
  else if (type === 'http' && configuration.url !== undefined)
69
- session = httpSession(name, configuration, signal)
64
+ session = httpSession(
65
+ name,
66
+ configuration.url,
67
+ {
68
+ ...configuration.headers,
69
+ ...(await helpedHeaders(name, configuration, signal)),
70
+ },
71
+ signal,
72
+ )
70
73
  else
71
74
  throw new Error(
72
75
  `The ${name} MCP server is reached over ${type ?? 'nothing this bridge knows'}, and a call reaches a server over stdio or http.`,
@@ -97,7 +100,7 @@ export async function callTool(
97
100
  content: [
98
101
  { type: 'text', text: called.error.message ?? 'failed' },
99
102
  ],
100
- failed: true,
103
+ isError: true,
101
104
  }
102
105
  return answerOf(called?.result)
103
106
  } finally {
@@ -108,11 +111,17 @@ export async function callTool(
108
111
  /** An MCP tool result as a `ToolAnswer`: text and images as they are, anything else as its text or JSON. */
109
112
  function answerOf(result: unknown): ToolAnswer {
110
113
  const { content, structuredContent, isError } = (result ?? {}) as {
111
- content?: McpPiece[]
114
+ content?: {
115
+ type: string
116
+ text?: string
117
+ data?: string
118
+ mimeType?: string
119
+ resource?: { text?: string }
120
+ }[]
112
121
  structuredContent?: unknown
113
122
  isError?: boolean
114
123
  }
115
- const pieces: AssistantContent[] = []
124
+ const pieces: ToolAnswer['content'] = []
116
125
  for (const piece of content ?? [])
117
126
  if (piece.type === 'text')
118
127
  pieces.push({ type: 'text', text: piece.text ?? '' })
@@ -133,7 +142,7 @@ function answerOf(result: unknown): ToolAnswer {
133
142
  })
134
143
  if (pieces.length === 0 && structuredContent !== undefined)
135
144
  pieces.push({ type: 'text', text: JSON.stringify(structuredContent) })
136
- return { content: pieces, failed: isError === true }
145
+ return { content: pieces, isError: isError === true }
137
146
  }
138
147
 
139
148
  /**
@@ -145,7 +154,7 @@ async function stdioSession(
145
154
  configuration: ServerConfiguration,
146
155
  signal: AbortSignal,
147
156
  ): Promise<Session> {
148
- const directory = await mkdtemp(`${tmpdir()}/abide-bridge-`)
157
+ const { directory, remove } = await scratchDirectory()
149
158
  let child: Bun.Subprocess<'pipe', 'pipe', 'pipe'>
150
159
  try {
151
160
  child = Bun.spawn({
@@ -161,9 +170,9 @@ async function stdioSession(
161
170
  signal,
162
171
  })
163
172
  } catch (thrown) {
164
- await rm(directory, { recursive: true, force: true })
173
+ await remove()
165
174
  throw new Error(
166
- `The ${name} MCP server could not be started: ${thrown instanceof Error ? thrown.message : String(thrown)}`,
175
+ `The ${name} MCP server could not be started: ${messageOf(thrown)}`,
167
176
  )
168
177
  }
169
178
  const stderr = new Response(child.stderr).text()
@@ -226,28 +235,77 @@ async function stdioSession(
226
235
  async close() {
227
236
  child.kill()
228
237
  await child.exited
229
- await rm(directory, { recursive: true, force: true })
238
+ await remove()
230
239
  },
231
240
  }
232
241
  }
233
242
 
243
+ /**
244
+ * 44.95 — the headers a server's `headersHelper` writes, run as Claude Code runs it: in a shell, told
245
+ * the server's name and address, given ten seconds, its stdout a JSON object of text.
246
+ */
247
+ async function helpedHeaders(
248
+ name: string,
249
+ configuration: ServerConfiguration,
250
+ signal: AbortSignal,
251
+ ): Promise<Record<string, string>> {
252
+ if (configuration.headersHelper === undefined) return {}
253
+ const child = Bun.spawn(['sh', '-c', configuration.headersHelper], {
254
+ env: {
255
+ ...Bun.env,
256
+ CLAUDE_CODE_MCP_SERVER_NAME: name,
257
+ CLAUDE_CODE_MCP_SERVER_URL: configuration.url as string,
258
+ },
259
+ stdout: 'pipe',
260
+ stderr: 'pipe',
261
+ timeout: HEADERS_HELPER_MILLISECONDS,
262
+ signal,
263
+ })
264
+ const [written, said, exited] = await Promise.all([
265
+ new Response(child.stdout).text(),
266
+ new Response(child.stderr).text(),
267
+ child.exited,
268
+ ])
269
+ if (exited !== 0)
270
+ throw new Error(
271
+ `The ${name} MCP server's headersHelper exited ${exited}: ${said.slice(-2000)}`,
272
+ )
273
+ let headers: unknown
274
+ try {
275
+ headers = JSON.parse(written)
276
+ } catch {
277
+ headers = undefined
278
+ }
279
+ if (
280
+ headers === null ||
281
+ typeof headers !== 'object' ||
282
+ Array.isArray(headers) ||
283
+ Object.values(headers).some((value) => typeof value !== 'string')
284
+ )
285
+ throw new Error(
286
+ `The ${name} MCP server's headersHelper wrote no JSON object of text headers.`,
287
+ )
288
+ return headers as Record<string, string>
289
+ }
290
+
234
291
  /** A server at an http address, each message posted, its answer read as JSON or from an event stream. */
235
292
  function httpSession(
236
293
  name: string,
237
- configuration: ServerConfiguration,
294
+ url: string,
295
+ sent: Record<string, string>,
238
296
  signal: AbortSignal,
239
297
  ): Session {
240
298
  let sessionId: string | null = null
241
299
  return {
242
300
  async send(message) {
243
301
  const headers: Record<string, string> = {
244
- ...configuration.headers,
302
+ ...sent,
245
303
  'content-type': 'application/json',
246
304
  accept: 'application/json, text/event-stream',
247
305
  'mcp-protocol-version': PROTOCOL_VERSION,
248
306
  }
249
307
  if (sessionId !== null) headers['mcp-session-id'] = sessionId
250
- const answer = await fetch(configuration.url as string, {
308
+ const answer = await fetch(url, {
251
309
  method: 'POST',
252
310
  headers,
253
311
  body: JSON.stringify({ jsonrpc: '2.0', ...message }),
@@ -256,7 +314,7 @@ function httpSession(
256
314
  sessionId = answer.headers.get('mcp-session-id') ?? sessionId
257
315
  if (answer.status === 401 || answer.status === 403)
258
316
  throw new Error(
259
- `The ${name} MCP server asks for a sign-in (${answer.status}): a call carries only the headers its configuration names, and none Claude Code signed in with.`,
317
+ `The ${name} MCP server asks for a sign-in (${answer.status}): a call carries only the headers its configuration names and its headersHelper writes, and none Claude Code signed in with.`,
260
318
  )
261
319
  if (!answer.ok)
262
320
  throw new Error(
@@ -290,10 +348,10 @@ function httpSession(
290
348
  },
291
349
  async close() {
292
350
  if (sessionId === null) return
293
- await fetch(configuration.url as string, {
351
+ await fetch(url, {
294
352
  method: 'DELETE',
295
353
  headers: {
296
- ...configuration.headers,
354
+ ...sent,
297
355
  'mcp-session-id': sessionId,
298
356
  },
299
357
  })
package/src/claudeTurn.ts CHANGED
@@ -12,9 +12,6 @@
12
12
  // A TOOL OF THIS MACHINE IS APPROVED AS AUTO MODE DECIDES, and what it would ask is asked of the page
13
13
  // (44.81): the site's own tools alone are approved without asking.
14
14
 
15
- import { mkdtemp, rm } from 'node:fs/promises' // bun has no temporary directory or recursive remove of its own
16
- import { tmpdir } from 'node:os' // bun exposes no temporary directory of its own
17
-
18
15
  import type { ClaudeCodeConfig, ProviderEvent } from '@abide/abide/server'
19
16
 
20
17
  import {
@@ -26,6 +23,7 @@ import {
26
23
  withheldNotices,
27
24
  } from './grant.ts'
28
25
  import { readLines } from './readLines.ts'
26
+ import { scratchDirectory } from './scratchDirectory.ts'
29
27
 
30
28
  // Every tool of that server, as `--allowedTools` names them.
31
29
  const SERVER_TOOLS = `mcp__${SERVER_NAME}`
@@ -41,42 +39,39 @@ export type TurnRequest = {
41
39
  maxTurns: number
42
40
  }
43
41
 
44
- type Usage = {
45
- input_tokens?: number
46
- cache_creation_input_tokens?: number
47
- cache_read_input_tokens?: number
48
- output_tokens?: number
42
+ /** What a tool answered, as a `user` line carries it: its words, or blocks — an image as the API's or as MCP's. */
43
+ type Answered = {
44
+ type: string
45
+ text?: string
46
+ source?: unknown
47
+ data?: string
48
+ mimeType?: string
49
49
  }
50
50
 
51
- type McpContent = { type: string; text?: string }
52
-
53
51
  type CodeLine = {
54
52
  type: string
55
53
  subtype?: string
54
+ // The Messages API's own event, as Claude Code streamed it.
56
55
  event?: {
57
56
  type: string
58
- delta?: { type: string; text?: string }
59
- content_block?: { type: string; id?: string; name?: string }
57
+ content_block?: { type: string; name?: string }
60
58
  }
61
59
  message?: {
62
60
  content:
63
61
  | string
64
62
  | {
65
63
  type: string
66
- id?: string
67
- name?: string
68
- input?: unknown
69
64
  tool_use_id?: string
70
- content?: McpContent[] | string
65
+ content?: Answered[] | string
71
66
  is_error?: boolean
72
67
  }[]
73
68
  }
74
- stop_reason?: string | null
75
69
  is_error?: boolean
76
70
  result?: string
77
- usage?: Usage
78
71
  }
79
72
 
73
+ type ResultContent = Extract<ProviderEvent, { type: 'tool_result' }>['content']
74
+
80
75
  // 44.16 — the options a site may set: each only shapes the answer, and reaches nothing of this machine.
81
76
  // Keyed by `ClaudeCodeConfig`'s own keys, so a key added on abide's side is a compile error here
82
77
  // until it is decided whether a site may set it.
@@ -134,9 +129,8 @@ async function launchFlags(
134
129
  full: boolean,
135
130
  ): Promise<{ flags: string[]; grant: Grant }> {
136
131
  const { tools: asked, ...options } = config
137
- const { grant, args } = await grantFor(asked ?? [], visitor, full)
138
132
  // 44.82 — the visitor's options as they gave them, and Claude Code's own settings and servers.
139
- const given = full ? [...visitor] : args
133
+ const { grant, args: given } = await grantFor(asked ?? [], visitor, full)
140
134
  const allowed = takeFlag(given, ['--allowedTools', '--allowed-tools'])
141
135
  const sources = full ? [] : takeFlag(given, ['--setting-sources'])
142
136
  const flags = [
@@ -159,26 +153,43 @@ async function launchFlags(
159
153
  return { flags, grant }
160
154
  }
161
155
 
162
- function textOf(content: McpContent[] | string | undefined): string {
163
- if (typeof content === 'string') return content
164
- let text = ''
165
- for (const part of content ?? [])
166
- if (part.text !== undefined) text += part.text
167
- return text
156
+ /** What a tool answered, as the Messages API's blocks for a `tool_result`: its words, and its images. */
157
+ function blocksOf(content: Answered[] | string | undefined): ResultContent {
158
+ if (typeof content === 'string') return [{ type: 'text', text: content }]
159
+ const blocks: ResultContent = []
160
+ for (const piece of content ?? [])
161
+ if (piece.type === 'text' && piece.text !== undefined)
162
+ blocks.push({ type: 'text', text: piece.text })
163
+ else if (piece.type === 'image' && piece.source !== undefined)
164
+ blocks.push(piece as ResultContent[number])
165
+ else if (piece.type === 'image' && piece.data !== undefined)
166
+ blocks.push({
167
+ type: 'image',
168
+ source: {
169
+ type: 'base64',
170
+ media_type: piece.mimeType as 'image/png',
171
+ data: piece.data,
172
+ },
173
+ })
174
+ return blocks
168
175
  }
169
176
 
170
- function done(stop: string, usage: Usage | undefined): ProviderEvent {
177
+ /**
178
+ * The API's event as Claude Code streamed it, a call to one of the site's tools named as the site
179
+ * lists it rather than as Claude Code's MCP server prefixes it. 44.2, 44.50.
180
+ */
181
+ function siteNamed(event: NonNullable<CodeLine['event']>): ProviderEvent {
182
+ const block = event.content_block
183
+ if (
184
+ event.type !== 'content_block_start' ||
185
+ block?.type !== 'tool_use' ||
186
+ block.name?.startsWith(TOOL_PREFIX) !== true
187
+ )
188
+ return event as ProviderEvent
171
189
  return {
172
- type: 'done',
173
- stop,
174
- usage: {
175
- input:
176
- (usage?.input_tokens ?? 0) +
177
- (usage?.cache_creation_input_tokens ?? 0) +
178
- (usage?.cache_read_input_tokens ?? 0),
179
- output: usage?.output_tokens ?? 0,
180
- },
181
- }
190
+ ...event,
191
+ content_block: { ...block, name: block.name.slice(TOOL_PREFIX.length) },
192
+ } as ProviderEvent
182
193
  }
183
194
 
184
195
  /**
@@ -207,7 +218,7 @@ export async function claudeTurn(
207
218
  )
208
219
  if (!options.full)
209
220
  for (const notice of withheldNotices(grant)) options.say(notice)
210
- const directory = await mkdtemp(`${tmpdir()}/abide-bridge-`)
221
+ const { directory, remove } = await scratchDirectory()
211
222
  const config = `${directory}/mcp.json`
212
223
  await Bun.write(
213
224
  config,
@@ -261,51 +272,28 @@ export async function claudeTurn(
261
272
  for await (const text of readLines(child.stdout)) {
262
273
  if (text === '') continue
263
274
  const line = JSON.parse(text) as CodeLine
264
- if (line.type === 'stream_event') {
265
- const delta = line.event?.delta
266
- const started = line.event?.content_block
267
- if (
268
- line.event?.type === 'content_block_delta' &&
269
- delta?.type === 'text_delta'
270
- )
271
- options.report({ type: 'text', text: delta.text as string })
272
- // 44.28 — the call is announced as the model starts writing it, its input once written.
273
- else if (
274
- line.event?.type === 'content_block_start' &&
275
- started?.type === 'tool_use'
276
- )
277
- options.report({
278
- type: 'tool',
279
- id: started.id as string,
280
- name: (started.name as string).replace(TOOL_PREFIX, ''),
281
- })
282
- } else if (
283
- (line.type === 'assistant' || line.type === 'user') &&
275
+ // 44.2 — each run as the API streamed it, event for event: Claude Code's partial
276
+ // messages are the API's own events, and nothing is reshaped but a site tool's name.
277
+ if (line.type === 'stream_event' && line.event !== undefined)
278
+ options.report(siteNamed(line.event))
279
+ // What a call answered, which Claude Code reports in the user message it sends back.
280
+ else if (
281
+ line.type === 'user' &&
284
282
  Array.isArray(line.message?.content)
285
283
  ) {
286
284
  for (const block of line.message.content)
287
- if (block.type === 'tool_use')
288
- options.report({
289
- type: 'input',
290
- id: block.id as string,
291
- input: block.input,
292
- })
293
- else if (block.type === 'tool_result')
285
+ if (block.type === 'tool_result')
294
286
  options.report({
295
- type: 'result',
296
- id: block.tool_use_id as string,
297
- text: textOf(block.content),
298
- failed: block.is_error === true,
287
+ type: 'tool_result',
288
+ tool_use_id: block.tool_use_id as string,
289
+ content: blocksOf(block.content),
290
+ is_error: block.is_error === true,
299
291
  })
300
292
  } else if (line.type === 'result') {
301
- // The turn cap is one stop, whichever provider reached it.
302
- if (line.subtype === 'error_max_turns') {
303
- options.report(done('max_turns', line.usage))
304
- return
305
- }
293
+ // The turn cap ends the answer as `provider.claudeApi`'s does: a call left unanswered.
294
+ if (line.subtype === 'error_max_turns') return
306
295
  if (line.is_error === true)
307
296
  throw new Error(line.result ?? line.subtype ?? 'failed')
308
- options.report(done(line.stop_reason ?? 'end_turn', line.usage))
309
297
  return
310
298
  }
311
299
  }
@@ -315,6 +303,6 @@ export async function claudeTurn(
315
303
  )
316
304
  } finally {
317
305
  child.kill()
318
- await rm(directory, { recursive: true, force: true })
306
+ await remove()
319
307
  }
320
308
  }
package/src/desktop.ts CHANGED
@@ -7,10 +7,9 @@
7
7
  // 44.64 — A QUESTION THAT CANNOT BE SHOWN IS A NO: a Linux desktop with neither `zenity` nor `kdialog`
8
8
  // pairs nothing from a link.
9
9
 
10
- import { rm } from 'node:fs/promises' // bun has no remove of its own
11
- import { tmpdir } from 'node:os' // bun exposes no temporary directory of its own
12
-
10
+ import { APP_NAME } from './APP_NAME.ts'
13
11
  import { macAlert } from './macAlert.ts'
12
+ import { scratchDirectory } from './scratchDirectory.ts'
14
13
 
15
14
  /**
16
15
  * What the visitor answered: don't pair, pair as the link asks, or — offered only where it asks for full
@@ -29,7 +28,6 @@ export type Question = {
29
28
  icon: Uint8Array | undefined
30
29
  }
31
30
 
32
- const TITLE = 'abide bridge'
33
31
  const DENY = 'Don’t Allow'
34
32
  const ALLOW = 'Allow'
35
33
  const SITE_TOOLS = 'Only Site Tools'
@@ -121,14 +119,15 @@ async function ran(
121
119
  }
122
120
  }
123
121
 
124
- /** Writes `icon` where a dialog can read it as a file, answering where, or `undefined` for none. */
122
+ /** Writes `icon` where a dialog can read it as a file: the file, and its removal, or `undefined`. */
125
123
  async function iconFile(
126
124
  icon: Uint8Array | undefined,
127
- ): Promise<string | undefined> {
125
+ ): Promise<{ file: string; remove: () => Promise<void> } | undefined> {
128
126
  if (icon === undefined) return undefined
129
- const file = `${tmpdir()}/abide-bridge-icon-${crypto.randomUUID()}.png`
127
+ const { directory, remove } = await scratchDirectory()
128
+ const file = `${directory}/icon.png`
130
129
  await Bun.write(file, icon)
131
- return file
130
+ return { file, remove }
132
131
  }
133
132
 
134
133
  /**
@@ -221,7 +220,7 @@ export async function ask(
221
220
  ABIDE_BRIDGE_TITLE: question.title,
222
221
  ABIDE_BRIDGE_HEADLINE: question.headline,
223
222
  ABIDE_BRIDGE_BODY: question.body,
224
- ABIDE_BRIDGE_ICON: icon ?? '',
223
+ ABIDE_BRIDGE_ICON: icon?.file ?? '',
225
224
  ABIDE_BRIDGE_BUTTONS: buttons.join('\n'),
226
225
  },
227
226
  )
@@ -233,7 +232,7 @@ export async function ask(
233
232
  question,
234
233
  offerSiteTools,
235
234
  (tool) => Bun.which(tool) !== null,
236
- icon,
235
+ icon?.file,
237
236
  )
238
237
  if (command === undefined) return 'deny'
239
238
  const shown = await ran(command)
@@ -245,7 +244,7 @@ export async function ask(
245
244
  return shown.printed === SITE_TOOLS ? 'siteTools' : 'deny'
246
245
  return shown.code === 1 ? 'siteTools' : 'deny'
247
246
  } finally {
248
- if (icon !== undefined) await rm(icon, { force: true })
247
+ await icon?.remove()
249
248
  }
250
249
  }
251
250
 
@@ -257,11 +256,11 @@ export async function notify(line: string): Promise<void> {
257
256
  '-e',
258
257
  'on run argv',
259
258
  '-e',
260
- `display notification (item 1 of argv) with title "${TITLE}"`,
259
+ `display notification (item 1 of argv) with title "${APP_NAME}"`,
261
260
  '-e',
262
261
  'end run',
263
262
  line,
264
263
  ])
265
264
  else if (process.platform === 'linux' && Bun.which('notify-send') !== null)
266
- await ran(['notify-send', TITLE, line])
265
+ await ran(['notify-send', APP_NAME, line])
267
266
  }
package/src/grant.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  // a server's as `mcp__<server>` — and of those, the MCP tools whose server the visitor's own Claude Code
4
4
  // configuration holds. A site names tools and never a server: a server is a command this machine runs.
5
5
 
6
+ import { messageOf } from './messageOf.ts'
7
+
6
8
  /** What Claude Code names the MCP server the bridge relays to the site, and so the prefix on each of its tools. */
7
9
  export const SERVER_NAME = 'app'
8
10
 
@@ -116,7 +118,7 @@ export async function visitorServers(
116
118
  )
117
119
  } catch (thrown) {
118
120
  throw new Error(
119
- `The --mcp-config ${source} could not be read: ${thrown instanceof Error ? thrown.message : String(thrown)}`,
121
+ `The --mcp-config ${source} could not be read: ${messageOf(thrown)}`,
120
122
  )
121
123
  }
122
124
  }
@@ -167,8 +169,8 @@ export function grantOf(
167
169
 
168
170
  /**
169
171
  * What a site asking for `asked` is given by a visitor who passed `claudeArgs`, beside those args with
170
- * `--tools` and `--mcp-config` taken out — every tool asked, where the bridge runs `full` (44.82). The
171
- * visitor's servers are read only where an MCP tool is asked.
172
+ * `--tools` and `--mcp-config` taken out — every tool asked, and the args untouched, where the bridge
173
+ * runs `full` (44.82). The visitor's servers are read only where an MCP tool is asked.
172
174
  *
173
175
  * Throws where an `--mcp-config` they named cannot be read, unless `unreadable` is given: then that is
174
176
  * said to it, and the grant is of no server.
@@ -191,11 +193,12 @@ export async function grantFor(
191
193
  configured = await visitorServers(sources)
192
194
  } catch (thrown) {
193
195
  if (unreadable === undefined) throw thrown
194
- unreadable(
195
- thrown instanceof Error ? thrown.message : String(thrown),
196
- )
196
+ unreadable(messageOf(thrown))
197
197
  }
198
- return { grant: grantOf(asked, granted, configured), args }
198
+ return {
199
+ grant: grantOf(asked, granted, configured),
200
+ args: full ? [...claudeArgs] : args,
201
+ }
199
202
  }
200
203
 
201
204
  /** The servers `unserved` tools are of, as one list to name in a sentence. */
@@ -267,9 +270,7 @@ export async function callGrant(
267
270
  const { grant, args } = await grantFor([tool], claudeArgs, full)
268
271
  if (grant.mcp.length === 0)
269
272
  return { refused: withheldNotices(grant).join(' ') }
270
- // 44.82 — a full bridge's options as the visitor gave them.
271
- const given = full ? [...claudeArgs] : args
272
- const denied = takeFlag(given, ['--disallowedTools', '--disallowed-tools'])
273
+ const denied = takeFlag(args, ['--disallowedTools', '--disallowed-tools'])
273
274
  if (namesTool(denied, tool, server))
274
275
  return {
275
276
  refused: `The site called ${tool}, which this bridge’s --disallowedTools names.`,
package/src/install.ts CHANGED
@@ -15,10 +15,10 @@
15
15
 
16
16
  import { rm } from 'node:fs/promises' // bun has no recursive remove of its own
17
17
 
18
+ import { APP_NAME } from './APP_NAME.ts'
18
19
  import type { HandlerSettings } from './opened.ts'
19
20
  import { PAIRING_SCHEME } from './PAIRING_SCHEME.ts'
20
21
 
21
- const APP_NAME = 'abide bridge'
22
22
  export const IDENTIFIER = 'abide.bridge'
23
23
  const DESKTOP_ENTRY = 'abide-bridge.desktop'
24
24
  const LAUNCH_SERVICES =
@@ -54,11 +54,11 @@ process.exit(await open(process.argv[2] ?? '', import.meta.dir))
54
54
  `
55
55
  }
56
56
 
57
- /** Where `XDG_DATA_HOME` points, or its default under the visitor's home. */
58
- function dataHome(): string {
59
- const declared = Bun.env.XDG_DATA_HOME
57
+ /** Where the XDG `variable` points, or its default `underHome` the visitor's home. */
58
+ function xdgDirectory(variable: string, underHome: string): string {
59
+ const declared = Bun.env[variable]
60
60
  return declared === undefined || declared === ''
61
- ? `${Bun.env.HOME ?? ''}/.local/share`
61
+ ? `${Bun.env.HOME ?? ''}${underHome}`
62
62
  : declared
63
63
  }
64
64
 
@@ -87,9 +87,8 @@ export function withoutDefault(list: string): string {
87
87
 
88
88
  /** Unregisters the Linux desktop entry: no longer the scheme's default, and gone. */
89
89
  async function uninstallLinux(directory: string): Promise<void> {
90
- const declared = Bun.env.XDG_CONFIG_HOME
91
90
  const list = Bun.file(
92
- `${declared === undefined || declared === '' ? `${Bun.env.HOME ?? ''}/.config` : declared}/mimeapps.list`,
91
+ `${xdgDirectory('XDG_CONFIG_HOME', '/.config')}/mimeapps.list`,
93
92
  )
94
93
  if (await list.exists()) {
95
94
  const written = await list.text()
@@ -104,7 +103,8 @@ export function installDirectory(): string {
104
103
  const platform = process.platform
105
104
  if (platform === 'win32')
106
105
  return `${Bun.env.LOCALAPPDATA ?? `${Bun.env.USERPROFILE ?? ''}\\AppData\\Local`}\\abide-bridge`
107
- if (platform === 'linux') return `${dataHome()}/abide-bridge`
106
+ if (platform === 'linux')
107
+ return `${xdgDirectory('XDG_DATA_HOME', '/.local/share')}/abide-bridge`
108
108
  return `${Bun.env.HOME ?? ''}/Library/Application Support/abide-bridge`
109
109
  }
110
110
 
@@ -126,7 +126,7 @@ function appletSource(bun: string, directory: string): string {
126
126
  end open location
127
127
 
128
128
  on run
129
- \tdisplay dialog "abide bridge opens the pairing links abide sites show, so your Claude Code can be their assistant. There is nothing to do here." buttons {"OK"} default button "OK" with title "abide bridge"
129
+ \tdisplay dialog "${APP_NAME} opens the pairing links abide sites show, so your Claude Code can be their assistant. There is nothing to do here." buttons {"OK"} default button "OK" with title "${APP_NAME}"
130
130
  end run
131
131
  `
132
132
  }
@@ -215,7 +215,7 @@ async function installMac(
215
215
  '-json',
216
216
  JSON.stringify([
217
217
  {
218
- CFBundleURLName: 'abide bridge pairing',
218
+ CFBundleURLName: `${APP_NAME} pairing`,
219
219
  CFBundleURLSchemes: [PAIRING_SCHEME],
220
220
  },
221
221
  ]),
@@ -230,7 +230,7 @@ async function installMac(
230
230
  /** The desktop entry's path: in `directory` where install is not registering, else the visitor's applications. */
231
231
  function entryPath(directory: string, register: boolean): string {
232
232
  return register
233
- ? `${dataHome()}/applications/${DESKTOP_ENTRY}`
233
+ ? `${xdgDirectory('XDG_DATA_HOME', '/.local/share')}/applications/${DESKTOP_ENTRY}`
234
234
  : `${directory}/${DESKTOP_ENTRY}`
235
235
  }
236
236
 
@@ -0,0 +1,5 @@
1
+ // abide's `messageOf`, spelled out because the bridge carries no abide at run time.
2
+ /** What a thrown value says: an `Error`'s message, or anything else as text. */
3
+ export function messageOf(thrown: unknown): string {
4
+ return thrown instanceof Error ? thrown.message : String(thrown)
5
+ }
package/src/opened.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  import { BRIDGE_PATH } from './BRIDGE_PATH.ts'
22
22
  import { type Answer, ask, notify, type Question } from './desktop.ts'
23
23
  import { grantFor, serversNamed } from './grant.ts'
24
+ import { messageOf } from './messageOf.ts'
24
25
  import { type Pairing, pairingOf, withoutScheme } from './pairingLink.ts'
25
26
  import { readLines } from './readLines.ts'
26
27
  import { requestedLines } from './requestedLines.ts'
@@ -409,9 +410,7 @@ export async function open(link: string, directory: string): Promise<number> {
409
410
  return settled(await pairWith(link, directory, say, record))
410
411
  } catch (thrown) {
411
412
  // The applet discards this process's output, so a throw is only seen if it is said.
412
- say(
413
- `The bridge could not open: ${thrown instanceof Error ? thrown.message : String(thrown)}`,
414
- )
413
+ say(`The bridge could not open: ${messageOf(thrown)}`)
415
414
  return settled(1)
416
415
  }
417
416
  }
@@ -0,0 +1,14 @@
1
+ import { mkdtemp, rm } from 'node:fs/promises' // bun has no temporary directory or recursive remove of its own
2
+ import { tmpdir } from 'node:os' // bun exposes no temporary directory of its own
3
+
4
+ /** An empty directory of the bridge's own, and the removal of it with all it holds. */
5
+ export async function scratchDirectory(): Promise<{
6
+ directory: string
7
+ remove: () => Promise<void>
8
+ }> {
9
+ const directory = await mkdtemp(`${tmpdir()}/abide-bridge-`)
10
+ return {
11
+ directory,
12
+ remove: () => rm(directory, { recursive: true, force: true }),
13
+ }
14
+ }
package/src/serveTurns.ts CHANGED
@@ -8,6 +8,7 @@ import type { ProviderEvent, ToolAnswer } from '@abide/abide/server'
8
8
  import { callTool } from './callTool.ts'
9
9
  import { claudeTurn, type TurnRequest } from './claudeTurn.ts'
10
10
  import { callGrant, PERMISSION_SERVER } from './grant.ts'
11
+ import { messageOf } from './messageOf.ts'
11
12
 
12
13
  // 44.24 — how long a relayed MCP request waits for the site's reply.
13
14
  const REPLY_MILLISECONDS = 120_000
@@ -259,54 +260,68 @@ export function serveTurns(options: {
259
260
  },
260
261
  })
261
262
 
263
+ // ONE LIFECYCLE for a turn and a call: registered to be cancelled, readied, worked, and answered
264
+ // once — by what it settled to, or a cancel's own reason where one cut it — and then forgotten.
262
265
  // A cancel or a signal aborts with no reason of its own, and ends the turn as asked.
263
- const missedBy = (controller: AbortController): string | undefined =>
264
- controller.signal.reason instanceof MissedTurn
265
- ? controller.signal.reason.message
266
- : undefined
267
-
268
- const run = async (turn: TurnRequest): Promise<void> => {
266
+ const served = async (
267
+ id: string,
268
+ work: (signal: AbortSignal) => Promise<TurnReport>,
269
+ ended?: () => void,
270
+ ): Promise<void> => {
269
271
  const controller = new AbortController()
270
- turns.set(turn.id, controller)
271
- await options.beforeTurn()
272
- const missed = (): string | undefined => missedBy(controller)
272
+ turns.set(id, controller)
273
+ const missed = (): string | undefined =>
274
+ controller.signal.reason instanceof MissedTurn
275
+ ? controller.signal.reason.message
276
+ : undefined
273
277
  try {
274
- await claudeTurn(turn, {
275
- claude: options.claude,
276
- claudeArgs: [...options.claudeArgs(turn)],
277
- full: options.full,
278
- mcpUrl: `http://127.0.0.1:${shim.port}/${secret}/${turn.id}`,
279
- signal: controller.signal,
280
- report: (event) =>
281
- report({ type: 'event', turn: turn.id, event }),
282
- say: options.say,
283
- })
278
+ await options.beforeTurn()
279
+ const settled = await work(controller.signal)
284
280
  const message = missed()
285
- if (message === undefined) report({ type: 'end', turn: turn.id })
286
- else report({ type: 'fail', turn: turn.id, message })
281
+ report(
282
+ message === undefined
283
+ ? settled
284
+ : { type: 'fail', turn: id, message },
285
+ )
287
286
  } catch (thrown) {
288
287
  report({
289
288
  type: 'fail',
290
- turn: turn.id,
291
- message:
292
- missed() ??
293
- (thrown instanceof Error ? thrown.message : String(thrown)),
289
+ turn: id,
290
+ message: missed() ?? messageOf(thrown),
294
291
  })
295
292
  } finally {
296
- turns.delete(turn.id)
297
- for (const [id, waiter] of waiting)
298
- if (waiter.turn === turn.id)
299
- answer(id, unanswered(waiter.method, 'The turn ended.'))
293
+ turns.delete(id)
294
+ ended?.()
300
295
  }
301
296
  }
302
297
 
298
+ const run = (turn: TurnRequest): Promise<void> =>
299
+ served(
300
+ turn.id,
301
+ async (signal) => {
302
+ await claudeTurn(turn, {
303
+ claude: options.claude,
304
+ claudeArgs: [...options.claudeArgs(turn)],
305
+ full: options.full,
306
+ mcpUrl: `http://127.0.0.1:${shim.port}/${secret}/${turn.id}`,
307
+ signal,
308
+ report: (event) =>
309
+ report({ type: 'event', turn: turn.id, event }),
310
+ say: options.say,
311
+ })
312
+ return { type: 'end', turn: turn.id }
313
+ },
314
+ () => {
315
+ for (const [id, waiter] of waiting)
316
+ if (waiter.turn === turn.id)
317
+ answer(id, unanswered(waiter.method, 'The turn ended.'))
318
+ },
319
+ )
320
+
303
321
  // 44.93, 44.97 — A CALL IS MADE AS IT ARRIVES, beside every other call and turn, by the grant a turn
304
322
  // naming its tool alone would have (44.94), on the visitor's server started for it alone (44.95).
305
- const call = async (asked: CallRequest): Promise<void> => {
306
- const controller = new AbortController()
307
- turns.set(asked.id, controller)
308
- try {
309
- await options.beforeTurn()
323
+ const call = (asked: CallRequest): Promise<void> =>
324
+ served(asked.id, async (signal) => {
310
325
  const granted = await callGrant(
311
326
  asked.name,
312
327
  options.claudeArgs(asked),
@@ -314,38 +329,21 @@ export function serveTurns(options: {
314
329
  )
315
330
  if (granted.refused !== undefined) {
316
331
  options.say(granted.refused)
317
- report({
332
+ return {
318
333
  type: 'refused',
319
334
  turn: asked.id,
320
335
  message: granted.refused,
321
- })
322
- return
336
+ }
323
337
  }
324
338
  const answer = await callTool(
325
339
  granted.server,
326
340
  granted.configuration,
327
341
  granted.name,
328
342
  asked.input,
329
- controller.signal,
330
- )
331
- const message = missedBy(controller)
332
- report(
333
- message === undefined
334
- ? { type: 'answer', turn: asked.id, answer }
335
- : { type: 'fail', turn: asked.id, message },
343
+ signal,
336
344
  )
337
- } catch (thrown) {
338
- report({
339
- type: 'fail',
340
- turn: asked.id,
341
- message:
342
- missedBy(controller) ??
343
- (thrown instanceof Error ? thrown.message : String(thrown)),
344
- })
345
- } finally {
346
- turns.delete(asked.id)
347
- }
348
- }
345
+ return { type: 'answer', turn: asked.id, answer }
346
+ })
349
347
 
350
348
  const cancelAll = (): void => {
351
349
  for (const controller of turns.values()) controller.abort()