@caplets/core 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/auth.d.ts +2 -1
  2. package/dist/caplet-files-bundle.d.ts +62 -0
  3. package/dist/caplet-sets.d.ts +2 -0
  4. package/dist/caplet-source.js +96 -4
  5. package/dist/cli/add.d.ts +10 -0
  6. package/dist/cli/auth.d.ts +22 -0
  7. package/dist/cli/code-mode.d.ts +3 -0
  8. package/dist/cli/commands.d.ts +1 -1
  9. package/dist/cli.d.ts +1 -1
  10. package/dist/code-mode/api.d.ts +3 -1
  11. package/dist/code-mode/diagnostics-builtins.generated.d.ts +1 -0
  12. package/dist/code-mode/diagnostics.d.ts +8 -0
  13. package/dist/code-mode/index.d.ts +1 -1
  14. package/dist/code-mode/journal.d.ts +103 -0
  15. package/dist/code-mode/platform-entry.d.ts +1 -0
  16. package/dist/code-mode/platform-host.d.ts +6 -0
  17. package/dist/code-mode/platform-runtime.generated.d.ts +1 -0
  18. package/dist/code-mode/runner.d.ts +5 -0
  19. package/dist/code-mode/runtime-api.generated.d.ts +1 -1
  20. package/dist/code-mode/sandbox.d.ts +14 -1
  21. package/dist/code-mode/sessions.d.ts +53 -0
  22. package/dist/code-mode/tool.d.ts +5 -0
  23. package/dist/code-mode/types.d.ts +30 -0
  24. package/dist/code-mode.js +21 -14
  25. package/dist/{completion-DnQujlrc.js → completion-CzHdM9B_.js} +14 -2
  26. package/dist/config/paths.d.ts +2 -0
  27. package/dist/config-runtime.d.ts +13 -1
  28. package/dist/config-runtime.js +44 -0
  29. package/dist/config.d.ts +25 -1
  30. package/dist/engine.d.ts +3 -0
  31. package/dist/google-discovery/index.d.ts +5 -0
  32. package/dist/google-discovery/manager.d.ts +37 -0
  33. package/dist/google-discovery/operations.d.ts +32 -0
  34. package/dist/google-discovery/request.d.ts +5 -0
  35. package/dist/google-discovery/schema.d.ts +2 -0
  36. package/dist/google-discovery/types.d.ts +70 -0
  37. package/dist/http/response.d.ts +14 -0
  38. package/dist/http-actions.d.ts +3 -0
  39. package/dist/index.js +190 -43
  40. package/dist/media/artifacts.d.ts +24 -0
  41. package/dist/media/index.d.ts +2 -0
  42. package/dist/media/input.d.ts +29 -0
  43. package/dist/native/options.d.ts +3 -6
  44. package/dist/native/remote.d.ts +2 -0
  45. package/dist/native/service.d.ts +2 -0
  46. package/dist/native/tools.d.ts +1 -0
  47. package/dist/native.js +1 -1
  48. package/dist/{observed-output-shapes-CL5MFXwM.js → observed-output-shapes-D2k2-q8K.js} +9 -0
  49. package/dist/observed-output-shapes.js +1 -1
  50. package/dist/openapi.d.ts +2 -0
  51. package/dist/registry.d.ts +6 -0
  52. package/dist/remote/options.d.ts +1 -1
  53. package/dist/runtime-plan.js +1 -1
  54. package/dist/runtime.d.ts +2 -0
  55. package/dist/serve/session.d.ts +1 -0
  56. package/dist/{service-4_chB2wu.js → service-BCT_Ls_3.js} +3878 -361
  57. package/dist/tools.d.ts +2 -1
  58. package/package.json +9 -2
