dsh-browser-firefox 0.4.6 → 0.4.7

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.
@@ -1,8 +1,18 @@
1
1
  /**
2
2
  * Track session ids that the browser extension has driven through the bridge.
3
- * Sessions the extension never touched must keep the host userQuestions
4
- * waterfall so the dsh web UI (or any other answerer) renders
5
- * ask_user_question cards.
3
+ * Sessions the extension never touched must keep the host waterfalls
4
+ * (user-questions, approvals) so the dsh web UI (or any other answerer)
5
+ * renders the cards.
6
+ *
7
+ * Ownership has three sources, all revocable:
8
+ * - **driven**: the extension created or prompted the session (kept until the
9
+ * plugin unloads);
10
+ * - **followed**: an open `session/follow` stream means the sidebar is
11
+ * displaying that session right now (released when the stream closes);
12
+ * - **inherited**: an ask from a subagent child session belongs to the
13
+ * nearest extension-owned ancestor, so child questions/approvals surface in
14
+ * the parent conversation the user is actually watching.
15
+ *
6
16
  * @module
7
17
  */
8
18
  /** Mutable registry of extension-owned session ids. */
@@ -10,17 +20,79 @@ export declare class ExtensionSessionRegistry {
10
20
  private readonly ids;
11
21
  /** Remember a session the extension successfully created or prompted. */
12
22
  note(sessionId: string | undefined): void;
23
+ /** Forget a session (a failed dispatch revoked an optimistic note). */
24
+ forget(sessionId: string | undefined): void;
13
25
  /** Whether the extension has touched this session over the bridge. */
14
26
  has(sessionId: string | undefined): boolean;
15
27
  /** Test helper: drop all tracked ids. */
16
28
  clear(): void;
17
29
  }
30
+ /**
31
+ * Live `session/follow` subscriptions: the sidebar is displaying these
32
+ * sessions, so they count as extension-owned while the stream is open.
33
+ * Reference-counted per session because one session can be followed by more
34
+ * than one panel connection.
35
+ */
36
+ export declare class FollowedSessions {
37
+ private readonly counts;
38
+ /** Register one open follow stream for a session. */
39
+ open(sessionId: string | undefined): void;
40
+ /** Release one follow stream; the last release drops the session. */
41
+ close(sessionId: string | undefined): void;
42
+ /** Whether any open follow stream is displaying this session. */
43
+ has(sessionId: string | undefined): boolean;
44
+ /** Drop every subscription (bridge generation replacement, plugin unload). */
45
+ clear(): void;
46
+ }
47
+ /** Ownership sources consulted by {@link owningSessionId}. */
48
+ export interface OwnershipSources {
49
+ /** Sessions the extension created or prompted. */
50
+ driven: Pick<ExtensionSessionRegistry, 'has'>;
51
+ /** Sessions an open follow stream is displaying. */
52
+ followed?: Pick<FollowedSessions, 'has'>;
53
+ }
54
+ /** Maximum ancestor hops when looking for an owned session. */
55
+ export declare const MAX_OWNER_DEPTH = 8;
56
+ /** Whether one exact session id is extension-owned by either source. */
57
+ export declare function isOwnedSession(sessionId: string | undefined, sources: OwnershipSources): boolean;
58
+ /**
59
+ * Resolve which session id the sidebar card should be filed under: the asking
60
+ * session itself when it is owned, otherwise the nearest owned ancestor (a
61
+ * subagent child session inherits its parent's ownership).
62
+ *
63
+ * @param sessionId - the asking session (the host event's agent id).
64
+ * @param sources - ownership sources.
65
+ * @param parentOf - session-id → parent-session-id lookup; absent disables inheritance.
66
+ * @returns the owned session id to route to, or undefined when nothing owns it.
67
+ */
68
+ export declare function owningSessionId(sessionId: string | undefined, sources: OwnershipSources, parentOf?: (sessionId: string) => string | undefined): string | undefined;
69
+ /** Why a host interaction was delegated to the next answerer. */
70
+ export type DelegateReason = 'no-connection' | 'unsupported-client' | 'not-owned';
71
+ /** One interaction-ownership decision, kept inspectable for logging and tests. */
72
+ export type InteractionOwnership = {
73
+ owned: true;
74
+ sessionId: string;
75
+ } | {
76
+ owned: false;
77
+ reason: DelegateReason;
78
+ };
79
+ /**
80
+ * Decide whether the bridge should own one host interaction (question or
81
+ * approval). All gates must pass: an extension is connected, it advertised
82
+ * the matching card capability in its hello caps, and the asking session is
83
+ * extension-owned (directly or through an owned ancestor). Everything else
84
+ * falls through to `next()` so the native answerer waterfall keeps working.
85
+ */
86
+ export declare function resolveInteractionOwnership(input: {
87
+ hasExtensionConnection: boolean;
88
+ clientSupports: boolean;
89
+ sessionId: string | undefined;
90
+ sources: OwnershipSources;
91
+ parentOf?: (sessionId: string) => string | undefined;
92
+ }): InteractionOwnership;
18
93
  /**
19
94
  * Decide whether the bridge should own ask_user_question for this request.
20
- * All three gates must pass: an extension is connected, that extension
21
- * advertised question-card support in its hello caps, and the asking session
22
- * was driven over the bridge. Everything else falls through to `next()` so
23
- * the native answerer waterfall (dsh web) keeps working.
95
+ * Thin compatibility wrapper over {@link resolveInteractionOwnership}.
24
96
  */
