@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.
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
3
3
  import { createHash, createPrivateKey, createPublicKey, randomBytes, sign, timingSafeEqual, verify } from "node:crypto";
4
- import { chmod, mkdir, open, readFile, rename } from "node:fs/promises";
4
+ import { chmod, mkdir, open, readFile, realpath, rename, stat } from "node:fs/promises";
5
5
  import { deflateRawSync } from "node:zlib";
6
6
  import { homedir, networkInterfaces } from "node:os";
7
7
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
@@ -785,6 +785,7 @@ const METHOD_SESSION_HISTORY_DEEP = "session.history.deep";
785
785
  const METHOD_SESSION_PROMPT = "session.prompt";
786
786
  const METHOD_SESSION_INTERRUPT = "session.interrupt";
787
787
  const METHOD_SESSION_ATTACHMENT = "session.attachment";
788
+ const METHOD_SESSION_ATTACHMENT_PATH = "session.attachment.path";
788
789
  const METHOD_SESSION_PERMISSIONS = "session.permissions";
789
790
  const METHOD_SESSION_SET_PERMISSION = "session.setPermission";
790
791
  const METHOD_SESSION_MODELS = "session.models";
@@ -1020,6 +1021,19 @@ const CAP_UI = "ui.v1";
1020
1021
  */
1021
1022
  const CAP_UI_LIST = "ui.list.v1";
