dsh-browser-firefox 0.4.7 → 0.5.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.
@@ -0,0 +1,46 @@
1
+ /**
2
+ * `session/follow` 的参数形状:宿主描述符要求
3
+ * `{request: {address: SessionAddress}}`,其中 address 是
4
+ * `{kind:'session', sessionId}` 或
5
+ * `{kind:'subagent', parentSessionId, childSessionId, mode}`。
6
+ *
7
+ * 扩展用 {@link sessionFollowArgs} 构造订阅参数,插件用
8
+ * {@link followedSessionOf} 从原生 args 里取回「正在展示哪个会话」。两者
9
+ * 同处一个模块,是为了让形状只有**一个**真实来源:0.4.7 曾因插件侧测试用
10
+ * 臆造形状(`request.sessionId`)而没发现 follow 归属在生产环境从未生效。
11
+ *
12
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-follow
13
+ */
14
+ /** 普通会话的 follow 地址。 */
15
+ export interface SessionFollowAddress {
16
+ kind: 'session';
17
+ sessionId: string;
18
+ }
19
+ /** 直接 subagent 子会话的 follow 地址(宿主 SessionAddress 的另一形态)。 */
20
+ export interface SubagentFollowAddress {
21
+ kind: 'subagent';
22
+ parentSessionId: string;
23
+ childSessionId: string;
24
+ mode: 'one-shot' | 'continuable' | 'unknown';
25
+ }
26
+ /** 一次性订阅参数(`stream.open` 的 args)。 */
27
+ export interface SessionFollowArgs {
28
+ request: {
29
+ address: SessionFollowAddress | SubagentFollowAddress;
30
+ };
31
+ }
32
+ /** 订阅一个普通会话(面板当前会话始终用这一形态)。 */
33
+ export declare function sessionFollowArgs(sessionId: string): SessionFollowArgs;
34
+ /** 订阅一个 direct subagent 子会话(预留:目前面板不展示子会话)。 */
35
+ export declare function subagentFollowArgs(parentSessionId: string, childSessionId: string, mode?: SubagentFollowAddress['mode']): SessionFollowArgs;
36
+ /**
37
+ * Session id displayed by a `session/follow` stream, read from the host's
38
+ * `SessionFollowRequest.address`. A subagent address carries the child session
39
+ * on `childSessionId`; ownership then walks up to the parent conversation, so
40
+ * either form routes the card correctly.
41
+ *
42
+ * @param args - native args of the `stream.open` frame.
43
+ * @returns the followed session id, or undefined when absent/malformed.
44
+ */
45
+ export declare function followedSessionOf(args: Record<string, unknown>): string | undefined;
46
+ //# sourceMappingURL=session-follow.d.ts.map
File without changes
File without changes
File without changes
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Bookkeeping shared by the host waterfalls the bridge claims
3
+ * (`user-questions/request`, `approval/request`).
4
+ *
5
+ * Both bridges need exactly the same lifecycle: one pending entry per
6
+ * generated id, a **single settlement** guarantee against concurrent paths
7
+ * (extension answer vs host abort vs connection loss vs plugin unload), an
8
+ * abort listener that is detached once settled, and the id+session match the
9
+ * uplink must pass before it may touch an entry. Only the outcome vocabulary
10
+ * and the push/settle policy differ, and those stay in the domain modules.
11
+ *
12
+ * @module
13
+ */
14
+ /** Registry of pending waterfall requests, keyed by the id sent to the extension. */
15
+ export declare class PendingWaterfalls<TOutcome, TPayload = undefined> {
16
+ private readonly entries;
17
+ /**
18
+ * Track one request pushed to the extension.
19
+ *
20
+ * @param input - id, asking session, host cancellation signal, the domain's
21
+ * settlement policy, and the abort handler (typically: tell the extension
22
+ * the card is gone, then settle).
23
+ */
24
+ register(input: {
25
+ id: string;
26
+ sessionId: string;
27
+ signal: AbortSignal | undefined;
28
+ payload: TPayload;
29
+ complete: (outcome: TOutcome) => void;
30
+ onAbort: () => void;
31
+ }): void;
32
+ /**
33
+ * Whether an unsettled entry exists for exactly this id and session. The
34
+ * uplink must not be able to settle another session's card.
35
+ */
36
+ matches(id: string, sessionId: string): boolean;
37
+ /** Domain payload registered with one unsettled entry (undefined once settled). */
38
+ payloadOf(id: string): TPayload | undefined;
39
+ /**
40
+ * Settle one request. Later settlements for the same id are no-ops, and the
41
+ * entry is dropped together with its abort listener.
42
+ *
43
+ * @returns true when this call performed the settlement.
44
+ */
45
+ settle(id: string, outcome: TOutcome): boolean;
46
+ /** Every unsettled id, for the connection-loss and unload sweeps. */
47
+ ids(): string[];
48
+ }
49
+ //# sourceMappingURL=waterfall.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-browser-firefox",
3
3
  "description": "Firefox browser control for DeepSeek Harness: token-authenticated WebSocket bridge + browser_* tools (native-image screenshots) driving the user's own Firefox via the companion AMO extension, with sidebar ask_user_question answering",