25
97
  export declare function shouldBridgeOwnQuestion(input: {
26
98
  hasExtensionConnection: boolean;
@@ -51,6 +51,8 @@ export interface BridgeCaps {
51
51
  maxInteractiveItems: number;
52
52
  /** Client advertises it can render ask_user_question cards; the plugin only claims the user-questions waterfall for extension-owned sessions when set. */
53
53
  questions?: boolean;
54
+ /** Client advertises it can render host approval (permission) cards; the plugin only claims the approval waterfall for extension-owned sessions when set. */
55
+ approvals?: boolean;
54
56
  }
55
57
  /** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
56
58
  export interface RemoteWireFailure {
@@ -194,6 +196,29 @@ export type ServerFrame =
194
196
  id: string;
195
197
  sessionId: string;
196
198
  }
199
+ /**
200
+ * The host needs one approval decision (a hooked tool call, a permission
201
+ * ask) in an extension-owned session and the bridge claimed the waterfall:
202
+ * the extension should render an approval card. The decision rides a normal
203
+ * `rpc` frame with the plugin-local method `bridge/approvalDecision` (args
204
+ * `{approvalId, sessionId, decision: 'allowed-once' | 'rejected'}`),
205
+ * answered `{accepted: true} | {accepted: false, reason: 'not-pending' |
206
+ * 'bad-decision'}`.
207
+ */
208
+ | {
209
+ t: 'approval.requested';
210
+ id: string;
211
+ sessionId: string;
212
+ toolName: string;
213
+ callId?: string;
214
+ reason?: string;
215
+ }
216
+ /** A previously pushed approval is gone (host cancelled it or the bridge delegated the waterfall elsewhere); dismiss the card without deciding. */
217
+ | {
218
+ t: 'approval.resolved';
219
+ id: string;
220
+ sessionId: string;
221
+ }
197
222
  /** Liveness probe. */
198
223
  | {
199
224
  t: 'ping';
@@ -64,6 +64,18 @@ export interface BridgeServerDeps {
64
64
  * rpc result value `{accepted: true} | {accepted: false, reason}`.
65
65
  */
66
66
  answerQuestion: (args: Record<string, unknown>) => unknown;
67
+ /**
68
+ * Plugin-local endpoint `bridge/approvalDecision`: settle one pending host
69
+ * approval the bridge pushed to this extension. Answered as the rpc result
70
+ * value `{accepted: true} | {accepted: false, reason}`.
71
+ */
72
+ answerApproval: (args: Record<string, unknown>) => unknown;
73
+ /**
74
+ * A `session/follow` stream opened (`open: true`) or ended (`open: false`)
75
+ * for a session: the sidebar is displaying that session while the stream
76
+ * lives, so interaction ownership can follow the visible conversation.
77
+ */
78
+ onFollowChanged?: (sessionId: string, open: boolean) => void;
67
79
  /** The active connection was replaced or closed (settle pushed questions). */
68
80
  onConnectionLost?: () => void;
69
81
  /**
@@ -133,6 +145,8 @@ export declare class BridgeServer {
133
145
  hasConnection(): boolean;
134
146
  /** @returns whether the connected extension advertised question-card support. */
135
147
  clientSupportsQuestions(): boolean;
148
+ /** @returns whether the connected extension advertised approval-card support. */
149
+ clientSupportsApprovals(): boolean;
136
150
  /**
137
151
  * Push one unsolicited server frame (question.requested/question.resolved)
138
152
  * to the connected extension. No-op when no extension is connected or the
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.6",
4
+ "version": "0.4.7",
5
5
  "author": "tuojc",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -53,18 +53,20 @@
53
53
  ],
54
54
  "peerDependencies": {
55
55
  "@deepseek-ai/cordis": "^4.0.2",
56
- "@deepseek-ai/dsh-api-gateway": "^0.1.2-alpha.2",
57
- "@deepseek-ai/dsh-api-session-controller": "^0.1.2-alpha.2",
58
- "@deepseek-ai/dsh-api-workspace-controller": "^0.1.2-alpha.2",
59
- "@deepseek-ai/dsh-attachment": "^0.1.2-alpha.2",
60
- "@deepseek-ai/dsh-host-webserver": "^0.1.2-alpha.2",
61
- "@deepseek-ai/dsh-invariants": "^0.1.2-alpha.2",
62
- "@deepseek-ai/dsh-home-paths": "^0.1.2-alpha.2",
63
- "@deepseek-ai/dsh-tools": "^0.1.2-alpha.2",
64
- "@deepseek-ai/dsh-user-questions": "^0.1.2-alpha.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"
65
67
  },
66
68
  "dependencies": {
67
- "@deepseek-ai/schemastery": "^3.18.1",
69
+ "@deepseek-ai/schemastery": "^3.18.4",
68
70
  "ws": "^8.21.0"
69
71
  },
70
72
  "scripts": {
@@ -74,32 +76,33 @@
74
76
  "prepublishOnly": "pnpm run build"
75
77
  },
76
78
  "devDependencies": {
77
- "@deepseek-ai/cordis": "4.0.2",
78
- "@deepseek-ai/cordis-plugin-include": "1.0.7",
79
- "@deepseek-ai/cordis-plugin-loader": "1.0.3",
80
- "@deepseek-ai/dsh-agent": "0.1.2-alpha.5",
81
- "@deepseek-ai/dsh-agent-loop": "0.1.2-alpha.5",
82
- "@deepseek-ai/dsh-api-gateway": "0.1.2-alpha.5",
83
- "@deepseek-ai/dsh-api-session-controller": "0.1.2-alpha.5",
84
- "@deepseek-ai/dsh-api-workspace-controller": "0.1.2-alpha.5",
85
- "@deepseek-ai/dsh-attachment": "0.1.2-alpha.5",
86
- "@deepseek-ai/dsh-host-webserver": "0.1.2-alpha.5",
87
- "@deepseek-ai/dsh-invariants": "0.1.2-alpha.5",
88
- "@deepseek-ai/dsh-llm": "0.1.2-alpha.5",
89
- "@deepseek-ai/dsh-home-paths": "0.1.2-alpha.5",
90
- "@deepseek-ai/dsh-session": "0.1.2-alpha.5",
91
- "@deepseek-ai/dsh-storage": "0.1.2-alpha.5",
92
- "@deepseek-ai/dsh-storage-domain": "0.1.2-alpha.5",
93
- "@deepseek-ai/dsh-storage-json": "0.1.2-alpha.5",
94
- "@deepseek-ai/dsh-system-prompt": "0.1.2-alpha.5",
95
- "@deepseek-ai/dsh-tools": "0.1.2-alpha.5",
96
- "@deepseek-ai/dsh-user-questions": "0.1.2-alpha.5",
97
- "@deepseek-ai/dsh-workspace": "0.1.2-alpha.5",
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",
98
100
  "@types/node": "^22.20.0",
99
101
  "@types/ws": "^8.18.1",
100
102
  "playwright-core": "^1.61.1",
101
103
  "tsdown": "0.22.2",
102
104
  "typescript": "^6.0.3",
103
- "vitest": "^4.1.8"
105
+ "vitest": "^4.1.8",
106
+ "@deepseek-ai/dsh-user-approval": "0.2.0-rc.1"
104
107
  }
105
108
  }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Host approval ownership: claim the host `approval/request` waterfall for
3
+ * extension-owned sessions, push the decision request to the connected
4
+ * extension, and settle the waterfall with the sidebar's choice.
5
+ *
6
+ * Settlement paths (first wins, later ones no-op):
7
+ * - the sidebar decides → the waterfall resolves with that outcome;
8
+ * - the host aborts `request.signal` (turn cancelled, session disposed) →
9
+ * the extension is sent `approval.resolved` and the waterfall resolves
10
+ * with `'cancelled'` (the host vocabulary has no rejection channel here);
11
+ * - the bridge connection drops ({@link delegateAll}) → the waterfall is
12
+ * delegated to `next()` so another answerer (dsh web) can still decide;
13
+ * - plugin unload ({@link dispose}) → `'unavailable'`, the fail-closed
14
+ * outcome of the host's closed outcome set.
15
+ *
16
+ * @module
17
+ */
18
+
19
+ import { randomUUID } from 'node:crypto'
20
+ import type { ServerFrame } from './protocol.ts'
21
+
22
+ /** The host's closed approval outcome vocabulary. */
23
+ export type ApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'
24
+
25
+ /** One approval prompt as it crosses the bridge. */
26
+ export interface ApprovalPrompt {
27
+ toolName: string
28
+ callId?: string
29
+ reason?: string
30
+ }
31
+
32
+ /** Decision the sidebar sends back over `bridge/approvalDecision`. */
33
+ export type ApprovalDecision = 'allowed-once' | 'rejected'
34
+
35
+ /** Receipt answered to the extension's `bridge/approvalDecision` rpc. */
36
+ export type ApprovalReceipt =
37
+ | { accepted: true }
38
+ | { accepted: false; reason: 'not-pending' | 'bad-decision' }
39
+
40
+ /** Args of the plugin-local `bridge/approvalDecision` rpc method. */
41
+ export interface ApprovalDecisionArgs {
42
+ approvalId: string
43
+ sessionId: string
44
+ decision?: unknown
45
+ }
46
+
47
+ type PendingOutcome =
48
+ | { kind: 'decide'; outcome: ApprovalOutcome }
49
+ | { kind: 'delegate' }
50
+
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
+ /** Parse the extension's `bridge/approvalDecision` rpc args (ids + closed decision). */
60
+ export function asApprovalDecisionArgs(value: unknown): ApprovalDecisionArgs | undefined {
61
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
62
+ const args = value as Record<string, unknown>
63
+ 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 }
66
+ }
67
+
68
+ /** Owns the host approval waterfall for extension-driven sessions. */
69
+ export class ApprovalBridge {
70
+ private readonly pending = new Map<string, PendingApproval>()
71
+
72
+ constructor(private readonly deps: {
73
+ /** Push one server frame to the connected extension (must tolerate a dead socket). */
74
+ push: (frame: ServerFrame) => void
75
+ }) {}
76
+
77
+ /**
78
+ * Own one host waterfall request: push `approval.requested` to the
79
+ * extension and suspend until one of the settlement paths wins.
80
+ *
81
+ * @param routingSessionId - extension-visible session id (the owned session the card is filed under).
82
+ * @param prompt - tool name, optional call id and human-readable reason.
83
+ * @param next - waterfall delegation, used when the bridge connection drops.
84
+ * @param signal - host cancellation lifetime for this request.
85
+ * @returns the host approval outcome.
86
+ */
87
+ ask(
88
+ routingSessionId: string,
89
+ prompt: ApprovalPrompt,
90
+ next: () => Promise<ApprovalOutcome>,
91
+ signal?: AbortSignal,
92
+ ): Promise<ApprovalOutcome> {
93
+ if (signal?.aborted) return Promise.resolve<ApprovalOutcome>('cancelled')
94
+ const approvalId = randomUUID()
95
+ return new Promise<ApprovalOutcome>((resolve, reject) => {
96
+ const entry: PendingApproval = {
97
+ sessionId: routingSessionId,
98
+ settled: false,
99
+ signal,
100
+ 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
+ if (outcome.kind === 'decide') resolve(outcome.outcome)
106
+ else next().then(resolve, reject)
107
+ },
108
+ onAbort: undefined,
109
+ }
110
+ if (signal !== undefined) {
111
+ entry.onAbort = () => {
112
+ // Withdraw the card before settling so a late click can never be
113
+ // reported as accepted for a dead request.
114
+ 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)
120
+ this.deps.push({
121
+ t: 'approval.requested',
122
+ id: approvalId,
123
+ sessionId: routingSessionId,
124
+ toolName: prompt.toolName,
125
+ ...(prompt.callId === undefined ? {} : { callId: prompt.callId }),
126
+ ...(prompt.reason === undefined ? {} : { reason: prompt.reason }),
127
+ })
128
+ })
129
+ }
130
+
131
+ /**
132
+ * Settle one pending approval from the extension's `bridge/approvalDecision`
133
+ * rpc. The server replies with this receipt.
134
+ */
135
+ decide(args: ApprovalDecisionArgs): ApprovalReceipt {
136
+ const entry = this.pending.get(args.approvalId)
137
+ if (entry === undefined || entry.settled || entry.sessionId !== args.sessionId) {
138
+ return { accepted: false, reason: 'not-pending' }
139
+ }
140
+ if (args.decision !== 'allowed-once' && args.decision !== 'rejected') {
141
+ return { accepted: false, reason: 'bad-decision' }
142
+ }
143
+ entry.complete({ kind: 'decide', outcome: args.decision })
144
+ return { accepted: true }
145
+ }
146
+
147
+ /** Bridge connection replaced/closed: delegate every unsettled approval. */
148
+ delegateAll(): void {
149
+ for (const entry of [...this.pending.values()]) {
150
+ if (!entry.settled) entry.complete({ kind: 'delegate' })
151
+ }
152
+ }
153
+
154
+ /** Plugin unload: answer everything fail-closed so no tool call outlives the plugin. */
155
+ dispose(): void {
156
+ for (const entry of [...this.pending.values()]) {
157
+ if (!entry.settled) entry.complete({ kind: 'decide', outcome: 'unavailable' })
158
+ }
159
+ }
160
+ }
@@ -1,8 +1,18 @@
1
1
  /**
2
2
  * Track session ids that the browser extension has driven through the bridge.
3
- * Sessions the extension never touched must keep the host userQuestions
4
- * waterfall so the dsh web UI (or any other answerer) renders
5
- * ask_user_question cards.
3
+ * Sessions the extension never touched must keep the host waterfalls
4
+ * (user-questions, approvals) so the dsh web UI (or any other answerer)
5
+ * renders the cards.
6
+ *
7
+ * Ownership has three sources, all revocable:
8
+ * - **driven**: the extension created or prompted the session (kept until the
9
+ * plugin unloads);
10
+ * - **followed**: an open `session/follow` stream means the sidebar is
11
+ * displaying that session right now (released when the stream closes);
12
+ * - **inherited**: an ask from a subagent child session belongs to the
13
+ * nearest extension-owned ancestor, so child questions/approvals surface in
14
+ * the parent conversation the user is actually watching.
15
+ *
6
16
  * @module
7
17
  */
8
18
 
@@ -15,6 +25,11 @@ export class ExtensionSessionRegistry {
15
25
  if (typeof sessionId === 'string' && sessionId.length > 0) this.ids.add(sessionId)
16
26
  }
17
27
 
28
+ /** Forget a session (a failed dispatch revoked an optimistic note). */
29
+ forget(sessionId: string | undefined): void {
30
+ if (typeof sessionId === 'string') this.ids.delete(sessionId)
31
+ }
32
+
18
33
  /** Whether the extension has touched this session over the bridge. */
19
34
  has(sessionId: string | undefined): boolean {
20
35
  return typeof sessionId === 'string' && this.ids.has(sessionId)
@@ -26,12 +41,120 @@ export class ExtensionSessionRegistry {
26
41
  }
27
42
  }
28
43
 
44
+ /**
45
+ * Live `session/follow` subscriptions: the sidebar is displaying these
46
+ * sessions, so they count as extension-owned while the stream is open.
47
+ * Reference-counted per session because one session can be followed by more
48
+ * than one panel connection.
49
+ */
50
+ export class FollowedSessions {
51
+ private readonly counts = new Map<string, number>()
52
+
53
+ /** Register one open follow stream for a session. */
54
+ open(sessionId: string | undefined): void {
55
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return
56
+ this.counts.set(sessionId, (this.counts.get(sessionId) ?? 0) + 1)
57
+ }
58
+
59
+ /** Release one follow stream; the last release drops the session. */
60
+ close(sessionId: string | undefined): void {
61
+ if (typeof sessionId !== 'string') return
62
+ const current = this.counts.get(sessionId)
63
+ if (current === undefined) return
64
+ if (current <= 1) this.counts.delete(sessionId)
65
+ else this.counts.set(sessionId, current - 1)
66
+ }
67
+
68
+ /** Whether any open follow stream is displaying this session. */
69
+ has(sessionId: string | undefined): boolean {
70
+ return typeof sessionId === 'string' && this.counts.has(sessionId)
71
+ }
72
+
73
+ /** Drop every subscription (bridge generation replacement, plugin unload). */
74
+ clear(): void {
75
+ this.counts.clear()
76
+ }
77
+ }
78
+
79
+ /** Ownership sources consulted by {@link owningSessionId}. */
80
+ export interface OwnershipSources {
81
+ /** Sessions the extension created or prompted. */
82
+ driven: Pick<ExtensionSessionRegistry, 'has'>
83
+ /** Sessions an open follow stream is displaying. */
84
+ followed?: Pick<FollowedSessions, 'has'>
85
+ }
86
+
87
+ /** Maximum ancestor hops when looking for an owned session. */
88
+ export const MAX_OWNER_DEPTH = 8
89
+
90
+ /** Whether one exact session id is extension-owned by either source. */
91
+ export function isOwnedSession(sessionId: string | undefined, sources: OwnershipSources): boolean {
92
+ if (sessionId === undefined) return false
93
+ return sources.driven.has(sessionId) || sources.followed?.has(sessionId) === true
94
+ }
95
+
96
+ /**
97
+ * Resolve which session id the sidebar card should be filed under: the asking
98
+ * session itself when it is owned, otherwise the nearest owned ancestor (a
99
+ * subagent child session inherits its parent's ownership).
100
+ *
101
+ * @param sessionId - the asking session (the host event's agent id).
102
+ * @param sources - ownership sources.
103
+ * @param parentOf - session-id → parent-session-id lookup; absent disables inheritance.
104
+ * @returns the owned session id to route to, or undefined when nothing owns it.
105
+ */
106
+ export function owningSessionId(
107
+ sessionId: string | undefined,
108
+ sources: OwnershipSources,
109
+ parentOf?: (sessionId: string) => string | undefined,
110
+ ): string | undefined {
111
+ if (sessionId === undefined) return undefined
112
+ if (isOwnedSession(sessionId, sources)) return sessionId
113
+ if (parentOf === undefined) return undefined
114
+ const seen = new Set<string>([sessionId])
115
+ let current = sessionId
116
+ for (let depth = 0; depth < MAX_OWNER_DEPTH; depth += 1) {
117
+ const parent = parentOf(current)
118
+ if (parent === undefined || parent.length === 0 || seen.has(parent)) return undefined
119
+ if (isOwnedSession(parent, sources)) return parent
120
+ seen.add(parent)
121
+ current = parent
122
+ }
123
+ return undefined
124
+ }
125
+
126
+ /** Why a host interaction was delegated to the next answerer. */
127
+ export type DelegateReason = 'no-connection' | 'unsupported-client' | 'not-owned'
128
+
129
+ /** One interaction-ownership decision, kept inspectable for logging and tests. */
130
+ export type InteractionOwnership =
131
+ | { owned: true; sessionId: string }
132
+ | { owned: false; reason: DelegateReason }
133
+
134
+ /**
135
+ * Decide whether the bridge should own one host interaction (question or
136
+ * approval). All gates must pass: an extension is connected, it advertised
137
+ * the matching card capability in its hello caps, and the asking session is
138
+ * extension-owned (directly or through an owned ancestor). Everything else
139
+ * falls through to `next()` so the native answerer waterfall keeps working.
140
+ */
141
+ export function resolveInteractionOwnership(input: {
142
+ hasExtensionConnection: boolean
143
+ clientSupports: boolean
144
+ sessionId: string | undefined
145
+ sources: OwnershipSources
146
+ parentOf?: (sessionId: string) => string | undefined
147
+ }): InteractionOwnership {
148
+ if (!input.hasExtensionConnection) return { owned: false, reason: 'no-connection' }
149
+ if (!input.clientSupports) return { owned: false, reason: 'unsupported-client' }
150
+ const sessionId = owningSessionId(input.sessionId, input.sources, input.parentOf)
151
+ if (sessionId === undefined) return { owned: false, reason: 'not-owned' }
152
+ return { owned: true, sessionId }
153
+ }
154
+
29
155
  /**
30
156
  * Decide whether the bridge should own ask_user_question for this request.
31
- * All three gates must pass: an extension is connected, that extension
32
- * advertised question-card support in its hello caps, and the asking session
33
- * was driven over the bridge. Everything else falls through to `next()` so
34
- * the native answerer waterfall (dsh web) keeps working.
157
+ * Thin compatibility wrapper over {@link resolveInteractionOwnership}.
35
158
  */
36
159
  export function shouldBridgeOwnQuestion(input: {
37
160
  hasExtensionConnection: boolean
@@ -39,8 +162,10 @@ export function shouldBridgeOwnQuestion(input: {
39
162
  sessionId: string | undefined
40
163
  extensionSessions: Pick<ExtensionSessionRegistry, 'has'>
41
164
  }): boolean {
42
- return input.hasExtensionConnection
43
- && input.clientSupportsQuestions
44
- && input.sessionId !== undefined
45
- && input.extensionSessions.has(input.sessionId)
165
+ return resolveInteractionOwnership({
166
+ hasExtensionConnection: input.hasExtensionConnection,
167
+ clientSupports: input.clientSupportsQuestions,
168
+ sessionId: input.sessionId,
169
+ sources: { driven: input.extensionSessions },
170
+ }).owned
46
171
  }