@abide/bridge 0.4.0 → 0.5.1

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,17 @@
1
1
  # @abide/bridge
2
2
 
3
+ ## 0.5.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 0e5f83e: a bridge ends a turn the site missed part of and reports it failed, says a lost site once, and speaks in shorter notifications (RULEBOOK 44.24, 44.45, 44.46) ([`ad9706e`](https://github.com/briancray/abide/commit/ad9706ee850811219c29cd58fe5289219da93c61))
8
+
9
+ ## 0.5.0
10
+
11
+ ### Minor Changes
12
+
13
+ - efef999: `abide-bridge install` keeps `--env NAME=VALUE` and the Claude Code options after its `--`, and every pairing link it opens runs with them — naming them in the question it asks first (RULEBOOK 44.42, 44.44)
14
+
3
15
  ## 0.4.0
4
16
 
5
17
  ### Minor Changes
@@ -1,33 +1,48 @@
1
1
  #!/usr/bin/env bun
2
- // `abide-bridge <site> <code> [--claude <path>] [-- <claude options>]` — the command an abide site shows
3
- // you to connect your Claude Code to its assistant. `--claude <path>` names the executable where `claude`
4
- // is not on PATH; whatever follows `--` is passed to Claude Code as you wrote it, and is how you give a
5
- // site what reaches this machine — `-- --tools WebSearch,WebFetch` for the built-in tools it asks for.
2
+ // `abide-bridge <site> <code> [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]` — the command
3
+ // an abide site shows you to connect your Claude Code to its assistant. `--claude <path>` names the
4
+ // executable where `claude` is not on PATH; each `--env` sets a variable Claude Code runs with; whatever
5
+ // follows `--` is passed to Claude Code as you wrote it, and is how you give a site what reaches this
6
+ // machine — `-- --tools WebSearch,WebFetch` for the built-in tools it asks for.
6
7
  //
7
- // `abide-bridge install [--claude <path>]` builds and registers, on macOS, the app that opens the pairing
8
- // link a site shows beside its command, so a click pairs instead of a terminal; `abide-bridge uninstall`
9
- // takes it away.
8
+ // `abide-bridge install` takes the same options and builds and registers, on macOS, the app that opens the
9
+ // pairing link a site shows beside its command, so a click pairs instead of a terminal — every link it
10
+ // opens runs with the `--env` and the `--` options given here (44.44); `abide-bridge uninstall` takes it
11
+ // away.
10
12
 
11
13
  import { bridge } from '../src/bridge.ts'
12
14
  import { install, installDirectory, uninstall } from '../src/install.ts'
13
15
 
16
+ const USAGE =
17
+ 'usage: abide-bridge <site> <code> [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge install [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge uninstall'
18
+
14
19
  const all = process.argv.slice(2)
15
20
  const split = all.indexOf('--')
16
21
  const args = split === -1 ? all : all.slice(0, split)
17
22
  const claudeArgs = split === -1 ? [] : all.slice(split + 1)
18
- const flag = args.indexOf('--claude')
19
- const claude = flag === -1 ? undefined : args[flag + 1]
20
- const [site, code] = args.filter(
21
- (_arg, index) => flag === -1 || (index !== flag && index !== flag + 1),
22
- )
23
+ let claude: string | undefined
24
+ const env: Record<string, string> = {}
25
+ const positional: string[] = []
26
+ let malformed = false
27
+ for (let index = 0; index < args.length; index++) {
28
+ const arg = args[index] as string
29
+ if (arg === '--claude') claude = args[++index]
30
+ else if (arg === '--env') {
31
+ const assignment = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(
32
+ args[++index] ?? '',
33
+ )
34
+ if (assignment === null) malformed = true
35
+ else env[assignment[1] as string] = assignment[2] as string
36
+ } else positional.push(arg)
37
+ }
38
+ const [site, code] = positional
23
39
 
24
40
  if (
41
+ malformed ||
25
42
  site === undefined ||
26
43
  (site !== 'uninstall' && site !== 'install' && code === undefined)
27
44
  ) {
28
- console.error(
29
- 'usage: abide-bridge <site> <code> [--claude <path>] [-- <claude options>]\n abide-bridge install [--claude <path>]\n abide-bridge uninstall',
30
- )
45
+ console.error(USAGE)
31
46
  process.exit(2)
32
47
  }
33
48
 
@@ -49,17 +64,22 @@ try {
49
64
  bun: process.execPath,
50
65
  claude: found,
51
66
  path: Bun.env.PATH ?? '',
67
+ claudeArgs,
68
+ env,
52
69
  })
53
70
  console.error(
54
71
  `Installed ${app}. A site's pairing link now opens here, and asks you before it pairs. \`abide-bridge uninstall\` removes it.`,
55
72
  )
