@covia/covia-sdk 1.5.0 → 1.6.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.
package/dist/index.mjs CHANGED
@@ -60,8 +60,10 @@ var JobFailedError = class extends CoviaError {
60
60
  const id = jobData.id ?? "unknown";
61
61
  const status = jobData.status ?? "unknown";
62
62
  let msg = `Job ${id} ${status}`;
63
- if (jobData.output?.error) {
64
- msg += `: ${jobData.output.error}`;
63
+ const output = jobData.output;
64
+ const errText = output && typeof output === "object" && "error" in output ? output.error : void 0;
65
+ if (typeof errText === "string") {
66
+ msg += `: ${errText}`;
65
67
  }
66
68
  super(msg);
67
69
  this.name = "JobFailedError";
@@ -89,26 +91,44 @@ var JobNotFoundError = class extends NotFoundError {
89
91
  }
90
92
  };
91
93
 
92
- // node_modules/@noble/ed25519/index.js
93
- var ed25519_CURVE = {
94
+ // node_modules/.pnpm/@noble+ed25519@3.1.0/node_modules/@noble/ed25519/index.js
95
+ var ed25519_CURVE = Object.freeze({
94
96
  p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
95
97
  n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
98
+ h: 8n,
96
99
  a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
97
100
  d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
98
101
  Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
99
102
  Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
100
- };
101
- var { p: P, n: N, Gx, Gy, a: _a, d: _d } = ed25519_CURVE;
102
- var h = 8n;
103
+ });
104
+ var { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
103
105
  var L = 32;
104
- var L2 = 64;
105
- var err = (m = "") => {
106
- throw new Error(m);
106
+ var captureTrace = (...args) => {
107
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
108
+ Error.captureStackTrace(...args);
109
+ }
110
+ };
111
+ var err = (message = "") => {
112
+ const e = new Error(message);
113
+ captureTrace(e, err);
114
+ throw e;
107
115
  };
108
116
  var isBig = (n) => typeof n === "bigint";
109
117
  var isStr = (s) => typeof s === "string";
110
- var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
111
- var abytes = (a, l) => !isBytes(a) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a;
118
+ var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
119
+ var abytes = (value, length, title = "") => {
120
+ const bytes = isBytes(value);
121
+ const len = value?.length;
122
+ const needsLen = length !== void 0;
123
+ if (!bytes || needsLen && len !== length) {
124
+ const prefix = title && `"${title}" `;
125
+ const ofLen = needsLen ? ` of length ${length}` : "";
126
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
127
+ const msg = prefix + "expected Uint8Array" + ofLen + ", got " + got;
128
+ throw bytes ? new RangeError(msg) : new TypeError(msg);
129
+ }
130
+ return value;
131
+ };
112
132
  var u8n = (len) => new Uint8Array(len);
113
133
  var u8fr = (buf) => Uint8Array.from(buf);
114
134
  var padh = (n, pad) => n.toString(16).padStart(pad, "0");
@@ -141,11 +161,13 @@ var hexToBytes = (hex) => {
141
161
  }
142
162
  return array;
143
163
  };
144
- var toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
145
164
  var cr = () => globalThis?.crypto;
146
- var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined");
165
+ var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
147
166
  var concatBytes = (...arrs) => {
148
- const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
167
+ let len = 0;
168
+ for (const a of arrs)
169
+ len += abytes(a).length;
170
+ const r = u8n(len);
149
171
  let pad = 0;
150
172
  arrs.forEach((a) => {
151
173
  r.set(a, pad);
@@ -158,11 +180,25 @@ var randomBytes = (len = L) => {
158
180
  return c.getRandomValues(u8n(len));
159
181
  };
160
182
  var big = BigInt;
161
- var arange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
183
+ var assertRange = (n, min, max, msg = "bad number: out of range") => {
184
+ if (!isBig(n))
185
+ throw new TypeError(msg);
186
+ if (min <= n && n < max)
187
+ return n;
188
+ throw new RangeError(msg);
189
+ };
162
190
  var M = (a, b = P) => {
163
191
  const r = a % b;
164
192
  return r >= 0n ? r : b + r;
165
193
  };
194
+ var P_MASK = (1n << 255n) - 1n;
195
+ var modP = (num) => {
196
+ if (num < 0n)
197
+ err("negative coordinate");
198
+ let r = (num >> 255n) * 19n + (num & P_MASK);
199
+ r = (r >> 255n) * 19n + (r & P_MASK);
200
+ return r % P;
201
+ };
166
202
  var modN = (a) => M(a, N);
167
203
  var invert = (num, md) => {
168
204
  if (num === 0n || md <= 0n)
@@ -176,41 +212,47 @@ var invert = (num, md) => {
176
212
  return b === 1n ? M(x, md) : err("no inverse");
177
213
  };
178
214
  var callHash = (name) => {
179
- const fn = etc[name];
215
+ const fn = hashes[name];
180
216
  if (typeof fn !== "function")
181
217
  err("hashes." + name + " not set");
182
218
  return fn;
183
219
  };
220
+ var checkDigest = (value) => abytes(value, 64, "digest");
184
221
  var apoint = (p) => p instanceof Point ? p : err("Point expected");
185
222
  var B256 = 2n ** 256n;
186
223
  var _Point = class _Point {
187
- constructor(ex, ey, ez, et) {
188
- __publicField(this, "ex");
189
- __publicField(this, "ey");
190
- __publicField(this, "ez");
191
- __publicField(this, "et");
224
+ // Constructor only bounds-checks and freezes XYZT coordinates; it does not prove the point is
225
+ // on-curve or that T matches X*Y/Z.
226
+ constructor(X, Y, Z, T) {
227
+ __publicField(this, "X");
228
+ __publicField(this, "Y");
229
+ __publicField(this, "Z");
230
+ __publicField(this, "T");
192
231
  const max = B256;
193
- this.ex = arange(ex, 0n, max);
194
- this.ey = arange(ey, 0n, max);
195
- this.ez = arange(ez, 1n, max);
196
- this.et = arange(et, 0n, max);
232
+ this.X = assertRange(X, 0n, max);
233
+ this.Y = assertRange(Y, 0n, max);
234
+ this.Z = assertRange(Z, 1n, max);
235
+ this.T = assertRange(T, 0n, max);
197
236
  Object.freeze(this);
198
237
  }
238
+ static CURVE() {
239
+ return ed25519_CURVE;
240
+ }
199
241
  static fromAffine(p) {
200
- return new _Point(p.x, p.y, 1n, M(p.x * p.y));
242
+ return new _Point(p.x, p.y, 1n, modP(p.x * p.y));
201
243
  }
202
- /** RFC8032 5.1.3: Uint8Array to Point. */
244
+ /** RFC8032 5.1.3: Bytes to Point. */
203
245
  static fromBytes(hex, zip215 = false) {
204
246
  const d = _d;
205
247
  const normed = u8fr(abytes(hex, L));
206
248
  const lastByte = hex[31];
207
249
  normed[31] = lastByte & -129;
208
- const y = bytesToNumLE(normed);
250
+ const y = bytesToNumberLE(normed);
209
251
  const max = zip215 ? B256 : P;
210
- arange(y, 0n, max);
211
- const y2 = M(y * y);
252
+ assertRange(y, 0n, max);
253
+ const y2 = modP(y * y);
212
254
  const u = M(y2 - 1n);
213
- const v = M(d * y2 + 1n);
255
+ const v = modP(d * y2 + 1n);
214
256
  let { isValid, value: x } = uvRatio(u, v);
215
257
  if (!isValid)
216
258
  err("bad point: y not sqrt");
@@ -220,7 +262,16 @@ var _Point = class _Point {
220
262
  err("bad point: x==0, isLastByteOdd");
221
263
  if (isLastByteOdd !== isXOdd)
222
264
  x = M(-x);
223
- return new _Point(x, y, 1n, M(x * y));
265
+ return new _Point(x, y, 1n, modP(x * y));
266
+ }
267
+ static fromHex(hex, zip215) {
268
+ return _Point.fromBytes(hexToBytes(hex), zip215);
269
+ }
270
+ get x() {
271
+ return this.toAffine().x;
272
+ }
273
+ get y() {
274
+ return this.toAffine().y;
224
275
  }
225
276
  /** Checks if the point is valid and on-curve. */
226
277
  assertValidity() {
@@ -228,31 +279,31 @@ var _Point = class _Point {
228
279
  const d = _d;
229
280
  const p = this;
230
281
  if (p.is0())
231
- throw new Error("bad point: ZERO");
232
- const { ex: X, ey: Y, ez: Z, et: T } = p;
233
- const X2 = M(X * X);
234
- const Y2 = M(Y * Y);
235
- const Z2 = M(Z * Z);
236
- const Z4 = M(Z2 * Z2);
237
- const aX2 = M(X2 * a);
238
- const left = M(Z2 * M(aX2 + Y2));
239
- const right = M(Z4 + M(d * M(X2 * Y2)));
282
+ return err("bad point: ZERO");
283
+ const { X, Y, Z, T } = p;
284
+ const X2 = modP(X * X);
285
+ const Y2 = modP(Y * Y);
286
+ const Z2 = modP(Z * Z);
287
+ const Z4 = modP(Z2 * Z2);
288
+ const aX2 = modP(X2 * a);
289
+ const left = modP(Z2 * (aX2 + Y2));
290
+ const right = M(Z4 + modP(d * modP(X2 * Y2)));
240
291
  if (left !== right)
241
- throw new Error("bad point: equation left != right (1)");
242
- const XY = M(X * Y);
243
- const ZT = M(Z * T);
292
+ return err("bad point: equation left != right (1)");
293
+ const XY = modP(X * Y);
294
+ const ZT = modP(Z * T);
244
295
  if (XY !== ZT)
245
- throw new Error("bad point: equation left != right (2)");
296
+ return err("bad point: equation left != right (2)");
246
297
  return this;
247
298
  }
248
299
  /** Equality check: compare points P&Q. */
249
300
  equals(other) {
250
- const { ex: X1, ey: Y1, ez: Z1 } = this;
251
- const { ex: X2, ey: Y2, ez: Z2 } = apoint(other);
252
- const X1Z2 = M(X1 * Z2);
253
- const X2Z1 = M(X2 * Z1);
254
- const Y1Z2 = M(Y1 * Z2);
255
- const Y2Z1 = M(Y2 * Z1);
301
+ const { X: X1, Y: Y1, Z: Z1 } = this;
302
+ const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
303
+ const X1Z2 = modP(X1 * Z2);
304
+ const X2Z1 = modP(X2 * Z1);
305
+ const Y1Z2 = modP(Y1 * Z2);
306
+ const Y2Z1 = modP(Y2 * Z1);
256
307
  return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
257
308
  }
258
309
  is0() {
@@ -260,58 +311,64 @@ var _Point = class _Point {
260
311
  }
261
312
  /** Flip point over y coordinate. */
262
313
  negate() {
263
- return new _Point(M(-this.ex), this.ey, this.ez, M(-this.et));
314
+ return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
264
315
  }
265
316
  /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
266
317
  double() {
267
- const { ex: X1, ey: Y1, ez: Z1 } = this;
318
+ const { X: X1, Y: Y1, Z: Z1 } = this;
268
319
  const a = _a;
269
- const A = M(X1 * X1);
270
- const B = M(Y1 * Y1);
271
- const C2 = M(2n * M(Z1 * Z1));
272
- const D = M(a * A);
273
- const x1y1 = X1 + Y1;
274
- const E = M(M(x1y1 * x1y1) - A - B);
275
- const G2 = D + B;
276
- const F = G2 - C2;
277
- const H = D - B;
278
- const X3 = M(E * F);
279
- const Y3 = M(G2 * H);
280
- const T3 = M(E * H);
281
- const Z3 = M(F * G2);
320
+ const A = modP(X1 * X1);
321
+ const B = modP(Y1 * Y1);
322
+ const C2 = modP(2n * Z1 * Z1);
323
+ const D = modP(a * A);
324
+ const x1y1 = M(X1 + Y1);
325
+ const E = M(modP(x1y1 * x1y1) - A - B);
326
+ const G2 = M(D + B);
327
+ const F = M(G2 - C2);
328
+ const H = M(D - B);
329
+ const X3 = modP(E * F);
330
+ const Y3 = modP(G2 * H);
331
+ const T3 = modP(E * H);
332
+ const Z3 = modP(F * G2);
282
333
  return new _Point(X3, Y3, Z3, T3);
283
334
  }
284
335
  /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
285
336
  add(other) {
286
- const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
287
- const { ex: X2, ey: Y2, ez: Z2, et: T2 } = apoint(other);
337
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
338
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
288
339
  const a = _a;
289
340
  const d = _d;
290
- const A = M(X1 * X2);
291
- const B = M(Y1 * Y2);
292
- const C2 = M(T1 * d * T2);
293
- const D = M(Z1 * Z2);
294
- const E = M((X1 + Y1) * (X2 + Y2) - A - B);
341
+ const A = modP(X1 * X2);
342
+ const B = modP(Y1 * Y2);
343
+ const C2 = modP(modP(T1 * d) * T2);
344
+ const D = modP(Z1 * Z2);
345
+ const E = M(modP(M(X1 + Y1) * M(X2 + Y2)) - A - B);
295
346
  const F = M(D - C2);
296
347
  const G2 = M(D + C2);
297
- const H = M(B - a * A);
298
- const X3 = M(E * F);
299
- const Y3 = M(G2 * H);
300
- const T3 = M(E * H);
301
- const Z3 = M(F * G2);
348
+ const H = M(B - modP(a * A));
349
+ const X3 = modP(E * F);
350
+ const Y3 = modP(G2 * H);
351
+ const T3 = modP(E * H);
352
+ const Z3 = modP(F * G2);
302
353
  return new _Point(X3, Y3, Z3, T3);
303
354
  }
355
+ subtract(other) {
356
+ return this.add(apoint(other).negate());
357
+ }
304
358
  /**
305
- * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
359
+ * Point-by-scalar multiplication. Safe mode requires `1 <= n < CURVE.n`.
360
+ * Unsafe mode additionally permits `n = 0` and returns the identity point for that case.
306
361
  * Uses {@link wNAF} for base point.
307
362
  * Uses fake point to mitigate side-channel leakage.
308
- * @param n scalar by which point is multiplied
309
- * @param safe safe mode guards against timing attacks; unsafe mode is faster
363
+ * @param n - scalar by which point is multiplied
364
+ * @param safe - safe mode guards against timing attacks; unsafe mode is faster
310
365
  */
311
366
  multiply(n, safe = true) {
312
- if (!safe && (n === 0n || this.is0()))
367
+ if (!safe && n === 0n)
368
+ return I;
369
+ assertRange(n, 1n, N);
370
+ if (!safe && this.is0())
313
371
  return I;
314
- arange(n, 1n, N);
315
372
  if (n === 1n)
316
373
  return this;
317
374
  if (this.equals(G))
@@ -326,18 +383,23 @@ var _Point = class _Point {
326
383
  }
327
384
  return p;
328
385
  }
386
+ multiplyUnsafe(scalar) {
387
+ return this.multiply(scalar, false);
388
+ }
329
389
  /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
330
390
  toAffine() {
331
- const { ex: x, ey: y, ez: z } = this;
391
+ const { X, Y, Z } = this;
332
392
  if (this.equals(I))
333
393
  return { x: 0n, y: 1n };
334
- const iz = invert(z, P);
335
- if (M(z * iz) !== 1n)
394
+ const iz = invert(Z, P);
395
+ if (modP(Z * iz) !== 1n)
336
396
  err("invalid inverse");
337
- return { x: M(x * iz), y: M(y * iz) };
397
+ const x = modP(X * iz);
398
+ const y = modP(Y * iz);
399
+ return { x, y };
338
400
  }
339
401
  toBytes() {
340
- const { x, y } = this.assertValidity().toAffine();
402
+ const { x, y } = this.toAffine();
341
403
  const b = numTo32bLE(y);
342
404
  b[31] |= x & 1n ? 128 : 0;
343
405
  return b;
@@ -345,7 +407,6 @@ var _Point = class _Point {
345
407
  toHex() {
346
408
  return bytesToHex(this.toBytes());
347
409
  }
348
- // encode to hex string
349
410
  clearCofactor() {
350
411
  return this.multiply(big(h), false);
351
412
  }
@@ -358,18 +419,6 @@ var _Point = class _Point {
358
419
  p = p.add(this);
359
420
  return p.is0();
360
421
  }
361
- static fromHex(hex, zip215) {
362
- return _Point.fromBytes(toU8(hex), zip215);
363
- }
364
- get x() {
365
- return this.toAffine().x;
366
- }
367
- get y() {
368
- return this.toAffine().y;
369
- }
370
- toRawBytes() {
371
- return this.toBytes();
372
- }
373
422
  };
374
423
  __publicField(_Point, "BASE");
375
424
  __publicField(_Point, "ZERO");
@@ -378,40 +427,39 @@ var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
378
427
  var I = new Point(0n, 1n, 1n, 0n);
379
428
  Point.BASE = G;
380
429
  Point.ZERO = I;
381
- var numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), L2)).reverse();
382
- var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
430
+ var numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), 64)).reverse();
431
+ var bytesToNumberLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
383
432
  var pow2 = (x, power) => {
384
433
  let r = x;
385
434
  while (power-- > 0n) {
386
- r *= r;
387
- r %= P;
435
+ r = modP(r * r);
388
436
  }
389
437
  return r;
390
438
  };
391
439
  var pow_2_252_3 = (x) => {
392
- const x2 = x * x % P;
393
- const b2 = x2 * x % P;
394
- const b4 = pow2(b2, 2n) * b2 % P;
395
- const b5 = pow2(b4, 1n) * x % P;
396
- const b10 = pow2(b5, 5n) * b5 % P;
397
- const b20 = pow2(b10, 10n) * b10 % P;
398
- const b40 = pow2(b20, 20n) * b20 % P;
399
- const b80 = pow2(b40, 40n) * b40 % P;
400
- const b160 = pow2(b80, 80n) * b80 % P;
401
- const b240 = pow2(b160, 80n) * b80 % P;
402
- const b250 = pow2(b240, 10n) * b10 % P;
403
- const pow_p_5_8 = pow2(b250, 2n) * x % P;
440
+ const x2 = modP(x * x);
441
+ const b2 = modP(x2 * x);
442
+ const b4 = modP(pow2(b2, 2n) * b2);
443
+ const b5 = modP(pow2(b4, 1n) * x);
444
+ const b10 = modP(pow2(b5, 5n) * b5);
445
+ const b20 = modP(pow2(b10, 10n) * b10);
446
+ const b40 = modP(pow2(b20, 20n) * b20);
447
+ const b80 = modP(pow2(b40, 40n) * b40);
448
+ const b160 = modP(pow2(b80, 80n) * b80);
449
+ const b240 = modP(pow2(b160, 80n) * b80);
450
+ const b250 = modP(pow2(b240, 10n) * b10);
451
+ const pow_p_5_8 = modP(pow2(b250, 2n) * x);
404
452
  return { pow_p_5_8, b2 };
405
453
  };
406
454
  var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
407
455
  var uvRatio = (u, v) => {
408
- const v3 = M(v * v * v);
409
- const v7 = M(v3 * v3 * v);
410
- const pow = pow_2_252_3(u * v7).pow_p_5_8;
411
- let x = M(u * v3 * pow);
412
- const vx2 = M(v * x * x);
456
+ const v3 = modP(v * modP(v * v));
457
+ const v7 = modP(modP(v3 * v3) * v);
458
+ const pow = pow_2_252_3(modP(u * v7)).pow_p_5_8;
459
+ let x = modP(u * modP(v3 * pow));
460
+ const vx2 = modP(v * modP(x * x));
413
461
  const root1 = x;
414
- const root2 = M(x * RM1);
462
+ const root2 = modP(x * RM1);
415
463
  const useRoot1 = vx2 === u;
416
464
  const useRoot2 = vx2 === M(-u);
417
465
  const noRoot = vx2 === M(-u * RM1);
@@ -423,22 +471,23 @@ var uvRatio = (u, v) => {
423
471
  x = M(-x);
424
472
  return { isValid: useRoot1 || useRoot2, value: x };
425
473
  };
426
- var modL_LE = (hash) => modN(bytesToNumLE(hash));
427
- var sha512a = (...m) => etc.sha512Async(...m);
428
- var sha512s = (...m) => callHash("sha512Sync")(...m);
474
+ var modL_LE = (hash) => modN(bytesToNumberLE(hash));
475
+ var sha512a = (...m) => Promise.resolve(callHash("sha512Async")(concatBytes(...m))).then(checkDigest);
476
+ var sha512s = (...m) => checkDigest(callHash("sha512")(concatBytes(...m)));
429
477
  var hash2extK = (hashed) => {
430
- const head = hashed.slice(0, L);
478
+ const copy = u8fr(hashed);
479
+ const head = copy.slice(0, 32);
431
480
  head[0] &= 248;
432
481
  head[31] &= 127;
433
482
  head[31] |= 64;
434
- const prefix = hashed.slice(L, L2);
483
+ const prefix = copy.slice(32, 64);
435
484
  const scalar = modL_LE(head);
436
485
  const point = G.multiply(scalar);
437
486
  const pointBytes = point.toBytes();
438
487
  return { head, prefix, scalar, point, pointBytes };
439
488
  };
440
- var getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, L)).then(hash2extK);
441
- var getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, L)));
489
+ var getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
490
+ var getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
442
491
  var getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
443
492
  var hashFinishS = (res) => res.finish(sha512s(res.hashable));
444
493
  var _sign = (e, rBytes, msg) => {
@@ -448,40 +497,33 @@ var _sign = (e, rBytes, msg) => {
448
497
  const hashable = concatBytes(R, P2, msg);
449
498
  const finish = (hashed) => {
450
499
  const S = modN(r + modL_LE(hashed) * s);
451
- return abytes(concatBytes(R, numTo32bLE(S)), L2);
500
+ return abytes(concatBytes(R, numTo32bLE(S)), 64);
452
501
  };
453
502
  return { hashable, finish };
454
503
  };
455
- var sign = (msg, privKey) => {
456
- const m = toU8(msg);
457
- const e = getExtendedPublicKey(privKey);
504
+ var sign = (message, secretKey) => {
505
+ const m = abytes(message);
506
+ const e = getExtendedPublicKey(secretKey);
458
507
  const rBytes = sha512s(e.prefix, m);
459
508
  return hashFinishS(_sign(e, rBytes, m));
460
509
  };
461
- var etc = {
462
- sha512Async: async (...messages) => {
510
+ var hashes = {
511
+ sha512Async: async (message) => {
463
512
  const s = subtle();
464
- const m = concatBytes(...messages);
513
+ const m = concatBytes(message);
465
514
  return u8n(await s.digest("SHA-512", m.buffer));
466
515
  },
467
- sha512Sync: void 0,
468
- bytesToHex,
469
- hexToBytes,
470
- concatBytes,
471
- mod: M,
472
- invert,
473
- randomBytes
516
+ sha512: void 0
474
517
  };
475
- var utils = {
518
+ var randomSecretKey = (seed) => {
519
+ seed = seed === void 0 ? randomBytes(L) : seed;
520
+ return abytes(seed, L);
521
+ };
522
+ var utils = /* @__PURE__ */ Object.freeze({
476
523
  getExtendedPublicKeyAsync,
477
524
  getExtendedPublicKey,
478
- randomPrivateKey: () => randomBytes(L),
479
- precompute: (w = 8, p = G) => {
480
- p.multiply(3n);
481
- return p;
482
- }
483
- // no-op
484
- };
525
+ randomSecretKey
526
+ });
485
527
  var W = 8;
486
528
  var scalarBits = 256;
487
529
  var pwindows = Math.ceil(scalarBits / W) + 1;
@@ -532,18 +574,29 @@ var wNAF = (n) => {
532
574
  p = p.add(ctneg(isNeg, comp[offP]));
533
575
  }
534
576
  }
577
+ if (n !== 0n)
578
+ err("invalid wnaf");
535
579
  return { p, f };
536
580
  };
537
581
 
538
- // node_modules/@noble/hashes/esm/utils.js
582
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js
539
583
  function isBytes2(a) {
540
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
584
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
541
585
  }
542
- function abytes2(b, ...lengths) {
543
- if (!isBytes2(b))
544
- throw new Error("Uint8Array expected");
545
- if (lengths.length > 0 && !lengths.includes(b.length))
546
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
586
+ function abytes2(value, length, title = "") {
587
+ const bytes = isBytes2(value);
588
+ const len = value?.length;
589
+ const needsLen = length !== void 0;
590
+ if (!bytes || needsLen) {
591
+ const prefix = title && `"${title}" `;
592
+ const ofLen = "";
593
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
594
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
595
+ if (!bytes)
596
+ throw new TypeError(message);
597
+ throw new RangeError(message);
598
+ }
599
+ return value;
547
600
  }
548
601
  function aexists(instance, checkFinished = true) {
549
602
  if (instance.destroyed)
@@ -552,10 +605,10 @@ function aexists(instance, checkFinished = true) {
552
605
  throw new Error("Hash#digest() has already been called");
553
606
  }
554
607
  function aoutput(out, instance) {
555
- abytes2(out);
608
+ abytes2(out, void 0, "digestInto() output");
556
609
  const min = instance.outputLen;
557
610
  if (out.length < min) {
558
- throw new Error("digestInto() expects output buffer of length at least " + min);
611
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
559
612
  }
560
613
  }
561
614
  function clean(...arrays) {
@@ -566,48 +619,37 @@ function clean(...arrays) {
566
619
  function createView(arr) {
567
620
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
568
621
  }
569
- function utf8ToBytes(str) {
570
- if (typeof str !== "string")
571
- throw new Error("string expected");
572
- return new Uint8Array(new TextEncoder().encode(str));
573
- }
574
- function toBytes(data) {
575
- if (typeof data === "string")
576
- data = utf8ToBytes(data);
577
- abytes2(data);
578
- return data;
579
- }
580
- var Hash = class {
581
- };
582
- function createHasher(hashCons) {
583
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
584
- const tmp = hashCons();
622
+ function createHasher(hashCons, info = {}) {
623
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
624
+ const tmp = hashCons(void 0);
585
625
  hashC.outputLen = tmp.outputLen;
586
626
  hashC.blockLen = tmp.blockLen;
587
- hashC.create = () => hashCons();
588
- return hashC;
627
+ hashC.canXOF = tmp.canXOF;
628
+ hashC.create = (opts) => hashCons(opts);
629
+ Object.assign(hashC, info);
630
+ return Object.freeze(hashC);
589
631
  }
632
+ var oidNist = (suffix) => ({
633
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
634
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
635
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
636
+ });
590
637
 
591
- // node_modules/@noble/hashes/esm/_md.js
592
- function setBigUint64(view, byteOffset, value, isLE) {
593
- if (typeof view.setBigUint64 === "function")
594
- return view.setBigUint64(byteOffset, value, isLE);
595
- const _32n2 = BigInt(32);
596
- const _u32_max = BigInt(4294967295);
597
- const wh = Number(value >> _32n2 & _u32_max);
598
- const wl = Number(value & _u32_max);
599
- const h2 = isLE ? 4 : 0;
600
- const l = isLE ? 0 : 4;
601
- view.setUint32(byteOffset + h2, wh, isLE);
602
- view.setUint32(byteOffset + l, wl, isLE);
603
- }
604
- var HashMD = class extends Hash {
638
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js
639
+ var HashMD = class {
605
640
  constructor(blockLen, outputLen, padOffset, isLE) {
606
- super();
607
- this.finished = false;
608
- this.length = 0;
609
- this.pos = 0;
610
- this.destroyed = false;
641
+ __publicField(this, "blockLen");
642
+ __publicField(this, "outputLen");
643
+ __publicField(this, "canXOF", false);
644
+ __publicField(this, "padOffset");
645
+ __publicField(this, "isLE");
646
+ // For partial updates less than block size
647
+ __publicField(this, "buffer");
648
+ __publicField(this, "view");
649
+ __publicField(this, "finished", false);
650
+ __publicField(this, "length", 0);
651
+ __publicField(this, "pos", 0);
652
+ __publicField(this, "destroyed", false);
611
653
  this.blockLen = blockLen;
612
654
  this.outputLen = outputLen;
613
655
  this.padOffset = padOffset;
@@ -617,7 +659,6 @@ var HashMD = class extends Hash {
617
659
  }
618
660
  update(data) {
619
661
  aexists(this);
620
- data = toBytes(data);
621
662
  abytes2(data);
622
663
  const { view, buffer, blockLen } = this;
623
664
  const len = data.length;
@@ -655,12 +696,12 @@ var HashMD = class extends Hash {
655
696
  }
656
697
  for (let i = pos; i < blockLen; i++)
657
698
  buffer[i] = 0;
658
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
699
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
659
700
  this.process(view, 0);
660
701
  const oview = createView(out);
661
702
  const len = this.outputLen;
662
703
  if (len % 4)
663
- throw new Error("_sha2: outputLen should be aligned to 32bit");
704
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
664
705
  const outLen = len / 4;
665
706
  const state = this.get();
666
707
  if (outLen > state.length)
@@ -710,7 +751,7 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
710
751
  327033209
711
752
  ]);
712
753
 
713
- // node_modules/@noble/hashes/esm/_u64.js
754
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js
714
755
  var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
715
756
  var _32n = /* @__PURE__ */ BigInt(32);
716
757
  function fromBig(n, le = false) {
@@ -745,7 +786,7 @@ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0
745
786
  var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
746
787
  var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
747
788
 
748
- // node_modules/@noble/hashes/esm/sha2.js
789
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js
749
790
  var K512 = /* @__PURE__ */ (() => split([
750
791
  "0x428a2f98d728ae22",
751
792
  "0x7137449123ef65cd",
@@ -832,25 +873,9 @@ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
832
873
  var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
833
874
  var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
834
875
  var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
835
- var SHA512 = class extends HashMD {
836
- constructor(outputLen = 64) {
876
+ var SHA2_64B = class extends HashMD {
877
+ constructor(outputLen) {
837
878
  super(128, outputLen, 16, false);
838
- this.Ah = SHA512_IV[0] | 0;
839
- this.Al = SHA512_IV[1] | 0;
840
- this.Bh = SHA512_IV[2] | 0;
841
- this.Bl = SHA512_IV[3] | 0;
842
- this.Ch = SHA512_IV[4] | 0;
843
- this.Cl = SHA512_IV[5] | 0;
844
- this.Dh = SHA512_IV[6] | 0;
845
- this.Dl = SHA512_IV[7] | 0;
846
- this.Eh = SHA512_IV[8] | 0;
847
- this.El = SHA512_IV[9] | 0;
848
- this.Fh = SHA512_IV[10] | 0;
849
- this.Fl = SHA512_IV[11] | 0;
850
- this.Gh = SHA512_IV[12] | 0;
851
- this.Gl = SHA512_IV[13] | 0;
852
- this.Hh = SHA512_IV[14] | 0;
853
- this.Hl = SHA512_IV[15] | 0;
854
879
  }
855
880
  // prettier-ignore
856
881
  get() {
@@ -939,23 +964,41 @@ var SHA512 = class extends HashMD {
939
964
  clean(SHA512_W_H, SHA512_W_L);
940
965
  }
941
966
  destroy() {
967
+ this.destroyed = true;
942
968
  clean(this.buffer);
943
969
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
944
970
  }
945
971
  };
946
- var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
947
-
948
- // node_modules/@noble/hashes/esm/sha512.js
949
- var sha5122 = sha512;
972
+ var _SHA512 = class extends SHA2_64B {
973
+ constructor() {
974
+ super(64);
975
+ __publicField(this, "Ah", SHA512_IV[0] | 0);
976
+ __publicField(this, "Al", SHA512_IV[1] | 0);
977
+ __publicField(this, "Bh", SHA512_IV[2] | 0);
978
+ __publicField(this, "Bl", SHA512_IV[3] | 0);
979
+ __publicField(this, "Ch", SHA512_IV[4] | 0);
980
+ __publicField(this, "Cl", SHA512_IV[5] | 0);
981
+ __publicField(this, "Dh", SHA512_IV[6] | 0);
982
+ __publicField(this, "Dl", SHA512_IV[7] | 0);
983
+ __publicField(this, "Eh", SHA512_IV[8] | 0);
984
+ __publicField(this, "El", SHA512_IV[9] | 0);
985
+ __publicField(this, "Fh", SHA512_IV[10] | 0);
986
+ __publicField(this, "Fl", SHA512_IV[11] | 0);
987
+ __publicField(this, "Gh", SHA512_IV[12] | 0);
988
+ __publicField(this, "Gl", SHA512_IV[13] | 0);
989
+ __publicField(this, "Hh", SHA512_IV[14] | 0);
990
+ __publicField(this, "Hl", SHA512_IV[15] | 0);
991
+ }
992
+ };
993
+ var sha512 = /* @__PURE__ */ createHasher(
994
+ () => new _SHA512(),
995
+ /* @__PURE__ */ oidNist(3)
996
+ );
950
997
 
951
998
  // src/crypto/keys.ts
952
- etc.sha512Sync = (...m) => {
953
- const h2 = sha5122.create();
954
- for (const msg of m) h2.update(msg);
955
- return h2.digest();
956
- };
999
+ hashes.sha512 = sha512;
957
1000
  function generateKeyPair() {
958
- const privateKey = utils.randomPrivateKey();
1001
+ const privateKey = utils.randomSecretKey();
959
1002
  const publicKey = getPublicKey(privateKey);
960
1003
  return { privateKey, publicKey };
961
1004
  }
@@ -1059,18 +1102,20 @@ function base64UrlEncode(data) {
1059
1102
  }
1060
1103
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1061
1104
  }
1062
- function createEdDSAJWT(privateKey, lifetimeSeconds = 300) {
1105
+ function createEdDSAJWT(privateKey, lifetimeSeconds = 300, audience) {
1063
1106
  const publicKey = getPublicKey2(privateKey);
1064
1107
  const multikey = encodePublicKey(publicKey);
1065
1108
  const did = `did:key:${multikey}`;
1066
1109
  const nowSecs = Math.floor(Date.now() / 1e3);
1067
1110
  const header = JSON.stringify({ alg: "EdDSA", typ: "JWT", kid: multikey });
1068
- const payload = JSON.stringify({
1111
+ const claims = {
1069
1112
  sub: did,
1070
1113
  iss: did,
1071
1114
  iat: nowSecs,
1072
1115
  exp: nowSecs + lifetimeSeconds
1073
- });
1116
+ };
1117
+ if (audience) claims.aud = audience;
1118
+ const payload = JSON.stringify(claims);
1074
1119
  const headerB64 = base64UrlEncode(encoder.encode(header));
1075
1120
  const payloadB64 = base64UrlEncode(encoder.encode(payload));
1076
1121
  const signingInput = `${headerB64}.${payloadB64}`;
@@ -1083,7 +1128,7 @@ function createEdDSAJWT(privateKey, lifetimeSeconds = 300) {
1083
1128
  var Auth = class {
1084
1129
  };
1085
1130
  var NoAuth = class extends Auth {
1086
- apply(_headers) {
1131
+ apply(_headers, _audience) {
1087
1132
  }
1088
1133
  };
1089
1134
  var BearerAuth = class extends Auth {
@@ -1091,11 +1136,22 @@ var BearerAuth = class extends Auth {
1091
1136
  super();
1092
1137
  this._token = token;
1093
1138
  }
1094
- apply(headers) {
1139
+ apply(headers, _audience) {
1095
1140
  headers["Authorization"] = `Bearer ${this._token}`;
1096
1141
  }
1097
1142
  };
1098
- var KeyPairAuth = class _KeyPairAuth extends Auth {
1143
+ var BasicAuth = class extends Auth {
1144
+ constructor(username, password) {
1145
+ super();
1146
+ this._username = username;
1147
+ this._password = password;
1148
+ }
1149
+ apply(headers, _audience) {
1150
+ const credentials = Buffer.from(`${this._username}:${this._password}`, "utf-8").toString("base64");
1151
+ headers["Authorization"] = `Basic ${credentials}`;
1152
+ }
1153
+ };
1154
+ var Ed25519Auth = class _Ed25519Auth extends Auth {
1099
1155
  /**
1100
1156
  * @param privateKey - 32-byte Ed25519 private key
1101
1157
  * @param tokenLifetimeSeconds - JWT lifetime in seconds (default 300 = 5 min)
@@ -1107,28 +1163,39 @@ var KeyPairAuth = class _KeyPairAuth extends Auth {
1107
1163
  this._did = didFromPublicKey(this._publicKey);
1108
1164
  this._lifetime = tokenLifetimeSeconds;
1109
1165
  }
1110
- apply(headers) {
1111
- const jwt = createEdDSAJWT(this._privateKey, this._lifetime);
1166
+ apply(headers, audience) {
1167
+ const jwt = createEdDSAJWT(this._privateKey, this._lifetime, this._audience ?? audience);
1112
1168
  headers["Authorization"] = `Bearer ${jwt}`;
1113
1169
  }
1114
1170
  /** The caller's DID derived from the public key. */
1115
1171
  getDID() {
1116
1172
  return this._did;
1117
1173
  }
1174
+ /**
1175
+ * Explicitly pin the JWT `aud` claim. Overrides the venue DID the transport
1176
+ * supplies — normally unnecessary, since the venue DID is the correct audience.
1177
+ */
1178
+ set audience(value) {
1179
+ this._audience = value;
1180
+ }
1181
+ get audience() {
1182
+ return this._audience;
1183
+ }
1118
1184
  /** The 32-byte Ed25519 public key. */
1119
1185
  getPublicKey() {
1120
1186
  return this._publicKey;
1121
1187
  }
1122
- /** Generate a new random keypair and return a KeyPairAuth instance. */
1188
+ /** Generate a new random keypair and return an Ed25519Auth instance. */
1123
1189
  static generate(tokenLifetimeSeconds = 300) {
1124
1190
  const { privateKey } = generateKeyPair();
1125
- return new _KeyPairAuth(privateKey, tokenLifetimeSeconds);
1191
+ return new _Ed25519Auth(privateKey, tokenLifetimeSeconds);
1126
1192
  }
1127
1193
  /** Create from a hex-encoded private key string. */
1128
1194
  static fromHex(privateKeyHex, tokenLifetimeSeconds = 300) {
1129
- return new _KeyPairAuth(hexToPrivateKey(privateKeyHex), tokenLifetimeSeconds);
1195
+ return new _Ed25519Auth(hexToPrivateKey(privateKeyHex), tokenLifetimeSeconds);
1130
1196
  }
1131
1197
  };
1198
+ var KeyPairAuth = Ed25519Auth;
1132
1199
  var CredentialsHTTP = class {
1133
1200
  constructor(venueId, apiKey, userId) {
1134
1201
  this.venueId = venueId;
@@ -1151,14 +1218,70 @@ var logger = {
1151
1218
  }
1152
1219
  };
1153
1220
 
1221
+ // src/did.ts
1222
+ var Namespace = {
1223
+ ASSET: "a",
1224
+ OPERATION: "o",
1225
+ JOB: "j",
1226
+ AGENT: "g",
1227
+ WORKSPACE: "w",
1228
+ SECRET: "s",
1229
+ // Virtual namespaces — resolved against the active request context:
1230
+ AGENT_SCRATCH: "n",
1231
+ SESSION_SCRATCH: "c",
1232
+ JOB_SCRATCH: "t",
1233
+ VENUE: "v"
1234
+ };
1235
+ function isDid(value) {
1236
+ if (value.includes("/")) return false;
1237
+ const parts = value.split(":");
1238
+ return parts.length >= 3 && parts[0] === "did" && parts.slice(1).every((p) => p.length > 0);
1239
+ }
1240
+ function didMethod(value) {
1241
+ return isDid(value) ? value.split(":")[1] : null;
1242
+ }
1243
+ function parseDidUrl(value) {
1244
+ let did = null;
1245
+ let rest;
1246
+ if (value.startsWith("did:")) {
1247
+ const slash2 = value.indexOf("/");
1248
+ if (slash2 === -1) return { did: value, namespace: null, path: "" };
1249
+ did = value.slice(0, slash2);
1250
+ rest = value.slice(slash2 + 1);
1251
+ } else {
1252
+ rest = value.replace(/^\/+/, "");
1253
+ }
1254
+ if (rest === "") return { did, namespace: null, path: "" };
1255
+ const slash = rest.indexOf("/");
1256
+ if (slash === -1) return { did, namespace: rest, path: "" };
1257
+ return { did, namespace: rest.slice(0, slash), path: rest.slice(slash + 1) };
1258
+ }
1259
+ function didUrl(did, namespace, ...segments) {
1260
+ const tail = segments.filter((s) => s !== "").map((s) => s.replace(/^\/+|\/+$/g, "")).join("/");
1261
+ const base = tail ? `${namespace}/${tail}` : namespace;
1262
+ return did ? `${did}/${base}` : base;
1263
+ }
1264
+ function assetHash(ref) {
1265
+ if (!ref.includes("/")) {
1266
+ const s = ref.startsWith("0x") ? ref.slice(2) : ref;
1267
+ return s.length > 0 && /^[0-9a-fA-F]+$/.test(s) ? ref : null;
1268
+ }
1269
+ const parsed = parseDidUrl(ref);
1270
+ if (parsed.namespace === Namespace.ASSET && parsed.path && !parsed.path.includes("/")) {
1271
+ return parsed.path;
1272
+ }
1273
+ return null;
1274
+ }
1275
+
1154
1276
  // src/Utils.ts
1155
1277
  async function parseErrorBody(response) {
1156
1278
  let body = null;
1157
1279
  let message = `Request failed with status ${response.status}`;
1158
1280
  try {
1159
1281
  body = await response.json();
1160
- if (body?.error) {
1161
- message = body.error;
1282
+ if (body && typeof body === "object" && "error" in body) {
1283
+ const err2 = body.error;
1284
+ if (typeof err2 === "string") message = err2;
1162
1285
  }
1163
1286
  } catch {
1164
1287
  try {
@@ -1219,9 +1342,7 @@ async function fetchStreamWithError(url, options) {
1219
1342
  return response;
1220
1343
  }
1221
1344
  function isJobComplete(jobStatus) {
1222
- if (jobStatus == null)
1223
- return false;
1224
- return jobStatus == "COMPLETE" /* COMPLETE */ ? true : false;
1345
+ return jobStatus === "COMPLETE" /* COMPLETE */;
1225
1346
  }
1226
1347
  function isJobPaused(jobStatus) {
1227
1348
  if (jobStatus == null)
@@ -1239,18 +1360,20 @@ function isJobFinished(jobStatus) {
1239
1360
  return false;
1240
1361
  }
1241
1362
  function getParsedAssetId(assetId) {
1242
- if (assetId.startsWith("did:web")) {
1363
+ if (assetId.startsWith("did:")) {
1243
1364
  const parts = assetId.split("/");
1244
1365
  return parts[parts.length - 1];
1245
1366
  }
1246
1367
  return assetId;
1247
1368
  }
1248
1369
  function getAssetIdFromPath(assetHex, assetPath) {
1249
- const venueDid = decodeURIComponent(assetPath.split("/")[4]);
1250
- return venueDid + "/a/" + assetHex;
1370
+ const parts = assetPath.split("/");
1371
+ const i = parts.indexOf("assets");
1372
+ const venueDid = decodeURIComponent(i >= 0 && i + 1 < parts.length ? parts[i + 1] : "");
1373
+ return getAssetIdFromVenueId(assetHex, venueDid);
1251
1374
  }
1252
1375
  function getAssetIdFromVenueId(assetHex, venueId) {
1253
- return venueId + "/a/" + assetHex;
1376
+ return didUrl(venueId, Namespace.ASSET, assetHex);
1254
1377
  }
1255
1378
  function createSSEEvent(fields) {
1256
1379
  const data = fields.data ?? "";
@@ -1370,21 +1493,6 @@ var AgentManager = class {
1370
1493
  async trigger(agentId) {
1371
1494
  return this.venue.operations.run("v/ops/agent/trigger", { agentId });
1372
1495
  }
1373
- async query(agentId) {
1374
- const read = (path) => this.venue.operations.run("v/ops/covia/read", { path }).catch(() => ({ value: null }));
1375
- const [info, timelineRes, stateRes, inboxRes] = await Promise.all([
1376
- this.venue.operations.run("v/ops/agent/info", { agentId }),
1377
- read(`g/${agentId}/timeline`),
1378
- read(`g/${agentId}/state`),
1379
- read(`g/${agentId}/inbox`)
1380
- ]);
1381
- return {
1382
- ...info,
1383
- timeline: Array.isArray(timelineRes.value) ? timelineRes.value : [],
1384
- state: stateRes.value ?? {},
1385
- inbox: Array.isArray(inboxRes.value) ? inboxRes.value : []
1386
- };
1387
- }
1388
1496
  async list(includeTerminated) {
1389
1497
  return this.venue.operations.run("v/ops/agent/list", { includeTerminated });
1390
1498
  }
@@ -1662,13 +1770,12 @@ var JobManager = class {
1662
1770
  }
1663
1771
  _buildHeaders() {
1664
1772
  const headers = { "Content-Type": "application/json" };
1665
- this.venue.auth.apply(headers);
1773
+ this.venue.auth.apply(headers, this.venue.venueId);
1666
1774
  return headers;
1667
1775
  }
1668
1776
  };
1669
1777
 
1670
1778
  // src/Asset.ts
1671
- var cache = /* @__PURE__ */ new Map();
1672
1779
  var Asset = class {
1673
1780
  constructor(id, venue, metadata = {}) {
1674
1781
  this.id = id;
@@ -1681,16 +1788,8 @@ var Asset = class {
1681
1788
  * Get asset metadata
1682
1789
  * @returns {Promise<AssetMetadata>}
1683
1790
  */
1684
- async getMetadata() {
1685
- if (cache.has(this.id)) {
1686
- return Promise.resolve(cache.get(this.id));
1687
- } else {
1688
- const data = this._assets.getMetadata(this.id);
1689
- if (data) {
1690
- cache.set(this.id, data);
1691
- }
1692
- return data;
1693
- }
1791
+ getMetadata() {
1792
+ return this._assets.getMetadata(this.id);
1694
1793
  }
1695
1794
  /**
1696
1795
  * Put content to asset
@@ -1715,20 +1814,22 @@ var Asset = class {
1715
1814
  return `${this.venue.baseUrl}/api/v1/assets/${this.id}/content`;
1716
1815
  }
1717
1816
  /**
1718
- * Execute the operation
1817
+ * Execute the operation and await its result.
1719
1818
  * @param input - Operation input parameters
1720
- * @returns {Promise<any>}
1819
+ * @param options - Invocation options (e.g. UCAN proofs)
1820
+ * @returns {Promise<T>} The operation result, typed as `T` (defaults to `unknown`)
1721
1821
  */
1722
- run(input) {
1723
- return this._operations.run(this.id, input);
1822
+ run(input, options) {
1823
+ return this._operations.run(this.id, input, options);
1724
1824
  }
1725
1825
  /**
1726
- * Execute the operation
1727
- * @param input - Operation input parameters
1728
- * @returns {Promise<Job>}
1729
- */
1730
- invoke(input) {
1731
- return this._operations.invoke(this.id, input);
1826
+ * Execute the operation, returning the Job without awaiting completion.
1827
+ * @param input - Operation input parameters
1828
+ * @param options - Invocation options (e.g. UCAN proofs)
1829
+ * @returns {Promise<Job>}
1830
+ */
1831
+ invoke(input, options) {
1832
+ return this._operations.invoke(this.id, input, options);
1732
1833
  }
1733
1834
  };
1734
1835
 
@@ -1751,20 +1852,25 @@ var DataAsset = class extends Asset {
1751
1852
  };
1752
1853
 
1753
1854
  // src/AssetManager.ts
1754
- var cache2 = /* @__PURE__ */ new Map();
1855
+ var cache = /* @__PURE__ */ new Map();
1755
1856
  var AssetManager = class {
1756
1857
  constructor(venue) {
1757
1858
  this.venue = venue;
1758
1859
  }
1759
1860
  /**
1760
- * Get asset by ID
1761
- * @param assetId - Asset identifier
1861
+ * Get an asset by lattice address.
1862
+ *
1863
+ * `assetId` may be a content hash (`<hash>`, `a/<hash>`, `<DID>/a/<hash>`) or
1864
+ * a mutable lattice path the venue resolves (`w/my-assets/foo`, `o/my-op`,
1865
+ * `<DID>/w/...`). Only content-addressed (immutable) refs are cached;
1866
+ * mutable paths are always re-fetched, so a changed value is never served stale.
1867
+ * @param assetId - Asset identifier or lattice address
1762
1868
  * @returns Returns either an Operation or DataAsset based on the asset's metadata
1763
1869
  */
1764
1870
  async get(assetId) {
1765
- if (cache2.has(assetId)) {
1766
- const cachedData = cache2.get(assetId);
1767
- if (cachedData.metadata?.operation) {
1871
+ if (cache.has(assetId)) {
1872
+ const cachedData = cache.get(assetId);
1873
+ if (cachedData.operation) {
1768
1874
  return new Operation(assetId, this.venue, cachedData);
1769
1875
  } else {
1770
1876
  return new DataAsset(assetId, this.venue, cachedData);
@@ -1772,8 +1878,8 @@ var AssetManager = class {
1772
1878
  }
1773
1879
  try {
1774
1880
  const data = await fetchWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}`);
1775
- cache2.set(assetId, data);
1776
- if (data.metadata?.operation) {
1881
+ if (assetHash(assetId)) cache.set(assetId, data);
1882
+ if (data.operation) {
1777
1883
  return new Operation(assetId, this.venue, data);
1778
1884
  } else {
1779
1885
  return new DataAsset(assetId, this.venue, data);
@@ -1832,7 +1938,7 @@ var AssetManager = class {
1832
1938
  try {
1833
1939
  return await fetchWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}/content`, {
1834
1940
  method: "PUT",
1835
- headers: this._buildHeaders(),
1941
+ headers: this._buildHeaders(null),
1836
1942
  body: content
1837
1943
  });
1838
1944
  } catch (error) {
@@ -1869,11 +1975,15 @@ var AssetManager = class {
1869
1975
  * Clear the asset cache.
1870
1976
  */
1871
1977
  clearCache() {
1872
- cache2.clear();
1873
- }
1874
- _buildHeaders() {
1875
- const headers = { "Content-Type": "application/json" };
1876
- this.venue.auth.apply(headers);
1978
+ cache.clear();
1979
+ }
1980
+ // `contentType` defaults to JSON for the metadata/register endpoints. Pass
1981
+ // `undefined` for binary content upload so fetch infers the type from the
1982
+ // body — forcing application/json would mislabel a Blob/ArrayBuffer/stream.
1983
+ _buildHeaders(contentType = "application/json") {
1984
+ const headers = {};
1985
+ if (contentType) headers["Content-Type"] = contentType;
1986
+ this.venue.auth.apply(headers, this.venue.venueId);
1877
1987
  return headers;
1878
1988
  }
1879
1989
  };
@@ -1904,7 +2014,7 @@ var OperationManager = class {
1904
2014
  */
1905
2015
  async run(assetId, input, options) {
1906
2016
  const job = await this.invoke(assetId, input, options);
1907
- return job.result();
2017
+ return await job.result();
1908
2018
  }
1909
2019
  /**
1910
2020
  * Execute an operation and return a Job for tracking
@@ -1925,43 +2035,121 @@ var OperationManager = class {
1925
2035
  headers: this._buildHeaders(),
1926
2036
  body: JSON.stringify(payload)
1927
2037
  });
1928
- return new Job(response?.id, this.venue, response);
2038
+ return new Job(response.id ?? "", this.venue, response);
1929
2039
  }
1930
2040
  _buildHeaders() {
1931
2041
  const headers = { "Content-Type": "application/json" };
1932
- this.venue.auth.apply(headers);
2042
+ this.venue.auth.apply(headers, this.venue.venueId);
1933
2043
  return headers;
1934
2044
  }
1935
2045
  };
1936
2046
 
1937
2047
  // src/WorkspaceManager.ts
2048
+ function versionAtLeast(version, major, minor) {
2049
+ const m = version?.match(/^(\d+)\.(\d+)/);
2050
+ if (!m) return true;
2051
+ const [maj, min] = [Number(m[1]), Number(m[2])];
2052
+ return maj > major || maj === major && min >= minor;
2053
+ }
1938
2054
  var WorkspaceManager = class {
1939
2055
  constructor(venue) {
1940
2056
  this.venue = venue;
2057
+ // Whether this venue serves GET /api/v1/values/* — flipped on the first 404
2058
+ // so pre-0.3 venues pay the probe once, not one failed GET per read.
2059
+ this.valuesSupported = true;
1941
2060
  }
1942
- async read(path, maxSize) {
1943
- return this.venue.operations.run("v/ops/covia/read", { path, maxSize });
2061
+ _headers() {
2062
+ const headers = { "Content-Type": "application/json" };
2063
+ this.venue.auth.apply(headers, this.venue.venueId);
2064
+ return headers;
1944
2065
  }
1945
- async write(path, value) {
1946
- return this.venue.operations.run("v/ops/covia/write", { path, value });
2066
+ /** GET a job-free `/api/v1/values/{op}` read; omit undefined params. */
2067
+ _values(op, params) {
2068
+ const qs = new URLSearchParams();
2069
+ for (const [k, v] of Object.entries(params)) if (v !== void 0) qs.set(k, String(v));
2070
+ return fetchWithError(`${this.venue.baseUrl}/api/v1/values/${op}?${qs.toString()}`, { headers: this._headers() });
1947
2071
  }
1948
- async delete(path) {
1949
- return this.venue.operations.run("v/ops/covia/delete", { path });
2072
+ /**
2073
+ * Whether the venue serves `GET /api/v1/values/*`: no if a probe already
2074
+ * 404'd, or if the venue's last known status identifies it as pre-0.3
2075
+ * (venues that old don't report a `version` at all). Checked per read —
2076
+ * connect/`status()` may populate the status after this manager exists.
2077
+ */
2078
+ supportsValues() {
2079
+ if (!this.valuesSupported) return false;
2080
+ const status = this.venue.lastKnownStatus;
2081
+ if (status && (!status.version || !versionAtLeast(status.version, 0, 3))) {
2082
+ this.valuesSupported = false;
2083
+ }
2084
+ return this.valuesSupported;
2085
+ }
2086
+ /** A job-free values read, falling back to the invoke path on pre-0.3 venues. */
2087
+ async _valuesOr(op, params, fallback) {
2088
+ if (this.supportsValues()) {
2089
+ try {
2090
+ return await this._values(op, params);
2091
+ } catch (e) {
2092
+ if (!(e instanceof NotFoundError)) throw e;
2093
+ this.valuesSupported = false;
2094
+ }
2095
+ }
2096
+ return fallback();
2097
+ }
2098
+ // ── job-free reads (#177) ───────────────────────────────────────────────────
2099
+ async read(path, maxSize, ucans) {
2100
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/read", { path, maxSize }, { ucans });
2101
+ return this._valuesOr("read", { path, maxSize }, () => this.venue.operations.run("v/ops/covia/read", { path, maxSize }));
2102
+ }
2103
+ async list(path, limit, offset, ucans) {
2104
+ if (ucans?.length || !path) return this.venue.operations.run("v/ops/covia/list", { path, limit, offset }, { ucans });
2105
+ return this._valuesOr("list", { path, limit, offset }, () => this.venue.operations.run("v/ops/covia/list", { path, limit, offset }));
2106
+ }
2107
+ async slice(path, offset, limit, ucans) {
2108
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/slice", { path, offset, limit }, { ucans });
2109
+ return this._valuesOr("slice", { path, offset, limit }, () => this.venue.operations.run("v/ops/covia/slice", { path, offset, limit }));
1950
2110
  }
1951
- async append(path, value) {
1952
- return this.venue.operations.run("v/ops/covia/append", { path, value });
2111
+ async inspect(paths, budget, compact, ucans) {
2112
+ if (ucans?.length || Array.isArray(paths)) return this.venue.operations.run("v/ops/covia/inspect", { paths, budget, compact }, { ucans });
2113
+ return this._valuesOr("inspect", { path: paths, budget, compact }, () => this.venue.operations.run("v/ops/covia/inspect", { paths, budget, compact }));
2114
+ }
2115
+ /**
2116
+ * Count entries at a depth below `path` — a job-free server-side tally, so the
2117
+ * caller never reads every record to learn "how many".
2118
+ *
2119
+ * `depth` = the exact number of `get`-steps below `path` to visit (default 1 =
2120
+ * direct children). Records nested at `w/x/<bucket>/<record>` are counted with
2121
+ * `depth: 2`. Absent path or a scalar → `{exists:false}`.
2122
+ */
2123
+ async count(path, opts = {}) {
2124
+ const { depth, ucans } = opts;
2125
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/aggregate", { path, depth }, { ucans });
2126
+ return this._valuesOr("count", { path, depth }, () => this.venue.operations.run("v/ops/covia/aggregate", { path, depth }));
2127
+ }
2128
+ /**
2129
+ * Count entries at a depth below `path`, optionally partitioned by a field —
2130
+ * the job-free, authoritative alternative to counting client-side.
2131
+ *
2132
+ * `groupBy` names the field whose value forms each group key (may be a relative
2133
+ * path, `foo/bar`); an entry missing it groups under `"null"`. Σ(group counts)
2134
+ * equals the top-level `count`.
2135
+ */
2136
+ async aggregate(path, opts = {}) {
2137
+ const { depth, groupBy, ucans } = opts;
2138
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/aggregate", { path, depth, groupBy }, { ucans });
2139
+ return this._valuesOr("aggregate", { path, depth, groupBy }, () => this.venue.operations.run("v/ops/covia/aggregate", { path, depth, groupBy }));
1953
2140
  }
1954
- async list(path, limit, offset) {
1955
- return this.venue.operations.run("v/ops/covia/list", { path, limit, offset });
2141
+ // ── writes stay on the job path (they should leave an audit record) ─────────
2142
+ async write(path, value, ucans) {
2143
+ return this.venue.operations.run("v/ops/covia/write", { path, value }, { ucans });
1956
2144
  }
1957
- async slice(path, offset, limit) {
1958
- return this.venue.operations.run("v/ops/covia/slice", { path, offset, limit });
2145
+ async delete(path, ucans) {
2146
+ return this.venue.operations.run("v/ops/covia/delete", { path }, { ucans });
1959
2147
  }
1960
- async copy(from, to) {
1961
- return this.venue.operations.run("v/ops/covia/copy", { from, to });
2148
+ async append(path, value, ucans) {
2149
+ return this.venue.operations.run("v/ops/covia/append", { path, value }, { ucans });
1962
2150
  }
1963
- async inspect(paths, budget, compact) {
1964
- return this.venue.operations.run("v/ops/covia/inspect", { paths, budget, compact });
2151
+ async copy(from, to, ucans) {
2152
+ return this.venue.operations.run("v/ops/covia/copy", { from, to }, { ucans });
1965
2153
  }
1966
2154
  };
1967
2155
 
@@ -1985,18 +2173,15 @@ var SecretManager = class {
1985
2173
  }
1986
2174
  /**
1987
2175
  * Extract a secret value by name.
1988
- * NOTE: This operation requires a UCAN capability grant. The backend
1989
- * may reject requests that lack the appropriate capability proof.
2176
+ * Requires a UCAN capability grant pass the proof token(s) as `ucans`.
2177
+ * Extracting another DID's secret needs a grant on that DID's `/s/<name>`.
1990
2178
  */
1991
- async extract(name) {
1992
- return this.venue.operations.run("v/ops/secret/extract", { name });
2179
+ async extract(name, ucans) {
2180
+ return this.venue.operations.run("v/ops/secret/extract", { name }, { ucans });
1993
2181
  }
1994
2182
  async list() {
1995
2183
  return this.venue.listSecrets();
1996
2184
  }
1997
- async put(name, value) {
1998
- return this.venue.putSecret(name, value);
1999
- }
2000
2185
  async delete(name) {
2001
2186
  return this.venue.deleteSecret(name);
2002
2187
  }
@@ -2028,9 +2213,6 @@ var Agent = class _Agent {
2028
2213
  async trigger() {
2029
2214
  return this._agents.trigger(this.id);
2030
2215
  }
2031
- async query() {
2032
- return this._agents.query(this.id);
2033
- }
2034
2216
  async suspend() {
2035
2217
  return this._agents.suspend(this.id);
2036
2218
  }
@@ -2087,6 +2269,33 @@ var ChatSession = class {
2087
2269
  // src/Venue.ts
2088
2270
  var webResolver = getResolver();
2089
2271
  var resolver = new Resolver(webResolver);
2272
+ function stripTrailingSlash(value) {
2273
+ return value.endsWith("/") ? value.slice(0, -1) : value;
2274
+ }
2275
+ function hostIsLocal(host) {
2276
+ const h2 = host.toLowerCase();
2277
+ if (h2 === "localhost" || h2.endsWith(".localhost") || h2.endsWith(".local")) return true;
2278
+ if (h2 === "::1" || h2 === "0.0.0.0") return true;
2279
+ if (/^127\./.test(h2)) return true;
2280
+ if (/^10\./.test(h2)) return true;
2281
+ if (/^192\.168\./.test(h2)) return true;
2282
+ if (/^172\.(1[6-9]|2\d|3[01])\./.test(h2)) return true;
2283
+ if (/^169\.254\./.test(h2)) return true;
2284
+ return false;
2285
+ }
2286
+ function schemelessVenueCandidates(venueId) {
2287
+ const authority = venueId.split("/")[0];
2288
+ const v6 = authority.match(/^\[([^\]]+)\]/);
2289
+ const host = v6 ? v6[1] : authority.split(":")[0];
2290
+ const bare = stripTrailingSlash(venueId);
2291
+ return hostIsLocal(host) ? [`http://${bare}`, `https://${bare}`] : [`https://${bare}`];
2292
+ }
2293
+ function venueBaseUrlCandidates(venueId) {
2294
+ if (venueId.startsWith("http:") || venueId.startsWith("https:")) {
2295
+ return [stripTrailingSlash(venueId)];
2296
+ }
2297
+ return schemelessVenueCandidates(venueId);
2298
+ }
2090
2299
  var Venue = class _Venue {
2091
2300
  get agents() {
2092
2301
  return this._agents ?? (this._agents = new AgentManager(this));
@@ -2113,16 +2322,32 @@ var Venue = class _Venue {
2113
2322
  this.baseUrl = options.baseUrl || "";
2114
2323
  this.venueId = options.venueId || "";
2115
2324
  this.auth = options.auth || new NoAuth();
2325
+ this.lastKnownStatus = options.status;
2116
2326
  this.metadata = {
2117
2327
  name: options.name || "default",
2118
2328
  description: options.description || ""
2119
2329
  };
2120
2330
  }
2121
2331
  /**
2122
- * Static method to connect to a venue
2123
- * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
2124
- * @param credentials - Optional credentials for venue authentication
2125
- * @returns {Promise<Venue>} A new Venue instance configured appropriately
2332
+ * Connect to a venue, validating it with `GET {base}/api/v1/status`. If the
2333
+ * venue is auth-gated (status answers 401/403 public access disabled), the
2334
+ * venue is validated against its public did:web document at
2335
+ * `/.well-known/did.json` instead, whose `id` becomes `venueId` identity is
2336
+ * publicly resolvable by spec even when the API is not.
2337
+ *
2338
+ * The input is permissive: a full `http(s)://` URL, a bare host / IP /
2339
+ * host:port, a `did:web:` id, or an existing Venue instance. Schemeless inputs
2340
+ * pick a scheme by host and may fall back across http/https (see
2341
+ * {@link venueBaseUrlCandidates}); did:web ids resolve to their `Covia.API.v1`
2342
+ * endpoint.
2343
+ *
2344
+ * @param venueId - A venue URL, DNS name / host:port, `did:web:` id, or existing Venue
2345
+ * @param auth - Optional credentials for venue authentication
2346
+ * @returns {Promise<Venue>} A connected venue. The actually resolved/validated
2347
+ * target is on the returned object: `venue.baseUrl` is the origin that
2348
+ * responded (the https candidate if an http fallback failed; the resolved
2349
+ * endpoint for a did:web id), and `venue.venueId` is the DID the venue
2350
+ * reported. The validated API root is `${venue.baseUrl}/api/v1`.
2126
2351
  */
2127
2352
  static async connect(venueId, auth) {
2128
2353
  if (venueId instanceof _Venue) {
@@ -2130,35 +2355,50 @@ var Venue = class _Venue {
2130
2355
  baseUrl: venueId.baseUrl,
2131
2356
  venueId: venueId.venueId,
2132
2357
  name: venueId.metadata.name,
2133
- auth
2358
+ auth,
2359
+ status: venueId.lastKnownStatus
2134
2360
  });
2135
2361
  }
2136
2362
  if (typeof venueId === "string") {
2137
- let baseUrl;
2138
- if (venueId.startsWith("http:") || venueId.startsWith("https:")) {
2139
- baseUrl = venueId;
2140
- if (baseUrl.endsWith("/"))
2141
- baseUrl = baseUrl.substring(0, baseUrl.length - 1);
2142
- } else if (venueId.startsWith("did:web:")) {
2363
+ let candidates;
2364
+ if (venueId.startsWith("did:web:")) {
2143
2365
  const didDoc = await resolver.resolve(venueId);
2144
2366
  if (!didDoc.didDocument) {
2145
2367
  throw new CoviaError("Invalid DID document");
2146
2368
  }
2147
2369
  const endpoint = didDoc.didDocument.service?.find((service) => service.type === "Covia.API.v1")?.serviceEndpoint;
2148
- if (!endpoint) {
2149
- throw new CoviaError("No endpoint found for DID");
2370
+ if (typeof endpoint !== "string") {
2371
+ throw new CoviaError("No (string) endpoint found for DID");
2150
2372
  }
2151
- baseUrl = endpoint.toString().replace(/\/api\/v1/, "");
2373
+ candidates = [endpoint.replace(/\/api\/v1/, "")];
2152
2374
  } else {
2153
- baseUrl = `https://${venueId}`;
2375
+ candidates = venueBaseUrlCandidates(venueId);
2154
2376
  }
2155
- const data = await fetchWithError(baseUrl + "/api/v1/status");
2156
- return new _Venue({
2157
- baseUrl,
2158
- venueId: data.did,
2159
- name: data.name,
2160
- auth
2161
- });
2377
+ let lastError;
2378
+ for (const baseUrl of candidates) {
2379
+ try {
2380
+ const data = await fetchWithError(baseUrl + "/api/v1/status");
2381
+ return new _Venue({
2382
+ baseUrl,
2383
+ venueId: data.did,
2384
+ name: data.name,
2385
+ auth,
2386
+ status: data
2387
+ });
2388
+ } catch (error) {
2389
+ if (error instanceof GridError && (error.statusCode === 401 || error.statusCode === 403)) {
2390
+ try {
2391
+ const doc = await fetchWithError(baseUrl + "/.well-known/did.json");
2392
+ if (doc?.id) {
2393
+ return new _Venue({ baseUrl, venueId: doc.id, auth });
2394
+ }
2395
+ } catch {
2396
+ }
2397
+ }
2398
+ lastError = error;
2399
+ }
2400
+ }
2401
+ throw lastError instanceof Error ? lastError : new CoviaError(`Could not connect to venue: ${venueId}`);
2162
2402
  }
2163
2403
  throw new CoviaError("Invalid venue ID parameter. Must be a string (URL/DNS) or Venue instance.");
2164
2404
  }
@@ -2212,18 +2452,6 @@ var Venue = class _Venue {
2212
2452
  });
2213
2453
  return Array.isArray(result.items) ? result.items : [];
2214
2454
  }
2215
- /**
2216
- * Store a secret value
2217
- * @param name - Secret name
2218
- * @param value - Secret value
2219
- */
2220
- async putSecret(name, value) {
2221
- await fetchWithError(`${this.baseUrl}/api/v1/secrets/${encodeURIComponent(name)}`, {
2222
- method: "PUT",
2223
- headers: this._buildHeaders(),
2224
- body: JSON.stringify({ value })
2225
- });
2226
- }
2227
2455
  /**
2228
2456
  * Delete a secret
2229
2457
  * @param name - Secret name
@@ -2238,8 +2466,39 @@ var Venue = class _Venue {
2238
2466
  * Get venue status
2239
2467
  * @returns {Promise<StatusData>}
2240
2468
  */
2241
- status() {
2242
- return fetchWithError(`${this.baseUrl}/api/v1/status`);
2469
+ async status() {
2470
+ const data = await fetchWithError(`${this.baseUrl}/api/v1/status`);
2471
+ this.lastKnownStatus = data;
2472
+ return data;
2473
+ }
2474
+ /**
2475
+ * Block until the venue is ready to serve operations.
2476
+ *
2477
+ * Polls {@link status} until it responds and reports either no explicit
2478
+ * `status` or `"OK"`. Connection/HTTP errors are treated as "not ready yet"
2479
+ * and retried until `timeoutMs` elapses — useful right after starting a venue,
2480
+ * since a cold venue may answer its root before its invoke layer is up.
2481
+ *
2482
+ * @param options.timeoutMs - Max time to wait (default 60000).
2483
+ * @param options.pollIntervalMs - Delay between polls (default 1000).
2484
+ * @returns The ready {@link StatusData}.
2485
+ * @throws {CoviaTimeoutError} If the venue is not ready within the timeout.
2486
+ */
2487
+ async waitUntilReady(options = {}) {
2488
+ const timeoutMs = options.timeoutMs ?? 6e4;
2489
+ const pollIntervalMs = options.pollIntervalMs ?? 1e3;
2490
+ const start = Date.now();
2491
+ for (; ; ) {
2492
+ try {
2493
+ const data = await this.status();
2494
+ if (data.status == null || data.status.toUpperCase() === "OK") return data;
2495
+ } catch {
2496
+ }
2497
+ if (Date.now() - start >= timeoutMs) {
2498
+ throw new CoviaTimeoutError(`Venue ${this.baseUrl} not ready within ${timeoutMs}ms`);
2499
+ }
2500
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
2501
+ }
2243
2502
  }
2244
2503
  /**
2245
2504
  * Get the full DID document for this venue
@@ -2277,35 +2536,33 @@ var Venue = class _Venue {
2277
2536
  }
2278
2537
  _buildHeaders() {
2279
2538
  const headers = { "Content-Type": "application/json" };
2280
- this.auth.apply(headers);
2539
+ this.auth.apply(headers, this.venueId);
2281
2540
  return headers;
2282
2541
  }
2283
2542
  };
2284
2543
 
2285
2544
  // src/Grid.ts
2286
- var cache3 = /* @__PURE__ */ new Map();
2545
+ var cache2 = /* @__PURE__ */ new Map();
2287
2546
  var Grid = class {
2288
2547
  /**
2289
2548
  * Static method to connect to a venue
2290
2549
  * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
2291
- * @param auth - Optional authentication provider (BearerAuth, KeyPairAuth, etc.)
2550
+ * @param auth - Optional authentication provider (BearerAuth, BasicAuth, Ed25519Auth, etc.)
2292
2551
  * @returns {Promise<Venue>} A new Venue instance configured appropriately
2293
2552
  */
2294
2553
  static async connect(venueId, auth) {
2295
- if (cache3.has(venueId))
2296
- return Promise.resolve(cache3.get(venueId));
2554
+ const cached = cache2.get(venueId);
2555
+ if (cached && cached.auth === auth)
2556
+ return cached.venue;
2297
2557
  const connectedVenue = await Venue.connect(venueId, auth);
2298
- cache3.set(venueId, connectedVenue);
2299
- return Promise.resolve(connectedVenue);
2558
+ cache2.set(venueId, { auth, venue: connectedVenue });
2559
+ return connectedVenue;
2300
2560
  }
2301
2561
  };
2302
2562
  /*! Bundled license information:
2303
2563
 
2304
2564
  @noble/ed25519/index.js:
2305
2565
  (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
2306
-
2307
- @noble/hashes/esm/utils.js:
2308
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2309
2566
  */
2310
2567
 
2311
- export { Agent, AgentManager, AgentStatus, Asset, AssetManager, AssetNotFoundError, Auth, BearerAuth, ChatSession, CoviaConnectionError, CoviaError, CoviaTimeoutError, CredentialsHTTP, DataAsset, Grid, GridError, Job, JobFailedError, JobManager, JobNotFoundError, JobStatus, KeyPairAuth, NoAuth, NotFoundError, Operation, OperationManager, RunStatus, SecretManager, UCANManager, Venue, WorkspaceManager, createSSEEvent, decodePublicKey, didFromPublicKey, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getParsedAssetId, hexToPrivateKey, isJobComplete, isJobFinished, isJobPaused, logger, parseSSEStream, privateKeyToHex };
2568
+ export { Agent, AgentManager, AgentStatus, Asset, AssetManager, AssetNotFoundError, Auth, BasicAuth, BearerAuth, ChatSession, CoviaConnectionError, CoviaError, CoviaTimeoutError, CredentialsHTTP, DataAsset, Ed25519Auth, Grid, GridError, Job, JobFailedError, JobManager, JobNotFoundError, JobStatus, KeyPairAuth, Namespace, NoAuth, NotFoundError, Operation, OperationManager, RunStatus, SecretManager, UCANManager, Venue, WorkspaceManager, assetHash, createSSEEvent, decodePublicKey, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getParsedAssetId, hexToPrivateKey, isDid, isJobComplete, isJobFinished, isJobPaused, logger, parseDidUrl, parseSSEStream, privateKeyToHex, venueBaseUrlCandidates };