@@ -0,0 +1 @@
1
+ export declare const CODE_MODE_PLATFORM_RUNTIME_SOURCE: "(function() {\n\t//#region node_modules/.pnpm/@ungap+structured-clone@1.3.1/node_modules/@ungap/structured-clone/esm/deserialize.js\n\tconst env = typeof self === \"object\" ? self : globalThis;\n\tconst guard = (name, init) => {\n\t\tswitch (name) {\n\t\t\tcase \"Function\":\n\t\t\tcase \"SharedWorker\":\n\t\t\tcase \"Worker\":\n\t\t\tcase \"eval\":\n\t\t\tcase \"setInterval\":\n\t\t\tcase \"setTimeout\": throw new TypeError(\"unable to deserialize \" + name);\n\t\t}\n\t\treturn new env[name](init);\n\t};\n\tconst deserializer = ($, _) => {\n\t\tconst as = (out, index) => {\n\t\t\t$.set(index, out);\n\t\t\treturn out;\n\t\t};\n\t\tconst unpair = (index) => {\n\t\t\tif ($.has(index)) return $.get(index);\n\t\t\tconst [type, value] = _[index];\n\t\t\tswitch (type) {\n\t\t\t\tcase 0:\n\t\t\t\tcase -1: return as(value, index);\n\t\t\t\tcase 1: {\n\t\t\t\t\tconst arr = as([], index);\n\t\t\t\t\tfor (const index of value) arr.push(unpair(index));\n\t\t\t\t\treturn arr;\n\t\t\t\t}\n\t\t\t\tcase 2: {\n\t\t\t\t\tconst object = as({}, index);\n\t\t\t\t\tfor (const [key, index] of value) object[unpair(key)] = unpair(index);\n\t\t\t\t\treturn object;\n\t\t\t\t}\n\t\t\t\tcase 3: return as(new Date(value), index);\n\t\t\t\tcase 4: {\n\t\t\t\t\tconst { source, flags } = value;\n\t\t\t\t\treturn as(new RegExp(source, flags), index);\n\t\t\t\t}\n\t\t\t\tcase 5: {\n\t\t\t\t\tconst map = as(/* @__PURE__ */ new Map(), index);\n\t\t\t\t\tfor (const [key, index] of value) map.set(unpair(key), unpair(index));\n\t\t\t\t\treturn map;\n\t\t\t\t}\n\t\t\t\tcase 6: {\n\t\t\t\t\tconst set = as(/* @__PURE__ */ new Set(), index);\n\t\t\t\t\tfor (const index of value) set.add(unpair(index));\n\t\t\t\t\treturn set;\n\t\t\t\t}\n\t\t\t\tcase 7: {\n\t\t\t\t\tconst { name, message } = value;\n\t\t\t\t\treturn as(guard(name, message), index);\n\t\t\t\t}\n\t\t\t\tcase 8: return as(BigInt(value), index);\n\t\t\t\tcase \"BigInt\": return as(Object(BigInt(value)), index);\n\t\t\t\tcase \"ArrayBuffer\": return as(new Uint8Array(value).buffer, value);\n\t\t\t\tcase \"DataView\": {\n\t\t\t\t\tconst { buffer } = new Uint8Array(value);\n\t\t\t\t\treturn as(new DataView(buffer), value);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn as(guard(type, value), index);\n\t\t};\n\t\treturn unpair;\n\t};\n\t/**\n\t* @typedef {Array<string,any>} Record a type representation\n\t*/\n\t/**\n\t* Returns a deserialized value from a serialized array of Records.\n\t* @param {Record[]} serialized a previously serialized value.\n\t* @returns {any}\n\t*/\n\tconst deserialize = (serialized) => deserializer(/* @__PURE__ */ new Map(), serialized)(0);\n\t//#endregion\n\t//#region node_modules/.pnpm/@ungap+structured-clone@1.3.1/node_modules/@ungap/structured-clone/esm/serialize.js\n\tconst EMPTY = \"\";\n\tconst { toString } = {};\n\tconst { keys } = Object;\n\tconst typeOf = (value) => {\n\t\tconst type = typeof value;\n\t\tif (type !== \"object\" || !value) return [0, type];\n\t\tconst asString = toString.call(value).slice(8, -1);\n\t\tswitch (asString) {\n\t\t\tcase \"Array\": return [1, EMPTY];\n\t\t\tcase \"Object\": return [2, EMPTY];\n\t\t\tcase \"Date\": return [3, EMPTY];\n\t\t\tcase \"RegExp\": return [4, EMPTY];\n\t\t\tcase \"Map\": return [5, EMPTY];\n\t\t\tcase \"Set\": return [6, EMPTY];\n\t\t\tcase \"DataView\": return [1, asString];\n\t\t}\n\t\tif (asString.includes(\"Array\")) return [1, asString];\n\t\tif (asString.includes(\"Error\")) return [7, asString];\n\t\treturn [2, asString];\n\t};\n\tconst shouldSkip = ([TYPE, type]) => TYPE === 0 && (type === \"function\" || type === \"symbol\");\n\tconst serializer = (strict, json, $, _) => {\n\t\tconst as = (out, value) => {\n\t\t\tconst index = _.push(out) - 1;\n\t\t\t$.set(value, index);\n\t\t\treturn index;\n\t\t};\n\t\tconst pair = (value) => {\n\t\t\tif ($.has(value)) return $.get(value);\n\t\t\tlet [TYPE, type] = typeOf(value);\n\t\t\tswitch (TYPE) {\n\t\t\t\tcase 0: {\n\t\t\t\t\tlet entry = value;\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase \"bigint\":\n\t\t\t\t\t\t\tTYPE = 8;\n\t\t\t\t\t\t\tentry = value.toString();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"function\":\n\t\t\t\t\t\tcase \"symbol\":\n\t\t\t\t\t\t\tif (strict) throw new TypeError(\"unable to serialize \" + type);\n\t\t\t\t\t\t\tentry = null;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"undefined\": return as([-1], value);\n\t\t\t\t\t}\n\t\t\t\t\treturn as([TYPE, entry], value);\n\t\t\t\t}\n\t\t\t\tcase 1: {\n\t\t\t\t\tif (type) {\n\t\t\t\t\t\tlet spread = value;\n\t\t\t\t\t\tif (type === \"DataView\") spread = new Uint8Array(value.buffer);\n\t\t\t\t\t\telse if (type === \"ArrayBuffer\") spread = new Uint8Array(value);\n\t\t\t\t\t\treturn as([type, [...spread]], value);\n\t\t\t\t\t}\n\t\t\t\t\tconst arr = [];\n\t\t\t\t\tconst index = as([TYPE, arr], value);\n\t\t\t\t\tfor (const entry of value) arr.push(pair(entry));\n\t\t\t\t\treturn index;\n\t\t\t\t}\n\t\t\t\tcase 2: {\n\t\t\t\t\tif (type) switch (type) {\n\t\t\t\t\t\tcase \"BigInt\": return as([type, value.toString()], value);\n\t\t\t\t\t\tcase \"Boolean\":\n\t\t\t\t\t\tcase \"Number\":\n\t\t\t\t\t\tcase \"String\": return as([type, value.valueOf()], value);\n\t\t\t\t\t}\n\t\t\t\t\tif (json && \"toJSON\" in value) return pair(value.toJSON());\n\t\t\t\t\tconst entries = [];\n\t\t\t\t\tconst index = as([TYPE, entries], value);\n\t\t\t\t\tfor (const key of keys(value)) if (strict || !shouldSkip(typeOf(value[key]))) entries.push([pair(key), pair(value[key])]);\n\t\t\t\t\treturn index;\n\t\t\t\t}\n\t\t\t\tcase 3: return as([TYPE, value.toISOString()], value);\n\t\t\t\tcase 4: {\n\t\t\t\t\tconst { source, flags } = value;\n\t\t\t\t\treturn as([TYPE, {\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tflags\n\t\t\t\t\t}], value);\n\t\t\t\t}\n\t\t\t\tcase 5: {\n\t\t\t\t\tconst entries = [];\n\t\t\t\t\tconst index = as([TYPE, entries], value);\n\t\t\t\t\tfor (const [key, entry] of value) if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry)))) entries.push([pair(key), pair(entry)]);\n\t\t\t\t\treturn index;\n\t\t\t\t}\n\t\t\t\tcase 6: {\n\t\t\t\t\tconst entries = [];\n\t\t\t\t\tconst index = as([TYPE, entries], value);\n\t\t\t\t\tfor (const entry of value) if (strict || !shouldSkip(typeOf(entry))) entries.push(pair(entry));\n\t\t\t\t\treturn index;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst { message } = value;\n\t\t\treturn as([TYPE, {\n\t\t\t\tname: type,\n\t\t\t\tmessage\n\t\t\t}], value);\n\t\t};\n\t\treturn pair;\n\t};\n\t/**\n\t* @typedef {Array<string,any>} Record a type representation\n\t*/\n\t/**\n\t* Returns an array of serialized Records.\n\t* @param {any} value a serializable value.\n\t* @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,\n\t* if `true`, will not throw errors on incompatible types, and behave more\n\t* like JSON stringify would behave. Symbol and Function will be discarded.\n\t* @returns {Record[]}\n\t*/\n\tconst serialize = (value, { json, lossy } = {}) => {\n\t\tconst _ = [];\n\t\treturn serializer(!(json || lossy), !!json, /* @__PURE__ */ new Map(), _)(value), _;\n\t};\n\t//#endregion\n\t//#region node_modules/.pnpm/@ungap+structured-clone@1.3.1/node_modules/@ungap/structured-clone/esm/index.js\n\t/**\n\t* @typedef {Array<string,any>} Record a type representation\n\t*/\n\t/**\n\t* Returns an array of serialized Records.\n\t* @param {any} any a serializable value.\n\t* @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with\n\t* a transfer option (ignored when polyfilled) and/or non standard fields that\n\t* fallback to the polyfill if present.\n\t* @returns {Record[]}\n\t*/\n\tvar esm_default = typeof structuredClone === \"function\" ? (any, options) => options && (\"json\" in options || \"lossy\" in options) ? deserialize(serialize(any, options)) : structuredClone(any) : (any, options) => deserialize(serialize(any, options));\n\t//#endregion\n\t//#region node_modules/.pnpm/formdata-node@6.0.3/node_modules/formdata-node/lib/form-data.js\n\tvar __accessCheck = (obj, member, msg) => {\n\t\tif (!member.has(obj)) throw TypeError(\"Cannot \" + msg);\n\t};\n\tvar __privateGet = (obj, member, getter) => {\n\t\t__accessCheck(obj, member, \"read from private field\");\n\t\treturn getter ? getter.call(obj) : member.get(obj);\n\t};\n\tvar __privateAdd = (obj, member, value) => {\n\t\tif (member.has(obj)) throw TypeError(\"Cannot add the same private member more than once\");\n\t\tmember instanceof WeakSet ? member.add(obj) : member.set(obj, value);\n\t};\n\tvar __privateSet = (obj, member, value, setter) => {\n\t\t__accessCheck(obj, member, \"write to private field\");\n\t\tsetter ? setter.call(obj, value) : member.set(obj, value);\n\t\treturn value;\n\t};\n\tvar __privateMethod = (obj, member, method) => {\n\t\t__accessCheck(obj, member, \"access private method\");\n\t\treturn method;\n\t};\n\tvar isFunction = (value) => typeof value === \"function\";\n\tvar isObject = (value) => typeof value === \"object\" && value != null && !Array.isArray(value);\n\tvar isAsyncIterable = (value) => isObject(value) && isFunction(value[Symbol.asyncIterator]);\n\tvar MAX_CHUNK_SIZE = 65536;\n\tasync function* clonePart(value) {\n\t\tif (value.byteLength <= MAX_CHUNK_SIZE) {\n\t\t\tyield value;\n\t\t\treturn;\n\t\t}\n\t\tlet offset = 0;\n\t\twhile (offset < value.byteLength) {\n\t\t\tconst size = Math.min(value.byteLength - offset, MAX_CHUNK_SIZE);\n\t\t\tconst buffer = value.buffer.slice(offset, offset + size);\n\t\t\toffset += buffer.byteLength;\n\t\t\tyield new Uint8Array(buffer);\n\t\t}\n\t}\n\tasync function* readStream(readable) {\n\t\tconst reader = readable.getReader();\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tyield value;\n\t\t}\n\t}\n\tasync function* chunkStream(stream) {\n\t\tfor await (const value of stream) yield* clonePart(value);\n\t}\n\tvar getStreamIterator = (source) => {\n\t\tif (isAsyncIterable(source)) return chunkStream(source);\n\t\tif (isFunction(source.getReader)) return chunkStream(readStream(source));\n\t\tthrow new TypeError(\"Unsupported data source: Expected either ReadableStream or async iterable.\");\n\t};\n\tasync function* consumeNodeBlob(blob) {\n\t\tlet position = 0;\n\t\twhile (position !== blob.size) {\n\t\t\tconst buffer = await blob.slice(position, Math.min(blob.size, position + MAX_CHUNK_SIZE)).arrayBuffer();\n\t\t\tposition += buffer.byteLength;\n\t\t\tyield new Uint8Array(buffer);\n\t\t}\n\t}\n\tasync function* consumeBlobParts(parts, clone = false) {\n\t\tfor (const part of parts) if (ArrayBuffer.isView(part)) if (clone) yield* clonePart(part);\n\t\telse yield part;\n\t\telse if (isFunction(part.stream)) yield* getStreamIterator(part.stream());\n\t\telse yield* consumeNodeBlob(part);\n\t}\n\tfunction* sliceBlob(blobParts, blobSize, start = 0, end) {\n\t\tend ??= blobSize;\n\t\tlet relativeStart = start < 0 ? Math.max(blobSize + start, 0) : Math.min(start, blobSize);\n\t\tlet relativeEnd = end < 0 ? Math.max(blobSize + end, 0) : Math.min(end, blobSize);\n\t\tconst span = Math.max(relativeEnd - relativeStart, 0);\n\t\tlet added = 0;\n\t\tfor (const part of blobParts) {\n\t\t\tif (added >= span) break;\n\t\t\tconst partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size;\n\t\t\tif (relativeStart && partSize <= relativeStart) {\n\t\t\t\trelativeStart -= partSize;\n\t\t\t\trelativeEnd -= partSize;\n\t\t\t} else {\n\t\t\t\tlet chunk;\n\t\t\t\tif (ArrayBuffer.isView(part)) {\n\t\t\t\t\tchunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd));\n\t\t\t\t\tadded += chunk.byteLength;\n\t\t\t\t} else {\n\t\t\t\t\tchunk = part.slice(relativeStart, Math.min(partSize, relativeEnd));\n\t\t\t\t\tadded += chunk.size;\n\t\t\t\t}\n\t\t\t\trelativeEnd -= partSize;\n\t\t\t\trelativeStart = 0;\n\t\t\t\tyield chunk;\n\t\t\t}\n\t\t}\n\t}\n\tvar _parts, _type, _size;\n\tvar _Blob = class _Blob {\n\t\t/**\n\t\t* Returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object.\n\t\t* The content of the blob consists of the concatenation of the values given in the parameter array.\n\t\t*\n\t\t* @param blobParts An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t\t* @param options An optional object of type `BlobPropertyBag`.\n\t\t*/\n\t\tconstructor(blobParts = [], options = {}) {\n\t\t\t/**\n\t\t\t* An `Array` of [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) or [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t\t\t*/\n\t\t\t__privateAdd(this, _parts, []);\n\t\t\t/**\n\t\t\t* Returns the [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).\n\t\t\t*/\n\t\t\t__privateAdd(this, _type, \"\");\n\t\t\t/**\n\t\t\t* Returns the size of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) in bytes.\n\t\t\t*/\n\t\t\t__privateAdd(this, _size, 0);\n\t\t\toptions ??= {};\n\t\t\tif (typeof blobParts !== \"object\" || blobParts === null) throw new TypeError(\"Failed to construct 'Blob': The provided value cannot be converted to a sequence.\");\n\t\t\tif (!isFunction(blobParts[Symbol.iterator])) throw new TypeError(\"Failed to construct 'Blob': The object must have a callable @@iterator property.\");\n\t\t\tif (typeof options !== \"object\" && !isFunction(options)) throw new TypeError(\"Failed to construct 'Blob': parameter 2 cannot convert to dictionary.\");\n\t\t\tconst encoder = new TextEncoder();\n\t\t\tfor (const raw of blobParts) {\n\t\t\t\tlet part;\n\t\t\t\tif (ArrayBuffer.isView(raw)) part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength));\n\t\t\t\telse if (raw instanceof ArrayBuffer) part = new Uint8Array(raw.slice(0));\n\t\t\t\telse if (raw instanceof _Blob) part = raw;\n\t\t\t\telse part = encoder.encode(String(raw));\n\t\t\t\t__privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size));\n\t\t\t\t__privateGet(this, _parts).push(part);\n\t\t\t}\n\t\t\tconst type = options.type === void 0 ? \"\" : String(options.type);\n\t\t\t__privateSet(this, _type, /^[\\x20-\\x7E]*$/.test(type) ? type : \"\");\n\t\t}\n\t\tstatic [Symbol.hasInstance](value) {\n\t\t\treturn Boolean(value && typeof value === \"object\" && isFunction(value.constructor) && (isFunction(value.stream) || isFunction(value.arrayBuffer)) && /^(Blob|File)$/.test(value[Symbol.toStringTag]));\n\t\t}\n\t\t/**\n\t\t* Returns the [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).\n\t\t*/\n\t\tget type() {\n\t\t\treturn __privateGet(this, _type);\n\t\t}\n\t\t/**\n\t\t* Returns the size of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) in bytes.\n\t\t*/\n\t\tget size() {\n\t\t\treturn __privateGet(this, _size);\n\t\t}\n\t\t/**\n\t\t* Creates and returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object which contains data from a subset of the blob on which it's called.\n\t\t*\n\t\t* @param start An index into the Blob indicating the first byte to include in the new Blob. If you specify a negative value, it's treated as an offset from the end of the Blob toward the beginning. For example, -10 would be the 10th from last byte in the Blob. The default value is 0. If you specify a value for start that is larger than the size of the source Blob, the returned Blob has size 0 and contains no data.\n\t\t* @param end An index into the Blob indicating the first byte that will *not* be included in the new Blob (i.e. the byte exactly at this index is not included). If you specify a negative value, it's treated as an offset from the end of the Blob toward the beginning. For example, -10 would be the 10th from last byte in the Blob. The default value is size.\n\t\t* @param contentType The content type to assign to the new Blob; this will be the value of its type property. The default value is an empty string.\n\t\t*/\n\t\tslice(start, end, contentType) {\n\t\t\treturn new _Blob(sliceBlob(__privateGet(this, _parts), this.size, start, end), { type: contentType });\n\t\t}\n\t\t/**\n\t\t* Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a string containing the contents of the blob, interpreted as UTF-8.\n\t\t*/\n\t\tasync text() {\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet result = \"\";\n\t\t\tfor await (const chunk of consumeBlobParts(__privateGet(this, _parts))) result += decoder.decode(chunk, { stream: true });\n\t\t\tresult += decoder.decode();\n\t\t\treturn result;\n\t\t}\n\t\t/**\n\t\t* Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the contents of the blob as binary data contained in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).\n\t\t*/\n\t\tasync arrayBuffer() {\n\t\t\tconst view = new Uint8Array(this.size);\n\t\t\tlet offset = 0;\n\t\t\tfor await (const chunk of consumeBlobParts(__privateGet(this, _parts))) {\n\t\t\t\tview.set(chunk, offset);\n\t\t\t\toffset += chunk.length;\n\t\t\t}\n\t\t\treturn view.buffer;\n\t\t}\n\t\t/**\n\t\t* Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t\t*/\n\t\tstream() {\n\t\t\tconst iterator = consumeBlobParts(__privateGet(this, _parts), true);\n\t\t\treturn new ReadableStream({\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\tconst { value, done } = await iterator.next();\n\t\t\t\t\tif (done) return queueMicrotask(() => controller.close());\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t},\n\t\t\t\tasync cancel() {\n\t\t\t\t\tawait iterator.return();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tget [Symbol.toStringTag]() {\n\t\t\treturn \"Blob\";\n\t\t}\n\t};\n\t_parts = /* @__PURE__ */ new WeakMap();\n\t_type = /* @__PURE__ */ new WeakMap();\n\t_size = /* @__PURE__ */ new WeakMap();\n\tvar Blob = _Blob;\n\tObject.defineProperties(Blob.prototype, {\n\t\ttype: { enumerable: true },\n\t\tsize: { enumerable: true },\n\t\tslice: { enumerable: true },\n\t\tstream: { enumerable: true },\n\t\ttext: { enumerable: true },\n\t\tarrayBuffer: { enumerable: true }\n\t});\n\tvar isBlob = (value) => value instanceof Blob;\n\tvar _name, _lastModified;\n\tvar File = class extends Blob {\n\t\t/**\n\t\t* Creates a new File instance.\n\t\t*\n\t\t* @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).\n\t\t* @param name The name of the file.\n\t\t* @param options An options object containing optional attributes for the file.\n\t\t*/\n\t\tconstructor(fileBits, name, options = {}) {\n\t\t\tsuper(fileBits, options);\n\t\t\t/**\n\t\t\t* Returns the name of the file referenced by the File object.\n\t\t\t*/\n\t\t\t__privateAdd(this, _name, void 0);\n\t\t\t/**\n\t\t\t* The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.\n\t\t\t*/\n\t\t\t__privateAdd(this, _lastModified, 0);\n\t\t\tif (arguments.length < 2) throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);\n\t\t\t__privateSet(this, _name, String(name));\n\t\t\tconst lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified);\n\t\t\tif (!Number.isNaN(lastModified)) __privateSet(this, _lastModified, lastModified);\n\t\t}\n\t\tstatic [Symbol.hasInstance](value) {\n\t\t\treturn value instanceof Blob && value[Symbol.toStringTag] === \"File\" && typeof value.name === \"string\";\n\t\t}\n\t\t/**\n\t\t* Name of the file referenced by the File object.\n\t\t*/\n\t\tget name() {\n\t\t\treturn __privateGet(this, _name);\n\t\t}\n\t\t/* c8 ignore next 3 */\n\t\tget webkitRelativePath() {\n\t\t\treturn \"\";\n\t\t}\n\t\t/**\n\t\t* The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.\n\t\t*/\n\t\tget lastModified() {\n\t\t\treturn __privateGet(this, _lastModified);\n\t\t}\n\t\tget [Symbol.toStringTag]() {\n\t\t\treturn \"File\";\n\t\t}\n\t};\n\t_name = /* @__PURE__ */ new WeakMap();\n\t_lastModified = /* @__PURE__ */ new WeakMap();\n\tvar isFile = (value) => value instanceof File;\n\tvar _entries, _setEntry, setEntry_fn;\n\tvar FormData = class {\n\t\tconstructor() {\n\t\t\t__privateAdd(this, _setEntry);\n\t\t\t/**\n\t\t\t* Stores internal data for every entry\n\t\t\t*/\n\t\t\t__privateAdd(this, _entries, /* @__PURE__ */ new Map());\n\t\t}\n\t\tstatic [Symbol.hasInstance](value) {\n\t\t\tif (!value) return false;\n\t\t\tconst val = value;\n\t\t\treturn Boolean(isFunction(val.constructor) && val[Symbol.toStringTag] === \"FormData\" && isFunction(val.append) && isFunction(val.set) && isFunction(val.get) && isFunction(val.getAll) && isFunction(val.has) && isFunction(val.delete) && isFunction(val.entries) && isFunction(val.values) && isFunction(val.keys) && isFunction(val[Symbol.iterator]) && isFunction(val.forEach));\n\t\t}\n\t\t/**\n\t\t* Appends a new value onto an existing key inside a FormData object,\n\t\t* or adds the key if it does not already exist.\n\t\t*\n\t\t* The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.\n\t\t*\n\t\t* @param name The name of the field whose data is contained in `value`.\n\t\t* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)\n\t\tor [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.\n\t\t* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is \"blob\". The default filename for File objects is the file's filename.\n\t\t*/\n\t\tappend(name, value, fileName) {\n\t\t\t__privateMethod(this, _setEntry, setEntry_fn).call(this, {\n\t\t\t\tname,\n\t\t\t\tfileName,\n\t\t\t\tappend: true,\n\t\t\t\trawValue: value,\n\t\t\t\targsLength: arguments.length\n\t\t\t});\n\t\t}\n\t\t/**\n\t\t* Set a new value for an existing key inside FormData,\n\t\t* or add the new field if it does not already exist.\n\t\t*\n\t\t* @param name The name of the field whose data is contained in `value`.\n\t\t* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)\n\t\tor [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.\n\t\t* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is \"blob\". The default filename for File objects is the file's filename.\n\t\t*\n\t\t*/\n\t\tset(name, value, fileName) {\n\t\t\t__privateMethod(this, _setEntry, setEntry_fn).call(this, {\n\t\t\t\tname,\n\t\t\t\tfileName,\n\t\t\t\tappend: false,\n\t\t\t\trawValue: value,\n\t\t\t\targsLength: arguments.length\n\t\t\t});\n\t\t}\n\t\t/**\n\t\t* Returns the first value associated with a given key from within a `FormData` object.\n\t\t* If you expect multiple values and want all of them, use the `getAll()` method instead.\n\t\t*\n\t\t* @param {string} name A name of the value you want to retrieve.\n\t\t*\n\t\t* @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.\n\t\t*/\n\t\tget(name) {\n\t\t\tconst field = __privateGet(this, _entries).get(String(name));\n\t\t\tif (!field) return null;\n\t\t\treturn field[0];\n\t\t}\n\t\t/**\n\t\t* Returns all the values associated with a given key from within a `FormData` object.\n\t\t*\n\t\t* @param {string} name A name of the value you want to retrieve.\n\t\t*\n\t\t* @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.\n\t\t*/\n\t\tgetAll(name) {\n\t\t\tconst field = __privateGet(this, _entries).get(String(name));\n\t\t\tif (!field) return [];\n\t\t\treturn field.slice();\n\t\t}\n\t\t/**\n\t\t* Returns a boolean stating whether a `FormData` object contains a certain key.\n\t\t*\n\t\t* @param name A string representing the name of the key you want to test for.\n\t\t*\n\t\t* @return A boolean value.\n\t\t*/\n\t\thas(name) {\n\t\t\treturn __privateGet(this, _entries).has(String(name));\n\t\t}\n\t\t/**\n\t\t* Deletes a key and its value(s) from a `FormData` object.\n\t\t*\n\t\t* @param name The name of the key you want to delete.\n\t\t*/\n\t\tdelete(name) {\n\t\t\t__privateGet(this, _entries).delete(String(name));\n\t\t}\n\t\t/**\n\t\t* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.\n\t\t* Each key is a `string`.\n\t\t*/\n\t\t*keys() {\n\t\t\tfor (const key of __privateGet(this, _entries).keys()) yield key;\n\t\t}\n\t\t/**\n\t\t* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.\n\t\t* The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).\n\t\t*/\n\t\t*entries() {\n\t\t\tfor (const name of this.keys()) {\n\t\t\t\tconst values = this.getAll(name);\n\t\t\t\tfor (const value of values) yield [name, value];\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.\n\t\t* Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).\n\t\t*/\n\t\t*values() {\n\t\t\tfor (const [, value] of this) yield value;\n\t\t}\n\t\t/**\n\t\t* An alias for FormData#entries()\n\t\t*/\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries();\n\t\t}\n\t\t/**\n\t\t* Executes given callback function for each field of the FormData instance\n\t\t*/\n\t\tforEach(callback, thisArg) {\n\t\t\tfor (const [name, value] of this) callback.call(thisArg, value, name, this);\n\t\t}\n\t\tget [Symbol.toStringTag]() {\n\t\t\treturn \"FormData\";\n\t\t}\n\t};\n\t_entries = /* @__PURE__ */ new WeakMap();\n\t_setEntry = /* @__PURE__ */ new WeakSet();\n\tsetEntry_fn = function({ name, rawValue, append, fileName, argsLength }) {\n\t\tconst methodName = append ? \"append\" : \"set\";\n\t\tif (argsLength < 2) throw new TypeError(`Failed to execute '${methodName}' on 'FormData': 2 arguments required, but only ${argsLength} present.`);\n\t\tname = String(name);\n\t\tlet value;\n\t\tif (isFile(rawValue)) value = fileName === void 0 ? rawValue : new File([rawValue], fileName, {\n\t\t\ttype: rawValue.type,\n\t\t\tlastModified: rawValue.lastModified\n\t\t});\n\t\telse if (isBlob(rawValue)) value = new File([rawValue], fileName === void 0 ? \"blob\" : fileName, { type: rawValue.type });\n\t\telse if (fileName) throw new TypeError(`Failed to execute '${methodName}' on 'FormData': parameter 2 is not of type 'Blob'.`);\n\t\telse value = String(rawValue);\n\t\tconst values = __privateGet(this, _entries).get(name);\n\t\tif (!values) {\n\t\t\t__privateGet(this, _entries).set(name, [value]);\n\t\t\treturn;\n\t\t}\n\t\tif (!append) {\n\t\t\t__privateGet(this, _entries).set(name, [value]);\n\t\t\treturn;\n\t\t}\n\t\tvalues.push(value);\n\t};\n\t/*! Based on fetch-blob. MIT License. Jimmy W\u00E4rting <https://jimmy.warting.se/opensource> & David Frank */\n\t//#endregion\n\t//#region node_modules/.pnpm/set-cookie-parser@3.1.0/node_modules/set-cookie-parser/lib/set-cookie.js\n\tvar defaultParseOptions = {\n\t\tdecodeValues: true,\n\t\tmap: false,\n\t\tsilent: false,\n\t\tsplit: \"auto\"\n\t};\n\tfunction isForbiddenKey(key) {\n\t\treturn typeof key !== \"string\" || key in {};\n\t}\n\tfunction createNullObj() {\n\t\treturn Object.create(null);\n\t}\n\tfunction isNonEmptyString(str) {\n\t\treturn typeof str === \"string\" && !!str.trim();\n\t}\n\tfunction parseString(setCookieValue, options) {\n\t\tvar parts = setCookieValue.split(\";\").filter(isNonEmptyString);\n\t\tvar parsed = parseNameValuePair(parts.shift());\n\t\tvar name = parsed.name;\n\t\tvar value = parsed.value;\n\t\toptions = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;\n\t\tif (isForbiddenKey(name)) return null;\n\t\ttry {\n\t\t\tvalue = options.decodeValues ? decodeURIComponent(value) : value;\n\t\t} catch (e) {\n\t\t\tconsole.error(\"set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.\", e);\n\t\t}\n\t\tvar cookie = createNullObj();\n\t\tcookie.name = name;\n\t\tcookie.value = value;\n\t\tparts.forEach(function(part) {\n\t\t\tvar sides = part.split(\"=\");\n\t\t\tvar key = sides.shift().trimLeft().toLowerCase();\n\t\t\tif (isForbiddenKey(key)) return;\n\t\t\tvar value = sides.join(\"=\");\n\t\t\tif (key === \"expires\") cookie.expires = new Date(value);\n\t\t\telse if (key === \"max-age\") {\n\t\t\t\tvar n = parseInt(value, 10);\n\t\t\t\tif (!Number.isNaN(n)) cookie.maxAge = n;\n\t\t\t} else if (key === \"secure\") cookie.secure = true;\n\t\t\telse if (key === \"httponly\") cookie.httpOnly = true;\n\t\t\telse if (key === \"samesite\") cookie.sameSite = value;\n\t\t\telse if (key === \"partitioned\") cookie.partitioned = true;\n\t\t\telse if (key) cookie[key] = value;\n\t\t});\n\t\treturn cookie;\n\t}\n\tfunction parseNameValuePair(nameValuePairStr) {\n\t\tvar name = \"\";\n\t\tvar value = \"\";\n\t\tvar nameValueArr = nameValuePairStr.split(\"=\");\n\t\tif (nameValueArr.length > 1) {\n\t\t\tname = nameValueArr.shift();\n\t\t\tvalue = nameValueArr.join(\"=\");\n\t\t} else value = nameValuePairStr;\n\t\treturn {\n\t\t\tname,\n\t\t\tvalue\n\t\t};\n\t}\n\tfunction parseSetCookie(input, options) {\n\t\toptions = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;\n\t\tif (!input) if (!options.map) return [];\n\t\telse return createNullObj();\n\t\tif (input.headers) if (typeof input.headers.getSetCookie === \"function\") input = input.headers.getSetCookie();\n\t\telse if (input.headers[\"set-cookie\"]) input = input.headers[\"set-cookie\"];\n\t\telse {\n\t\t\tvar sch = input.headers[Object.keys(input.headers).find(function(key) {\n\t\t\t\treturn key.toLowerCase() === \"set-cookie\";\n\t\t\t})];\n\t\t\tif (!sch && input.headers.cookie && !options.silent) console.warn(\"Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.\");\n\t\t\tinput = sch;\n\t\t}\n\t\tvar split = options.split;\n\t\tvar isArray = Array.isArray(input);\n\t\tif (split === \"auto\") split = !isArray;\n\t\tif (!isArray) input = [input];\n\t\tinput = input.filter(isNonEmptyString);\n\t\tif (split) input = input.map(splitCookiesString).flat();\n\t\tif (!options.map) return input.map(function(str) {\n\t\t\treturn parseString(str, options);\n\t\t}).filter(Boolean);\n\t\telse {\n\t\t\tvar cookies = createNullObj();\n\t\t\treturn input.reduce(function(cookies, str) {\n\t\t\t\tvar cookie = parseString(str, options);\n\t\t\t\tif (cookie && !isForbiddenKey(cookie.name)) cookies[cookie.name] = cookie;\n\t\t\t\treturn cookies;\n\t\t\t}, cookies);\n\t\t}\n\t}\n\tfunction splitCookiesString(cookiesString) {\n\t\tif (Array.isArray(cookiesString)) return cookiesString;\n\t\tif (typeof cookiesString !== \"string\") return [];\n\t\tvar cookiesStrings = [];\n\t\tvar pos = 0;\n\t\tvar start;\n\t\tvar ch;\n\t\tvar lastComma;\n\t\tvar nextStart;\n\t\tvar cookiesSeparatorFound;\n\t\tfunction skipWhitespace() {\n\t\t\twhile (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) pos += 1;\n\t\t\treturn pos < cookiesString.length;\n\t\t}\n\t\tfunction notSpecialChar() {\n\t\t\tch = cookiesString.charAt(pos);\n\t\t\treturn ch !== \"=\" && ch !== \";\" && ch !== \",\";\n\t\t}\n\t\twhile (pos < cookiesString.length) {\n\t\t\tstart = pos;\n\t\t\tcookiesSeparatorFound = false;\n\t\t\twhile (skipWhitespace()) {\n\t\t\t\tch = cookiesString.charAt(pos);\n\t\t\t\tif (ch === \",\") {\n\t\t\t\t\tlastComma = pos;\n\t\t\t\t\tpos += 1;\n\t\t\t\t\tskipWhitespace();\n\t\t\t\t\tnextStart = pos;\n\t\t\t\t\twhile (pos < cookiesString.length && notSpecialChar()) pos += 1;\n\t\t\t\t\tif (pos < cookiesString.length && cookiesString.charAt(pos) === \"=\") {\n\t\t\t\t\t\tcookiesSeparatorFound = true;\n\t\t\t\t\t\tpos = nextStart;\n\t\t\t\t\t\tcookiesStrings.push(cookiesString.substring(start, lastComma));\n\t\t\t\t\t\tstart = pos;\n\t\t\t\t\t} else pos = lastComma + 1;\n\t\t\t\t} else pos += 1;\n\t\t\t}\n\t\t\tif (!cookiesSeparatorFound || pos >= cookiesString.length) cookiesStrings.push(cookiesString.substring(start, cookiesString.length));\n\t\t}\n\t\treturn cookiesStrings;\n\t}\n\tparseSetCookie.parseSetCookie = parseSetCookie;\n\tparseSetCookie.parse = parseSetCookie;\n\tparseSetCookie.parseString = parseString;\n\tparseSetCookie.splitCookiesString = splitCookiesString;\n\t//#endregion\n\t//#region node_modules/.pnpm/headers-polyfill@5.0.1/node_modules/headers-polyfill/lib/index.mjs\n\tconst HEADERS_INVALID_CHARACTERS = /[^a-z0-9\\-#$%&'*+.^_`|~]/i;\n\tfunction normalizeHeaderName(name) {\n\t\tif (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === \"\") throw new TypeError(\"Invalid character in header field name\");\n\t\treturn name.trim().toLowerCase();\n\t}\n\tconst charCodesToRemove = [\n\t\tString.fromCharCode(10),\n\t\tString.fromCharCode(13),\n\t\tString.fromCharCode(9),\n\t\tString.fromCharCode(32)\n\t];\n\tconst HEADER_VALUE_REMOVE_REGEXP = new RegExp(`(^[${charCodesToRemove.join(\"\")}]|$[${charCodesToRemove.join(\"\")}])`, \"g\");\n\t/**\n\t* Normalize the given header value.\n\t* @see https://fetch.spec.whatwg.org/#concept-header-value-normalize\n\t*/\n\tfunction normalizeHeaderValue(value) {\n\t\treturn value.replace(HEADER_VALUE_REMOVE_REGEXP, \"\");\n\t}\n\t/**\n\t* Validate the given header name.\n\t* @see https://fetch.spec.whatwg.org/#header-name\n\t*/\n\tfunction isValidHeaderName(value) {\n\t\tif (typeof value !== \"string\") return false;\n\t\tif (value.length === 0) return false;\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst character = value.charCodeAt(i);\n\t\t\tif (character > 127 || !isToken(character)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tfunction isToken(value) {\n\t\treturn ![\n\t\t\t127,\n\t\t\t32,\n\t\t\t\"(\",\n\t\t\t\")\",\n\t\t\t\"<\",\n\t\t\t\">\",\n\t\t\t\"@\",\n\t\t\t\",\",\n\t\t\t\";\",\n\t\t\t\":\",\n\t\t\t\"\\\\\",\n\t\t\t\"\\\"\",\n\t\t\t\"/\",\n\t\t\t\"[\",\n\t\t\t\"]\",\n\t\t\t\"?\",\n\t\t\t\"=\",\n\t\t\t\"{\",\n\t\t\t\"}\"\n\t\t].includes(value);\n\t}\n\t/**\n\t* Validate the given header value.\n\t* @see https://fetch.spec.whatwg.org/#header-value\n\t*/\n\tfunction isValidHeaderValue(value) {\n\t\tif (typeof value !== \"string\") return false;\n\t\tif (value.trim() !== value) return false;\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst character = value.charCodeAt(i);\n\t\t\tif (character === 0 || character === 10 || character === 13) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tlet _Symbol$toStringTag;\n\tconst NORMALIZED_HEADERS = Symbol(\"normalizedHeaders\");\n\tconst RAW_HEADER_NAMES = Symbol(\"rawHeaderNames\");\n\tconst HEADER_VALUE_DELIMITER = \", \";\n\tvar Headers = class Headers {\n\t\tconstructor(init) {\n\t\t\tthis[NORMALIZED_HEADERS] = {};\n\t\t\tthis[RAW_HEADER_NAMES] = /* @__PURE__ */ new Map();\n\t\t\tthis[_Symbol$toStringTag] = \"Headers\";\n\t\t\t/**\n\t\t\t* @note Cannot necessarily check if the `init` is an instance of the\n\t\t\t* `Headers` because that class may not be defined in Node or jsdom.\n\t\t\t*/\n\t\t\tif ([\"Headers\", \"HeadersPolyfill\"].includes(init?.constructor?.name) || init instanceof Headers || typeof globalThis.Headers !== \"undefined\" && init instanceof globalThis.Headers) init.forEach((value, name) => {\n\t\t\t\tthis.append(name, value);\n\t\t\t}, this);\n\t\t\telse if (Array.isArray(init)) init.forEach(([name, value]) => {\n\t\t\t\tthis.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value);\n\t\t\t});\n\t\t\telse if (init) Object.getOwnPropertyNames(init).forEach((name) => {\n\t\t\t\tconst value = init[name];\n\t\t\t\tthis.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value);\n\t\t\t});\n\t\t}\n\t\t[(_Symbol$toStringTag = Symbol.toStringTag, Symbol.iterator)]() {\n\t\t\treturn this.entries();\n\t\t}\n\t\t*keys() {\n\t\t\tfor (const [name] of this.entries()) yield name;\n\t\t}\n\t\t*values() {\n\t\t\tfor (const [, value] of this.entries()) yield value;\n\t\t}\n\t\t*entries() {\n\t\t\tlet sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) => a.localeCompare(b));\n\t\t\tfor (const name of sortedKeys) if (name === \"set-cookie\") for (const value of this.getSetCookie()) yield [name, value];\n\t\t\telse yield [name, this.get(name)];\n\t\t}\n\t\t/**\n\t\t* Returns a boolean stating whether a `Headers` object contains a certain header.\n\t\t*/\n\t\thas(name) {\n\t\t\tif (!isValidHeaderName(name)) throw new TypeError(`Invalid header name \"${name}\"`);\n\t\t\treturn this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name));\n\t\t}\n\t\t/**\n\t\t* Returns a `ByteString` sequence of all the values of a header with a given name.\n\t\t*/\n\t\tget(name) {\n\t\t\tif (!isValidHeaderName(name)) throw TypeError(`Invalid header name \"${name}\"`);\n\t\t\treturn this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null;\n\t\t}\n\t\t/**\n\t\t* Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.\n\t\t*/\n\t\tset(name, value) {\n\t\t\tif (!isValidHeaderName(name) || !isValidHeaderValue(value)) return;\n\t\t\tconst normalizedName = normalizeHeaderName(name);\n\t\t\tconst normalizedValue = normalizeHeaderValue(value);\n\t\t\tthis[NORMALIZED_HEADERS][normalizedName] = normalizeHeaderValue(normalizedValue);\n\t\t\tthis[RAW_HEADER_NAMES].set(normalizedName, name);\n\t\t}\n\t\t/**\n\t\t* Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.\n\t\t*/\n\t\tappend(name, value) {\n\t\t\tif (!isValidHeaderName(name) || !isValidHeaderValue(value)) return;\n\t\t\tconst normalizedName = normalizeHeaderName(name);\n\t\t\tconst normalizedValue = normalizeHeaderValue(value);\n\t\t\tlet resolvedValue = this.has(normalizedName) ? `${this.get(normalizedName)}, ${normalizedValue}` : normalizedValue;\n\t\t\tthis.set(name, resolvedValue);\n\t\t}\n\t\t/**\n\t\t* Deletes a header from the `Headers` object.\n\t\t*/\n\t\tdelete(name) {\n\t\t\tif (!isValidHeaderName(name)) return;\n\t\t\tif (!this.has(name)) return;\n\t\t\tconst normalizedName = normalizeHeaderName(name);\n\t\t\tdelete this[NORMALIZED_HEADERS][normalizedName];\n\t\t\tthis[RAW_HEADER_NAMES].delete(normalizedName);\n\t\t}\n\t\t/**\n\t\t* Traverses the `Headers` object,\n\t\t* calling the given callback for each header.\n\t\t*/\n\t\tforEach(callback, thisArg) {\n\t\t\tfor (const [name, value] of this.entries()) callback.call(thisArg, value, name, this);\n\t\t}\n\t\t/**\n\t\t* Returns an array containing the values\n\t\t* of all Set-Cookie headers associated\n\t\t* with a response\n\t\t*/\n\t\tgetSetCookie() {\n\t\t\tconst setCookieHeader = this.get(\"set-cookie\");\n\t\t\tif (setCookieHeader === null) return [];\n\t\t\tif (setCookieHeader === \"\") return [\"\"];\n\t\t\treturn splitCookiesString(setCookieHeader);\n\t\t}\n\t};\n\t//#endregion\n\t//#region packages/core/src/code-mode/platform-entry.ts\n\tconst platformBridgeGlobalThis = globalThis;\n\tconst capletsPlatformHost = {\n\t\trandomUUID: platformBridgeGlobalThis.__caplets_platform_random_uuid,\n\t\trandomValues: platformBridgeGlobalThis.__caplets_platform_random_values,\n\t\tsleep: platformBridgeGlobalThis.__caplets_platform_sleep,\n\t\tclearTimer: platformBridgeGlobalThis.__caplets_platform_clear_timer\n\t};\n\tdelete platformBridgeGlobalThis.__caplets_platform_random_uuid;\n\tdelete platformBridgeGlobalThis.__caplets_platform_random_values;\n\tdelete platformBridgeGlobalThis.__caplets_platform_sleep;\n\tdelete platformBridgeGlobalThis.__caplets_platform_clear_timer;\n\tconst DISABLED_FETCH_MESSAGE = \"Direct fetch is not available in Code Mode; use a Caplet instead.\";\n\tconst BASE64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\tconst base64Lookup = new Map(BASE64_ALPHABET.split(\"\").map((char, index) => [char, index]));\n\tfunction utf8Encode(input) {\n\t\tconst encoded = encodeURIComponent(input);\n\t\tconst bytes = [];\n\t\tfor (let index = 0; index < encoded.length; index += 1) {\n\t\t\tif (encoded[index] === \"%\") {\n\t\t\t\tbytes.push(Number.parseInt(encoded.slice(index + 1, index + 3), 16));\n\t\t\t\tindex += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbytes.push(encoded.charCodeAt(index));\n\t\t}\n\t\treturn Uint8Array.from(bytes);\n\t}\n\tfunction utf8Decode(input) {\n\t\tlet output = \"\";\n\t\tfor (let index = 0; index < input.length; index += 1) {\n\t\t\tconst first = input[index] ?? 0;\n\t\t\tif (first < 128) {\n\t\t\t\toutput += String.fromCharCode(first);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (first >= 194 && first <= 223) {\n\t\t\t\tconst second = input[index + 1];\n\t\t\t\tif (isUtf8Continuation(second)) {\n\t\t\t\t\toutput += String.fromCodePoint((first & 31) << 6 | second & 63);\n\t\t\t\t\tindex += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\toutput += \"\uFFFD\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (first >= 224 && first <= 239) {\n\t\t\t\tconst second = input[index + 1];\n\t\t\t\tconst third = input[index + 2];\n\t\t\t\tif (isValidUtf8SecondForThreeByte(first, second) && isUtf8Continuation(third)) {\n\t\t\t\t\toutput += String.fromCodePoint((first & 15) << 12 | (second & 63) << 6 | third & 63);\n\t\t\t\t\tindex += 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\toutput += \"\uFFFD\";\n\t\t\t\tif (isValidUtf8SecondForThreeByte(first, second)) index += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (first >= 240 && first <= 244) {\n\t\t\t\tconst second = input[index + 1];\n\t\t\t\tconst third = input[index + 2];\n\t\t\t\tconst fourth = input[index + 3];\n\t\t\t\tif (isValidUtf8SecondForFourByte(first, second) && isUtf8Continuation(third) && isUtf8Continuation(fourth)) {\n\t\t\t\t\toutput += String.fromCodePoint((first & 7) << 18 | (second & 63) << 12 | (third & 63) << 6 | fourth & 63);\n\t\t\t\t\tindex += 3;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\toutput += \"\uFFFD\";\n\t\t\t\tif (isValidUtf8SecondForFourByte(first, second)) index += isUtf8Continuation(third) ? 2 : 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toutput += \"\uFFFD\";\n\t\t}\n\t\treturn output;\n\t}\n\tfunction isUtf8Continuation(value) {\n\t\treturn value !== void 0 && value >= 128 && value <= 191;\n\t}\n\tfunction isValidUtf8SecondForThreeByte(first, second) {\n\t\tif (second === void 0) return false;\n\t\tif (first === 224) return second >= 160 && second <= 191;\n\t\tif (first === 237) return second >= 128 && second <= 159;\n\t\treturn second >= 128 && second <= 191;\n\t}\n\tfunction isValidUtf8SecondForFourByte(first, second) {\n\t\tif (second === void 0) return false;\n\t\tif (first === 240) return second >= 144 && second <= 191;\n\t\tif (first === 244) return second >= 128 && second <= 143;\n\t\treturn second >= 128 && second <= 191;\n\t}\n\tvar TextEncoderShim = class {\n\t\tencoding = \"utf-8\";\n\t\tencode(input = \"\") {\n\t\t\treturn utf8Encode(String(input));\n\t\t}\n\t};\n\tvar TextDecoderShim = class {\n\t\tencoding;\n\t\tconstructor(label = \"utf-8\") {\n\t\t\tconst normalized = label.toLowerCase();\n\t\t\tif (![\n\t\t\t\t\"utf-8\",\n\t\t\t\t\"utf8\",\n\t\t\t\t\"unicode-1-1-utf-8\"\n\t\t\t].includes(normalized)) throw new TypeError(`Unsupported encoding: ${label}`);\n\t\t\tthis.encoding = \"utf-8\";\n\t\t}\n\t\tdecode(input) {\n\t\t\tif (input === void 0) return \"\";\n\t\t\treturn utf8Decode(copyBytes(input));\n\t\t}\n\t};\n\tconst textEncoder = new TextEncoderShim();\n\tconst textDecoder = new TextDecoderShim();\n\tvar URLSearchParamsShim = class URLSearchParamsShim {\n\t\t#entries = [];\n\t\t#onChange;\n\t\tconstructor(init = \"\", onChange) {\n\t\t\tthis.#onChange = onChange;\n\t\t\tif (typeof init === \"string\") {\n\t\t\t\tconst source = init.startsWith(\"?\") ? init.slice(1) : init;\n\t\t\t\tif (!source) return;\n\t\t\t\tfor (const pair of source.split(\"&\")) {\n\t\t\t\t\tif (!pair) continue;\n\t\t\t\t\tconst separatorIndex = pair.indexOf(\"=\");\n\t\t\t\t\tconst key = separatorIndex >= 0 ? pair.slice(0, separatorIndex) : pair;\n\t\t\t\t\tconst value = separatorIndex >= 0 ? pair.slice(separatorIndex + 1) : \"\";\n\t\t\t\t\tthis.#entries.push([decodeUrlParam(key), decodeUrlParam(value)]);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (init instanceof URLSearchParamsShim) {\n\t\t\t\tthis.#entries = [...init.#entries];\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (Array.isArray(init)) {\n\t\t\t\tthis.#entries = init.map(([key, value]) => [String(key), String(value)]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#entries = Object.entries(init).map(([key, value]) => [key, String(value)]);\n\t\t}\n\t\tappend(name, value) {\n\t\t\tthis.#entries.push([String(name), String(value)]);\n\t\t\tthis.#onChange?.();\n\t\t}\n\t\tdelete(name) {\n\t\t\tconst normalized = String(name);\n\t\t\tthis.#entries = this.#entries.filter(([key]) => key !== normalized);\n\t\t\tthis.#onChange?.();\n\t\t}\n\t\tentries() {\n\t\t\treturn this.#entries[Symbol.iterator]();\n\t\t}\n\t\tforEach(callback) {\n\t\t\tfor (const [key, value] of this.#entries) callback(value, key, this);\n\t\t}\n\t\tget(name) {\n\t\t\treturn this.#entries.find(([key]) => key === String(name))?.[1] ?? null;\n\t\t}\n\t\tgetAll(name) {\n\t\t\treturn this.#entries.filter(([key]) => key === String(name)).map(([, value]) => value);\n\t\t}\n\t\thas(name) {\n\t\t\treturn this.#entries.some(([key]) => key === String(name));\n\t\t}\n\t\tkeys() {\n\t\t\treturn this.#entries.map(([key]) => key)[Symbol.iterator]();\n\t\t}\n\t\tset(name, value) {\n\t\t\tconst normalizedName = String(name);\n\t\t\tconst normalizedValue = String(value);\n\t\t\tconst next = [];\n\t\t\tlet replaced = false;\n\t\t\tfor (const entry of this.#entries) {\n\t\t\t\tif (entry[0] !== normalizedName) {\n\t\t\t\t\tnext.push(entry);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!replaced) {\n\t\t\t\t\tnext.push([normalizedName, normalizedValue]);\n\t\t\t\t\treplaced = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!replaced) next.push([normalizedName, normalizedValue]);\n\t\t\tthis.#entries = next;\n\t\t\tthis.#onChange?.();\n\t\t}\n\t\ttoString() {\n\t\t\treturn this.#entries.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join(\"&\");\n\t\t}\n\t\tvalues() {\n\t\t\treturn this.#entries.map(([, value]) => value)[Symbol.iterator]();\n\t\t}\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries();\n\t\t}\n\t};\n\tfunction decodeUrlParam(value) {\n\t\treturn decodeURIComponent(value.replace(/\\+/gu, \" \"));\n\t}\n\tfunction parseAbsoluteUrl(input) {\n\t\tconst match = /^(?<protocol>[a-zA-Z][a-zA-Z\\d+.-]*:)\\/\\/(?<host>[^/?#]*)(?<pathname>[^?#]*)?(?<search>\\?[^#]*)?(?<hash>#.*)?$/u.exec(input);\n\t\tif (!match?.groups?.protocol || !match.groups.host) return;\n\t\treturn {\n\t\t\tprotocol: match.groups.protocol,\n\t\t\thost: match.groups.host,\n\t\t\tpathname: match.groups.pathname || \"/\",\n\t\t\tsearch: match.groups.search || \"\",\n\t\t\thash: match.groups.hash || \"\"\n\t\t};\n\t}\n\tfunction normalizePathname(pathname) {\n\t\tconst segments = [];\n\t\tfor (const part of pathname.split(\"/\")) {\n\t\t\tif (!part || part === \".\") continue;\n\t\t\tif (part === \"..\") {\n\t\t\t\tsegments.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsegments.push(part);\n\t\t}\n\t\treturn `/${segments.join(\"/\")}`;\n\t}\n\tfunction resolveUrl(input, base) {\n\t\tconst absolute = parseAbsoluteUrl(input);\n\t\tif (absolute) return absolute;\n\t\tif (base === void 0) throw new TypeError(`Invalid URL: ${input}`);\n\t\tconst baseUrl = base instanceof URLShim ? base : new URLShim(String(base));\n\t\tconst basePath = baseUrl.pathname.endsWith(\"/\") ? baseUrl.pathname : baseUrl.pathname.slice(0, baseUrl.pathname.lastIndexOf(\"/\") + 1);\n\t\tconst [beforeHash, rawHash = \"\"] = input.split(\"#\");\n\t\tconst hasExplicitSearch = beforeHash?.includes(\"?\") ?? false;\n\t\tconst [rawPath, rawSearch = \"\"] = (beforeHash ?? \"\").split(\"?\");\n\t\tconst pathname = rawPath === \"\" && (input === \"\" || input.startsWith(\"?\") || input.startsWith(\"#\")) ? baseUrl.pathname : rawPath?.startsWith(\"/\") ? rawPath : `${basePath}${rawPath || \"\"}`;\n\t\treturn {\n\t\t\tprotocol: baseUrl.protocol,\n\t\t\thost: baseUrl.host,\n\t\t\tpathname: normalizePathname(pathname),\n\t\t\tsearch: hasExplicitSearch ? `?${rawSearch}` : rawPath === \"\" && (input === \"\" || input.startsWith(\"#\")) ? baseUrl.search : \"\",\n\t\t\thash: rawHash ? `#${rawHash}` : \"\"\n\t\t};\n\t}\n\tvar URLShim = class {\n\t\thost;\n\t\thostname;\n\t\torigin;\n\t\tpassword = \"\";\n\t\tport;\n\t\tprotocol;\n\t\tsearchParams;\n\t\tusername = \"\";\n\t\thash;\n\t\tpathname;\n\t\t#search;\n\t\tconstructor(input, base) {\n\t\t\tconst parsed = resolveUrl(String(input), base);\n\t\t\tthis.protocol = parsed.protocol;\n\t\t\tthis.host = parsed.host;\n\t\t\tconst portIndex = this.host.lastIndexOf(\":\");\n\t\t\tthis.hostname = portIndex >= 0 ? this.host.slice(0, portIndex) : this.host;\n\t\t\tthis.port = portIndex >= 0 ? this.host.slice(portIndex + 1) : \"\";\n\t\t\tthis.pathname = parsed.pathname;\n\t\t\tthis.#search = parsed.search;\n\t\t\tthis.hash = parsed.hash;\n\t\t\tthis.origin = `${this.protocol}//${this.host}`;\n\t\t\tthis.searchParams = new URLSearchParamsShim(this.#search, () => {\n\t\t\t\tconst next = this.searchParams.toString();\n\t\t\t\tthis.#search = next ? `?${next}` : \"\";\n\t\t\t});\n\t\t}\n\t\tget href() {\n\t\t\treturn `${this.origin}${this.pathname}${this.#search}${this.hash}`;\n\t\t}\n\t\tget search() {\n\t\t\treturn this.#search;\n\t\t}\n\t\ttoString() {\n\t\t\treturn this.href;\n\t\t}\n\t\ttoJSON() {\n\t\t\treturn this.href;\n\t\t}\n\t};\n\tvar ReadableStreamShim = class {\n\t\t#queue = [];\n\t\t#closed = false;\n\t\t#pulling = false;\n\t\t#source;\n\t\t#controller;\n\t\t#pending;\n\t\tconstructor(source = {}) {\n\t\t\tthis.#source = source;\n\t\t\tthis.#controller = {\n\t\t\t\tenqueue: (value) => {\n\t\t\t\t\tif (this.#pending) {\n\t\t\t\t\t\tthis.#pending.resolve({\n\t\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.#pending = void 0;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.#queue.push(value);\n\t\t\t\t},\n\t\t\t\tclose: () => {\n\t\t\t\t\tthis.#closed = true;\n\t\t\t\t\tif (this.#pending) {\n\t\t\t\t\t\tthis.#pending.resolve({ done: true });\n\t\t\t\t\t\tthis.#pending = void 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tsource.start?.(this.#controller);\n\t\t}\n\t\tasync #pull() {\n\t\t\tif (this.#pulling || this.#closed || !this.#source.pull) return;\n\t\t\tthis.#pulling = true;\n\t\t\ttry {\n\t\t\t\tawait this.#source.pull(this.#controller);\n\t\t\t} finally {\n\t\t\t\tthis.#pulling = false;\n\t\t\t}\n\t\t}\n\t\tgetReader() {\n\t\t\treturn { read: async () => {\n\t\t\t\tif (this.#queue.length > 0) return {\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue: this.#queue.shift()\n\t\t\t\t};\n\t\t\t\tawait this.#pull();\n\t\t\t\tif (this.#queue.length > 0) return {\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue: this.#queue.shift()\n\t\t\t\t};\n\t\t\t\tif (this.#closed) return {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t\treturn await new Promise((resolve) => {\n\t\t\t\t\tthis.#pending = { resolve };\n\t\t\t\t\tthis.#pull();\n\t\t\t\t});\n\t\t\t} };\n\t\t}\n\t};\n\tvar WritableStreamShim = class {\n\t\t#sink;\n\t\tconstructor(sink = {}) {\n\t\t\tthis.#sink = sink;\n\t\t}\n\t\tgetWriter() {\n\t\t\treturn {\n\t\t\t\twrite: async (chunk) => {\n\t\t\t\t\tawait this.#sink.write?.(chunk);\n\t\t\t\t},\n\t\t\t\tclose: async () => {\n\t\t\t\t\tawait this.#sink.close?.();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t};\n\tvar TransformStreamShim = class {\n\t\treadable;\n\t\twritable;\n\t\tconstructor(transformer = {}) {\n\t\t\tconst queue = [];\n\t\t\tlet closed = false;\n\t\t\tlet pending;\n\t\t\tconst controller = {\n\t\t\t\tenqueue: (value) => {\n\t\t\t\t\tif (pending) {\n\t\t\t\t\t\tpending.resolve({\n\t\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t});\n\t\t\t\t\t\tpending = void 0;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tqueue.push(value);\n\t\t\t\t},\n\t\t\t\tclose: () => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tif (pending) {\n\t\t\t\t\t\tpending.resolve({ done: true });\n\t\t\t\t\t\tpending = void 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.readable = { getReader() {\n\t\t\t\treturn { read: async () => {\n\t\t\t\t\tif (queue.length > 0) return {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: queue.shift()\n\t\t\t\t\t};\n\t\t\t\t\tif (closed) return {\n\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\tvalue: void 0\n\t\t\t\t\t};\n\t\t\t\t\treturn await new Promise((resolve) => {\n\t\t\t\t\t\tpending = { resolve };\n\t\t\t\t\t});\n\t\t\t\t} };\n\t\t\t} };\n\t\t\tthis.writable = new WritableStreamShim({\n\t\t\t\twrite: async (chunk) => {\n\t\t\t\t\ttransformer.transform?.(chunk, controller);\n\t\t\t\t},\n\t\t\t\tclose: async () => {\n\t\t\t\t\ttransformer.flush?.(controller);\n\t\t\t\t\tcontroller.close();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\tfunction definePlatformGlobal(name, value, options = {}) {\n\t\tif (!options.overwrite && name in globalThis) return;\n\t\tObject.defineProperty(globalThis, name, {\n\t\t\tvalue,\n\t\t\twritable: true,\n\t\t\tconfigurable: true\n\t\t});\n\t}\n\tfunction formatLogArg(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\ttry {\n\t\t\treturn JSON.stringify(value);\n\t\t} catch {\n\t\t\treturn String(value);\n\t\t}\n\t}\n\tfunction formatLogLine(args) {\n\t\treturn args.map(formatLogArg).join(\" \");\n\t}\n\tconst platformConsole = {\n\t\tlog: (...args) => __caplets_log(\"log\", formatLogLine(args)),\n\t\tinfo: (...args) => __caplets_log(\"info\", formatLogLine(args)),\n\t\twarn: (...args) => __caplets_log(\"warn\", formatLogLine(args)),\n\t\terror: (...args) => __caplets_log(\"error\", formatLogLine(args)),\n\t\tdebug: (...args) => __caplets_log(\"debug\", formatLogLine(args))\n\t};\n\tfunction normalizeEncoding(encoding) {\n\t\tconst normalized = (encoding ?? \"utf8\").toLowerCase();\n\t\tswitch (normalized) {\n\t\t\tcase \"utf8\":\n\t\t\tcase \"utf-8\":\n\t\t\tcase \"base64\":\n\t\t\tcase \"base64url\":\n\t\t\tcase \"hex\": return normalized;\n\t\t\tdefault: throw new TypeError(`Unsupported Buffer encoding: ${encoding}`);\n\t\t}\n\t}\n\tfunction hexToBytes(value) {\n\t\tif (value.length % 2 !== 0) throw new TypeError(\"Invalid hex string length\");\n\t\tconst bytes = new Uint8Array(value.length / 2);\n\t\tfor (let index = 0; index < value.length; index += 2) {\n\t\t\tconst parsed = Number.parseInt(value.slice(index, index + 2), 16);\n\t\t\tif (Number.isNaN(parsed)) throw new TypeError(\"Invalid hex string\");\n\t\t\tbytes[index / 2] = parsed;\n\t\t}\n\t\treturn bytes;\n\t}\n\tfunction bytesToHex(bytes) {\n\t\treturn Array.from(bytes, (value) => value.toString(16).padStart(2, \"0\")).join(\"\");\n\t}\n\tfunction base64ToBytes(value, encoding) {\n\t\tlet normalized = value.replace(/\\s+/gu, \"\");\n\t\tif (encoding === \"base64url\") normalized = normalized.replace(/-/gu, \"+\").replace(/_/gu, \"/\");\n\t\tconst padding = normalized.length % 4;\n\t\tif (padding === 1) throw new TypeError(\"Invalid base64 string\");\n\t\tif (padding > 0) normalized = normalized.padEnd(normalized.length + (4 - padding), \"=\");\n\t\tconst output = [];\n\t\tfor (let index = 0; index < normalized.length; index += 4) {\n\t\t\tconst values = normalized.slice(index, index + 4).split(\"\").map((char) => char === \"=\" ? 64 : base64Lookup.get(char) ?? NaN);\n\t\t\tif (values.some((entry) => Number.isNaN(entry))) throw new TypeError(\"Invalid base64 string\");\n\t\t\tconst [a = 0, b = 0, c = 64, d = 64] = values;\n\t\t\tconst triple = a << 18 | b << 12 | (c & 63) << 6 | d & 63;\n\t\t\toutput.push(triple >> 16 & 255);\n\t\t\tif (c !== 64) output.push(triple >> 8 & 255);\n\t\t\tif (d !== 64) output.push(triple & 255);\n\t\t}\n\t\treturn Uint8Array.from(output);\n\t}\n\tfunction bytesToBase64(bytes, encoding) {\n\t\tlet output = \"\";\n\t\tfor (let index = 0; index < bytes.length; index += 3) {\n\t\t\tconst a = bytes[index] ?? 0;\n\t\t\tconst b = bytes[index + 1] ?? 0;\n\t\t\tconst c = bytes[index + 2] ?? 0;\n\t\t\tconst triple = a << 16 | b << 8 | c;\n\t\t\toutput += BASE64_ALPHABET[triple >> 18 & 63];\n\t\t\toutput += BASE64_ALPHABET[triple >> 12 & 63];\n\t\t\toutput += index + 1 < bytes.length ? BASE64_ALPHABET[triple >> 6 & 63] : \"=\";\n\t\t\toutput += index + 2 < bytes.length ? BASE64_ALPHABET[triple & 63] : \"=\";\n\t\t}\n\t\tif (encoding === \"base64url\") return output.replace(/\\+/gu, \"-\").replace(/\\//gu, \"_\").replace(/=+$/gu, \"\");\n\t\treturn output;\n\t}\n\tfunction copyBytes(input) {\n\t\tif (input instanceof ArrayBuffer) return new Uint8Array(input.slice(0));\n\t\treturn new Uint8Array(input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength));\n\t}\n\tfunction toBytes(input, encoding) {\n\t\tif (input instanceof BufferShim) return input.toUint8Array();\n\t\tif (typeof input === \"string\") switch (normalizeEncoding(encoding)) {\n\t\t\tcase \"utf8\":\n\t\t\tcase \"utf-8\": return textEncoder.encode(input);\n\t\t\tcase \"base64\":\n\t\t\tcase \"base64url\": return base64ToBytes(input, normalizeEncoding(encoding));\n\t\t\tcase \"hex\": return hexToBytes(input);\n\t\t}\n\t\tif (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) return copyBytes(input);\n\t\tif (Array.isArray(input)) return Uint8Array.from(input);\n\t\tthrow new TypeError(\"Buffer.from only supports strings, arrays, ArrayBuffers, and typed arrays\");\n\t}\n\tvar BufferShim = class BufferShim {\n\t\t#bytes;\n\t\tbyteLength;\n\t\tlength;\n\t\tconstructor(bytes) {\n\t\t\tthis.#bytes = bytes;\n\t\t\tthis.byteLength = bytes.byteLength;\n\t\t\tthis.length = bytes.length;\n\t\t}\n\t\tstatic from(input, encoding) {\n\t\t\treturn new BufferShim(toBytes(input, encoding));\n\t\t}\n\t\tstatic isBuffer(value) {\n\t\t\treturn value instanceof BufferShim;\n\t\t}\n\t\tstatic byteLength(input, encoding) {\n\t\t\treturn toBytes(input, encoding).byteLength;\n\t\t}\n\t\ttoUint8Array() {\n\t\t\treturn new Uint8Array(this.#bytes);\n\t\t}\n\t\ttoString(encoding) {\n\t\t\tswitch (normalizeEncoding(encoding)) {\n\t\t\t\tcase \"utf8\":\n\t\t\t\tcase \"utf-8\": return textDecoder.decode(this.#bytes);\n\t\t\t\tcase \"base64\":\n\t\t\t\tcase \"base64url\": return bytesToBase64(this.#bytes, normalizeEncoding(encoding));\n\t\t\t\tcase \"hex\": return bytesToHex(this.#bytes);\n\t\t\t}\n\t\t}\n\t};\n\tfunction atobShim(input) {\n\t\treturn Array.from(base64ToBytes(String(input), \"base64\"), (value) => String.fromCharCode(value)).join(\"\");\n\t}\n\tfunction btoaShim(input) {\n\t\tconst bytes = new Uint8Array(input.length);\n\t\tfor (let index = 0; index < input.length; index += 1) {\n\t\t\tconst codePoint = input.charCodeAt(index);\n\t\t\tif (codePoint > 255) throw new TypeError(\"The string to be encoded contains characters outside of Latin1\");\n\t\t\tbytes[index] = codePoint;\n\t\t}\n\t\treturn bytesToBase64(bytes, \"base64\");\n\t}\n\tfunction queueMicrotaskShim(callback) {\n\t\tPromise.resolve().then(callback);\n\t}\n\tvar AbortSignalShim = class AbortSignalShim {\n\t\taborted = false;\n\t\treason;\n\t\tonabort = null;\n\t\t#listeners = /* @__PURE__ */ new Set();\n\t\taddEventListener(type, listener) {\n\t\t\tif (type === \"abort\" && listener) this.#listeners.add(listener);\n\t\t}\n\t\tremoveEventListener(type, listener) {\n\t\t\tif (type === \"abort\" && listener) this.#listeners.delete(listener);\n\t\t}\n\t\tdispatchEvent(event) {\n\t\t\tif (event.type !== \"abort\") return true;\n\t\t\tthis.onabort?.(event);\n\t\t\tfor (const listener of this.#listeners) listener(event);\n\t\t\treturn true;\n\t\t}\n\t\tthrowIfAborted() {\n\t\t\tif (this.aborted) throw this.reason ?? /* @__PURE__ */ new Error(\"Operation was aborted\");\n\t\t}\n\t\tstatic abort(reason) {\n\t\t\tconst signal = new AbortSignalShim();\n\t\t\tsignal.abort(reason);\n\t\t\treturn signal;\n\t\t}\n\t\tabort(reason) {\n\t\t\tif (this.aborted) return;\n\t\t\tthis.aborted = true;\n\t\t\tthis.reason = reason;\n\t\t\tthis.dispatchEvent({\n\t\t\t\ttype: \"abort\",\n\t\t\t\ttarget: this\n\t\t\t});\n\t\t}\n\t};\n\tvar AbortControllerShim = class {\n\t\tsignal = new AbortSignalShim();\n\t\tabort(reason) {\n\t\t\tthis.signal.abort(reason);\n\t\t}\n\t};\n\tfunction cloneFormData(input) {\n\t\tconst clone = new FormData();\n\t\tfor (const [name, value] of input.entries()) {\n\t\t\tif (value instanceof File) {\n\t\t\t\tclone.append(name, new File([value], value.name, { type: value.type }), value.name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tclone.append(name, value);\n\t\t}\n\t\treturn clone;\n\t}\n\tfunction cloneBodyValue(input) {\n\t\tif (input === null || input === void 0 || typeof input === \"string\") return input;\n\t\tif (input instanceof FormData) return cloneFormData(input);\n\t\tif (input instanceof Blob) return input.slice(0, input.size, input.type);\n\t\tif (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) return copyBytes(input);\n\t\treturn input;\n\t}\n\tfunction blobFromBody(input) {\n\t\tif (input instanceof Blob) return input;\n\t\tif (typeof input === \"string\") return new Blob([input], { type: \"text/plain;charset=utf-8\" });\n\t\tif (input instanceof FormData) throw new TypeError(\"FormData body reading is not supported in Code Mode\");\n\t\tif (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) return new Blob([copyBytes(input)]);\n\t\treturn new Blob([]);\n\t}\n\tvar BodyMixin = class {\n\t\t_bodyInit;\n\t\tbodyUsed = false;\n\t\tbody = null;\n\t\tconstructor(body) {\n\t\t\tthis._bodyInit = cloneBodyValue(body);\n\t\t}\n\t\tasync arrayBuffer() {\n\t\t\tthis.bodyUsed = true;\n\t\t\treturn await blobFromBody(this._bodyInit).arrayBuffer();\n\t\t}\n\t\tasync blob() {\n\t\t\tthis.bodyUsed = true;\n\t\t\treturn blobFromBody(this._bodyInit);\n\t\t}\n\t\tasync formData() {\n\t\t\tthis.bodyUsed = true;\n\t\t\tif (this._bodyInit instanceof FormData) return cloneFormData(this._bodyInit);\n\t\t\tthrow new TypeError(\"Body does not contain FormData\");\n\t\t}\n\t\tasync json() {\n\t\t\treturn JSON.parse(await this.text());\n\t\t}\n\t\tasync text() {\n\t\t\tthis.bodyUsed = true;\n\t\t\treturn await blobFromBody(this._bodyInit).text();\n\t\t}\n\t};\n\tfunction toHeaders(init) {\n\t\treturn init instanceof Headers ? new Headers(init) : new Headers(init ?? {});\n\t}\n\tfunction normalizeMethod(method) {\n\t\treturn String(method ?? \"GET\").toUpperCase();\n\t}\n\tvar RequestShim = class RequestShim extends BodyMixin {\n\t\theaders;\n\t\tmethod;\n\t\tsignal;\n\t\turl;\n\t\tconstructor(input, init = {}) {\n\t\t\tconst sourceBody = input instanceof RequestShim ? input._bodyInit : void 0;\n\t\t\tsuper(init.body ?? sourceBody);\n\t\t\tif (input instanceof RequestShim) this.url = input.url;\n\t\t\telse this.url = input instanceof URLShim ? input.href : new URLShim(String(input)).href;\n\t\t\tthis.method = normalizeMethod(init.method ?? (input instanceof RequestShim ? input.method : \"GET\"));\n\t\t\tthis.headers = toHeaders(init.headers ?? (input instanceof RequestShim ? input.headers : void 0));\n\t\t\tthis.signal = init.signal ?? (input instanceof RequestShim ? input.signal : new AbortControllerShim().signal);\n\t\t}\n\t\tclone() {\n\t\t\treturn new RequestShim(this, {\n\t\t\t\tmethod: this.method,\n\t\t\t\theaders: this.headers,\n\t\t\t\tbody: this._bodyInit,\n\t\t\t\tsignal: this.signal\n\t\t\t});\n\t\t}\n\t};\n\tvar ResponseShim = class ResponseShim extends BodyMixin {\n\t\theaders;\n\t\tok;\n\t\tredirected = false;\n\t\tstatus;\n\t\tstatusText;\n\t\ttype = \"default\";\n\t\turl = \"\";\n\t\tconstructor(body, init = {}) {\n\t\t\tsuper(body);\n\t\t\tthis.status = init.status ?? 200;\n\t\t\tthis.statusText = init.statusText ?? \"\";\n\t\t\tthis.headers = toHeaders(init.headers);\n\t\t\tthis.ok = this.status >= 200 && this.status <= 299;\n\t\t}\n\t\tclone() {\n\t\t\treturn new ResponseShim(this._bodyInit, {\n\t\t\t\theaders: this.headers,\n\t\t\t\tstatus: this.status,\n\t\t\t\tstatusText: this.statusText\n\t\t\t});\n\t\t}\n\t\tstatic json(data, init) {\n\t\t\tconst headers = toHeaders(init?.headers);\n\t\t\tif (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n\t\t\tconst responseInit = { headers };\n\t\t\tif (init?.status !== void 0) responseInit.status = init.status;\n\t\t\tif (init?.statusText !== void 0) responseInit.statusText = init.statusText;\n\t\t\treturn new ResponseShim(JSON.stringify(data), responseInit);\n\t\t}\n\t};\n\tfunction disabledFetch() {\n\t\tthrow new Error(DISABLED_FETCH_MESSAGE);\n\t}\n\tconst integerTypedArrayConstructors = new Set([\n\t\tInt8Array,\n\t\tUint8Array,\n\t\tUint8ClampedArray,\n\t\tInt16Array,\n\t\tUint16Array,\n\t\tInt32Array,\n\t\tUint32Array,\n\t\ttypeof BigInt64Array === \"undefined\" ? void 0 : BigInt64Array,\n\t\ttypeof BigUint64Array === \"undefined\" ? void 0 : BigUint64Array\n\t]);\n\tvar QuotaExceededErrorShim = class extends Error {\n\t\tconstructor(message) {\n\t\t\tsuper(message);\n\t\t\tthis.name = \"QuotaExceededError\";\n\t\t}\n\t};\n\tconst platformCrypto = {\n\t\trandomUUID() {\n\t\t\tconst randomUUID = capletsPlatformHost.randomUUID;\n\t\t\tif (!randomUUID) throw new Error(\"Code Mode platform random UUID bridge is not installed\");\n\t\t\treturn randomUUID();\n\t\t},\n\t\tgetRandomValues(typedArray) {\n\t\t\tif (!ArrayBuffer.isView(typedArray) || typedArray instanceof DataView) throw new TypeError(\"crypto.getRandomValues requires an integer typed array\");\n\t\t\tif (!integerTypedArrayConstructors.has(typedArray.constructor)) throw new TypeError(\"crypto.getRandomValues requires an integer typed array\");\n\t\t\tif (typedArray.byteLength > 65536) throw new QuotaExceededErrorShim(\"crypto.getRandomValues cannot generate more than 65,536 bytes\");\n\t\t\tconst randomValues = capletsPlatformHost.randomValues;\n\t\t\tif (!randomValues) throw new Error(\"Code Mode platform random values bridge is not installed\");\n\t\t\tconst bytes = randomValues(typedArray.byteLength);\n\t\t\tnew Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength).set(bytes);\n\t\t\treturn typedArray;\n\t\t}\n\t};\n\tlet nextTimerId = 1;\n\tconst activeTimers = /* @__PURE__ */ new Set();\n\tfunction normalizeTimerDelay(delay) {\n\t\tconst value = Number(delay ?? 0);\n\t\tif (!Number.isFinite(value) || value <= 0) return 0;\n\t\treturn Math.trunc(value);\n\t}\n\tfunction setTimeoutShim(callback, delay, ...args) {\n\t\tif (typeof callback !== \"function\") throw new TypeError(\"setTimeout callback must be a function\");\n\t\tconst timerId = nextTimerId++;\n\t\tactiveTimers.add(timerId);\n\t\tconst sleep = capletsPlatformHost.sleep;\n\t\tif (!sleep) throw new Error(\"Code Mode platform sleep bridge is not installed\");\n\t\tsleep(timerId, normalizeTimerDelay(delay)).then((fired) => {\n\t\t\tactiveTimers.delete(timerId);\n\t\t\tif (fired) callback(...args);\n\t\t});\n\t\treturn timerId;\n\t}\n\tfunction clearTimeoutShim(timerId) {\n\t\tconst id = Number(timerId);\n\t\tactiveTimers.delete(id);\n\t\tcapletsPlatformHost.clearTimer?.(id);\n\t}\n\tfunction setIntervalShim(callback, delay, ...args) {\n\t\tif (typeof callback !== \"function\") throw new TypeError(\"setInterval callback must be a function\");\n\t\tconst timerId = nextTimerId++;\n\t\tconst intervalDelay = normalizeTimerDelay(delay);\n\t\tactiveTimers.add(timerId);\n\t\tconst tick = () => {\n\t\t\tconst sleep = capletsPlatformHost.sleep;\n\t\t\tif (!sleep) throw new Error(\"Code Mode platform sleep bridge is not installed\");\n\t\t\tsleep(timerId, intervalDelay).then((fired) => {\n\t\t\t\tif (!fired || !activeTimers.has(timerId)) {\n\t\t\t\t\tactiveTimers.delete(timerId);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcallback(...args);\n\t\t\t\tif (activeTimers.has(timerId)) tick();\n\t\t\t});\n\t\t};\n\t\ttick();\n\t\treturn timerId;\n\t}\n\tfunction clearIntervalShim(timerId) {\n\t\tclearTimeoutShim(timerId);\n\t}\n\tdefinePlatformGlobal(\"atob\", atobShim);\n\tdefinePlatformGlobal(\"btoa\", btoaShim);\n\tdefinePlatformGlobal(\"Buffer\", BufferShim);\n\tdefinePlatformGlobal(\"TextEncoder\", TextEncoderShim);\n\tdefinePlatformGlobal(\"TextDecoder\", TextDecoderShim);\n\tdefinePlatformGlobal(\"URL\", URLShim);\n\tdefinePlatformGlobal(\"URLSearchParams\", URLSearchParamsShim);\n\tdefinePlatformGlobal(\"structuredClone\", esm_default);\n\tdefinePlatformGlobal(\"Headers\", Headers);\n\tdefinePlatformGlobal(\"Blob\", Blob);\n\tdefinePlatformGlobal(\"File\", File);\n\tdefinePlatformGlobal(\"FormData\", FormData);\n\tdefinePlatformGlobal(\"ReadableStream\", ReadableStreamShim);\n\tdefinePlatformGlobal(\"WritableStream\", WritableStreamShim);\n\tdefinePlatformGlobal(\"TransformStream\", TransformStreamShim);\n\tdefinePlatformGlobal(\"AbortController\", AbortControllerShim);\n\tdefinePlatformGlobal(\"AbortSignal\", AbortSignalShim);\n\tdefinePlatformGlobal(\"Request\", RequestShim);\n\tdefinePlatformGlobal(\"Response\", ResponseShim);\n\tdefinePlatformGlobal(\"crypto\", platformCrypto);\n\tdefinePlatformGlobal(\"setTimeout\", setTimeoutShim);\n\tdefinePlatformGlobal(\"clearTimeout\", clearTimeoutShim);\n\tdefinePlatformGlobal(\"setInterval\", setIntervalShim);\n\tdefinePlatformGlobal(\"clearInterval\", clearIntervalShim);\n\tdefinePlatformGlobal(\"queueMicrotask\", queueMicrotaskShim);\n\tdefinePlatformGlobal(\"console\", platformConsole);\n\tdefinePlatformGlobal(\"fetch\", disabledFetch, { overwrite: true });\n\t//#endregion\n})();";
@@ -1,6 +1,8 @@
1
1
  import type { NativeCapletsService } from "../native/service";