1022
1023
  /**
1024
+ * Capability a client declares in `hello`'s `cap` array to be told that this
1025
+ * bridge can hand it the bytes of an image a session already offloaded.
1026
+ *
1027
+ * An announcement and nothing more, the same shape as
1028
+ * {@link CAP_SESSION_DEEP_HISTORY}: `session.attachment.path` is open to every
1029
+ * paired connection, because it is a pure read of one session's own durable
1030
+ * transcript that costs no other client anything. Declaring the capability is how
1031
+ * a client learns the method exists, and a client that does not declare it loses
1032
+ * only that knowledge — it never sees a frame from this channel, because it never
1033
+ * asks for one.
1034
+ */
1035
+ const CAP_SESSION_ATTACHMENT_PATH = "session.attachment.path.v1";
1036
+ /**
1023
1037
  * 宿主配了第二会合点时,在 `hello` 的 `capabilities` 里公告的能力名。
1024
1038
  *
1025
1039
  * 它是这条通道的全部门槛,而且门槛落在宿主这一侧:一个配了第二会合点的宿主才
@@ -1194,6 +1208,7 @@ const KNOWN_METHODS = /* @__PURE__ */ new Set([
1194
1208
  METHOD_SESSION_PROMPT,
1195
1209
  METHOD_SESSION_INTERRUPT,
1196
1210
  METHOD_SESSION_ATTACHMENT,
1211
+ METHOD_SESSION_ATTACHMENT_PATH,
1197
1212
  METHOD_SESSION_PERMISSIONS,
1198
1213
  METHOD_SESSION_SET_PERMISSION,
1199
1214
  METHOD_SESSION_MODELS,
@@ -1281,6 +1296,23 @@ const CODE_UI_LIST_UNAVAILABLE = "ui-list-unavailable";
1281
1296
  * an unaddressable one, rather than reading it blind.
1282
1297
  */
1283
1298
  const CODE_SESSION_NOT_FOLLOWABLE = "session-not-followable";
1299
+ /**
1300
+ * 该路径不在这次会话自己的持久 transcript 里:白名单只有两处来源,客户端自选的路径
1301
+ * 一律不在其中。`realpath()` 解析结果不再等于该字符串时也回这一码——那个路径已经
1302
+ * 指向别处,就不再是这次会话点过的那个文件。
1303
+ */
1304
+ const CODE_PATH_NOT_IN_SESSION = "path-not-in-session";
1305
+ /**
1306
+ * 白名单里有这个路径,但它已经不是一个常规文件:文件被删了,或被换成了目录、设备或
1307
+ * fifo。它与 {@link CODE_PATH_NOT_IN_SESSION} 是两个答案——「这次会话没点过它」与
1308
+ * 「点过的那个文件不在了」。
1309
+ */
1310
+ const CODE_ATTACHMENT_NOT_FOUND = "not-found";
1311
+ /**
1312
+ * 文件确实在,但它的文件头魔数不是 png/jpeg/webp/gif 四种之一。扩展名不作数:`.png`
1313
+ * 里装的不是 PNG 就回这一码,而一个叫 `.txt` 的 PNG 照常服务。
1314
+ */
1315
+ const CODE_NOT_AN_IMAGE = "not-an-image";
1284
1316
  const CODE_SNAPSHOT_UNAVAILABLE = "snapshot-unavailable";
1285
1317
  /**
1286
1318
  * This host composes no job registry, so it has no background jobs to publish.
@@ -1359,7 +1391,8 @@ const SERVED_CAPABILITIES = [
1359
1391
  CAP_USAGE,
1360
1392
  CAP_USAGE_STATS,
1361
1393
  CAP_UI,
1362
- CAP_UI_LIST
1394
+ CAP_UI_LIST,
1395
+ CAP_SESSION_ATTACHMENT_PATH
1363
1396
  ];
1364
1397
  /** `server` field of the hello response. */
1365
1398
  const SERVER_ID = "dsh-remote-bridge";
@@ -1879,6 +1912,499 @@ var ModelEffortPreferences = class {
1879
1912
  }
1880
1913
  };
1881
1914
  //#endregion
1915
+ //#region src/core/envelope.ts
1916
+ /**
1917
+ * Protocol v1 frame envelope: the one JSON-object-per-text-frame codec both
1918
+ * ends of the bridge speak. Shapes are frozen by the parent card and are not
1919
+ * ours to extend:
1920
+ *
1921
+ * request {"t":"req","id":<uint>,"m":"<method>","p":{...}}
1922
+ * response {"t":"res","id":<uint>,"ok":true,"r":{...}}
1923
+ * {"t":"res","id":<uint>,"ok":false,"e":{"code":"<str>","msg":"<str>"}}
1924
+ * event {"t":"ev","seq":<uint>,"m":"<topic>","p":{...}}
1925
+ * heartbeat {"t":"ping","ts":<ms>} / {"t":"pong","ts":<ms>}
1926
+ *
1927
+ * Decisions this module owns (not restated by the frozen design):
1928
+ * - the 10 MiB cap is measured in UTF-8 bytes of the received text, before
1929
+ * parsing, so an oversized frame never allocates a parsed object graph;
1930
+ * - direction violations (a `res` or `ev` arriving FROM the client) are their
1931
+ * own failure code instead of `malformed`, because "the peer is speaking the
1932
+ * wrong half of the protocol" is an actionable diagnostic;
1933
+ * - a frame whose identity cannot be recovered is answered with the reserved
1934
+ * id 0, since the envelope has no way to decline answering.
1935
+ * @module dsh-remote-bridge/core/envelope
1936
+ */
1937
+ /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
1938
+ const MAX_FRAME_BYTES = 10 * 1024 * 1024;
1939
+ /** Failure codes the codec itself raises. */
1940
+ const FRAME_TOO_LARGE = "frame-too-large";
1941
+ const MALFORMED_FRAME = "malformed";
1942
+ const DIRECTION_VIOLATION = "direction-violation";
1943
+ function isRecord$5(value) {
1944
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1945
+ }
1946
+ /** An envelope id is a non-negative safe integer. */
1947
+ function isFrameId(value) {
1948
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1949
+ }
1950
+ /**
1951
+ * Decode one received text frame.
1952
+ * @param text - the frame body exactly as it crossed the wire.
1953
+ * @returns the frame, or the refusal to answer with.
1954
+ */
1955
+ function decodeClientFrame(text) {
1956
+ if (Buffer.byteLength(text, "utf8") > 10485760) return {
1957
+ ok: false,
1958
+ id: 0,
1959
+ code: FRAME_TOO_LARGE,
1960
+ msg: `frame exceeds ${MAX_FRAME_BYTES} bytes`
1961
+ };
1962
+ let parsed;
1963
+ try {
1964
+ parsed = JSON.parse(text);
1965
+ } catch {
1966
+ return {
1967
+ ok: false,
1968
+ id: 0,
1969
+ code: MALFORMED_FRAME,
1970
+ msg: "frame is not JSON"
1971
+ };
1972
+ }
1973
+ if (!isRecord$5(parsed)) return {
1974
+ ok: false,
1975
+ id: 0,
1976
+ code: MALFORMED_FRAME,
1977
+ msg: "frame is not a JSON object"
1978
+ };
1979
+ const kind = parsed.t;
1980
+ if (kind === "ping" || kind === "pong") {
1981
+ if (typeof parsed.ts !== "number" || !Number.isFinite(parsed.ts)) return {
1982
+ ok: false,
1983
+ id: 0,
1984
+ code: MALFORMED_FRAME,
1985
+ msg: `${kind} requires a numeric ts`
1986
+ };
1987
+ return {
1988
+ ok: true,
1989
+ frame: {
1990
+ t: kind,
1991
+ ts: parsed.ts
1992
+ }
1993
+ };
1994
+ }
1995
+ if (kind === "res" || kind === "ev") return {
1996
+ ok: false,
1997
+ id: isFrameId(parsed.id) ? parsed.id : 0,
1998
+ code: DIRECTION_VIOLATION,
1999
+ msg: `a client must not send a ${kind} frame`
2000
+ };
2001
+ if (kind !== "req") return {
2002
+ ok: false,
2003
+ id: 0,
2004
+ code: MALFORMED_FRAME,
2005
+ msg: "frame has no known t discriminator"
2006
+ };
2007
+ if (!isFrameId(parsed.id)) return {
2008
+ ok: false,
2009
+ id: 0,
2010
+ code: MALFORMED_FRAME,
2011
+ msg: "req requires a non-negative integer id"
2012
+ };
2013
+ if (typeof parsed.m !== "string" || parsed.m === "") return {
2014
+ ok: false,
2015
+ id: parsed.id,
2016
+ code: MALFORMED_FRAME,
2017
+ msg: "req requires a method name"
2018
+ };
2019
+ if (parsed.p !== void 0 && !isRecord$5(parsed.p)) return {
2020
+ ok: false,
2021
+ id: parsed.id,
2022
+ code: MALFORMED_FRAME,
2023
+ msg: "req payload must be a JSON object"
2024
+ };
2025
+ return {
2026
+ ok: true,
2027
+ frame: {
2028
+ t: "req",
2029
+ id: parsed.id,
2030
+ m: parsed.m,
2031
+ p: parsed.p ?? {}
2032
+ }
2033
+ };
2034
+ }
2035
+ /** Encode one outgoing frame. */
2036
+ function encodeFrame(frame) {
2037
+ return JSON.stringify(frame);
2038
+ }
2039
+ /**
2040
+ * Decide the wire form of one encoded frame.
2041
+ *
2042
+ * The decision is a byte-level question only, asked after the frame has been
2043
+ * measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
2044
+ * stands, so a peer that inflates gets back the frame the text path would have
2045
+ * written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
2046
+ * does not shrink (zlib's default level), both stay text — a binary frame that
2047
+ * is larger than the text it replaces would pay for itself in neither direction.
2048
+ * @param text - the frame as {@link encodeFrame} produced it.
2049
+ * @param compress - whether the peer declared the capability that permits this.
2050
+ * @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
2051
+ * a caller injects one. Real deflate shrinks every frame that reaches the
2052
+ * threshold, so an injected compressor is the only way to exercise the no-gain
2053
+ * rule with content that truly cannot be compressed.
2054
+ * @returns the text, or raw DEFLATE of it.
2055
+ */
2056
+ function outboundPayloadOf(text, compress, deflate = deflateRawSync) {
2057
+ if (!compress) return {
2058
+ binary: false,
2059
+ text
2060
+ };
2061
+ const source = Buffer.from(text, "utf8");
2062
+ if (source.length < 1024) return {
2063
+ binary: false,
2064
+ text
2065
+ };
2066
+ const deflated = deflate(source);
2067
+ if (deflated.length >= source.length) return {
2068
+ binary: false,
2069
+ text
2070
+ };
2071
+ return {
2072
+ binary: true,
2073
+ deflated
2074
+ };
2075
+ }
2076
+ /** One successful response frame. */
2077
+ function responseFrame(id, result) {
2078
+ return {
2079
+ t: "res",
2080
+ id,
2081
+ ok: true,
2082
+ r: result
2083
+ };
2084
+ }
2085
+ /** One failed response frame. */
2086
+ function errorFrame(id, code, msg) {
2087
+ return {
2088
+ t: "res",
2089
+ id,
2090
+ ok: false,
2091
+ e: {
2092
+ code,
2093
+ msg
2094
+ }
2095
+ };
2096
+ }
2097
+ /**
2098
+ * Per-connection event sequence. The frozen design gives each connection its
2099
+ * own counter starting at 1; it is deliberately NOT the DSH session cursor
2100
+ * (§3.4), so the two numbers are never compared.
2101
+ */
2102
+ var EventSequence = class {
2103
+ #next = 1;
2104
+ /** @returns the next sequence number, advancing the counter. */
2105
+ take() {
2106
+ const value = this.#next;
2107
+ this.#next += 1;
2108
+ return value;
2109
+ }
2110
+ /** @returns the value {@link take} will return next, without advancing. */
2111
+ peek() {
2112
+ return this.#next;
2113
+ }
2114
+ };
2115
+ //#endregion
2116
+ //#region src/core/attachment-paths.ts
2117
+ /**
2118
+ * The image paths one session's own durable transcript whitelists, and the file
2119
+ * decisions `session.attachment.path` takes on the one path it is handed.
2120
+ *
2121
+ * This module IS that method's authorization. The bridge serves bytes only for a
2122
+ * path the session itself named, so the whitelist is computed here from that
2123
+ * session's store and from nothing else: never a path a client chose, never a
2124
+ * directory listing, never a second session.
2125
+ *
2126
+ * Two sources and no others:
2127
+ * - an offload placeholder in a message body, `<path>…</path>` immediately
2128
+ * followed by `<type>image</type>` — the envelope the harness writes when
2129
+ * it keeps image bytes out of a durable message, and the one a phone already
2130
+ * reads with `OffloadedImages.segments(of:)`;
2131
+ * - the image reference of a durable tool result — `meta.path`, what
2132
+ * `read_image` publishes through its `output.presentationMeta`, or a
2133
+ * text block that is itself a JSON image reference, which is how a
2134
+ * `run_code` program's own return value is persisted — and what a client
2135
+ * draws as `ToolBlock.image(ImageRef(path:))`.
2136
+ *
2137
+ * A path either source names is kept only when it is a host absolute path: the
2138
+ * request side admits nothing else, so a name that could never be asked for —
2139
+ * a plugin's own namespace, a relative path — is not a whitelist entry.
2140
+ *
2141
+ * Records are the ones `session/page` answers and `turnsOfRecords`
2142
+ * projects: `{event: {type, seq, time, data}}`.
2143
+ * @module dsh-remote-bridge/core/attachment-paths
2144
+ */
2145
+ /**
2146
+ * `<path>…</path>` immediately followed by `<type>image</type>`, plus
2147
+ * the facts the `<content>` body beside them states when it states any.
2148
+ */
2149
+ const OFFLOAD_PLACEHOLDER = /<path>([^<]*)<\/path>\s*<type>image<\/type>\s*(?:<content>\s*([^<]*?)\s*<\/content>)?/gu;
2150
+ /** One envelope body: `image/jpeg image, 1600x1000 px, 93031 bytes`. */
2151
+ const ENVELOPE_FACTS = /^(\S+)\s+image,\s*(\d+)x(\d+)\s+px,\s*(\d+)\s+bytes/u;
2152
+ /** The four heads a durable image may declare, byte for byte. */
2153
+ const PNG_SIGNATURE = Buffer.from([
2154
+ 137,
2155
+ 80,
2156
+ 78,
2157
+ 71,
2158
+ 13,
2159
+ 10,
2160
+ 26,
2161
+ 10
2162
+ ]);
2163
+ const JPEG_SIGNATURE = Buffer.from([
2164
+ 255,
2165
+ 216,
2166
+ 255
2167
+ ]);
2168
+ const GIF_SIGNATURES = [Buffer.from("GIF87a", "ascii"), Buffer.from("GIF89a", "ascii")];
2169
+ const RIFF_SIGNATURE = Buffer.from("RIFF", "ascii");
2170
+ const WEBP_SIGNATURE = Buffer.from("WEBP", "ascii");
2171
+ function isRecord$4(value) {
2172
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2173
+ }
2174
+ /** One durable record's `type` and `data`, or undefined when it is not one. */
2175
+ function entryOf(record) {
2176
+ const event = isRecord$4(record) ? record.event : void 0;
2177
+ if (!isRecord$4(event) || typeof event.type !== "string") return void 0;
2178
+ return {
2179
+ type: event.type,
2180
+ data: event.data
2181
+ };
2182
+ }
2183
+ /**
2184
+ * The oldest entry seq one store page carries.
2185
+ *
2186
+ * A page read walks backwards by this number, so the walk has to read it off the
2187
+ * page itself: the store's own `hasMore` says that older entries exist,
2188
+ * never where they end.
2189
+ * @param records - one `session/page` answer's records.
2190
+ * @returns the smallest `event.seq` they carry, or undefined when they carry none.
2191
+ */
2192
+ function oldestSeqOf(records) {
2193
+ let oldest;
2194
+ for (const record of records) {
2195
+ const seq = isRecord$4(record) && isRecord$4(record.event) ? record.event.seq : void 0;
2196
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq)) continue;
2197
+ if (oldest === void 0 || seq < oldest) oldest = seq;
2198
+ }
2199
+ return oldest;
2200
+ }
2201
+ /**
2202
+ * Every image path one session's durable records whitelist.
2203
+ * @param records - that session's own records, as `session/page` answered them.
2204
+ * @returns one entry per path; a second sighting never erases a stated fact.
2205
+ */
2206
+ function attachmentPathsOf(records) {
2207
+ const found = /* @__PURE__ */ new Map();
2208
+ for (const record of records) {
2209
+ const entry = entryOf(record);
2210
+ if (entry === void 0) continue;
2211
+ if (entry.type === "user/message") {
2212
+ for (const facts of placeholderFacts(entry.data)) remember(found, facts);
2213
+ continue;
2214
+ }
2215
+ if (entry.type !== "tool/result" && entry.type !== "tool/ptc-dispatch") continue;
2216
+ const path = toolResultImagePath(entry.data);
2217
+ if (path !== void 0) remember(found, { path });
2218
+ }
2219
+ return found;
2220
+ }
2221
+ /** The facts every offload placeholder of one message body states, in body order. */
2222
+ function placeholderFacts(data) {
2223
+ if (!isRecord$4(data) || !Array.isArray(data.content)) return [];
2224
+ const found = [];
2225
+ for (const block of data.content) {
2226
+ if (!isRecord$4(block) || block.type !== "text" || typeof block.text !== "string") continue;
2227
+ for (const match of block.text.matchAll(OFFLOAD_PLACEHOLDER)) {
2228
+ const path = match[1] ?? "";
2229
+ if (path === "") continue;
2230
+ found.push({
2231
+ path,
2232
+ ...envelopeFacts(match[2])
2233
+ });
2234
+ }
2235
+ }
2236
+ return found;
2237
+ }
2238
+ /** The facts one `<content>` body states, or nothing when it states none. */
2239
+ function envelopeFacts(body) {
2240
+ const stated = body === void 0 ? null : ENVELOPE_FACTS.exec(body.trim());
2241
+ if (stated === null) return {};
2242
+ return {
2243
+ mediaType: stated[1] ?? "",
2244
+ width: Number(stated[2]),
2245
+ height: Number(stated[3]),
2246
+ bytes: Number(stated[4])
2247
+ };
2248
+ }
2249
+ /**
2250
+ * The image reference one durable tool result states, or undefined.
2251
+ *
2252
+ * Two readings, the first that hits wins:
2253
+ * - `meta.path`, what `read_image` publishes through its
2254
+ * `output.presentationMeta` — kept only when the same result carried the
2255
+ * image block it names, because `read` publishes a `meta.path` of its
2256
+ * own and a session must not whitelist every file it ever read as text;
2257
+ * - a text block that IS a JSON image reference,
2258
+ * `{path, image:{attachmentId, mediaType, bytes, width, height, name}}` —
2259
+ * the shape a `run_code` program's own return value is persisted as.
2260
+ *
2261
+ * The JSON reading keeps its gate: the parsed object has to carry an `image`
2262
+ * object whose `mediaType` starts with `image/`. That gate is exactly what
2263
+ * separates a result that published an image from one that merely named a file —
2264
+ * measured over this host's whole store, 83 tool results carry a bare `path`
2265
+ * in the same JSON shape against 10 image references — and a path a tool named is
2266
+ * not an image this session offloaded.
2267
+ *
2268
+ * What is read is the reference the TOOL published, never the call's own argument
2269
+ * and never prose a model wrote: an argument is what the model asked for, and a
2270
+ * model's own words are not a record of anything.
2271
+ */
2272
+ function toolResultImagePath(data) {
2273
+ if (!isRecord$4(data)) return void 0;
2274
+ const content = isRecord$4(data.message) ? data.message.content : data.content;
2275
+ return publishedImagePath(data.meta, content) ?? jsonImageReference(content);
2276
+ }
2277
+ /** `meta.path`, but only when the same result carried the image block it names. */
2278
+ function publishedImagePath(meta, content) {
2279
+ const path = isRecord$4(meta) ? meta.path : void 0;
2280
+ if (typeof path !== "string" || path === "") return void 0;
2281
+ if (!Array.isArray(content) || !content.some((block) => isRecord$4(block) && block.type === "image")) return void 0;
2282
+ return path;
2283
+ }
2284
+ /** The path one text block states as a JSON image reference, or undefined. */
2285
+ function jsonImageReference(content) {
2286
+ if (!Array.isArray(content)) return void 0;
2287
+ for (const block of content) {
2288
+ if (!isRecord$4(block) || block.type !== "text" || typeof block.text !== "string") continue;
2289
+ let parsed;
2290
+ try {
2291
+ parsed = JSON.parse(block.text);
2292
+ } catch {
2293
+ continue;
2294
+ }
2295
+ if (!isRecord$4(parsed)) continue;
2296
+ const path = parsed.path;
2297
+ const image = parsed.image;
2298
+ if (typeof path !== "string" || path === "") continue;
2299
+ if (!isRecord$4(image) || typeof image.mediaType !== "string" || !image.mediaType.startsWith("image/")) continue;
2300
+ return path;
2301
+ }
2302
+ }
2303
+ /**
2304
+ * Remember one sighting, or drop it.
2305
+ *
2306
+ * A path that is not a host absolute path is not a whitelist entry at all. A
2307
+ * request has to name an absolute path, so `browser-view:screenshot/<tab>.png`
2308
+ * — the plugin-namespace name `browser_screenshot` writes into its envelope,
2309
+ * with no file behind it — could never be asked for, and a list of names no
2310
+ * request can match is not a whitelist. What an entry keeps is the reading that
2311
+ * states more: a later sighting never erases a stated fact.
2312
+ */
2313
+ function remember(found, facts) {
2314
+ if (!isAbsolute(facts.path)) return;
2315
+ const previous = found.get(facts.path);
2316
+ if (previous === void 0 || facts.mediaType !== void 0 && previous.mediaType === void 0) found.set(facts.path, facts);
2317
+ }
2318
+ /**
2319
+ * The media type one head declares, or undefined when it is none of the four.
2320
+ *
2321
+ * The signatures are the harness's own four — PNG, JPEG, GIF87a/89a and
2322
+ * RIFF-WebP — because the bytes are what a client will decode.
2323
+ * @param head - the file's first bytes, as read.
2324
+ * @returns the media type, or undefined.
2325
+ */
2326
+ function mediaTypeOfSignature(head) {
2327
+ if (head.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) return "image/png";
2328
+ if (head.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)) return "image/jpeg";
2329
+ if (GIF_SIGNATURES.some((signature) => head.subarray(0, signature.length).equals(signature))) return "image/gif";
2330
+ if (head.subarray(0, RIFF_SIGNATURE.length).equals(RIFF_SIGNATURE) && head.subarray(8, 12).equals(WEBP_SIGNATURE)) return "image/webp";
2331
+ }
2332
+ /**
2333
+ * Read one whitelisted path, applying the three file decisions in order.
2334
+ *
2335
+ * The whitelist is the first decision and it is not this function's: a caller
2336
+ * hands over a path it already matched byte for byte. What is left is whether the
2337
+ * file at that path is still the one the session named — `realpath()` has to
2338
+ * return the same string, so a symlink pointing anywhere else is refused rather
2339
+ * than followed — whether it is a regular file at all, and whether its own first
2340
+ * bytes are one of the four image signatures. The extension is never consulted: a
2341
+ * `.png` that is not a PNG is refused, and a PNG named `.txt` is served.
2342
+ *
2343
+ * The answer's `image` is the reference the session's transcript named; this
2344
+ * read measures nothing into it. The magic decides, and the bytes are what crosses.
2345
+ * @param facts - the whitelist entry the request matched.
2346
+ * @returns the bytes as base64, or the refusal the first failing decision states.
2347
+ */
2348
+ async function readAttachment(facts) {
2349
+ const path = facts.path;
2350
+ let resolved;
2351
+ try {
2352
+ resolved = await realpath(path);
2353
+ } catch {
2354
+ return {
2355
+ ok: false,
2356
+ code: CODE_ATTACHMENT_NOT_FOUND,
2357
+ msg: "no file at " + path
2358
+ };
2359
+ }
2360
+ if (resolved !== path) return {
2361
+ ok: false,
2362
+ code: CODE_PATH_NOT_IN_SESSION,
2363
+ msg: path + " resolves to " + resolved + ", which this session never named"
2364
+ };
2365
+ let size;
2366
+ try {
2367
+ const info = await stat(path);
2368
+ if (!info.isFile()) return {
2369
+ ok: false,
2370
+ code: CODE_ATTACHMENT_NOT_FOUND,
2371
+ msg: path + " is not a regular file"
2372
+ };
2373
+ size = info.size;
2374
+ } catch {
2375
+ return {
2376
+ ok: false,
2377
+ code: CODE_ATTACHMENT_NOT_FOUND,
2378
+ msg: "no file at " + path
2379
+ };
2380
+ }
2381
+ if (size >= 10485760) return {
2382
+ ok: false,
2383
+ code: FRAME_TOO_LARGE,
2384
+ msg: path + " is " + String(size) + " bytes, past the " + String(MAX_FRAME_BYTES) + " byte frame"
2385
+ };
2386
+ let bytes;
2387
+ try {
2388
+ bytes = await readFile(path);
2389
+ } catch {
2390
+ return {
2391
+ ok: false,
2392
+ code: CODE_ATTACHMENT_NOT_FOUND,
2393
+ msg: "no file at " + path
2394
+ };
2395
+ }
2396
+ if (mediaTypeOfSignature(bytes) === void 0) return {
2397
+ ok: false,
2398
+ code: CODE_NOT_AN_IMAGE,
2399
+ msg: path + " is not a PNG, JPEG, WebP or GIF"
2400
+ };
2401
+ return {
2402
+ ok: true,
2403
+ image: facts,
2404
+ data: bytes.toString("base64")
2405
+ };
2406
+ }
2407
+ //#endregion
1882
2408
  //#region src/core/commands.ts