56
- } else
73
+ } else {
74
+ // Claude Code is started with this process's environment.
75
+ Object.assign(process.env, env)
57
76
  await bridge({
58
77
  site,
59
78
  code: code as string,
60
79
  claudeArgs,
61
80
  claude: found,
62
81
  })
82
+ }
63
83
  }
64
84
  process.exit(0)
65
85
  } catch (thrown) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abide/bridge",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
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",
package/src/bridge.ts CHANGED
@@ -62,6 +62,9 @@ type Waiting = {
62
62
  deadline: ReturnType<typeof setTimeout>
63
63
  }
64
64
 
65
+ /** 44.46 — the abort reason of a turn the site missed part of, which it reports failed with. */
66
+ class MissedTurn extends Error {}
67
+
65
68
  /** What Claude Code is answered where the site never replied: a failed call, or a JSON-RPC error. */
66
69
  function unanswered(method: string, message: string): Record<string, unknown> {
67
70
  return method === 'tools/call'
@@ -85,6 +88,9 @@ export async function bridge(options: {
85
88
  silenceMilliseconds?: number
86
89
  }): Promise<void> {
87
90
  const site = options.site.replace(/\/+$/, '')
91
+ // WHAT IS SAID IS READ AS A NOTIFICATION, where a link opened the bridge (`opened.ts`): one short
92
+ // sentence naming the site by its host. The detail goes to Claude Code, in the failure it is answered.
93
+ const host = new URL(site).host
88
94
  const say = options.say ?? ((line: string) => console.error(line))
89
95
  const replyMilliseconds = options.replyMilliseconds ?? REPLY_MILLISECONDS
90
96
  const silenceMilliseconds =
@@ -100,7 +106,7 @@ export async function bridge(options: {
100
106
  )
101
107
  if (!stream.ok || stream.body === null)
102
108
  throw new Error(
103
- `${site} refused the pairing (${stream.status}): ${await stream.text()}`,
109
+ `${host} refused to pair (${stream.status}). ${await stream.text()}`,
104
110
  )
105
111
 
106
112
  let token = ''
@@ -115,6 +121,9 @@ export async function bridge(options: {
115
121
  const outbox: Report[] = []
116
122
  let flushing: Promise<void> = Promise.resolve()
117
123
  let scheduled = false
124
+ // 44.45 — `failing` once a report the site did not take has been said, until one is taken; a
125
+ // redial is what is said while it lasts (44.25), and no failed report is.
126
+ let link: 'up' | 'failing' | 'redialing' = 'up'
118
127
  const flush = async (): Promise<void> => {
119
128
  scheduled = false
120
129
  const batch = outbox.splice(0)
@@ -122,6 +131,7 @@ export async function bridge(options: {
122
131
  const lines: string[] = []
123
132
  for (const item of batch) lines.push(JSON.stringify(item))
124
133
  let failure: string | undefined
134
+ let notice = ''
125
135
  try {
126
136
  const posted = await fetch(`${site}${BRIDGE_PATH}`, {
127
137
  method: 'POST',
@@ -131,18 +141,32 @@ export async function bridge(options: {
131
141
  },
132
142
  body: lines.join('\n'),
133
143
  })
134
- if (!posted.ok)
144
+ if (!posted.ok) {
135
145
  failure = `${site} refused a report (${posted.status}): ${await posted.text()}`
136
- else await posted.body?.cancel()
146
+ notice = `${host} didn’t take Claude Code’s reply (${posted.status}), so it stopped.`
147
+ } else await posted.body?.cancel()
137
148
  } catch (thrown) {
138
149
  failure = `${site} could not be reached: ${thrown instanceof Error ? thrown.message : String(thrown)}`
150
+ notice = `Can’t reach ${host}, so Claude Code stopped its reply.`
151
+ }
152
+ if (failure === undefined) {
153
+ if (link === 'failing') link = 'up'
154
+ return
139
155
  }
140
- if (failure === undefined) return
141
- say(failure)
142
- // 44.24 — a request the site never heard of is answered failed rather than waited on.
156
+ if (link === 'up') {
157
+ say(notice)
158
+ link = 'failing'
159
+ }
160
+ // 44.46 — a turn the site missed part of has no answer left to give, and is ended: what it
161
+ // still waits on is answered as `run` ends it, and the reason is what it reports it failed with.
143
162
  for (const item of batch)
144
- if (item.type === 'mcp')
145
- answer(item.id, unanswered(item.method, failure))
163
+ turns
164
+ .get(item.turn)
165
+ ?.abort(
166
+ new MissedTurn(
167
+ `The site missed part of this turn, so it was ended: ${failure}`,
168
+ ),
169
+ )
146
170
  }
147
171
  // One post at a time, in order: a turn's `end` never overtakes its last event.
148
172
  const report = (item: Report): void => {
@@ -236,6 +260,11 @@ export async function bridge(options: {
236
260
  const run = async (turn: TurnRequest): Promise<void> => {
237
261
  const controller = new AbortController()
238
262
  turns.set(turn.id, controller)
263
+ // A cancel or a signal aborts with no reason of its own, and ends the turn as asked.
264
+ const missed = (): string | undefined =>
265
+ controller.signal.reason instanceof MissedTurn
266
+ ? controller.signal.reason.message
267
+ : undefined
239
268
  try {
240
269
  await claudeTurn(turn, {
241
270
  claude: options.claude ?? 'claude',
@@ -246,13 +275,16 @@ export async function bridge(options: {
246
275
  report({ type: 'event', turn: turn.id, event }),
247
276
  say: sayOnce,
248
277
  })
249
- report({ type: 'end', turn: turn.id })
278
+ const message = missed()
279
+ if (message === undefined) report({ type: 'end', turn: turn.id })
280
+ else report({ type: 'fail', turn: turn.id, message })
250
281
  } catch (thrown) {
251
282
  report({
252
283
  type: 'fail',
253
284
  turn: turn.id,
254
285
  message:
255
- thrown instanceof Error ? thrown.message : String(thrown),
286
+ missed() ??
287
+ (thrown instanceof Error ? thrown.message : String(thrown)),
256
288
  })
257
289
  } finally {
258
290
  turns.delete(turn.id)
@@ -266,7 +298,8 @@ export async function bridge(options: {
266
298
  // stops holding the pairing.
267
299
  const redial = async (): Promise<Response | undefined> => {
268
300
  if (token === '') return undefined
269
- say(`Lost ${site}; reconnecting.`)
301
+ say(`Lost ${host}. Reconnecting…`)
302
+ link = 'redialing'
270
303
  const until = Date.now() + RESUME_MILLISECONDS
271
304
  let delay = FIRST_REDIAL_MILLISECONDS
272
305
  while (Date.now() < until) {
@@ -282,7 +315,8 @@ export async function bridge(options: {
282
315
  signal: dialed.signal,
283
316
  })
284
317
  if (resumed.ok && resumed.body !== null) {
285
- say(`Reconnected to ${site}.`)
318
+ say(`Reconnected to ${host}.`)
319
+ link = 'up'
286
320
  return resumed
287
321
  }
288
322
  await resumed.body?.cancel()
@@ -314,7 +348,7 @@ export async function bridge(options: {
314
348
  if (frame.type === 'paired') {
315
349
  token = frame.token
316
350
  say(
317
- `Connected to ${site}. Keep this running while you chat; it ends when you close the page.`,
351
+ `Connected to ${host}. Close the page to disconnect.`,
318
352
  )
319
353
  } else if (frame.type === 'turn') void run(frame)
320
354
  else if (frame.type === 'reply')
@@ -343,6 +377,6 @@ export async function bridge(options: {
343
377
  await flushing
344
378
  await flush()
345
379
  shim.stop(true)
346
- say(`Disconnected from ${site}.`)
380
+ say(`Disconnected from ${host}.`)
347
381
  }
348
382
  }
package/src/claudeTurn.ts CHANGED
@@ -210,7 +210,7 @@ export async function claudeTurn(
210
210
  const { flags, ungranted } = launchFlags(turn.config, options.claudeArgs)
211
211
  if (ungranted.length > 0)
212
212
  options.say(
213
- `The site asked for ${ungranted.join(', ')}, which this bridge was not given. Run it with \`-- --tools ${ungranted.join(',')}\` to allow it.`,
213
+ `The site asked for ${ungranted.join(', ')}, which this bridge wasn’t given. Add \`-- --tools ${ungranted.join(',')}\` to allow it.`,
214
214
  )
215
215
  const directory = await mkdtemp(`${tmpdir()}/abide-bridge-`)
216
216
  const config = `${directory}/mcp.json`
package/src/opened.ts CHANGED
@@ -11,27 +11,48 @@
11
11
  import { type Pairing, pairingOf } from './pairingLink.ts'
12
12
  import { readLines } from './readLines.ts'
13
13
 
14
- /** What install found, kept beside this file: `bun`, `claude`, and the `PATH` it was run on. */
15
- export type HandlerSettings = { bun: string; claude: string; path: string }
14
+ /**
15
+ * What install found, kept beside this file: `bun`, `claude`, and the `PATH` it was run on — and what
16
+ * the visitor gave it for every link (44.44): the Claude Code options after its `--` and each `--env`.
17
+ */
18
+ export type HandlerSettings = {
19
+ bun: string
20
+ claude: string
21
+ path: string
22
+ claudeArgs: string[]
23
+ env: Record<string, string>
24
+ }
16
25
 
17
26
  /**
18
27
  * What the visitor is asked before `pairing` runs. EVERY LINK IS ASKED (44.42): a code proves only
19
28
  * that the site minted it, never that this visitor's browser asked for it, so an answer kept for a
20
29
  * site would pair any page's link to whoever minted its code.
21
30
  */
22
- export function question(pairing: Pairing): string {
31
+ export function question(pairing: Pairing, settings: HandlerSettings): string {
23
32
  const tools =
24
33
  pairing.tools.length === 0
25
34
  ? 'It gets none of this Mac’s tools.'
26
35
  : `It also asks for these tools of this Mac’s: ${pairing.tools.join(', ')}.`
27
- return `${pairing.site} wants to use your Claude Code as its assistant, with its own tools, on your Claude account.\n\n${tools}\n\nIt runs @abide/bridge ${pairing.version}. Allow it only if you just asked to pair on that site.`
36
+ // A variable's value is only named, never shown: it is as likely a token as a host.
37
+ const names = Object.keys(settings.env)
38
+ const kept =
39
+ settings.claudeArgs.length === 0 && names.length === 0
40
+ ? ''
41
+ : `\n\nIt also gets what you gave install for every site: ${[...settings.claudeArgs, ...names].join(' ')}.`
42
+ return `${pairing.site} wants to use your Claude Code as its assistant, with its own tools, on your Claude account.\n\n${tools}${kept}\n\nIt runs @abide/bridge ${pairing.version}. Allow it only if you just asked to pair on that site.`
28
43
  }
29
44
 
30
- /** The bridge the link names, run as the command a site shows would run it. 44.32. */
45
+ /**
46
+ * The bridge the link names, run as the command a site shows would run it (44.32), with the options
47
+ * install kept ahead of the link's tools (44.44).
48
+ */
31
49
  export function bridgeArguments(
32
50
  pairing: Pairing,
33
51
  settings: HandlerSettings,
34
52
  ): string[] {
53
+ const claudeArgs = [...settings.claudeArgs]
54
+ if (pairing.tools.length > 0)
55
+ claudeArgs.push('--tools', pairing.tools.join(','))
35
56
  return [
36
57
  settings.bun,
37
58
  'x',
@@ -40,9 +61,7 @@ export function bridgeArguments(
40
61
  pairing.code,
41
62
  '--claude',
42
63
  settings.claude,
43
- ...(pairing.tools.length === 0
44
- ? []
45
- : ['--', '--tools', pairing.tools.join(',')]),
64
+ ...(claudeArgs.length === 0 ? [] : ['--', ...claudeArgs]),
46
65
  ]
47
66
  }
48
67
 
@@ -76,13 +95,16 @@ async function appleScript(
76
95
  }
77
96
 
78
97
  /** Asks the visitor about `pairing` in a dialog; closing it is a no. */
79
- async function allowed(pairing: Pairing): Promise<boolean> {
98
+ async function allowed(
99
+ pairing: Pairing,
100
+ settings: HandlerSettings,
101
+ ): Promise<boolean> {
80
102
  const pressed = await appleScript(
81
103
  [
82
104
  'display dialog (item 1 of argv) with title "abide bridge" buttons {"Don’t Allow", "Allow"} default button "Don’t Allow" cancel button "Don’t Allow" with icon caution',
83
105
  'button returned of result',
84
106
  ],
85
- question(pairing),
107
+ question(pairing, settings),
86
108
  )
87
109
  return pressed === 'Allow'
88
110
  }
@@ -127,18 +149,19 @@ async function open(link: string): Promise<number> {
127
149
  }
128
150
  const pairing = pairingOf(link)
129
151
  if (pairing === undefined) {
130
- say('That link is not a pairing this bridge opens.')
152
+ say('That link isn’t one this bridge can pair with.')
131
153
  await notifications.settled()
132
154
  return 1
133
155
  }
134
156
  const settings = (await Bun.file(
135
157
  `${import.meta.dir}/settings.json`,
136
158
  ).json()) as HandlerSettings
137
- if (!(await allowed(pairing))) return 0
159
+ if (!(await allowed(pairing, settings))) return 0
138
160
  const running = Bun.spawn(bridgeArguments(pairing, settings), {
139
161
  stdout: 'ignore',
140
162
  stderr: 'pipe',
141
- env: { ...Bun.env, PATH: searchPath(settings) },
163
+ // The visitor's own `--env` last, so a `PATH` they gave install wins over the one it found.
164
+ env: { ...Bun.env, PATH: searchPath(settings), ...settings.env },
142
165
  })
143
166
  for await (const line of readLines(
144
167
  running.stderr as ReadableStream<Uint8Array>,