2
2
  import { CodeModeLogStore } from "./logs";
3
+ import { CodeModeJournalStore } from "./journal";
3
4
  import { type CodeModeSandbox } from "./sandbox";
5
+ import { type CodeModeSessionManager } from "./sessions";
4
6
  import type { CodeModeRunEnvelope } from "./types";
5
7
  export type RunCodeModeInput = {
6
8
  code: string;
@@ -8,8 +10,11 @@ export type RunCodeModeInput = {
8
10
  timeoutMs?: number;
9
11
  maxTimeoutMs?: number;
10
12
  runtimeScope?: string;
13
+ sessionId?: string;
11
14
  logStore?: CodeModeLogStore;
15
+ journalStore?: CodeModeJournalStore;
12
16
  sandbox?: CodeModeSandbox;
17
+ sessionManager?: CodeModeSessionManager;
13
18
  returnedLogBytes?: number;
14
19
  };
15
20
  export declare function runCodeMode(input: RunCodeModeInput): Promise<CodeModeRunEnvelope>;
@@ -1 +1 @@
1
- export declare const CODE_MODE_RUNTIME_API_DECLARATION: "type JsonPrimitive=string|number|boolean|null;type JsonValue=JsonPrimitive|JsonValue[]|{[key:string]:JsonValue};interface CapletHandle<Id extends string>{readonly id:Id;/** Show this Caplet card,without tool/resource/prompt schemas. */ inspect():Promise<CapletCard<Id>>;/** Check backend readiness/auth;expected unavailable states return ok:false. */ check():Promise<CapletsResult<BackendCheckResult>>;/** List tool summaries for the discovery pass;may be empty. */ tools(input?:PageInput):Promise<Page<ToolSummary>>;/** Search tool summaries for the discovery pass;may be empty. */ searchTools(query:string,input?:PageInput):Promise<Page<ToolSummary>>;/** Get schema,callSignature,types,examples;prefer outputSchema/outputTypeScript over observed hints. */ describeTool(name:string):Promise<CapletsResult<ToolDescriptor>>;/** Call one tool;expected failures return ok:false. Filter bulky data in script before returning. */ callTool(name:string,args?:unknown):Promise<CapletsResult<unknown>>;/** List readable resources for the discovery pass;many backends expose none. */ resources(input?:PageInput):Promise<Page<ResourceSummary>>;/** Search readable resources for the discovery pass;many backends expose none. */ searchResources(query:string,input?:PageInput):Promise<Page<ResourceSummary>>;/** List resource templates for the discovery pass;many backends expose none. */ resourceTemplates(input?:PageInput):Promise<Page<ResourceTemplateSummary>>;/** Read one resource by URI;unsupported/missing resources return ok:false. */ readResource(uri:string):Promise<CapletsResult<ResourceReadResult>>;/** List reusable prompts for the discovery pass;many backends expose none. */ prompts(input?:PageInput):Promise<Page<PromptSummary>>;/** Search reusable prompts for the discovery pass;many backends expose none. */ searchPrompts(query:string,input?:PageInput):Promise<Page<PromptSummary>>;/** Get one prompt by name and args;unsupported/missing prompts return ok:false. */ getPrompt(name:string,args?:unknown):Promise<CapletsResult<PromptResult>>;/** Complete a prompt or resource-template argument. */ complete(input:CompleteInput):Promise<CapletsResult<CompleteResult>>;}interface DebugApi{readLogs(input:ReadLogsInput):Promise<ReadLogsResult>;}type CapletCard<Id extends string>={id:Id;name:string;description:string;useWhen?:string;avoidWhen?:string;tags?:string[];backend?:unknown;};type PageInput={limit?:number;cursor?:string};type Page<T>={items:T[];nextCursor?:string;truncated?:boolean};type CapletsResult<T>=|{ok:true;data:T;meta?:CapletsMeta}|{ok:false;error:CapletsError;meta?:CapletsMeta};type CapletsMeta={[key:string]:unknown};type CapletsError={code:string;message:string;details?:unknown};type BackendCheckResult=unknown;type ToolSummary={/** Exact downstream tool identifier for describeTool(name)and callTool(name,args). */ name:string;title?:string;description?:string;/** Optional author-supplied hint for when to prefer this tool. */ useWhen?:string;/** Optional author-supplied hint for when to avoid this tool. */ avoidWhen?:string;/** True when the tool declares that it only reads data. */ readOnlyHint?:boolean;/** True when the tool declares that it may perform destructive writes. */ destructiveHint?:boolean;};type ToolDescriptor={id?:string;tool?:unknown;inputSchema?:unknown;outputSchema?:unknown;callSignature?:string;inputTypeScript?:string;outputTypeScript?:string;observedOutputShape?:ObservedOutputShape;examples?:unknown[];};type ObservedOutputShape={version:1;source:\"observed\";observedAt:string;sampleCount:number;typeScript:string;jsonShape:JsonShape;truncated:boolean;};type JsonShape=|{kind:\"null\"}|{kind:\"boolean\"}|{kind:\"number\"}|{kind:\"string\"}|{kind:\"unknown\"}|{kind:\"array\";element?:JsonShape;truncated?:boolean}|{kind:\"object\";fields:Record<string,{optional:boolean;shape:JsonShape}>;truncated?:boolean;}|{kind:\"union\";variants:JsonShape[]};type ResourceSummary={uri?:string;name?:string;title?:string;description?:string};type ResourceTemplateSummary={uriTemplate?:string;name?:string;title?:string;description?:string;};type ResourceReadResult=unknown;type PromptSummary={name?:string;title?:string;description?:string};type PromptResult=unknown;type CompleteInput={ref:{type:\"prompt\";name:string}|{type:\"resourceTemplate\";uri:string};argument:{name:string;value:string};};type CompleteResult=unknown;type ReadLogsInput={logRef:string;cursor?:string;limit?:number};type ReadLogsResult={entries:CodeModeLogEntry[];nextCursor?:string};type CodeModeLogEntry={level:\"log\"|\"info\"|\"warn\"|\"error\"|\"debug\";message:string;timestamp:string;};interface Console{log(...values:unknown[]):void;info(...values:unknown[]):void;warn(...values:unknown[]):void;error(...values:unknown[]):void;debug(...values:unknown[]):void;}declare const console:Console;";
1
+ export declare const CODE_MODE_RUNTIME_API_DECLARATION: "type JsonPrimitive=string|number|boolean|null;type JsonValue=JsonPrimitive|JsonValue[]|{[key:string]:JsonValue};interface CapletHandle<Id extends string>{readonly id:Id;/** Show this Caplet card,without tool/resource/prompt schemas. */ inspect():Promise<CapletCard<Id>>;/** Check backend readiness/auth;expected unavailable states return ok:false. */ check():Promise<CapletsResult<BackendCheckResult>>;/** List tool summaries for the discovery pass;may be empty. */ tools(input?:PageInput):Promise<Page<ToolSummary>>;/** Search tool summaries for the discovery pass;may be empty. */ searchTools(query:string,input?:PageInput):Promise<Page<ToolSummary>>;/** Get schema,callSignature,types,examples;prefer outputSchema/outputTypeScript over observed hints. */ describeTool(name:string):Promise<CapletsResult<ToolDescriptor>>;/** Call one tool;expected failures return ok:false. Filter bulky data in script before returning. */ callTool(name:string,args?:unknown):Promise<CapletsResult<unknown>>;/** List readable resources for the discovery pass;many backends expose none. */ resources(input?:PageInput):Promise<Page<ResourceSummary>>;/** Search readable resources for the discovery pass;many backends expose none. */ searchResources(query:string,input?:PageInput):Promise<Page<ResourceSummary>>;/** List resource templates for the discovery pass;many backends expose none. */ resourceTemplates(input?:PageInput):Promise<Page<ResourceTemplateSummary>>;/** Read one resource by URI;unsupported/missing resources return ok:false. */ readResource(uri:string):Promise<CapletsResult<ResourceReadResult>>;/** List reusable prompts for the discovery pass;many backends expose none. */ prompts(input?:PageInput):Promise<Page<PromptSummary>>;/** Search reusable prompts for the discovery pass;many backends expose none. */ searchPrompts(query:string,input?:PageInput):Promise<Page<PromptSummary>>;/** Get one prompt by name and args;unsupported/missing prompts return ok:false. */ getPrompt(name:string,args?:unknown):Promise<CapletsResult<PromptResult>>;/** Complete a prompt or resource-template argument. */ complete(input:CompleteInput):Promise<CapletsResult<CompleteResult>>;}interface DebugApi{readLogs(input:ReadLogsInput):Promise<ReadLogsResult>;readRecovery(input:ReadCodeModeRecoveryInput):Promise<ReadCodeModeRecoveryResult>;}type CapletCard<Id extends string>={id:Id;name:string;description:string;useWhen?:string;avoidWhen?:string;tags?:string[];backend?:unknown;};type PageInput={limit?:number;cursor?:string};type Page<T>={items:T[];nextCursor?:string;truncated?:boolean};type CapletsResult<T>=|{ok:true;data:T;meta?:CapletsMeta}|{ok:false;error:CapletsError;meta?:CapletsMeta};type CapletsMeta={[key:string]:unknown};type CapletsError={code:string;message:string;details?:unknown};type BackendCheckResult=unknown;type ToolSummary={/** Exact downstream tool identifier for describeTool(name)and callTool(name,args). */ name:string;title?:string;description?:string;/** Optional author-supplied hint for when to prefer this tool. */ useWhen?:string;/** Optional author-supplied hint for when to avoid this tool. */ avoidWhen?:string;/** True when the tool declares that it only reads data. */ readOnlyHint?:boolean;/** True when the tool declares that it may perform destructive writes. */ destructiveHint?:boolean;};type ToolDescriptor={id?:string;tool?:unknown;inputSchema?:unknown;outputSchema?:unknown;callSignature?:string;inputTypeScript?:string;outputTypeScript?:string;observedOutputShape?:ObservedOutputShape;examples?:unknown[];};type ObservedOutputShape={version:1;source:\"observed\";observedAt:string;sampleCount:number;typeScript:string;jsonShape:JsonShape;truncated:boolean;};type JsonShape=|{kind:\"null\"}|{kind:\"boolean\"}|{kind:\"number\"}|{kind:\"string\"}|{kind:\"unknown\"}|{kind:\"array\";element?:JsonShape;truncated?:boolean}|{kind:\"object\";fields:Record<string,{optional:boolean;shape:JsonShape}>;truncated?:boolean;}|{kind:\"union\";variants:JsonShape[]};type ResourceSummary={uri?:string;name?:string;title?:string;description?:string};type ResourceTemplateSummary={uriTemplate?:string;name?:string;title?:string;description?:string;};type ResourceReadResult=unknown;type PromptSummary={name?:string;title?:string;description?:string};type PromptResult=unknown;type CompleteInput={ref:{type:\"prompt\";name:string}|{type:\"resourceTemplate\";uri:string};argument:{name:string;value:string};};type CompleteResult=unknown;type ReadLogsInput={logRef:string;cursor?:string;limit?:number};type ReadLogsResult={entries:CodeModeLogEntry[];nextCursor?:string};type ReadCodeModeRecoveryInput={recoveryRef:string;cursor?:string;limit?:number};type CodeModeDiagnostic={code:string;message:string;severity:\"error\"|\"warning\"|\"info\";line?:number;column?:number;};type CodeModeRecoveryClassification=\"setup_like\"|\"side_effecting\"|\"unknown\";type CodeModeRecoveryEntry={timestamp:string;code:string;declarationHash:string;outcome:{ok:true}|{ok:false;code:string;message:string};diagnostics:Array<Pick<CodeModeDiagnostic,\"code\"|\"severity\"|\"message\">>;recoveryClassification:CodeModeRecoveryClassification;logsStored?:boolean;summary?:string;};type ReadCodeModeRecoveryResult={entries:CodeModeRecoveryEntry[];nextCursor?:string};type CodeModeLogEntry={level:\"log\"|\"info\"|\"warn\"|\"error\"|\"debug\";message:string;timestamp:string;};type CodeModeSessionStatus=\"created\"|\"reused\";type CodeModeRunMeta={runId:string;traceId:string;declarationHash:string;durationMs:number;timeoutMs:number;maxTimeoutMs:number;sessionId?:string|null;sessionStatus?:CodeModeSessionStatus|null;recoveryRef?:string|null;};interface Console{log(...values:unknown[]):void;info(...values:unknown[]):void;warn(...values:unknown[]):void;error(...values:unknown[]):void;debug(...values:unknown[]):void;}declare const console:Console;";
@@ -1,7 +1,8 @@
1
+ import { type QuickJSRuntime } from "quickjs-emscripten";
1
2
  import type { CodeModeLogEntry } from "./types";
2
3
  export type CodeModeSandboxInvokeInput = {
3
4
  capletId: string;
4
- method: "inspect" | "check" | "tools" | "searchTools" | "describeTool" | "callTool" | "resources" | "searchResources" | "resourceTemplates" | "readResource" | "prompts" | "searchPrompts" | "getPrompt" | "complete" | "readLogs";
5
+ method: "inspect" | "check" | "tools" | "searchTools" | "describeTool" | "callTool" | "resources" | "searchResources" | "resourceTemplates" | "readResource" | "prompts" | "searchPrompts" | "getPrompt" | "complete" | "readLogs" | "readRecovery";
5
6
  args: unknown[];
6
7
  };
7
8
  export type CodeModeSandboxInput = {
@@ -23,6 +24,18 @@ export type CodeModeSandboxResult = {
23
24
  export interface CodeModeSandbox {
24
25
  run(input: CodeModeSandboxInput): Promise<CodeModeSandboxResult>;
25
26
  }
27
+ export interface CodeModeReplSession extends CodeModeSandbox {
28
+ dispose(): void;
29
+ isDisposed(): boolean;
30
+ }
26
31
  export declare class QuickJsCodeModeSandbox implements CodeModeSandbox {
27
32
  run(input: CodeModeSandboxInput): Promise<CodeModeSandboxResult>;
33
+ createSession(): Promise<QuickJsCodeModeReplSession>;
34
+ }
35
+ export declare class QuickJsCodeModeReplSession implements CodeModeReplSession {
36
+ #private;
37
+ constructor(runtime: QuickJSRuntime);
38
+ run(input: CodeModeSandboxInput): Promise<CodeModeSandboxResult>;
39
+ dispose(): void;
40
+ isDisposed(): boolean;
28
41
  }
@@ -0,0 +1,53 @@
1
+ import { type CodeModeReplSession, type CodeModeSandboxResult, type CodeModeSandboxInput } from "./sandbox";
2
+ import { CodeModeDiagnosticsSession } from "./diagnostics";
3
+ import type { CodeModeSessionStatus } from "./types";
4
+ export declare const CODE_MODE_SESSION_COMPATIBILITY_VERSION = 1;
5
+ export declare const DEFAULT_CODE_MODE_SESSION_TTL_MS: number;
6
+ export declare const DEFAULT_CODE_MODE_SESSION_LIMIT = 32;
7
+ export type CodeModeSessionCompatibility = {
8
+ declarationHash: string;
9
+ platformRuntimeHash: string;
10
+ runtimeScope: string;
11
+ version?: number;
12
+ };
13
+ export type CodeModeSessionRunInput = CodeModeSandboxInput & {
14
+ sessionId?: string;
15
+ compatibility: CodeModeSessionCompatibility;
16
+ onSuccessfulCell?: (sessionId: string, code: string) => void;
17
+ };
18
+ export type CodeModeSessionRunResult = {
19
+ ok: true;
20
+ sessionId: string;
21
+ sessionStatus: CodeModeSessionStatus;
22
+ sessionDisposedAfterRun: boolean;
23
+ compatibilityKey: string;
24
+ result: CodeModeSandboxResult;
25
+ } | {
26
+ ok: false;
27
+ sessionId: string;
28
+ sessionStatus: null;
29
+ error: "not_found" | "busy" | "closed";
30
+ };
31
+ export type CodeModeSessionManagerOptions = {
32
+ idGenerator?: () => string;
33
+ now?: () => number;
34
+ ttlMs?: number;
35
+ maxSessions?: number;
36
+ sandboxFactory?: () => CodeModeReplSessionFactory;
37
+ };
38
+ export type CodeModeReplSessionFactory = {
39
+ createSession(): Promise<CodeModeReplSession>;
40
+ };
41
+ export declare class CodeModeSessionManager {
42
+ #private;
43
+ readonly ttlMs: number;
44
+ readonly maxSessions: number;
45
+ constructor(options?: CodeModeSessionManagerOptions);
46
+ run(input: CodeModeSessionRunInput): Promise<CodeModeSessionRunResult>;
47
+ close(): void;
48
+ has(sessionId: string): boolean;
49
+ compatibilityKey(sessionId: string): string | undefined;
50
+ diagnosticsSession(sessionId: string, compatibility: CodeModeSessionCompatibility): CodeModeDiagnosticsSession | undefined;
51
+ isBusy(sessionId: string, compatibility: CodeModeSessionCompatibility): boolean;
52
+ recordSuccessfulCell(sessionId: string, code: string, declaration?: string): void;
53
+ }
@@ -1,11 +1,16 @@
1
1
  import { z } from "zod";
2
+ import type { CodeModeRunMeta } from "./types";
3
+ export declare const CODE_MODE_SESSION_ID_DESCRIPTION = "Optional Code Mode session identifier. Omit to create a fresh reusable session; pass a known live session ID from meta.sessionId to reuse existing REPL state. Unknown or unavailable session IDs fail before code execution instead of starting an empty context.";
2
4
  export declare const codeModeRunInputSchema: z.ZodObject<{
3
5
  code: z.ZodString;
4
6
  timeoutMs: z.ZodOptional<z.ZodNumber>;
7
+ sessionId: z.ZodOptional<z.ZodString>;
5
8
  }, z.core.$strip>;
6
9
  export declare const codeModeRunParamsSchema: {
7
10
  code: z.ZodString;
8
11
  timeoutMs: z.ZodOptional<z.ZodNumber>;
12
+ sessionId: z.ZodOptional<z.ZodString>;
9
13
  };
10
14
  export declare function codeModeRunInputJsonSchema(): Record<string, unknown>;
11
15
  export declare function isCodeModeRunRequest(value: unknown): boolean;
16
+ export declare function emptyCodeModeRunMeta(): CodeModeRunMeta;
@@ -27,6 +27,7 @@ export type CodeModeDiagnostic = {
27
27
  line?: number;
28
28
  column?: number;
29
29
  };
30
+ export type CodeModeSessionStatus = "created" | "reused";
30
31
  export type CodeModeRunMeta = {
31
32
  runId: string;
32
33
  traceId: string;
@@ -34,6 +35,9 @@ export type CodeModeRunMeta = {
34
35
  durationMs: number;
35
36
  timeoutMs: number;
36
37
  maxTimeoutMs: number;
38
+ sessionId?: string | null;
39
+ sessionStatus?: CodeModeSessionStatus | null;
40
+ recoveryRef?: string | null;
37
41
  };
38
42
  export type CodeModeRunError = {
39
43
  code: string;
@@ -119,3 +123,29 @@ export type ReadLogsResult = {
119
123
  entries: CodeModeLogEntry[];
120
124
  nextCursor?: string;
121
125
  };
126
+ export type ReadCodeModeRecoveryInput = {
127
+ recoveryRef: string;
128
+ cursor?: string;
129
+ limit?: number;
130
+ };
131
+ export type CodeModeRecoveryClassification = "setup_like" | "side_effecting" | "unknown";
132
+ export type CodeModeRecoveryEntry = {
133
+ timestamp: string;
134
+ code: string;
135
+ declarationHash: string;
136
+ outcome: {
137
+ ok: true;
138
+ } | {
139
+ ok: false;
140
+ code: string;
141
+ message: string;
142
+ };
143
+ diagnostics: Array<Pick<CodeModeDiagnostic, "code" | "severity" | "message">>;
144
+ recoveryClassification: CodeModeRecoveryClassification;
145
+ logsStored?: boolean;
146
+ summary?: string;
147
+ };
148
+ export type ReadCodeModeRecoveryResult = {
149
+ entries: CodeModeRecoveryEntry[];
150
+ nextCursor?: string;
151
+ };
package/dist/code-mode.js CHANGED
@@ -2,11 +2,12 @@
2
2
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
3
3
  //#endregion
4
4
  //#region src/code-mode/runtime-api.generated.ts
5
- const CODE_MODE_RUNTIME_API_DECLARATION = "type JsonPrimitive=string|number|boolean|null;type JsonValue=JsonPrimitive|JsonValue[]|{[key:string]:JsonValue};interface CapletHandle<Id extends string>{readonly id:Id;/** Show this Caplet card,without tool/resource/prompt schemas. */ inspect():Promise<CapletCard<Id>>;/** Check backend readiness/auth;expected unavailable states return ok:false. */ check():Promise<CapletsResult<BackendCheckResult>>;/** List tool summaries for the discovery pass;may be empty. */ tools(input?:PageInput):Promise<Page<ToolSummary>>;/** Search tool summaries for the discovery pass;may be empty. */ searchTools(query:string,input?:PageInput):Promise<Page<ToolSummary>>;/** Get schema,callSignature,types,examples;prefer outputSchema/outputTypeScript over observed hints. */ describeTool(name:string):Promise<CapletsResult<ToolDescriptor>>;/** Call one tool;expected failures return ok:false. Filter bulky data in script before returning. */ callTool(name:string,args?:unknown):Promise<CapletsResult<unknown>>;/** List readable resources for the discovery pass;many backends expose none. */ resources(input?:PageInput):Promise<Page<ResourceSummary>>;/** Search readable resources for the discovery pass;many backends expose none. */ searchResources(query:string,input?:PageInput):Promise<Page<ResourceSummary>>;/** List resource templates for the discovery pass;many backends expose none. */ resourceTemplates(input?:PageInput):Promise<Page<ResourceTemplateSummary>>;/** Read one resource by URI;unsupported/missing resources return ok:false. */ readResource(uri:string):Promise<CapletsResult<ResourceReadResult>>;/** List reusable prompts for the discovery pass;many backends expose none. */ prompts(input?:PageInput):Promise<Page<PromptSummary>>;/** Search reusable prompts for the discovery pass;many backends expose none. */ searchPrompts(query:string,input?:PageInput):Promise<Page<PromptSummary>>;/** Get one prompt by name and args;unsupported/missing prompts return ok:false. */ getPrompt(name:string,args?:unknown):Promise<CapletsResult<PromptResult>>;/** Complete a prompt or resource-template argument. */ complete(input:CompleteInput):Promise<CapletsResult<CompleteResult>>;}interface DebugApi{readLogs(input:ReadLogsInput):Promise<ReadLogsResult>;}type CapletCard<Id extends string>={id:Id;name:string;description:string;useWhen?:string;avoidWhen?:string;tags?:string[];backend?:unknown;};type PageInput={limit?:number;cursor?:string};type Page<T>={items:T[];nextCursor?:string;truncated?:boolean};type CapletsResult<T>=|{ok:true;data:T;meta?:CapletsMeta}|{ok:false;error:CapletsError;meta?:CapletsMeta};type CapletsMeta={[key:string]:unknown};type CapletsError={code:string;message:string;details?:unknown};type BackendCheckResult=unknown;type ToolSummary={/** Exact downstream tool identifier for describeTool(name)and callTool(name,args). */ name:string;title?:string;description?:string;/** Optional author-supplied hint for when to prefer this tool. */ useWhen?:string;/** Optional author-supplied hint for when to avoid this tool. */ avoidWhen?:string;/** True when the tool declares that it only reads data. */ readOnlyHint?:boolean;/** True when the tool declares that it may perform destructive writes. */ destructiveHint?:boolean;};type ToolDescriptor={id?:string;tool?:unknown;inputSchema?:unknown;outputSchema?:unknown;callSignature?:string;inputTypeScript?:string;outputTypeScript?:string;observedOutputShape?:ObservedOutputShape;examples?:unknown[];};type ObservedOutputShape={version:1;source:\"observed\";observedAt:string;sampleCount:number;typeScript:string;jsonShape:JsonShape;truncated:boolean;};type JsonShape=|{kind:\"null\"}|{kind:\"boolean\"}|{kind:\"number\"}|{kind:\"string\"}|{kind:\"unknown\"}|{kind:\"array\";element?:JsonShape;truncated?:boolean}|{kind:\"object\";fields:Record<string,{optional:boolean;shape:JsonShape}>;truncated?:boolean;}|{kind:\"union\";variants:JsonShape[]};type ResourceSummary={uri?:string;name?:string;title?:string;description?:string};type ResourceTemplateSummary={uriTemplate?:string;name?:string;title?:string;description?:string;};type ResourceReadResult=unknown;type PromptSummary={name?:string;title?:string;description?:string};type PromptResult=unknown;type CompleteInput={ref:{type:\"prompt\";name:string}|{type:\"resourceTemplate\";uri:string};argument:{name:string;value:string};};type CompleteResult=unknown;type ReadLogsInput={logRef:string;cursor?:string;limit?:number};type ReadLogsResult={entries:CodeModeLogEntry[];nextCursor?:string};type CodeModeLogEntry={level:\"log\"|\"info\"|\"warn\"|\"error\"|\"debug\";message:string;timestamp:string;};interface Console{log(...values:unknown[]):void;info(...values:unknown[]):void;warn(...values:unknown[]):void;error(...values:unknown[]):void;debug(...values:unknown[]):void;}declare const console:Console;";
5
+ const CODE_MODE_RUNTIME_API_DECLARATION = "type JsonPrimitive=string|number|boolean|null;type JsonValue=JsonPrimitive|JsonValue[]|{[key:string]:JsonValue};interface CapletHandle<Id extends string>{readonly id:Id;/** Show this Caplet card,without tool/resource/prompt schemas. */ inspect():Promise<CapletCard<Id>>;/** Check backend readiness/auth;expected unavailable states return ok:false. */ check():Promise<CapletsResult<BackendCheckResult>>;/** List tool summaries for the discovery pass;may be empty. */ tools(input?:PageInput):Promise<Page<ToolSummary>>;/** Search tool summaries for the discovery pass;may be empty. */ searchTools(query:string,input?:PageInput):Promise<Page<ToolSummary>>;/** Get schema,callSignature,types,examples;prefer outputSchema/outputTypeScript over observed hints. */ describeTool(name:string):Promise<CapletsResult<ToolDescriptor>>;/** Call one tool;expected failures return ok:false. Filter bulky data in script before returning. */ callTool(name:string,args?:unknown):Promise<CapletsResult<unknown>>;/** List readable resources for the discovery pass;many backends expose none. */ resources(input?:PageInput):Promise<Page<ResourceSummary>>;/** Search readable resources for the discovery pass;many backends expose none. */ searchResources(query:string,input?:PageInput):Promise<Page<ResourceSummary>>;/** List resource templates for the discovery pass;many backends expose none. */ resourceTemplates(input?:PageInput):Promise<Page<ResourceTemplateSummary>>;/** Read one resource by URI;unsupported/missing resources return ok:false. */ readResource(uri:string):Promise<CapletsResult<ResourceReadResult>>;/** List reusable prompts for the discovery pass;many backends expose none. */ prompts(input?:PageInput):Promise<Page<PromptSummary>>;/** Search reusable prompts for the discovery pass;many backends expose none. */ searchPrompts(query:string,input?:PageInput):Promise<Page<PromptSummary>>;/** Get one prompt by name and args;unsupported/missing prompts return ok:false. */ getPrompt(name:string,args?:unknown):Promise<CapletsResult<PromptResult>>;/** Complete a prompt or resource-template argument. */ complete(input:CompleteInput):Promise<CapletsResult<CompleteResult>>;}interface DebugApi{readLogs(input:ReadLogsInput):Promise<ReadLogsResult>;readRecovery(input:ReadCodeModeRecoveryInput):Promise<ReadCodeModeRecoveryResult>;}type CapletCard<Id extends string>={id:Id;name:string;description:string;useWhen?:string;avoidWhen?:string;tags?:string[];backend?:unknown;};type PageInput={limit?:number;cursor?:string};type Page<T>={items:T[];nextCursor?:string;truncated?:boolean};type CapletsResult<T>=|{ok:true;data:T;meta?:CapletsMeta}|{ok:false;error:CapletsError;meta?:CapletsMeta};type CapletsMeta={[key:string]:unknown};type CapletsError={code:string;message:string;details?:unknown};type BackendCheckResult=unknown;type ToolSummary={/** Exact downstream tool identifier for describeTool(name)and callTool(name,args). */ name:string;title?:string;description?:string;/** Optional author-supplied hint for when to prefer this tool. */ useWhen?:string;/** Optional author-supplied hint for when to avoid this tool. */ avoidWhen?:string;/** True when the tool declares that it only reads data. */ readOnlyHint?:boolean;/** True when the tool declares that it may perform destructive writes. */ destructiveHint?:boolean;};type ToolDescriptor={id?:string;tool?:unknown;inputSchema?:unknown;outputSchema?:unknown;callSignature?:string;inputTypeScript?:string;outputTypeScript?:string;observedOutputShape?:ObservedOutputShape;examples?:unknown[];};type ObservedOutputShape={version:1;source:\"observed\";observedAt:string;sampleCount:number;typeScript:string;jsonShape:JsonShape;truncated:boolean;};type JsonShape=|{kind:\"null\"}|{kind:\"boolean\"}|{kind:\"number\"}|{kind:\"string\"}|{kind:\"unknown\"}|{kind:\"array\";element?:JsonShape;truncated?:boolean}|{kind:\"object\";fields:Record<string,{optional:boolean;shape:JsonShape}>;truncated?:boolean;}|{kind:\"union\";variants:JsonShape[]};type ResourceSummary={uri?:string;name?:string;title?:string;description?:string};type ResourceTemplateSummary={uriTemplate?:string;name?:string;title?:string;description?:string;};type ResourceReadResult=unknown;type PromptSummary={name?:string;title?:string;description?:string};type PromptResult=unknown;type CompleteInput={ref:{type:\"prompt\";name:string}|{type:\"resourceTemplate\";uri:string};argument:{name:string;value:string};};type CompleteResult=unknown;type ReadLogsInput={logRef:string;cursor?:string;limit?:number};type ReadLogsResult={entries:CodeModeLogEntry[];nextCursor?:string};type ReadCodeModeRecoveryInput={recoveryRef:string;cursor?:string;limit?:number};type CodeModeDiagnostic={code:string;message:string;severity:\"error\"|\"warning\"|\"info\";line?:number;column?:number;};type CodeModeRecoveryClassification=\"setup_like\"|\"side_effecting\"|\"unknown\";type CodeModeRecoveryEntry={timestamp:string;code:string;declarationHash:string;outcome:{ok:true}|{ok:false;code:string;message:string};diagnostics:Array<Pick<CodeModeDiagnostic,\"code\"|\"severity\"|\"message\">>;recoveryClassification:CodeModeRecoveryClassification;logsStored?:boolean;summary?:string;};type ReadCodeModeRecoveryResult={entries:CodeModeRecoveryEntry[];nextCursor?:string};type CodeModeLogEntry={level:\"log\"|\"info\"|\"warn\"|\"error\"|\"debug\";message:string;timestamp:string;};type CodeModeSessionStatus=\"created\"|\"reused\";type CodeModeRunMeta={runId:string;traceId:string;declarationHash:string;durationMs:number;timeoutMs:number;maxTimeoutMs:number;sessionId?:string|null;sessionStatus?:CodeModeSessionStatus|null;recoveryRef?:string|null;};interface Console{log(...values:unknown[]):void;info(...values:unknown[]):void;warn(...values:unknown[]):void;error(...values:unknown[]):void;debug(...values:unknown[]):void;}declare const console:Console;";
6
6
  //#endregion
7
7
  //#region src/code-mode/declarations.ts
8
8
  const JS_IDENTIFIER = /^[A-Za-z_$][\w$]*$/u;
9
9
  const MAX_JSDOC_CHARS = 180;
10
+ const CODE_MODE_REPL_GUIDANCE = "REPL reuse: omit `sessionId` to start a fresh reusable Code Mode session; after a successful run, keep `meta.sessionId` and pass it as `sessionId` on later calls when you want to reuse live state. Reused sessions preserve successful top-level `var` bindings, function declarations, and runtime state only while the live session remains available and compatible. A supplied `sessionId` that is unknown or no longer available fails before executing your code instead of starting an empty context. Use `meta.recoveryRef` with `caplets.debug.readRecovery({ recoveryRef })` for audit and manual reconstruction; do not automatically replay recovery history.";
10
11
  function generateCodeModeDeclarations(input) {
11
12
  const caplets = [...input.caplets].sort((left, right) => left.id.localeCompare(right.id));
12
13
  const properties = caplets.map((caplet) => {
@@ -26,6 +27,7 @@ function generateCodeModeDeclarations(input) {
26
27
  function generateCodeModeRunToolDescription(declaration) {
27
28
  return [
28
29
  "Run TypeScript with generated `caplets.<id>` handles and declaration hints below. Prefer a compact one-pass script for most tasks: discover, filter, execute, and synthesize inside Code Mode, then return only decision-ready JSON. Do not return full tool lists, full descriptors, schemas, raw tool payloads, or exploratory transcripts unless the user specifically needs them; keep bulky intermediate data inside the script. For discovery, use tools/searchTools for names and arg hints, then describeTool only for short-listed operations needing exact schemas, nested args, fields, or disambiguation. Never invent tool names, resource URIs, prompt names, input args, output fields, or schemas; use requiredArgs/acceptedArgs for simple calls, otherwise use describeTool for the exact callSignature/inputSchema/inputTypeScript. For fallback, check candidate handles first: `for(const h of candidates){const ready=await h.check();if(!ready.ok)continue;}`. For triage, list broad candidate records and filter in script before targeted searches so adjacent relevant items are not missed. Execute with exact args, handle `{ok:false}`, and derive final recommendations from all relevant records, not the first matching record. If records disagree or have ranges/statuses, compute the strictest applicable conclusion and preserve only the compact evidence used. Return summaries, key ids/names/titles/statuses/urls, derived fields, recommendation, caveats, and residual missing data. Before returning, remove unused descriptors/schemas/raw content. Pattern: `const h=caplets[\"caplet-id\"];const tools=await h.searchTools(\"query\");const d=needSchema?await h.describeTool(\"tool_name\"):undefined;const r=await h.callTool(\"tool_name\",args);return {facts:[...],evidence:[...]};`",
30
+ CODE_MODE_REPL_GUIDANCE,
29
31
  "",
30
32
  "Generated declaration hints:",
31
33
  "```ts",
@@ -41,7 +43,7 @@ function capletHintText(caplet) {
41
43
  ].filter((value) => Boolean(value)).join(" ");
42
44
  }
43
45
  function minifyCodeModeDeclarationText(value) {
44
- return value.replace(/^\s*export\s*\{\s*\}\s*;?\s*/u, "").replace(/\r\n?/gu, "\n").split("\n").map((line) => line.trim()).filter(Boolean).join(" ").replace(/\s+/gu, " ").replace(/\s*([{}()[\]:;,|&=])\s*/gu, "$1").replace(/\s*<\s*/gu, "<").replace(/\s*>\s*/gu, ">").replace(/\?\s*:/gu, "?:").trim();
46
+ return value.replace(/^\s*export\s*\{\s*\}\s*;?\s*/u, "").replace(/\s*export\s*\{\s*\}\s*;?\s*$/u, "").replace(/\r\n?/gu, "\n").split("\n").map((line) => line.trim()).filter(Boolean).join(" ").replace(/\s+/gu, " ").replace(/\s*([{}()[\]:;,|&=])\s*/gu, "$1").replace(/\s*<\s*/gu, "<").replace(/\s*>\s*/gu, ">").replace(/\?\s*:/gu, "?:").trim();
45
47
  }
46
48
  function codeModeDeclarationHash(declaration) {
47
49
  return [
@@ -12678,7 +12680,7 @@ const PARSER_OPTIONS = {
12678
12680
  ]
12679
12681
  };
12680
12682
  function hasDirectFetchCall(code) {
12681
- return hasMatchingAstNode(code, (node) => isCallExpression(node) && isFetchCallee(node.callee));
12683
+ return hasMatchingAstNode(code, isDirectFetchCallNode);
12682
12684
  }
12683
12685
  function hasExecutableImport(code) {
12684
12686
  return hasMatchingAstNode(code, isExecutableImportNode);
@@ -12687,9 +12689,9 @@ function hasMatchingAstNode(code, predicate) {
12687
12689
  const ast = parseCode(code);
12688
12690
  if (!ast) return false;
12689
12691
  let found = false;
12690
- visitAst(ast, (node) => {
12692
+ visitAst(ast, (node, parent) => {
12691
12693
  if (found) return;
12692
- found = predicate(node);
12694
+ found = predicate(node, parent);
12693
12695
  });
12694
12696
  return found;
12695
12697
  }
@@ -12707,11 +12709,10 @@ function isExecutableImportNode(node) {
12707
12709
  function isCallExpression(node) {
12708
12710
  return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && "callee" in node;
12709
12711
  }
12710
- function isFetchCallee(value) {
12711
- if (!isNode(value)) return false;
12712
- if (value.type === "Identifier") return value.name === "fetch";
12713
- if (value.type === "MemberExpression" || value.type === "OptionalMemberExpression") return isGlobalFetchMember(value);
12714
- return false;
12712
+ function isDirectFetchCallNode(node) {
12713
+ if (!isCallExpression(node) || !isNode(node.callee)) return false;
12714
+ if (isIdentifierNamed(node.callee, "fetch")) return true;
12715
+ return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && isGlobalFetchMember(node.callee);
12715
12716
  }
12716
12717
  function isGlobalFetchMember(node) {
12717
12718
  if (!isIdentifierNamed(node.object, "globalThis", "window", "self")) return false;
@@ -12721,16 +12722,22 @@ function isGlobalFetchMember(node) {
12721
12722
  function isExportDeclaration(node) {
12722
12723
  return node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration";
12723
12724
  }
12724
- function visitAst(value, visit) {
12725
+ function visitAst(value, visit, parent) {
12725
12726
  if (!isNode(value)) return;
12726
- visit(value);
12727
+ visit(value, parent);
12727
12728
  for (const [key, child] of Object.entries(value)) {
12728
12729
  if (key === "loc" || key === "start" || key === "end" || key === "extra") continue;
12729
12730
  if (Array.isArray(child)) {
12730
- for (const item of child) visitAst(item, visit);
12731
+ for (const item of child) visitAst(item, visit, {
12732
+ node: value,
12733
+ key
12734
+ });
12731
12735
  continue;
12732
12736
  }
12733
- visitAst(child, visit);
12737
+ visitAst(child, visit, {
12738
+ node: value,
12739
+ key
12740
+ });
12734
12741
  }
12735
12742
  }
12736
12743
  function isNode(value) {
@@ -1,4 +1,4 @@
1
- import { Ct as resolveCapletsRoot, Et as resolveProjectConfigPath, Q as loadConfigWithSources, Sn as __exportAll, _t as DEFAULT_AUTH_DIR, vt as DEFAULT_COMPLETION_CACHE_DIR, wt as resolveConfigPath } from "./service-4_chB2wu.js";
1
+ import { Dt as resolveConfigPath, Et as resolveCapletsRoot, Tn as __exportAll, bt as DEFAULT_AUTH_DIR, kt as resolveProjectConfigPath, tt as loadConfigWithSources, xt as DEFAULT_COMPLETION_CACHE_DIR } from "./service-BCT_Ls_3.js";
2
2
  import { u as CapletsError } from "./validation-DgxCzt-A.js";
3
3
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
@@ -75,6 +75,7 @@ const cliSubcommands = {
75
75
  "cli",
76
76
  "mcp",
77
77
  "openapi",
78
+ "google-discovery",
78
79
  "graphql",
79
80
  "http"
80
81
  ],
@@ -142,6 +143,7 @@ function allCaplets(config) {
142
143
  return [
143
144
  ...Object.values(config.mcpServers),
144
145
  ...Object.values(config.openapiEndpoints),
146
+ ...Object.values(config.googleDiscoveryApis ?? {}),
145
147
  ...Object.values(config.graphqlEndpoints),
146
148
  ...Object.values(config.httpApis),
147
149
  ...Object.values(config.cliTools),
@@ -383,6 +385,16 @@ function secretFreeServerShape(server) {
383
385
  authType: server.auth.type,
384
386
  requestTimeoutMs: server.requestTimeoutMs
385
387
  };
388
+ case "googleDiscovery": return {
389
+ ...base,
390
+ discoveryPath: server.discoveryPath,
391
+ discoveryUrl: server.discoveryUrl,
392
+ baseUrl: server.baseUrl,
393
+ includeOperations: server.includeOperations,
394
+ excludeOperations: server.excludeOperations,
395
+ authType: server.auth.type,
396
+ requestTimeoutMs: server.requestTimeoutMs
397
+ };
386
398
  case "graphql": return {
387
399
  ...base,
388
400
  endpointUrl: server.endpointUrl,
@@ -441,7 +453,7 @@ async function withTimeout(promise, timeoutMs) {
441
453
  }
442
454
  }
443
455
  function enabledServer(serverId, config) {
444
- const server = config.mcpServers[serverId] ?? config.openapiEndpoints[serverId] ?? config.graphqlEndpoints[serverId] ?? config.httpApis[serverId] ?? config.cliTools[serverId] ?? config.capletSets[serverId];
456
+ const server = config.mcpServers[serverId] ?? config.openapiEndpoints[serverId] ?? config.googleDiscoveryApis[serverId] ?? config.graphqlEndpoints[serverId] ?? config.httpApis[serverId] ?? config.cliTools[serverId] ?? config.capletSets[serverId];
445
457
  return server && !server.disabled ? server : void 0;
446
458
  }
447
459
  function dedupeCandidates(candidates) {
@@ -5,10 +5,12 @@ export declare function defaultStateBaseDir(env?: PathEnv, home?: string, platfo
5
5
  export declare function defaultCacheBaseDir(env?: PathEnv, home?: string, platform?: Platform): string;
6
6
  export declare function defaultConfigPath(env?: PathEnv, home?: string, platform?: Platform): string;
7
7
  export declare function defaultAuthDir(env?: PathEnv, home?: string, platform?: Platform): string;
8
+ export declare function defaultArtifactDir(env?: PathEnv, home?: string, platform?: Platform): string;
8
9
  export declare function defaultCompletionCacheDir(env?: PathEnv, home?: string, platform?: Platform): string;
9
10
  export declare function defaultObservedOutputShapeCacheDir(env?: PathEnv, home?: string, platform?: Platform): string;
10
11
  export declare const DEFAULT_CONFIG_PATH: string;
11
12
  export declare const DEFAULT_AUTH_DIR: string;
13
+ export declare const DEFAULT_ARTIFACT_DIR: string;
12
14
  export declare const DEFAULT_COMPLETION_CACHE_DIR: string;
13
15
  export declare const DEFAULT_OBSERVED_OUTPUT_SHAPE_CACHE_DIR: string;
14
16
  export declare const PROJECT_CONFIG_FILE: string;
@@ -73,6 +73,17 @@ export type OpenApiEndpointConfig = CommonCapletConfig & {
73
73
  requestTimeoutMs: number;
74
74
  operationCacheTtlMs: number;
75
75
  };
76
+ export type GoogleDiscoveryApiConfig = CommonCapletConfig & {
77
+ backend: "googleDiscovery";
78
+ discoveryPath?: string | undefined;
79
+ discoveryUrl?: string | undefined;
80
+ baseUrl?: string | undefined;
81
+ includeOperations?: string[] | undefined;
82
+ excludeOperations?: string[] | undefined;
83
+ auth: OpenApiAuthConfig;
84
+ requestTimeoutMs: number;
85
+ operationCacheTtlMs: number;
86
+ };
76
87
  export type GraphQlOperationConfig = AgentSelectionHintsConfig & {
77
88
  document?: string | undefined;
78
89
  documentPath?: string | undefined;
@@ -145,7 +156,7 @@ export type CapletSetConfig = CommonCapletConfig & {
145
156
  maxSearchLimit: number;
146
157
  toolCacheTtlMs: number;
147
158
  };
148
- export type CapletConfig = CapletServerConfig | OpenApiEndpointConfig | GraphQlEndpointConfig | HttpApiConfig | CliToolsConfig | CapletSetConfig;
159
+ export type CapletConfig = CapletServerConfig | OpenApiEndpointConfig | GoogleDiscoveryApiConfig | GraphQlEndpointConfig | HttpApiConfig | CliToolsConfig | CapletSetConfig;
149
160
  export type CapletsConfig = {
150
161
  version: 1;
151
162
  options: {
@@ -163,6 +174,7 @@ export type CapletsConfig = {
163
174
  };
164
175
  mcpServers: Record<string, CapletServerConfig>;
165
176
  openapiEndpoints: Record<string, OpenApiEndpointConfig>;
177
+ googleDiscoveryApis: Record<string, GoogleDiscoveryApiConfig>;
166
178
  graphqlEndpoints: Record<string, GraphQlEndpointConfig>;
167
179
  httpApis: Record<string, HttpApiConfig>;
168
180
  cliTools: Record<string, CliToolsConfig>;