@linxin666/dsh-client-ui-task-board 0.3.22 → 0.3.24

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.
Files changed (42) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +2 -0
  3. package/README.zh.md +2 -0
  4. package/lib/client.js +726 -71
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +2619 -175
  7. package/lib/types/client/board/EditTaskModal.d.ts +6 -0
  8. package/lib/types/client/board/NewTaskModal.d.ts +6 -1
  9. package/lib/types/client/board/TaskBoard.d.ts +2 -0
  10. package/lib/types/client/board/TaskForm.d.ts +8 -3
  11. package/lib/types/client/board/parse-model-pref.d.ts +4 -0
  12. package/lib/types/client/host-api.d.ts +23 -1
  13. package/lib/types/client/locales.d.ts +26 -0
  14. package/lib/types/client/plugin-card-seat.d.ts +96 -0
  15. package/lib/types/client/sidebar-entry-core.d.ts +32 -0
  16. package/lib/types/core/controller.d.ts +35 -1
  17. package/lib/types/core/session-reuse.d.ts +4 -2
  18. package/lib/types/host-ai.d.ts +51 -0
  19. package/lib/types/host-ledger.d.ts +15 -0
  20. package/lib/types/host-routes.d.ts +11 -1
  21. package/lib/types/index.d.ts +9 -0
  22. package/lib/types/protocol.d.ts +19 -0
  23. package/package.json +2 -1
  24. package/src/client/board/EditTaskModal.tsx +36 -0
  25. package/src/client/board/NewTaskModal.tsx +119 -5
  26. package/src/client/board/TaskBoard.tsx +89 -0
  27. package/src/client/board/TaskDetail.tsx +38 -2
  28. package/src/client/board/TaskForm.tsx +17 -11
  29. package/src/client/board/parse-model-pref.ts +35 -0
  30. package/src/client/board.module.css +61 -0
  31. package/src/client/host-api.ts +124 -5
  32. package/src/client/index.ts +18 -17
  33. package/src/client/locales.ts +52 -0
  34. package/src/client/plugin-card-seat.ts +185 -0
  35. package/src/client/sidebar-entry-core.ts +96 -12
  36. package/src/core/controller.ts +57 -1
  37. package/src/core/session-reuse.ts +14 -5
  38. package/src/host-ai.ts +152 -0
  39. package/src/host-ledger.ts +84 -14
  40. package/src/host-routes.ts +68 -3
  41. package/src/index.ts +26 -1
  42. package/src/protocol.ts +34 -0
package/lib/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createRequire } from "node:module";
1
2
  import z from "schemastery";
2
3
  import { spawn, spawnSync } from "node:child_process";
3
4
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -5,6 +6,7 @@ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readF
5
6
  import { dirname, isAbsolute, join, win32 } from "node:path";
6
7
  import { homedir } from "node:os";
7
8
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
9
+ import { Service } from "@deepseek-ai/cordis";
8
10
  //#region src/core/schedule.ts
9
11
  /** Inclusive ranges per field, in cron order. */
10
12
  const FIELD_RANGES = [
@@ -179,8 +181,10 @@ function isDigits(value) {
179
181
  * Pick the session a new execution of this task may continue in, or undefined
180
182
  * to mint a fresh conversation. Reuse requires ALL of:
181
183
  * - the task opted in (`reuseSession === true`);
182
- * - the task's newest execution carries a session id and has settled (an open
183
- * execution would have made the ledger refuse the run in the first place);
184
+ * - the task's newest SETTLED execution carries a session id (issue #1587: the
185
+ * launch path calls this after `startExecution` appended this run's own open
186
+ * record, so reading the array tail always found an unsettled row and reuse
187
+ * never happened);
184
188
  * - the roster is known and that session is present and idle.
185
189
  *
186
190
  * An unknown roster (session/list unavailable) never reuses: minting a fresh
