@linxin666/dsh-remote-bridge 0.4.16 → 0.4.18

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.
@@ -16,6 +16,8 @@
16
16
  * @module dsh-remote-bridge/core/connection
17
17
  */
18
18
 
19
+ import { isAbsolute } from 'node:path'
20
+ import { attachmentPathsOf, oldestSeqOf, readAttachment, type AttachmentFacts } from './attachment-paths.ts'
19
21
  import type { ApprovalRegistry } from './approvals.ts'
20
22
  import { commandItems, commandsUnavailable } from './commands.ts'
21
23
  import type { DeviceRoster, PushEnvironment, PushLiveActivityToken, PushRegistration } from './devices.ts'
@@ -66,6 +68,7 @@ import {
66
68
  CODE_QUESTION_LIST_UNAVAILABLE,
67
69
  CODE_SESSION_NOT_FOLLOWABLE,
68
70
  CODE_SNAPSHOT_TOO_LARGE,
71
+ CODE_PATH_NOT_IN_SESSION,
69
72
  CODE_SNAPSHOT_UNAVAILABLE,
70
73
  CODE_SQUADS_UNAVAILABLE,
71
74
  CODE_TOKEN_INVALID,
@@ -85,6 +88,7 @@ import {
85
88
  METHOD_QUESTION_LIST,
86
89
  METHOD_SESSION_ARCHIVE,
87
90
  METHOD_SESSION_ATTACHMENT,
91
+ METHOD_SESSION_ATTACHMENT_PATH,
88
92
  METHOD_SESSION_COMMAND,
89
93
  METHOD_SESSION_COMMANDS,
90
94
  METHOD_SESSION_CREATE,
@@ -132,7 +136,7 @@ import { TITLES_MAX_IDS, type SessionMeta } from './session-meta.ts'
132
136
  import type { SessionPermissions } from './session-permissions.ts'
133
137
  import { USAGE_METHODS, type UsageService } from './usage.ts'
134
138
  import type { BridgeGateway, GatewayPeer } from './wire.ts'
135
- import { CODE_SUBAGENT_ADDRESS_REQUIRED, sessionAddress, subagentAddress, wireArgs, type SessionAddress } from './wire.ts'
139
+ import { CODE_HOST_SESSION_NOT_FOUND, CODE_SUBAGENT_ADDRESS_REQUIRED, sessionAddress, subagentAddress, wireArgs, type SessionAddress } from './wire.ts'
136
140
  import { CLOSE_LIVENESS_TIMEOUT } from './ws-frames.ts'
137
141
 
138
142
  /** Protocol-level heartbeat period: a frame is sent after this long without one. */
@@ -168,6 +172,15 @@ export const DEEP_HISTORY_WINDOW = {
168
172
  maxMessages: 500,
169
173
  turnWindow: { minMessages: 50, minTurns: 2 },
170
174
  } as const
175
+
176
+ /**
177
+ * Highest number of sessions one connection keeps a computed whitelist for.
178
+ *
179
+ * Bounded because a long-lived connection must not grow with every session its
180
+ * client opens: four is a phone's own working set of session screens, and the
181
+ * least recently used one goes first.
182
+ */
183
+ export const ATTACHMENT_WHITELIST_SESSIONS = 4
171
184
  /** Highest number of prompt receipts one connection remembers for idempotency. */
172
185
  export const PROMPT_RECEIPT_LIMIT = 512
173
186
  /** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
@@ -398,6 +411,12 @@ interface CallFailure {
398
411
 
399
412
  type DispatchOutcome = { readonly ok: true; readonly r: unknown } | CallFailure
400
413
 
414
+ /** One session's computed whitelist, valid for exactly the durable watermark it was read at. */
415
+ interface AttachmentWhitelist {
416
+ readonly asOfSeq: number
417
+ readonly facts: ReadonlyMap<string, AttachmentFacts>
418
+ }
419
+
401
420
  /**
402
421
  * One snapshot baseline answer, typed rather than opaque so the incremental
403
422
  * fallback can extend the very payload protocol v1 serves instead of rebuilding
@@ -788,6 +807,27 @@ export class BridgeConnection {
788
807
  readonly #receipts = new Set<string>()
789
808
  readonly #toolCalls = new ToolCallIndex()
790
809
  readonly #messages = new MessageIndex()
810
+
811
+ /**
812
+ * The whitelists this connection has already computed, keyed by session id and
813
+ * ordered least recently used first.
814
+ *
815
+ * This is not the cache `session.attachment` refuses to keep, and it does not
816
+ * weaken that rule: that one is about image BYTES — an image can be offloaded
817
+ * after the fact, so every read of a file goes to the disk it is on. This is a
818
+ * set of PATHS, keyed by the durable watermark that would invalidate it, so a
819
+ * request arriving under the same `asOfSeq` can only be answered the same
820
+ * set. Nothing stale can be served, and an offload that moves the watermark
821
+ * moves the key with it.
822
+ *
823
+ * What it buys is the walk. A cold read of the longest session this host holds
824
+ * (measured: 5,680 entries, 6.0 MiB compressed) inflates in 40.8 ms and
825
+ * inflates plus parses in 108 ms, and the walk pays that once per page — two
826
+ * pages at {@link DEEP_HISTORY_WINDOW}. A phone scrolling a screen of tool
827
+ * cards asks several times with no event in between, so without this it would
828
+ * pay the inflate once per card.
829
+ */
830
+ readonly #attachmentWhitelists = new Map<string, AttachmentWhitelist>()
791
831
  #capabilities: ReadonlySet<string> = new Set()
792
832
  /** Delegated children this connection has learned the durable parent of, by child id. */
793
833
  readonly #lineage = new Map<string, string>()
@@ -1095,6 +1135,7 @@ export class BridgeConnection {
1095
1135
  case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p)
1096
1136
  case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p)
1097
1137
  case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id)
