@isoloop/protocol 0.1.0-next.1 → 0.1.0-next.11

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.js CHANGED
@@ -1,10 +1,10 @@
1
- // src/envelope.ts
1
+ // src/messages/envelope.ts
2
2
  /** Protocol version this build speaks (`v`) and the oldest it still accepts (`min`). */
3
3
  const PROTOCOL = {
4
4
  v: 1,
5
5
  min: 1
6
6
  };
7
- const isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
7
+ const isRecord$1 = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
8
8
  const isOptionalString = (x) => x === void 0 || typeof x === "string";
9
9
  /**
10
10
  * True for a well-formed envelope this build can read: `v` is a supported
@@ -13,7 +13,7 @@ const isOptionalString = (x) => x === void 0 || typeof x === "string";
13
13
  * Says nothing about whether `t` is known; see the per-port guards.
14
14
  */
15
15
  function isEnvelope(x) {
16
- return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
16
+ return isRecord$1(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
17
17
  }
18
18
  /**
19
19
  * Builds a guard for one port's union from its message types. Each side drops
@@ -27,8 +27,8 @@ function envelopeGuard(types) {
27
27
  function assertNever(x, message = "Unexpected value") {
28
28
  throw new Error(`${message}: ${JSON.stringify(x)}`);
29
29
  }
30
- // src/errors.ts
31
- /** Every error code on the wire (design §3, §4.7, §6.1, §6.3; ADRs 0002, 0003, 0007, 0008). */
30
+ // src/errors/errors.ts
31
+ /** Every error code the bus and the host answer with. */
32
32
  const ERROR_CODES = [
33
33
  "protocol_mismatch",
34
34
  "timeout",
@@ -48,6 +48,9 @@ const ERROR_CODES = [
48
48
  "not_requestable",
49
49
  "already_replied",
50
50
  "reply_invalid",
51
+ "aborted",
52
+ "no_responder",
53
+ "dropped",
51
54
  "contracts_failed",
52
55
  "contracts_invalid",
53
56
  "contracts_mismatch",
@@ -59,7 +62,7 @@ const codes = new Set(ERROR_CODES);
59
62
  function isErrorCode(x) {
60
63
  return typeof x === "string" && codes.has(x);
61
64
  }
62
- // src/grants.ts
65
+ // src/topics/grants.ts
63
66
  /** Topics under this prefix belong to the kernel (ADR 0002). */
64
67
  const SYSTEM_TOPIC_PREFIX = "isoloop.";
65
68
  function isSystemTopic(topic) {
@@ -85,13 +88,17 @@ function matchTopic(grant, topic) {
85
88
  function matchAny(patterns, topic) {
86
89
  return patterns.some((p) => matchTopic(p, topic));
87
90
  }
88
- // src/isolate.ts
91
+ // src/messages/isolate.ts
92
+ /** The longest `block` a runtime runs; a longer one is cut to this (ADR 0020, decision 4). */
93
+ const MAX_BLOCK_MS = 1e4;
89
94
  const HOST_TO_ISOLATE = {
90
95
  init: true,
91
96
  event: true,
92
97
  result: true,
93
98
  shutdown: true,
94
- reattach: true
99
+ reattach: true,
100
+ block: true,
101
+ inspect: true
95
102
  };
96
103
  const ISOLATE_TO_HOST = {
97
104
  ready: true,
@@ -103,7 +110,26 @@ const ISOLATE_TO_HOST = {
103
110
  };
104
111
  const isHostToIsolate = envelopeGuard(HOST_TO_ISOLATE);
105
112
  const isIsolateToHost = envelopeGuard(ISOLATE_TO_HOST);
106
- // src/bus.ts
113
+ // src/messages/bus.ts
114
+ /** Every {@link RequestVia}, for guards. @experimental */
115
+ const REQUEST_VIA = Object.freeze([
116
+ "mcp",
117
+ "webmcp",
118
+ "builder"
119
+ ]);
120
+ /** True for a known {@link RequestVia}. @experimental */
121
+ function isRequestVia(x) {
122
+ return typeof x === "string" && REQUEST_VIA.includes(x);
123
+ }
124
+ /**
125
+ * True for a well-formed `BusRecord.req`: string `from` and `id`, and `via`
126
+ * absent or a known {@link RequestVia}.
127
+ */
128
+ function isRecordReq(x) {
129
+ if (typeof x !== "object" || x === null) return false;
130
+ const via = Reflect.get(x, "via");
131
+ return typeof Reflect.get(x, "from") === "string" && typeof Reflect.get(x, "id") === "string" && (via === void 0 || isRequestVia(via));
132
+ }
107
133
  const ISOLATE_TO_BUS = {
108
134
  publish: true,
109
135
  subscribe: true,
@@ -119,7 +145,7 @@ const BUS_TO_ISOLATE = {
119
145
  };
120
146
  const isIsolateToBus = envelopeGuard(ISOLATE_TO_BUS);
121
147
  const isBusToIsolate = envelopeGuard(BUS_TO_ISOLATE);
122
- // src/commits.ts
148
+ // src/topics/commits.ts
123
149
  /** `KernelConfig.bus.commitIntervalMs` when unset (ADR 0016, decision 1, point 7). */
124
150
  const DEFAULT_COMMIT_INTERVAL_MS = 100;
125
151
  /** The highest allowed interval: keeps the redelivery window after a crash under a second. */
@@ -135,7 +161,9 @@ function commitIntervalProblem(ms) {
135
161
  * The commit point each record of one `deliver` settles to, in order. A
136
162
  * record settles its delivery `seq` only as the delivery's last record, and
137
163
  * `seq − 1` before that: a delivery counts once all its records are settled,
138
- * and records settle in the order they arrived. Its offset is the highest
164
+ * and records settle in the order they arrived. Before the last, the `i`-th
165
+ * record also settles the first `i + 1` records of its delivery (`partial`,
166
+ * ADR 0016, point 17). Its offset is the highest
139
167
  * delivered on the subscription up to it, `highest` being the highest before
140
168
  * this delivery (`-1` for none), so a commit that counts a delivery settled
141
169
  * also reaches every offset in it.
@@ -144,12 +172,38 @@ function deliveryPoints(seq, offsets, highest) {
144
172
  let top = highest;
145
173
  return offsets.map((offset, i) => {
146
174
  top = Math.max(top, offset);
147
- return {
175
+ return i === offsets.length - 1 ? {
176
+ offset: top,
177
+ seq
178
+ } : {
148
179
  offset: top,
149
- seq: i === offsets.length - 1 ? seq : seq - 1
180
+ seq: seq - 1,
181
+ partial: i + 1
150
182
  };
151
183
  });
152
184
  }
185
+ const point = ({ offset, seq, partial }) => partial ? {
186
+ offset,
187
+ seq,
188
+ partial
189
+ } : {
190
+ offset,
191
+ seq
192
+ };
193
+ /**
194
+ * The further of two commit points: the highest offset, and the delivery
195
+ * reached furthest, a whole delivery being further than any part of it.
196
+ */
197
+ function later(a, b) {
198
+ const offset = Math.max(a.offset, b.offset);
199
+ const reach = (p) => [p.seq, p.partial ?? 0];
200
+ const [as, ap] = reach(a);
201
+ const [bs, bp] = reach(b);
202
+ return point({
203
+ ...bs > as || bs === as && bp >= ap ? b : a,
204
+ offset
205
+ });
206
+ }
153
207
  function createCommitter(o) {
154
208
  const intervalMs = o.intervalMs ?? 100;
155
209
  const half = Math.max(1, Math.floor((o.credit ?? 1e3) / 2));
@@ -167,7 +221,12 @@ function createCommitter(o) {
167
221
  queued = false;
168
222
  if (offsets.size === 0) return void 0;
169
223
  const out = [];
170
- for (const [topic, { offset, seq }] of offsets) out.push({
224
+ for (const [topic, { offset, seq, partial }] of offsets) out.push(partial ? {
225
+ topic,
226
+ offset,
227
+ seq,
228
+ partial
229
+ } : {
171
230
  topic,
172
231
  offset,
173
232
  seq
@@ -194,13 +253,7 @@ function createCommitter(o) {
194
253
  return {
195
254
  settle(topic, at, records = 1) {
196
255
  const prev = offsets.get(topic);
197
- offsets.set(topic, prev === void 0 ? {
198
- offset: at.offset,
199
- seq: at.seq
200
- } : {
201
- offset: Math.max(prev.offset, at.offset),
202
- seq: Math.max(prev.seq, at.seq)
203
- });
256
+ offsets.set(topic, prev === void 0 ? point(at) : later(prev, at));
204
257
  const n = (counts.get(topic) ?? 0) + records;
205
258
  counts.set(topic, n);
206
259
  if (n >= half) flush();
@@ -220,14 +273,17 @@ function createCommitter(o) {
220
273
  }
221
274
  };
222
275
  }
223
- // src/bus-error.ts
276
+ // src/errors/bus-error.ts
224
277
  /**
225
278
  * A rejected bus call (`kernel.publish`, `ctx.bus.publish`, `request`,
226
279
  * `reply`): the broker's error code, and the schema issues for `invalid`.
227
280
  */
228
281
  var BusError = class extends Error {
282
+ /** What went wrong, to branch on: `invalid`, `forbidden`, `timeout`, `bus_unavailable`, … */
229
283
  code;
284
+ /** For `invalid`: where the value failed its schema, and why. */
230
285
  issues;
286
+ /** @param error The broker's error: its code, message and issues. */
231
287
  constructor(error) {
232
288
  super(error.message);
233
289
  this.name = "BusError";
@@ -235,15 +291,31 @@ var BusError = class extends Error {
235
291
  this.issues = error.issues;
236
292
  }
237
293
  };
238
- // src/control.ts
294
+ // src/messages/control.ts
295
+ /** Longest preview of a record's value, in characters (ADR 0020, decision 3). */
296
+ const PREVIEW_CHARS = 2048;
297
+ /** Records a `tap` sends each second when its `maxPerSec` isn't given. */
298
+ const DEFAULT_TAP_PER_SEC = 50;
299
+ /** Most records one `read` returns. */
300
+ const MAX_READ = 100;
239
301
  const HOST_TO_BUS = {
240
302
  boot: true,
241
303
  attach: true,
242
304
  detach: true,
243
305
  publish: true,
306
+ request: true,
244
307
  flush: true,
245
- drop: true
308
+ drop: true,
309
+ tap: true,
310
+ read: true
311
+ };
312
+ /** The message types a tap's port carries from the bus (ADR 0020, decision 3). @experimental */
313
+ const BUS_TO_TAP = {
314
+ record: true,
315
+ skipped: true
246
316
  };
317
+ /** The message types a tap's port carries to the bus. @experimental */
318
+ const TAP_TO_BUS = { close: true };
247
319
  const BUS_TO_HOST = {
248
320
  ready: true,
249
321
  beat: true,
@@ -255,7 +327,11 @@ const BUS_TO_HOST = {
255
327
  };
256
328
  const isHostToBus = envelopeGuard(HOST_TO_BUS);
257
329
  const isBusToHost = envelopeGuard(BUS_TO_HOST);
258
- // src/system-topics.ts
330
+ /** A well-formed message from the bus on a tap's port. @experimental */
331
+ const isBusToTap = envelopeGuard(BUS_TO_TAP);
332
+ /** A well-formed message from the host on a tap's port. @experimental */
333
+ const isTapToBus = envelopeGuard(TAP_TO_BUS);
334
+ // src/topics/system-topics.ts
259
335
  /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
260
336
  function systemSchema(check) {
261
337
  return { "~standard": {
@@ -290,7 +366,7 @@ const checks = {
290
366
  },
291
367
  any: () => []
292
368
  };
293
- // src/route.ts
369
+ // src/topics/route.ts
294
370
  const stringOrNull = (v, path) => v === null || typeof v === "string" ? [] : [{
295
371
  message: "expected a string or null",
296
372
  path
@@ -316,7 +392,7 @@ const routeTopic = systemTopic("isoloop.route.v1", {
316
392
  const ROUTE_KEY = "current";
317
393
  /** Every system topic, built into the bus. */
318
394
  const SYSTEM_TOPICS = [routeTopic];
319
- // src/topics.ts
395
+ // src/topics/topics.ts
320
396
  /**
321
397
  * The structured-cloneable part of a topic, sent at `boot` and compared with
322
398
  * the contracts module's (ADR 0003, decision 5). Host and bus both use this
@@ -336,7 +412,7 @@ function topicConfigOf(t) {
336
412
  };
337
413
  return cfg;
338
414
  }
339
- // src/version.ts
415
+ // src/messages/version.ts
340
416
  /** `"0.4.2"` → `"0.4"`. Anything that isn't `major.minor[.patch…]` gives `undefined`. */
341
417
  function majorMinor(version) {
342
418
  const m = /^(\d+)\.(\d+)(?:[.+-].*)?$/.exec(version);
@@ -354,4 +430,195 @@ function compareVersions(a, b) {
354
430
  const [bm, bn] = parse(b);
355
431
  return am - bm || an - bn;
356
432
  }
357
- export { BUS_TO_HOST, BUS_TO_ISOLATE, BusError, DEFAULT_COMMIT_INTERVAL_MS, DEFAULT_CREDIT, ERROR_CODES, HOST_TO_BUS, HOST_TO_ISOLATE, ISOLATE_TO_BUS, ISOLATE_TO_HOST, MAX_COMMIT_INTERVAL_MS, PROTOCOL, ROUTE_KEY, SYSTEM_TOPICS, SYSTEM_TOPIC_PREFIX, assertNever, checks, commitIntervalProblem, compareVersions, createCommitter, deliveryPoints, envelopeGuard, isBusToHost, isBusToIsolate, isEnvelope, isErrorCode, isHostToBus, isHostToIsolate, isIsolateToBus, isIsolateToHost, isSystemTopic, majorMinor, matchAny, matchTopic, routeTopic, systemSchema, systemTopic, topicConfigOf };
433
+ // src/topics/json-schema.ts
434
+ /**
435
+ * The vendor `unchecked()` in `@isoloop/bus` gives its schemas.
436
+ *
437
+ * @internal
438
+ */
439
+ const UNCHECKED_VENDOR = "isoloop/unchecked";
440
+ /**
441
+ * The JSON Schema target Isoloop uses everywhere (ADR 0003, decision 21).
442
+ *
443
+ * @internal
444
+ */
445
+ const JSON_SCHEMA_TARGET = "draft-2020-12";
446
+ const isRecord = (x) => typeof x === "object" && x !== null;
447
+ /**
448
+ * True if the schema implements Standard JSON Schema (`~standard.jsonSchema`).
449
+ *
450
+ * @internal
451
+ */
452
+ function hasJsonSchema(schema) {
453
+ if (!isRecord(schema)) return false;
454
+ const std = schema["~standard"];
455
+ if (!isRecord(std)) return false;
456
+ const js = std["jsonSchema"];
457
+ return isRecord(js) && typeof js["input"] === "function" && typeof js["output"] === "function";
458
+ }
459
+ /** `~standard.vendor`, when the value has one. */
460
+ function vendorOf(schema) {
461
+ if (!isRecord(schema)) return void 0;
462
+ const std = schema["~standard"];
463
+ if (!isRecord(std)) return void 0;
464
+ const vendor = std["vendor"];
465
+ return typeof vendor === "string" ? vendor : void 0;
466
+ }
467
+ const messageOf = (e) => e instanceof Error ? e.message : String(e);
468
+ /**
469
+ * Makes a schema's input and output JSON Schema (draft 2020-12) through the
470
+ * Standard JSON Schema interface. Never throws: an `unchecked()` schema, one
471
+ * without the interface, or a converter that throws gives `{ ok: false }`
472
+ * with the reason, so callers decide (`not_exposable` for the kernel, a flag
473
+ * for `isoloop contracts export`).
474
+ *
475
+ * @internal Used by the kernel's agent tools and `isoloop contracts export`.
476
+ */
477
+ function jsonSchemaOf(schema) {
478
+ const vendor = vendorOf(schema);
479
+ if (vendor === "isoloop/unchecked") return {
480
+ ok: false,
481
+ reason: "unchecked",
482
+ message: "is unchecked()"
483
+ };
484
+ if (!hasJsonSchema(schema)) return {
485
+ ok: false,
486
+ reason: "unsupported",
487
+ message: `doesn't implement Standard JSON Schema (${vendor ?? "not a Standard Schema"})`
488
+ };
489
+ const options = { target: JSON_SCHEMA_TARGET };
490
+ try {
491
+ const { jsonSchema } = schema["~standard"];
492
+ return {
493
+ ok: true,
494
+ input: jsonSchema.input(options),
495
+ output: jsonSchema.output(options)
496
+ };
497
+ } catch (e) {
498
+ return {
499
+ ok: false,
500
+ reason: "failed",
501
+ message: `can't be made into JSON Schema: ${messageOf(e)}`
502
+ };
503
+ }
504
+ }
505
+ const pair = (r) => ({
506
+ input: r.input,
507
+ output: r.output
508
+ });
509
+ /**
510
+ * Makes a topic's JSON Schemas: the topic schema's input and output, and the
511
+ * `reply` schema's when it has one. A tool's input schema is `schema.input`;
512
+ * its output schema is `reply.output` (ADR 0018, decision 1). Never throws.
513
+ *
514
+ * @internal Used by the kernel's agent tools and `isoloop contracts export`.
515
+ */
516
+ function topicJsonSchemas(def) {
517
+ const fail = (part, r) => ({
518
+ ok: false,
519
+ topic: def.name,
520
+ part,
521
+ reason: r.reason,
522
+ message: `${def.name}: ${part} ${r.message}`
523
+ });
524
+ const schema = jsonSchemaOf(def.schema);
525
+ if (!schema.ok) return fail("schema", schema);
526
+ if (def.reply === void 0) return {
527
+ ok: true,
528
+ schema: pair(schema)
529
+ };
530
+ const reply = jsonSchemaOf(def.reply);
531
+ if (!reply.ok) return fail("reply", reply);
532
+ return {
533
+ ok: true,
534
+ schema: pair(schema),
535
+ reply: pair(reply)
536
+ };
537
+ }
538
+ // src/messages/dev-mcp.ts
539
+ /** `DevMcpOp['op']`, as a list. @internal */
540
+ const DEV_MCP_OPS = [
541
+ "isolates",
542
+ "topics",
543
+ "records",
544
+ "tap",
545
+ "events",
546
+ "restart",
547
+ "kill",
548
+ "block",
549
+ "publish",
550
+ "request"
551
+ ];
552
+ /** @internal */
553
+ const PAGE_TO_CLI = {
554
+ hello: true,
555
+ result: true
556
+ };
557
+ /** @internal */
558
+ const CLI_TO_PAGE = {
559
+ welcome: true,
560
+ call: true,
561
+ op: true,
562
+ cancel: true
563
+ };
564
+ /** @internal */
565
+ const isPageToCli = envelopeGuard(PAGE_TO_CLI);
566
+ /** @internal */
567
+ const isCliToPage = envelopeGuard(CLI_TO_PAGE);
568
+ /**
569
+ * WebSocket close codes the CLI uses (4000–4999 are the application's).
570
+ * @internal
571
+ */
572
+ const DEV_MCP_CLOSE = {
573
+ /** The first message wasn't a well-formed `hello`, or its `v` differs. */
574
+ badHello: 4400,
575
+ /** The token didn't match. */
576
+ badToken: 4401,
577
+ /** The CLI is shutting down. */
578
+ shutdown: 4e3
579
+ };
580
+ /** The CLI's WebSocket port when `--port` isn't given. @internal */
581
+ const DEV_MCP_PORT = 4317;
582
+ // src/messages/inspect.ts
583
+ /** @experimental */
584
+ const INSPECT_MESSAGES = {
585
+ snapshot: true,
586
+ event: true,
587
+ beats: true,
588
+ metrics: true,
589
+ memory: true
590
+ };
591
+ /**
592
+ * True for an envelope of a feed message this build knows. A reader drops
593
+ * anything else, which is how it ignores message types added later.
594
+ * @experimental
595
+ */
596
+ const isInspectMessage = envelopeGuard(INSPECT_MESSAGES);
597
+ /** How many events the kernel keeps for late readers (ADR 0020, decision 5). */
598
+ const INSPECT_RING_SIZE = 200;
599
+ /** How often beats and bus metrics are coalesced (ADR 0020, decision 2). */
600
+ const INSPECT_COALESCE_MS = 1e3;
601
+ /** The shortest time between two memory measurements (ADR 0020, decision 4). */
602
+ const INSPECT_MEMORY_MS = 5e3;
603
+ /** @experimental */
604
+ const ISOLATE_TO_INSPECT = {
605
+ listen: true,
606
+ unlisten: true,
607
+ snapshot: true,
608
+ records: true,
609
+ tap: true,
610
+ untap: true,
611
+ control: true
612
+ };
613
+ /** @experimental */
614
+ const INSPECT_TO_ISOLATE = {
615
+ ...INSPECT_MESSAGES,
616
+ result: true,
617
+ record: true,
618
+ skipped: true
619
+ };
620
+ /** @experimental */
621
+ const isIsolateToInspect = envelopeGuard(ISOLATE_TO_INSPECT);
622
+ /** @experimental */
623
+ const isInspectToIsolate = envelopeGuard(INSPECT_TO_ISOLATE);
624
+ export { BUS_TO_HOST, BUS_TO_ISOLATE, BUS_TO_TAP, BusError, CLI_TO_PAGE, DEFAULT_COMMIT_INTERVAL_MS, DEFAULT_CREDIT, DEFAULT_TAP_PER_SEC, DEV_MCP_CLOSE, DEV_MCP_OPS, DEV_MCP_PORT, ERROR_CODES, HOST_TO_BUS, HOST_TO_ISOLATE, INSPECT_COALESCE_MS, INSPECT_MEMORY_MS, INSPECT_MESSAGES, INSPECT_RING_SIZE, INSPECT_TO_ISOLATE, ISOLATE_TO_BUS, ISOLATE_TO_HOST, ISOLATE_TO_INSPECT, JSON_SCHEMA_TARGET, MAX_BLOCK_MS, MAX_COMMIT_INTERVAL_MS, MAX_READ, PAGE_TO_CLI, PREVIEW_CHARS, PROTOCOL, REQUEST_VIA, ROUTE_KEY, SYSTEM_TOPICS, SYSTEM_TOPIC_PREFIX, TAP_TO_BUS, UNCHECKED_VENDOR, assertNever, checks, commitIntervalProblem, compareVersions, createCommitter, deliveryPoints, envelopeGuard, hasJsonSchema, isBusToHost, isBusToIsolate, isBusToTap, isCliToPage, isEnvelope, isErrorCode, isHostToBus, isHostToIsolate, isInspectMessage, isInspectToIsolate, isIsolateToBus, isIsolateToHost, isIsolateToInspect, isPageToCli, isRecordReq, isRequestVia, isSystemTopic, isTapToBus, jsonSchemaOf, majorMinor, matchAny, matchTopic, routeTopic, systemSchema, systemTopic, topicConfigOf, topicJsonSchemas };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@isoloop/protocol",
3
- "version": "0.1.0-next.1",
4
- "description": "Wire protocol types and guards shared by every Isoloop package.",
3
+ "version": "0.1.0-next.11",
4
+ "description": "Internal: Isoloop's wire protocol types and guards. Used by the @isoloop/* packages; not for app code.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": false,