@vorim/sdk 3.22.1 → 4.0.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 (103) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +48 -0
  3. package/dist/httpSignatures.cjs +726 -0
  4. package/dist/httpSignatures.cjs.map +1 -0
  5. package/dist/httpSignatures.d.cts +131 -0
  6. package/dist/httpSignatures.d.ts +131 -0
  7. package/dist/httpSignatures.js +686 -0
  8. package/dist/httpSignatures.js.map +1 -0
  9. package/dist/index.cjs +975 -26
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +243 -16
  12. package/dist/index.d.ts +243 -16
  13. package/dist/index.js +967 -25
  14. package/dist/index.js.map +1 -1
  15. package/dist/integrations/anthropic.d.cts +2 -1
  16. package/dist/integrations/anthropic.d.ts +2 -1
  17. package/dist/integrations/ap2.d.cts +2 -1
  18. package/dist/integrations/ap2.d.ts +2 -1
  19. package/dist/integrations/aws-iam.d.cts +2 -1
  20. package/dist/integrations/aws-iam.d.ts +2 -1
  21. package/dist/integrations/bank-rails.d.cts +2 -1
  22. package/dist/integrations/bank-rails.d.ts +2 -1
  23. package/dist/integrations/circle.d.cts +2 -1
  24. package/dist/integrations/circle.d.ts +2 -1
  25. package/dist/integrations/cloudflare.d.cts +2 -1
  26. package/dist/integrations/cloudflare.d.ts +2 -1
  27. package/dist/integrations/coinbase-cdp.d.cts +2 -1
  28. package/dist/integrations/coinbase-cdp.d.ts +2 -1
  29. package/dist/integrations/commerce-agents.d.cts +2 -1
  30. package/dist/integrations/commerce-agents.d.ts +2 -1
  31. package/dist/integrations/crewai.d.cts +2 -1
  32. package/dist/integrations/crewai.d.ts +2 -1
  33. package/dist/integrations/entra.d.cts +2 -1
  34. package/dist/integrations/entra.d.ts +2 -1
  35. package/dist/integrations/fhir.d.cts +2 -1
  36. package/dist/integrations/fhir.d.ts +2 -1
  37. package/dist/integrations/grok.d.cts +2 -1
  38. package/dist/integrations/grok.d.ts +2 -1
  39. package/dist/integrations/guidewire.d.cts +2 -1
  40. package/dist/integrations/guidewire.d.ts +2 -1
  41. package/dist/integrations/hermes.d.cts +2 -1
  42. package/dist/integrations/hermes.d.ts +2 -1
  43. package/dist/integrations/jira.d.cts +2 -1
  44. package/dist/integrations/jira.d.ts +2 -1
  45. package/dist/integrations/langchain.d.cts +2 -1
  46. package/dist/integrations/langchain.d.ts +2 -1
  47. package/dist/integrations/langgraph.d.cts +2 -1
  48. package/dist/integrations/langgraph.d.ts +2 -1
  49. package/dist/integrations/legal.d.cts +2 -1
  50. package/dist/integrations/legal.d.ts +2 -1
  51. package/dist/integrations/life-sciences.d.cts +2 -1
  52. package/dist/integrations/life-sciences.d.ts +2 -1
  53. package/dist/integrations/linear.d.cts +2 -1
  54. package/dist/integrations/linear.d.ts +2 -1
  55. package/dist/integrations/lithic.d.cts +2 -1
  56. package/dist/integrations/lithic.d.ts +2 -1
  57. package/dist/integrations/llamaindex.d.cts +2 -1
  58. package/dist/integrations/llamaindex.d.ts +2 -1
  59. package/dist/integrations/marqeta.d.cts +2 -1
  60. package/dist/integrations/marqeta.d.ts +2 -1
  61. package/dist/integrations/modern-treasury.d.cts +2 -1
  62. package/dist/integrations/modern-treasury.d.ts +2 -1
  63. package/dist/integrations/muse.d.cts +2 -1
  64. package/dist/integrations/muse.d.ts +2 -1
  65. package/dist/integrations/nekuda.d.cts +2 -1
  66. package/dist/integrations/nekuda.d.ts +2 -1
  67. package/dist/integrations/okta.d.cts +2 -1
  68. package/dist/integrations/okta.d.ts +2 -1
  69. package/dist/integrations/openai.d.cts +2 -1
  70. package/dist/integrations/openai.d.ts +2 -1
  71. package/dist/integrations/openrouter.d.cts +2 -1
  72. package/dist/integrations/openrouter.d.ts +2 -1
  73. package/dist/integrations/paypal-agent.d.cts +2 -1
  74. package/dist/integrations/paypal-agent.d.ts +2 -1
  75. package/dist/integrations/perplexity.d.cts +2 -1
  76. package/dist/integrations/perplexity.d.ts +2 -1
  77. package/dist/integrations/plaid.d.cts +2 -1
  78. package/dist/integrations/plaid.d.ts +2 -1
  79. package/dist/integrations/ramp.d.cts +2 -1
  80. package/dist/integrations/ramp.d.ts +2 -1
  81. package/dist/integrations/shopify.d.cts +2 -1
  82. package/dist/integrations/shopify.d.ts +2 -1
  83. package/dist/integrations/siem.d.cts +1 -1
  84. package/dist/integrations/siem.d.ts +1 -1
  85. package/dist/integrations/skyfire.d.cts +2 -1
  86. package/dist/integrations/skyfire.d.ts +2 -1
  87. package/dist/integrations/stripe-acp.d.cts +2 -1
  88. package/dist/integrations/stripe-acp.d.ts +2 -1
  89. package/dist/integrations/stripe-issuing.d.cts +2 -1
  90. package/dist/integrations/stripe-issuing.d.ts +2 -1
  91. package/dist/integrations/truanon.d.cts +2 -1
  92. package/dist/integrations/truanon.d.ts +2 -1
  93. package/dist/integrations/typesafe.d.cts +2 -1
  94. package/dist/integrations/typesafe.d.ts +2 -1
  95. package/dist/integrations/ucp.d.cts +2 -1
  96. package/dist/integrations/ucp.d.ts +2 -1
  97. package/dist/integrations/vercel-ai.d.cts +2 -1
  98. package/dist/integrations/vercel-ai.d.ts +2 -1
  99. package/dist/integrations/x402.d.cts +2 -1
  100. package/dist/integrations/x402.d.ts +2 -1
  101. package/dist/{types-BrDQAJdl.d.cts → types-DphtTyIC.d.cts} +72 -3
  102. package/dist/{types-BrDQAJdl.d.ts → types-DphtTyIC.d.ts} +72 -3
  103. package/package.json +11 -1
package/dist/index.cjs CHANGED
@@ -32,6 +32,7 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  CANONICAL_TOOL_CATALOGUE_VERSION: () => CANONICAL_TOOL_CATALOGUE_VERSION,
34
34
  HMAC_SHA256_PREFIX: () => HMAC_SHA256_PREFIX,
35
+ HttpSignatureError: () => HttpSignatureError,
35
36
  SHA256_PREFIX: () => SHA256_PREFIX,
36
37
  VorimDeniedError: () => VorimDeniedError,
37
38
  VorimError: () => VorimError,
@@ -39,19 +40,25 @@ __export(index_exports, {
39
40
  canonicalPayloadV0: () => canonicalPayloadV0,
40
41
  canonicalPayloadV1: () => canonicalPayloadV1,
41
42
  commitPayload: () => commitPayload,
43
+ contentDigest: () => contentDigest,
44
+ createSignatureBase: () => createSignatureBase,
42
45
  default: () => createVorim,
43
46
  deviceLogin: () => deviceLogin,
44
47
  eventDigest: () => eventDigest,
48
+ foldTraceparent: () => foldTraceparent,
45
49
  hashPayload: () => hashPayload,
46
50
  hashPreviousEvent: () => hashPreviousEvent,
47
51
  hashSystemPrompt: () => hashSystemPrompt,
48
52
  hashTool: () => hashTool,
49
53
  hashToolCatalogue: () => hashToolCatalogue,
54
+ httpSignatureAlgForKey: () => httpSignatureAlgForKey,
50
55
  isDigest: () => isDigest,
51
56
  isKeyedCommitment: () => isKeyedCommitment,
52
57
  jcsCanonicalise: () => jcsCanonicalise,
53
58
  portableReceiptCanonicalBytes: () => portableReceiptCanonicalBytes,
54
- prepareReplayContext: () => prepareReplayContext
59
+ prepareReplayContext: () => prepareReplayContext,
60
+ signHttpRequest: () => signHttpRequest,
61
+ verifyHttpRequest: () => verifyHttpRequest
55
62
  });