1138
+ case METHOD_SESSION_ATTACHMENT_PATH: return await this.#sessionAttachmentPath(frame.p, frame.id)
1098
1139
  case METHOD_SESSION_PERMISSIONS: return this.#sessionPermissions(frame.p)
1099
1140
  case METHOD_SESSION_SET_PERMISSION: return this.#sessionSetPermission(frame.p)
1100
1141
  case METHOD_SESSION_MODELS: return await this.#sessionModels(frame.p)
@@ -1829,6 +1870,123 @@ export class BridgeConnection {
1829
1870
  return { ok: true, r: call.value }
1830
1871
  }
1831
1872
 
1873
+ /**
1874
+ * Answer `session.attachment.path`: the bytes of one image a session already
1875
+ * offloaded, addressed by the absolute path that session's own transcript names.
1876
+ *
1877
+ * The whitelist is the whole authorization and it lives in
1878
+ * `core/attachment-paths.ts`: this method serves a path only when the named
1879
+ * session's own durable store named it, and the store is read here on every call,
1880
+ * for the reason `session.attachment` keeps no cache either — an image can be
1881
+ * offloaded after the fact.
1882
+ *
1883
+ * The store is the one `session.history.deep` walks, so this read passes the
1884
+ * same fence: a delegated child whose parent this connection may not read is
1885
+ * refused before any store call. A session this host does not have answers
1886
+ * `unknown-session`: the harness's own name for that fact is
1887
+ * `session/not-found` on the store and a `null` projections answer, and
1888
+ * both are folded into this method's own code here rather than crossing as two
1889
+ * different failures.
1890
+ *
1891
+ * The budget is measured on the ENCODED answer, exactly as `session.attachment`
1892
+ * measures its own: a frame that cannot cross is reported as `frame-too-large`
1893
+ * rather than truncated into half an image.
1894
+ * @param payload - `{sessionId, path}`.
1895
+ * @param id - the request id the frame budget is measured against.
1896
+ */
1897
+ async #sessionAttachmentPath(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
1898
+ const sessionId = stringArg(payload, 'sessionId')
1899
+ const path = stringArg(payload, 'path')
1900
+ if (sessionId === undefined || path === undefined) {
1901
+ return refusal(CODE_INVALID_ARGS, 'session.attachment.path requires sessionId and path')
1902
+ }
1903
+ if (!isAbsolute(path)) {
1904
+ return refusal(CODE_INVALID_ARGS, `session.attachment.path requires an absolute path, got ${path}`)
1905
+ }
1906
+ const whitelist = await this.#sessionAttachmentPaths(sessionId)
1907
+ if (!whitelist.ok) return whitelist
1908
+ const facts = whitelist.facts.get(path)
1909
+ if (facts === undefined) {
1910
+ return refusal(CODE_PATH_NOT_IN_SESSION, `${path} is not an image session ${sessionId} offloaded`)
1911
+ }
1912
+ const read = await readAttachment(facts)
1913
+ if (!read.ok) return refusal(read.code, read.msg)
1914
+ const answer = { image: read.image, data: read.data }
1915
+ if (Buffer.byteLength(JSON.stringify(responseFrame(id, answer)), 'utf8') > MAX_FRAME_BYTES) {
1916
+ return refusal(FRAME_TOO_LARGE, `${path} needs more than one ${MAX_FRAME_BYTES} byte frame once encoded`)
1917
+ }
1918
+ return { ok: true, r: answer }
1919
+ }
1920
+
1921
+ /**
1922
+ * The images one session's own durable store names.
1923
+ *
1924
+ * The store is paged backwards to its oldest entry, exactly as
1925
+ * `session.history.deep` pages it: a whitelist cut at one page would forget an
1926
+ * image the session offloaded a month ago. Each page is folded into the map and
1927
+ * dropped, so a long session costs memory in proportion to the images it named
1928
+ * rather than to its whole log.
1929
+ * @param sessionId - the session whose transcript is read; no path of this read
1930
+ * ever comes from the client.
1931
+ * @returns the whitelist keyed by path, or the refusal the read produced.
1932
+ */
1933
+ async #sessionAttachmentPaths(
1934
+ sessionId: string,
1935
+ ): Promise<{ readonly ok: true; readonly facts: ReadonlyMap<string, AttachmentFacts> } | CallFailure> {
1936
+ const unfollowable = await this.#unfollowable(sessionId)
1937
+ if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
1938
+ const projections = await this.#unary('session', 'projections', { sessionId })
1939
+ if (!projections.ok) return projections
1940
+ const cut = isRecord(projections.value) ? projections.value.asOfSeq : undefined
1941
+ if (typeof cut !== 'number' || !Number.isSafeInteger(cut) || cut < -1) {
1942
+ // A null projections answer is the harness's own "no such session" on that
1943
+ // endpoint; anything else is a session that exists and reports no cut.
1944
+ return projections.value === null
1945
+ ? refusal(CODE_UNKNOWN_SESSION, `session ${sessionId} does not exist on this host`)
1946
+ : refusal(CODE_SNAPSHOT_UNAVAILABLE, `session ${sessionId} reported no durable cut to read its images from`)
1947
+ }
1948
+ const remembered = this.#attachmentWhitelists.get(sessionId)
1949
+ if (remembered !== undefined && remembered.asOfSeq === cut) {
1950
+ this.#rememberAttachmentWhitelist(sessionId, cut, remembered.facts)
1951
+ return { ok: true, facts: remembered.facts }
1952
+ }
1953
+ const facts = new Map<string, AttachmentFacts>()
1954
+ let before: number | undefined
1955
+ for (;;) {
1956
+ const store = await this.#storePageOf(sessionId, cut, before)
1957
+ if (!store.ok) {
1958
+ return store.code === CODE_HOST_SESSION_NOT_FOUND
1959
+ ? refusal(CODE_UNKNOWN_SESSION, `session ${sessionId} does not exist on this host`)
1960
+ : store
1961
+ }
1962
+ for (const [named, entry] of attachmentPathsOf(store.records)) facts.set(named, entry)
1963
+ const oldest = oldestSeqOf(store.records)
1964
+ // A page that does not move the watermark is the store's last word: stop
1965
+ // rather than ask for the same page again.
1966
+ if (!store.hasMore || oldest === undefined || (before !== undefined && oldest >= before)) break
1967
+ before = oldest
1968
+ }
1969
+ this.#rememberAttachmentWhitelist(sessionId, cut, facts)
1970
+ return { ok: true, facts }
1971
+ }
1972
+
1973
+ /**
1974
+ * Keep one session's whitelist, evicting the least recently used one past the
1975
+ * bound.
1976
+ *
1977
+ * A hit moves its session to the back, so what is evicted is the entry no
1978
+ * request has needed for longest rather than the one that arrived first.
1979
+ */
1980
+ #rememberAttachmentWhitelist(sessionId: string, asOfSeq: number, facts: ReadonlyMap<string, AttachmentFacts>): void {
1981
+ this.#attachmentWhitelists.delete(sessionId)
1982
+ this.#attachmentWhitelists.set(sessionId, { asOfSeq, facts })
1983
+ while (this.#attachmentWhitelists.size > ATTACHMENT_WHITELIST_SESSIONS) {
1984
+ const oldest = this.#attachmentWhitelists.keys().next().value
1985
+ if (oldest === undefined) break
1986
+ this.#attachmentWhitelists.delete(oldest)
1987
+ }
1988
+ }
1989
+
1832
1990
  /** Answer `session.permissions` out of the host's own preset service. */
