dsh-browser-firefox 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,9 +1,7 @@
1
1
  import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, parseBridgeFrame } from "./protocol.js";
2
- import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
2
  import z from "@deepseek-ai/schemastery";
4
- import { RpcId } from "@deepseek-ai/dsh-host-apiproxy/api";
5
- import { toFetchHandler } from "@deepseek-ai/dsh-host-apiproxy";
6
3
  import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
4
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
5
  import { WebSocket, WebSocketServer } from "ws";
8
6
  import { chmod, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
9
7
  import { dirname, join } from "node:path";
@@ -103,53 +101,57 @@ async function resolveToken(configured, file = tokenFilePath()) {
103
101
  //#endregion
104
102
  //#region lib/types/server.js
105
103
  /**
106
- * Bridge WebSocket carrier: token-authenticated connection registry, gateway
107
- * RPC passthrough, per-connection event pump, and tool-call dispatch to the
104
+ * Bridge WebSocket carrier: token-authenticated connection registry, Typert
105
+ * Remote passthrough (unary + streams), and tool-call dispatch to the
108
106
  * connected browser extension.
109
107
  *
110
108
  * The route this server mounts (`/ext/bridge`) lives OUTSIDE the /api trust
111
109
  * fence (which only guards the client-connection routes), so the bridge brings
112
110
  * its own authentication: a bearer token presented in the `hello` frame within
113
- * HELLO_TIMEOUT_MS. Gateway RPCs are dispatched through the same fetch-shaped
114
- * handler the /api carrier uses (`toFetchHandler`), so schema validation and
115
- * error envelopes are identical to the GUI path. Methods the /api carrier
116
- * pins to loopback (`PRIVILEGED_METHODS`) stay loopback-only here regardless
117
- * of the token, defense in depth for `--host 0.0.0.0` deployments.
111
+ * HELLO_TIMEOUT_MS. RPC and stream frames speak the alpha Typert dialect
112
+ * verbatim: slash-joined endpoints, native `args` objects, and unmodified
113
+ * follow frames. Methods the bridge pins to loopback (`PRIVILEGED_METHODS`)
114
+ * stay loopback-only here regardless of the token, defense in depth for
115
+ * `--host 0.0.0.0` deployments.
118
116
  *
119
117
  * One active connection at a time: a new authenticated socket replaces the
120
- * previous one (the old socket is closed and its in-flight tool calls settle
121
- * as `bridge-closed`).
118
+ * previous one (the old socket is closed, its in-flight tool calls settle as
119
+ * `bridge-closed`, and its streams are aborted).
122
120
  *
123
121
  * @module
124
122
  */
125
123
  /**
126
- * Gateway methods the /api carrier pins to loopback (mirror of
127
- * client-connection's PRIVILEGED_METHODS; kept verbatim so the two fences
128
- * cannot drift). The bridge rejects these for non-loopback remotes even with
129
- * a valid token.
124
+ * Gateway endpoints the bridge pins to loopback (the rc line's
125
+ * PRIVILEGED_METHODS, restated against the alpha Remote endpoint names:
126
+ * settings/credentials mutation and host-desktop/filesystem actions). The
127
+ * bridge rejects these for non-loopback remotes even with a valid token.
130
128
  */
131
129
  const PRIVILEGED_METHODS = /* @__PURE__ */ new Set([
132
- "host.pickDirectory",
133
- "host.openPath",
134
- "settings.describe",
135
- "settings.openDocument",
136
- "settings.update",
137
- "settings.replace",
138
- "settings.mutate",
139
- "credentials.describe",
140
- "credentials.set",
141
- "credentials.unset"
130
+ "settings/describe",
131
+ "settings/openSettingsDocument",
132
+ "settings/openAgentPresetDirectory",
133
+ "settings/update",
134
+ "settings/replace",
135
+ "settings/mutate",
136
+ "credentials/describe",
137
+ "credentials/set",
138
+ "credentials/unset",
139
+ "directoryPicker/pick",
140
+ "directoryPicker/createDirectory",
141
+ "directoryPicker/list",
142
+ "session/openWorkspacePath"
142
143
  ]);
143
144
  /** Session mutations whose WebSocket arrival order is behaviorally significant. */
144
- const ORDERED_SESSION_METHODS = /* @__PURE__ */ new Set(["session.prompt", "session.cancel"]);
145
+ const ORDERED_SESSION_METHODS = /* @__PURE__ */ new Set(["session/prompt", "session/cancel"]);
145
146
  /**
146
147
  * Extract the session id ordering key from an rpc frame, or undefined when
147
148
  * the method does not mutate a specific session (those dispatch freely).
148
149
  */
149
150
  function orderedSessionId(frame) {
150
151
  if (!ORDERED_SESSION_METHODS.has(frame.method)) return void 0;
151
- if (typeof frame.payload !== "object" || frame.payload === null || Array.isArray(frame.payload)) return void 0;
152
- const sessionId = frame.payload.sessionId;
152
+ const request = frame.args.request;
153
+ if (typeof request !== "object" || request === null || Array.isArray(request)) return void 0;
154
+ const sessionId = request.sessionId;
153
155
  return typeof sessionId === "string" ? sessionId : void 0;
154
156
  }
155
157
  /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
@@ -272,13 +274,13 @@ var BridgeServer = class {
272
274
  }
273
275
  /**
274
276
  * Terminate the server: close the acceptor, drop all sockets, reject all
275
- * in-flight tool calls.
277
+ * in-flight tool calls, abort all streams.
276
278
  * @returns a promise resolving after the acceptor and all pumps stop.
277
279
  */
278
280
  async close() {
279
281
  if (this.closed) return;
280
282
  this.closed = true;
281
- const pumps = this.current === null ? [] : [this.current.pump];
283
+ const pumps = this.current === null ? [] : [...this.current.streams.values()].map((stream) => stream.pump);
282
284
  this.replaceConnection();
283
285
  for (const socket of this.wss.clients) socket.terminate();
284
286
  this.current = null;
@@ -337,33 +339,12 @@ var BridgeServer = class {
337
339
  const ping = setInterval(() => {
338
340
  sendFrame(ws, { t: "ping" });
339
341
  }, this.deps.pingIntervalMs ?? 3e4);
340
- const pump = (async () => {
341
- try {
342
- for await (const envelope of this.deps.openEvents(abort.signal)) {
343
- if (ws.readyState !== WebSocket.OPEN) break;
344
- sendFrame(ws, {
345
- t: "event",
346
- frame: {
347
- rpcId: envelope.rpcId,
348
- method: envelope.payload.type,
349
- payload: envelope.payload
350
- }
351
- });
352
- }
353
- } catch (error) {
354
- if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) sendFrame(ws, {
355
- t: "error",
356
- code: "stream-failed",
357
- message: String(error)
358
- });
359
- }
360
- })();
361
342
  this.current = {
362
343
  ws,
363
344
  remoteAddress,
364
345
  abort,
365
- pump,
366
- ping
346
+ ping,
347
+ streams: /* @__PURE__ */ new Map()
367
348
  };
368
349
  sendFrame(ws, {
369
350
  t: "hello.ok",
@@ -379,6 +360,12 @@ var BridgeServer = class {
379
360
  case "rpc":
380
361
  this.routeRpc(frame);
381
362
  break;
363
+ case "stream.open":
364
+ this.openStream(frame);
365
+ break;
366
+ case "stream.close":
367
+ this.closeStream(frame.id);
368
+ break;
382
369
  case "tool.result":
383
370
  this.settleTool(frame.id, frame.ok, frame.ok ? frame.result : frame.error);
384
371
  break;
@@ -386,7 +373,8 @@ var BridgeServer = class {
386
373
  case "hello":
387
374
  case "hello.ok":
388
375
  case "rpc.result":
389
- case "event":
376
+ case "stream.frame":
377
+ case "stream.error":
390
378
  case "tool.call":
391
379
  case "ping":
392
380
  case "error": break;
@@ -410,12 +398,17 @@ var BridgeServer = class {
410
398
  };
411
399
  task.then(clear, clear);
412
400
  }
401
+ /** Whether the connection owning this frame may call the endpoint at all. */
402
+ forbidden(method) {
403
+ const conn = this.current;
404
+ return conn !== null && PRIVILEGED_METHODS.has(method) && !isLoopbackAddress(conn.remoteAddress);
405
+ }
413
406
  async handleRpc(frame) {
414
407
  const conn = this.current;
415
408
  /* v8 ignore next -- replacement race: a frame can land between a socket
416
409
  replacement and the next promotion; the re-check keeps the handler total */
417
410
  if (conn === null) return;
418
- if (PRIVILEGED_METHODS.has(frame.method) && !isLoopbackAddress(conn.remoteAddress)) {
411
+ if (this.forbidden(frame.method)) {
419
412
  sendFrame(conn.ws, {
420
413
  t: "rpc.result",
421
414
  id: frame.id,
@@ -427,43 +420,19 @@ var BridgeServer = class {
427
420
  });
428
421
  return;
429
422
  }
430
- const body = JSON.stringify({
431
- type: "client-request",
432
- rpcId: frame.id,
433
- method: frame.method,
434
- payload: frame.payload
435
- });
436
- const request = new Request(new URL(`/api/${frame.method}`, "http://dsh.internal"), {
437
- method: "POST",
438
- headers: { "content-type": "application/json" },
439
- body
440
- });
441
423
  try {
442
- const response = await this.deps.apiHandler.fetch(request);
443
- const text = await response.text();
444
- if (!response.ok) {
445
- sendFrame(conn.ws, {
446
- t: "rpc.result",
447
- id: frame.id,
448
- ok: false,
449
- error: {
450
- code: "http",
451
- message: text
452
- }
453
- });
454
- return;
455
- }
456
- let result;
457
- try {
458
- result = JSON.parse(text);
459
- } catch {
460
- result = text;
461
- }
462
- sendFrame(conn.ws, {
424
+ const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal);
425
+ if (result.ok) sendFrame(conn.ws, {
463
426
  t: "rpc.result",
464
427
  id: frame.id,
465
428
  ok: true,
466
- result
429
+ value: result.value
430
+ });
431
+ else sendFrame(conn.ws, {
432
+ t: "rpc.result",
433
+ id: frame.id,
434
+ ok: false,
435
+ error: result.error
467
436
  });
468
437
  } catch (error) {
469
438
  sendFrame(conn.ws, {
@@ -477,6 +446,61 @@ var BridgeServer = class {
477
446
  });
478
447
  }
479
448
  }
449
+ /** Open one Remote stream and pump its frames until closed, failed, or replaced. */
450
+ openStream(frame) {
451
+ const conn = this.current;
452
+ if (conn === null) return;
453
+ if (this.forbidden(frame.method)) {
454
+ sendFrame(conn.ws, {
455
+ t: "stream.error",
456
+ id: frame.id,
457
+ message: "method is loopback-only"
458
+ });
459
+ return;
460
+ }
461
+ this.closeStream(frame.id);
462
+ const ws = conn.ws;
463
+ const abort = new AbortController();
464
+ conn.abort.signal.addEventListener("abort", () => {
465
+ abort.abort();
466
+ }, { once: true });
467
+ let pump;
468
+ pump = (async () => {
469
+ try {
470
+ const iterable = await this.deps.openStream(frame.method, frame.args, abort.signal);
471
+ for await (const value of iterable) {
472
+ if (ws.readyState !== WebSocket.OPEN) break;
473
+ sendFrame(ws, {
474
+ t: "stream.frame",
475
+ id: frame.id,
476
+ frame: value
477
+ });
478
+ }
479
+ } catch (error) {
480
+ if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) sendFrame(ws, {
481
+ t: "stream.error",
482
+ id: frame.id,
483
+ message: String(error)
484
+ });
485
+ } finally {
486
+ const current = this.current;
487
+ if (current !== null && current.streams.get(frame.id)?.pump === pump) current.streams.delete(frame.id);
488
+ }
489
+ })();
490
+ conn.streams.set(frame.id, {
491
+ abort,
492
+ pump
493
+ });
494
+ }
495
+ /** Abort one open stream (client `stream.close`). */
496
+ closeStream(id) {
497
+ const conn = this.current;
498
+ if (conn === null) return;
499
+ const stream = conn.streams.get(id);
500
+ if (stream === void 0) return;
501
+ conn.streams.delete(id);
502
+ stream.abort.abort();
503
+ }
480
504
  settleTool(id, ok, payload) {
481
505
  const pending = this.pendingTools.get(id);
482
506
  if (pending === void 0) return;
@@ -485,13 +509,15 @@ var BridgeServer = class {
485
509
  if (ok) pending.resolve(payload);
486
510
  else pending.reject(new BridgeToolError(payloadCode(payload), payloadMessage(payload)));
487
511
  }
488
- /** Close the current connection (if any) and settle its in-flight calls. */
512
+ /** Close the current connection (if any) and settle its in-flight calls and streams. */
489
513
  replaceConnection() {
490
514
  const conn = this.current;
491
515
  if (conn === null) return;
492
516
  this.current = null;
493
517
  clearInterval(conn.ping);
494
518
  conn.abort.abort();
519
+ for (const stream of conn.streams.values()) stream.abort.abort();
520
+ conn.streams.clear();
495
521
  if (conn.ws.readyState === WebSocket.OPEN || conn.ws.readyState === WebSocket.CONNECTING) conn.ws.close(4e3, "replaced");
496
522
  for (const [id, pending] of this.pendingTools) {
497
523
  clearTimeout(pending.timer);
@@ -904,136 +930,125 @@ function defineTools(call, options) {
904
930
  /**
905
931
  * Defer real session creation until the first prompt.
906
932
  *
907
- * The panel calls `session.create` as soon as it connects, but a session that
933
+ * The panel calls `session/create` as soon as it connects, but a session that
908
934
  * is opened and never used should leave zero trace in the store/GUI. This
909
- * wrapper answers `session.create` with a provisional id (minted locally,
910
- * nothing persisted), serves `session.history` for provisional ids as empty,
911
- * and materializes the real session — same id, original create payload — on
912
- * the first `session.prompt` for that id. Abandoned provisional ids are
913
- * pruned after {@link PROVISIONAL_TTL_MS}.
935
+ * interceptor answers `session/create` with a provisional id (minted locally,
936
+ * nothing persisted) and materializes the real session — same id, original
937
+ * create request — on the first `session/prompt` for that id. Abandoned
938
+ * provisional ids are pruned after {@link PROVISIONAL_TTL_MS}.
914
939
  *
915
940
  * @module @deepseek-ai/dsh-bridge-browser/src/session-deferral
916
941
  */
917
942
  /** Provisional entries older than this are dropped on the next create. */
918
943
  const PROVISIONAL_TTL_MS = 30 * 6e4;
944
+ /** Extract the `request` arg object from one dispatch's native args, when present. */
945
+ function requestArg$1(args) {
946
+ const request = args.request;
947
+ return typeof request === "object" && request !== null && !Array.isArray(request) ? request : {};
948
+ }
919
949
  /**
920
- * Wrap the gateway sessions API so `session.create` returns a provisional id
950
+ * Intercept the Remote dispatch so `session/create` returns a provisional id
921
951
  * without creating anything; the real session materializes on the first
922
- * `session.prompt` for that id.
952
+ * `session/prompt` for that id.
923
953
  *
924
- * @param api - Gateway API implementation.
925
- * @param enabled - Whether deferral is active; false returns the API untouched.
926
- * @returns the original API when disabled, otherwise the wrapped API.
954
+ * @param dispatch - Inner Remote dispatch.
955
+ * @param enabled - Whether deferral is active; false returns the dispatch untouched.
956
+ * @returns the original dispatch when disabled, otherwise the intercepting dispatch.
927
957
  */
928
- function withSessionDeferral(api, enabled) {
929
- if (!enabled) return api;
958
+ function withSessionDeferral(dispatch, enabled) {
959
+ if (!enabled) return dispatch;
930
960
  const provisional = /* @__PURE__ */ new Map();
931
961
  const materializing = /* @__PURE__ */ new Map();
932
962
  const prune = () => {
933
963
  const cutoff = Date.now() - PROVISIONAL_TTL_MS;
934
964
  for (const [id, entry] of provisional) if (entry.createdAt < cutoff) provisional.delete(id);
935
965
  };
936
- const mintedId = (payload) => payload.sessionId ?? `session-${randomUUID()}`;
937
- return {
938
- ...api,
939
- sessions: {
940
- ...api.sessions,
941
- async create(request) {
942
- prune();
943
- const sessionId = mintedId(request.payload);
944
- provisional.set(sessionId, {
945
- payload: { ...request.payload },
946
- createdAt: Date.now()
947
- });
948
- return {
949
- rpcId: request.rpcId,
950
- result: {
951
- ok: true,
952
- value: { sessionId }
953
- }
954
- };
955
- },
956
- async history(request) {
957
- if (!provisional.has(request.payload.sessionId)) return api.sessions.history(request);
958
- return {
959
- rpcId: request.rpcId,
960
- result: {
961
- ok: true,
962
- value: {
963
- events: [],
964
- hasMore: false
965
- }
966
- }
967
- };
968
- },
969
- async prompt(request) {
970
- const entry = provisional.get(request.payload.sessionId);
971
- if (entry === void 0) return api.sessions.prompt(request);
972
- const existing = materializing.get(request.payload.sessionId);
973
- const pending = existing ?? api.sessions.create({
974
- rpcId: RpcId(randomUUID()),
975
- payload: {
976
- ...entry.payload,
977
- sessionId: request.payload.sessionId
978
- }
966
+ return async (method, args, signal) => {
967
+ if (method === "session/create") {
968
+ prune();
969
+ const request = requestArg$1(args);
970
+ const sessionId = typeof request.sessionId === "string" ? request.sessionId : `session-${randomUUID()}`;
971
+ provisional.set(sessionId, {
972
+ request: { ...request },
973
+ createdAt: Date.now()
974
+ });
975
+ return {
976
+ ok: true,
977
+ value: { sessionId }
978
+ };
979
+ }
980
+ if (method === "session/prompt") {
981
+ const request = requestArg$1(args);
982
+ const sessionId = typeof request.sessionId === "string" ? request.sessionId : void 0;
983
+ const entry = sessionId === void 0 ? void 0 : provisional.get(sessionId);
984
+ if (sessionId === void 0 || entry === void 0) return dispatch(method, args, signal);
985
+ const existing = materializing.get(sessionId);
986
+ const pending = existing ?? dispatch("session/create", { request: {
987
+ ...entry.request,
988
+ sessionId
989
+ } }, signal);
990
+ if (existing === void 0) {
991
+ materializing.set(sessionId, pending);
992
+ pending.then(() => {
993
+ materializing.delete(sessionId);
994
+ }, () => {
995
+ materializing.delete(sessionId);
979
996
  });
980
- if (existing === void 0) {
981
- materializing.set(request.payload.sessionId, pending);
982
- pending.then(() => {
983
- materializing.delete(request.payload.sessionId);
984
- }, () => {
985
- materializing.delete(request.payload.sessionId);
986
- });
987
- }
988
- const created = await pending;
989
- if (!created.result.ok) return created;
990
- provisional.delete(request.payload.sessionId);
991
- return api.sessions.prompt(request);
992
997
  }
998
+ const created = await pending;
999
+ if (!created.ok) return {
1000
+ ok: false,
1001
+ error: created.error
1002
+ };
1003
+ provisional.delete(sessionId);
1004
+ return dispatch(method, args, signal);
993
1005
  }
1006
+ return dispatch(method, args, signal);
994
1007
  };
995
1008
  }
996
1009
  //#endregion
997
1010
  //#region lib/types/session-workspace.js
998
1011
  /**
999
1012
  * Best-effort workspace grouping for sessions created through the browser
1000
- * bridge. The wrapper changes only implicit `session.create` requests;
1001
- * explicit workspace choices and every other gateway method pass through.
1013
+ * bridge. The interceptor changes only implicit `session/create` requests;
1014
+ * explicit workspace choices and every other Remote endpoint pass through.
1002
1015
  * @module @deepseek-ai/dsh-bridge-browser/src/session-workspace
1003
1016
  */
1017
+ /** Extract the `request` arg object from one dispatch's native args, when present. */
1018
+ function requestArg(args) {
1019
+ const request = args.request;
1020
+ return typeof request === "object" && request !== null && !Array.isArray(request) ? request : {};
1021
+ }
1004
1022
  /**
1005
- * Add a dedicated Workspace to implicit session creation without making
1023
+ * Add the dedicated Workspace to implicit session creation without making
1006
1024
  * grouping a session-creation dependency. The first implicit create mkdirs
1007
- * and registers the configured path; that result, including failure, is
1008
- * cached for the wrapper lifetime.
1025
+ * and registers the configured path (`workspace/create`); that result,
1026
+ * including failure, is cached for the interceptor lifetime.
1009
1027
  *
1010
- * @param api - Injected gateway API implementation.
1028
+ * @param dispatch - Inner Remote dispatch.
1011
1029
  * @param workspacePath - Dedicated directory, or an empty string to opt out.
1012
1030
  * @param warn - Logger called once when grouping cannot be established.
1013
- * @returns the original API for opt-out, otherwise an API with wrapped session creation.
1031
+ * @returns the original dispatch for opt-out, otherwise a dispatch with intercepted session creation.
1014
1032
  */
1015
- function withSessionWorkspace(api, workspacePath, warn) {
1016
- if (workspacePath === "") return api;
1033
+ function withSessionWorkspace(dispatch, workspacePath, warn) {
1034
+ if (workspacePath === "") return dispatch;
1017
1035
  let workspacePromise;
1018
1036
  const ensureWorkspace = () => {
1019
1037
  if (workspacePromise !== void 0) return workspacePromise;
1020
1038
  workspacePromise = (async () => {
1021
1039
  try {
1022
1040
  await mkdir(workspacePath, { recursive: true });
1023
- const workspaceApi = api.workspace;
1024
- if (workspaceApi === void 0) {
1025
- warn(`browser bridge: workspace API is unavailable; sessions will remain ungrouped`);
1041
+ const result = await dispatch("workspace/create", { request: { path: workspacePath } }, new AbortController().signal);
1042
+ if (!result.ok) {
1043
+ warn(`browser bridge: workspace/create failed for "${workspacePath}" (${result.error.code}: ${result.error.message}); sessions will remain ungrouped`);
1026
1044
  return;
1027
1045
  }
1028
- const response = await workspaceApi.create({
1029
- rpcId: RpcId(randomUUID()),
1030
- payload: { path: workspacePath }
1031
- });
1032
- if (!response.result.ok) {
1033
- warn(`browser bridge: workspace.create failed for "${workspacePath}" (${response.result.error.code}: ${response.result.error.message}); sessions will remain ungrouped`);
1046
+ const workspaceId = result.value.workspace?.workspaceId;
1047
+ if (typeof workspaceId !== "string") {
1048
+ warn(`browser bridge: workspace/create for "${workspacePath}" returned no workspace id; sessions will remain ungrouped`);
1034
1049
  return;
1035
1050
  }
1036
- return response.result.value.workspace.workspaceId;
1051
+ return workspaceId;
1037
1052
  } catch (error) {
1038
1053
  warn(`browser bridge: could not prepare session workspace "${workspacePath}": ${String(error)}; sessions will remain ungrouped`);
1039
1054
  return;
@@ -1041,25 +1056,21 @@ function withSessionWorkspace(api, workspacePath, warn) {
1041
1056
  })();
1042
1057
  return workspacePromise;
1043
1058
  };
1044
- return {
1045
- ...api,
1046
- sessions: {
1047
- ...api.sessions,
1048
- async create(request) {
1049
- if (request.payload.workspaceId !== void 0) return api.sessions.create(request);
1050
- const workspaceId = await ensureWorkspace();
1051
- if (workspaceId === void 0) return api.sessions.create(request);
1052
- const payload = {
1053
- ...request.payload,
1054
- workspaceId
1055
- };
1056
- delete payload.cwd;
1057
- return api.sessions.create({
1058
- ...request,
1059
- payload
1060
- });
1061
- }
1062
- }
1059
+ return async (method, args, signal) => {
1060
+ if (method !== "session/create") return dispatch(method, args, signal);
1061
+ const request = requestArg(args);
1062
+ if (request.workspaceId !== void 0) return dispatch(method, args, signal);
1063
+ const workspaceId = await ensureWorkspace();
1064
+ if (workspaceId === void 0) return dispatch(method, args, signal);
1065
+ const next = {
1066
+ ...request,
1067
+ workspaceId
1068
+ };
1069
+ delete next.cwd;
1070
+ return dispatch(method, {
1071
+ ...args,
1072
+ request: next
1073
+ }, signal);
1063
1074
  };
1064
1075
  }
1065
1076
  //#endregion
@@ -1070,11 +1081,13 @@ function withSessionWorkspace(api, workspacePath, warn) {
1070
1081
  *
1071
1082
  * The bridge mounts its own upgrade route (`/ext/bridge`) on the host
1072
1083
  * webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
1073
- * authentication (first frame `hello` within HELLO_TIMEOUT_MS). Gateway RPCs
1074
- * from the extension are dispatched through the same fetch-shaped handler the
1075
- * /api carrier uses, and session events are pumped per connection. Tools
1076
- * execute by dispatching `tool.call` frames to the connected extension, which
1077
- * performs the action in the user's active tab.
1084
+ * authentication (first frame `hello` within HELLO_TIMEOUT_MS). The wire
1085
+ * protocol IS the alpha Typert Remote dialect: unary `rpc` frames carry
1086
+ * slash-joined endpoints and native args objects straight into
1087
+ * `ctx.typertGateway.invoke`, and `stream.open` frames open
1088
+ * `ctx.typertGateway.stream` subscriptions whose native follow frames flow
1089
+ * back unmodified. Tools execute by dispatching `tool.call` frames to the
1090
+ * connected extension, which performs the action in the user's active tab.
1078
1091
  *
1079
1092
  * Opt-in by design: nothing is registered unless this plugin appears in the
1080
1093
  * composition. No dsh core code is touched.
@@ -1086,7 +1099,7 @@ const name = "bridge-browser";
1086
1099
  /** Services required by this plugin. */
1087
1100
  const inject = [
1088
1101
  "webServer",
1089
- "apiProxy",
1102
+ "typertGateway",
1090
1103
  "tools"
1091
1104
  ];
1092
1105
  /** Default per-tool-call budget (ms). */
@@ -1140,16 +1153,44 @@ function resolveConfig(config) {
1140
1153
  async function apply(ctx, config) {
1141
1154
  const resolved = resolveConfig(config);
1142
1155
  const tokenRes = await resolveToken(resolved.token);
1143
- const api = withSessionDeferral(withSessionWorkspace(ctx.apiProxy, resolved.sessionWorkspacePath, (message) => {
1156
+ const invoke = async (method, args, signal) => {
1157
+ const slash = method.indexOf("/");
1158
+ const namespace = slash === -1 ? method : method.slice(0, slash);
1159
+ const remoteMethod = slash === -1 ? "" : method.slice(slash + 1);
1160
+ try {
1161
+ return {
1162
+ ok: true,
1163
+ value: await ctx.typertGateway.invoke({
1164
+ namespace,
1165
+ method: remoteMethod,
1166
+ args,
1167
+ signal
1168
+ })
1169
+ };
1170
+ } catch (error) {
1171
+ return {
1172
+ ok: false,
1173
+ error: ctx.typertGateway.wireStream.failure(error)
1174
+ };
1175
+ }
1176
+ };
1177
+ const dispatchRpc = withSessionDeferral(withSessionWorkspace(invoke, resolved.sessionWorkspacePath, (message) => {
1144
1178
  ctx.logger.warn(message);
1145
1179
  }), resolved.deferSessionCreate);
1146
1180
  const server = new BridgeServer({
1147
1181
  token: tokenRes.token,
1148
- apiHandler: toFetchHandler(api),
1149
- openEvents: (signal) => api.events.mux({
1150
- rpcId: RpcId(randomUUID()),
1151
- payload: {}
1152
- }, signal),
1182
+ dispatchRpc,
1183
+ openStream: (method, args, signal) => {
1184
+ const slash = method.indexOf("/");
1185
+ const namespace = slash === -1 ? method : method.slice(0, slash);
1186
+ const remoteMethod = slash === -1 ? "" : method.slice(slash + 1);
1187
+ return ctx.typertGateway.stream({
1188
+ namespace,
1189
+ method: remoteMethod,
1190
+ args,
1191
+ signal
1192
+ });
1193
+ },
1153
1194
  toolTimeoutMs: resolved.toolTimeoutMs,
1154
1195
  caps: {
1155
1196
  textOnly: true,