56
63
  module.exports = __toCommonJS(index_exports);
57
64
 
@@ -89,9 +96,9 @@ function jcsCanonicalise(value) {
89
96
  }
90
97
  async function sha256Hex(input) {
91
98
  const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
92
- const subtle = globalThis.crypto?.subtle;
93
- if (subtle) {
94
- const buf = await subtle.digest("SHA-256", bytes);
99
+ const subtle2 = globalThis.crypto?.subtle;
100
+ if (subtle2) {
101
+ const buf = await subtle2.digest("SHA-256", bytes);
95
102
  return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
96
103
  }
97
104
  const nodeCrypto = await import("crypto");
@@ -207,9 +214,9 @@ function toHex(buf) {
207
214
  }
208
215
  async function hashPayload(content) {
209
216
  const bytes = toBytes(content);
210
- const subtle = globalThis.crypto?.subtle;
211
- if (subtle) {
212
- return SHA256_PREFIX + toHex(await subtle.digest("SHA-256", bytes));
217
+ const subtle2 = globalThis.crypto?.subtle;
218
+ if (subtle2) {
219
+ return SHA256_PREFIX + toHex(await subtle2.digest("SHA-256", bytes));
213
220
  }
214
221
  const nodeCrypto = await import("crypto");
215
222
  return SHA256_PREFIX + nodeCrypto.createHash("sha256").update(bytes).digest("hex");
@@ -222,16 +229,16 @@ async function commitPayload(content, key) {
222
229
  );
223
230
  }
224
231
  const bytes = toBytes(content);
225
- const subtle = globalThis.crypto?.subtle;
226
- if (subtle) {
227
- const cryptoKey = await subtle.importKey(
232
+ const subtle2 = globalThis.crypto?.subtle;
233
+ if (subtle2) {
234
+ const cryptoKey = await subtle2.importKey(
228
235
  "raw",
229
236
  keyBytes,
230
237
  { name: "HMAC", hash: "SHA-256" },
231
238
  false,
232
239
  ["sign"]
233
240
  );
234
- const sig = await subtle.sign("HMAC", cryptoKey, bytes);
241
+ const sig = await subtle2.sign("HMAC", cryptoKey, bytes);
235
242
  return HMAC_SHA256_PREFIX + toHex(sig);
236
243
  }
237
244
  const nodeCrypto = await import("crypto");
@@ -245,8 +252,686 @@ function isDigest(digest) {
245
252
  return typeof digest === "string" && DIGEST_RE.test(digest);
246
253
  }
247
254
 
255
+ // src/httpSignatures.ts
256
+ var FUTURE_SKEW_SECONDS = 60;
257
+ var HttpSignatureError = class extends Error {
258
+ constructor(message) {
259
+ super(message);
260
+ this.name = "HttpSignatureError";
261
+ }
262
+ };
263
+ var SfParser = class {
264
+ constructor(s) {
265
+ this.s = s;
266
+ }
267
+ s;
268
+ i = 0;
269
+ fail(msg) {
270
+ throw new HttpSignatureError(`structured field parse error: ${msg} at ${this.i}`);
271
+ }
272
+ peek() {
273
+ return this.s[this.i];
274
+ }
275
+ eof() {
276
+ return this.i >= this.s.length;
277
+ }
278
+ skipSP() {
279
+ while (this.s[this.i] === " ") this.i++;
280
+ }
281
+ skipOWS() {
282
+ while (this.s[this.i] === " " || this.s[this.i] === " ") this.i++;
283
+ }
284
+ parseDictionary() {
285
+ const out = [];
286
+ this.skipSP();
287
+ if (this.eof()) return out;
288
+ for (; ; ) {
289
+ const key = this.parseKey();
290
+ let member;
291
+ if (this.peek() === "=") {
292
+ this.i++;
293
+ member = this.parseItemOrInnerList();
294
+ } else {
295
+ member = { kind: "item", value: { t: "bool", v: true }, params: this.parseParams() };
296
+ }
297
+ const existing = out.findIndex(([k]) => k === key);
298
+ if (existing >= 0) out[existing] = [key, member];
299
+ else out.push([key, member]);
300
+ this.skipOWS();
301
+ if (this.eof()) return out;
302
+ if (this.peek() !== ",") this.fail('expected ","');
303
+ this.i++;
304
+ this.skipOWS();
305
+ if (this.eof()) this.fail('trailing ","');
306
+ }
307
+ }
308
+ parseItemOrInnerList() {
309
+ if (this.peek() === "(") return this.parseInnerList();
310
+ return this.parseItem();
311
+ }
312
+ parseInnerList() {
313
+ if (this.peek() !== "(") this.fail('expected "("');
314
+ this.i++;
315
+ const items = [];
316
+ for (; ; ) {
317
+ this.skipSP();
318
+ if (this.peek() === ")") {
319
+ this.i++;
320
+ return { kind: "list", items, params: this.parseParams() };
321
+ }
322
+ if (this.eof()) this.fail("unterminated inner list");
323
+ items.push(this.parseItem());
324
+ const c = this.peek();
325
+ if (c !== " " && c !== ")") this.fail('expected SP or ")"');
326
+ }
327
+ }
328
+ parseItem() {
329
+ const value = this.parseBareItem();
330
+ return { kind: "item", value, params: this.parseParams() };
331
+ }
332
+ parseParams() {
333
+ const out = [];
334
+ while (this.peek() === ";") {
335
+ this.i++;
336
+ this.skipSP();
337
+ const key = this.parseKey();
338
+ let value = { t: "bool", v: true };
339
+ if (this.peek() === "=") {
340
+ this.i++;
341
+ value = this.parseBareItem();
342
+ }
343
+ const existing = out.findIndex(([k]) => k === key);
344
+ if (existing >= 0) out[existing] = [key, value];
345
+ else out.push([key, value]);
346
+ }
347
+ return out;
348
+ }
349
+ parseKey() {
350
+ const m = /^[a-z*][a-z0-9_\-.*]*/.exec(this.s.slice(this.i));
351
+ if (!m) this.fail("expected key");
352
+ this.i += m[0].length;
353
+ return m[0];
354
+ }
355
+ parseBareItem() {
356
+ const c = this.peek();
357
+ if (c === '"') return this.parseString();
358
+ if (c === ":") return this.parseBytes();
359
+ if (c === "?") {
360
+ const v = this.s[this.i + 1];
361
+ if (v !== "0" && v !== "1") this.fail("bad boolean");
362
+ this.i += 2;
363
+ return { t: "bool", v: v === "1" };
364
+ }
365
+ if (c === "-" || c >= "0" && c <= "9") {
366
+ const m = /^-?\d{1,15}(\.\d{1,3})?/.exec(this.s.slice(this.i));
367
+ if (!m) this.fail("bad number");
368
+ this.i += m[0].length;
369
+ return m[1] ? { t: "dec", v: Number(m[0]) } : { t: "int", v: Number(m[0]) };
370
+ }
371
+ const tm = /^[A-Za-z*][!#$%&'*+\-.^_`|~0-9A-Za-z:/]*/.exec(this.s.slice(this.i));
372
+ if (tm) {
373
+ this.i += tm[0].length;
374
+ return { t: "tok", v: tm[0] };
375
+ }
376
+ this.fail("unexpected character");
377
+ }
378
+ parseString() {
379
+ this.i++;
380
+ let out = "";
381
+ for (; ; ) {
382
+ if (this.eof()) this.fail("unterminated string");
383
+ const c = this.s[this.i++];
384
+ if (c === "\\") {
385
+ const n = this.s[this.i++];
386
+ if (n !== '"' && n !== "\\") this.fail("bad escape");
387
+ out += n;
388
+ } else if (c === '"') {
389
+ return { t: "str", v: out };
390
+ } else {
391
+ const code = c.charCodeAt(0);
392
+ if (code < 32 || code > 126) this.fail("non-printable in string");
393
+ out += c;
394
+ }
395
+ }
396
+ }
397
+ parseBytes() {
398
+ this.i++;
399
+ const end = this.s.indexOf(":", this.i);
400
+ if (end < 0) this.fail("unterminated byte sequence");
401
+ const b64 = this.s.slice(this.i, end);
402
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) this.fail("bad base64");
403
+ this.i = end + 1;
404
+ return { t: "bin", v: base64ToBytes(b64) };
405
+ }
406
+ };
407
+ function serializeBareItem(b) {
408
+ switch (b.t) {
409
+ case "int":
410
+ return String(Math.trunc(b.v));
411
+ case "dec": {
412
+ const r = Math.round(b.v * 1e3) / 1e3;
413
+ return Number.isInteger(r) ? `${r}.0` : String(r);
414
+ }
415
+ case "str":
416
+ return serializeString(b.v);
417
+ case "tok":
418
+ return b.v;
419
+ case "bool":
420
+ return b.v ? "?1" : "?0";
421
+ case "bin":
422
+ return `:${bytesToBase64(b.v)}:`;
423
+ }
424
+ }
425
+ function serializeString(v) {
426
+ if (!/^[\x20-\x7e]*$/.test(v)) throw new HttpSignatureError(`string parameter must be printable ASCII: ${JSON.stringify(v)}`);
427
+ return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
428
+ }
429
+ function serializeParams(params) {
430
+ return params.map(([k, v]) => v.t === "bool" && v.v === true ? `;${k}` : `;${k}=${serializeBareItem(v)}`).join("");
431
+ }
432
+ function serializeItem(item) {
433
+ return serializeBareItem(item.value) + serializeParams(item.params);
434
+ }
435
+ function serializeInnerList(list) {
436
+ return `(${list.items.map(serializeItem).join(" ")})${serializeParams(list.params)}`;
437
+ }
438
+ var DERIVED = /* @__PURE__ */ new Set([
439
+ "@method",
440
+ "@target-uri",
441
+ "@authority",
442
+ "@scheme",
443
+ "@request-target",
444
+ "@path",
445
+ "@query",
446
+ "@query-param",
447
+ "@status"
448
+ ]);
449
+ function parseComponent(input) {
450
+ const s = input.trim();
451
+ let name;
452
+ let params;
453
+ if (s.startsWith('"')) {
454
+ const p = new SfParser(s);
455
+ const item = p.parseItem();
456
+ if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
457
+ if (item.value.t !== "str") throw new HttpSignatureError(`bad component identifier: ${input}`);
458
+ name = item.value.v;
459
+ params = item.params;
460
+ } else {
461
+ const semi = s.indexOf(";");
462
+ name = semi < 0 ? s : s.slice(0, semi);
463
+ const p = new SfParser(semi < 0 ? "" : s.slice(semi));
464
+ params = p.parseParams();
465
+ if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
466
+ }
467
+ if (!name) throw new HttpSignatureError("empty component name");
468
+ if (!name.startsWith("@")) name = name.toLowerCase();
469
+ return { name, params };
470
+ }
471
+ function serializeComponent(c) {
472
+ return serializeString(c.name) + serializeParams(c.params);
473
+ }
474
+ function componentKey(c) {
475
+ const sorted = [...c.params].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
476
+ return serializeString(c.name) + serializeParams(sorted);
477
+ }
478
+ function componentToItem(c) {
479
+ return { kind: "item", value: { t: "str", v: c.name }, params: c.params };
480
+ }
481
+ function fieldValues(headers, name) {
482
+ const out = [];
483
+ let found = false;
484
+ for (const [k, v] of Object.entries(headers ?? {})) {
485
+ if (k.toLowerCase() !== name || v === void 0 || v === null) continue;
486
+ found = true;
487
+ for (const one of Array.isArray(v) ? v : [v]) out.push(String(one));
488
+ }
489
+ return found ? out : null;
490
+ }
491
+ function cleanFieldValue(v) {
492
+ return v.replace(/\r?\n[ \t]+/g, " ").trim();
493
+ }
494
+ function formPercentEncode(s) {
495
+ const bytes = new TextEncoder().encode(s);
496
+ let out = "";
497
+ for (const b of bytes) {
498
+ const ch = String.fromCharCode(b);
499
+ if (/[A-Za-z0-9*\-._]/.test(ch)) out += ch;
500
+ else out += "%" + b.toString(16).toUpperCase().padStart(2, "0");
501
+ }
502
+ return out;
503
+ }
504
+ function parseUrl(url, what) {
505
+ if (!url) throw new HttpSignatureError(`${what} requires the message url`);
506
+ try {
507
+ return new URL(url);
508
+ } catch {
509
+ throw new HttpSignatureError(`invalid url: ${url}`);
510
+ }
511
+ }
512
+ function derivedValue(c, msg, isResponse) {
513
+ const nameParam = c.params.find(([k]) => k === "name");
514
+ if (c.name !== "@query-param" && nameParam) throw new HttpSignatureError(`parameter "name" is not valid on ${c.name}`);
515
+ switch (c.name) {
516
+ case "@method":
517
+ if (isResponse || !msg.method) throw new HttpSignatureError("@method requires a request");
518
+ return msg.method;
519
+ case "@target-uri": {
520
+ if (isResponse) throw new HttpSignatureError("@target-uri requires a request");
521
+ const u = parseUrl(msg.url, "@target-uri");
522
+ u.hash = "";
523
+ return u.href;
524
+ }
525
+ case "@authority":
526
+ if (isResponse) throw new HttpSignatureError("@authority requires a request");
527
+ return parseUrl(msg.url, "@authority").host.toLowerCase();
528
+ case "@scheme":
529
+ if (isResponse) throw new HttpSignatureError("@scheme requires a request");
530
+ return parseUrl(msg.url, "@scheme").protocol.replace(/:$/, "").toLowerCase();
531
+ case "@request-target": {
532
+ if (isResponse) throw new HttpSignatureError("@request-target requires a request");
533
+ const u = parseUrl(msg.url, "@request-target");
534
+ return (u.pathname || "/") + u.search;
535
+ }
536
+ case "@path":
537
+ if (isResponse) throw new HttpSignatureError("@path requires a request");
538
+ return parseUrl(msg.url, "@path").pathname || "/";
539
+ case "@query": {
540
+ if (isResponse) throw new HttpSignatureError("@query requires a request");
541
+ const u = parseUrl(msg.url, "@query");
542
+ return u.search || "?";
543
+ }
544
+ case "@query-param": {
545
+ if (isResponse) throw new HttpSignatureError("@query-param requires a request");
546
+ if (!nameParam || nameParam[1].t !== "str") throw new HttpSignatureError("@query-param requires a name parameter (String)");
547
+ const wanted = nameParam[1].v;
548
+ const u = parseUrl(msg.url, "@query-param");
549
+ const matches = [];
550
+ for (const [n, v] of new URLSearchParams(u.search)) {
551
+ if (formPercentEncode(n) === wanted) matches.push(v);
552
+ }
553
+ if (matches.length === 0) throw new HttpSignatureError(`query parameter "${wanted}" not found`);
554
+ if (matches.length > 1) throw new HttpSignatureError(`query parameter "${wanted}" occurs more than once and cannot be signed individually`);
555
+ return formPercentEncode(matches[0]);
556
+ }
557
+ case "@status":
558
+ if (!isResponse || msg.status === void 0) throw new HttpSignatureError("@status is only valid on a response");
559
+ return String(Math.trunc(msg.status)).padStart(3, "0");
560
+ default:
561
+ throw new HttpSignatureError(`unknown derived component ${c.name}`);
562
+ }
563
+ }
564
+ var FIELD_PARAMS = /* @__PURE__ */ new Set(["req", "bs"]);
565
+ var DERIVED_PARAMS = /* @__PURE__ */ new Set(["req", "name"]);
566
+ var UNSUPPORTED_FIELD_PARAMS = /* @__PURE__ */ new Set(["sf", "key", "tr"]);
567
+ function componentValue(c, message) {
568
+ const isDerived = c.name.startsWith("@");
569
+ if (c.name === "@signature-params") throw new HttpSignatureError("@signature-params cannot be a covered component");
570
+ if (isDerived && !DERIVED.has(c.name)) throw new HttpSignatureError(`unknown derived component ${c.name}`);
571
+ for (const [k, v] of c.params) {
572
+ const allowed = isDerived ? DERIVED_PARAMS : FIELD_PARAMS;
573
+ if (!allowed.has(k)) {
574
+ if (!isDerived && UNSUPPORTED_FIELD_PARAMS.has(k)) throw new HttpSignatureError(`component parameter "${k}" is not supported`);
575
+ throw new HttpSignatureError(`unknown component parameter "${k}" on ${c.name}`);
576
+ }
577
+ if ((k === "req" || k === "bs") && !(v.t === "bool" && v.v === true)) {
578
+ throw new HttpSignatureError(`component parameter "${k}" must be a true Boolean`);
579
+ }
580
+ }
581
+ let target = message;
582
+ let isResponse = message.status !== void 0;
583
+ if (c.params.some(([k]) => k === "req")) {
584
+ if (!isResponse) throw new HttpSignatureError(`component ${c.name} has the req parameter but the message is a request`);
585
+ if (!message.request) throw new HttpSignatureError(`component ${c.name} has the req parameter but no related request was given`);
586
+ target = message.request;
587
+ isResponse = false;
588
+ }
589
+ let value;
590
+ if (isDerived) {
591
+ value = derivedValue(c, target, isResponse);
592
+ } else {
593
+ const raw = fieldValues(target.headers, c.name);
594
+ if (raw === null) throw new HttpSignatureError(`header field "${c.name}" is missing`);
595
+ if (c.params.some(([k]) => k === "bs")) {
596
+ value = raw.map((v) => `:${bytesToBase64(new TextEncoder().encode(cleanFieldValue(v)))}:`).join(", ");
597
+ } else {
598
+ value = raw.map(cleanFieldValue).join(", ");
599
+ }
600
+ }
601
+ if (/[\r\n]/.test(value)) throw new HttpSignatureError(`component ${c.name} contains a newline`);
602
+ if (!/^[\x20-\x7e\t]*$/.test(value)) throw new HttpSignatureError(`component ${c.name} contains non-ASCII characters`);
603
+ return value;
604
+ }
605
+ function paramsFromObject(params) {
606
+ const out = [];
607
+ for (const [k, v] of Object.entries(params ?? {})) {
608
+ if (v === void 0 || v === null) continue;
609
+ if (!/^[a-z*][a-z0-9_\-.*]*$/.test(k)) throw new HttpSignatureError(`invalid signature parameter name "${k}"`);
610
+ if (typeof v === "number") {
611
+ if (!Number.isInteger(v)) throw new HttpSignatureError(`signature parameter "${k}" must be an integer`);
612
+ out.push([k, { t: "int", v }]);
613
+ } else if (typeof v === "boolean") {
614
+ out.push([k, { t: "bool", v }]);
615
+ } else {
616
+ out.push([k, { t: "str", v: String(v) }]);
617
+ }
618
+ }
619
+ return out;
620
+ }
621
+ function buildBase(message, components, params) {
622
+ const seen = /* @__PURE__ */ new Set();
623
+ const lines = [];
624
+ for (const c of components) {
625
+ const key = componentKey(c);
626
+ if (seen.has(key)) throw new HttpSignatureError(`duplicate component ${serializeComponent(c)}`);
627
+ seen.add(key);
628
+ lines.push(`${serializeComponent(c)}: ${componentValue(c, message)}`);
629
+ }
630
+ const signatureParams = serializeInnerList({ kind: "list", items: components.map(componentToItem), params });
631
+ lines.push(`"@signature-params": ${signatureParams}`);
632
+ const base = lines.join("\n");
633
+ if (!/^[\x20-\x7e\t\n]*$/.test(base)) throw new HttpSignatureError("signature base is not ASCII");
634
+ return { base, signatureParams };
635
+ }
636
+ function createSignatureBase(message, components, params = {}) {
637
+ return buildBase(message, components.map(parseComponent), paramsFromObject(params)).base;
638
+ }
639
+ function bytesToBase64(bytes) {
640
+ let s = "";
641
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
642
+ return btoa(s);
643
+ }
644
+ function base64ToBytes(b64) {
645
+ const raw = atob(b64);
646
+ const out = new Uint8Array(raw.length);
647
+ for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
648
+ return out;
649
+ }
650
+ function toBytes2(body) {
651
+ return typeof body === "string" ? new TextEncoder().encode(body) : body;
652
+ }
653
+ function pemToDer(pem) {
654
+ const body = pem.replace(/-----BEGIN [^-]+-----/, "").replace(/-----END [^-]+-----/, "").replace(/\s+/g, "");
655
+ if (!body) throw new HttpSignatureError("empty PEM");
656
+ return base64ToBytes(body);
657
+ }
658
+ function toArrayBuffer(bytes) {
659
+ const out = new ArrayBuffer(bytes.length);
660
+ new Uint8Array(out).set(bytes);
661
+ return out;
662
+ }
663
+ function constantTimeEqual(a, b) {
664
+ if (a.length !== b.length) return false;
665
+ let d = 0;
666
+ for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
667
+ return d === 0;
668
+ }
669
+ var OID_ED25519 = [6, 3, 43, 101, 112];
670
+ var OID_EC_PUBLIC_KEY = [6, 7, 42, 134, 72, 206, 61, 2, 1];
671
+ var OID_P256 = [6, 8, 42, 134, 72, 206, 61, 3, 1, 7];
672
+ function hasSeq(hay, needle) {
673
+ outer: for (let i = 0; i + needle.length <= hay.length; i++) {
674
+ for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
675
+ return true;
676
+ }
677
+ return false;
678
+ }
679
+ function algFromKeyDer(der) {
680
+ const head = der.slice(0, 32);
681
+ if (hasSeq(head, OID_ED25519)) return "ed25519";
682
+ if (hasSeq(head, OID_EC_PUBLIC_KEY)) {
683
+ if (hasSeq(der.slice(0, 40), OID_P256)) return "ecdsa-p256-sha256";
684
+ throw new HttpSignatureError("unsupported EC curve (only P-256 is supported)");
685
+ }
686
+ throw new HttpSignatureError("unsupported key type (Ed25519 or ECDSA P-256 required)");
687
+ }
688
+ function httpSignatureAlgForKey(pem) {
689
+ return algFromKeyDer(pemToDer(pem));
690
+ }
691
+ function subtle() {
692
+ return globalThis.crypto?.subtle;
693
+ }
694
+ async function digestBytes(alg, data) {
695
+ const s = subtle();
696
+ if (s) return new Uint8Array(await s.digest(alg === "sha-256" ? "SHA-256" : "SHA-512", toArrayBuffer(data)));
697
+ const nodeCrypto = await import("crypto");
698
+ return new Uint8Array(nodeCrypto.createHash(alg === "sha-256" ? "sha256" : "sha512").update(data).digest());
699
+ }
700
+ async function signBytes(alg, privateKeyPem, data) {
701
+ const s = subtle();
702
+ if (s) {
703
+ const der = toArrayBuffer(pemToDer(privateKeyPem));
704
+ if (alg === "ed25519") {
705
+ const key2 = await s.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
706
+ return new Uint8Array(await s.sign("Ed25519", key2, toArrayBuffer(data)));
707
+ }
708
+ const key = await s.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
709
+ return new Uint8Array(await s.sign({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(data)));
710
+ }
711
+ const nodeCrypto = await import("crypto");
712
+ if (alg === "ed25519") return new Uint8Array(nodeCrypto.sign(null, data, privateKeyPem));
713
+ return new Uint8Array(nodeCrypto.sign("sha256", data, { key: privateKeyPem, dsaEncoding: "ieee-p1363" }));
714
+ }
715
+ async function verifyBytes(alg, publicKeyPem, data, sig) {
716
+ if (sig.length !== 64) return false;
717
+ const s = subtle();
718
+ if (s) {
719
+ const der = toArrayBuffer(pemToDer(publicKeyPem));
720
+ if (alg === "ed25519") {
721
+ const key2 = await s.importKey("spki", der, { name: "Ed25519" }, false, ["verify"]);
722
+ return s.verify("Ed25519", key2, toArrayBuffer(sig), toArrayBuffer(data));
723
+ }
724
+ const key = await s.importKey("spki", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
725
+ return s.verify({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(sig), toArrayBuffer(data));
726
+ }
727
+ const nodeCrypto = await import("crypto");
728
+ if (alg === "ed25519") return nodeCrypto.verify(null, data, publicKeyPem, sig);
729
+ return nodeCrypto.verify("sha256", data, { key: publicKeyPem, dsaEncoding: "ieee-p1363" }, sig);
730
+ }
731
+ async function contentDigest(body, alg = "sha-256") {
732
+ if (alg !== "sha-256" && alg !== "sha-512") throw new HttpSignatureError(`unsupported digest algorithm ${alg}`);
733
+ return `${alg}=:${bytesToBase64(await digestBytes(alg, toBytes2(body)))}:`;
734
+ }
735
+ async function checkContentDigest(fieldValue, body) {
736
+ let dict;
737
+ try {
738
+ dict = new SfParser(fieldValue).parseDictionary();
739
+ } catch {
740
+ return "Content-Digest is not a valid structured field";
741
+ }
742
+ const bytes = toBytes2(body);
743
+ let checked = 0;
744
+ for (const [alg, member] of dict) {
745
+ if (alg !== "sha-256" && alg !== "sha-512") continue;
746
+ if (member.kind !== "item" || member.value.t !== "bin") return `Content-Digest ${alg} is not a byte sequence`;
747
+ const actual = await digestBytes(alg, bytes);
748
+ if (!constantTimeEqual(actual, member.value.v)) return `Content-Digest ${alg} does not match the body`;
749
+ checked++;
750
+ }
751
+ return checked > 0 ? null : "Content-Digest has no supported algorithm (sha-256 or sha-512)";
752
+ }
753
+ var LABEL_RE = /^[a-z*][a-z0-9_\-.*]*$/;
754
+ async function signHttpRequest(request, options) {
755
+ if (!options?.privateKey) throw new HttpSignatureError("signHttpRequest requires privateKey (PKCS#8 PEM)");
756
+ const label = options.label ?? "sig1";
757
+ if (!LABEL_RE.test(label)) throw new HttpSignatureError(`invalid label "${label}"`);
758
+ const keyAlg = httpSignatureAlgForKey(options.privateKey);
759
+ if (options.alg && options.alg !== keyAlg) {
760
+ throw new HttpSignatureError(`alg "${options.alg}" does not match the private key (${keyAlg})`);
761
+ }
762
+ const alg = keyAlg;
763
+ const headers = { ...request.headers ?? {} };
764
+ const hasBody = request.body !== void 0 && request.body !== null;
765
+ let digestHeader;
766
+ if (hasBody) {
767
+ digestHeader = await contentDigest(request.body, "sha-256");
768
+ for (const k of Object.keys(headers)) if (k.toLowerCase() === "content-digest") delete headers[k];
769
+ headers["content-digest"] = digestHeader;
770
+ }
771
+ let componentStrs;
772
+ if (options.components) {
773
+ componentStrs = [...options.components];
774
+ } else {
775
+ componentStrs = ["@method", "@target-uri", "@authority"];
776
+ if (fieldValues(headers, "content-type") !== null) componentStrs.push("content-type");
777
+ }
778
+ const components = componentStrs.map(parseComponent);
779
+ if (hasBody && !components.some((c) => c.name === "content-digest" && c.params.length === 0)) {
780
+ components.push({ name: "content-digest", params: [] });
781
+ }
782
+ const created = options.created ?? Math.floor(Date.now() / 1e3);
783
+ const expires = options.expires === null ? void 0 : options.expires ?? created + 300;
784
+ const params = { created };
785
+ if (expires !== void 0) params.expires = expires;
786
+ if (options.nonce !== void 0) params.nonce = options.nonce;
787
+ if (options.includeAlg !== false) params.alg = alg;
788
+ if (options.keyid !== void 0) params.keyid = options.keyid;
789
+ if (options.tag !== void 0) params.tag = options.tag;
790
+ const { base, signatureParams } = buildBase(
791
+ { method: request.method, url: request.url, headers, body: request.body },
792
+ components,
793
+ paramsFromObject(params)
794
+ );
795
+ const sig = await signBytes(alg, options.privateKey, new TextEncoder().encode(base));
796
+ const out = {
797
+ "Signature-Input": `${label}=${signatureParams}`,
798
+ "Signature": `${label}=:${bytesToBase64(sig)}:`
799
+ };
800
+ if (digestHeader) out["Content-Digest"] = digestHeader;
801
+ return { headers: out, signatureBase: base };
802
+ }
803
+ var SUPPORTED_ALGS = /* @__PURE__ */ new Set(["ed25519", "ecdsa-p256-sha256"]);
804
+ async function verifyHttpRequest(request, options) {
805
+ if (!options?.publicKey && !options?.resolveKey) {
806
+ throw new HttpSignatureError("verifyHttpRequest requires publicKey or resolveKey");
807
+ }
808
+ const result = {
809
+ valid: false,
810
+ label: options.label ?? "",
811
+ covered: [],
812
+ contentDigestChecked: false
813
+ };
814
+ const fail = (reason) => ({ ...result, valid: false, reason });
815
+ const inputRaw = fieldValues(request.headers, "signature-input");
816
+ const sigRaw = fieldValues(request.headers, "signature");
817
+ if (!inputRaw) return fail("missing Signature-Input header");
818
+ if (!sigRaw) return fail("missing Signature header");
819
+ let inputs;
820
+ let sigs;
821
+ try {
822
+ inputs = new SfParser(inputRaw.map(cleanFieldValue).join(", ")).parseDictionary();
823
+ sigs = new SfParser(sigRaw.map(cleanFieldValue).join(", ")).parseDictionary();
824
+ } catch (e) {
825
+ return fail(`malformed signature headers: ${e.message}`);
826
+ }
827
+ const label = options.label ?? inputs[0]?.[0];
828
+ if (!label) return fail("Signature-Input has no signatures");
829
+ result.label = label;
830
+ const input = inputs.find(([k]) => k === label)?.[1];
831
+ const sigMember = sigs.find(([k]) => k === label)?.[1];
832
+ if (!input) return fail(`no Signature-Input for label "${label}"`);
833
+ if (!sigMember) return fail(`no Signature for label "${label}"`);
834
+ if (input.kind !== "list") return fail("Signature-Input member is not an inner list");
835
+ if (sigMember.kind !== "item" || sigMember.value.t !== "bin") return fail("Signature member is not a byte sequence");
836
+ const components = [];
837
+ for (const item of input.items) {
838
+ if (item.value.t !== "str") return fail("covered component is not a string");
839
+ components.push({ name: item.value.v, params: item.params });
840
+ }
841
+ result.covered = components.map(serializeComponent);
842
+ const p = new Map(input.params);
843
+ const getInt = (k) => {
844
+ const v = p.get(k);
845
+ if (v === void 0) return void 0;
846
+ return v.t === "int" ? v.v : null;
847
+ };
848
+ const getStr = (k) => {
849
+ const v = p.get(k);
850
+ if (v === void 0) return void 0;
851
+ return v.t === "str" ? v.v : null;
852
+ };
853
+ const created = getInt("created");
854
+ const expires = getInt("expires");
855
+ const keyid = getStr("keyid");
856
+ const algParam = getStr("alg");
857
+ if (created === null) return fail("created must be an integer");
858
+ if (expires === null) return fail("expires must be an integer");
859
+ if (keyid === null) return fail("keyid must be a string");
860
+ if (algParam === null) return fail("alg must be a string");
861
+ result.created = created;
862
+ result.expires = expires;
863
+ result.keyid = keyid;
864
+ if (options.requiredComponents?.length) {
865
+ const have = new Set(components.map(componentKey));
866
+ for (const r of options.requiredComponents) {
867
+ let rc;
868
+ try {
869
+ rc = parseComponent(r);
870
+ } catch (e) {
871
+ return fail(e.message);
872
+ }
873
+ if (!have.has(componentKey(rc))) return fail(`required component ${serializeComponent(rc)} is not covered`);
874
+ }
875
+ }
876
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
877
+ if (expires !== void 0 && now > expires) return fail("signature has expired");
878
+ if (created !== void 0 && created > now + FUTURE_SKEW_SECONDS) return fail("signature created in the future");
879
+ if (options.maxAgeSeconds !== void 0) {
880
+ if (created === void 0) return fail("signature has no created parameter, so its age cannot be checked");
881
+ if (now - created > options.maxAgeSeconds) return fail("signature is older than maxAgeSeconds");
882
+ }
883
+ let publicKey = options.publicKey;
884
+ let resolvedAlg;
885
+ if (!publicKey) {
886
+ let resolved;
887
+ try {
888
+ resolved = await options.resolveKey(keyid);
889
+ } catch (e) {
890
+ return fail(`key resolution failed: ${e.message}`);
891
+ }
892
+ if (!resolved?.publicKey) return fail(`unknown key${keyid ? ` "${keyid}"` : ""}`);
893
+ publicKey = resolved.publicKey;
894
+ resolvedAlg = resolved.alg;
895
+ }
896
+ let keyAlg;
897
+ try {
898
+ keyAlg = httpSignatureAlgForKey(publicKey);
899
+ } catch (e) {
900
+ return fail(e.message);
901
+ }
902
+ if (algParam !== void 0 && !SUPPORTED_ALGS.has(algParam)) return fail(`unsupported algorithm "${algParam}"`);
903
+ if (algParam !== void 0 && algParam !== keyAlg) return fail(`alg "${algParam}" does not match the key (${keyAlg})`);
904
+ if (resolvedAlg !== void 0 && resolvedAlg !== keyAlg) return fail(`resolved key alg "${resolvedAlg}" does not match the key (${keyAlg})`);
905
+ result.alg = keyAlg;
906
+ let base;
907
+ try {
908
+ base = buildBase(
909
+ { method: request.method, url: request.url, headers: request.headers, body: request.body },
910
+ components,
911
+ input.params
912
+ ).base;
913
+ } catch (e) {
914
+ return fail(e.message);
915
+ }
916
+ let ok;
917
+ try {
918
+ ok = await verifyBytes(keyAlg, publicKey, new TextEncoder().encode(base), sigMember.value.v);
919
+ } catch (e) {
920
+ return fail(`signature check failed: ${e.message}`);
921
+ }
922
+ if (!ok) return fail("signature does not verify");
923
+ const coversDigest = components.some((c) => c.name === "content-digest");
924
+ if (coversDigest && request.body !== void 0 && request.body !== null) {
925
+ const dv = fieldValues(request.headers, "content-digest");
926
+ const reason = await checkContentDigest((dv ?? []).map(cleanFieldValue).join(", "), request.body);
927
+ if (reason) return fail(reason);
928
+ result.contentDigestChecked = true;
929
+ }
930
+ return { ...result, valid: true };
931
+ }
932
+
248
933
  // src/index.ts
249
- var SDK_VERSION = true ? "3.22.1" : "0.0.0";
934
+ var SDK_VERSION = true ? "4.0.0" : "0.0.0";
250
935
  var USER_AGENT = `vorim-sdk/${SDK_VERSION}`;
251
936
  function sleep(ms) {
252
937
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -289,6 +974,17 @@ function toApprovalAttestation(raw) {
289
974
  signature: raw.signature
290
975
  };
291
976
  }
977
+ function foldTraceparent(input) {
978
+ if (!input.traceparent) return input;
979
+ const { traceparent, ...rest } = input;
980
+ const m = /^[0-9a-f]{2}-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i.exec(traceparent.trim());
981
+ const out = { ...rest };
982
+ if (m) {
983
+ if (!out.trace_id) out.trace_id = m[1].toLowerCase();
984
+ if (!out.span_id) out.span_id = m[2].toLowerCase();
985
+ }
986
+ return out;
987
+ }
292
988
  var VorimSDK = class _VorimSDK {
293
989
  apiKey;
294
990
  baseUrl;
@@ -344,7 +1040,7 @@ var VorimSDK = class _VorimSDK {
344
1040
  }
345
1041
  }
346
1042
  this.chainEvents = config.chainEvents ?? false;
347
- this.runtimeFailOpen = config.runtimeFailOpen ?? true;
1043
+ this.runtimeFailOpen = config.runtimeFailOpen ?? false;
348
1044
  this.noPayload = config.noPayload !== void 0 && config.noPayload !== false;
349
1045
  this.maxMetadataChars = typeof config.noPayload === "object" && typeof config.noPayload.maxMetadataChars === "number" ? config.noPayload.maxMetadataChars : 256;
350
1046
  }
@@ -447,11 +1143,26 @@ var VorimSDK = class _VorimSDK {
447
1143
  return { agents: env.data ?? [], meta: env.meta ?? null };
448
1144
  }
449
1145
  /**
450
- * Update an agent's metadata.
1146
+ * Update an agent's metadata or status.
1147
+ *
1148
+ * `status: 'suspended'` is the kill switch and, since 4.0.0, cascades to
1149
+ * every agent reachable through the agent's active identity delegations
1150
+ * unless `cascade: false`. Setting `status: 'active'` on a suspended agent
1151
+ * reverses exactly that cascade. The returned agent carries
1152
+ * `cascade.suspended` / `cascade.reactivated` with the agent ids touched.
1153
+ * See {@link suspendPreview} for the blast radius before acting.
451
1154
  */
452
1155
  async updateAgent(agentId, updates) {
453
1156
  return this.patch(`/agents/${agentId}`, updates);
454
1157
  }
1158
+ /**
1159
+ * What suspending (or revoking) this agent would touch: its delegation
1160
+ * subtree, how many of those agents are still active, open escalations
1161
+ * across the subtree, and live delegation links. Writes nothing.
1162
+ */
1163
+ async suspendPreview(agentId) {
1164
+ return this.get(`/agents/${agentId}/suspend-preview`);
1165
+ }
455
1166
  /**
456
1167
  * Revoke an agent (permanent deactivation).
457
1168
  */
@@ -811,9 +1522,9 @@ var VorimSDK = class _VorimSDK {
811
1522
  * poll {@link waitForDecisionResolution} for the human decision.
812
1523
  *
813
1524
  * Transport failures (network/DNS/timeout/5xx) respect the constructor's
814
- * `runtimeFailOpen` flag: when true (default) a synthetic `fallback`
815
- * decision is returned so a control-plane blip does not block the agent;
816
- * when false the underlying error is re-thrown.
1525
+ * `runtimeFailOpen` flag: when false (default) the underlying error is
1526
+ * re-thrown; when true a synthetic `fallback` decision is returned so a
1527
+ * control-plane blip does not block the agent.
817
1528
  *
818
1529
  * Always pass the public `agid_*` id as `agentId`.
819
1530
  *
@@ -838,7 +1549,10 @@ var VorimSDK = class _VorimSDK {
838
1549
  required_scope: input.requiredScope,
839
1550
  idempotency_key: input.idempotencyKey,
840
1551
  workflow_id: input.workflowId,
841
- estimated_tokens: input.estimatedTokens
1552
+ estimated_tokens: input.estimatedTokens,
1553
+ trace_id: input.traceId,
1554
+ span_id: input.spanId,
1555
+ traceparent: input.traceparent
842
1556
  };
843
1557
  let raw;
844
1558
  try {
@@ -858,6 +1572,7 @@ var VorimSDK = class _VorimSDK {
858
1572
  latencyMs: 0,
859
1573
  isFallback: true,
860
1574
  policyVersion: 0,
1575
+ swarmId: null,
861
1576
  escalationResolution: null,
862
1577
  approval: null
863
1578
  };
@@ -876,8 +1591,9 @@ var VorimSDK = class _VorimSDK {
876
1591
  // Enforcement runs inside beforeAction(): pass `workflowId` + `estimatedTokens`
877
1592
  // on the action, and a `token_budget_gt` policy rule denies the action before
878
1593
  // the spend if it would breach the budget. These methods manage the budgets
879
- // and read live spend (dashboard-oriented; require a JWT-authed client or an
880
- // owner/admin API key).
1594
+ // and read live spend. They need an API key holding the `runtime:manage`
1595
+ // scope (deliberately separate from `runtime:decide`, so an agent's own key
1596
+ // cannot raise its ceiling).
881
1597
  /**
882
1598
  * Create or update a token budget for an agent or workflow. One budget per
883
1599
  * (scope, scope_ref) — calling this again for the same target updates it.
@@ -972,19 +1688,20 @@ var VorimSDK = class _VorimSDK {
972
1688
  * row's `decision` column off `'escalate'`. If we returned that verbatim,
973
1689
  * a caller's obvious `if (d.decision === 'deny')` check would never fire
974
1690
  * on a human DENIAL — a silent fail-open. So when a resolution is present
975
- * we translate the verdict: approved → 'allow', denied → 'deny'. The raw
976
- * resolution is also surfaced as `escalationResolution` for callers that
977
- * want it explicitly.
1691
+ * we translate the verdict: approved → 'allow', denied → 'deny', and
1692
+ * timed_out (nobody answered within the org's escalation window) → 'deny'.
1693
+ * The raw resolution is also surfaced as `escalationResolution` for
1694
+ * callers that want it explicitly.
978
1695
  *
979
1696
  * A missing verdict (malformed/truncated response) fails CLOSED to 'deny'
980
1697
  * rather than 'fallback', so the deny check fires on garbled input.
981
1698
  */
982
1699
  toRuntimeDecision(raw) {
983
- const resolution = raw?.escalation_resolution === "approved" ? "approved" : raw?.escalation_resolution === "denied" ? "denied" : null;
1700
+ const resolution = raw?.escalation_resolution === "approved" ? "approved" : raw?.escalation_resolution === "denied" ? "denied" : raw?.escalation_resolution === "timed_out" ? "timed_out" : null;
984
1701
  const hasVerdict = typeof raw?.decision === "string";
985
1702
  let decision;
986
1703
  if (raw?.decision === "escalate" && resolution === "approved") decision = "allow";
987
- else if (raw?.decision === "escalate" && resolution === "denied") decision = "deny";
1704
+ else if (raw?.decision === "escalate" && (resolution === "denied" || resolution === "timed_out")) decision = "deny";
988
1705
  else if (hasVerdict) decision = raw.decision;
989
1706
  else decision = "deny";
990
1707
  return {
@@ -999,6 +1716,7 @@ var VorimSDK = class _VorimSDK {
999
1716
  latencyMs: raw?.latency_ms ?? 0,
1000
1717
  isFallback: raw?.is_fallback ?? !hasVerdict,
1001
1718
  policyVersion: raw?.policy_version ?? 0,
1719
+ swarmId: typeof raw?.swarm_id === "string" ? raw.swarm_id : null,
1002
1720
  escalationResolution: resolution,
1003
1721
  approval: toApprovalAttestation(raw?.approval)
1004
1722
  };
@@ -1133,6 +1851,7 @@ var VorimSDK = class _VorimSDK {
1133
1851
  }
1134
1852
  async prepareEvent(event, signOverride) {
1135
1853
  this.assertNoPayload(event);
1854
+ event = foldTraceparent(event);
1136
1855
  const shouldSign = signOverride ?? this.autoSign;
1137
1856
  if (!shouldSign && !this.chainEvents) return event;
1138
1857
  if (this.chainEvents) {
@@ -1252,6 +1971,168 @@ var VorimSDK = class _VorimSDK {
1252
1971
  }
1253
1972
  return result;
1254
1973
  }
1974
+ /**
1975
+ * The server-minted swarm an agent belongs to and every member of it.
1976
+ * `{ swarm_id: null, members: [] }` for a standalone agent.
1977
+ */
1978
+ async getSwarm(agentId) {
1979
+ return this.get(`/agents/${agentId}/swarm`);
1980
+ }
1981
+ // ─── Many agents at once ─────────────────────────────────────────────
1982
+ /**
1983
+ * Register up to 50 agents in one call: an explicit list, or a template
1984
+ * repeated `count` times (names `<prefix>-1` .. `<prefix>-N`), optionally
1985
+ * grouped into a new swarm (`swarm: { name?, root? }`; the first created
1986
+ * agent roots it when `root` is absent). Each created agent's private key
1987
+ * is cached, like `register()`, so the SDK can sign for it at once. The
1988
+ * plan allowance is checked for the whole batch first; a single failure is
1989
+ * listed in `failed`, not thrown.
1990
+ */
1991
+ async registerMany(input) {
1992
+ const result = await this.post("/agents/bulk", input);
1993
+ for (const c of result?.created ?? []) {
1994
+ const id = c?.agent?.agent_id;
1995
+ if (id && c?.private_key) this.agentKeys.set(id, c.private_key);
1996
+ }
1997
+ return result;
1998
+ }
1999
+ // ─── Declarative swarm spec (vorim.swarm/v1) ─────────────────────────
2000
+ /**
2001
+ * Create or update a swarm from a spec: root, members and who they report
2002
+ * to, guardians, charter, budget and shares, breakers, tripwires. Pass the
2003
+ * YAML or JSON text, or the parsed object. `dryRun` returns the plan
2004
+ * without writing. Needs an org key with `runtime:manage`.
2005
+ */
2006
+ async applySwarmSpec(spec, opts = {}) {
2007
+ const body = typeof spec === "string" ? { spec } : spec;
2008
+ return this.post(`/swarms/apply?dry_run=${opts.dryRun ? "true" : "false"}`, body);
2009
+ }
2010
+ /**
2011
+ * Rehearse a swarm: every active member against a scenario set, through
2012
+ * the real decision pipeline with nothing written, signed with the roster,
2013
+ * charter, budget and policy version it ran under. `preset: 'hazards'`
2014
+ * (default) runs generic side tasks plus one main task; `'replay'` re-judges
2015
+ * the swarm's last 100 decisions; `scenarios` runs your own (each with
2016
+ * `expect: 'allow' | 'not_allow' | 'deny' | 'escalate'`). Verdict is pass,
2017
+ * pass_with_findings or fail. Needs `runtime:manage`.
2018
+ */
2019
+ async rehearseSwarm(swarmId, input = {}) {
2020
+ return this.post(`/swarms/${encodeURIComponent(swarmId)}/rehearse`, input);
2021
+ }
2022
+ /** Past rehearsals, newest first (summary only; fetch `/swarms/:id/rehearsals/:rid` for the signed payload). */
2023
+ async listSwarmRehearsals(swarmId) {
2024
+ return this.get(`/swarms/${encodeURIComponent(swarmId)}/rehearsals`);
2025
+ }
2026
+ /**
2027
+ * A swarm's trust: `min` (gate on it: the least trusted active member),
2028
+ * `weighted_mean` (display, weighted by recent activity), `trimmed_mean`
2029
+ * (for anything derived from peer reports), per member.
2030
+ */
2031
+ async getSwarmScore(swarmId) {
2032
+ return this.get(`/swarms/${encodeURIComponent(swarmId)}/score`);
2033
+ }
2034
+ /**
2035
+ * Issue a platform-signed attestation of the swarm as it is now: roster
2036
+ * and its hash, policy version and rules hash, charter, budget, kills,
2037
+ * latest rehearsal, receipt chain head and the three scores. Valid 24 h.
2038
+ * Hand it to a counterparty; they verify it against GET /trust/keys.
2039
+ */
2040
+ async attestSwarm(swarmId) {
2041
+ return this.post(`/swarms/${encodeURIComponent(swarmId)}/attest`, {});
2042
+ }
2043
+ /** Past attestations, newest first (fetch one by id for the signed payload). */
2044
+ async listSwarmAttestations(swarmId) {
2045
+ return this.get(`/swarms/${encodeURIComponent(swarmId)}/attestations`);
2046
+ }
2047
+ /** A swarm as it is now, as a spec: `{ spec, yaml }`. Keep the YAML in git and apply it again. */
2048
+ async getSwarmSpec(swarmId) {
2049
+ return this.get(`/swarms/${encodeURIComponent(swarmId)}/spec`);
2050
+ }
2051
+ /**
2052
+ * A swarm's attention picture: escalations in the last hour against its
2053
+ * budget, the rate to expect, median time to resolve, mean time between
2054
+ * interventions, and the fan-out estimate after Olsen and Goodrich (how
2055
+ * many swarms like this one person could supervise).
2056
+ */
2057
+ async getSwarmAttention(swarmId) {
2058
+ return this.get(`/swarms/${encodeURIComponent(swarmId)}/attention`);
2059
+ }
2060
+ /**
2061
+ * Set the swarm's attention budget: `perHour` escalations per rolling hour
2062
+ * a person may be asked to read (null = no budget). Past it `onExceed`
2063
+ * decides: 'deny' (the escalation is denied unread, the default) or
2064
+ * 'suspend' (the whole swarm stops). Returns the swarm detail.
2065
+ */
2066
+ async setSwarmAttention(swarmId, input) {
2067
+ const body = {};
2068
+ if (input.perHour !== void 0) body.attention_budget_per_hour = input.perHour;
2069
+ if (input.onExceed !== void 0) body.attention_exceeded_action = input.onExceed;
2070
+ return this.patch(`/swarms/${encodeURIComponent(swarmId)}`, body);
2071
+ }
2072
+ // ─── OpenTelemetry ───────────────────────────────────────────────────
2073
+ /**
2074
+ * Attributes for the agent's own spans: the OTel GenAI `gen_ai.agent.id`
2075
+ * plus Vorim's swarm and parent-agent ids (the conventions have no field
2076
+ * for either), so any OTel backend can group a swarm's spans. Cached for
2077
+ * 60 seconds per agent. Pass the active span's trace/span id back to
2078
+ * `beforeAction` / `emit` and Vorim's OTLP connector parents its spans
2079
+ * under yours.
2080
+ */
2081
+ async otelAttributes(agentId) {
2082
+ const cached = this.otelCache.get(agentId);
2083
+ if (cached && cached.expires > Date.now()) return cached.attrs;
2084
+ const attrs = { "gen_ai.agent.id": agentId, "vorim.agent.id": agentId };
2085
+ try {
2086
+ const swarm = await this.getSwarm(agentId);
2087
+ if (swarm?.swarm_id) {
2088
+ attrs["vorim.swarm.id"] = swarm.swarm_id;
2089
+ const me = swarm.members?.find((m) => m.agent_id === agentId);
2090
+ if (me?.parent_agent_id) attrs["vorim.parent_agent.id"] = me.parent_agent_id;
2091
+ }
2092
+ } catch {
2093
+ }
2094
+ this.otelCache.set(agentId, { attrs, expires: Date.now() + 6e4 });
2095
+ return attrs;
2096
+ }
2097
+ otelCache = /* @__PURE__ */ new Map();
2098
+ // ─── Guardian agents ─────────────────────────────────────────────────
2099
+ //
2100
+ // An agent with metadata.class = 'guardian' judges escalations that a rule
2101
+ // with approver_role 'guardian' assigned to its swarm. It reads the queue
2102
+ // from the server (never from a peer) and answers with a verdict signed by
2103
+ // its own key over one canonical line, so the approval is verifiable
2104
+ // offline against the agent's registered public key. An unanswered
2105
+ // escalation times out as denied: an absent guardian fails closed.
2106
+ /** Pending escalations this guardian may judge (empty for a non-guardian). */
2107
+ async listGuardianEscalations(agentId) {
2108
+ return this.get(`/runtime/guardian/escalations?agent_id=${encodeURIComponent(agentId)}`);
2109
+ }
2110
+ /**
2111
+ * Approve or veto an escalation as a guardian. Needs the agent's private
2112
+ * key (loaded by register(), registerEphemeral() or useAgentKey()). A
2113
+ * quorum rule returns `{ status: 'partial', approvals, required_approvals }`
2114
+ * until enough distinct approvals arrive; one veto denies at once.
2115
+ */
2116
+ async guardianResolve(agentId, decisionId, resolution) {
2117
+ const key = this.agentKeys.get(agentId);
2118
+ if (!key) {
2119
+ throw new VorimError(
2120
+ 400,
2121
+ "AGENT_KEY_NOT_LOADED",
2122
+ `No private key is cached for agent ${agentId}. Call register() or useAgentKey(agentId, privateKeyPem) first.`
2123
+ );
2124
+ }
2125
+ const signedAt = (/* @__PURE__ */ new Date()).toISOString();
2126
+ const line = `vorim-escalation-approval|v1|${decisionId}|${resolution}|agent:${agentId}|${signedAt}`;
2127
+ const signature = await this.sign(line, key);
2128
+ return this.post("/runtime/guardian/resolve", {
2129
+ agent_id: agentId,
2130
+ decision_id: decisionId,
2131
+ resolution,
2132
+ signed_at: signedAt,
2133
+ signature
2134
+ });
2135
+ }
1255
2136
  // ─── Credential Delegation ──────────────────────────────────────────
1256
2137
  /**
1257
2138
  * Register an OAuth provider for credential delegation.
@@ -1306,6 +2187,67 @@ var VorimSDK = class _VorimSDK {
1306
2187
  async requestToken(input) {
1307
2188
  return this.post("/credentials/token", input);
1308
2189
  }
2190
+ // ─── HTTP Message Signatures (RFC 9421) ─────────────────────────
2191
+ /**
2192
+ * Sign an outbound HTTP request (RFC 9421) with an agent's cached Ed25519
2193
+ * key, so the receiver can tell which Vorim agent sent it. `keyid` is the
2194
+ * agent_id, `alg` is `ed25519`, and `tag` defaults to `vorim`. When the
2195
+ * request has a body, a Content-Digest header is added and covered.
2196
+ *
2197
+ * The key must already be in this instance's keyring (from `register()`,
2198
+ * `registerEphemeral()` or `useAgentKey()`). Returns the headers to add.
2199
+ *
2200
+ * ```ts
2201
+ * const { headers } = await vorim.signHttpRequest(agentId, {
2202
+ * method: 'POST', url: 'https://agent-b.example/tasks',
2203
+ * headers: { 'content-type': 'application/json' }, body,
2204
+ * });
2205
+ * await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body });
2206
+ * ```
2207
+ */
2208
+ async signHttpRequest(agentId, request, options = {}) {
2209
+ const privateKey = this.agentKeys.get(agentId);
2210
+ if (!privateKey) {
2211
+ throw new VorimError(
2212
+ 400,
2213
+ "AGENT_KEY_NOT_LOADED",
2214
+ `No private key is cached for agent ${agentId}. Call register() or useAgentKey(agentId, privateKeyPem) first.`
2215
+ );
2216
+ }
2217
+ return signHttpRequest(request, {
2218
+ ...options,
2219
+ tag: options.tag ?? "vorim",
2220
+ privateKey,
2221
+ keyid: agentId,
2222
+ alg: "ed25519"
2223
+ });
2224
+ }
2225
+ /**
2226
+ * Verify an RFC 9421 signed request through Vorim. The server resolves the
2227
+ * signature's keyid (an agent_id) to that agent's registered public key,
2228
+ * rejects suspended or revoked agents, and checks Content-Digest when the
2229
+ * body is passed. Public endpoint: no API key scope is needed.
2230
+ *
2231
+ * Pass the request exactly as received: method, full URL, headers, and the
2232
+ * raw body if `content-digest` is covered.
2233
+ */
2234
+ async verifyHttpRequest(request, options = {}) {
2235
+ const payload = {
2236
+ method: request.method,
2237
+ url: request.url,
2238
+ headers: request.headers
2239
+ };
2240
+ if (typeof request.body === "string") {
2241
+ payload.body = request.body;
2242
+ } else if (request.body instanceof Uint8Array) {
2243
+ let bin = "";
2244
+ for (let i = 0; i < request.body.length; i++) bin += String.fromCharCode(request.body[i]);
2245
+ payload.body_base64 = btoa(bin);
2246
+ }
2247
+ if (options.label !== void 0) payload.label = options.label;
2248
+ if (options.maxAgeSeconds !== void 0) payload.max_age_seconds = options.maxAgeSeconds;
2249
+ return this.post("/http-signatures/verify", payload);
2250
+ }
1309
2251
  // ─── Signing ──────────────────────────────────────────────────────
1310
2252
  /**
1311
2253
  * Sign a payload with an Ed25519 private key (client-side).
@@ -1494,6 +2436,7 @@ async function deviceLogin(opts) {
1494
2436
  0 && (module.exports = {
1495
2437
  CANONICAL_TOOL_CATALOGUE_VERSION,
1496
2438
  HMAC_SHA256_PREFIX,
2439
+ HttpSignatureError,
1497
2440
  SHA256_PREFIX,
1498
2441
  VorimDeniedError,
1499
2442
  VorimError,
@@ -1501,17 +2444,23 @@ async function deviceLogin(opts) {
1501
2444
  canonicalPayloadV0,
1502
2445
  canonicalPayloadV1,
1503
2446
  commitPayload,
2447
+ contentDigest,
2448
+ createSignatureBase,
1504
2449
  deviceLogin,
1505
2450
  eventDigest,
2451
+ foldTraceparent,
1506
2452
  hashPayload,
1507
2453
  hashPreviousEvent,
1508
2454
  hashSystemPrompt,
1509
2455
  hashTool,
1510
2456
  hashToolCatalogue,
2457
+ httpSignatureAlgForKey,
1511
2458
  isDigest,
1512
2459
  isKeyedCommitment,
1513
2460
  jcsCanonicalise,
1514
2461
  portableReceiptCanonicalBytes,
1515
- prepareReplayContext
2462
+ prepareReplayContext,
2463
+ signHttpRequest,
2464
+ verifyHttpRequest
1516
2465
  });
1517
2466
  //# sourceMappingURL=index.cjs.map