4
- "version": "0.4.7",
4
+ "version": "0.5.0",
5
5
  "author": "tuojc",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -35,38 +35,32 @@
35
35
  "types": "./lib/types/protocol.d.ts",
36
36
  "default": "./lib/protocol.js"
37
37
  },
38
- "./invariant": {
39
- "types": "./lib/types/invariant.d.ts",
40
- "default": "./lib/invariant.js"
41
- },
42
38
  "./cordis.patch.yml": "./cordis.patch.yml",
43
39
  "./src/*": "./src/*",
44
40
  "./package.json": "./package.json"
45
41
  },
46
42
  "files": [
47
43
  "lib/index.js",
48
- "lib/invariant.js",
49
44
  "lib/protocol.js",
50
45
  "lib/types/**/*.d.ts",
51
46
  "cordis.patch.yml",
52
47
  "src"
53
48
  ],
54
49
  "peerDependencies": {
55
- "@deepseek-ai/cordis": "^4.0.2",
56
- "@deepseek-ai/dsh-api-gateway": "^0.2.0-rc.1",
57
- "@deepseek-ai/dsh-api-session-controller": "^0.2.0-rc.1",
58
- "@deepseek-ai/dsh-api-workspace-controller": "^0.2.0-rc.1",
59
- "@deepseek-ai/dsh-attachment": "^0.2.0-rc.1",
60
- "@deepseek-ai/dsh-home-paths": "^0.2.0-rc.1",
61
- "@deepseek-ai/dsh-host-webserver": "^0.2.0-rc.1",
62
- "@deepseek-ai/dsh-invariants": "^0.2.0-rc.1",
63
- "@deepseek-ai/dsh-session": "^0.2.0-rc.1",
64
- "@deepseek-ai/dsh-tools": "^0.2.0-rc.1",
65
- "@deepseek-ai/dsh-user-approval": "^0.2.0-rc.1",
66
- "@deepseek-ai/dsh-user-questions": "^0.2.0-rc.1"
50
+ "@deepseek-ai/cordis": "^4.0.5",
51
+ "@deepseek-ai/dsh-api-gateway": "^0.2.1-rc.5",
52
+ "@deepseek-ai/dsh-api-session-controller": "^0.2.1-rc.5",
53
+ "@deepseek-ai/dsh-api-workspace-controller": "^0.2.1-rc.5",
54
+ "@deepseek-ai/dsh-attachment": "^0.2.1-rc.5",
55
+ "@deepseek-ai/dsh-home-paths": "^0.2.1-rc.5",
56
+ "@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.5",
57
+ "@deepseek-ai/dsh-session": "^0.2.1-rc.5",
58
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.5",
59
+ "@deepseek-ai/dsh-user-approval": "^0.2.1-rc.5",
60
+ "@deepseek-ai/dsh-user-questions": "^0.2.1-rc.5"
67
61
  },
68
62
  "dependencies": {
69
- "@deepseek-ai/schemastery": "^3.18.4",
63
+ "@deepseek-ai/schemastery": "^3.18.5",
70
64
  "ws": "^8.21.0"
71
65
  },
72
66
  "scripts": {
@@ -76,33 +70,25 @@
76
70
  "prepublishOnly": "pnpm run build"
77
71
  },
