@linxin666/dsh-remote-bridge 0.4.15 → 0.4.17

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,288 @@
1
+ /**
2
+ * The image paths one session's own durable transcript whitelists, and the file
3
+ * decisions `session.attachment.path` takes on the one path it is handed.
4
+ *
5
+ * This module IS that method's authorization. The bridge serves bytes only for a
6
+ * path the session itself named, so the whitelist is computed here from that
7
+ * session's store and from nothing else: never a path a client chose, never a
8
+ * directory listing, never a second session.
9
+ *
10
+ * Two sources and no others:
11
+ * - an offload placeholder in a message body, `<path>…</path>` immediately
12
+ * followed by `<type>image</type>` — the envelope the harness writes when
13
+ * it keeps image bytes out of a durable message, and the one a phone already
14
+ * reads with `OffloadedImages.segments(of:)`;
15
+ * - the image reference of a durable tool result — `meta.path`, what
16
+ * `read_image` publishes through its `output.presentationMeta`, or a
17
+ * text block that is itself a JSON image reference, which is how a
18
+ * `run_code` program's own return value is persisted — and what a client
19
+ * draws as `ToolBlock.image(ImageRef(path:))`.
20
+ *
21
+ * A path either source names is kept only when it is a host absolute path: the
22
+ * request side admits nothing else, so a name that could never be asked for —
23
+ * a plugin's own namespace, a relative path — is not a whitelist entry.
24
+ *
25
+ * Records are the ones `session/page` answers and `turnsOfRecords`
26
+ * projects: `{event: {type, seq, time, data}}`.
27
+ * @module dsh-remote-bridge/core/attachment-paths
28
+ */
29
+
30
+ import { isAbsolute } from 'node:path'
31
+ import { readFile, realpath, stat } from 'node:fs/promises'
32
+ import { FRAME_TOO_LARGE, MAX_FRAME_BYTES } from './envelope.ts'
33
+ import { CODE_ATTACHMENT_NOT_FOUND, CODE_NOT_AN_IMAGE, CODE_PATH_NOT_IN_SESSION } from './protocol.ts'
34
+
35
+ /** One image a session's transcript names: the reference a client already drew. */
36
+ export interface AttachmentFacts {
37
+ /** The absolute path, byte for byte as the transcript wrote it. */
38
+ readonly path: string
39
+ readonly mediaType?: string
40
+ readonly bytes?: number
41
+ readonly width?: number
42
+ readonly height?: number
43
+ }
44
+
45
+ /**
46
+ * `<path>…</path>` immediately followed by `<type>image</type>`, plus
47
+ * the facts the `<content>` body beside them states when it states any.
48
+ */
49
+ const OFFLOAD_PLACEHOLDER = /<path>([^<]*)<\/path>\s*<type>image<\/type>\s*(?:<content>\s*([^<]*?)\s*<\/content>)?/gu
50
+
51
+ /** One envelope body: `image/jpeg image, 1600x1000 px, 93031 bytes`. */
52
+ const ENVELOPE_FACTS = /^(\S+)\s+image,\s*(\d+)x(\d+)\s+px,\s*(\d+)\s+bytes/u
53
+
54
+ /** The four heads a durable image may declare, byte for byte. */
55
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
56
+ const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff])
57
+ const GIF_SIGNATURES = [Buffer.from('GIF87a', 'ascii'), Buffer.from('GIF89a', 'ascii')]
58
+ const RIFF_SIGNATURE = Buffer.from('RIFF', 'ascii')
59
+ const WEBP_SIGNATURE = Buffer.from('WEBP', 'ascii')
60
+
61
+ /** One whitelisted path's bytes, or the code that refused them. */
62
+ export type AttachmentRead =
63
+ | { readonly ok: true; readonly image: AttachmentFacts; readonly data: string }
64
+ | { readonly ok: false; readonly code: string; readonly msg: string }
65
+
66
+ function isRecord(value: unknown): value is Record<string, unknown> {
67
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
68
+ }
69
+
70
+ /** One durable record's `type` and `data`, or undefined when it is not one. */
71
+ function entryOf(record: unknown): { readonly type: string; readonly data: unknown } | undefined {
72
+ const event = isRecord(record) ? record.event : undefined
73
+ if (!isRecord(event) || typeof event.type !== 'string') return undefined
74
+ return { type: event.type, data: event.data }
75
+ }
76
+
77
+ /**
78
+ * The oldest entry seq one store page carries.
79
+ *
80
+ * A page read walks backwards by this number, so the walk has to read it off the
81
+ * page itself: the store's own `hasMore` says that older entries exist,
82
+ * never where they end.
83
+ * @param records - one `session/page` answer's records.
84
+ * @returns the smallest `event.seq` they carry, or undefined when they carry none.
85
+ */
86
+ export function oldestSeqOf(records: readonly unknown[]): number | undefined {
87
+ let oldest: number | undefined
88
+ for (const record of records) {
89
+ const seq = isRecord(record) && isRecord(record.event) ? record.event.seq : undefined
90
+ if (typeof seq !== 'number' || !Number.isSafeInteger(seq)) continue
91
+ if (oldest === undefined || seq < oldest) oldest = seq
92
+ }
93
+ return oldest
94
+ }
95
+
96
+ /**
97
+ * Every image path one session's durable records whitelist.
98
+ * @param records - that session's own records, as `session/page` answered them.
99
+ * @returns one entry per path; a second sighting never erases a stated fact.
100
+ */
101
+ export function attachmentPathsOf(records: readonly unknown[]): Map<string, AttachmentFacts> {
102
+ const found = new Map<string, AttachmentFacts>()
103
+ for (const record of records) {
104
+ const entry = entryOf(record)
105
+ if (entry === undefined) continue
106
+ // A message body. The harness writes the envelope into the INPUT message that
107
+ // carried the image, so only `user/message` is read: an assistant message
108
+ // is model output, and reading one would whitelist a path the model merely wrote.
109
+ if (entry.type === 'user/message') {
110
+ for (const facts of placeholderFacts(entry.data)) remember(found, facts)
111
+ continue
112
+ }
113
+ // A durable tool result. `tool/ptc-dispatch` is the same record for a
114
+ // tool a `run_code` program called, so both shapes of one result are read.
115
+ if (entry.type !== 'tool/result' && entry.type !== 'tool/ptc-dispatch') continue
116
+ const path = toolResultImagePath(entry.data)
117
+ if (path !== undefined) remember(found, { path })
118
+ }
119
+ return found
120
+ }
121
+
122
+ /** The facts every offload placeholder of one message body states, in body order. */
123
+ function placeholderFacts(data: unknown): AttachmentFacts[] {
124
+ if (!isRecord(data) || !Array.isArray(data.content)) return []
125
+ const found: AttachmentFacts[] = []
126
+ for (const block of data.content) {
127
+ if (!isRecord(block) || block.type !== 'text' || typeof block.text !== 'string') continue
128
+ for (const match of block.text.matchAll(OFFLOAD_PLACEHOLDER)) {
129
+ const path = match[1] ?? ''
130
+ if (path === '') continue
131
+ found.push({ path, ...envelopeFacts(match[2]) })
132
+ }
133
+ }
134
+ return found
135
+ }
136
+
137
+ /** The facts one `<content>` body states, or nothing when it states none. */
138
+ function envelopeFacts(body: string | undefined): Omit<AttachmentFacts, 'path'> {
139
+ const stated = body === undefined ? null : ENVELOPE_FACTS.exec(body.trim())
140
+ if (stated === null) return {}
141
+ return { mediaType: stated[1] ?? '', width: Number(stated[2]), height: Number(stated[3]), bytes: Number(stated[4]) }
142
+ }
143
+
144
+ /**
145
+ * The image reference one durable tool result states, or undefined.
146
+ *
147
+ * Two readings, the first that hits wins:
148
+ * - `meta.path`, what `read_image` publishes through its
149
+ * `output.presentationMeta` — kept only when the same result carried the
150
+ * image block it names, because `read` publishes a `meta.path` of its
151
+ * own and a session must not whitelist every file it ever read as text;
152
+ * - a text block that IS a JSON image reference,
153
+ * `{path, image:{attachmentId, mediaType, bytes, width, height, name}}` —
154
+ * the shape a `run_code` program's own return value is persisted as.
155
+ *
156
+ * The JSON reading keeps its gate: the parsed object has to carry an `image`
157
+ * object whose `mediaType` starts with `image/`. That gate is exactly what
158
+ * separates a result that published an image from one that merely named a file —
159
+ * measured over this host's whole store, 83 tool results carry a bare `path`
160
+ * in the same JSON shape against 10 image references — and a path a tool named is
161
+ * not an image this session offloaded.
162
+ *
163
+ * What is read is the reference the TOOL published, never the call's own argument
164
+ * and never prose a model wrote: an argument is what the model asked for, and a
165
+ * model's own words are not a record of anything.
166
+ */
167
+ function toolResultImagePath(data: unknown): string | undefined {
168
+ if (!isRecord(data)) return undefined
169
+ const content = isRecord(data.message) ? data.message.content : data.content
170
+ return publishedImagePath(data.meta, content) ?? jsonImageReference(content)
171
+ }
172
+
173
+ /** `meta.path`, but only when the same result carried the image block it names. */
174
+ function publishedImagePath(meta: unknown, content: unknown): string | undefined {
175
+ const path = isRecord(meta) ? meta.path : undefined
176
+ if (typeof path !== 'string' || path === '') return undefined
177
+ if (!Array.isArray(content) || !content.some(block => isRecord(block) && block.type === 'image')) return undefined
178
+ return path
179
+ }
180
+
181
+ /** The path one text block states as a JSON image reference, or undefined. */
182
+ function jsonImageReference(content: unknown): string | undefined {
183
+ if (!Array.isArray(content)) return undefined
184
+ for (const block of content) {
185
+ if (!isRecord(block) || block.type !== 'text' || typeof block.text !== 'string') continue
186
+ let parsed: unknown
187
+ try {
188
+ parsed = JSON.parse(block.text)
189
+ } catch {
190
+ continue
191
+ }
192
+ if (!isRecord(parsed)) continue
193
+ const path = parsed.path
194
+ const image = parsed.image
195
+ if (typeof path !== 'string' || path === '') continue
196
+ if (!isRecord(image) || typeof image.mediaType !== 'string' || !image.mediaType.startsWith('image/')) continue
197
+ return path
198
+ }
199
+ return undefined
200
+ }
201
+
202
+ /**
203
+ * Remember one sighting, or drop it.
204
+ *
205
+ * A path that is not a host absolute path is not a whitelist entry at all. A
206
+ * request has to name an absolute path, so `browser-view:screenshot/<tab>.png`
207
+ * — the plugin-namespace name `browser_screenshot` writes into its envelope,
208
+ * with no file behind it — could never be asked for, and a list of names no
209
+ * request can match is not a whitelist. What an entry keeps is the reading that
210
+ * states more: a later sighting never erases a stated fact.
211
+ */
212
+ function remember(found: Map<string, AttachmentFacts>, facts: AttachmentFacts): void {
213
+ if (!isAbsolute(facts.path)) return
214
+ const previous = found.get(facts.path)
215
+ if (previous === undefined || (facts.mediaType !== undefined && previous.mediaType === undefined)) {
216
+ found.set(facts.path, facts)
217
+ }
218
+ }
219
+
220
+ /**
221
+ * The media type one head declares, or undefined when it is none of the four.
222
+ *
223
+ * The signatures are the harness's own four — PNG, JPEG, GIF87a/89a and
224
+ * RIFF-WebP — because the bytes are what a client will decode.
225
+ * @param head - the file's first bytes, as read.
226
+ * @returns the media type, or undefined.
227
+ */
228
+ export function mediaTypeOfSignature(head: Buffer): string | undefined {
229
+ if (head.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) return 'image/png'
230
+ if (head.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)) return 'image/jpeg'
231
+ if (GIF_SIGNATURES.some(signature => head.subarray(0, signature.length).equals(signature))) return 'image/gif'
232
+ if (head.subarray(0, RIFF_SIGNATURE.length).equals(RIFF_SIGNATURE) && head.subarray(8, 12).equals(WEBP_SIGNATURE)) return 'image/webp'
233
+ return undefined
234
+ }
235
+
236
+ /**
237
+ * Read one whitelisted path, applying the three file decisions in order.
238
+ *
239
+ * The whitelist is the first decision and it is not this function's: a caller
240
+ * hands over a path it already matched byte for byte. What is left is whether the
241
+ * file at that path is still the one the session named — `realpath()` has to
242
+ * return the same string, so a symlink pointing anywhere else is refused rather
243
+ * than followed — whether it is a regular file at all, and whether its own first
244
+ * bytes are one of the four image signatures. The extension is never consulted: a
245
+ * `.png` that is not a PNG is refused, and a PNG named `.txt` is served.
246
+ *
247
+ * The answer's `image` is the reference the session's transcript named; this
248
+ * read measures nothing into it. The magic decides, and the bytes are what crosses.
249
+ * @param facts - the whitelist entry the request matched.
250
+ * @returns the bytes as base64, or the refusal the first failing decision states.
251
+ */
252
+ export async function readAttachment(facts: AttachmentFacts): Promise<AttachmentRead> {
253
+ const path = facts.path
254
+ let resolved: string
255
+ try {
256
+ resolved = await realpath(path)
257
+ } catch {
258
+ // Gone, unreadable, or a parent that is not a directory: either way there is
259
+ // no file at this path, which is the one thing `not-found` states.
260
+ return { ok: false, code: CODE_ATTACHMENT_NOT_FOUND, msg: 'no file at ' + path }
261
+ }
262
+ if (resolved !== path) {
263
+ return { ok: false, code: CODE_PATH_NOT_IN_SESSION, msg: path + ' resolves to ' + resolved + ', which this session never named' }
264
+ }
265
+ let size: number
266
+ try {
267
+ const info = await stat(path)
268
+ if (!info.isFile()) return { ok: false, code: CODE_ATTACHMENT_NOT_FOUND, msg: path + ' is not a regular file' }
269
+ size = info.size
270
+ } catch {
271
+ return { ok: false, code: CODE_ATTACHMENT_NOT_FOUND, msg: 'no file at ' + path }
272
+ }
273
+ // Base64 inflates by a third, so a file at or past the frame cap cannot fit one
274
+ // whatever the envelope costs: refused before it is read into memory.
275
+ if (size >= MAX_FRAME_BYTES) {
276
+ return { ok: false, code: FRAME_TOO_LARGE, msg: path + ' is ' + String(size) + ' bytes, past the ' + String(MAX_FRAME_BYTES) + ' byte frame' }
277
+ }
278
+ let bytes: Buffer
279
+ try {
280
+ bytes = await readFile(path)
281
+ } catch {
282
+ return { ok: false, code: CODE_ATTACHMENT_NOT_FOUND, msg: 'no file at ' + path }
283
+ }
284
+ if (mediaTypeOfSignature(bytes) === undefined) {
285
+ return { ok: false, code: CODE_NOT_AN_IMAGE, msg: path + ' is not a PNG, JPEG, WebP or GIF' }
286
+ }
287
+ return { ok: true, image: facts, data: bytes.toString('base64') }
288
+ }
@@ -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
@@ -605,7 +624,7 @@ function capabilitiesOf(value: unknown): ReadonlySet<string> {
605
624
  * @param value - the request's `answers` member, or undefined.
606
625
  * @returns the batch in protocol vocabulary, or undefined when it is not one.
607
626
  */
608
- function answersOf(value: unknown): readonly QuestionAnswerItem[] | undefined {
627
+ function answersOf(value: unknown): QuestionAnswerItem[] | undefined {
609
628
  if (!Array.isArray(value)) return undefined
610
629
  const answers: QuestionAnswerItem[] = []
611
630
  for (const entry of value) {
@@ -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')