@themoltnet/pi-extension 0.15.1 → 0.16.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 (3) hide show
  1. package/dist/index.d.ts +22 -0
  2. package/dist/index.js +2142 -2055
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -4,9 +4,9 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } fr
4
4
  import path, { join } from "node:path";
5
5
  import { DefaultResourceLoader, SessionManager, createAgentSession, createBashTool, createBashToolDefinition, createEditTool, createEditToolDefinition, createReadTool, createReadToolDefinition, createSyntheticSourceInfo, createWriteTool, createWriteToolDefinition, defineTool, parseFrontmatter } from "@earendil-works/pi-coding-agent";
6
6
  import { createHash } from "node:crypto";
7
- import crypto, { createHash as createHash$1 } from "crypto";
8
7
  import { readFile } from "node:fs/promises";
9
8
  import { homedir } from "node:os";
9
+ import crypto, { createHash as createHash$1 } from "crypto";
10
10
  import { Type, getModel } from "@earendil-works/pi-ai";
11
11
  import { MemoryProvider, RealFSProvider, ShadowProvider, VM, VmCheckpoint, createHttpHooks, createShadowPathPredicate, ensureImageSelector, loadGuestAssets } from "@earendil-works/gondolin";
12
12
  import { parseEnv } from "node:util";
@@ -2609,7 +2609,6 @@ function createDiaryGrantsNamespace(context) {
2609
2609
  }
2610
2610
  };
2611
2611
  }
2612
- new TextEncoder();
2613
2612
  //#endregion
2614
2613
  //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
2615
2614
  /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
@@ -4333,941 +4332,1323 @@ var wNAF = (n) => {
4333
4332
  };
4334
4333
  };
4335
4334
  //#endregion
4336
- //#region ../crypto-service/src/crypto.service.ts
4337
- etc.sha512Sync = (...m) => {
4338
- const hash = createHash$1("sha512");
4339
- m.forEach((msg) => hash.update(msg));
4340
- return hash.digest();
4341
- };
4342
- //#endregion
4343
- //#region ../crypto-service/src/executor-attestation.ts
4344
- etc.sha512Sync = (...m) => {
4345
- const hash = createHash("sha512");
4346
- m.forEach((msg) => hash.update(msg));
4347
- return hash.digest();
4348
- };
4349
- //#endregion
4350
- //#region ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/codecs/json.js
4351
- var textEncoder$1 = new TextEncoder();
4352
- new TextDecoder();
4353
- function encode(node) {
4354
- return textEncoder$1.encode(JSON.stringify(node));
4355
- }
4356
- //#endregion
4357
- //#region ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/hasher.js
4358
- var DEFAULT_MIN_DIGEST_LENGTH = 20;
4359
- function from({ name, code, encode, minDigestLength, maxDigestLength }) {
4360
- return new Hasher(name, code, encode, minDigestLength, maxDigestLength);
4361
- }
4362
- /**
4363
- * Hasher represents a hashing algorithm implementation that produces as
4364
- * `MultihashDigest`.
4365
- */
4366
- var Hasher = class {
4367
- name;
4368
- code;
4369
- encode;
4370
- minDigestLength;
4371
- maxDigestLength;
4372
- constructor(name, code, encode, minDigestLength, maxDigestLength) {
4373
- this.name = name;
4374
- this.code = code;
4375
- this.encode = encode;
4376
- this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH;
4377
- this.maxDigestLength = maxDigestLength;
4378
- }
4379
- digest(input, options) {
4380
- if (options?.truncate != null) {
4381
- if (options.truncate < this.minDigestLength) throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);
4382
- if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`);
4335
+ //#region ../sdk/src/namespaces/entries.ts
4336
+ function createEntriesNamespace(context) {
4337
+ const { client, auth } = context;
4338
+ return {
4339
+ async create(diaryId, body) {
4340
+ return unwrapResult(await createDiaryEntry({
4341
+ client,
4342
+ auth,
4343
+ body,
4344
+ path: { diaryId }
4345
+ }));
4346
+ },
4347
+ async list(diaryId, query) {
4348
+ return unwrapResult(await listDiaryEntries({
4349
+ client,
4350
+ auth,
4351
+ query,
4352
+ path: { diaryId }
4353
+ }));
4354
+ },
4355
+ async get(entryId) {
4356
+ return unwrapResult(await getDiaryEntryById({
4357
+ client,
4358
+ auth,
4359
+ path: { entryId }
4360
+ }));
4361
+ },
4362
+ async update(entryId, body) {
4363
+ return unwrapResult(await updateDiaryEntryById({
4364
+ client,
4365
+ auth,
4366
+ path: { entryId },
4367
+ body
4368
+ }));
4369
+ },
4370
+ async delete(entryId) {
4371
+ return unwrapResult(await deleteDiaryEntryById({
4372
+ client,
4373
+ auth,
4374
+ path: { entryId }
4375
+ }));
4376
+ },
4377
+ async search(body) {
4378
+ return unwrapResult(await searchDiary({
4379
+ client,
4380
+ auth,
4381
+ body
4382
+ }));
4383
+ },
4384
+ async reflect(query) {
4385
+ return unwrapResult(await reflectDiary({
4386
+ client,
4387
+ auth,
4388
+ query
4389
+ }));
4390
+ },
4391
+ async verify(entryId) {
4392
+ return unwrapResult(await verifyDiaryEntryById({
4393
+ client,
4394
+ auth,
4395
+ path: { entryId }
4396
+ }));
4397
+ },
4398
+ async createSigned(diaryId, body, privateKey) {
4399
+ const signingRequest = unwrapResult(await createSigningRequest({
4400
+ client,
4401
+ auth,
4402
+ body: { message: computeContentCid(body.entryType ?? "semantic", body.title ?? null, body.content, body.tags ?? null) }
4403
+ }));
4404
+ const privateKeyBytes = new Uint8Array(Buffer.from(privateKey, "base64"));
4405
+ const signature = await signAsync(new Uint8Array(Buffer.from(signingRequest.signingInput, "base64")), privateKeyBytes);
4406
+ const signatureB64 = Buffer.from(signature).toString("base64");
4407
+ unwrapResult(await submitSignature({
4408
+ client,
4409
+ auth,
4410
+ path: { id: signingRequest.id },
4411
+ body: { signature: signatureB64 }
4412
+ }));
4413
+ return unwrapResult(await createDiaryEntry({
4414
+ client,
4415
+ auth,
4416
+ path: { diaryId },
4417
+ body: {
4418
+ ...body,
4419
+ signingRequestId: signingRequest.id
4420
+ }
4421
+ }));
4383
4422
  }
4384
- if (input instanceof Uint8Array) {
4385
- const result = this.encode(input);
4386
- if (result instanceof Uint8Array) return createDigest(result, this.code, options?.truncate);
4387
- return result.then((digest) => createDigest(digest, this.code, options?.truncate));
4388
- } else throw Error("Unknown type, must be binary type");
4389
- }
4390
- };
4391
- /**
4392
- * Create a Digest from the passed uint8array and code, optionally truncating it
4393
- * first.
4394
- */
4395
- function createDigest(digest, code, truncate) {
4396
- if (truncate != null && truncate !== digest.byteLength) {
4397
- if (truncate > digest.byteLength) throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`);
4398
- digest = digest.subarray(0, truncate);
4399
- }
4400
- return create(code, digest);
4401
- }
4402
- //#endregion
4403
- //#region ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/sha2.js
4404
- var sha256 = from({
4405
- name: "sha2-256",
4406
- code: 18,
4407
- encode: (input) => coerce(crypto.createHash("sha256").update(input).digest())
4408
- });
4409
- from({
4410
- name: "sha2-512",
4411
- code: 19,
4412
- encode: (input) => coerce(crypto.createHash("sha512").update(input).digest())
4413
- });
4414
- //#endregion
4415
- //#region ../crypto-service/src/json-cid.ts
4416
- /**
4417
- * Generic JSON CID — CIDv1 for arbitrary JSON-serialisable values.
4418
- *
4419
- * Uses the dag-json codec and sha2-256, producing a base32lower CIDv1.
4420
- * Suitable for content-addressing task inputs, schema objects, and other
4421
- * JSON payloads that don't need diary-entry canonical normalisation.
4422
- */
4423
- async function computeJsonCid(value) {
4424
- const bytes = encode(value);
4425
- const hash = await sha256.digest(bytes);
4426
- return CID.create(1, 512, hash).toString();
4423
+ };
4427
4424
  }
4428
4425
  //#endregion