78
72
  "devDependencies": {
79
- "@deepseek-ai/cordis": "4.0.4",
80
- "@deepseek-ai/cordis-plugin-include": "1.0.9",
81
- "@deepseek-ai/cordis-plugin-loader": "1.0.5",
82
- "@deepseek-ai/dsh-agent": "0.2.0-rc.1",
83
- "@deepseek-ai/dsh-agent-loop": "0.2.0-rc.1",
84
- "@deepseek-ai/dsh-api-gateway": "0.2.0-rc.1",
85
- "@deepseek-ai/dsh-api-session-controller": "0.2.0-rc.1",
86
- "@deepseek-ai/dsh-api-workspace-controller": "0.2.0-rc.1",
87
- "@deepseek-ai/dsh-attachment": "0.2.0-rc.1",
88
- "@deepseek-ai/dsh-host-webserver": "0.2.0-rc.1",
89
- "@deepseek-ai/dsh-invariants": "0.2.0-rc.1",
90
- "@deepseek-ai/dsh-llm": "0.2.0-rc.1",
91
- "@deepseek-ai/dsh-home-paths": "0.2.0-rc.1",
92
- "@deepseek-ai/dsh-session": "0.2.0-rc.1",
93
- "@deepseek-ai/dsh-storage": "0.2.0-rc.1",
94
- "@deepseek-ai/dsh-storage-domain": "0.2.0-rc.1",
95
- "@deepseek-ai/dsh-storage-json": "0.2.0-rc.1",
96
- "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.1",
97
- "@deepseek-ai/dsh-tools": "0.2.0-rc.1",
98
- "@deepseek-ai/dsh-user-questions": "0.2.0-rc.1",
99
- "@deepseek-ai/dsh-workspace": "0.2.0-rc.1",
73
+ "@deepseek-ai/cordis": "4.0.5",
74
+ "@deepseek-ai/cordis-plugin-include": "1.0.10",
75
+ "@deepseek-ai/cordis-plugin-loader": "1.0.6",
76
+ "@deepseek-ai/dsh-api-gateway": "0.2.1-rc.5",
77
+ "@deepseek-ai/dsh-api-session-controller": "0.2.1-rc.5",
78
+ "@deepseek-ai/dsh-api-workspace-controller": "0.2.1-rc.5",
79
+ "@deepseek-ai/dsh-attachment": "0.2.1-rc.5",
80
+ "@deepseek-ai/dsh-home-paths": "0.2.1-rc.5",
81
+ "@deepseek-ai/dsh-host-webserver": "0.2.1-rc.5",
82
+ "@deepseek-ai/dsh-session": "0.2.1-rc.5",
83
+ "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.5",
84
+ "@deepseek-ai/dsh-tools": "0.2.1-rc.5",
85
+ "@deepseek-ai/dsh-user-approval": "0.2.1-rc.5",
86
+ "@deepseek-ai/dsh-user-questions": "0.2.1-rc.5",
100
87
  "@types/node": "^22.20.0",
101
88
  "@types/ws": "^8.18.1",
102
89
  "playwright-core": "^1.61.1",
103
90
  "tsdown": "0.22.2",
104
91
  "typescript": "^6.0.3",
105
- "vitest": "^4.1.8",
106
- "@deepseek-ai/dsh-user-approval": "0.2.0-rc.1"
92
+ "vitest": "^4.1.8"
107
93
  }
108
94
  }
package/src/approvals.ts CHANGED
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { randomUUID } from 'node:crypto'
20
20
  import type { ServerFrame } from './protocol.ts'
21
+ import { PendingWaterfalls } from './waterfall.ts'
21
22
 
22
23
  /** The host's closed approval outcome vocabulary. */
23
24
  export type ApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'
@@ -37,37 +38,30 @@ export type ApprovalReceipt =
37
38
  | { accepted: true }
38
39
  | { accepted: false; reason: 'not-pending' | 'bad-decision' }
39
40
 
40
- /** Args of the plugin-local `bridge/approvalDecision` rpc method. */
41
+ /** Args of the plugin-local `bridge/approvalDecision` rpc method (decision already narrowed by the parser). */
41
42
  export interface ApprovalDecisionArgs {
42
43
  approvalId: string
43
44
  sessionId: string
44
- decision?: unknown
45
+ decision: ApprovalDecision
45
46
  }
46
47
 