1833
1991
  #sessionPermissions(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1834
1992
  const sessionId = stringArg(payload, 'sessionId')
@@ -14,6 +14,7 @@ export const METHOD_SESSION_HISTORY_DEEP = 'session.history.deep'
14
14
  export const METHOD_SESSION_PROMPT = 'session.prompt'
15
15
  export const METHOD_SESSION_INTERRUPT = 'session.interrupt'
16
16
  export const METHOD_SESSION_ATTACHMENT = 'session.attachment'
17
+ export const METHOD_SESSION_ATTACHMENT_PATH = 'session.attachment.path'
17
18
  export const METHOD_SESSION_PERMISSIONS = 'session.permissions'
18
19
  export const METHOD_SESSION_SET_PERMISSION = 'session.setPermission'
19
20
  export const METHOD_SESSION_MODELS = 'session.models'
@@ -289,6 +290,19 @@ export const CAP_UI = 'ui.v1'
289
290
  * `ui.request` 说 `settled` 时结束),而不是按一次它信不过的应答清卡。
290
291
  */
291
292
  export const CAP_UI_LIST = 'ui.list.v1'
293
+ /**
294
+ * Capability a client declares in `hello`'s `cap` array to be told that this
295
+ * bridge can hand it the bytes of an image a session already offloaded.
296
+ *
297
+ * An announcement and nothing more, the same shape as
298
+ * {@link CAP_SESSION_DEEP_HISTORY}: `session.attachment.path` is open to every
299
+ * paired connection, because it is a pure read of one session's own durable
300
+ * transcript that costs no other client anything. Declaring the capability is how
301
+ * a client learns the method exists, and a client that does not declare it loses
302
+ * only that knowledge — it never sees a frame from this channel, because it never
303
+ * asks for one.
304
+ */
305
+ export const CAP_SESSION_ATTACHMENT_PATH = 'session.attachment.path.v1'
292
306
 
