@chenacc/dsh-agentbridge 0.2.0 → 0.2.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.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/lib/index.js +977 -970
  3. package/package.json +61 -61
package/lib/index.js CHANGED
@@ -1,970 +1,977 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import path from "node:path";
5
- import { fileURLToPath } from "node:url";
6
-
7
- const name = "agentbridge-dsh-phone";
8
- // `agents` is not optional: creating a conversation from the phone asks the agent
9
- // service to open one, and touching a service that was not injected throws
10
- // `cannot get property "agents" without inject` — which is what the phone showed
11
- // as a failed "新建对话" instead of the friendly message below.
12
- const inject = ["commands", "apiProxy", "llm", "agents"];
13
- const DEFAULT_ORIGIN = "http://127.0.0.1:8787";
14
- const POLL_DELAY_MS = 800;
15
- const EVENT_BATCH_DELAY_MS = 120;
16
- const APPROVAL_PREFIX = "approval:";
17
- // The bridge accepts at most 1 MB per /events POST (readJson limit), and this batch
18
- // carries a JSON wrapper on top of the events. 448 KB leaves headroom, and it is also
19
- // the cap for a single shrunken event, so one giant tool output can never wedge the
20
- // queue behind a batch the bridge would refuse.
21
- const EVENT_POST_BUDGET_BYTES = 448 * 1024;
22
- const EVENT_MAX_ITEMS = 200;
23
- const EVENT_EVENT_BUDGET_BYTES = 384 * 1024;
24
- // A string longer than this in one event is clipped before it crosses the wire: the
25
- // phone renders a summary of tool output, not a faithful copy, and a clipped giant is
26
- // better than a batch that the bridge rejects.
27
- const EVENT_STRING_CLIP = 2_048;
28
- // Bumped whenever the integration gains something the phone relies on. The bridge
29
- // compares it with the version it needs, because this file is *copied* into the DSH
30
- // profile: changing the repository does nothing until install:dsh-phone runs again.
31
- const INTEGRATION_VERSION = 6;
32
- // Reconnect pacing. The first attempt is immediate (a bridge restart is usually already
33
- // over by the time the next poll fails), then it backs off to `RECONNECT_MAX_MS`.
34
- const RECONNECT_MIN_MS = 1_000;
35
- const RECONNECT_MAX_MS = 30_000;
36
-
37
- function sleep(ms, signal) {
38
- return new Promise((resolve) => {
39
- if (signal.aborted) return resolve();
40
- const timer = setTimeout(resolve, ms);
41
- signal.addEventListener("abort", () => {
42
- clearTimeout(timer);
43
- resolve();
44
- }, { once: true });
45
- });
46
- }
47
-
48
- function textFromError(error) {
49
- return error instanceof Error ? error.message : String(error);
50
- }
51
-
52
- /**
53
- * Whether the bridge was simply not there.
54
- *
55
- * The distinction matters for the message the user sees: a refused connection
56
- * means the plugin loaded fine and only the local bridge is missing, which is a
57
- * setup step — while a 401 from a live bridge is a different problem entirely.
58
- */
59
- function isBridgeAbsent(error) {
60
- const cause = error && typeof error === "object" ? error.cause?.code ?? "" : "";
61
- return /ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|UND_ERR_CONNECT|fetch failed|socket hang up/i
62
- .test(`${textFromError(error)} ${cause}`);
63
- }
64
-
65
- /** The setup steps a user needs when /phone finds nothing listening. */
66
- function bridgeSetupText(origin) {
67
- return [
68
- `无法连接 AgentBridge 桥(${origin})。插件本身已经加载,缺的是电脑上这个本地服务。`,
69
- "",
70
- "手动起桥只要一条命令:",
71
- "npx @chenacc/agentbridge",
72
- "",
73
- "想长期使用就装成全局命令:",
74
- "npm install -g @chenacc/agentbridge",
75
- "agentbridge phone --agent claude",
76
- "",
77
- `桥启动后再敲一次 /phone。桥不在默认端口的话,先设置环境变量 AGENTBRIDGE_ORIGIN,再重启 DSH Desktop。`,
78
- ].join("\n");
79
- }
80
-
81
- const BRIDGE_PACKAGE = "@chenacc/agentbridge";
82
- // Long enough for a detached server to bind its port on a slow disk, short
83
- // enough that /phone still reads as a command rather than a hang.
84
- const AUTOSTART_TIMEOUT_MS = 8_000;
85
-
86
- /**
87
- * Where the bridge's server entry lives on this machine, if it is installed.
88
- *
89
- * The plugin ships `@chenacc/agentbridge` as a dependency, so the normal answer
90
- * comes from module resolution next to this file. `AGENTBRIDGE_BRIDGE_ENTRY`
91
- * exists for tests and for unusual installs.
92
- *
93
- * The resolved manifest must live under a `node_modules` directory: without that
94
- * check, Node's package self-reference resolves this repository's own root
95
- * package as `@chenacc/agentbridge`, so a development checkout would start a
96
- * second bridge from the source tree and steal port 8787 from the developer.
97
- */
98
- function bridgeServerEntry() {
99
- if (process.env.AGENTBRIDGE_BRIDGE_ENTRY) return process.env.AGENTBRIDGE_BRIDGE_ENTRY;
100
- try {
101
- const resolved = fileURLToPath(import.meta.resolve(`${BRIDGE_PACKAGE}/package.json`));
102
- if (!resolved.split(path.sep).includes("node_modules")) return null;
103
- return path.join(path.dirname(resolved), "src", "server.js");
104
- } catch {
105
- return null;
106
- }
107
- }
108
-
109
- async function bridgeIsReady(origin) {
110
- try {
111
- const response = await fetch(`${origin}/api/health`, { signal: AbortSignal.timeout(700) });
112
- if (!response.ok) return false;
113
- const body = await response.json().catch(() => null);
114
- return body?.ok === true;
115
- } catch {
116
- return false;
117
- }
118
- }
119
-
120
- /**
121
- * Whether this process may start a bridge at all.
122
- *
123
- * A unit test must never spawn a server: node:test sets NODE_TEST_CONTEXT, and a
124
- * bridge started there would bind a real port and outlive the run. An explicit
125
- * AGENTBRIDGE_BRIDGE_ENTRY is the single way to opt back in, which is what the
126
- * autostart test relies on.
127
- */
128
- function autoStartAllowed() {
129
- if (process.env.AGENTBRIDGE_NO_AUTOSTART === "1") return false;
130
- if (process.env.AGENTBRIDGE_BRIDGE_ENTRY) return true;
131
- return process.env.NODE_TEST_CONTEXT === undefined;
132
- }
133
-
134
- /**
135
- * Start the local bridge and wait until it answers.
136
- *
137
- * Returns true only once the health check passes, so the caller retries the real
138
- * registration instead of trusting that a spawn means a working server. Every
139
- * failure path is silent: the caller falls back to the manual setup text.
140
- */
141
- async function startBridge(origin) {
142
- if (await bridgeIsReady(origin)) return true;
143
- if (!autoStartAllowed()) return false;
144
- const entry = bridgeServerEntry();
145
- if (!entry || !existsSync(entry)) return false;
146
-
147
- let port;
148
- try {
149
- port = new URL(origin).port || "8787";
150
- } catch {
151
- return false;
152
- }
153
-
154
- try {
155
- // Loaded lazily: the plugin normally runs with a bridge already up, so the
156
- // child-process machinery is dead weight on the common path.
157
- const { spawn } = await import("node:child_process");
158
- const child = spawn(process.execPath, [entry], {
159
- // State belongs next to the user's DSH data, not in whatever directory the
160
- // desktop happened to launch from.
161
- cwd: process.env.DSH_HOME || homedir(),
162
- detached: true,
163
- stdio: "ignore",
164
- windowsHide: true,
165
- env: { ...process.env, AGENTBRIDGE_PORT: process.env.AGENTBRIDGE_PORT || port },
166
- });
167
- child.unref();
168
- } catch {
169
- return false;
170
- }
171
-
172
- const deadline = Date.now() + AUTOSTART_TIMEOUT_MS;
173
- while (Date.now() < deadline) {
174
- await new Promise((resolve) => setTimeout(resolve, 150));
175
- if (await bridgeIsReady(origin)) return true;
176
- }
177
- return false;
178
- }
179
-
180
- function clipped(value, limit) {
181
- return typeof value === "string" ? value.slice(0, limit) : "";
182
- }
183
-
184
- /**
185
- * Bound one event's wire size.
186
- *
187
- * The bridge rejects a batch over its limit, and a rejected batch is replayed whole
188
- * on the next flush — so an event that is too big by itself wedges the channel: the
189
- * same batch fails again and again, nothing ever advances, and the phone goes blind.
190
- * That loop is what used to fill the desktop log with `Request body is too large`.
191
- *
192
- * Clipping long strings keeps the event useful (the phone only ever shows a summary
193
- * of tool output); the last resort is a stub carrying just the type, because a queued
194
- * stub is progress while a queued giant is not.
195
- */
196
- function shrinkEventForWire(event) {
197
- if (JSON.stringify(event).length <= EVENT_EVENT_BUDGET_BYTES) return event;
198
- const copy = { ...event };
199
- if (copy.data !== undefined && typeof copy.data === "object") copy.data = { ...copy.data };
200
- const clipStrings = (value, limit) => {
201
- if (typeof value === "string") return value.length > limit ? `${value.slice(0, limit)}…[clipped]` : value;
202
- if (Array.isArray(value)) return value.map((item) => clipStrings(item, limit));
203
- if (value && typeof value === "object") {
204
- const result = {};
205
- for (const [key, child] of Object.entries(value)) result[key] = clipStrings(child, limit);
206
- return result;
207
- }
208
- return value;
209
- };
210
- copy.data = clipStrings(copy.data, EVENT_STRING_CLIP);
211
- if (JSON.stringify(copy).length <= EVENT_EVENT_BUDGET_BYTES) return copy;
212
- // Pathological: still over the budget after clipping. The phone only needs the
213
- // event's type to keep the transcript consistent; the payload is display-only.
214
- return { type: copy.type, time: copy.time, data: { note: "事件过大,手机侧省略了内容" } };
215
- }
216
-
217
- /**
218
- * Project one DSH mux frame onto the interaction record the bridge ingests.
219
- *
220
- * Only this session's frames matter, and only the four interaction payloads:
221
- * everything else on the stream is ordinary conversation traffic that already
222
- * travels on the event channel. Fields are copied out one by one because the
223
- * frame carries live DSH objects that must not be handed to another process.
224
- */
225
- export function interactionRecord(envelope, sessionId) {
226
- const payload = envelope?.payload;
227
- const rpcId = typeof envelope?.rpcId === "string" ? envelope.rpcId : "";
228
- if (!payload || !rpcId || payload.sessionId !== sessionId) return null;
229
- if (payload.type === "question/requested") {
230
- const questions = Array.isArray(payload.questions) ? payload.questions : [];
231
- const projected = questions.slice(0, 10).flatMap((question, index) => {
232
- if (!question || typeof question !== "object") return [];
233
- const questionText = clipped(question.question, 4_000);
234
- if (!questionText) return [];
235
- const options = Array.isArray(question.options) ? question.options.slice(0, 25).flatMap((option) => {
236
- const label = clipped(option?.label, 200);
237
- if (!label) return [];
238
- const description = clipped(option?.description, 500);
239
- return [{ label, ...(description ? { description } : {}) }];
240
- }) : [];
241
- const header = clipped(question.header, 200);
242
- return [{
243
- id: clipped(question.id, 100) || `q${index + 1}`,
244
- question: questionText,
245
- ...(header ? { header } : {}),
246
- ...(options.length ? { options } : {}),
247
- ...(question.multiSelect === true ? { multiSelect: true } : {}),
248
- }];
249
- });
250
- if (!projected.length) return null;
251
- return { kind: "question-requested", requestId: rpcId, questions: projected };
252
- }
253
- if (payload.type === "approval/requested") {
254
- return {
255
- kind: "approval-requested",
256
- requestId: rpcId,
257
- dshApprovalId: clipped(payload.approvalId, 200),
258
- toolName: clipped(payload.toolName, 200) || "tool",
259
- ...(payload.reason ? { reason: clipped(payload.reason, 2_000) } : {}),
260
- ...(payload.callId ? { callId: clipped(payload.callId, 200) } : {}),
261
- };
262
- }
263
- if (payload.type === "question/resolved") {
264
- return { kind: "question-resolved", requestId: clipped(payload.questionRpcId, 200), outcome: clipped(payload.outcome, 40) };
265
- }
266
- if (payload.type === "approval/resolved") {
267
- return {
268
- kind: "approval-resolved",
269
- requestId: "",
270
- dshApprovalId: clipped(payload.approvalId, 200),
271
- outcome: clipped(payload.outcome, 40),
272
- };
273
- }
274
- return null;
275
- }
276
-
277
- function deepFreeze(value) {
278
- if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
279
- for (const child of Object.values(value)) deepFreeze(child);
280
- return Object.freeze(value);
281
- }
282
-
283
- function createUserMessage(text) {
284
- return deepFreeze({
285
- id: randomUUID(),
286
- role: "user",
287
- content: [{ type: "text", text }],
288
- source: { kind: "user" },
289
- });
290
- }
291
-
292
- function selectionFromAgent(agent) {
293
- let logged;
294
- try {
295
- logged = agent.session.requestHeader?.()?.config;
296
- } catch {
297
- logged = undefined;
298
- }
299
- const provider = agent.options?.provider || logged?.provider;
300
- const model = agent.options?.model || logged?.model;
301
- if (!provider || !model) return null;
302
- const reasoningEffort = agent.options?.reasoningEffort || logged?.reasoningEffort;
303
- return { provider, model, ...(reasoningEffort ? { reasoningEffort } : {}) };
304
- }
305
-
306
- function compactModelDirectory(value, current, extraFailures = []) {
307
- const groups = Array.isArray(value?.groups) ? value.groups.slice(0, 30).map((group) => ({
308
- id: group.id,
309
- name: group.name,
310
- models: Array.isArray(group.models) ? group.models.slice(0, 200).map((model) => ({
311
- id: model.id,
312
- name: model.name,
313
- ...(model.reasoning ? { reasoning: {
314
- efforts: Array.isArray(model.reasoning.efforts) ? model.reasoning.efforts.slice(0, 20) : [],
315
- ...(model.reasoning.defaultEffort ? { defaultEffort: model.reasoning.defaultEffort } : {}),
316
- } } : {}),
317
- })) : [],
318
- })) : [];
319
- const failures = [...extraFailures, ...(Array.isArray(value?.failures) ? value.failures : [])].slice(0, 30);
320
- return {
321
- current,
322
- routable: current ? groups.some((group) => group.id === current.provider) : false,
323
- groups,
324
- failures,
325
- };
326
- }
327
-
328
- async function readResponse(response) {
329
- const body = await response.json().catch(() => ({}));
330
- if (!response.ok) {
331
- // The status matters to the caller: 401/403/404/409 mean "this channel no
332
- // longer exists", which is the signal to re-register instead of retrying.
333
- const error = new Error(body.error || `AgentBridge request failed (${response.status})`);
334
- error.status = response.status;
335
- throw error;
336
- }
337
- return body;
338
- }
339
-
340
- function isStaleChannel(error) {
341
- return [401, 403, 404, 409, 410].includes(Number(error?.status));
342
- }
343
-
344
- export class PhoneConnections {
345
- constructor(ctx, options = {}) {
346
- this.ctx = ctx;
347
- this.bySession = new Map();
348
- // One lifetime per conversation, independent of any single channel connection.
349
- // A reconnect tears the connection down (aborting its controller) *before* it knows
350
- // whether the bridge is back, so a retry loop tied to that controller could only
351
- // ever run one attempt — the exact bug that left a conversation dead after a manual
352
- // bridge restart. Only the desktop disposing the conversation ends a lifetime.
353
- this.lifetimes = new Map();
354
- this.reconnectMinMs = options.reconnectMinMs ?? RECONNECT_MIN_MS;
355
- this.reconnectMaxMs = options.reconnectMaxMs ?? RECONNECT_MAX_MS;
356
- // Failed interaction cards survive a reconnect, so they are keyed to the
357
- // conversation, not to the channel that tried to carry them.
358
- this.interactionScopes = new Map();
359
- this.liveModelSelections = new WeakMap();
360
- this.ctx.on("session/event", (session, event) => this.captureEvent(session, event));
361
- this.ctx.on("agent/disposed", ({ agent }) => this.dispose(agent.session.id));
362
- }
363
-
364
- lifetimeFor(sessionId) {
365
- let lifetime = this.lifetimes.get(sessionId);
366
- if (!lifetime) {
367
- lifetime = new AbortController();
368
- this.lifetimes.set(sessionId, lifetime);
369
- }
370
- return lifetime;
371
- }
372
-
373
- async connect(agent, options = {}) {
374
- this.close(agent.session.id);
375
- const origin = String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "");
376
- const modelDirectory = await this.modelDirectory(agent);
377
- // A conversation the phone asked for registers against the session it already
378
- // opened, so the bridge binds that one instead of minting a second pairing.
379
- const bridgeSessionId = typeof options.bridgeSessionId === "string" ? options.bridgeSessionId : "";
380
- // A reconnect must not consume a pairing code or add a device: the phone that
381
- // already owns this conversation keeps owning it.
382
- const reconnecting = options.reconnecting === true;
383
- const response = await fetch(`${origin}/api/local/dsh-desktop/register`, {
384
- method: "POST",
385
- headers: { "content-type": "application/json" },
386
- body: JSON.stringify({
387
- sessionId: agent.session.id,
388
- cwd: agent.session.header.cwd,
389
- title: agent.session.header.title,
390
- provider: agent.options.provider,
391
- model: agent.options.model,
392
- modelDirectory,
393
- integrationVersion: INTEGRATION_VERSION,
394
- ...(bridgeSessionId ? { bridgeSessionId } : {}),
395
- ...(reconnecting ? { reconnect: true } : {}),
396
- }),
397
- });
398
- const registration = await readResponse(response);
399
- const state = {
400
- agent,
401
- origin,
402
- channel: registration.channel,
403
- controller: new AbortController(),
404
- lifetime: this.lifetimeFor(agent.session.id),
405
- cursor: 0,
406
- pendingEvents: [],
407
- phoneMessageIds: new Set(),
408
- // rpc ids this phone already answered, so DSH's own "resolved" echo is
409
- // not forwarded back and rendered as a second, duplicate resolution.
410
- answered: new Set(),
411
- eventTimer: null,
412
- flushing: false,
413
- retryPending: false,
414
- };
415
- this.bySession.set(agent.session.id, state);
416
- void this.poll(state);
417
- void this.watchInteractions(state);
418
- return registration;
419
- }
420
-
421
- /**
422
- * Re-register after the bridge forgot this channel.
423
- *
424
- * A bridge restart, a crash, or a replaced channel all look the same from here:
425
- * every call 401/404/409. Before this, that state was permanent — the only fix
426
- * was walking back to the computer and running /phone again — so the agent looks
427
- * dead from the phone while the desktop is perfectly healthy. Reconnecting keeps
428
- * the same DSH conversation and the same bridge session.
429
- *
430
- * There is deliberately no attempt cap. Stopping the bridge by hand (安全停止) and
431
- * starting it again is a human-scale pause that easily outlives a minute, and giving
432
- * up then left the conversation dead until someone walked back to the desktop. The
433
- * only bound is the interval, so a bridge that stays down is polled at most every
434
- * `RECONNECT_MAX_MS`, and disposing the conversation still stops the loop.
435
- */
436
- async ensureConnection(state) {
437
- const lifetime = state.lifetime ?? this.lifetimeFor(state.agent.session.id);
438
- if (lifetime.signal.aborted) return false;
439
- if (state.reconnecting) return state.reconnecting;
440
- state.reconnecting = (async () => {
441
- let delay = 0;
442
- let attempt = 0;
443
- while (!lifetime.signal.aborted) {
444
- // First attempt is immediate (a bridge restart is usually already over);
445
- // later ones back off so a permanently dead bridge is not hammered.
446
- if (delay > 0) await sleep(delay, lifetime.signal);
447
- delay = Math.min(Math.max(delay * 2, this.reconnectMinMs), this.reconnectMaxMs);
448
- if (lifetime.signal.aborted) return false;
449
- attempt += 1;
450
- try {
451
- await this.connect(state.agent, { reconnecting: true });
452
- this.ctx.logger.warn?.(`AgentBridge: reconnected "${state.agent.session.header.title ?? state.agent.session.id}" after the bridge forgot the channel (attempt ${attempt})`);
453
- return true;
454
- } catch (error) {
455
- // One line per attempt would bury the desktop log during a long outage.
456
- if (attempt === 1 || attempt % 10 === 0) {
457
- this.ctx.logger.warn?.(`AgentBridge reconnect attempt ${attempt} failed: ${textFromError(error)} (still retrying)`);
458
- }
459
- }
460
- }
461
- return false;
462
- })().finally(() => { state.reconnecting = null; });
463
- return state.reconnecting;
464
- }
465
- // Interaction retries live on the *lifetime*, not on the channel state. A reconnect
466
- // (or a dropped channel) throws the state away; a question that failed to cross the
467
- // wire must survive that, otherwise the phone sees the card a second after the
468
- // desktop — or not at all, which is the bug this queue removes.
469
- #interactionScope(sessionId) {
470
- let scope = this.interactionScopes.get(sessionId);
471
- if (!scope) {
472
- scope = { queue: [], draining: false };
473
- this.interactionScopes.set(sessionId, scope);
474
- }
475
- return scope;
476
- }
477
-
478
- // Questions and approvals never reach the session event log with an
479
- // answerable id, so they are read from DSH's own client stream and answered
480
- // through `apiProxy.respond`. Same seam the desktop window uses, which is what
481
- // lets a phone answer a question the desktop is also showing.
482
- async watchInteractions(state) {
483
- const events = this.ctx.apiProxy?.events;
484
- if (typeof events?.mux !== "function") return;
485
- const sessionId = state.agent.session.id;
486
- const scope = this.#interactionScope(sessionId);
487
- // Cards that failed before this channel existed are still owed to the phone.
488
- void this.#drainInteractions(state, scope, sessionId);
489
- try {
490
- for await (const envelope of events.mux({}, state.controller.signal)) {
491
- if (state.controller.signal.aborted) return;
492
- const record = interactionRecord(envelope, sessionId);
493
- if (!record) continue;
494
- if (this.#claimEcho(state, record)) continue;
495
- scope.queue.push(record);
496
- void this.#drainInteractions(state, scope, sessionId);
497
- }
498
- } catch (error) {
499
- if (state.controller.signal.aborted) return;
500
- if (isStaleChannel(error)) {
501
- await this.ensureConnection(state);
502
- return;
503
- }
504
- this.ctx.logger.warn(`AgentBridge interaction stream failed: ${textFromError(error)}`);
505
- }
506
- }
507
-
508
- async #drainInteractions(state, scope, sessionId) {
509
- if (scope.draining) return;
510
- scope.draining = true;
511
- try {
512
- while (scope.queue.length > 0) {
513
- // Always post through whatever channel owns the conversation right now:
514
- // a reconnect replaced `state`, and the new channel is the only one that
515
- // the bridge still knows.
516
- const current = this.bySession.get(sessionId);
517
- if (!current || current.controller.signal.aborted) return;
518
- try {
519
- await this.postInteractions(current, scope.queue[0]);
520
- scope.queue.shift();
521
- } catch (error) {
522
- if (this.bySession.get(sessionId) !== current) return; // replaced; the new drain takes over
523
- if (isStaleChannel(error)) {
524
- await this.ensureConnection(current);
525
- return; // the new state's watchInteractions drains this scope
526
- }
527
- // Keep the failed card at the head and retry it: losing it is the bug
528
- // this queue exists to remove.
529
- this.ctx.logger.warn(`AgentBridge interaction sync failed: ${textFromError(error)} (kept in the queue)`);
530
- await sleep(1_000, current.controller.signal);
531
- }
532
- }
533
- } finally {
534
- scope.draining = false;
535
- // A newer channel may have taken over while we were waiting; whoever owns
536
- // the conversation now finishes the queue.
537
- if (scope.queue.length > 0 && this.interactionScopes.has(sessionId)) {
538
- const current = this.bySession.get(sessionId);
539
- if (current) void this.#drainInteractions(current, scope, sessionId);
540
- }
541
- }
542
- }
543
-
544
- // Drop the resolution echo of an interaction this phone answered itself.
545
- #claimEcho(state, record) {
546
- if (record.kind === "question-resolved" && state.answered.has(record.requestId)) {
547
- state.answered.delete(record.requestId);
548
- return true;
549
- }
550
- if (record.kind === "approval-resolved" && state.answered.has(`${APPROVAL_PREFIX}${record.dshApprovalId}`)) {
551
- state.answered.delete(`${APPROVAL_PREFIX}${record.dshApprovalId}`);
552
- return true;
553
- }
554
- return false;
555
- }
556
-
557
- async postInteractions(state, record) {
558
- if (!state.channel.interactionsPath) return;
559
- const response = await fetch(`${state.origin}${state.channel.interactionsPath}`, {
560
- method: "POST",
561
- headers: {
562
- authorization: `Bearer ${state.channel.token}`,
563
- "content-type": "application/json",
564
- },
565
- body: JSON.stringify({ interactions: [record] }),
566
- signal: state.controller.signal,
567
- });
568
- await readResponse(response);
569
- }
570
-
571
- async respond(rpcId, result) {
572
- if (typeof this.ctx.apiProxy?.respond !== "function") throw new Error("This DSH Desktop build cannot answer questions from the phone");
573
- return await this.ctx.apiProxy.respond({ type: "client-response", rpcId, result });
574
- }
575
-
576
- async modelDirectory(agent) {
577
- const current = selectionFromAgent(agent);
578
- try {
579
- const response = await this.ctx.apiProxy.sessions.models({
580
- rpcId: randomUUID(),
581
- payload: { sessionId: agent.session.id },
582
- });
583
- const result = response?.result;
584
- if (!result?.ok) {
585
- if (result?.error?.code === "session-not-found") {
586
- return await this.hostModelDirectory(current, result.error.message);
587
- }
588
- throw new Error(result?.error?.message || "DSH Desktop did not provide its model directory");
589
- }
590
- return result.value;
591
- } catch (error) {
592
- return {
593
- current,
594
- routable: false,
595
- groups: [],
596
- failures: [{ id: "dsh-model-directory", name: "DSH Desktop", message: textFromError(error) }],
597
- };
598
- }
599
- }
600
-
601
- async hostModelDirectory(current, sessionError) {
602
- const response = await this.ctx.apiProxy.llm.models({ rpcId: randomUUID(), payload: {} });
603
- const result = response?.result;
604
- if (!result?.ok) throw new Error(result?.error?.message || "DSH Desktop did not provide its host model directory");
605
- return compactModelDirectory(result.value, current, [{
606
- id: "dsh-session-models",
607
- name: "DSH Desktop",
608
- message: `当前 UI 会话不在 session.models 注册表中,已改用 DSH 全局模型目录:${sessionError}`,
609
- }]);
610
- }
611
-
612
- liveModelSelection(agent) {
613
- const existing = this.liveModelSelections.get(agent);
614
- if (existing) return existing;
615
- const selection = { current: selectionFromAgent(agent), assembled: undefined };
616
- agent.ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
617
- const selected = selection.current;
618
- const assembled = await next();
619
- selection.assembled = selected;
620
- if (!selected) return assembled;
621
- return { ...assembled, variables: { ...assembled.variables, provider: selected.provider, model: selected.model } };
622
- });
623
- agent.ctx.on("agent/request", async (_payload, next) => {
624
- const resolved = await next();
625
- const selected = selection.assembled;
626
- if (!selected) return resolved;
627
- const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved;
628
- return {
629
- ...withoutInheritedEffort,
630
- provider: selected.provider,
631
- model: selected.model,
632
- ...(selected.reasoningEffort ? { reasoningEffort: selected.reasoningEffort } : {}),
633
- };
634
- });
635
- this.liveModelSelections.set(agent, selection);
636
- return selection;
637
- }
638
-
639
- async selectModel(agent, requested) {
640
- const response = await this.ctx.apiProxy.sessions.selectModel({
641
- rpcId: randomUUID(),
642
- payload: { sessionId: agent.session.id, ...requested },
643
- });
644
- const result = response?.result;
645
- if (result?.ok) return result.value.selected;
646
- if (result?.error?.code !== "session-not-found") {
647
- throw new Error(result?.error?.message || "DSH Desktop rejected the model selection");
648
- }
649
- const resolved = await this.ctx.llm.resolveCallConfig(requested);
650
- const selected = {
651
- provider: resolved.provider,
652
- model: resolved.model,
653
- ...(resolved.reasoningEffort ? { reasoningEffort: resolved.reasoningEffort } : {}),
654
- };
655
- this.liveModelSelection(agent).current = selected;
656
- return selected;
657
- }
658
-
659
- async reportCommandResult(state, requestId, result) {
660
- const response = await fetch(`${state.origin}${state.channel.resultsPath}`, {
661
- method: "POST",
662
- headers: {
663
- authorization: `Bearer ${state.channel.token}`,
664
- "content-type": "application/json",
665
- },
666
- body: JSON.stringify({ requestId, result }),
667
- signal: state.controller.signal,
668
- });
669
- await readResponse(response);
670
- }
671
-
672
- /**
673
- * Open a new conversation inside this desktop app and hand it to the phone.
674
- *
675
- * The conversation has to be a real DSH session, so it is created through the
676
- * agent service rather than faked in the bridge. Registering it against the
677
- * bridge session the phone already opened is what resolves the phone's create
678
- * call; if anything here fails the reason travels back as the command result.
679
- */
680
- async createSession(state, command) {
681
- try {
682
- // Read defensively: a build that does not inject `agents` throws on the bare
683
- // property access, and that raw Cordis error was all the phone ever saw. The
684
- // try/catch keeps the explanatory error reachable in that case too.
685
- let service = null;
686
- try {
687
- service = this.ctx.agents ?? null;
688
- } catch {
689
- service = null;
690
- }
691
- const create = typeof service?.create === "function" ? service.create.bind(service) : null;
692
- if (!create) throw new Error("这个 DSH Desktop 版本不支持从手机新建会话(缺少 ctx.agents.create)");
693
- const cwd = typeof command.cwd === "string" && command.cwd ? command.cwd : state.agent.session.header.cwd;
694
- if (!cwd) throw new Error("这个会话没有项目目录,无法新建");
695
- const sessionId = `session-${randomUUID()}`;
696
- const options = state.agent.options ?? {};
697
- const handle = await create({
698
- sessionId,
699
- meta: { cwd },
700
- ...(options.provider && options.model
701
- ? { agentOptions: { ...options, provider: options.provider, model: options.model } }
702
- : {}),
703
- });
704
- const agent = handle?.agent;
705
- if (!agent) throw new Error("DSH Desktop 没有返回新建的会话");
706
- await this.connect(agent, { bridgeSessionId: command.bridgeSessionId });
707
- await this.reportCommandResult(state, command.requestId, { ok: true, sessionId: agent.session.id });
708
- } catch (error) {
709
- await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) }).catch(() => undefined);
710
- }
711
- }
712
-
713
- async answerQuestion(state, command) {
714
- const cancelled = command.kind === "cancel-question";
715
- const answers = Array.isArray(command.answers) ? command.answers : [];
716
- // Claim the rpc id before answering: DSH broadcasts `question/resolved`
717
- // while `respond()` is still settling, and the echo must not be forwarded
718
- // as a second resolution for this same card.
719
- state.answered.add(command.rpcId);
720
- try {
721
- const receipt = await this.respond(command.rpcId, cancelled
722
- ? { ok: false, error: { code: "cancelled", message: "the user skipped the question" } }
723
- : { ok: true, value: { sessionId: state.agent.session.id, answer: { answers } } });
724
- if (!receipt?.accepted) {
725
- state.answered.delete(command.rpcId);
726
- await this.reportCommandResult(state, command.requestId, {
727
- ok: false,
728
- error: `DSH Desktop did not accept this answer (${receipt?.reason ?? "unknown"})`,
729
- });
730
- return;
731
- }
732
- await this.reportCommandResult(state, command.requestId, { ok: true });
733
- } catch (error) {
734
- state.answered.delete(command.rpcId);
735
- await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
736
- }
737
- }
738
-
739
- async answerApproval(state, command) {
740
- const key = `${APPROVAL_PREFIX}${command.dshApprovalId}`;
741
- state.answered.add(key);
742
- try {
743
- const receipt = await this.respond(command.rpcId, {
744
- ok: true,
745
- value: {
746
- sessionId: state.agent.session.id,
747
- approvalId: command.dshApprovalId,
748
- outcome: command.outcome === "allowed-once" ? "allowed-once" : "rejected",
749
- },
750
- });
751
- if (!receipt?.accepted) {
752
- state.answered.delete(key);
753
- await this.reportCommandResult(state, command.requestId, {
754
- ok: false,
755
- error: `DSH Desktop did not accept this decision (${receipt?.reason ?? "unknown"})`,
756
- });
757
- return;
758
- }
759
- await this.reportCommandResult(state, command.requestId, { ok: true });
760
- } catch (error) {
761
- state.answered.delete(key);
762
- await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
763
- }
764
- }
765
-
766
- /** Tear the channel down; the conversation itself lives on (a reconnect reuses it). */
767
- close(sessionId) {
768
- const state = this.bySession.get(sessionId);
769
- if (!state) return;
770
- state.controller.abort();
771
- if (state.eventTimer) clearTimeout(state.eventTimer);
772
- this.bySession.delete(sessionId);
773
- }
774
-
775
- /** The desktop let go of the conversation: stop every loop, including reconnect. */
776
- dispose(sessionId) {
777
- this.lifetimes.get(sessionId)?.abort();
778
- this.lifetimes.delete(sessionId);
779
- // A disposed conversation can no longer answer its own questions, so the queue
780
- // that would deliver them goes with it.
781
- this.interactionScopes.delete(sessionId);
782
- this.close(sessionId);
783
- }
784
-
785
- captureEvent(session, event) {
786
- const state = this.bySession.get(session.id);
787
- if (!state || state.controller.signal.aborted) return;
788
- const origin = event.type === "user/message" && state.phoneMessageIds.delete(event.data?.id)
789
- ? "phone"
790
- : "desktop";
791
- // Shrink before queueing: a giant event wedges the channel if it reaches the
792
- // wire inside a rejected batch, and then every later flush replays it.
793
- state.pendingEvents.push({ event: shrinkEventForWire(event), origin });
794
- this.scheduleFlush(state);
795
- }
796
-
797
- // Only one batch may be in flight at a time. Overlapping flushes used to let a
798
- // newer batch overtake an older one, which reordered a turn's streamed text on
799
- // the phone and made the bridge treat the older batch as already seen.
800
- scheduleFlush(state) {
801
- if (state.flushing || state.retryPending || state.eventTimer || state.controller.signal.aborted) return;
802
- const delay = state.pendingEvents.length >= 50 ? 0 : EVENT_BATCH_DELAY_MS;
803
- state.eventTimer = setTimeout(() => {
804
- state.eventTimer = null;
805
- void this.flushEvents(state);
806
- }, delay);
807
- }
808
-
809
- async flushEvents(state) {
810
- if (state.flushing || state.retryPending || state.controller.signal.aborted || state.pendingEvents.length === 0) return;
811
- state.flushing = true;
812
- let failure = null;
813
- // One batch per POST, chosen by byte budget as well as item count: the bridge
814
- // refuses a whole batch that overruns its limit, and a rejected batch is replayed
815
- // in full on the next flush — so an oversized event wedged the channel behind
816
- // itself in an endless `Request body is too large` loop. Each item here was
817
- // already shrunk at capture time, so a batch under the budget always gets through.
818
- while (state.pendingEvents.length > 0 && !state.controller.signal.aborted && !failure) {
819
- const batch = [];
820
- let bytes = 12; // `{"events":[`
821
- for (let count = 0; count < EVENT_MAX_ITEMS && state.pendingEvents.length > 0; count += 1) {
822
- const item = state.pendingEvents.shift();
823
- const itemBytes = JSON.stringify(item).length + 1;
824
- if (bytes + itemBytes > EVENT_POST_BUDGET_BYTES && batch.length > 0) {
825
- state.pendingEvents.unshift(item);
826
- break;
827
- }
828
- batch.push(item);
829
- bytes += itemBytes;
830
- }
831
- // should not happen: items are shrunk at capture time; a lone item over the
832
- // budget would wedge the loop, so send it as-is and let the bridge's own cap
833
- // (1 MB, above the per-item budget) be the safety net.
834
- if (batch.length === 0) {
835
- batch.push(state.pendingEvents.shift());
836
- }
837
- let failed = null;
838
- try {
839
- const response = await fetch(`${state.origin}${state.channel.eventsPath}`, {
840
- method: "POST",
841
- headers: {
842
- authorization: `Bearer ${state.channel.token}`,
843
- "content-type": "application/json",
844
- },
845
- body: JSON.stringify({ events: batch }),
846
- signal: state.controller.signal,
847
- });
848
- await readResponse(response);
849
- } catch (error) {
850
- failed = error;
851
- state.pendingEvents.unshift(...batch);
852
- }
853
- if (failed) {
854
- failure = failed;
855
- break;
856
- }
857
- if (state.controller.signal.aborted) break;
858
- }
859
- state.flushing = false;
860
- if (state.controller.signal.aborted) return;
861
-
862
- if (failure && isStaleChannel(failure)) {
863
- await this.ensureConnection(state);
864
- return;
865
- }
866
- if (failure) {
867
- this.ctx.logger.warn(`AgentBridge event sync failed: ${textFromError(failure)}`);
868
- // Hold everything back until the failed batch has been retried, so the
869
- // bridge never receives a newer batch ahead of an older one.
870
- state.retryPending = true;
871
- await sleep(1_000, state.controller.signal);
872
- state.retryPending = false;
873
- if (!state.controller.signal.aborted) void this.flushEvents(state);
874
- return;
875
- }
876
- if (state.pendingEvents.length) this.scheduleFlush(state);
877
- }
878
-
879
- async poll(state) {
880
- while (!state.controller.signal.aborted) {
881
- try {
882
- const response = await fetch(`${state.origin}${state.channel.pollPath}?after=${state.cursor}`, {
883
- headers: { authorization: `Bearer ${state.channel.token}` },
884
- signal: state.controller.signal,
885
- });
886
- const body = await readResponse(response);
887
- for (const command of body.commands || []) {
888
- if (command.kind === "message") {
889
- const message = createUserMessage(command.text);
890
- state.phoneMessageIds.add(message.id);
891
- state.agent.followup(message);
892
- } else if (command.kind === "cancel") {
893
- state.agent.cancel({ kind: "user" }, { keepInbox: true });
894
- } else if (command.kind === "select-model") {
895
- try {
896
- const selected = await this.selectModel(state.agent, {
897
- provider: command.selection?.provider,
898
- model: command.selection?.model,
899
- ...(command.selection?.reasoningEffort ? { reasoningEffort: command.selection.reasoningEffort } : {}),
900
- });
901
- await this.reportCommandResult(state, command.requestId, { ok: true, selected });
902
- } catch (error) {
903
- await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
904
- }
905
- } else if (command.kind === "answer-question" || command.kind === "cancel-question") {
906
- await this.answerQuestion(state, command);
907
- } else if (command.kind === "create-session") {
908
- await this.createSession(state, command);
909
- } else if (command.kind === "answer-approval") {
910
- await this.answerApproval(state, command);
911
- }
912
- state.cursor = Math.max(state.cursor, command.seq);
913
- }
914
- } catch (error) {
915
- if (state.controller.signal.aborted) return;
916
- if (isStaleChannel(error)) {
917
- await this.ensureConnection(state);
918
- return;
919
- }
920
- this.ctx.logger.warn(`AgentBridge command polling failed: ${textFromError(error)}`);
921
- }
922
- await sleep(POLL_DELAY_MS, state.controller.signal);
923
- }
924
- }
925
- }
926
-
927
- function apply(ctx) {
928
- const connections = new PhoneConnections(ctx);
929
- ctx.commands.register({
930
- name: "phone",
931
- description: "pair this exact DSH Desktop conversation with a phone",
932
- recordInput: false,
933
- handler: async ({ agent }) => {
934
- if (!agent.session.header.cwd) {
935
- return { kind: "error", text: "当前会话没有项目目录,无法绑定手机。请先在项目文件夹中打开会话。" };
936
- }
937
- try {
938
- const registration = await connections.connect(agent);
939
- const model = [agent.options.provider, agent.options.model].filter(Boolean).join(" / ") || "当前 DSH 配置";
940
- return {
941
- kind: "success",
942
- text: [
943
- "手机接管二维码已生成(5 分钟内、仅可使用一次):",
944
- `![AgentBridge 手机二维码](${registration.qrImageUrl})`,
945
- registration.pairing.url,
946
- `项目:${registration.project.cwd}`,
947
- `会话:${agent.session.id}`,
948
- `模型:${model}`,
949
- ].join("\n\n"),
950
- };
951
- } catch (error) {
952
- const origin = String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "");
953
- return {
954
- kind: "error",
955
- text: isBridgeAbsent(error)
956
- ? bridgeSetupText(origin)
957
- : `无法连接 AgentBridge:${textFromError(error)}。请确认本机 ${origin} 正在运行。`,
958
- };
959
- }
960
- },
961
- });
962
-
963
- // Bring the bridge up in the background as soon as the plugin loads, so by the
964
- // time the user types /phone the local service is already there. Deliberately
965
- // not awaited: a slow spawn must never delay desktop startup, and every failure
966
- // is silent — /phone still prints the manual steps when nothing came up.
967
- void startBridge(String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "")).catch(() => {});
968
- }
969
-
970
- export { apply, inject, name };
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const name = "agentbridge-dsh-phone";
8
+ // `agents` is not optional: creating a conversation from the phone asks the agent
9
+ // service to open one, and touching a service that was not injected throws
10
+ // `cannot get property "agents" without inject` — which is what the phone showed
11
+ // as a failed "新建对话" instead of the friendly message below.
12
+ const inject = ["commands", "apiProxy", "llm", "agents"];
13
+ const DEFAULT_ORIGIN = "http://127.0.0.1:8787";
14
+ const POLL_DELAY_MS = 800;
15
+ const EVENT_BATCH_DELAY_MS = 120;
16
+ const APPROVAL_PREFIX = "approval:";
17
+ // The bridge accepts at most 1 MB per /events POST (readJson limit), and this batch
18
+ // carries a JSON wrapper on top of the events. 448 KB leaves headroom, and it is also
19
+ // the cap for a single shrunken event, so one giant tool output can never wedge the
20
+ // queue behind a batch the bridge would refuse.
21
+ const EVENT_POST_BUDGET_BYTES = 448 * 1024;
22
+ const EVENT_MAX_ITEMS = 200;
23
+ const EVENT_EVENT_BUDGET_BYTES = 384 * 1024;
24
+ // A string longer than this in one event is clipped before it crosses the wire: the
25
+ // phone renders a summary of tool output, not a faithful copy, and a clipped giant is
26
+ // better than a batch that the bridge rejects.
27
+ const EVENT_STRING_CLIP = 2_048;
28
+ // Bumped whenever the integration gains something the phone relies on. The bridge
29
+ // compares it with the version it needs, because this file is *copied* into the DSH
30
+ // profile: changing the repository does nothing until install:dsh-phone runs again.
31
+ const INTEGRATION_VERSION = 6;
32
+ // Reconnect pacing. The first attempt is immediate (a bridge restart is usually already
33
+ // over by the time the next poll fails), then it backs off to `RECONNECT_MAX_MS`.
34
+ const RECONNECT_MIN_MS = 1_000;
35
+ const RECONNECT_MAX_MS = 30_000;
36
+
37
+ function sleep(ms, signal) {
38
+ return new Promise((resolve) => {
39
+ if (signal.aborted) return resolve();
40
+ const timer = setTimeout(resolve, ms);
41
+ signal.addEventListener("abort", () => {
42
+ clearTimeout(timer);
43
+ resolve();
44
+ }, { once: true });
45
+ });
46
+ }
47
+
48
+ function textFromError(error) {
49
+ return error instanceof Error ? error.message : String(error);
50
+ }
51
+
52
+ /**
53
+ * Whether the bridge was simply not there.
54
+ *
55
+ * The distinction matters for the message the user sees: a refused connection
56
+ * means the plugin loaded fine and only the local bridge is missing, which is a
57
+ * setup step — while a 401 from a live bridge is a different problem entirely.
58
+ */
59
+ function isBridgeAbsent(error) {
60
+ const cause = error && typeof error === "object" ? error.cause?.code ?? "" : "";
61
+ return /ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|UND_ERR_CONNECT|fetch failed|socket hang up/i
62
+ .test(`${textFromError(error)} ${cause}`);
63
+ }
64
+
65
+ /** The setup steps a user needs when /phone finds nothing listening. */
66
+ function bridgeSetupText(origin) {
67
+ return [
68
+ `无法连接 AgentBridge 桥(${origin})。插件本身已经加载,缺的是电脑上这个本地服务。`,
69
+ "",
70
+ "手动起桥只要一条命令:",
71
+ "npx @chenacc/agentbridge",
72
+ "",
73
+ "想长期使用就装成全局命令:",
74
+ "npm install -g @chenacc/agentbridge",
75
+ "agentbridge phone --agent claude",
76
+ "",
77
+ `桥启动后再敲一次 /phone。桥不在默认端口的话,先设置环境变量 AGENTBRIDGE_ORIGIN,再重启 DSH Desktop。`,
78
+ ].join("\n");
79
+ }
80
+
81
+ const BRIDGE_PACKAGE = "@chenacc/agentbridge";
82
+ // Long enough for a detached server to bind its port on a slow disk, short
83
+ // enough that /phone still reads as a command rather than a hang.
84
+ const AUTOSTART_TIMEOUT_MS = 8_000;
85
+
86
+ /**
87
+ * Where the bridge's server entry lives on this machine, if it is installed.
88
+ *
89
+ * The plugin ships `@chenacc/agentbridge` as a dependency, so the normal answer
90
+ * comes from module resolution next to this file. `AGENTBRIDGE_BRIDGE_ENTRY`
91
+ * exists for tests and for unusual installs.
92
+ *
93
+ * The resolved manifest must live under a `node_modules` directory: without that
94
+ * check, Node's package self-reference resolves this repository's own root
95
+ * package as `@chenacc/agentbridge`, so a development checkout would start a
96
+ * second bridge from the source tree and steal port 8787 from the developer.
97
+ */
98
+ function bridgeServerEntry() {
99
+ if (process.env.AGENTBRIDGE_BRIDGE_ENTRY) return process.env.AGENTBRIDGE_BRIDGE_ENTRY;
100
+ try {
101
+ const resolved = fileURLToPath(import.meta.resolve(`${BRIDGE_PACKAGE}/package.json`));
102
+ if (!resolved.split(path.sep).includes("node_modules")) return null;
103
+ return path.join(path.dirname(resolved), "src", "server.js");
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+
109
+ async function bridgeIsReady(origin) {
110
+ try {
111
+ const response = await fetch(`${origin}/api/health`, { signal: AbortSignal.timeout(700) });
112
+ if (!response.ok) return false;
113
+ const body = await response.json().catch(() => null);
114
+ return body?.ok === true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Whether this process may start a bridge at all.
122
+ *
123
+ * A unit test must never spawn a server: node:test sets NODE_TEST_CONTEXT, and a
124
+ * bridge started there would bind a real port and outlive the run. An explicit
125
+ * AGENTBRIDGE_BRIDGE_ENTRY is the single way to opt back in, which is what the
126
+ * autostart test relies on.
127
+ */
128
+ function autoStartAllowed() {
129
+ if (process.env.AGENTBRIDGE_NO_AUTOSTART === "1") return false;
130
+ if (process.env.AGENTBRIDGE_BRIDGE_ENTRY) return true;
131
+ return process.env.NODE_TEST_CONTEXT === undefined;
132
+ }
133
+
134
+ /**
135
+ * Start the local bridge and wait until it answers.
136
+ *
137
+ * Returns true only once the health check passes, so the caller retries the real
138
+ * registration instead of trusting that a spawn means a working server. Every
139
+ * failure path is silent: the caller falls back to the manual setup text.
140
+ */
141
+ async function startBridge(origin) {
142
+ if (await bridgeIsReady(origin)) return true;
143
+ if (!autoStartAllowed()) return false;
144
+ const entry = bridgeServerEntry();
145
+ if (!entry || !existsSync(entry)) return false;
146
+
147
+ let port;
148
+ try {
149
+ port = new URL(origin).port || "8787";
150
+ } catch {
151
+ return false;
152
+ }
153
+
154
+ try {
155
+ // Loaded lazily: the plugin normally runs with a bridge already up, so the
156
+ // child-process machinery is dead weight on the common path.
157
+ const { spawn } = await import("node:child_process");
158
+ const child = spawn(process.execPath, [entry], {
159
+ // State gets its own directory: the bridge writes sessions, pairings and
160
+ // logs under AGENTBRIDGE_DATA_DIR, and dropping that inside the DSH data
161
+ // directory would mix two products' state in one place. The working
162
+ // directory stays the user's home so the bridge's default project is not
163
+ // some internal folder.
164
+ cwd: homedir(),
165
+ detached: true,
166
+ stdio: "ignore",
167
+ windowsHide: true,
168
+ env: {
169
+ ...process.env,
170
+ AGENTBRIDGE_PORT: process.env.AGENTBRIDGE_PORT || port,
171
+ AGENTBRIDGE_DATA_DIR: process.env.AGENTBRIDGE_DATA_DIR || path.join(homedir(), ".agentbridge"),
172
+ },
173
+ });
174
+ child.unref();
175
+ } catch {
176
+ return false;
177
+ }
178
+
179
+ const deadline = Date.now() + AUTOSTART_TIMEOUT_MS;
180
+ while (Date.now() < deadline) {
181
+ await new Promise((resolve) => setTimeout(resolve, 150));
182
+ if (await bridgeIsReady(origin)) return true;
183
+ }
184
+ return false;
185
+ }
186
+
187
+ function clipped(value, limit) {
188
+ return typeof value === "string" ? value.slice(0, limit) : "";
189
+ }
190
+
191
+ /**
192
+ * Bound one event's wire size.
193
+ *
194
+ * The bridge rejects a batch over its limit, and a rejected batch is replayed whole
195
+ * on the next flush — so an event that is too big by itself wedges the channel: the
196
+ * same batch fails again and again, nothing ever advances, and the phone goes blind.
197
+ * That loop is what used to fill the desktop log with `Request body is too large`.
198
+ *
199
+ * Clipping long strings keeps the event useful (the phone only ever shows a summary
200
+ * of tool output); the last resort is a stub carrying just the type, because a queued
201
+ * stub is progress while a queued giant is not.
202
+ */
203
+ function shrinkEventForWire(event) {
204
+ if (JSON.stringify(event).length <= EVENT_EVENT_BUDGET_BYTES) return event;
205
+ const copy = { ...event };
206
+ if (copy.data !== undefined && typeof copy.data === "object") copy.data = { ...copy.data };
207
+ const clipStrings = (value, limit) => {
208
+ if (typeof value === "string") return value.length > limit ? `${value.slice(0, limit)}…[clipped]` : value;
209
+ if (Array.isArray(value)) return value.map((item) => clipStrings(item, limit));
210
+ if (value && typeof value === "object") {
211
+ const result = {};
212
+ for (const [key, child] of Object.entries(value)) result[key] = clipStrings(child, limit);
213
+ return result;
214
+ }
215
+ return value;
216
+ };
217
+ copy.data = clipStrings(copy.data, EVENT_STRING_CLIP);
218
+ if (JSON.stringify(copy).length <= EVENT_EVENT_BUDGET_BYTES) return copy;
219
+ // Pathological: still over the budget after clipping. The phone only needs the
220
+ // event's type to keep the transcript consistent; the payload is display-only.
221
+ return { type: copy.type, time: copy.time, data: { note: "事件过大,手机侧省略了内容" } };
222
+ }
223
+
224
+ /**
225
+ * Project one DSH mux frame onto the interaction record the bridge ingests.
226
+ *
227
+ * Only this session's frames matter, and only the four interaction payloads:
228
+ * everything else on the stream is ordinary conversation traffic that already
229
+ * travels on the event channel. Fields are copied out one by one because the
230
+ * frame carries live DSH objects that must not be handed to another process.
231
+ */
232
+ export function interactionRecord(envelope, sessionId) {
233
+ const payload = envelope?.payload;
234
+ const rpcId = typeof envelope?.rpcId === "string" ? envelope.rpcId : "";
235
+ if (!payload || !rpcId || payload.sessionId !== sessionId) return null;
236
+ if (payload.type === "question/requested") {
237
+ const questions = Array.isArray(payload.questions) ? payload.questions : [];
238
+ const projected = questions.slice(0, 10).flatMap((question, index) => {
239
+ if (!question || typeof question !== "object") return [];
240
+ const questionText = clipped(question.question, 4_000);
241
+ if (!questionText) return [];
242
+ const options = Array.isArray(question.options) ? question.options.slice(0, 25).flatMap((option) => {
243
+ const label = clipped(option?.label, 200);
244
+ if (!label) return [];
245
+ const description = clipped(option?.description, 500);
246
+ return [{ label, ...(description ? { description } : {}) }];
247
+ }) : [];
248
+ const header = clipped(question.header, 200);
249
+ return [{
250
+ id: clipped(question.id, 100) || `q${index + 1}`,
251
+ question: questionText,
252
+ ...(header ? { header } : {}),
253
+ ...(options.length ? { options } : {}),
254
+ ...(question.multiSelect === true ? { multiSelect: true } : {}),
255
+ }];
256
+ });
257
+ if (!projected.length) return null;
258
+ return { kind: "question-requested", requestId: rpcId, questions: projected };
259
+ }
260
+ if (payload.type === "approval/requested") {
261
+ return {
262
+ kind: "approval-requested",
263
+ requestId: rpcId,
264
+ dshApprovalId: clipped(payload.approvalId, 200),
265
+ toolName: clipped(payload.toolName, 200) || "tool",
266
+ ...(payload.reason ? { reason: clipped(payload.reason, 2_000) } : {}),
267
+ ...(payload.callId ? { callId: clipped(payload.callId, 200) } : {}),
268
+ };
269
+ }
270
+ if (payload.type === "question/resolved") {
271
+ return { kind: "question-resolved", requestId: clipped(payload.questionRpcId, 200), outcome: clipped(payload.outcome, 40) };
272
+ }
273
+ if (payload.type === "approval/resolved") {
274
+ return {
275
+ kind: "approval-resolved",
276
+ requestId: "",
277
+ dshApprovalId: clipped(payload.approvalId, 200),
278
+ outcome: clipped(payload.outcome, 40),
279
+ };
280
+ }
281
+ return null;
282
+ }
283
+
284
+ function deepFreeze(value) {
285
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
286
+ for (const child of Object.values(value)) deepFreeze(child);
287
+ return Object.freeze(value);
288
+ }
289
+
290
+ function createUserMessage(text) {
291
+ return deepFreeze({
292
+ id: randomUUID(),
293
+ role: "user",
294
+ content: [{ type: "text", text }],
295
+ source: { kind: "user" },
296
+ });
297
+ }
298
+
299
+ function selectionFromAgent(agent) {
300
+ let logged;
301
+ try {
302
+ logged = agent.session.requestHeader?.()?.config;
303
+ } catch {
304
+ logged = undefined;
305
+ }
306
+ const provider = agent.options?.provider || logged?.provider;
307
+ const model = agent.options?.model || logged?.model;
308
+ if (!provider || !model) return null;
309
+ const reasoningEffort = agent.options?.reasoningEffort || logged?.reasoningEffort;
310
+ return { provider, model, ...(reasoningEffort ? { reasoningEffort } : {}) };
311
+ }
312
+
313
+ function compactModelDirectory(value, current, extraFailures = []) {
314
+ const groups = Array.isArray(value?.groups) ? value.groups.slice(0, 30).map((group) => ({
315
+ id: group.id,
316
+ name: group.name,
317
+ models: Array.isArray(group.models) ? group.models.slice(0, 200).map((model) => ({
318
+ id: model.id,
319
+ name: model.name,
320
+ ...(model.reasoning ? { reasoning: {
321
+ efforts: Array.isArray(model.reasoning.efforts) ? model.reasoning.efforts.slice(0, 20) : [],
322
+ ...(model.reasoning.defaultEffort ? { defaultEffort: model.reasoning.defaultEffort } : {}),
323
+ } } : {}),
324
+ })) : [],
325
+ })) : [];
326
+ const failures = [...extraFailures, ...(Array.isArray(value?.failures) ? value.failures : [])].slice(0, 30);
327
+ return {
328
+ current,
329
+ routable: current ? groups.some((group) => group.id === current.provider) : false,
330
+ groups,
331
+ failures,
332
+ };
333
+ }
334
+
335
+ async function readResponse(response) {
336
+ const body = await response.json().catch(() => ({}));
337
+ if (!response.ok) {
338
+ // The status matters to the caller: 401/403/404/409 mean "this channel no
339
+ // longer exists", which is the signal to re-register instead of retrying.
340
+ const error = new Error(body.error || `AgentBridge request failed (${response.status})`);
341
+ error.status = response.status;
342
+ throw error;
343
+ }
344
+ return body;
345
+ }
346
+
347
+ function isStaleChannel(error) {
348
+ return [401, 403, 404, 409, 410].includes(Number(error?.status));
349
+ }
350
+
351
+ export class PhoneConnections {
352
+ constructor(ctx, options = {}) {
353
+ this.ctx = ctx;
354
+ this.bySession = new Map();
355
+ // One lifetime per conversation, independent of any single channel connection.
356
+ // A reconnect tears the connection down (aborting its controller) *before* it knows
357
+ // whether the bridge is back, so a retry loop tied to that controller could only
358
+ // ever run one attempt — the exact bug that left a conversation dead after a manual
359
+ // bridge restart. Only the desktop disposing the conversation ends a lifetime.
360
+ this.lifetimes = new Map();
361
+ this.reconnectMinMs = options.reconnectMinMs ?? RECONNECT_MIN_MS;
362
+ this.reconnectMaxMs = options.reconnectMaxMs ?? RECONNECT_MAX_MS;
363
+ // Failed interaction cards survive a reconnect, so they are keyed to the
364
+ // conversation, not to the channel that tried to carry them.
365
+ this.interactionScopes = new Map();
366
+ this.liveModelSelections = new WeakMap();
367
+ this.ctx.on("session/event", (session, event) => this.captureEvent(session, event));
368
+ this.ctx.on("agent/disposed", ({ agent }) => this.dispose(agent.session.id));
369
+ }
370
+
371
+ lifetimeFor(sessionId) {
372
+ let lifetime = this.lifetimes.get(sessionId);
373
+ if (!lifetime) {
374
+ lifetime = new AbortController();
375
+ this.lifetimes.set(sessionId, lifetime);
376
+ }
377
+ return lifetime;
378
+ }
379
+
380
+ async connect(agent, options = {}) {
381
+ this.close(agent.session.id);
382
+ const origin = String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "");
383
+ const modelDirectory = await this.modelDirectory(agent);
384
+ // A conversation the phone asked for registers against the session it already
385
+ // opened, so the bridge binds that one instead of minting a second pairing.
386
+ const bridgeSessionId = typeof options.bridgeSessionId === "string" ? options.bridgeSessionId : "";
387
+ // A reconnect must not consume a pairing code or add a device: the phone that
388
+ // already owns this conversation keeps owning it.
389
+ const reconnecting = options.reconnecting === true;
390
+ const response = await fetch(`${origin}/api/local/dsh-desktop/register`, {
391
+ method: "POST",
392
+ headers: { "content-type": "application/json" },
393
+ body: JSON.stringify({
394
+ sessionId: agent.session.id,
395
+ cwd: agent.session.header.cwd,
396
+ title: agent.session.header.title,
397
+ provider: agent.options.provider,
398
+ model: agent.options.model,
399
+ modelDirectory,
400
+ integrationVersion: INTEGRATION_VERSION,
401
+ ...(bridgeSessionId ? { bridgeSessionId } : {}),
402
+ ...(reconnecting ? { reconnect: true } : {}),
403
+ }),
404
+ });
405
+ const registration = await readResponse(response);
406
+ const state = {
407
+ agent,
408
+ origin,
409
+ channel: registration.channel,
410
+ controller: new AbortController(),
411
+ lifetime: this.lifetimeFor(agent.session.id),
412
+ cursor: 0,
413
+ pendingEvents: [],
414
+ phoneMessageIds: new Set(),
415
+ // rpc ids this phone already answered, so DSH's own "resolved" echo is
416
+ // not forwarded back and rendered as a second, duplicate resolution.
417
+ answered: new Set(),
418
+ eventTimer: null,
419
+ flushing: false,
420
+ retryPending: false,
421
+ };
422
+ this.bySession.set(agent.session.id, state);
423
+ void this.poll(state);
424
+ void this.watchInteractions(state);
425
+ return registration;
426
+ }
427
+
428
+ /**
429
+ * Re-register after the bridge forgot this channel.
430
+ *
431
+ * A bridge restart, a crash, or a replaced channel all look the same from here:
432
+ * every call 401/404/409. Before this, that state was permanent — the only fix
433
+ * was walking back to the computer and running /phone again — so the agent looks
434
+ * dead from the phone while the desktop is perfectly healthy. Reconnecting keeps
435
+ * the same DSH conversation and the same bridge session.
436
+ *
437
+ * There is deliberately no attempt cap. Stopping the bridge by hand (安全停止) and
438
+ * starting it again is a human-scale pause that easily outlives a minute, and giving
439
+ * up then left the conversation dead until someone walked back to the desktop. The
440
+ * only bound is the interval, so a bridge that stays down is polled at most every
441
+ * `RECONNECT_MAX_MS`, and disposing the conversation still stops the loop.
442
+ */
443
+ async ensureConnection(state) {
444
+ const lifetime = state.lifetime ?? this.lifetimeFor(state.agent.session.id);
445
+ if (lifetime.signal.aborted) return false;
446
+ if (state.reconnecting) return state.reconnecting;
447
+ state.reconnecting = (async () => {
448
+ let delay = 0;
449
+ let attempt = 0;
450
+ while (!lifetime.signal.aborted) {
451
+ // First attempt is immediate (a bridge restart is usually already over);
452
+ // later ones back off so a permanently dead bridge is not hammered.
453
+ if (delay > 0) await sleep(delay, lifetime.signal);
454
+ delay = Math.min(Math.max(delay * 2, this.reconnectMinMs), this.reconnectMaxMs);
455
+ if (lifetime.signal.aborted) return false;
456
+ attempt += 1;
457
+ try {
458
+ await this.connect(state.agent, { reconnecting: true });
459
+ this.ctx.logger.warn?.(`AgentBridge: reconnected "${state.agent.session.header.title ?? state.agent.session.id}" after the bridge forgot the channel (attempt ${attempt})`);
460
+ return true;
461
+ } catch (error) {
462
+ // One line per attempt would bury the desktop log during a long outage.
463
+ if (attempt === 1 || attempt % 10 === 0) {
464
+ this.ctx.logger.warn?.(`AgentBridge reconnect attempt ${attempt} failed: ${textFromError(error)} (still retrying)`);
465
+ }
466
+ }
467
+ }
468
+ return false;
469
+ })().finally(() => { state.reconnecting = null; });
470
+ return state.reconnecting;
471
+ }
472
+ // Interaction retries live on the *lifetime*, not on the channel state. A reconnect
473
+ // (or a dropped channel) throws the state away; a question that failed to cross the
474
+ // wire must survive that, otherwise the phone sees the card a second after the
475
+ // desktop — or not at all, which is the bug this queue removes.
476
+ #interactionScope(sessionId) {
477
+ let scope = this.interactionScopes.get(sessionId);
478
+ if (!scope) {
479
+ scope = { queue: [], draining: false };
480
+ this.interactionScopes.set(sessionId, scope);
481
+ }
482
+ return scope;
483
+ }
484
+
485
+ // Questions and approvals never reach the session event log with an
486
+ // answerable id, so they are read from DSH's own client stream and answered
487
+ // through `apiProxy.respond`. Same seam the desktop window uses, which is what
488
+ // lets a phone answer a question the desktop is also showing.
489
+ async watchInteractions(state) {
490
+ const events = this.ctx.apiProxy?.events;
491
+ if (typeof events?.mux !== "function") return;
492
+ const sessionId = state.agent.session.id;
493
+ const scope = this.#interactionScope(sessionId);
494
+ // Cards that failed before this channel existed are still owed to the phone.
495
+ void this.#drainInteractions(state, scope, sessionId);
496
+ try {
497
+ for await (const envelope of events.mux({}, state.controller.signal)) {
498
+ if (state.controller.signal.aborted) return;
499
+ const record = interactionRecord(envelope, sessionId);
500
+ if (!record) continue;
501
+ if (this.#claimEcho(state, record)) continue;
502
+ scope.queue.push(record);
503
+ void this.#drainInteractions(state, scope, sessionId);
504
+ }
505
+ } catch (error) {
506
+ if (state.controller.signal.aborted) return;
507
+ if (isStaleChannel(error)) {
508
+ await this.ensureConnection(state);
509
+ return;
510
+ }
511
+ this.ctx.logger.warn(`AgentBridge interaction stream failed: ${textFromError(error)}`);
512
+ }
513
+ }
514
+
515
+ async #drainInteractions(state, scope, sessionId) {
516
+ if (scope.draining) return;
517
+ scope.draining = true;
518
+ try {
519
+ while (scope.queue.length > 0) {
520
+ // Always post through whatever channel owns the conversation right now:
521
+ // a reconnect replaced `state`, and the new channel is the only one that
522
+ // the bridge still knows.
523
+ const current = this.bySession.get(sessionId);
524
+ if (!current || current.controller.signal.aborted) return;
525
+ try {
526
+ await this.postInteractions(current, scope.queue[0]);
527
+ scope.queue.shift();
528
+ } catch (error) {
529
+ if (this.bySession.get(sessionId) !== current) return; // replaced; the new drain takes over
530
+ if (isStaleChannel(error)) {
531
+ await this.ensureConnection(current);
532
+ return; // the new state's watchInteractions drains this scope
533
+ }
534
+ // Keep the failed card at the head and retry it: losing it is the bug
535
+ // this queue exists to remove.
536
+ this.ctx.logger.warn(`AgentBridge interaction sync failed: ${textFromError(error)} (kept in the queue)`);
537
+ await sleep(1_000, current.controller.signal);
538
+ }
539
+ }
540
+ } finally {
541
+ scope.draining = false;
542
+ // A newer channel may have taken over while we were waiting; whoever owns
543
+ // the conversation now finishes the queue.
544
+ if (scope.queue.length > 0 && this.interactionScopes.has(sessionId)) {
545
+ const current = this.bySession.get(sessionId);
546
+ if (current) void this.#drainInteractions(current, scope, sessionId);
547
+ }
548
+ }
549
+ }
550
+
551
+ // Drop the resolution echo of an interaction this phone answered itself.
552
+ #claimEcho(state, record) {
553
+ if (record.kind === "question-resolved" && state.answered.has(record.requestId)) {
554
+ state.answered.delete(record.requestId);
555
+ return true;
556
+ }
557
+ if (record.kind === "approval-resolved" && state.answered.has(`${APPROVAL_PREFIX}${record.dshApprovalId}`)) {
558
+ state.answered.delete(`${APPROVAL_PREFIX}${record.dshApprovalId}`);
559
+ return true;
560
+ }
561
+ return false;
562
+ }
563
+
564
+ async postInteractions(state, record) {
565
+ if (!state.channel.interactionsPath) return;
566
+ const response = await fetch(`${state.origin}${state.channel.interactionsPath}`, {
567
+ method: "POST",
568
+ headers: {
569
+ authorization: `Bearer ${state.channel.token}`,
570
+ "content-type": "application/json",
571
+ },
572
+ body: JSON.stringify({ interactions: [record] }),
573
+ signal: state.controller.signal,
574
+ });
575
+ await readResponse(response);
576
+ }
577
+
578
+ async respond(rpcId, result) {
579
+ if (typeof this.ctx.apiProxy?.respond !== "function") throw new Error("This DSH Desktop build cannot answer questions from the phone");
580
+ return await this.ctx.apiProxy.respond({ type: "client-response", rpcId, result });
581
+ }
582
+
583
+ async modelDirectory(agent) {
584
+ const current = selectionFromAgent(agent);
585
+ try {
586
+ const response = await this.ctx.apiProxy.sessions.models({
587
+ rpcId: randomUUID(),
588
+ payload: { sessionId: agent.session.id },
589
+ });
590
+ const result = response?.result;
591
+ if (!result?.ok) {
592
+ if (result?.error?.code === "session-not-found") {
593
+ return await this.hostModelDirectory(current, result.error.message);
594
+ }
595
+ throw new Error(result?.error?.message || "DSH Desktop did not provide its model directory");
596
+ }
597
+ return result.value;
598
+ } catch (error) {
599
+ return {
600
+ current,
601
+ routable: false,
602
+ groups: [],
603
+ failures: [{ id: "dsh-model-directory", name: "DSH Desktop", message: textFromError(error) }],
604
+ };
605
+ }
606
+ }
607
+
608
+ async hostModelDirectory(current, sessionError) {
609
+ const response = await this.ctx.apiProxy.llm.models({ rpcId: randomUUID(), payload: {} });
610
+ const result = response?.result;
611
+ if (!result?.ok) throw new Error(result?.error?.message || "DSH Desktop did not provide its host model directory");
612
+ return compactModelDirectory(result.value, current, [{
613
+ id: "dsh-session-models",
614
+ name: "DSH Desktop",
615
+ message: `当前 UI 会话不在 session.models 注册表中,已改用 DSH 全局模型目录:${sessionError}`,
616
+ }]);
617
+ }
618
+
619
+ liveModelSelection(agent) {
620
+ const existing = this.liveModelSelections.get(agent);
621
+ if (existing) return existing;
622
+ const selection = { current: selectionFromAgent(agent), assembled: undefined };
623
+ agent.ctx.on("system-prompt/assemble", async (_assembly, _context, next) => {
624
+ const selected = selection.current;
625
+ const assembled = await next();
626
+ selection.assembled = selected;
627
+ if (!selected) return assembled;
628
+ return { ...assembled, variables: { ...assembled.variables, provider: selected.provider, model: selected.model } };
629
+ });
630
+ agent.ctx.on("agent/request", async (_payload, next) => {
631
+ const resolved = await next();
632
+ const selected = selection.assembled;
633
+ if (!selected) return resolved;
634
+ const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved;
635
+ return {
636
+ ...withoutInheritedEffort,
637
+ provider: selected.provider,
638
+ model: selected.model,
639
+ ...(selected.reasoningEffort ? { reasoningEffort: selected.reasoningEffort } : {}),
640
+ };
641
+ });
642
+ this.liveModelSelections.set(agent, selection);
643
+ return selection;
644
+ }
645
+
646
+ async selectModel(agent, requested) {
647
+ const response = await this.ctx.apiProxy.sessions.selectModel({
648
+ rpcId: randomUUID(),
649
+ payload: { sessionId: agent.session.id, ...requested },
650
+ });
651
+ const result = response?.result;
652
+ if (result?.ok) return result.value.selected;
653
+ if (result?.error?.code !== "session-not-found") {
654
+ throw new Error(result?.error?.message || "DSH Desktop rejected the model selection");
655
+ }
656
+ const resolved = await this.ctx.llm.resolveCallConfig(requested);
657
+ const selected = {
658
+ provider: resolved.provider,
659
+ model: resolved.model,
660
+ ...(resolved.reasoningEffort ? { reasoningEffort: resolved.reasoningEffort } : {}),
661
+ };
662
+ this.liveModelSelection(agent).current = selected;
663
+ return selected;
664
+ }
665
+
666
+ async reportCommandResult(state, requestId, result) {
667
+ const response = await fetch(`${state.origin}${state.channel.resultsPath}`, {
668
+ method: "POST",
669
+ headers: {
670
+ authorization: `Bearer ${state.channel.token}`,
671
+ "content-type": "application/json",
672
+ },
673
+ body: JSON.stringify({ requestId, result }),
674
+ signal: state.controller.signal,
675
+ });
676
+ await readResponse(response);
677
+ }
678
+
679
+ /**
680
+ * Open a new conversation inside this desktop app and hand it to the phone.
681
+ *
682
+ * The conversation has to be a real DSH session, so it is created through the
683
+ * agent service rather than faked in the bridge. Registering it against the
684
+ * bridge session the phone already opened is what resolves the phone's create
685
+ * call; if anything here fails the reason travels back as the command result.
686
+ */
687
+ async createSession(state, command) {
688
+ try {
689
+ // Read defensively: a build that does not inject `agents` throws on the bare
690
+ // property access, and that raw Cordis error was all the phone ever saw. The
691
+ // try/catch keeps the explanatory error reachable in that case too.
692
+ let service = null;
693
+ try {
694
+ service = this.ctx.agents ?? null;
695
+ } catch {
696
+ service = null;
697
+ }
698
+ const create = typeof service?.create === "function" ? service.create.bind(service) : null;
699
+ if (!create) throw new Error("这个 DSH Desktop 版本不支持从手机新建会话(缺少 ctx.agents.create)");
700
+ const cwd = typeof command.cwd === "string" && command.cwd ? command.cwd : state.agent.session.header.cwd;
701
+ if (!cwd) throw new Error("这个会话没有项目目录,无法新建");
702
+ const sessionId = `session-${randomUUID()}`;
703
+ const options = state.agent.options ?? {};
704
+ const handle = await create({
705
+ sessionId,
706
+ meta: { cwd },
707
+ ...(options.provider && options.model
708
+ ? { agentOptions: { ...options, provider: options.provider, model: options.model } }
709
+ : {}),
710
+ });
711
+ const agent = handle?.agent;
712
+ if (!agent) throw new Error("DSH Desktop 没有返回新建的会话");
713
+ await this.connect(agent, { bridgeSessionId: command.bridgeSessionId });
714
+ await this.reportCommandResult(state, command.requestId, { ok: true, sessionId: agent.session.id });
715
+ } catch (error) {
716
+ await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) }).catch(() => undefined);
717
+ }
718
+ }
719
+
720
+ async answerQuestion(state, command) {
721
+ const cancelled = command.kind === "cancel-question";
722
+ const answers = Array.isArray(command.answers) ? command.answers : [];
723
+ // Claim the rpc id before answering: DSH broadcasts `question/resolved`
724
+ // while `respond()` is still settling, and the echo must not be forwarded
725
+ // as a second resolution for this same card.
726
+ state.answered.add(command.rpcId);
727
+ try {
728
+ const receipt = await this.respond(command.rpcId, cancelled
729
+ ? { ok: false, error: { code: "cancelled", message: "the user skipped the question" } }
730
+ : { ok: true, value: { sessionId: state.agent.session.id, answer: { answers } } });
731
+ if (!receipt?.accepted) {
732
+ state.answered.delete(command.rpcId);
733
+ await this.reportCommandResult(state, command.requestId, {
734
+ ok: false,
735
+ error: `DSH Desktop did not accept this answer (${receipt?.reason ?? "unknown"})`,
736
+ });
737
+ return;
738
+ }
739
+ await this.reportCommandResult(state, command.requestId, { ok: true });
740
+ } catch (error) {
741
+ state.answered.delete(command.rpcId);
742
+ await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
743
+ }
744
+ }
745
+
746
+ async answerApproval(state, command) {
747
+ const key = `${APPROVAL_PREFIX}${command.dshApprovalId}`;
748
+ state.answered.add(key);
749
+ try {
750
+ const receipt = await this.respond(command.rpcId, {
751
+ ok: true,
752
+ value: {
753
+ sessionId: state.agent.session.id,
754
+ approvalId: command.dshApprovalId,
755
+ outcome: command.outcome === "allowed-once" ? "allowed-once" : "rejected",
756
+ },
757
+ });
758
+ if (!receipt?.accepted) {
759
+ state.answered.delete(key);
760
+ await this.reportCommandResult(state, command.requestId, {
761
+ ok: false,
762
+ error: `DSH Desktop did not accept this decision (${receipt?.reason ?? "unknown"})`,
763
+ });
764
+ return;
765
+ }
766
+ await this.reportCommandResult(state, command.requestId, { ok: true });
767
+ } catch (error) {
768
+ state.answered.delete(key);
769
+ await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
770
+ }
771
+ }
772
+
773
+ /** Tear the channel down; the conversation itself lives on (a reconnect reuses it). */
774
+ close(sessionId) {
775
+ const state = this.bySession.get(sessionId);
776
+ if (!state) return;
777
+ state.controller.abort();
778
+ if (state.eventTimer) clearTimeout(state.eventTimer);
779
+ this.bySession.delete(sessionId);
780
+ }
781
+
782
+ /** The desktop let go of the conversation: stop every loop, including reconnect. */
783
+ dispose(sessionId) {
784
+ this.lifetimes.get(sessionId)?.abort();
785
+ this.lifetimes.delete(sessionId);
786
+ // A disposed conversation can no longer answer its own questions, so the queue
787
+ // that would deliver them goes with it.
788
+ this.interactionScopes.delete(sessionId);
789
+ this.close(sessionId);
790
+ }
791
+
792
+ captureEvent(session, event) {
793
+ const state = this.bySession.get(session.id);
794
+ if (!state || state.controller.signal.aborted) return;
795
+ const origin = event.type === "user/message" && state.phoneMessageIds.delete(event.data?.id)
796
+ ? "phone"
797
+ : "desktop";
798
+ // Shrink before queueing: a giant event wedges the channel if it reaches the
799
+ // wire inside a rejected batch, and then every later flush replays it.
800
+ state.pendingEvents.push({ event: shrinkEventForWire(event), origin });
801
+ this.scheduleFlush(state);
802
+ }
803
+
804
+ // Only one batch may be in flight at a time. Overlapping flushes used to let a
805
+ // newer batch overtake an older one, which reordered a turn's streamed text on
806
+ // the phone and made the bridge treat the older batch as already seen.
807
+ scheduleFlush(state) {
808
+ if (state.flushing || state.retryPending || state.eventTimer || state.controller.signal.aborted) return;
809
+ const delay = state.pendingEvents.length >= 50 ? 0 : EVENT_BATCH_DELAY_MS;
810
+ state.eventTimer = setTimeout(() => {
811
+ state.eventTimer = null;
812
+ void this.flushEvents(state);
813
+ }, delay);
814
+ }
815
+
816
+ async flushEvents(state) {
817
+ if (state.flushing || state.retryPending || state.controller.signal.aborted || state.pendingEvents.length === 0) return;
818
+ state.flushing = true;
819
+ let failure = null;
820
+ // One batch per POST, chosen by byte budget as well as item count: the bridge
821
+ // refuses a whole batch that overruns its limit, and a rejected batch is replayed
822
+ // in full on the next flush — so an oversized event wedged the channel behind
823
+ // itself in an endless `Request body is too large` loop. Each item here was
824
+ // already shrunk at capture time, so a batch under the budget always gets through.
825
+ while (state.pendingEvents.length > 0 && !state.controller.signal.aborted && !failure) {
826
+ const batch = [];
827
+ let bytes = 12; // `{"events":[`
828
+ for (let count = 0; count < EVENT_MAX_ITEMS && state.pendingEvents.length > 0; count += 1) {
829
+ const item = state.pendingEvents.shift();
830
+ const itemBytes = JSON.stringify(item).length + 1;
831
+ if (bytes + itemBytes > EVENT_POST_BUDGET_BYTES && batch.length > 0) {
832
+ state.pendingEvents.unshift(item);
833
+ break;
834
+ }
835
+ batch.push(item);
836
+ bytes += itemBytes;
837
+ }
838
+ // should not happen: items are shrunk at capture time; a lone item over the
839
+ // budget would wedge the loop, so send it as-is and let the bridge's own cap
840
+ // (1 MB, above the per-item budget) be the safety net.
841
+ if (batch.length === 0) {
842
+ batch.push(state.pendingEvents.shift());
843
+ }
844
+ let failed = null;
845
+ try {
846
+ const response = await fetch(`${state.origin}${state.channel.eventsPath}`, {
847
+ method: "POST",
848
+ headers: {
849
+ authorization: `Bearer ${state.channel.token}`,
850
+ "content-type": "application/json",
851
+ },
852
+ body: JSON.stringify({ events: batch }),
853
+ signal: state.controller.signal,
854
+ });
855
+ await readResponse(response);
856
+ } catch (error) {
857
+ failed = error;
858
+ state.pendingEvents.unshift(...batch);
859
+ }
860
+ if (failed) {
861
+ failure = failed;
862
+ break;
863
+ }
864
+ if (state.controller.signal.aborted) break;
865
+ }
866
+ state.flushing = false;
867
+ if (state.controller.signal.aborted) return;
868
+
869
+ if (failure && isStaleChannel(failure)) {
870
+ await this.ensureConnection(state);
871
+ return;
872
+ }
873
+ if (failure) {
874
+ this.ctx.logger.warn(`AgentBridge event sync failed: ${textFromError(failure)}`);
875
+ // Hold everything back until the failed batch has been retried, so the
876
+ // bridge never receives a newer batch ahead of an older one.
877
+ state.retryPending = true;
878
+ await sleep(1_000, state.controller.signal);
879
+ state.retryPending = false;
880
+ if (!state.controller.signal.aborted) void this.flushEvents(state);
881
+ return;
882
+ }
883
+ if (state.pendingEvents.length) this.scheduleFlush(state);
884
+ }
885
+
886
+ async poll(state) {
887
+ while (!state.controller.signal.aborted) {
888
+ try {
889
+ const response = await fetch(`${state.origin}${state.channel.pollPath}?after=${state.cursor}`, {
890
+ headers: { authorization: `Bearer ${state.channel.token}` },
891
+ signal: state.controller.signal,
892
+ });
893
+ const body = await readResponse(response);
894
+ for (const command of body.commands || []) {
895
+ if (command.kind === "message") {
896
+ const message = createUserMessage(command.text);
897
+ state.phoneMessageIds.add(message.id);
898
+ state.agent.followup(message);
899
+ } else if (command.kind === "cancel") {
900
+ state.agent.cancel({ kind: "user" }, { keepInbox: true });
901
+ } else if (command.kind === "select-model") {
902
+ try {
903
+ const selected = await this.selectModel(state.agent, {
904
+ provider: command.selection?.provider,
905
+ model: command.selection?.model,
906
+ ...(command.selection?.reasoningEffort ? { reasoningEffort: command.selection.reasoningEffort } : {}),
907
+ });
908
+ await this.reportCommandResult(state, command.requestId, { ok: true, selected });
909
+ } catch (error) {
910
+ await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
911
+ }
912
+ } else if (command.kind === "answer-question" || command.kind === "cancel-question") {
913
+ await this.answerQuestion(state, command);
914
+ } else if (command.kind === "create-session") {
915
+ await this.createSession(state, command);
916
+ } else if (command.kind === "answer-approval") {
917
+ await this.answerApproval(state, command);
918
+ }
919
+ state.cursor = Math.max(state.cursor, command.seq);
920
+ }
921
+ } catch (error) {
922
+ if (state.controller.signal.aborted) return;
923
+ if (isStaleChannel(error)) {
924
+ await this.ensureConnection(state);
925
+ return;
926
+ }
927
+ this.ctx.logger.warn(`AgentBridge command polling failed: ${textFromError(error)}`);
928
+ }
929
+ await sleep(POLL_DELAY_MS, state.controller.signal);
930
+ }
931
+ }
932
+ }
933
+
934
+ function apply(ctx) {
935
+ const connections = new PhoneConnections(ctx);
936
+ ctx.commands.register({
937
+ name: "phone",
938
+ description: "pair this exact DSH Desktop conversation with a phone",
939
+ recordInput: false,
940
+ handler: async ({ agent }) => {
941
+ if (!agent.session.header.cwd) {
942
+ return { kind: "error", text: "当前会话没有项目目录,无法绑定手机。请先在项目文件夹中打开会话。" };
943
+ }
944
+ try {
945
+ const registration = await connections.connect(agent);
946
+ const model = [agent.options.provider, agent.options.model].filter(Boolean).join(" / ") || "当前 DSH 配置";
947
+ return {
948
+ kind: "success",
949
+ text: [
950
+ "手机接管二维码已生成(5 分钟内、仅可使用一次):",
951
+ `![AgentBridge 手机二维码](${registration.qrImageUrl})`,
952
+ registration.pairing.url,
953
+ `项目:${registration.project.cwd}`,
954
+ `会话:${agent.session.id}`,
955
+ `模型:${model}`,
956
+ ].join("\n\n"),
957
+ };
958
+ } catch (error) {
959
+ const origin = String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "");
960
+ return {
961
+ kind: "error",
962
+ text: isBridgeAbsent(error)
963
+ ? bridgeSetupText(origin)
964
+ : `无法连接 AgentBridge:${textFromError(error)}。请确认本机 ${origin} 正在运行。`,
965
+ };
966
+ }
967
+ },
968
+ });
969
+
970
+ // Bring the bridge up in the background as soon as the plugin loads, so by the
971
+ // time the user types /phone the local service is already there. Deliberately
972
+ // not awaited: a slow spawn must never delay desktop startup, and every failure
973
+ // is silent — /phone still prints the manual steps when nothing came up.
974
+ void startBridge(String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "")).catch(() => {});
975
+ }
976
+
977
+ export { apply, inject, name };