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.
@@ -1,49 +1,52 @@
1
1
  /**
2
2
  * Defer real session creation until the first prompt.
3
3
  *
4
- * The panel calls `session.create` as soon as it connects, but a session that
4
+ * The panel calls `session/create` as soon as it connects, but a session that
5
5
  * is opened and never used should leave zero trace in the store/GUI. This
6
- * wrapper answers `session.create` with a provisional id (minted locally,
7
- * nothing persisted), serves `session.history` for provisional ids as empty,
8
- * and materializes the real session — same id, original create payload — on
9
- * the first `session.prompt` for that id. Abandoned provisional ids are
10
- * pruned after {@link PROVISIONAL_TTL_MS}.
6
+ * interceptor answers `session/create` with a provisional id (minted locally,
7
+ * nothing persisted) and materializes the real session — same id, original
8
+ * create request — on the first `session/prompt` for that id. Abandoned
9
+ * provisional ids are pruned after {@link PROVISIONAL_TTL_MS}.
11
10
  *
12
11
  * @module @deepseek-ai/dsh-bridge-browser/src/session-deferral
13
12
  */
14
13
 
15
14
  import { randomUUID } from 'node:crypto'
16
- import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api'
17
- import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api'
18
15
  import type { SessionId } from '@deepseek-ai/dsh-session/types'
16
+ import type { RemoteWireResult } from './protocol.ts'
17
+ import type { RpcDispatch } from './session-workspace.ts'
19
18
 
20
19
  /** Provisional entries older than this are dropped on the next create. */
21
20
  const PROVISIONAL_TTL_MS = 30 * 60_000
22
21
 
23
- type CreateRequest = Parameters<ApiProxy['sessions']['create']>[0]
24
- type HistoryRequest = Parameters<ApiProxy['sessions']['history']>[0]
25
- type PromptRequest = Parameters<ApiProxy['sessions']['prompt']>[0]
26
-
27
22
  interface ProvisionalEntry {
28
- /** The original create payload, replayed at materialization (keeps cwd/workspaceId). */
29
- payload: CreateRequest['payload']
23
+ /** The original create request, replayed at materialization (keeps cwd/workspaceId). */
24
+ request: Record<string, unknown>
30
25
  createdAt: number
31
26
  }
32
27
 
28
+ /** Extract the `request` arg object from one dispatch's native args, when present. */
29
+ function requestArg(args: Record<string, unknown>): Record<string, unknown> {
30
+ const request = args.request
31
+ return typeof request === 'object' && request !== null && !Array.isArray(request)
32
+ ? request as Record<string, unknown>
33
+ : {}
34
+ }
35
+
33
36
  /**
34
- * Wrap the gateway sessions API so `session.create` returns a provisional id
37
+ * Intercept the Remote dispatch so `session/create` returns a provisional id
35
38
  * without creating anything; the real session materializes on the first
36
- * `session.prompt` for that id.
39
+ * `session/prompt` for that id.
37
40
  *
38
- * @param api - Gateway API implementation.
39
- * @param enabled - Whether deferral is active; false returns the API untouched.
40
- * @returns the original API when disabled, otherwise the wrapped API.
41
+ * @param dispatch - Inner Remote dispatch.
42
+ * @param enabled - Whether deferral is active; false returns the dispatch untouched.
43
+ * @returns the original dispatch when disabled, otherwise the intercepting dispatch.
41
44
  */
