@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.
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";
@@ -215,6 +215,18 @@ var ApprovalRegistry = class {
215
215
  return this.#settle(id, decision) !== void 0;
216
216
  }
217
217
  /**
218
+ * Release one question the host's own panel answered first.
219
+ *
220
+ * The release is not a decision: the panel's answer travels back through the
221
+ * answerer chain it came from, so the claim only has to stop being pending —
222
+ * which is what also makes a later answer from the phone refuse as unknown
223
+ * instead of settling a question that is already over.
224
+ * @returns whether this call released it; false when the phone already had.
225
+ */
226
+ releaseToHost(id) {
227
+ return this.#settle(id, void 0) === true;
228
+ }
229
+ /**
218
230
  * Withdraw the named questions, delegating each to the next answerer.
219
231
  * @returns how many were still pending.
220
232
  */
@@ -773,6 +785,7 @@ const METHOD_SESSION_HISTORY_DEEP = "session.history.deep";
773
785
  const METHOD_SESSION_PROMPT = "session.prompt";
774
786
  const METHOD_SESSION_INTERRUPT = "session.interrupt";
775
787
  const METHOD_SESSION_ATTACHMENT = "session.attachment";
788
+ const METHOD_SESSION_ATTACHMENT_PATH = "session.attachment.path";
776
789
  const METHOD_SESSION_PERMISSIONS = "session.permissions";
777
790
  const METHOD_SESSION_SET_PERMISSION = "session.setPermission";
778
791
  const METHOD_SESSION_MODELS = "session.models";
@@ -1008,6 +1021,19 @@ const CAP_UI = "ui.v1";
1008
1021
  */
1009
1022
  const CAP_UI_LIST = "ui.list.v1";