@@ -192,8 +196,15 @@ function isDigits(value) {
192
196
  */
193
197
  function reusableSessionId(task, idleSessionIds) {
194
198
  if (task.reuseSession !== true || idleSessionIds === void 0) return void 0;
195
- const last = task.executions[task.executions.length - 1];
196
- if (last === void 0 || last.sessionId === void 0 || last.endedAt === void 0) return void 0;
199
+ let last;
200
+ for (let index = task.executions.length - 1; index >= 0; index -= 1) {
201
+ const candidate = task.executions[index];
202
+ if (candidate.sessionId !== void 0 && candidate.endedAt !== void 0) {
203
+ last = candidate;
204
+ break;
205
+ }
206
+ }
207
+ if (last === void 0 || last.sessionId === void 0) return void 0;
197
208
  return idleSessionIds.has(last.sessionId) ? last.sessionId : void 0;
198
209
  }
199
210
  //#endregion
@@ -1026,6 +1037,18 @@ function applyUpdateTask(tasks, id, patch, now) {
1026
1037
  //#endregion
1027
1038
  //#region src/protocol.ts
1028
1039
  const TASK_BOARD_API_PREFIX = "/api/task-board";
1040
+ /** Strict parse of a `/parse` request body; undefined rejects the request. */
1041
+ function parseTaskParseRequest(value) {
1042
+ if (typeof value !== "object" || value === null) return void 0;
1043
+ const record = value;
1044
+ if (typeof record.text !== "string" || record.text.trim() === "") return void 0;
1045
+ if (record.model !== void 0 && typeof record.model !== "string") return void 0;
1046
+ const model = typeof record.model === "string" ? record.model.trim() : "";
1047
+ return {
1048
+ text: record.text,
1049
+ ...model === "" ? {} : { model }
1050
+ };
1051
+ }
1029
1052
  function record(value) {
1030
1053
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1031
1054
  }
@@ -1392,6 +1415,11 @@ function processIsAlive(pid) {
1392
1415
  }
1393
1416
  }
1394
1417
  const PROCESS_PROBE_TIMEOUT_MS = 3e3;
1418
+ /**
1419
+ * The CIM fallback pays a WMI cold start, so it gets a wider budget than the
1420
+ * direct `Get-Process` read it backs up.
1421
+ */
1422
+ const CIM_PROBE_TIMEOUT_MS = 8e3;
1395
1423
  let ownStartTime;
1396
1424
  let ownStartTimeResolved = false;
1397
1425
  /**
@@ -1416,6 +1444,52 @@ function linuxStartTimeMs(pid) {
1416
1444
  return;
1417
1445
  }
1418
1446
  }
1447
+ /** Default probe: one hidden, profile-free PowerShell process per script. */
1448
+ const runPowerShellProbe = (script, timeoutMs) => {
1449
+ const probe = spawnSync("powershell", [
1450
+ "-NoProfile",
1451
+ "-NonInteractive",
1452
+ "-Command",
1453
+ script
1454
+ ], {
1455
+ timeout: timeoutMs,
1456
+ windowsHide: true
1457
+ });
1458
+ if (probe.status !== 0 || probe.stdout.length === 0) return void 0;
1459
+ return probe.stdout.toString("utf8").trim();
1460
+ };
1461
+ /** The epoch-millisecond reading a probe printed, or undefined when unusable. */
1462
+ function parseProbeEpochMs(raw) {
1463
+ if (raw === void 0 || raw.trim() === "") return void 0;
1464
+ const started = Number(raw.trim());
1465
+ return Number.isFinite(started) ? started : void 0;
1466
+ }
1467
+ /** Start time through Get-Process: precise, but empty for protected processes. */
1468
+ function getProcessStartScript(pid) {
1469
+ return "[DateTimeOffset]::FromFileTime((Get-Process -Id " + String(pid) + " -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToFileTime()).ToUnixTimeMilliseconds()";
1470
+ }
1471
+ /** Start time through Win32_Process: readable for System/svchost too. */
1472
+ function cimStartScript(pid) {
1473
+ return "$p=Get-CimInstance Win32_Process -Filter \"ProcessId=" + String(pid) + "\" -ErrorAction SilentlyContinue;if($p -ne $null){[DateTimeOffset]::FromFileTime($p.CreationDate.ToUniversalTime().ToFileTime()).ToUnixTimeMilliseconds()}";
1474
+ }
1475
+ /**
1476
+ * Windows start time (Unix epoch ms) of a live process.
1477
+ *
1478
+ * `Get-Process` is the precise first choice, but an unprivileged caller cannot
1479
+ * read `.StartTime` for a protected process (System, svchost): the property is
1480
+ * empty, so the probe returns nothing. Without a fallback, a crash leftover
1481
+ * lock whose PID was reused by such a process could never be proven stale and
1482
+ * blocked every startup until the lock was deleted by hand (issue #1629).
1483
+ * Win32_Process through CIM reports the same CreationDate for those processes
1484
+ * at the same millisecond precision, so it is the second identity source. The
1485
+ * probe is injectable so the fallback chain is testable off Windows.
1486
+ */
1487
+ function win32StartTimeMs(pid, probe = runPowerShellProbe) {
1488
+ if (!Number.isSafeInteger(pid) || pid <= 0) return void 0;
1489
+ const direct = parseProbeEpochMs(probe(getProcessStartScript(pid), PROCESS_PROBE_TIMEOUT_MS));
1490
+ if (direct !== void 0) return direct;
1491
+ return parseProbeEpochMs(probe(cimStartScript(pid), CIM_PROBE_TIMEOUT_MS));
1492
+ }
1419
1493
  /**
1420
1494
  * Best-effort start time (Unix epoch ms) of a live process. Used to prove
1421
1495
  * whether the ledger lock really belongs to the PID recorded in it, so a
@@ -1425,20 +1499,7 @@ function linuxStartTimeMs(pid) {
1425
1499
  */
1426
1500
  function processStartTimeMs(pid) {
1427
1501
  if (process.platform === "linux") return linuxStartTimeMs(pid);
1428
- if (process.platform === "win32") {
1429
- const probe = spawnSync("powershell", [
1430
- "-NoProfile",
1431
- "-NonInteractive",
1432
- "-Command",
1433
- "[DateTimeOffset]::FromFileTime((Get-Process -Id " + String(pid) + " -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToFileTime()).ToUnixTimeMilliseconds()"
1434
- ], {
1435
- timeout: PROCESS_PROBE_TIMEOUT_MS,
1436
- windowsHide: true
1437
- });
1438
- if (probe.status !== 0 || probe.stdout.length === 0) return void 0;
1439
- const started = Number(probe.stdout.toString("utf8").trim());
1440
- return Number.isFinite(started) ? started : void 0;
1441
- }
1502
+ if (process.platform === "win32") return win32StartTimeMs(pid);
1442
1503
  const env = {
1443
1504
  ...process.env,
1444
1505
  LC_ALL: "C"
@@ -1488,6 +1549,15 @@ function ownProcessStartTimeMs() {
1488
1549
  * falls back to this bounded tolerance.
1489
1550
  */
1490
1551
  const LEGACY_START_TOLERANCE_MS = 2e3;
1552
+ /**
1553
+ * How long an unreadable lock must sit untouched before it may be reclaimed.
1554
+ * The owner writes and fsyncs its record immediately after creating the file
1555
+ * with O_EXCL, so a lock that cannot be parsed may still be mid-write by a
1556
+ * live owner; only one that has been unreadable for longer than any write can
1557
+ * take is treated as an unclean-shutdown leftover (issue #1528: a 0-byte lock
1558
+ * kept the Host half from mounting until it was deleted by hand).
1559
+ */
1560
+ const UNREADABLE_LOCK_GRACE_MS = 6e4;
1491
1561
  /** Whether the recorded start time proves the recorded PID is another process. */
1492
1562
  function startTimeMismatch(recorded, actual, exact) {
1493
1563
  return exact ? recorded !== actual : Math.abs(recorded - actual) > LEGACY_START_TOLERANCE_MS;
@@ -2089,7 +2159,19 @@ var HostTaskLedger = class {
2089
2159
  if (typeof owner.startedAt === "number") ownerStartedAt = owner.startedAt;
2090
2160
  ownerExact = owner.probe === "exact";
2091
2161
  } catch {
2092
- throw new Error(`task-board ledger lock is unreadable: ${this.lockFile}; if this is a leftover from an unclean shutdown and no other DSH host is running, remove it manually and retry`);
2162
+ if ((() => {
2163
+ try {
2164
+ return this.now() - statSync(this.lockFile).mtimeMs;
2165
+ } catch {
2166
+ return Number.POSITIVE_INFINITY;
2167
+ }
2168
+ })() < UNREADABLE_LOCK_GRACE_MS) throw new Error(`task-board ledger lock is unreadable: ${this.lockFile}; if this is a leftover from an unclean shutdown and no other DSH host is running, remove it manually and retry`);
2169
+ try {
2170
+ unlinkSync(this.lockFile);
2171
+ } catch (unlinkError) {
2172
+ if (unlinkError.code !== "ENOENT") throw unlinkError;
2173
+ }
2174
+ continue;
2093
2175
  }
2094
2176
  if (pid !== void 0 && processIsAlive(pid)) {
2095
2177
  const actualStartedAt = pid === process.pid ? ownProcessStartTimeMs() : processStartTimeMs(pid);
@@ -2997,183 +3079,2465 @@ function safeConsoleError(message, ...args) {
2997
3079
  } catch {}
2998
3080
  }
2999
3081
  //#endregion
3000
- //#region src/http.ts
3001
- /** Family-default JSON response headers; callers may append or override. */
3002
- const JSON_HEADERS = {
3003
- "content-type": "application/json; charset=utf-8",
3004
- "referrer-policy": "no-referrer"
3082
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.1.5-rc.1_@deepseek-ai+cordis@4.0.2/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
3083
+ /** The one Remote failure class shared by owners, the Gateway, and consumers. */
3084
+ /**
3085
+ * One Remote call failure: a real Error carrying its stable code and typed
3086
+ * details. Owners throw it at the failure point; the Host Gateway encodes it
3087
+ * onto the wire unchanged; the Client face rebuilds an instance for the
3088
+ * `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
3089
+ * Discrimination is always by `code`, never by instanceof.
3090
+ */
3091
+ var RemoteError = class extends Error {
3092
+ code;
3093
+ details;
3094
+ /** Structural marker: cross-realm/bundle identification never uses instanceof. */
3095
+ isDSHRemoteError = true;
3096
+ /**
3097
+ * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
3098
+ * @param message - human diagnostic carried across the wire.
3099
+ * @param details - structured payload typed by the code.
3100
+ * @param options - standard Error options (`cause` survives in-process only).
3101
+ */
3102
+ constructor(code, message, details, options) {
3103
+ super(message, options);
3104
+ this.code = code;
3105
+ this.details = details;
3106
+ this.name = "RemoteError";
3107
+ }
3005
3108
  };
3006
3109
  /**
3007
- * Write one JSON response. Default headers are the family defaults
3008
- * (content-type and referrer-policy); caller headers are appended or
3009
- * override them.
3110
+ * Remote decorators and explicit Gateway bindings backed by versioned
3111
+ * descriptors carried on decorated class prototypes. Strict reflection
3112
+ * remains a Typert compiler responsibility.
3113
+ * @module @deepseek-ai/dsh-typert-protocol
3010
3114
  */
3011
- function writeJson(res, status, body, headers = {}) {
3012
- const payload = JSON.stringify(body);
3013
- res.writeHead(status, {
3014
- ...JSON_HEADERS,
3015
- ...headers
3016
- });
3017
- res.end(payload);
3018
- }
3019
- //#endregion
3020
- //#region src/loopback.ts
3021
- /** IPv4 127/8 predicate (four decimal octets, first == 127). */
3022
- function isIPv4Loopback(v4) {
3023
- const parts = v4.split(".");
3024
- return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
3025
- }
3026
- /** Whether a socket remote address names the loopback range (127/8, ::1, IPv4-mapped). */
3027
- function isLoopbackAddress(address) {
3028
- if (address === void 0) return false;
3029
- const normalized = address.toLowerCase();
3030
- if (normalized === "::1") return true;
3031
- if (normalized.startsWith("::ffff:")) return isIPv4Loopback(normalized.slice(7));
3032
- return isIPv4Loopback(normalized);
3033
- }
3034
- /** Whether a normalized URL hostname names the loopback authority (localhost, [::1], 127/8). */
3035
- function isLoopbackHostname(hostname) {
3036
- if (hostname === "localhost" || hostname === "[::1]") return true;
3037
- return isIPv4Loopback(hostname);
3115
+ const TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
3116
+ /**
3117
+ * Test one generated Remote name against the Connection endpoint grammar.
3118
+ * @param value - namespace, method, lookup, or Context segment.
3119
+ * @returns whether the value can cross the shared RPC carrier unchanged.
3120
+ */
3121
+ function isTypertRemoteSegment(value) {
3122
+ return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
3038
3123
  }
3124
+ const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
3039
3125
  /**
3040
- * Request-level trust fence: a loopback socket address AND a loopback Host
3041
- * header, plus browser same-origin markers. The socket address is
3042
- * authoritative; X-Forwarded-For is never trusted.
3126
+ * Bind one visible Service field to a Cordis key and Remote namespace.
3127
+ * @param service - owning Service instance, normally `this`.
3128
+ * @param serviceKey - exact Cordis service key.
3129
+ * @param options - optional distinct wire namespace.
3130
+ * @returns a frozen, inspectable binding with no compiler-injected metadata.
3043
3131
  */
3044
- function isLoopbackRequest(request) {
3045
- if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
3046
- const host = request.headers.host;
3047
- if (typeof host !== "string") return false;
3048
- let hostUrl;
3049
- try {
3050
- hostUrl = new URL("http://" + host);
3051
- } catch {
3052
- return false;
3132
+ function bindTypertRemote(service, serviceKey, options = {}) {
3133
+ validateName("service key", serviceKey);
3134
+ const namespace = options.namespace ?? serviceKey;
3135
+ validateName("namespace", namespace);
3136
+ return Object.freeze({
3137
+ service,
3138
+ serviceKey,
3139
+ namespace
3140
+ });
3141
+ }
3142
+ /** Cordis Service base that exposes its registered name through Typert Gateway. */
3143
+ var TypertRemoteService = class extends Service {
3144
+ /** Visible binding consumed by the Gateway's source-mode discovery. */
3145
+ typertRemote;
3146
+ /**
3147
+ * Register the Service and bind the same key to Typert Gateway.
3148
+ * @param ctx - owning Cordis Context.
3149
+ * @param serviceKey - exact Cordis service key and default wire namespace.
3150
+ * @param options - optional distinct wire namespace.
3151
+ */
3152
+ constructor(ctx, serviceKey, options = {}) {
3153
+ super(ctx, serviceKey);
3154
+ this.typertRemote = bindTypertRemote(this, this.name, options);
3053
3155
  }
3054
- if (!isLoopbackHostname(hostUrl.hostname)) return false;
3055
- if (request.headers["sec-fetch-site"] === "cross-site") return false;
3056
- const origin = request.headers.origin;
3057
- if (origin === void 0) return true;
3058
- try {
3059
- return new URL(origin).host === hostUrl.host;
3060
- } catch {
3061
- return false;
3156
+ };
3157
+ function Remote(methodExportOrOptions, context) {
3158
+ if (typeof methodExportOrOptions === "string") {
3159
+ validateName("Remote export name", methodExportOrOptions);
3160
+ return remoteDecorator({ kind: "direct" }, void 0, methodExportOrOptions);
3062
3161
  }
3063
- }
3064
- //#endregion
3065
- //#region src/host-routes.ts
3066
- const ACTION_LIMIT = 64 * 1024;
3067
- const IMPORT_LIMIT = 2 * 1024 * 1024;
3068
- const HEARTBEAT_MS = 15e3;
3069
- /** Header replaced by an authenticated same-host reverse proxy. */
3070
- const TASK_BOARD_PROXY_TOKEN_HEADER = "x-dsh-task-board-proxy-token";
3071
- function parseAuthority(authority) {
3072
- if (authority.trim() !== authority) return void 0;
3073
- const match = authority.startsWith("[") ? /^\[[^\]]+\](?::([0-9]+))?$/.exec(authority) : /^[^:@/?#\s]+(?::([0-9]+))?$/.exec(authority);
3074
- if (match === null) return void 0;
3075
- try {
3076
- const url = new URL(`http://${authority}`);
3077
- if (url.username !== "" || url.password !== "" || url.pathname !== "/" || url.search !== "" || url.hash !== "") return void 0;
3078
- const rawPort = match[1];
3079
- if (rawPort !== void 0 && (String(Number(rawPort)) !== rawPort || Number(rawPort) > 65535)) return void 0;
3080
- return {
3081
- canonical: url.hostname.toLowerCase() + (rawPort === void 0 ? "" : `:${rawPort}`),
3082
- url
3083
- };
3084
- } catch {
3085
- return;
3162
+ if (typeof methodExportOrOptions === "object") {
3163
+ if (remoteOptionMode(methodExportOrOptions) !== "stream" || Reflect.ownKeys(methodExportOrOptions).length !== 1) throw new TypeError("typert-protocol: Remote options must contain exactly mode: \"stream\"");
3164
+ return remoteDecorator({ kind: "direct" }, "stream");
3086
3165
  }
3166
+ if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
3167
+ addMarkerInitializer(context, { kind: "direct" });
3087
3168
  }
3088
- function resolveAccess(access) {
3089
- const trustedProxyHosts = /* @__PURE__ */ new Set();
3090
- for (const authority of access.trustedProxyHosts ?? []) {
3091
- const parsed = parseAuthority(authority);
3092
- if (parsed === void 0 || parsed.canonical !== authority.toLowerCase()) throw new Error(`task-board: trustedProxyHosts entry ${JSON.stringify(authority)} is not a canonical host[:port] authority`);
3093
- trustedProxyHosts.add(parsed.canonical);
3094
- }
3095
- if (trustedProxyHosts.size > 0 && (access.proxyToken === void 0 || access.proxyToken === "")) throw new Error("task-board: authenticated proxy hosts require a non-empty proxy token");
3096
- return {
3097
- trustedProxyHosts,
3098
- ...access.proxyToken === void 0 ? {} : { proxyToken: access.proxyToken }
3169
+ function remoteOptionMode(options) {
3170
+ return Reflect.get(options, "mode");
3171
+ }
3172
+ function remoteDecorator(invocation, mode, exportName) {
3173
+ return function(_method, context) {
3174
+ addMarkerInitializer(context, invocation, mode, exportName);
3099
3175
  };
3100
3176
  }
3177
+ function readRemoteMethodDescriptor(prototype) {
3178
+ const property = Object.getOwnPropertyDescriptor(prototype, REMOTE_METHOD_DESCRIPTOR);
3179
+ if (property === void 0) return void 0;
3180
+ const descriptor = property.value;
3181
+ if (descriptor === null || typeof descriptor !== "object") throw new TypeError("typert-protocol: Remote method descriptor must be an object");
3182
+ const version = Reflect.get(descriptor, "version");
3183
+ if (version !== 1) throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(version)}`);
3184
+ const methods = Reflect.get(descriptor, "methods");
3185
+ if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
3186
+ return descriptor;
3187
+ }
3188
+ function addMarkerInitializer(context, invocation, mode, exportName) {
3189
+ if (context.private || context.static || typeof context.name !== "string") throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");
3190
+ const method = context.name;
3191
+ context.addInitializer(function() {
3192
+ const prototype = Object.getPrototypeOf(this);
3193
+ if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
3194
+ mark(prototype, method, invocation, mode, exportName);
3195
+ });
3196
+ }
3197
+ function mark(prototype, method, invocation, mode, exportName) {
3198
+ const descriptor = readRemoteMethodDescriptor(prototype);
3199
+ const marker = Object.freeze({
3200
+ method,
3201
+ ...exportName === void 0 || exportName === method ? {} : { exportName },
3202
+ ...mode === void 0 ? {} : { mode },
3203
+ invocation: Object.freeze(invocation)
3204
+ });
3205
+ const current = descriptor?.methods.find((candidate) => candidate.method === method);
3206
+ if (current !== void 0) {
3207
+ if (current.exportName === marker.exportName && current.mode === marker.mode && sameInvocation(current.invocation, invocation)) return;
3208
+ throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
3209
+ }
3210
+ Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
3211
+ configurable: true,
3212
+ value: Object.freeze({
3213
+ version: 1,
3214
+ methods: Object.freeze([...descriptor?.methods ?? [], marker])
3215
+ })
3216
+ });
3217
+ }
3218
+ function sameInvocation(left, right) {
3219
+ if (left.kind === "direct") return right.kind === "direct";
3220
+ if (right.kind === "direct") return false;
3221
+ return left.context === right.context;
3222
+ }
3223
+ function validateName(subject, value) {
3224
+ if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
3225
+ }
3226
+ //#endregion
3227
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.1.5-rc.1_@deepseek-ai+cordis@4.0.2/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
3101
3228
  /**
3102
- * Browser-signal tripwire, NOT an authority check: a bare curl sends neither
3103
- * header and is refused, but a curl with a forged Origin passes this too.
3104
- * The real boundary is the loopback socket + Host + origin-equality checks
3105
- * in isTrustedTaskBoardRequest below; do not rely on this marker alone.
3229
+ * Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
3230
+ * @param value - value to freeze.
3231
+ * @returns the same value after every reachable enumerable child is frozen.
3106
3232
  */
3107
- function browserSameOriginMarker(req) {
3108
- return req.headers["sec-fetch-site"] === "same-origin" || typeof req.headers.origin === "string";
3109
- }
3110
- function sameAuthority(req, host) {
3111
- if (req.headers["sec-fetch-site"] === "cross-site") return false;
3112
- const origin = req.headers.origin;
3113
- if (origin === void 0) return req.headers["sec-fetch-site"] === "same-origin";
3114
- try {
3115
- return new URL(origin).host === host.host;
3116
- } catch {
3117
- return false;
3233
+ function deepFreeze(value) {
3234
+ const seen = /* @__PURE__ */ new WeakSet();
3235
+ const pending = [{
3236
+ kind: "visit",
3237
+ node: value
3238
+ }];
3239
+ while (pending.length > 0) {
3240
+ const task = pending.pop();
3241
+ /* v8 ignore next -- the loop condition guarantees one pending task. */
3242
+ if (task === void 0) continue;
3243
+ if (task.kind === "property") {
3244
+ pending.push({
3245
+ kind: "visit",
3246
+ node: task.source[task.key]
3247
+ });
3248
+ continue;
3249
+ }
3250
+ const node = task.node;
3251
+ if (node === null || typeof node !== "object") continue;
3252
+ if (node instanceof AbortSignal) continue;
3253
+ if (seen.has(node)) continue;
3254
+ seen.add(node);
3255
+ Object.freeze(node);
3256
+ const keys = Object.keys(node);
3257
+ for (let index = keys.length - 1; index >= 0; index--) {
3258
+ const key = keys[index];
3259
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
3260
+ if (key === void 0) continue;
3261
+ pending.push({
3262
+ kind: "property",
3263
+ source: node,
3264
+ key
3265
+ });
3266
+ }
3118
3267
  }
3268
+ return value;
3119
3269
  }
3120
- function matchesToken(candidate, expected) {
3121
- if (typeof candidate !== "string" || expected === void 0 || candidate === "" || expected === "") return false;
3122
- const actual = Buffer.from(candidate);
3123
- const wanted = Buffer.from(expected);
3124
- return actual.length === wanted.length && timingSafeEqual(actual, wanted);
3270
+ //#endregion
3271
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-crypto@0.1.5-rc.1_@deepseek-ai+cordis@4.0.2/node_modules/@deepseek-ai/dsh-util-crypto/lib/index.js
3272
+ /**
3273
+ * Random v4 UUID, minted from `crypto.getRandomValues`.
3274
+ * @returns the UUID string.
3275
+ */
3276
+ function randomUUID() {
3277
+ const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
3278
+ const hex = Array.from(bytes, (byte, index) => {
3279
+ return (index === 6 ? byte & 15 | 64 : index === 8 ? byte & 63 | 128 : byte).toString(16).padStart(2, "0");
3280
+ }).join("");
3281
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
3125
3282
  }
3283
+ //#endregion
3284
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-brand@0.1.5-rc.1_@deepseek-ai+cordis@4.0.2/node_modules/@deepseek-ai/dsh-brand/lib/index.js
3126
3285
  /**
3127
- * Task-board route fence. Direct desktop access uses the repository-wide
3128
- * loopback socket + Host guard and additionally requires a browser same-origin
3129
- * marker: a bare local curl without any browser signal cannot exercise the
3130
- * agent control plane (a forged Origin does pass the marker — it is a
3131
- * tripwire, the socket/Host/origin-equality checks carry the authority).
3132
- * Authenticated proxies must be explicitly allowlisted and replace the
3133
- * internal token header after their own authentication step.
3286
+ * Duplicate-install-safe nominal primitive helpers.
3287
+ *
3288
+ * A brand makes structurally identical strings or numbers non-interchangeable
3289
+ * at the type level: a `SessionId` cannot be passed where a `ToolCallId` is
3290
+ * expected, and an event sequence cannot be passed as a log offset. Comparison,
3291
+ * logging, and serialization retain the underlying primitive behavior.
3292
+ *
3293
+ * This package owns no concrete domain value and keeps no runtime identity or mutable
3294
+ * state, so independently installed copies produce interchangeable values.
3295
+ *
3296
+ * @module @deepseek-ai/dsh-brand
3134
3297
  */
3135
- function isTrustedTaskBoardRequest(req, access) {
3136
- if (!browserSameOriginMarker(req)) return false;
3137
- if (isLoopbackRequest(req)) return true;
3138
- if (!isLoopbackAddress(req.socket.remoteAddress)) return false;
3139
- const host = req.headers.host;
3140
- if (typeof host !== "string") return false;
3141
- const parsed = parseAuthority(host);
3142
- if (parsed === void 0 || parsed.canonical !== host.toLowerCase()) return false;
3143
- if (!access.trustedProxyHosts.has(parsed.canonical) || !sameAuthority(req, parsed.url)) return false;
3144
- return matchesToken(req.headers[TASK_BOARD_PROXY_TOKEN_HEADER], access.proxyToken);
3298
+ /**
3299
+ * Apply a compile-time string brand without changing the value.
3300
+ * @param value - string admitted by the domain that owns the target brand.
3301
+ * @returns the same string with the requested compile-time brand.
3302
+ */
3303
+ function brandString(value) {
3304
+ return value;
3145
3305
  }
3146
- async function readBody(req) {
3147
- const chunks = [];
3148
- let size = 0;
3149
- for await (const chunk of req) {
3150
- const buffer = chunk;
3151
- size += buffer.length;
3152
- if (size > IMPORT_LIMIT) throw new Error("body-too-large");
3153
- chunks.push(buffer);
3306
+ //#endregion
3307
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.3/node_modules/@deepseek-ai/cosmokit/lib/index.js
3308
+ /** Return true when a value is `null` or `undefined`. */
3309
+ function isNullable(value) {
3310
+ return value === null || value === void 0;
3311
+ }
3312
+ /** Return true for non-array object values. */
3313
+ function isPlainObject(data) {
3314
+ return data && typeof data === "object" && !Array.isArray(data);
3315
+ }
3316
+ /** Filter object entries and return a new object. */
3317
+ function filterKeys(object, filter) {
3318
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
3319
+ }
3320
+ /** Map object values while preserving the original key set. */
3321
+ function mapValues(object, transform) {
3322
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
3323
+ }
3324
+ /** Pick selected keys from an object, optionally including `undefined` values. */
3325
+ function pick(source, keys, forced) {
3326
+ if (!keys) return { ...source };
3327
+ const result = {};
3328
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
3329
+ return result;
3330
+ }
3331
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
3332
+ function is(type, value) {
3333
+ if (arguments.length === 1) return (value) => is(type, value);
3334
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
3335
+ }
3336
+ function isArrayBufferLike(value) {
3337
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
3338
+ }
3339
+ function isArrayBufferSource(value) {
3340
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
3341
+ }
3342
+ /** Binary source detection and base64/hex conversion helpers. */
3343
+ var Binary;
3344
+ (function(Binary) {
3345
+ Binary.is = isArrayBufferLike;
3346
+ Binary.isSource = isArrayBufferSource;
3347
+ function fromSource(source) {
3348
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
3349
+ else return source;
3154
3350
  }
3155
- const raw = Buffer.concat(chunks).toString("utf8");
3156
- return {
3157
- raw,
3158
- value: JSON.parse(raw)
3159
- };
3351
+ Binary.fromSource = fromSource;
3352
+ function toBase64(source) {
3353
+ source = fromSource(source);
3354
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
3355
+ let binary = "";
3356
+ const bytes = new Uint8Array(source);
3357
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
3358
+ return btoa(binary);
3359
+ }
3360
+ Binary.toBase64 = toBase64;
3361
+ function fromBase64(source) {
3362
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
3363
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
3364
+ }
3365
+ Binary.fromBase64 = fromBase64;
3366
+ function toHex(source) {
3367
+ source = fromSource(source);
3368
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
3369
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
3370
+ }
3371
+ Binary.toHex = toHex;
3372
+ function fromHex(source) {
3373
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
3374
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
3375
+ const buffer = [];
3376
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
3377
+ return Uint8Array.from(buffer).buffer;
3378
+ }
3379
+ Binary.fromHex = fromHex;
3380
+ })(Binary || (Binary = {}));
3381
+ Binary.fromBase64;
3382
+ Binary.toBase64;
3383
+ Binary.fromHex;
3384
+ Binary.toHex;
3385
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
3386
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
3387
+ if (!source || typeof source !== "object") return source;
3388
+ if (is("Date", source)) return new Date(source.valueOf());
3389
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
3390
+ if (isArrayBufferLike(source)) return source.slice(0);
3391
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
3392
+ const cached = refs.get(source);
3393
+ if (cached) return cached;
3394
+ if (Array.isArray(source)) {
3395
+ const result = [];
3396
+ refs.set(source, result);
3397
+ source.forEach((value, index) => {
3398
+ result[index] = Reflect.apply(clone, null, [value, refs]);
3399
+ });
3400
+ return result;
3401
+ }
3402
+ const result = Object.create(Object.getPrototypeOf(source));
3403
+ refs.set(source, result);
3404
+ for (const key of Reflect.ownKeys(source)) {
3405
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
3406
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
3407
+ Reflect.defineProperty(result, key, descriptor);
3408
+ }
3409
+ return result;
3160
3410
  }
3161
- function makeTaskBoardRoutes(service, access = {}) {
3162
- const resolvedAccess = resolveAccess(access);
3163
- const guard = (req, res) => {
3164
- if (isTrustedTaskBoardRequest(req, resolvedAccess)) return true;
3165
- writeJson(res, 403, {
3166
- ok: false,
3167
- error: "forbidden"
3168
- }, { "cache-control": "no-store" });
3169
- return false;
3411
+ /** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
3412
+ function deepEqual(a, b, strict) {
3413
+ if (a === b) return true;
3414
+ if (!strict && isNullable(a) && isNullable(b)) return true;
3415
+ if (typeof a !== typeof b) return false;
3416
+ if (typeof a !== "object") return false;
3417
+ if (!a || !b) return false;
3418
+ function check(test, then) {
3419
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
3420
+ }
3421
+ return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
3422
+ if (a.byteLength !== b.byteLength) return false;
3423
+ const viewA = new Uint8Array(a);
3424
+ const viewB = new Uint8Array(b);
3425
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
3426
+ return true;
3427
+ }) ?? Object.keys({
3428
+ ...a,
3429
+ ...b
3430
+ }).every((key) => deepEqual(a[key], b[key], strict));
3431
+ }
3432
+ /** Time constants plus parsing and formatting helpers. */
3433
+ var Time;
3434
+ (function(Time) {
3435
+ Time.millisecond = 1;
3436
+ Time.second = 1e3;
3437
+ Time.minute = Time.second * 60;
3438
+ Time.hour = Time.minute * 60;
3439
+ Time.day = Time.hour * 24;
3440
+ Time.week = Time.day * 7;
3441
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
3442
+ function setTimezoneOffset(offset) {
3443
+ timezoneOffset = offset;
3444
+ }
3445
+ Time.setTimezoneOffset = setTimezoneOffset;
3446
+ function getTimezoneOffset() {
3447
+ return timezoneOffset;
3448
+ }
3449
+ Time.getTimezoneOffset = getTimezoneOffset;
3450
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
3451
+ if (typeof date === "number") date = new Date(date);
3452
+ if (offset === void 0) offset = timezoneOffset;
3453
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
3454
+ }
3455
+ Time.getDateNumber = getDateNumber;
3456
+ function fromDateNumber(value, offset) {
3457
+ const date = new Date(value * Time.day);
3458
+ if (offset === void 0) offset = timezoneOffset;
3459
+ return new Date(+date + offset * Time.minute);
3460
+ }
3461
+ Time.fromDateNumber = fromDateNumber;
3462
+ const numeric = /\d+(?:\.\d+)?/.source;
3463
+ const timeRegExp = new RegExp(`^${[
3464
+ "w(?:eek(?:s)?)?",
3465
+ "d(?:ay(?:s)?)?",
3466
+ "h(?:our(?:s)?)?",
3467
+ "m(?:in(?:ute)?(?:s)?)?",
3468
+ "s(?:ec(?:ond)?(?:s)?)?"
3469
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
3470
+ function parseTime(source) {
3471
+ const capture = timeRegExp.exec(source);
3472
+ if (!capture) return 0;
3473
+ return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
3474
+ }
3475
+ Time.parseTime = parseTime;
3476
+ function parseDate(date) {
3477
+ const parsed = parseTime(date);
3478
+ if (parsed) date = Date.now() + parsed;
3479
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
3480
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
3481
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
3482
+ }
3483
+ Time.parseDate = parseDate;
3484
+ function format(ms) {
3485
+ const abs = Math.abs(ms);
3486
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
3487
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
3488
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
3489
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
3490
+ return ms + "ms";
3491
+ }
3492
+ Time.format = format;
3493
+ function toDigits(source, length = 2) {
3494
+ return source.toString().padStart(length, "0");
3495
+ }
3496
+ Time.toDigits = toDigits;
3497
+ function template(template, time = /* @__PURE__ */ new Date()) {
3498
+ return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
3499
+ }
3500
+ Time.template = template;
3501
+ })(Time || (Time = {}));
3502
+ //#endregion
3503
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.2/node_modules/@deepseek-ai/schemastery/lib/index.mjs
3504
+ const kSchema = Symbol.for("schemastery");
3505
+ const kValidationError = Symbol.for("ValidationError");
3506
+ globalThis.__schemastery_index__ ??= 0;
3507
+ globalThis.__schemastery_refs__ = void 0;
3508
+ var ValidationError = class extends TypeError {
3509
+ options;
3510
+ name = "ValidationError";
3511
+ constructor(message, options) {
3512
+ let prefix = "$";
3513
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
3514
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
3515
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
3516
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
3517
+ super((prefix === "$" ? "" : `${prefix} `) + message);
3518
+ this.options = options;
3519
+ }
3520
+ static is(error) {
3521
+ return !!error?.[kValidationError];
3522
+ }
3523
+ };
3524
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
3525
+ const Schema = function(options) {
3526
+ const schema = function(data, options = {}) {
3527
+ return Schema.resolve(data, schema, options)[0];
3170
3528
  };
3171
- return [
3172
- {
3173
- kind: "exact",
3174
- path: `${TASK_BOARD_API_PREFIX}/state`,
3175
- handler: (req, res) => {
3176
- if (req.method !== "GET") return writeJson(res, 405, {
3529
+ if (options.refs) {
3530
+ const refs = mapValues(options.refs, (options) => new Schema(options));
3531
+ const getRef = (uid) => refs[uid];
3532
+ for (const key in refs) {
3533
+ const options = refs[key];
3534
+ options.sKey = getRef(options.sKey);
3535
+ options.inner = getRef(options.inner);
3536
+ options.list = options.list && options.list.map(getRef);
3537
+ options.dict = options.dict && mapValues(options.dict, getRef);
3538
+ }
3539
+ return refs[options.uid];
3540
+ }
3541
+ Object.assign(schema, options);
3542
+ if (typeof schema.callback === "string") try {
3543
+ schema.callback = new Function("return " + schema.callback)();
3544
+ } catch {}
3545
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
3546
+ Object.setPrototypeOf(schema, Schema.prototype);
3547
+ schema.meta ||= {};
3548
+ schema.toString = schema.toString.bind(schema);
3549
+ return schema;
3550
+ };
3551
+ Schema.prototype = Object.create(Function.prototype);
3552
+ Schema.prototype[kSchema] = true;
3553
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
3554
+ return {
3555
+ version: 1,
3556
+ vendor: "schemastery",
3557
+ validate: (value) => {
3558
+ try {
3559
+ return { value: Schema.resolve(value, this, {})[0] };
3560
+ } catch (error) {
3561
+ if (ValidationError.is(error)) return { issues: [{
3562
+ message: error.message,
3563
+ path: error.options.path
3564
+ }] };
3565
+ throw error;
3566
+ }
3567
+ }
3568
+ };
3569
+ } });
3570
+ Schema.ValidationError = ValidationError;
3571
+ Schema.prototype.toJSON = function toJSON() {
3572
+ if (globalThis.__schemastery_refs__) {
3573
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
3574
+ return this.uid;
3575
+ }
3576
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
3577
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
3578
+ const result = {
3579
+ uid: this.uid,
3580
+ refs: globalThis.__schemastery_refs__
3581
+ };
3582
+ globalThis.__schemastery_refs__ = void 0;
3583
+ return result;
3584
+ };
3585
+ Schema.prototype.set = function set(key, value) {
3586
+ this.dict[key] = value;
3587
+ return this;
3588
+ };
3589
+ Schema.prototype.push = function push(value) {
3590
+ this.list.push(value);
3591
+ return this;
3592
+ };
3593
+ function mergeDesc(original, messages) {
3594
+ const result = typeof original === "string" ? { "": original } : { ...original };
3595
+ for (const locale in messages) {
3596
+ const value = messages[locale];
3597
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
3598
+ else if (typeof value === "string") result[locale] = value;
3599
+ }
3600
+ return result;
3601
+ }
3602
+ function getInner(value) {
3603
+ return value?.$value ?? value?.$inner;
3604
+ }
3605
+ function extractKeys(data) {
3606
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
3607
+ }
3608
+ Schema.prototype.i18n = function i18n(messages) {
3609
+ const schema = Schema(this);
3610
+ const desc = mergeDesc(schema.meta.description, messages);
3611
+ if (Object.keys(desc).length) schema.meta.description = desc;
3612
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
3613
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
3614
+ });
3615
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
3616
+ return inner.i18n(mapValues(messages, (data = {}) => {
3617
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
3618
+ if (Array.isArray(data)) return data[index];
3619
+ return extractKeys(data);
3620
+ }));
3621
+ });
3622
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
3623
+ if (getInner(data)) return getInner(data);
3624
+ return extractKeys(data);
3625
+ }));
3626
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
3627
+ return schema;
3628
+ };
3629
+ Schema.prototype.extra = function extra(key, value) {
3630
+ const schema = Schema(this);
3631
+ schema.meta = {
3632
+ ...schema.meta,
3633
+ [key]: value
3634
+ };
3635
+ return schema;
3636
+ };
3637
+ for (const key of [
3638
+ "required",
3639
+ "disabled",
3640
+ "collapse",
3641
+ "hidden",
3642
+ "loose"
3643
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
3644
+ const schema = Schema(this);
3645
+ schema.meta = {
3646
+ ...schema.meta,
3647
+ [key]: value
3648
+ };
3649
+ return schema;
3650
+ } });
3651
+ Schema.prototype.deprecated = function deprecated() {
3652
+ const schema = Schema(this);
3653
+ schema.meta.badges ||= [];
3654
+ schema.meta.badges.push({
3655
+ text: "deprecated",
3656
+ type: "danger"
3657
+ });
3658
+ return schema;
3659
+ };
3660
+ Schema.prototype.experimental = function experimental() {
3661
+ const schema = Schema(this);
3662
+ schema.meta.badges ||= [];
3663
+ schema.meta.badges.push({
3664
+ text: "experimental",
3665
+ type: "warning"
3666
+ });
3667
+ return schema;
3668
+ };
3669
+ Schema.prototype.pattern = function pattern(regexp) {
3670
+ const schema = Schema(this);
3671
+ const pattern = pick(regexp, ["source", "flags"]);
3672
+ schema.meta = {
3673
+ ...schema.meta,
3674
+ pattern
3675
+ };
3676
+ return schema;
3677
+ };
3678
+ Schema.prototype.simplify = function simplify(value) {
3679
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
3680
+ if (isNullable(value)) return value;
3681
+ if (this.type === "object" || this.type === "dict") {
3682
+ const result = {};
3683
+ for (const key in value) {
3684
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
3685
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
3686
+ }
3687
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
3688
+ return result;
3689
+ } else if (this.type === "array" || this.type === "tuple") {
3690
+ const result = [];
3691
+ value.forEach((value, index) => {
3692
+ const schema = this.type === "array" ? this.inner : this.list[index];
3693
+ const item = schema ? schema.simplify(value) : value;
3694
+ result.push(item);
3695
+ });
3696
+ return result;
3697
+ } else if (this.type === "intersect") {
3698
+ const result = {};
3699
+ for (const item of this.list) Object.assign(result, item.simplify(value));
3700
+ return result;
3701
+ } else if (this.type === "union") for (const schema of this.list) try {
3702
+ Schema.resolve(value, schema, {});
3703
+ return schema.simplify(value);
3704
+ } catch {}
3705
+ return value;
3706
+ };
3707
+ Schema.prototype.toString = function toString(inline) {
3708
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
3709
+ };
3710
+ Schema.prototype.role = function role(role, extra) {
3711
+ const schema = Schema(this);
3712
+ schema.meta = {
3713
+ ...schema.meta,
3714
+ role,
3715
+ extra
3716
+ };
3717
+ return schema;
3718
+ };
3719
+ for (const key of [
3720
+ "default",
3721
+ "link",
3722
+ "comment",
3723
+ "description",
3724
+ "max",
3725
+ "min",
3726
+ "step"
3727
+ ]) Object.assign(Schema.prototype, { [key](value) {
3728
+ const schema = Schema(this);
3729
+ schema.meta = {
3730
+ ...schema.meta,
3731
+ [key]: value
3732
+ };
3733
+ return schema;
3734
+ } });
3735
+ const resolvers = {};
3736
+ Schema.extend = function extend(type, resolve) {
3737
+ resolvers[type] = resolve;
3738
+ };
3739
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
3740
+ if (!schema) return [data];
3741
+ if (options.ignore?.(data, schema)) return [data];
3742
+ if (isNullable(data) && schema.type !== "lazy") {
3743
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
3744
+ let current = schema;
3745
+ let fallback = schema.meta.default;
3746
+ while (current?.type === "intersect" && isNullable(fallback)) {
3747
+ current = current.list[0];
3748
+ fallback = current?.meta.default;
3749
+ }
3750
+ if (isNullable(fallback)) return [data];
3751
+ data = clone(fallback);
3752
+ }
3753
+ const callback = resolvers[schema.type];
3754
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
3755
+ try {
3756
+ return callback(data, schema, options, strict);
3757
+ } catch (error) {
3758
+ if (!schema.meta.loose) throw error;
3759
+ return [schema.meta.default];
3760
+ }
3761
+ };
3762
+ Schema.from = function from(source) {
3763
+ if (isNullable(source)) return Schema.any();
3764
+ else if ([
3765
+ "string",
3766
+ "number",
3767
+ "boolean"
3768
+ ].includes(typeof source)) return Schema.const(source).required();
3769
+ else if (source[kSchema]) return source;
3770
+ else if (typeof source === "function") switch (source) {
3771
+ case String: return Schema.string().required();
3772
+ case Number: return Schema.number().required();
3773
+ case Boolean: return Schema.boolean().required();
3774
+ case Function: return Schema.function().required();
3775
+ default: return Schema.is(source).required();
3776
+ }
3777
+ else throw new TypeError(`cannot infer schema from ${source}`);
3778
+ };
3779
+ Schema.lazy = function lazy(builder) {
3780
+ const toJSON = () => {
3781
+ if (!schema.inner[kSchema]) {
3782
+ schema.inner = schema.builder();
3783
+ schema.inner.meta = {
3784
+ ...schema.meta,
3785
+ ...schema.inner.meta
3786
+ };
3787
+ }
3788
+ return schema.inner.toJSON();
3789
+ };
3790
+ const schema = new Schema({
3791
+ type: "lazy",
3792
+ builder,
3793
+ inner: { toJSON }
3794
+ });
3795
+ return schema;
3796
+ };
3797
+ Schema.natural = function natural() {
3798
+ return Schema.number().step(1).min(0);
3799
+ };
3800
+ Schema.percent = function percent() {
3801
+ return Schema.number().step(.01).min(0).max(1).role("slider");
3802
+ };
3803
+ Schema.date = function date() {
3804
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
3805
+ const date = new Date(value);
3806
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
3807
+ return date;
3808
+ }, true)]);
3809
+ };
3810
+ Schema.regExp = function regExp(flag = "") {
3811
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
3812
+ try {
3813
+ return new RegExp(value, flag);
3814
+ } catch (e) {
3815
+ throw new ValidationError(e.message, options);
3816
+ }
3817
+ }, true)]);
3818
+ };
3819
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
3820
+ return Schema.union([
3821
+ Schema.is(ArrayBuffer),
3822
+ Schema.is(SharedArrayBuffer),
3823
+ Schema.transform(Schema.any(), (value, options) => {
3824
+ if (Binary.isSource(value)) return Binary.fromSource(value);
3825
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
3826
+ }, true),
3827
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
3828
+ try {
3829
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
3830
+ } catch (e) {
3831
+ throw new ValidationError(e.message, options);
3832
+ }
3833
+ }, true)] : []
3834
+ ]);
3835
+ };
3836
+ Schema.extend("lazy", (data, schema, options, strict) => {
3837
+ if (!schema.inner[kSchema]) {
3838
+ schema.inner = schema.builder();
3839
+ schema.inner.meta = {
3840
+ ...schema.meta,
3841
+ ...schema.inner.meta
3842
+ };
3843
+ }
3844
+ return Schema.resolve(data, schema.inner, options, strict);
3845
+ });
3846
+ Schema.extend("any", (data) => {
3847
+ return [data];
3848
+ });
3849
+ Schema.extend("never", (data, _, options) => {
3850
+ throw new ValidationError(`expected nullable but got ${data}`, options);
3851
+ });
3852
+ Schema.extend("const", (data, { value }, options) => {
3853
+ if (deepEqual(data, value)) return [value];
3854
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
3855
+ });
3856
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
3857
+ const { max = Infinity, min = -Infinity } = meta;
3858
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
3859
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
3860
+ }
3861
+ Schema.extend("string", (data, { meta }, options) => {
3862
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
3863
+ if (meta.pattern) {
3864
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
3865
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
3866
+ }
3867
+ checkWithinRange(data.length, meta, "string length", options);
3868
+ return [data];
3869
+ });
3870
+ function decimalShift(data, digits) {
3871
+ const str = data.toString();
3872
+ if (str.includes("e")) return data * Math.pow(10, digits);
3873
+ const index = str.indexOf(".");
3874
+ if (index === -1) return data * Math.pow(10, digits);
3875
+ const frac = str.slice(index + 1);
3876
+ const integer = str.slice(0, index);
3877
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
3878
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
3879
+ }
3880
+ function isMultipleOf(data, min, step) {
3881
+ step = Math.abs(step);
3882
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
3883
+ const index = step.toString().indexOf(".");
3884
+ const digits = step.toString().slice(index + 1).length;
3885
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
3886
+ }
3887
+ Schema.extend("number", (data, { meta }, options) => {
3888
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
3889
+ checkWithinRange(data, meta, "number", options);
3890
+ const { step } = meta;
3891
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
3892
+ return [data];
3893
+ });
3894
+ Schema.extend("boolean", (data, _, options) => {
3895
+ if (typeof data === "boolean") return [data];
3896
+ throw new ValidationError(`expected boolean but got ${data}`, options);
3897
+ });
3898
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
3899
+ let value = 0, keys = [];
3900
+ if (typeof data === "number") {
3901
+ value = data;
3902
+ for (const key in bits) if (data & bits[key]) keys.push(key);
3903
+ } else if (Array.isArray(data)) {
3904
+ keys = data;
3905
+ for (const key of keys) {
3906
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
3907
+ if (key in bits) value |= bits[key];
3908
+ }
3909
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
3910
+ if (value === meta.default) return [value];
3911
+ return [value, keys];
3912
+ });
3913
+ Schema.extend("function", (data, _, options) => {
3914
+ if (typeof data === "function") return [data];
3915
+ throw new ValidationError(`expected function but got ${data}`, options);
3916
+ });
3917
+ Schema.extend("is", (data, { constructor }, options) => {
3918
+ if (typeof constructor === "function") {
3919
+ if (data instanceof constructor) return [data];
3920
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
3921
+ } else {
3922
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
3923
+ let prototype = Object.getPrototypeOf(data);
3924
+ while (prototype) {
3925
+ if (prototype.constructor?.name === constructor) return [data];
3926
+ prototype = Object.getPrototypeOf(prototype);
3927
+ }
3928
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
3929
+ }
3930
+ });
3931
+ function property(data, key, schema, options) {
3932
+ try {
3933
+ const [value, adapted] = Schema.resolve(data[key], schema, {
3934
+ ...options,
3935
+ path: [...options.path || [], key]
3936
+ });
3937
+ if (adapted !== void 0) data[key] = adapted;
3938
+ return value;
3939
+ } catch (e) {
3940
+ if (!options?.autofix) throw e;
3941
+ delete data[key];
3942
+ return schema.meta.default;
3943
+ }
3944
+ }
3945
+ Schema.extend("array", (data, { inner, meta }, options) => {
3946
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
3947
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
3948
+ return [data.map((_, index) => property(data, index, inner, options))];
3949
+ });
3950
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
3951
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
3952
+ const result = {};
3953
+ for (const key in data) {
3954
+ let rKey;
3955
+ try {
3956
+ rKey = Schema.resolve(key, sKey, options)[0];
3957
+ } catch (error) {
3958
+ if (strict) continue;
3959
+ throw error;
3960
+ }
3961
+ result[rKey] = property(data, key, inner, options);
3962
+ data[rKey] = data[key];
3963
+ if (key !== rKey) delete data[key];
3964
+ }
3965
+ return [result];
3966
+ });
3967
+ Schema.extend("tuple", (data, { list }, options, strict) => {
3968
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
3969
+ const result = list.map((inner, index) => property(data, index, inner, options));
3970
+ if (strict) return [result];
3971
+ result.push(...data.slice(list.length));
3972
+ return [result];
3973
+ });
3974
+ function merge(result, data) {
3975
+ for (const key in data) {
3976
+ if (key in result) continue;
3977
+ result[key] = data[key];
3978
+ }
3979
+ }
3980
+ Schema.extend("object", (data, { dict }, options, strict) => {
3981
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
3982
+ const result = {};
3983
+ for (const key in dict) {
3984
+ const value = property(data, key, dict[key], options);
3985
+ if (!isNullable(value) || key in data) result[key] = value;
3986
+ }
3987
+ if (!strict) merge(result, data);
3988
+ return [result];
3989
+ });
3990
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
3991
+ const messages = [];
3992
+ for (const inner of list) try {
3993
+ return Schema.resolve(data, inner, options, strict);
3994
+ } catch (error) {
3995
+ messages.push(error);
3996
+ }
3997
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
3998
+ });
3999
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
4000
+ if (!list.length) return [data];
4001
+ let result;
4002
+ for (const inner of list) {
4003
+ const value = Schema.resolve(data, inner, options, true)[0];
4004
+ if (isNullable(value)) continue;
4005
+ if (isNullable(result)) result = value;
4006
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
4007
+ else if (typeof value === "object") merge(result ??= {}, value);
4008
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
4009
+ }
4010
+ if (!strict && isPlainObject(data)) merge(result, data);
4011
+ return [result];
4012
+ });
4013
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
4014
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
4015
+ if (preserve) return [callback(result)];
4016
+ else return [callback(result), callback(adapted)];
4017
+ });
4018
+ const formatters = {};
4019
+ function defineMethod(name, keys, format) {
4020
+ formatters[name] = format;
4021
+ Object.assign(Schema, { [name](...args) {
4022
+ const schema = new Schema({ type: name });
4023
+ keys.forEach((key, index) => {
4024
+ switch (key) {
4025
+ case "sKey":
4026
+ schema.sKey = args[index] ?? Schema.string();
4027
+ break;
4028
+ case "inner":
4029
+ schema.inner = Schema.from(args[index]);
4030
+ break;
4031
+ case "list":
4032
+ schema.list = args[index].map(Schema.from);
4033
+ break;
4034
+ case "dict":
4035
+ schema.dict = mapValues(args[index], Schema.from);
4036
+ break;
4037
+ case "bits":
4038
+ schema.bits = {};
4039
+ for (const key in args[index]) {
4040
+ if (typeof args[index][key] !== "number") continue;
4041
+ schema.bits[key] = args[index][key];
4042
+ }
4043
+ break;
4044
+ case "callback": {
4045
+ const callback = schema.callback = args[index];
4046
+ callback["toJSON"] ||= () => callback.toString();
4047
+ break;
4048
+ }
4049
+ case "constructor": {
4050
+ const constructor = schema.constructor = args[index];
4051
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
4052
+ break;
4053
+ }
4054
+ default: schema[key] = args[index];
4055
+ }
4056
+ });
4057
+ if (name === "object" || name === "dict") schema.meta.default = {};
4058
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
4059
+ else if (name === "bitset") schema.meta.default = 0;
4060
+ return schema;
4061
+ } });
4062
+ }
4063
+ defineMethod("is", ["constructor"], ({ constructor }) => {
4064
+ if (typeof constructor === "function") return constructor.name;
4065
+ else return constructor;
4066
+ });
4067
+ defineMethod("any", [], () => "any");
4068
+ defineMethod("never", [], () => "never");
4069
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
4070
+ defineMethod("string", [], () => "string");
4071
+ defineMethod("number", [], () => "number");
4072
+ defineMethod("boolean", [], () => "boolean");
4073
+ defineMethod("bitset", ["bits"], () => "bitset");
4074
+ defineMethod("function", [], () => "function");
4075
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
4076
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
4077
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
4078
+ defineMethod("object", ["dict"], ({ dict }) => {
4079
+ if (Object.keys(dict).length === 0) return "{}";
4080
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
4081
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
4082
+ }).join(", ")} }`;
4083
+ });
4084
+ defineMethod("union", ["list"], ({ list }, inline) => {
4085
+ const result = list.map(({ toString: format }) => format()).join(" | ");
4086
+ return inline ? `(${result})` : result;
4087
+ });
4088
+ defineMethod("intersect", ["list"], ({ list }) => {
4089
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
4090
+ });
4091
+ defineMethod("transform", [
4092
+ "inner",
4093
+ "callback",
4094
+ "preserve"
4095
+ ], ({ inner }, isInner) => inner.toString(isInner));
4096
+ //#endregion
4097
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.1.5-rc.1_@deepseek-ai+cordis@4.0.2/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
4098
+ /** Largest delay Node schedules without clamping it to one millisecond. */
4099
+ const MAX_TIMER_DELAY_MS = 2147483647;
4100
+ //#endregion
4101
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.1.5-rc.1_@deepseek-ai+cordis@4.0.2/node_modules/@deepseek-ai/dsh-llm/lib/index.js
4102
+ /**
4103
+ * Detach and deep-freeze a message whose identity already exists.
4104
+ * @param message - complete message, including its stable identity.
4105
+ * @returns an immutable snapshot that preserves the identity.
4106
+ */
4107
+ function freezeMessage(message) {
4108
+ return deepFreeze(structuredClone(message));
4109
+ }
4110
+ /**
4111
+ * Create one identified message and freeze it before publication.
4112
+ * @param input - complete role, content, and source for a new message.
4113
+ * @returns an immutable message with a fresh stable identity.
4114
+ */
4115
+ function createMessage(input) {
4116
+ return freezeMessage({
4117
+ ...input,
4118
+ id: brandString(randomUUID())
4119
+ });
4120
+ }
4121
+ /**
4122
+ * Create one identified user-role message and freeze it before publication.
4123
+ * @param input - complete content and source for a new user message.
4124
+ * @returns an immutable user message with a fresh stable identity.
4125
+ */
4126
+ function createUserMessage(input) {
4127
+ return createMessage({
4128
+ ...input,
4129
+ role: "user"
4130
+ });
4131
+ }
4132
+ /**
4133
+ * Harness error base with a stable machine-routable code and chained cause.
4134
+ * Package errors extend it so tool results and replay can retain failure class.
4135
+ * @module @deepseek-ai/dsh-llm/error
4136
+ */
4137
+ /**
4138
+ * Base class for all harness errors. Carries a `code` (stable, programmatic —
4139
+ * e.g. `NO_ADAPTER`, `INVALID_ARGS`, `INVARIANT`) distinct from the
4140
+ * human-readable `message`, and supports `cause` chaining via the standard
4141
+ * `ErrorOptions`. `name` defaults to the subclass constructor name.
4142
+ */
4143
+ var HarnessError = class extends Error {
4144
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
4145
+ code;
4146
+ constructor(message, code, options) {
4147
+ super(message, options);
4148
+ this.code = code;
4149
+ this.name = new.target.name;
4150
+ }
4151
+ };
4152
+ /**
4153
+ * Canonical provider-neutral code for a response that completed normally but
4154
+ * carried no content blocks at all. Providers occasionally emit a degenerate
4155
+ * completion (a terminal stop with zero output); adapters classify it as this
4156
+ * failure instead of yielding an empty assistant message, because an empty
4157
+ * message silently ends the turn with nothing for the user or the loop to act
4158
+ * on. The attempt produced nothing durable, so retry policy treats it as safe
4159
+ * to repeat.
4160
+ */
4161
+ const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
4162
+ new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` + String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`, "i");
4163
+ new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?` + String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?` + String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`, "i");
4164
+ new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}` + String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}` + String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`, "i");
4165
+ /**
4166
+ * Provider-owned request-retry policy configuration and resolution.
4167
+ *
4168
+ * Adapters expose one resolved policy per registered provider route; the
4169
+ * optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
4170
+ *
4171
+ * @module @deepseek-ai/dsh-llm/retry-policy
4172
+ */
4173
+ const DEFAULT_MAX_RETRIES = 5;
4174
+ const DEFAULT_INITIAL_DELAY_MS = 500;
4175
+ const DEFAULT_MAX_DELAY_MS = 1e4;
4176
+ const DEFAULT_JITTER_RATIO = .1;
4177
+ const DEFAULT_RETRYABLE_CODES = Object.freeze([
4178
+ EMPTY_RESPONSE_CODE,
4179
+ "RATE_LIMIT",
4180
+ "SERVER",
4181
+ "TIMEOUT",
4182
+ "TRANSPORT"
4183
+ ]);
4184
+ const backoffSchema = Schema.object({
4185
+ initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
4186
+ maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
4187
+ jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
4188
+ });
4189
+ const normalPolicySchema = Schema.object({
4190
+ mode: Schema.const("normal").required(),
4191
+ maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
4192
+ retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
4193
+ backoff: backoffSchema
4194
+ });
4195
+ const alwaysPolicySchema = Schema.object({
4196
+ mode: Schema.const("always").required(),
4197
+ backoff: backoffSchema
4198
+ });
4199
+ Schema.union([normalPolicySchema, alwaysPolicySchema]);
4200
+ const NORMAL_POLICY_KEYS = /* @__PURE__ */ new Set([
4201
+ "mode",
4202
+ "maxRetries",
4203
+ "retryableCodes",
4204
+ "backoff"
4205
+ ]);
4206
+ const ALWAYS_POLICY_KEYS = /* @__PURE__ */ new Set([
4207
+ "mode",
4208
+ "maxRetries",
4209
+ "retryableCodes",
4210
+ "backoff"
4211
+ ]);
4212
+ const BACKOFF_KEYS = /* @__PURE__ */ new Set([
4213
+ "initialDelayMs",
4214
+ "maxDelayMs",
4215
+ "jitterRatio"
4216
+ ]);
4217
+ function validateKeys(value, allowed, path) {
4218
+ for (const key of Object.keys(value)) if (!allowed.has(key)) throw new Error(`${path}: unknown key "${key}"`);
4219
+ }
4220
+ function resolveBackoff(config, path) {
4221
+ if (config !== void 0) validateKeys(config, BACKOFF_KEYS, path);
4222
+ const initialDelayMs = config?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
4223
+ const maxDelayMs = config?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
4224
+ const jitterRatio = config?.jitterRatio ?? DEFAULT_JITTER_RATIO;
4225
+ if (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > 2147483647) throw new Error(`${path}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4226
+ if (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > 2147483647) throw new Error(`${path}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4227
+ if (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
4228
+ if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) throw new Error(`${path}.jitterRatio must be between 0 and 1`);
4229
+ return Object.freeze({
4230
+ initialDelayMs,
4231
+ maxDelayMs,
4232
+ jitterRatio
4233
+ });
4234
+ }
4235
+ /**
4236
+ * Validate, default, and detach one provider-owned retry policy.
4237
+ * @param config - optional provider configuration; omission selects normal defaults.
4238
+ * @param path - diagnostic path naming the provider config that owns the value.
4239
+ * @returns an immutable policy safe to capture in provider registration state.
4240
+ */
4241
+ function resolveRetryPolicy(config, path) {
4242
+ if (config === void 0) return Object.freeze({
4243
+ mode: "normal",
4244
+ maxRetries: DEFAULT_MAX_RETRIES,
4245
+ retryableCodes: DEFAULT_RETRYABLE_CODES,
4246
+ ...resolveBackoff(void 0, `${path}.backoff`)
4247
+ });
4248
+ switch (config.mode) {
4249
+ case "normal": {
4250
+ validateKeys(config, NORMAL_POLICY_KEYS, path);
4251
+ const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
4252
+ const retryableCodes = config.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];
4253
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) throw new Error(`${path}.maxRetries must be a non-negative safe integer`);
4254
+ if (retryableCodes.length === 0) throw new Error(`${path}.retryableCodes must not be empty`);
4255
+ if (retryableCodes.some((code) => typeof code !== "string" || code.length === 0)) throw new Error(`${path}.retryableCodes must contain only non-empty strings`);
4256
+ if (new Set(retryableCodes).size !== retryableCodes.length) throw new Error(`${path}.retryableCodes must not contain duplicates`);
4257
+ return Object.freeze({
4258
+ mode: "normal",
4259
+ maxRetries,
4260
+ retryableCodes: Object.freeze([...retryableCodes]),
4261
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
4262
+ });
4263
+ }
4264
+ case "always":
4265
+ validateKeys(config, ALWAYS_POLICY_KEYS, path);
4266
+ return Object.freeze({
4267
+ mode: "always",
4268
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
4269
+ });
4270
+ default: throw new Error(`${path}.mode must be "normal" or "always"`);
4271
+ }
4272
+ }
4273
+ /**
4274
+ * Field-wise equality over {@link LlmCallConfig} — the comparison a caller
4275
+ * runs to decide whether a proposed configuration is a real change (worth a
4276
+ * logged header snapshot) or the held one restated.
4277
+ * @param a - one configuration.
4278
+ * @param b - the other.
4279
+ * @returns whether every field (including the `stop` list, element-wise) matches.
4280
+ */
4281
+ function callConfigEquals(a, b) {
4282
+ if (a.provider !== b.provider || a.model !== b.model || a.reasoningEffort !== b.reasoningEffort || a.temperature !== b.temperature || a.maxTokens !== b.maxTokens) return false;
4283
+ if (a.stop === void 0 || b.stop === void 0) return a.stop === b.stop;
4284
+ return a.stop.length === b.stop.length && a.stop.every((s, i) => s === b.stop?.[i]);
4285
+ }
4286
+ /**
4287
+ * Normalization for values thrown by a final LLM adapter boundary.
4288
+ *
4289
+ * @module @deepseek-ai/dsh-llm/adapter-failure
4290
+ */
4291
+ /**
4292
+ * Detach serializable provider facts from a value thrown by an adapter.
4293
+ * @param value - arbitrary value thrown during adapter dispatch or iteration.
4294
+ * @returns immutable provider-neutral facts suitable for a terminal finish chunk.
4295
+ * @internal
4296
+ */
4297
+ function normalizeLlmFailure(value) {
4298
+ const error = value instanceof Error ? value : new HarnessError(thrownMessage(value), "UNKNOWN", { cause: value });
4299
+ const carried = ownFailureSnapshot(error);
4300
+ if (carried !== void 0 && carried.code === ownErrorCode(error)) return carried;
4301
+ return Object.freeze({
4302
+ message: errorMessage(error),
4303
+ code: harnessErrorCode(error)
4304
+ });
4305
+ }
4306
+ /** Render a non-Error throw without letting hostile coercion escape normalization. */
4307
+ function thrownMessage(value) {
4308
+ try {
4309
+ const message = String(value);
4310
+ return message.length > 0 ? message : "LLM adapter failed";
4311
+ } catch (_hostileThrownValue) {
4312
+ return "LLM adapter failed";
4313
+ }
4314
+ }
4315
+ /** Read a foreign error's own data-backed `code` without invoking accessors. */
4316
+ function ownErrorCode(error) {
4317
+ try {
4318
+ const descriptor = Object.getOwnPropertyDescriptor(error, "code");
4319
+ return descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0;
4320
+ } catch (_sdkPropertyTrap) {
4321
+ return;
4322
+ }
4323
+ }
4324
+ /** Snapshot an own data property without invoking an SDK-defined accessor. */
4325
+ function ownFailureSnapshot(error) {
4326
+ try {
4327
+ const descriptor = Object.getOwnPropertyDescriptor(error, "failure");
4328
+ return descriptor !== void 0 && "value" in descriptor ? failureSnapshot(descriptor.value) : void 0;
4329
+ } catch (_sdkPropertyTrap) {
4330
+ return;
4331
+ }
4332
+ }
4333
+ /** Validate and detach an arbitrary serializable failure payload. */
4334
+ function failureSnapshot(value) {
4335
+ if (typeof value !== "object" || value === null) return void 0;
4336
+ try {
4337
+ const candidate = value;
4338
+ const message = candidate.message;
4339
+ const code = candidate.code;
4340
+ const status = candidate.status;
4341
+ const providerRetryAfterMs = candidate.providerRetryAfterMs;
4342
+ const requestId = candidate.requestId;
4343
+ if (typeof message !== "string" || message.length === 0 || typeof code !== "string" || code.length === 0 || status !== void 0 && (!Number.isInteger(status) || status < 100 || status > 599) || providerRetryAfterMs !== void 0 && (!Number.isFinite(providerRetryAfterMs) || providerRetryAfterMs <= 0) || requestId !== void 0 && (typeof requestId !== "string" || requestId.length === 0)) return void 0;
4344
+ return Object.freeze({
4345
+ message,
4346
+ code,
4347
+ ...status === void 0 ? {} : { status },
4348
+ ...providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs },
4349
+ ...requestId === void 0 ? {} : { requestId }
4350
+ });
4351
+ } catch (_sdkFailureGetter) {
4352
+ return;
4353
+ }
4354
+ }
4355
+ /** Read an SDK error message without letting an accessor replace the primary failure. */
4356
+ function errorMessage(error) {
4357
+ try {
4358
+ const message = error.message;
4359
+ if (typeof message === "string" && message.length > 0) return message;
4360
+ } catch (_sdkMessageGetter) {}
4361
+ return "LLM adapter failed";
4362
+ }
4363
+ /** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */
4364
+ function harnessErrorCode(error) {
4365
+ return error instanceof HarnessError ? error.code : "UNKNOWN";
4366
+ }
4367
+ function quoted(value) {
4368
+ return JSON.stringify(value);
4369
+ }
4370
+ /**
4371
+ * Stable text shown to a model that cannot accept one durable image reference.
4372
+ * @param ref - durable normalized attachment omitted from the request.
4373
+ * @returns deterministic text-only placeholder.
4374
+ */
4375
+ function textOnlyImageText(ref) {
4376
+ return `[image omitted because this model accepts text only; attachment sha256:${String(ref.attachmentId).slice(7, 15)}]`;
4377
+ }
4378
+ /**
4379
+ * True when typed model content contains an image block, walking nested
4380
+ * tool-result content. This is the one recursive image walk shared by every
4381
+ * image policy (capability gating, text-only serialization, compaction
4382
+ * survey), so a consumer cannot silently diverge on nesting depth.
4383
+ * @param content - typed model content blocks.
4384
+ * @returns whether any nested block is an image.
4385
+ */
4386
+ function contentHasImage(content) {
4387
+ return content.some((block) => block.type === "image" || block.type === "tool-result" && contentHasImage(block.content));
4388
+ }
4389
+ /**
4390
+ * True when typed model content contains a file block, walking nested
4391
+ * tool-result content on the same recursion every file policy shares.
4392
+ * Reads current content on every call without retaining scan results.
4393
+ * @param content - typed model content blocks.
4394
+ * @returns whether any nested block is a file.
4395
+ */
4396
+ function contentHasFile(content) {
4397
+ for (const block of content) if (block.type === "file" || block.type === "tool-result" && contentHasFile(block.content)) return true;
4398
+ return false;
4399
+ }
4400
+ /**
4401
+ * Stable model-facing handle for one durable file reference: the address of
4402
+ * the verbatim stored copy and the instruction to read it on demand. This is
4403
+ * the only representation a provider ever receives for a file.
4404
+ * @param ref - durable verbatim file reference.
4405
+ * @param readonlyPath - execution-world path of the stored copy, when resolvable.
4406
+ * @returns deterministic handle text naming the file, its size, and its address.
4407
+ */
4408
+ function fileHandleText(ref, readonlyPath) {
4409
+ const digest = String(ref.attachmentId).slice(7, 15);
4410
+ const identity = `File ${quoted(ref.name)} (${ref.bytes} bytes, sha256:${digest})`;
4411
+ if (readonlyPath === void 0) return `[${identity} was uploaded, but the current execution environment cannot access a readable path. Report that limitation if its contents are needed; do not claim to have read it.]`;
4412
+ return `[${identity}: verbatim read-only copy saved at ${quoted(readonlyPath)}. Read that path with your file tools when its contents are needed; copy it to a writable location before modifying it. When delegating file work, include this saved path in the delegation prompt; only subagents sharing this execution environment can read it.]`;
4413
+ }
4414
+ /** Replace every file occurrence, including nested tool results, with handle text. */
4415
+ function replaceFilesWithHandles(blocks, resolvePath) {
4416
+ let next;
4417
+ for (const [index, block] of blocks.entries()) {
4418
+ if (block.type === "file") {
4419
+ next ??= blocks.slice(0, index);
4420
+ next.push({
4421
+ type: "text",
4422
+ text: fileHandleText(block.attachment, resolvePath(block.attachment))
4423
+ });
4424
+ continue;
4425
+ }
4426
+ if (block.type === "tool-result") {
4427
+ const content = replaceFilesWithHandles(block.content, resolvePath);
4428
+ if (content !== block.content) {
4429
+ next ??= blocks.slice(0, index);
4430
+ next.push({
4431
+ ...block,
4432
+ content
4433
+ });
4434
+ continue;
4435
+ }
4436
+ }
4437
+ next?.push(block);
4438
+ }
4439
+ return next ?? blocks;
4440
+ }
4441
+ /**
4442
+ * Project durable file history into deterministic handle text for every model
4443
+ * route. Unlike images, no provider receives file blocks natively, so this
4444
+ * projection is unconditional in request assembly.
4445
+ * @param messages - complete request history.
4446
+ * @param resolvePath - resolve one reference's current execution-world read path.
4447
+ * @returns the original list without files, otherwise shallow message copies with handle text.
4448
+ */
4449
+ function projectFilesToText(messages, resolvePath) {
4450
+ if (!messages.some((message) => contentHasFile(message.content))) return messages;
4451
+ return messages.map((message) => {
4452
+ const content = replaceFilesWithHandles(message.content, resolvePath);
4453
+ return content === message.content ? message : {
4454
+ ...message,
4455
+ content
4456
+ };
4457
+ });
4458
+ }
4459
+ /** Replace every image occurrence, including nested tool results, for a text-only model. */
4460
+ function replaceImagesForTextModel(blocks) {
4461
+ let next;
4462
+ for (const [index, block] of blocks.entries()) {
4463
+ if (block.type === "image") {
4464
+ next ??= blocks.slice(0, index);
4465
+ next.push({
4466
+ type: "text",
4467
+ text: textOnlyImageText(block.attachment)
4468
+ });
4469
+ continue;
4470
+ }
4471
+ if (block.type === "tool-result") {
4472
+ const content = replaceImagesForTextModel(block.content);
4473
+ if (content !== block.content) {
4474
+ next ??= blocks.slice(0, index);
4475
+ next.push({
4476
+ ...block,
4477
+ content
4478
+ });
4479
+ continue;
4480
+ }
4481
+ }
4482
+ next?.push(block);
4483
+ }
4484
+ return next ?? blocks;
4485
+ }
4486
+ /**
4487
+ * Project durable image history into deterministic text for an exact text-only model.
4488
+ * @param messages - complete request history.
4489
+ * @returns the original list without images, otherwise shallow message copies with stable placeholders.
4490
+ */
4491
+ function projectImagesForTextModel(messages) {
4492
+ if (!messages.some((message) => contentHasImage(message.content))) return messages;
4493
+ return messages.map((message) => {
4494
+ const content = replaceImagesForTextModel(message.content);
4495
+ return content === message.content ? message : {
4496
+ ...message,
4497
+ content
4498
+ };
4499
+ });
4500
+ }
4501
+ /**
4502
+ * Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping
4503
+ * adapters from drifting. See
4504
+ * `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.
4505
+ *
4506
+ * App-attribution vocabulary for provider requests.
4507
+ * @module @deepseek-ai/dsh-llm/attribution
4508
+ */
4509
+ const { version } = createRequire(import.meta.url)("../package.json");
4510
+ /**
4511
+ * LLM service: adapter registry with a waterfall-interceptable streaming call
4512
+ * API. Exports the `LlmRuntime` default, the abstract `LlmAdapter` for
4513
+ * provider backends, and `BlockAssembler` for chunk assembly.
4514
+ *
4515
+ * @module @deepseek-ai/dsh-llm
4516
+ */
4517
+ var __runInitializers = function(thisArg, initializers, value) {
4518
+ var useValue = arguments.length > 2;
4519
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
4520
+ return useValue ? value : void 0;
4521
+ };
4522
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
4523
+ function accept(f) {
4524
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
4525
+ return f;
4526
+ }
4527
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
4528
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
4529
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
4530
+ var _, done = false;
4531
+ for (var i = decorators.length - 1; i >= 0; i--) {
4532
+ var context = {};
4533
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
4534
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
4535
+ context.addInitializer = function(f) {
4536
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
4537
+ extraInitializers.push(accept(f || null));
4538
+ };
4539
+ var result = (0, decorators[i])(kind === "accessor" ? {
4540
+ get: descriptor.get,
4541
+ set: descriptor.set
4542
+ } : descriptor[key], context);
4543
+ if (kind === "accessor") {
4544
+ if (result === void 0) continue;
4545
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
4546
+ if (_ = accept(result.get)) descriptor.get = _;
4547
+ if (_ = accept(result.set)) descriptor.set = _;
4548
+ if (_ = accept(result.init)) initializers.unshift(_);
4549
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
4550
+ else descriptor[key] = _;
4551
+ }
4552
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
4553
+ done = true;
4554
+ };
4555
+ /**
4556
+ * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
4557
+ * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
4558
+ */
4559
+ var LlmError = class extends HarnessError {
4560
+ /** Serializable facts retained beside this live Error. */
4561
+ failure;
4562
+ /**
4563
+ * @param message - non-empty human-readable failure summary.
4564
+ * @param code - non-empty stable provider-neutral machine code.
4565
+ * @param options - optional cause and validated serializable provider facts.
4566
+ */
4567
+ constructor(message, code, options) {
4568
+ if (typeof message !== "string" || message.length === 0) throw new Error("LlmError message must be a non-empty string");
4569
+ if (typeof code !== "string" || code.length === 0) throw new Error("LlmError code must be a non-empty string");
4570
+ if (options?.status !== void 0 && (!Number.isInteger(options.status) || options.status < 100 || options.status > 599)) throw new Error("LlmError status must be an integer from 100 through 599");
4571
+ if (options?.providerRetryAfterMs !== void 0 && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) throw new Error("LlmError providerRetryAfterMs must be a positive finite number");
4572
+ if (options?.requestId !== void 0 && (typeof options.requestId !== "string" || options.requestId.length === 0)) throw new Error("LlmError requestId must be a non-empty string");
4573
+ super(message, code, options);
4574
+ this.name = "LlmError";
4575
+ this.failure = Object.freeze({
4576
+ message,
4577
+ code,
4578
+ ...options?.status === void 0 ? {} : { status: options.status },
4579
+ ...options?.providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs: options.providerRetryAfterMs },
4580
+ ...options?.requestId === void 0 ? {} : { requestId: options.requestId }
4581
+ });
4582
+ }
4583
+ };
4584
+ (() => {
4585
+ let _classSuper = TypertRemoteService;
4586
+ let _instanceExtraInitializers = [];
4587
+ let _listProviders_decorators;
4588
+ let _listConfigurableProviders_decorators;
4589
+ let _remoteDiscoverModels_decorators;
4590
+ return class LlmRuntime extends _classSuper {
4591
+ static {
4592
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
4593
+ _listProviders_decorators = [Remote];
4594
+ _listConfigurableProviders_decorators = [Remote];
4595
+ _remoteDiscoverModels_decorators = [Remote("discoverModels")];
4596
+ __esDecorate(this, null, _listProviders_decorators, {
4597
+ kind: "method",
4598
+ name: "listProviders",
4599
+ static: false,
4600
+ private: false,
4601
+ access: {
4602
+ has: (obj) => "listProviders" in obj,
4603
+ get: (obj) => obj.listProviders
4604
+ },
4605
+ metadata: _metadata
4606
+ }, null, _instanceExtraInitializers);
4607
+ __esDecorate(this, null, _listConfigurableProviders_decorators, {
4608
+ kind: "method",
4609
+ name: "listConfigurableProviders",
4610
+ static: false,
4611
+ private: false,
4612
+ access: {
4613
+ has: (obj) => "listConfigurableProviders" in obj,
4614
+ get: (obj) => obj.listConfigurableProviders
4615
+ },
4616
+ metadata: _metadata
4617
+ }, null, _instanceExtraInitializers);
4618
+ __esDecorate(this, null, _remoteDiscoverModels_decorators, {
4619
+ kind: "method",
4620
+ name: "remoteDiscoverModels",
4621
+ static: false,
4622
+ private: false,
4623
+ access: {
4624
+ has: (obj) => "remoteDiscoverModels" in obj,
4625
+ get: (obj) => obj.remoteDiscoverModels
4626
+ },
4627
+ metadata: _metadata
4628
+ }, null, _instanceExtraInitializers);
4629
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
4630
+ enumerable: true,
4631
+ configurable: true,
4632
+ writable: true,
4633
+ value: _metadata
4634
+ });
4635
+ }
4636
+ adapters = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map());
4637
+ directory = /* @__PURE__ */ new Map();
4638
+ discoveries = /* @__PURE__ */ new Map();
4639
+ constructor(ctx) {
4640
+ super(ctx, "llm");
4641
+ }
4642
+ /** Notify topology observers without letting one broken listener veto the commit. */
4643
+ emitAdaptersUpdated() {
4644
+ let invariantFailure;
4645
+ for (const listener of this.ctx.events.dispatch("emit", ["llm/adapters-updated"])) try {
4646
+ const returned = listener();
4647
+ if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
4648
+ this.warnAdaptersListenerFailure(error);
4649
+ });
4650
+ } catch (error) {
4651
+ if (error?.code === "INVARIANT") {
4652
+ invariantFailure ??= error;
4653
+ continue;
4654
+ }
4655
+ this.warnAdaptersListenerFailure(error);
4656
+ }
4657
+ if (invariantFailure !== void 0) throw invariantFailure;
4658
+ }
4659
+ /** Contained-listener diagnostic shared by the sync and async failure paths. */
4660
+ warnAdaptersListenerFailure(error) {
4661
+ this.ctx.logger.warn("llm: an llm/adapters-updated listener failed");
4662
+ this.ctx.logger.warn(error);
4663
+ }
4664
+ /**
4665
+ * Register an adapter for the given provider routes. Throws `LlmError` with code
4666
+ * `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).
4667
+ * Disposed with the fiber.
4668
+ * @param providers - every provider route this adapter should serve.
4669
+ * @param adapter - the adapter that streams calls for those providers.
4670
+ * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.
4671
+ */
4672
+ registerAdapter(providers, adapter) {
4673
+ const owned = /* @__PURE__ */ new Set();
4674
+ let released = false;
4675
+ const dispose = this.ctx.effect(function* () {
4676
+ if (providers.length === 0) throw new LlmError("an adapter must register at least one provider", "INVALID_ADAPTER");
4677
+ this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned));
4678
+ yield () => {
4679
+ released = true;
4680
+ for (const provider of owned) this.adapters.delete(provider);
4681
+ owned.clear();
4682
+ this.emitAdaptersUpdated();
4683
+ };
4684
+ }.bind(this), "llm.registerAdapter()");
4685
+ const handle = (() => void dispose());
4686
+ handle.replace = (next) => {
4687
+ if (released) throw new LlmError("a disposed adapter registration cannot replace its routes", "REGISTRATION_DISPOSED");
4688
+ this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned));
4689
+ };
4690
+ return handle;
4691
+ }
4692
+ /**
4693
+ * Validate one candidate route set for `adapter`, treating routes this
4694
+ * registration already holds as available. Nothing is mutated: a rejected
4695
+ * candidate leaves the registry exactly as it was.
4696
+ */
4697
+ prepareRoutes(providers, adapter, owned) {
4698
+ const unique = /* @__PURE__ */ new Set();
4699
+ const registrations = [];
4700
+ for (const provider of providers) {
4701
+ if (provider.length === 0) throw new LlmError("adapter provider names must be non-empty", "INVALID_ADAPTER");
4702
+ if (unique.has(provider) || this.adapters.has(provider) && !owned.has(provider)) throw new LlmError(`an adapter for provider "${provider}" is already registered`, "DUPLICATE_ADAPTER");
4703
+ const info = adapter.providerInfo(provider);
4704
+ if (typeof info.id !== "string" || info.id !== provider || typeof info.name !== "string" || info.name.length === 0) throw new LlmError(`adapter metadata for provider "${provider}" must preserve its id and have a non-empty name`, "INVALID_ADAPTER");
4705
+ unique.add(provider);
4706
+ const retryPolicy = adapter.providerRetryPolicy(provider) ?? resolveRetryPolicy(void 0, `llm: provider "${provider}" retryPolicy`);
4707
+ registrations.push({
4708
+ adapter,
4709
+ provider: {
4710
+ id: info.id,
4711
+ name: info.name
4712
+ },
4713
+ retryPolicy
4714
+ });
4715
+ }
4716
+ return registrations;
4717
+ }
4718
+ /**
4719
+ * Swap this registration's routes for the prepared ones in one synchronous
4720
+ * section, so no observer can see the registry between the release and the
4721
+ * re-registration. The route set's one mutation point is also where
4722
+ * `llm/adapters-updated` is published, so a `replace` announces itself
4723
+ * exactly like a first registration.
4724
+ */
4725
+ commitRoutes(owned, registrations) {
4726
+ for (const provider of owned) this.adapters.delete(provider);
4727
+ owned.clear();
4728
+ for (const registration of registrations) {
4729
+ this.adapters.set(registration.provider.id, registration);
4730
+ owned.add(registration.provider.id);
4731
+ }
4732
+ this.emitAdaptersUpdated();
4733
+ }
4734
+ /**
4735
+ * Describe provider routes with a registered adapter.
4736
+ * @returns detached provider metadata in registration order.
4737
+ */
4738
+ listProviders() {
4739
+ return [...this.adapters.values()].map(({ provider }) => ({ ...provider }));
4740
+ }
4741
+ /**
4742
+ * Declare provider routes an adapter plugin can activate through
4743
+ * configuration. Registration is all-or-nothing: an empty list, invalid
4744
+ * entry, or a provider already declared by any registration throws
4745
+ * `LlmError` without registering the rest. Disposed with the fiber.
4746
+ * @param entries - every configurable provider this plugin owns.
4747
+ * @returns a handle that withdraws all of them, and can atomically replace them.
4748
+ */
4749
+ registerConfigurableProviders(entries) {
4750
+ let held = [];
4751
+ let disposed = false;
4752
+ /**
4753
+ * Validate a candidate set in full against everything this registration
4754
+ * does not already hold, then publish it. Nothing is written until the
4755
+ * whole set passes, so a refused candidate leaves the current entries in
4756
+ * place — the property that makes `replace` a swap rather than a
4757
+ * delete-then-add that can strand the directory empty.
4758
+ */
4759
+ const commit = (candidates) => {
4760
+ const detached = [];
4761
+ const own = new Set(held.map((entry) => entry.provider));
4762
+ for (const entry of candidates) {
4763
+ if (entry.provider.length === 0 || entry.displayName.length === 0 || entry.settingsNs.length === 0) throw new LlmError("configurable providers need a non-empty provider, displayName, and settingsNs", "INVALID_DIRECTORY");
4764
+ if (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider "${entry.provider}" has an empty settingsPath segment`, "INVALID_DIRECTORY");
4765
+ if (this.directory.has(entry.provider) && !own.has(entry.provider) || detached.some((seen) => seen.provider === entry.provider)) throw new LlmError(`configurable provider "${entry.provider}" is already declared`, "DUPLICATE_DIRECTORY");
4766
+ detached.push({
4767
+ ...entry,
4768
+ settingsPath: [...entry.settingsPath]
4769
+ });
4770
+ }
4771
+ for (const entry of held) this.directory.delete(entry.provider);
4772
+ for (const entry of detached) this.directory.set(entry.provider, entry);
4773
+ held = detached;
4774
+ this.emitAdaptersUpdated();
4775
+ };
4776
+ const dispose = this.ctx.effect(function* () {
4777
+ if (entries.length === 0) throw new LlmError("a configurable-provider registration must declare at least one provider", "INVALID_DIRECTORY");
4778
+ commit(entries);
4779
+ yield () => {
4780
+ disposed = true;
4781
+ for (const entry of held) this.directory.delete(entry.provider);
4782
+ held = [];
4783
+ this.emitAdaptersUpdated();
4784
+ };
4785
+ }.bind(this), "llm.registerConfigurableProviders()");
4786
+ const handle = (() => void dispose());
4787
+ handle.replace = (next) => {
4788
+ if (disposed) throw new LlmError("this configurable-provider registration was disposed", "REGISTRATION_DISPOSED");
4789
+ commit(next);
4790
+ };
4791
+ return handle;
4792
+ }
4793
+ /**
4794
+ * List every declared configurable provider, registered or dormant.
4795
+ * @returns detached directory entries in declaration order.
4796
+ */
4797
+ listConfigurableProviders() {
4798
+ return [...this.directory.values()].map((entry) => ({
4799
+ ...entry,
4800
+ settingsPath: [...entry.settingsPath]
4801
+ }));
4802
+ }
4803
+ /**
4804
+ * Offer to interrogate provider endpoints on behalf of the settings
4805
+ * namespace this plugin owns. The namespace is the key because that is what
4806
+ * a configuration surface already holds from the configurable-provider
4807
+ * directory, and because a provider being *added* has no route to name yet.
4808
+ * Disposed with the fiber.
4809
+ * @param settingsNs - the namespace whose profiles this discovery serves.
4810
+ * @param discover - interrogates one endpoint and must honor the supplied signal.
4811
+ * @returns the disposer that withdraws the offer.
4812
+ */
4813
+ registerModelDiscovery(settingsNs, discover) {
4814
+ const dispose = this.ctx.effect(function* () {
4815
+ if (settingsNs.length === 0) throw new LlmError("model discovery needs a non-empty settings namespace", "INVALID_DISCOVERY");
4816
+ if (this.discoveries.has(settingsNs)) throw new LlmError(`model discovery for "${settingsNs}" is already registered`, "DUPLICATE_DISCOVERY");
4817
+ this.discoveries.set(settingsNs, discover);
4818
+ yield () => {
4819
+ this.discoveries.delete(settingsNs);
4820
+ };
4821
+ }.bind(this), "llm.registerModelDiscovery()");
4822
+ return () => void dispose();
4823
+ }
4824
+ /**
4825
+ * Interrogate one provider endpoint for the models it advertises. The
4826
+ * request describes a draft, not a stored route, so nothing here reads or
4827
+ * writes settings or credentials — the caller owns both, and the reply is
4828
+ * candidate metadata a surface may offer for adoption.
4829
+ * @param settingsNs - namespace whose registered discovery serves this draft.
4830
+ * @param request - the endpoint, protocol, and one-shot credential to use.
4831
+ * @param signal - caller cancellation.
4832
+ * @returns the advertised models, deduplicated in endpoint order.
4833
+ */
4834
+ async discoverModels(settingsNs, request, signal) {
4835
+ const discover = this.discoveries.get(settingsNs);
4836
+ if (discover === void 0) throw new LlmError(`no model discovery is registered for "${settingsNs}"`, "NO_DISCOVERY");
4837
+ if ((request.provider ?? "").length === 0 && (request.baseURL ?? "").length === 0) throw new LlmError("model discovery needs a provider route or a baseURL", "INVALID_DISCOVERY");
4838
+ const discovered = signal === void 0 ? await discover(request) : await discover(request, signal);
4839
+ const seen = /* @__PURE__ */ new Set();
4840
+ const models = [];
4841
+ for (const model of discovered) {
4842
+ if (typeof model.id !== "string" || model.id.length === 0 || seen.has(model.id)) continue;
4843
+ seen.add(model.id);
4844
+ models.push({
4845
+ id: model.id,
4846
+ ...model.name === void 0 ? {} : { name: model.name },
4847
+ ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
4848
+ ...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens }
4849
+ });
4850
+ }
4851
+ return models;
4852
+ }
4853
+ /**
4854
+ * Remote adapter for one draft provider interrogation.
4855
+ * @param settingsNs - namespace whose registered discovery serves this draft.
4856
+ * @param request - endpoint, protocol, and one-shot credential to use.
4857
+ * @param signal - caller cancellation supplied by the Remote carrier.
4858
+ * @returns advertised models in endpoint order.
4859
+ * @throws RemoteError with `llm/model-discovery-rejected` when discovery refuses or fails.
4860
+ */
4861
+ async remoteDiscoverModels(settingsNs, request, signal) {
4862
+ try {
4863
+ return await this.discoverModels(settingsNs, request, signal);
4864
+ } catch (error) {
4865
+ throw new RemoteError("llm/model-discovery-rejected", error instanceof Error ? error.message : String(error), {
4866
+ settingsNs,
4867
+ ...request.baseURL === void 0 ? {} : { baseURL: request.baseURL }
4868
+ }, { cause: error });
4869
+ }
4870
+ }
4871
+ /**
4872
+ * Resolve the retry policy captured when one provider route was registered.
4873
+ * @param provider - registered provider route to inspect.
4874
+ * @returns the provider-owned policy, with normal defaults already resolved.
4875
+ */
4876
+ providerRetryPolicy(provider) {
4877
+ return this.registration(provider).retryPolicy;
4878
+ }
4879
+ /**
4880
+ * Resolve provider-side request-image pricing for one exact route, or
4881
+ * `undefined` when the provider is unregistered or declares none. Unknown
4882
+ * providers degrade to `undefined` rather than throwing because callers
4883
+ * price durable history whose route may no longer be mounted.
4884
+ * @param provider - provider route named by a request header.
4885
+ * @param model - exact model id named by the same header.
4886
+ * @returns the owning adapter's image pricing for the route, when declared.
4887
+ */
4888
+ imageRequestPricing(provider, model) {
4889
+ return this.adapters.get(provider)?.adapter.imageRequestPricing(provider, model);
4890
+ }
4891
+ /**
4892
+ * Resolve the exact text one durable file occurrence contributes to every
4893
+ * provider request in the current execution environment.
4894
+ * @param ref - durable verbatim file reference from model history.
4895
+ * @returns the same deterministic handle text used at adapter dispatch.
4896
+ */
4897
+ fileRequestText(ref) {
4898
+ return fileHandleText(ref, this.fileReadPath(ref));
4899
+ }
4900
+ /** Detach typed adapter-owned modality metadata. */
4901
+ detachedModalities(modalities) {
4902
+ return modalities === void 0 ? void 0 : [...modalities];
4903
+ }
4904
+ /**
4905
+ * Discover models advertised by one registered provider. Catalog membership
4906
+ * is advisory and never changes routing or request validation.
4907
+ * @param provider - registered provider route to inspect.
4908
+ * @returns detached model metadata in adapter-preferred order.
4909
+ */
4910
+ async listModels(provider) {
4911
+ const models = await this.registration(provider).adapter.listModels(provider);
4912
+ const seen = /* @__PURE__ */ new Set();
4913
+ return models.map((model) => {
4914
+ if (typeof model.provider !== "string" || model.provider !== provider || typeof model.id !== "string" || model.id.length === 0 || typeof model.name !== "string" || model.name.length === 0 || model.description !== void 0 && typeof model.description !== "string" || seen.has(model.id)) throw new LlmError(`adapter returned invalid or duplicate model metadata for provider "${provider}"`, "INVALID_CATALOG");
4915
+ seen.add(model.id);
4916
+ const inputModalities = this.detachedModalities(model.inputModalities);
4917
+ return {
4918
+ provider: model.provider,
4919
+ id: model.id,
4920
+ name: model.name,
4921
+ ...model.description === void 0 ? {} : { description: model.description },
4922
+ ...inputModalities === void 0 ? {} : { inputModalities }
4923
+ };
4924
+ });
4925
+ }
4926
+ /**
4927
+ * Resolve and validate all metadata from the adapter that owns one exact
4928
+ * route. The result is detached from adapter-owned objects; catalog
4929
+ * membership remains advisory and does not control request routing.
4930
+ * @param provider - registered provider route to inspect.
4931
+ * @param model - exact model id passed to the adapter.
4932
+ * @param signal - optional cancellation for adapter-owned asynchronous lookup.
4933
+ * @returns exact model identity plus available context and reasoning metadata.
4934
+ */
4935
+ async resolveModelInfo(provider, model, signal) {
4936
+ return this.resolveModelInfoFor(this.registration(provider), model, signal);
4937
+ }
4938
+ async resolveModelInfoFor(registration, model, signal) {
4939
+ const resolved = await registration.adapter.resolveModel(registration.provider.id, model, signal);
4940
+ return this.normalizeModelInfo(registration, model, resolved);
4941
+ }
4942
+ /** Validate and detach one adapter-returned exact model result. */
4943
+ normalizeModelInfo(registration, model, resolved) {
4944
+ const provider = registration.provider.id;
4945
+ if (typeof resolved.provider !== "string" || resolved.provider !== provider || typeof resolved.id !== "string" || resolved.id !== model || typeof resolved.name !== "string" || resolved.name.length === 0 || resolved.description !== void 0 && typeof resolved.description !== "string") throw new LlmError(`adapter returned invalid exact model metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_INFO");
4946
+ const context = resolved.context;
4947
+ if (context !== void 0 && (!Number.isInteger(context.contextWindow) || context.contextWindow <= 0)) throw new LlmError(`adapter returned invalid context metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_CONTEXT");
4948
+ const inputModalities = this.detachedModalities(resolved.inputModalities);
4949
+ const systemPromptUpdate = resolved.systemPromptUpdate;
4950
+ if (systemPromptUpdate !== void 0 && systemPromptUpdate !== "in-history") throw new LlmError(`adapter returned invalid system prompt update mode for provider "${provider}" model "${model}"`, "INVALID_MODEL_INFO");
4951
+ const defaultMaxTokens = resolved.defaultMaxTokens;
4952
+ if (defaultMaxTokens !== void 0 && (!Number.isSafeInteger(defaultMaxTokens) || defaultMaxTokens <= 0)) throw new LlmError(`adapter returned invalid default maxTokens for provider "${provider}" model "${model}"`, "INVALID_MODEL_MAX_TOKENS");
4953
+ const info = {
4954
+ provider,
4955
+ id: model,
4956
+ name: resolved.name,
4957
+ ...resolved.description === void 0 ? {} : { description: resolved.description },
4958
+ ...inputModalities === void 0 ? {} : { inputModalities },
4959
+ ...context === void 0 ? {} : { context: { contextWindow: context.contextWindow } },
4960
+ ...defaultMaxTokens === void 0 ? {} : { defaultMaxTokens },
4961
+ ...resolved.systemPromptUpdate === void 0 ? {} : { systemPromptUpdate: resolved.systemPromptUpdate }
4962
+ };
4963
+ const reasoning = resolved.reasoning;
4964
+ if (reasoning === void 0) return info;
4965
+ if (reasoning.efforts.length === 0) throw new LlmError(`adapter returned invalid reasoning metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
4966
+ const seen = /* @__PURE__ */ new Set();
4967
+ const efforts = reasoning.efforts.map((effort) => {
4968
+ if (typeof effort.id !== "string" || effort.id.length === 0 || typeof effort.name !== "string" || effort.name.length === 0 || effort.description !== void 0 && typeof effort.description !== "string" || seen.has(effort.id)) throw new LlmError(`adapter returned invalid or duplicate reasoning effort metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
4969
+ seen.add(effort.id);
4970
+ return {
4971
+ id: effort.id,
4972
+ name: effort.name,
4973
+ ...effort.description === void 0 ? {} : { description: effort.description }
4974
+ };
4975
+ });
4976
+ if (reasoning.defaultEffort !== void 0 && !seen.has(reasoning.defaultEffort)) throw new LlmError(`adapter returned an unknown default reasoning effort for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
4977
+ return {
4978
+ ...info,
4979
+ reasoning: {
4980
+ efforts,
4981
+ ...reasoning.defaultEffort === void 0 ? {} : { defaultEffort: reasoning.defaultEffort }
4982
+ }
4983
+ };
4984
+ }
4985
+ /**
4986
+ * Validate a conversation call config against its exact model capability and
4987
+ * materialize adapter-configured defaults. Unsupported explicit efforts
4988
+ * reject before provider I/O; no clamping or aliasing is performed. This
4989
+ * standalone query does not bind a later dispatch; use {@link prepareCall}
4990
+ * when logging and streaming must share one adapter registration.
4991
+ * @param config - provider/model route and optional request controls.
4992
+ * @param signal - optional cancellation for adapter-owned capability lookup.
4993
+ * @returns a detached config only when a default must be materialized.
4994
+ */
4995
+ async resolveCallConfig(config, signal) {
4996
+ return (await this.resolveCallFor(this.registration(config.provider), config, signal)).config;
4997
+ }
4998
+ async resolveCallFor(registration, config, signal) {
4999
+ const info = await this.resolveModelInfoFor(registration, config.model, signal);
5000
+ return this.resolveCallWithInfo(config, info);
5001
+ }
5002
+ /** Validate request controls against one already-bound exact model result. */
5003
+ resolveCallWithInfo(config, info) {
5004
+ const defaulted = config.maxTokens === void 0 && info.defaultMaxTokens !== void 0 ? {
5005
+ ...config,
5006
+ maxTokens: info.defaultMaxTokens
5007
+ } : config;
5008
+ const reasoning = info.reasoning;
5009
+ const requested = defaulted.reasoningEffort;
5010
+ let resolvedConfig = defaulted;
5011
+ if (reasoning === void 0) {
5012
+ if (requested !== void 0) throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${requested}"`, "UNSUPPORTED_REASONING_EFFORT");
5013
+ } else {
5014
+ const effective = requested ?? reasoning.defaultEffort;
5015
+ if (effective !== void 0) {
5016
+ if (!reasoning.efforts.some((effort) => effort.id === effective)) throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${effective}"`, "UNSUPPORTED_REASONING_EFFORT");
5017
+ if (requested !== effective) resolvedConfig = {
5018
+ ...defaulted,
5019
+ reasoningEffort: effective
5020
+ };
5021
+ }
5022
+ }
5023
+ return {
5024
+ config: resolvedConfig,
5025
+ ...info.context === void 0 ? {} : { context: info.context },
5026
+ modelInfo: info
5027
+ };
5028
+ }
5029
+ /**
5030
+ * Resolve one call under its current adapter registration. The returned
5031
+ * one-shot handle keeps that registration across header logging and dispatch,
5032
+ * so HMR cannot combine one adapter's capability result with another adapter.
5033
+ * @param config - provider/model route and optional request controls.
5034
+ * @param signal - optional cancellation for adapter-owned capability lookup.
5035
+ * @returns a prepared config and its registration-bound stream entry point.
5036
+ */
5037
+ async prepareCall(config, signal) {
5038
+ const registration = this.registration(config.provider);
5039
+ const adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal);
5040
+ const modelInfo = this.normalizeModelInfo(registration, config.model, adapterCall.model);
5041
+ const resolved = this.resolveCallWithInfo(config, modelInfo);
5042
+ const resolvedConfig = deepFreeze(structuredClone(resolved.config));
5043
+ const context = resolved.context === void 0 ? void 0 : deepFreeze(structuredClone(resolved.context));
5044
+ const adapterDefaults = deepFreeze({
5045
+ ...config.reasoningEffort === void 0 && resolvedConfig.reasoningEffort !== void 0 ? { reasoningEffort: true } : {},
5046
+ ...config.maxTokens === void 0 && resolvedConfig.maxTokens !== void 0 ? { maxTokens: true } : {}
5047
+ });
5048
+ let dispatched = false;
5049
+ return Object.freeze({
5050
+ config: resolvedConfig,
5051
+ retryPolicy: registration.retryPolicy,
5052
+ adapterDefaults,
5053
+ ...context === void 0 ? {} : { context },
5054
+ ...modelInfo.inputModalities === void 0 ? {} : { inputModalities: Object.freeze([...modelInfo.inputModalities]) },
5055
+ ...modelInfo.systemPromptUpdate === void 0 ? {} : { systemPromptUpdate: modelInfo.systemPromptUpdate },
5056
+ stream: (options) => {
5057
+ if (dispatched) throw new LlmError("a prepared LLM call can only be dispatched once", "INVALID_PREPARED_CALL");
5058
+ if (!callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
5059
+ dispatched = true;
5060
+ return this.streamWithRegistration(options, {
5061
+ registration,
5062
+ config: resolvedConfig,
5063
+ modelInfo,
5064
+ dispatch: (options) => adapterCall.stream(options)
5065
+ });
5066
+ }
5067
+ });
5068
+ }
5069
+ registration(provider) {
5070
+ const registration = this.adapters.get(provider);
5071
+ if (!registration) throw new LlmError(`no adapter registered for provider "${provider}"`, "NO_ADAPTER");
5072
+ return registration;
5073
+ }
5074
+ /** Remove replay state whose historical route is owned by another adapter. */
5075
+ forAdapter(options, adapter) {
5076
+ const messages = options.messages.map((message) => {
5077
+ const source = message.source;
5078
+ if (message.role !== "assistant" || source.kind !== "model" || source.replayState === void 0) return message;
5079
+ if (this.adapters.get(source.provider)?.adapter === adapter) return message;
5080
+ return freezeMessage({
5081
+ ...message,
5082
+ source: {
5083
+ kind: "model",
5084
+ provider: source.provider,
5085
+ model: source.model
5086
+ }
5087
+ });
5088
+ });
5089
+ if (messages.every((message, index) => message === options.messages[index])) return options;
5090
+ const filtered = {
5091
+ ...options,
5092
+ messages
5093
+ };
5094
+ return Object.isFrozen(options) ? deepFreeze(filtered) : filtered;
5095
+ }
5096
+ /**
5097
+ * Resolve the current execution-world read path of one durable file
5098
+ * reference through the mounted attachment and filesystem providers.
5099
+ */
5100
+ fileReadPath(ref) {
5101
+ let hostPath;
5102
+ try {
5103
+ hostPath = this.ctx.get("attachments")?.fileHostPath(ref);
5104
+ } catch {
5105
+ return;
5106
+ }
5107
+ if (hostPath === void 0) return void 0;
5108
+ return this.ctx.get("fs")?.processPathFromHostPath(hostPath);
5109
+ }
5110
+ /**
5111
+ * Final adapter boundary. Adapter selection, dispatch, iterator construction,
5112
+ * and iteration failures become one terminal failure chunk. Middleware and
5113
+ * downstream consumer failures remain thrown plugin or consumer errors.
5114
+ */
5115
+ async *adapterStream(options, prepared) {
5116
+ let iterator;
5117
+ try {
5118
+ const registration = prepared?.registration ?? this.registration(options.provider);
5119
+ const adapter = registration.adapter;
5120
+ let modelInfo;
5121
+ let resolvedConfig;
5122
+ let dispatch;
5123
+ if (prepared === void 0) {
5124
+ const adapterCall = await adapter.prepareCall(options.provider, options.model, options.signal);
5125
+ modelInfo = this.normalizeModelInfo(registration, options.model, adapterCall.model);
5126
+ resolvedConfig = this.resolveCallWithInfo(options, modelInfo).config;
5127
+ dispatch = (options) => adapterCall.stream(options);
5128
+ } else {
5129
+ modelInfo = prepared.modelInfo;
5130
+ resolvedConfig = prepared.config;
5131
+ dispatch = prepared.dispatch;
5132
+ }
5133
+ if (prepared !== void 0 && !callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
5134
+ const resolvedOptions = callConfigEquals(options, resolvedConfig) ? options : Object.isFrozen(options) ? deepFreeze({
5135
+ ...options,
5136
+ ...resolvedConfig
5137
+ }) : {
5138
+ ...options,
5139
+ ...resolvedConfig
5140
+ };
5141
+ let projectedMessages = resolvedOptions.messages;
5142
+ if (projectedMessages.some((message) => contentHasFile(message.content))) projectedMessages = projectFilesToText(projectedMessages, (ref) => this.fileReadPath(ref));
5143
+ if (modelInfo.inputModalities !== void 0 && !modelInfo.inputModalities.includes("image") && projectedMessages.some((message) => contentHasImage(message.content))) projectedMessages = projectImagesForTextModel(projectedMessages);
5144
+ const projectedOptions = projectedMessages === resolvedOptions.messages ? resolvedOptions : Object.isFrozen(resolvedOptions) ? deepFreeze({
5145
+ ...resolvedOptions,
5146
+ messages: projectedMessages
5147
+ }) : {
5148
+ ...resolvedOptions,
5149
+ messages: projectedMessages
5150
+ };
5151
+ iterator = dispatch(this.forAdapter(projectedOptions, adapter))[Symbol.asyncIterator]();
5152
+ } catch (error) {
5153
+ yield adapterFailureChunk(error, options.signal);
5154
+ return;
5155
+ }
5156
+ let completed = false;
5157
+ try {
5158
+ while (true) {
5159
+ let item;
5160
+ try {
5161
+ const next = await iterator.next();
5162
+ item = next.done ? { done: true } : {
5163
+ done: false,
5164
+ value: next.value
5165
+ };
5166
+ } catch (error) {
5167
+ completed = true;
5168
+ yield adapterFailureChunk(error, options.signal);
5169
+ return;
5170
+ }
5171
+ if (item.done) {
5172
+ completed = true;
5173
+ return;
5174
+ }
5175
+ yield item.value;
5176
+ }
5177
+ } finally {
5178
+ if (!completed) {
5179
+ const close = iterator.return?.bind(iterator);
5180
+ if (close) await close();
5181
+ }
5182
+ }
5183
+ }
5184
+ /**
5185
+ * Stream one model call as raw chunks (token-level deltas). Replay state is
5186
+ * retained only when the same adapter instance owns its historical provider
5187
+ * and the target provider. Final adapter selection remains fixed through
5188
+ * asynchronous exact-model resolution and dispatch. Adapter selection,
5189
+ * dispatch, and iteration failures become terminal `error` or `aborted`
5190
+ * finish chunks; middleware, nested-call, cleanup, and consumer failures
5191
+ * remain thrown.
5192
+ * @param options - the full request; `options.provider` selects the adapter.
5193
+ * @returns the chunk stream, possibly wrapped by `llm/stream` listeners.
5194
+ */
5195
+ stream(options) {
5196
+ return this.streamWithRegistration(options);
5197
+ }
5198
+ streamWithRegistration(options, prepared) {
5199
+ return this.ctx.waterfall(this, "llm/stream", options, () => this.adapterStream(options, prepared));
5200
+ }
5201
+ };
5202
+ })();
5203
+ /** Convert one adapter throw into the stream protocol's terminal outcome. */
5204
+ function adapterFailureChunk(error, signal) {
5205
+ const failure = normalizeLlmFailure(error);
5206
+ return {
5207
+ type: "finish",
5208
+ reason: signal?.aborted || failure.code === "ABORTED" ? {
5209
+ kind: "aborted",
5210
+ failure
5211
+ } : {
5212
+ kind: "error",
5213
+ failure
5214
+ }
5215
+ };
5216
+ }
5217
+ //#endregion
5218
+ //#region src/host-ai.ts
5219
+ /**
5220
+ * One-shot model parse behind the board's "parse pasted text" action
5221
+ * (issue #1540).
5222
+ *
5223
+ * The browser half never talks to a model: it posts the pasted text and the
5224
+ * route the user picked to the Host, which calls the injected `llm` service
5225
+ * once and answers with the three draft fields the new-task form accepts. The
5226
+ * reply is untrusted text, so extraction is defensive: code fences are
5227
+ * stripped, the first JSON object wins, and an unusable reply falls back to
5228
+ * the user's own words instead of an empty form.
5229
+ */
5230
+ /** How long one parse may take before the Host gives up on the model. */
5231
+ const TASK_PARSE_TIMEOUT_MS = 45e3;
5232
+ /** Longest title the form is willing to receive from a model. */
5233
+ const TASK_PARSE_TITLE_LIMIT = 120;
5234
+ /** Typed parse failure; the route maps the code onto a status and a body. */
5235
+ var TaskParseError = class extends Error {
5236
+ code;
5237
+ constructor(code, message) {
5238
+ super(message);
5239
+ this.code = code;
5240
+ this.name = "TaskParseError";
5241
+ }
5242
+ };
5243
+ const SYSTEM_PROMPT = [
5244
+ "You turn one pasted note into a task for a kanban board.",
5245
+ "Reply with a single JSON object and nothing else, with exactly these keys:",
5246
+ "{\"title\": string, \"description\": string, \"prompt\": string}",
5247
+ "- title: one line, at most 80 characters, in the language of the note.",
5248
+ "- description: what the task is and the context the note carries, as plain text.",
5249
+ "- prompt: the instruction an agent should execute, keeping every fact that matters."
5250
+ ].join("\n");
5251
+ /** Split a qualified `provider/model` route the same way the runner does. */
5252
+ function splitModelRoute(qualified) {
5253
+ const raw = qualified?.trim() ?? "";
5254
+ if (raw === "") return void 0;
5255
+ const slash = raw.indexOf("/");
5256
+ if (slash <= 0 || slash === raw.length - 1) return void 0;
5257
+ const provider = raw.slice(0, slash).trim();
5258
+ const model = raw.slice(slash + 1).trim();
5259
+ if (provider === "" || model === "") return void 0;
5260
+ return {
5261
+ provider,
5262
+ model
5263
+ };
5264
+ }
5265
+ /** Trim one model-provided field to a single-line, bounded string. */
5266
+ function field(value, limit) {
5267
+ if (typeof value !== "string") return "";
5268
+ const text = value.trim();
5269
+ return limit === void 0 || text.length <= limit ? text : text.slice(0, limit).trim();
5270
+ }
5271
+ /** First non-empty line of the pasted text, used when the model omits a title. */
5272
+ function firstLine(source) {
5273
+ const line = source.split(/\r?\n/).map((entry) => entry.trim()).find((entry) => entry !== "") ?? "";
5274
+ return line.length <= TASK_PARSE_TITLE_LIMIT ? line : line.slice(0, TASK_PARSE_TITLE_LIMIT).trim();
5275
+ }
5276
+ /**
5277
+ * Read the draft out of a model reply. Fences and surrounding prose are
5278
+ * tolerated; anything unusable returns undefined so the caller can decide
5279
+ * between a typed failure and a fallback.
5280
+ * @param reply - raw model text.
5281
+ */
5282
+ function extractTaskParseReply(reply) {
5283
+ const withoutFences = reply.replace(/```[a-zA-Z]*\s*/g, "");
5284
+ const start = withoutFences.indexOf("{");
5285
+ const end = withoutFences.lastIndexOf("}");
5286
+ if (start === -1 || end <= start) return void 0;
5287
+ let payload;
5288
+ try {
5289
+ payload = JSON.parse(withoutFences.slice(start, end + 1));
5290
+ } catch {
5291
+ return;
5292
+ }
5293
+ if (typeof payload !== "object" || payload === null) return void 0;
5294
+ const record = payload;
5295
+ const draft = {
5296
+ title: field(record.title, TASK_PARSE_TITLE_LIMIT),
5297
+ description: field(record.description),
5298
+ prompt: field(record.prompt)
5299
+ };
5300
+ return draft.title === "" && draft.description === "" && draft.prompt === "" ? void 0 : draft;
5301
+ }
5302
+ /**
5303
+ * Fill the three form fields, falling back to the pasted text so a weak model
5304
+ * reply never loses what the user actually wrote.
5305
+ * @param reply - raw model text.
5306
+ * @param source - the text the user pasted.
5307
+ */
5308
+ function draftFromReply(reply, source) {
5309
+ const parsed = extractTaskParseReply(reply);
5310
+ return {
5311
+ title: parsed?.title !== void 0 && parsed.title !== "" ? parsed.title : firstLine(source),
5312
+ description: parsed?.description ?? "",
5313
+ prompt: parsed?.prompt !== void 0 && parsed.prompt !== "" ? parsed.prompt : source.trim()
5314
+ };
5315
+ }
5316
+ /**
5317
+ * Parse one pasted text through the injected `llm` service.
5318
+ * @param llm - the Host's llm service.
5319
+ * @param request - pasted text plus the qualified model route.
5320
+ * @param signal - caller cancellation (client disconnect); combined with the timeout.
5321
+ * @returns the draft fields.
5322
+ * @throws TaskParseError with a code the route maps onto a status.
5323
+ */
5324
+ async function parseTaskDraft(llm, request, signal) {
5325
+ const text = request.text.trim();
5326
+ if (text === "") throw new TaskParseError("parse-failed", "there is nothing to parse");
5327
+ const route = splitModelRoute(request.model);
5328
+ if (route === void 0) throw new TaskParseError("no-model", "no model route was selected for parsing");
5329
+ const timeout = new AbortController();
5330
+ const timer = setTimeout(() => {
5331
+ timeout.abort();
5332
+ }, TASK_PARSE_TIMEOUT_MS);
5333
+ const abortFromCaller = () => {
5334
+ timeout.abort();
5335
+ };
5336
+ signal?.addEventListener("abort", abortFromCaller, { once: true });
5337
+ try {
5338
+ const options = {
5339
+ provider: route.provider,
5340
+ model: route.model,
5341
+ system: SYSTEM_PROMPT,
5342
+ messages: [createUserMessage({
5343
+ content: [{
5344
+ type: "text",
5345
+ text
5346
+ }],
5347
+ source: { kind: "user" }
5348
+ })],
5349
+ signal: timeout.signal
5350
+ };
5351
+ let reply = "";
5352
+ for await (const chunk of llm.stream(options)) if (chunk.type === "text-delta") reply += chunk.text;
5353
+ return draftFromReply(reply, text);
5354
+ } catch (error) {
5355
+ if (error instanceof TaskParseError) throw error;
5356
+ if (timeout.signal.aborted) throw new TaskParseError("timeout", `the model did not answer within ${TASK_PARSE_TIMEOUT_MS / 1e3}s`);
5357
+ throw new TaskParseError("model-error", error instanceof Error ? error.message : String(error));
5358
+ } finally {
5359
+ clearTimeout(timer);
5360
+ signal?.removeEventListener("abort", abortFromCaller);
5361
+ }
5362
+ }
5363
+ //#endregion
5364
+ //#region src/http.ts
5365
+ /** Family-default JSON response headers; callers may append or override. */
5366
+ const JSON_HEADERS = {
5367
+ "content-type": "application/json; charset=utf-8",
5368
+ "referrer-policy": "no-referrer"
5369
+ };
5370
+ /**
5371
+ * Write one JSON response. Default headers are the family defaults
5372
+ * (content-type and referrer-policy); caller headers are appended or
5373
+ * override them.
5374
+ */
5375
+ function writeJson(res, status, body, headers = {}) {
5376
+ const payload = JSON.stringify(body);
5377
+ res.writeHead(status, {
5378
+ ...JSON_HEADERS,
5379
+ ...headers
5380
+ });
5381
+ res.end(payload);
5382
+ }
5383
+ //#endregion
5384
+ //#region src/loopback.ts
5385
+ /** IPv4 127/8 predicate (four decimal octets, first == 127). */
5386
+ function isIPv4Loopback(v4) {
5387
+ const parts = v4.split(".");
5388
+ return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
5389
+ }
5390
+ /** Whether a socket remote address names the loopback range (127/8, ::1, IPv4-mapped). */
5391
+ function isLoopbackAddress(address) {
5392
+ if (address === void 0) return false;
5393
+ const normalized = address.toLowerCase();
5394
+ if (normalized === "::1") return true;
5395
+ if (normalized.startsWith("::ffff:")) return isIPv4Loopback(normalized.slice(7));
5396
+ return isIPv4Loopback(normalized);
5397
+ }
5398
+ /** Whether a normalized URL hostname names the loopback authority (localhost, [::1], 127/8). */
5399
+ function isLoopbackHostname(hostname) {
5400
+ if (hostname === "localhost" || hostname === "[::1]") return true;
5401
+ return isIPv4Loopback(hostname);
5402
+ }
5403
+ /**
5404
+ * Request-level trust fence: a loopback socket address AND a loopback Host
5405
+ * header, plus browser same-origin markers. The socket address is
5406
+ * authoritative; X-Forwarded-For is never trusted.
5407
+ */
5408
+ function isLoopbackRequest(request) {
5409
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
5410
+ const host = request.headers.host;
5411
+ if (typeof host !== "string") return false;
5412
+ let hostUrl;
5413
+ try {
5414
+ hostUrl = new URL("http://" + host);
5415
+ } catch {
5416
+ return false;
5417
+ }
5418
+ if (!isLoopbackHostname(hostUrl.hostname)) return false;
5419
+ if (request.headers["sec-fetch-site"] === "cross-site") return false;
5420
+ const origin = request.headers.origin;
5421
+ if (origin === void 0) return true;
5422
+ try {
5423
+ return new URL(origin).host === hostUrl.host;
5424
+ } catch {
5425
+ return false;
5426
+ }
5427
+ }
5428
+ //#endregion
5429
+ //#region src/host-routes.ts
5430
+ const ACTION_LIMIT = 64 * 1024;
5431
+ const IMPORT_LIMIT = 2 * 1024 * 1024;
5432
+ const HEARTBEAT_MS = 15e3;
5433
+ /** Header replaced by an authenticated same-host reverse proxy. */
5434
+ const TASK_BOARD_PROXY_TOKEN_HEADER = "x-dsh-task-board-proxy-token";
5435
+ function parseAuthority(authority) {
5436
+ if (authority.trim() !== authority) return void 0;
5437
+ const match = authority.startsWith("[") ? /^\[[^\]]+\](?::([0-9]+))?$/.exec(authority) : /^[^:@/?#\s]+(?::([0-9]+))?$/.exec(authority);
5438
+ if (match === null) return void 0;
5439
+ try {
5440
+ const url = new URL(`http://${authority}`);
5441
+ if (url.username !== "" || url.password !== "" || url.pathname !== "/" || url.search !== "" || url.hash !== "") return void 0;
5442
+ const rawPort = match[1];
5443
+ if (rawPort !== void 0 && (String(Number(rawPort)) !== rawPort || Number(rawPort) > 65535)) return void 0;
5444
+ return {
5445
+ canonical: url.hostname.toLowerCase() + (rawPort === void 0 ? "" : `:${rawPort}`),
5446
+ url
5447
+ };
5448
+ } catch {
5449
+ return;
5450
+ }
5451
+ }
5452
+ function resolveAccess(access) {
5453
+ const trustedProxyHosts = /* @__PURE__ */ new Set();
5454
+ for (const authority of access.trustedProxyHosts ?? []) {
5455
+ const parsed = parseAuthority(authority);
5456
+ if (parsed === void 0 || parsed.canonical !== authority.toLowerCase()) throw new Error(`task-board: trustedProxyHosts entry ${JSON.stringify(authority)} is not a canonical host[:port] authority`);
5457
+ trustedProxyHosts.add(parsed.canonical);
5458
+ }
5459
+ if (trustedProxyHosts.size > 0 && (access.proxyToken === void 0 || access.proxyToken === "")) throw new Error("task-board: authenticated proxy hosts require a non-empty proxy token");
5460
+ return {
5461
+ trustedProxyHosts,
5462
+ ...access.proxyToken === void 0 ? {} : { proxyToken: access.proxyToken }
5463
+ };
5464
+ }
5465
+ /**
5466
+ * Browser-signal tripwire, NOT an authority check: a bare curl sends neither
5467
+ * header and is refused, but a curl with a forged Origin passes this too.
5468
+ * The real boundary is the loopback socket + Host + origin-equality checks
5469
+ * in isTrustedTaskBoardRequest below; do not rely on this marker alone.
5470
+ */
5471
+ function browserSameOriginMarker(req) {
5472
+ return req.headers["sec-fetch-site"] === "same-origin" || typeof req.headers.origin === "string";
5473
+ }
5474
+ function sameAuthority(req, host) {
5475
+ if (req.headers["sec-fetch-site"] === "cross-site") return false;
5476
+ const origin = req.headers.origin;
5477
+ if (origin === void 0) return req.headers["sec-fetch-site"] === "same-origin";
5478
+ try {
5479
+ return new URL(origin).host === host.host;
5480
+ } catch {
5481
+ return false;
5482
+ }
5483
+ }
5484
+ function matchesToken(candidate, expected) {
5485
+ if (typeof candidate !== "string" || expected === void 0 || candidate === "" || expected === "") return false;
5486
+ const actual = Buffer.from(candidate);
5487
+ const wanted = Buffer.from(expected);
5488
+ return actual.length === wanted.length && timingSafeEqual(actual, wanted);
5489
+ }
5490
+ /**
5491
+ * Task-board route fence. Direct desktop access uses the repository-wide
5492
+ * loopback socket + Host guard and additionally requires a browser same-origin
5493
+ * marker: a bare local curl without any browser signal cannot exercise the
5494
+ * agent control plane (a forged Origin does pass the marker — it is a
5495
+ * tripwire, the socket/Host/origin-equality checks carry the authority).
5496
+ * Authenticated proxies must be explicitly allowlisted and replace the
5497
+ * internal token header after their own authentication step.
5498
+ */
5499
+ function isTrustedTaskBoardRequest(req, access) {
5500
+ if (!browserSameOriginMarker(req)) return false;
5501
+ if (isLoopbackRequest(req)) return true;
5502
+ if (!isLoopbackAddress(req.socket.remoteAddress)) return false;
5503
+ const host = req.headers.host;
5504
+ if (typeof host !== "string") return false;
5505
+ const parsed = parseAuthority(host);
5506
+ if (parsed === void 0 || parsed.canonical !== host.toLowerCase()) return false;
5507
+ if (!access.trustedProxyHosts.has(parsed.canonical) || !sameAuthority(req, parsed.url)) return false;
5508
+ return matchesToken(req.headers[TASK_BOARD_PROXY_TOKEN_HEADER], access.proxyToken);
5509
+ }
5510
+ async function readBody(req) {
5511
+ const chunks = [];
5512
+ let size = 0;
5513
+ for await (const chunk of req) {
5514
+ const buffer = chunk;
5515
+ size += buffer.length;
5516
+ if (size > IMPORT_LIMIT) throw new Error("body-too-large");
5517
+ chunks.push(buffer);
5518
+ }
5519
+ const raw = Buffer.concat(chunks).toString("utf8");
5520
+ return {
5521
+ raw,
5522
+ value: JSON.parse(raw)
5523
+ };
5524
+ }
5525
+ function makeTaskBoardRoutes(service, access = {}, options = {}) {
5526
+ const resolvedAccess = resolveAccess(access);
5527
+ const guard = (req, res) => {
5528
+ if (isTrustedTaskBoardRequest(req, resolvedAccess)) return true;
5529
+ writeJson(res, 403, {
5530
+ ok: false,
5531
+ error: "forbidden"
5532
+ }, { "cache-control": "no-store" });
5533
+ return false;
5534
+ };
5535
+ return [
5536
+ {
5537
+ kind: "exact",
5538
+ path: `${TASK_BOARD_API_PREFIX}/state`,
5539
+ handler: (req, res) => {
5540
+ if (req.method !== "GET") return writeJson(res, 405, {
3177
5541
  ok: false,
3178
5542
  error: "method-not-allowed"
3179
5543
  }, { "cache-control": "no-store" });
@@ -3246,6 +5610,66 @@ function makeTaskBoardRoutes(service, access = {}) {
3246
5610
  res.once("close", close);
3247
5611
  push();
3248
5612
  }
5613
+ },
5614
+ {
5615
+ kind: "exact",
5616
+ path: `${TASK_BOARD_API_PREFIX}/parse`,
5617
+ handler: async (req, res) => {
5618
+ if (req.method !== "POST") return writeJson(res, 405, {
5619
+ ok: false,
5620
+ error: "method-not-allowed"
5621
+ }, { "cache-control": "no-store" });
5622
+ if (!guard(req, res)) return;
5623
+ if (!(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return writeJson(res, 415, {
5624
+ ok: false,
5625
+ error: "json-required"
5626
+ }, { "cache-control": "no-store" });
5627
+ let body;
5628
+ try {
5629
+ body = await readBody(req);
5630
+ } catch (error) {
5631
+ const message = error instanceof Error ? error.message : String(error);
5632
+ return writeJson(res, message === "body-too-large" ? 413 : 400, {
5633
+ ok: false,
5634
+ error: message
5635
+ }, { "cache-control": "no-store" });
5636
+ }
5637
+ const request = parseTaskParseRequest(body.value);
5638
+ if (request === void 0) return writeJson(res, 400, {
5639
+ ok: false,
5640
+ error: "invalid-parse-request"
5641
+ }, { "cache-control": "no-store" });
5642
+ if (Buffer.byteLength(request.text, "utf8") > 16384) return writeJson(res, 413, {
5643
+ ok: false,
5644
+ error: "text-too-large"
5645
+ }, { "cache-control": "no-store" });
5646
+ const parseTask = options.parseTask;
5647
+ if (parseTask === void 0) return writeJson(res, 503, {
5648
+ ok: false,
5649
+ code: "no-model",
5650
+ error: "task-board parsing is unavailable"
5651
+ }, { "cache-control": "no-store" });
5652
+ const controller = new AbortController();
5653
+ const onClose = () => {
5654
+ controller.abort();
5655
+ };
5656
+ res.once("close", onClose);
5657
+ try {
5658
+ writeJson(res, 200, {
5659
+ ok: true,
5660
+ draft: await parseTask(request, controller.signal)
5661
+ }, { "cache-control": "no-store" });
5662
+ } catch (error) {
5663
+ const failure = error instanceof TaskParseError ? error : new TaskParseError("model-error", error instanceof Error ? error.message : String(error));
5664
+ writeJson(res, failure.code === "no-model" ? 503 : failure.code === "timeout" ? 504 : 502, {
5665
+ ok: false,
5666
+ code: failure.code,
5667
+ error: failure.message
5668
+ }, { "cache-control": "no-store" });
5669
+ } finally {
5670
+ res.off("close", onClose);
5671
+ }
5672
+ }
3249
5673
  }
3250
5674
  ];
3251
5675
  }
@@ -3336,6 +5760,21 @@ function resolveProxyAccess(config, env = process.env) {
3336
5760
  /** Schema default, re-read for hand-built test contexts (the loader applies them normally). */
3337
5761
  const DEFAULT_ANNOUNCE = false;
3338
5762
  /**
5763
+ * Read the optional `llm` service. The board deliberately does not inject it:
5764
+ * a deployment without a model must still mount the board, and the parse route
5765
+ * answers a typed failure instead of the plugin failing to load (issue #1540).
5766
+ * @param ctx - the plugin context.
5767
+ * @returns the llm service, or undefined when this deployment serves none.
5768
+ */
5769
+ function resolveLlmRuntime(ctx) {
5770
+ try {
5771
+ const llm = ctx.get("llm");
5772
+ return llm !== void 0 && typeof llm.stream === "function" ? llm : void 0;
5773
+ } catch {
5774
+ return;
5775
+ }
5776
+ }
5777
+ /**
3339
5778
  * Register the board's announcement section, gated on the composition entry's
3340
5779
  * `announceToAgent` (and the live settings value once the web settings
3341
5780
  * surface is served). The section is re-registered whenever the source
@@ -3359,7 +5798,12 @@ function applyImpl(ctx, config) {
3359
5798
  ctx.effect(() => {
3360
5799
  const disposers = [];
3361
5800
  try {
3362
- for (const route of makeTaskBoardRoutes(host, resolveProxyAccess(config))) disposers.push(ctx.webServer.register(route));
5801
+ const routes = makeTaskBoardRoutes(host, resolveProxyAccess(config), { parseTask: async (request, signal) => {
5802
+ const llm = resolveLlmRuntime(ctx);
5803
+ if (llm === void 0) throw new TaskParseError("no-model", "this deployment serves no llm service");
5804
+ return await parseTaskDraft(llm, request, signal);
5805
+ } });
5806
+ for (const route of routes) disposers.push(ctx.webServer.register(route));
3363
5807
  } catch (error) {
3364
5808
  for (const dispose of disposers) dispose();
3365
5809
  host.dispose();
@@ -3407,4 +5851,4 @@ function applyImpl(ctx, config) {
3407
5851
  sync();
3408
5852
  }
3409
5853
  //#endregion
3410
- export { Config, DEFAULT_PROXY_TOKEN_ENV, TASK_BOARD_GUIDANCE, TASK_BOARD_SETTINGS_NAMESPACE, apply, inject, resolveProxyAccess };
5854
+ export { Config, DEFAULT_PROXY_TOKEN_ENV, TASK_BOARD_GUIDANCE, TASK_BOARD_SETTINGS_NAMESPACE, apply, inject, resolveLlmRuntime, resolveProxyAccess };