@pairdraw/mcp 0.0.0-stage → 0.16.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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/dist/connect.d.mts +1 -0
  4. package/dist/connect.mjs +192 -0
  5. package/dist/connect.mjs.map +1 -0
  6. package/dist/discovery-CB2Bv5WA.mjs +167 -0
  7. package/dist/discovery-CB2Bv5WA.mjs.map +1 -0
  8. package/dist/discovery.d.mts +59 -0
  9. package/dist/discovery.mjs +2 -0
  10. package/dist/index.d.mts +1 -0
  11. package/dist/index.mjs +95 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/metadata-DVz00c8R.d.mts +26 -0
  14. package/dist/paths-BpcXnrbP.mjs +168 -0
  15. package/dist/paths-BpcXnrbP.mjs.map +1 -0
  16. package/dist/policy-B8Ka4WRH.mjs +206 -0
  17. package/dist/policy-B8Ka4WRH.mjs.map +1 -0
  18. package/dist/rolldown-runtime-ClRpJifh.mjs +3 -0
  19. package/dist/root-BzmoiT2g.mjs +9 -0
  20. package/dist/root-BzmoiT2g.mjs.map +1 -0
  21. package/dist/scope-D2LTTsDw.mjs +66 -0
  22. package/dist/scope-D2LTTsDw.mjs.map +1 -0
  23. package/dist/scope-DJ9hsBYV.d.mts +31 -0
  24. package/dist/server--T-KD99G.mjs +3261 -0
  25. package/dist/server--T-KD99G.mjs.map +1 -0
  26. package/dist/server.d.mts +265 -0
  27. package/dist/server.mjs +2 -0
  28. package/dist/stdio.d.mts +1 -0
  29. package/dist/stdio.mjs +411 -0
  30. package/dist/stdio.mjs.map +1 -0
  31. package/dist/tools.d.mts +17 -0
  32. package/dist/tools.mjs +33 -0
  33. package/dist/tools.mjs.map +1 -0
  34. package/dist/transport.d.mts +59 -0
  35. package/dist/transport.mjs +2 -0
  36. package/package.json +64 -4
  37. package/src/agents/acp.ts +110 -0
  38. package/src/agents/claude-cloud.ts +99 -0
  39. package/src/agents/filter.ts +85 -0
  40. package/src/agents/index.ts +299 -0
  41. package/src/agents/install.ts +44 -0
  42. package/src/agents/link.ts +79 -0
  43. package/src/agents/lookup.ts +136 -0
  44. package/src/agents/pairing.ts +182 -0
  45. package/src/agents/path.ts +85 -0
  46. package/src/agents/process.ts +88 -0
  47. package/src/agents/registry.ts +36 -0
  48. package/src/agents/schema.ts +77 -0
  49. package/src/agents/sign-in.ts +106 -0
  50. package/src/agents/socket.ts +79 -0
  51. package/src/auth.ts +21 -0
  52. package/src/browser-rpc.ts +440 -0
  53. package/src/connect.ts +170 -0
  54. package/src/global.d.ts +5 -0
  55. package/src/http-options.ts +14 -0
  56. package/src/index.ts +179 -0
  57. package/src/json.ts +1 -0
  58. package/src/result.ts +37 -0
  59. package/src/root.ts +5 -0
  60. package/src/rpc-types.ts +5 -0
  61. package/src/server/connections.ts +58 -0
  62. package/src/server/files.ts +49 -0
  63. package/src/server/install-command.ts +24 -0
  64. package/src/server/lifecycle.ts +389 -0
  65. package/src/server/origin.ts +53 -0
  66. package/src/server/pending-requests.ts +62 -0
  67. package/src/server/sessions.ts +335 -0
  68. package/src/server.ts +597 -0
  69. package/src/skill/content.ts +40 -0
  70. package/src/skill/instructions.ts +69 -0
  71. package/src/skill/register.ts +77 -0
  72. package/src/stdio/bridge.ts +460 -0
  73. package/src/stdio.ts +130 -0
  74. package/src/tool/browser.ts +183 -0
  75. package/src/tool/index.ts +12 -0
  76. package/src/tool/manifest.ts +221 -0
  77. package/src/tool/metadata.ts +44 -0
  78. package/src/tool/output.ts +336 -0
  79. package/src/tool/policy.ts +37 -0
  80. package/src/tool/registration.ts +523 -0
  81. package/src/tool/scope.ts +71 -0
  82. package/src/transport/discovery.ts +235 -0
  83. package/src/transport/origins.ts +85 -0
  84. package/src/transport/paths.ts +179 -0