4429
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/is.js
4430
- var objectTypeNames = [
4431
- "Object",
4432
- "RegExp",
4433
- "Date",
4434
- "Error",
4435
- "Map",
4436
- "Set",
4437
- "WeakMap",
4438
- "WeakSet",
4439
- "ArrayBuffer",
4440
- "SharedArrayBuffer",
4441
- "DataView",
4442
- "Promise",
4443
- "URL",
4444
- "HTMLElement",
4445
- "Int8Array",
4446
- "Uint8ClampedArray",
4447
- "Int16Array",
4448
- "Uint16Array",
4449
- "Int32Array",
4450
- "Uint32Array",
4451
- "Float32Array",
4452
- "Float64Array",
4453
- "BigInt64Array",
4454
- "BigUint64Array"
4455
- ];
4456
- /**
4457
- * @param {any} value
4458
- * @returns {string}
4459
- */
4460
- function is(value) {
4461
- if (value === null) return "null";
4462
- if (value === void 0) return "undefined";
4463
- if (value === true || value === false) return "boolean";
4464
- const typeOf = typeof value;
4465
- if (typeOf === "string" || typeOf === "number" || typeOf === "bigint" || typeOf === "symbol") return typeOf;
4466
- /* c8 ignore next 3 */
4467
- if (typeOf === "function") return "Function";
4468
- if (Array.isArray(value)) return "Array";
4469
- if (value instanceof Uint8Array) return "Uint8Array";
4470
- if (value.constructor === Object) return "Object";
4471
- const objectType = getObjectType(value);
4472
- if (objectType) return objectType;
4473
- /* c8 ignore next */
4474
- return "Object";
4475
- }
4476
- /**
4477
- * @param {any} value
4478
- * @returns {string|undefined}
4479
- */
4480
- function getObjectType(value) {
4481
- const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
4482
- if (objectTypeNames.includes(objectTypeName)) return objectTypeName;
4426
+ //#region ../sdk/src/namespaces/legreffier.ts
4427
+ function createLegreffierNamespace(context) {
4428
+ const { client } = context;
4429
+ return {
4430
+ async startOnboarding(body) {
4431
+ return unwrapResult(await startLegreffierOnboarding({
4432
+ client,
4433
+ body
4434
+ }));
4435
+ },
4436
+ async getOnboardingStatus(workflowId) {
4437
+ return unwrapResult(await getLegreffierOnboardingStatus({
4438
+ client,
4439
+ path: { workflowId }
4440
+ }));
4441
+ }
4442
+ };
4483
4443
  }
4484
4444
  //#endregion
4485
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/token.js
4486
- var Type$2 = class {
4487
- /**
4488
- * @param {number} major
4489
- * @param {string} name
4490
- * @param {boolean} terminal
4491
- */
4492
- constructor(major, name, terminal) {
4493
- this.major = major;
4494
- this.majorEncoded = major << 5;
4495
- this.name = name;
4496
- this.terminal = terminal;
4497
- }
4498
- /* c8 ignore next 3 */
4499
- toString() {
4500
- return `Type[${this.major}].${this.name}`;
4501
- }
4502
- /**
4503
- * @param {Type} typ
4504
- * @returns {number}
4505
- */
4506
- compare(typ) {
4507
- /* c8 ignore next 1 */
4508
- return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
4509
- }
4510
- /**
4511
- * Check equality between two Type instances. Safe to use across different
4512
- * copies of the Type class (e.g., when bundlers duplicate the module).
4513
- * (major, name) uniquely identifies a Type; terminal is implied by these.
4514
- * @param {Type} a
4515
- * @param {Type} b
4516
- * @returns {boolean}
4517
- */
4518
- static equals(a, b) {
4519
- return a === b || a.major === b.major && a.name === b.name;
4520
- }
4521
- };
4522
- Type$2.uint = new Type$2(0, "uint", true);
4523
- Type$2.negint = new Type$2(1, "negint", true);
4524
- Type$2.bytes = new Type$2(2, "bytes", true);
4525
- Type$2.string = new Type$2(3, "string", true);
4526
- Type$2.array = new Type$2(4, "array", false);
4527
- Type$2.map = new Type$2(5, "map", false);
4528
- Type$2.tag = new Type$2(6, "tag", false);
4529
- Type$2.float = new Type$2(7, "float", true);
4530
- Type$2.false = new Type$2(7, "false", true);
4531
- Type$2.true = new Type$2(7, "true", true);
4532
- Type$2.null = new Type$2(7, "null", true);
4533
- Type$2.undefined = new Type$2(7, "undefined", true);
4534
- Type$2.break = new Type$2(7, "break", true);
4535
- var Token = class {
4536
- /**
4537
- * @param {Type} type
4538
- * @param {any} [value]
4539
- * @param {number} [encodedLength]
4540
- */
4541
- constructor(type, value, encodedLength) {
4542
- this.type = type;
4543
- this.value = value;
4544
- this.encodedLength = encodedLength;
4545
- /** @type {Uint8Array|undefined} */
4546
- this.encodedBytes = void 0;
4547
- /** @type {Uint8Array|undefined} */
4548
- this.byteValue = void 0;
4549
- }
4550
- /* c8 ignore next 3 */
4551
- toString() {
4552
- return `Token[${this.type}].${this.value}`;
4553
- }
4554
- };
4445
+ //#region ../sdk/src/namespaces/packs.ts
4446
+ function createPacksNamespace(context) {
4447
+ const { client, auth } = context;
4448
+ return {
4449
+ async get(id, query) {
4450
+ return unwrapResult(await getContextPackById({
4451
+ client,
4452
+ auth,
4453
+ path: { id },
4454
+ query
4455
+ }));
4456
+ },
4457
+ async list(selector) {
4458
+ if ("diaryId" in selector) {
4459
+ const { diaryId, ...query } = selector;
4460
+ return unwrapResult(await listDiaryPacks({
4461
+ client,
4462
+ auth,
4463
+ path: { id: diaryId },
4464
+ query
4465
+ }));
4466
+ }
4467
+ const { containsEntry, ...query } = selector;
4468
+ return unwrapResult(await listContextPacks({
4469
+ client,
4470
+ auth,
4471
+ query: {
4472
+ ...query,
4473
+ containsEntry
4474
+ }
4475
+ }));
4476
+ },
4477
+ async getProvenance(id, query) {
4478
+ return unwrapResult(await getContextPackProvenanceById({
4479
+ client,
4480
+ auth,
4481
+ path: { id },
4482
+ query
4483
+ }));
4484
+ },
4485
+ async getProvenanceByCid(cid, query) {
4486
+ return unwrapResult(await getContextPackProvenanceByCid({
4487
+ client,
4488
+ auth,
4489
+ path: { cid },
4490
+ query
4491
+ }));
4492
+ },
4493
+ async previewRendered(id, body) {
4494
+ return unwrapResult(await previewRenderedPack({
4495
+ client,
4496
+ auth,
4497
+ path: { id },
4498
+ body
4499
+ }));
4500
+ },
4501
+ async render(id, body) {
4502
+ return unwrapResult(await renderContextPack({
4503
+ client,
4504
+ auth,
4505
+ path: { id },
4506
+ body
4507
+ }));
4508
+ },
4509
+ async getLatestRendered(id, query) {
4510
+ return unwrapResult(await getLatestRenderedPack({
4511
+ client,
4512
+ auth,
4513
+ path: { id },
4514
+ query
4515
+ }));
4516
+ },
4517
+ async listRendered(diaryId, query) {
4518
+ return unwrapResult(await listDiaryRenderedPacks({
4519
+ client,
4520
+ auth,
4521
+ path: { id: diaryId },
4522
+ query
4523
+ }));
4524
+ },
4525
+ async getRendered(id, query) {
4526
+ return unwrapResult(await getRenderedPackById({
4527
+ client,
4528
+ auth,
4529
+ path: { id },
4530
+ query
4531
+ }));
4532
+ },
4533
+ async update(id, body) {
4534
+ return unwrapResult(await updateContextPack({
4535
+ client,
4536
+ auth,
4537
+ path: { id },
4538
+ body
4539
+ }));
4540
+ },
4541
+ async updateRendered(id, body) {
4542
+ return unwrapResult(await updateRenderedPack({
4543
+ client,
4544
+ auth,
4545
+ path: { id },
4546
+ body
4547
+ }));
4548
+ },
4549
+ async create(diaryId, body) {
4550
+ return unwrapResult(await createDiaryCustomPack({
4551
+ client,
4552
+ auth,
4553
+ path: { id: diaryId },
4554
+ body
4555
+ }));
4556
+ },
4557
+ async preview(diaryId, body) {
4558
+ return unwrapResult(await previewDiaryCustomPack({
4559
+ client,
4560
+ auth,
4561
+ path: { id: diaryId },
4562
+ body
4563
+ }));
4564
+ }
4565
+ };
4566
+ }
4555
4567
  //#endregion
4556
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/byte-utils.js
4557
- var useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === "function";
4558
- var textEncoder = new TextEncoder();
4559
- /**
4560
- * @param {Uint8Array} buf
4561
- * @returns {boolean}
4562
- */
4563
- function isBuffer(buf) {
4564
- return useBuffer && globalThis.Buffer.isBuffer(buf);
4568
+ //#region ../sdk/src/namespaces/problems.ts
4569
+ function createProblemsNamespace(context) {
4570
+ const { client } = context;
4571
+ return {
4572
+ async list() {
4573
+ return unwrapRequired(await listProblemTypes({ client }), "Failed to list problem types", "PROBLEMS_FAILED");
4574
+ },
4575
+ async get(type) {
4576
+ return unwrapRequired(await getProblemType({
4577
+ client,
4578
+ path: { type }
4579
+ }), `Failed to get problem type: ${type}`, "PROBLEM_TYPE_FAILED");
4580
+ }
4581
+ };
4565
4582
  }
4566
- /**
4567
- * @param {Uint8Array|number[]} buf
4568
- * @returns {Uint8Array}
4569
- */
4570
- function asU8A(buf) {
4571
- /* c8 ignore next */
4572
- if (!(buf instanceof Uint8Array)) return Uint8Array.from(buf);
4573
- return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;
4583
+ //#endregion
4584
+ //#region ../sdk/src/namespaces/public.ts
4585
+ function createPublicNamespace(context) {
4586
+ const { client } = context;
4587
+ return {
4588
+ async feed(query) {
4589
+ return unwrapResult(await getPublicFeed({
4590
+ client,
4591
+ query
4592
+ }));
4593
+ },
4594
+ async searchFeed(query) {
4595
+ return unwrapResult(await searchPublicFeed({
4596
+ client,
4597
+ query
4598
+ }));
4599
+ },
4600
+ async entry(id) {
4601
+ return unwrapResult(await getPublicEntry({
4602
+ client,
4603
+ path: { id }
4604
+ }));
4605
+ },
4606
+ async networkInfo() {
4607
+ return unwrapRequired(await getNetworkInfo({ client }), "Failed to fetch network info", "NETWORK_INFO_FAILED");
4608
+ },
4609
+ async llmsTxt() {
4610
+ return unwrapRequired(await getLlmsTxt({ client }), "Failed to fetch llms.txt", "LLMS_TXT_FAILED");
4611
+ },
4612
+ async health() {
4613
+ return unwrapRequired(await getHealth({ client }), "Failed to fetch health", "HEALTH_FAILED");
4614
+ }
4615
+ };
4574
4616
  }
4575
- var FROM_STRING_THRESHOLD_BUFFER = 24;
4576
- var FROM_STRING_THRESHOLD_TEXTENCODER = 200;
4577
- var fromString = useBuffer ? (string) => {
4578
- return string.length >= FROM_STRING_THRESHOLD_BUFFER ? globalThis.Buffer.from(string) : utf8ToBytes(string);
4579
- } : (string) => {
4580
- return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string);
4581
- };
4582
- /**
4583
- * Buffer variant not fast enough for what we need
4584
- * @param {number[]} arr
4585
- * @returns {Uint8Array}
4586
- */
4587
- var fromArray = (arr) => {
4588
- return Uint8Array.from(arr);
4589
- };
4590
- var slice = useBuffer ? (bytes, start, end) => {
4591
- if (isBuffer(bytes)) return new Uint8Array(bytes.subarray(start, end));
4592
- return bytes.slice(start, end);
4593
- } : (bytes, start, end) => {
4594
- return bytes.slice(start, end);
4595
- };
4596
- var concat = useBuffer ? (chunks, length) => {
4597
- /* c8 ignore next 1 */
4598
- chunks = chunks.map((c) => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));
4599
- return asU8A(globalThis.Buffer.concat(chunks, length));
4600
- } : (chunks, length) => {
4601
- const out = new Uint8Array(length);
4602
- let off = 0;
4603
- for (let b of chunks) {
4604
- if (off + b.length > out.length) b = b.subarray(0, out.length - off);
4605
- out.set(b, off);
4606
- off += b.length;
4607
- }
4608
- return out;
4609
- };
4610
- var alloc = useBuffer ? (size) => {
4611
- return globalThis.Buffer.allocUnsafe(size);
4612
- } : (size) => {
4613
- return new Uint8Array(size);
4614
- };
4615
- /**
4616
- * @param {Uint8Array} b1
4617
- * @param {Uint8Array} b2
4618
- * @returns {number}
4619
- */
4620
- function compare(b1, b2) {
4621
- /* c8 ignore next 5 */
4622
- if (isBuffer(b1) && isBuffer(b2)) return b1.compare(b2);
4623
- for (let i = 0; i < b1.length; i++) {
4624
- if (b1[i] === b2[i]) continue;
4625
- return b1[i] < b2[i] ? -1 : 1;
4626
- }
4627
- return 0;
4628
- }
4629
- /**
4630
- * @param {string} str
4631
- * @returns {number[]}
4632
- */
4633
- function utf8ToBytes(str) {
4634
- const out = [];
4635
- let p = 0;
4636
- for (let i = 0; i < str.length; i++) {
4637
- let c = str.charCodeAt(i);
4638
- if (c < 128) out[p++] = c;
4639
- else if (c < 2048) {
4640
- out[p++] = c >> 6 | 192;
4641
- out[p++] = c & 63 | 128;
4642
- } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
4643
- c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
4644
- out[p++] = c >> 18 | 240;
4645
- out[p++] = c >> 12 & 63 | 128;
4646
- out[p++] = c >> 6 & 63 | 128;
4647
- out[p++] = c & 63 | 128;
4648
- } else {
4649
- if (c >= 55296 && c <= 57343) c = 65533;
4650
- out[p++] = c >> 12 | 224;
4651
- out[p++] = c >> 6 & 63 | 128;
4652
- out[p++] = c & 63 | 128;
4617
+ //#endregion
4618
+ //#region ../sdk/src/namespaces/recovery.ts
4619
+ function createRecoveryNamespace(context) {
4620
+ const { client } = context;
4621
+ return {
4622
+ async requestChallenge(body) {
4623
+ return unwrapResult(await requestRecoveryChallenge({
4624
+ client,
4625
+ body
4626
+ }));
4627
+ },
4628
+ async verifyChallenge(body) {
4629
+ return unwrapResult(await verifyRecoveryChallenge({
4630
+ client,
4631
+ body
4632
+ }));
4653
4633
  }
4654
- }
4655
- return out;
4634
+ };
4656
4635
  }
4657
4636
  //#endregion
4658
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/bl.js
4659
- /**
4660
- * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
4661
- * writing rather than reading.
4662
- * A Bl object accepts set() operations for individual bytes and copyTo() for
4663
- * inserting byte arrays. These write operations don't automatically increment
4664
- * the internal cursor so its "length" won't be changed. Instead, increment()
4665
- * must be called to extend its length to cover the inserted data.
4666
- * The toBytes() call will convert all internal memory to a single Uint8Array of
4667
- * the correct length, truncating any data that is stored but hasn't been
4668
- * included by an increment().
4669
- * get() can retrieve a single byte.
4670
- * All operations (except toBytes()) take an "offset" argument that will perform
4671
- * the write at the offset _from the current cursor_. For most operations this
4672
- * will be `0` to write at the current cursor position but it can be ahead of
4673
- * the current cursor. Negative offsets probably work but are untested.
4674
- */
4675
- var defaultChunkSize = 256;
4676
- var Bl = class {
4677
- /**
4678
- * @param {number} [chunkSize]
4679
- */
4680
- constructor(chunkSize = defaultChunkSize) {
4681
- this.chunkSize = chunkSize;
4682
- /** @type {number} */
4683
- this.cursor = 0;
4684
- /** @type {number} */
4685
- this.maxCursor = -1;
4686
- /** @type {(Uint8Array|number[])[]} */
4687
- this.chunks = [];
4688
- /** @type {Uint8Array|number[]|null} */
4689
- this._initReuseChunk = null;
4690
- }
4691
- reset() {
4692
- this.cursor = 0;
4693
- this.maxCursor = -1;
4694
- if (this.chunks.length) this.chunks = [];
4695
- if (this._initReuseChunk !== null) {
4696
- this.chunks.push(this._initReuseChunk);
4697
- this.maxCursor = this._initReuseChunk.length - 1;
4698
- }
4699
- }
4700
- /**
4701
- * @param {Uint8Array|number[]} bytes
4702
- */
4703
- push(bytes) {
4704
- let topChunk = this.chunks[this.chunks.length - 1];
4705
- if (this.cursor + bytes.length <= this.maxCursor + 1) {
4706
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
4707
- topChunk.set(bytes, chunkPos);
4708
- } else {
4709
- if (topChunk) {
4710
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
4711
- if (chunkPos < topChunk.length) {
4712
- this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
4713
- this.maxCursor = this.cursor - 1;
4714
- }
4715
- }
4716
- if (bytes.length < 64 && bytes.length < this.chunkSize) {
4717
- topChunk = alloc(this.chunkSize);
4718
- this.chunks.push(topChunk);
4719
- this.maxCursor += topChunk.length;
4720
- if (this._initReuseChunk === null) this._initReuseChunk = topChunk;
4721
- topChunk.set(bytes, 0);
4722
- } else {
4723
- this.chunks.push(bytes);
4724
- this.maxCursor += bytes.length;
4725
- }
4637
+ //#region ../sdk/src/namespaces/signing-requests.ts
4638
+ function createSigningRequestsNamespace(context) {
4639
+ const { client, auth } = context;
4640
+ return {
4641
+ async list(query) {
4642
+ return unwrapResult(await listSigningRequests({
4643
+ client,
4644
+ auth,
4645
+ query
4646
+ }));
4647
+ },
4648
+ async create(body) {
4649
+ return unwrapResult(await createSigningRequest({
4650
+ client,
4651
+ auth,
4652
+ body
4653
+ }));
4654
+ },
4655
+ async get(id) {
4656
+ return unwrapResult(await getSigningRequest({
4657
+ client,
4658
+ auth,
4659
+ path: { id }
4660
+ }));
4661
+ },
4662
+ async submit(id, body) {
4663
+ return unwrapResult(await submitSignature({
4664
+ client,
4665
+ auth,
4666
+ path: { id },
4667
+ body
4668
+ }));
4726
4669
  }
4727
- this.cursor += bytes.length;
4728
- }
4729
- /**
4730
- * @param {boolean} [reset]
4731
- * @returns {Uint8Array}
4732
- */
4733
- toBytes(reset = false) {
4734
- let byts;
4735
- if (this.chunks.length === 1) {
4736
- const chunk = this.chunks[0];
4737
- if (reset && this.cursor > chunk.length / 2) {
4738
- /* c8 ignore next 2 */
4739
- byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
4740
- this._initReuseChunk = null;
4741
- this.chunks = [];
4742
- } else byts = slice(chunk, 0, this.cursor);
4743
- } else byts = concat(this.chunks, this.cursor);
4744
- if (reset) this.reset();
4745
- return byts;
4746
- }
4747
- };
4748
- /**
4749
- * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
4750
- * It provides the same interface as Bl but writes to a fixed destination.
4751
- */
4752
- var U8Bl = class {
4753
- /**
4754
- * @param {Uint8Array} dest
4755
- */
4756
- constructor(dest) {
4757
- this.dest = dest;
4758
- /** @type {number} */
4759
- this.cursor = 0;
4760
- /** @type {Uint8Array[]} */
4761
- this.chunks = [dest];
4762
- }
4763
- reset() {
4764
- this.cursor = 0;
4765
- }
4766
- /**
4767
- * @param {Uint8Array|number[]} bytes
4768
- */
4769
- push(bytes) {
4770
- if (this.cursor + bytes.length > this.dest.length) throw new Error("write out of bounds, destination buffer is too small");
4771
- this.dest.set(bytes, this.cursor);
4772
- this.cursor += bytes.length;
4773
- }
4774
- /**
4775
- * @param {boolean} [reset]
4776
- * @returns {Uint8Array}
4777
- */
4778
- toBytes(reset = false) {
4779
- const byts = this.dest.subarray(0, this.cursor);
4780
- if (reset) this.reset();
4781
- return byts;
4782
- }
4783
- };
4670
+ };
4671
+ }
4784
4672
  //#endregion
4785
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/common.js
4786
- var decodeErrPrefix = "CBOR decode error:";
4787
- var encodeErrPrefix = "CBOR encode error:";
4788
- var uintMinorPrefixBytes = [];
4789
- uintMinorPrefixBytes[23] = 1;
4790
- uintMinorPrefixBytes[24] = 2;
4791
- uintMinorPrefixBytes[25] = 3;
4792
- uintMinorPrefixBytes[26] = 5;
4793
- uintMinorPrefixBytes[27] = 9;
4794
- /**
4795
- * @param {Uint8Array} data
4796
- * @param {number} pos
4797
- * @param {number} need
4798
- */
4799
- function assertEnoughData(data, pos, need) {
4800
- if (data.length - pos < need) throw new Error(`${decodeErrPrefix} not enough data for type`);
4673
+ //#region ../sdk/src/namespaces/tasks.ts
4674
+ function createTasksNamespace(context) {
4675
+ const { client, auth } = context;
4676
+ return {
4677
+ async schemas() {
4678
+ return unwrapResult(await listTaskSchemas({
4679
+ client,
4680
+ auth
4681
+ }));
4682
+ },
4683
+ async list(query) {
4684
+ return unwrapResult(await listTasks({
4685
+ client,
4686
+ auth,
4687
+ query
4688
+ }));
4689
+ },
4690
+ async create(body) {
4691
+ return unwrapResult(await createTask({
4692
+ client,
4693
+ auth,
4694
+ body
4695
+ }));
4696
+ },
4697
+ async get(id) {
4698
+ return unwrapResult(await getTask({
4699
+ client,
4700
+ auth,
4701
+ path: { id }
4702
+ }));
4703
+ },
4704
+ async claim(id, body) {
4705
+ const result = await claimTask({
4706
+ client,
4707
+ auth,
4708
+ path: { id },
4709
+ body
4710
+ });
4711
+ const data = unwrapResult(result);
4712
+ const traceHeaders = {};
4713
+ const traceparent = result.response.headers.get("traceparent");
4714
+ if (traceparent) {
4715
+ traceHeaders["traceparent"] = traceparent;
4716
+ const tracestate = result.response.headers.get("tracestate");
4717
+ if (tracestate) traceHeaders["tracestate"] = tracestate;
4718
+ }
4719
+ return {
4720
+ ...data,
4721
+ traceHeaders
4722
+ };
4723
+ },
4724
+ async heartbeat(id, n, body) {
4725
+ return unwrapResult(await taskHeartbeat({
4726
+ client,
4727
+ auth,
4728
+ path: {
4729
+ id,
4730
+ n
4731
+ },
4732
+ body
4733
+ }));
4734
+ },
4735
+ async complete(id, n, body) {
4736
+ return unwrapResult(await completeTask({
4737
+ client,
4738
+ auth,
4739
+ path: {
4740
+ id,
4741
+ n
4742
+ },
4743
+ body
4744
+ }));
4745
+ },
4746
+ async fail(id, n, body) {
4747
+ return unwrapResult(await failTask({
4748
+ client,
4749
+ auth,
4750
+ path: {
4751
+ id,
4752
+ n
4753
+ },
4754
+ body
4755
+ }));
4756
+ },
4757
+ async cancel(id, body) {
4758
+ return unwrapResult(await cancelTask({
4759
+ client,
4760
+ auth,
4761
+ path: { id },
4762
+ body
4763
+ }));
4764
+ },
4765
+ async listAttempts(id) {
4766
+ return unwrapResult(await listTaskAttempts({
4767
+ client,
4768
+ auth,
4769
+ path: { id }
4770
+ }));
4771
+ },
4772
+ async listMessages(id, n, query) {
4773
+ return unwrapResult(await listTaskMessages({
4774
+ client,
4775
+ auth,
4776
+ path: {
4777
+ id,
4778
+ n
4779
+ },
4780
+ query
4781
+ }));
4782
+ },
4783
+ async appendMessages(id, n, body) {
4784
+ return unwrapResult(await appendTaskMessages({
4785
+ client,
4786
+ auth,
4787
+ path: {
4788
+ id,
4789
+ n
4790
+ },
4791
+ body
4792
+ }));
4793
+ }
4794
+ };
4801
4795
  }
4802
4796
  //#endregion
4803
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/0uint.js
4804
- var uintBoundaries = [
4805
- 24,
4806
- 256,
4807
- 65536,
4808
- 4294967296,
4809
- BigInt("18446744073709551616")
4810
- ];
4811
- /**
4812
- * @typedef {import('../interface').ByteWriter} ByteWriter
4813
- * @typedef {import('../interface').DecodeOptions} DecodeOptions
4814
- */
4815
- /**
4816
- * @param {Uint8Array} data
4817
- * @param {number} offset
4818
- * @param {DecodeOptions} options
4819
- * @returns {number}
4820
- */
4821
- function readUint8(data, offset, options) {
4822
- assertEnoughData(data, offset, 1);
4823
- const value = data[offset];
4824
- if (options.strict === true && value < uintBoundaries[0]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
4825
- return value;
4826
- }
4827
- /**
4828
- * @param {Uint8Array} data
4829
- * @param {number} offset
4830
- * @param {DecodeOptions} options
4831
- * @returns {number}
4832
- */
4833
- function readUint16(data, offset, options) {
4834
- assertEnoughData(data, offset, 2);
4835
- const value = data[offset] << 8 | data[offset + 1];
4836
- if (options.strict === true && value < uintBoundaries[1]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
4837
- return value;
4797
+ //#region ../sdk/src/namespaces/teams.ts
4798
+ function createTeamsNamespace(context) {
4799
+ const { client, auth } = context;
4800
+ return {
4801
+ async list() {
4802
+ return unwrapResult(await listTeams({
4803
+ client,
4804
+ auth
4805
+ }));
4806
+ },
4807
+ async get(id) {
4808
+ return unwrapResult(await getTeam({
4809
+ client,
4810
+ auth,
4811
+ path: { id }
4812
+ }));
4813
+ },
4814
+ async listMembers(id) {
4815
+ return unwrapResult(await listTeamMembers({
4816
+ client,
4817
+ auth,
4818
+ path: { id }
4819
+ }));
4820
+ },
4821
+ async create(body) {
4822
+ return unwrapResult(await createTeam({
4823
+ client,
4824
+ auth,
4825
+ body
4826
+ }));
4827
+ },
4828
+ async join(code) {
4829
+ return unwrapResult(await joinTeam({
4830
+ client,
4831
+ auth,
4832
+ body: { code }
4833
+ }));
4834
+ },
4835
+ async delete(id) {
4836
+ return unwrapResult(await deleteTeam({
4837
+ client,
4838
+ auth,
4839
+ path: { id }
4840
+ }));
4841
+ },
4842
+ async removeMember(teamId, subjectId) {
4843
+ return unwrapResult(await removeTeamMember({
4844
+ client,
4845
+ auth,
4846
+ path: {
4847
+ id: teamId,
4848
+ subjectId
4849
+ }
4850
+ }));
4851
+ },
4852
+ invites: {
4853
+ async create(teamId, body) {
4854
+ return unwrapResult(await createTeamInvite({
4855
+ client,
4856
+ auth,
4857
+ path: { id: teamId },
4858
+ body
4859
+ }));
4860
+ },
4861
+ async list(teamId) {
4862
+ return unwrapResult(await listTeamInvites({
4863
+ client,
4864
+ auth,
4865
+ path: { id: teamId }
4866
+ }));
4867
+ },
4868
+ async delete(teamId, inviteId) {
4869
+ return unwrapResult(await deleteTeamInvite({
4870
+ client,
4871
+ auth,
4872
+ path: {
4873
+ id: teamId,
4874
+ inviteId
4875
+ }
4876
+ }));
4877
+ }
4878
+ }
4879
+ };
4838
4880
  }
4839
- /**
4840
- * @param {Uint8Array} data
4841
- * @param {number} offset
4842
- * @param {DecodeOptions} options
4843
- * @returns {number}
4844
- */
4845
- function readUint32(data, offset, options) {
4846
- assertEnoughData(data, offset, 4);
4847
- const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
4848
- if (options.strict === true && value < uintBoundaries[2]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
4849
- return value;
4881
+ //#endregion
4882
+ //#region ../sdk/src/namespaces/vouch.ts
4883
+ function createVouchNamespace(context) {
4884
+ const { client, auth } = context;
4885
+ return {
4886
+ async issue() {
4887
+ return unwrapResult(await issueVoucher({
4888
+ client,
4889
+ auth
4890
+ }));
4891
+ },
4892
+ async listActive() {
4893
+ return unwrapResult(await listActiveVouchers({
4894
+ client,
4895
+ auth
4896
+ }));
4897
+ },
4898
+ async trustGraph(query) {
4899
+ return unwrapResult(await getTrustGraph({
4900
+ client,
4901
+ query
4902
+ }));
4903
+ }
4904
+ };
4850
4905
  }
4851
- /**
4852
- * @param {Uint8Array} data
4853
- * @param {number} offset
4854
- * @param {DecodeOptions} options
4855
- * @returns {number|bigint}
4856
- */
4857
- function readUint64(data, offset, options) {
4858
- assertEnoughData(data, offset, 8);
4859
- const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
4860
- const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
4861
- const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
4862
- if (options.strict === true && value < uintBoundaries[3]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
4863
- if (value <= Number.MAX_SAFE_INTEGER) return Number(value);
4864
- if (options.allowBigInt === true) return value;
4865
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
4906
+ //#endregion
4907
+ //#region ../sdk/src/agent.ts
4908
+ function createAgent(options) {
4909
+ const { client, tokenManager, auth } = options;
4910
+ const context = {
4911
+ client,
4912
+ auth
4913
+ };
4914
+ return {
4915
+ diaries: createDiariesNamespace(context),
4916
+ diaryGrants: createDiaryGrantsNamespace(context),
4917
+ packs: createPacksNamespace(context),
4918
+ entries: createEntriesNamespace(context),
4919
+ agents: createAgentsNamespace(context),
4920
+ crypto: createCryptoNamespace(context, createSigningRequestsNamespace(context)),
4921
+ vouch: createVouchNamespace(context),
4922
+ auth: createAuthNamespace(context),
4923
+ recovery: createRecoveryNamespace(context),
4924
+ public: createPublicNamespace(context),
4925
+ legreffier: createLegreffierNamespace(context),
4926
+ problems: createProblemsNamespace(context),
4927
+ teams: createTeamsNamespace(context),
4928
+ tasks: createTasksNamespace(context),
4929
+ client,
4930
+ getToken: () => tokenManager.getToken()
4931
+ };
4866
4932
  }
4933
+ //#endregion
4934
+ //#region ../sdk/src/config.ts
4867
4935
  /**
4868
- * @param {Uint8Array} data
4869
- * @param {number} pos
4870
- * @param {number} _minor
4871
- * @param {DecodeOptions} options
4872
- * @returns {Token}
4936
+ * Read MoltNet credentials from environment variables.
4937
+ * Reads MOLTNET_CLIENT_ID, MOLTNET_CLIENT_SECRET, and MOLTNET_API_URL.
4873
4938
  */
4874
- function decodeUint8(data, pos, _minor, options) {
4875
- return new Token(Type$2.uint, readUint8(data, pos + 1, options), 2);
4939
+ function readEnvCredentials() {
4940
+ return {
4941
+ clientId: process.env.MOLTNET_CLIENT_ID,
4942
+ clientSecret: process.env.MOLTNET_CLIENT_SECRET,
4943
+ apiUrl: process.env.MOLTNET_API_URL
4944
+ };
4876
4945
  }
4877
- /**
4878
- * @param {Uint8Array} data
4879
- * @param {number} pos
4880
- * @param {number} _minor
4881
- * @param {DecodeOptions} options
4882
- * @returns {Token}
4883
- */
4884
- function decodeUint16(data, pos, _minor, options) {
4885
- return new Token(Type$2.uint, readUint16(data, pos + 1, options), 3);
4946
+ //#endregion
4947
+ //#region ../sdk/src/credentials.ts
4948
+ function getConfigDir() {
4949
+ return join(homedir(), ".config", "moltnet");
4886
4950
  }
4887
4951
  /**
4888
- * @param {Uint8Array} data
4889
- * @param {number} pos
4890
- * @param {number} _minor
4891
- * @param {DecodeOptions} options
4892
- * @returns {Token}
4952
+ * Read the MoltNet config file.
4953
+ * Tries `moltnet.json` first; falls back to `credentials.json` with a
4954
+ * deprecation warning printed to stderr.
4893
4955
  */
4894
- function decodeUint32(data, pos, _minor, options) {
4895
- return new Token(Type$2.uint, readUint32(data, pos + 1, options), 5);
4956
+ async function readConfig(configDir) {
4957
+ const dir = configDir ?? getConfigDir();
4958
+ try {
4959
+ const content = await readFile(join(dir, "moltnet.json"), "utf-8");
4960
+ return JSON.parse(content);
4961
+ } catch {}
4962
+ try {
4963
+ const content = await readFile(join(dir, "credentials.json"), "utf-8");
4964
+ console.warn("Warning: credentials.json is deprecated. New writes use moltnet.json. Support will be removed in 3 minor versions.");
4965
+ return JSON.parse(content);
4966
+ } catch {
4967
+ return null;
4968
+ }
4896
4969
  }
4970
+ //#endregion
4971
+ //#region ../sdk/src/retry.ts
4972
+ var AUTH_RETRY_DEFAULT = 1;
4897
4973
  /**
4898
- * @param {Uint8Array} data
4899
- * @param {number} pos
4900
- * @param {number} _minor
4901
- * @param {DecodeOptions} options
4902
- * @returns {Token}
4974
+ * Create a fetch wrapper that retries on 401 and 429.
4975
+ *
4976
+ * - **401**: Invalidates the cached token, re-authenticates, replays once.
4977
+ * - **429**: Delegates to `createRateLimitFetch` from `@moltnet/api-client/retry`.
4978
+ *
4979
+ * 5xx and network errors are not retried — non-idempotent methods (POST, PATCH)
4980
+ * could cause duplicate side effects.
4903
4981
  */
4904
- function decodeUint64(data, pos, _minor, options) {
4905
- return new Token(Type$2.uint, readUint64(data, pos + 1, options), 9);
4982
+ function createRetryFetch(tokenManager, options) {
4983
+ const maxAuthRetries = options?.maxAuthRetries ?? AUTH_RETRY_DEFAULT;
4984
+ const rateLimitFetch = createRateLimitFetch({
4985
+ maxRetries: options?.maxRateLimitRetries,
4986
+ baseDelayMs: options?.baseDelayMs,
4987
+ maxDelayMs: options?.maxDelayMs
4988
+ });
4989
+ return async (input, init) => {
4990
+ let authRetries = 0;
4991
+ const doFetch = async (fetchInit) => {
4992
+ const response = await rateLimitFetch(input, fetchInit);
4993
+ if (response.status === 401 && authRetries < maxAuthRetries) {
4994
+ authRetries++;
4995
+ tokenManager.invalidate();
4996
+ const freshToken = await tokenManager.authenticate();
4997
+ const headers = new Headers(fetchInit?.headers);
4998
+ headers.set("Authorization", `Bearer ${freshToken}`);
4999
+ return doFetch({
5000
+ ...fetchInit,
5001
+ headers
5002
+ });
5003
+ }
5004
+ return response;
5005
+ };
5006
+ return doFetch(init);
5007
+ };
4906
5008
  }
4907
- /**
4908
- * @param {ByteWriter} writer
4909
- * @param {Token} token
4910
- */
4911
- function encodeUint(writer, token) {
4912
- return encodeUintValue(writer, 0, token.value);
5009
+ //#endregion
5010
+ //#region ../sdk/src/token.ts
5011
+ var TokenManager = class {
5012
+ clientId;
5013
+ clientSecret;
5014
+ tokenUrl;
5015
+ expiryBufferMs;
5016
+ cached = null;
5017
+ constructor(options) {
5018
+ const apiUrl = options.apiUrl.replace(/\/$/, "");
5019
+ this.clientId = options.clientId;
5020
+ this.clientSecret = options.clientSecret;
5021
+ this.tokenUrl = `${apiUrl}/oauth2/token`;
5022
+ this.expiryBufferMs = options.expiryBufferMs ?? 3e4;
5023
+ }
5024
+ /** Return a valid access token, obtaining or refreshing as needed. */
5025
+ async getToken() {
5026
+ if (this.cached && Date.now() < this.cached.expiresAt) return this.cached.accessToken;
5027
+ return this.authenticate();
5028
+ }
5029
+ /** Force-obtain a new token, replacing any cached value. */
5030
+ async authenticate() {
5031
+ const body = new URLSearchParams({
5032
+ grant_type: "client_credentials",
5033
+ client_id: this.clientId,
5034
+ client_secret: this.clientSecret
5035
+ });
5036
+ let response;
5037
+ try {
5038
+ response = await fetch(this.tokenUrl, {
5039
+ method: "POST",
5040
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
5041
+ body: body.toString()
5042
+ });
5043
+ } catch (error) {
5044
+ throw new NetworkError(error instanceof Error ? error.message : "Token request failed", { detail: error instanceof Error ? error.cause?.toString() : String(error) });
5045
+ }
5046
+ const json = await response.json();
5047
+ if (!response.ok || "error" in json) {
5048
+ const errBody = json;
5049
+ throw new AuthenticationError(errBody.error_description ?? errBody.error, {
5050
+ statusCode: response.status,
5051
+ detail: errBody.error
5052
+ });
5053
+ }
5054
+ const tokenBody = json;
5055
+ this.cached = {
5056
+ accessToken: tokenBody.access_token,
5057
+ expiresAt: Date.now() + tokenBody.expires_in * 1e3 - this.expiryBufferMs
5058
+ };
5059
+ return this.cached.accessToken;
5060
+ }
5061
+ /** Clear the cached token. Next getToken() call will re-authenticate. */
5062
+ invalidate() {
5063
+ this.cached = null;
5064
+ }
5065
+ };
5066
+ //#endregion
5067
+ //#region ../sdk/src/connect.ts
5068
+ var DEFAULT_API_URL = "https://api.themolt.net";
5069
+ async function resolveCredentials(options) {
5070
+ if (options.clientId && options.clientSecret) return {
5071
+ clientId: options.clientId,
5072
+ clientSecret: options.clientSecret,
5073
+ apiUrl: (options.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "")
5074
+ };
5075
+ const env = readEnvCredentials();
5076
+ if (env.clientId && env.clientSecret) return {
5077
+ clientId: env.clientId,
5078
+ clientSecret: env.clientSecret,
5079
+ apiUrl: (env.apiUrl ?? options.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "")
5080
+ };
5081
+ const config = await readConfig(options.configDir);
5082
+ if (config?.oauth2?.client_id && config?.oauth2?.client_secret) return {
5083
+ clientId: config.oauth2.client_id,
5084
+ clientSecret: config.oauth2.client_secret,
5085
+ apiUrl: (options.apiUrl ?? config.endpoints?.api ?? DEFAULT_API_URL).replace(/\/$/, "")
5086
+ };
5087
+ throw new MoltNetError("No credentials found. Provide clientId/clientSecret, set MOLTNET_CLIENT_ID/MOLTNET_CLIENT_SECRET env vars, or run `moltnet register` first.", { code: "NO_CREDENTIALS" });
4913
5088
  }
4914
5089
  /**
4915
- * @param {ByteWriter} writer
4916
- * @param {number} major
4917
- * @param {number|bigint} uint
5090
+ * Connect to MoltNet and return an authenticated Agent facade.
5091
+ *
5092
+ * Credential resolution order:
5093
+ * 1. Explicit `clientId` / `clientSecret` in options
5094
+ * 2. `MOLTNET_CLIENT_ID` / `MOLTNET_CLIENT_SECRET` environment variables
5095
+ * 3. Config file (`~/.config/moltnet/moltnet.json`)
4918
5096
  */
4919
- function encodeUintValue(writer, major, uint) {
4920
- if (uint < uintBoundaries[0]) {
4921
- const nuint = Number(uint);
4922
- writer.push([major | nuint]);
4923
- } else if (uint < uintBoundaries[1]) {
4924
- const nuint = Number(uint);
4925
- writer.push([major | 24, nuint]);
4926
- } else if (uint < uintBoundaries[2]) {
4927
- const nuint = Number(uint);
4928
- writer.push([
4929
- major | 25,
4930
- nuint >>> 8,
4931
- nuint & 255
4932
- ]);
4933
- } else if (uint < uintBoundaries[3]) {
4934
- const nuint = Number(uint);
4935
- writer.push([
4936
- major | 26,
4937
- nuint >>> 24 & 255,
4938
- nuint >>> 16 & 255,
4939
- nuint >>> 8 & 255,
4940
- nuint & 255
4941
- ]);
4942
- } else {
4943
- const buint = BigInt(uint);
4944
- if (buint < uintBoundaries[4]) {
4945
- const set = [
4946
- major | 27,
4947
- 0,
4948
- 0,
4949
- 0,
4950
- 0,
4951
- 0,
4952
- 0,
4953
- 0
4954
- ];
4955
- let lo = Number(buint & BigInt(4294967295));
4956
- let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
4957
- set[8] = lo & 255;
4958
- lo = lo >> 8;
4959
- set[7] = lo & 255;
4960
- lo = lo >> 8;
4961
- set[6] = lo & 255;
4962
- lo = lo >> 8;
4963
- set[5] = lo & 255;
4964
- set[4] = hi & 255;
4965
- hi = hi >> 8;
4966
- set[3] = hi & 255;
4967
- hi = hi >> 8;
4968
- set[2] = hi & 255;
4969
- hi = hi >> 8;
4970
- set[1] = hi & 255;
4971
- writer.push(set);
4972
- } else throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
4973
- }
5097
+ async function connect(options = {}) {
5098
+ const creds = await resolveCredentials(options);
5099
+ const autoToken = options.autoToken ?? true;
5100
+ const tokenManager = new TokenManager({
5101
+ clientId: creds.clientId,
5102
+ clientSecret: creds.clientSecret,
5103
+ apiUrl: creds.apiUrl
5104
+ });
5105
+ const retryFetch = autoToken && options.retry !== false ? createRetryFetch(tokenManager, options.retry === void 0 ? void 0 : options.retry) : void 0;
5106
+ const customFetch = retryFetch ?? (autoToken && !retryFetch ? async (input, init) => {
5107
+ const response = await fetch(input, init);
5108
+ if (response.status === 401) tokenManager.invalidate();
5109
+ return response;
5110
+ } : void 0);
5111
+ return createAgent({
5112
+ client: createClient({
5113
+ baseUrl: creds.apiUrl,
5114
+ ...customFetch && { fetch: customFetch }
5115
+ }),
5116
+ tokenManager,
5117
+ auth: autoToken ? () => tokenManager.getToken() : void 0
5118
+ });
4974
5119
  }
4975
- /**
4976
- * @param {Token} token
4977
- * @returns {number}
4978
- */
4979
- encodeUint.encodedSize = function encodedSize(token) {
4980
- return encodeUintValue.encodedSize(token.value);
5120
+ new TextEncoder();
5121
+ //#endregion
5122
+ //#region ../crypto-service/src/crypto.service.ts
5123
+ etc.sha512Sync = (...m) => {
5124
+ const hash = createHash$1("sha512");
5125
+ m.forEach((msg) => hash.update(msg));
5126
+ return hash.digest();
4981
5127
  };
5128
+ //#endregion
5129
+ //#region ../crypto-service/src/executor-attestation.ts
5130
+ etc.sha512Sync = (...m) => {
5131
+ const hash = createHash("sha512");
5132
+ m.forEach((msg) => hash.update(msg));
5133
+ return hash.digest();
5134
+ };
5135
+ //#endregion
5136
+ //#region ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/codecs/json.js
5137
+ var textEncoder$1 = new TextEncoder();
5138
+ new TextDecoder();
5139
+ function encode(node) {
5140
+ return textEncoder$1.encode(JSON.stringify(node));
5141
+ }
5142
+ //#endregion
5143
+ //#region ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/hasher.js
5144
+ var DEFAULT_MIN_DIGEST_LENGTH = 20;
5145
+ function from({ name, code, encode, minDigestLength, maxDigestLength }) {
5146
+ return new Hasher(name, code, encode, minDigestLength, maxDigestLength);
5147
+ }
4982
5148
  /**
4983
- * @param {number} uint
4984
- * @returns {number}
5149
+ * Hasher represents a hashing algorithm implementation that produces as
5150
+ * `MultihashDigest`.
4985
5151
  */
4986
- encodeUintValue.encodedSize = function encodedSize(uint) {
4987
- if (uint < uintBoundaries[0]) return 1;
4988
- if (uint < uintBoundaries[1]) return 2;
4989
- if (uint < uintBoundaries[2]) return 3;
4990
- if (uint < uintBoundaries[3]) return 5;
4991
- return 9;
5152
+ var Hasher = class {
5153
+ name;
5154
+ code;
5155
+ encode;
5156
+ minDigestLength;
5157
+ maxDigestLength;
5158
+ constructor(name, code, encode, minDigestLength, maxDigestLength) {
5159
+ this.name = name;
5160
+ this.code = code;
5161
+ this.encode = encode;
5162
+ this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH;
5163
+ this.maxDigestLength = maxDigestLength;
5164
+ }
5165
+ digest(input, options) {
5166
+ if (options?.truncate != null) {
5167
+ if (options.truncate < this.minDigestLength) throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);
5168
+ if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`);
5169
+ }
5170
+ if (input instanceof Uint8Array) {
5171
+ const result = this.encode(input);
5172
+ if (result instanceof Uint8Array) return createDigest(result, this.code, options?.truncate);
5173
+ return result.then((digest) => createDigest(digest, this.code, options?.truncate));
5174
+ } else throw Error("Unknown type, must be binary type");
5175
+ }
4992
5176
  };
4993
5177
  /**
4994
- * @param {Token} tok1
4995
- * @param {Token} tok2
4996
- * @returns {number}
5178
+ * Create a Digest from the passed uint8array and code, optionally truncating it
5179
+ * first.
4997
5180
  */
4998
- encodeUint.compareTokens = function compareTokens(tok1, tok2) {
4999
- return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;
5000
- };
5181
+ function createDigest(digest, code, truncate) {
5182
+ if (truncate != null && truncate !== digest.byteLength) {
5183
+ if (truncate > digest.byteLength) throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`);
5184
+ digest = digest.subarray(0, truncate);
5185
+ }
5186
+ return create(code, digest);
5187
+ }
5001
5188
  //#endregion
5002
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/1negint.js
5189
+ //#region ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/sha2.js
5190
+ var sha256 = from({
5191
+ name: "sha2-256",
5192
+ code: 18,
5193
+ encode: (input) => coerce(crypto.createHash("sha256").update(input).digest())
5194
+ });
5195
+ from({
5196
+ name: "sha2-512",
5197
+ code: 19,
5198
+ encode: (input) => coerce(crypto.createHash("sha512").update(input).digest())
5199
+ });
5200
+ //#endregion
5201
+ //#region ../crypto-service/src/json-cid.ts
5003
5202
  /**
5004
- * @typedef {import('../interface').ByteWriter} ByteWriter
5005
- * @typedef {import('../interface').DecodeOptions} DecodeOptions
5203
+ * Generic JSON CID — CIDv1 for arbitrary JSON-serialisable values.
5204
+ *
5205
+ * Uses the dag-json codec and sha2-256, producing a base32lower CIDv1.
5206
+ * Suitable for content-addressing task inputs, schema objects, and other
5207
+ * JSON payloads that don't need diary-entry canonical normalisation.
5006
5208
  */
5209
+ async function computeJsonCid(value) {
5210
+ const bytes = encode(value);
5211
+ const hash = await sha256.digest(bytes);
5212
+ return CID.create(1, 512, hash).toString();
5213
+ }
5214
+ //#endregion
5215
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/is.js
5216
+ var objectTypeNames = [
5217
+ "Object",
5218
+ "RegExp",
5219
+ "Date",
5220
+ "Error",
5221
+ "Map",
5222
+ "Set",
5223
+ "WeakMap",
5224
+ "WeakSet",
5225
+ "ArrayBuffer",
5226
+ "SharedArrayBuffer",
5227
+ "DataView",
5228
+ "Promise",
5229
+ "URL",
5230
+ "HTMLElement",
5231
+ "Int8Array",
5232
+ "Uint8ClampedArray",
5233
+ "Int16Array",
5234
+ "Uint16Array",
5235
+ "Int32Array",
5236
+ "Uint32Array",
5237
+ "Float32Array",
5238
+ "Float64Array",
5239
+ "BigInt64Array",
5240
+ "BigUint64Array"
5241
+ ];
5007
5242
  /**
5008
- * @param {Uint8Array} data
5009
- * @param {number} pos
5010
- * @param {number} _minor
5011
- * @param {DecodeOptions} options
5012
- * @returns {Token}
5243
+ * @param {any} value
5244
+ * @returns {string}
5013
5245
  */
5014
- function decodeNegint8(data, pos, _minor, options) {
5015
- return new Token(Type$2.negint, -1 - readUint8(data, pos + 1, options), 2);
5246
+ function is(value) {
5247
+ if (value === null) return "null";
5248
+ if (value === void 0) return "undefined";
5249
+ if (value === true || value === false) return "boolean";
5250
+ const typeOf = typeof value;
5251
+ if (typeOf === "string" || typeOf === "number" || typeOf === "bigint" || typeOf === "symbol") return typeOf;
5252
+ /* c8 ignore next 3 */
5253
+ if (typeOf === "function") return "Function";
5254
+ if (Array.isArray(value)) return "Array";
5255
+ if (value instanceof Uint8Array) return "Uint8Array";
5256
+ if (value.constructor === Object) return "Object";
5257
+ const objectType = getObjectType(value);
5258
+ if (objectType) return objectType;
5259
+ /* c8 ignore next */
5260
+ return "Object";
5016
5261
  }
5017
5262
  /**
5018
- * @param {Uint8Array} data
5019
- * @param {number} pos
5020
- * @param {number} _minor
5021
- * @param {DecodeOptions} options
5022
- * @returns {Token}
5263
+ * @param {any} value
5264
+ * @returns {string|undefined}
5023
5265
  */
5024
- function decodeNegint16(data, pos, _minor, options) {
5025
- return new Token(Type$2.negint, -1 - readUint16(data, pos + 1, options), 3);
5266
+ function getObjectType(value) {
5267
+ const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
5268
+ if (objectTypeNames.includes(objectTypeName)) return objectTypeName;
5026
5269
  }
5027
- /**
5028
- * @param {Uint8Array} data
5029
- * @param {number} pos
5030
- * @param {number} _minor
5031
- * @param {DecodeOptions} options
5032
- * @returns {Token}
5033
- */
5034
- function decodeNegint32(data, pos, _minor, options) {
5035
- return new Token(Type$2.negint, -1 - readUint32(data, pos + 1, options), 5);
5036
- }
5037
- var neg1b = BigInt(-1);
5038
- var pos1b = BigInt(1);
5039
- /**
5040
- * @param {Uint8Array} data
5041
- * @param {number} pos
5042
- * @param {number} _minor
5043
- * @param {DecodeOptions} options
5044
- * @returns {Token}
5045
- */
5046
- function decodeNegint64(data, pos, _minor, options) {
5047
- const int = readUint64(data, pos + 1, options);
5048
- if (typeof int !== "bigint") {
5049
- const value = -1 - int;
5050
- if (value >= Number.MIN_SAFE_INTEGER) return new Token(Type$2.negint, value, 9);
5270
+ //#endregion
5271
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/token.js
5272
+ var Type$2 = class {
5273
+ /**
5274
+ * @param {number} major
5275
+ * @param {string} name
5276
+ * @param {boolean} terminal
5277
+ */
5278
+ constructor(major, name, terminal) {
5279
+ this.major = major;
5280
+ this.majorEncoded = major << 5;
5281
+ this.name = name;
5282
+ this.terminal = terminal;
5283
+ }
5284
+ /* c8 ignore next 3 */
5285
+ toString() {
5286
+ return `Type[${this.major}].${this.name}`;
5287
+ }
5288
+ /**
5289
+ * @param {Type} typ
5290
+ * @returns {number}
5291
+ */
5292
+ compare(typ) {
5293
+ /* c8 ignore next 1 */
5294
+ return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
5295
+ }
5296
+ /**
5297
+ * Check equality between two Type instances. Safe to use across different
5298
+ * copies of the Type class (e.g., when bundlers duplicate the module).
5299
+ * (major, name) uniquely identifies a Type; terminal is implied by these.
5300
+ * @param {Type} a
5301
+ * @param {Type} b
5302
+ * @returns {boolean}
5303
+ */
5304
+ static equals(a, b) {
5305
+ return a === b || a.major === b.major && a.name === b.name;
5051
5306
  }
5052
- if (options.allowBigInt !== true) throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
5053
- return new Token(Type$2.negint, neg1b - BigInt(int), 9);
5054
- }
5055
- /**
5056
- * @param {ByteWriter} writer
5057
- * @param {Token} token
5058
- */
5059
- function encodeNegint(writer, token) {
5060
- const negint = token.value;
5061
- const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
5062
- encodeUintValue(writer, token.type.majorEncoded, unsigned);
5063
- }
5064
- /**
5065
- * @param {Token} token
5066
- * @returns {number}
5067
- */
5068
- encodeNegint.encodedSize = function encodedSize(token) {
5069
- const negint = token.value;
5070
- const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
5071
- /* c8 ignore next 4 */
5072
- if (unsigned < uintBoundaries[0]) return 1;
5073
- if (unsigned < uintBoundaries[1]) return 2;
5074
- if (unsigned < uintBoundaries[2]) return 3;
5075
- if (unsigned < uintBoundaries[3]) return 5;
5076
- return 9;
5077
5307
  };
5078
- /**
5079
- * @param {Token} tok1
5080
- * @param {Token} tok2
5081
- * @returns {number}
5082
- */
5083
- encodeNegint.compareTokens = function compareTokens(tok1, tok2) {
5084
- return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;
5308
+ Type$2.uint = new Type$2(0, "uint", true);
5309
+ Type$2.negint = new Type$2(1, "negint", true);
5310
+ Type$2.bytes = new Type$2(2, "bytes", true);
5311
+ Type$2.string = new Type$2(3, "string", true);
5312
+ Type$2.array = new Type$2(4, "array", false);
5313
+ Type$2.map = new Type$2(5, "map", false);
5314
+ Type$2.tag = new Type$2(6, "tag", false);
5315
+ Type$2.float = new Type$2(7, "float", true);
5316
+ Type$2.false = new Type$2(7, "false", true);
5317
+ Type$2.true = new Type$2(7, "true", true);
5318
+ Type$2.null = new Type$2(7, "null", true);
5319
+ Type$2.undefined = new Type$2(7, "undefined", true);
5320
+ Type$2.break = new Type$2(7, "break", true);
5321
+ var Token = class {
5322
+ /**
5323
+ * @param {Type} type
5324
+ * @param {any} [value]
5325
+ * @param {number} [encodedLength]
5326
+ */
5327
+ constructor(type, value, encodedLength) {
5328
+ this.type = type;
5329
+ this.value = value;
5330
+ this.encodedLength = encodedLength;
5331
+ /** @type {Uint8Array|undefined} */
5332
+ this.encodedBytes = void 0;
5333
+ /** @type {Uint8Array|undefined} */
5334
+ this.byteValue = void 0;
5335
+ }
5336
+ /* c8 ignore next 3 */
5337
+ toString() {
5338
+ return `Token[${this.type}].${this.value}`;
5339
+ }
5085
5340
  };
5086
5341
  //#endregion
5087
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/2bytes.js
5088
- /**
5089
- * @typedef {import('../interface').ByteWriter} ByteWriter
5090
- * @typedef {import('../interface').DecodeOptions} DecodeOptions
5091
- */
5342
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/byte-utils.js
5343
+ var useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === "function";
5344
+ var textEncoder = new TextEncoder();
5092
5345
  /**
5093
- * @param {Uint8Array} data
5094
- * @param {number} pos
5095
- * @param {number} prefix
5096
- * @param {number} length
5097
- * @returns {Token}
5346
+ * @param {Uint8Array} buf
5347
+ * @returns {boolean}
5098
5348
  */
5099
- function toToken$3(data, pos, prefix, length) {
5100
- assertEnoughData(data, pos, prefix + length);
5101
- const buf = data.slice(pos + prefix, pos + prefix + length);
5102
- return new Token(Type$2.bytes, buf, prefix + length);
5349
+ function isBuffer(buf) {
5350
+ return useBuffer && globalThis.Buffer.isBuffer(buf);
5103
5351
  }
5104
5352
  /**
5105
- * @param {Uint8Array} data
5106
- * @param {number} pos
5107
- * @param {number} minor
5108
- * @param {DecodeOptions} _options
5109
- * @returns {Token}
5353
+ * @param {Uint8Array|number[]} buf
5354
+ * @returns {Uint8Array}
5110
5355
  */
5111
- function decodeBytesCompact(data, pos, minor, _options) {
5112
- return toToken$3(data, pos, 1, minor);
5356
+ function asU8A(buf) {
5357
+ /* c8 ignore next */
5358
+ if (!(buf instanceof Uint8Array)) return Uint8Array.from(buf);
5359
+ return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;
5113
5360
  }
5361
+ var FROM_STRING_THRESHOLD_BUFFER = 24;
5362
+ var FROM_STRING_THRESHOLD_TEXTENCODER = 200;
5363
+ var fromString = useBuffer ? (string) => {
5364
+ return string.length >= FROM_STRING_THRESHOLD_BUFFER ? globalThis.Buffer.from(string) : utf8ToBytes(string);
5365
+ } : (string) => {
5366
+ return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string);
5367
+ };
5114
5368
  /**
5115
- * @param {Uint8Array} data
5116
- * @param {number} pos
5117
- * @param {number} _minor
5118
- * @param {DecodeOptions} options
5119
- * @returns {Token}
5369
+ * Buffer variant not fast enough for what we need
5370
+ * @param {number[]} arr
5371
+ * @returns {Uint8Array}
5120
5372
  */
5121
- function decodeBytes8(data, pos, _minor, options) {
5122
- return toToken$3(data, pos, 2, readUint8(data, pos + 1, options));
5123
- }
5373
+ var fromArray = (arr) => {
5374
+ return Uint8Array.from(arr);
5375
+ };
5376
+ var slice = useBuffer ? (bytes, start, end) => {
5377
+ if (isBuffer(bytes)) return new Uint8Array(bytes.subarray(start, end));
5378
+ return bytes.slice(start, end);
5379
+ } : (bytes, start, end) => {
5380
+ return bytes.slice(start, end);
5381
+ };
5382
+ var concat = useBuffer ? (chunks, length) => {
5383
+ /* c8 ignore next 1 */
5384
+ chunks = chunks.map((c) => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));
5385
+ return asU8A(globalThis.Buffer.concat(chunks, length));
5386
+ } : (chunks, length) => {
5387
+ const out = new Uint8Array(length);
5388
+ let off = 0;
5389
+ for (let b of chunks) {
5390
+ if (off + b.length > out.length) b = b.subarray(0, out.length - off);
5391
+ out.set(b, off);
5392
+ off += b.length;
5393
+ }
5394
+ return out;
5395
+ };
5396
+ var alloc = useBuffer ? (size) => {
5397
+ return globalThis.Buffer.allocUnsafe(size);
5398
+ } : (size) => {
5399
+ return new Uint8Array(size);
5400
+ };
5124
5401
  /**
5125
- * @param {Uint8Array} data
5126
- * @param {number} pos
5127
- * @param {number} _minor
5128
- * @param {DecodeOptions} options
5129
- * @returns {Token}
5402
+ * @param {Uint8Array} b1
5403
+ * @param {Uint8Array} b2
5404
+ * @returns {number}
5130
5405
  */
5131
- function decodeBytes16(data, pos, _minor, options) {
5132
- return toToken$3(data, pos, 3, readUint16(data, pos + 1, options));
5406
+ function compare(b1, b2) {
5407
+ /* c8 ignore next 5 */
5408
+ if (isBuffer(b1) && isBuffer(b2)) return b1.compare(b2);
5409
+ for (let i = 0; i < b1.length; i++) {
5410
+ if (b1[i] === b2[i]) continue;
5411
+ return b1[i] < b2[i] ? -1 : 1;
5412
+ }
5413
+ return 0;
5133
5414
  }
5134
5415
  /**
5135
- * @param {Uint8Array} data
5136
- * @param {number} pos
5137
- * @param {number} _minor
5138
- * @param {DecodeOptions} options
5139
- * @returns {Token}
5416
+ * @param {string} str
5417
+ * @returns {number[]}
5140
5418
  */
5141
- function decodeBytes32(data, pos, _minor, options) {
5142
- return toToken$3(data, pos, 5, readUint32(data, pos + 1, options));
5419
+ function utf8ToBytes(str) {
5420
+ const out = [];
5421
+ let p = 0;
5422
+ for (let i = 0; i < str.length; i++) {
5423
+ let c = str.charCodeAt(i);
5424
+ if (c < 128) out[p++] = c;
5425
+ else if (c < 2048) {
5426
+ out[p++] = c >> 6 | 192;
5427
+ out[p++] = c & 63 | 128;
5428
+ } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
5429
+ c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
5430
+ out[p++] = c >> 18 | 240;
5431
+ out[p++] = c >> 12 & 63 | 128;
5432
+ out[p++] = c >> 6 & 63 | 128;
5433
+ out[p++] = c & 63 | 128;
5434
+ } else {
5435
+ if (c >= 55296 && c <= 57343) c = 65533;
5436
+ out[p++] = c >> 12 | 224;
5437
+ out[p++] = c >> 6 & 63 | 128;
5438
+ out[p++] = c & 63 | 128;
5439
+ }
5440
+ }
5441
+ return out;
5143
5442
  }
5443
+ //#endregion
5444
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/bl.js
5144
5445
  /**
5145
- * @param {Uint8Array} data
5146
- * @param {number} pos
5147
- * @param {number} _minor
5148
- * @param {DecodeOptions} options
5149
- * @returns {Token}
5150
- */
5151
- function decodeBytes64(data, pos, _minor, options) {
5152
- const l = readUint64(data, pos + 1, options);
5153
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
5154
- return toToken$3(data, pos, 9, l);
5155
- }
5156
- /**
5157
- * `encodedBytes` allows for caching when we do a byte version of a string
5158
- * for key sorting purposes
5159
- * @param {Token} token
5160
- * @returns {Uint8Array}
5161
- */
5162
- function tokenBytes(token) {
5163
- if (token.encodedBytes === void 0) token.encodedBytes = Type$2.equals(token.type, Type$2.string) ? fromString(token.value) : token.value;
5164
- return token.encodedBytes;
5165
- }
5166
- /**
5167
- * @param {ByteWriter} writer
5168
- * @param {Token} token
5169
- */
5170
- function encodeBytes(writer, token) {
5171
- const bytes = tokenBytes(token);
5172
- encodeUintValue(writer, token.type.majorEncoded, bytes.length);
5173
- writer.push(bytes);
5174
- }
5175
- /**
5176
- * @param {Token} token
5177
- * @returns {number}
5446
+ * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
5447
+ * writing rather than reading.
5448
+ * A Bl object accepts set() operations for individual bytes and copyTo() for
5449
+ * inserting byte arrays. These write operations don't automatically increment
5450
+ * the internal cursor so its "length" won't be changed. Instead, increment()
5451
+ * must be called to extend its length to cover the inserted data.
5452
+ * The toBytes() call will convert all internal memory to a single Uint8Array of
5453
+ * the correct length, truncating any data that is stored but hasn't been
5454
+ * included by an increment().
5455
+ * get() can retrieve a single byte.
5456
+ * All operations (except toBytes()) take an "offset" argument that will perform
5457
+ * the write at the offset _from the current cursor_. For most operations this
5458
+ * will be `0` to write at the current cursor position but it can be ahead of
5459
+ * the current cursor. Negative offsets probably work but are untested.
5178
5460
  */
5179
- encodeBytes.encodedSize = function encodedSize(token) {
5180
- const bytes = tokenBytes(token);
5181
- return encodeUintValue.encodedSize(bytes.length) + bytes.length;
5461
+ var defaultChunkSize = 256;
5462
+ var Bl = class {
5463
+ /**
5464
+ * @param {number} [chunkSize]
5465
+ */
5466
+ constructor(chunkSize = defaultChunkSize) {
5467
+ this.chunkSize = chunkSize;
5468
+ /** @type {number} */
5469
+ this.cursor = 0;
5470
+ /** @type {number} */
5471
+ this.maxCursor = -1;
5472
+ /** @type {(Uint8Array|number[])[]} */
5473
+ this.chunks = [];
5474
+ /** @type {Uint8Array|number[]|null} */
5475
+ this._initReuseChunk = null;
5476
+ }
5477
+ reset() {
5478
+ this.cursor = 0;
5479
+ this.maxCursor = -1;
5480
+ if (this.chunks.length) this.chunks = [];
5481
+ if (this._initReuseChunk !== null) {
5482
+ this.chunks.push(this._initReuseChunk);
5483
+ this.maxCursor = this._initReuseChunk.length - 1;
5484
+ }
5485
+ }
5486
+ /**
5487
+ * @param {Uint8Array|number[]} bytes
5488
+ */
5489
+ push(bytes) {
5490
+ let topChunk = this.chunks[this.chunks.length - 1];
5491
+ if (this.cursor + bytes.length <= this.maxCursor + 1) {
5492
+ const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
5493
+ topChunk.set(bytes, chunkPos);
5494
+ } else {
5495
+ if (topChunk) {
5496
+ const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
5497
+ if (chunkPos < topChunk.length) {
5498
+ this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
5499
+ this.maxCursor = this.cursor - 1;
5500
+ }
5501
+ }
5502
+ if (bytes.length < 64 && bytes.length < this.chunkSize) {
5503
+ topChunk = alloc(this.chunkSize);
5504
+ this.chunks.push(topChunk);
5505
+ this.maxCursor += topChunk.length;
5506
+ if (this._initReuseChunk === null) this._initReuseChunk = topChunk;
5507
+ topChunk.set(bytes, 0);
5508
+ } else {
5509
+ this.chunks.push(bytes);
5510
+ this.maxCursor += bytes.length;
5511
+ }
5512
+ }
5513
+ this.cursor += bytes.length;
5514
+ }
5515
+ /**
5516
+ * @param {boolean} [reset]
5517
+ * @returns {Uint8Array}
5518
+ */
5519
+ toBytes(reset = false) {
5520
+ let byts;
5521
+ if (this.chunks.length === 1) {
5522
+ const chunk = this.chunks[0];
5523
+ if (reset && this.cursor > chunk.length / 2) {
5524
+ /* c8 ignore next 2 */
5525
+ byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
5526
+ this._initReuseChunk = null;
5527
+ this.chunks = [];
5528
+ } else byts = slice(chunk, 0, this.cursor);
5529
+ } else byts = concat(this.chunks, this.cursor);
5530
+ if (reset) this.reset();
5531
+ return byts;
5532
+ }
5182
5533
  };
5183
5534
  /**
5184
- * @param {Token} tok1
5185
- * @param {Token} tok2
5186
- * @returns {number}
5535
+ * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
5536
+ * It provides the same interface as Bl but writes to a fixed destination.
5187
5537
  */
5188
- encodeBytes.compareTokens = function compareTokens(tok1, tok2) {
5189
- return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
5538
+ var U8Bl = class {
5539
+ /**
5540
+ * @param {Uint8Array} dest
5541
+ */
5542
+ constructor(dest) {
5543
+ this.dest = dest;
5544
+ /** @type {number} */
5545
+ this.cursor = 0;
5546
+ /** @type {Uint8Array[]} */
5547
+ this.chunks = [dest];
5548
+ }
5549
+ reset() {
5550
+ this.cursor = 0;
5551
+ }
5552
+ /**
5553
+ * @param {Uint8Array|number[]} bytes
5554
+ */
5555
+ push(bytes) {
5556
+ if (this.cursor + bytes.length > this.dest.length) throw new Error("write out of bounds, destination buffer is too small");
5557
+ this.dest.set(bytes, this.cursor);
5558
+ this.cursor += bytes.length;
5559
+ }
5560
+ /**
5561
+ * @param {boolean} [reset]
5562
+ * @returns {Uint8Array}
5563
+ */
5564
+ toBytes(reset = false) {
5565
+ const byts = this.dest.subarray(0, this.cursor);
5566
+ if (reset) this.reset();
5567
+ return byts;
5568
+ }
5190
5569
  };
5570
+ //#endregion
5571
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/common.js
5572
+ var decodeErrPrefix = "CBOR decode error:";
5573
+ var encodeErrPrefix = "CBOR encode error:";
5574
+ var uintMinorPrefixBytes = [];
5575
+ uintMinorPrefixBytes[23] = 1;
5576
+ uintMinorPrefixBytes[24] = 2;
5577
+ uintMinorPrefixBytes[25] = 3;
5578
+ uintMinorPrefixBytes[26] = 5;
5579
+ uintMinorPrefixBytes[27] = 9;
5191
5580
  /**
5192
- * @param {Uint8Array} b1
5193
- * @param {Uint8Array} b2
5194
- * @returns {number}
5581
+ * @param {Uint8Array} data
5582
+ * @param {number} pos
5583
+ * @param {number} need
5195
5584
  */
5196
- function compareBytes(b1, b2) {
5197
- return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
5585
+ function assertEnoughData(data, pos, need) {
5586
+ if (data.length - pos < need) throw new Error(`${decodeErrPrefix} not enough data for type`);
5198
5587
  }
5199
5588
  //#endregion
5200
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/3string.js
5201
- var textDecoder = new TextDecoder();
5202
- var ASCII_THRESHOLD = 32;
5589
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/0uint.js
5590
+ var uintBoundaries = [
5591
+ 24,
5592
+ 256,
5593
+ 65536,
5594
+ 4294967296,
5595
+ BigInt("18446744073709551616")
5596
+ ];
5203
5597
  /**
5204
5598
  * @typedef {import('../interface').ByteWriter} ByteWriter
5205
5599
  * @typedef {import('../interface').DecodeOptions} DecodeOptions
5206
5600
  */
5207
5601
  /**
5208
- * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
5209
- * a simple loop is faster than TextDecoder.
5210
- * @param {Uint8Array} bytes
5211
- * @param {number} start
5212
- * @param {number} end
5213
- * @returns {string}
5214
- */
5215
- function toStr(bytes, start, end) {
5216
- if (end - start < ASCII_THRESHOLD) {
5217
- let str = "";
5218
- for (let i = start; i < end; i++) {
5219
- const c = bytes[i];
5220
- if (c & 128) return textDecoder.decode(bytes.subarray(start, end));
5221
- str += String.fromCharCode(c);
5222
- }
5223
- return str;
5224
- }
5225
- return textDecoder.decode(bytes.subarray(start, end));
5226
- }
5227
- /**
5228
5602
  * @param {Uint8Array} data
5229
- * @param {number} pos
5230
- * @param {number} prefix
5231
- * @param {number} length
5603
+ * @param {number} offset
5232
5604
  * @param {DecodeOptions} options
5233
- * @returns {Token}
5605
+ * @returns {number}
5234
5606
  */
5235
- function toToken$2(data, pos, prefix, length, options) {
5236
- const totLength = prefix + length;
5237
- assertEnoughData(data, pos, totLength);
5238
- const tok = new Token(Type$2.string, toStr(data, pos + prefix, pos + totLength), totLength);
5239
- if (options.retainStringBytes === true) tok.byteValue = data.slice(pos + prefix, pos + totLength);
5240
- return tok;
5607
+ function readUint8(data, offset, options) {
5608
+ assertEnoughData(data, offset, 1);
5609
+ const value = data[offset];
5610
+ if (options.strict === true && value < uintBoundaries[0]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
5611
+ return value;
5241
5612
  }
5242
5613
  /**
5243
5614
  * @param {Uint8Array} data
5244
- * @param {number} pos
5245
- * @param {number} minor
5615
+ * @param {number} offset
5246
5616
  * @param {DecodeOptions} options
5247
- * @returns {Token}
5617
+ * @returns {number}
5248
5618
  */
5249
- function decodeStringCompact(data, pos, minor, options) {
5250
- return toToken$2(data, pos, 1, minor, options);
5619
+ function readUint16(data, offset, options) {
5620
+ assertEnoughData(data, offset, 2);
5621
+ const value = data[offset] << 8 | data[offset + 1];
5622
+ if (options.strict === true && value < uintBoundaries[1]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
5623
+ return value;
5251
5624
  }
5252
5625
  /**
5253
5626
  * @param {Uint8Array} data
5254
- * @param {number} pos
5255
- * @param {number} _minor
5627
+ * @param {number} offset
5256
5628
  * @param {DecodeOptions} options
5257
- * @returns {Token}
5629
+ * @returns {number}
5258
5630
  */
5259
- function decodeString8(data, pos, _minor, options) {
5260
- return toToken$2(data, pos, 2, readUint8(data, pos + 1, options), options);
5631
+ function readUint32(data, offset, options) {
5632
+ assertEnoughData(data, offset, 4);
5633
+ const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
5634
+ if (options.strict === true && value < uintBoundaries[2]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
5635
+ return value;
5261
5636
  }
5262
5637
  /**
5263
5638
  * @param {Uint8Array} data
5264
- * @param {number} pos
5265
- * @param {number} _minor
5639
+ * @param {number} offset
5266
5640
  * @param {DecodeOptions} options
5267
- * @returns {Token}
5641
+ * @returns {number|bigint}
5268
5642
  */
5269
- function decodeString16(data, pos, _minor, options) {
5270
- return toToken$2(data, pos, 3, readUint16(data, pos + 1, options), options);
5643
+ function readUint64(data, offset, options) {
5644
+ assertEnoughData(data, offset, 8);
5645
+ const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
5646
+ const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
5647
+ const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
5648
+ if (options.strict === true && value < uintBoundaries[3]) throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
5649
+ if (value <= Number.MAX_SAFE_INTEGER) return Number(value);
5650
+ if (options.allowBigInt === true) return value;
5651
+ throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
5271
5652
  }
5272
5653
  /**
5273
5654
  * @param {Uint8Array} data
@@ -5276,8 +5657,8 @@ function decodeString16(data, pos, _minor, options) {
5276
5657
  * @param {DecodeOptions} options
5277
5658
  * @returns {Token}
5278
5659
  */
5279
- function decodeString32(data, pos, _minor, options) {
5280
- return toToken$2(data, pos, 5, readUint32(data, pos + 1, options), options);
5660
+ function decodeUint8(data, pos, _minor, options) {
5661
+ return new Token(Type$2.uint, readUint8(data, pos + 1, options), 2);
5281
5662
  }
5282
5663
  /**
5283
5664
  * @param {Uint8Array} data
@@ -5286,37 +5667,18 @@ function decodeString32(data, pos, _minor, options) {
5286
5667
  * @param {DecodeOptions} options
5287
5668
  * @returns {Token}
5288
5669
  */
5289
- function decodeString64(data, pos, _minor, options) {
5290
- const l = readUint64(data, pos + 1, options);
5291
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
5292
- return toToken$2(data, pos, 9, l, options);
5293
- }
5294
- var encodeString = encodeBytes;
5295
- //#endregion
5296
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/4array.js
5297
- /**
5298
- * @typedef {import('../interface').ByteWriter} ByteWriter
5299
- * @typedef {import('../interface').DecodeOptions} DecodeOptions
5300
- */
5301
- /**
5302
- * @param {Uint8Array} _data
5303
- * @param {number} _pos
5304
- * @param {number} prefix
5305
- * @param {number} length
5306
- * @returns {Token}
5307
- */
5308
- function toToken$1(_data, _pos, prefix, length) {
5309
- return new Token(Type$2.array, length, prefix);
5670
+ function decodeUint16(data, pos, _minor, options) {
5671
+ return new Token(Type$2.uint, readUint16(data, pos + 1, options), 3);
5310
5672
  }
5311
5673
  /**
5312
5674
  * @param {Uint8Array} data
5313
5675
  * @param {number} pos
5314
- * @param {number} minor
5315
- * @param {DecodeOptions} _options
5676
+ * @param {number} _minor
5677
+ * @param {DecodeOptions} options
5316
5678
  * @returns {Token}
5317
5679
  */
5318
- function decodeArrayCompact(data, pos, minor, _options) {
5319
- return toToken$1(data, pos, 1, minor);
5680
+ function decodeUint32(data, pos, _minor, options) {
5681
+ return new Token(Type$2.uint, readUint32(data, pos + 1, options), 5);
5320
5682
  }
5321
5683
  /**
5322
5684
  * @param {Uint8Array} data
@@ -5325,18 +5687,118 @@ function decodeArrayCompact(data, pos, minor, _options) {
5325
5687
  * @param {DecodeOptions} options
5326
5688
  * @returns {Token}
5327
5689
  */
5328
- function decodeArray8(data, pos, _minor, options) {
5329
- return toToken$1(data, pos, 2, readUint8(data, pos + 1, options));
5690
+ function decodeUint64(data, pos, _minor, options) {
5691
+ return new Token(Type$2.uint, readUint64(data, pos + 1, options), 9);
5692
+ }
5693
+ /**
5694
+ * @param {ByteWriter} writer
5695
+ * @param {Token} token
5696
+ */
5697
+ function encodeUint(writer, token) {
5698
+ return encodeUintValue(writer, 0, token.value);
5699
+ }
5700
+ /**
5701
+ * @param {ByteWriter} writer
5702
+ * @param {number} major
5703
+ * @param {number|bigint} uint
5704
+ */
5705
+ function encodeUintValue(writer, major, uint) {
5706
+ if (uint < uintBoundaries[0]) {
5707
+ const nuint = Number(uint);
5708
+ writer.push([major | nuint]);
5709
+ } else if (uint < uintBoundaries[1]) {
5710
+ const nuint = Number(uint);
5711
+ writer.push([major | 24, nuint]);
5712
+ } else if (uint < uintBoundaries[2]) {
5713
+ const nuint = Number(uint);
5714
+ writer.push([
5715
+ major | 25,
5716
+ nuint >>> 8,
5717
+ nuint & 255
5718
+ ]);
5719
+ } else if (uint < uintBoundaries[3]) {
5720
+ const nuint = Number(uint);
5721
+ writer.push([
5722
+ major | 26,
5723
+ nuint >>> 24 & 255,
5724
+ nuint >>> 16 & 255,
5725
+ nuint >>> 8 & 255,
5726
+ nuint & 255
5727
+ ]);
5728
+ } else {
5729
+ const buint = BigInt(uint);
5730
+ if (buint < uintBoundaries[4]) {
5731
+ const set = [
5732
+ major | 27,
5733
+ 0,
5734
+ 0,
5735
+ 0,
5736
+ 0,
5737
+ 0,
5738
+ 0,
5739
+ 0
5740
+ ];
5741
+ let lo = Number(buint & BigInt(4294967295));
5742
+ let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
5743
+ set[8] = lo & 255;
5744
+ lo = lo >> 8;
5745
+ set[7] = lo & 255;
5746
+ lo = lo >> 8;
5747
+ set[6] = lo & 255;
5748
+ lo = lo >> 8;
5749
+ set[5] = lo & 255;
5750
+ set[4] = hi & 255;
5751
+ hi = hi >> 8;
5752
+ set[3] = hi & 255;
5753
+ hi = hi >> 8;
5754
+ set[2] = hi & 255;
5755
+ hi = hi >> 8;
5756
+ set[1] = hi & 255;
5757
+ writer.push(set);
5758
+ } else throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
5759
+ }
5330
5760
  }
5331
5761
  /**
5762
+ * @param {Token} token
5763
+ * @returns {number}
5764
+ */
5765
+ encodeUint.encodedSize = function encodedSize(token) {
5766
+ return encodeUintValue.encodedSize(token.value);
5767
+ };
5768
+ /**
5769
+ * @param {number} uint
5770
+ * @returns {number}
5771
+ */
5772
+ encodeUintValue.encodedSize = function encodedSize(uint) {
5773
+ if (uint < uintBoundaries[0]) return 1;
5774
+ if (uint < uintBoundaries[1]) return 2;
5775
+ if (uint < uintBoundaries[2]) return 3;
5776
+ if (uint < uintBoundaries[3]) return 5;
5777
+ return 9;
5778
+ };
5779
+ /**
5780
+ * @param {Token} tok1
5781
+ * @param {Token} tok2
5782
+ * @returns {number}
5783
+ */
5784
+ encodeUint.compareTokens = function compareTokens(tok1, tok2) {
5785
+ return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;
5786
+ };
5787
+ //#endregion
5788
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/1negint.js
5789
+ /**
5790
+ * @typedef {import('../interface').ByteWriter} ByteWriter
5791
+ * @typedef {import('../interface').DecodeOptions} DecodeOptions
5792
+ */
5793
+ /**
5332
5794
  * @param {Uint8Array} data
5333
5795
  * @param {number} pos
5334
5796
  * @param {number} _minor
5335
5797
  * @param {DecodeOptions} options
5336
5798
  * @returns {Token}
5337
5799
  */
5338
- function decodeArray16(data, pos, _minor, options) {
5339
- return toToken$1(data, pos, 3, readUint16(data, pos + 1, options));
5800
+ function decodeNegint8(data, pos, _minor, options) {
5801
+ return new Token(Type$2.negint, -1 - readUint8(data, pos + 1, options), 2);
5340
5802
  }
5341
5803
  /**
5342
5804
  * @param {Uint8Array} data
@@ -5345,8 +5807,8 @@ function decodeArray16(data, pos, _minor, options) {
5345
5807
  * @param {DecodeOptions} options
5346
5808
  * @returns {Token}
5347
5809
  */
5348
- function decodeArray32(data, pos, _minor, options) {
5349
- return toToken$1(data, pos, 5, readUint32(data, pos + 1, options));
5810
+ function decodeNegint16(data, pos, _minor, options) {
5811
+ return new Token(Type$2.negint, -1 - readUint16(data, pos + 1, options), 3);
5350
5812
  }
5351
5813
  /**
5352
5814
  * @param {Uint8Array} data
@@ -5355,11 +5817,11 @@ function decodeArray32(data, pos, _minor, options) {
5355
5817
  * @param {DecodeOptions} options
5356
5818
  * @returns {Token}
5357
5819
  */
5358
- function decodeArray64(data, pos, _minor, options) {
5359
- const l = readUint64(data, pos + 1, options);
5360
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
5361
- return toToken$1(data, pos, 9, l);
5820
+ function decodeNegint32(data, pos, _minor, options) {
5821
+ return new Token(Type$2.negint, -1 - readUint32(data, pos + 1, options), 5);
5362
5822
  }
5823
+ var neg1b = BigInt(-1);
5824
+ var pos1b = BigInt(1);
5363
5825
  /**
5364
5826
  * @param {Uint8Array} data
5365
5827
  * @param {number} pos
@@ -5367,40 +5829,63 @@ function decodeArray64(data, pos, _minor, options) {
5367
5829
  * @param {DecodeOptions} options
5368
5830
  * @returns {Token}
5369
5831
  */
5370
- function decodeArrayIndefinite(data, pos, _minor, options) {
5371
- if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
5372
- return toToken$1(data, pos, 1, Infinity);
5832
+ function decodeNegint64(data, pos, _minor, options) {
5833
+ const int = readUint64(data, pos + 1, options);
5834
+ if (typeof int !== "bigint") {
5835
+ const value = -1 - int;
5836
+ if (value >= Number.MIN_SAFE_INTEGER) return new Token(Type$2.negint, value, 9);
5837
+ }
5838
+ if (options.allowBigInt !== true) throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
5839
+ return new Token(Type$2.negint, neg1b - BigInt(int), 9);
5373
5840
  }
5374
5841
  /**
5375
5842
  * @param {ByteWriter} writer
5376
5843
  * @param {Token} token
5377
5844
  */
5378
- function encodeArray(writer, token) {
5379
- encodeUintValue(writer, Type$2.array.majorEncoded, token.value);
5845
+ function encodeNegint(writer, token) {
5846
+ const negint = token.value;
5847
+ const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
5848
+ encodeUintValue(writer, token.type.majorEncoded, unsigned);
5380
5849
  }
5381
- encodeArray.compareTokens = encodeUint.compareTokens;
5382
5850
  /**
5383
5851
  * @param {Token} token
5384
5852
  * @returns {number}
5385
5853
  */
5386
- encodeArray.encodedSize = function encodedSize(token) {
5387
- return encodeUintValue.encodedSize(token.value);
5854
+ encodeNegint.encodedSize = function encodedSize(token) {
5855
+ const negint = token.value;
5856
+ const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
5857
+ /* c8 ignore next 4 */
5858
+ if (unsigned < uintBoundaries[0]) return 1;
5859
+ if (unsigned < uintBoundaries[1]) return 2;
5860
+ if (unsigned < uintBoundaries[2]) return 3;
5861
+ if (unsigned < uintBoundaries[3]) return 5;
5862
+ return 9;
5863
+ };
5864
+ /**
5865
+ * @param {Token} tok1
5866
+ * @param {Token} tok2
5867
+ * @returns {number}
5868
+ */
5869
+ encodeNegint.compareTokens = function compareTokens(tok1, tok2) {
5870
+ return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;
5388
5871
  };
5389
5872
  //#endregion
5390
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/5map.js
5873
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/2bytes.js
5391
5874
  /**
5392
5875
  * @typedef {import('../interface').ByteWriter} ByteWriter
5393
5876
  * @typedef {import('../interface').DecodeOptions} DecodeOptions
5394
5877
  */
5395
5878
  /**
5396
- * @param {Uint8Array} _data
5397
- * @param {number} _pos
5879
+ * @param {Uint8Array} data
5880
+ * @param {number} pos
5398
5881
  * @param {number} prefix
5399
5882
  * @param {number} length
5400
5883
  * @returns {Token}
5401
5884
  */
5402
- function toToken(_data, _pos, prefix, length) {
5403
- return new Token(Type$2.map, length, prefix);
5885
+ function toToken$3(data, pos, prefix, length) {
5886
+ assertEnoughData(data, pos, prefix + length);
5887
+ const buf = data.slice(pos + prefix, pos + prefix + length);
5888
+ return new Token(Type$2.bytes, buf, prefix + length);
5404
5889
  }
5405
5890
  /**
5406
5891
  * @param {Uint8Array} data
@@ -5409,8 +5894,8 @@ function toToken(_data, _pos, prefix, length) {
5409
5894
  * @param {DecodeOptions} _options
5410
5895
  * @returns {Token}
5411
5896
  */
5412
- function decodeMapCompact(data, pos, minor, _options) {
5413
- return toToken(data, pos, 1, minor);
5897
+ function decodeBytesCompact(data, pos, minor, _options) {
5898
+ return toToken$3(data, pos, 1, minor);
5414
5899
  }
5415
5900
  /**
5416
5901
  * @param {Uint8Array} data
@@ -5419,8 +5904,8 @@ function decodeMapCompact(data, pos, minor, _options) {
5419
5904
  * @param {DecodeOptions} options
5420
5905
  * @returns {Token}
5421
5906
  */
5422
- function decodeMap8(data, pos, _minor, options) {
5423
- return toToken(data, pos, 2, readUint8(data, pos + 1, options));
5907
+ function decodeBytes8(data, pos, _minor, options) {
5908
+ return toToken$3(data, pos, 2, readUint8(data, pos + 1, options));
5424
5909
  }
5425
5910
  /**
5426
5911
  * @param {Uint8Array} data
@@ -5429,8 +5914,8 @@ function decodeMap8(data, pos, _minor, options) {
5429
5914
  * @param {DecodeOptions} options
5430
5915
  * @returns {Token}
5431
5916
  */
5432
- function decodeMap16(data, pos, _minor, options) {
5433
- return toToken(data, pos, 3, readUint16(data, pos + 1, options));
5917
+ function decodeBytes16(data, pos, _minor, options) {
5918
+ return toToken$3(data, pos, 3, readUint16(data, pos + 1, options));
5434
5919
  }
5435
5920
  /**
5436
5921
  * @param {Uint8Array} data
@@ -5439,8 +5924,8 @@ function decodeMap16(data, pos, _minor, options) {
5439
5924
  * @param {DecodeOptions} options
5440
5925
  * @returns {Token}
5441
5926
  */
5442
- function decodeMap32(data, pos, _minor, options) {
5443
- return toToken(data, pos, 5, readUint32(data, pos + 1, options));
5927
+ function decodeBytes32(data, pos, _minor, options) {
5928
+ return toToken$3(data, pos, 5, readUint32(data, pos + 1, options));
5444
5929
  }
5445
5930
  /**
5446
5931
  * @param {Uint8Array} data
@@ -5449,39 +5934,152 @@ function decodeMap32(data, pos, _minor, options) {
5449
5934
  * @param {DecodeOptions} options
5450
5935
  * @returns {Token}
5451
5936
  */
5452
- function decodeMap64(data, pos, _minor, options) {
5937
+ function decodeBytes64(data, pos, _minor, options) {
5453
5938
  const l = readUint64(data, pos + 1, options);
5454
- if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
5455
- return toToken(data, pos, 9, l);
5939
+ if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
5940
+ return toToken$3(data, pos, 9, l);
5456
5941
  }
5457
5942
  /**
5458
- * @param {Uint8Array} data
5459
- * @param {number} pos
5460
- * @param {number} _minor
5461
- * @param {DecodeOptions} options
5462
- * @returns {Token}
5943
+ * `encodedBytes` allows for caching when we do a byte version of a string
5944
+ * for key sorting purposes
5945
+ * @param {Token} token
5946
+ * @returns {Uint8Array}
5463
5947
  */
5464
- function decodeMapIndefinite(data, pos, _minor, options) {
5465
- if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
5466
- return toToken(data, pos, 1, Infinity);
5948
+ function tokenBytes(token) {
5949
+ if (token.encodedBytes === void 0) token.encodedBytes = Type$2.equals(token.type, Type$2.string) ? fromString(token.value) : token.value;
5950
+ return token.encodedBytes;
5467
5951
  }
5468
5952
  /**
5469
5953
  * @param {ByteWriter} writer
5470
5954
  * @param {Token} token
5471
5955
  */
5472
- function encodeMap(writer, token) {
5473
- encodeUintValue(writer, Type$2.map.majorEncoded, token.value);
5474
- }
5475
- encodeMap.compareTokens = encodeUint.compareTokens;
5956
+ function encodeBytes(writer, token) {
5957
+ const bytes = tokenBytes(token);
5958
+ encodeUintValue(writer, token.type.majorEncoded, bytes.length);
5959
+ writer.push(bytes);
5960
+ }
5476
5961
  /**
5477
5962
  * @param {Token} token
5478
5963
  * @returns {number}
5479
5964
  */
5480
- encodeMap.encodedSize = function encodedSize(token) {
5481
- return encodeUintValue.encodedSize(token.value);
5965
+ encodeBytes.encodedSize = function encodedSize(token) {
5966
+ const bytes = tokenBytes(token);
5967
+ return encodeUintValue.encodedSize(bytes.length) + bytes.length;
5968
+ };
5969
+ /**
5970
+ * @param {Token} tok1
5971
+ * @param {Token} tok2
5972
+ * @returns {number}
5973
+ */
5974
+ encodeBytes.compareTokens = function compareTokens(tok1, tok2) {
5975
+ return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
5482
5976
  };
5977
+ /**
5978
+ * @param {Uint8Array} b1
5979
+ * @param {Uint8Array} b2
5980
+ * @returns {number}
5981
+ */
5982
+ function compareBytes(b1, b2) {
5983
+ return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
5984
+ }
5483
5985
  //#endregion
5484
- //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/6tag.js
5986
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/3string.js
5987
+ var textDecoder = new TextDecoder();
5988
+ var ASCII_THRESHOLD = 32;
5989
+ /**
5990
+ * @typedef {import('../interface').ByteWriter} ByteWriter
5991
+ * @typedef {import('../interface').DecodeOptions} DecodeOptions
5992
+ */
5993
+ /**
5994
+ * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
5995
+ * a simple loop is faster than TextDecoder.
5996
+ * @param {Uint8Array} bytes
5997
+ * @param {number} start
5998
+ * @param {number} end
5999
+ * @returns {string}
6000
+ */
6001
+ function toStr(bytes, start, end) {
6002
+ if (end - start < ASCII_THRESHOLD) {
6003
+ let str = "";
6004
+ for (let i = start; i < end; i++) {
6005
+ const c = bytes[i];
6006
+ if (c & 128) return textDecoder.decode(bytes.subarray(start, end));
6007
+ str += String.fromCharCode(c);
6008
+ }
6009
+ return str;
6010
+ }
6011
+ return textDecoder.decode(bytes.subarray(start, end));
6012
+ }
6013
+ /**
6014
+ * @param {Uint8Array} data
6015
+ * @param {number} pos
6016
+ * @param {number} prefix
6017
+ * @param {number} length
6018
+ * @param {DecodeOptions} options
6019
+ * @returns {Token}
6020
+ */
6021
+ function toToken$2(data, pos, prefix, length, options) {
6022
+ const totLength = prefix + length;
6023
+ assertEnoughData(data, pos, totLength);
6024
+ const tok = new Token(Type$2.string, toStr(data, pos + prefix, pos + totLength), totLength);
6025
+ if (options.retainStringBytes === true) tok.byteValue = data.slice(pos + prefix, pos + totLength);
6026
+ return tok;
6027
+ }
6028
+ /**
6029
+ * @param {Uint8Array} data
6030
+ * @param {number} pos
6031
+ * @param {number} minor
6032
+ * @param {DecodeOptions} options
6033
+ * @returns {Token}
6034
+ */
6035
+ function decodeStringCompact(data, pos, minor, options) {
6036
+ return toToken$2(data, pos, 1, minor, options);
6037
+ }
6038
+ /**
6039
+ * @param {Uint8Array} data
6040
+ * @param {number} pos
6041
+ * @param {number} _minor
6042
+ * @param {DecodeOptions} options
6043
+ * @returns {Token}
6044
+ */
6045
+ function decodeString8(data, pos, _minor, options) {
6046
+ return toToken$2(data, pos, 2, readUint8(data, pos + 1, options), options);
6047
+ }
6048
+ /**
6049
+ * @param {Uint8Array} data
6050
+ * @param {number} pos
6051
+ * @param {number} _minor
6052
+ * @param {DecodeOptions} options
6053
+ * @returns {Token}
6054
+ */
6055
+ function decodeString16(data, pos, _minor, options) {
6056
+ return toToken$2(data, pos, 3, readUint16(data, pos + 1, options), options);
6057
+ }
6058
+ /**
6059
+ * @param {Uint8Array} data
6060
+ * @param {number} pos
6061
+ * @param {number} _minor
6062
+ * @param {DecodeOptions} options
6063
+ * @returns {Token}
6064
+ */
6065
+ function decodeString32(data, pos, _minor, options) {
6066
+ return toToken$2(data, pos, 5, readUint32(data, pos + 1, options), options);
6067
+ }
6068
+ /**
6069
+ * @param {Uint8Array} data
6070
+ * @param {number} pos
6071
+ * @param {number} _minor
6072
+ * @param {DecodeOptions} options
6073
+ * @returns {Token}
6074
+ */
6075
+ function decodeString64(data, pos, _minor, options) {
6076
+ const l = readUint64(data, pos + 1, options);
6077
+ if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
6078
+ return toToken$2(data, pos, 9, l, options);
6079
+ }
6080
+ var encodeString = encodeBytes;
6081
+ //#endregion
6082
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/4array.js
5485
6083
  /**
5486
6084
  * @typedef {import('../interface').ByteWriter} ByteWriter
5487
6085
  * @typedef {import('../interface').DecodeOptions} DecodeOptions
@@ -5489,12 +6087,22 @@ encodeMap.encodedSize = function encodedSize(token) {
5489
6087
  /**
5490
6088
  * @param {Uint8Array} _data
5491
6089
  * @param {number} _pos
6090
+ * @param {number} prefix
6091
+ * @param {number} length
6092
+ * @returns {Token}
6093
+ */
6094
+ function toToken$1(_data, _pos, prefix, length) {
6095
+ return new Token(Type$2.array, length, prefix);
6096
+ }
6097
+ /**
6098
+ * @param {Uint8Array} data
6099
+ * @param {number} pos
5492
6100
  * @param {number} minor
5493
6101
  * @param {DecodeOptions} _options
5494
6102
  * @returns {Token}
5495
6103
  */
5496
- function decodeTagCompact(_data, _pos, minor, _options) {
5497
- return new Token(Type$2.tag, minor, 1);
6104
+ function decodeArrayCompact(data, pos, minor, _options) {
6105
+ return toToken$1(data, pos, 1, minor);
5498
6106
  }
5499
6107
  /**
5500
6108
  * @param {Uint8Array} data
@@ -5503,8 +6111,8 @@ function decodeTagCompact(_data, _pos, minor, _options) {
5503
6111
  * @param {DecodeOptions} options
5504
6112
  * @returns {Token}
5505
6113
  */
5506
- function decodeTag8(data, pos, _minor, options) {
5507
- return new Token(Type$2.tag, readUint8(data, pos + 1, options), 2);
6114
+ function decodeArray8(data, pos, _minor, options) {
6115
+ return toToken$1(data, pos, 2, readUint8(data, pos + 1, options));
5508
6116
  }
5509
6117
  /**
5510
6118
  * @param {Uint8Array} data
@@ -5513,8 +6121,8 @@ function decodeTag8(data, pos, _minor, options) {
5513
6121
  * @param {DecodeOptions} options
5514
6122
  * @returns {Token}
5515
6123
  */
5516
- function decodeTag16(data, pos, _minor, options) {
5517
- return new Token(Type$2.tag, readUint16(data, pos + 1, options), 3);
6124
+ function decodeArray16(data, pos, _minor, options) {
6125
+ return toToken$1(data, pos, 3, readUint16(data, pos + 1, options));
5518
6126
  }
5519
6127
  /**
5520
6128
  * @param {Uint8Array} data
@@ -5523,8 +6131,8 @@ function decodeTag16(data, pos, _minor, options) {
5523
6131
  * @param {DecodeOptions} options
5524
6132
  * @returns {Token}
5525
6133
  */
5526
- function decodeTag32(data, pos, _minor, options) {
5527
- return new Token(Type$2.tag, readUint32(data, pos + 1, options), 5);
6134
+ function decodeArray32(data, pos, _minor, options) {
6135
+ return toToken$1(data, pos, 5, readUint32(data, pos + 1, options));
5528
6136
  }
5529
6137
  /**
5530
6138
  * @param {Uint8Array} data
@@ -5533,59 +6141,82 @@ function decodeTag32(data, pos, _minor, options) {
5533
6141
  * @param {DecodeOptions} options
5534
6142
  * @returns {Token}
5535
6143
  */
5536
- function decodeTag64(data, pos, _minor, options) {
5537
- return new Token(Type$2.tag, readUint64(data, pos + 1, options), 9);
6144
+ function decodeArray64(data, pos, _minor, options) {
6145
+ const l = readUint64(data, pos + 1, options);
6146
+ if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
6147
+ return toToken$1(data, pos, 9, l);
6148
+ }
6149
+ /**
6150
+ * @param {Uint8Array} data
6151
+ * @param {number} pos
6152
+ * @param {number} _minor
6153
+ * @param {DecodeOptions} options
6154
+ * @returns {Token}
6155
+ */
6156
+ function decodeArrayIndefinite(data, pos, _minor, options) {
6157
+ if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
6158
+ return toToken$1(data, pos, 1, Infinity);
5538
6159
  }
5539
6160
  /**
5540
6161
  * @param {ByteWriter} writer
5541
6162
  * @param {Token} token
5542
6163
  */
5543
- function encodeTag(writer, token) {
5544
- encodeUintValue(writer, Type$2.tag.majorEncoded, token.value);
6164
+ function encodeArray(writer, token) {
6165
+ encodeUintValue(writer, Type$2.array.majorEncoded, token.value);
5545
6166
  }
5546
- encodeTag.compareTokens = encodeUint.compareTokens;
6167
+ encodeArray.compareTokens = encodeUint.compareTokens;
5547
6168
  /**
5548
6169
  * @param {Token} token
5549
6170
  * @returns {number}
5550
6171
  */
5551
- encodeTag.encodedSize = function encodedSize(token) {
6172
+ encodeArray.encodedSize = function encodedSize(token) {
5552
6173
  return encodeUintValue.encodedSize(token.value);
5553
6174
  };
6175
+ //#endregion
6176
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/5map.js
6177
+ /**
6178
+ * @typedef {import('../interface').ByteWriter} ByteWriter
6179
+ * @typedef {import('../interface').DecodeOptions} DecodeOptions
6180
+ */
5554
6181
  /**
5555
6182
  * @param {Uint8Array} _data
5556
6183
  * @param {number} _pos
5557
- * @param {number} _minor
5558
- * @param {DecodeOptions} options
6184
+ * @param {number} prefix
6185
+ * @param {number} length
5559
6186
  * @returns {Token}
5560
6187
  */
5561
- function decodeUndefined(_data, _pos, _minor, options) {
5562
- if (options.allowUndefined === false) throw new Error(`${decodeErrPrefix} undefined values are not supported`);
5563
- else if (options.coerceUndefinedToNull === true) return new Token(Type$2.null, null, 1);
5564
- return new Token(Type$2.undefined, void 0, 1);
6188
+ function toToken(_data, _pos, prefix, length) {
6189
+ return new Token(Type$2.map, length, prefix);
5565
6190
  }
5566
6191
  /**
5567
- * @param {Uint8Array} _data
5568
- * @param {number} _pos
6192
+ * @param {Uint8Array} data
6193
+ * @param {number} pos
6194
+ * @param {number} minor
6195
+ * @param {DecodeOptions} _options
6196
+ * @returns {Token}
6197
+ */
6198
+ function decodeMapCompact(data, pos, minor, _options) {
6199
+ return toToken(data, pos, 1, minor);
6200
+ }
6201
+ /**
6202
+ * @param {Uint8Array} data
6203
+ * @param {number} pos
5569
6204
  * @param {number} _minor
5570
6205
  * @param {DecodeOptions} options
5571
6206
  * @returns {Token}
5572
6207
  */
5573
- function decodeBreak(_data, _pos, _minor, options) {
5574
- if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
5575
- return new Token(Type$2.break, void 0, 1);
6208
+ function decodeMap8(data, pos, _minor, options) {
6209
+ return toToken(data, pos, 2, readUint8(data, pos + 1, options));
5576
6210
  }
5577
6211
  /**
5578
- * @param {number} value
5579
- * @param {number} bytes
6212
+ * @param {Uint8Array} data
6213
+ * @param {number} pos
6214
+ * @param {number} _minor
5580
6215
  * @param {DecodeOptions} options
5581
6216
  * @returns {Token}
5582
6217
  */
5583
- function createToken(value, bytes, options) {
5584
- if (options) {
5585
- if (options.allowNaN === false && Number.isNaN(value)) throw new Error(`${decodeErrPrefix} NaN values are not supported`);
5586
- if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
5587
- }
5588
- return new Token(Type$2.float, value, bytes);
6218
+ function decodeMap16(data, pos, _minor, options) {
6219
+ return toToken(data, pos, 3, readUint16(data, pos + 1, options));
5589
6220
  }
5590
6221
  /**
5591
6222
  * @param {Uint8Array} data
@@ -5594,8 +6225,8 @@ function createToken(value, bytes, options) {
5594
6225
  * @param {DecodeOptions} options
5595
6226
  * @returns {Token}
5596
6227
  */
5597
- function decodeFloat16(data, pos, _minor, options) {
5598
- return createToken(readFloat16(data, pos + 1), 3, options);
6228
+ function decodeMap32(data, pos, _minor, options) {
6229
+ return toToken(data, pos, 5, readUint32(data, pos + 1, options));
5599
6230
  }
5600
6231
  /**
5601
6232
  * @param {Uint8Array} data
@@ -5604,8 +6235,10 @@ function decodeFloat16(data, pos, _minor, options) {
5604
6235
  * @param {DecodeOptions} options
5605
6236
  * @returns {Token}
5606
6237
  */
5607
- function decodeFloat32(data, pos, _minor, options) {
5608
- return createToken(readFloat32(data, pos + 1), 5, options);
6238
+ function decodeMap64(data, pos, _minor, options) {
6239
+ const l = readUint64(data, pos + 1, options);
6240
+ if (typeof l === "bigint") throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
6241
+ return toToken(data, pos, 9, l);
5609
6242
  }
5610
6243
  /**
5611
6244
  * @param {Uint8Array} data
@@ -5614,31 +6247,184 @@ function decodeFloat32(data, pos, _minor, options) {
5614
6247
  * @param {DecodeOptions} options
5615
6248
  * @returns {Token}
5616
6249
  */
5617
- function decodeFloat64(data, pos, _minor, options) {
5618
- return createToken(readFloat64(data, pos + 1), 9, options);
6250
+ function decodeMapIndefinite(data, pos, _minor, options) {
6251
+ if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
6252
+ return toToken(data, pos, 1, Infinity);
5619
6253
  }
5620
6254
  /**
5621
6255
  * @param {ByteWriter} writer
5622
6256
  * @param {Token} token
5623
- * @param {EncodeOptions} options
5624
6257
  */
5625
- function encodeFloat(writer, token, options) {
5626
- const float = token.value;
5627
- if (float === false) writer.push([Type$2.float.majorEncoded | 20]);
5628
- else if (float === true) writer.push([Type$2.float.majorEncoded | 21]);
5629
- else if (float === null) writer.push([Type$2.float.majorEncoded | 22]);
5630
- else if (float === void 0) writer.push([Type$2.float.majorEncoded | 23]);
5631
- else {
5632
- let decoded;
5633
- let success = false;
5634
- if (!options || options.float64 !== true) {
5635
- encodeFloat16(float);
5636
- decoded = readFloat16(ui8a, 1);
5637
- if (float === decoded || Number.isNaN(float)) {
5638
- ui8a[0] = 249;
5639
- writer.push(ui8a.slice(0, 3));
5640
- success = true;
5641
- } else {
6258
+ function encodeMap(writer, token) {
6259
+ encodeUintValue(writer, Type$2.map.majorEncoded, token.value);
6260
+ }
6261
+ encodeMap.compareTokens = encodeUint.compareTokens;
6262
+ /**
6263
+ * @param {Token} token
6264
+ * @returns {number}
6265
+ */
6266
+ encodeMap.encodedSize = function encodedSize(token) {
6267
+ return encodeUintValue.encodedSize(token.value);
6268
+ };
6269
+ //#endregion
6270
+ //#region ../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/6tag.js
6271
+ /**
6272
+ * @typedef {import('../interface').ByteWriter} ByteWriter
6273
+ * @typedef {import('../interface').DecodeOptions} DecodeOptions
6274
+ */
6275
+ /**
6276
+ * @param {Uint8Array} _data
6277
+ * @param {number} _pos
6278
+ * @param {number} minor
6279
+ * @param {DecodeOptions} _options
6280
+ * @returns {Token}
6281
+ */
6282
+ function decodeTagCompact(_data, _pos, minor, _options) {
6283
+ return new Token(Type$2.tag, minor, 1);
6284
+ }
6285
+ /**
6286
+ * @param {Uint8Array} data
6287
+ * @param {number} pos
6288
+ * @param {number} _minor
6289
+ * @param {DecodeOptions} options
6290
+ * @returns {Token}
6291
+ */
6292
+ function decodeTag8(data, pos, _minor, options) {
6293
+ return new Token(Type$2.tag, readUint8(data, pos + 1, options), 2);
6294
+ }
6295
+ /**
6296
+ * @param {Uint8Array} data
6297
+ * @param {number} pos
6298
+ * @param {number} _minor
6299
+ * @param {DecodeOptions} options
6300
+ * @returns {Token}
6301
+ */
6302
+ function decodeTag16(data, pos, _minor, options) {
6303
+ return new Token(Type$2.tag, readUint16(data, pos + 1, options), 3);
6304
+ }
6305
+ /**
6306
+ * @param {Uint8Array} data
6307
+ * @param {number} pos
6308
+ * @param {number} _minor
6309
+ * @param {DecodeOptions} options
6310
+ * @returns {Token}
6311
+ */
6312
+ function decodeTag32(data, pos, _minor, options) {
6313
+ return new Token(Type$2.tag, readUint32(data, pos + 1, options), 5);
6314
+ }
6315
+ /**
6316
+ * @param {Uint8Array} data
6317
+ * @param {number} pos
6318
+ * @param {number} _minor
6319
+ * @param {DecodeOptions} options
6320
+ * @returns {Token}
6321
+ */
6322
+ function decodeTag64(data, pos, _minor, options) {
6323
+ return new Token(Type$2.tag, readUint64(data, pos + 1, options), 9);
6324
+ }
6325
+ /**
6326
+ * @param {ByteWriter} writer
6327
+ * @param {Token} token
6328
+ */
6329
+ function encodeTag(writer, token) {
6330
+ encodeUintValue(writer, Type$2.tag.majorEncoded, token.value);
6331
+ }
6332
+ encodeTag.compareTokens = encodeUint.compareTokens;
6333
+ /**
6334
+ * @param {Token} token
6335
+ * @returns {number}
6336
+ */
6337
+ encodeTag.encodedSize = function encodedSize(token) {
6338
+ return encodeUintValue.encodedSize(token.value);
6339
+ };
6340
+ /**
6341
+ * @param {Uint8Array} _data
6342
+ * @param {number} _pos
6343
+ * @param {number} _minor
6344
+ * @param {DecodeOptions} options
6345
+ * @returns {Token}
6346
+ */
6347
+ function decodeUndefined(_data, _pos, _minor, options) {
6348
+ if (options.allowUndefined === false) throw new Error(`${decodeErrPrefix} undefined values are not supported`);
6349
+ else if (options.coerceUndefinedToNull === true) return new Token(Type$2.null, null, 1);
6350
+ return new Token(Type$2.undefined, void 0, 1);
6351
+ }
6352
+ /**
6353
+ * @param {Uint8Array} _data
6354
+ * @param {number} _pos
6355
+ * @param {number} _minor
6356
+ * @param {DecodeOptions} options
6357
+ * @returns {Token}
6358
+ */
6359
+ function decodeBreak(_data, _pos, _minor, options) {
6360
+ if (options.allowIndefinite === false) throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
6361
+ return new Token(Type$2.break, void 0, 1);
6362
+ }
6363
+ /**
6364
+ * @param {number} value
6365
+ * @param {number} bytes
6366
+ * @param {DecodeOptions} options
6367
+ * @returns {Token}
6368
+ */
6369
+ function createToken(value, bytes, options) {
6370
+ if (options) {
6371
+ if (options.allowNaN === false && Number.isNaN(value)) throw new Error(`${decodeErrPrefix} NaN values are not supported`);
6372
+ if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
6373
+ }
6374
+ return new Token(Type$2.float, value, bytes);
6375
+ }
6376
+ /**
6377
+ * @param {Uint8Array} data
6378
+ * @param {number} pos
6379
+ * @param {number} _minor
6380
+ * @param {DecodeOptions} options
6381
+ * @returns {Token}
6382
+ */
6383
+ function decodeFloat16(data, pos, _minor, options) {
6384
+ return createToken(readFloat16(data, pos + 1), 3, options);
6385
+ }
6386
+ /**
6387
+ * @param {Uint8Array} data
6388
+ * @param {number} pos
6389
+ * @param {number} _minor
6390
+ * @param {DecodeOptions} options
6391
+ * @returns {Token}
6392
+ */
6393
+ function decodeFloat32(data, pos, _minor, options) {
6394
+ return createToken(readFloat32(data, pos + 1), 5, options);
6395
+ }
6396
+ /**
6397
+ * @param {Uint8Array} data
6398
+ * @param {number} pos
6399
+ * @param {number} _minor
6400
+ * @param {DecodeOptions} options
6401
+ * @returns {Token}
6402
+ */
6403
+ function decodeFloat64(data, pos, _minor, options) {
6404
+ return createToken(readFloat64(data, pos + 1), 9, options);
6405
+ }
6406
+ /**
6407
+ * @param {ByteWriter} writer
6408
+ * @param {Token} token
6409
+ * @param {EncodeOptions} options
6410
+ */
6411
+ function encodeFloat(writer, token, options) {
6412
+ const float = token.value;
6413
+ if (float === false) writer.push([Type$2.float.majorEncoded | 20]);
6414
+ else if (float === true) writer.push([Type$2.float.majorEncoded | 21]);
6415
+ else if (float === null) writer.push([Type$2.float.majorEncoded | 22]);
6416
+ else if (float === void 0) writer.push([Type$2.float.majorEncoded | 23]);
6417
+ else {
6418
+ let decoded;
6419
+ let success = false;
6420
+ if (!options || options.float64 !== true) {
6421
+ encodeFloat16(float);
6422
+ decoded = readFloat16(ui8a, 1);
6423
+ if (float === decoded || Number.isNaN(float)) {
6424
+ ui8a[0] = 249;
6425
+ writer.push(ui8a.slice(0, 3));
6426
+ success = true;
6427
+ } else {
5642
6428
  encodeFloat32(float);
5643
6429
  decoded = readFloat32(ui8a, 1);
5644
6430
  if (float === decoded) {
@@ -5959,1071 +6745,285 @@ var simpleTokens = {
5959
6745
  true: new Token(Type$2.true, true),
5960
6746
  false: new Token(Type$2.false, false),
5961
6747
  emptyArray: new Token(Type$2.array, 0),
5962
- emptyMap: new Token(Type$2.map, 0)
5963
- };
5964
- /** @type {{[typeName: string]: StrictTypeEncoder}} */
5965
- var typeEncoders = {
5966
- number(obj, _typ, _options, _refStack) {
5967
- if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) return new Token(Type$2.float, obj);
5968
- else if (obj >= 0) return new Token(Type$2.uint, obj);
5969
- else return new Token(Type$2.negint, obj);
5970
- },
5971
- bigint(obj, _typ, _options, _refStack) {
5972
- if (obj >= BigInt(0)) return new Token(Type$2.uint, obj);
5973
- else return new Token(Type$2.negint, obj);
5974
- },
5975
- Uint8Array(obj, _typ, _options, _refStack) {
5976
- return new Token(Type$2.bytes, obj);
5977
- },
5978
- string(obj, _typ, _options, _refStack) {
5979
- return new Token(Type$2.string, obj);
5980
- },
5981
- boolean(obj, _typ, _options, _refStack) {
5982
- return obj ? simpleTokens.true : simpleTokens.false;
5983
- },
5984
- null(_obj, _typ, _options, _refStack) {
5985
- return simpleTokens.null;
5986
- },
5987
- undefined(_obj, _typ, _options, _refStack) {
5988
- return simpleTokens.undefined;
5989
- },
5990
- ArrayBuffer(obj, _typ, _options, _refStack) {
5991
- return new Token(Type$2.bytes, new Uint8Array(obj));
5992
- },
5993
- DataView(obj, _typ, _options, _refStack) {
5994
- return new Token(Type$2.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
5995
- },
5996
- Array(obj, _typ, options, refStack) {
5997
- if (!obj.length) {
5998
- if (options.addBreakTokens === true) return [simpleTokens.emptyArray, new Token(Type$2.break)];
5999
- return simpleTokens.emptyArray;
6000
- }
6001
- refStack = Ref.createCheck(refStack, obj);
6002
- const entries = [];
6003
- let i = 0;
6004
- for (const e of obj) entries[i++] = objectToTokens(e, options, refStack);
6005
- if (options.addBreakTokens) return [
6006
- new Token(Type$2.array, obj.length),
6007
- entries,
6008
- new Token(Type$2.break)
6009
- ];
6010
- return [new Token(Type$2.array, obj.length), entries];
6011
- },
6012
- Object(obj, typ, options, refStack) {
6013
- const isMap = typ !== "Object";
6014
- const keys = isMap ? obj.keys() : Object.keys(obj);
6015
- const maxLength = isMap ? obj.size : keys.length;
6016
- /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
6017
- let entries;
6018
- if (maxLength) {
6019
- entries = new Array(maxLength);
6020
- refStack = Ref.createCheck(refStack, obj);
6021
- const skipUndefined = !isMap && options.ignoreUndefinedProperties;
6022
- let i = 0;
6023
- for (const key of keys) {
6024
- const value = isMap ? obj.get(key) : obj[key];
6025
- if (skipUndefined && value === void 0) continue;
6026
- entries[i++] = [objectToTokens(key, options, refStack), objectToTokens(value, options, refStack)];
6027
- }
6028
- if (i < maxLength) entries.length = i;
6029
- }
6030
- if (!entries?.length) {
6031
- if (options.addBreakTokens === true) return [simpleTokens.emptyMap, new Token(Type$2.break)];
6032
- return simpleTokens.emptyMap;
6033
- }
6034
- sortMapEntries(entries, options);
6035
- if (options.addBreakTokens) return [
6036
- new Token(Type$2.map, entries.length),
6037
- entries,
6038
- new Token(Type$2.break)
6039
- ];
6040
- return [new Token(Type$2.map, entries.length), entries];
6041
- }
6042
- };
6043
- typeEncoders.Map = typeEncoders.Object;
6044
- typeEncoders.Buffer = typeEncoders.Uint8Array;
6045
- for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) typeEncoders[`${typ}Array`] = typeEncoders.DataView;
6046
- /**
6047
- * @param {any} obj
6048
- * @param {EncodeOptions} [options]
6049
- * @param {Reference} [refStack]
6050
- * @returns {TokenOrNestedTokens}
6051
- */
6052
- function objectToTokens(obj, options = {}, refStack) {
6053
- const typ = is(obj);
6054
- const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];
6055
- if (typeof customTypeEncoder === "function") {
6056
- const tokens = customTypeEncoder(obj, typ, options, refStack);
6057
- if (tokens != null) return tokens;
6058
- }
6059
- const typeEncoder = typeEncoders[typ];
6060
- if (!typeEncoder) throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
6061
- return typeEncoder(obj, typ, options, refStack);
6062
- }
6063
- /**
6064
- * @param {TokenOrNestedTokens[]} entries
6065
- * @param {EncodeOptions} options
6066
- */
6067
- function sortMapEntries(entries, options) {
6068
- if (options.mapSorter) entries.sort(options.mapSorter);
6069
- }
6070
- /**
6071
- * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
6072
- *
6073
- * @param {(Token|Token[])[]} e1
6074
- * @param {(Token|Token[])[]} e2
6075
- * @returns {number}
6076
- */
6077
- function rfc8949MapSorter(e1, e2) {
6078
- if (e1[0] instanceof Token && e2[0] instanceof Token) {
6079
- const t1 = e1[0];
6080
- const t2 = e2[0];
6081
- if (!t1._keyBytes) t1._keyBytes = encodeRfc8949(t1.value);
6082
- if (!t2._keyBytes) t2._keyBytes = encodeRfc8949(t2.value);
6083
- return compare(t1._keyBytes, t2._keyBytes);
6084
- }
6085
- throw new Error("rfc8949MapSorter: complex key types are not supported yet");
6086
- }
6087
- /**
6088
- * @param {any} data
6089
- * @returns {Uint8Array}
6090
- */
6091
- function encodeRfc8949(data) {
6092
- return encodeCustom(data, cborEncoders, rfc8949EncodeOptions);
6093
- }
6094
- /**
6095
- * @param {ByteWriter} writer
6096
- * @param {TokenOrNestedTokens} tokens
6097
- * @param {TokenTypeEncoder[]} encoders
6098
- * @param {EncodeOptions} options
6099
- */
6100
- function tokensToEncoded(writer, tokens, encoders, options) {
6101
- if (Array.isArray(tokens)) for (const token of tokens) tokensToEncoded(writer, token, encoders, options);
6102
- else encoders[tokens.type.major](writer, tokens, options);
6103
- }
6104
- Type$2.uint.majorEncoded;
6105
- Type$2.negint.majorEncoded;
6106
- Type$2.bytes.majorEncoded;
6107
- Type$2.string.majorEncoded;
6108
- Type$2.array.majorEncoded;
6109
- Type$2.float.majorEncoded | 20;
6110
- Type$2.float.majorEncoded | 21;
6111
- Type$2.float.majorEncoded | 22;
6112
- Type$2.float.majorEncoded | 23;
6113
- /**
6114
- * @param {any} data
6115
- * @param {TokenTypeEncoder[]} encoders
6116
- * @param {EncodeOptions} options
6117
- * @param {Uint8Array} [destination]
6118
- * @returns {Uint8Array}
6119
- */
6120
- function encodeCustom(data, encoders, options, destination) {
6121
- const hasDest = destination instanceof Uint8Array;
6122
- let writeTo = hasDest ? new U8Bl(destination) : defaultWriter;
6123
- const tokens = objectToTokens(data, options);
6124
- if (!Array.isArray(tokens) && options.quickEncodeToken) {
6125
- const quickBytes = options.quickEncodeToken(tokens);
6126
- if (quickBytes) {
6127
- if (hasDest) {
6128
- writeTo.push(quickBytes);
6129
- return writeTo.toBytes();
6130
- }
6131
- return quickBytes;
6132
- }
6133
- const encoder = encoders[tokens.type.major];
6134
- if (encoder.encodedSize) {
6135
- const size = encoder.encodedSize(tokens, options);
6136
- if (!hasDest) writeTo = new Bl(size);
6137
- encoder(writeTo, tokens, options);
6138
- /* c8 ignore next 4 */
6139
- if (writeTo.chunks.length !== 1) throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
6140
- return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0]);
6141
- }
6142
- }
6143
- writeTo.reset();
6144
- tokensToEncoded(writeTo, tokens, encoders, options);
6145
- return writeTo.toBytes(true);
6146
- }
6147
- //#endregion
6148
- //#region ../../node_modules/.pnpm/@ipld+dag-cbor@9.2.5/node_modules/@ipld/dag-cbor/src/index.js
6149
- var CID_CBOR_TAG = 42;
6150
- /**
6151
- * cidEncoder will receive all Objects during encode, it needs to filter out
6152
- * anything that's not a CID and return `null` for that so it's encoded as
6153
- * normal.
6154
- *
6155
- * @param {any} obj
6156
- * @returns {cborg.Token[]|null}
6157
- */
6158
- function cidEncoder(obj) {
6159
- if (obj.asCID !== obj && obj["/"] !== obj.bytes) return null;
6160
- const cid = CID.asCID(obj);
6161
- /* c8 ignore next 4 */
6162
- if (!cid) return null;
6163
- const bytes = new Uint8Array(cid.bytes.byteLength + 1);
6164
- bytes.set(cid.bytes, 1);
6165
- return [new Token(Type$2.tag, CID_CBOR_TAG), new Token(Type$2.bytes, bytes)];
6166
- }
6167
- /**
6168
- * Intercept all `undefined` values from an object walk and reject the entire
6169
- * object if we find one.
6170
- *
6171
- * @returns {null}
6172
- */
6173
- function undefinedEncoder() {
6174
- throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded");
6175
- }
6176
- /**
6177
- * Intercept all `number` values from an object walk and reject the entire
6178
- * object if we find something that doesn't fit the IPLD data model (NaN &
6179
- * Infinity).
6180
- *
6181
- * @param {number} num
6182
- * @returns {null}
6183
- */
6184
- function numberEncoder(num) {
6185
- if (Number.isNaN(num)) throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");
6186
- if (num === Infinity || num === -Infinity) throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");
6187
- return null;
6188
- }
6189
- /**
6190
- * @param {Map<any, any>} map
6191
- * @returns {null}
6192
- */
6193
- function mapEncoder(map) {
6194
- for (const key of map.keys()) if (typeof key !== "string" || key.length === 0) throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");
6195
- return null;
6196
- }
6197
- var _encodeOptions = {
6198
- float64: true,
6199
- typeEncoders: {
6200
- Map: mapEncoder,
6201
- Object: cidEncoder,
6202
- undefined: undefinedEncoder,
6203
- number: numberEncoder
6204
- }
6205
- };
6206
- ({ ..._encodeOptions }), { ..._encodeOptions.typeEncoders };
6207
- /**
6208
- * @param {Uint8Array} bytes
6209
- * @returns {CID}
6210
- */
6211
- function cidDecoder(bytes) {
6212
- if (bytes[0] !== 0) throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
6213
- return CID.decode(bytes.subarray(1));
6214
- }
6215
- var _decodeOptions = {
6216
- allowIndefinite: false,
6217
- coerceUndefinedToNull: true,
6218
- allowNaN: false,
6219
- allowInfinity: false,
6220
- allowBigInt: true,
6221
- strict: true,
6222
- useMaps: false,
6223
- rejectDuplicateMapKeys: true,
6224
- tags: []
6225
- };
6226
- _decodeOptions.tags[CID_CBOR_TAG] = cidDecoder;
6227
- ({ ..._decodeOptions }), _decodeOptions.tags.slice();
6228
- //#endregion
6229
- //#region ../crypto-service/src/ssh.ts
6230
- /**
6231
- * SSH key format conversion for MoltNet Ed25519 keys
6232
- *
6233
- * Converts MoltNet agent keys (ed25519:<base64>) to OpenSSH format
6234
- * for use with git commit signing and SSH authentication.
6235
- */
6236
- if (!etc.sha512Sync) etc.sha512Sync = (...m) => {
6237
- const hash = createHash$1("sha512");
6238
- m.forEach((msg) => hash.update(msg));
6239
- return hash.digest();
6240
- };
6241
- //#endregion
6242
- //#region ../sdk/src/namespaces/entries.ts
6243
- function createEntriesNamespace(context) {
6244
- const { client, auth } = context;
6245
- return {
6246
- async create(diaryId, body) {
6247
- return unwrapResult(await createDiaryEntry({
6248
- client,
6249
- auth,
6250
- body,
6251
- path: { diaryId }
6252
- }));
6253
- },
6254
- async list(diaryId, query) {
6255
- return unwrapResult(await listDiaryEntries({
6256
- client,
6257
- auth,
6258
- query,
6259
- path: { diaryId }
6260
- }));
6261
- },
6262
- async get(entryId) {
6263
- return unwrapResult(await getDiaryEntryById({
6264
- client,
6265
- auth,
6266
- path: { entryId }
6267
- }));
6268
- },
6269
- async update(entryId, body) {
6270
- return unwrapResult(await updateDiaryEntryById({
6271
- client,
6272
- auth,
6273
- path: { entryId },
6274
- body
6275
- }));
6276
- },
6277
- async delete(entryId) {
6278
- return unwrapResult(await deleteDiaryEntryById({
6279
- client,
6280
- auth,
6281
- path: { entryId }
6282
- }));
6283
- },
6284
- async search(body) {
6285
- return unwrapResult(await searchDiary({
6286
- client,
6287
- auth,
6288
- body
6289
- }));
6290
- },
6291
- async reflect(query) {
6292
- return unwrapResult(await reflectDiary({
6293
- client,
6294
- auth,
6295
- query
6296
- }));
6297
- },
6298
- async verify(entryId) {
6299
- return unwrapResult(await verifyDiaryEntryById({
6300
- client,
6301
- auth,
6302
- path: { entryId }
6303
- }));
6304
- },
6305
- async createSigned(diaryId, body, privateKey) {
6306
- const signingRequest = unwrapResult(await createSigningRequest({
6307
- client,
6308
- auth,
6309
- body: { message: computeContentCid(body.entryType ?? "semantic", body.title ?? null, body.content, body.tags ?? null) }
6310
- }));
6311
- const privateKeyBytes = new Uint8Array(Buffer.from(privateKey, "base64"));
6312
- const signature = await signAsync(new Uint8Array(Buffer.from(signingRequest.signingInput, "base64")), privateKeyBytes);
6313
- const signatureB64 = Buffer.from(signature).toString("base64");
6314
- unwrapResult(await submitSignature({
6315
- client,
6316
- auth,
6317
- path: { id: signingRequest.id },
6318
- body: { signature: signatureB64 }
6319
- }));
6320
- return unwrapResult(await createDiaryEntry({
6321
- client,
6322
- auth,
6323
- path: { diaryId },
6324
- body: {
6325
- ...body,
6326
- signingRequestId: signingRequest.id
6327
- }
6328
- }));
6329
- }
6330
- };
6331
- }
6332
- //#endregion
6333
- //#region ../sdk/src/namespaces/legreffier.ts
6334
- function createLegreffierNamespace(context) {
6335
- const { client } = context;
6336
- return {
6337
- async startOnboarding(body) {
6338
- return unwrapResult(await startLegreffierOnboarding({
6339
- client,
6340
- body
6341
- }));
6342
- },
6343
- async getOnboardingStatus(workflowId) {
6344
- return unwrapResult(await getLegreffierOnboardingStatus({
6345
- client,
6346
- path: { workflowId }
6347
- }));
6348
- }
6349
- };
6350
- }
6351
- //#endregion
6352
- //#region ../sdk/src/namespaces/packs.ts
6353
- function createPacksNamespace(context) {
6354
- const { client, auth } = context;
6355
- return {
6356
- async get(id, query) {
6357
- return unwrapResult(await getContextPackById({
6358
- client,
6359
- auth,
6360
- path: { id },
6361
- query
6362
- }));
6363
- },
6364
- async list(selector) {
6365
- if ("diaryId" in selector) {
6366
- const { diaryId, ...query } = selector;
6367
- return unwrapResult(await listDiaryPacks({
6368
- client,
6369
- auth,
6370
- path: { id: diaryId },
6371
- query
6372
- }));
6373
- }
6374
- const { containsEntry, ...query } = selector;
6375
- return unwrapResult(await listContextPacks({
6376
- client,
6377
- auth,
6378
- query: {
6379
- ...query,
6380
- containsEntry
6381
- }
6382
- }));
6383
- },
6384
- async getProvenance(id, query) {
6385
- return unwrapResult(await getContextPackProvenanceById({
6386
- client,
6387
- auth,
6388
- path: { id },
6389
- query
6390
- }));
6391
- },
6392
- async getProvenanceByCid(cid, query) {
6393
- return unwrapResult(await getContextPackProvenanceByCid({
6394
- client,
6395
- auth,
6396
- path: { cid },
6397
- query
6398
- }));
6399
- },
6400
- async previewRendered(id, body) {
6401
- return unwrapResult(await previewRenderedPack({
6402
- client,
6403
- auth,
6404
- path: { id },
6405
- body
6406
- }));
6407
- },
6408
- async render(id, body) {
6409
- return unwrapResult(await renderContextPack({
6410
- client,
6411
- auth,
6412
- path: { id },
6413
- body
6414
- }));
6415
- },
6416
- async getLatestRendered(id, query) {
6417
- return unwrapResult(await getLatestRenderedPack({
6418
- client,
6419
- auth,
6420
- path: { id },
6421
- query
6422
- }));
6423
- },
6424
- async listRendered(diaryId, query) {
6425
- return unwrapResult(await listDiaryRenderedPacks({
6426
- client,
6427
- auth,
6428
- path: { id: diaryId },
6429
- query
6430
- }));
6431
- },
6432
- async getRendered(id, query) {
6433
- return unwrapResult(await getRenderedPackById({
6434
- client,
6435
- auth,
6436
- path: { id },
6437
- query
6438
- }));
6439
- },
6440
- async update(id, body) {
6441
- return unwrapResult(await updateContextPack({
6442
- client,
6443
- auth,
6444
- path: { id },
6445
- body
6446
- }));
6447
- },
6448
- async updateRendered(id, body) {
6449
- return unwrapResult(await updateRenderedPack({
6450
- client,
6451
- auth,
6452
- path: { id },
6453
- body
6454
- }));
6455
- },
6456
- async create(diaryId, body) {
6457
- return unwrapResult(await createDiaryCustomPack({
6458
- client,
6459
- auth,
6460
- path: { id: diaryId },
6461
- body
6462
- }));
6463
- },
6464
- async preview(diaryId, body) {
6465
- return unwrapResult(await previewDiaryCustomPack({
6466
- client,
6467
- auth,
6468
- path: { id: diaryId },
6469
- body
6470
- }));
6471
- }
6472
- };
6473
- }
6474
- //#endregion
6475
- //#region ../sdk/src/namespaces/problems.ts
6476
- function createProblemsNamespace(context) {
6477
- const { client } = context;
6478
- return {
6479
- async list() {
6480
- return unwrapRequired(await listProblemTypes({ client }), "Failed to list problem types", "PROBLEMS_FAILED");
6481
- },
6482
- async get(type) {
6483
- return unwrapRequired(await getProblemType({
6484
- client,
6485
- path: { type }
6486
- }), `Failed to get problem type: ${type}`, "PROBLEM_TYPE_FAILED");
6487
- }
6488
- };
6489
- }
6490
- //#endregion
6491
- //#region ../sdk/src/namespaces/public.ts
6492
- function createPublicNamespace(context) {
6493
- const { client } = context;
6494
- return {
6495
- async feed(query) {
6496
- return unwrapResult(await getPublicFeed({
6497
- client,
6498
- query
6499
- }));
6500
- },
6501
- async searchFeed(query) {
6502
- return unwrapResult(await searchPublicFeed({
6503
- client,
6504
- query
6505
- }));
6506
- },
6507
- async entry(id) {
6508
- return unwrapResult(await getPublicEntry({
6509
- client,
6510
- path: { id }
6511
- }));
6512
- },
6513
- async networkInfo() {
6514
- return unwrapRequired(await getNetworkInfo({ client }), "Failed to fetch network info", "NETWORK_INFO_FAILED");
6515
- },
6516
- async llmsTxt() {
6517
- return unwrapRequired(await getLlmsTxt({ client }), "Failed to fetch llms.txt", "LLMS_TXT_FAILED");
6518
- },
6519
- async health() {
6520
- return unwrapRequired(await getHealth({ client }), "Failed to fetch health", "HEALTH_FAILED");
6521
- }
6522
- };
6523
- }
6524
- //#endregion
6525
- //#region ../sdk/src/namespaces/recovery.ts
6526
- function createRecoveryNamespace(context) {
6527
- const { client } = context;
6528
- return {
6529
- async requestChallenge(body) {
6530
- return unwrapResult(await requestRecoveryChallenge({
6531
- client,
6532
- body
6533
- }));
6534
- },
6535
- async verifyChallenge(body) {
6536
- return unwrapResult(await verifyRecoveryChallenge({
6537
- client,
6538
- body
6539
- }));
6540
- }
6541
- };
6542
- }
6543
- //#endregion
6544
- //#region ../sdk/src/namespaces/signing-requests.ts
6545
- function createSigningRequestsNamespace(context) {
6546
- const { client, auth } = context;
6547
- return {
6548
- async list(query) {
6549
- return unwrapResult(await listSigningRequests({
6550
- client,
6551
- auth,
6552
- query
6553
- }));
6554
- },
6555
- async create(body) {
6556
- return unwrapResult(await createSigningRequest({
6557
- client,
6558
- auth,
6559
- body
6560
- }));
6561
- },
6562
- async get(id) {
6563
- return unwrapResult(await getSigningRequest({
6564
- client,
6565
- auth,
6566
- path: { id }
6567
- }));
6568
- },
6569
- async submit(id, body) {
6570
- return unwrapResult(await submitSignature({
6571
- client,
6572
- auth,
6573
- path: { id },
6574
- body
6575
- }));
6576
- }
6577
- };
6578
- }
6579
- //#endregion
6580
- //#region ../sdk/src/namespaces/tasks.ts
6581
- function createTasksNamespace(context) {
6582
- const { client, auth } = context;
6583
- return {
6584
- async schemas() {
6585
- return unwrapResult(await listTaskSchemas({
6586
- client,
6587
- auth
6588
- }));
6589
- },
6590
- async list(query) {
6591
- return unwrapResult(await listTasks({
6592
- client,
6593
- auth,
6594
- query
6595
- }));
6596
- },
6597
- async create(body) {
6598
- return unwrapResult(await createTask({
6599
- client,
6600
- auth,
6601
- body
6602
- }));
6603
- },
6604
- async get(id) {
6605
- return unwrapResult(await getTask({
6606
- client,
6607
- auth,
6608
- path: { id }
6609
- }));
6610
- },
6611
- async claim(id, body) {
6612
- const result = await claimTask({
6613
- client,
6614
- auth,
6615
- path: { id },
6616
- body
6617
- });
6618
- const data = unwrapResult(result);
6619
- const traceHeaders = {};
6620
- const traceparent = result.response.headers.get("traceparent");
6621
- if (traceparent) {
6622
- traceHeaders["traceparent"] = traceparent;
6623
- const tracestate = result.response.headers.get("tracestate");
6624
- if (tracestate) traceHeaders["tracestate"] = tracestate;
6625
- }
6626
- return {
6627
- ...data,
6628
- traceHeaders
6629
- };
6630
- },
6631
- async heartbeat(id, n, body) {
6632
- return unwrapResult(await taskHeartbeat({
6633
- client,
6634
- auth,
6635
- path: {
6636
- id,
6637
- n
6638
- },
6639
- body
6640
- }));
6641
- },
6642
- async complete(id, n, body) {
6643
- return unwrapResult(await completeTask({
6644
- client,
6645
- auth,
6646
- path: {
6647
- id,
6648
- n
6649
- },
6650
- body
6651
- }));
6652
- },
6653
- async fail(id, n, body) {
6654
- return unwrapResult(await failTask({
6655
- client,
6656
- auth,
6657
- path: {
6658
- id,
6659
- n
6660
- },
6661
- body
6662
- }));
6663
- },
6664
- async cancel(id, body) {
6665
- return unwrapResult(await cancelTask({
6666
- client,
6667
- auth,
6668
- path: { id },
6669
- body
6670
- }));
6671
- },
6672
- async listAttempts(id) {
6673
- return unwrapResult(await listTaskAttempts({
6674
- client,
6675
- auth,
6676
- path: { id }
6677
- }));
6678
- },
6679
- async listMessages(id, n, query) {
6680
- return unwrapResult(await listTaskMessages({
6681
- client,
6682
- auth,
6683
- path: {
6684
- id,
6685
- n
6686
- },
6687
- query
6688
- }));
6689
- },
6690
- async appendMessages(id, n, body) {
6691
- return unwrapResult(await appendTaskMessages({
6692
- client,
6693
- auth,
6694
- path: {
6695
- id,
6696
- n
6697
- },
6698
- body
6699
- }));
6700
- }
6701
- };
6702
- }
6703
- //#endregion
6704
- //#region ../sdk/src/namespaces/teams.ts
6705
- function createTeamsNamespace(context) {
6706
- const { client, auth } = context;
6707
- return {
6708
- async list() {
6709
- return unwrapResult(await listTeams({
6710
- client,
6711
- auth
6712
- }));
6713
- },
6714
- async get(id) {
6715
- return unwrapResult(await getTeam({
6716
- client,
6717
- auth,
6718
- path: { id }
6719
- }));
6720
- },
6721
- async listMembers(id) {
6722
- return unwrapResult(await listTeamMembers({
6723
- client,
6724
- auth,
6725
- path: { id }
6726
- }));
6727
- },
6728
- async create(body) {
6729
- return unwrapResult(await createTeam({
6730
- client,
6731
- auth,
6732
- body
6733
- }));
6734
- },
6735
- async join(code) {
6736
- return unwrapResult(await joinTeam({
6737
- client,
6738
- auth,
6739
- body: { code }
6740
- }));
6741
- },
6742
- async delete(id) {
6743
- return unwrapResult(await deleteTeam({
6744
- client,
6745
- auth,
6746
- path: { id }
6747
- }));
6748
- },
6749
- async removeMember(teamId, subjectId) {
6750
- return unwrapResult(await removeTeamMember({
6751
- client,
6752
- auth,
6753
- path: {
6754
- id: teamId,
6755
- subjectId
6756
- }
6757
- }));
6758
- },
6759
- invites: {
6760
- async create(teamId, body) {
6761
- return unwrapResult(await createTeamInvite({
6762
- client,
6763
- auth,
6764
- path: { id: teamId },
6765
- body
6766
- }));
6767
- },
6768
- async list(teamId) {
6769
- return unwrapResult(await listTeamInvites({
6770
- client,
6771
- auth,
6772
- path: { id: teamId }
6773
- }));
6774
- },
6775
- async delete(teamId, inviteId) {
6776
- return unwrapResult(await deleteTeamInvite({
6777
- client,
6778
- auth,
6779
- path: {
6780
- id: teamId,
6781
- inviteId
6782
- }
6783
- }));
6748
+ emptyMap: new Token(Type$2.map, 0)
6749
+ };
6750
+ /** @type {{[typeName: string]: StrictTypeEncoder}} */
6751
+ var typeEncoders = {
6752
+ number(obj, _typ, _options, _refStack) {
6753
+ if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) return new Token(Type$2.float, obj);
6754
+ else if (obj >= 0) return new Token(Type$2.uint, obj);
6755
+ else return new Token(Type$2.negint, obj);
6756
+ },
6757
+ bigint(obj, _typ, _options, _refStack) {
6758
+ if (obj >= BigInt(0)) return new Token(Type$2.uint, obj);
6759
+ else return new Token(Type$2.negint, obj);
6760
+ },
6761
+ Uint8Array(obj, _typ, _options, _refStack) {
6762
+ return new Token(Type$2.bytes, obj);
6763
+ },
6764
+ string(obj, _typ, _options, _refStack) {
6765
+ return new Token(Type$2.string, obj);
6766
+ },
6767
+ boolean(obj, _typ, _options, _refStack) {
6768
+ return obj ? simpleTokens.true : simpleTokens.false;
6769
+ },
6770
+ null(_obj, _typ, _options, _refStack) {
6771
+ return simpleTokens.null;
6772
+ },
6773
+ undefined(_obj, _typ, _options, _refStack) {
6774
+ return simpleTokens.undefined;
6775
+ },
6776
+ ArrayBuffer(obj, _typ, _options, _refStack) {
6777
+ return new Token(Type$2.bytes, new Uint8Array(obj));
6778
+ },
6779
+ DataView(obj, _typ, _options, _refStack) {
6780
+ return new Token(Type$2.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
6781
+ },
6782
+ Array(obj, _typ, options, refStack) {
6783
+ if (!obj.length) {
6784
+ if (options.addBreakTokens === true) return [simpleTokens.emptyArray, new Token(Type$2.break)];
6785
+ return simpleTokens.emptyArray;
6786
+ }
6787
+ refStack = Ref.createCheck(refStack, obj);
6788
+ const entries = [];
6789
+ let i = 0;
6790
+ for (const e of obj) entries[i++] = objectToTokens(e, options, refStack);
6791
+ if (options.addBreakTokens) return [
6792
+ new Token(Type$2.array, obj.length),
6793
+ entries,
6794
+ new Token(Type$2.break)
6795
+ ];
6796
+ return [new Token(Type$2.array, obj.length), entries];
6797
+ },
6798
+ Object(obj, typ, options, refStack) {
6799
+ const isMap = typ !== "Object";
6800
+ const keys = isMap ? obj.keys() : Object.keys(obj);
6801
+ const maxLength = isMap ? obj.size : keys.length;
6802
+ /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
6803
+ let entries;
6804
+ if (maxLength) {
6805
+ entries = new Array(maxLength);
6806
+ refStack = Ref.createCheck(refStack, obj);
6807
+ const skipUndefined = !isMap && options.ignoreUndefinedProperties;
6808
+ let i = 0;
6809
+ for (const key of keys) {
6810
+ const value = isMap ? obj.get(key) : obj[key];
6811
+ if (skipUndefined && value === void 0) continue;
6812
+ entries[i++] = [objectToTokens(key, options, refStack), objectToTokens(value, options, refStack)];
6784
6813
  }
6814
+ if (i < maxLength) entries.length = i;
6785
6815
  }
6786
- };
6787
- }
6788
- //#endregion
6789
- //#region ../sdk/src/namespaces/vouch.ts
6790
- function createVouchNamespace(context) {
6791
- const { client, auth } = context;
6792
- return {
6793
- async issue() {
6794
- return unwrapResult(await issueVoucher({
6795
- client,
6796
- auth
6797
- }));
6798
- },
6799
- async listActive() {
6800
- return unwrapResult(await listActiveVouchers({
6801
- client,
6802
- auth
6803
- }));
6804
- },
6805
- async trustGraph(query) {
6806
- return unwrapResult(await getTrustGraph({
6807
- client,
6808
- query
6809
- }));
6816
+ if (!entries?.length) {
6817
+ if (options.addBreakTokens === true) return [simpleTokens.emptyMap, new Token(Type$2.break)];
6818
+ return simpleTokens.emptyMap;
6810
6819
  }
6811
- };
6820
+ sortMapEntries(entries, options);
6821
+ if (options.addBreakTokens) return [
6822
+ new Token(Type$2.map, entries.length),
6823
+ entries,
6824
+ new Token(Type$2.break)
6825
+ ];
6826
+ return [new Token(Type$2.map, entries.length), entries];
6827
+ }
6828
+ };
6829
+ typeEncoders.Map = typeEncoders.Object;
6830
+ typeEncoders.Buffer = typeEncoders.Uint8Array;
6831
+ for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) typeEncoders[`${typ}Array`] = typeEncoders.DataView;
6832
+ /**
6833
+ * @param {any} obj
6834
+ * @param {EncodeOptions} [options]
6835
+ * @param {Reference} [refStack]
6836
+ * @returns {TokenOrNestedTokens}
6837
+ */
6838
+ function objectToTokens(obj, options = {}, refStack) {
6839
+ const typ = is(obj);
6840
+ const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];
6841
+ if (typeof customTypeEncoder === "function") {
6842
+ const tokens = customTypeEncoder(obj, typ, options, refStack);
6843
+ if (tokens != null) return tokens;
6844
+ }
6845
+ const typeEncoder = typeEncoders[typ];
6846
+ if (!typeEncoder) throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
6847
+ return typeEncoder(obj, typ, options, refStack);
6812
6848
  }
6813
- //#endregion
6814
- //#region ../sdk/src/agent.ts
6815
- function createAgent(options) {
6816
- const { client, tokenManager, auth } = options;
6817
- const context = {
6818
- client,
6819
- auth
6820
- };
6821
- return {
6822
- diaries: createDiariesNamespace(context),
6823
- diaryGrants: createDiaryGrantsNamespace(context),
6824
- packs: createPacksNamespace(context),
6825
- entries: createEntriesNamespace(context),
6826
- agents: createAgentsNamespace(context),
6827
- crypto: createCryptoNamespace(context, createSigningRequestsNamespace(context)),
6828
- vouch: createVouchNamespace(context),
6829
- auth: createAuthNamespace(context),
6830
- recovery: createRecoveryNamespace(context),
6831
- public: createPublicNamespace(context),
6832
- legreffier: createLegreffierNamespace(context),
6833
- problems: createProblemsNamespace(context),
6834
- teams: createTeamsNamespace(context),
6835
- tasks: createTasksNamespace(context),
6836
- client,
6837
- getToken: () => tokenManager.getToken()
6838
- };
6849
+ /**
6850
+ * @param {TokenOrNestedTokens[]} entries
6851
+ * @param {EncodeOptions} options
6852
+ */
6853
+ function sortMapEntries(entries, options) {
6854
+ if (options.mapSorter) entries.sort(options.mapSorter);
6839
6855
  }
6840
- //#endregion
6841
- //#region ../sdk/src/config.ts
6842
6856
  /**
6843
- * Read MoltNet credentials from environment variables.
6844
- * Reads MOLTNET_CLIENT_ID, MOLTNET_CLIENT_SECRET, and MOLTNET_API_URL.
6857
+ * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
6858
+ *
6859
+ * @param {(Token|Token[])[]} e1
6860
+ * @param {(Token|Token[])[]} e2
6861
+ * @returns {number}
6845
6862
  */
6846
- function readEnvCredentials() {
6847
- return {
6848
- clientId: process.env.MOLTNET_CLIENT_ID,
6849
- clientSecret: process.env.MOLTNET_CLIENT_SECRET,
6850
- apiUrl: process.env.MOLTNET_API_URL
6851
- };
6863
+ function rfc8949MapSorter(e1, e2) {
6864
+ if (e1[0] instanceof Token && e2[0] instanceof Token) {
6865
+ const t1 = e1[0];
6866
+ const t2 = e2[0];
6867
+ if (!t1._keyBytes) t1._keyBytes = encodeRfc8949(t1.value);
6868
+ if (!t2._keyBytes) t2._keyBytes = encodeRfc8949(t2.value);
6869
+ return compare(t1._keyBytes, t2._keyBytes);
6870
+ }
6871
+ throw new Error("rfc8949MapSorter: complex key types are not supported yet");
6872
+ }
6873
+ /**
6874
+ * @param {any} data
6875
+ * @returns {Uint8Array}
6876
+ */
6877
+ function encodeRfc8949(data) {
6878
+ return encodeCustom(data, cborEncoders, rfc8949EncodeOptions);
6879
+ }
6880
+ /**
6881
+ * @param {ByteWriter} writer
6882
+ * @param {TokenOrNestedTokens} tokens
6883
+ * @param {TokenTypeEncoder[]} encoders
6884
+ * @param {EncodeOptions} options
6885
+ */
6886
+ function tokensToEncoded(writer, tokens, encoders, options) {
6887
+ if (Array.isArray(tokens)) for (const token of tokens) tokensToEncoded(writer, token, encoders, options);
6888
+ else encoders[tokens.type.major](writer, tokens, options);
6889
+ }
6890
+ Type$2.uint.majorEncoded;
6891
+ Type$2.negint.majorEncoded;
6892
+ Type$2.bytes.majorEncoded;
6893
+ Type$2.string.majorEncoded;
6894
+ Type$2.array.majorEncoded;
6895
+ Type$2.float.majorEncoded | 20;
6896
+ Type$2.float.majorEncoded | 21;
6897
+ Type$2.float.majorEncoded | 22;
6898
+ Type$2.float.majorEncoded | 23;
6899
+ /**
6900
+ * @param {any} data
6901
+ * @param {TokenTypeEncoder[]} encoders
6902
+ * @param {EncodeOptions} options
6903
+ * @param {Uint8Array} [destination]
6904
+ * @returns {Uint8Array}
6905
+ */
6906
+ function encodeCustom(data, encoders, options, destination) {
6907
+ const hasDest = destination instanceof Uint8Array;
6908
+ let writeTo = hasDest ? new U8Bl(destination) : defaultWriter;
6909
+ const tokens = objectToTokens(data, options);
6910
+ if (!Array.isArray(tokens) && options.quickEncodeToken) {
6911
+ const quickBytes = options.quickEncodeToken(tokens);
6912
+ if (quickBytes) {
6913
+ if (hasDest) {
6914
+ writeTo.push(quickBytes);
6915
+ return writeTo.toBytes();
6916
+ }
6917
+ return quickBytes;
6918
+ }
6919
+ const encoder = encoders[tokens.type.major];
6920
+ if (encoder.encodedSize) {
6921
+ const size = encoder.encodedSize(tokens, options);
6922
+ if (!hasDest) writeTo = new Bl(size);
6923
+ encoder(writeTo, tokens, options);
6924
+ /* c8 ignore next 4 */
6925
+ if (writeTo.chunks.length !== 1) throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
6926
+ return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0]);
6927
+ }
6928
+ }
6929
+ writeTo.reset();
6930
+ tokensToEncoded(writeTo, tokens, encoders, options);
6931
+ return writeTo.toBytes(true);
6852
6932
  }
6853
6933
  //#endregion
6854
- //#region ../sdk/src/credentials.ts
6855
- function getConfigDir() {
6856
- return join(homedir(), ".config", "moltnet");
6934
+ //#region ../../node_modules/.pnpm/@ipld+dag-cbor@9.2.5/node_modules/@ipld/dag-cbor/src/index.js
6935
+ var CID_CBOR_TAG = 42;
6936
+ /**
6937
+ * cidEncoder will receive all Objects during encode, it needs to filter out
6938
+ * anything that's not a CID and return `null` for that so it's encoded as
6939
+ * normal.
6940
+ *
6941
+ * @param {any} obj
6942
+ * @returns {cborg.Token[]|null}
6943
+ */
6944
+ function cidEncoder(obj) {
6945
+ if (obj.asCID !== obj && obj["/"] !== obj.bytes) return null;
6946
+ const cid = CID.asCID(obj);
6947
+ /* c8 ignore next 4 */
6948
+ if (!cid) return null;
6949
+ const bytes = new Uint8Array(cid.bytes.byteLength + 1);
6950
+ bytes.set(cid.bytes, 1);
6951
+ return [new Token(Type$2.tag, CID_CBOR_TAG), new Token(Type$2.bytes, bytes)];
6857
6952
  }
6858
6953
  /**
6859
- * Read the MoltNet config file.
6860
- * Tries `moltnet.json` first; falls back to `credentials.json` with a
6861
- * deprecation warning printed to stderr.
6954
+ * Intercept all `undefined` values from an object walk and reject the entire
6955
+ * object if we find one.
6956
+ *
6957
+ * @returns {null}
6862
6958
  */
6863
- async function readConfig(configDir) {
6864
- const dir = configDir ?? getConfigDir();
6865
- try {
6866
- const content = await readFile(join(dir, "moltnet.json"), "utf-8");
6867
- return JSON.parse(content);
6868
- } catch {}
6869
- try {
6870
- const content = await readFile(join(dir, "credentials.json"), "utf-8");
6871
- console.warn("Warning: credentials.json is deprecated. New writes use moltnet.json. Support will be removed in 3 minor versions.");
6872
- return JSON.parse(content);
6873
- } catch {
6874
- return null;
6875
- }
6959
+ function undefinedEncoder() {
6960
+ throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded");
6876
6961
  }
6877
- //#endregion
6878
- //#region ../sdk/src/retry.ts
6879
- var AUTH_RETRY_DEFAULT = 1;
6880
6962
  /**
6881
- * Create a fetch wrapper that retries on 401 and 429.
6882
- *
6883
- * - **401**: Invalidates the cached token, re-authenticates, replays once.
6884
- * - **429**: Delegates to `createRateLimitFetch` from `@moltnet/api-client/retry`.
6963
+ * Intercept all `number` values from an object walk and reject the entire
6964
+ * object if we find something that doesn't fit the IPLD data model (NaN &
6965
+ * Infinity).
6885
6966
  *
6886
- * 5xx and network errors are not retried — non-idempotent methods (POST, PATCH)
6887
- * could cause duplicate side effects.
6967
+ * @param {number} num
6968
+ * @returns {null}
6888
6969
  */
6889
- function createRetryFetch(tokenManager, options) {
6890
- const maxAuthRetries = options?.maxAuthRetries ?? AUTH_RETRY_DEFAULT;
6891
- const rateLimitFetch = createRateLimitFetch({
6892
- maxRetries: options?.maxRateLimitRetries,
6893
- baseDelayMs: options?.baseDelayMs,
6894
- maxDelayMs: options?.maxDelayMs
6895
- });
6896
- return async (input, init) => {
6897
- let authRetries = 0;
6898
- const doFetch = async (fetchInit) => {
6899
- const response = await rateLimitFetch(input, fetchInit);
6900
- if (response.status === 401 && authRetries < maxAuthRetries) {
6901
- authRetries++;
6902
- tokenManager.invalidate();
6903
- const freshToken = await tokenManager.authenticate();
6904
- const headers = new Headers(fetchInit?.headers);
6905
- headers.set("Authorization", `Bearer ${freshToken}`);
6906
- return doFetch({
6907
- ...fetchInit,
6908
- headers
6909
- });
6910
- }
6911
- return response;
6912
- };
6913
- return doFetch(init);
6914
- };
6970
+ function numberEncoder(num) {
6971
+ if (Number.isNaN(num)) throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");
6972
+ if (num === Infinity || num === -Infinity) throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");
6973
+ return null;
6915
6974
  }
6916
- //#endregion
6917
- //#region ../sdk/src/token.ts
6918
- var TokenManager = class {
6919
- clientId;
6920
- clientSecret;
6921
- tokenUrl;
6922
- expiryBufferMs;
6923
- cached = null;
6924
- constructor(options) {
6925
- const apiUrl = options.apiUrl.replace(/\/$/, "");
6926
- this.clientId = options.clientId;
6927
- this.clientSecret = options.clientSecret;
6928
- this.tokenUrl = `${apiUrl}/oauth2/token`;
6929
- this.expiryBufferMs = options.expiryBufferMs ?? 3e4;
6930
- }
6931
- /** Return a valid access token, obtaining or refreshing as needed. */
6932
- async getToken() {
6933
- if (this.cached && Date.now() < this.cached.expiresAt) return this.cached.accessToken;
6934
- return this.authenticate();
6935
- }
6936
- /** Force-obtain a new token, replacing any cached value. */
6937
- async authenticate() {
6938
- const body = new URLSearchParams({
6939
- grant_type: "client_credentials",
6940
- client_id: this.clientId,
6941
- client_secret: this.clientSecret
6942
- });
6943
- let response;
6944
- try {
6945
- response = await fetch(this.tokenUrl, {
6946
- method: "POST",
6947
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
6948
- body: body.toString()
6949
- });
6950
- } catch (error) {
6951
- throw new NetworkError(error instanceof Error ? error.message : "Token request failed", { detail: error instanceof Error ? error.cause?.toString() : String(error) });
6952
- }
6953
- const json = await response.json();
6954
- if (!response.ok || "error" in json) {
6955
- const errBody = json;
6956
- throw new AuthenticationError(errBody.error_description ?? errBody.error, {
6957
- statusCode: response.status,
6958
- detail: errBody.error
6959
- });
6960
- }
6961
- const tokenBody = json;
6962
- this.cached = {
6963
- accessToken: tokenBody.access_token,
6964
- expiresAt: Date.now() + tokenBody.expires_in * 1e3 - this.expiryBufferMs
6965
- };
6966
- return this.cached.accessToken;
6967
- }
6968
- /** Clear the cached token. Next getToken() call will re-authenticate. */
6969
- invalidate() {
6970
- this.cached = null;
6975
+ /**
6976
+ * @param {Map<any, any>} map
6977
+ * @returns {null}
6978
+ */
6979
+ function mapEncoder(map) {
6980
+ for (const key of map.keys()) if (typeof key !== "string" || key.length === 0) throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");
6981
+ return null;
6982
+ }
6983
+ var _encodeOptions = {
6984
+ float64: true,
6985
+ typeEncoders: {
6986
+ Map: mapEncoder,
6987
+ Object: cidEncoder,
6988
+ undefined: undefinedEncoder,
6989
+ number: numberEncoder
6971
6990
  }
6972
6991
  };
6973
- //#endregion
6974
- //#region ../sdk/src/connect.ts
6975
- var DEFAULT_API_URL = "https://api.themolt.net";
6976
- async function resolveCredentials(options) {
6977
- if (options.clientId && options.clientSecret) return {
6978
- clientId: options.clientId,
6979
- clientSecret: options.clientSecret,
6980
- apiUrl: (options.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "")
6981
- };
6982
- const env = readEnvCredentials();
6983
- if (env.clientId && env.clientSecret) return {
6984
- clientId: env.clientId,
6985
- clientSecret: env.clientSecret,
6986
- apiUrl: (env.apiUrl ?? options.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "")
6987
- };
6988
- const config = await readConfig(options.configDir);
6989
- if (config?.oauth2?.client_id && config?.oauth2?.client_secret) return {
6990
- clientId: config.oauth2.client_id,
6991
- clientSecret: config.oauth2.client_secret,
6992
- apiUrl: (options.apiUrl ?? config.endpoints?.api ?? DEFAULT_API_URL).replace(/\/$/, "")
6993
- };
6994
- throw new MoltNetError("No credentials found. Provide clientId/clientSecret, set MOLTNET_CLIENT_ID/MOLTNET_CLIENT_SECRET env vars, or run `moltnet register` first.", { code: "NO_CREDENTIALS" });
6992
+ ({ ..._encodeOptions }), { ..._encodeOptions.typeEncoders };
6993
+ /**
6994
+ * @param {Uint8Array} bytes
6995
+ * @returns {CID}
6996
+ */
6997
+ function cidDecoder(bytes) {
6998
+ if (bytes[0] !== 0) throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
6999
+ return CID.decode(bytes.subarray(1));
6995
7000
  }
7001
+ var _decodeOptions = {
7002
+ allowIndefinite: false,
7003
+ coerceUndefinedToNull: true,
7004
+ allowNaN: false,
7005
+ allowInfinity: false,
7006
+ allowBigInt: true,
7007
+ strict: true,
7008
+ useMaps: false,
7009
+ rejectDuplicateMapKeys: true,
7010
+ tags: []
7011
+ };
7012
+ _decodeOptions.tags[CID_CBOR_TAG] = cidDecoder;
7013
+ ({ ..._decodeOptions }), _decodeOptions.tags.slice();
7014
+ //#endregion
7015
+ //#region ../crypto-service/src/ssh.ts
6996
7016
  /**
6997
- * Connect to MoltNet and return an authenticated Agent facade.
7017
+ * SSH key format conversion for MoltNet Ed25519 keys
6998
7018
  *
6999
- * Credential resolution order:
7000
- * 1. Explicit `clientId` / `clientSecret` in options
7001
- * 2. `MOLTNET_CLIENT_ID` / `MOLTNET_CLIENT_SECRET` environment variables
7002
- * 3. Config file (`~/.config/moltnet/moltnet.json`)
7019
+ * Converts MoltNet agent keys (ed25519:<base64>) to OpenSSH format
7020
+ * for use with git commit signing and SSH authentication.
7003
7021
  */
7004
- async function connect(options = {}) {
7005
- const creds = await resolveCredentials(options);
7006
- const autoToken = options.autoToken ?? true;
7007
- const tokenManager = new TokenManager({
7008
- clientId: creds.clientId,
7009
- clientSecret: creds.clientSecret,
7010
- apiUrl: creds.apiUrl
7011
- });
7012
- const retryFetch = autoToken && options.retry !== false ? createRetryFetch(tokenManager, options.retry === void 0 ? void 0 : options.retry) : void 0;
7013
- const customFetch = retryFetch ?? (autoToken && !retryFetch ? async (input, init) => {
7014
- const response = await fetch(input, init);
7015
- if (response.status === 401) tokenManager.invalidate();
7016
- return response;
7017
- } : void 0);
7018
- return createAgent({
7019
- client: createClient({
7020
- baseUrl: creds.apiUrl,
7021
- ...customFetch && { fetch: customFetch }
7022
- }),
7023
- tokenManager,
7024
- auth: autoToken ? () => tokenManager.getToken() : void 0
7025
- });
7026
- }
7022
+ if (!etc.sha512Sync) etc.sha512Sync = (...m) => {
7023
+ const hash = createHash$1("sha512");
7024
+ m.forEach((msg) => hash.update(msg));
7025
+ return hash.digest();
7026
+ };
7027
7027
  //#endregion
7028
7028
  //#region src/commands/moltnet-reflect.ts
7029
7029
  var registerMoltnetReflectCommand = (pi, state) => {
@@ -7673,7 +7673,7 @@ function createMoltNetTools(config) {
7673
7673
  const createEntry = defineTool({
7674
7674
  name: "moltnet_create_entry",
7675
7675
  label: "Create MoltNet Diary Entry",
7676
- description: "Create a new diary entry to record decisions, findings, incidents, or reflections. During an active task, the entry is forced into the task diary and tagged with the task:* provenance namespace (task:id:<id>, task:type:<type>, task:attempt:<n>, plus task:correlation:<id> when set); an explicit diaryId mismatching the task diary is rejected.",
7676
+ description: "Create a new diary entry to record decisions, findings, incidents, or reflections. During an active task, the entry is forced into the task diary and tagged with the task:* provenance namespace (task:id:<id>, task:type:<type>, task:attempt:<n>, plus task:correlation:<id> when set); an explicit diaryId mismatching the task diary is rejected. Use this tool — NOT `moltnet entry create` / `moltnet entry create-signed` via bash. The CLI path bypasses task-tag auto-injection and leaves entries invisible to taskFilter queries.",
7677
7677
  parameters: Type.Object({
7678
7678
  title: Type.String({ description: "Entry title (concise, descriptive)" }),
7679
7679
  content: Type.String({ description: "Entry content (markdown)" }),
@@ -8253,38 +8253,48 @@ async function resumeVm(config) {
8253
8253
  [GUEST_TASK_SKILLS_MOUNT]: new MemoryProvider()
8254
8254
  } }
8255
8255
  });
8256
- await vm.exec(`sh -c '
8256
+ try {
8257
+ await vm.exec(`sh -c '
8257
8258
  cp /etc/gondolin/mitm/ca.crt /usr/local/share/ca-certificates/gondolin-mitm.crt
8258
8259
  update-ca-certificates 2>/dev/null
8259
8260
  cat /etc/gondolin/mitm/ca.crt >> /etc/ssl/certs/ca-certificates.crt
8260
8261
  '`);
8261
- await vmRun(vm, "DNS resolvers", `printf 'nameserver 8.8.8.8\\nnameserver 1.1.1.1\\n' > /etc/resolv.conf`);
8262
- await vmRun(vm, "git safe.directory", `git config --system --add safe.directory '*'`);
8263
- for (const [i, cmd] of (config.sandboxConfig?.resumeCommands ?? []).entries()) await vmRun(vm, `resumeCommands[${i}]`, cmd);
8264
- const vmSshDir = `${vmAgentDir}/ssh`;
8265
- await vm.exec(`mkdir -p ${vmAgentDir}/ssh /home/agent/.pi/agent`);
8266
- if (creds.piAuthJson !== null) await vm.fs.writeFile("/home/agent/.pi/agent/auth.json", creds.piAuthJson, { mode: 384 });
8267
- const vmMoltnetJson = rewriteMoltnetJsonPaths(creds.moltnetJson, vmAgentDir, vmSshDir, creds.githubAppPemFilename);
8268
- await vm.fs.writeFile(`${vmAgentDir}/moltnet.json`, vmMoltnetJson, { mode: 384 });
8269
- await vm.fs.writeFile(`${vmAgentDir}/env`, creds.agentEnvRaw, { mode: 384 });
8270
- if (creds.gitconfig) {
8271
- const vmSigningKey = `${vmSshDir}/id_ed25519`;
8272
- let vmGitconfig = creds.gitconfig.replace(/signingKey\s*=\s*.+/g, `signingKey = ${vmSigningKey}`);
8273
- vmGitconfig = ensureRelativeWorktreePaths(vmGitconfig);
8274
- await vm.fs.writeFile(`${vmAgentDir}/gitconfig`, vmGitconfig, { mode: 420 });
8275
- }
8276
- if (creds.sshPrivateKey) await vm.fs.writeFile(`${vmSshDir}/id_ed25519`, creds.sshPrivateKey, { mode: 384 });
8277
- if (creds.sshPublicKey) await vm.fs.writeFile(`${vmSshDir}/id_ed25519.pub`, creds.sshPublicKey, { mode: 420 });
8278
- if (creds.allowedSigners) await vm.fs.writeFile(`${vmSshDir}/allowed_signers`, creds.allowedSigners, { mode: 420 });
8279
- if (creds.githubAppPem && creds.githubAppPemFilename) await vm.fs.writeFile(`${vmAgentDir}/${creds.githubAppPemFilename}`, creds.githubAppPem, { mode: 384 });
8280
- await vm.exec("chown -R agent:agent /home/agent/.pi /home/agent/.moltnet");
8281
- return {
8282
- vm,
8283
- credentials: creds,
8284
- mountPath: config.mountPath,
8285
- guestWorkspace: GUEST_WORKSPACE$2,
8286
- agentDir
8287
- };
8262
+ await vmRun(vm, "DNS resolvers", `printf 'nameserver 8.8.8.8\\nnameserver 1.1.1.1\\n' > /etc/resolv.conf`);
8263
+ await vmRun(vm, "git safe.directory", `git config --system --add safe.directory '*'`);
8264
+ for (const [i, cmd] of (config.sandboxConfig?.resumeCommands ?? []).entries()) await vmRun(vm, `resumeCommands[${i}]`, cmd);
8265
+ const vmSshDir = `${vmAgentDir}/ssh`;
8266
+ await vm.exec(`mkdir -p ${vmAgentDir}/ssh /home/agent/.pi/agent`);
8267
+ if (creds.piAuthJson !== null) await vm.fs.writeFile("/home/agent/.pi/agent/auth.json", creds.piAuthJson, { mode: 384 });
8268
+ const vmMoltnetJson = rewriteMoltnetJsonPaths(creds.moltnetJson, vmAgentDir, vmSshDir, creds.githubAppPemFilename);
8269
+ await vm.fs.writeFile(`${vmAgentDir}/moltnet.json`, vmMoltnetJson, { mode: 384 });
8270
+ await vm.fs.writeFile(`${vmAgentDir}/env`, creds.agentEnvRaw, { mode: 384 });
8271
+ if (creds.gitconfig) {
8272
+ const vmSigningKey = `${vmSshDir}/id_ed25519`;
8273
+ let vmGitconfig = creds.gitconfig.replace(/signingKey\s*=\s*.+/g, `signingKey = ${vmSigningKey}`);
8274
+ vmGitconfig = ensureRelativeWorktreePaths(vmGitconfig);
8275
+ await vm.fs.writeFile(`${vmAgentDir}/gitconfig`, vmGitconfig, { mode: 420 });
8276
+ }
8277
+ if (creds.sshPrivateKey) await vm.fs.writeFile(`${vmSshDir}/id_ed25519`, creds.sshPrivateKey, { mode: 384 });
8278
+ if (creds.sshPublicKey) await vm.fs.writeFile(`${vmSshDir}/id_ed25519.pub`, creds.sshPublicKey, { mode: 420 });
8279
+ if (creds.allowedSigners) await vm.fs.writeFile(`${vmSshDir}/allowed_signers`, creds.allowedSigners, { mode: 420 });
8280
+ if (creds.githubAppPem && creds.githubAppPemFilename) await vm.fs.writeFile(`${vmAgentDir}/${creds.githubAppPemFilename}`, creds.githubAppPem, { mode: 384 });
8281
+ await vm.exec("chown -R agent:agent /home/agent/.pi /home/agent/.moltnet");
8282
+ return {
8283
+ vm,
8284
+ credentials: creds,
8285
+ mountPath: config.mountPath,
8286
+ guestWorkspace: GUEST_WORKSPACE$2,
8287
+ agentDir
8288
+ };
8289
+ } catch (err) {
8290
+ try {
8291
+ await vm.close();
8292
+ } catch (closeErr) {
8293
+ const m = closeErr instanceof Error ? closeErr.message : String(closeErr);
8294
+ process.stderr.write(`[vm] post-throw vm.close() failed: ${m}\n`);
8295
+ }
8296
+ throw err;
8297
+ }
8288
8298
  }
8289
8299
  /**
8290
8300
  * Rewrite host-absolute paths inside moltnet.json to VM-local equivalents.
@@ -14706,8 +14716,8 @@ function buildRuntimeInstructor(ctx) {
14706
14716
  "## Diary discipline",
14707
14717
  "",
14708
14718
  `- During this task, every diary entry MUST land in \`${ctx.diaryId}\``,
14709
- " (the task diary). The MCP `moltnet_create_entry` tool enforces this",
14710
- " and rejects mismatched explicit `diaryId` parameters.",
14719
+ " (the task diary). The `moltnet_create_entry` custom tool enforces",
14720
+ " this and rejects mismatched explicit `diaryId` parameters.",
14711
14721
  `- Provenance tags \`task:id:${ctx.taskId}\`, \`task:type:${ctx.taskType}\`,`,
14712
14722
  ` and \`task:attempt:${ctx.attemptN}\`${ctx.correlationId ? `, plus \`task:correlation:${ctx.correlationId}\`` : ""} are auto-injected on every entry.`,
14713
14723
  " These share the `task:` namespace so `moltnet_diary_tags` with",
@@ -14715,12 +14725,23 @@ function buildRuntimeInstructor(ctx) {
14715
14725
  " `taskFilter` shorthand on `moltnet_list_entries` /",
14716
14726
  " `moltnet_search_entries` expands into them. You may add additional",
14717
14727
  " tags but you cannot remove the auto-injected ones.",
14728
+ "- **DO NOT shell out to `moltnet entry create` / `moltnet entry",
14729
+ " create-signed` / any other `moltnet entry` subcommand via bash.**",
14730
+ " Those CLI paths hit the REST API directly and bypass the",
14731
+ " custom tool's task-tag auto-injection, leaving you with",
14732
+ " untagged entries that `moltnet_list_entries` with a",
14733
+ " `taskFilter: { taskId: ... }` cannot find. The legreffier skill",
14734
+ " recommends `moltnet entry *` for normal interactive sessions —",
14735
+ " inside a running task that advice does not apply. Use the",
14736
+ " `moltnet_create_entry` custom tool only.",
14718
14737
  "",
14719
14738
  "## Accountable commits",
14720
14739
  "",
14721
14740
  "- Every commit you make during this task MUST be paired with a signed",
14722
- " diary entry created via `moltnet_create_entry`. Embed the returned",
14723
- " entry id in the commit trailer `MoltNet-Diary: <id>`.",
14741
+ " diary entry created via the `moltnet_create_entry` custom tool",
14742
+ " (NOT via `moltnet entry create-signed` from bash see Diary",
14743
+ " discipline above). Embed the returned entry id in the commit",
14744
+ " trailer `MoltNet-Diary: <id>`.",
14724
14745
  "- Commits must be signed with the agent credentials (gitconfig is",
14725
14746
  " pre-configured). Do not bypass signing.",
14726
14747
  "",
@@ -15417,6 +15438,11 @@ async function executePiTask(claimedTask, reporter, opts) {
15417
15438
  let assistantText = "";
15418
15439
  let reporterError = null;
15419
15440
  const usage = finalUsage;
15441
+ let capAbort = null;
15442
+ let toolUseTurnCount = 0;
15443
+ let bashTimeoutCount = 0;
15444
+ const maxTurns = opts.maxTurns ?? 0;
15445
+ const maxBashTimeouts = opts.maxBashTimeouts ?? 3;
15420
15446
  cancelListener = wireSessionAbort(reporter.cancelSignal, session);
15421
15447
  const recordingPromise = [];
15422
15448
  const track = (p) => {
@@ -15431,6 +15457,23 @@ async function executePiTask(claimedTask, reporter, opts) {
15431
15457
  }
15432
15458
  }));
15433
15459
  };
15460
+ const liveSession = session;
15461
+ const triggerCapAbort = (code, message) => {
15462
+ if (capAbort) return;
15463
+ capAbort = {
15464
+ code,
15465
+ message
15466
+ };
15467
+ liveSession.abort().catch((err) => {
15468
+ const m = err instanceof Error ? err.message : String(err);
15469
+ process.stderr.write(`[cap] session.abort() failed: ${m}\n`);
15470
+ });
15471
+ track(emit("info", {
15472
+ event: "cap_abort",
15473
+ code,
15474
+ message
15475
+ }));
15476
+ };
15434
15477
  session.subscribe((event) => {
15435
15478
  if (event.type === "message_update") {
15436
15479
  const ae = event.assistantMessageEvent;
@@ -15439,12 +15482,17 @@ async function executePiTask(claimedTask, reporter, opts) {
15439
15482
  track(emit("text_delta", { delta: ae.delta }));
15440
15483
  }
15441
15484
  } else if (event.type === "tool_execution_start") track(emit("tool_call_start", { tool_name: event.toolName }));
15442
- else if (event.type === "tool_execution_end") track(emit("tool_call_end", {
15443
- tool_name: event.toolName,
15444
- is_error: event.isError,
15445
- result: event.isError ? truncateForWire(event.result) : void 0
15446
- }));
15447
- else if (event.type === "turn_end") {
15485
+ else if (event.type === "tool_execution_end") {
15486
+ track(emit("tool_call_end", {
15487
+ tool_name: event.toolName,
15488
+ is_error: event.isError,
15489
+ result: event.isError ? truncateForWire(event.result) : void 0
15490
+ }));
15491
+ if (maxBashTimeouts > 0 && event.toolName === "bash" && event.isError && isBashTimeoutResult(event.result)) {
15492
+ bashTimeoutCount += 1;
15493
+ if (bashTimeoutCount >= maxBashTimeouts) triggerCapAbort("max_bash_timeouts_exceeded", `Aborted after ${bashTimeoutCount} bash timeouts in this attempt (cap ${maxBashTimeouts}).`);
15494
+ }
15495
+ } else if (event.type === "turn_end") {
15448
15496
  const msg = event.message;
15449
15497
  if (msg?.role === "assistant" && msg.usage) {
15450
15498
  usage.inputTokens += Math.max(0, msg.usage.input ?? 0);
@@ -15454,7 +15502,12 @@ async function executePiTask(claimedTask, reporter, opts) {
15454
15502
  if (cr) usage.cacheReadTokens = (usage.cacheReadTokens ?? 0) + cr;
15455
15503
  if (cw) usage.cacheWriteTokens = (usage.cacheWriteTokens ?? 0) + cw;
15456
15504
  }
15457
- track(emit("turn_end", { stop_reason: msg?.stopReason ?? "end_turn" }));
15505
+ const stopReason = msg?.stopReason ?? "end_turn";
15506
+ track(emit("turn_end", { stop_reason: stopReason }));
15507
+ if (maxTurns > 0 && stopReason !== "end_turn" && stopReason !== "aborted" && stopReason !== "error") {
15508
+ toolUseTurnCount += 1;
15509
+ if (toolUseTurnCount >= maxTurns) triggerCapAbort("max_turns_exceeded", `Aborted after ${toolUseTurnCount} tool-use turns (cap ${maxTurns}).`);
15510
+ }
15458
15511
  llmAbort = msg?.stopReason === "error";
15459
15512
  if (msg?.stopReason === "error") llmErrorMessage = typeof msg.errorMessage === "string" && msg.errorMessage.length > 0 ? msg.errorMessage : null;
15460
15513
  else llmErrorMessage = null;
@@ -15483,7 +15536,7 @@ async function executePiTask(claimedTask, reporter, opts) {
15483
15536
  let parsedOutput = null;
15484
15537
  let parsedOutputCid = null;
15485
15538
  let parseError = null;
15486
- if (!runError && !llmAbort && !cancelled) {
15539
+ if (!runError && !llmAbort && !cancelled && !capAbort) {
15487
15540
  const captured = submitToolHandle?.getCaptured() ?? null;
15488
15541
  if (captured) try {
15489
15542
  parsedOutput = captured;
@@ -15536,6 +15589,21 @@ async function executePiTask(claimedTask, reporter, opts) {
15536
15589
  retryable: false
15537
15590
  }
15538
15591
  };
15592
+ const capAbortSnapshot = capAbort;
15593
+ if (capAbortSnapshot) return {
15594
+ taskId: task.id,
15595
+ attemptN,
15596
+ status: "failed",
15597
+ output: null,
15598
+ outputCid: null,
15599
+ usage,
15600
+ durationMs: Date.now() - startTime,
15601
+ error: {
15602
+ code: capAbortSnapshot.code,
15603
+ message: capAbortSnapshot.message,
15604
+ retryable: false
15605
+ }
15606
+ };
15539
15607
  const status = runError || llmAbort || parseError || reporterError ? "failed" : "completed";
15540
15608
  const errorCode = runError?.code ?? parseError?.code ?? reporterError?.code ?? (llmAbort ? "llm_api_error" : void 0);
15541
15609
  const errorMessage = runError?.message ?? parseError?.message ?? reporterError?.message ?? (llmAbort ? llmErrorMessage ?? "LLM API error during turn" : void 0);
@@ -15637,6 +15705,25 @@ function summarizePayloadForLog(kind, payload) {
15637
15705
  default: return payload;
15638
15706
  }
15639
15707
  }
15708
+ /**
15709
+ * Detect pi's bash-timeout error wrapper in a `tool_execution_end`
15710
+ * result. The bash tool surfaces a timeout as a structured tool result
15711
+ * `{ content: [{ type: 'text', text: '… Command timed out after N
15712
+ * seconds' }] }` (see `@earendil-works/pi-coding-agent`'s bash.js).
15713
+ * Substring-match against the stable wrapper string is the only
15714
+ * mechanism short of patching pi; the string is part of pi's external
15715
+ * tool-error API and changing it would break agents that read tool
15716
+ * errors.
15717
+ */
15718
+ function isBashTimeoutResult(result) {
15719
+ if (result === null || result === void 0) return false;
15720
+ if (typeof result === "string") return result.includes("Command timed out after");
15721
+ if (typeof result !== "object") return false;
15722
+ const content = result.content;
15723
+ if (!Array.isArray(content)) return false;
15724
+ for (const part of content) if (typeof part === "object" && part !== null && typeof part.text === "string" && part.text.includes("Command timed out after")) return true;
15725
+ return false;
15726
+ }
15640
15727
  var TRUNCATE_LIMIT = 4 * 1024;
15641
15728
  function truncateForWire(value) {
15642
15729
  if (value === null || value === void 0) return value;