1010
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
+ /**
1011
1037
  * 宿主配了第二会合点时,在 `hello` 的 `capabilities` 里公告的能力名。
1012
1038
  *
1013
1039
  * 它是这条通道的全部门槛,而且门槛落在宿主这一侧:一个配了第二会合点的宿主才
@@ -1182,6 +1208,7 @@ const KNOWN_METHODS = /* @__PURE__ */ new Set([
1182
1208
  METHOD_SESSION_PROMPT,
1183
1209
  METHOD_SESSION_INTERRUPT,
1184
1210
  METHOD_SESSION_ATTACHMENT,
1211
+ METHOD_SESSION_ATTACHMENT_PATH,
1185
1212
  METHOD_SESSION_PERMISSIONS,
1186
1213
  METHOD_SESSION_SET_PERMISSION,
1187
1214
  METHOD_SESSION_MODELS,
@@ -1269,6 +1296,23 @@ const CODE_UI_LIST_UNAVAILABLE = "ui-list-unavailable";
1269
1296
  * an unaddressable one, rather than reading it blind.
1270
1297
  */
1271
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";
1272
1316
  const CODE_SNAPSHOT_UNAVAILABLE = "snapshot-unavailable";
1273
1317
  /**
1274
1318
  * This host composes no job registry, so it has no background jobs to publish.
@@ -1347,7 +1391,8 @@ const SERVED_CAPABILITIES = [
1347
1391
  CAP_USAGE,
1348
1392
  CAP_USAGE_STATS,
1349
1393
  CAP_UI,
1350
- CAP_UI_LIST
1394
+ CAP_UI_LIST,
1395
+ CAP_SESSION_ATTACHMENT_PATH
1351
1396
  ];
1352
1397
  /** `server` field of the hello response. */
1353
1398
  const SERVER_ID = "dsh-remote-bridge";
@@ -1867,6 +1912,499 @@ var ModelEffortPreferences = class {
1867
1912
  }
1868
1913
  };
1869
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
1870
2408
  //#region src/core/commands.ts
1871
2409
  /** The draft text one host name completes to: the gesture plus its separator. */
1872
2410
  function lineOf(name) {
@@ -2108,11 +2646,11 @@ const RENDERED_ENTRY_TYPES = /* @__PURE__ */ new Set([
2108
2646
  "tool/result",
2109
2647
  "subagent/catalog"
2110
2648
  ]);
2111
- function isRecord$4(value) {
2649
+ function isRecord$3(value) {
2112
2650
  return typeof value === "object" && value !== null && !Array.isArray(value);
2113
2651
  }
2114
2652
  function stringField(value, key) {
2115
- if (!isRecord$4(value)) return void 0;
2653
+ if (!isRecord$3(value)) return void 0;
2116
2654
  const field = value[key];
2117
2655
  return typeof field === "string" ? field : void 0;
2118
2656
  }
@@ -2188,9 +2726,9 @@ var MessageIndex = class {
2188
2726
  * @returns the child ids the payload names, in the order it names them.
2189
2727
  */
2190
2728
  function spawnedChildIdsOf(data) {
2191
- const message = isRecord$4(data) ? data.message : void 0;
2729
+ const message = isRecord$3(data) ? data.message : void 0;
2192
2730
  const ids = [];
2193
- 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);
2194
2732
  return ids;
2195
2733
  }
2196
2734
  /** The spawn signatures above, as the two patterns that carry a child id. */
@@ -2219,8 +2757,8 @@ function spawnIdsIn(text) {
2219
2757
  function spawnCallEvidence(records) {
2220
2758
  const evidence = /* @__PURE__ */ new Map();
2221
2759
  for (const record of records) {
2222
- const event = isRecord$4(record) ? record.event : void 0;
2223
- 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;
2224
2762
  const callId = toolResultCallIdOf(event.data);
2225
2763
  if (callId === void 0) continue;
2226
2764
  for (const childId of spawnedChildIdsOf(event.data)) evidence.set(childId, callId);
@@ -2229,7 +2767,7 @@ function spawnCallEvidence(records) {
2229
2767
  }
2230
2768
  /** @returns the call id one durable `tool/result` payload belongs to. */
2231
2769
  function toolResultCallIdOf(data) {
2232
- const callId = stringField(isRecord$4(data) ? data.message : void 0, "toolCallId");
2770
+ const callId = stringField(isRecord$3(data) ? data.message : void 0, "toolCallId");
2233
2771
  return callId === void 0 || callId === "" ? void 0 : callId;
2234
2772
  }
2235
2773
  /**
@@ -2276,15 +2814,15 @@ var SpawnCallIndex = class {
2276
2814
  */
2277
2815
  observe(type, data) {
2278
2816
  if (type === "turn/start") {
2279
- this.#turn = numberOf(isRecord$4(data) ? data.turn : void 0);
2817
+ this.#turn = numberOf(isRecord$3(data) ? data.turn : void 0);
2280
2818
  this.#step = void 0;
2281
2819
  this.#calls = [];
2282
2820
  this.#correlated.clear();
2283
2821
  return;
2284
2822
  }
2285
2823
  if (type === "step/start") {
2286
- this.#turn = numberOf(isRecord$4(data) ? data.turn : void 0) ?? this.#turn;
2287
- 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);
2288
2826
  this.#calls = [];
2289
2827
  this.#correlated.clear();
2290
2828
  return;
@@ -2298,8 +2836,8 @@ var SpawnCallIndex = class {
2298
2836
  if (type !== "tool/call") return;
2299
2837
  const callId = stringField(data, "callId");
2300
2838
  if (callId === void 0 || callId === "") return;
2301
- this.#turn = numberOf(isRecord$4(data) ? data.turn : void 0) ?? this.#turn;
2302
- 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;
2303
2841
  this.#calls.push(callId);
2304
2842
  }
2305
2843
  /**
@@ -2326,7 +2864,7 @@ var SpawnCallIndex = class {
2326
2864
  * @returns the cursor and records, or undefined when this frame is not a snapshot.
2327
2865
  */
2328
2866
  function readFollowBaseline(frame) {
2329
- if (!isRecord$4(frame) || frame.type !== "snapshot") return void 0;
2867
+ if (!isRecord$3(frame) || frame.type !== "snapshot") return void 0;
2330
2868
  const cursor = frame.cursor;
2331
2869
  const records = frame.records;
2332
2870
  if (typeof cursor !== "number" || !Array.isArray(records)) return void 0;
@@ -2345,11 +2883,11 @@ function readFollowBaseline(frame) {
2345
2883
  * @param memory - the stream's own correlation state, and which optional kinds it declared.
2346
2884
  */
2347
2885
  function deltaOfFollowFrame(frame, toolCalls, messages, memory = {}) {
2348
- if (!isRecord$4(frame)) return void 0;
2886
+ if (!isRecord$3(frame)) return void 0;
2349
2887
  if (frame.type === "assistant-stream") return deltaOfAssistantStream(frame.frame, toolCalls);
2350
2888
  if (frame.type !== "event") return void 0;
2351
2889
  const event = frame.event;
2352
- if (!isRecord$4(event)) return void 0;
2890
+ if (!isRecord$3(event)) return void 0;
2353
2891
  const type = event.type;
2354
2892
  const data = event.data;
2355
2893
  memory.spawnCalls?.observe(typeof type === "string" ? type : "", data);
@@ -2390,7 +2928,7 @@ function subagentDelta(data, spawnCalls) {
2390
2928
  * report an origin the host never recorded.
2391
2929
  */
2392
2930
  function actorOf(data) {
2393
- return actorOfSource(isRecord$4(data) ? data.source : void 0);
2931
+ return actorOfSource(isRecord$3(data) ? data.source : void 0);
2394
2932
  }
2395
2933
  /**
2396
2934
  * Derive one message's actor from the host's own `source` record, mechanically.
@@ -2426,9 +2964,9 @@ function textField(value, key) {
2426
2964
  return field === void 0 || field === "" ? void 0 : field;
2427
2965
  }
2428
2966
  function deltaOfAssistantStream(frame, toolCalls) {
2429
- if (!isRecord$4(frame) || frame.type !== "chunk") return void 0;
2967
+ if (!isRecord$3(frame) || frame.type !== "chunk") return void 0;
2430
2968
  const chunk = frame.chunk;
2431
- if (!isRecord$4(chunk)) return void 0;
2969
+ if (!isRecord$3(chunk)) return void 0;
2432
2970
  const index = typeof chunk.index === "number" ? chunk.index : 0;
2433
2971
  if (chunk.type === "text-delta" && typeof chunk.text === "string") return {
2434
2972
  kind: "text",
@@ -2453,8 +2991,8 @@ function deltaOfAssistantStream(frame, toolCalls) {
2453
2991
  }
2454
2992
  }
2455
2993
  function toolResultDelta(data) {
2456
- const message = isRecord$4(data) ? data.message : void 0;
2457
- 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;
2458
2996
  const callId = message.toolCallId;
2459
2997
  if (typeof callId !== "string" || callId === "") return void 0;
2460
2998
  return {
@@ -2465,8 +3003,8 @@ function toolResultDelta(data) {
2465
3003
  };
2466
3004
  }
2467
3005
  function turnEndDelta(data) {
2468
- const reason = isRecord$4(data) ? data.reason : void 0;
2469
- 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;
2470
3008
  return {
2471
3009
  kind: "turn-end",
2472
3010
  reason: typeof kind === "string" ? kind : "unknown"
@@ -2496,7 +3034,7 @@ function textOfBlocks(content) {
2496
3034
  if (!Array.isArray(content)) return "";
2497
3035
  const parts = [];
2498
3036
  for (const block of content) {
2499
- if (!isRecord$4(block)) continue;
3037
+ if (!isRecord$3(block)) continue;
2500
3038
  if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
2501
3039
  }
2502
3040
  return parts.join("\n");
@@ -2510,7 +3048,7 @@ function textOfBlocks(content) {
2510
3048
  * and file blocks travel in `attachments`, never inside it.
2511
3049
  */
2512
3050
  function userMessageDelta(data, messages) {
2513
- if (!isRecord$4(data)) return void 0;
3051
+ if (!isRecord$3(data)) return void 0;
2514
3052
  const messageId = stringField(data, "id");
2515
3053
  if (messageId !== void 0) {
2516
3054
  if (messages.has(messageId)) return void 0;
@@ -2537,9 +3075,9 @@ function imageAttachmentsOf(content) {
2537
3075
  if (!Array.isArray(content)) return [];
2538
3076
  const attachments = [];
2539
3077
  for (const block of content) {
2540
- if (!isRecord$4(block) || block.type !== "image") continue;
3078
+ if (!isRecord$3(block) || block.type !== "image") continue;
2541
3079
  const ref = block.attachment;
2542
- if (!isRecord$4(ref)) continue;
3080
+ if (!isRecord$3(ref)) continue;
2543
3081
  const attachmentId = stringField(ref, "attachmentId");
2544
3082
  const mediaType = stringField(ref, "mediaType");
2545
3083
  if (attachmentId === void 0 || mediaType === void 0) continue;
@@ -2559,7 +3097,7 @@ function imageAttachmentsOf(content) {
2559
3097
  * must never record a token count the harness did not report.
2560
3098
  */
2561
3099
  function usageDelta(data) {
2562
- if (!isRecord$4(data)) return void 0;
3100
+ if (!isRecord$3(data)) return void 0;
2563
3101
  const usage = usageOf(data.usage);
2564
3102
  if (usage === void 0) return void 0;
2565
3103
  const turn = numberOf(data.turn);
@@ -2573,7 +3111,7 @@ function usageDelta(data) {
2573
3111
  }
2574
3112
  /** Read one `TokenUsage` verbatim; undefined when its two mandatory counters are not numbers. */
2575
3113
  function usageOf(value) {
2576
- if (!isRecord$4(value)) return void 0;
3114
+ if (!isRecord$3(value)) return void 0;
2577
3115
  const inputTokens = numberOf(value.inputTokens);
2578
3116
  const outputTokens = numberOf(value.outputTokens);
2579
3117
  if (inputTokens === void 0 || outputTokens === void 0) return void 0;
@@ -2629,7 +3167,7 @@ function turnsOfRecords(records) {
2629
3167
  if (entry.type === "turn/end") {
2630
3168
  current.endSeq = entry.seq;
2631
3169
  current.endTime = entry.time;
2632
- 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";
2633
3171
  turns.push(current);
2634
3172
  current = void 0;
2635
3173
  }
@@ -2649,7 +3187,7 @@ function turnsOfRecords(records) {
2649
3187
  * @param spawns - the index holding this session's spawn evidence.
2650
3188
  */
2651
3189
  function catalogEntryWithCall(entry, spawns) {
2652
- if (!isRecord$4(entry.data)) return entry;
3190
+ if (!isRecord$3(entry.data)) return entry;
2653
3191
  const childId = stringField(entry.data, "childId");
2654
3192
  if (childId === void 0 || childId === "") return entry;
2655
3193
  const callId = spawns.spawnCallId(childId);
@@ -2804,8 +3342,8 @@ function groupEntries(items) {
2804
3342
  return page;
2805
3343
  }
2806
3344
  function snapshotEntryOf(record) {
2807
- const event = isRecord$4(record) ? record.event : void 0;
2808
- if (!isRecord$4(event)) return void 0;
3345
+ const event = isRecord$3(record) ? record.event : void 0;
3346
+ if (!isRecord$3(event)) return void 0;
2809
3347
  if (typeof event.type !== "string" || typeof event.seq !== "number") return void 0;
2810
3348
  const actor = event.type === "user/message" ? actorOf(event.data) : void 0;
2811
3349
  return {
@@ -2816,207 +3354,6 @@ function snapshotEntryOf(record) {
2816
3354
  ...actor === void 0 ? {} : { actor }
2817
3355
  };
2818
3356
  }
2819
- //#endregion
2820
- //#region src/core/envelope.ts
2821
- /**
2822
- * Protocol v1 frame envelope: the one JSON-object-per-text-frame codec both
2823
- * ends of the bridge speak. Shapes are frozen by the parent card and are not
2824
- * ours to extend:
2825
- *
2826
- * request {"t":"req","id":<uint>,"m":"<method>","p":{...}}
2827
- * response {"t":"res","id":<uint>,"ok":true,"r":{...}}
2828
- * {"t":"res","id":<uint>,"ok":false,"e":{"code":"<str>","msg":"<str>"}}
2829
- * event {"t":"ev","seq":<uint>,"m":"<topic>","p":{...}}
2830
- * heartbeat {"t":"ping","ts":<ms>} / {"t":"pong","ts":<ms>}
2831
- *
2832
- * Decisions this module owns (not restated by the frozen design):
2833
- * - the 10 MiB cap is measured in UTF-8 bytes of the received text, before
2834
- * parsing, so an oversized frame never allocates a parsed object graph;
2835
- * - direction violations (a `res` or `ev` arriving FROM the client) are their
2836
- * own failure code instead of `malformed`, because "the peer is speaking the
2837
- * wrong half of the protocol" is an actionable diagnostic;
2838
- * - a frame whose identity cannot be recovered is answered with the reserved
2839
- * id 0, since the envelope has no way to decline answering.
2840
- * @module dsh-remote-bridge/core/envelope
2841
- */
2842
- /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
2843
- const MAX_FRAME_BYTES = 10 * 1024 * 1024;
2844
- /** Failure codes the codec itself raises. */
2845
- const FRAME_TOO_LARGE = "frame-too-large";
2846
- const MALFORMED_FRAME = "malformed";
2847
- const DIRECTION_VIOLATION = "direction-violation";
2848
- function isRecord$3(value) {
2849
- return typeof value === "object" && value !== null && !Array.isArray(value);
2850
- }
2851
- /** An envelope id is a non-negative safe integer. */
2852
- function isFrameId(value) {
2853
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2854
- }
2855
- /**
2856
- * Decode one received text frame.
2857
- * @param text - the frame body exactly as it crossed the wire.
2858
- * @returns the frame, or the refusal to answer with.
2859
- */
2860
- function decodeClientFrame(text) {
2861
- if (Buffer.byteLength(text, "utf8") > 10485760) return {
2862
- ok: false,
2863
- id: 0,
2864
- code: FRAME_TOO_LARGE,
2865
- msg: `frame exceeds ${MAX_FRAME_BYTES} bytes`
2866
- };
2867
- let parsed;
2868
- try {
2869
- parsed = JSON.parse(text);
2870
- } catch {
2871
- return {
2872
- ok: false,
2873
- id: 0,
2874
- code: MALFORMED_FRAME,
2875
- msg: "frame is not JSON"
2876
- };
2877
- }
2878
- if (!isRecord$3(parsed)) return {
2879
- ok: false,
2880
- id: 0,
2881
- code: MALFORMED_FRAME,
2882
- msg: "frame is not a JSON object"
2883
- };
2884
- const kind = parsed.t;
2885
- if (kind === "ping" || kind === "pong") {
2886
- if (typeof parsed.ts !== "number" || !Number.isFinite(parsed.ts)) return {
2887
- ok: false,
2888
- id: 0,
2889
- code: MALFORMED_FRAME,
2890
- msg: `${kind} requires a numeric ts`
2891
- };
2892
- return {
2893
- ok: true,
2894
- frame: {
2895
- t: kind,
2896
- ts: parsed.ts
2897
- }
2898
- };
2899
- }
2900
- if (kind === "res" || kind === "ev") return {
2901
- ok: false,
2902
- id: isFrameId(parsed.id) ? parsed.id : 0,
2903
- code: DIRECTION_VIOLATION,
2904
- msg: `a client must not send a ${kind} frame`
2905
- };
2906
- if (kind !== "req") return {
2907
- ok: false,
2908
- id: 0,
2909
- code: MALFORMED_FRAME,
2910
- msg: "frame has no known t discriminator"
2911
- };
2912
- if (!isFrameId(parsed.id)) return {
2913
- ok: false,
2914
- id: 0,
2915
- code: MALFORMED_FRAME,
2916
- msg: "req requires a non-negative integer id"
2917
- };
2918
- if (typeof parsed.m !== "string" || parsed.m === "") return {
2919
- ok: false,
2920
- id: parsed.id,
2921
- code: MALFORMED_FRAME,
2922
- msg: "req requires a method name"
2923
- };
2924
- if (parsed.p !== void 0 && !isRecord$3(parsed.p)) return {
2925
- ok: false,
2926
- id: parsed.id,
2927
- code: MALFORMED_FRAME,
2928
- msg: "req payload must be a JSON object"
2929
- };
2930
- return {
2931
- ok: true,
2932
- frame: {
2933
- t: "req",
2934
- id: parsed.id,
2935
- m: parsed.m,
2936
- p: parsed.p ?? {}
2937
- }
2938
- };
2939
- }
2940
- /** Encode one outgoing frame. */
2941
- function encodeFrame(frame) {
2942
- return JSON.stringify(frame);
2943
- }
2944
- /**
2945
- * Decide the wire form of one encoded frame.
2946
- *
2947
- * The decision is a byte-level question only, asked after the frame has been
2948
- * measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
2949
- * stands, so a peer that inflates gets back the frame the text path would have
2950
- * written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
2951
- * does not shrink (zlib's default level), both stay text — a binary frame that
2952
- * is larger than the text it replaces would pay for itself in neither direction.
2953
- * @param text - the frame as {@link encodeFrame} produced it.
2954
- * @param compress - whether the peer declared the capability that permits this.
2955
- * @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
2956
- * a caller injects one. Real deflate shrinks every frame that reaches the
2957
- * threshold, so an injected compressor is the only way to exercise the no-gain
2958
- * rule with content that truly cannot be compressed.
2959
- * @returns the text, or raw DEFLATE of it.
2960
- */
2961
- function outboundPayloadOf(text, compress, deflate = deflateRawSync) {
2962
- if (!compress) return {
2963
- binary: false,
2964
- text
2965
- };
2966
- const source = Buffer.from(text, "utf8");
2967
- if (source.length < 1024) return {
2968
- binary: false,
2969
- text
2970
- };
2971
- const deflated = deflate(source);
2972
- if (deflated.length >= source.length) return {
2973
- binary: false,
2974
- text
2975
- };
2976
- return {
2977
- binary: true,
2978
- deflated
2979
- };
2980
- }
2981
- /** One successful response frame. */
2982
- function responseFrame(id, result) {
2983
- return {
2984
- t: "res",
2985
- id,
2986
- ok: true,
2987
- r: result
2988
- };
2989
- }
2990
- /** One failed response frame. */
2991
- function errorFrame(id, code, msg) {
2992
- return {
2993
- t: "res",
2994
- id,
2995
- ok: false,
2996
- e: {
2997
- code,
2998
- msg
2999
- }
3000
- };
3001
- }
3002
- /**
3003
- * Per-connection event sequence. The frozen design gives each connection its
3004
- * own counter starting at 1; it is deliberately NOT the DSH session cursor
3005
- * (§3.4), so the two numbers are never compared.
3006
- */
3007
- var EventSequence = class {
3008
- #next = 1;
3009
- /** @returns the next sequence number, advancing the counter. */
3010
- take() {
3011
- const value = this.#next;
3012
- this.#next += 1;
3013
- return value;
3014
- }
3015
- /** @returns the value {@link take} will return next, without advancing. */
3016
- peek() {
3017
- return this.#next;
3018
- }
3019
- };
3020
3357
  /** The only deep-link form this channel emits. */
3021
3358
  const PUSH_DEEP_LINK_PREFIX = "whale://session/";
3022
3359
  /**
@@ -5693,6 +6030,26 @@ var BridgeConnection = class {
5693
6030
  #receipts = /* @__PURE__ */ new Set();
5694
6031
  #toolCalls = new ToolCallIndex();
5695
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();
5696
6053
  #capabilities = /* @__PURE__ */ new Set();
5697
6054
  /** Delegated children this connection has learned the durable parent of, by child id. */
5698
6055
  #lineage = /* @__PURE__ */ new Map();
@@ -5895,6 +6252,7 @@ var BridgeConnection = class {
5895
6252
  case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p);
5896
6253
  case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p);
5897
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);
5898
6256
  case METHOD_SESSION_PERMISSIONS: return this.#sessionPermissions(frame.p);
5899
6257
  case METHOD_SESSION_SET_PERMISSION: return this.#sessionSetPermission(frame.p);
5900
6258
  case METHOD_SESSION_MODELS: return await this.#sessionModels(frame.p);
@@ -5987,7 +6345,7 @@ var BridgeConnection = class {
5987
6345
  ok: true,
5988
6346
  r: {
5989
6347
  proto: 1,
5990
- minor: 21,
6348
+ minor: 22,
5991
6349
  server: SERVER_ID,
5992
6350
  capabilities: this.#servedCapabilities(),
5993
6351
  resume: "snapshot",
@@ -6581,6 +6939,113 @@ var BridgeConnection = class {
6581
6939
  r: call.value
6582
6940
  };
6583
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
+ }
6584
7049
  /** Answer `session.permissions` out of the host's own preset service. */
6585
7050
  #sessionPermissions(payload) {
6586
7051
  const sessionId = stringArg(payload, "sessionId");
@@ -8105,6 +8570,19 @@ var QuestionClaims = class {
8105
8570
  resolveDeadline(void 0);
8106
8571
  }
8107
8572
  };
8573
+ /**
8574
+ * Hand this claim to the host's own answerers, once.
8575
+ *
8576
+ * Both surfaces are shown the question and the first answer settles it: an
8577
+ * answer from the chain ends the claim here, and an answer from the phone
8578
+ * ends it in {@link answer} — which leaves the chain's later answer ignored
8579
+ * instead of settling or broadcasting a second time.
8580
+ */
8581
+ const startHostChain = () => {
8582
+ startNext().then((answer) => {
8583
+ this.#settleFromHost(input.callId, answer);
8584
+ }, () => void 0);
8585
+ };
8108
8586
  this.#claims.set(input.callId, record);
8109
8587
  if (signal?.aborted === true) onAbort();
8110
8588
  else signal?.addEventListener("abort", onAbort, { once: true });
@@ -8113,7 +8591,8 @@ var QuestionClaims = class {
8113
8591
  return {
8114
8592
  ...viewOf(record),
8115
8593
  answer,
8116
- deadline
8594
+ deadline,
8595
+ startHostChain
8117
8596
  };
8118
8597
  }
8119
8598
  /**
@@ -8232,6 +8711,26 @@ var QuestionClaims = class {
8232
8711
  }
8233
8712
  }
8234
8713
  /**
8714
+ * Settle one claim from the host's own answerer chain.
8715
+ *
8716
+ * Only a claim this bridge still holds can be ended this way: a phone that
8717
+ * answered first deletes it, and the chain's late answer must not settle it a
8718
+ * second time or announce a card that is already gone. A claim the host's own
8719
+ * deadline turned into `continued` is left alone as well — its answer promise
8720
+ * is that deadline, and the phone's late answer still has its own road.
8721
+ * @param callId - the claim the host answered.
8722
+ * @param answer - the host's own answer.
8723
+ */
8724
+ #settleFromHost(callId, answer) {
8725
+ const record = this.#claims.get(callId);
8726
+ if (record === void 0 || record.state !== "open") return;
8727
+ this.#claims.delete(callId);
8728
+ record.detach();
8729
+ record.stopWait();
8730
+ record.notifySettled();
8731
+ record.settle(answer);
8732
+ }
8733
+ /**
8235
8734
  * Settle one open claim from the host's own cancellation lifetime.
8236
8735
  *
8237
8736
  * The reason is propagated verbatim, so the host's deadline still maps to its
@@ -8261,17 +8760,22 @@ function approvalSummary(request) {
8261
8760
  /**
8262
8761
  * The `approval.request` payload for one claim.
8263
8762
  *
8264
- * The first broadcast and the replay of a still-open claim go through this one
8265
- * function, so the card a phone was originally shown and the same card handed to
8266
- * it again after a reconnect cannot drift apart.
8763
+ * The first broadcast, the replay of a still-open claim and the notice that the
8764
+ * host's own panel answered it all go through this one function, so the card a
8765
+ * phone was originally shown and the same card handed to it again after a
8766
+ * reconnect cannot drift apart. `state` is published only when it is not the
8767
+ * default, so every frame that existed before it is byte for byte what it was.
8267
8768
  * @param prompt - the claim being published.
8769
+ * @param state - `open` for a question a phone can answer, `settled` for the
8770
+ * notice that the host's own panel answered it first.
8268
8771
  */
8269
- function approvalPayload(prompt) {
8772
+ function approvalPayload(prompt, state = "open") {
8270
8773
  return {
8271
8774
  sessionId: prompt.sessionId,
8272
8775
  id: prompt.id,
8273
8776
  summary: prompt.summary,
8274
- toolName: prompt.toolName
8777
+ toolName: prompt.toolName,
8778
+ ...state === "open" ? {} : { state }
8275
8779
  };
8276
8780
  }
8277
8781
  /**
@@ -8288,20 +8792,6 @@ function approvalPayload(prompt) {
8288
8792
  * expiry exactly as it was before.
8289
8793
  */
8290
8794
  const QUESTION_CLAIM_GRACE_MS = 6e4;
8291
- /**
8292
- * How long a user question is held for a phone this bridge reached by
8293
- * notification only, in milliseconds (§32.2).
8294
- *
8295
- * Inside this window the question exists only on the phone's side: the alert is
8296
- * out, no socket has it, and the host's own answerer chain has not been started.
8297
- * When it runs out the claim is withdrawn and delegated, so the agent behind a
8298
- * timed ask waits at most this long past its own deadline and the agent behind a
8299
- * blocking ask (no call id, no deadline) waits at most this long in total — an
8300
- * accepted cost, because the alternative is a question that vanished while the
8301
- * phone was asleep. The window is the bridge's own constant and not the host's:
8302
- * a deployment overrides it, the host never sees it.
8303
- */
8304
- const OFFLINE_QUESTION_CLAIM_TTL_MS = 6e5;
8305
8795
  /** The bridge's live connections plus the answerer it composes onto the approval chain. */
8306
8796
  var BridgeHub = class {
8307
8797
  #options;
@@ -8313,16 +8803,6 @@ var BridgeHub = class {
8313
8803
  */
8314
8804
  #questionReleaseTimer;
8315
8805
  /**
8316
- * The offline claims still waiting on a phone, by wire call id, each with the
8317
- * timer that holds it for its window.
8318
- *
8319
- * A question leaves this table the moment the phone takes it over, answers it,
8320
- * or the window releases it, so a call id in here is a question no reachable
8321
- * device has been shown — which is exactly what {@link #reviewOfflineClaims}
8322
- * withdraws when a hello makes that permanent.
8323
- */
8324
- #offlineClaims = /* @__PURE__ */ new Map();
8325
- /**
8326
8806
  * 整页卡(§35)的那一个释放窗口。卡表是全局的,所以一个定时器覆盖每一张卡,
8327
8807
  * 同一时刻只可能有一个;它与 {@link #questionReleaseTimer} 各管各的通道。
8328
8808
  */
@@ -8348,7 +8828,6 @@ var BridgeHub = class {
8348
8828
  this.replayQuestions(fresh);
8349
8829
  this.replayApprovals(fresh);
8350
8830
  this.replayUi(fresh);
8351
- this.#reviewOfflineClaims();
8352
8831
  }
8353
8832
  }, transport, auth);
8354
8833
  this.#connections.add(connection);
@@ -8392,7 +8871,6 @@ var BridgeHub = class {
8392
8871
  */
8393
8872
  replayQuestions(connection) {
8394
8873
  if (!connection.paired || !connection.declares("questions.v1")) return;
8395
- this.#cancelOfflineClaims();
8396
8874
  for (const held of this.#options.questions.listed()) connection.emit(TOPIC_QUESTION_REQUEST, held.payload);
8397
8875
  }
8398
8876
  /**
@@ -8449,9 +8927,14 @@ var BridgeHub = class {
8449
8927
  }
8450
8928
  /**
8451
8929
  * The body of this plugin's `approval/request` listener.
8930
+ *
8931
+ * The claim yields the moment it exists: the host's own panel is offered the
8932
+ * same question, so the phone and the panel hold one card each and the first
8933
+ * answer decides. A panel that answers first ends the phone's claim and the phone
8934
+ * is told; a phone that answers first leaves the panel's later answer ignored.
8452
8935
  * @param request - the pending question.
8453
8936
  * @param next - the rest of the answerer chain.
8454
- * @returns a claimed decision, or whatever the next answerer says.
8937
+ * @returns the first decision, or whatever the next answerer says.
8455
8938
  */
8456
8939
  async approve(request, next) {
8457
8940
  if (this.pairedClients === 0) return await next();
@@ -8464,11 +8947,12 @@ var BridgeHub = class {
8464
8947
  });
8465
8948
  if (this.broadcast("approval.request", approvalPayload(prompt)) === 0) this.#options.approvals.abandon([prompt.id]);
8466
8949
  else {
8467
- this.#options.push?.notify("approval", sessionId);
8950
+ if (!this.#hasLiveClient()) this.#options.push?.notify("approval", sessionId);
8468
8951
  this.#options.liveActivity?.noteApproval(sessionId);
8469
8952
  }
8953
+ const chain = this.#startApprovalChain(prompt, next);
8470
8954
  const answer = await prompt.answer;
8471
- return answer === void 0 ? await next() : answer;
8955
+ return answer === void 0 ? await chain : answer;
8472
8956
  }
8473
8957
  /**
8474
8958
  * The body of this plugin's `user-questions/request` listener.
@@ -8481,9 +8965,11 @@ var BridgeHub = class {
8481
8965
  * host's own when the ask is timed, and minted here when it is blocking and the
8482
8966
  * host assigned none — either way the phone answers the id it was shown. A claim
8483
8967
  * nobody received is withdrawn at once instead of holding the agent until the
8484
- * host's deadline. For a timed ask the host's own remaining wait travels with
8485
- * the first frame as `expiresAt`, and every later move of that deadline is
8486
- * re-published under the same call id.
8968
+ * host's deadline. The host's own answerer chain is entered the instant the
8969
+ * claim exists, in every mode, so the host's panel shows the same question and
8970
+ * the first answer settles both. For a timed ask the host's own remaining wait
8971
+ * travels with the first frame as `expiresAt`, and every later move of that
8972
+ * deadline is re-published under the same call id.
8487
8973
  * @param request - the pending question batch.
8488
8974
  * @param next - the rest of the answerer chain.
8489
8975
  * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
@@ -8515,6 +9001,7 @@ var BridgeHub = class {
8515
9001
  }
8516
9002
  });
8517
9003
  if (claim === void 0) return await next();
9004
+ claim.startHostChain();
8518
9005
  if (mode === "offline") return await this.#holdOfflineClaim(sessionId, callId, claim);
8519
9006
  const expiresAt = await claim.deadline;
8520
9007
  if (this.#options.questions.stateOf(callId) !== "open") return await claim.answer;
@@ -8523,7 +9010,7 @@ var BridgeHub = class {
8523
9010
  expiresAt
8524
9011
  })) === 0) this.#options.questions.withdraw([callId]);
8525
9012
  else {
8526
- this.#options.push?.notify("question", sessionId);
9013
+ if (!this.#hasLiveClient()) this.#options.push?.notify("question", sessionId);
8527
9014
  const first = request.questions[0];
8528
9015
  this.#options.liveActivity?.noteQuestion(sessionId, {
8529
9016
  ...first?.header === void 0 ? {} : { header: first.header },
@@ -8596,7 +9083,6 @@ var BridgeHub = class {
8596
9083
  }
8597
9084
  /** Close every connection and withdraw every question. Idempotent. */
8598
9085
  dispose() {
8599
- this.#releaseOfflineClaims("the bridge unloaded");
8600
9086
  this.#cancelQuestionRelease();
8601
9087
  this.#cancelUiRelease();
8602
9088
  for (const connection of [...this.#connections]) {
@@ -8634,11 +9120,8 @@ var BridgeHub = class {
8634
9120
  /**
8635
9121
  * Which path a user question takes right now (§11.3).
8636
9122
  *
8637
- * The one entry, read twice: when a question arrives, and again when a paired
8638
- * connection finishes its hello while an offline claim is still held. Both
8639
- * moments ask the same thing — can a device that is reachable right now receive
8640
- * a question card — and answering it in two places is how two answers drift
8641
- * apart.
9123
+ * The one judgement behind both deliveries: can a device that is reachable
9124
+ * right now receive a question card, or does the alert have to stand in for it.
8642
9125
  * @returns `online` for the ordinary claim-and-broadcast path, `offline` for a
8643
9126
  * claim held for a phone reached by notification, and `nobody` when the question
8644
9127
  * has to go straight to the next answerer.
@@ -8651,28 +9134,23 @@ var BridgeHub = class {
8651
9134
  return (push.mode === "relay" ? this.#options.roster.relayTargets() : this.#options.roster.pushTargets()).length > 0 ? "offline" : "nobody";
8652
9135
  }
8653
9136
  /**
8654
- * Hold one question for a phone that is not on the wire (§32).
9137
+ * Claim one question for a phone that is not on the wire (§32).
8655
9138
  *
8656
9139
  * No socket is paired, so this claim's own first frame would reach nobody: the
8657
- * notification IS its delivery, and it is sent whether or not a broadcast would
8658
- * have landed. Inside the window the question exists only on the phone's side;
8659
- * the phone that comes back is handed the card by the replay in `onDeclare`,
8660
- * and the phone that answers settles it through the ordinary path.
9140
+ * notification IS its delivery. Nothing is held on the phone's behalf any more —
9141
+ * the host's own chain was offered the same question at claim time — so the
9142
+ * claim lives exactly as long as any other: until the phone answers it, the
9143
+ * host's deadline ends it, or this bridge unloads.
8661
9144
  * @param sessionId - the session that asked.
8662
9145
  * @param callId - the wire id the phone will answer under.
8663
9146
  * @param claim - the claim this bridge just opened.
8664
9147
  * @returns the phone's answer, or whatever the next answerer says.
8665
9148
  */
8666
9149
  async #holdOfflineClaim(sessionId, callId, claim) {
8667
- this.#armOfflineClaim(callId);
8668
- this.#options.push?.notify("question", sessionId, (report) => {
9150
+ if (!this.#hasLiveClient()) this.#options.push?.notify("question", sessionId, (report) => {
8669
9151
  this.#onQuestionPushed(callId, report);
8670
9152
  });
8671
- try {
8672
- return await claim.answer;
8673
- } finally {
8674
- this.#cancelOfflineClaim(callId);
8675
- }
9153
+ return await claim.answer;
8676
9154
  }
8677
9155
  /**
8678
9156
  * Read one alert's delivery report (§32.5).
@@ -8680,9 +9158,8 @@ var BridgeHub = class {
8680
9158
  * Three APNs answers are final about a registration: 410 with `Unregistered`, or
8681
9159
  * `Unregistered`/`BadDeviceToken` on any status. The device is cleaned off the
8682
9160
  * roster, and the claim is kept only while some other registered device is still
8683
- * there to be told; when the last one is gone the question cannot reach a phone
8684
- * at all, so it goes back to the host's chain now instead of at the end of a
8685
- * window nobody is left to use.
9161
+ * there to be told; when the last one is gone the claim is given up, because no
9162
+ * phone can be told this question exists.
8686
9163
  * @param callId - the offline claim this notification was about.
8687
9164
  * @param report - how the announcement ended.
8688
9165
  */
@@ -8692,7 +9169,7 @@ var BridgeHub = class {
8692
9169
  const survivors = (this.#options.push?.mode === "relay" ? this.#options.roster.relayTargets() : this.#options.roster.pushTargets()).filter(({ push }) => !dead.includes(push.deviceToken));
8693
9170
  this.#forgetDeadTokens(dead);
8694
9171
  if (survivors.length > 0) return;
8695
- this.#releaseOfflineClaim(callId, "APNs refused every device token on the roster");
9172
+ this.#releaseUnreachableClaim(callId, "APNs refused every device token on the roster");
8696
9173
  }
8697
9174
  /** Drop each dead registration from the roster, then let the watchers settle. */
8698
9175
  async #forgetDeadTokens(tokens) {
@@ -8705,73 +9182,74 @@ var BridgeHub = class {
8705
9182
  }
8706
9183
  }
8707
9184
  /**
8708
- * End every offline claim the wire has just made unreachable (§11.3).
9185
+ * Give up one claim no phone can be told about any more.
8709
9186
  *
8710
- * A hello that leaves no paired connection able to take a card — the client
8711
- * written before `questions.v1` going online — is the same fact the claim point
8712
- * reads, so it releases the claim at once instead of at the end of its window.
8713
- */
8714
- #reviewOfflineClaims() {
8715
- if (this.#offlineClaims.size === 0) return;
8716
- if (this.#questionMode() === "offline") return;
8717
- this.#releaseOfflineClaims("no paired connection on the wire can receive a question");
8718
- }
8719
- /**
8720
- * Arm the window that holds one offline claim.
8721
- *
8722
- * Deliberately a second timer beside {@link #armQuestionRelease}, never the same
8723
- * one: that window is the reconnect budget of a phone that just left, this one is
8724
- * the whole lifetime of a claim no phone ever had, and one claim can be governed
8725
- * by both in turn. Whichever is due first releases it, and the release is
8726
- * idempotent, so the later one finds no claim.
8727
- * @param callId - the claim to hold.
8728
- */
8729
- #armOfflineClaim(callId) {
8730
- if (this.#offlineClaims.has(callId)) return;
8731
- const ttl = this.#options.offlineClaimTtlMs ?? 6e5;
8732
- const timer = setTimeout(() => {
8733
- this.#releaseOfflineClaim(callId, "the offline claim window ended");
8734
- }, Math.max(0, ttl));
8735
- timer.unref?.();
8736
- this.#offlineClaims.set(callId, timer);
8737
- }
8738
- /** Drop one claim's window. The claim itself keeps whatever state it has. */
8739
- #cancelOfflineClaim(callId) {
8740
- const timer = this.#offlineClaims.get(callId);
8741
- if (timer === void 0) return;
8742
- clearTimeout(timer);
8743
- this.#offlineClaims.delete(callId);
8744
- }
8745
- /** Drop every offline window: a phone is on the wire for those claims now, or they are about to be released. */
8746
- #cancelOfflineClaims() {
8747
- for (const timer of this.#offlineClaims.values()) clearTimeout(timer);
8748
- this.#offlineClaims.clear();
8749
- }
8750
- /**
8751
- * Release one offline claim back to the host's own chain.
8752
- *
8753
- * The one entry every route uses — the window ending, a roster whose tokens are
8754
- * all dead, a hello that left nobody able to receive, the bridge unloading — so
8755
- * "the host's chain is started at most once" is a property of this entry rather
8756
- * than of its callers: `withdraw` deletes the claim before it delegates, and the
8757
- * chain a claim starts is memoized, so a second route releases nothing and starts
8758
- * nothing, and no notification is sent for a question that already left.
9187
+ * The one route for that fact — a roster whose every registered token APNs
9188
+ * refuses — so nobody settles the question twice: `withdraw` deletes the claim
9189
+ * before it hands the question to the chain that was started at claim time, and
9190
+ * the chain is memoized, so a second route releases nothing and announces
9191
+ * nothing.
8759
9192
  * @param callId - the claim to release.
8760
9193
  * @param reason - why, logged once when something really was released.
8761
9194
  */
8762
- #releaseOfflineClaim(callId, reason) {
8763
- this.#cancelOfflineClaim(callId);
9195
+ #releaseUnreachableClaim(callId, reason) {
8764
9196
  if (this.#options.questions.withdraw([callId]) > 0) this.#options.log(`an offline-claimed user question was released: ${reason}`);
8765
9197
  }
8766
- /** Release every offline claim through {@link #releaseOfflineClaim}. */
8767
- #releaseOfflineClaims(reason) {
8768
- for (const callId of [...this.#offlineClaims.keys()]) this.#releaseOfflineClaim(callId, reason);
8769
- }
8770
9198
  /** Abandon every approval: no paired device is left to answer one. */
8771
9199
  #abandonApprovals() {
8772
9200
  const withdrawn = this.#options.approvals.abandonAll();
8773
9201
  if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`);
8774
9202
  }
9203
+ /**
9204
+ * Hand one approval question to the host's own answerers.
9205
+ *
9206
+ * The chain is entered once, at claim time, so the panel is shown the same card
9207
+ * the phone holds. Only a real decision ends the phone's claim: a rejection is
9208
+ * not an answer, and neither is the fail-closed `'unavailable'` the chain returns
9209
+ * when no panel took the question at all — the phone may still answer either way.
9210
+ * @param prompt - the claim the chain is answering for.
9211
+ * @param next - the rest of the answerer chain.
9212
+ * @returns the chain's outcome, rejection included, for the caller that has to
9213
+ * wait on it after the phone stopped being able to answer.
9214
+ */
9215
+ #startApprovalChain(prompt, next) {
9216
+ let chain;
9217
+ try {
9218
+ chain = next();
9219
+ } catch (error) {
9220
+ chain = Promise.reject(error);
9221
+ }
9222
+ chain.then((outcome) => {
9223
+ this.#settleApprovalFromHost(prompt, outcome);
9224
+ }, () => void 0);
9225
+ return chain;
9226
+ }
9227
+ /**
9228
+ * End one claim on the decision the host's own panel gave.
9229
+ *
9230
+ * The release decides, not the outcome alone: a claim the phone already answered
9231
+ * is not pending any more, so its answer stands and nothing is announced a second
9232
+ * time. `'unavailable'` is the chain's fail-closed default rather than a decision
9233
+ * — no panel took the question — and it leaves the claim exactly as it was.
9234
+ * @param prompt - the claim the chain was started for.
9235
+ * @param outcome - what the host's own answerers decided.
9236
+ */
9237
+ #settleApprovalFromHost(prompt, outcome) {
9238
+ if (outcome === "unavailable") return;
9239
+ if (!this.#options.approvals.releaseToHost(prompt.id)) return;
9240
+ this.broadcast(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt, "settled"));
9241
+ }
9242
+ /**
9243
+ * @returns whether a browser client that can answer these waterfalls is on the wire.
9244
+ *
9245
+ * The gateway's own predicate, read through the bridge's structural face. A
9246
+ * notification stands in for that panel, so it is only sent when the panel is not
9247
+ * there; a host without the Web GUI — and a capture-only test context — answers
9248
+ * `false`, which is the state in which the alert has always been the delivery.
9249
+ */
9250
+ #hasLiveClient() {
9251
+ return this.#options.gateway.hasLiveClient?.() === true;
9252
+ }
8775
9253
  /** Release every user question to the next answerer. */
8776
9254
  #releaseQuestions() {
8777
9255
  const released = this.#options.questions.withdrawAll();
@@ -11440,7 +11918,7 @@ function makePairTokenRoute(deps) {
11440
11918
  };
11441
11919
  }
11442
11920
  //#endregion
11443
- //#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
11444
11922
  /** The one Remote failure class shared by owners, the Gateway, and consumers. */
11445
11923
  /**
11446
11924
  * One Remote call failure: a real Error carrying its stable code and typed
@@ -11622,7 +12100,7 @@ function validateName(subject, value) {
11622
12100
  if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
11623
12101
  }
11624
12102
  //#endregion
11625
- //#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
11626
12104
  /**
11627
12105
  * Lazily scanned view of one JSON object's top-level fields, built from text
11628
12106
  * that may still be streaming or from an already parsed object. Nothing is
@@ -13328,23 +13806,15 @@ defineMethod("transform", [
13328
13806
  "preserve"
13329
13807
  ], ({ inner }, isInner) => inner.toString(isInner));
13330
13808
  //#endregion
13331
- //#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
13332
13810
  /** Largest delay Node schedules without clamping it to one millisecond. */
13333
13811
  const MAX_TIMER_DELAY_MS = 2147483647;
13334
13812
  //#endregion
13335
- //#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
13336
- /**
13337
- * Detach and deep-freeze a message whose identity already exists.
13338
- * @param message - complete message, including its stable identity.
13339
- * @returns an immutable snapshot that preserves the identity.
13340
- */
13341
- function freezeMessage(message) {
13342
- return deepFreeze(structuredClone(message));
13343
- }
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
13344
13814
  /**
13345
13815
  * Harness error base with a stable machine-routable code and chained cause.
13346
13816
  * Package errors extend it so tool results and replay can retain failure class.
13347
- * @module @deepseek-ai/dsh-llm/error
13817
+ * @module @deepseek-ai/dsh-error
13348
13818
  */
13349
13819
  /**
13350
13820
  * Base class for all harness errors. Carries a `code` (stable, programmatic —
@@ -13361,6 +13831,83 @@ var HarnessError = class extends Error {
13361
13831
  this.name = new.target.name;
13362
13832
  }
13363
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]));
13364
13911
  /**
13365
13912
  * Canonical provider-neutral code for a response that completed normally but
13366
13913
  * carried no content blocks at all. Providers occasionally emit a degenerate
@@ -13394,14 +13941,14 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
13394
13941
  "TRANSPORT"
13395
13942
  ]);
13396
13943
  const backoffSchema = Schema.object({
13397
- initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
13398
- 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),
13399
13946
  jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
13400
13947
  });
13401
13948
  const normalPolicySchema = Schema.object({
13402
13949
  mode: Schema.const("normal").required(),
13403
13950
  maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
13404
- 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]),
13405
13952
  backoff: backoffSchema
13406
13953
  });
13407
13954
  const alwaysPolicySchema = Schema.object({
@@ -13679,27 +14226,47 @@ function withoutDeveloperMessages(messages) {
13679
14226
  const retained = messages.filter((message) => message.role !== "developer");
13680
14227
  return retained.length === messages.length ? messages : retained;
13681
14228
  }
13682
- function toolDeclarations(tools, mode, history) {
14229
+ function toolDeclarations(history) {
13683
14230
  const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
13684
14231
  for (const update of history.updates) for (const tool of update.additions) if (!declarations.has(tool.name)) declarations.set(tool.name, {
13685
14232
  ...tool,
13686
14233
  deferLoading: true
13687
14234
  });
13688
- switch (mode) {
13689
- case "in-history": return declarations;
13690
- case "addition-only": {
13691
- const activeNames = new Set(tools?.map((tool) => tool.name));
13692
- for (const name of declarations.keys()) if (!activeNames.has(name)) declarations.delete(name);
13693
- return declarations;
13694
- }
13695
- /* v8 ignore next 2 -- closed-union exhaustiveness guard */
13696
- default: return assertNever$1(mode);
13697
- }
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
+ };
13698
14261
  }
13699
14262
  /**
13700
14263
  * Construct provider declarations from session-folded history without changing logged active tools.
13701
14264
  * Unsupported routes and incomplete history use current declarations without developer updates.
13702
- * 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.
13703
14270
  * @param messages - complete request inputs, or the prefix selected for an auxiliary call.
13704
14271
  * @param tools - currently active tool schemas.
13705
14272
  * @param toolUpdate - the resolved route's update mode.
@@ -13719,14 +14286,16 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
13719
14286
  messages: withoutDeveloperMessages(messages),
13720
14287
  tools
13721
14288
  };
13722
- const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
13723
- 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 {
13724
14291
  messages: withoutDeveloperMessages(messages),
13725
14292
  tools
13726
14293
  };
13727
- const declarations = toolDeclarations(tools, toolUpdate, history);
14294
+ const projectedHistory = toolUpdate === "addition-only" ? rebaseAdditionOnlyHistory(history, updates) : history;
14295
+ const declarations = toolDeclarations(projectedHistory);
13728
14296
  const updateIds = new Set(history.updates.map((update) => update.messageId));
13729
- 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));
13730
14299
  const projectedMessages = [];
13731
14300
  for (const message of messages) {
13732
14301
  if (message.role !== "developer") {
@@ -13737,6 +14306,7 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
13737
14306
  const content = message.content.filter((block) => {
13738
14307
  switch (block.type) {
13739
14308
  case "tool-addition":
14309
+ if (!retainedUpdateIds.has(message.id)) return false;
13740
14310
  if (!declarations.has(block.toolName) || offered.has(block.toolName)) return false;
13741
14311
  offered.add(block.toolName);
13742
14312
  return true;
@@ -13815,13 +14385,16 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
13815
14385
  /**
13816
14386
  * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
13817
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}.
13818
14391
  */
13819
- var LlmError = class extends HarnessError {
14392
+ var LlmError = class LlmError extends HarnessError {
13820
14393
  /** Serializable facts retained beside this live Error. */
13821
14394
  failure;
13822
14395
  /**
13823
14396
  * @param message - non-empty human-readable failure summary.
13824
- * @param code - non-empty stable provider-neutral machine code.
14397
+ * @param code - built-in stable provider-neutral machine code.
13825
14398
  * @param options - optional cause and validated serializable provider facts.
13826
14399
  */
13827
14400
  constructor(message, code, options) {
@@ -13841,6 +14414,18 @@ var LlmError = class extends HarnessError {
13841
14414
  ...options?.offloadImages === void 0 ? {} : { offloadImages: options.offloadImages }
13842
14415
  });
13843
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
+ }
13844
14429
  };
13845
14430
  (() => {
13846
14431
  let _classSuper = TypertRemoteService;
@@ -14516,7 +15101,7 @@ function detachDirectoryEntry(entry) {
14516
15101
  };
14517
15102
  }
14518
15103
  //#endregion
14519
- //#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
14520
15105
  /** The selected provider is missing or unloaded; another provider must not take its calls. */
14521
15106
  var ToolExecutorUnavailableError = class extends HarnessError {
14522
15107
  constructor() {
@@ -15053,7 +15638,7 @@ var ToolActivationError = class extends HarnessError {
15053
15638
  }
15054
15639
  };
15055
15640
  //#endregion
15056
- //#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
15057
15642
  /**
15058
15643
  * Shared insertion-ordered storage and effect ownership for scope-aware registries.
15059
15644
  *
@@ -15306,7 +15891,7 @@ function scopeOf(ctx) {
15306
15891
  return ctx[kScope];
15307
15892
  }
15308
15893
  //#endregion
15309
- //#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
15310
15895
  /** Unified JSON-value schema DSL, inference, compilation, and tool definition helpers. @module dsh-tools/schema */
15311
15896
  const ANNOTATION_KEYS = [
15312
15897
  "description",
@@ -15942,12 +16527,12 @@ var GuardLayer = class {
15942
16527
  /**
15943
16528
  * Check global and inherited guards after pre-execute policy and approval resolve.
15944
16529
  * @param exec - invocation whose guards are checked before dispatch.
15945
- * @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.
15946
16531
  */
15947
16532
  checkGuards(exec) {
15948
16533
  for (const layer of [this.guards.global, ...this.guards.chainLayers(exec.agent)]) for (const guard of layer.guards.values()) {
15949
- const reason = guard(exec);
15950
- if (reason !== void 0) return reason;
16534
+ const denial = guard(exec);
16535
+ if (denial !== void 0) return typeof denial === "string" ? { reason: denial } : denial;
15951
16536
  }
15952
16537
  }
15953
16538
  });
@@ -27853,7 +28438,7 @@ var require_negotiator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27853
28438
  Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
27854
28439
  }));
27855
28440
  //#endregion
27856
- //#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
27857
28442
  var lib_exports = /* @__PURE__ */ __exportAll({
27858
28443
  WebServer: () => WebServer,
27859
28444
  bindUrlHost: () => bindUrlHost,
@@ -33299,22 +33884,6 @@ const ROSTER_PATH = "remote-bridge/devices.json";
33299
33884
  * than to any one session, and it outlives every process (core/model-efforts.ts).
33300
33885
  */
33301
33886
  const EFFORT_PATH = "remote-bridge/model-efforts.json";
33302
- /** The environment variable that moves the offline claim window (§32.2). */
33303
- const OFFLINE_CLAIM_TTL_ENV = "DSH_REMOTE_BRIDGE_OFFLINE_CLAIM_TTL_MS";
33304
- /**
33305
- * The offline claim window this process runs with.
33306
- *
33307
- * The window is the bridge's own constant and never a host fact, so a deployment
33308
- * moves it here. A value that is missing, unreadable or not positive falls back to
33309
- * the constant instead of closing the window: a zero window would silently switch
33310
- * the channel off, and an operator who wanted that would be turning off push.
33311
- * @param env - the process environment, injectable for a suite.
33312
- * @returns the window in milliseconds.
33313
- */
33314
- function offlineClaimTtl(env = process.env) {
33315
- const configured = Number(env[OFFLINE_CLAIM_TTL_ENV]);
33316
- return Number.isFinite(configured) && configured > 0 ? configured : OFFLINE_QUESTION_CLAIM_TTL_MS;
33317
- }
33318
33887
  /**
33319
33888
  * The environment variable that moves when a still-waiting turn end is reported (§28).
33320
33889
  *
@@ -34381,7 +34950,6 @@ function applyImpl(ctx, config) {
34381
34950
  log
34382
34951
  });
34383
34952
  const extensions = new RemoteBridgeRegistry();
34384
- const offlineClaimTtlMs = offlineClaimTtl();
34385
34953
  /**
34386
34954
  * 第二会合点在协议面上的两处接线:`hello` 的公告与 `relay.grant` 的收帧。
34387
34955
  *
@@ -34428,7 +34996,6 @@ function applyImpl(ctx, config) {
34428
34996
  push,
34429
34997
  liveActivity,
34430
34998
  turnEndQuiet,
34431
- offlineClaimTtlMs,
34432
34999
  onPushRegistered: () => {
34433
35000
  watchers.sync();
34434
35001
  },
@@ -34793,4 +35360,4 @@ function applyImpl(ctx, config) {
34793
35360
  */
34794
35361
  const apply = mountOnce("@linxin666/dsh-remote-bridge", applyImpl);
34795
35362
  //#endregion
34796
- export { EFFORT_PATH, OFFLINE_CLAIM_TTL_ENV, PORT_SETTLE_RETRY_MS, ROSTER_PATH, TURN_END_QUIET_MAX_ENV, apply, bridgeWiringPlanOf, createDedupedStateLogger, createLeaseClaimer, createLegacyBlockCleaner, createPortSettleRetry, createRelayAnnouncer, createRelayHalfSwitch, disposeBridgeStack, inject, lanBasesOf, lanBindCapabilityOf, lanBindFrameOf, lanOriginOf, leaseConnectorSeams, leaseConnectorWants, livePublicOriginOf, name, offlineClaimTtl, relayAnnounceTargetOf, relayBridgeStateLine, relayStateLine, resolveBridgeConfig, retireStaleRelayHalfOf, turnEndQuietMaxWait };
35363
+ export { EFFORT_PATH, PORT_SETTLE_RETRY_MS, ROSTER_PATH, TURN_END_QUIET_MAX_ENV, apply, bridgeWiringPlanOf, createDedupedStateLogger, createLeaseClaimer, createLegacyBlockCleaner, createPortSettleRetry, createRelayAnnouncer, createRelayHalfSwitch, disposeBridgeStack, inject, lanBasesOf, lanBindCapabilityOf, lanBindFrameOf, lanOriginOf, leaseConnectorSeams, leaseConnectorWants, livePublicOriginOf, name, relayAnnounceTargetOf, relayBridgeStateLine, relayStateLine, resolveBridgeConfig, retireStaleRelayHalfOf, turnEndQuietMaxWait };