@isoloop/bus 0.1.0-next.1 → 0.1.0-next.3

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.
@@ -48,6 +48,16 @@ function matchTopic(grant, topic) {
48
48
  function matchAny(patterns, topic) {
49
49
  return patterns.some((p) => matchTopic(p, topic));
50
50
  }
51
+ /** Every {@link RequestVia}, for guards. @experimental */
52
+ const REQUEST_VIA = Object.freeze([
53
+ "mcp",
54
+ "webmcp",
55
+ "builder"
56
+ ]);
57
+ /** True for a known {@link RequestVia}. @experimental */
58
+ function isRequestVia(x) {
59
+ return typeof x === "string" && REQUEST_VIA.includes(x);
60
+ }
51
61
  const isIsolateToBus = envelopeGuard({
52
62
  publish: true,
53
63
  subscribe: true,
@@ -56,14 +66,24 @@ const isIsolateToBus = envelopeGuard({
56
66
  request: true,
57
67
  reply: true
58
68
  });
59
- const isHostToBus = envelopeGuard({
69
+ /** Longest preview of a record's value, in characters (ADR 0020, decision 3). */
70
+ const PREVIEW_CHARS = 2048;
71
+ const HOST_TO_BUS = {
60
72
  boot: true,
61
73
  attach: true,
62
74
  detach: true,
63
75
  publish: true,
76
+ request: true,
64
77
  flush: true,
65
- drop: true
66
- });
78
+ drop: true,
79
+ tap: true,
80
+ read: true
81
+ };
82
+ /** The message types a tap's port carries to the bus. @experimental */
83
+ const TAP_TO_BUS = { close: true };
84
+ const isHostToBus = envelopeGuard(HOST_TO_BUS);
85
+ /** A well-formed message from the host on a tap's port. @experimental */
86
+ const isTapToBus = envelopeGuard(TAP_TO_BUS);
67
87
  /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
68
88
  function systemSchema(check) {
69
89
  return { "~standard": {
@@ -958,6 +978,8 @@ var Broker = class {
958
978
  #sources = /* @__PURE__ */ new Set();
959
979
  #followReports = /* @__PURE__ */ new Map();
960
980
  #dropped = 0;
981
+ /** Inspection taps, with the topic patterns each one matches. */
982
+ #taps = /* @__PURE__ */ new Map();
961
983
  constructor(opts) {
962
984
  this.#engine = opts.engine;
963
985
  this.#now = opts.now ?? Date.now;
@@ -1037,7 +1059,9 @@ var Broker = class {
1037
1059
  topics: [...this.#topics].map(([topic, t]) => ({
1038
1060
  topic,
1039
1061
  records: t.records,
1040
- bytes: t.bytes
1062
+ bytes: t.bytes,
1063
+ head: this.#engine.head(topic),
1064
+ retained: this.#engine.retained(topic)
1041
1065
  })),
1042
1066
  subscriptions,
1043
1067
  rejected: { ...this.#rejected }
@@ -1261,6 +1285,46 @@ var Broker = class {
1261
1285
  publish(from, topic, key, value, id) {
1262
1286
  return new Promise((resolve) => this.#publish(from, topic, key, value, void 0, resolve, id));
1263
1287
  }
1288
+ /**
1289
+ * A request from the host (`kernel.request`, ADR 0018, decision 4): like
1290
+ * an isolate's `bus.request`, with `req: { from: 'host', id, via }` on the
1291
+ * record. `answer` gets one result: a failure to append, or the first
1292
+ * valid reply (or `reply_invalid`). Nothing, if no reply comes before the
1293
+ * caller's timeout; the request is forgotten after `timeoutMs`.
1294
+ */
1295
+ request(topic, key, value, opts, answer, appendId) {
1296
+ let answered = false;
1297
+ const once = (r) => {
1298
+ if (answered) return;
1299
+ answered = true;
1300
+ answer(r);
1301
+ };
1302
+ const req = {
1303
+ from: {
1304
+ isolateId: HOST_PRODUCER,
1305
+ grants: {
1306
+ publish: [],
1307
+ subscribe: []
1308
+ },
1309
+ port: {
1310
+ post: (m) => {
1311
+ if (m.t === "result") once(m.p);
1312
+ },
1313
+ onMessage: () => {},
1314
+ close: () => {}
1315
+ },
1316
+ subs: /* @__PURE__ */ new Map(),
1317
+ reset: void 0,
1318
+ host: true
1319
+ },
1320
+ id: opts.id,
1321
+ timeoutMs: opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_REQUEST_TIMEOUT_MS,
1322
+ ...opts.via === void 0 ? {} : { via: opts.via }
1323
+ };
1324
+ this.#publish({ kind: "host" }, topic, key, value, req, (r) => {
1325
+ if (!r.ok) once(r);
1326
+ }, appendId);
1327
+ }
1264
1328
  #receive(conn, msg) {
1265
1329
  if (!isIsolateToBus(msg) || msg.t !== "commits" && !hasTopic(msg.p)) {
1266
1330
  this.#dropped++;
@@ -1359,7 +1423,7 @@ var Broker = class {
1359
1423
  value: null
1360
1424
  };
1361
1425
  for (const e of offsets) {
1362
- const r = typeof e === "object" && e !== null && "topic" in e && typeof e.topic === "string" ? this.#commit(conn, e.topic, "offset" in e ? e.offset : void 0, "seq" in e ? e.seq : void 0) : fail("invalid", "each commit needs a topic, an offset and a seq");
1426
+ const r = typeof e === "object" && e !== null && "topic" in e && typeof e.topic === "string" ? this.#commit(conn, e.topic, "offset" in e ? e.offset : void 0, "seq" in e ? e.seq : void 0, "partial" in e ? e.partial : void 0) : fail("invalid", "each commit needs a topic, an offset and a seq");
1363
1427
  if (!r.ok && first.ok) first = r;
1364
1428
  }
1365
1429
  reply(first);
@@ -1464,13 +1528,17 @@ var Broker = class {
1464
1528
  ...rec,
1465
1529
  key: p.key
1466
1530
  };
1467
- if (p.req) rec = {
1468
- ...rec,
1469
- req: {
1470
- from: p.req.from.isolateId,
1471
- id: p.req.id
1472
- }
1473
- };
1531
+ if (p.req) {
1532
+ const { via } = p.req;
1533
+ rec = {
1534
+ ...rec,
1535
+ req: {
1536
+ from: p.req.from.isolateId,
1537
+ id: p.req.id,
1538
+ ...via === void 0 ? {} : { via }
1539
+ }
1540
+ };
1541
+ }
1474
1542
  const offset = this.#engine.append(name, rec, p.id);
1475
1543
  topic.records++;
1476
1544
  topic.bytes += p.bytes;
@@ -1486,6 +1554,66 @@ var Broker = class {
1486
1554
  ...rec,
1487
1555
  offset
1488
1556
  });
1557
+ if (this.#taps.size > 0) this.#toTaps(name, {
1558
+ ...rec,
1559
+ offset
1560
+ }, p.bytes);
1561
+ }
1562
+ #toTaps(name, rec, bytes) {
1563
+ for (const [sink, patterns] of this.#taps) {
1564
+ if (!matchAny(patterns, name)) continue;
1565
+ try {
1566
+ sink(name, rec, bytes);
1567
+ } catch (e) {
1568
+ console.error("[isoloop] bus: a tap threw", e);
1569
+ }
1570
+ }
1571
+ }
1572
+ /**
1573
+ * The inspection feed's tap (ADR 0020, decision 3): `sink` gets every
1574
+ * record appended to a topic matching one of `patterns` from now on,
1575
+ * through the publish pipeline. Seeds copying into a topic before it opens
1576
+ * aren't tapped. Returns the function that ends it.
1577
+ */
1578
+ tap(patterns, sink) {
1579
+ this.#taps.set(sink, [...patterns]);
1580
+ return () => {
1581
+ this.#taps.delete(sink);
1582
+ };
1583
+ }
1584
+ /**
1585
+ * The last `last` retained records of `topic`, oldest first (ADR 0020,
1586
+ * decision 3), paging evicted records in from disk when needed. Seed
1587
+ * sources the contracts don't list are unknown here, as to isolates.
1588
+ */
1589
+ async read(name, last) {
1590
+ if (!this.#topics.has(name)) return {
1591
+ ok: false,
1592
+ error: {
1593
+ code: "unknown_topic",
1594
+ message: `unknown topic ${name}`
1595
+ }
1596
+ };
1597
+ if (!Number.isInteger(last) || last < 1) return {
1598
+ ok: false,
1599
+ error: {
1600
+ code: "invalid",
1601
+ message: "last must be a positive whole number"
1602
+ }
1603
+ };
1604
+ const tail = this.#engine.tail(name);
1605
+ const head = this.#engine.head(name);
1606
+ let span = last;
1607
+ for (;;) {
1608
+ const from = Math.max(tail, head - span);
1609
+ if (!this.#engine.readable(name, from)) await this.#engine.page(name, from);
1610
+ const got = this.#engine.read(name, from, Number.MAX_SAFE_INTEGER);
1611
+ if (got.length >= last || from <= this.#engine.tail(name)) return {
1612
+ ok: true,
1613
+ records: got.slice(-last)
1614
+ };
1615
+ span *= 2;
1616
+ }
1489
1617
  }
1490
1618
  /**
1491
1619
  * Turns a schema result into the value to store, or the error to send. A
@@ -1551,7 +1679,7 @@ var Broker = class {
1551
1679
  if (req.done) return settle(fail("already_replied", `request ${name}@${offset} has an answer`));
1552
1680
  req.done = true;
1553
1681
  const checked = this.#check(name, r);
1554
- const callerAlive = this.#conns.get(req.caller.isolateId) === req.caller;
1682
+ const callerAlive = req.caller.host === true || this.#conns.get(req.caller.isolateId) === req.caller;
1555
1683
  if (!checked.ok) {
1556
1684
  settle(checked);
1557
1685
  if (callerAlive) {
@@ -1690,17 +1818,21 @@ var Broker = class {
1690
1818
  * A commit covers the records delivered up to `offset`. In a group it also
1691
1819
  * needs their delivery's `seq` at or below `seq`: a record redelivered to
1692
1820
  * this member after the deliveries the commit settled has a higher one,
1693
- * whatever its offset (ADR 0016, point 12). An own subscription's
1694
- * deliveries are in order, so the offset alone decides there.
1821
+ * whatever its offset (ADR 0016, point 12). `partial` also covers the
1822
+ * first records of delivery `seq + 1`, the ones settled before a member
1823
+ * stops partway through it (point 17). An own subscription's deliveries
1824
+ * are in order, so the offset alone decides there.
1695
1825
  */
1696
- #commit(conn, name, offset, seq) {
1826
+ #commit(conn, name, offset, seq, partial) {
1697
1827
  const sub = conn.subs.get(name);
1698
1828
  if (!sub) return fail("forbidden", `not subscribed to ${name}`);
1699
1829
  if (!isOffset(offset)) return fail("invalid", "offset must be a non-negative integer");
1700
1830
  if (!isSeq(seq)) return fail("invalid", "seq must be a non-negative integer");
1831
+ if (partial !== void 0 && !isSeq(partial)) return fail("invalid", "partial must be a non-negative integer");
1832
+ const part = isSeq(partial) ? partial : 0;
1701
1833
  if (offset >= this.#engine.head(name)) return fail("invalid", `offset ${offset} is not in ${name} yet`);
1702
1834
  const g = sub.group;
1703
- const covers = (d) => d.offset <= offset && (!g || d.seq <= seq);
1835
+ const covers = (d) => g ? d.offset <= offset && d.seq <= seq || d.seq === seq + 1 && d.i < part : d.offset <= offset;
1704
1836
  const before = sub.unacked.length;
1705
1837
  if (g) sub.unacked = sub.unacked.filter((d) => !covers(d));
1706
1838
  else while (sub.unacked[0] && covers(sub.unacked[0])) sub.unacked.shift();
@@ -1772,10 +1904,11 @@ var Broker = class {
1772
1904
  /** Sends one `deliver`, numbered with the subscription's next `seq`, and returns it. */
1773
1905
  #deliver(sub, records, gap) {
1774
1906
  const seq = ++sub.seq;
1775
- for (const r of records) {
1907
+ for (const [i, r] of records.entries()) {
1776
1908
  sub.unacked.push({
1777
1909
  offset: r.offset,
1778
- seq
1910
+ seq,
1911
+ i
1779
1912
  });
1780
1913
  if (r.req) this.#requests.get(reqKey(sub.topic, r.offset))?.recipients.add(sub.conn.isolateId);
1781
1914
  }
@@ -1842,7 +1975,10 @@ var Broker = class {
1842
1975
  batches.delete(m);
1843
1976
  if (!b || b.records.length === 0) return;
1844
1977
  const seq = this.#deliver(m, b.records);
1845
- for (const e of b.entries) e.seq = seq;
1978
+ for (const { entry, i } of b.entries) {
1979
+ entry.seq = seq;
1980
+ entry.i = i;
1981
+ }
1846
1982
  };
1847
1983
  /** Credit left once the records batched for it go out. */
1848
1984
  const room = (m) => m ? m.credit - (batches.get(m)?.records.length ?? 0) : 0;
@@ -1851,8 +1987,11 @@ var Broker = class {
1851
1987
  records: [],
1852
1988
  entries: []
1853
1989
  };
1990
+ if (entry) b.entries.push({
1991
+ entry,
1992
+ i: b.records.length
1993
+ });
1854
1994
  b.records.push(rec);
1855
- if (entry) b.entries.push(entry);
1856
1995
  batches.set(m, b);
1857
1996
  if (rec.key === void 0) g.rr++;
1858
1997
  if (b.records.length >= this.#batch) flush(m);
@@ -1908,7 +2047,8 @@ var Broker = class {
1908
2047
  const entry = {
1909
2048
  offset: rec.offset,
1910
2049
  member: m,
1911
- seq: 0
2050
+ seq: 0,
2051
+ i: 0
1912
2052
  };
1913
2053
  g.unacked.push(entry);
1914
2054
  give(m, rec, entry);
@@ -2039,7 +2179,22 @@ function scanFrames(bytes) {
2039
2179
  };
2040
2180
  }
2041
2181
  const isList = (x) => Array.isArray(x);
2042
- const isReq = (x) => typeof x === "object" && x !== null && typeof Reflect.get(x, "from") === "string" && typeof Reflect.get(x, "id") === "string";
2182
+ /** A stored `req`, rebuilt from its known fields; a `via` this version doesn't know is left out. */
2183
+ function reqOf(x) {
2184
+ if (typeof x !== "object" || x === null) return void 0;
2185
+ const from = Reflect.get(x, "from");
2186
+ const id = Reflect.get(x, "id");
2187
+ if (typeof from !== "string" || typeof id !== "string") return void 0;
2188
+ const via = Reflect.get(x, "via");
2189
+ return isRequestVia(via) ? {
2190
+ from,
2191
+ id,
2192
+ via
2193
+ } : {
2194
+ from,
2195
+ id
2196
+ };
2197
+ }
2043
2198
  /** Decodes one frame written by `encodeFrame`. */
2044
2199
  function decodeFrame(frame) {
2045
2200
  const offset = frameOffset(frame);
@@ -2053,7 +2208,8 @@ function decodeFrame(frame) {
2053
2208
  producer
2054
2209
  };
2055
2210
  if (typeof key === "string") rec.key = key;
2056
- if (isReq(req)) rec.req = req;
2211
+ const r = reqOf(req);
2212
+ if (r) rec.req = r;
2057
2213
  if (typeof epoch === "number") rec.epoch = epoch;
2058
2214
  if (typeof seq === "number") rec.seq = seq;
2059
2215
  return rec;
@@ -2352,6 +2508,9 @@ var TsEngine = class {
2352
2508
  tail(topic) {
2353
2509
  return this.#topic(topic).tail;
2354
2510
  }
2511
+ retained(topic) {
2512
+ return this.#topic(topic).live;
2513
+ }
2355
2514
  commit(topic, consumer, offset) {
2356
2515
  const t = this.#topic(topic);
2357
2516
  t.commits.set(consumer, offset);
@@ -3270,6 +3429,177 @@ var OpfsStorage = class {
3270
3429
  this.#topics.clear();
3271
3430
  }
3272
3431
  };
3432
+ // src/preview.ts
3433
+ /** Typed arrays and `ArrayBuffer`s show their length, not their contents. */
3434
+ const binary = (v) => {
3435
+ if (v instanceof ArrayBuffer) return `ArrayBuffer(${v.byteLength})`;
3436
+ if (ArrayBuffer.isView(v)) {
3437
+ const len = "length" in v && typeof v.length === "number" ? v.length : v.byteLength;
3438
+ return `${v.constructor.name}(${len})`;
3439
+ }
3440
+ };
3441
+ /** `value` as text, at most `max` characters. `truncated` when it was longer. */
3442
+ function previewText(value, max = PREVIEW_CHARS) {
3443
+ let out = "";
3444
+ let full = false;
3445
+ const seen = /* @__PURE__ */ new Set();
3446
+ const put = (s) => {
3447
+ if (full) return;
3448
+ if (out.length + s.length > max) {
3449
+ out += s.slice(0, max - out.length);
3450
+ full = true;
3451
+ return;
3452
+ }
3453
+ out += s;
3454
+ };
3455
+ const walk = (v) => {
3456
+ if (full) return;
3457
+ switch (typeof v) {
3458
+ case "string":
3459
+ put(JSON.stringify(v.length > max ? v.slice(0, max) : v));
3460
+ if (v.length > max) full = true;
3461
+ return;
3462
+ case "number":
3463
+ put(String(v));
3464
+ return;
3465
+ case "bigint":
3466
+ put(`${v}n`);
3467
+ return;
3468
+ case "boolean":
3469
+ put(String(v));
3470
+ return;
3471
+ case "undefined":
3472
+ put("undefined");
3473
+ return;
3474
+ case "symbol":
3475
+ case "function":
3476
+ put("null");
3477
+ return;
3478
+ }
3479
+ if (v === null) return put("null");
3480
+ if (seen.has(v)) return put("[Circular]");
3481
+ const bin = binary(v);
3482
+ if (bin !== void 0) return put(bin);
3483
+ if (v instanceof Date) return put(Number.isNaN(v.getTime()) ? "Invalid Date" : v.toISOString());
3484
+ if (v instanceof RegExp) return put(String(v));
3485
+ seen.add(v);
3486
+ if (Array.isArray(v)) {
3487
+ put("[");
3488
+ v.forEach((x, i) => {
3489
+ if (i > 0) put(",");
3490
+ walk(x);
3491
+ });
3492
+ put("]");
3493
+ } else if (v instanceof Map) {
3494
+ put("Map{");
3495
+ let i = 0;
3496
+ for (const [k, x] of v) {
3497
+ if (full) break;
3498
+ if (i++ > 0) put(",");
3499
+ walk(k);
3500
+ put("=>");
3501
+ walk(x);
3502
+ }
3503
+ put("}");
3504
+ } else if (v instanceof Set) {
3505
+ put("Set[");
3506
+ let i = 0;
3507
+ for (const x of v) {
3508
+ if (full) break;
3509
+ if (i++ > 0) put(",");
3510
+ walk(x);
3511
+ }
3512
+ put("]");
3513
+ } else if (v instanceof Error) put(JSON.stringify(`${v.name}: ${v.message}`));
3514
+ else {
3515
+ put("{");
3516
+ let i = 0;
3517
+ for (const k of Object.keys(v)) {
3518
+ if (full) break;
3519
+ if (i++ > 0) put(",");
3520
+ put(JSON.stringify(k));
3521
+ put(":");
3522
+ walk(Reflect.get(v, k));
3523
+ }
3524
+ put("}");
3525
+ }
3526
+ seen.delete(v);
3527
+ };
3528
+ walk(value);
3529
+ return {
3530
+ text: out,
3531
+ truncated: full
3532
+ };
3533
+ }
3534
+ /** A retained record as the inspection feed shows it. */
3535
+ function recordPreview(topic, r, bytes) {
3536
+ const { text, truncated } = previewText(r.value);
3537
+ return {
3538
+ topic,
3539
+ offset: r.offset,
3540
+ ...r.key === void 0 ? {} : { key: r.key },
3541
+ ts: r.ts,
3542
+ producer: r.producer,
3543
+ ...r.req === void 0 ? {} : { req: r.req },
3544
+ bytes: bytes ?? estimateSize(r.value),
3545
+ preview: text,
3546
+ truncated
3547
+ };
3548
+ }
3549
+ // src/tap.ts
3550
+ /** `maxPerSec` as given when it's a positive number, else the default. */
3551
+ const tapRate = (n) => typeof n === "number" && Number.isFinite(n) && n > 0 ? n : 50;
3552
+ /** Starts a tap on `broker`. Returns the function that ends it; `close` on the port ends it too. */
3553
+ function openTap(broker, o) {
3554
+ const max = tapRate(o.maxPerSec);
3555
+ const now = o.now ?? (() => performance.now());
3556
+ const every = o.every ?? ((fn, ms) => {
3557
+ const t = setInterval(fn, ms);
3558
+ return () => clearInterval(t);
3559
+ });
3560
+ let windowAt = now();
3561
+ let sent = 0;
3562
+ let skipped = 0;
3563
+ let open = true;
3564
+ const untap = broker.tap(o.topics, (topic, rec, bytes) => {
3565
+ const t = now();
3566
+ if (t - windowAt >= 1e3) {
3567
+ windowAt = t;
3568
+ sent = 0;
3569
+ }
3570
+ if (sent >= max) {
3571
+ skipped++;
3572
+ return;
3573
+ }
3574
+ sent++;
3575
+ o.port.postMessage({
3576
+ v: 1,
3577
+ t: "record",
3578
+ p: recordPreview(topic, rec, bytes)
3579
+ });
3580
+ });
3581
+ const stopReport = every(() => {
3582
+ if (skipped === 0) return;
3583
+ o.port.postMessage({
3584
+ v: 1,
3585
+ t: "skipped",
3586
+ p: { count: skipped }
3587
+ });
3588
+ skipped = 0;
3589
+ }, 1e3);
3590
+ const end = () => {
3591
+ if (!open) return;
3592
+ open = false;
3593
+ untap();
3594
+ stopReport();
3595
+ o.port.close();
3596
+ };
3597
+ o.port.addEventListener("message", (e) => {
3598
+ if (isTapToBus(e.data) && e.data.t === "close") end();
3599
+ });
3600
+ o.port.start();
3601
+ return end;
3602
+ }
3273
3603
  // src/server.ts
3274
3604
  /** Storage use at or past this share of the quota counts as full (M2b task 14). */
3275
3605
  const FULL = 1;
@@ -3431,6 +3761,39 @@ function serve(scope, opts = {}) {
3431
3761
  });
3432
3762
  return;
3433
3763
  }
3764
+ case "request": {
3765
+ const { id } = msg;
3766
+ if (id === void 0) return;
3767
+ const answer = (p) => post({
3768
+ v: 1,
3769
+ t: "result",
3770
+ re: id,
3771
+ p
3772
+ });
3773
+ const key = msg.p.key;
3774
+ const via = msg.p.via;
3775
+ const timeoutMs = msg.p.timeoutMs;
3776
+ if (key !== void 0 && typeof key !== "string") return answer({
3777
+ ok: false,
3778
+ error: {
3779
+ code: "invalid",
3780
+ message: "key must be a string"
3781
+ }
3782
+ });
3783
+ if (via !== void 0 && !isRequestVia(via)) return answer({
3784
+ ok: false,
3785
+ error: {
3786
+ code: "invalid",
3787
+ message: `via must be one of ${REQUEST_VIA.join(", ")}`
3788
+ }
3789
+ });
3790
+ b.request(msg.p.topic, key, msg.p.value, {
3791
+ id,
3792
+ timeoutMs: typeof timeoutMs === "number" ? timeoutMs : 0,
3793
+ ...via === void 0 ? {} : { via }
3794
+ }, answer, publishId(msg.p));
3795
+ return;
3796
+ }
3434
3797
  case "flush": {
3435
3798
  const { id } = msg;
3436
3799
  b.flush().then(() => id !== void 0 && post({
@@ -3485,6 +3848,47 @@ function serve(scope, opts = {}) {
3485
3848
  }));
3486
3849
  return;
3487
3850
  }
3851
+ case "tap":
3852
+ openTap(b, {
3853
+ topics: Array.isArray(msg.p.topics) ? msg.p.topics.filter((x) => typeof x === "string") : [],
3854
+ ...msg.p.maxPerSec === void 0 ? {} : { maxPerSec: msg.p.maxPerSec },
3855
+ port: msg.p.port,
3856
+ now
3857
+ });
3858
+ return;
3859
+ case "read": {
3860
+ const { id } = msg;
3861
+ if (id === void 0) return;
3862
+ const answer = (p) => post({
3863
+ v: 1,
3864
+ t: "result",
3865
+ re: id,
3866
+ p
3867
+ });
3868
+ const topic = msg.p.topic;
3869
+ const last = msg.p.last;
3870
+ if (typeof last !== "number" || !Number.isInteger(last) || last < 1) return answer({
3871
+ ok: false,
3872
+ error: {
3873
+ code: "invalid",
3874
+ message: "last must be a positive whole number"
3875
+ }
3876
+ });
3877
+ b.read(topic, Math.min(last, 100)).then((r) => answer(r.ok ? {
3878
+ ok: true,
3879
+ value: r.records.map((rec) => recordPreview(topic, rec))
3880
+ } : {
3881
+ ok: false,
3882
+ error: r.error
3883
+ }), (e) => answer({
3884
+ ok: false,
3885
+ error: {
3886
+ code: "bus_unavailable",
3887
+ message: `read ${topic}: ${String(e)}`
3888
+ }
3889
+ }));
3890
+ return;
3891
+ }
3488
3892
  default: return msg;
3489
3893
  }
3490
3894
  };
@@ -3508,18 +3912,21 @@ function serve(scope, opts = {}) {
3508
3912
  ports.delete(msg.p.isolateId);
3509
3913
  break;
3510
3914
  case "publish":
3915
+ case "request":
3511
3916
  if (earlyPublishes >= limit) {
3512
3917
  if (msg.id !== void 0) post({
3513
3918
  v: 1,
3514
3919
  t: "result",
3515
3920
  re: msg.id,
3516
- p: unavailable("kernel.publish")
3921
+ p: unavailable(`kernel.${msg.t}`)
3517
3922
  });
3518
3923
  return;
3519
3924
  }
3520
3925
  earlyPublishes++;
3521
3926
  break;
3522
3927
  case "drop":
3928
+ case "tap":
3929
+ case "read":
3523
3930
  early.push(msg);
3524
3931
  return;
3525
3932
  case "flush":
@@ -3579,7 +3986,9 @@ function serve(scope, opts = {}) {
3579
3986
  topics: stats.topics.map((x) => ({
3580
3987
  topic: x.topic,
3581
3988
  recordsPerSec: (x.records - (before.get(x.topic)?.records ?? 0)) / secs,
3582
- bytesPerSec: (x.bytes - (before.get(x.topic)?.bytes ?? 0)) / secs
3989
+ bytesPerSec: (x.bytes - (before.get(x.topic)?.bytes ?? 0)) / secs,
3990
+ head: x.head,
3991
+ retained: x.retained
3583
3992
  })),
3584
3993
  subscriptions: stats.subscriptions,
3585
3994
  rejected: stats.rejected,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as StandardSchemaV1, a as InputOf, c as ReplyOutputOf, d as contracts, f as isContracts, g as unchecked, h as topicConfig, i as DEFAULT_MAX_RECORD_BYTES, l as Retention, m as topic, n as Contracts, o as OutputOf, p as isUnchecked, r as ContractsError, s as ReplyInputOf, t as AnyTopicDef, u as TopicDef, v as toIssues } from "./topic-BQbes-gX.js";
2
- import { BusRecord, BusToIsolate, CallResult, ErrorCode, Grants, SeedEvent, TopicConfig } from "@isoloop/protocol";
1
+ import { _ as unchecked, a as InputOf, c as ReplyOutputOf, d as TopicDef, f as contracts, g as topicConfig, h as topic, i as DEFAULT_MAX_RECORD_BYTES, l as Retention, m as isUnchecked, n as Contracts, o as OutputOf, p as isContracts, r as ContractsError, s as ReplyInputOf, t as AnyTopicDef, u as ToolSpec, v as StandardSchemaV1, y as toIssues } from "./topic-BgqMD0WA.js";
2
+ import { BusRecord, BusToIsolate, CallError, CallResult, ErrorCode, Grants, JSON_SCHEMA_TARGET, JsonSchema, JsonSchemaPair, JsonSchemaResult, NotExportableReason, RequestVia, SeedEvent, StandardJSONSchemaV1, TopicConfig, TopicJsonSchemas, TopicJsonSchemasResult, hasJsonSchema, jsonSchemaOf, topicJsonSchemas } from "@isoloop/protocol";
3
3
  /** A record before the engine gives it an offset. */
4
4
  type NewRecord = Omit<BusRecord, "offset">;
5
5
  /** A publish's instance and counter, for deduplicating re-sends (ADR 0007, step 5). */
@@ -38,6 +38,11 @@ interface LogEngine {
38
38
  head(topic: string): number;
39
39
  /** Oldest retained offset; equals `head` when nothing is retained. */
40
40
  tail(topic: string): number;
41
+ /**
42
+ * How many records are retained in `[tail, head)`: what `read` from the
43
+ * tail would return, counting records evicted to disk (ADR 0020, decision 2).
44
+ */
45
+ retained(topic: string): number;
41
46
  /** Stores a consumer's committed offset. Kept even when the records it names are dropped. */
42
47
  commit(topic: string, consumer: string, offset: number): void;
43
48
  committed(topic: string, consumer: string): number | undefined;
@@ -186,6 +191,7 @@ export declare class TsEngine implements LogEngine {
186
191
  /** Lowest offset held in memory; below it, records are on disk only. For tests and metrics. */
187
192
  resident(topic: string): number;
188
193
  tail(topic: string): number;
194
+ retained(topic: string): number;
189
195
  commit(topic: string, consumer: string, offset: number): void;
190
196
  committed(topic: string, consumer: string): number | undefined;
191
197
  durable(topic: string): boolean;
@@ -247,6 +253,11 @@ export type BrokerOptions = {
247
253
  /** Seeding news for the host: rejected source records and ended seeds (ADR 0003, decision 18). */
248
254
  onSeed?: (e: SeedEvent) => void;
249
255
  };
256
+ /**
257
+ * Gets each record appended to a tapped topic (ADR 0020, decision 3), with
258
+ * its estimated size. A tap is not a consumer: it has no cursor or credit.
259
+ */
260
+ export type TapSink = (topic: string, rec: BusRecord, bytes: number) => void;
250
261
  /** Who is publishing: an isolate (grants apply), the host (`kernel.publish`), or the kernel itself (system topics). */
251
262
  export type Publisher = {
252
263
  kind: "isolate";
@@ -258,10 +269,13 @@ export type Publisher = {
258
269
  };
259
270
  /** Cumulative counters for metrics (design §6.3); the bus worker turns them into rates. */
260
271
  export type BrokerStats = {
272
+ /** `head` and `retained` are the engine's, at the time of the sample (ADR 0020, decision 2). */
261
273
  topics: {
262
274
  topic: string;
263
275
  records: number;
264
276
  bytes: number;
277
+ head: number;
278
+ retained: number;
265
279
  }[];
266
280
  /** `lag` is `head − cursor`: records not yet delivered. */
267
281
  subscriptions: {
@@ -347,6 +361,37 @@ export declare class Broker {
347
361
  * The host can't publish system topics; the kernel can only publish them.
348
362
  */
349
363
  publish(from: Publisher, topic: string, key: string | undefined, value: unknown, id?: AppendId): Promise<CallResult>;
364
+ /**
365
+ * A request from the host (`kernel.request`, ADR 0018, decision 4): like
366
+ * an isolate's `bus.request`, with `req: { from: 'host', id, via }` on the
367
+ * record. `answer` gets one result: a failure to append, or the first
368
+ * valid reply (or `reply_invalid`). Nothing, if no reply comes before the
369
+ * caller's timeout; the request is forgotten after `timeoutMs`.
370
+ */
371
+ request(topic: string, key: string | undefined, value: unknown, opts: {
372
+ id: string;
373
+ timeoutMs: number;
374
+ via?: RequestVia;
375
+ }, answer: (r: CallResult) => void, appendId?: AppendId): void;
376
+ /**
377
+ * The inspection feed's tap (ADR 0020, decision 3): `sink` gets every
378
+ * record appended to a topic matching one of `patterns` from now on,
379
+ * through the publish pipeline. Seeds copying into a topic before it opens
380
+ * aren't tapped. Returns the function that ends it.
381
+ */
382
+ tap(patterns: readonly string[], sink: TapSink): () => void;
383
+ /**
384
+ * The last `last` retained records of `topic`, oldest first (ADR 0020,
385
+ * decision 3), paging evicted records in from disk when needed. Seed
386
+ * sources the contracts don't list are unknown here, as to isolates.
387
+ */
388
+ read(name: string, last: number): Promise<{
389
+ ok: true;
390
+ records: BusRecord[];
391
+ } | {
392
+ ok: false;
393
+ error: CallError;
394
+ }>;
350
395
  }
351
396
  /**
352
397
  * A rough structured size of a value in bytes, for `maxRecordBytes` (design
@@ -355,4 +400,4 @@ export declare class Broker {
355
400
  * exact: it only has to tell a 1 KiB record from a 1 MiB one.
356
401
  */
357
402
  export declare function estimateSize(value: unknown, limit?: number): number;
358
- export { AnyTopicDef, Contracts, ContractsError, DEFAULT_MAX_RECORD_BYTES, type EngineOptions, InputOf, type LogEngine, type LogStorage, type NewRecord, OutputOf, ReplyInputOf, ReplyOutputOf, type Retention, StandardSchemaV1, type StoredState, TopicDef, type TsEngineOptions, contracts, isContracts, isUnchecked, toIssues, topic, topicConfig, unchecked };
403
+ export { AnyTopicDef, Contracts, ContractsError, DEFAULT_MAX_RECORD_BYTES, type EngineOptions, InputOf, JSON_SCHEMA_TARGET, type JsonSchema, type JsonSchemaPair, type JsonSchemaResult, type LogEngine, type LogStorage, type NewRecord, type NotExportableReason, OutputOf, ReplyInputOf, ReplyOutputOf, type Retention, type StandardJSONSchemaV1, StandardSchemaV1, type StoredState, type ToolSpec, TopicDef, type TopicJsonSchemas, type TopicJsonSchemasResult, type TsEngineOptions, contracts, hasJsonSchema, isContracts, isUnchecked, jsonSchemaOf, toIssues, topic, topicConfig, topicJsonSchemas, unchecked };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as toIssues } from "./standard-schema-DnJtEmJw.js";
2
- import { SYSTEM_TOPICS, isIsolateToBus, isSystemTopic, matchAny, topicConfigOf } from "@isoloop/protocol";
2
+ import { JSON_SCHEMA_TARGET, SYSTEM_TOPICS, UNCHECKED_VENDOR, hasJsonSchema, isIsolateToBus, isRequestVia, isSystemTopic, jsonSchemaOf, matchAny, topicConfigOf, topicJsonSchemas } from "@isoloop/protocol";
3
3
  import { CodecError, decode, encode } from "@isoloop/codec";
4
4
  // src/topic.ts
5
5
  /** Default `maxRecordBytes`: 256 KiB (design §6.1). */
@@ -11,7 +11,6 @@ function topic(name, def) {
11
11
  name
12
12
  });
13
13
  }
14
- const UNCHECKED_VENDOR = "isoloop/unchecked";
15
14
  /**
16
15
  * A Standard Schema that accepts any value unchanged and only carries the type
17
16
  * (ADR 0003, decision 2). Tools list topics that use it.
@@ -47,6 +46,14 @@ const RETENTION_KINDS = /* @__PURE__ */ new Set([
47
46
  const isRecord = (x) => typeof x === "object" && x !== null;
48
47
  const isSchema = (x) => isRecord(x) && isRecord(x["~standard"]) && typeof x["~standard"]["validate"] === "function";
49
48
  const positiveInt = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
49
+ const optionalBoolean = (x) => x === void 0 || typeof x === "boolean";
50
+ function toolProblemOf(tool) {
51
+ if (!isRecord(tool)) return "has a `tool` that is not an object";
52
+ if (typeof tool["description"] !== "string" || tool["description"] === "") return "has a `tool` without a `description`";
53
+ if (typeof tool["readOnly"] !== "boolean") return "has a `tool` without a boolean `readOnly`";
54
+ if (tool["title"] !== void 0 && typeof tool["title"] !== "string") return "has a `tool` whose `title` is not a string";
55
+ if (!optionalBoolean(tool["consequential"]) || !optionalBoolean(tool["untrustedContent"])) return "has a `tool` whose hints are not booleans";
56
+ }
50
57
  function problemOf(t) {
51
58
  if (typeof t.name !== "string" || t.name === "") return "has no name";
52
59
  if (!isSchema(t.schema)) return "has no Standard Schema";
@@ -57,6 +64,10 @@ function problemOf(t) {
57
64
  if (r.kind === "time" && !positiveInt(r.ms)) return "needs a positive integer `ms`";
58
65
  if (t.maxRecordBytes !== void 0 && !positiveInt(t.maxRecordBytes)) return "needs a positive integer `maxRecordBytes`";
59
66
  if (t.durability !== void 0 && t.durability !== "memory" && t.durability !== "persistent") return "has a durability other than 'memory' or 'persistent'";
67
+ if (t.tool !== void 0) {
68
+ const problem = toolProblemOf(t.tool);
69
+ if (problem) return problem;
70
+ }
60
71
  if (t.seed !== void 0) {
61
72
  const s = t.seed;
62
73
  if (!isRecord(s) || !isRecord(s.from) || typeof s.from.name !== "string") return "has a seed without a `from` topic";
@@ -207,7 +218,22 @@ function frameOffset(frame) {
207
218
  return new DataView(frame.buffer, frame.byteOffset).getFloat64(8, true);
208
219
  }
209
220
  const isList = (x) => Array.isArray(x);
210
- const isReq = (x) => typeof x === "object" && x !== null && typeof Reflect.get(x, "from") === "string" && typeof Reflect.get(x, "id") === "string";
221
+ /** A stored `req`, rebuilt from its known fields; a `via` this version doesn't know is left out. */
222
+ function reqOf(x) {
223
+ if (typeof x !== "object" || x === null) return void 0;
224
+ const from = Reflect.get(x, "from");
225
+ const id = Reflect.get(x, "id");
226
+ if (typeof from !== "string" || typeof id !== "string") return void 0;
227
+ const via = Reflect.get(x, "via");
228
+ return isRequestVia(via) ? {
229
+ from,
230
+ id,
231
+ via
232
+ } : {
233
+ from,
234
+ id
235
+ };
236
+ }
211
237
  /** Decodes one frame written by `encodeFrame`. */
212
238
  function decodeFrame(frame) {
213
239
  const offset = frameOffset(frame);
@@ -221,7 +247,8 @@ function decodeFrame(frame) {
221
247
  producer
222
248
  };
223
249
  if (typeof key === "string") rec.key = key;
224
- if (isReq(req)) rec.req = req;
250
+ const r = reqOf(req);
251
+ if (r) rec.req = r;
225
252
  if (typeof epoch === "number") rec.epoch = epoch;
226
253
  if (typeof seq === "number") rec.seq = seq;
227
254
  return rec;
@@ -520,6 +547,9 @@ var TsEngine = class {
520
547
  tail(topic) {
521
548
  return this.#topic(topic).tail;
522
549
  }
550
+ retained(topic) {
551
+ return this.#topic(topic).live;
552
+ }
523
553
  commit(topic, consumer, offset) {
524
554
  const t = this.#topic(topic);
525
555
  t.commits.set(consumer, offset);
@@ -947,6 +977,8 @@ var Broker = class {
947
977
  #sources = /* @__PURE__ */ new Set();
948
978
  #followReports = /* @__PURE__ */ new Map();
949
979
  #dropped = 0;
980
+ /** Inspection taps, with the topic patterns each one matches. */
981
+ #taps = /* @__PURE__ */ new Map();
950
982
  constructor(opts) {
951
983
  this.#engine = opts.engine;
952
984
  this.#now = opts.now ?? Date.now;
@@ -1026,7 +1058,9 @@ var Broker = class {
1026
1058
  topics: [...this.#topics].map(([topic, t]) => ({
1027
1059
  topic,
1028
1060
  records: t.records,
1029
- bytes: t.bytes
1061
+ bytes: t.bytes,
1062
+ head: this.#engine.head(topic),
1063
+ retained: this.#engine.retained(topic)
1030
1064
  })),
1031
1065
  subscriptions,
1032
1066
  rejected: { ...this.#rejected }
@@ -1250,6 +1284,46 @@ var Broker = class {
1250
1284
  publish(from, topic, key, value, id) {
1251
1285
  return new Promise((resolve) => this.#publish(from, topic, key, value, void 0, resolve, id));
1252
1286
  }
1287
+ /**
1288
+ * A request from the host (`kernel.request`, ADR 0018, decision 4): like
1289
+ * an isolate's `bus.request`, with `req: { from: 'host', id, via }` on the
1290
+ * record. `answer` gets one result: a failure to append, or the first
1291
+ * valid reply (or `reply_invalid`). Nothing, if no reply comes before the
1292
+ * caller's timeout; the request is forgotten after `timeoutMs`.
1293
+ */
1294
+ request(topic, key, value, opts, answer, appendId) {
1295
+ let answered = false;
1296
+ const once = (r) => {
1297
+ if (answered) return;
1298
+ answered = true;
1299
+ answer(r);
1300
+ };
1301
+ const req = {
1302
+ from: {
1303
+ isolateId: HOST_PRODUCER,
1304
+ grants: {
1305
+ publish: [],
1306
+ subscribe: []
1307
+ },
1308
+ port: {
1309
+ post: (m) => {
1310
+ if (m.t === "result") once(m.p);
1311
+ },
1312
+ onMessage: () => {},
1313
+ close: () => {}
1314
+ },
1315
+ subs: /* @__PURE__ */ new Map(),
1316
+ reset: void 0,
1317
+ host: true
1318
+ },
1319
+ id: opts.id,
1320
+ timeoutMs: opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_REQUEST_TIMEOUT_MS,
1321
+ ...opts.via === void 0 ? {} : { via: opts.via }
1322
+ };
1323
+ this.#publish({ kind: "host" }, topic, key, value, req, (r) => {
1324
+ if (!r.ok) once(r);
1325
+ }, appendId);
1326
+ }
1253
1327
  #receive(conn, msg) {
1254
1328
  if (!isIsolateToBus(msg) || msg.t !== "commits" && !hasTopic(msg.p)) {
1255
1329
  this.#dropped++;
@@ -1348,7 +1422,7 @@ var Broker = class {
1348
1422
  value: null
1349
1423
  };
1350
1424
  for (const e of offsets) {
1351
- const r = typeof e === "object" && e !== null && "topic" in e && typeof e.topic === "string" ? this.#commit(conn, e.topic, "offset" in e ? e.offset : void 0, "seq" in e ? e.seq : void 0) : fail("invalid", "each commit needs a topic, an offset and a seq");
1425
+ const r = typeof e === "object" && e !== null && "topic" in e && typeof e.topic === "string" ? this.#commit(conn, e.topic, "offset" in e ? e.offset : void 0, "seq" in e ? e.seq : void 0, "partial" in e ? e.partial : void 0) : fail("invalid", "each commit needs a topic, an offset and a seq");
1352
1426
  if (!r.ok && first.ok) first = r;
1353
1427
  }
1354
1428
  reply(first);
@@ -1453,13 +1527,17 @@ var Broker = class {
1453
1527
  ...rec,
1454
1528
  key: p.key
1455
1529
  };
1456
- if (p.req) rec = {
1457
- ...rec,
1458
- req: {
1459
- from: p.req.from.isolateId,
1460
- id: p.req.id
1461
- }
1462
- };
1530
+ if (p.req) {
1531
+ const { via } = p.req;
1532
+ rec = {
1533
+ ...rec,
1534
+ req: {
1535
+ from: p.req.from.isolateId,
1536
+ id: p.req.id,
1537
+ ...via === void 0 ? {} : { via }
1538
+ }
1539
+ };
1540
+ }
1463
1541
  const offset = this.#engine.append(name, rec, p.id);
1464
1542
  topic.records++;
1465
1543
  topic.bytes += p.bytes;
@@ -1475,6 +1553,66 @@ var Broker = class {
1475
1553
  ...rec,
1476
1554
  offset
1477
1555
  });
1556
+ if (this.#taps.size > 0) this.#toTaps(name, {
1557
+ ...rec,
1558
+ offset
1559
+ }, p.bytes);
1560
+ }
1561
+ #toTaps(name, rec, bytes) {
1562
+ for (const [sink, patterns] of this.#taps) {
1563
+ if (!matchAny(patterns, name)) continue;
1564
+ try {
1565
+ sink(name, rec, bytes);
1566
+ } catch (e) {
1567
+ console.error("[isoloop] bus: a tap threw", e);
1568
+ }
1569
+ }
1570
+ }
1571
+ /**
1572
+ * The inspection feed's tap (ADR 0020, decision 3): `sink` gets every
1573
+ * record appended to a topic matching one of `patterns` from now on,
1574
+ * through the publish pipeline. Seeds copying into a topic before it opens
1575
+ * aren't tapped. Returns the function that ends it.
1576
+ */
1577
+ tap(patterns, sink) {
1578
+ this.#taps.set(sink, [...patterns]);
1579
+ return () => {
1580
+ this.#taps.delete(sink);
1581
+ };
1582
+ }
1583
+ /**
1584
+ * The last `last` retained records of `topic`, oldest first (ADR 0020,
1585
+ * decision 3), paging evicted records in from disk when needed. Seed
1586
+ * sources the contracts don't list are unknown here, as to isolates.
1587
+ */
1588
+ async read(name, last) {
1589
+ if (!this.#topics.has(name)) return {
1590
+ ok: false,
1591
+ error: {
1592
+ code: "unknown_topic",
1593
+ message: `unknown topic ${name}`
1594
+ }
1595
+ };
1596
+ if (!Number.isInteger(last) || last < 1) return {
1597
+ ok: false,
1598
+ error: {
1599
+ code: "invalid",
1600
+ message: "last must be a positive whole number"
1601
+ }
1602
+ };
1603
+ const tail = this.#engine.tail(name);
1604
+ const head = this.#engine.head(name);
1605
+ let span = last;
1606
+ for (;;) {
1607
+ const from = Math.max(tail, head - span);
1608
+ if (!this.#engine.readable(name, from)) await this.#engine.page(name, from);
1609
+ const got = this.#engine.read(name, from, Number.MAX_SAFE_INTEGER);
1610
+ if (got.length >= last || from <= this.#engine.tail(name)) return {
1611
+ ok: true,
1612
+ records: got.slice(-last)
1613
+ };
1614
+ span *= 2;
1615
+ }
1478
1616
  }
1479
1617
  /**
1480
1618
  * Turns a schema result into the value to store, or the error to send. A
@@ -1540,7 +1678,7 @@ var Broker = class {
1540
1678
  if (req.done) return settle(fail("already_replied", `request ${name}@${offset} has an answer`));
1541
1679
  req.done = true;
1542
1680
  const checked = this.#check(name, r);
1543
- const callerAlive = this.#conns.get(req.caller.isolateId) === req.caller;
1681
+ const callerAlive = req.caller.host === true || this.#conns.get(req.caller.isolateId) === req.caller;
1544
1682
  if (!checked.ok) {
1545
1683
  settle(checked);
1546
1684
  if (callerAlive) {
@@ -1679,17 +1817,21 @@ var Broker = class {
1679
1817
  * A commit covers the records delivered up to `offset`. In a group it also
1680
1818
  * needs their delivery's `seq` at or below `seq`: a record redelivered to
1681
1819
  * this member after the deliveries the commit settled has a higher one,
1682
- * whatever its offset (ADR 0016, point 12). An own subscription's
1683
- * deliveries are in order, so the offset alone decides there.
1820
+ * whatever its offset (ADR 0016, point 12). `partial` also covers the
1821
+ * first records of delivery `seq + 1`, the ones settled before a member
1822
+ * stops partway through it (point 17). An own subscription's deliveries
1823
+ * are in order, so the offset alone decides there.
1684
1824
  */
1685
- #commit(conn, name, offset, seq) {
1825
+ #commit(conn, name, offset, seq, partial) {
1686
1826
  const sub = conn.subs.get(name);
1687
1827
  if (!sub) return fail("forbidden", `not subscribed to ${name}`);
1688
1828
  if (!isOffset(offset)) return fail("invalid", "offset must be a non-negative integer");
1689
1829
  if (!isSeq(seq)) return fail("invalid", "seq must be a non-negative integer");
1830
+ if (partial !== void 0 && !isSeq(partial)) return fail("invalid", "partial must be a non-negative integer");
1831
+ const part = isSeq(partial) ? partial : 0;
1690
1832
  if (offset >= this.#engine.head(name)) return fail("invalid", `offset ${offset} is not in ${name} yet`);
1691
1833
  const g = sub.group;
1692
- const covers = (d) => d.offset <= offset && (!g || d.seq <= seq);
1834
+ const covers = (d) => g ? d.offset <= offset && d.seq <= seq || d.seq === seq + 1 && d.i < part : d.offset <= offset;
1693
1835
  const before = sub.unacked.length;
1694
1836
  if (g) sub.unacked = sub.unacked.filter((d) => !covers(d));
1695
1837
  else while (sub.unacked[0] && covers(sub.unacked[0])) sub.unacked.shift();
@@ -1761,10 +1903,11 @@ var Broker = class {
1761
1903
  /** Sends one `deliver`, numbered with the subscription's next `seq`, and returns it. */
1762
1904
  #deliver(sub, records, gap) {
1763
1905
  const seq = ++sub.seq;
1764
- for (const r of records) {
1906
+ for (const [i, r] of records.entries()) {
1765
1907
  sub.unacked.push({
1766
1908
  offset: r.offset,
1767
- seq
1909
+ seq,
1910
+ i
1768
1911
  });
1769
1912
  if (r.req) this.#requests.get(reqKey(sub.topic, r.offset))?.recipients.add(sub.conn.isolateId);
1770
1913
  }
@@ -1831,7 +1974,10 @@ var Broker = class {
1831
1974
  batches.delete(m);
1832
1975
  if (!b || b.records.length === 0) return;
1833
1976
  const seq = this.#deliver(m, b.records);
1834
- for (const e of b.entries) e.seq = seq;
1977
+ for (const { entry, i } of b.entries) {
1978
+ entry.seq = seq;
1979
+ entry.i = i;
1980
+ }
1835
1981
  };
1836
1982
  /** Credit left once the records batched for it go out. */
1837
1983
  const room = (m) => m ? m.credit - (batches.get(m)?.records.length ?? 0) : 0;
@@ -1840,8 +1986,11 @@ var Broker = class {
1840
1986
  records: [],
1841
1987
  entries: []
1842
1988
  };
1989
+ if (entry) b.entries.push({
1990
+ entry,
1991
+ i: b.records.length
1992
+ });
1843
1993
  b.records.push(rec);
1844
- if (entry) b.entries.push(entry);
1845
1994
  batches.set(m, b);
1846
1995
  if (rec.key === void 0) g.rr++;
1847
1996
  if (b.records.length >= this.#batch) flush(m);
@@ -1897,7 +2046,8 @@ var Broker = class {
1897
2046
  const entry = {
1898
2047
  offset: rec.offset,
1899
2048
  member: m,
1900
- seq: 0
2049
+ seq: 0,
2050
+ i: 0
1901
2051
  };
1902
2052
  g.unacked.push(entry);
1903
2053
  give(m, rec, entry);
@@ -1918,4 +2068,4 @@ function validate(schema, value) {
1918
2068
  if (!(r instanceof Promise)) return r;
1919
2069
  return r.then((x) => x, (thrown) => ({ thrown }));
1920
2070
  }
1921
- export { Broker, ContractsError, DEFAULT_MAX_RECORD_BYTES, DEFAULT_REQUEST_TIMEOUT_MS, HOST_PRODUCER, KERNEL_PRODUCER, MemoryStorage, TsEngine, contracts, effectiveDurability, estimateSize, isContracts, isUnchecked, publishId, toIssues, topic, topicConfig, unchecked };
2071
+ export { Broker, ContractsError, DEFAULT_MAX_RECORD_BYTES, DEFAULT_REQUEST_TIMEOUT_MS, HOST_PRODUCER, JSON_SCHEMA_TARGET, KERNEL_PRODUCER, MemoryStorage, TsEngine, contracts, effectiveDurability, estimateSize, hasJsonSchema, isContracts, isUnchecked, jsonSchemaOf, publishId, toIssues, topic, topicConfig, topicJsonSchemas, unchecked };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as Contracts } from "./topic-BQbes-gX.js";
1
+ import { n as Contracts } from "./topic-BgqMD0WA.js";
2
2
  import { Issue } from "@isoloop/protocol";
3
3
  /** Sample values for one topic. An array is shorthand for `{ values }`. */
4
4
  export type TopicSamples = readonly unknown[] | {
@@ -1,4 +1,4 @@
1
- import { BusRecord, ErrorCode, Issue as Issue$1, Retention, Retention as Retention$1, TopicConfig } from "@isoloop/protocol";
1
+ import { BusRecord, ErrorCode, Issue as Issue$1, Retention, Retention as Retention$1, ToolSpec, ToolSpec as ToolSpec$1, TopicConfig } from "@isoloop/protocol";
2
2
  /**
3
3
  * The Standard Schema V1 interface (https://standardschema.dev), vendored so
4
4
  * the bus depends on no schema library (ADR 0003, decision 1). Zod 4, Valibot
@@ -78,6 +78,14 @@ type TopicDef<In, Out = In, RIn = never, ROut = RIn> = {
78
78
  readonly map: (value: any, record: BusRecord) => In;
79
79
  readonly follow?: boolean;
80
80
  };
81
+ /**
82
+ * Describes this topic as a tool for agents (ADR 0018, decision 1). Only a
83
+ * topic with `reply` can have one: without it this field's type is `never`.
84
+ * It exposes nothing by itself; the app's `agents.expose` does. The bus
85
+ * never sees it (not part of `topicConfig`).
86
+ * @experimental
87
+ */
88
+ readonly tool?: [RIn] extends [never] ? never : ToolSpec$1;
81
89
  };
82
90
  type AnyTopicDef = TopicDef<any, any, any, any>;
83
91
  /** What a publisher passes. */
@@ -124,4 +132,4 @@ declare function contracts(...topics: AnyTopicDef[]): Contracts;
124
132
  declare function isContracts(x: unknown): x is Contracts;
125
133
  /** The structured-cloneable part of a topic, sent at `boot` for the contracts check (ADR 0003, decision 5). */
126
134
  declare function topicConfig(t: AnyTopicDef): TopicConfig;
127
- export { StandardSchemaV1 as _, InputOf as a, ReplyOutputOf as c, contracts as d, isContracts as f, unchecked as g, topicConfig as h, DEFAULT_MAX_RECORD_BYTES as i, Retention as l, topic as m, Contracts as n, OutputOf as o, isUnchecked as p, ContractsError as r, ReplyInputOf as s, AnyTopicDef as t, TopicDef as u, toIssues as v };
135
+ export { unchecked as _, InputOf as a, ReplyOutputOf as c, TopicDef as d, contracts as f, topicConfig as g, topic as h, DEFAULT_MAX_RECORD_BYTES as i, Retention as l, isUnchecked as m, Contracts as n, OutputOf as o, isContracts as p, ContractsError as r, ReplyInputOf as s, AnyTopicDef as t, ToolSpec as u, StandardSchemaV1 as v, toIssues as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isoloop/bus",
3
- "version": "0.1.0-next.1",
3
+ "version": "0.1.0-next.3",
4
4
  "description": "Log bus that runs in its own worker: topics, schemas, offsets, replay.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -27,8 +27,8 @@
27
27
  }
28
28
  },
29
29
  "dependencies": {
30
- "@isoloop/codec": "0.1.0-next.1",
31
- "@isoloop/protocol": "0.1.0-next.1"
30
+ "@isoloop/codec": "0.1.0-next.3",
31
+ "@isoloop/protocol": "0.1.0-next.3"
32
32
  },
33
33
  "devDependencies": {
34
34
  "fast-check": "4.10.2",