47
48
  type PendingOutcome =
48
49
  | { kind: 'decide'; outcome: ApprovalOutcome }
49
50
  | { kind: 'delegate' }
50
51
 
51
- interface PendingApproval {
52
- readonly sessionId: string
53
- settled: boolean
54
- readonly complete: (outcome: PendingOutcome) => void
55
- readonly signal: AbortSignal | undefined
56
- onAbort: (() => void) | undefined
57
- }
58
-
59
52
  /** Parse the extension's `bridge/approvalDecision` rpc args (ids + closed decision). */
60
53
  export function asApprovalDecisionArgs(value: unknown): ApprovalDecisionArgs | undefined {
61
54
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
62
55
  const args = value as Record<string, unknown>
63
56
  if (typeof args.approvalId !== 'string' || typeof args.sessionId !== 'string') return undefined
64
- if (args.decision !== 'allowed-once' && args.decision !== 'rejected') return undefined
65
- return { approvalId: args.approvalId, sessionId: args.sessionId, decision: args.decision }
57
+ const decision = args.decision
58
+ if (decision !== 'allowed-once' && decision !== 'rejected') return undefined
59
+ return { approvalId: args.approvalId, sessionId: args.sessionId, decision }
66
60
  }
67
61
 
68
62
  /** Owns the host approval waterfall for extension-driven sessions. */