1883
2409
  /** The draft text one host name completes to: the gesture plus its separator. */
1884
2410
  function lineOf(name) {
@@ -2120,11 +2646,11 @@ const RENDERED_ENTRY_TYPES = /* @__PURE__ */ new Set([
2120
2646
  "tool/result",
2121
2647
  "subagent/catalog"
2122
2648
  ]);
2123
- function isRecord$4(value) {
2649
+ function isRecord$3(value) {
2124
2650
  return typeof value === "object" && value !== null && !Array.isArray(value);
2125
2651
  }
2126
2652
  function stringField(value, key) {
2127
- if (!isRecord$4(value)) return void 0;
2653
+ if (!isRecord$3(value)) return void 0;
2128
2654
  const field = value[key];
2129
2655
  return typeof field === "string" ? field : void 0;
2130
2656
  }
@@ -2200,9 +2726,9 @@ var MessageIndex = class {
2200
2726
  * @returns the child ids the payload names, in the order it names them.
2201
2727
  */
2202
2728
  function spawnedChildIdsOf(data) {
2203
- const message = isRecord$4(data) ? data.message : void 0;
2729
+ const message = isRecord$3(data) ? data.message : void 0;
2204
2730
  const ids = [];
2205
- for (const id of spawnIdsIn(textOfBlocks(isRecord$4(message) ? message.content : void 0))) if (!ids.includes(id)) ids.push(id);
2731
+ for (const id of spawnIdsIn(textOfBlocks(isRecord$3(message) ? message.content : void 0))) if (!ids.includes(id)) ids.push(id);
2206
2732
  return ids;
2207
2733
  }
2208
2734
  /** The spawn signatures above, as the two patterns that carry a child id. */
@@ -2231,8 +2757,8 @@ function spawnIdsIn(text) {
2231
2757
  function spawnCallEvidence(records) {
2232
2758
  const evidence = /* @__PURE__ */ new Map();
2233
2759
  for (const record of records) {
2234
- const event = isRecord$4(record) ? record.event : void 0;
2235
- if (!isRecord$4(event) || event.type !== "tool/result") continue;
2760
+ const event = isRecord$3(record) ? record.event : void 0;
2761
+ if (!isRecord$3(event) || event.type !== "tool/result") continue;
2236
2762
  const callId = toolResultCallIdOf(event.data);
2237
2763
  if (callId === void 0) continue;
2238
2764
  for (const childId of spawnedChildIdsOf(event.data)) evidence.set(childId, callId);
@@ -2241,7 +2767,7 @@ function spawnCallEvidence(records) {
2241
2767
  }
2242
2768
  /** @returns the call id one durable `tool/result` payload belongs to. */
2243
2769
  function toolResultCallIdOf(data) {
2244
- const callId = stringField(isRecord$4(data) ? data.message : void 0, "toolCallId");
2770
+ const callId = stringField(isRecord$3(data) ? data.message : void 0, "toolCallId");
2245
2771
  return callId === void 0 || callId === "" ? void 0 : callId;
2246
2772
  }
2247
2773
  /**
@@ -2288,15 +2814,15 @@ var SpawnCallIndex = class {
2288
2814
  */
2289
2815
  observe(type, data) {
2290
2816
  if (type === "turn/start") {
2291
- this.#turn = numberOf(isRecord$4(data) ? data.turn : void 0);
2817
+ this.#turn = numberOf(isRecord$3(data) ? data.turn : void 0);
2292
2818
  this.#step = void 0;
2293
2819
  this.#calls = [];
2294
2820
  this.#correlated.clear();
2295
2821
  return;
2296
2822
  }
2297
2823
  if (type === "step/start") {
2298
- this.#turn = numberOf(isRecord$4(data) ? data.turn : void 0) ?? this.#turn;
2299
- this.#step = numberOf(isRecord$4(data) ? data.step : void 0);
2824
+ this.#turn = numberOf(isRecord$3(data) ? data.turn : void 0) ?? this.#turn;
2825
+ this.#step = numberOf(isRecord$3(data) ? data.step : void 0);
2300
2826
  this.#calls = [];
2301
2827
  this.#correlated.clear();
2302
2828
  return;
@@ -2310,8 +2836,8 @@ var SpawnCallIndex = class {
2310
2836
  if (type !== "tool/call") return;
2311
2837
  const callId = stringField(data, "callId");
2312
2838
  if (callId === void 0 || callId === "") return;
2313
- this.#turn = numberOf(isRecord$4(data) ? data.turn : void 0) ?? this.#turn;
2314
- this.#step = numberOf(isRecord$4(data) ? data.step : void 0) ?? this.#step;
2839
+ this.#turn = numberOf(isRecord$3(data) ? data.turn : void 0) ?? this.#turn;
2840
+ this.#step = numberOf(isRecord$3(data) ? data.step : void 0) ?? this.#step;
2315
2841
  this.#calls.push(callId);
2316
2842
  }
2317
2843
  /**
@@ -2338,7 +2864,7 @@ var SpawnCallIndex = class {
2338
2864
  * @returns the cursor and records, or undefined when this frame is not a snapshot.
2339
2865
  */
2340
2866
  function readFollowBaseline(frame) {
2341
- if (!isRecord$4(frame) || frame.type !== "snapshot") return void 0;
2867
+ if (!isRecord$3(frame) || frame.type !== "snapshot") return void 0;
2342
2868
  const cursor = frame.cursor;
2343
2869
  const records = frame.records;
2344
2870
  if (typeof cursor !== "number" || !Array.isArray(records)) return void 0;
@@ -2357,11 +2883,11 @@ function readFollowBaseline(frame) {
2357
2883
  * @param memory - the stream's own correlation state, and which optional kinds it declared.
2358
2884
  */
2359
2885
  function deltaOfFollowFrame(frame, toolCalls, messages, memory = {}) {
2360
- if (!isRecord$4(frame)) return void 0;
2886
+ if (!isRecord$3(frame)) return void 0;
2361
2887
  if (frame.type === "assistant-stream") return deltaOfAssistantStream(frame.frame, toolCalls);
2362
2888
  if (frame.type !== "event") return void 0;
2363
2889
  const event = frame.event;
2364
- if (!isRecord$4(event)) return void 0;
2890
+ if (!isRecord$3(event)) return void 0;
2365
2891
  const type = event.type;
2366
2892
  const data = event.data;
2367
2893
  memory.spawnCalls?.observe(typeof type === "string" ? type : "", data);
@@ -2402,7 +2928,7 @@ function subagentDelta(data, spawnCalls) {
2402
2928
  * report an origin the host never recorded.
2403
2929
  */
2404
2930
  function actorOf(data) {
2405
- return actorOfSource(isRecord$4(data) ? data.source : void 0);
2931
+ return actorOfSource(isRecord$3(data) ? data.source : void 0);
2406
2932
  }
2407
2933
  /**
2408
2934
  * Derive one message's actor from the host's own `source` record, mechanically.
@@ -2438,9 +2964,9 @@ function textField(value, key) {
2438
2964
  return field === void 0 || field === "" ? void 0 : field;
2439
2965
  }
2440
2966
  function deltaOfAssistantStream(frame, toolCalls) {
2441
- if (!isRecord$4(frame) || frame.type !== "chunk") return void 0;
2967
+ if (!isRecord$3(frame) || frame.type !== "chunk") return void 0;
2442
2968
  const chunk = frame.chunk;
2443
- if (!isRecord$4(chunk)) return void 0;
2969
+ if (!isRecord$3(chunk)) return void 0;
2444
2970
  const index = typeof chunk.index === "number" ? chunk.index : 0;
2445
2971
  if (chunk.type === "text-delta" && typeof chunk.text === "string") return {
2446
2972
  kind: "text",
@@ -2465,8 +2991,8 @@ function deltaOfAssistantStream(frame, toolCalls) {
2465
2991
  }
2466
2992
  }
2467
2993
  function toolResultDelta(data) {
2468
- const message = isRecord$4(data) ? data.message : void 0;
2469
- if (!isRecord$4(message)) return void 0;
2994
+ const message = isRecord$3(data) ? data.message : void 0;
2995
+ if (!isRecord$3(message)) return void 0;
2470
2996
  const callId = message.toolCallId;
2471
2997
  if (typeof callId !== "string" || callId === "") return void 0;
2472
2998
  return {
@@ -2477,8 +3003,8 @@ function toolResultDelta(data) {
2477
3003
  };
2478
3004
  }
2479
3005
  function turnEndDelta(data) {
2480
- const reason = isRecord$4(data) ? data.reason : void 0;
2481
- const kind = isRecord$4(reason) ? reason.kind : void 0;
3006
+ const reason = isRecord$3(data) ? data.reason : void 0;
3007
+ const kind = isRecord$3(reason) ? reason.kind : void 0;
2482
3008
  return {
2483
3009
  kind: "turn-end",
2484
3010
  reason: typeof kind === "string" ? kind : "unknown"
@@ -2508,7 +3034,7 @@ function textOfBlocks(content) {
2508
3034
  if (!Array.isArray(content)) return "";
2509
3035
  const parts = [];
2510
3036
  for (const block of content) {
2511
- if (!isRecord$4(block)) continue;
3037
+ if (!isRecord$3(block)) continue;
2512
3038
  if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
2513
3039
  }
2514
3040
  return parts.join("\n");
@@ -2522,7 +3048,7 @@ function textOfBlocks(content) {
2522
3048
  * and file blocks travel in `attachments`, never inside it.
2523
3049
  */
2524
3050
  function userMessageDelta(data, messages) {
2525
- if (!isRecord$4(data)) return void 0;
3051
+ if (!isRecord$3(data)) return void 0;
2526
3052
  const messageId = stringField(data, "id");
2527
3053
  if (messageId !== void 0) {
2528
3054
  if (messages.has(messageId)) return void 0;
@@ -2549,9 +3075,9 @@ function imageAttachmentsOf(content) {
2549
3075
  if (!Array.isArray(content)) return [];
2550
3076
  const attachments = [];
2551
3077
  for (const block of content) {
2552
- if (!isRecord$4(block) || block.type !== "image") continue;
3078
+ if (!isRecord$3(block) || block.type !== "image") continue;
2553
3079
  const ref = block.attachment;
2554
- if (!isRecord$4(ref)) continue;
3080
+ if (!isRecord$3(ref)) continue;
2555
3081
  const attachmentId = stringField(ref, "attachmentId");
2556
3082
  const mediaType = stringField(ref, "mediaType");
2557
3083
  if (attachmentId === void 0 || mediaType === void 0) continue;
@@ -2571,7 +3097,7 @@ function imageAttachmentsOf(content) {
2571
3097
  * must never record a token count the harness did not report.
2572
3098
  */
2573
3099
  function usageDelta(data) {
2574
- if (!isRecord$4(data)) return void 0;
3100
+ if (!isRecord$3(data)) return void 0;
2575
3101
  const usage = usageOf(data.usage);
2576
3102
  if (usage === void 0) return void 0;
2577
3103
  const turn = numberOf(data.turn);
@@ -2585,7 +3111,7 @@ function usageDelta(data) {
2585
3111
  }
2586
3112
  /** Read one `TokenUsage` verbatim; undefined when its two mandatory counters are not numbers. */
2587
3113
  function usageOf(value) {
2588
- if (!isRecord$4(value)) return void 0;
3114
+ if (!isRecord$3(value)) return void 0;
2589
3115
  const inputTokens = numberOf(value.inputTokens);
2590
3116
  const outputTokens = numberOf(value.outputTokens);
2591
3117
  if (inputTokens === void 0 || outputTokens === void 0) return void 0;
@@ -2641,7 +3167,7 @@ function turnsOfRecords(records) {
2641
3167
  if (entry.type === "turn/end") {
2642
3168
  current.endSeq = entry.seq;
2643
3169
  current.endTime = entry.time;
2644
- current.reason = isRecord$4(entry.data) && isRecord$4(entry.data.reason) && typeof entry.data.reason.kind === "string" ? entry.data.reason.kind : "unknown";
3170
+ current.reason = isRecord$3(entry.data) && isRecord$3(entry.data.reason) && typeof entry.data.reason.kind === "string" ? entry.data.reason.kind : "unknown";
2645
3171
  turns.push(current);
2646
3172
  current = void 0;
2647
3173
  }
@@ -2661,7 +3187,7 @@ function turnsOfRecords(records) {
2661
3187
  * @param spawns - the index holding this session's spawn evidence.
2662
3188
  */
2663
3189
  function catalogEntryWithCall(entry, spawns) {
2664
- if (!isRecord$4(entry.data)) return entry;
3190
+ if (!isRecord$3(entry.data)) return entry;
2665
3191
  const childId = stringField(entry.data, "childId");
2666
3192
  if (childId === void 0 || childId === "") return entry;
2667
3193
  const callId = spawns.spawnCallId(childId);
@@ -2740,295 +3266,94 @@ function pageTurns(turns, before, maxBytes, measure) {
2740
3266
  if (start < flat.length && estimate + cost > maxBytes) break;
2741
3267
  estimate += cost;
2742
3268
  start = index;
2743
- }
2744
- for (;;) {
2745
- const oldest = flat[start]?.entry.seq;
2746
- if (oldest === void 0) return {
2747
- turns: [],
2748
- hasMore: false
2749
- };
2750
- const page = groupEntries(flat.slice(start));
2751
- const hasMore = start > 0;
2752
- if (flat.length - start === 1 || measure(page, hasMore ? oldest : void 0, hasMore) <= maxBytes) return hasMore ? {
2753
- turns: page,
2754
- nextBefore: oldest,
2755
- hasMore
2756
- } : {
2757
- turns: page,
2758
- hasMore
2759
- };
2760
- start += 1;
2761
- }
2762
- }
2763
- /**
2764
- * Durable seq of a projection's oldest entry, or undefined when it carries none.
2765
- *
2766
- * The oldest entry is the first entry of the first turn that has one: a trimmed
2767
- * turn may keep no entry at all, so the scan skips those rather than reading
2768
- * `turns[0].entries[0]` and calling an empty-leading view an empty window.
2769
- * @param turns - the projection to read, in order.
2770
- */
2771
- function oldestEntrySeq(turns) {
2772
- for (const turn of turns) {
2773
- const first = turn.entries[0];
2774
- if (first !== void 0) return first.seq;
2775
- }
2776
- }
2777
- /**
2778
- * Cut a projection at a durable watermark, keeping what is strictly above it.
2779
- *
2780
- * This is the forward twin of {@link pageTurns}' own slice: the same
2781
- * entry-level rule (`seq` is a durable watermark, not an index), the same
2782
- * turn rebuild, so an incremental snapshot carries turns shaped exactly like
2783
- * the baseline it continues — a turn whose remaining entries are fewer keeps
2784
- * its own `seq`, `endSeq`, `reason` and `time`.
2785
- * @param turns - the projection to cut, in order.
2786
- * @param watermark - exclusive durable watermark; entries at or below it are dropped.
2787
- */
2788
- function turnsAbove(turns, watermark) {
2789
- const kept = [];
2790
- for (const turn of turns) for (const entry of turn.entries) if (entry.seq > watermark) kept.push({
2791
- turn,
2792
- entry
2793
- });
2794
- return groupEntries(kept);
2795
- }
2796
- /** Rebuild the turn list around one contiguous run of entries. */
2797
- function groupEntries(items) {
2798
- const page = [];
2799
- let current;
2800
- let entries = [];
2801
- for (const item of items) {
2802
- if (current !== item.turn) {
2803
- if (current !== void 0) page.push({
2804
- ...current,
2805
- entries
2806
- });
2807
- current = item.turn;
2808
- entries = [];
2809
- }
2810
- entries.push(item.entry);
2811
- }
2812
- if (current !== void 0) page.push({
2813
- ...current,
2814
- entries
2815
- });
2816
- return page;
2817
- }
2818
- function snapshotEntryOf(record) {
2819
- const event = isRecord$4(record) ? record.event : void 0;
2820
- if (!isRecord$4(event)) return void 0;
2821
- if (typeof event.type !== "string" || typeof event.seq !== "number") return void 0;
2822
- const actor = event.type === "user/message" ? actorOf(event.data) : void 0;
2823
- return {
2824
- seq: event.seq,
2825
- time: typeof event.time === "number" ? event.time : 0,
2826
- type: event.type,
2827
- data: event.data,
2828
- ...actor === void 0 ? {} : { actor }
2829
- };
2830
- }
2831
- //#endregion
2832
- //#region src/core/envelope.ts
2833
- /**
2834
- * Protocol v1 frame envelope: the one JSON-object-per-text-frame codec both
2835
- * ends of the bridge speak. Shapes are frozen by the parent card and are not
2836
- * ours to extend:
2837
- *
2838
- * request {"t":"req","id":<uint>,"m":"<method>","p":{...}}
2839
- * response {"t":"res","id":<uint>,"ok":true,"r":{...}}
2840
- * {"t":"res","id":<uint>,"ok":false,"e":{"code":"<str>","msg":"<str>"}}
2841
- * event {"t":"ev","seq":<uint>,"m":"<topic>","p":{...}}
2842
- * heartbeat {"t":"ping","ts":<ms>} / {"t":"pong","ts":<ms>}
2843
- *
2844
- * Decisions this module owns (not restated by the frozen design):
2845
- * - the 10 MiB cap is measured in UTF-8 bytes of the received text, before
2846
- * parsing, so an oversized frame never allocates a parsed object graph;
2847
- * - direction violations (a `res` or `ev` arriving FROM the client) are their
2848
- * own failure code instead of `malformed`, because "the peer is speaking the
2849
- * wrong half of the protocol" is an actionable diagnostic;
2850
- * - a frame whose identity cannot be recovered is answered with the reserved
2851
- * id 0, since the envelope has no way to decline answering.
2852
- * @module dsh-remote-bridge/core/envelope
2853
- */
2854
- /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
2855
- const MAX_FRAME_BYTES = 10 * 1024 * 1024;
2856
- /** Failure codes the codec itself raises. */
2857
- const FRAME_TOO_LARGE = "frame-too-large";
2858
- const MALFORMED_FRAME = "malformed";
2859
- const DIRECTION_VIOLATION = "direction-violation";
2860
- function isRecord$3(value) {
2861
- return typeof value === "object" && value !== null && !Array.isArray(value);
2862
- }
2863
- /** An envelope id is a non-negative safe integer. */
2864
- function isFrameId(value) {
2865
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2866
- }
2867
- /**
2868
- * Decode one received text frame.
2869
- * @param text - the frame body exactly as it crossed the wire.
2870
- * @returns the frame, or the refusal to answer with.
2871
- */
2872
- function decodeClientFrame(text) {
2873
- if (Buffer.byteLength(text, "utf8") > 10485760) return {
2874
- ok: false,
2875
- id: 0,
2876
- code: FRAME_TOO_LARGE,
2877
- msg: `frame exceeds ${MAX_FRAME_BYTES} bytes`
2878
- };
2879
- let parsed;
2880
- try {
2881
- parsed = JSON.parse(text);
2882
- } catch {
2883
- return {
2884
- ok: false,
2885
- id: 0,
2886
- code: MALFORMED_FRAME,
2887
- msg: "frame is not JSON"
2888
- };
2889
- }
2890
- if (!isRecord$3(parsed)) return {
2891
- ok: false,
2892
- id: 0,
2893
- code: MALFORMED_FRAME,
2894
- msg: "frame is not a JSON object"
2895
- };
2896
- const kind = parsed.t;
2897
- if (kind === "ping" || kind === "pong") {
2898
- if (typeof parsed.ts !== "number" || !Number.isFinite(parsed.ts)) return {
2899
- ok: false,
2900
- id: 0,
2901
- code: MALFORMED_FRAME,
2902
- msg: `${kind} requires a numeric ts`
3269
+ }
3270
+ for (;;) {
3271
+ const oldest = flat[start]?.entry.seq;
3272
+ if (oldest === void 0) return {
3273
+ turns: [],
3274
+ hasMore: false
2903
3275
  };
2904
- return {
2905
- ok: true,
2906
- frame: {
2907
- t: kind,
2908
- ts: parsed.ts
2909
- }
3276
+ const page = groupEntries(flat.slice(start));
3277
+ const hasMore = start > 0;
3278
+ if (flat.length - start === 1 || measure(page, hasMore ? oldest : void 0, hasMore) <= maxBytes) return hasMore ? {
3279
+ turns: page,
3280
+ nextBefore: oldest,
3281
+ hasMore
3282
+ } : {
3283
+ turns: page,
3284
+ hasMore
2910
3285
  };
3286
+ start += 1;
2911
3287
  }
2912
- if (kind === "res" || kind === "ev") return {
2913
- ok: false,
2914
- id: isFrameId(parsed.id) ? parsed.id : 0,
2915
- code: DIRECTION_VIOLATION,
2916
- msg: `a client must not send a ${kind} frame`
2917
- };
2918
- if (kind !== "req") return {
2919
- ok: false,
2920
- id: 0,
2921
- code: MALFORMED_FRAME,
2922
- msg: "frame has no known t discriminator"
2923
- };
2924
- if (!isFrameId(parsed.id)) return {
2925
- ok: false,
2926
- id: 0,
2927
- code: MALFORMED_FRAME,
2928
- msg: "req requires a non-negative integer id"
2929
- };
2930
- if (typeof parsed.m !== "string" || parsed.m === "") return {
2931
- ok: false,
2932
- id: parsed.id,
2933
- code: MALFORMED_FRAME,
2934
- msg: "req requires a method name"
2935
- };
2936
- if (parsed.p !== void 0 && !isRecord$3(parsed.p)) return {
2937
- ok: false,
2938
- id: parsed.id,
2939
- code: MALFORMED_FRAME,
2940
- msg: "req payload must be a JSON object"
2941
- };
2942
- return {
2943
- ok: true,
2944
- frame: {
2945
- t: "req",
2946
- id: parsed.id,
2947
- m: parsed.m,
2948
- p: parsed.p ?? {}
2949
- }
2950
- };
2951
3288
  }
2952
- /** Encode one outgoing frame. */
2953
- function encodeFrame(frame) {
2954
- return JSON.stringify(frame);
3289
+ /**
3290
+ * Durable seq of a projection's oldest entry, or undefined when it carries none.
3291
+ *
3292
+ * The oldest entry is the first entry of the first turn that has one: a trimmed
3293
+ * turn may keep no entry at all, so the scan skips those rather than reading
3294
+ * `turns[0].entries[0]` and calling an empty-leading view an empty window.
3295
+ * @param turns - the projection to read, in order.
3296
+ */
3297
+ function oldestEntrySeq(turns) {
3298
+ for (const turn of turns) {
3299
+ const first = turn.entries[0];
3300
+ if (first !== void 0) return first.seq;
3301
+ }
2955
3302
  }
2956
3303
  /**
2957
- * Decide the wire form of one encoded frame.
3304
+ * Cut a projection at a durable watermark, keeping what is strictly above it.
2958
3305
  *
2959
- * The decision is a byte-level question only, asked after the frame has been
2960
- * measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
2961
- * stands, so a peer that inflates gets back the frame the text path would have
2962
- * written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
2963
- * does not shrink (zlib's default level), both stay text — a binary frame that
2964
- * is larger than the text it replaces would pay for itself in neither direction.
2965
- * @param text - the frame as {@link encodeFrame} produced it.
2966
- * @param compress - whether the peer declared the capability that permits this.
2967
- * @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
2968
- * a caller injects one. Real deflate shrinks every frame that reaches the
2969
- * threshold, so an injected compressor is the only way to exercise the no-gain
2970
- * rule with content that truly cannot be compressed.
2971
- * @returns the text, or raw DEFLATE of it.
3306
+ * This is the forward twin of {@link pageTurns}' own slice: the same
3307
+ * entry-level rule (`seq` is a durable watermark, not an index), the same
3308
+ * turn rebuild, so an incremental snapshot carries turns shaped exactly like
3309
+ * the baseline it continues — a turn whose remaining entries are fewer keeps
3310
+ * its own `seq`, `endSeq`, `reason` and `time`.
3311
+ * @param turns - the projection to cut, in order.
3312
+ * @param watermark - exclusive durable watermark; entries at or below it are dropped.
2972
3313
  */
2973
- function outboundPayloadOf(text, compress, deflate = deflateRawSync) {
2974
- if (!compress) return {
2975
- binary: false,
2976
- text
2977
- };
2978
- const source = Buffer.from(text, "utf8");
2979
- if (source.length < 1024) return {
2980
- binary: false,
2981
- text
2982
- };
2983
- const deflated = deflate(source);
2984
- if (deflated.length >= source.length) return {
2985
- binary: false,
2986
- text
2987
- };
2988
- return {
2989
- binary: true,
2990
- deflated
2991
- };
3314
+ function turnsAbove(turns, watermark) {
3315
+ const kept = [];
3316
+ for (const turn of turns) for (const entry of turn.entries) if (entry.seq > watermark) kept.push({
3317
+ turn,
3318
+ entry
3319
+ });
3320
+ return groupEntries(kept);
2992
3321
  }
2993
- /** One successful response frame. */
2994
- function responseFrame(id, result) {
2995
- return {
2996
- t: "res",
2997
- id,
2998
- ok: true,
2999
- r: result
3000
- };
3322
+ /** Rebuild the turn list around one contiguous run of entries. */
3323
+ function groupEntries(items) {
3324
+ const page = [];
3325
+ let current;
3326
+ let entries = [];
3327
+ for (const item of items) {
3328
+ if (current !== item.turn) {
3329
+ if (current !== void 0) page.push({
3330
+ ...current,
3331
+ entries
3332
+ });
3333
+ current = item.turn;
3334
+ entries = [];
3335
+ }
3336
+ entries.push(item.entry);
3337
+ }
3338
+ if (current !== void 0) page.push({
3339
+ ...current,
3340
+ entries
3341
+ });
3342
+ return page;
3001
3343
  }
3002
- /** One failed response frame. */
3003
- function errorFrame(id, code, msg) {
3344
+ function snapshotEntryOf(record) {
3345
+ const event = isRecord$3(record) ? record.event : void 0;
3346
+ if (!isRecord$3(event)) return void 0;
3347
+ if (typeof event.type !== "string" || typeof event.seq !== "number") return void 0;
3348
+ const actor = event.type === "user/message" ? actorOf(event.data) : void 0;
3004
3349
  return {
3005
- t: "res",
3006
- id,
3007
- ok: false,
3008
- e: {
3009
- code,
3010
- msg
3011
- }
3350
+ seq: event.seq,
3351
+ time: typeof event.time === "number" ? event.time : 0,
3352
+ type: event.type,
3353
+ data: event.data,
3354
+ ...actor === void 0 ? {} : { actor }
3012
3355
  };
3013
3356
  }
3014
- /**
3015
- * Per-connection event sequence. The frozen design gives each connection its
3016
- * own counter starting at 1; it is deliberately NOT the DSH session cursor
3017
- * (§3.4), so the two numbers are never compared.
3018
- */
3019
- var EventSequence = class {
3020
- #next = 1;
3021
- /** @returns the next sequence number, advancing the counter. */
3022
- take() {
3023
- const value = this.#next;
3024
- this.#next += 1;
3025
- return value;
3026
- }
3027
- /** @returns the value {@link take} will return next, without advancing. */
3028
- peek() {
3029
- return this.#next;
3030
- }
3031
- };
3032
3357
  /** The only deep-link form this channel emits. */
3033
3358
  const PUSH_DEEP_LINK_PREFIX = "whale://session/";
3034
3359
  /**
@@ -5705,6 +6030,26 @@ var BridgeConnection = class {
5705
6030
  #receipts = /* @__PURE__ */ new Set();
5706
6031
  #toolCalls = new ToolCallIndex();
5707
6032
  #messages = new MessageIndex();
6033
+ /**
6034
+ * The whitelists this connection has already computed, keyed by session id and
6035
+ * ordered least recently used first.
6036
+ *
6037
+ * This is not the cache `session.attachment` refuses to keep, and it does not
6038
+ * weaken that rule: that one is about image BYTES — an image can be offloaded
6039
+ * after the fact, so every read of a file goes to the disk it is on. This is a
6040
+ * set of PATHS, keyed by the durable watermark that would invalidate it, so a
6041
+ * request arriving under the same `asOfSeq` can only be answered the same
6042
+ * set. Nothing stale can be served, and an offload that moves the watermark
6043
+ * moves the key with it.
6044
+ *
6045
+ * What it buys is the walk. A cold read of the longest session this host holds
6046
+ * (measured: 5,680 entries, 6.0 MiB compressed) inflates in 40.8 ms and
6047
+ * inflates plus parses in 108 ms, and the walk pays that once per page — two
6048
+ * pages at {@link DEEP_HISTORY_WINDOW}. A phone scrolling a screen of tool
6049
+ * cards asks several times with no event in between, so without this it would
6050
+ * pay the inflate once per card.
6051
+ */
6052
+ #attachmentWhitelists = /* @__PURE__ */ new Map();
5708
6053
  #capabilities = /* @__PURE__ */ new Set();
5709
6054
  /** Delegated children this connection has learned the durable parent of, by child id. */
5710
6055
  #lineage = /* @__PURE__ */ new Map();
@@ -5907,6 +6252,7 @@ var BridgeConnection = class {
5907
6252
  case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p);
5908
6253
  case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p);
5909
6254
  case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id);
6255
+ case METHOD_SESSION_ATTACHMENT_PATH: return await this.#sessionAttachmentPath(frame.p, frame.id);
5910
6256
  case METHOD_SESSION_PERMISSIONS: return this.#sessionPermissions(frame.p);
5911
6257
  case METHOD_SESSION_SET_PERMISSION: return this.#sessionSetPermission(frame.p);
5912
6258
  case METHOD_SESSION_MODELS: return await this.#sessionModels(frame.p);
@@ -5999,7 +6345,7 @@ var BridgeConnection = class {
5999
6345
  ok: true,
6000
6346
  r: {
6001
6347
  proto: 1,
6002
- minor: 21,
6348
+ minor: 22,
6003
6349
  server: SERVER_ID,
6004
6350
  capabilities: this.#servedCapabilities(),
6005
6351
  resume: "snapshot",
@@ -6593,6 +6939,113 @@ var BridgeConnection = class {
6593
6939
  r: call.value
6594
6940
  };
6595
6941
  }
6942
+ /**
6943
+ * Answer `session.attachment.path`: the bytes of one image a session already
6944
+ * offloaded, addressed by the absolute path that session's own transcript names.
6945
+ *
6946
+ * The whitelist is the whole authorization and it lives in
6947
+ * `core/attachment-paths.ts`: this method serves a path only when the named
6948
+ * session's own durable store named it, and the store is read here on every call,
6949
+ * for the reason `session.attachment` keeps no cache either — an image can be
6950
+ * offloaded after the fact.
6951
+ *
6952
+ * The store is the one `session.history.deep` walks, so this read passes the
6953
+ * same fence: a delegated child whose parent this connection may not read is
6954
+ * refused before any store call. A session this host does not have answers
6955
+ * `unknown-session`: the harness's own name for that fact is
6956
+ * `session/not-found` on the store and a `null` projections answer, and
6957
+ * both are folded into this method's own code here rather than crossing as two
6958
+ * different failures.
6959
+ *
6960
+ * The budget is measured on the ENCODED answer, exactly as `session.attachment`
6961
+ * measures its own: a frame that cannot cross is reported as `frame-too-large`
6962
+ * rather than truncated into half an image.
6963
+ * @param payload - `{sessionId, path}`.
6964
+ * @param id - the request id the frame budget is measured against.
6965
+ */
6966
+ async #sessionAttachmentPath(payload, id) {
6967
+ const sessionId = stringArg(payload, "sessionId");
6968
+ const path = stringArg(payload, "path");
6969
+ if (sessionId === void 0 || path === void 0) return refusal(CODE_INVALID_ARGS, "session.attachment.path requires sessionId and path");
6970
+ if (!isAbsolute(path)) return refusal(CODE_INVALID_ARGS, `session.attachment.path requires an absolute path, got ${path}`);
6971
+ const whitelist = await this.#sessionAttachmentPaths(sessionId);
6972
+ if (!whitelist.ok) return whitelist;
6973
+ const facts = whitelist.facts.get(path);
6974
+ if (facts === void 0) return refusal(CODE_PATH_NOT_IN_SESSION, `${path} is not an image session ${sessionId} offloaded`);
6975
+ const read = await readAttachment(facts);
6976
+ if (!read.ok) return refusal(read.code, read.msg);
6977
+ const answer = {
6978
+ image: read.image,
6979
+ data: read.data
6980
+ };
6981
+ if (Buffer.byteLength(JSON.stringify(responseFrame(id, answer)), "utf8") > 10485760) return refusal(FRAME_TOO_LARGE, `${path} needs more than one ${MAX_FRAME_BYTES} byte frame once encoded`);
6982
+ return {
6983
+ ok: true,
6984
+ r: answer
6985
+ };
6986
+ }
6987
+ /**
6988
+ * The images one session's own durable store names.
6989
+ *
6990
+ * The store is paged backwards to its oldest entry, exactly as
6991
+ * `session.history.deep` pages it: a whitelist cut at one page would forget an
6992
+ * image the session offloaded a month ago. Each page is folded into the map and
6993
+ * dropped, so a long session costs memory in proportion to the images it named
6994
+ * rather than to its whole log.
6995
+ * @param sessionId - the session whose transcript is read; no path of this read
6996
+ * ever comes from the client.
6997
+ * @returns the whitelist keyed by path, or the refusal the read produced.
6998
+ */
6999
+ async #sessionAttachmentPaths(sessionId) {
7000
+ const unfollowable = await this.#unfollowable(sessionId);
7001
+ if (unfollowable !== void 0) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable);
7002
+ const projections = await this.#unary("session", "projections", { sessionId });
7003
+ if (!projections.ok) return projections;
7004
+ const cut = isRecord(projections.value) ? projections.value.asOfSeq : void 0;
7005
+ if (typeof cut !== "number" || !Number.isSafeInteger(cut) || cut < -1) return projections.value === null ? refusal(CODE_UNKNOWN_SESSION, `session ${sessionId} does not exist on this host`) : refusal(CODE_SNAPSHOT_UNAVAILABLE, `session ${sessionId} reported no durable cut to read its images from`);
7006
+ const remembered = this.#attachmentWhitelists.get(sessionId);
7007
+ if (remembered !== void 0 && remembered.asOfSeq === cut) {
7008
+ this.#rememberAttachmentWhitelist(sessionId, cut, remembered.facts);
7009
+ return {
7010
+ ok: true,
7011
+ facts: remembered.facts
7012
+ };
7013
+ }
7014
+ const facts = /* @__PURE__ */ new Map();
7015
+ let before;
7016
+ for (;;) {
7017
+ const store = await this.#storePageOf(sessionId, cut, before);
7018
+ if (!store.ok) return store.code === "session/not-found" ? refusal(CODE_UNKNOWN_SESSION, `session ${sessionId} does not exist on this host`) : store;
7019
+ for (const [named, entry] of attachmentPathsOf(store.records)) facts.set(named, entry);
7020
+ const oldest = oldestSeqOf(store.records);
7021
+ if (!store.hasMore || oldest === void 0 || before !== void 0 && oldest >= before) break;
7022
+ before = oldest;
7023
+ }
7024
+ this.#rememberAttachmentWhitelist(sessionId, cut, facts);
7025
+ return {
7026
+ ok: true,
7027
+ facts
7028
+ };
7029
+ }
7030
+ /**
7031
+ * Keep one session's whitelist, evicting the least recently used one past the
7032
+ * bound.
7033
+ *
7034
+ * A hit moves its session to the back, so what is evicted is the entry no
7035
+ * request has needed for longest rather than the one that arrived first.
7036
+ */
7037
+ #rememberAttachmentWhitelist(sessionId, asOfSeq, facts) {
7038
+ this.#attachmentWhitelists.delete(sessionId);
7039
+ this.#attachmentWhitelists.set(sessionId, {
7040
+ asOfSeq,
7041
+ facts
7042
+ });
7043
+ while (this.#attachmentWhitelists.size > 4) {
7044
+ const oldest = this.#attachmentWhitelists.keys().next().value;
7045
+ if (oldest === void 0) break;
7046
+ this.#attachmentWhitelists.delete(oldest);
7047
+ }
7048
+ }
6596
7049
  /** Answer `session.permissions` out of the host's own preset service. */
6597
7050
  #sessionPermissions(payload) {
6598
7051
  const sessionId = stringArg(payload, "sessionId");
@@ -11465,7 +11918,7 @@ function makePairTokenRoute(deps) {
11465
11918
  };
11466
11919
  }
11467
11920
  //#endregion
11468
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
11921
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
11469
11922
  /** The one Remote failure class shared by owners, the Gateway, and consumers. */
11470
11923
  /**
11471
11924
  * One Remote call failure: a real Error carrying its stable code and typed
@@ -11647,7 +12100,7 @@ function validateName(subject, value) {
11647
12100
  if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
11648
12101
  }
11649
12102
  //#endregion
11650
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
12103
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
11651
12104
  /**
11652
12105
  * Lazily scanned view of one JSON object's top-level fields, built from text
11653
12106
  * that may still be streaming or from an already parsed object. Nothing is
@@ -13353,23 +13806,15 @@ defineMethod("transform", [
13353
13806
  "preserve"
13354
13807
  ], ({ inner }, isInner) => inner.toString(isInner));
13355
13808
  //#endregion
13356
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
13809
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
13357
13810
  /** Largest delay Node schedules without clamping it to one millisecond. */
13358
13811
  const MAX_TIMER_DELAY_MS = 2147483647;
13359
13812
  //#endregion
13360
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-llm/lib/index.js
13361
- /**
13362
- * Detach and deep-freeze a message whose identity already exists.
13363
- * @param message - complete message, including its stable identity.
13364
- * @returns an immutable snapshot that preserves the identity.
13365
- */
13366
- function freezeMessage(message) {
13367
- return deepFreeze(structuredClone(message));
13368
- }
13813
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-error@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-error/lib/index.js
13369
13814
  /**
13370
13815
  * Harness error base with a stable machine-routable code and chained cause.
13371
13816
  * Package errors extend it so tool results and replay can retain failure class.
13372
- * @module @deepseek-ai/dsh-llm/error
13817
+ * @module @deepseek-ai/dsh-error
13373
13818
  */
13374
13819
  /**
13375
13820
  * Base class for all harness errors. Carries a `code` (stable, programmatic —
@@ -13386,6 +13831,83 @@ var HarnessError = class extends Error {
13386
13831
  this.name = new.target.name;
13387
13832
  }
13388
13833
  };
13834
+ //#endregion
13835
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-error@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_/node_modules/@deepseek-ai/dsh-llm/lib/index.js
13836
+ /**
13837
+ * Detach and deep-freeze a message whose identity already exists.
13838
+ * @param message - complete message, including its stable identity.
13839
+ * @returns an immutable snapshot that preserves the identity.
13840
+ */
13841
+ function freezeMessage(message) {
13842
+ return deepFreeze(structuredClone(message));
13843
+ }
13844
+ /**
13845
+ * LLM failure codes and helpers over the shared Harness error base. The base
13846
+ * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
13847
+ * import paths name the same class.
13848
+ * @module @deepseek-ai/dsh-llm/error
13849
+ */
13850
+ /**
13851
+ * Every failure code the built-in providers and the LLM runtime raise. An entry
13852
+ * marked `retryChoice` is offered as a choice for a provider retry policy's
13853
+ * `retryableCodes`; being a choice does not make a code retried by default.
13854
+ */
13855
+ const LLM_FAILURE_CODES = {
13856
+ ABORTED: {},
13857
+ ACCOUNT_QUOTA: {},
13858
+ ACCOUNT_SIGN_IN_REQUIRED: {},
13859
+ ACCOUNT_TOKEN_INVALID: {},
13860
+ AUTH: {},
13861
+ CLIENT_UPGRADE_REQUIRED: {},
13862
+ CONTEXT_WINDOW_EXCEEDED: {},
13863
+ DISCOVERY_FAILED: {},
13864
+ DISCOVERY_UNSUPPORTED: {},
13865
+ DUPLICATE_ADAPTER: {},
13866
+ DUPLICATE_DIRECTORY: {},
13867
+ DUPLICATE_DISCOVERY: {},
13868
+ EMPTY_RESPONSE: { retryChoice: true },
13869
+ FILES_API: {},
13870
+ IMAGE_OFFLOAD_REQUIRED: {},
13871
+ INVALID_ADAPTER: {},
13872
+ INVALID_CATALOG: {},
13873
+ INVALID_CONFIG: {},
13874
+ INVALID_CREDENTIAL: {},
13875
+ INVALID_DIRECTORY: {},
13876
+ INVALID_DISCOVERY: {},
13877
+ INVALID_MODEL_CONTEXT: {},
13878
+ INVALID_MODEL_INFO: {},
13879
+ INVALID_MODEL_MAX_TOKENS: {},
13880
+ INVALID_MODEL_REASONING: {},
13881
+ INVALID_PREPARED_CALL: {},
13882
+ INVALID_REPLAY_STATE: {},
13883
+ INVALID_REQUEST: {},
13884
+ INVALID_RESPONSE: {},
13885
+ MALFORMED_RESPONSE: { retryChoice: true },
13886
+ MISSING_CREDENTIAL: {},
13887
+ MODEL_SWITCH_COMPACTION_FAILED: {},
13888
+ MODEL_UNSUPPORTED: {},
13889
+ NO_ADAPTER: {},
13890
+ NO_CREDENTIAL_STORE: {},
13891
+ NO_DISCOVERY: {},
13892
+ PI_AI_ERROR: {},
13893
+ QUOTA: { retryChoice: true },
13894
+ RATE_LIMIT: { retryChoice: true },
13895
+ REGISTRATION_DISPOSED: {},
13896
+ REQUEST_EXTENSION: {},
13897
+ REQUEST_HEADERS: {},
13898
+ SERVER: { retryChoice: true },
13899
+ STREAM_CLOSED: { retryChoice: true },
13900
+ TIMEOUT: { retryChoice: true },
13901
+ TRANSPORT: { retryChoice: true },
13902
+ UNKNOWN: {},
13903
+ UNKNOWN_MODEL: {},
13904
+ UNSTORABLE_PROVIDER_ID: {},
13905
+ UNSUPPORTED_CONTENT: {},
13906
+ UNSUPPORTED_OPTION: {},
13907
+ UNSUPPORTED_REASONING_EFFORT: {}
13908
+ };
13909
+ /** The {@link LLM_FAILURE_CODES} entries marked as retry-policy choices, in definition order. */
13910
+ const RETRY_CODE_CHOICES = Object.freeze(Object.keys(LLM_FAILURE_CODES).filter((code) => "retryChoice" in LLM_FAILURE_CODES[code]));
13389
13911
  /**
13390
13912
  * Canonical provider-neutral code for a response that completed normally but
13391
13913
  * carried no content blocks at all. Providers occasionally emit a degenerate
@@ -13419,14 +13941,14 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
13419
13941
  "TRANSPORT"
13420
13942
  ]);
13421
13943
  const backoffSchema = Schema.object({
13422
- initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
13423
- maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
13944
+ initialDelayMs: Schema.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
13945
+ maxDelayMs: Schema.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
13424
13946
  jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
13425
13947
  });
13426
13948
  const normalPolicySchema = Schema.object({
13427
13949
  mode: Schema.const("normal").required(),
13428
13950
  maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
13429
- retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
13951
+ retryableCodes: Schema.array(Schema.union([...RETRY_CODE_CHOICES.map((code) => Schema.const(code)), Schema.string().min(1)])).min(1).default([...DEFAULT_RETRYABLE_CODES]),
13430
13952
  backoff: backoffSchema
13431
13953
  });
13432
13954
  const alwaysPolicySchema = Schema.object({
@@ -13704,27 +14226,47 @@ function withoutDeveloperMessages(messages) {
13704
14226
  const retained = messages.filter((message) => message.role !== "developer");
13705
14227
  return retained.length === messages.length ? messages : retained;
13706
14228
  }
13707
- function toolDeclarations(tools, mode, history) {
14229
+ function toolDeclarations(history) {
13708
14230
  const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
13709
14231
  for (const update of history.updates) for (const tool of update.additions) if (!declarations.has(tool.name)) declarations.set(tool.name, {
13710
14232
  ...tool,
13711
14233
  deferLoading: true
13712
14234
  });
13713
- switch (mode) {
13714
- case "in-history": return declarations;
13715
- case "addition-only": {
13716
- const activeNames = new Set(tools?.map((tool) => tool.name));
13717
- for (const name of declarations.keys()) if (!activeNames.has(name)) declarations.delete(name);
13718
- return declarations;
13719
- }
13720
- /* v8 ignore next 2 -- closed-union exhaustiveness guard */
13721
- default: return assertNever$1(mode);
13722
- }
14235
+ return declarations;
14236
+ }
14237
+ /** Rebuild declarations on removals or additions to an empty set, where the request prefix changes. */
14238
+ function rebaseAdditionOnlyHistory(history, messages) {
14239
+ const available = new Map(history.tools.map((tool) => [tool.name, tool]));
14240
+ let baseline = history.tools;
14241
+ let retainedFrom = 0;
14242
+ for (const [index, update] of history.updates.entries()) {
14243
+ const additions = new Map(update.additions.map((tool) => [tool.name, tool]));
14244
+ let reset = available.size === 0 && additions.size > 0;
14245
+ for (const block of messages.get(update.messageId)) if (block.type === "tool-addition") {
14246
+ const { deferLoading: _loading, ...tool } = additions.get(block.toolName);
14247
+ available.set(tool.name, tool);
14248
+ } else if (block.type === "tool-removal") {
14249
+ reset = true;
14250
+ available.delete(block.toolName);
14251
+ }
14252
+ if (reset) {
14253
+ baseline = [...available.values()];
14254
+ retainedFrom = index + 1;
14255
+ }
14256
+ }
14257
+ return retainedFrom === 0 ? history : {
14258
+ tools: baseline,
14259
+ updates: history.updates.slice(retainedFrom)
14260
+ };
13723
14261
  }
13724
14262
  /**
13725
14263
  * Construct provider declarations from session-folded history without changing logged active tools.
13726
14264
  * Unsupported routes and incomplete history use current declarations without developer updates.
13727
- * Explicitly deferred baseline tools become available only after their first retained addition.
14265
+ * Explicitly deferred declarations require an addition to activate them.
14266
+ * A rebuild makes previously activated declarations immediate; unactivated declarations stay deferred.
14267
+ * Addition-only routes rebuild when a tool is removed or tools are added to an empty set;
14268
+ * deferred declarations count as existing tools.
14269
+ * Later additions remain deferred and superseded tool blocks are omitted without dropping other content.
13728
14270
  * @param messages - complete request inputs, or the prefix selected for an auxiliary call.
13729
14271
  * @param tools - currently active tool schemas.
13730
14272
  * @param toolUpdate - the resolved route's update mode.
@@ -13744,14 +14286,16 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
13744
14286
  messages: withoutDeveloperMessages(messages),
13745
14287
  tools
13746
14288
  };
13747
- const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
13748
- if (history.updates.some((update) => !messageIds.has(update.messageId))) return {
14289
+ const updates = new Map(messages.flatMap((message) => message.role === "developer" ? [[message.id, message.content]] : []));
14290
+ if (history.updates.some((update) => !updates.has(update.messageId))) return {
13749
14291
  messages: withoutDeveloperMessages(messages),
13750
14292
  tools
13751
14293
  };
13752
- const declarations = toolDeclarations(tools, toolUpdate, history);
14294
+ const projectedHistory = toolUpdate === "addition-only" ? rebaseAdditionOnlyHistory(history, updates) : history;
14295
+ const declarations = toolDeclarations(projectedHistory);
13753
14296
  const updateIds = new Set(history.updates.map((update) => update.messageId));
13754
- const offered = new Set(history.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
14297
+ const retainedUpdateIds = new Set(projectedHistory.updates.map((update) => update.messageId));
14298
+ const offered = new Set(projectedHistory.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
13755
14299
  const projectedMessages = [];
13756
14300
  for (const message of messages) {
13757
14301
  if (message.role !== "developer") {
@@ -13762,6 +14306,7 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
13762
14306
  const content = message.content.filter((block) => {
13763
14307
  switch (block.type) {
13764
14308
  case "tool-addition":
14309
+ if (!retainedUpdateIds.has(message.id)) return false;
13765
14310
  if (!declarations.has(block.toolName) || offered.has(block.toolName)) return false;
13766
14311
  offered.add(block.toolName);
13767
14312
  return true;
@@ -13840,13 +14385,16 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
13840
14385
  /**
13841
14386
  * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
13842
14387
  * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
14388
+ * The constructor takes only a {@link BuiltinLlmFailureCode}; a failure from
14389
+ * another provider, whose code may be any string, is re-raised through
14390
+ * {@link LlmError.fromFailure}.
13843
14391
  */
13844
- var LlmError = class extends HarnessError {
14392
+ var LlmError = class LlmError extends HarnessError {
13845
14393
  /** Serializable facts retained beside this live Error. */
13846
14394
  failure;
13847
14395
  /**
13848
14396
  * @param message - non-empty human-readable failure summary.
13849
- * @param code - non-empty stable provider-neutral machine code.
14397
+ * @param code - built-in stable provider-neutral machine code.
13850
14398
  * @param options - optional cause and validated serializable provider facts.
13851
14399
  */
13852
14400
  constructor(message, code, options) {
@@ -13866,6 +14414,18 @@ var LlmError = class extends HarnessError {
13866
14414
  ...options?.offloadImages === void 0 ? {} : { offloadImages: options.offloadImages }
13867
14415
  });
13868
14416
  }
14417
+ /**
14418
+ * Raise an observed failure again with its own code, which any provider may have chosen.
14419
+ * @param failure - the serializable failure, typically from a stream's terminal chunk.
14420
+ * @param options - optional cause.
14421
+ * @returns an error carrying the failure's message, code, and provider facts.
14422
+ */
14423
+ static fromFailure(failure, options) {
14424
+ return new LlmError(failure.message, failure.code, {
14425
+ ...failure,
14426
+ ...options
14427
+ });
14428
+ }
13869
14429
  };
13870
14430
  (() => {
13871
14431
  let _classSuper = TypertRemoteService;
@@ -14541,7 +15101,7 @@ function detachDirectoryEntry(entry) {
14541
15101
  };
14542
15102
  }
14543
15103
  //#endregion
14544
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.1_ae856b2e556350e94bf8d8f84b2f857e/node_modules/@deepseek-ai/dsh-tools/lib/shared-DTdn5dXO.js
15104
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-agent@0.2._d54d331d737d4347e4d7b0f13cb396ba/node_modules/@deepseek-ai/dsh-tools/lib/shared-DGx6D7zk.js
14545
15105
  /** The selected provider is missing or unloaded; another provider must not take its calls. */
14546
15106
  var ToolExecutorUnavailableError = class extends HarnessError {
14547
15107
  constructor() {
@@ -15078,7 +15638,7 @@ var ToolActivationError = class extends HarnessError {
15078
15638
  }
15079
15639
  };
15080
15640
  //#endregion
15081
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-scope/lib/index.js
15641
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-scope/lib/index.js
15082
15642
  /**
15083
15643
  * Shared insertion-ordered storage and effect ownership for scope-aware registries.
15084
15644
  *
@@ -15331,7 +15891,7 @@ function scopeOf(ctx) {
15331
15891
  return ctx[kScope];
15332
15892
  }
15333
15893
  //#endregion
15334
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.1_ae856b2e556350e94bf8d8f84b2f857e/node_modules/@deepseek-ai/dsh-tools/lib/index.js
15894
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-agent@0.2._d54d331d737d4347e4d7b0f13cb396ba/node_modules/@deepseek-ai/dsh-tools/lib/index.js
15335
15895
  /** Unified JSON-value schema DSL, inference, compilation, and tool definition helpers. @module dsh-tools/schema */
15336
15896
  const ANNOTATION_KEYS = [
15337
15897
  "description",
@@ -15967,12 +16527,12 @@ var GuardLayer = class {
15967
16527
  /**
15968
16528
  * Check global and inherited guards after pre-execute policy and approval resolve.
15969
16529
  * @param exec - invocation whose guards are checked before dispatch.
15970
- * @returns the first denial reason, or undefined when no guard denies.
16530
+ * @returns the first denial with its optional structured identity, or undefined when no guard denies.
15971
16531
  */
15972
16532
  checkGuards(exec) {
15973
16533
  for (const layer of [this.guards.global, ...this.guards.chainLayers(exec.agent)]) for (const guard of layer.guards.values()) {
15974
- const reason = guard(exec);
15975
- if (reason !== void 0) return reason;
16534
+ const denial = guard(exec);
16535
+ if (denial !== void 0) return typeof denial === "string" ? { reason: denial } : denial;
15976
16536
  }
15977
16537
  }
15978
16538
  });
@@ -27878,7 +28438,7 @@ var require_negotiator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27878
28438
  Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
27879
28439
  }));
27880
28440
  //#endregion
27881
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-host-webserver@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0_supports-color@7.2.0/node_modules/@deepseek-ai/dsh-host-webserver/lib/index.js
28441
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-host-webserver@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_supports-color@7.2.0/node_modules/@deepseek-ai/dsh-host-webserver/lib/index.js
27882
28442
  var lib_exports = /* @__PURE__ */ __exportAll({
27883
28443
  WebServer: () => WebServer,
27884
28444
  bindUrlHost: () => bindUrlHost,