@@ -0,0 +1,299 @@
1
+ import type { ChildProcess } from 'node:child_process'
2
+ import type { IncomingMessage } from 'node:http'
3
+ import type { Duplex } from 'node:stream'
4
+
5
+ import type { Hono, MiddlewareHandler } from 'hono'
6
+ import { bodyLimit } from 'hono/body-limit'
7
+ import * as v from 'valibot'
8
+ import { WebSocketServer, type WebSocket } from 'ws'
9
+
10
+ import { bearerToken } from '#mcp/auth'
11
+ import { getAgentWorkspacePath } from '#mcp/transport/paths'
12
+
13
+ import { pipeAgent, type AgentProcessContext } from './acp'
14
+ import { createACPFilter, isLoopbackMCP } from './filter'
15
+ import { installWithNpm, type PackageInstaller } from './install'
16
+ import { ensureWorkspace, lookupAgents } from './lookup'
17
+ import { createPairing, type PairingOptions, type TrustedSession } from './pairing'
18
+ import { augmentPath } from './path'
19
+ import { terminate } from './process'
20
+ import { COMPANION_AGENTS, findCompanionAgent, type CompanionAgent } from './registry'
21
+ import { devAgentSessionEnvSchema, pairRequestSchema } from './schema'
22
+ import { runSignIn } from './sign-in'
23
+ import { authenticate, CLOSE_CODES, keepAlive } from './socket'
24
+
25
+ /** Frames an agent's ACP stream may carry; prompts can hold images. */
26
+ const ACP_MAX_FRAME_BYTES = 16 * 1024 * 1024
27
+ const CONTROL_MAX_FRAME_BYTES = 64 * 1024
28
+ const MAX_REQUEST_BYTES = 1024
29
+ /** Agents and sign-ins running at once, across every paired tab. */
30
+ const MAX_AGENT_PROCESSES = 8
31
+ /** Sockets that may wait for their first message at once, so unpaired clients cannot pile up. */
32
+ const MAX_UNAUTHENTICATED_SOCKETS = 16
33
+
34
+ export interface AgentBridgeOptions {
35
+ /** Where agents start, created on first use; defaults to a folder beside the discovery file. */
36
+ workspace?: string
37
+ /** The agents the bridge may start. Defaults to `ACP_AGENTS`; tests pass stand-ins. */
38
+ registry?: readonly CompanionAgent[]
39
+ /** The PATH agents are found on and started with; defaults to an augmented `PATH`. */
40
+ searchPath?: string
41
+ /** Installs adapter packages; defaults to `npm install --global`. */
42
+ installer?: PackageInstaller
43
+ /** Code and session lifetimes; trusted sessions come from `trustedSessions`. */
44
+ pairing?: Omit<PairingOptions, 'trusted'>
45
+ /**
46
+ * Sessions that need no `/pair`, for the tab of the process that started the server
47
+ * (`devAgentBridgeFromEnv`). They never expire and cannot be revoked.
48
+ */
49
+ trustedSessions?: readonly TrustedSession[]
50
+ /** The TCP port the server listens on, which is where the companion's own MCP endpoint is. */
51
+ port?: () => number
52
+ /** Told each time a tab pairs, so the companion can say so in its terminal. */
53
+ onPaired?: () => void
54
+ }
55
+
56
+ const AGENT_SOCKET_PATH = /^\/agents\/([\w-]{1,64})\/(acp|sign-in)$/
57
+
58
+ /**
59
+ * The bridge `bun run dev` asks the MCP server it starts for: `PAIRDRAW_MCP_AGENTS=1`, with its
60
+ * tab's session in `PAIRDRAW_MCP_AGENT_SESSION` and `PAIRDRAW_MCP_AGENT_TOKEN`. Null without
61
+ * them or when they are malformed, and the server then has no bridge. The tokens stay in this
62
+ * process: the discovery file never holds them.
63
+ */
64
+ export function devAgentBridgeFromEnv(
65
+ env: NodeJS.ProcessEnv = process.env
66
+ ): AgentBridgeOptions | null {
67
+ if (env.PAIRDRAW_MCP_AGENTS !== '1') return null
68
+ const session = v.safeParse(devAgentSessionEnvSchema, env)
69
+ return session.success ? { trustedSessions: [session.output] } : null
70
+ }
71
+
72
+ function rejectUpgrade(socket: Duplex, status: number, reason: string): void {
73
+ socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
74
+ }
75
+
76
+ /**
77
+ * The companion's agent bridge: pairing, finding and installing agents, and starting them for a
78
+ * paired tab. Every route and socket here needs a session token from `/pair`; the MCP server's
79
+ * own token, which local MCP clients read from the discovery file, does not start programs.
80
+ */
81
+ export function createAgentBridge(
82
+ options: AgentBridgeOptions & { version: string; entry: string }
83
+ ) {
84
+ const registry = options.registry ?? COMPANION_AGENTS
85
+ const searchPath = options.searchPath ?? augmentPath(process.env.PATH ?? '')
86
+ const installer = options.installer ?? installWithNpm
87
+ const pairing = createPairing({ ...options.pairing, trusted: options.trustedSessions })
88
+ const children = new Set<ChildProcess>()
89
+ const signIns = new Map<string, WebSocket>()
90
+ const acpSockets = new WebSocketServer({ noServer: true, maxPayload: ACP_MAX_FRAME_BYTES })
91
+ const controlSockets = new WebSocketServer({
92
+ noServer: true,
93
+ maxPayload: CONTROL_MAX_FRAME_BYTES
94
+ })
95
+ let installing = false
96
+ let closed = false
97
+ let reserved = 0
98
+ let unauthenticated = 0
99
+ let workspacePath: Promise<string> | null = null
100
+
101
+ function track(child: ChildProcess) {
102
+ children.add(child)
103
+ child.once('exit', () => children.delete(child))
104
+ child.once('error', () => children.delete(child))
105
+ }
106
+
107
+ /**
108
+ * Holds a place for a process before anything is awaited, so sockets authenticating at once
109
+ * cannot all pass the limit. The place is released once the process is tracked, or not started.
110
+ */
111
+ function reserve(): (() => void) | null {
112
+ if (children.size + reserved >= MAX_AGENT_PROCESSES) return null
113
+ reserved++
114
+ let released = false
115
+ return () => {
116
+ if (released) return
117
+ released = true
118
+ reserved--
119
+ }
120
+ }
121
+
122
+ function workspace(): Promise<string> {
123
+ workspacePath ??= (async () =>
124
+ ensureWorkspace(options.workspace ?? (await getAgentWorkspacePath())))()
125
+ // A failed attempt, such as a folder that could not be created, is tried again next time.
126
+ workspacePath.catch(() => {
127
+ workspacePath = null
128
+ })
129
+ return workspacePath
130
+ }
131
+
132
+ async function processContext(): Promise<AgentProcessContext> {
133
+ return { workspace: await workspace(), searchPath, track }
134
+ }
135
+
136
+ function routes(app: Hono) {
137
+ const limit = bodyLimit({
138
+ maxSize: MAX_REQUEST_BYTES,
139
+ onError: (c) => c.json({ error: 'Request is too large' }, 413)
140
+ })
141
+
142
+ app.post('/pair', limit, async (c) => {
143
+ const body = v.safeParse(
144
+ v.pipe(v.string(), v.parseJson(), pairRequestSchema),
145
+ await c.req.text()
146
+ )
147
+ if (!body.success) return c.json({ error: 'Invalid request body' }, 400)
148
+ const result = pairing.exchange(body.output.code)
149
+ if (result.ok) {
150
+ options.onPaired?.()
151
+ return c.json({
152
+ token: result.token,
153
+ agentToken: result.agentToken,
154
+ version: options.version
155
+ })
156
+ }
157
+ if (result.reason === 'rate-limited') {
158
+ return c.json(
159
+ { error: 'Too many attempts' },
160
+ { status: 429, headers: { 'Retry-After': '60' } }
161
+ )
162
+ }
163
+ return c.json({ error: 'The link expired or was already used' }, 401)
164
+ })
165
+
166
+ const requireSession: MiddlewareHandler = async (c, next) => {
167
+ if (!pairing.isSession(bearerToken(c.req.header('authorization')))) {
168
+ return c.json({ error: 'Unauthorized' }, 401)
169
+ }
170
+ return next()
171
+ }
172
+ app.use('/companion', requireSession)
173
+ app.use('/agents', requireSession)
174
+ app.use('/agents/*', requireSession)
175
+ app.use('/pair/revoke', requireSession)
176
+
177
+ // The tab signs out, as when the person disconnects it; its tokens stop working at once.
178
+ app.post('/pair/revoke', limit, (c) => {
179
+ const token = bearerToken(c.req.header('authorization'))
180
+ if (token) pairing.revoke(token)
181
+ return c.body(null, 204)
182
+ })
183
+
184
+ app.get('/companion', async (c) =>
185
+ c.json({ version: options.version, workspace: await workspace() })
186
+ )
187
+
188
+ app.get('/agents', async (c) =>
189
+ c.json(
190
+ await lookupAgents(registry, { searchPath, version: options.version, entry: options.entry })
191
+ )
192
+ )
193
+
194
+ app.post('/agents/:id/install', limit, async (c) => {
195
+ const agent = findCompanionAgent(registry, c.req.param('id'))
196
+ if (!agent) return c.json({ error: 'Unknown agent' }, 404)
197
+ if (!agent.adapterPackage)
198
+ return c.json({ error: 'This agent has no adapter to install' }, 400)
199
+ if (installing) return c.json({ error: 'Another installation is running' }, 409)
200
+ installing = true
201
+ try {
202
+ await installer(agent.adapterPackage, searchPath, await workspace())
203
+ return c.json({ ok: true })
204
+ } catch {
205
+ return c.json({ error: 'The installation failed' }, 500)
206
+ } finally {
207
+ installing = false
208
+ }
209
+ })
210
+ }
211
+
212
+ async function serveSocket(ws: WebSocket, agent: CompanionAgent, kind: 'acp' | 'sign-in') {
213
+ keepAlive(ws)
214
+ unauthenticated++
215
+ let authenticated: boolean
216
+ try {
217
+ authenticated = await authenticate(ws, pairing.isSession)
218
+ } finally {
219
+ unauthenticated--
220
+ }
221
+ if (!authenticated) return
222
+ if (closed) {
223
+ ws.close(1001, 'Companion is shutting down')
224
+ return
225
+ }
226
+ if (kind === 'sign-in' && signIns.has(agent.id)) {
227
+ ws.close(CLOSE_CODES.conflict, 'A sign-in is already running')
228
+ return
229
+ }
230
+ const release = reserve()
231
+ if (!release) {
232
+ ws.close(CLOSE_CODES.busy, 'Too many agents are running')
233
+ return
234
+ }
235
+ try {
236
+ if (kind === 'sign-in') {
237
+ signIns.set(agent.id, ws)
238
+ ws.once('close', () => signIns.delete(agent.id))
239
+ runSignIn(ws, agent, await processContext())
240
+ return
241
+ }
242
+ const context = await processContext()
243
+ const filter = createACPFilter({
244
+ workspace: context.workspace,
245
+ isOwnMCP: (url) => isLoopbackMCP(url, options.port?.() ?? 0)
246
+ })
247
+ pipeAgent(ws, agent, { ...context, filter })
248
+ } finally {
249
+ // The process, if it started, is tracked by now; otherwise its place is free again.
250
+ release()
251
+ }
252
+ }
253
+
254
+ /** Takes upgrades under `/agents/`; returns false for other paths. The caller checked Origin. */
255
+ function handleUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer): boolean {
256
+ const pathname = new URL(request.url ?? '/', 'http://localhost').pathname
257
+ if (!pathname.startsWith('/agents/')) return false
258
+ const match = AGENT_SOCKET_PATH.exec(pathname)
259
+ const agent = match ? findCompanionAgent(registry, match[1]) : undefined
260
+ if (!match || !agent || closed) {
261
+ rejectUpgrade(socket, 404, 'Not Found')
262
+ return true
263
+ }
264
+ if (unauthenticated >= MAX_UNAUTHENTICATED_SOCKETS) {
265
+ rejectUpgrade(socket, 503, 'Service Unavailable')
266
+ return true
267
+ }
268
+ const kind = match[2] === 'acp' ? 'acp' : 'sign-in'
269
+ const server = kind === 'acp' ? acpSockets : controlSockets
270
+ server.handleUpgrade(request, socket, head, (ws) => {
271
+ void serveSocket(ws, agent, kind).catch(() => {
272
+ if (ws.readyState === ws.OPEN) ws.close(CLOSE_CODES.failed, 'Agent bridge failed')
273
+ })
274
+ })
275
+ return true
276
+ }
277
+
278
+ /** Stops every agent and sign-in and closes their sockets. */
279
+ async function close(): Promise<void> {
280
+ closed = true
281
+ for (const server of [acpSockets, controlSockets]) {
282
+ for (const ws of server.clients) ws.terminate()
283
+ server.close()
284
+ }
285
+ await Promise.all([...children].map((child) => terminate(child)))
286
+ children.clear()
287
+ }
288
+
289
+ return {
290
+ routes,
291
+ handleUpgrade,
292
+ close,
293
+ issuePairingCode: pairing.issueCode,
294
+ isSession: pairing.isSession,
295
+ isAgentToken: pairing.isAgentToken
296
+ }
297
+ }
298
+
299
+ export type AgentBridge = ReturnType<typeof createAgentBridge>
@@ -0,0 +1,44 @@
1
+ import { spawnFixed, terminate } from './process'
2
+
3
+ const INSTALL_TIMEOUT_MS = 120_000
4
+
5
+ // These are public packages; a person's private project registry may not mirror them.
6
+ const PUBLIC_REGISTRY = '--registry=https://registry.npmjs.org'
7
+
8
+ /** The npm arguments that install a package globally, the same the desktop shell scope pins. */
9
+ function npmInstallArgs(packageName: string): string[] {
10
+ return ['install', '--global', packageName, PUBLIC_REGISTRY]
11
+ }
12
+
13
+ /**
14
+ * Installs an agent's adapter package globally with npm; rejects when npm did not finish. It
15
+ * runs in the companion's workspace, so an `.npmrc` in the folder the companion started in
16
+ * cannot point npm elsewhere.
17
+ */
18
+ export type PackageInstaller = (
19
+ packageName: string,
20
+ searchPath: string,
21
+ cwd: string
22
+ ) => Promise<void>
23
+
24
+ export const installWithNpm: PackageInstaller = (packageName, searchPath, cwd) =>
25
+ new Promise((resolve, reject) => {
26
+ const child = spawnFixed('npm', npmInstallArgs(packageName), {
27
+ searchPath,
28
+ cwd,
29
+ stdio: ['ignore', 'ignore', 'ignore']
30
+ })
31
+ const timer = setTimeout(() => {
32
+ void terminate(child)
33
+ reject(new Error('The installation timed out.'))
34
+ }, INSTALL_TIMEOUT_MS)
35
+ child.once('error', () => {
36
+ clearTimeout(timer)
37
+ reject(new Error('The installation could not start.'))
38
+ })
39
+ child.once('close', (code) => {
40
+ clearTimeout(timer)
41
+ if (code === 0) resolve()
42
+ else reject(new Error('The installation failed.'))
43
+ })
44
+ })
@@ -0,0 +1,79 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { rm, writeFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+
5
+ import { uniq } from 'es-toolkit'
6
+
7
+ import { DEFAULT_CONNECT_APP_URL, resolveCORSOrigins } from '#mcp/transport/origins'
8
+
9
+ /** Hosts a development server may run the app on with plain HTTP. */
10
+ function isLocalHost(hostname: string): boolean {
11
+ return (
12
+ hostname === 'localhost' ||
13
+ hostname.endsWith('.localhost') ||
14
+ hostname === '127.0.0.1' ||
15
+ hostname === '[::1]'
16
+ )
17
+ }
18
+
19
+ /**
20
+ * The web app the companion pairs with: the editor on this computer, or one the operator names,
21
+ * such as a Cloud server's. Plain HTTP is accepted only on this machine. Returns null for anything
22
+ * else.
23
+ */
24
+ export function resolveConnectAppURL(raw: string | undefined): URL | null {
25
+ const text = raw?.trim() || DEFAULT_CONNECT_APP_URL
26
+ let url: URL
27
+ try {
28
+ url = new URL(text)
29
+ } catch {
30
+ return null
31
+ }
32
+ if (url.username || url.password) return null
33
+ if (url.protocol === 'https:') return url
34
+ return url.protocol === 'http:' && isLocalHost(url.hostname) ? url : null
35
+ }
36
+
37
+ /**
38
+ * The link that pairs a tab: the app with `#connect=<code>` in its fragment, which browsers never
39
+ * send to a server, and the port when it is not the default one.
40
+ */
41
+ export function connectLink(appURL: URL, code: string, port: number, defaultPort: number): string {
42
+ const link = new URL(appURL)
43
+ const params = new URLSearchParams({ connect: code })
44
+ if (port !== defaultPort) params.set('port', String(port))
45
+ link.hash = params.toString()
46
+ return link.toString()
47
+ }
48
+
49
+ /**
50
+ * The origins the companion lets call it: the configured ones and the app it pairs with. `*`
51
+ * would let any site drive the agent bridge, so it is dropped here, whatever was configured.
52
+ */
53
+ export function connectCORSOrigins(raw: string | undefined, appURL: URL): string[] {
54
+ const configured = resolveCORSOrigins(raw).filter((origin) => origin !== '*')
55
+ return uniq([...configured, appURL.origin])
56
+ }
57
+
58
+ function escapeAttribute(value: string): string {
59
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
60
+ }
61
+
62
+ /**
63
+ * Writes a page that forwards to the link, readable only by this user, so the browser is opened
64
+ * with the page's path rather than the link: a command line, which other users of the computer
65
+ * can list, then never holds the pairing code. Returns the path and a function that deletes it.
66
+ */
67
+ export async function writeConnectPage(
68
+ dir: string,
69
+ link: string
70
+ ): Promise<{ path: string; remove: () => Promise<void> }> {
71
+ const path = join(dir, `connect-${randomBytes(8).toString('hex')}.html`)
72
+ const href = escapeAttribute(link)
73
+ const html =
74
+ `<!doctype html><meta charset="utf-8"><meta name="referrer" content="no-referrer">` +
75
+ `<meta http-equiv="refresh" content="0;url=${href}"><title>Pairdraw</title>` +
76
+ `<a href="${href}">Open Pairdraw</a>\n`
77
+ await writeFile(path, html, { mode: 0o600, flag: 'wx' })
78
+ return { path, remove: () => rm(path, { force: true }) }
79
+ }
@@ -0,0 +1,136 @@
1
+ import { access, constants, mkdir, rm, stat, writeFile } from 'node:fs/promises'
2
+ import { platform } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+
5
+ import { claudeCodeCloud, type ClaudeCodeCloud } from './claude-cloud'
6
+ import { which } from './path'
7
+ import { spawnFixed, terminate } from './process'
8
+ import type { CompanionAgent } from './registry'
9
+
10
+ /** The program the app knows Pairdraw's MCP server by; the companion is that server. */
11
+ const MCP_EXECUTABLE = 'pairdraw-mcp-http'
12
+ const MCP_PACKAGE = '@pairdraw/mcp'
13
+ const HARNESS_PACKAGE = '@pairdraw/harness'
14
+ const PACKAGE_MANAGERS = ['npm', 'bun'] as const
15
+
16
+ /** What the app's setup reads, in the shape the desktop shell's `agent_lookup` reports. */
17
+ export interface CompanionLookup {
18
+ executables: Record<string, string | null>
19
+ versions: Record<string, string | null>
20
+ npmGlobalWritable: boolean | null
21
+ searchPath: string
22
+ /** The cloud Claude Code is set up to use instead of an Anthropic sign-in. */
23
+ claudeCodeCloud: ClaudeCodeCloud | null
24
+ }
25
+
26
+ const OUTPUT_TIMEOUT_MS = 5_000
27
+ const MAX_OUTPUT_BYTES = 16_384
28
+
29
+ /** Runs a found program and returns what it printed, or null when it fails or outlives the timeout. */
30
+ async function outputOf(
31
+ command: string,
32
+ args: string[],
33
+ searchPath: string
34
+ ): Promise<string | null> {
35
+ let child
36
+ try {
37
+ child = spawnFixed(command, args, { searchPath, stdio: ['ignore', 'pipe', 'ignore'] })
38
+ } catch {
39
+ return null
40
+ }
41
+ const running = child
42
+ return new Promise((resolve) => {
43
+ let output = ''
44
+ const timer = setTimeout(() => {
45
+ void terminate(running)
46
+ resolve(null)
47
+ }, OUTPUT_TIMEOUT_MS)
48
+ running.stdout?.on('data', (chunk: Buffer) => {
49
+ if (output.length < MAX_OUTPUT_BYTES) output += chunk.toString('utf8')
50
+ })
51
+ running.once('error', () => {
52
+ clearTimeout(timer)
53
+ resolve(null)
54
+ })
55
+ running.once('close', (code) => {
56
+ clearTimeout(timer)
57
+ resolve(code === 0 ? output : null)
58
+ })
59
+ })
60
+ }
61
+
62
+ /** The folder `npm install --global` writes packages into, below the prefix npm reports. */
63
+ function npmGlobalPackages(prefix: string, runtimePlatform = platform()): string {
64
+ return runtimePlatform === 'win32'
65
+ ? join(prefix, 'node_modules')
66
+ : join(prefix, 'lib', 'node_modules')
67
+ }
68
+
69
+ async function nearestExisting(path: string): Promise<string | null> {
70
+ let current = path
71
+ for (;;) {
72
+ const found = await stat(current).then(
73
+ (info) => info.isDirectory(),
74
+ () => false
75
+ )
76
+ if (found) return current
77
+ const parent = dirname(current)
78
+ if (parent === current) return null
79
+ current = parent
80
+ }
81
+ }
82
+
83
+ /** Whether this process can create files in `dir`, checked by creating and removing one. */
84
+ async function canWrite(dir: string): Promise<boolean> {
85
+ const probe = join(dir, `.pairdraw-write-check-${process.pid}`)
86
+ try {
87
+ await writeFile(probe, '', { flag: 'wx' })
88
+ await rm(probe, { force: true })
89
+ return true
90
+ } catch {
91
+ return false
92
+ }
93
+ }
94
+
95
+ async function npmGlobalWritable(searchPath: string): Promise<boolean | null> {
96
+ const output = await outputOf('npm', ['prefix', '--global'], searchPath)
97
+ const prefix = output?.split('\n')[0]?.trim()
98
+ if (!prefix) return null
99
+ const dir = await nearestExisting(npmGlobalPackages(prefix))
100
+ return dir ? canWrite(dir) : null
101
+ }
102
+
103
+ /**
104
+ * Looks up the agents in `registry`, the package managers, and Pairdraw's companions, as the
105
+ * desktop shell's `agent_lookup` does. It never starts an agent: only `npm prefix` runs, and of
106
+ * Claude Code's settings only the switches that pick a cloud are read. The MCP server is this
107
+ * program itself, so it reports its own entry and version.
108
+ */
109
+ export async function lookupAgents(
110
+ registry: readonly CompanionAgent[],
111
+ options: { searchPath: string; version: string; entry: string }
112
+ ): Promise<CompanionLookup> {
113
+ const { searchPath } = options
114
+ const names = new Set<string>(PACKAGE_MANAGERS)
115
+ for (const agent of registry) {
116
+ names.add(agent.command)
117
+ if (agent.cliCommand) names.add(agent.cliCommand)
118
+ }
119
+ const executables: Record<string, string | null> = {}
120
+ for (const name of names) executables[name] = which(name, searchPath)
121
+ executables[MCP_EXECUTABLE] = options.entry
122
+ return {
123
+ executables,
124
+ versions: { [MCP_PACKAGE]: options.version, [HARNESS_PACKAGE]: null },
125
+ npmGlobalWritable: executables.npm ? await npmGlobalWritable(searchPath) : null,
126
+ searchPath,
127
+ claudeCodeCloud: await claudeCodeCloud()
128
+ }
129
+ }
130
+
131
+ /** The folder agents start in, outside the person's projects, created on first use. */
132
+ export async function ensureWorkspace(path: string): Promise<string> {
133
+ await mkdir(path, { recursive: true, mode: 0o700 })
134
+ await access(path, constants.W_OK)
135
+ return path
136
+ }