293
307
  /**
294
308
  * 宿主配了第二会合点时,在 `hello` 的 `capabilities` 里公告的能力名。
@@ -476,6 +490,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
476
490
  METHOD_SESSION_PROMPT,
477
491
  METHOD_SESSION_INTERRUPT,
478
492
  METHOD_SESSION_ATTACHMENT,
493
+ METHOD_SESSION_ATTACHMENT_PATH,
479
494
  METHOD_SESSION_PERMISSIONS,
480
495
  METHOD_SESSION_SET_PERMISSION,
481
496
  METHOD_SESSION_MODELS,
@@ -565,6 +580,23 @@ export const CODE_UI_LIST_UNAVAILABLE = 'ui-list-unavailable'
565
580
  * an unaddressable one, rather than reading it blind.
566
581
  */
567
582
  export const CODE_SESSION_NOT_FOLLOWABLE = 'session-not-followable'
583
+ /**
584
+ * 该路径不在这次会话自己的持久 transcript 里:白名单只有两处来源,客户端自选的路径
585
+ * 一律不在其中。`realpath()` 解析结果不再等于该字符串时也回这一码——那个路径已经
586
+ * 指向别处,就不再是这次会话点过的那个文件。
587
+ */
588
+ export const CODE_PATH_NOT_IN_SESSION = 'path-not-in-session'
589
+ /**
590
+ * 白名单里有这个路径,但它已经不是一个常规文件:文件被删了,或被换成了目录、设备或
591
+ * fifo。它与 {@link CODE_PATH_NOT_IN_SESSION} 是两个答案——「这次会话没点过它」与
592
+ * 「点过的那个文件不在了」。
593
+ */
594
+ export const CODE_ATTACHMENT_NOT_FOUND = 'not-found'
595
+ /**
596
+ * 文件确实在,但它的文件头魔数不是 png/jpeg/webp/gif 四种之一。扩展名不作数:`.png`
597
+ * 里装的不是 PNG 就回这一码,而一个叫 `.txt` 的 PNG 照常服务。
598
+ */
599
+ export const CODE_NOT_AN_IMAGE = 'not-an-image'
568
600
  export const CODE_SNAPSHOT_UNAVAILABLE = 'snapshot-unavailable'
