Connect Claude Code sessions in your AgentKib workspaces to AgentKib on this Mac.

First-party local Mods plugin for Claude Code 2.1.301 or later, using AgentKib bridge contract 0.3.0. It connects AgentKib's existing chat interface to the terminal's original execution process. It never starts a replacement Claude process, resumes another UUID, calls a model itself, or changes the user's permission rules.
Use AgentKib's connection panel for the selected session. Register the bundled agentkib-local marketplace and install agentkib-bridge@agentkib-local using the commands displayed there. In an existing terminal, run /reload-plugins to load the plugin, then execute the one-time /agentkib-connect … command generated by AgentKib. For isolated development only, claude --plugin-dir <this-directory> loads the plugin for that invocation without installing it.
Once the plugin is installed, sessions in a workspace registered in AgentKib connect without a code. While its broker runs, Backend writes <AgentKib home>/claude-bridge/auto-v1.json with mode 0600, holding the socket path and a key that rotates with every Runtime start. At session start, and after each turn until it succeeds, the plugin reads that file (AGENTKIB_HOME, then ~/.agentkib, then ~/.agentkib-dev) and calls /v1/auto-pair with its own native identity. AgentKib pairs the session only when its working directory belongs to a registered workspace whose automatic connection is on (the default; it can be switched off per workspace in the connection dialog), the session is indexed, and the user has not disconnected it. A disconnect is remembered, so that session connects again only with a new one-time code. A workspace switched off keeps its open terminals retrying, so they connect on their next turn once it is switched back on. A saved binding still reconnects with its own credential. The same version, capability and identity checks apply as for a code; when they fail, /agentkib-status explains why and AgentKib shows the same reason in that session's connection dialog. Updating the plugin and running /reload-plugins starts the session hooks again, so the session connects without a new code.
Only the native session UUID and working directory selected in AgentKib can pair. Each pairing and reconnect checks the minimum stable CLI version and required native capabilities: session identity, messages, usage, credential storage, and plugin-file reads. Older or unrecognized versions and missing required capabilities are rejected. Only 2.1.301 and 2.1.310 are currently listed as verified; higher stable versions that pass these checks may connect read-only. The connection dialog shows a neutral notice that the version has not been verified and synchronized content may be incomplete; the session page does not repeat it. Production sending remains disabled. /agentkib-status is a local command and does not call a model.
$.prompt.submit has no atomic idle/CAS contract and skips this plugin's own hook by re-entry; a competing terminal submission cannot be guaranteed never to queue. The retained correlation implementation is an isolated protocol experiment only. Renderer, Web and plugin configuration cannot enable it.turn.start using $.turn.abort.Snapshots are previews of the latest 80 text rows and 100 tool records, subject to a byte budget. Clipped text has an explicit marker. Complete history continues to use AgentKib's original history provider. Hidden thinking is never forwarded.
Native cancellation and reading are verified separately from experimental send correlation. Approval and question completion remain unavailable in AgentKib. A bounded event buffer retains turn-completion evidence until ACK, including across reconnect; an unknown send is never unlocked merely because the TUI is idle.
The connection uses HTTP over a private local Unix socket. Persistent credentials are written by Backend with mode 0600. The plugin reads that file through the native API; its store keeps only the credential file path. Tokens do not enter commands, URLs, or the chat UI. Native identity changes and session end invalidate the lease; Runtime owns persistent request receipts and unknown outcome recovery.
A saved, unrevoked binding survives terminal exit and AgentKib restart. While offline, the desktop connection dialog shows a neutral waiting state with a quoted resume command, a fallback to generate a new code, and inline-confirmed clearing. Clearing revokes both the saved binding and unused codes; resuming the terminal afterward cannot restore that connection without explicit pairing. Recoverable transport failures are retried using the existing Mods timer and terminal events, with identity, version, capabilities and credentials checked again. Retry never replays a send or creates a replacement terminal process. An expired or invalid fallback pairing code does not revoke an existing valid binding or permanently cancel its recovery, including after overlapping failed pairing attempts. No additional background recovery starts while pairing is pending; stale handshake responses cannot affect the current generation. Explicit revocation, identity changes and session end still prevent that binding from reconnecting.
The Claude terminal compatibility workflow checks the minimum and latest CLI daily at 04:17 UTC, on related pull requests, or when manually triggered. Scheduled runs use the default branch and start after the workflow is merged there; local or PR validation does not prove the daily trigger has run. Failures report only known capability names. Checks do not sign in, call a model, change the verified version list, or publish a release.
claude plugin validate ./packages/claude-bridge-plugin --strict
claude plugin test ./packages/claude-bridge-plugin
pnpm --filter @agentkib/desktop exec vitest run test/claude-bridge-plugin.test.ts
The official plugin tests need no sign-in, network or model. An optional macOS integration test starts the installed TUI in an isolated config directory and uses a synthetic localhost provider with no real credentials:
AGENTKIB_CLAUDE_BRIDGE_NATIVE=1 \
pnpm --filter @agentkib/desktop exec vitest run test/claude-bridge-native.test.ts
Set AGENTKIB_CLAUDE_EXECUTABLE when the installed binary is elsewhere, and AGENTKIB_NATIVE_BRIDGE_EVIDENCE_DIR to retain redacted terminal output and the binary/type identity. For the separate send-correlation experiment only, set AGENTKIB_CLAUDE_BRIDGE_SEND_EXPERIMENT=1 on this test command: the test changes one literal in its temporary plugin copy, never the shipped plugin. Passing that experiment does not open production send capability. This verifies transport and native execution contracts; it does not substitute for real provider or physical phone acceptance.
Official references: Mods, API and events, native test kit.
hooks/register.js 1636 lines1// Host calls stay explicit for Claude Code's static plugin validation.
2import {
3 CLAUDE_BRIDGE_COMPATIBILITY,
4 CLAUDE_BRIDGE_REQUIRED_CAPABILITIES,
5 claudeBridgeCompatibility,
6} from "./compatibility.js";
7
8const CLI_VERSION = CLAUDE_BRIDGE_COMPATIBILITY.minimumCliVersion;
9const PLUGIN_VERSION = CLAUDE_BRIDGE_COMPATIBILITY.pluginVersion;
10// Native prompt.submit has no atomic idle/CAS option. Production sending stays
11// closed; only an isolated test COPY replaces this literal to study the contract.
12const SEND_CONTRACT_EXPERIMENT = false;
13const MAX_STREAM = 96 * 1024;
14const MAX_EVENTS = 256;
15// The existing 250ms pump skips these ticks before retrying: about 1/2/4/8s.
16const RECONNECT_BACKOFF_TICKS = [3, 7, 15, 31];
17const PREVIEW_MARKER = "\n[AgentKib preview truncated; read the original history for full content]";
18// A new session is pairable only after AgentKib indexes its transcript, so
19// automatic pairing retries after later turns, a bounded number of times.
20const AUTO_RETRY_LIMIT = 20;
21// Versions AgentKib rejects; /agentkib-status explains them.
22const INCOMPATIBLE_ERRORS = [
23 "bridge-cli-too-old",
24 "bridge-cli-unsupported",
25 "bridge-capabilities-missing",
26 "bridge-plugin-update-required",
27];
28// Refusals that a retry cannot change for this session. Other refusals retry
29// after later turns: a workspace switched back on connects, and a version
30// refusal reaches the AgentKib dialog once the new session is indexed.
31const AUTO_FINAL_ERRORS = ["bridge-auto-declined", "unsupported-native-identity"];
32function utf8Prefix(value, budget) {
33 let read = 0;
34 let written = 0;
35 // The pinned Mods runtime only promises TextEncoder.encode, not encodeInto.
36 // Count a bounded prefix directly without allocating an encoder per character.
37 while (read < value.length) {
38 const unit = value.charCodeAt(read);
39 let units = 1;
40 let width = unit < 0x80 ? 1 : unit < 0x800 ? 2 : 3;
41 if (unit >= 0xd800 && unit <= 0xdbff) {
42 const next = value.charCodeAt(read + 1);
43 if (next >= 0xdc00 && next <= 0xdfff) {
44 units = 2;
45 width = 4;
46 }
47 }
48 if (written + width > budget) break;
49 read += units;
50 written += width;
51 }
52 return { read, written };
53}
54
55export function previewText(value, budget = 16 * 1024) {
56 if (typeof value !== "string") return "";
57 // Every UTF-16 code unit costs at most three UTF-8 bytes. Small chunks need
58 // neither an allocation nor an encoding pass just to prove they fit.
59 if (value.length * 3 <= budget || utf8Prefix(value, budget).read === value.length) return value;
60 // The marker is ASCII; the prefix count never splits a surrogate pair.
61 // Slice the original text so even an unpaired surrogate is passed unchanged.
62 const marker = PREVIEW_MARKER.slice(0, Math.max(0, budget));
63 const { read } = utf8Prefix(value, Math.max(0, budget - marker.length));
64 return value.slice(0, read) + marker;
65}
66
67function appendStreamText(state, text) {
68 if (state.streamTruncated) return;
69 const last = state.streamText.charCodeAt(state.streamText.length - 1);
70 const first = text.charCodeAt(0);
71 // Two lone-surrogate encodings cost six bytes; their joined pair costs four.
72 const joined = last >= 0xd800 && last <= 0xdbff && first >= 0xdc00 && first <= 0xdfff;
73 const repair = joined ? 2 : 0;
74 const { read, written } = utf8Prefix(text, MAX_STREAM - state.streamBytes + repair);
75 if (read === text.length) {
76 state.streamText += text;
77 state.streamBytes += written - repair;
78 } else {
79 state.streamText = previewText(state.streamText + text, MAX_STREAM);
80 state.streamTruncated = true;
81 }
82}
83
84export function safeSocket(path) {
85 return (
86 typeof path === "string" &&
87 path.startsWith("/") &&
88 !path.includes("\0") &&
89 !path.split("/").includes("..") &&
90 new TextEncoder().encode(path).length <= 100
91 );
92}
93
94export function decodeTicket(text) {
95 if (typeof text !== "string" || !/^[A-Za-z0-9_-]{1,4096}$/.test(text))
96 throw new Error("invalid-ticket");
97 const bytes = Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) =>
98 c.charCodeAt(0),
99 );
100 const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
101 if (
102 value?.protocol !== 1 ||
103 typeof value.ticket !== "string" ||
104 !/^[A-Za-z0-9_-]{24,256}$/.test(value.ticket) ||
105 !safeSocket(value.socketPath)
106 )
107 throw new Error("invalid-ticket");
108 return { protocol: 1, socketPath: value.socketPath, ticket: value.ticket };
109}
110
111export function validSend(command) {
112 return (
113 typeof command?.text === "string" &&
114 command.text.trim().length > 0 &&
115 !command.text.trimStart().startsWith("/") &&
116 [...command.text].length <= 16_000 &&
117 new TextEncoder().encode(command.text).length <= 16_384 &&
118 typeof command.requestId === "string" &&
119 command.requestId.length > 0 &&
120 command.requestId.length <= 256
121 );
122}
123
124function boundedJson(value) {
125 try {
126 return previewText(JSON.stringify(value ?? {}));
127 } catch {
128 return "[unavailable]";
129 }
130}
131
132export function visibleMessages(rows) {
133 if (!Array.isArray(rows)) throw new Error("invalid-native-history");
134 return rows
135 .filter(
136 (row) => (row?.role === "user" || row?.role === "assistant") && typeof row.text === "string",
137 )
138 .slice(-80)
139 .map((row) => ({ role: row.role, text: previewText(row.text, 8 * 1024) }));
140}
141
142export function visibleTools(rows) {
143 if (!Array.isArray(rows)) throw new Error("invalid-native-history");
144 return rows
145 .flatMap((row) => (Array.isArray(row?.toolUses) ? row.toolUses : []))
146 .filter((tool) => typeof tool?.tool_use_id === "string" && typeof tool.tool === "string")
147 .slice(-100)
148 .map((tool) => ({
149 id: tool.tool_use_id,
150 name: tool.tool,
151 input: boundedJson(tool.input),
152 ...(typeof tool.text === "string" ? { output: previewText(tool.text) } : {}),
153 status: tool.isError
154 ? "failed"
155 : tool.result !== undefined || typeof tool.text === "string"
156 ? "completed"
157 : "running",
158 }));
159}
160
161export function initialState() {
162 return {
163 identity: null,
164 instanceId: crypto.randomUUID(),
165 connection: null,
166 connectionFailure: null,
167 socketPath: null,
168 credentialPath: null,
169 revision: 0,
170 seq: 0,
171 events: [],
172 completions: new Map(),
173 generation: 0,
174 results: new Map(),
175 unacknowledgedResults: new Map(),
176 afterCommandId: null,
177 currentTurnId: null,
178 streamText: "",
179 streamBytes: 0,
180 streamTruncated: false,
181 nativeWorking: null,
182 activeTools: new Map(),
183 waits: new Map(),
184 // A reload can happen mid-turn. Only native activity events establish idle.
185 activityVerified: false,
186 bufferPaused: false,
187 overflowEpoch: 0,
188 snapshotRecovery: null,
189 sendDisabled: false,
190 pendingSend: null,
191 dirty: true,
192 pumping: false,
193 flushing: false,
194 closed: false,
195 needsReconnect: false,
196 pairingRecoveryGeneration: null,
197 reconnectGeneration: null,
198 reconnectFailures: 0,
199 reconnectDelayTicks: 0,
200 lastSnapshot: null,
201 termination: null,
202 terminating: false,
203 autoConnecting: false,
204 autoTries: new Map(),
205 autoDone: new Set(),
206 };
207}
208
209function lease(state) {
210 if (!state.identity || !state.connection) throw new Error("not-connected");
211 return {
212 bindingId: state.connection.bindingId,
213 leaseId: state.connection.leaseId,
214 nativeId: state.identity.nativeId,
215 cwd: state.identity.cwd,
216 instanceId: state.instanceId,
217 };
218}
219
220function compatibilityFailure(reason, cliVersion, missingCapabilities) {
221 const error = new Error(reason);
222 if (claudeBridgeCompatibility(cliVersion) !== "invalid") error.cliVersion = cliVersion;
223 if (missingCapabilities) error.missingCapabilities = missingCapabilities;
224 return error;
225}
226
227function requireGeneration(state, generation, reason) {
228 if (state.generation !== generation) throw new Error(reason);
229}
230
231async function identity($, state) {
232 const generation = state.generation;
233 let version;
234 try {
235 version = await $.session.version();
236 } catch {
237 requireGeneration(state, generation, "stale-native-identity");
238 throw compatibilityFailure("bridge-capabilities-missing", undefined, ["session-identity"]);
239 }
240 requireGeneration(state, generation, "stale-native-identity");
241 const compatibility = claudeBridgeCompatibility(version?.version);
242 if (compatibility === "invalid") throw compatibilityFailure("bridge-cli-unsupported");
243 if (compatibility === "too-old")
244 throw compatibilityFailure("bridge-cli-too-old", version.version);
245 let nativeId;
246 let cwd;
247 try {
248 nativeId = await $.session.id();
249 requireGeneration(state, generation, "stale-native-identity");
250 cwd = await $.session.cwd();
251 } catch {
252 requireGeneration(state, generation, "stale-native-identity");
253 throw compatibilityFailure("bridge-capabilities-missing", version.version, [
254 "session-identity",
255 ]);
256 }
257 // A completed host read can belong to the session that just ended. It must
258 // not overwrite or invalidate an identity explicitly paired in a later generation.
259 requireGeneration(state, generation, "stale-native-identity");
260 if (
261 typeof nativeId !== "string" ||
262 !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(nativeId) ||
263 typeof cwd !== "string" ||
264 !cwd.startsWith("/")
265 )
266 throw new Error("unsupported-native-identity");
267 if (state.identity && (state.identity.nativeId !== nativeId || state.identity.cwd !== cwd)) {
268 invalidate(state, "native-identity-changed");
269 void flush($, state);
270 throw new Error("native-identity-changed");
271 }
272 state.identity = {
273 protocol: 1,
274 nativeId,
275 cwd,
276 cliVersion: version.version,
277 instanceId: state.instanceId,
278 pluginVersion: PLUGIN_VERSION,
279 nativeCapabilities: state.identity?.nativeCapabilities ?? {
280 version: CLAUDE_BRIDGE_COMPATIBILITY.capabilityVersion,
281 available: [],
282 },
283 };
284 return state.identity;
285}
286
287/** Probe only on pair/reconnect. Never submit a prompt, abort a turn or read user configuration. */
288export async function probeCapabilities($, state) {
289 const generation = state.generation;
290 const observed = await identity($, state);
291 requireGeneration(state, generation, "stale-capability-probe");
292 const missing = [];
293 try {
294 const rows = await $.session.messages();
295 requireGeneration(state, generation, "stale-capability-probe");
296 if (
297 !Array.isArray(rows) ||
298 rows.some(
299 (row) =>
300 !row ||
301 typeof row !== "object" ||
302 Array.isArray(row) ||
303 typeof row.role !== "string" ||
304 ((row.role === "user" || row.role === "assistant") && typeof row.text !== "string") ||
305 (row.toolUses !== undefined && !Array.isArray(row.toolUses)),
306 )
307 )
308 throw new Error("invalid-native-history");
309 if (
310 visibleTools(rows).some(
311 (tool) =>
312 tool.id.length === 0 ||
313 tool.id.length > 256 ||
314 tool.name.length === 0 ||
315 tool.name.length > 256,
316 )
317 )
318 throw new Error("invalid-native-history");
319 } catch {
320 requireGeneration(state, generation, "stale-capability-probe");
321 missing.push("session-messages");
322 }
323 try {
324 const usage = await $.session.usage();
325 requireGeneration(state, generation, "stale-capability-probe");
326 if (usage !== null && (typeof usage !== "object" || Array.isArray(usage)))
327 throw new Error("invalid-native-usage");
328 const context = usage?.context;
329 if (context !== undefined && context !== null) {
330 if (typeof context !== "object" || Array.isArray(context))
331 throw new Error("invalid-native-usage");
332 for (const key of ["tokens", "window", "percent"]) {
333 const value = context[key];
334 if (
335 value !== undefined &&
336 value !== null &&
337 (typeof value !== "number" ||
338 !Number.isFinite(value) ||
339 value < 0 ||
340 (key === "percent" ? value > 100 : !Number.isSafeInteger(value)))
341 )
342 throw new Error("invalid-native-usage");
343 }
344 }
345 } catch {
346 requireGeneration(state, generation, "stale-capability-probe");
347 missing.push("session-usage");
348 }
349 try {
350 // A constant probe value avoids races between sessions sharing this store.
351 // This separate key never overwrites a saved credential path.
352 const value = `agentkib-bridge:${PLUGIN_VERSION}:capabilities:1`;
353 await $.store.set("compatibility:credential-store:1", value);
354 requireGeneration(state, generation, "stale-capability-probe");
355 const stored = await $.store.get("compatibility:credential-store:1");
356 requireGeneration(state, generation, "stale-capability-probe");
357 if (stored !== value) throw new Error("invalid-native-store");
358 } catch {
359 requireGeneration(state, generation, "stale-capability-probe");
360 missing.push("credential-store");
361 }
362 try {
363 const root = $.plugin.root;
364 if (
365 typeof root !== "string" ||
366 !root.startsWith("/") ||
367 root.includes("\0") ||
368 root.split("/").includes("..")
369 )
370 throw new Error("invalid-plugin-root");
371 const manifest = JSON.parse(await $.fs.read(`${root}/package.json`));
372 requireGeneration(state, generation, "stale-capability-probe");
373 if (manifest?.version !== PLUGIN_VERSION)
374 throw compatibilityFailure("bridge-plugin-update-required", observed.cliVersion);
375 } catch (error) {
376 requireGeneration(state, generation, "stale-capability-probe");
377 if (error?.message === "bridge-plugin-update-required") throw error;
378 missing.push("credential-read");
379 }
380 if (missing.length)
381 throw compatibilityFailure("bridge-capabilities-missing", observed.cliVersion, missing);
382 if (
383 state.generation !== generation ||
384 state.identity?.nativeId !== observed.nativeId ||
385 state.identity?.cwd !== observed.cwd ||
386 state.identity?.cliVersion !== observed.cliVersion
387 )
388 throw new Error("stale-capability-probe");
389 const report = {
390 version: CLAUDE_BRIDGE_COMPATIBILITY.capabilityVersion,
391 available: [...CLAUDE_BRIDGE_REQUIRED_CAPABILITIES],
392 };
393 // Another identity read can replace the object while these calls await.
394 // Publish the successful probe to the matching current identity too, so its
395 // first snapshot cannot lose the report accepted in the pairing handshake.
396 observed.nativeCapabilities = report;
397 state.identity.nativeCapabilities = report;
398 return observed;
399}
400
401function record(state, event) {
402 if (state.closed || (!state.connection && !state.credentialPath)) return;
403 if (event.type === "turn-complete") {
404 if (state.completions.size >= MAX_EVENTS && !state.completions.has(event.turnId)) {
405 invalidate(state, "completion-capacity-reached");
406 return;
407 }
408 state.completions.set(event.turnId, event);
409 }
410 if (state.bufferPaused && event.type !== "snapshot") {
411 // A lost start cannot be followed by deltas against the host's old turn.
412 // Snapshots reconstruct previews; only terminal evidence bypasses the pause.
413 state.overflowEpoch += 1;
414 state.dirty = true;
415 return;
416 }
417 if (state.events.length >= MAX_EVENTS) {
418 markGap(state);
419 return;
420 }
421 const seq = ++state.seq;
422 state.events.push({ seq, event });
423 return seq;
424}
425
426function markGap(state) {
427 // Replace unacknowledged previews, retaining terminal evidence separately.
428 // New sequence numbers keep an older in-flight ACK from deleting this fence.
429 state.events = [{ seq: ++state.seq, event: { type: "gap", revision: state.revision } }];
430 state.bufferPaused = true;
431 state.overflowEpoch += 1;
432 state.snapshotRecovery = null;
433 state.dirty = true;
434}
435
436function waitingState(state) {
437 const waits = [...state.waits.values()];
438 if (waits.includes("question")) return "question";
439 if (waits.includes("permission")) return "permission";
440 return waits.includes("unknown") ? "unknown" : null;
441}
442
443function sameNativeValue(left, right) {
444 if (left === right) return true;
445 if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
446 const keys = Object.keys(left);
447 return (
448 Array.isArray(left) === Array.isArray(right) &&
449 keys.length === Object.keys(right).length &&
450 keys.every((key) => Object.hasOwn(right, key) && sameNativeValue(left[key], right[key]))
451 );
452}
453
454function permissionTool(state, event) {
455 if (!event.tool_input || typeof event.tool_input !== "object") return null;
456 // PermissionRequest has no native tool-use ID. Associate only an unambiguous
457 // matching call; rewritten or duplicate inputs remain explicitly unverified.
458 const matches = [...state.activeTools.values()].filter(
459 (tool) =>
460 tool.name === event.tool_name &&
461 Object.keys(event.tool_input).every(
462 (key) =>
463 Object.hasOwn(tool.input, key) && sameNativeValue(event.tool_input[key], tool.input[key]),
464 ),
465 );
466 return matches.length === 1 ? matches[0] : null;
467}
468
469function invalidate(state, reason) {
470 state.generation += 1;
471 state.sendDisabled = true;
472 state.activityVerified = false;
473 state.nativeWorking = null;
474 state.currentTurnId = null;
475 state.streamText = "";
476 state.streamBytes = 0;
477 state.streamTruncated = false;
478 state.activeTools.clear();
479 state.waits.clear();
480 state.revision += 1;
481 if (state.connection && state.identity && state.lastSnapshot) {
482 const revoked = {
483 ...state.lastSnapshot,
484 revision: state.revision,
485 status: "disconnected",
486 streamText: "",
487 currentTurnId: null,
488 waiting: null,
489 messages: [],
490 toolItems: [],
491 usage: null,
492 capabilities: { read: false, send: false, stop: false, approve: false, answer: false },
493 };
494 state.termination = {
495 socketPath: state.socketPath,
496 token: state.connection.token,
497 body: {
498 ...lease(state),
499 events: [
500 { seq: ++state.seq, event: { type: "snapshot", snapshot: revoked } },
501 { seq: ++state.seq, event: { type: "invalidated", reason, revision: state.revision } },
502 ],
503 },
504 };
505 }
506 state.closed = true;
507 state.connection = null;
508 state.connectionFailure = null;
509 state.needsReconnect = false;
510 state.pairingRecoveryGeneration = null;
511 state.reconnectGeneration = null;
512 state.reconnectFailures = 0;
513 state.reconnectDelayTicks = 0;
514}
515
516async function request($, state, path, body, authenticated = true) {
517 if (!safeSocket(state.socketPath)) throw new Error("invalid-socket");
518 const generation = state.generation;
519 const connection = state.connection;
520 let response;
521 try {
522 response = await $.http.fetch(`http://localhost${path}`, {
523 socketPath: state.socketPath,
524 method: "POST",
525 headers: {
526 "Content-Type": "application/json",
527 ...(authenticated ? { Authorization: `Bearer ${state.connection?.token ?? ""}` } : {}),
528 },
529 body: JSON.stringify(body),
530 });
531 } catch {
532 if (state.generation === generation && state.connection === connection && !state.closed)
533 state.needsReconnect = true;
534 throw new Error("bridge-unavailable");
535 }
536 if (state.generation !== generation || (authenticated && state.connection !== connection))
537 throw new Error("stale-bridge-response");
538 const decoded = typeof response?.text === "string" ? JSON.parse(response.text) : null;
539 if (response?.status === 409 && decoded?.error === "bridge-lease-expired") {
540 state.needsReconnect = true;
541 throw new Error("bridge-lease-expired");
542 }
543 if ([401, 403, 410].includes(response?.status)) {
544 invalidate(state, "binding-revoked");
545 throw new Error("binding-revoked");
546 }
547 if (!response?.ok || typeof response.text !== "string")
548 throw compatibilityFailure(
549 [
550 "invalid-bridge-challenge",
551 "expired-bridge-challenge",
552 "bridge-version-mismatch",
553 "bridge-cli-too-old",
554 "bridge-cli-unsupported",
555 "bridge-capabilities-missing",
556 "bridge-plugin-update-required",
557 "bridge-identity-mismatch",
558 "control-outcome-unconfirmed",
559 "claude-bridge-binding-limit",
560 "unsupported-native-identity",
561 "native-identity-changed",
562 ].includes(decoded?.error)
563 ? decoded.error
564 : "bridge-unavailable",
565 state.identity?.cliVersion,
566 );
567 return decoded;
568}
569
570function connectionFrom(value) {
571 if (
572 value?.protocol !== 1 ||
573 ![value.bindingId, value.token, value.leaseId].every(
574 (v) => typeof v === "string" && v.length >= 16 && v.length <= 512,
575 ) ||
576 typeof value.credentialPath !== "string" ||
577 !value.credentialPath.startsWith("/") ||
578 value.credentialPath.includes("\0") ||
579 value.credentialPath.split("/").includes("..")
580 )
581 throw new Error("invalid-bridge-connection");
582 return value;
583}
584
585async function snapshot($, state) {
586 const observed = await identity($, state);
587 const rows = await $.session.messages();
588 const usage = await $.session.usage();
589 const context = usage?.context;
590 const numeric = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
591 const waiting = waitingState(state);
592 const result = {
593 ...observed,
594 revision: state.revision,
595 currentTurnId: state.currentTurnId,
596 status:
597 waiting === "question" || waiting === "permission"
598 ? "waiting"
599 : state.currentTurnId || state.nativeWorking !== false || waiting === "unknown"
600 ? "running"
601 : "idle",
602 waiting,
603 messages: visibleMessages(rows),
604 toolItems: visibleTools(rows),
605 streamText: state.streamText,
606 usage: context
607 ? {
608 tokens: numeric(context.tokens),
609 window: numeric(context.window),
610 percent: numeric(context.percent),
611 observedAt: Date.now(),
612 }
613 : null,
614 capabilities: {
615 read: true,
616 send:
617 SEND_CONTRACT_EXPERIMENT &&
618 !state.closed &&
619 !state.needsReconnect &&
620 state.activityVerified &&
621 !state.sendDisabled &&
622 !state.bufferPaused &&
623 !state.currentTurnId &&
624 !state.pendingSend,
625 stop:
626 !state.closed &&
627 !state.needsReconnect &&
628 !state.bufferPaused &&
629 Boolean(state.currentTurnId),
630 approve: false,
631 answer: false,
632 },
633 };
634 // JSON escaping counts too: a body of control characters must fit the same
635 // transport budget as ordinary text. This is a preview, never the full log.
636 while (new TextEncoder().encode(JSON.stringify(result)).length > 512 * 1024) {
637 if (result.messages.length > 1) result.messages.shift();
638 else if (result.toolItems.length) result.toolItems.shift();
639 else {
640 result.streamText = previewText(result.streamText, 8 * 1024);
641 break;
642 }
643 }
644 state.lastSnapshot = result;
645 return result;
646}
647
648async function flush($, state) {
649 if (state.termination && !state.terminating) {
650 state.terminating = true;
651 const ending = state.termination;
652 // End the local lease immediately; this best-effort notification uses only
653 // the old lease and does not read the newly selected native session.
654 try {
655 await $.http.fetch("http://localhost/v1/events", {
656 socketPath: ending.socketPath,
657 method: "POST",
658 headers: { "Content-Type": "application/json", Authorization: `Bearer ${ending.token}` },
659 body: JSON.stringify(ending.body),
660 });
661 } catch {
662 /* A closed socket is expected during application shutdown. */
663 }
664 state.termination = null;
665 state.terminating = false;
666 return;
667 }
668 if (
669 !state.connection ||
670 state.connection.leaseId === "reconnecting" ||
671 state.needsReconnect ||
672 state.reconnectGeneration === state.generation ||
673 state.closed ||
674 state.flushing
675 )
676 return;
677 state.flushing = true;
678 try {
679 // Terminal evidence survives delta overflow and reconnect until acknowledged.
680 for (const event of state.completions.values()) {
681 if (state.events.length >= MAX_EVENTS) break;
682 if (!state.events.some((entry) => entry.event === event))
683 state.events.push({ seq: ++state.seq, event });
684 }
685 if (state.dirty && state.events.length < MAX_EVENTS) {
686 state.dirty = false;
687 const epoch = state.overflowEpoch;
688 const seq = record(state, { type: "snapshot", snapshot: await snapshot($, state) });
689 if (seq !== undefined) state.snapshotRecovery = { seq, epoch };
690 }
691 const batch = [];
692 for (const entry of state.events.slice(0, 32)) {
693 if (new TextEncoder().encode(JSON.stringify([...batch, entry])).length > 900 * 1024) break;
694 batch.push(entry);
695 }
696 if (!batch.length) return;
697 const connection = state.connection;
698 const response = await request($, state, "/v1/events", { ...lease(state), events: batch });
699 if (state.connection !== connection) return;
700 if (
701 !Number.isSafeInteger(response?.ackSeq) ||
702 response.ackSeq !== batch[batch.length - 1].seq
703 ) {
704 invalidate(state, "invalid-event-acknowledgement");
705 return;
706 }
707 for (const entry of batch) {
708 if (
709 entry.event.type === "turn-complete" &&
710 state.completions.get(entry.event.turnId) === entry.event
711 )
712 state.completions.delete(entry.event.turnId);
713 }
714 state.events = state.events.filter((entry) => entry.seq > response.ackSeq);
715 if (
716 state.bufferPaused &&
717 state.snapshotRecovery &&
718 state.snapshotRecovery.seq <= response.ackSeq &&
719 state.snapshotRecovery.epoch === state.overflowEpoch
720 ) {
721 state.bufferPaused = false;
722 state.dirty = true;
723 }
724 } catch {
725 state.dirty = true;
726 } finally {
727 state.flushing = false;
728 }
729}
730
731async function reportResult($, state, result) {
732 if (!state.connection || state.closed) return;
733 await request($, state, "/v1/results", { ...lease(state), ...result });
734 state.unacknowledgedResults.delete(result.commandId);
735}
736
737async function execute($, state, command) {
738 if (
739 !command ||
740 typeof command.commandId !== "string" ||
741 !command.commandId ||
742 command.commandId.length > 256
743 ) {
744 invalidate(state, "invalid-command");
745 return;
746 }
747 const prior = state.results.get(command.commandId);
748 const fingerprint = JSON.stringify(command);
749 if (prior) {
750 if (prior.fingerprint !== fingerprint) {
751 invalidate(state, "command-identity-conflict");
752 return;
753 }
754 await reportResult($, state, prior.result);
755 state.afterCommandId = command.commandId;
756 return;
757 }
758 const result = {
759 commandId: command.commandId,
760 status: "rejected",
761 reason: "unsupported-command",
762 revision: state.revision,
763 };
764 // Lost acknowledgements replay this receipt, never a native action.
765 state.results.set(command.commandId, { fingerprint, result });
766 if (state.results.size > 2048) {
767 invalidate(state, "receipt-capacity-reached");
768 return;
769 }
770 await identity($, state);
771 if (command.expectedRevision !== state.revision) result.reason = "revision-conflict";
772 else if (command.kind === "send") {
773 if (!SEND_CONTRACT_EXPERIMENT) result.reason = "claude-native-send-experimental-disabled";
774 else if (!validSend(command)) result.reason = "invalid-text";
775 else if (
776 state.closed ||
777 state.sendDisabled ||
778 state.bufferPaused ||
779 !state.activityVerified ||
780 state.currentTurnId ||
781 state.pendingSend
782 )
783 result.reason = "session-not-idle";
784 else {
785 const pending = {
786 text: command.text,
787 expectedRevision: command.expectedRevision,
788 observed: false,
789 competing: false,
790 turnId: null,
791 };
792 state.pendingSend = pending;
793 try {
794 const submitted = await $.prompt.submit({ text: command.text, asUser: true });
795 if (submitted?.drop) result.reason = "native-prompt-refused";
796 else if (
797 state.pendingSend === pending &&
798 pending.observed &&
799 !pending.competing &&
800 pending.turnId &&
801 submitted?.text === pending.text
802 ) {
803 result.status = "accepted";
804 delete result.reason;
805 result.turnId = pending.turnId;
806 } else {
807 result.status = "unknown";
808 result.reason = "native-turn-unconfirmed";
809 state.sendDisabled = true;
810 }
811 } catch {
812 result.status = "unknown";
813 result.reason = "native-submit-result-unknown";
814 state.sendDisabled = true;
815 } finally {
816 if (state.pendingSend === pending) state.pendingSend = null;
817 }
818 }
819 } else if (command.kind === "stop") {
820 if (state.closed || state.bufferPaused || state.needsReconnect)
821 result.reason = "session-state-unverified";
822 else if (!state.currentTurnId || command.turnId !== state.currentTurnId)
823 result.reason = "turn-conflict";
824 else {
825 try {
826 await $.turn.abort({ turnId: command.turnId });
827 result.status = "accepted";
828 delete result.reason;
829 result.turnId = command.turnId;
830 } catch {
831 result.status = "unknown";
832 result.reason = "native-stop-result-unknown";
833 }
834 }
835 }
836 result.revision = state.revision;
837 state.unacknowledgedResults.set(command.commandId, result);
838 state.dirty = true;
839 await flush($, state);
840 await reportResult($, state, result);
841 state.afterCommandId = command.commandId;
842}
843
844async function pump($, state, nativeEvent = false) {
845 if (
846 (!state.connection && !state.needsReconnect) ||
847 state.connection?.leaseId === "reconnecting" ||
848 state.reconnectGeneration === state.generation ||
849 state.closed ||
850 state.pumping
851 )
852 return;
853 if (state.needsReconnect && !state.pendingSend && !nativeEvent && state.reconnectDelayTicks > 0) {
854 state.reconnectDelayTicks -= 1;
855 return;
856 }
857 const generation = state.generation;
858 state.pumping = true;
859 try {
860 if (state.needsReconnect && !state.pendingSend) await reconnect($, state);
861 if (state.generation !== generation || !state.connection || state.closed) return;
862 await identity($, state);
863 for (const result of state.unacknowledgedResults.values()) await reportResult($, state, result);
864 const connection = state.connection;
865 const response = await request($, state, "/v1/commands", {
866 ...lease(state),
867 afterCommandId: state.afterCommandId,
868 waitMs: 20_000,
869 });
870 if (state.closed || state.connection !== connection) return;
871 if (!Array.isArray(response?.commands) || response.commands.length > 1) {
872 invalidate(state, "invalid-command-batch");
873 return;
874 }
875 for (const command of response.commands) await execute($, state, command);
876 } catch {
877 state.dirty = true;
878 } finally {
879 state.pumping = false;
880 }
881}
882
883async function connect($, state, ticket) {
884 // A new one-time ticket is the explicit authorization to bind the currently
885 // selected native session after clear/resume or a prior disconnect.
886 if (!state.connection && state.closed && !state.pendingSend) state.identity = null;
887 if (state.connection && state.connection.leaseId !== "reconnecting")
888 throw new Error("already-connected");
889 // A newer code can supersede an awaiting pairing. Transfer only that current
890 // attempt's saved-binding recovery intent without waking the pump mid-pair.
891 const resumeRecovery =
892 state.needsReconnect || state.pairingRecoveryGeneration === state.generation;
893 const generation = ++state.generation;
894 state.pairingRecoveryGeneration = resumeRecovery ? generation : null;
895 state.connection = null;
896 state.connectionFailure = null;
897 state.needsReconnect = false;
898 state.reconnectFailures = 0;
899 state.reconnectDelayTicks = 0;
900 state.socketPath = ticket.socketPath;
901 try {
902 await connectOnce($, state, ticket, generation);
903 } catch (error) {
904 // A rejected replacement code does not revoke the saved binding. Resume its
905 // full reconnect checks only if this attempt still owns the open generation.
906 if (resumeRecovery && state.generation === generation && !state.closed && !state.connection)
907 state.needsReconnect = true;
908 throw error;
909 } finally {
910 if (state.pairingRecoveryGeneration === generation) state.pairingRecoveryGeneration = null;
911 }
912}
913
914async function connectOnce($, state, ticket, generation) {
915 let observed;
916 try {
917 observed = await probeCapabilities($, state);
918 } catch (error) {
919 if (
920 [
921 "bridge-version-mismatch",
922 "bridge-cli-too-old",
923 "bridge-cli-unsupported",
924 "bridge-capabilities-missing",
925 "bridge-plugin-update-required",
926 "unsupported-native-identity",
927 "native-identity-changed",
928 ].includes(error?.message)
929 ) {
930 try {
931 await request(
932 $,
933 state,
934 "/v1/pair",
935 {
936 ticket: ticket.ticket,
937 connectionError: error.message,
938 ...(error.cliVersion ? { cliVersion: error.cliVersion } : {}),
939 ...(error.missingCapabilities
940 ? { missingCapabilities: error.missingCapabilities }
941 : {}),
942 },
943 false,
944 );
945 } catch {
946 // Preserve the native validation error even when the broker is offline.
947 }
948 }
949 throw error;
950 }
951 if (state.generation !== generation) throw new Error("stale-connect");
952 const response = await request(
953 $,
954 state,
955 "/v1/pair",
956 { ...observed, ticket: ticket.ticket },
957 false,
958 );
959 if (state.generation !== generation) throw new Error("stale-connect");
960 await adopt($, state, observed, response);
961}
962
963async function adopt($, state, observed, response) {
964 state.connection = connectionFrom(response);
965 state.credentialPath = response.credentialPath;
966 state.closed = false;
967 state.sendDisabled = false;
968 state.needsReconnect = false;
969 state.seq = 0;
970 state.events = [];
971 state.completions.clear();
972 state.bufferPaused = false;
973 state.snapshotRecovery = null;
974 state.afterCommandId = null;
975 await $.store.set(`credentialPath:${observed.nativeId}`, response.credentialPath);
976 state.dirty = true;
977 await flush($, state);
978}
979
980// Diagnostic reports authenticate an existing binding without establishing a
981// lease. Fresh native identity reads are required even when version probing
982// failed before identity() could complete; cached identity is not evidence.
983async function reportReconnectFailure($, state, generation, failure) {
984 const current = () => state.generation === generation && !state.closed;
985 const nativeId = await $.session.id();
986 if (!current()) return;
987 const cwd = await $.session.cwd();
988 if (!current()) return;
989 if (
990 typeof nativeId !== "string" ||
991 !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(nativeId) ||
992 typeof cwd !== "string" ||
993 !cwd.startsWith("/") ||
994 cwd.includes("\0") ||
995 cwd.split("/").includes("..")
996 )
997 return;
998 const path = await $.store.get(`credentialPath:${nativeId}`);
999 if (!current()) return;
1000 if (
1001 typeof path !== "string" ||
1002 !path.startsWith("/") ||
1003 path.includes("\0") ||
1004 path.split("/").includes("..")
1005 )
1006 return;
1007 const credential = JSON.parse(await $.fs.read(path));
1008 if (!current()) return;
1009 if (
1010 credential?.protocol !== 1 ||
1011 credential.nativeId !== nativeId ||
1012 credential.cwd !== cwd ||
1013 credential.pluginVersion !== PLUGIN_VERSION ||
1014 ["invalid", "too-old"].includes(claudeBridgeCompatibility(credential.cliVersion)) ||
1015 !safeSocket(credential.socketPath) ||
1016 typeof credential.bindingId !== "string" ||
1017 !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(credential.bindingId) ||
1018 typeof credential.token !== "string" ||
1019 !/^[a-f0-9]{64}$/.test(credential.token)
1020 )
1021 return;
1022 await $.http.fetch("http://localhost/v1/reconnect", {
1023 socketPath: credential.socketPath,
1024 method: "POST",
1025 headers: { "Content-Type": "application/json", Authorization: `Bearer ${credential.token}` },
1026 body: JSON.stringify({
1027 protocol: 1,
1028 pluginVersion: PLUGIN_VERSION,
1029 bindingId: credential.bindingId,
1030 nativeId,
1031 cwd,
1032 instanceId: state.instanceId,
1033 connectionError: failure.reason,
1034 ...(failure.cliVersion ? { cliVersion: failure.cliVersion } : {}),
1035 ...(failure.missingCapabilities ? { missingCapabilities: failure.missingCapabilities } : {}),
1036 }),
1037 });
1038}
1039
1040async function reconnect($, state) {
1041 const generation = state.generation;
1042 if (state.closed || state.reconnectGeneration === generation) return;
1043 state.reconnectGeneration = generation;
1044 state.needsReconnect = true;
1045 // Once a lease needs recovery, no event may reuse it while probes/backoff run.
1046 state.connection = null;
1047 try {
1048 await reconnectOnce($, state);
1049 if (state.generation === generation && !state.closed) {
1050 state.reconnectFailures = 0;
1051 state.reconnectDelayTicks = 0;
1052 }
1053 } catch (error) {
1054 if (state.generation === generation && !state.closed) {
1055 state.needsReconnect = true;
1056 state.reconnectFailures = Math.min(
1057 state.reconnectFailures + 1,
1058 RECONNECT_BACKOFF_TICKS.length,
1059 );
1060 state.reconnectDelayTicks = RECONNECT_BACKOFF_TICKS[state.reconnectFailures - 1];
1061 }
1062 if (
1063 state.generation === generation &&
1064 !state.closed &&
1065 INCOMPATIBLE_ERRORS.includes(error?.message)
1066 ) {
1067 const failure = {
1068 reason: error.message,
1069 ...(error.cliVersion ? { cliVersion: error.cliVersion } : {}),
1070 ...(error.missingCapabilities ? { missingCapabilities: error.missingCapabilities } : {}),
1071 };
1072 state.connection = null;
1073 state.connectionFailure = failure;
1074 try {
1075 await reportReconnectFailure($, state, generation, failure);
1076 } catch {
1077 // A local compatibility reason remains useful when the authenticated
1078 // diagnostic cannot be delivered. Never substitute raw host errors.
1079 }
1080 }
1081 throw error;
1082 } finally {
1083 if (state.generation === generation && state.reconnectGeneration === generation)
1084 state.reconnectGeneration = null;
1085 }
1086}
1087
1088async function reconnectOnce($, state) {
1089 const generation = state.generation;
1090 const previousIdentity = await identity($, state);
1091 const path = await $.store.get(`credentialPath:${previousIdentity.nativeId}`);
1092 if (state.generation !== generation || state.closed) throw new Error("stale-reconnect");
1093 if (typeof path !== "string" || !path.startsWith("/") || path.includes("\0")) {
1094 state.needsReconnect = false;
1095 return;
1096 }
1097 // A terminal with no saved binding does not need history/file/store-write
1098 // probes on startup. Every actual reconnect still repeats the full probe.
1099 const observed = await probeCapabilities($, state);
1100 if (state.generation !== generation || state.closed) throw new Error("stale-reconnect");
1101 const credential = JSON.parse(await $.fs.read(path));
1102 if (
1103 credential?.protocol !== 1 ||
1104 credential.nativeId !== observed.nativeId ||
1105 credential.cwd !== observed.cwd ||
1106 claudeBridgeCompatibility(credential.cliVersion) === "invalid" ||
1107 claudeBridgeCompatibility(credential.cliVersion) === "too-old" ||
1108 credential.pluginVersion !== PLUGIN_VERSION ||
1109 !safeSocket(credential.socketPath) ||
1110 typeof credential.bindingId !== "string" ||
1111 typeof credential.token !== "string"
1112 )
1113 throw new Error("invalid-reconnect-credential");
1114 if (state.generation !== generation || state.closed) throw new Error("stale-reconnect");
1115 state.socketPath = credential.socketPath;
1116 state.credentialPath = path;
1117 const connecting = {
1118 protocol: 1,
1119 bindingId: credential.bindingId,
1120 token: credential.token,
1121 leaseId: "reconnecting",
1122 credentialPath: path,
1123 };
1124 state.connection = connecting;
1125 try {
1126 const response = await request($, state, "/v1/reconnect", {
1127 ...observed,
1128 bindingId: credential.bindingId,
1129 });
1130 if (state.generation !== generation || state.closed || state.connection !== connecting)
1131 throw new Error("stale-reconnect");
1132 state.connection = connectionFrom(response);
1133 state.connectionFailure = null;
1134 state.credentialPath = path;
1135 state.closed = false;
1136 state.needsReconnect = false;
1137 state.seq = 0;
1138 state.events = [];
1139 state.snapshotRecovery = null;
1140 state.afterCommandId = null;
1141 state.dirty = true;
1142 } finally {
1143 // A failed HTTP call must release only its own placeholder. A newer ticket
1144 // or session.end has already replaced this generation and must stay intact.
1145 if (state.generation === generation && state.connection === connecting) state.connection = null;
1146 }
1147}
1148
1149function safeAbsolute(path) {
1150 return (
1151 typeof path === "string" &&
1152 path.startsWith("/") &&
1153 !path.includes("\0") &&
1154 !path.split("/").includes("..")
1155 );
1156}
1157
1158/** AgentKib's 0600 discovery files, production first. Missing or invalid files are skipped. */
1159export async function discoverAgentKib($) {
1160 const roots = [];
1161 try {
1162 const custom = await $.env.get("AGENTKIB_HOME");
1163 if (safeAbsolute(custom)) roots.push(custom);
1164 const home = await $.env.get("HOME");
1165 if (safeAbsolute(home)) roots.push(`${home}/.agentkib`, `${home}/.agentkib-dev`);
1166 } catch {
1167 return [];
1168 }
1169 const found = [];
1170 for (const root of roots) {
1171 const file = `${root.replace(/\/+$/, "")}/claude-bridge/auto-v1.json`;
1172 try {
1173 if (!(await $.fs.exists(file))) continue;
1174 const value = JSON.parse(await $.fs.read(file));
1175 if (
1176 value?.protocol === 1 &&
1177 safeSocket(value.socketPath) &&
1178 typeof value.autoKey === "string" &&
1179 /^[a-f0-9]{64}$/.test(value.autoKey) &&
1180 !found.some((item) => item.socketPath === value.socketPath)
1181 )
1182 found.push({ socketPath: value.socketPath, autoKey: value.autoKey });
1183 } catch {
1184 // An unreadable discovery file means that AgentKib is not available here.
1185 }
1186 }
1187 return found;
1188}
1189
1190/**
1191 * Pairs this terminal's own session without a code when AgentKib allows it for
1192 * the session's workspace. A saved binding, an explicit code or a disconnect in
1193 * AgentKib always takes precedence.
1194 */
1195export async function autoConnect($, state) {
1196 if (state.connection || state.needsReconnect || state.autoConnecting || state.pendingSend) return;
1197 state.autoConnecting = true;
1198 let nativeId;
1199 try {
1200 nativeId = await $.session.id();hooks/compatibility.js 47 lines1// One policy shared by the shipped plugin and Runtime. Only add a verified
2// version after recording native read-only acceptance evidence in QA.
3export const CLAUDE_BRIDGE_COMPATIBILITY = Object.freeze({
4 minimumCliVersion: "2.1.301",
5 verifiedCliVersions: Object.freeze(["2.1.301", "2.1.310"]),
6 pluginVersion: "0.3.0",
7 capabilityVersion: 1,
8});
9
10export const CLAUDE_BRIDGE_REQUIRED_CAPABILITIES = Object.freeze([
11 "session-identity",
12 "session-messages",
13 "session-usage",
14 "credential-store",
15 "credential-read",
16]);
17
18export function claudeBridgeCompatibility(version) {
19 // Reject ambiguous/prerelease versions instead of coercing them into a
20 // supported stable release. Bound each component before numeric comparison.
21 if (
22 typeof version !== "string" ||
23 !/^(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})$/.test(version)
24 )
25 return "invalid";
26 const actual = version.split(".").map(Number);
27 const minimum = CLAUDE_BRIDGE_COMPATIBILITY.minimumCliVersion.split(".").map(Number);
28 for (let index = 0; index < minimum.length; index++) {
29 if (actual[index] < minimum[index]) return "too-old";
30 if (actual[index] > minimum[index]) break;
31 }
32 return CLAUDE_BRIDGE_COMPATIBILITY.verifiedCliVersions.includes(version)
33 ? "verified"
34 : "unverified";
35}
36
37export function missingClaudeBridgeCapabilities(report) {
38 if (
39 report?.version !== CLAUDE_BRIDGE_COMPATIBILITY.capabilityVersion ||
40 !Array.isArray(report.available) ||
41 report.available.length > 32 ||
42 report.available.some((name) => typeof name !== "string" || name.length > 64)
43 )
44 return [...CLAUDE_BRIDGE_REQUIRED_CAPABILITIES];
45 return CLAUDE_BRIDGE_REQUIRED_CAPABILITIES.filter((name) => !report.available.includes(name));
46}
47