42
- export function withSessionDeferral(api: ApiProxy, enabled: boolean): ApiProxy {
43
- if (!enabled) return api
45
+ export function withSessionDeferral(dispatch: RpcDispatch, enabled: boolean): RpcDispatch {
46
+ if (!enabled) return dispatch
44
47
 
45
- const provisional = new Map<SessionId, ProvisionalEntry>()
46
- const materializing = new Map<SessionId, ReturnType<ApiProxy['sessions']['create']>>()
48
+ const provisional = new Map<string, ProvisionalEntry>()
49
+ const materializing = new Map<string, Promise<RemoteWireResult>>()
47
50
 
48
51
  const prune = (): void => {
49
52
  const cutoff = Date.now() - PROVISIONAL_TTL_MS
@@ -52,48 +55,38 @@ export function withSessionDeferral(api: ApiProxy, enabled: boolean): ApiProxy {
52
55
  }
53
56
  }
54
57
 
55
- const mintedId = (payload: CreateRequest['payload']): SessionId =>
56
- payload.sessionId ?? `session-${randomUUID()}` as SessionId
57
-
58
- return {
59
- ...api,
60
- sessions: {
61
- ...api.sessions,
62
- async create(request: CreateRequest) {
63
- prune()
64
- const sessionId = mintedId(request.payload)
65
- provisional.set(sessionId, { payload: { ...request.payload }, createdAt: Date.now() })
66
- return { rpcId: request.rpcId, result: { ok: true, value: { sessionId } } }
67
- },
68
- async history(request: HistoryRequest) {
69
- if (!provisional.has(request.payload.sessionId)) return api.sessions.history(request)
70
- return { rpcId: request.rpcId, result: { ok: true, value: { events: [], hasMore: false } } }
71
- },
72
- async prompt(request: PromptRequest) {
73
- const entry = provisional.get(request.payload.sessionId)
74
- if (entry === undefined) return api.sessions.prompt(request)
75
- const existing = materializing.get(request.payload.sessionId)
76
- const pending = existing ?? api.sessions.create({
77
- rpcId: RpcId(randomUUID()),
78
- payload: { ...entry.payload, sessionId: request.payload.sessionId },
79
- })
80
- if (existing === undefined) {
81
- materializing.set(request.payload.sessionId, pending)
82
- void pending.then(
83
- () => { materializing.delete(request.payload.sessionId) },
84
- () => { materializing.delete(request.payload.sessionId) },
85
- )
86
- }
87
- const created = await pending
88
- if (!created.result.ok) {
89
- // The create failure value shape differs from prompt's success
90
- // shape; the carrier relays only result.ok/error, so the value
91
- // side is irrelevant here.
92
- return created as unknown as Awaited<ReturnType<ApiProxy['sessions']['prompt']>>
93
- }
94
- provisional.delete(request.payload.sessionId)
95
- return api.sessions.prompt(request)
96
- },
97
- },
58
+ return async (method, args, signal): Promise<RemoteWireResult> => {
59
+ if (method === 'session/create') {
60
+ prune()
61
+ const request = requestArg(args)
62
+ const sessionId = typeof request.sessionId === 'string' ? request.sessionId : `session-${randomUUID()}`
63
+ provisional.set(sessionId, { request: { ...request }, createdAt: Date.now() })
64
+ return { ok: true, value: { sessionId: sessionId as SessionId } }
65
+ }
66
+ if (method === 'session/prompt') {
67
+ const request = requestArg(args)
68
+ const sessionId = typeof request.sessionId === 'string' ? request.sessionId : undefined
69
+ const entry = sessionId === undefined ? undefined : provisional.get(sessionId)
70
+ if (sessionId === undefined || entry === undefined) return dispatch(method, args, signal)
71
+ const existing = materializing.get(sessionId)
72
+ const pending = existing ?? dispatch('session/create', { request: { ...entry.request, sessionId } }, signal)
73
+ if (existing === undefined) {
74
+ materializing.set(sessionId, pending)
75
+ void pending.then(
76
+ () => { materializing.delete(sessionId) },
77
+ () => { materializing.delete(sessionId) },
78
+ )
79
+ }
80
+ const created = await pending
81
+ if (!created.ok) {
82
+ // Materialization failed: relay the failure as the prompt answer so
83
+ // the extension surfaces the real reason; the provisional entry
84
+ // survives and the next prompt retries.
85
+ return { ok: false, error: created.error }
86
+ }
87
+ provisional.delete(sessionId)
88
+ return dispatch(method, args, signal)
89
+ }
90
+ return dispatch(method, args, signal)
98
91
  }
99
92
  }
@@ -1,34 +1,47 @@
1
1
  /**
2
2
  * Best-effort workspace grouping for sessions created through the browser
3
- * bridge. The wrapper changes only implicit `session.create` requests;
4
- * explicit workspace choices and every other gateway method pass through.
3
+ * bridge. The interceptor changes only implicit `session/create` requests;
4
+ * explicit workspace choices and every other Remote endpoint pass through.
5
5
  * @module @deepseek-ai/dsh-bridge-browser/src/session-workspace
6
6
  */
7
7
 
8
- import { randomUUID } from 'node:crypto'
9
8
  import { mkdir } from 'node:fs/promises'
10
- import type { ApiProxy, WorkspaceId } from '@deepseek-ai/dsh-host-apiproxy/api'
11
- import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api'
9
+ import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/types'
10
+ import type { RemoteWireResult } from './protocol.ts'
11
+
12
+ /**
13
+ * Unary Remote dispatch seam: slash-joined endpoint, native args object,
14
+ * RemoteResult wire form. The bridge server and the interceptors share it.
15
+ */
16
+ export type RpcDispatch = (method: string, args: Record<string, unknown>, signal: AbortSignal) => Promise<RemoteWireResult>
12
17
 
13
18
  type Warn = (message: string) => void
14
19
 
20
+ /** Extract the `request` arg object from one dispatch's native args, when present. */
21
+ function requestArg(args: Record<string, unknown>): Record<string, unknown> {
22
+ const request = args.request
23
+ return typeof request === 'object' && request !== null && !Array.isArray(request)
24
+ ? request as Record<string, unknown>
25
+ : {}
26
+ }
27
+
15
28
  /**
16
- * Add a dedicated Workspace to implicit session creation without making
29
+ * Add the dedicated Workspace to implicit session creation without making
17
30
  * grouping a session-creation dependency. The first implicit create mkdirs
18
- * and registers the configured path; that result, including failure, is
19
- * cached for the wrapper lifetime.
31
+ * and registers the configured path (`workspace/create`); that result,
32
+ * including failure, is cached for the interceptor lifetime.
20
33
  *
21
- * @param api - Injected gateway API implementation.
34
+ * @param dispatch - Inner Remote dispatch.
22
35
  * @param workspacePath - Dedicated directory, or an empty string to opt out.
23
36
  * @param warn - Logger called once when grouping cannot be established.
24
- * @returns the original API for opt-out, otherwise an API with wrapped session creation.
37
+ * @returns the original dispatch for opt-out, otherwise a dispatch with intercepted session creation.
25
38
  */
26
39
  export function withSessionWorkspace(
27
- api: ApiProxy,
40
+ dispatch: RpcDispatch,
28
41
  workspacePath: string,
29
42
  warn: Warn,
30
- ): ApiProxy {
31
- if (workspacePath === '') return api
43
+ ): RpcDispatch {
44
+ if (workspacePath === '') return dispatch
32
45
 
33
46
  let workspacePromise: Promise<WorkspaceId | undefined> | undefined
34
47
  const ensureWorkspace = (): Promise<WorkspaceId | undefined> => {
@@ -36,23 +49,21 @@ export function withSessionWorkspace(
36
49
  workspacePromise = (async () => {
37
50
  try {
38
51
  await mkdir(workspacePath, { recursive: true })
39
- const workspaceApi = (api as { workspace?: ApiProxy['workspace'] }).workspace
40
- if (workspaceApi === undefined) {
41
- warn(`browser bridge: workspace API is unavailable; sessions will remain ungrouped`)
42
- return undefined
43
- }
44
- const response = await workspaceApi.create({
45
- rpcId: RpcId(randomUUID()),
46
- payload: { path: workspacePath },
47
- })
48
- if (!response.result.ok) {
52
+ const result = await dispatch('workspace/create', { request: { path: workspacePath } }, new AbortController().signal)
53
+ if (!result.ok) {
49
54
  warn(
50
- `browser bridge: workspace.create failed for "${workspacePath}" `
51
- + `(${response.result.error.code}: ${response.result.error.message}); sessions will remain ungrouped`,
55
+ `browser bridge: workspace/create failed for "${workspacePath}" `
56
+ + `(${result.error.code}: ${result.error.message}); sessions will remain ungrouped`,
52
57
  )
53
58
  return undefined
54
59
  }
55
- return response.result.value.workspace.workspaceId
60
+ const workspace = (result.value as { workspace?: { workspaceId?: unknown } }).workspace
61
+ const workspaceId = workspace?.workspaceId
62
+ if (typeof workspaceId !== 'string') {
63
+ warn(`browser bridge: workspace/create for "${workspacePath}" returned no workspace id; sessions will remain ungrouped`)
64
+ return undefined
65
+ }
66
+ return workspaceId as WorkspaceId
56
67
  } catch (error: unknown) {
57
68
  warn(
58
69
  `browser bridge: could not prepare session workspace "${workspacePath}": `
@@ -64,18 +75,14 @@ export function withSessionWorkspace(
64
75
  return workspacePromise
65
76
  }
66
77
 
67
- return {
68
- ...api,
69
- sessions: {
70
- ...api.sessions,
71
- async create(request) {
72
- if (request.payload.workspaceId !== undefined) return api.sessions.create(request)
73
- const workspaceId = await ensureWorkspace()
74
- if (workspaceId === undefined) return api.sessions.create(request)
75
- const payload = { ...request.payload, workspaceId }
76
- delete payload.cwd
77
- return api.sessions.create({ ...request, payload })
78
- },
79
- },
78
+ return async (method, args, signal) => {
79
+ if (method !== 'session/create') return dispatch(method, args, signal)
80
+ const request = requestArg(args)
81
+ if (request.workspaceId !== undefined) return dispatch(method, args, signal)
82
+ const workspaceId = await ensureWorkspace()
83
+ if (workspaceId === undefined) return dispatch(method, args, signal)
84
+ const next: Record<string, unknown> = { ...request, workspaceId }
85
+ delete next.cwd
86
+ return dispatch(method, { ...args, request: next }, signal)
80
87
  }
81
88
  }