69
63
  export class ApprovalBridge {
70
- private readonly pending = new Map<string, PendingApproval>()
64
+ private readonly waterfalls = new PendingWaterfalls<PendingOutcome>()
71
65
 
72
66
  constructor(private readonly deps: {
73
67
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
@@ -93,30 +87,22 @@ export class ApprovalBridge {
93
87
  if (signal?.aborted) return Promise.resolve<ApprovalOutcome>('cancelled')
94
88
  const approvalId = randomUUID()
95
89
  return new Promise<ApprovalOutcome>((resolve, reject) => {
96
- const entry: PendingApproval = {
90
+ this.waterfalls.register({
91
+ id: approvalId,
97
92
  sessionId: routingSessionId,
98
- settled: false,
99
93
  signal,
94
+ payload: undefined,
100
95
  complete: (outcome) => {
101
- if (entry.settled) return
102
- entry.settled = true
103
- this.pending.delete(approvalId)
104
- if (entry.onAbort !== undefined) entry.signal?.removeEventListener('abort', entry.onAbort)
105
96
  if (outcome.kind === 'decide') resolve(outcome.outcome)
106
97
  else next().then(resolve, reject)
107
98
  },
108
- onAbort: undefined,
109
- }
110
- if (signal !== undefined) {
111
- entry.onAbort = () => {
99
+ onAbort: () => {
112
100
  // Withdraw the card before settling so a late click can never be
113
101
  // reported as accepted for a dead request.
114
102
  this.deps.push({ t: 'approval.resolved', id: approvalId, sessionId: routingSessionId })
115
- entry.complete({ kind: 'decide', outcome: 'cancelled' })
116
- }
117
- signal.addEventListener('abort', entry.onAbort, { once: true })
118
- }
119
- this.pending.set(approvalId, entry)
103
+ this.waterfalls.settle(approvalId, { kind: 'decide', outcome: 'cancelled' })
104
+ },
105
+ })
120
106
  this.deps.push({
121
107
  t: 'approval.requested',
122
108
  id: approvalId,
@@ -133,28 +119,25 @@ export class ApprovalBridge {
133
119
  * rpc. The server replies with this receipt.
134
120
  */
135
121
  decide(args: ApprovalDecisionArgs): ApprovalReceipt {
136
- const entry = this.pending.get(args.approvalId)
137
- if (entry === undefined || entry.settled || entry.sessionId !== args.sessionId) {
122
+ if (!this.waterfalls.matches(args.approvalId, args.sessionId)) {
138
123
  return { accepted: false, reason: 'not-pending' }
139
124
  }
140
125
  if (args.decision !== 'allowed-once' && args.decision !== 'rejected') {
141
126
  return { accepted: false, reason: 'bad-decision' }
142
127
  }
143
- entry.complete({ kind: 'decide', outcome: args.decision })
128
+ this.waterfalls.settle(args.approvalId, { kind: 'decide', outcome: args.decision })
144
129
  return { accepted: true }
145
130
  }
146
131
 
147
132
  /** Bridge connection replaced/closed: delegate every unsettled approval. */
148
133
  delegateAll(): void {
149
- for (const entry of [...this.pending.values()]) {
150
- if (!entry.settled) entry.complete({ kind: 'delegate' })
151
- }
134
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: 'delegate' })
152
135
  }
153
136
 
154
137
  /** Plugin unload: answer everything fail-closed so no tool call outlives the plugin. */
155
138
  dispose(): void {
156
- for (const entry of [...this.pending.values()]) {
157
- if (!entry.settled) entry.complete({ kind: 'decide', outcome: 'unavailable' })
139
+ for (const id of this.waterfalls.ids()) {
140
+ this.waterfalls.settle(id, { kind: 'decide', outcome: 'unavailable' })
158
141
  }
159
142
  }
160
143
  }
@@ -85,7 +85,7 @@ export interface OwnershipSources {
85
85
  }
86
86
 
87
87
  /** Maximum ancestor hops when looking for an owned session. */
88
- export const MAX_OWNER_DEPTH = 8
88
+ const MAX_OWNER_DEPTH = 8
89
89
 
90
90
  /** Whether one exact session id is extension-owned by either source. */
91
91
  export function isOwnedSession(sessionId: string | undefined, sources: OwnershipSources): boolean {
@@ -151,21 +151,3 @@ export function resolveInteractionOwnership(input: {
151
151
  if (sessionId === undefined) return { owned: false, reason: 'not-owned' }
152
152
  return { owned: true, sessionId }
153
153
  }
154
-
155
- /**
156
- * Decide whether the bridge should own ask_user_question for this request.
157
- * Thin compatibility wrapper over {@link resolveInteractionOwnership}.
158
- */
159
- export function shouldBridgeOwnQuestion(input: {
160
- hasExtensionConnection: boolean
161
- clientSupportsQuestions: boolean
162
- sessionId: string | undefined
163
- extensionSessions: Pick<ExtensionSessionRegistry, 'has'>
164
- }): boolean {
165
- return resolveInteractionOwnership({
166
- hasExtensionConnection: input.hasExtensionConnection,
167
- clientSupports: input.clientSupportsQuestions,
168
- sessionId: input.sessionId,
169
- sources: { driven: input.extensionSessions },
170
- }).owned
171
- }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * In-process owner Peer for Typert Remote dispatch.
3
+ *
4
+ * dsh 0.2.1 requires every `typertGateway.invoke` / `stream` request to name a
5
+ * live {@link PeerScope}: the Gateway reads `peer.signal` and `peer.principal`
6
+ * without a fallback, because the 0.2.0 operator-peer default is gone. The
7
+ * bridge mounts its own token-authenticated carrier, so it speaks as the host
8
+ * owner; the Peer lives exactly as long as the plugin fiber.
9
+ *
10
+ * @module
11
+ */
12
+
13
+ import { randomUUID } from 'node:crypto'
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import type { InvokeRemoteRequest } from '@deepseek-ai/dsh-api-gateway/types'
16
+
17
+ /** The Peer a Gateway request must name (required since dsh 0.2.1). */
18
+ export type GatewayPeer = InvokeRemoteRequest['peer']
19
+
20
+ /**
21
+ * Create the bridge's owner Peer and tie its lifetime to the calling fiber.
22
+ *
23
+ * The returned scope is structurally a full `PeerScope`; the Gateway only
24
+ * needs `id`, `principal`, `signal`, and `interactions` for unary calls and
25
+ * streams, while `ctx` keeps a future event-stream registration fiber-scoped.
26
+ *
27
+ * @param ctx - plugin context whose disposal aborts the peer.
28
+ * @returns a live owner Peer that is aborted when the plugin unloads.
29
+ */
30
+ export function createGatewayPeer(ctx: Context): GatewayPeer {
31
+ const lifetime = new AbortController()
32
+ const dispose = async (): Promise<void> => {
33
+ if (!lifetime.signal.aborted) {
34
+ lifetime.abort(new Error('bridge-browser: gateway peer disposed'))
35
+ }
36
+ }
37
+ ctx.effect(() => () => { void dispose() }, 'bridge-browser: gateway peer')
38
+ return {
39
+ id: randomUUID() as GatewayPeer['id'],
40
+ ctx,
41
+ principal: { kind: 'owner' },
42
+ signal: lifetime.signal,
43
+ interactions: 'none',
44
+ dispose,
45
+ }
46
+ }
package/src/index.ts CHANGED
@@ -32,6 +32,7 @@ import type {} from '@deepseek-ai/dsh-tools'
32
32
  import type {} from '@deepseek-ai/dsh-api-gateway/types'
33
33
  import type {} from '@deepseek-ai/dsh-user-questions/types'
34
34
  import type { ApprovalRequestEvent } from '@deepseek-ai/dsh-user-approval/types'
35
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
35
36
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
36
37
  import { readFileSync } from 'node:fs'
37
38
  import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
@@ -41,6 +42,7 @@ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, type RemoteWireResult } from './protoc
41
42
  import { withSessionDeferral } from './session-deferral.ts'
42
43
  import { withSessionWorkspace, type RpcDispatch } from './session-workspace.ts'
43
44
  import { resolveToken } from './token.ts'
45
+ import { createGatewayPeer } from './gateway-peer.ts'
44
46
  import { ExtensionSessionRegistry, FollowedSessions, resolveInteractionOwnership, type DelegateReason } from './extension-sessions.ts'
45
47
  import { asQuestionAnswerArgs, QuestionBridge } from './questions.ts'
46
48
  import { ApprovalBridge, asApprovalDecisionArgs } from './approvals.ts'
@@ -155,6 +157,9 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
155
157
  const resolved = resolveConfig(config)
156
158
 
157
159
  const tokenRes = await resolveToken(resolved.token)
160
+ // dsh 0.2.1 made the Gateway Peer mandatory; the bridge's token-authenticated
161
+ // carrier speaks as the host owner and aborts the peer when this fiber dies.
162
+ const peer = createGatewayPeer(ctx)
158
163
  // Base dispatch: split the slash-joined endpoint and invoke the Remote
159
164
  // method; Remote failures are folded into the wire result (never thrown
160
165
  // across the bridge), everything else is an internal failure.
@@ -163,7 +168,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
163
168
  const namespace = slash === -1 ? method : method.slice(0, slash)
164
169
  const remoteMethod = slash === -1 ? '' : method.slice(slash + 1)
165
170
  try {
166
- const value = await ctx.typertGateway.invoke({ namespace, method: remoteMethod, args, signal })
171
+ const value = await ctx.typertGateway.invoke({ namespace, method: remoteMethod, args, signal, peer })
167
172
  return { ok: true, value }
168
173
  } catch (error: unknown) {
169
174
  const failure = ctx.typertGateway.wireStream.failure(error)
@@ -192,10 +197,13 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
192
197
  const ownershipSources = { driven: extensionSessions, followed: followedSessions }
193
198
  // Subagent child sessions inherit their parent's ownership: a question asked
194
199
  // by a delegated agent belongs in the conversation the user is watching.
195
- const sessions = ctx.get('sessions')
196
- const parentOf = sessions === undefined
197
- ? undefined
198
- : (sessionId: string): string | undefined => sessions.get(sessionId as never)?.header.parentSession
200
+ // The Session store is read lazily on every hop: capturing it once at mount
201
+ // would silently disable inheritance whenever it is registered after this
202
+ // plugin (or recreated by an HMR reload).
203
+ const parentOf = (sessionId: string): string | undefined => {
204
+ const sessions = ctx.get('sessions')
205
+ return sessions?.get(sessionId as SessionId)?.header.parentSession
206
+ }
199
207
  const notingDispatchRpc: RpcDispatch = async (method, args, signal) => {
200
208
  const tracksOwnership = method === 'session/create' || method === 'session/prompt'
201
209
  const dispatched = tracksOwnership ? sessionIdOf(args.request) : undefined
@@ -237,7 +245,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
237
245
  const slash = method.indexOf('/')
238
246
  const namespace = slash === -1 ? method : method.slice(0, slash)
239
247
  const remoteMethod = slash === -1 ? '' : method.slice(slash + 1)
240
- return ctx.typertGateway.stream({ namespace, method: remoteMethod, args, signal })
248
+ return ctx.typertGateway.stream({ namespace, method: remoteMethod, args, signal, peer })
241
249
  },
242
250
  answerQuestion: (args) => {
243
251
  const parsed = asQuestionAnswerArgs(args)
@@ -277,8 +285,12 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
277
285
  // Prepended so the claim runs before the Remote event forwarding listener
278
286
  // in dsh-api-remotes. Delegations are logged with the failing gate so an
279
287
  // "invisible card" report is diagnosable from the host log.
288
+ // 委托日志:只有「扩展在线但不支持该卡片」是用户可操作的(扩展版本旧),
289
+ // 其余(无连接、会话不归属)在 dsh web 会话里每次都发生,压到 debug 免得刷屏。
280
290
  const logDelegation = (kind: 'user-questions' | 'approval', sessionId: string | undefined, reason: DelegateReason): void => {
281
- ctx.logger.info(`browser bridge: delegated ${kind} for session ${sessionId ?? '<unknown>'} (${reason})`)
291
+ const line = `browser bridge: delegated ${kind} for session ${sessionId ?? '<unknown>'} (${reason})`
292
+ if (reason === 'unsupported-client') ctx.logger.info(line)
293
+ else ctx.logger.debug(line)
282
294
  }
283
295
  ctx.effect(() => {
284
296
  const disposeListener = ctx.on('user-questions/request', (request, next) => {
@@ -287,7 +299,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
287
299
  clientSupports: server.clientSupportsQuestions(),
288
300
  sessionId: request.agent?.id,
289
301
  sources: ownershipSources,
290
- ...(parentOf === undefined ? {} : { parentOf }),
302
+ parentOf,
291
303
  })
292
304
  if (!ownership.owned) {
293
305
  logDelegation('user-questions', request.agent?.id, ownership.reason)
@@ -310,18 +322,19 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
310
322
  clientSupports: server.clientSupportsApprovals(),
311
323
  sessionId: request.agent?.id,
312
324
  sources: ownershipSources,
313
- ...(parentOf === undefined ? {} : { parentOf }),
325
+ parentOf,
314
326
  })
315
327
  if (!ownership.owned) {
316
328
  logDelegation('approval', request.agent?.id, ownership.reason)
317
329
  return next()
318
330
  }
331
+ const reason = approvalReasonText(request)
319
332
  return approvals.ask(
320
333
  ownership.sessionId,
321
334
  {
322
335
  toolName: request.toolName,
323
336
  ...(typeof request.callId === 'string' ? { callId: request.callId } : {}),
324
- ...(approvalReasonText(request) === undefined ? {} : { reason: approvalReasonText(request) as string }),
337
+ ...(reason === undefined ? {} : { reason }),
325
338
  },
326
339
  next,
327
340
  request.signal,
package/src/protocol.ts CHANGED
File without changes
package/src/questions.ts CHANGED
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { randomUUID } from 'node:crypto'
20
20
  import type { QuestionItem, ServerFrame } from './protocol.ts'
21
+ import { PendingWaterfalls } from './waterfall.ts'
21
22
 
22
23
  /** One answer item, mirroring the host AskUserQuestionAnswerItem wire form. */
23
24
  export interface QuestionAnswerItem {
@@ -49,15 +50,6 @@ type PendingOutcome =
49
50
  | { kind: 'reject'; error: Error }
50
51
  | { kind: 'delegate' }
51
52
 
52
- interface PendingQuestion {
53
- readonly sessionId: string
54
- readonly questionIds: ReadonlySet<string>
55
- settled: boolean
56
- readonly complete: (outcome: PendingOutcome) => void
57
- readonly signal: AbortSignal | undefined
58
- onAbort: (() => void) | undefined
59
- }
60
-
61
53
  /** Error matching the host's ASK_ABORTED semantics (the service remaps it). */
62
54
  function abortedError(): Error {
63
55
  return new Error('ask_user_question was aborted before the user answered')
@@ -99,7 +91,7 @@ export function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs | undef
99
91
 
100
92
  /** Owns the user-questions waterfall for extension-driven sessions. */
101
93
  export class QuestionBridge {
102
- private readonly pending = new Map<string, PendingQuestion>()
94
+ private readonly waterfalls = new PendingWaterfalls<PendingOutcome, ReadonlySet<string>>()
103
95
 
104
96
  constructor(private readonly deps: {
105
97
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
@@ -124,33 +116,28 @@ export class QuestionBridge {
124
116
  ): Promise<QuestionAnswerPayload> {
125
117
  if (signal?.aborted) return Promise.reject(abortedError())
126
118
  const questionId = randomUUID()
119
+ const questionIds = new Set(questions.map(question => question.id))
127
120
  return new Promise<QuestionAnswerPayload>((resolve, reject) => {
128
- const entry: PendingQuestion = {
121
+ const settle = (outcome: PendingOutcome): void => {
122
+ this.waterfalls.settle(questionId, outcome)
123
+ }
124
+ this.waterfalls.register({
125
+ id: questionId,
129
126
  sessionId,
130
- questionIds: new Set(questions.map(question => question.id)),
131
- settled: false,
132
127
  signal,
128
+ payload: questionIds,
133
129
  complete: (outcome) => {
134
- if (entry.settled) return
135
- entry.settled = true
136
- this.pending.delete(questionId)
137
- if (entry.onAbort !== undefined) entry.signal?.removeEventListener('abort', entry.onAbort)
138
130
  if (outcome.kind === 'answer') resolve(outcome.answer)
139
131
  else if (outcome.kind === 'reject') reject(outcome.error)
140
132
  else next().then(resolve, reject)
141
133
  },
142
- onAbort: undefined,
143
- }
144
- if (signal !== undefined) {
145
- entry.onAbort = () => {
134
+ onAbort: () => {
146
135
  // Tell the extension to drop the card before settling so a late
147
136
  // answer can never report acceptance for a dead request.
148
137
  this.deps.push({ t: 'question.resolved', id: questionId, sessionId })
149
- entry.complete({ kind: 'reject', error: abortedError() })
150
- }
151
- signal.addEventListener('abort', entry.onAbort, { once: true })
152
- }
153
- this.pending.set(questionId, entry)
138
+ settle({ kind: 'reject', error: abortedError() })
139
+ },
140
+ })
154
141
  this.deps.push({ t: 'question.requested', id: questionId, sessionId, questions })
155
142
  })
156
143
  }
@@ -160,33 +147,28 @@ export class QuestionBridge {
160
147
  * rpc. The server replies with this receipt.
161
148
  */
162
149
  answer(args: QuestionAnswerArgs): QuestionAnswerReceipt {
163
- const entry = this.pending.get(args.questionId)
164
- if (entry === undefined || entry.settled || entry.sessionId !== args.sessionId) {
150
+ if (!this.waterfalls.matches(args.questionId, args.sessionId)) {
165
151
  return { accepted: false, reason: 'not-pending' }
166
152
  }
167
153
  if (args.decline === true) {
168
- entry.complete({ kind: 'reject', error: declinedError() })
154
+ this.waterfalls.settle(args.questionId, { kind: 'reject', error: declinedError() })
169
155
  return { accepted: true }
170
156
  }
171
- const answer = asAnswerPayload(args.answer, entry.questionIds)
157
+ const answer = asAnswerPayload(args.answer, this.waterfalls.payloadOf(args.questionId) ?? new Set())
172
158
  if (answer === undefined) return { accepted: false, reason: 'bad-answer' }
173
- entry.complete({ kind: 'answer', answer })
159
+ this.waterfalls.settle(args.questionId, { kind: 'answer', answer })
174
160
  return { accepted: true }
175
161
  }
176
162
 
177
163
  /** Bridge connection replaced/closed: delegate every unsettled question. */
178
164
  delegateAll(): void {
179
- for (const entry of [...this.pending.values()]) {
180
- if (!entry.settled) entry.complete({ kind: 'delegate' })
181
- }
165
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: 'delegate' })
182
166
  }
183
167
 
184
168
  /** Plugin unload: reject everything so no tool call outlives the plugin. */
185
169
  dispose(): void {
186
- for (const entry of [...this.pending.values()]) {
187
- if (!entry.settled) {
188
- entry.complete({ kind: 'reject', error: new Error('browser bridge plugin was unloaded') })
189
- }
170
+ for (const id of this.waterfalls.ids()) {
171
+ this.waterfalls.settle(id, { kind: 'reject', error: new Error('browser bridge plugin was unloaded') })
190
172
  }
191
173
  }
192
174
  }