{"version":3,"file":"xllm_deno.cjs","sources":["../src/xllm/hosts/deno/deno_api.ts","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_blake.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/blake2.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/blake3.js","../src/xllm/hosts/deno/identity.ts","../src/xllm/hosts/deno/native_tools.ts","../src/xllm/hosts/deno/native_runtime.ts","../src/xllm/hosts/deno/store.ts","../src/xllm/hosts/deno/provider.ts","../src/xllm/hosts/deno/index.ts"],"sourcesContent":["// The part of the `Deno` namespace the Deno host uses, typed here so the\n// host compiles with the SDK's TypeScript build (no Deno lib) and with\n// `deno check`. Only `hosts/deno/` touches it; the browser entries never\n// import this directory.\n\nexport interface DenoFsFile {\n  write(p: Uint8Array): Promise<number>\n  sync(): Promise<void>\n  close(): void\n  tryLock(exclusive?: boolean): Promise<boolean>\n  unlock(): Promise<void>\n}\n\nexport interface DenoFileInfo {\n  isFile: boolean\n  isDirectory: boolean\n  isSymlink: boolean\n  size: number\n  mtime: Date | null\n}\n\nexport interface DenoDirEntry {\n  name: string\n  isFile: boolean\n  isDirectory: boolean\n}\n\nexport interface DenoChildStatus {\n  success: boolean\n  code: number\n  signal: string | null\n}\n\nexport interface DenoChildProcess {\n  readonly pid: number\n  readonly status: Promise<DenoChildStatus>\n  kill(signo?: string): void\n}\n\nexport interface DenoCommandOutput extends DenoChildStatus {\n  stdout: Uint8Array\n  stderr: Uint8Array\n}\n\nexport interface DenoCommandOptions {\n  args?: string[]\n  cwd?: string\n  env?: Record<string, string>\n  clearEnv?: boolean\n  stdin?: 'piped' | 'inherit' | 'null'\n  stdout?: 'piped' | 'inherit' | 'null'\n  stderr?: 'piped' | 'inherit' | 'null'\n  signal?: AbortSignal\n}\n\nexport interface DenoApi {\n  readonly pid: number\n  readonly build: { os: string }\n  readonly errors: { NotFound: new (...a: never[]) => Error; AlreadyExists: new (...a: never[]) => Error }\n  readonly env: { get(name: string): string | undefined; toObject(): Record<string, string> }\n  open(path: string, options: { read?: boolean; write?: boolean; create?: boolean; truncate?: boolean; createNew?: boolean }): Promise<DenoFsFile>\n  readFile(path: string): Promise<Uint8Array>\n  readTextFile(path: string): Promise<string>\n  writeFile(path: string, data: Uint8Array): Promise<void>\n  writeTextFile(path: string, data: string): Promise<void>\n  mkdir(path: string, options?: { recursive?: boolean; mode?: number }): Promise<void>\n  rename(from: string, to: string): Promise<void>\n  remove(path: string, options?: { recursive?: boolean }): Promise<void>\n  stat(path: string): Promise<DenoFileInfo>\n  lstat(path: string): Promise<DenoFileInfo>\n  realPath(path: string): Promise<string>\n  readDir(path: string): AsyncIterable<DenoDirEntry>\n  cwd(): string\n  makeTempDir(options?: { prefix?: string }): Promise<string>\n  Command: new (cmd: string, options?: DenoCommandOptions) => { spawn(): DenoChildProcess; output(): Promise<DenoCommandOutput> }\n}\n\nexport function deno(): DenoApi {\n  const d = (globalThis as unknown as { Deno?: DenoApi }).Deno\n  if (!d) throw new Error('the xllm Deno host needs the Deno runtime')\n  return d\n}\n\nexport function isNotFound(e: unknown): boolean {\n  return e instanceof deno().errors.NotFound\n}\n\nexport function isAlreadyExists(e: unknown): boolean {\n  return e instanceof deno().errors.AlreadyExists\n}\n\nexport function errorText(e: unknown): string {\n  return e instanceof Error ? e.message : String(e)\n}\n\n/** `$HOME` (`USERPROFILE` on Windows). */\nexport function homeDir(): string | undefined {\n  const env = deno().env\n  return env.get('HOME') ?? env.get('USERPROFILE')\n}\n\nexport function joinPath(...parts: string[]): string {\n  let out = ''\n  for (const p of parts) {\n    if (!p) continue\n    if (p.startsWith('/') || !out) out = p\n    else out = out.endsWith('/') ? out + p : `${out}/${p}`\n  }\n  return out\n}\n\nexport function parentDir(p: string): string {\n  const t = p.replace(/\\/+$/, '')\n  const i = t.lastIndexOf('/')\n  return i < 0 ? '.' : i === 0 ? '/' : t.slice(0, i)\n}\n\nexport async function pathExists(p: string): Promise<boolean> {\n  try {\n    await deno().lstat(p)\n    return true\n  } catch (e) {\n    if (isNotFound(e)) return false\n    throw e\n  }\n}\n\nexport async function isDir(p: string): Promise<boolean> {\n  try {\n    return (await deno().stat(p)).isDirectory\n  } catch {\n    return false\n  }\n}\n\n/** Write a file and fsync it (`write_file_synced`). */\nexport async function writeFileSynced(path: string, bytes: Uint8Array): Promise<void> {\n  const f = await deno().open(path, { write: true, create: true, truncate: true })\n  try {\n    let off = 0\n    while (off < bytes.length) off += await f.write(bytes.subarray(off))\n    await f.sync()\n  } finally {\n    f.close()\n  }\n}\n\n/** fsync a directory so a rename in it is durable (`sync_dir`). */\nexport async function syncDir(dir: string): Promise<void> {\n  if (deno().build.os === 'windows') return\n  const f = await deno().open(dir, { read: true })\n  try {\n    await f.sync()\n  } finally {\n    f.close()\n  }\n}\n","const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n    if (le)\n        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n    const len = lst.length;\n    let Ah = new Uint32Array(len);\n    let Al = new Uint32Array(len);\n    for (let i = 0; i < len; i++) {\n        const { h, l } = fromBig(lst[i], le);\n        [Ah[i], Al[i]] = [h, l];\n    }\n    return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n    const h = fromNumH(n);\n    const l = fromNumL(n);\n    view.setUint32(byteOffset, isLE ? l : h, isLE);\n    view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n    const l = (Al >>> 0) + (Bl >>> 0);\n    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n    // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n    // The fallback still requires a real ArrayBuffer view, so plain\n    // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n    // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n    return (a instanceof Uint8Array ||\n        (ArrayBuffer.isView(a) &&\n            a.constructor.name === 'Uint8Array' &&\n            'BYTES_PER_ELEMENT' in a &&\n            a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n    if (typeof n !== 'number')\n        throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n    if (!Number.isSafeInteger(n) || n < 0)\n        throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n    return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n    if (typeof value !== 'boolean')\n        throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n    return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n    // Success path first: this runs at the start of every update() / digestInto(), and the\n    // common `abytes(data)` form must not pay for length handling it does not use.\n    if (isBytes(value) && (length === undefined || value.length === length))\n        return value;\n    // Error path: recompute freely to build the exact message.\n    if (length !== undefined)\n        anumber(length, 'length');\n    const bytes = isBytes(value);\n    const ofLen = length !== undefined ? ` of length ${length}` : '';\n    const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n    const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n    if (!bytes)\n        throw new TypeError(message);\n    throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n    // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n    // because callers use it at byte-validation boundaries before mutating the detached copy.\n    return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n    if (typeof h !== 'function' || typeof h.create !== 'function')\n        throw new TypeError('expected hash wrapped by utils.createHasher');\n    anumber(h.outputLen);\n    anumber(h.blockLen);\n    // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n    // validation and can produce empty outputs instead of failing fast.\n    if (h.outputLen < 1 || h.blockLen < 1)\n        throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n    if (value === null || typeof value !== 'object' || Array.isArray(value))\n        throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n    aobject(value, label);\n    const proto = Object.getPrototypeOf(value);\n    if (proto !== Object.prototype && proto !== null)\n        throw new TypeError(`\"${label}\" expected plain object`);\n    // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n    // prototype setter. Reject it before merging so inherited option values cannot be injected.\n    if (Object.hasOwn(value, '__proto__'))\n        throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n    // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n    // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n    if (instance.destroyed)\n        throw new Error('hash was destroyed');\n    if (checkFinished && instance.finished)\n        throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n    abytes(out, undefined, 'output');\n    // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n    // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n    const min = instance.outputLen;\n    if (!(out.length >= min)) {\n        throw new RangeError('\"output\" expected length >= ' + min);\n    }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n    for (let i = 0; i < arrays.length; i++) {\n        arrays[i].fill(0);\n    }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n    return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n    return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n    return (((word << 24) & 0xff000000) |\n        ((word << 8) & 0xff0000) |\n        ((word >>> 8) & 0xff00) |\n        ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n    ? (n) => n\n    : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n    for (let i = 0; i < arr.length; i++) {\n        arr[i] = byteSwap(arr[i]);\n    }\n    return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n *   On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n    ? (u) => u\n    : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = '';\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n    return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n        : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n            : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n                : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== 'string')\n        throw new TypeError('hex string expected, got ' + typeof hex);\n    if (hasHexBuiltin) {\n        try {\n            return Uint8Array.fromHex(hex);\n        }\n        catch (error) {\n            if (error instanceof SyntaxError)\n                throw new RangeError(error.message);\n            throw error;\n        }\n    }\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2)\n        throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n        }\n        array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n    }\n    return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n    const host = globalThis;\n    if (typeof host.scheduler?.yield === 'function') {\n        const promise = host.scheduler.yield();\n        // Keep the original scheduler rejection; this handler exists only for cleanup.\n        if (onReject)\n            promise.catch(onReject);\n        return promise;\n    }\n    return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n    anumber(iters, 'iters');\n    anumber(tick, 'tick');\n    if (typeof cb !== 'function')\n        throw new TypeError('callback must be a function');\n    // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n    let ts = Date.now();\n    for (let i = 0; i < iters; i++) {\n        cb(i);\n        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n        const diff = Date.now() - ts;\n        if (diff >= 0 && diff < tick)\n            continue;\n        await nextTick(onReject);\n        // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n        ts = Date.now();\n    }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== 'string')\n        throw new TypeError('string expected');\n    const encoded = new TextEncoder().encode(str);\n    try {\n        // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n        // buffer can then wipe it independently of TextEncoder's temporary result.\n        return new Uint8Array(encoded); // https://bugzil.la/1681809\n    }\n    finally {\n        clean(encoded);\n    }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n    if (typeof data === 'string')\n        return utf8ToBytes(data);\n    return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n    aobject(object, title);\n    aobject(fields, 'fields');\n    aobject(optFields, 'optFields');\n    function checkField(fieldName, expectedType, isOpt) {\n        const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n        // Config fields must be explicit own properties. Optional inherited values are rejected too\n        // because callers keep reading the same options object after validation.\n        const val = object[fieldName];\n        // Runtime objects such as Field instances intentionally satisfy required method slots\n        // via their shared prototype.\n        if (!Object.hasOwn(object, fieldName) &&\n            (isOpt ? val !== undefined : expectedType !== 'function')) {\n            throw new TypeError(`${label} is invalid: expected own property`);\n        }\n        if (isOpt && val === undefined)\n            return;\n        const current = typeof val;\n        if (current !== expectedType || val === null)\n            throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n    }\n    const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n    iter(fields, false);\n    iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n    aopts(defaults, 'defaults');\n    if (opts !== undefined)\n        aopts(opts, title);\n    // Callers read optional fields directly, so omitted values must not fall through to ambient\n    // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n    const merged = Object.assign(Object.create(null), defaults, opts);\n    return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n *   Wrapper construction eagerly calls `hashCons(undefined)` once to read\n *   `outputLen` / `blockLen`, so constructor side effects happen at module\n *   init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n    if (typeof hashCons !== 'function')\n        throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n    info = checkOpts({}, info, 'info');\n    const hashC = (msg, opts) => hashCons(opts)\n        .update(msg)\n        .digest();\n    const tmp = hashCons(undefined);\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.canXOF = tmp.canXOF;\n    hashC.create = (opts) => hashCons(opts);\n    Object.assign(hashC, info);\n    return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n    // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n    anumber(bytesLength, 'bytesLength');\n    const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n    if (typeof cr?.getRandomValues !== 'function')\n        throw new Error('crypto.getRandomValues must be defined');\n    // Web Cryptography API Level 2 §10.1.1:\n    // if `byteLength > 65536`, throw `QuotaExceededError`.\n    // Keep the guard explicit so callers can see the quota in code\n    // instead of discovering it by reading the spec or host errors.\n    // This wrapper surfaces the same quota as a stable library RangeError.\n    if (bytesLength > 65536)\n        throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n    return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n *   The helper accepts any byte even though only the documented NIST hash\n *   suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n    // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n    // Larger suffix values would need base-128 OID encoding and a different length byte.\n    oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n    return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n    return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n    blockLen;\n    outputLen;\n    canXOF = false;\n    padOffset;\n    isLE;\n    // For partial updates less than block size\n    buffer;\n    view;\n    finished = false;\n    length = 0;\n    pos = 0;\n    destroyed = false;\n    constructor(blockLen, outputLen, padOffset, isLE) {\n        this.blockLen = blockLen;\n        this.outputLen = outputLen;\n        this.padOffset = padOffset;\n        this.isLE = isLE;\n        this.buffer = new Uint8Array(blockLen);\n        this.view = createView(this.buffer);\n    }\n    update(data) {\n        aexists(this);\n        abytes(data);\n        const { view, buffer, blockLen } = this;\n        const len = data.length;\n        let processed = false;\n        for (let pos = 0; pos < len;) {\n            const take = Math.min(blockLen - this.pos, len - pos);\n            // Fast path only when there is no buffered partial block: `take === blockLen` implies\n            // `this.pos === 0`, so we can process full blocks directly from the input view.\n            if (take === blockLen) {\n                const dataView = createView(data);\n                for (; blockLen <= len - pos; pos += blockLen)\n                    this.process(dataView, pos);\n                processed = true;\n                continue;\n            }\n            // When the whole input is buffered in one go (common for short messages), passing `data`\n            // directly avoids allocating a subarray view.\n            buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n            this.pos += take;\n            pos += take;\n            if (this.pos === blockLen) {\n                this.process(view, 0);\n                this.pos = 0;\n                processed = true;\n            }\n        }\n        this.length += data.length;\n        // Shared schedule buffers only pick up input-derived words inside process(); if everything\n        // was buffered without processing, there is nothing to zero.\n        if (processed)\n            this.roundClean();\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        this.finished = true;\n        // Padding\n        // We can avoid allocation of buffer for padding completely if it\n        // was previously not allocated here. But it won't change performance.\n        const { buffer, view, blockLen, isLE } = this;\n        let { pos } = this;\n        // append the bit '1' to the message, then zero-pad the rest of the block\n        buffer[pos++] = 0b10000000;\n        buffer.fill(0, pos);\n        // we have less than padOffset left in buffer, so we cannot put length in\n        // current block, need process it and pad again\n        if (this.padOffset > blockLen - pos) {\n            this.process(view, 0);\n            buffer.fill(0);\n        }\n        // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n        // the padding fill above, and JS will overflow before user input can make that half non-zero.\n        // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n        // integer below 2**53, so the split inside the helper stays exact).\n        setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n        this.process(view, 0);\n        // The final block above is processed outside update(), so the shared message-schedule\n        // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n        this.roundClean();\n        // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n        const oview = out === buffer ? view : createView(out);\n        const len = this.outputLen;\n        // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n        const outLen = len / 4;\n        const state = this.get();\n        // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n        if (len % 4 || outLen > state.length)\n            throw new Error('invalid outputLen');\n        for (let i = 0; i < outLen; i++)\n            oview.setUint32(4 * i, state[i], isLE);\n    }\n    digest() {\n        const { buffer, outputLen } = this;\n        this.digestInto(buffer);\n        // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n        // fresh bytes to the caller.\n        const res = buffer.slice(0, outputLen);\n        this.destroy();\n        return res;\n    }\n    _cloneIntoMeta(to) {\n        const { buffer, length, finished, destroyed, pos } = this;\n        to.destroyed = destroyed;\n        to.finished = finished;\n        to.length = length;\n        to.pos = pos;\n        // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n        // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n        if (pos)\n            to.buffer.set(buffer); // Avoid a hot modulo guard.\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * Internal helpers for blake hash.\n * @module\n */\nimport { rotr } from \"./utils.js\";\n// Unrealized speed-up: a file-local copy of rotr measured ~1-2% faster blake2s/blake256/blake3\n// on Node 24 (V8 does not inline it into G1s/G2s across the module boundary). Reused from\n// utils for deduplication.\n/**\n * Internal blake permutation table.\n * Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also\n * reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows\n * `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants.\n */\n// prettier-ignore\nexport const BSIGMA = /* @__PURE__ */ Uint8Array.from([\n    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n    14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n    11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n    7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n    9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n    2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n    12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n    13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n    6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n    10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n    14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n    // Blake1, unused in others\n    11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n    7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n    9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n    2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n]);\n// Unrealized speed-up: G1s/G2s return a fresh {a,b,c,d} per call (160×/blake2s block), which\n// V8's escape analysis does not eliminate when G stays a real call. Writing into one reused\n// module-level slot instead measured +4-6% blake2s/blake256 1MB throughput on Node 24 — but\n// ~2% slower blake3 (whose profile inlines G and scalar-replaces the fresh object) and no\n// difference on 32-byte inputs. Kept simple.\n// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair.\n// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed\n// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path.\nexport function G1s(a, b, c, d, x) {\n    a = (a + b + x) | 0;\n    d = rotr(d ^ a, 16);\n    c = (c + d) | 0;\n    b = rotr(b ^ c, 12);\n    return { a, b, c, d };\n}\n// 32-bit / BLAKE2s second half of G.\n// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed\n// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path.\nexport function G2s(a, b, c, d, x) {\n    a = (a + b + x) | 0;\n    d = rotr(d ^ a, 8);\n    c = (c + d) | 0;\n    b = rotr(b ^ c, 7);\n    return { a, b, c, d };\n}\n","/**\n * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.\n * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.\n * @module\n */\nimport { BSIGMA, G1s, G2s } from \"./_blake.js\";\nimport { SHA256_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, checkOpts, clean, copyBytes, createHasher, swap32IfBE, swap8IfBE, u32 } from \"./utils.js\";\n// Same IV words as `SHA512_IV`, but endian-swapped into LE u32 low/high halves\n// for the BLAKE2b u64 helpers below.\nconst B2B_IV = /* @__PURE__ */ Uint32Array.from([\n    0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,\n    0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,\n]);\n// Shared synchronous BLAKE2b work vector as LE u32 low/high halves.\nconst BBUF = /* @__PURE__ */ new Uint32Array(32);\n// BLAKE2b G mix split into two half-rounds over LE u32 low/high limbs.\nfunction G1b(a, b, c, d, msg, x) {\n    // NOTE: V is LE here\n    const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n    let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n    let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n    let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n    let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n    // v[a] = (v[a] + v[b] + x) | 0;\n    const ll = u64.add3L(Al, Bl, Xl);\n    Ah = u64.add3H(ll, Ah, Bh, Xh);\n    Al = ll | 0;\n    // v[d] = rotr(v[d] ^ v[a], 32)\n    let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore\n    Dh = u64.rotr32H(xh, xl);\n    Dl = u64.rotr32L(xh, xl);\n    // v[c] = (v[c] + v[d]) | 0;\n    ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n    // v[b] = rotr(v[b] ^ v[c], 24)\n    xh = Bh ^ Ch;\n    xl = Bl ^ Cl;\n    Bh = u64.rotrSH(xh, xl, 24);\n    Bl = u64.rotrSL(xh, xl, 24);\n    BBUF[2 * a] = Al;\n    BBUF[2 * a + 1] = Ah;\n    BBUF[2 * b] = Bl;\n    BBUF[2 * b + 1] = Bh;\n    BBUF[2 * c] = Cl;\n    BBUF[2 * c + 1] = Ch;\n    BBUF[2 * d] = Dl;\n    BBUF[2 * d + 1] = Dh;\n}\n// Second half-round of the same LE-limb BLAKE2b G mix; `x` is the message word offset.\nfunction G2b(a, b, c, d, msg, x) {\n    // NOTE: V is LE here\n    const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n    let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n    let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n    let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n    let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n    // v[a] = (v[a] + v[b] + x) | 0;\n    const ll = u64.add3L(Al, Bl, Xl);\n    Ah = u64.add3H(ll, Ah, Bh, Xh);\n    Al = ll | 0;\n    // v[d] = rotr(v[d] ^ v[a], 16)\n    let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore\n    Dh = u64.rotrSH(xh, xl, 16);\n    Dl = u64.rotrSL(xh, xl, 16);\n    // v[c] = (v[c] + v[d]) | 0;\n    ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n    // v[b] = rotr(v[b] ^ v[c], 63)\n    xh = Bh ^ Ch;\n    xl = Bl ^ Cl;\n    Bh = u64.rotrBH(xh, xl, 63);\n    Bl = u64.rotrBL(xh, xl, 63);\n    BBUF[2 * a] = Al;\n    BBUF[2 * a + 1] = Ah;\n    BBUF[2 * b] = Bl;\n    BBUF[2 * b + 1] = Bh;\n    BBUF[2 * c] = Cl;\n    BBUF[2 * c + 1] = Ch;\n    BBUF[2 * d] = Dl;\n    BBUF[2 * d + 1] = Dh;\n}\nfunction checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {\n    anumber(keyLen);\n    // RFC 7693 §2.1 requires digest length nn in 1..keyLen (keyLen doubles as\n    // the per-variant max for both key and digest lengths: 64 for b, 32 for s).\n    if (outputLen <= 0 || outputLen > keyLen)\n        throw new Error('\"dkLen\" must be 1..' + keyLen + ', got ' + outputLen);\n    const { key, salt, personalization } = opts;\n    // This API uses `undefined` for the RFC 7693 `kk = 0` case, so a provided key must be non-empty.\n    if (key !== undefined && (key.length < 1 || key.length > keyLen))\n        throw new Error('\"key\" expected to be undefined or of length=1..' + keyLen);\n    if (salt !== undefined)\n        abytes(salt, saltLen, 'salt');\n    if (personalization !== undefined)\n        abytes(personalization, persLen, 'personalization');\n}\n/** Internal base class for BLAKE2. */\nexport class _BLAKE2 {\n    buffer;\n    buffer32;\n    finished = false;\n    destroyed = false;\n    length = 0;\n    pos = 0;\n    blockLen;\n    outputLen;\n    canXOF = false;\n    constructor(blockLen, outputLen) {\n        anumber(blockLen);\n        anumber(outputLen);\n        this.blockLen = blockLen;\n        this.outputLen = outputLen;\n        this.buffer = new Uint8Array(blockLen);\n        this.buffer32 = u32(this.buffer);\n    }\n    update(data) {\n        aexists(this);\n        abytes(data);\n        // Main difference with other hashes: there is flag for last block,\n        // so we cannot process current block before we know that there\n        // is the next one. This significantly complicates logic and reduces ability\n        // to do zero-copy processing\n        const { blockLen, buffer, buffer32 } = this;\n        const len = data.length;\n        const offset = data.byteOffset;\n        const buf = data.buffer;\n        for (let pos = 0; pos < len;) {\n            // If buffer is full and we still have input (don't process last block, same as blake2s)\n            if (this.pos === blockLen) {\n                swap32IfBE(buffer32);\n                this.compress(buffer32, 0, false);\n                swap32IfBE(buffer32);\n                this.pos = 0;\n            }\n            const take = Math.min(blockLen - this.pos, len - pos);\n            const dataOffset = offset + pos;\n            // Zero-copy only for full, 4-byte-aligned, non-final blocks.\n            if (take === blockLen && !(dataOffset % 4) && pos + take < len) {\n                const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));\n                swap32IfBE(data32);\n                for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {\n                    this.length += blockLen;\n                    this.compress(data32, pos32, false);\n                }\n                swap32IfBE(data32);\n                continue;\n            }\n            // When the whole input is buffered in one go (common for short messages), passing `data`\n            // directly avoids allocating a subarray view.\n            buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n            this.pos += take;\n            this.length += take;\n            pos += take;\n        }\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        // Reject unaligned views explicitly instead of hiding them behind a full scratch copy.\n        if (out.byteOffset & 3)\n            throw new RangeError('\"output\" expected 4-byte aligned byteOffset, got ' + out.byteOffset);\n        const { pos, buffer32 } = this;\n        this.finished = true;\n        // Padding\n        this.buffer.fill(0, pos);\n        swap32IfBE(buffer32);\n        this.compress(buffer32, 0, true);\n        swap32IfBE(buffer32);\n        const state = this.get();\n        // digest() passes our own `buffer` as `out`; reuse its cached u32 view instead of allocating.\n        const out32 = out === this.buffer ? buffer32 : u32(out);\n        const full = Math.floor(this.outputLen / 4);\n        for (let i = 0; i < full; i++)\n            out32[i] = swap8IfBE(state[i]);\n        const tail = this.outputLen % 4;\n        if (!tail)\n            return;\n        const off = full * 4;\n        const word = state[full];\n        for (let i = 0; i < tail; i++)\n            out[off + i] = word >>> (8 * i);\n    }\n    digest() {\n        const { buffer, outputLen } = this;\n        this.digestInto(buffer);\n        // Return a copy so callers do not alias the instance scratch buffer used during finalization.\n        const res = buffer.slice(0, outputLen);\n        this.destroy();\n        return res;\n    }\n    _cloneInto(to) {\n        const { buffer, length, finished, destroyed, outputLen, pos } = this;\n        // Recreate only `dkLen`; key/salt/personalization are already absorbed into the copied state.\n        to ||= new this.constructor({ dkLen: outputLen });\n        to.set(...this.get());\n        // Last-block-aware lazy compression keeps the pending block live even when full.\n        to.buffer.set(buffer);\n        to.destroyed = destroyed;\n        to.finished = finished;\n        to.length = length;\n        to.pos = pos;\n        // @ts-ignore\n        to.outputLen = outputLen;\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n}\n/** Internal blake2b hash class with state stored as LE u32 low/high halves. */\nexport class _BLAKE2b extends _BLAKE2 {\n    // Same IV words as SHA-512 / BLAKE2b, encoded as LE u32 low/high halves.\n    v0l = B2B_IV[0] | 0;\n    v0h = B2B_IV[1] | 0;\n    v1l = B2B_IV[2] | 0;\n    v1h = B2B_IV[3] | 0;\n    v2l = B2B_IV[4] | 0;\n    v2h = B2B_IV[5] | 0;\n    v3l = B2B_IV[6] | 0;\n    v3h = B2B_IV[7] | 0;\n    v4l = B2B_IV[8] | 0;\n    v4h = B2B_IV[9] | 0;\n    v5l = B2B_IV[10] | 0;\n    v5h = B2B_IV[11] | 0;\n    v6l = B2B_IV[12] | 0;\n    v6h = B2B_IV[13] | 0;\n    v7l = B2B_IV[14] | 0;\n    v7h = B2B_IV[15] | 0;\n    constructor(opts = {}) {\n        opts = checkOpts({}, opts);\n        const olen = opts.dkLen === undefined ? 64 : opts.dkLen;\n        super(128, olen);\n        checkBlake2Opts(olen, opts, 64, 16, 16);\n        let { key, personalization, salt } = opts;\n        let keyLength = 0;\n        if (key !== undefined) {\n            abytes(key, undefined, 'key');\n            keyLength = key.length;\n        }\n        // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`;\n        // the high 32 bits stay at `IV[0]`.\n        this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n        if (salt !== undefined) {\n            abytes(salt, undefined, 'salt');\n            // Copy: u32() would throw on views with byteOffset not divisible by 4.\n            const slt = u32(copyBytes(salt));\n            this.v4l ^= swap8IfBE(slt[0]);\n            this.v4h ^= swap8IfBE(slt[1]);\n            this.v5l ^= swap8IfBE(slt[2]);\n            this.v5h ^= swap8IfBE(slt[3]);\n        }\n        if (personalization !== undefined) {\n            abytes(personalization, undefined, 'personalization');\n            // Copy: u32() would throw on views with byteOffset not divisible by 4.\n            const pers = u32(copyBytes(personalization));\n            this.v6l ^= swap8IfBE(pers[0]);\n            this.v6h ^= swap8IfBE(pers[1]);\n            this.v7l ^= swap8IfBE(pers[2]);\n            this.v7h ^= swap8IfBE(pers[3]);\n        }\n        if (key !== undefined) {\n            // Pad to blockLen and update\n            const tmp = new Uint8Array(this.blockLen);\n            tmp.set(key);\n            this.update(tmp);\n            // The padded copy holds key material; buffer/state keep what they need.\n            clean(tmp);\n        }\n    }\n    // prettier-ignore\n    get() {\n        let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;\n        return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];\n    }\n    // prettier-ignore\n    set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {\n        this.v0l = v0l | 0;\n        this.v0h = v0h | 0;\n        this.v1l = v1l | 0;\n        this.v1h = v1h | 0;\n        this.v2l = v2l | 0;\n        this.v2h = v2h | 0;\n        this.v3l = v3l | 0;\n        this.v3h = v3h | 0;\n        this.v4l = v4l | 0;\n        this.v4h = v4h | 0;\n        this.v5l = v5l | 0;\n        this.v5h = v5h | 0;\n        this.v6l = v6l | 0;\n        this.v6h = v6h | 0;\n        this.v7l = v7l | 0;\n        this.v7h = v7h | 0;\n    }\n    compress(msg, offset, isLast) {\n        // First half from state. Direct writes: get() would allocate an array +\n        // closure per block.\n        // prettier-ignore\n        const { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;\n        // prettier-ignore\n        {\n            BBUF[0] = v0l;\n            BBUF[1] = v0h;\n            BBUF[2] = v1l;\n            BBUF[3] = v1h;\n            BBUF[4] = v2l;\n            BBUF[5] = v2h;\n            BBUF[6] = v3l;\n            BBUF[7] = v3h;\n            BBUF[8] = v4l;\n            BBUF[9] = v4h;\n            BBUF[10] = v5l;\n            BBUF[11] = v5h;\n            BBUF[12] = v6l;\n            BBUF[13] = v6h;\n            BBUF[14] = v7l;\n            BBUF[15] = v7h;\n        }\n        BBUF.set(B2B_IV, 16); // Second half from IV.\n        const l = u64.fromNumL(this.length);\n        const h = u64.fromNumH(this.length);\n        BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.\n        BBUF[25] = B2B_IV[9] ^ h; // High word.\n        // Invert all bits for last block\n        if (isLast) {\n            BBUF[28] = ~BBUF[28];\n            BBUF[29] = ~BBUF[29];\n        }\n        let j = 0;\n        const s = BSIGMA;\n        // SIGMA selects 64-bit message words; multiply by 2 because `msg` stores\n        // each word as [low32, high32].\n        for (let i = 0; i < 12; i++) {\n            G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n            G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n            G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n            G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n            G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n            G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n            G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n            G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n            G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n            G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n            G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n            G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n            G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n            G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n            G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n            G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n        }\n        this.v0l ^= BBUF[0] ^ BBUF[16];\n        this.v0h ^= BBUF[1] ^ BBUF[17];\n        this.v1l ^= BBUF[2] ^ BBUF[18];\n        this.v1h ^= BBUF[3] ^ BBUF[19];\n        this.v2l ^= BBUF[4] ^ BBUF[20];\n        this.v2h ^= BBUF[5] ^ BBUF[21];\n        this.v3l ^= BBUF[6] ^ BBUF[22];\n        this.v3h ^= BBUF[7] ^ BBUF[23];\n        this.v4l ^= BBUF[8] ^ BBUF[24];\n        this.v4h ^= BBUF[9] ^ BBUF[25];\n        this.v5l ^= BBUF[10] ^ BBUF[26];\n        this.v5h ^= BBUF[11] ^ BBUF[27];\n        this.v6l ^= BBUF[12] ^ BBUF[28];\n        this.v6h ^= BBUF[13] ^ BBUF[29];\n        this.v7l ^= BBUF[14] ^ BBUF[30];\n        this.v7h ^= BBUF[15] ^ BBUF[31];\n        clean(BBUF);\n    }\n    destroy() {\n        this.destroyed = true;\n        clean(this.buffer32);\n        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n    }\n}\n/**\n * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.\n * @param msg - message that would be hashed\n * @param opts - Optional output, MAC, salt, and personalization settings.\n *   `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present,\n *   must be 16 bytes each. See {@link Blake2Opts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with Blake2b.\n * ```ts\n * blake2b(new Uint8Array([97, 98, 99]));\n * ```\n * @example\n * Hash a message with Blake2b while selecting output, MAC, salt, and personalization settings.\n * ```ts\n * blake2b(new Uint8Array([97, 98, 99]), {\n *   dkLen: 32,\n *   key: new Uint8Array(32),\n *   salt: new Uint8Array(16),\n *   personalization: new Uint8Array(16),\n * });\n * ```\n */\nexport const blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts));\n/**\n * BLAKE2-compress core method.\n * Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15`\n * and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves.\n * @param s - flattened sigma schedule bytes\n * @param offset - starting word offset inside `msg`, not a byte offset\n * @param msg - message words\n * @param rounds - round count to execute\n * @param v0 - state word 0\n * @param v1 - state word 1\n * @param v2 - state word 2\n * @param v3 - state word 3\n * @param v4 - state word 4\n * @param v5 - state word 5\n * @param v6 - state word 6\n * @param v7 - state word 7\n * @param v8 - state word 8\n * @param v9 - state word 9\n * @param v10 - state word 10\n * @param v11 - state word 11\n * @param v12 - state word 12\n * @param v13 - state word 13\n * @param v14 - state word 14\n * @param v15 - state word 15\n * @returns Updated compression state words.\n * @example\n * Run the BLAKE2 compression core on zeroed state and message words.\n * ```ts\n * import { _compress } from '@noble/hashes/blake2.js';\n * const state = _compress(\n *   new Uint8Array(16),\n *   0,\n *   new Uint32Array(16),\n *   1,\n *   0, 0, 0, 0, 0, 0, 0, 0,\n *   0, 0, 0, 0, 0, 0, 0, 0\n * );\n * state.v0;\n * ```\n */\n// prettier-ignore\nexport function _compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {\n    let j = 0;\n    for (let i = 0; i < rounds; i++) {\n        ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));\n        ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));\n        ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));\n        ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));\n        ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));\n        ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));\n        ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));\n        ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));\n        ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));\n        ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));\n        ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));\n        ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));\n        ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));\n        ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));\n        ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));\n        ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));\n    }\n    return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };\n}\n// Blake2s reuses the SHA-256 IV words as-is.\nconst B2S_IV = /* @__PURE__ */ SHA256_IV.slice();\n/** Internal blake2s hash class. */\nexport class _BLAKE2s extends _BLAKE2 {\n    // Internal state, same as SHA-256\n    v0 = B2S_IV[0] | 0;\n    v1 = B2S_IV[1] | 0;\n    v2 = B2S_IV[2] | 0;\n    v3 = B2S_IV[3] | 0;\n    v4 = B2S_IV[4] | 0;\n    v5 = B2S_IV[5] | 0;\n    v6 = B2S_IV[6] | 0;\n    v7 = B2S_IV[7] | 0;\n    constructor(opts = {}) {\n        opts = checkOpts({}, opts);\n        const olen = opts.dkLen === undefined ? 32 : opts.dkLen;\n        super(64, olen);\n        checkBlake2Opts(olen, opts, 32, 8, 8);\n        let { key, personalization, salt } = opts;\n        let keyLength = 0;\n        if (key !== undefined) {\n            abytes(key, undefined, 'key');\n            keyLength = key.length;\n        }\n        // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` directly into `h[0]`, since\n        // BLAKE2s stores each state word as one `u32`.\n        this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n        if (salt !== undefined) {\n            abytes(salt, undefined, 'salt');\n            // Copy: u32() would throw on views with byteOffset not divisible by 4.\n            const slt = u32(copyBytes(salt));\n            this.v4 ^= swap8IfBE(slt[0]);\n            this.v5 ^= swap8IfBE(slt[1]);\n        }\n        if (personalization !== undefined) {\n            abytes(personalization, undefined, 'personalization');\n            // Copy: u32() would throw on views with byteOffset not divisible by 4.\n            const pers = u32(copyBytes(personalization));\n            this.v6 ^= swap8IfBE(pers[0]);\n            this.v7 ^= swap8IfBE(pers[1]);\n        }\n        if (key !== undefined) {\n            // Pad to blockLen and update\n            const tmp = new Uint8Array(this.blockLen);\n            tmp.set(key);\n            this.update(tmp);\n            // The padded copy holds key material; buffer/state keep what they need.\n            clean(tmp);\n        }\n    }\n    get() {\n        const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;\n        return [v0, v1, v2, v3, v4, v5, v6, v7];\n    }\n    // prettier-ignore\n    set(v0, v1, v2, v3, v4, v5, v6, v7) {\n        this.v0 = v0 | 0;\n        this.v1 = v1 | 0;\n        this.v2 = v2 | 0;\n        this.v3 = v3 | 0;\n        this.v4 = v4 | 0;\n        this.v5 = v5 | 0;\n        this.v6 = v6 | 0;\n        this.v7 = v7 | 0;\n    }\n    compress(msg, offset, isLast) {\n        const l = u64.fromNumL(this.length);\n        const h = u64.fromNumH(this.length);\n        // Seed v8..v15 from the IV, xor the low/high 32-bit byte counter into\n        // v12/v13, and invert v14 on the final block.\n        // prettier-ignore\n        const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);\n        this.v0 ^= v0 ^ v8;\n        this.v1 ^= v1 ^ v9;\n        this.v2 ^= v2 ^ v10;\n        this.v3 ^= v3 ^ v11;\n        this.v4 ^= v4 ^ v12;\n        this.v5 ^= v5 ^ v13;\n        this.v6 ^= v6 ^ v14;\n        this.v7 ^= v7 ^ v15;\n    }\n    destroy() {\n        this.destroyed = true;\n        clean(this.buffer32);\n        this.set(0, 0, 0, 0, 0, 0, 0, 0);\n    }\n}\n/**\n * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.\n * @param msg - message that would be hashed\n * @param opts - Optional output, MAC, salt, and personalization settings.\n *   `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present,\n *   must be 8 bytes each. See {@link Blake2Opts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with Blake2s.\n * ```ts\n * blake2s(new Uint8Array([97, 98, 99]));\n * ```\n * @example\n * Hash a message with Blake2s while selecting output, MAC, salt, and personalization settings.\n * ```ts\n * blake2s(new Uint8Array([97, 98, 99]), {\n *   dkLen: 16,\n *   key: new Uint8Array(32),\n *   salt: new Uint8Array(8),\n *   personalization: new Uint8Array(8),\n * });\n * ```\n */\nexport const blake2s = /* @__PURE__ */ createHasher((opts) => new _BLAKE2s(opts));\n","/**\n * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.\n *\n * It is advertised as \"the fastest cryptographic hash\". However, it isn't true in JS.\n * Why is this so slow? While it must be 6x faster than blake2b, perf diff is only 20%:\n *\n * * There is only 30% reduction in number of rounds from blake2s\n * * Speed-up comes from tree structure, which is parallelized using SIMD & threading.\n *   These features are not present in JS, so we only get overhead from trees.\n * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.\n * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm\n * @module\n */\nimport { SHA256_IV } from \"./_md.js\";\nimport { fromNumH, fromNumL } from \"./_u64.js\";\nimport { _BLAKE2, _compress } from \"./blake2.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, checkOpts, clean, copyBytes, createHasher, swap32IfBE, u32, u8 } from \"./utils.js\";\n// Constructor-time mode flags (`KEYED_HASH`, `DERIVE_*`) plus per-node tree\n// flags (`CHUNK_*`, `PARENT`, `ROOT`).\nconst B3_Flags = {\n    CHUNK_START: 0b1,\n    CHUNK_END: 0b10,\n    PARENT: 0b100,\n    ROOT: 0b1000,\n    KEYED_HASH: 0b10000,\n    DERIVE_KEY_CONTEXT: 0b100000,\n    DERIVE_KEY_MATERIAL: 0b1000000,\n};\n// Default BLAKE3 IV, cloned from the shared BLAKE2s / SHA-256 IV basis.\nconst B3_IV = /* @__PURE__ */ SHA256_IV.slice();\n// Seven 16-word rounds of BLAKE3 message schedule, generated by repeatedly\n// permuting the identity row.\nconst B3_SIGMA = /* @__PURE__ */ (() => {\n    const Id = Array.from({ length: 16 }, (_, i) => i);\n    const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);\n    const res = [];\n    for (let i = 0, v = Id; i < 7; i++, v = permute(v))\n        res.push(...v);\n    return Uint8Array.from(res);\n})();\n/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */\nexport class _BLAKE3 extends _BLAKE2 {\n    canXOF = true;\n    chunkPos = 0; // Position of current block in chunk\n    // How many chunks we already have; exact while this stays within\n    // JS's safe-integer range.\n    chunksDone = 0;\n    flags = 0 | 0;\n    IV;\n    state;\n    stack = [];\n    // Output\n    posOut = 0;\n    bufferOut32 = new Uint32Array(16);\n    bufferOut;\n    // Index of output chunk; exact while this stays within JS's\n    // safe-integer range.\n    chunkOut = 0;\n    enableXOF = true;\n    constructor(opts = {}, flags = 0) {\n        opts = checkOpts({}, opts);\n        super(64, opts.dkLen === undefined ? 32 : opts.dkLen);\n        const { key, context } = opts;\n        const hasContext = context !== undefined;\n        if (key !== undefined) {\n            if (hasContext)\n                throw new Error('cannot use both \"key\" and \"context\"');\n            abytes(key, 32, 'key');\n            const k = copyBytes(key);\n            this.IV = u32(k);\n            swap32IfBE(this.IV);\n            this.flags = flags | B3_Flags.KEYED_HASH;\n        }\n        else if (hasContext) {\n            abytes(context, undefined, 'context');\n            const ctx = context;\n            const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)\n                .update(ctx)\n                .digest();\n            this.IV = u32(contextKey);\n            swap32IfBE(this.IV);\n            this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;\n        }\n        else {\n            this.IV = B3_IV; // Share the module-private immutable default IV.\n            this.flags = flags;\n        }\n        this.state = this.IV.slice();\n        this.bufferOut = u8(this.bufferOut32);\n    }\n    // _BLAKE2's scalar-state hooks are unused here: BLAKE3 keeps its tree/XOF state in arrays and\n    // copies it directly in _cloneInto().\n    get() {\n        return [];\n    }\n    set() { }\n    // Truncated chunk/parent compression: seed v8..v15 as IV[0..3], t0, t1,\n    // block length, and flags, then keep only the first 8 output words.\n    b2Compress(counter, flags, buf, bufPos = 0) {\n        const { state: s, pos } = this;\n        const t0 = fromNumL(counter);\n        const t1 = fromNumH(counter);\n        // prettier-ignore\n        const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], t0, t1, pos, flags);\n        s[0] = v0 ^ v8;\n        s[1] = v1 ^ v9;\n        s[2] = v2 ^ v10;\n        s[3] = v3 ^ v11;\n        s[4] = v4 ^ v12;\n        s[5] = v5 ^ v13;\n        s[6] = v6 ^ v14;\n        s[7] = v7 ^ v15;\n    }\n    compress(buf, bufPos = 0, isLast = false) {\n        // Compress last block\n        let flags = this.flags;\n        if (!this.chunkPos)\n            flags |= B3_Flags.CHUNK_START;\n        if (this.chunkPos === 15 || isLast)\n            flags |= B3_Flags.CHUNK_END;\n        if (!isLast)\n            this.pos = this.blockLen;\n        this.b2Compress(this.chunksDone, flags, buf, bufPos);\n        this.chunkPos += 1;\n        // If current block is last in chunk (16 blocks), then compress chunks\n        if (this.chunkPos === 16 || isLast) {\n            let chunk = this.state;\n            this.state = this.IV.slice();\n            // If not the last one, compress only when there are trailing zeros in chunk counter\n            // Chunks are used as a binary tree where the current stack is the path.\n            // Zero means the current leaf is finished and can be compressed.\n            // 1 (001) - leaf not finished (just push current chunk to stack)\n            // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)\n            // 3 (011) - last leaf not finished\n            // 4 (100) - leafs finished at depth=1 and depth=2\n            // Reading the low bit is safe for parity, but keep division full-width: shifting would\n            // truncate the safe-integer chunk counter to 32 bits.\n            for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks = Math.floor(chunks / 2)) {\n                if (!(last = this.stack.pop()))\n                    break;\n                this.buffer32.set(last, 0);\n                this.buffer32.set(chunk, 8);\n                this.pos = this.blockLen;\n                this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);\n                chunk = this.state;\n                this.state = this.IV.slice();\n            }\n            this.chunksDone++;\n            this.chunkPos = 0;\n            this.stack.push(chunk);\n        }\n        this.pos = 0;\n    }\n    // Overriding hides _BLAKE2's flat implementation, which would otherwise be inherited\n    // and silently miss the tree state (CV stack, chunk counters; get()/set() are stubs here).\n    _cloneInto(to) {\n        const staleOutput = !!to && to.finished && !to.destroyed; // Save before super copies lifecycle.\n        to = super._cloneInto(to);\n        const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;\n        to.state.set(state);\n        // Clone each CV stack entry by value so extending or destroying the clone\n        // cannot alias the source tree state.\n        to.stack = stack.map((i) => Uint32Array.from(i));\n        if (IV === B3_IV) {\n            if (to.IV !== B3_IV)\n                clean(to.IV);\n            to.IV = B3_IV; // Share immutable default; configured IVs stay private.\n        }\n        else if (to.IV === B3_IV) {\n            to.IV = IV.slice();\n        }\n        else {\n            to.IV.set(IV);\n        }\n        to.flags = flags;\n        to.chunkPos = chunkPos;\n        to.chunksDone = chunksDone;\n        to.posOut = posOut;\n        to.chunkOut = chunkOut;\n        to.enableXOF = this.enableXOF;\n        if (this.finished) {\n            to.bufferOut32.set(this.bufferOut32);\n        }\n        else if (staleOutput) {\n            clean(to.bufferOut32); // Wipe stale output; finish() overwrites scratch.\n        }\n        return to;\n    }\n    destroy() {\n        this.destroyed = true;\n        clean(this.state, this.buffer32, this.bufferOut32);\n        if (this.IV !== B3_IV)\n            clean(this.IV);\n        clean(...this.stack);\n    }\n    // Root/XOF compression: rerun the same ROOT inputs with incrementing output\n    // counter `t` and materialize all 16 output words.\n    // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)\n    b2CompressOut() {\n        const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;\n        const outCounter = this.chunkOut++;\n        const t0 = fromNumL(outCounter);\n        const t1 = fromNumH(outCounter);\n        swap32IfBE(buffer32);\n        // prettier-ignore\n        const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], t0, t1, pos, flags);\n        out32[0] = v0 ^ v8;\n        out32[1] = v1 ^ v9;\n        out32[2] = v2 ^ v10;\n        out32[3] = v3 ^ v11;\n        out32[4] = v4 ^ v12;\n        out32[5] = v5 ^ v13;\n        out32[6] = v6 ^ v14;\n        out32[7] = v7 ^ v15;\n        out32[8] = s[0] ^ v8;\n        out32[9] = s[1] ^ v9;\n        out32[10] = s[2] ^ v10;\n        out32[11] = s[3] ^ v11;\n        out32[12] = s[4] ^ v12;\n        out32[13] = s[5] ^ v13;\n        out32[14] = s[6] ^ v14;\n        out32[15] = s[7] ^ v15;\n        swap32IfBE(buffer32);\n        swap32IfBE(out32);\n        this.posOut = 0;\n    }\n    finish() {\n        if (this.finished)\n            return;\n        this.finished = true;\n        // Padding\n        this.buffer.fill(0, this.pos);\n        // Process last chunk\n        let flags = this.flags | B3_Flags.ROOT;\n        if (this.stack.length) {\n            // Finalize the current chunk first, then rerun the last parent\n            // compression as ROOT with t = 0 and b = 64.\n            flags |= B3_Flags.PARENT;\n            swap32IfBE(this.buffer32);\n            this.compress(this.buffer32, 0, true);\n            swap32IfBE(this.buffer32);\n            this.chunksDone = 0;\n            this.pos = this.blockLen;\n        }\n        else {\n            flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;\n        }\n        this.flags = flags;\n        this.b2CompressOut();\n    }\n    writeInto(out) {\n        aexists(this, false);\n        abytes(out);\n        this.finish();\n        const { blockLen, bufferOut } = this;\n        for (let pos = 0, len = out.length; pos < len;) {\n            if (this.posOut >= blockLen)\n                this.b2CompressOut();\n            const take = Math.min(blockLen - this.posOut, len - pos);\n            out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n            this.posOut += take;\n            pos += take;\n        }\n        return out;\n    }\n    xofInto(out) {\n        if (!this.enableXOF)\n            throw new Error('no XOF after digest()');\n        return this.writeInto(out);\n    }\n    xof(bytes) {\n        anumber(bytes);\n        return this.xofInto(new Uint8Array(bytes));\n    }\n    digestInto(out) {\n        aoutput(out, this);\n        if (this.finished)\n            throw new Error('digest() was already called');\n        this.enableXOF = false;\n        // `aoutput(...)` allows oversized buffers; digestInto() must fill only the configured digest.\n        this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));\n        this.destroy();\n    }\n    digest() {\n        const out = new Uint8Array(this.outputLen);\n        this.digestInto(out);\n        return out;\n    }\n}\n/**\n * BLAKE3 hash function. Can be used as MAC and KDF.\n * @param msg - message that would be hashed\n * @param opts - Optional output, MAC, or KDF configuration. `key` must be\n *   exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be\n *   0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}.\n * @returns Digest bytes.\n * @example\n * Hash, MAC, or derive key material with BLAKE3.\n * ```ts\n * import { blake3 } from '@noble/hashes/blake3.js';\n * import { utf8ToBytes } from '@noble/hashes/utils.js';\n * const data = new Uint8Array(32);\n * const hash = blake3(data);\n * const mac = blake3(data, { key: new Uint8Array(32) });\n * const kdf = blake3(data, { context: utf8ToBytes('application name') });\n * const xof = blake3(data, { dkLen: 64 });\n * ```\n */\nexport const blake3 = /* @__PURE__ */ createHasher((opts = {}) => new _BLAKE3(opts));\n","// Identity of the native runtime and of locks, byte for byte as Rust:\n// `native_host_id()` (`AGENT_TOOL_HOST_ID`, else /etc/hostname +\n// /etc/machine-id), `runtime_id` = `native:` + blake3(target JSON)[..24],\n// workdir lock = blake3(workdir display string)[..24].lock (vector (h)).\n\nimport { blake3 } from '@noble/hashes/blake3.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport type { JsonValue } from '../../core/types'\nimport { canonicalJson } from '../../core/json'\nimport { deno, joinPath } from './deno_api'\n\n/** Names the local execution environment where the hostname is not a stable identity (`HOST_ID_ENV`). */\nexport const HOST_ID_ENV = 'AGENT_TOOL_HOST_ID'\n\nexport function blake3Hex(text: string): string {\n  return bytesToHex(blake3(new TextEncoder().encode(text)))\n}\n\nasync function readText(path: string): Promise<string | null> {\n  try {\n    return await deno().readTextFile(path)\n  } catch {\n    return null\n  }\n}\n\n/** The inputs of `native_host_id` (`null`: unset / unreadable). */\nexport interface HostIdInputs {\n  agent_tool_host_id: string | null\n  etc_hostname: string | null\n  hostname_env: string | null\n  machine_id: string | null\n}\n\n/** `native_host_id_from`: `AGENT_TOOL_HOST_ID` when not blank, else /etc/hostname (or `HOSTNAME`) + /etc/machine-id. */\nexport function nativeHostIdFrom(i: HostIdInputs): string {\n  const id = i.agent_tool_host_id?.trim()\n  if (id) return `host:${id}:`\n  const host = i.etc_hostname ?? i.hostname_env ?? 'unknown'\n  return `host:${host.trim()}:${(i.machine_id ?? '').trim()}`\n}\n\n/** `native_host_id()` of this machine. */\nexport async function nativeHostId(): Promise<string> {\n  const env = deno().env.get(HOST_ID_ENV) ?? null\n  if (env?.trim()) return nativeHostIdFrom({ agent_tool_host_id: env, etc_hostname: null, hostname_env: null, machine_id: null })\n  return nativeHostIdFrom({\n    agent_tool_host_id: env,\n    etc_hostname: await readText('/etc/hostname'),\n    hostname_env: deno().env.get('HOSTNAME') ?? null,\n    machine_id: await readText('/etc/machine-id'),\n  })\n}\n\n/** `native_target`: what a native runtime's identity is made of. */\nexport function nativeTarget(hostId: string, uid: string): { host: string; uid: string } {\n  return { host: hostId, uid }\n}\n\n/** The exact text blake3 hashes for a runtime id (serde_json: sorted keys, compact). */\nexport function targetText(target: JsonValue): string {\n  return canonicalJson(target)\n}\n\n/** `derive_runtime_id`: the configured id, else `<kind>:` + blake3(target)[..24]. */\nexport function deriveRuntimeId(configuredId: string | null | undefined, kind: string, target: JsonValue): string {\n  return configuredId ?? runtimeIdOf(kind, target)\n}\n\n/** `<kind>:` + the first 24 hex of blake3 over the target's JSON (serde_json: sorted keys, compact). */\nexport function runtimeIdOf(kind: string, target: JsonValue): string {\n  return `${kind}:${blake3Hex(targetText(target)).slice(0, 24)}`\n}\n\n/** `<lockDir>/<blake3(workdir)[..24]>.lock` (`workdir_lock_path`). */\nexport function workdirLockPath(lockDir: string, workdir: string): string {\n  return joinPath(lockDir, `${blake3Hex(workdir).slice(0, 24)}.lock`)\n}\n","// The `bash` tool group of the native runtime (Rust `builtin_bash_group`):\n// `read_file`, `write_file`, `edit_file`, `shell`. Names, descriptions and\n// argument schemas are Rust's to the byte — they are advertised to models and\n// saved in run.json, and a run moves between the two executors with them.\n// Semantics follow `file_tools.rs` (workspace policy on real paths),\n// `read_tool.rs` (`read_file` dedup key) and `llm_bash.rs` (`shell` in its\n// wait form: the command runs in the call until it ends or `timeout_ms`,\n// output in `runs/<run_id>/exec/<call_id>/{command,stdout,stderr,exit}`,\n// head 1/4 + tail 3/4 of 64 KB, `XLLM_CALL_ID` / `XLLM_RUN_ID`).\n//\n// Difference from Rust: `Deno.Command` cannot start the command in its own\n// process group, so a timeout or an interrupt kills the wrapper process only;\n// what the command started keeps running (Rust kills the whole group).\n\nimport type { JsonValue, ToolSpecLite } from '../../core/types'\nimport { canonicalJson, isObject } from '../../core/json'\nimport { normalizePath } from '../../core/config'\nimport type { ToolCallCtx } from '../../core/deps'\nimport type { AgentToolResult } from '../../runtime/tool_result'\nimport { deno, errorText, isDir, isNotFound, joinPath, parentDir } from './deno_api'\nimport type { DenoChildProcess } from './deno_api'\nimport { blake3Hex } from './identity'\n\nexport const TOOL_READ_FILE = 'read_file'\nexport const TOOL_WRITE_FILE = 'write_file'\nexport const TOOL_EDIT_FILE = 'edit_file'\nexport const TOOL_SHELL = 'shell'\nexport const BASH_GROUP_TOOLS = [TOOL_READ_FILE, TOOL_WRITE_FILE, TOOL_EDIT_FILE, TOOL_SHELL]\n\n/** `EXEC_MAX_OUTPUT_BYTES`: what one `shell` call keeps of each stream. */\nexport const EXEC_MAX_OUTPUT_BYTES = 64 * 1024\n/** Bytes of output in a progress / cancel / interrupted text (`OUTPUT_TAIL_BYTES`). */\nexport const OUTPUT_TAIL_BYTES = 2048\nexport const TIMEOUT_EXIT_CODE = 124\nexport const ENV_CALL_ID = 'XLLM_CALL_ID'\nexport const ENV_RUN_ID = 'XLLM_RUN_ID'\nconst LOCAL_ENGINE = 'native'\nconst READ_FILE_PREVIEW_MAX_LINES = 200\nconst CMD_PARAM_PREVIEW_KEEP_CHARS = 32\nconst HISTORY_COMPACT_CMD_MAX_CHARS = 96\n\n// ---------------------------------------------------------------- errors\n\nexport type ToolErrorKind = 'invalid_args' | 'exec_failed' | 'timeout' | 'transport' | 'cancelled'\n\n/** `AgentToolError`: the message is its Display text. */\nexport class NativeToolError extends Error {\n  constructor(readonly kind: ToolErrorKind, readonly detail: string, readonly effectUnknown = false) {\n    super(kind === 'invalid_args' ? `invalid args: ${detail}`\n      : kind === 'exec_failed' ? `execution failed: ${detail}`\n        : kind === 'timeout' ? 'timeout'\n          : kind === 'transport' ? `runtime transport: ${detail}` : `cancelled: ${detail}`)\n    this.name = 'NativeToolError'\n  }\n}\n\nconst invalidArgs = (m: string) => new NativeToolError('invalid_args', m)\nconst execFailed = (m: string) => new NativeToolError('exec_failed', m)\n\n// ---------------------------------------------------------------- results\n\n/** `tokenize_bash_command_line`. */\nexport function tokenizeBashCommandLine(line: string): string[] | undefined {\n  const tokens: string[] = []\n  let cur = ''\n  let single = false\n  let double = false\n  const chars = [...line]\n  for (let i = 0; i < chars.length; i++) {\n    const ch = chars[i]\n    if (ch === \"'\" && !double) single = !single\n    else if (ch === '\"' && !single) double = !double\n    else if (ch === '\\\\' && !single) {\n      if (i + 1 < chars.length) cur += chars[++i]\n    } else if (/\\s/.test(ch) && !single && !double) {\n      if (cur) {\n        tokens.push(cur)\n        cur = ''\n      }\n    } else cur += ch\n  }\n  if (single || double) return undefined\n  if (cur) tokens.push(cur)\n  return tokens\n}\n\nfunction truncateText(text: string, max: number): string {\n  const chars = [...text]\n  return chars.length <= max ? text : `${chars.slice(0, max).join('')}...[TRUNCATED]`\n}\n\nfunction defaultTitle(r: AgentToolResult): string {\n  const line = r.cmd_name !== undefined ? (r.cmd_args?.trim() ? `${r.cmd_name} ${r.cmd_args.trim()}` : r.cmd_name) : undefined\n  const cmd = (line !== undefined ? truncateText(line.trim(), HISTORY_COMPACT_CMD_MAX_CHARS) : '') || 'action'\n  const status = r.status === 'pending' ? (r.pending_reason !== undefined ? `pending (${r.pending_reason})` : 'pending') : r.status\n  return `${cmd} => ${status}`\n}\n\n/** `build_builtin_tool_result(detail, cmd_line, summary)` (+ `with_tool`). */\nexport function builtinResult(tool: string, detail: JsonValue, cmdLine: string, summary: string): AgentToolResult {\n  const r: AgentToolResult = { agent_tool_protocol: '1', tool, status: 'success', summary, detail }\n  const tokens = tokenizeBashCommandLine(cmdLine)\n  const parts = tokens && tokens.length ? tokens : cmdLine.split(/\\s+/).filter(Boolean)\n  if (parts.length) {\n    r.cmd_name = parts[0]\n    if (parts.length > 1) r.cmd_args = parts.slice(1).join(' ')\n  }\n  r.title = defaultTitle(r)\n  return r\n}\n\nfunction withOutput(r: AgentToolResult, output: string): AgentToolResult {\n  if (output.trim()) r.output = output\n  else delete r.output\n  return r\n}\n\n// ---------------------------------------------------------------- paths\n\nfunction pathStartsWith(p: string, root: string): boolean {\n  if (root === '/') return p.startsWith('/')\n  return p === root || p.startsWith(`${root}/`)\n}\n\nfunction checkAllowed(path: string, roots: string[]) {\n  if (roots.length === 0 || roots.some(r => pathStartsWith(path, r))) return\n  throw invalidArgs(`path not allowed by policy: ${path}`)\n}\n\n/** Real path of `path`, its missing tail appended (`canonical_missing`). */\nasync function canonicalMissing(path: string): Promise<string> {\n  let ancestor = path.replace(/\\/+$/, '') || '/'\n  const missing: string[] = []\n  for (;;) {\n    try {\n      const real = await deno().realPath(ancestor)\n      return normalizePath(joinPath(real, ...missing.slice().reverse()))\n    } catch (e) {\n      if (!isNotFound(e)) throw execFailed(errorText(e))\n      try {\n        await deno().lstat(ancestor)\n        throw invalidArgs(`dangling symlink: ${ancestor}`)\n      } catch (le) {\n        if (le instanceof NativeToolError) throw le\n      }\n      const name = ancestor.slice(ancestor.lastIndexOf('/') + 1)\n      if (!name || name === '..') throw invalidArgs(`cannot resolve ${path}`)\n      if (name !== '.') missing.push(name)\n      const parent = parentDir(ancestor)\n      if (parent === ancestor || ancestor === '/') throw invalidArgs('path has no existing ancestor')\n      ancestor = parent\n    }\n  }\n}\n\n/** `LocalFileBackend::resolve`: the lexical path and the real path must both be under an allowed root. */\nexport async function resolvePath(root: string, raw: string, allowed: string[]): Promise<string> {\n  if (!raw.trim()) throw invalidArgs('path cannot be empty')\n  const candidate = raw.startsWith('/') ? raw : joinPath(root, raw)\n  checkAllowed(normalizePath(candidate), allowed)\n  const real = await canonicalMissing(candidate)\n  const roots = await Promise.all(allowed.map(canonicalMissing))\n  checkAllowed(real, roots)\n  return real\n}\n\nfunction encodeObjSegment(seg: string): string {\n  let out = ''\n  for (const b of new TextEncoder().encode(seg)) {\n    const c = String.fromCharCode(b)\n    out += /[A-Za-z0-9\\-._~!$&'()*+,;=:@]/.test(c) ? c : `%${b.toString(16).toUpperCase().padStart(2, '0')}`\n  }\n  return out\n}\n\n/** `FileToolConfig::cyfs_url`: a file below `$BUCKYOS_ROOT/data` is the Zone file `cyfs:///<path>`. */\nfunction cyfsUrl(dfsRoot: string | undefined, abs: string): string | undefined {\n  if (!dfsRoot) return undefined\n  const root = normalizePath(dfsRoot)\n  if (!pathStartsWith(abs, root)) return undefined\n  const rel = abs.slice(root.length).split('/').filter(s => s && s !== '.')\n  return `cyfs://${['', ...rel].map(encodeObjSegment).join('/') || '/'}`\n}\n\n// ---------------------------------------------------------------- args\n\nfunction serdeKind(v: JsonValue): string {\n  if (v === null) return 'null'\n  if (typeof v === 'boolean') return `boolean \\`${v}\\``\n  if (typeof v === 'number') return Number.isInteger(v) ? `integer \\`${v}\\`` : `floating point \\`${v}\\``\n  if (typeof v === 'string') return `string ${JSON.stringify(v)}`\n  if (Array.isArray(v)) return 'sequence'\n  return 'map'\n}\n\nfunction argError(tool: string, reason: string): NativeToolError {\n  return invalidArgs(`invalid args for \\`${tool}\\`: ${reason}`)\n}\n\nfunction reqString(tool: string, args: Record<string, JsonValue>, key: string): string {\n  const v = args[key]\n  if (v === undefined) throw argError(tool, `missing field \\`${key}\\``)\n  if (typeof v !== 'string') throw argError(tool, `invalid type: ${serdeKind(v)}, expected a string`)\n  return v\n}\n\nfunction optString(tool: string, args: Record<string, JsonValue>, key: string): string | undefined {\n  const v = args[key]\n  if (v === undefined || v === null) return undefined\n  if (typeof v !== 'string') throw argError(tool, `invalid type: ${serdeKind(v)}, expected a string`)\n  return v\n}\n\n// ---------------------------------------------------------------- text helpers\n\nconst utf8 = new TextEncoder()\n\nfunction byteLength(s: string): number {\n  return utf8.encode(s).length\n}\n\nfunction decodeLossy(bytes: Uint8Array): string {\n  return new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes)\n}\n\n/** `split_inclusive('\\n')`. */\nfunction splitLinesPreserveEnding(content: string): string[] {\n  if (!content) return []\n  return content.match(/[^\\n]*\\n|[^\\n]+$/g) ?? []\n}\n\n/** `str::lines()`. */\nfunction strLines(s: string): string[] {\n  if (!s) return []\n  const parts = s.split('\\n')\n  if (parts[parts.length - 1] === '') parts.pop()\n  return parts.map(l => (l.endsWith('\\r') ? l.slice(0, -1) : l))\n}\n\nfunction trimEndLineBreaks(s: string): string {\n  return s.replace(/[\\r\\n]+$/, '')\n}\n\nfunction compactCmdParamPreview(raw: string): string {\n  const escaped = raw.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\r/g, '\\\\r').replace(/\\n/g, '\\\\n')\n  const totalLines = raw ? Math.max(strLines(raw).length, 1) : 0\n  const chars = [...escaped]\n  if (chars.length <= CMD_PARAM_PREVIEW_KEEP_CHARS * 2) return escaped\n  return `${chars.slice(0, CMD_PARAM_PREVIEW_KEEP_CHARS).join('')}...(total ${totalLines} lines)...${chars.slice(-CMD_PARAM_PREVIEW_KEEP_CHARS).join('')}`\n}\n\nfunction buildSimpleDiff(path: string, before: string, after: string): string {\n  const a = strLines(before)\n  const b = strLines(after)\n  const body: string[] = []\n  for (let i = 0; i < Math.max(a.length, b.length); i++) {\n    const o = a[i]\n    const n = b[i]\n    if (o !== undefined && n !== undefined) {\n      if (o === n) body.push(` ${o}`)\n      else body.push(`-${o}`, `+${n}`)\n    } else if (o !== undefined) body.push(`-${o}`)\n    else if (n !== undefined) body.push(`+${n}`)\n  }\n  return [`--- a/${path}`, `+++ b/${path}`, `@@ -1,${a.length} +1,${b.length} @@`, ...body].join('\\n')\n}\n\n// ---------------------------------------------------------------- read_file range\n\ntype LineMarker = number | 'end'\n\ninterface LineRangeSpec {\n  start?: LineMarker\n  end?: LineMarker\n  count?: number\n  defaultEnd: 'same_as_start' | 'end' | 'tail_if_start_negative'\n}\n\nfunction parseMarkerToken(raw: string, rangeText: string): LineMarker {\n  const t = raw.trim()\n  if (t === '$') return 'end'\n  if (t.startsWith('+') || !/^-?\\d+$/.test(t)) throw invalidArgs(`invalid range text \\`${rangeText}\\``)\n  const v = Number(t)\n  if (v === 0) throw invalidArgs('range must be 1-based, zero is invalid')\n  return v\n}\n\nfunction parseCountText(raw: string, rangeText: string): number {\n  const t = raw.trim()\n  if (!t.startsWith('+')) throw invalidArgs(`invalid range text \\`${rangeText}\\``)\n  const c = t.slice(1).trim()\n  if (!/^\\d+$/.test(c)) throw invalidArgs(`invalid range text \\`${rangeText}\\``)\n  const n = Number(c)\n  if (n === 0) throw invalidArgs('range count must be positive integer')\n  return n\n}\n\nfunction parseMarkerJson(v: JsonValue, name: string): LineMarker {\n  if (typeof v === 'string') return parseMarkerToken(v, name)\n  if (typeof v === 'number' && Number.isInteger(v)) {\n    if (v === 0) throw invalidArgs(`${name} must be non-zero integer`)\n    return v\n  }\n  throw invalidArgs(`${name} must be integer or \\`$\\``)\n}\n\nfunction parseCountJson(v: JsonValue, name: string): number {\n  if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) throw invalidArgs(`${name} must be positive integer`)\n  return v\n}\n\nfunction parseRangeText(raw: string): LineRangeSpec | undefined {\n  const text = raw.trim()\n  if (!text || text === '-') return undefined\n  if (text.includes(',') || text.includes(':')) {\n    if (text.includes(',') && text.includes(':')) throw invalidArgs(`invalid range text \\`${raw}\\``)\n    const parts = text.split(text.includes(',') ? ',' : ':')\n    if (parts.length !== 2) throw invalidArgs(`invalid range text \\`${raw}\\``)\n    const start = parts[0].trim() ? parseMarkerToken(parts[0].trim(), raw) : undefined\n    const endText = parts[1].trim()\n    if (endText.startsWith('+')) {\n      if (start === undefined) throw invalidArgs(`range \\`${raw}\\` with \\`+count\\` requires start`)\n      return { start, count: parseCountText(endText, raw), defaultEnd: 'same_as_start' }\n    }\n    return { start, end: endText ? parseMarkerToken(endText, raw) : undefined, defaultEnd: 'end' }\n  }\n  const dash = text.indexOf('-')\n  if (dash >= 0) {\n    const left = text.slice(0, dash).trim()\n    const right = text.slice(dash + 1).trim()\n    if (left && right && /^\\d+$/.test(left) && /^\\d+$/.test(right)) {\n      return { start: parseMarkerToken(left, raw), end: parseMarkerToken(right, raw), defaultEnd: 'same_as_start' }\n    }\n  }\n  return { start: parseMarkerToken(text, raw), defaultEnd: 'same_as_start' }\n}\n\nfunction parseRangeSpec(raw: JsonValue | undefined): LineRangeSpec | undefined {\n  if (raw === undefined || raw === null) return undefined\n  if (isObject(raw)) {\n    const start = raw.start !== undefined ? parseMarkerJson(raw.start, 'range.start') : undefined\n    const end = raw.end !== undefined ? parseMarkerJson(raw.end, 'range.end') : undefined\n    const count = raw.count !== undefined ? parseCountJson(raw.count, 'range.count') : undefined\n    if (count !== undefined && end !== undefined) throw invalidArgs('range cannot set both `end` and `count`')\n    if (count !== undefined && start === undefined) throw invalidArgs('range.count requires range.start')\n    if (start === undefined && end === undefined && count === undefined) {\n      throw invalidArgs('range object must contain at least one of start/end/count')\n    }\n    return { start, end, count, defaultEnd: 'tail_if_start_negative' }\n  }\n  if (Array.isArray(raw)) {\n    if (raw.length === 0 || raw.length > 2) throw invalidArgs('range array must be [start] or [start,end]')\n    return {\n      start: parseMarkerJson(raw[0], 'range[0]'),\n      end: raw.length === 2 ? parseMarkerJson(raw[1], 'range[1]') : undefined,\n      defaultEnd: 'same_as_start',\n    }\n  }\n  if (typeof raw === 'number' && Number.isInteger(raw)) return { start: parseMarkerJson(raw, 'range'), defaultEnd: 'same_as_start' }\n  if (typeof raw === 'string') return parseRangeText(raw)\n  throw invalidArgs('range must be string/number/array/object')\n}\n\nfunction resolveMarker(m: LineMarker, total: number): number {\n  if (m === 'end') return total\n  return m > 0 ? m : total + m + 1\n}\n\nfunction resolveRange(spec: LineRangeSpec, total: number): [number, number] {\n  const startMarker = spec.start ?? 1\n  const startRaw = resolveMarker(startMarker, total)\n  let endRaw: number\n  if (spec.count !== undefined) endRaw = startRaw + spec.count - 1\n  else if (spec.end !== undefined) endRaw = resolveMarker(spec.end, total)\n  else if (spec.defaultEnd === 'same_as_start') endRaw = startRaw\n  else if (spec.defaultEnd === 'end') endRaw = total\n  else endRaw = typeof startMarker === 'number' && startMarker < 0 ? total : startRaw\n  return [Math.min(Math.max(startRaw, 1), total + 1), Math.min(Math.max(endRaw, 0), total)]\n}\n\nfunction readCmdLine(path: string, firstChunk: string | undefined, range: JsonValue | undefined): string {\n  let cmd = `${TOOL_READ_FILE} ${path}`\n  if (firstChunk !== undefined) cmd += ` first_chunk=\"${compactCmdParamPreview(firstChunk)}\"`\n  if (range !== undefined && range !== null) {\n    const text = typeof range === 'string' ? range : canonicalJson(range)\n    if (text.trim()) cmd += ` range=${text}`\n  }\n  return cmd\n}\n\n// ---------------------------------------------------------------- tools\n\nexport interface FileToolConfig {\n  /** The working directory (real path). */\n  root: string\n  allowedRead: string[]\n  allowedWrite: string[]\n  /** `$BUCKYOS_ROOT/data` on this machine. */\n  dfsRoot?: string\n}\n\nexport interface NativeToolCtx {\n  call_id: string\n  run_id: string\n  run_dir?: string\n  call: ToolCallCtx\n}\n\nexport interface NativeTool {\n  spec: ToolSpecLite\n  idempotent: boolean\n  /** Observes the call's cancellation itself (`shell`). */\n  cancellable: boolean\n  call(args: Record<string, JsonValue>, ctx: NativeToolCtx): Promise<AgentToolResult>\n}\n\nexport const READ_FILE_SPEC: ToolSpecLite = {\n  name: TOOL_READ_FILE,\n  description: 'Read a text file. range selects 1-based lines (\"120-200\", \"120:$\", \"120:+20\", \"-50:$\" for the last 50); first_chunk starts the read at the first occurrence of that text. Paths are relative to the working directory; paths outside it only where the run\\'s filesystem policy allows.',\n  args_schema: {\n    properties: {\n      first_chunk: { description: 'Start the read at the first occurrence of this text (range then counts from there).', type: 'string' },\n      path: { description: 'File to read, relative to the working directory.', type: 'string' },\n      range: { description: '1-based line range: \"120-200\", \"120:$\" (to the end), \"120:+20\" (20 lines from 120); negative numbers count from the end (\"-50:$\").' },\n    },\n    required: ['path'],\n    type: 'object',\n  },\n}\n\nexport const WRITE_FILE_SPEC: ToolSpecLite = {\n  name: TOOL_WRITE_FILE,\n  description: 'Write a text file: mode \"write\" (default) creates or overwrites it, \"append\" adds to its end, \"new\" creates it and fails if it exists. Parent directories are created. Paths are relative to the working directory; paths outside it only where the run\\'s filesystem policy allows.',\n  args_schema: {\n    properties: {\n      content: { description: 'The text to write.', type: 'string' },\n      mode: { description: '`write` (default): create or overwrite; `append`: add to the end; `new`: create, fail if the file exists.', type: 'string' },\n      path: { description: 'File to write, relative to the working directory.', type: 'string' },\n    },\n    required: ['content', 'path'],\n    type: 'object',\n  },\n}\n\nexport const EDIT_FILE_SPEC: ToolSpecLite = {\n  name: TOOL_EDIT_FILE,\n  description: 'Replace the one exact occurrence of old_string with new_string in a text file. Fails when old_string is absent or occurs more than once: include enough surrounding text to make it unique. Paths are relative to the working directory; paths outside it only where the run\\'s filesystem policy allows.',\n  args_schema: {\n    properties: {\n      new_string: { description: 'The replacement text.', type: 'string' },\n      old_string: { description: 'The exact text to replace; it must occur exactly once.', type: 'string' },\n      path: { description: 'File to edit, relative to the working directory.', type: 'string' },\n    },\n    required: ['new_string', 'old_string', 'path'],\n    type: 'object',\n  },\n}\n\nasync function readRaw(path: string): Promise<Uint8Array> {\n  try {\n    return await deno().readFile(path)\n  } catch (e) {\n    throw execFailed(`read file failed: ${errorText(e)}`)\n  }\n}\n\nasync function readText(path: string): Promise<string> {\n  return decodeLossy(await readRaw(path))\n}\n\n/** `BINARY_PROBE_BYTES`: how much of a file `looksBinary` inspects. */\nconst BINARY_PROBE_BYTES = 8192\n\n/** `looks_binary`: a NUL byte near the start. Text in a legacy encoding (GBK, Latin-1) has none, so it still reads, lossily. */\nfunction looksBinary(bytes: Uint8Array): boolean {\n  return bytes.subarray(0, BINARY_PROBE_BYTES).includes(0)\n}\n\nasync function writeText(path: string, text: string): Promise<void> {\n  try {\n    await deno().mkdir(parentDir(path), { recursive: true })\n  } catch (e) {\n    throw execFailed(errorText(e))\n  }\n  try {\n    await deno().writeFile(path, utf8.encode(text))\n  } catch (e) {\n    throw execFailed(`write file failed: ${errorText(e)}`)\n  }\n}\n\nasync function exists(path: string): Promise<boolean> {\n  try {\n    await deno().stat(path)\n    return true\n  } catch (e) {\n    if (isNotFound(e)) return false\n    throw execFailed(errorText(e))\n  }\n}\n\n/** `read_file` (`ReadFileTool` behind `DedupReadFile`). */\nexport function readFileTool(cfg: FileToolConfig): NativeTool {\n  return {\n    spec: READ_FILE_SPEC,\n    idempotent: true,\n    cancellable: false,\n    async call(args) {\n      const rawPath = reqString(TOOL_READ_FILE, args, 'path')\n      const firstChunk = optString(TOOL_READ_FILE, args, 'first_chunk')\n      const range = args.range === null ? undefined : args.range\n      const filePath = rawPath.trim()\n      if (!filePath) throw invalidArgs('missing required arg `path`')\n      const abs = await resolvePath(cfg.root, filePath, cfg.allowedRead)\n      const raw = await readRaw(abs)\n      if (looksBinary(raw)) {\n        throw invalidArgs(`\\`${filePath}\\` is a binary file (${raw.length} bytes): read_file only reads text. Use llm_understand_media for images, PDFs and office documents, or a shell command that converts or inspects the format.`)\n      }\n      const full = decodeLossy(raw)\n      let chunk: string\n      let matched = true\n      let chunkStart = 1\n      if (firstChunk !== undefined) {\n        const pos = full.indexOf(firstChunk)\n        if (pos >= 0) {\n          chunk = full.slice(pos)\n          chunkStart = (full.slice(0, pos).match(/\\n/g) ?? []).length + 1\n        } else {\n          chunk = ''\n          matched = false\n        }\n      } else chunk = full\n      const lines = splitLinesPreserveEnding(chunk)\n      const total = lines.length\n      const spec = parseRangeSpec(range)\n      let start: number\n      let end: number\n      let label = ''\n      if (spec) {\n        ;[start, end] = resolveRange(spec, total)\n        label = `${start}-${end}`\n      } else if (total === 0) {\n        start = 1\n        end = 0\n      } else {\n        start = 1\n        end = total\n      }\n      const si = Math.min(Math.max(start - 1, 0), total)\n      const ei = Math.min(end, total)\n      const selected = si < ei ? lines.slice(si, ei) : []\n      const content = selected.join('')\n      const count = selected.length\n      const startLine = count === 0 ? null : chunkStart + si\n      const endLine = startLine === null ? null : startLine + Math.max(count - 1, 0)\n      let preview = ''\n      if (startLine !== null) {\n        preview = selected.slice(0, READ_FILE_PREVIEW_MAX_LINES).map((l, i) => `${startLine + i}: ${trimEndLineBreaks(l)}`).join('\\n')\n        if (selected.length > READ_FILE_PREVIEW_MAX_LINES) preview += `${preview ? '\\n' : ''}... truncated to ${READ_FILE_PREVIEW_MAX_LINES} lines`\n      }\n      const bytes = byteLength(content)\n      const cmdLine = readCmdLine(filePath, firstChunk, range)\n      let summary: string\n      if (matched) {\n        const linesText = startLine !== null && endLine !== null\n          ? (startLine === endLine ? `1 line at ${startLine}` : `${count} lines at ${startLine}-${endLine}`) : '0 lines'\n        const base = `succeeded, read ${bytes} bytes across ${linesText}`\n        summary = preview ? `${base}\\n\\`\\`\\`content\\n${preview}\\n\\`\\`\\`` : base\n      } else {\n        summary = 'succeeded, first_chunk was not found, read 0 bytes across 0 lines'\n      }\n      const detail: Record<string, JsonValue> = {}\n      const url = cyfsUrl(cfg.dfsRoot, abs)\n      if (url !== undefined) detail.cyfs_url = url\n      Object.assign(detail, {\n        content, matched, line_range: label, bytes, line_count: count, start_line: startLine, end_line: endLine,\n        preview_truncated: count > READ_FILE_PREVIEW_MAX_LINES,\n      })\n      const result = builtinResult(TOOL_READ_FILE, detail, cmdLine, summary)\n      result.title = `${cmdLine} => ${matched ? 'success' : 'anchor not found'}`\n      return withReadDedup(result, filePath, canonicalJson(Object.fromEntries(Object.entries(args).filter(([k]) => k !== 'path'))))\n    },\n  }\n}\n\n/** `with_read_dedup`: the same window of the same content read again answers with one line. */\nfunction withReadDedup(result: AgentToolResult, what: string, window: string): AgentToolResult {\n  if (result.status !== 'success') return result\n  const text = result.output?.trim() ? result.output : result.summary.trim() ? result.summary : canonicalJson(result.detail)\n  result.dedup = {\n    key: `read:${what}#${window}:${blake3Hex(text).slice(0, 16)}`,\n    hint: `\\`${what}\\` is unchanged since you read it earlier in this run; use that content.`,\n  }\n  return result\n}\n\nfunction normalizeWriteMode(raw: string | undefined): 'new' | 'append' | 'write' {\n  const m = (raw ?? 'write').trim().toLowerCase()\n  if (m === 'new' || m === 'create') return 'new'\n  if (m === 'append') return 'append'\n  if (m === '' || m === 'write' || m === 'overwrite') return 'write'\n  throw invalidArgs(`invalid write mode \\`${m}\\`, expected new/append/write`)\n}\n\n/** `write_file`. */\nexport function writeFileTool(cfg: FileToolConfig): NativeTool {\n  return {\n    spec: WRITE_FILE_SPEC,\n    idempotent: false,\n    cancellable: false,\n    async call(args) {\n      const rawPath = reqString(TOOL_WRITE_FILE, args, 'path')\n      const content = reqString(TOOL_WRITE_FILE, args, 'content')\n      const rawMode = optString(TOOL_WRITE_FILE, args, 'mode')\n      let cmdMode: string\n      try {\n        cmdMode = normalizeWriteMode(rawMode)\n      } catch {\n        cmdMode = 'write'\n      }\n      const cmdLine = `${TOOL_WRITE_FILE} ${rawPath} mode=${cmdMode}`\n      const filePath = rawPath.trim()\n      if (!filePath) throw invalidArgs('missing required arg `path`')\n      const mode = normalizeWriteMode(rawMode)\n      const abs = await resolvePath(cfg.root, filePath, cfg.allowedWrite)\n      const present = await exists(abs)\n      if (mode === 'new' && present) throw invalidArgs(`write mode \\`new\\` requires target file not exist: ${filePath}`)\n      const original = present ? await readText(abs) : ''\n      const operation = mode === 'append' ? 'append' : mode === 'new' ? 'new' : present ? 'write' : 'create'\n      const updated = mode === 'append' ? `${original}${content}` : content\n      await writeText(abs, updated)\n      const lineCount = splitLinesPreserveEnding(content).length\n      const detail: Record<string, JsonValue> = {}\n      const url = cyfsUrl(cfg.dfsRoot, abs)\n      if (url !== undefined) detail.cyfs_url = url\n      const bytesAfter = byteLength(updated)\n      Object.assign(detail, { created: !present, changed: original !== updated, bytes_written: bytesAfter, line_count: lineCount })\n      const verb = operation === 'append' ? 'appended' : operation === 'new' || operation === 'create' ? 'created' : 'wrote'\n      const summary = `${verb} ${filePath}, wrote ${byteLength(content)} bytes across ${lineCount === 1 ? '1 line' : `${lineCount} lines`}`\n      const result = builtinResult(TOOL_WRITE_FILE, detail, cmdLine, summary)\n      const label = operation === 'append' ? 'append' : operation === 'new' || operation === 'create' ? 'new' : 'write'\n      result.title = `${TOOL_WRITE_FILE} ${filePath} mode=${label} => success (${bytesAfter} bytes)`\n      return result\n    },\n  }\n}\n\n/** `edit_file`. */\nexport function editFileTool(cfg: FileToolConfig): NativeTool {\n  return {\n    spec: EDIT_FILE_SPEC,\n    idempotent: false,\n    cancellable: false,\n    async call(args) {\n      const rawPath = reqString(TOOL_EDIT_FILE, args, 'path')\n      const oldString = reqString(TOOL_EDIT_FILE, args, 'old_string')\n      const newString = reqString(TOOL_EDIT_FILE, args, 'new_string')\n      const cmdLine = `${TOOL_EDIT_FILE} ${rawPath} old_string=\"${compactCmdParamPreview(oldString)}\"`\n      const filePath = rawPath.trim()\n      if (!filePath) throw invalidArgs('missing required arg `path`')\n      if (!oldString) throw invalidArgs('missing required arg `old_string`')\n      if (oldString === newString) throw invalidArgs('`new_string` must be different from `old_string`')\n      const abs = await resolvePath(cfg.root, filePath, cfg.allowedWrite)\n      const original = await readText(abs)\n      const matches: number[] = []\n      for (let at = original.indexOf(oldString); at >= 0; at = original.indexOf(oldString, at + oldString.length)) matches.push(at)\n      if (matches.length === 0) throw invalidArgs('`old_string` was not found in the file')\n      if (matches.length > 1) throw invalidArgs(`\\`old_string\\` must match exactly once, found ${matches.length} matches`)\n      const pos = matches[0]\n      const updated = original.slice(0, pos) + newString + original.slice(pos + oldString.length)\n      const changed = original !== updated\n      if (changed) await writeText(abs, updated)\n      const diff = buildSimpleDiff(filePath, original, updated)\n      const line = (original.slice(0, pos).match(/\\n/g) ?? []).length + 1\n      const detail: Record<string, JsonValue> = {}\n      const url = cyfsUrl(cfg.dfsRoot, abs)\n      if (url !== undefined) detail.cyfs_url = url\n      Object.assign(detail, { matched: true, changed, mode: 'replace', line, diff, diff_truncated: false })\n      const summary = changed\n        ? (diff.trim() ? `edited ${filePath} with replace at line ${line}\\n\\`\\`\\`diff\\n${diff}\\n\\`\\`\\`` : `edited ${filePath} with replace at line ${line}`)\n        : `edit ${filePath} made no change`\n      const result = builtinResult(TOOL_EDIT_FILE, detail, cmdLine, summary)\n      result.title = `${TOOL_EDIT_FILE} ${filePath} => ${changed ? `success (line ${line})` : 'no change'}`\n      return result\n    },\n  }\n}\n\n// ---------------------------------------------------------------- shell\n\n/**\n * Wrapper run as `bash -c WRAPPER <command> <exec_dir>` (`NATIVE_WRAPPER`):\n * output to files, exit code to `exit`, so the command outlives the executor\n * without SIGPIPE and its end is readable after a crash.\n */\nexport const NATIVE_WRAPPER = `if [ \"$#\" -ge 2 ]; then export PATH=\"$2\"; fi\nprintf '%s\\\\n' \"$0\" > \"$1/command\"\n\"$BASH\" -c \"$0\" </dev/null >\"$1/stdout\" 2>\"$1/stderr\"\n__llm_ec=$?\nprintf '%s\\\\n' \"$__llm_ec\" > \"$1/exit.tmp\" && command -p mv -f \"$1/exit.tmp\" \"$1/exit\"\nexit $__llm_ec`\n\nconst SYSTEM_PATH_ENTRIES = ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin']\n\n/** `sanitize_call_id`. */\nexport function sanitizeCallId(callId: string): string {\n  const s = [...callId].map(c => (/[A-Za-z0-9\\-_.]/.test(c) ? c : '_')).join('')\n  return !s || s.startsWith('.') ? `c_${s}` : s\n}\n\n/** `<run_dir>/exec/<call_id>` (`exec_dir_for`). */\nexport function execDirFor(runDir: string | undefined, callId: string | undefined): string | undefined {\n  if (!runDir || !callId) return undefined\n  return joinPath(runDir, 'exec', sanitizeCallId(callId))\n}\n\n/** `fmt_elapsed`. */\nexport function fmtElapsed(ms: number): string {\n  const s = Math.floor(ms / 1000)\n  if (s < 60) return `${s}s`\n  if (s < 3600) return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`\n  return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`\n}\n\n/** Head 1/4 + tail 3/4 of a stream (`OutputCollector`). */\nfunction boundedText(bytes: Uint8Array, max: number): [string, boolean] {\n  const headCap = Math.floor(max / 4)\n  const tailCap = max - headCap\n  const head = bytes.subarray(0, Math.min(headCap, bytes.length))\n  const rest = bytes.subarray(head.length)\n  const tail = rest.subarray(Math.max(0, rest.length - tailCap))\n  const truncated = bytes.length > head.length + tail.length\n  if (!truncated) return [decodeLossy(head) + decodeLossy(tail), false]\n  return [`${decodeLossy(head)}\\n…[${bytes.length - head.length - tail.length} bytes omitted]…\\n${decodeLossy(tail)}`, true]\n}\n\nasync function readBytes(path: string): Promise<Uint8Array | undefined> {\n  try {\n    return await deno().readFile(path)\n  } catch {\n    return undefined\n  }\n}\n\n/** `read_file_bounded`. */\nasync function readFileBounded(path: string, max: number): Promise<[string, boolean]> {\n  const bytes = await readBytes(path)\n  return bytes ? boundedText(bytes, Math.max(max, 16)) : ['', false]\n}\n\n/** `read_file_tail`: the last `max` bytes as text. */\nexport async function readFileTail(path: string, max: number): Promise<string> {\n  const bytes = await readBytes(path)\n  return bytes ? decodeLossy(bytes.subarray(Math.max(0, bytes.length - max))) : ''\n}\n\n/** `read_exit_file`. */\nexport async function readExitFile(dir: string): Promise<number | undefined> {\n  try {\n    const t = (await deno().readTextFile(joinPath(dir, 'exit'))).trim()\n    return /^[+-]?\\d+$/.test(t) ? Number(t) : undefined\n  } catch {\n    return undefined\n  }\n}\n\ninterface ShellOutput {\n  exit_code: number\n  stdout: string\n  stderr: string\n  output: string\n  output_truncated: boolean\n  timed_out: boolean\n  duration_ms: number\n  cwd: string\n}\n\n/** `output_from_exec_dir`. */\nasync function outputFromExecDir(dir: string, exitCode: number, timedOut: boolean, elapsedMs: number, max: number, cwd: string): Promise<ShellOutput> {\n  const [stdout, outTrunc] = await readFileBounded(joinPath(dir, 'stdout'), max)\n  const [stderr, errTrunc] = await readFileBounded(joinPath(dir, 'stderr'), max)\n  let output = stdout\n  if (stderr) {\n    if (output && !output.endsWith('\\n')) output += '\\n'\n    output += stderr\n  }\n  return { exit_code: exitCode, stdout, stderr, output, output_truncated: outTrunc || errTrunc, timed_out: timedOut, duration_ms: Math.floor(elapsedMs), cwd }\n}\n\nconst SIGNALS: Record<string, number> = {\n  SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGILL: 4, SIGTRAP: 5, SIGABRT: 6, SIGBUS: 7, SIGFPE: 8, SIGKILL: 9, SIGUSR1: 10, SIGSEGV: 11,\n  SIGUSR2: 12, SIGPIPE: 13, SIGALRM: 14, SIGTERM: 15,\n}\n\nfunction exitCodeOf(status: { code: number; signal: string | null }): number {\n  if (status.signal) return 128 + (SIGNALS[status.signal] ?? 0)\n  return status.code\n}\n\nfunction commandHasShellOperator(command: string): boolean {\n  let single = false\n  let double = false\n  let escaped = false\n  for (const ch of command) {\n    if (escaped) {\n      escaped = false\n      continue\n    }\n    if (ch === '\\\\' && !single) escaped = true\n    else if (ch === \"'\" && !double) single = !single\n    else if (ch === '\"' && !single) double = !double\n    else if ('|;&><\\n\\r'.includes(ch) && !single && !double) return true\n  }\n  return false\n}\n\nconst RESULT_STRING_FIELDS = ['tool', 'cmd_name', 'task_id', 'pending_reason', 'estimated_wait', 'title', 'summary', 'cmd_args', 'partial_output', 'output']\n\n/** `try_forward_inner_agent_tool_result`: a simple command printing an AgentToolResult is that result. */\nfunction forwardInnerResult(command: string, out: ShellOutput): AgentToolResult | undefined {\n  if (commandHasShellOperator(command) || !tokenizeBashCommandLine(command)?.length) return undefined\n  const stdout = out.stdout.trim()\n  if (!stdout) return undefined\n  let v: unknown\n  try {\n    v = JSON.parse(stdout)\n  } catch {\n    return undefined\n  }\n  if (!isObject(v) || v.agent_tool_protocol !== '1') return undefined\n  const status = v.status ?? 'success'\n  if (status !== 'success' && status !== 'error' && status !== 'pending') return undefined\n  for (const k of RESULT_STRING_FIELDS) if (v[k] !== undefined && v[k] !== null && typeof v[k] !== 'string') return undefined\n  if (status === 'pending' && (typeof v.task_id !== 'string')) return undefined\n  const r = { ...v, status, summary: typeof v.summary === 'string' ? v.summary : '', detail: v.detail === undefined ? {} : v.detail } as unknown as AgentToolResult\n  if (r.return_code === undefined && out.exit_code !== 0) r.return_code = out.exit_code\n  return r\n}\n\nexport interface ShellToolConfig {\n  workspace: string\n  restrictCwd: boolean\n  timeoutMs: number\n  maxTimeoutMs: number\n  /** The runtime's environment for every command (`runtime.env`, PATH). */\n  env: Record<string, string>\n}\n\n/** `shell`'s spec in its wait form (Rust `ShellTool::spec`, `ShellMode::Wait`, native, bash). */\nexport function shellSpec(cfg: { restrictCwd: boolean; timeoutMs: number; maxTimeoutMs: number }): ToolSpecLite {\n  const max = cfg.maxTimeoutMs\n  const description = 'Run a command in this run\\'s runtime (native) with bash syntax. It starts in the working directory unless cwd is given; it is not sandboxed and runs with the current user\\'s permissions. The command is a child process of this executor: an interrupt or a timeout ends its process group; processes it leaves behind after returning are not managed. '\n    + `Waits for the command to finish. Default timeout ${Math.floor(cfg.timeoutMs / 1000)}s${max === 0 ? ', no upper limit' : `, max ${Math.floor(max / 1000)}s`}; on timeout the command is stopped and the output so far is returned. `\n    + 'Start a long-lived service with nohup / setsid and return at once; on Unix, processes started with `&` / nohup in the foreground command\\'s process group also end when that command is interrupted or times out. Long output keeps its beginning and end.'\n  const timeout: Record<string, JsonValue> = {\n    description: `Timeout in milliseconds (default ${cfg.timeoutMs}${max === 0 ? '' : `, max ${max}`}). Set it explicitly for long builds, tests or media commands.`,\n    minimum: 1,\n    type: 'integer',\n  }\n  if (max !== 0) timeout.maximum = max\n  return {\n    name: TOOL_SHELL,\n    description,\n    args_schema: {\n      properties: {\n        command: { description: 'bash command to execute', type: 'string' },\n        cwd: {\n          description: cfg.restrictCwd\n            ? 'Working directory, relative to or within the configured workspace. Defaults to the workspace.'\n            : 'Working directory, absolute or relative to the default working directory. Defaults to that directory; outside paths are allowed subject to OS permissions.',\n          type: 'string',\n        },\n        timeout_ms: timeout,\n      },\n      required: ['command'],\n      type: 'object',\n    },\n  }\n}\n\nfunction parseMs(raw: JsonValue | undefined, name: string): number | undefined {\n  if (raw === undefined || raw === null) return undefined\n  if (typeof raw === 'number' && Number.isInteger(raw) && raw >= 0) return raw\n  if (typeof raw === 'string' && /^\\d+$/.test(raw.trim())) return Number(raw.trim())\n  throw invalidArgs(`\\`${name}\\` must be a non-negative integer`)\n}\n\nfunction parseEnv(raw: JsonValue | undefined): [string, string][] {\n  if (raw === undefined || raw === null) return []\n  if (!isObject(raw)) throw invalidArgs('`env` must be an object of string=>string')\n  const out: [string, string][] = []\n  for (const [k, v] of Object.entries(raw)) {\n    if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) throw invalidArgs(`invalid env key \\`${k}\\` (must match [A-Za-z_][A-Za-z0-9_]*)`)\n    if (typeof v === 'string') out.push([k, v])\n    else if (typeof v === 'number' || typeof v === 'boolean') out.push([k, String(v)])\n    else if (v === null) out.push([k, ''])\n    else throw invalidArgs(`env value for \\`${k}\\` must be string/number/bool, got ${canonicalJson(v)}`)\n  }\n  return out\n}\n\nfunction appendPathEntry(entry: string, base: string): string {\n  if (!base) return entry\n  return base.split(':').includes(entry) ? base : `${base}:${entry}`\n}\n\nlet localSeq = 0\n\nfunction sleepOrStop(ms: number): { done: Promise<'timeout'>; stop(): void } {\n  let timer: ReturnType<typeof setTimeout> | undefined\n  const done = new Promise<'timeout'>(resolve => {\n    timer = setTimeout(() => resolve('timeout'), Math.min(ms, 2 ** 31 - 1))\n  })\n  return { done, stop: () => clearTimeout(timer) }\n}\n\nfunction causeText(cause: string): string {\n  return cause === 'finishing' ? 'the run is finishing' : cause === 'deadline' ? 'the run\\'s total time limit was reached' : 'the run was interrupted'\n}\n\n/** `shell` (Rust `ShellTool` with `LocalProcessBashRunner`, wait form). */\nexport function shellTool(cfg: ShellToolConfig): NativeTool {\n  const resolveTimeout = (raw: number | undefined) => {\n    const c = raw ?? cfg.timeoutMs\n    return cfg.maxTimeoutMs === 0 ? c : Math.min(Math.max(c, 1), cfg.maxTimeoutMs)\n  }\n  return {\n    spec: shellSpec(cfg),\n    idempotent: false,\n    cancellable: true,\n    async call(args, ctx) {\n      const command = typeof args.command === 'string' ? args.command.trim() : ''\n      if (!command) throw invalidArgs('`command` is required and must be non-empty')\n      const rawCwd = typeof args.cwd === 'string' ? args.cwd : undefined\n      const root = normalizePath(cfg.workspace)\n      const cwd = await resolvePath(root, rawCwd ?? '.', cfg.restrictCwd ? [root] : [])\n      if (!(await isDir(cwd))) throw invalidArgs(`cwd does not exist: ${cwd}`)\n      const userEnv = parseEnv(args.env)\n      const timeoutRaw = parseMs(args.timeout_ms, 'timeout_ms')\n      if (timeoutRaw === 0 && cfg.maxTimeoutMs !== 0) throw invalidArgs('`timeout_ms` must be a positive integer')\n      const timeoutMs = resolveTimeout(timeoutRaw)\n      parseMs(args.wait_ms, 'wait_ms')\n\n      const reqEnv = new Map<string, string>(userEnv)\n      let path = (reqEnv.get('PATH') ?? deno().env.get('PATH') ?? '').trim()\n      for (const e of SYSTEM_PATH_ENTRIES) path = appendPathEntry(e, path)\n      reqEnv.set('PATH', path)\n      if (ctx.call_id) reqEnv.set(ENV_CALL_ID, ctx.call_id)\n      if (ctx.run_id) reqEnv.set(ENV_RUN_ID, ctx.run_id)\n      const env: Record<string, string> = { ...cfg.env, ...Object.fromEntries(reqEnv) }\n      env.PATH = [...new Set(path.split(':').filter(Boolean))].join(':')\n\n      const bound = execDirFor(ctx.run_dir, ctx.call_id)\n      const temp = bound === undefined\n      const dir = bound ?? joinPath(deno().env.get('TMPDIR') || '/tmp', `llm-shell-${deno().pid}-${++localSeq}`)\n      try {\n        await deno().mkdir(dir, { recursive: true, mode: 0o700 })\n      } catch (e) {\n        throw execFailed(`execution directory: ${errorText(e)}`)\n      }\n      for (const stale of ['exit', 'exit.tmp']) await deno().remove(joinPath(dir, stale)).catch(() => undefined)\n      let child: DenoChildProcess\n      const started = performance.now()\n      try {\n        child = new (deno().Command)('/bin/bash', {\n          args: ['-c', NATIVE_WRAPPER, command, dir], cwd, env, stdin: 'null', stdout: 'null', stderr: 'null',\n        }).spawn()\n      } catch (e) {\n        throw execFailed(`spawn shell failed: ${errorText(e)}`)\n      }\n      const cleanup = async () => {\n        if (temp) await deno().remove(dir, { recursive: true }).catch(() => undefined)\n      }\n      const kill = async (): Promise<ShellOutput> => {\n        try {\n          child.kill('SIGKILL')\n        } catch {\n          // already gone\n        }\n        const t = sleepOrStop(5000)\n        await Promise.race([child.status, t.done])\n        t.stop()\n        const out = await outputFromExecDir(dir, TIMEOUT_EXIT_CODE, true, performance.now() - started, EXEC_MAX_OUTPUT_BYTES, cwd)\n        await cleanup()\n        return out\n      }\n      const timer = sleepOrStop(timeoutMs === 0 ? 365 * 24 * 3600 * 1000 : timeoutMs)\n      const first = await Promise.race([\n        child.status.then(s => ({ exited: s })),\n        timer.done.then(() => ({ timeout: true as const })),\n        ctx.call.cancelled().then(cause => ({ cancel: cause })),\n      ])\n      timer.stop()\n      let out: ShellOutput\n      if ('exited' in first) {\n        out = await outputFromExecDir(dir, exitCodeOf(first.exited), false, performance.now() - started, EXEC_MAX_OUTPUT_BYTES, cwd)\n        await cleanup()\n      } else if ('timeout' in first) {\n        out = await kill()\n      } else {\n        const tail = (await readFileTail(joinPath(dir, 'stdout'), OUTPUT_TAIL_BYTES)).trimEnd()\n        const stopped = await kill()\n        throw new NativeToolError('cancelled',\n          `shell (native): \\`${command}\\` was stopped after ${stopped.duration_ms}ms because ${causeText(first.cancel)}. It may have had partial side effects; check before repeating it.${tail.trim() ? `\\n--- output so far (tail) ---\\n${tail}` : ''}`)\n      }\n      return shellFinishedResult(command, out, timeoutMs, cfg.maxTimeoutMs)\n    },\n  }\n}\n\n/** `shell_finished_result`. */\nexport function shellFinishedResult(command: string, out: ShellOutput, timeoutMs: number, maxTimeoutMs: number): AgentToolResult {\n  if (!out.timed_out) {\n    const inner = forwardInnerResult(command, out)\n    if (inner) return inner\n  }\n  const summary = out.timed_out\n    ? `timed out after ${out.duration_ms}ms (timeout_ms=${timeoutMs}); the command was stopped. Retry with a larger timeout_ms${maxTimeoutMs === 0 ? '' : ` (max ${maxTimeoutMs})`}, or start a long-lived service with nohup / setsid and return at once.`\n    : `exit=${out.exit_code} in ${out.duration_ms}ms`\n  const detail: JsonValue = {\n    command, cwd: out.cwd, exit_code: out.exit_code, stdout: out.stdout, stderr: out.stderr, output: out.output,\n    output_truncated: out.output_truncated, timed_out: out.timed_out, duration_ms: out.duration_ms, engine: LOCAL_ENGINE, runtime: 'native',\n  }\n  const r = builtinResult(TOOL_SHELL, detail, `${TOOL_SHELL} ${command}`, summary)\n  r.status = out.exit_code === 0 && !out.timed_out ? 'success' : 'error'\n  r.return_code = out.exit_code\n  r.title = defaultTitle(r)\n  return withOutput(r, out.output)\n}\n","// The `native` runtime of the Deno host (Rust `runtime::Runtime` of kind\n// native): the same probe (`LOCAL_PROBE`), the same identity\n// (`target = { host: native_host_id(), uid }`, `runtime_id` = blake3 of the\n// target, `host`, `workdir` = the probed real cwd, `capabilities.tools` the\n// probed commands), so a run directory written by Rust on this machine\n// resumes here (descriptors equal field by field) and the other way round.\n//\n// Tools: the `bash` group only, in the form a host without a task backend can\n// run — `shell` waits in the call until its command ends or times out, which\n// Rust does when `runtime.task_wait_ms` ≥ `tools.shell.timeout_ms`. A\n// configuration that would make `shell` hand commands to tasks, `bash_core`,\n// the `executor` group, MCP and named host tools are `capability` errors for a\n// new task and `not_resumable` when a saved run needs them.\n\nimport type {\n  AiToolCall, EffectiveTools, JsonValue, LoopModel, Observation, ResolvedTool, RuntimeConfig, RuntimeDescriptor, RuntimeInfo, ShellSettings,\n  ToolSource, ToolSpecLite, ToolsConfig,\n} from '../../core/types'\nimport type { ToolCallCtx } from '../../core/deps'\nimport { ToolDispatchException } from '../../core/deps'\nimport { XllmError } from '../../core/errors'\nimport { BUILTIN_TOOL_GROUP_BASH, BUILTIN_TOOL_GROUP_BASH_CORE, PLANNED_RUNTIME_KINDS, describeToolSource, normalizePath, shellSettings } from '../../core/config'\nimport { cloneJson } from '../../core/json'\nimport type { AgentRuntime, OpenedTools, RunBinding, RunToolManager, RuntimeOpenCtx } from '../../runtime/types'\nimport { unresolvedReason } from '../../runtime/types'\nimport { envelopeObservation } from '../../runtime/site_manager'\nimport { HINT_NS_DEDUP, MemoryHintLedger, applyHints } from '../../runtime/hints'\nimport type { HintLedger } from '../../runtime/hints'\nimport { taskStateObservation } from '../../runtime/task_model'\nimport type { RunningTaskResolver } from '../../runtime/task_model'\nimport { toHost } from '../../runtime/tool_result'\nimport { deno, errorText, isDir, joinPath } from './deno_api'\nimport { deriveRuntimeId, nativeHostId, nativeTarget } from './identity'\nimport {\n  BASH_GROUP_TOOLS, NativeToolError, OUTPUT_TAIL_BYTES, TOOL_EDIT_FILE, TOOL_SHELL, TOOL_WRITE_FILE, editFileTool, execDirFor, fmtElapsed,\n  readExitFile, readFileTail, readFileTool, shellTool, writeFileTool,\n} from './native_tools'\nimport type { FileToolConfig, NativeTool } from './native_tools'\n\nexport const NATIVE_KIND = 'native'\n\n/** `LOCAL_PROBE` (`runtime/ssh.rs`), run as `/bin/bash -c` in the runtime's cwd with its env. */\nexport const LOCAL_PROBE = `set -e\ncommand -v bash >/dev/null\nmachine_id=\"$(cat /etc/machine-id 2>/dev/null || true)\"\n[ -n \"$machine_id\" ] || machine_id=\"$(hostname)\"\nprintf '%s\\\\0' \"$machine_id\" \"$(hostname)\" \"$(id -u)\" \"$(uname -s | tr '[:upper:]' '[:lower:]')\" \"$(uname -m)\" \"$(command -v bash)\" \"$(pwd -P)\" \"\\${PATH}\" \"$(date +%Y-%m-%dT%H:%M:%S%z)\" \"$(date +%Z%z)\"\nfor tool in bash realpath base64; do if command -v \"$tool\" >/dev/null; then printf '%s\\\\0' \"$tool\"; fi; done\n`\n\nexport interface Probe {\n  machine: string\n  hostname: string\n  uid: string\n  os: string\n  arch: string\n  shell: string\n  cwd: string\n  path: string\n  current_time: string\n  timezone: string\n  tools: string[]\n}\n\n/** `parse_probe`: NUL-separated fields, the first ten non-empty. */\nexport function parseProbe(bytes: Uint8Array): Probe {\n  let text = new TextDecoder().decode(bytes)\n  if (text.endsWith('\\0')) text = text.slice(0, -1)\n  const p = text.split('\\0')\n  if (p.length < 10 || p.slice(0, 10).some(f => f === '')) throw XllmError.capability('execution environment probe returned incomplete data')\n  return {\n    machine: p[0], hostname: p[1], uid: p[2], os: p[3], arch: p[4], shell: p[5], cwd: p[6], path: p[7], current_time: p[8], timezone: p[9],\n    tools: p.slice(10, 42),\n  }\n}\n\n/** Run `LOCAL_PROBE` in `cwd` (10 s at most). */\nexport async function localProbe(cwd: string, env: Record<string, string>): Promise<Probe> {\n  if (deno().build.os === 'windows') throw XllmError.capability('the Deno host\\'s native runtime needs bash (Linux / macOS); Windows PowerShell runtimes are Rust-only')\n  let out\n  try {\n    out = await new (deno().Command)('/bin/bash', {\n      args: ['-c', LOCAL_PROBE], cwd, env, stdin: 'null', stdout: 'piped', stderr: 'piped', signal: AbortSignal.timeout(10_000),\n    }).output()\n  } catch (e) {\n    throw XllmError.capability(errorText(e))\n  }\n  if (!out.success) throw XllmError.capability(`native capability probe failed: ${new TextDecoder().decode(out.stderr)}`)\n  return parseProbe(out.stdout)\n}\n\nfunction configError(reason: string): XllmError {\n  return XllmError.config('.llm_context', 'runtime', reason)\n}\n\n/** `RuntimeConfig::validate` for what this host runs (kind native). */\nfunction validateConfig(c: RuntimeConfig) {\n  const kind = c.kind ?? NATIVE_KIND\n  if (PLANNED_RUNTIME_KINDS.includes(kind)) throw XllmError.capability(`runtime \\`${kind}\\` is planned but not implemented`)\n  if (kind === 'site') throw XllmError.capability('runtime `site` is built by a website (createSiteRuntime); the Deno host runs `native`')\n  if (kind === 'remote_ssh' || kind === 'remote_node') throw XllmError.capability(`runtime \\`${kind}\\` is not available on the Deno host (only \\`native\\`)`)\n  if (kind !== NATIVE_KIND) throw configError(`unknown runtime kind \\`${kind}\\``)\n  if (c.remote_ssh && c.kind !== undefined) throw configError('remote_ssh connection block requires kind: remote_ssh')\n  if (c.remote_node && c.kind !== undefined) throw configError('remote_node connection block requires kind: remote_node')\n  if (c.remote_ssh || c.remote_node) throw configError('connection block does not match runtime kind')\n  validateEnv(c.env ?? {})\n  if (c.id !== undefined && !c.id.trim()) throw configError('id cannot be empty')\n  if (c.task_wait_ms === 0) throw configError('task_wait_ms must be positive')\n}\n\nfunction validateEnv(env: Record<string, string>) {\n  for (const [k, v] of Object.entries(env)) {\n    if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || v.includes('\\0')) throw configError(`invalid env key or value \\`${k}\\``)\n  }\n}\n\n/** `RuntimeInfo::with_declared`. */\nfunction infoOf(probe: Probe, id: string, target: JsonValue, baseline: string | undefined): RuntimeInfo {\n  const os = probe.os.toLowerCase()\n  const shellName = probe.shell.split(/[/\\\\]/).pop() ?? ''\n  return {\n    id, kind: NATIVE_KIND, os: probe.os, arch: probe.arch, hostname: probe.hostname, shell: probe.shell, cwd: probe.cwd, tools: probe.tools,\n    current_time: probe.current_time, timezone: probe.timezone, target,\n    platform: os === 'darwin' || os === 'macos' ? 'macos' : os,\n    shell_kind: shellName.replace(/\\.exe$/, '').replace(/\\.EXE$/, '').toLowerCase(),\n    baseline: baseline ?? '',\n  }\n}\n\n// ------------------------------------------------------------- tool manager\n\nconst INTENT_ARG = 'intent'\nconst INTENT_OPTIONAL_DESCRIPTION = 'Optional: why you make this call now and what you expect it to give you, in one short sentence. Shown as the progress of your work.'\n\n/** `with_intent(spec, IntentPolicy::Optional)`. */\nfunction withOptionalIntent(spec: ToolSpecLite): ToolSpecLite {\n  const s = cloneJson(spec)\n  let schema = s.args_schema as Record<string, JsonValue>\n  if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) schema = s.args_schema = { type: 'object' }\n  if (typeof schema.properties !== 'object' || schema.properties === null || Array.isArray(schema.properties)) schema.properties = {}\n  ;(schema.properties as Record<string, JsonValue>)[INTENT_ARG] = { type: 'string', description: INTENT_OPTIONAL_DESCRIPTION }\n  if (Array.isArray(schema.required)) schema.required = schema.required.filter(r => r !== INTENT_ARG)\n  return s\n}\n\nfunction causeName(cause: string | undefined): string {\n  return cause === 'deadline' ? 'Deadline' : cause === 'finishing' ? 'Finishing' : 'Interrupted'\n}\n\n/** The dispatcher of a native run (Rust `XllmToolManager` over the bash group). */\nexport class NativeToolManager implements RunToolManager {\n  private binding: RunBinding = { run_id: '' }\n  private recovering: { callId: string; reason: string } | undefined\n  private readonly ledger: HintLedger = new MemoryHintLedger()\n  private readonly written: string[] = []\n\n  constructor(\n    private readonly tools: Map<string, NativeTool>,\n    private readonly workdir: string,\n    /** Resume: the specs saved with the run, shown instead of the tools' own (freeze TODO F6). */\n    private readonly advertised?: Map<string, ToolSpecLite>,\n  ) {}\n\n  bindRun(binding: RunBinding) {\n    this.binding = { ...binding }\n  }\n\n  setRecovering(callId: string, reason: string) {\n    this.recovering = { callId, reason }\n  }\n\n  artifacts(): string[] {\n    return [...this.written]\n  }\n\n  has(name: string): boolean {\n    return this.tools.has(name)\n  }\n\n  hintLedger(): HintLedger {\n    return this.ledger\n  }\n\n  clearDedup() {\n    this.ledger.clear(HINT_NS_DEDUP)\n  }\n\n  taskResolver(): RunningTaskResolver | undefined {\n    return undefined\n  }\n\n  listToolSpecs(): ToolSpecLite[] {\n    const specs = this.advertised ? [...this.advertised.values()] : [...this.tools.values()].map(t => t.spec)\n    return specs.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n      .map(s => (BASH_GROUP_TOOLS.includes(s.name) ? withOptionalIntent(s) : cloneJson(s)))\n  }\n\n  private names(): string {\n    return [...this.tools.keys()].sort().join(', ')\n  }\n\n  async callTool(call: AiToolCall, ctx: ToolCallCtx): Promise<Observation> {\n    const callId = call.call_id\n    const tool = this.tools.get(call.name)\n    if (!tool) return { kind: 'error', call_id: callId, message: `tool \\`${call.name}\\` is not available in this run (available: ${this.names()})` }\n    const args: Record<string, JsonValue> = { ...(call.args ?? {}) }\n    if (BASH_GROUP_TOOLS.includes(call.name)) delete args[INTENT_ARG]\n    if (this.recovering?.callId === callId) {\n      const reason = this.recovering.reason\n      this.recovering = undefined\n      // `shell` would look up task `local:shell:<call_id>` first; this host has no task resolver.\n      if (!tool.idempotent) return { kind: 'unresolved', call_id: callId, reason, effect_unknown: true }\n    }\n    const running = tool.call(args, { call_id: callId, run_id: this.binding.run_id, run_dir: this.binding.run_dir, call: ctx })\n      .then(ok => ({ ok }), err => ({ err }))\n    let settled: { ok: Awaited<ReturnType<NativeTool['call']>> } | { err: unknown }\n    if (tool.cancellable) {\n      settled = await running\n    } else {\n      const first = await Promise.race([running, ctx.cancelledHard().then(cause => ({ cancelled: cause }))])\n      if ('cancelled' in first) {\n        return {\n          kind: 'cancelled', call_id: callId,\n          reason: `tool \\`${call.name}\\` was abandoned while running (${causeName(first.cancelled)}); it cannot be cancelled, so its effect is unknown`,\n          effect_unknown: true,\n        }\n      }\n      settled = first\n    }\n    if ('err' in settled) {\n      const e = settled.err\n      if (e instanceof NativeToolError) {\n        if (e.kind === 'transport') throw new ToolDispatchException(e.detail, e.effectUnknown)\n        if (e.kind === 'cancelled') return { kind: 'cancelled', call_id: callId, reason: e.detail, effect_unknown: e.effectUnknown }\n        return { kind: 'error', call_id: callId, message: e.message }\n      }\n      return { kind: 'error', call_id: callId, message: `execution failed: ${errorText(e)}` }\n    }\n    const result = settled.ok\n    if (result.status === 'success' && (call.name === TOOL_WRITE_FILE || call.name === TOOL_EDIT_FILE)) {\n      const p = args.path\n      if (typeof p === 'string') {\n        const abs = p.startsWith('/') ? p : normalizePath(joinPath(this.workdir, p))\n        if (!this.written.includes(abs)) this.written.push(abs)\n      }\n    }\n    if (result.status === 'pending') {\n      const taskId = result.task_id?.trim()\n      if (!taskId) return { kind: 'error', call_id: callId, message: `tool \\`${call.name}\\` returned a pending result without a task_id`, host: toHost(result) }\n      return taskStateObservation(callId, taskId, { kind: 'unknown', reason: 'this runtime has no task backend' }, { kind: 'tools' })\n    }\n    return envelopeObservation(callId, result, applyHints(result, this.ledger))\n  }\n}\n\n// ------------------------------------------------------------- runtime\n\nexport interface NativeRuntimeOptions {\n  /** The configuration's `runtime` block (kind `native`): `workdir`, `env`, `id`, `baseline`, `task_wait_ms`. */\n  config?: RuntimeConfig\n  /** Where the runtime works when `config.workdir` is unset (default: the current directory). */\n  workdir?: string\n  /**\n   * Taking over a saved run: `open` for this run id rebuilds the run's saved\n   * tool sources and shows the model the specs saved with them (F6).\n   */\n  takeover?: { run_id: string; tools: EffectiveTools }\n}\n\nexport interface NativeRuntime extends AgentRuntime {\n  readonly kind: 'native'\n  /** The probe the runtime was opened with. */\n  readonly probe: Probe\n}\n\n/** `runtime_descriptor` of a native runtime: identity from the target, workdir / os / tools from the probe. */\nexport function nativeDescriptor(runtimeId: string, target: { host: string; uid: string }, probe: { cwd: string; os: string; tools: string[] }): RuntimeDescriptor {\n  return {\n    runtime_id: runtimeId,\n    kind: NATIVE_KIND,\n    host: target.host,\n    target,\n    workdir: probe.cwd,\n    capabilities: { tools: Object.fromEntries(probe.tools.map(t => [t, 'available'])), network: true, os: probe.os },\n  }\n}\n\nfunction shellNeedsTasks(shell: ShellSettings): boolean {\n  return shell.wait_ms < shell.timeout_ms\n}\n\n/** Open the native runtime (`Runtime::initialize`): validate, resolve the cwd, probe, derive the identity. */\nexport async function createNativeRuntime(options: NativeRuntimeOptions = {}): Promise<NativeRuntime> {\n  const configured: RuntimeConfig = cloneJson(options.config ?? { env: {} })\n  configured.env = configured.env ?? {}\n  validateConfig(configured)\n  const rawCwd = configured.workdir ?? options.workdir ?? deno().cwd()\n  let cwd: string\n  try {\n    cwd = await deno().realPath(rawCwd)\n  } catch (e) {\n    throw XllmError.capability(`runtime cwd ${rawCwd}: ${errorText(e)}`)\n  }\n  if (!(await isDir(cwd))) throw XllmError.capability('runtime workdir must be a directory')\n  const probe = await localProbe(cwd, configured.env)\n  const target = nativeTarget(await nativeHostId(), probe.uid)\n  const id = deriveRuntimeId(configured.id, NATIVE_KIND, target)\n  const info = infoOf(probe, id, target, configured.baseline)\n  const config: RuntimeConfig = { ...configured, kind: NATIVE_KIND, id, workdir: info.cwd }\n  const descriptor = nativeDescriptor(id, target, probe)\n  const dfsRoot = joinPath(deno().env.get('BUCKYOS_ROOT') || '/opt/buckyos', 'data')\n\n  const expand = (sources: ToolSource[], field: string, shell: ShellSettings, fsPolicy: string, env: Record<string, string>,\n    tools: Map<string, NativeTool>): ResolvedTool[] => {\n    const out: ResolvedTool[] = []\n    for (const src of sources) {\n      const desc = describeToolSource(src)\n      if (src.kind === 'mcp') throw XllmError.capability(`${field}: \\`${desc}\\`: MCP tools are not available on the Deno host`)\n      if (src.kind === 'named') throw XllmError.capability(`${field}: \\`${desc}\\`: named host tools are not available on the Deno host (only the \\`bash\\` group)`)\n      if (src.groupname === BUILTIN_TOOL_GROUP_BASH_CORE || src.groupname === 'executor') {\n        throw XllmError.capability(`${field}: \\`${desc}\\` needs a host task CLI / executor that the Deno host does not provide (use \\`bash\\`)`)\n      }\n      if (src.groupname !== BUILTIN_TOOL_GROUP_BASH) {\n        throw XllmError.tools(`unknown builtin tool group \\`${src.groupname}\\` (available: ${BUILTIN_TOOL_GROUP_BASH}, ${BUILTIN_TOOL_GROUP_BASH_CORE}, executor)`)\n      }\n      if (shellNeedsTasks(shell)) {\n        throw XllmError.capability(`${field}: \\`shell\\` would hand commands still running after runtime.task_wait_ms (${shell.wait_ms} ms) to a task backend, which the Deno host does not have; set runtime.task_wait_ms to at least tools.shell.timeout_ms (${shell.timeout_ms} ms) so \\`shell\\` waits for its command`)\n      }\n      const restrict = fsPolicy === 'workspace'\n      const fileCfg: FileToolConfig = {\n        root: info.cwd, allowedRead: restrict ? [info.cwd] : [], allowedWrite: restrict ? [info.cwd] : [], dfsRoot,\n      }\n      const group = [\n        readFileTool(fileCfg), writeFileTool(fileCfg), editFileTool(fileCfg),\n        shellTool({ workspace: info.cwd, restrictCwd: restrict, timeoutMs: shell.timeout_ms, maxTimeoutMs: shell.max_timeout_ms, env }),\n      ]\n      for (const t of group) {\n        if (tools.has(t.spec.name)) {\n          throw XllmError.tools(`tool name \\`${t.spec.name}\\` from ${desc} conflicts with an already expanded tool of the same name`)\n        }\n        tools.set(t.spec.name, t)\n        out.push({ name: t.spec.name, description: t.spec.description, args_schema: cloneJson(t.spec.args_schema), source: desc })\n      }\n    }\n    return out\n  }\n\n  let openedNames: string[] | undefined\n  const runtime: NativeRuntime = {\n    kind: NATIVE_KIND,\n    probe,\n    descriptor: () => cloneJson(descriptor),\n    config: () => cloneJson(config),\n    // After `open`, the info of the opened tool set (Rust prompts read the manager's: probed\n    // commands and the run's tool names, sorted, at most 32).\n    async info(): Promise<RuntimeInfo> {\n      const now = await localProbe(info.cwd, config.env)\n      const tools = openedNames ? [...new Set([...info.tools, ...openedNames])].sort().slice(0, 32) : info.tools\n      return { ...cloneJson(info), tools, current_time: now.current_time, timezone: now.timezone }\n    },\n    // deno-lint-ignore require-await\n    async open(ctx: RuntimeOpenCtx, requested: ToolsConfig): Promise<OpenedTools> {\n      validateEnv(ctx.env)\n      const env: Record<string, string> = { ...config.env, ...ctx.env }\n      env.PATH = env.PATH ?? probe.path\n      const take = options.takeover && options.takeover.run_id === ctx.run_id ? options.takeover.tools : undefined\n      const cfg: ToolsConfig = take\n        ? {\n          enabled: take.enabled, filesystem_policy: take.filesystem_policy, tools2actions: take.tools2actions, tools: take.tool_sources,\n          actions: take.action_sources, bash_tools: take.bash_tools, shell: { timeout_ms: take.shell.timeout_ms, max_timeout_ms: take.shell.max_timeout_ms },\n        }\n        : requested\n      const enabled = cfg.enabled ?? false\n      const fsPolicy = cfg.filesystem_policy ?? 'workspace'\n      const tools2actions = cfg.tools2actions ?? false\n      const shell = shellSettings(cfg.shell, ctx.task_wait_ms)\n      const loop: LoopModel = ctx.loop_model\n      const eff: EffectiveTools = {\n        enabled, filesystem_policy: fsPolicy, tools2actions, tool_sources: cloneJson(cfg.tools ?? []), action_sources: cloneJson(cfg.actions ?? []),\n        native: [], actions: [], bash_tools: cloneJson(cfg.bash_tools ?? []), shell, exec_enabled: false, sources: { ...ctx.sources },\n      }\n      if (loop === 'function_call') {\n        if (tools2actions) {\n          throw XllmError.capability('`tools2actions: true` requires `loop_model: behavior`; function_call cannot convert tools into actions')\n        }\n        if ((cfg.actions ?? []).length > 0) {\n          throw XllmError.capability('`actions` are configured but `loop_model` is function_call; use `loop_model: behavior` or remove `actions`')\n        }\n      }\n      const tools = new Map<string, NativeTool>()\n      if (enabled) {\n        const toolSources = cfg.tools ?? [{ kind: 'group', groupname: BUILTIN_TOOL_GROUP_BASH }]\n        eff.tool_sources = cloneJson(toolSources)\n        const native = expand(toolSources, 'tools.tools', shell, fsPolicy, env, tools)\n        const explicit = expand(eff.action_sources, 'tools.actions', shell, fsPolicy, env, tools)\n        if (loop === 'behavior' && tools2actions) {\n          eff.actions = [...native, ...explicit]\n        } else {\n          eff.native = native\n          eff.actions = explicit\n        }\n        eff.exec_enabled = tools.has(TOOL_SHELL) && [...eff.native, ...eff.actions].some(t => t.name === TOOL_SHELL)\n      }\n      let advertised: Map<string, ToolSpecLite> | undefined\n      if (take) {\n        advertised = new Map()\n        for (const t of [...take.native, ...take.actions]) {\n          if (tools.has(t.name)) advertised.set(t.name, { name: t.name, description: t.description, args_schema: cloneJson(t.args_schema) })\n        }\n      }\n      openedNames = [...eff.native, ...eff.actions].map(t => t.name)\n      return { tools: eff, manager: new NativeToolManager(tools, info.cwd, advertised) }\n    },\n    async describeInterrupted(run: RunBinding, call: AiToolCall): Promise<string> {\n      if (call.name !== TOOL_SHELL) return unresolvedReason(call.name)\n      const dir = execDirFor(run.run_dir, call.call_id)\n      if (dir === undefined) return interruptedShellText(call, undefined, '(no execution directory)')\n      return interruptedShellText(call, await readExecDir(dir), dir)\n    },\n  }\n  return runtime\n}\n\n// ------------------------------------------------------------- describe_interrupted\n\n/** What a `shell` command's execution directory says (`ExecDirFacts`). */\nexport interface ExecDirFacts {\n  exit_code?: number\n  stdout_tail: string\n  stderr_tail: string\n  exists: boolean\n  /** mtime of `command`: when the command was written there. */\n  started_at_ms?: number\n}\n\nexport async function readExecDir(dir: string): Promise<ExecDirFacts> {\n  let started: number | undefined\n  try {\n    const m = (await deno().stat(joinPath(dir, 'command'))).mtime\n    if (m) started = Math.floor(m.getTime())\n  } catch {\n    started = undefined\n  }\n  return {\n    exit_code: await readExitFile(dir),\n    stdout_tail: await readFileTail(joinPath(dir, 'stdout'), OUTPUT_TAIL_BYTES),\n    stderr_tail: await readFileTail(joinPath(dir, 'stderr'), OUTPUT_TAIL_BYTES),\n    exists: await isDir(dir),\n    started_at_ms: started,\n  }\n}\n\nfunction shellCommandOf(call: AiToolCall): string {\n  const c = call.args?.command\n  if (typeof c !== 'string') return ''\n  const one = c.split(/\\s+/).filter(Boolean).join(' ')\n  const chars = [...one]\n  return chars.length > 160 ? `${chars.slice(0, 160).join('')}…` : one\n}\n\nfunction tails(f: ExecDirFacts): string {\n  let s = ''\n  if (f.stdout_tail.trim()) s += `\\n--- stdout (tail) ---\\n${f.stdout_tail.trimEnd()}`\n  if (f.stderr_tail.trim()) s += `\\n--- stderr (tail) ---\\n${f.stderr_tail.trimEnd()}`\n  return s\n}\n\n/** `interrupted_shell_text` for the native kind. */\nexport function interruptedShellText(call: AiToolCall, facts: ExecDirFacts | undefined, location: string): string {\n  const command = shellCommandOf(call)\n  const started = facts?.started_at_ms !== undefined\n    ? `started ${fmtElapsed(Math.max(0, Date.now() - facts.started_at_ms))} ago (at ${facts.started_at_ms} ms since epoch)`\n    : 'start time unknown'\n  if (facts?.exit_code !== undefined) {\n    return `shell (native): the previous executor exited while \\`${command}\\` was running (${started}). The command has since ended with exit code ${facts.exit_code} (read from ${location}); its result was never returned, so review it before deciding whether to repeat anything.${tails(facts)}`\n  }\n  return `shell (native): the previous executor exited while \\`${command}\\` was running (${started}). The command may have partly executed; it usually ended together with the executor, but not necessarily (e.g. after kill -9 it may still be running). Background processes it started are unaffected. Check the actual state before repeating it.${facts ? tails(facts) : ''}`\n}\n","// `FileRunStore` (Rust `RunStore::Disk`): the same directory layout and the\n// same write discipline, so a run directory is shared by Rust and Deno\n// executors on one machine.\n//\n//   <runs_dir>/<run_id>/run.json             pretty JSON, tmp + fsync + rename + fsync dir\n//   <runs_dir>/<run_id>/snapshots/NNNN.json  compact JSON, same discipline\n//   <runs_dir>/<run_id>/.lock                exclusive flock while a process executes the run\n//   <lock_dir>/<blake3(workdir)[..24]>.lock  tool-enabled runs of one working directory\n//\n// Locks are `Deno.FsFile.tryLock(true)`: flock(2) on Unix, the same advisory\n// lock as Rust's fs2 (`try_lock_exclusive`), so a Rust process holding a run\n// makes it busy here and the other way round.\n\nimport type { LLMContextSnapshot, RunRecord, RunsDirSetting } from '../../core/types'\nimport { XllmError } from '../../core/errors'\nimport { RUN_RECORD_VERSION, generateRunId } from '../../core/store'\nimport type { ExportedRun, RunLock, RunStore } from '../../core/store'\nimport { resolveConfigPath } from '../../core/config'\nimport { deno, errorText, homeDir, isAlreadyExists, isDir, isNotFound, joinPath, parentDir, syncDir, writeFileSynced } from './deno_api'\nimport type { DenoFsFile } from './deno_api'\nimport { workdirLockPath } from './identity'\n\n/** `DEFAULT_RUNS_DIR` / `DEFAULT_LOCK_DIR`. */\nexport const DEFAULT_RUNS_DIR = '~/.xllm/runs'\nexport const DEFAULT_LOCK_DIR = '~/.xllm/locks'\n\n/** `resolve_config_path`: `~` is the home directory, an absolute path stays, a relative one is under `baseDir`. */\nexport function resolveHostPath(raw: string, baseDir: string): string {\n  return resolveConfigPath(raw, baseDir, homeDir())\n}\n\n/**\n * Where the runs of a configuration go: `runs_dir` of the `.llm_context`\n * (`none` → `undefined`, a memory store), else `~/.xllm/runs`. `origin` is\n * the configuration's path (relative `runs_dir` is relative to its\n * directory).\n */\nexport function runsDirOf(setting: RunsDirSetting | undefined, origin: string): string | undefined {\n  if (setting?.kind === 'disabled') return undefined\n  const raw = setting?.kind === 'path' ? setting.path : DEFAULT_RUNS_DIR\n  return resolveHostPath(raw, parentDir(origin.startsWith('/') ? origin : joinPath(deno().cwd(), origin)))\n}\n\n/** A held flock; `release` (or process exit) frees it. */\nexport class FileLock implements RunLock {\n  private released = false\n\n  private constructor(private readonly file: DenoFsFile, readonly path: string) {}\n\n  /** Non-blocking (`FileLock::try_acquire`): `null` when another open file holds it. */\n  static async tryAcquire(path: string): Promise<FileLock | null> {\n    try {\n      await deno().mkdir(parentDir(path), { recursive: true })\n    } catch (e) {\n      throw XllmError.storage(`cannot create lock directory ${parentDir(path)}: ${errorText(e)}`)\n    }\n    let file: DenoFsFile\n    try {\n      file = await deno().open(path, { read: true, write: true, create: true })\n    } catch (e) {\n      throw XllmError.storage(`cannot open lock ${path}: ${errorText(e)}`)\n    }\n    if (!(await file.tryLock(true))) {\n      file.close()\n      return null\n    }\n    try {\n      await deno().writeTextFile(path, `${deno().pid}\\n`)\n    } catch {\n      // the lock is held; the owner note is informational\n    }\n    return new FileLock(file, path)\n  }\n\n  async release(): Promise<void> {\n    if (this.released) return\n    this.released = true\n    try {\n      await this.file.unlock()\n    } finally {\n      this.file.close()\n    }\n  }\n}\n\n/** Some open file holds the flock at `path` (`is_run_live`). */\nexport async function isLocked(path: string): Promise<boolean> {\n  let file: DenoFsFile\n  try {\n    file = await deno().open(path, { read: true, write: true, create: true })\n  } catch {\n    return false\n  }\n  try {\n    if (await file.tryLock(true)) {\n      await file.unlock()\n      return false\n    }\n    return true\n  } finally {\n    file.close()\n  }\n}\n\nlet tmpCounter = 0\n\nfunction pad4(n: number): string {\n  return String(n).padStart(4, '0')\n}\n\nexport class FileRunStore implements RunStore {\n  readonly persistent = true\n  private readonly dir: string\n\n  /** `runsDir`: absolute, or relative to the current directory; `~` is the home directory. */\n  constructor(runsDir: string) {\n    this.dir = resolveHostPath(runsDir, deno().cwd())\n  }\n\n  runsDir(): string {\n    return this.dir\n  }\n\n  runDir(runId: string): string {\n    return joinPath(this.dir, runId)\n  }\n\n  /** The runs directory can be created and written (`ensure_writable`). */\n  async ensureWritable(): Promise<void> {\n    try {\n      await deno().mkdir(this.dir, { recursive: true })\n    } catch (e) {\n      throw XllmError.storage(`runs directory ${this.dir} cannot be created: ${errorText(e)}`)\n    }\n    const probe = joinPath(this.dir, `.probe-${deno().pid}`)\n    try {\n      await deno().writeFile(probe, new Uint8Array())\n    } catch (e) {\n      throw XllmError.storage(`runs directory ${this.dir} is not writable: ${errorText(e)}`)\n    }\n    await deno().remove(probe).catch(() => undefined)\n  }\n\n  async createRun(): Promise<string> {\n    await this.ensureWritable()\n    for (let i = 0; i < 8; i++) {\n      const runId = generateRunId()\n      const dir = this.runDir(runId)\n      try {\n        await deno().mkdir(dir)\n      } catch (e) {\n        if (isAlreadyExists(e)) continue\n        throw XllmError.storage(`cannot create run directory ${dir}: ${errorText(e)}`)\n      }\n      await deno().mkdir(joinPath(dir, 'snapshots'), { recursive: true })\n      return runId\n    }\n    throw XllmError.storage('cannot allocate a unique run id')\n  }\n\n  async writeRecord(record: RunRecord): Promise<void> {\n    const dir = this.runDir(record.run_id)\n    const path = joinPath(dir, 'run.json')\n    const tmp = joinPath(dir, `run.json.tmp-${deno().pid}-${tmpCounter++}`)\n    try {\n      await deno().mkdir(dir, { recursive: true })\n      await writeFileSynced(tmp, new TextEncoder().encode(JSON.stringify(record, null, 2)))\n    } catch (e) {\n      throw XllmError.storage(`write ${tmp}: ${errorText(e)}`)\n    }\n    try {\n      await deno().rename(tmp, path)\n    } catch (e) {\n      throw XllmError.storage(`commit ${path}: ${errorText(e)}`)\n    }\n    try {\n      await syncDir(dir)\n    } catch (e) {\n      throw XllmError.storage(`sync ${dir}: ${errorText(e)}`)\n    }\n  }\n\n  /** Rejects with `run_not_found`, `not_resumable` (another record version, like Rust) or `corrupted_run`. */\n  async readRecord(runId: string): Promise<RunRecord> {\n    const path = joinPath(this.runDir(runId), 'run.json')\n    let text: string\n    try {\n      text = await deno().readTextFile(path)\n    } catch (e) {\n      if (isNotFound(e)) throw new XllmError({ kind: 'run_not_found', run_id: runId, runs_dir: this.dir })\n      throw XllmError.storage(`read ${path}: ${errorText(e)}`)\n    }\n    let value: unknown\n    try {\n      value = JSON.parse(text)\n    } catch (e) {\n      throw new XllmError({ kind: 'corrupted_run', run_id: runId, reason: errorText(e) })\n    }\n    const v = value as { version?: unknown; run_id?: unknown; status?: unknown; config?: unknown; prompt?: unknown }\n    if (v?.version !== RUN_RECORD_VERSION) throw XllmError.notResumable(runId, 'unsupported run record version')\n    if (typeof v.run_id !== 'string' || typeof v.status !== 'string' || typeof v.config !== 'object' || typeof v.prompt !== 'object') {\n      throw new XllmError({ kind: 'corrupted_run', run_id: runId, reason: 'run.json unreadable: missing run_id / status / config / prompt' })\n    }\n    return value as RunRecord\n  }\n\n  async listRecords(): Promise<RunRecord[]> {\n    const out: RunRecord[] = []\n    let entries: AsyncIterable<{ name: string; isDirectory: boolean }>\n    try {\n      entries = deno().readDir(this.dir)\n      for await (const entry of entries) {\n        if (!entry.isDirectory) continue\n        try {\n          const rec = JSON.parse(await deno().readTextFile(joinPath(this.dir, entry.name, 'run.json')))\n          if (rec && typeof rec.run_id === 'string') out.push(rec as RunRecord)\n        } catch {\n          // not a run, or an unreadable one: skipped like Rust\n        }\n      }\n    } catch (e) {\n      if (isNotFound(e)) return out\n      throw XllmError.storage(`read runs directory ${this.dir}: ${errorText(e)}`)\n    }\n    return out\n  }\n\n  async putSnapshot(runId: string, snapshot: LLMContextSnapshot): Promise<number> {\n    const dir = joinPath(this.runDir(runId), 'snapshots')\n    try {\n      await deno().mkdir(dir, { recursive: true })\n      const idxs = await this.listSnapshots(runId)\n      const next = idxs.length ? idxs[idxs.length - 1] + 1 : 1\n      const path = joinPath(dir, `${pad4(next)}.json`)\n      const tmp = joinPath(dir, `${pad4(next)}.json.tmp`)\n      await writeFileSynced(tmp, new TextEncoder().encode(JSON.stringify(snapshot)))\n      await deno().rename(tmp, path)\n      await syncDir(dir)\n      return next\n    } catch (e) {\n      if (e instanceof XllmError) throw e\n      throw XllmError.storage(`write snapshot of ${runId}: ${errorText(e)}`)\n    }\n  }\n\n  async getSnapshot(runId: string, idx: number): Promise<LLMContextSnapshot> {\n    const path = joinPath(this.runDir(runId), 'snapshots', `${pad4(idx)}.json`)\n    let text: string\n    try {\n      text = await deno().readTextFile(path)\n    } catch (e) {\n      throw new XllmError({ kind: 'corrupted_run', run_id: runId, reason: `snapshot ${idx} missing at ${path}: ${errorText(e)}` })\n    }\n    try {\n      return JSON.parse(text) as LLMContextSnapshot\n    } catch (e) {\n      throw new XllmError({ kind: 'corrupted_run', run_id: runId, reason: `snapshot ${idx} unreadable: ${errorText(e)}` })\n    }\n  }\n\n  async listSnapshots(runId: string): Promise<number[]> {\n    const dir = joinPath(this.runDir(runId), 'snapshots')\n    const idxs: number[] = []\n    try {\n      for await (const entry of deno().readDir(dir)) {\n        const m = /^(\\d+)\\.json$/.exec(entry.name)\n        if (m) idxs.push(Number(m[1]))\n      }\n    } catch (e) {\n      if (isNotFound(e)) return []\n      throw e\n    }\n    return idxs.sort((a, b) => a - b)\n  }\n\n  /** The run's execution lock (`<run>/.lock`), `null` when another process (or open file) holds it. */\n  lockRun(runId: string): Promise<FileLock | null> {\n    return FileLock.tryAcquire(joinPath(this.runDir(runId), '.lock'))\n  }\n\n  /** Some process holds the run's `.lock` (`is_run_live`). */\n  async isRunLive(runId: string): Promise<boolean> {\n    if (!(await isDir(this.runDir(runId)))) return false\n    return isLocked(joinPath(this.runDir(runId), '.lock'))\n  }\n\n  /** Delete the run directory; the caller holds its lock and has nothing unreconciled in flight. */\n  async removeRun(runId: string): Promise<void> {\n    const dir = this.runDir(runId)\n    try {\n      await deno().remove(dir, { recursive: true })\n    } catch (e) {\n      if (!isNotFound(e)) throw XllmError.storage(`remove ${dir}: ${errorText(e)}`)\n    }\n    await syncDir(this.dir).catch(() => undefined)\n  }\n\n  /** Write a run exported from another store: same id, same snapshot indices. */\n  async importRun(run: ExportedRun): Promise<void> {\n    const id = run.record.run_id\n    if (await this.isRunLive(id)) throw new XllmError({ kind: 'run_busy', run_id: id })\n    const dir = this.runDir(id)\n    await deno().mkdir(joinPath(dir, 'snapshots'), { recursive: true })\n    for (const [idx, snapshot] of run.snapshots) {\n      const path = joinPath(dir, 'snapshots', `${pad4(idx)}.json`)\n      const tmp = `${path}.tmp`\n      await writeFileSynced(tmp, new TextEncoder().encode(JSON.stringify(snapshot)))\n      await deno().rename(tmp, path)\n    }\n    await syncDir(joinPath(dir, 'snapshots'))\n    await this.writeRecord(run.record)\n  }\n}\n\n/**\n * `XllmDeps.lockWorkdir` of a host with a filesystem: the flock\n * `<lockDir>/<blake3(workdir)[..24]>.lock`, the run id written into it.\n */\nexport function workdirLocker(lockDir: string = DEFAULT_LOCK_DIR) {\n  const dir = resolveHostPath(lockDir, deno().cwd())\n  return async (workdir: string, runId: string): Promise<RunLock | null> => {\n    const lock = await FileLock.tryAcquire(workdirLockPath(dir, workdir))\n    if (lock) await deno().writeTextFile(lock.path, `${runId}\\n`).catch(() => undefined)\n    return lock\n  }\n}\n\n/** `XllmDeps.workdirExists`. */\nexport function workdirExists(workdir: string): Promise<boolean> {\n  return isDir(workdir)\n}\n","// Model clients of the Deno host, from a run's saved provider configuration\n// (Rust `DefaultLlmClientFactory`): credentials are re-resolved from their\n// references (`SecretRef`), never read from run.json.\n//\n//   openai  → the dev `OpenAiLlmClient` (`base_url`, `api_key` / `api_key_env`\n//             or `OPENAI_API_KEY`, `headers`); no key → `capability`\n//   buckyos → websdk's node runtime as an AppClient with the session in\n//             `BUCKYOS_APPCLIENT_SESSION_TOKEN` (or `provider.session_token`)\n//             → `getAiccClient()`. Without a session the client refuses every\n//             request as `credentials`, so the run pauses (`last_error.kind =\n//             credentials`) until it is resumed with a session.\n\nimport type { LlmClient, ProviderConfig, SecretRef } from '../../core/types'\nimport type { AiccClient } from '../../../aicc_client'\nimport { XllmError, providerError } from '../../core/errors'\nimport { isObject } from '../../core/json'\nimport { REFUSED_CREDENTIALS } from '../../core/run'\nimport { AiccLlmClient } from '../../providers/aicc'\nimport { OpenAiLlmClient } from '../../dev/openai'\nimport { deno, errorText } from './deno_api'\n\nexport const SESSION_TOKEN_ENV = 'BUCKYOS_APPCLIENT_SESSION_TOKEN'\n\n/**\n * `SecretRef::resolve`. A `config_file` reference is re-read; the Deno host\n * reads JSON configuration files (a reference into a YAML `.llm_context`\n * written by Rust is a `capability` error here).\n */\nexport async function resolveSecret(ref: SecretRef): Promise<string> {\n  if (ref.kind === 'env') {\n    const v = deno().env.get(ref.name)\n    if (v === undefined) throw XllmError.capability(`environment variable \\`${ref.name}\\` is not set`)\n    return v\n  }\n  let raw: string\n  try {\n    raw = await deno().readTextFile(ref.path)\n  } catch (e) {\n    throw XllmError.capability(`cannot re-read credential source ${ref.path}:${ref.field}: ${errorText(e)}`)\n  }\n  let doc: unknown\n  try {\n    doc = JSON.parse(raw)\n  } catch (e) {\n    throw XllmError.capability(`cannot parse credential source ${ref.path} (the Deno host reads JSON configuration): ${errorText(e)}`)\n  }\n  let cur: unknown = doc\n  for (const seg of ref.field.split('.')) {\n    if (!isObject(cur) || !(seg in cur)) throw XllmError.capability(`credential field \\`${ref.field}\\` no longer exists in ${ref.path}`)\n    cur = cur[seg]\n  }\n  if (typeof cur !== 'string' || !cur.trim()) throw XllmError.capability(`credential field \\`${ref.field}\\` in ${ref.path} is empty or not a string`)\n  return cur\n}\n\n/** A client whose every request is refused as `credentials` (no session on this host). */\nexport function credentialsRefusedClient(message: string): LlmClient {\n  return {\n    // deno-lint-ignore require-await\n    async infer() {\n      throw providerError({ refused: { code: REFUSED_CREDENTIALS } }, message)\n    },\n  }\n}\n\ninterface NodeSdk {\n  BuckyOSSDK: new (target: 'node') => {\n    initBuckyOS(appId: string, config: Record<string, unknown>): Promise<void>\n    getAiccClient(): AiccClient\n  }\n}\n\n/**\n * websdk's node entry (`buckyos/node`, `dist/node.mjs` beside this bundle),\n * loaded only when a run uses the buckyos provider.\n */\nasync function loadNodeSdk(): Promise<NodeSdk> {\n  // @ts-ignore: the SDK's tsc build is CommonJS; this bundle is ESM (Deno)\n  const url = new URL('./node.mjs', import.meta.url).href\n  return await import(/* @vite-ignore */ url) as NodeSdk\n}\n\n/** The model client of `provider` on this host. */\nexport async function createLlmClient(provider: ProviderConfig): Promise<LlmClient> {\n  if ((provider.kind ?? 'buckyos') === 'openai') {\n    const key = provider.api_key ? await resolveSecret(provider.api_key) : deno().env.get('OPENAI_API_KEY')\n    if (!key?.trim()) {\n      throw XllmError.capability('openai provider: no API key; set `provider.api_key`, `provider.api_key_env` or the OPENAI_API_KEY environment variable')\n    }\n    return new OpenAiLlmClient({ baseUrl: provider.base_url, apiKey: key, headers: provider.headers })\n  }\n  if (provider.on_behalf_of !== undefined && provider.on_behalf_of !== null) {\n    throw XllmError.capability('buckyos provider: `on_behalf_of` (a system service paying for a user) is not available on the Deno host')\n  }\n  const token = provider.session_token ? await resolveSecret(provider.session_token) : deno().env.get(SESSION_TOKEN_ENV)?.trim()\n  if (!token) {\n    return credentialsRefusedClient(`buckyos provider: no BuckyOS session on this host (set ${SESSION_TOKEN_ENV}), sign in and resume`)\n  }\n  const appId = deno().env.get('BUCKYOS_APP_ID')?.trim() || 'buckycli'\n  const sdk = new (await loadNodeSdk()).BuckyOSSDK('node')\n  try {\n    await sdk.initBuckyOS(appId, {\n      zoneHost: deno().env.get('BUCKYOS_ZONE_HOST')?.trim() ?? '',\n      appId,\n      defaultProtocol: 'https://',\n      runtimeType: 'AppClient',\n      sessionToken: token,\n      privateKeySearchPaths: [],\n      autoRenew: false,\n    })\n  } catch (e) {\n    throw XllmError.capability(`buckyos provider: cannot initialize the BuckyOS runtime (check zone/session setup): ${errorText(e)}`)\n  }\n  return new AiccLlmClient(sdk.getAiccClient())\n}\n","// `buckyos/xllm/deno`: the Deno host of the xllm TypeScript runtime — the\n// `native` runtime (files, processes), `FileRunStore` with flock, and taking\n// over run directories a Rust `agent_tool xllm` on this machine left half\n// done (and the other way round). Not part of the browser entries.\n\nimport type { JsonValue, LlmClient, RunObserver, Tokenizer } from '../../core/types'\nimport { XllmError } from '../../core/errors'\nimport { mergeConfigLayers, parseLlmContextJson } from '../../core/config'\nimport { MemoryRunStore } from '../../core/store'\nimport type { RunStore } from '../../core/store'\nimport { XllmRun, XllmTask, isTerminal } from '../../core/run'\nimport type { PreparedTask, ResumeLimits, ResumeStart, XllmDeps } from '../../core/run'\nimport type { TaskInput, TaskOverrides } from '../../core/prepare'\nimport type { AgentRuntime } from '../../runtime/types'\nimport { deno } from './deno_api'\nimport { createNativeRuntime } from './native_runtime'\nimport { FileRunStore, runsDirOf, workdirExists, workdirLocker } from './store'\nimport { createLlmClient } from './provider'\n\nexport { FileLock, FileRunStore, DEFAULT_LOCK_DIR, DEFAULT_RUNS_DIR, isLocked, resolveHostPath, runsDirOf, workdirExists, workdirLocker } from './store'\nexport {\n  HOST_ID_ENV, blake3Hex, deriveRuntimeId, nativeHostId, nativeHostIdFrom, nativeTarget, runtimeIdOf, targetText, workdirLockPath,\n} from './identity'\nexport type { HostIdInputs } from './identity'\nexport {\n  LOCAL_PROBE, NATIVE_KIND, NativeToolManager, createNativeRuntime, interruptedShellText, localProbe, nativeDescriptor, parseProbe, readExecDir,\n} from './native_runtime'\nexport type { ExecDirFacts, NativeRuntime, NativeRuntimeOptions, Probe } from './native_runtime'\nexport {\n  BASH_GROUP_TOOLS, EDIT_FILE_SPEC, EXEC_MAX_OUTPUT_BYTES, NATIVE_WRAPPER, READ_FILE_SPEC, WRITE_FILE_SPEC, execDirFor, fmtElapsed,\n  sanitizeCallId, shellSpec,\n} from './native_tools'\nexport { SESSION_TOKEN_ENV, createLlmClient, credentialsRefusedClient, resolveSecret } from './provider'\n\nexport interface NativeHostOptions {\n  /** The model client; default: built from the run's provider configuration (`createLlmClient`). */\n  llm?: LlmClient\n  observer?: RunObserver\n  tokenizer?: Tokenizer\n  /** Directory of the working-directory locks (default `~/.xllm/locks`). */\n  lockDir?: string\n}\n\n/** `XllmDeps` of a native run on this host: flock working-directory locks, this process's pid. */\nexport function nativeDeps(runtime: AgentRuntime, store: RunStore, llm: LlmClient, options: NativeHostOptions = {}): XllmDeps {\n  const deps: XllmDeps = {\n    llm, runtime, store, pid: deno().pid, lockWorkdir: workdirLocker(options.lockDir), workdirExists,\n  }\n  if (options.observer) deps.observer = options.observer\n  if (options.tokenizer) deps.tokenizer = options.tokenizer\n  return deps\n}\n\nexport interface NativeTaskOptions extends NativeHostOptions {\n  /** The control-side working directory: where `runtime.workdir` defaults to (default: the current directory). */\n  workdir?: string\n  /** Default: the configuration's `runs_dir` (`none` → memory), else `~/.xllm/runs`. */\n  store?: RunStore\n}\n\nconst pendingLlm: LlmClient = {\n  infer() {\n    throw XllmError.other('the model client is created after the task is prepared')\n  },\n}\n\n/**\n * Prepare a new native task (`XllmTask.prepare` with this host's runtime,\n * store and model client): one JSON configuration (`origin` names it and\n * anchors relative paths), the input and explicit overrides.\n */\nexport async function prepareNativeTask(llmContext: JsonValue | undefined, origin: string, input: TaskInput, overrides: TaskOverrides,\n  options: NativeTaskOptions = {}): Promise<{ task: PreparedTask; deps: XllmDeps }> {\n  const merged = mergeConfigLayers([{ path: origin, file: parseLlmContextJson(origin, llmContext ?? null) }])\n  const runtime = await createNativeRuntime({ config: merged.runtime, workdir: options.workdir })\n  let store = options.store\n  if (!store) {\n    const dir = runsDirOf(merged.runs_dir, origin)\n    store = dir === undefined ? new MemoryRunStore() : new FileRunStore(dir)\n  }\n  const draft = nativeDeps(runtime, store, options.llm ?? pendingLlm, options)\n  const task = await XllmTask.prepare(llmContext, origin, input, overrides, draft)\n  return { task, deps: { ...draft, llm: options.llm ?? await createLlmClient(task.config.provider) } }\n}\n\n/** A runtime that could not be opened: every use reports why (the resume gate reaches it after its own checks). */\nfunction unavailableRuntime(error: unknown): AgentRuntime {\n  const err = error instanceof XllmError ? error : XllmError.capability(error instanceof Error ? error.message : String(error))\n  const fail = (): never => {\n    throw err\n  }\n  const rejected = () => Promise.reject(err)\n  return { descriptor: fail, config: fail, info: rejected, open: rejected, describeInterrupted: rejected }\n}\n\n/**\n * Take a run back on this host (`XllmRun.resume` with the native runtime\n * rebuilt from the saved `config.runtime`, the saved tool sources and specs,\n * and a model client from the saved provider). Works the same for runs a\n * Rust executor started: whether it can be taken over is decided by the\n * resume gate — record and snapshot versions, protocol, lock, descriptor\n * equality, rebuildable tools — not by who wrote it.\n */\nexport async function resumeNativeRun(store: RunStore, runId: string, limits: ResumeLimits = {},\n  options: NativeHostOptions = {}): Promise<ResumeStart> {\n  const record = await store.readRecord(runId)\n  let runtime: AgentRuntime\n  let llm = options.llm\n  if (isTerminal(record.status)) {\n    runtime = unavailableRuntime(XllmError.other('a terminal run is not executed'))\n  } else {\n    try {\n      runtime = await createNativeRuntime({\n        config: record.config.runtime, workdir: record.workdir, takeover: { run_id: record.run_id, tools: record.config.tools },\n      })\n    } catch (e) {\n      runtime = unavailableRuntime(e)\n    }\n    llm = llm ?? await createLlmClient(record.config.provider)\n  }\n  return XllmRun.resume(store, runId, limits, nativeDeps(runtime, store, llm ?? pendingLlm, options))\n}\n"],"names":["deno","d","globalThis","Deno","Error","isNotFound","e","errors","NotFound","isAlreadyExists","AlreadyExists","errorText","message","String","joinPath","parts","out","p","startsWith","endsWith","parentDir","t","replace","i","lastIndexOf","slice","async","isDir","stat","isDirectory","writeFileSynced","path","bytes","f","open","write","create","truncate","off","length","subarray","sync","close","syncDir","dir","build","os","read","fromNumH","n","fromNumL","isBytes","a","Uint8Array","ArrayBuffer","isView","constructor","name","BYTES_PER_ELEMENT","atitle","title","anumber","TypeError","Number","isSafeInteger","RangeError","abytes","value","ofLen","got","aopts","label","Array","isArray","aobject","proto","Object","getPrototypeOf","prototype","hasOwn","aexists","instance","checkFinished","destroyed","finished","aoutput","min","outputLen","u32","arr","Uint32Array","buffer","byteOffset","Math","floor","byteLength","clean","arrays","fill","rotr","word","shift","isLE","byteSwap","swap8IfBE","swap32IfBE","u","hasHexBuiltin","from","toHex","fromHex","hexes","_","toString","padStart","checkOpts","defaults","opts","assign","createHasher","hashCons","info","hashC","msg","update","digest","tmp","blockLen","canXOF","freeze","SHA256_IV","G1s","b","c","x","G2s","_BLAKE2","__publicField","this","buffer32","data","len","offset","buf","pos","compress","take","dataOffset","set","data32","pos32","digestInto","state","get","out32","full","tail","res","destroy","_cloneInto","to","dkLen","clone","_compress","s","rounds","v0","v1","v2","v3","v4","v5","v6","v7","v8","v9","v10","v11","v12","v13","v14","v15","j","B3_Flags","B3_IV","B3_SIGMA","Id","permute","map","v","push","_BLAKE3","flags","super","key","context","hasContext","k","IV","ctx","contextKey","bufferOut","bufferOut32","b2Compress","counter","bufPos","t0","t1","isLast","chunkPos","chunksDone","chunk","last","chunks","stack","pop","staleOutput","posOut","chunkOut","enableXOF","b2CompressOut","outCounter","finish","writeInto","xofInto","xof","blake3","HOST_ID_ENV","blake3Hex","text","hex","bytesToHex","TextEncoder","encode","readText","readTextFile","nativeHostIdFrom","id","_a","agent_tool_host_id","trim","etc_hostname","hostname_env","machine_id","nativeHostId","env","nativeTarget","hostId","uid","host","targetText","target","canonicalJson","deriveRuntimeId","configuredId","kind","runtimeIdOf","workdirLockPath","lockDir","workdir","TOOL_READ_FILE","TOOL_WRITE_FILE","TOOL_EDIT_FILE","TOOL_SHELL","BASH_GROUP_TOOLS","EXEC_MAX_OUTPUT_BYTES","OUTPUT_TAIL_BYTES","LOCAL_ENGINE","READ_FILE_PREVIEW_MAX_LINES","NativeToolError","detail","effectUnknown","invalidArgs","m","execFailed","tokenizeBashCommandLine","line","tokens","cur","single","double","chars","ch","test","defaultTitle","r","cmd_name","cmd_args","max","join","truncateText","status","pending_reason","builtinResult","tool","cmdLine","summary","agent_tool_protocol","split","filter","Boolean","pathStartsWith","root","checkAllowed","roots","some","canonicalMissing","ancestor","missing","real","realPath","normalizePath","reverse","lstat","le","parent","resolvePath","raw","allowed","candidate","Promise","all","encodeObjSegment","seg","fromCharCode","toUpperCase","cyfsUrl","dfsRoot","abs","serdeKind","isInteger","JSON","stringify","argError","reason","reqString","args","optString","utf8","decodeLossy","TextDecoder","ignoreBOM","decode","splitLinesPreserveEnding","content","match","strLines","l","compactCmdParamPreview","escaped","totalLines","CMD_PARAM_PREVIEW_KEEP_CHARS","parseMarkerToken","rangeText","parseCountText","parseMarkerJson","parseRangeSpec","isObject","start","end","count","parseCountJson","defaultEnd","includes","endText","dash","indexOf","left","right","parseRangeText","resolveMarker","total","READ_FILE_SPEC","description","args_schema","properties","first_chunk","type","range","required","WRITE_FILE_SPEC","mode","EDIT_FILE_SPEC","new_string","old_string","readRaw","readFile","writeText","mkdir","recursive","writeFile","readFileTool","cfg","spec","idempotent","cancellable","call","rawPath","firstChunk","filePath","allowedRead","looksBinary","matched","chunkStart","lines","startMarker","startRaw","endRaw","resolveRange","si","ei","selected","startLine","endLine","preview","cmd","readCmdLine","base","url","cyfs_url","line_range","line_count","start_line","end_line","preview_truncated","result","what","window","output","dedup","hint","withReadDedup","fromEntries","entries","normalizeWriteMode","toLowerCase","writeFileTool","rawMode","cmdMode","allowedWrite","present","exists","original","operation","updated","lineCount","bytesAfter","created","changed","bytes_written","editFileTool","oldString","newString","matches","at","diff","before","after","body","o","buildSimpleDiff","diff_truncated","NATIVE_WRAPPER","SYSTEM_PATH_ENTRIES","sanitizeCallId","callId","execDirFor","runDir","fmtElapsed","ms","readBytes","readFileBounded","headCap","tailCap","head","rest","boundedText","readFileTail","readExitFile","outputFromExecDir","exitCode","timedOut","elapsedMs","cwd","stdout","outTrunc","stderr","errTrunc","exit_code","output_truncated","timed_out","duration_ms","SIGNALS","SIGHUP","SIGINT","SIGQUIT","SIGILL","SIGTRAP","SIGABRT","SIGBUS","SIGFPE","SIGKILL","SIGUSR1","SIGSEGV","SIGUSR2","SIGPIPE","SIGALRM","SIGTERM","RESULT_STRING_FIELDS","shellSpec","maxTimeoutMs","timeoutMs","timeout","minimum","maximum","command","restrictCwd","timeout_ms","parseMs","localSeq","sleepOrStop","timer","done","resolve","setTimeout","stop","clearTimeout","shellTool","rawCwd","workspace","userEnv","parseEnv","timeoutRaw","resolveTimeout","wait_ms","reqEnv","Map","entry","call_id","run_id","PATH","Set","bound","run_dir","temp","pid","stale","remove","catch","child","started","performance","now","Command","stdin","spawn","cleanup","kill","race","first","then","exited","cancelled","cause","cancel","signal","code","trimEnd","stopped","inner","commandHasShellOperator","parse","task_id","return_code","forwardInnerResult","engine","runtime","withOutput","shellFinishedResult","NATIVE_KIND","LOCAL_PROBE","parseProbe","XllmError","capability","machine","hostname","arch","shell","current_time","timezone","tools","localProbe","AbortSignal","success","configError","config","validateEnv","INTENT_ARG","NativeToolManager","advertised","binding","ledger","MemoryHintLedger","written","bindRun","setRecovering","recovering","artifacts","has","hintLedger","clearDedup","clear","HINT_NS_DEDUP","taskResolver","listToolSpecs","values","sort","cloneJson","schema","withOptionalIntent","names","keys","callTool","effect_unknown","running","ok","err","settled","cancelledHard","ToolDispatchException","taskId","_b","taskStateObservation","toHost","envelopeObservation","applyHints","nativeDescriptor","runtimeId","probe","runtime_id","capabilities","network","shellNeedsTasks","createNativeRuntime","options","configured","PLANNED_RUNTIME_KINDS","remote_ssh","remote_node","task_wait_ms","validateConfig","baseline","shellName","platform","shell_kind","infoOf","descriptor","expand","sources","field","fsPolicy","src","desc","describeToolSource","groupname","BUILTIN_TOOL_GROUP_BASH_CORE","BUILTIN_TOOL_GROUP_BASH","restrict","fileCfg","group","max_timeout_ms","source","openedNames","requested","takeover","enabled","filesystem_policy","tools2actions","tool_sources","actions","action_sources","bash_tools","shellSettings","loop","loop_model","eff","native","exec_enabled","toolSources","explicit","manager","describeInterrupted","run","unresolvedReason","interruptedShellText","readExecDir","mtime","getTime","stdout_tail","stderr_tail","started_at_ms","tails","facts","location","one","shellCommandOf","Date","DEFAULT_RUNS_DIR","DEFAULT_LOCK_DIR","resolveHostPath","baseDir","resolveConfigPath","homeDir","runsDirOf","setting","origin","FileLock","file","released","tryAcquire","storage","tryLock","writeTextFile","release","unlock","isLocked","tmpCounter","pad4","FileRunStore","runsDir","persistent","runId","ensureWritable","createRun","generateRunId","writeRecord","record","rename","readRecord","runs_dir","version","RUN_RECORD_VERSION","notResumable","prompt","listRecords","readDir","rec","putSnapshot","snapshot","idxs","listSnapshots","next","getSnapshot","idx","exec","lockRun","isRunLive","removeRun","importRun","snapshots","workdirLocker","lock","workdirExists","SESSION_TOKEN_ENV","resolveSecret","ref","doc","credentialsRefusedClient","infer","providerError","refused","REFUSED_CREDENTIALS","createLlmClient","provider","api_key","OpenAiLlmClient","baseUrl","base_url","apiKey","headers","on_behalf_of","token","session_token","appId","sdk","URL","self","href","import","loadNodeSdk","BuckyOSSDK","initBuckyOS","zoneHost","_c","defaultProtocol","runtimeType","sessionToken","privateKeySearchPaths","autoRenew","AiccLlmClient","getAiccClient","nativeDeps","store","llm","deps","lockWorkdir","observer","tokenizer","pendingLlm","other","unavailableRuntime","error","fail","rejected","reject","llmContext","input","overrides","merged","mergeConfigLayers","parseLlmContextJson","MemoryRunStore","draft","task","XllmTask","prepare","limits","isTerminal","XllmRun","resume"],"mappings":"gWA6EO,SAASA,IACd,MAAMC,EAAKC,WAA6CC,KACxD,IAAKF,EAAS,MAAA,IAAIG,MAAM,6CACjB,OAAAH,CACT,CAEO,SAASI,EAAWC,GAClB,OAAAA,aAAaN,IAAOO,OAAOC,QACpC,CAEO,SAASC,EAAgBH,GACvB,OAAAA,aAAaN,IAAOO,OAAOG,aACpC,CAEO,SAASC,EAAUL,GACxB,OAAOA,aAAaF,MAAQE,EAAEM,QAAUC,OAAOP,EACjD,CAQO,SAASQ,KAAYC,GAC1B,IAAIC,EAAM,GACV,IAAA,MAAWC,KAAKF,EACTE,IACgCD,EAAjCC,EAAEC,WAAW,OAASF,EAAWC,EAC1BD,EAAIG,SAAS,KAAOH,EAAMC,EAAI,GAAGD,KAAOC,KAE9C,OAAAD,CACT,CAEO,SAASI,EAAUH,GACxB,MAAMI,EAAIJ,EAAEK,QAAQ,OAAQ,IACtBC,EAAIF,EAAEG,YAAY,KACjB,OAAAD,EAAI,EAAI,IAAY,IAANA,EAAU,IAAMF,EAAEI,MAAM,EAAGF,EAClD,CAYAG,eAAsBC,EAAMV,GACtB,IACF,aAAcjB,IAAO4B,KAAKX,IAAIY,WAAA,CACxB,MACC,OAAA,CACT,CACF,CAGsBH,eAAAI,EAAgBC,EAAcC,GAClD,MAAMC,QAAUjC,IAAOkC,KAAKH,EAAM,CAAEI,OAAO,EAAMC,QAAQ,EAAMC,UAAU,IACrE,IACF,IAAIC,EAAM,EACV,KAAOA,EAAMN,EAAMO,QAAQD,SAAaL,EAAEE,MAAMH,EAAMQ,SAASF,UACzDL,EAAEQ,MAAK,CACb,QACAR,EAAES,OACJ,CACF,CAGAhB,eAAsBiB,EAAQC,GACxB,GAAoB,YAApB5C,IAAO6C,MAAMC,GAAkB,OAC7B,MAAAb,QAAUjC,IAAOkC,KAAKU,EAAK,CAAEG,MAAM,IACrC,UACId,EAAEQ,MAAK,CACb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