569
601
  /**
570
602
  * This host composes no job registry, so it has no background jobs to publish.
@@ -606,6 +638,13 @@ export const PROTO = 1
606
638
  /**
607
639
  * Minor version this package speaks.
608
640
  *
641
+ * 22 当按路径取图落地(与协议 §18 的 `session.history.deep` 同例的一条读通道):
642
+ * 新增 {@link CAP_SESSION_ATTACHMENT_PATH} 一个能力名与
643
+ * {@link METHOD_SESSION_ATTACHMENT_PATH} 一个方法,客户端因此从线路上读到一种新的
644
+ * 应答体,所以 minor 抬一格。这个方法对每一条已配对连接都开放,能力名只公告:它决定
645
+ * 的是客户端要不要露出取图能力,不决定桥放不放行,理由与 {@link CAP_SESSION_DEEP_HISTORY}
646
+ * 逐字相同。`proto` 仍为 1,没有任何既有帧、既有方法或既有键改形状;不声明这个
647
+ * 名字的客户端一帧都不发,两边互不知情时线路逐字节不变。
609
648
  * 21 当可交互回复(协议 §35)落地:新增 {@link CAP_UI} 与 {@link CAP_UI_LIST}
610
649
  * 两个能力名、{@link TOPIC_UI_REQUEST} 一个主题、{@link METHOD_UI_EVENT} 与
611
650
  * {@link METHOD_UI_LIST} 两个方法,宿主半区还多一个模型工具 `ui_present`。客户端
@@ -717,7 +756,7 @@ export const PROTO = 1
717
756
  * declares the capability that plugin requires. No addition changed the major
718
757
  * version, a frozen field, or an existing method or topic name.
719
758
  */
720
- export const MINOR = 21
759
+ export const MINOR = 22
721
760
 
722
761
  /**
723
762
  * The capabilities this bridge itself serves, and the opening half of what
@@ -763,6 +802,7 @@ export const SERVED_CAPABILITIES: readonly string[] = [
763
802
  CAP_USAGE_STATS,
764
803
  CAP_UI,
765
804
  CAP_UI_LIST,
805
+ CAP_SESSION_ATTACHMENT_PATH,
766
806
  ]
767
807
  /** `server` field of the hello response. */
768
808
  export const SERVER_ID = 'dsh-remote-bridge'
package/src/core/wire.ts CHANGED
@@ -88,6 +88,15 @@ export function subagentAddress(parentSessionId: string, childSessionId: string)
88
88
  /** The failure code the harness raises for a child addressed as an ordinary session. */
89
89
  export const CODE_SUBAGENT_ADDRESS_REQUIRED = 'session/agent-busy'
90
90
 
91
+ /**
92
+ * The failure the harness raises when a session address names a session this host
93
+ * does not have. `session/page` answers it, `session/projections` answers
94
+ * `null` for the same fact, and a caller that needs one name for "no such
95
+ * session" folds both into its own code rather than letting one fact cross as two
96
+ * different failures.
97
+ */
98
+ export const CODE_HOST_SESSION_NOT_FOUND = 'session/not-found'
99
+
91
100
  /**
92
101
  * One endpoint's declared argument names: the name of its single parameter, the
93
102
  * empty declaration of a parameterless endpoint, or the exact names of an
@@ -18,8 +18,8 @@
18
18
 
19
19
  import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'
20
20
  import type { UiPresentReply } from '../core/hub.ts'
21
- import { UI_HTML_MAX_BYTES, UI_PAYLOAD_MAX_BYTES, uiHtmlFits, uiKey } from '../core/ui.ts'
22
- import type { JsonValue, UiCardView, UiRefusalReason, UiState } from '../core/ui.ts'
21
+ import { UI_HTML_MAX_BYTES, uiHtmlFits, uiKey } from '../core/ui.ts'
22
+ import type { JsonValue, UiCardView, UiState } from '../core/ui.ts'
23
23
 
24
24
  /**
25
25
  * The one thing this tool needs from the hub.