@isoloop/protocol 0.1.0-next.0 → 0.1.0-next.10

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/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # @isoloop/protocol
2
+
3
+ **Internal.** The wire protocol of [Isoloop](https://github.com/isoloop/isoloop): the message, event and error types that the kernel, the bus and isolates exchange. `@isoloop/host`, `@isoloop/runtime`, `@isoloop/bus` and the adapters depend on it. App code never imports it: the types it needs come re-exported from those packages, and this package's API carries no semver promise of its own.
4
+
5
+ | Entry | What it is |
6
+ | --- | --- |
7
+ | `@isoloop/protocol` | The envelopes, events, grants, bus and control messages, system topics and error codes, and the guards that check a message's shape. |
package/dist/index.d.ts CHANGED
@@ -43,11 +43,24 @@ export type MessageTypes<E extends AnyEnvelope> = Readonly<Record<E["t"], true>>
43
43
  export declare function envelopeGuard<E extends AnyEnvelope>(types: MessageTypes<E>): (x: unknown) => x is E;
44
44
  /** Exhaustiveness check for switches over message unions. */
45
45
  export declare function assertNever(x: never, message?: string): never;
46
- /** Every error code on the wire (design §3, §4.7, §6.1, §6.3; ADRs 0002, 0003, 0007, 0008). */
47
- export declare const ERROR_CODES: readonly ["protocol_mismatch", "timeout", "no_surface", "forbidden", "not_found", "unsupported", "cross_origin", "routing_disabled", "navigate_failed", "unknown_topic", "too_large", "invalid", "not_encodable", "quota_exceeded", "bus_unavailable", "not_requestable", "already_replied", "reply_invalid", "contracts_failed", "contracts_invalid", "contracts_mismatch", "reserved_topic", "seed_async", "seed_pending"];
46
+ /** Every error code the bus and the host answer with. */
47
+ export declare const ERROR_CODES: readonly ["protocol_mismatch", "timeout", "no_surface", "forbidden", "not_found", "unsupported", "cross_origin", "routing_disabled", "navigate_failed", "unknown_topic", "too_large", "invalid", "not_encodable", "quota_exceeded", "bus_unavailable", "not_requestable", "already_replied", "reply_invalid", "aborted", "no_responder", "dropped", "contracts_failed", "contracts_invalid", "contracts_mismatch", "reserved_topic", "seed_async", "seed_pending"];
48
+ /**
49
+ * An error code a `BusError` or `HostCallError` carries. By where it comes from:
50
+ * - host calls: `timeout`, `no_surface`, `forbidden`, `not_found`, `unsupported`;
51
+ * - routing: `cross_origin`, `routing_disabled`, `navigate_failed`;
52
+ * - the broker: `unknown_topic`, `too_large`, `invalid`, `not_encodable`,
53
+ * `quota_exceeded`, `bus_unavailable`, `not_requestable`, `already_replied`,
54
+ * `reply_invalid`;
55
+ * - `kernel.request`: `aborted`, `no_responder`, `dropped`;
56
+ * - the contracts, fatal and never retried: `contracts_failed`,
57
+ * `contracts_invalid`, `contracts_mismatch`, `reserved_topic`;
58
+ * - seeding: `seed_async`, `seed_pending`;
59
+ * - the version handshake: `protocol_mismatch`.
60
+ */
48
61
  export type ErrorCode = (typeof ERROR_CODES)[number];
49
62
  export declare function isErrorCode(x: unknown): x is ErrorCode;
50
- /** A schema issue, as reported with `invalid` (design §6.3). */
63
+ /** A schema issue, as reported with `invalid`: what's wrong, and where in the value. */
51
64
  export type Issue = {
52
65
  message: string;
53
66
  path: (string | number)[];
@@ -72,14 +85,22 @@ export type ErrorPayload = {
72
85
  fatal: boolean;
73
86
  code?: ErrorCode;
74
87
  };
75
- /** What an isolate may do on the bus and the host (design §3). */
88
+ /** What an isolate may do on the bus and the host: `IsolateManifest.grants`. */
76
89
  export type Grants = {
77
- /** Topic patterns the isolate may publish to. */
90
+ /** Topic patterns the isolate may publish to. `*` matches one or more characters, dots included. */
78
91
  publish: string[];
79
- /** Topic patterns the isolate may subscribe to. */
92
+ /** Topic patterns the isolate may subscribe to, the same way. */
80
93
  subscribe: string[];
81
- /** Programmatic `navigate()` allowed (ADR 0002). Default false. */
94
+ /** `ctx.host.navigate()` allowed. Default false. */
82
95
  navigate?: boolean;
96
+ /**
97
+ * The inspection feed and its controls: the isolate gets `ctx.inspector` on a port of its own, which reads the feed and can
98
+ * restart, kill and block isolates. Default false. Never in a pool: spawning
99
+ * a pooled isolate with it fails with `invalid_config`, since a pool merges
100
+ * its members' grants.
101
+ * @experimental
102
+ */
103
+ inspect?: boolean;
83
104
  };
84
105
  /** Topics under this prefix belong to the kernel (ADR 0002). */
85
106
  export declare const SYSTEM_TOPIC_PREFIX = "isoloop.";
@@ -126,7 +147,7 @@ export type SerializedEvent = {
126
147
  scrollTop?: number;
127
148
  scrollLeft?: number;
128
149
  };
129
- /** Why the host asks an isolate to shut down. `suspend` keeps its offsets (M2, ADR 0001). */
150
+ /** Why the host asks an isolate to shut down. `suspend` keeps its offsets, to replay what it missed on waking. */
130
151
  export type ShutdownReason = "stop" | "restart" | "suspend";
131
152
  /** Calls an isolate can make to the host (design §4.7). */
132
153
  export type HostMethod = "measure" | "focus" | "navigate" | "scrollIntoView" | "requestCanvas";
@@ -184,12 +205,18 @@ export type IdleReport = {
184
205
  */
185
206
  busyMs?: number;
186
207
  };
208
+ /** The longest `block` a runtime runs; a longer one is cut to this (ADR 0020, decision 4). */
209
+ export declare const MAX_BLOCK_MS = 1e4;
187
210
  /** Isolate port: host → isolate. */
188
211
  export type HostToIsolate = Envelope<"init", InitPayload> | Envelope<"event", SerializedEvent> | Envelope<"result", CallResult> | Envelope<"shutdown", {
189
212
  reason: ShutdownReason;
190
213
  graceMs: number;
191
214
  }> | Envelope<"reattach", {
192
215
  busPort: MessagePort;
216
+ }> | Envelope<"block", {
217
+ ms: number;
218
+ }> | Envelope<"inspect", {
219
+ port: MessagePort;
193
220
  }>;
194
221
  /** Isolate port: isolate → host. */
195
222
  export type IsolateToHost = Envelope<"ready", {
@@ -198,6 +225,14 @@ export type IsolateToHost = Envelope<"ready", {
198
225
  renderFmt: string;
199
226
  /** The Isoloop `major.minor` the isolate was built against, from `defineIsolate` (ADR 0012). */
200
227
  requires?: string;
228
+ /**
229
+ * True when the worker started from `@isoloop/runtime/worker`, the tiny
230
+ * entry no chunk imports. Only such a worker can start from a URL with
231
+ * a fragment of its own without loading the bootstrap twice, which is
232
+ * what memory per isolate needs (ADR 0020, decision 4). Runtimes
233
+ * before it leave it out.
234
+ */
235
+ entry?: true;
201
236
  }> | Envelope<"patch", {
202
237
  fmt: string;
203
238
  batch: unknown;
@@ -208,7 +243,6 @@ export type IsolateToHost = Envelope<"ready", {
208
243
  args: unknown[];
209
244
  }> | Envelope<"beat", {
210
245
  lagMs: number;
211
- heapBytes?: number;
212
246
  idle?: IdleReport;
213
247
  members?: Record<string, IdleReport>;
214
248
  }> | Envelope<"error", ErrorPayload> | Envelope<"bye", Record<string, never>>;
@@ -216,24 +250,50 @@ export declare const HOST_TO_ISOLATE: MessageTypes<HostToIsolate>;
216
250
  export declare const ISOLATE_TO_HOST: MessageTypes<IsolateToHost>;
217
251
  export declare const isHostToIsolate: (x: unknown) => x is HostToIsolate;
218
252
  export declare const isIsolateToHost: (x: unknown) => x is IsolateToHost;
219
- /** One record in a topic's log (design §6.1). */
253
+ /** One record in a topic's log. */
220
254
  export type BusRecord = {
255
+ /** Its place in the topic's log, from 0. */
221
256
  offset: number;
257
+ /** The key it was published with, if any. */
222
258
  key?: string;
259
+ /** The value, checked against the topic's schema. */
223
260
  value: unknown;
224
261
  /** `Date.now()` at append. */
225
262
  ts: number;
226
263
  /** Isolate id of the publisher. */
227
264
  producer: string;
228
265
  /**
229
- * Set on a `bus.request` record: the caller's isolate id and its request id.
230
- * A recipient answers with `reply { topic, offset }` (design §6.3).
266
+ * Set on a `bus.request` record: the caller's isolate id (`'host'` for
267
+ * `kernel.request`) and its request id. A recipient answers with
268
+ * `bus.reply(record, value)`. `via` names the agent transport that made the
269
+ * call; an isolate's own `bus.request` never sets it.
231
270
  */
232
- req?: {
233
- from: string;
234
- id: string;
235
- };
271
+ req?: RecordReq;
236
272
  };
273
+ /**
274
+ * The agent transports that call through `kernel.request`: `mcp` (the dev
275
+ * MCP) and `webmcp` (WebMCP). Nothing in Isoloop sets `builder`.
276
+ *
277
+ * Self-declared by the caller: a label for logging and policy between
278
+ * cooperating code on one page. Never authorize anything by it.
279
+ * @experimental
280
+ */
281
+ export type RequestVia = "mcp" | "webmcp" | "builder";
282
+ /** Every {@link RequestVia}, for guards. @experimental */
283
+ export declare const REQUEST_VIA: readonly RequestVia[];
284
+ /** True for a known {@link RequestVia}. @experimental */
285
+ export declare function isRequestVia(x: unknown): x is RequestVia;
286
+ /** `BusRecord.req`: who asked, under which request id, and through which transport. */
287
+ export type RecordReq = {
288
+ from: string;
289
+ id: string;
290
+ via?: RequestVia;
291
+ };
292
+ /**
293
+ * True for a well-formed `BusRecord.req`: string `from` and `id`, and `via`
294
+ * absent or a known {@link RequestVia}.
295
+ */
296
+ export declare function isRecordReq(x: unknown): x is RecordReq;
237
297
  /**
238
298
  * Identifies a publish so a re-send after a bus crash isn't appended twice to
239
299
  * a persistent topic (ADR 0007, step 5): `epoch` names the publisher's
@@ -245,7 +305,12 @@ export type PublishId = {
245
305
  epoch?: number;
246
306
  seq?: number;
247
307
  };
248
- /** Where a new subscription starts reading. */
308
+ /**
309
+ * Where a new subscription starts reading: `latest`, only records appended
310
+ * from now on; `earliest`, the oldest record still retained; `committed`,
311
+ * after the last record this subscriber committed, or the oldest retained
312
+ * when it has committed none.
313
+ */
249
314
  export type StartPosition = "latest" | "earliest" | "committed";
250
315
  /** Bus port: isolate → bus worker. */
251
316
  export type IsolateToBus = Envelope<"publish", {
@@ -263,6 +328,7 @@ export type IsolateToBus = Envelope<"publish", {
263
328
  topic: string;
264
329
  offset: number;
265
330
  seq: number;
331
+ partial?: number;
266
332
  }[];
267
333
  }> | Envelope<"request", {
268
334
  topic: string;
@@ -299,10 +365,15 @@ export declare const MAX_COMMIT_INTERVAL_MS = 1e3;
299
365
  export declare const DEFAULT_CREDIT = 1e3;
300
366
  /** Why an interval is invalid, or `undefined` when it's an integer from 0 to 1,000. */
301
367
  export declare function commitIntervalProblem(ms: unknown): string | undefined;
302
- /** Where one subscription has settled to: the highest settled offset, and the delivery `seq` (ADR 0016, point 11). */
368
+ /**
369
+ * Where one subscription has settled to: the highest settled offset, the
370
+ * delivery `seq` settled whole (ADR 0016, point 11), and how many records of
371
+ * delivery `seq + 1` are settled, when some are (point 17).
372
+ */
303
373
  export type CommitPoint = {
304
374
  offset: number;
305
375
  seq: number;
376
+ partial?: number;
306
377
  };
307
378
  export type CommitOffsets = ({
308
379
  topic: string;
@@ -311,7 +382,9 @@ export type CommitOffsets = ({
311
382
  * The commit point each record of one `deliver` settles to, in order. A
312
383
  * record settles its delivery `seq` only as the delivery's last record, and
313
384
  * `seq − 1` before that: a delivery counts once all its records are settled,
314
- * and records settle in the order they arrived. Its offset is the highest
385
+ * and records settle in the order they arrived. Before the last, the `i`-th
386
+ * record also settles the first `i + 1` records of its delivery (`partial`,
387
+ * ADR 0016, point 17). Its offset is the highest
315
388
  * delivered on the subscription up to it, `highest` being the highest before
316
389
  * this delivery (`-1` for none), so a commit that counts a delivery settled
317
390
  * also reaches every offset in it.
@@ -353,15 +426,25 @@ export declare function createCommitter(o: CommitterOptions): Committer;
353
426
  * `reply`): the broker's error code, and the schema issues for `invalid`.
354
427
  */
355
428
  export declare class BusError extends Error {
429
+ /** What went wrong, to branch on: `invalid`, `forbidden`, `timeout`, `bus_unavailable`, … */
356
430
  readonly code: ErrorCode;
431
+ /** For `invalid`: where the value failed its schema, and why. */
357
432
  readonly issues: readonly Issue[] | undefined;
433
+ /** @param error The broker's error: its code, message and issues. */
358
434
  constructor(error: CallError);
359
435
  }
436
+ /**
437
+ * What a topic's log keeps: `last-n`, the newest `n` records; `time`, the
438
+ * records younger than `ms` by their `ts`; `compacted`, the latest record per
439
+ * key.
440
+ */
360
441
  export type Retention = {
361
442
  kind: "last-n";
443
+ /** How many records to keep, a positive integer. */
362
444
  n: number;
363
445
  } | {
364
446
  kind: "time";
447
+ /** How long to keep a record, in milliseconds, a positive integer. */
365
448
  ms: number;
366
449
  } | {
367
450
  kind: "compacted";
@@ -385,8 +468,8 @@ export type TopicConfig = {
385
468
  follow: boolean;
386
469
  };
387
470
  };
388
- /** Why persistent topics run in memory (`bus:durability-degraded`). */
389
- export type DurabilityDegraded = "another-tab" | "no-sync-access" | "open-failed";
471
+ /** Why persistent topics run in memory (`bus:durability_degraded`). */
472
+ export type DurabilityDegraded = "another_tab" | "no_sync_access" | "open_failed";
390
473
  /**
391
474
  * Seeding news (ADR 0003, decision 18). `rejected`: a source record `map`
392
475
  * threw on, returned a promise for (`seed_async`), or the topic's schema
@@ -406,20 +489,30 @@ export type SeedEvent = {
406
489
  copied: number;
407
490
  rejected: number;
408
491
  };
409
- /** Sampled every second on the control port (design §6.3). */
492
+ /** The bus's figures, sampled every second: `bus:metrics`. */
410
493
  export type BusMetrics = {
494
+ /**
495
+ * Per topic: records and bytes a second; `head`, the next offset to be
496
+ * written; and `retained`, how many records the topic still holds.
497
+ */
411
498
  topics: {
412
499
  topic: string;
413
500
  recordsPerSec: number;
414
501
  bytesPerSec: number;
502
+ head: number;
503
+ retained: number;
415
504
  }[];
416
- /** `lag` is `head − cursor`. */
505
+ /**
506
+ * Per consumer and topic: `lag` is `head − cursor`; `credit` is how many
507
+ * records may still be delivered before its next commit.
508
+ */
417
509
  subscriptions: {
418
510
  consumer: string;
419
511
  topic: string;
420
512
  lag: number;
421
513
  credit: number;
422
514
  }[];
515
+ /** Rejected publishes by error code, since the bus worker started. */
423
516
  rejected: Partial<Record<ErrorCode, number>>;
424
517
  /** The origin's storage use, from `navigator.storage.estimate()`, while the bus keeps files. */
425
518
  storage?: {
@@ -427,6 +520,47 @@ export type BusMetrics = {
427
520
  quota: number;
428
521
  };
429
522
  };
523
+ /** Longest preview of a record's value, in characters (ADR 0020, decision 3). */
524
+ export declare const PREVIEW_CHARS = 2048;
525
+ /** Records a `tap` sends each second when its `maxPerSec` isn't given. */
526
+ export declare const DEFAULT_TAP_PER_SEC = 50;
527
+ /** Most records one `read` returns. */
528
+ export declare const MAX_READ = 100;
529
+ /**
530
+ * A record as the inspection feed shows it: its value as text, cut to 2,048
531
+ * characters, with the value's estimated size in bytes.
532
+ * @experimental
533
+ */
534
+ export type RecordPreview = {
535
+ /** The topic's name. */
536
+ topic: string;
537
+ /** Its place in the topic's log. */
538
+ offset: number;
539
+ /** The key it was published with, if any. */
540
+ key?: string;
541
+ /** `Date.now()` at append. */
542
+ ts: number;
543
+ /** Who published it: an isolate's id, or the host. */
544
+ producer: string;
545
+ /** For a request record: who asked, and the request's id. */
546
+ req?: RecordReq;
547
+ /** The value's estimated size, as the bus counts it for `too_large` and the byte rates. */
548
+ bytes: number;
549
+ /** The value as JSON-like text, at most 2,048 characters. */
550
+ preview: string;
551
+ /** `preview` was cut short. */
552
+ truncated: boolean;
553
+ };
554
+ /**
555
+ * A tap's port: bus → host. `skipped` counts the records over the tap's
556
+ * `maxPerSec` since the last `skipped`, sent at most once a second.
557
+ * @experimental
558
+ */
559
+ export type BusToTap = Envelope<"record", RecordPreview> | Envelope<"skipped", {
560
+ count: number;
561
+ }>;
562
+ /** A tap's port: host → bus. `close` ends the tap. @experimental */
563
+ export type TapToBus = Envelope<"close", Record<string, never>>;
430
564
  /** Control port: host → bus worker. */
431
565
  export type HostToBus = Envelope<"boot", {
432
566
  contractsUrl: string;
@@ -453,9 +587,22 @@ export type HostToBus = Envelope<"boot", {
453
587
  topic: string;
454
588
  key?: string;
455
589
  value: unknown;
590
+ } & PublishId> | Envelope<"request", {
591
+ topic: string;
592
+ key?: string;
593
+ value: unknown;
594
+ timeoutMs: number;
595
+ via?: RequestVia;
456
596
  } & PublishId> | Envelope<"flush", Record<string, never>> | Envelope<"drop", {
457
597
  topic: string;
458
598
  force: boolean;
599
+ }> | Envelope<"tap", {
600
+ topics: string[];
601
+ maxPerSec?: number;
602
+ port: MessagePort;
603
+ }> | Envelope<"read", {
604
+ topic: string;
605
+ last: number;
459
606
  }>;
460
607
  /** Control port: bus worker → host. */
461
608
  export type BusToHost = Envelope<"ready", {
@@ -488,9 +635,17 @@ export type BusToHost = Envelope<"ready", {
488
635
  topic: string;
489
636
  }> | Envelope<"metrics", BusMetrics> | Envelope<"result", CallResult> | Envelope<"seed", SeedEvent> | Envelope<"error", ErrorPayload>;
490
637
  export declare const HOST_TO_BUS: MessageTypes<HostToBus>;
638
+ /** The message types a tap's port carries from the bus (ADR 0020, decision 3). @experimental */
639
+ export declare const BUS_TO_TAP: MessageTypes<BusToTap>;
640
+ /** The message types a tap's port carries to the bus. @experimental */
641
+ export declare const TAP_TO_BUS: MessageTypes<TapToBus>;
491
642
  export declare const BUS_TO_HOST: MessageTypes<BusToHost>;
492
643
  export declare const isHostToBus: (x: unknown) => x is HostToBus;
493
644
  export declare const isBusToHost: (x: unknown) => x is BusToHost;
645
+ /** A well-formed message from the bus on a tap's port. @experimental */
646
+ export declare const isBusToTap: (x: unknown) => x is BusToTap;
647
+ /** A well-formed message from the host on a tap's port. @experimental */
648
+ export declare const isTapToBus: (x: unknown) => x is TapToBus;
494
649
  /**
495
650
  * A Standard Schema V1 built by hand (ADR 0003, decision 6). Protocol depends
496
651
  * on nothing, so this is the structural subset of the interface that system
@@ -537,14 +692,17 @@ export declare const checks: {
537
692
  /** Any value. */
538
693
  any: Check;
539
694
  };
540
- /** The current location, as the kernel publishes it (ADR 0002). */
695
+ /** The host page's current location, as the kernel publishes it on each navigation. */
541
696
  export type RouteValue = {
542
- /** Absolute URL. */
697
+ /** The absolute URL. */
543
698
  href: string;
699
+ /** The URL's path, as `location.pathname` has it. */
544
700
  pathname: string;
545
701
  /** `pathname` relative to `basePath`, starting with `/`; `null` outside it. */
546
702
  path: string | null;
703
+ /** The query string, with its `?`, or `''`. */
547
704
  search: string;
705
+ /** The fragment, with its `#`, or `''`. */
548
706
  hash: string;
549
707
  /** `history.state` as is; `null` when it was too large for the bus (`route:state_dropped`). */
550
708
  state: unknown;
@@ -560,10 +718,16 @@ export declare const routeTopic: SystemTopicDef<RouteValue>;
560
718
  export declare const ROUTE_KEY = "current";
561
719
  /** Every system topic, built into the bus. */
562
720
  export declare const SYSTEM_TOPICS: readonly SystemTopicDef<any>[];
563
- /** A topic as `kernel.publish`, `kernel.subscribe` and `BusClient` take it. */
721
+ /**
722
+ * A topic as `kernel.publish`, `kernel.subscribe` and `BusClient` take it:
723
+ * any `topic()` from `@isoloop/bus` fits, and its schema types carry over.
724
+ */
564
725
  export type TopicRef<In = unknown, Out = In, RIn = never, ROut = RIn> = {
726
+ /** The topic's name. */
565
727
  readonly name: string;
728
+ /** Its schema's types. */
566
729
  readonly schema: SchemaTypes<In, Out>;
730
+ /** Its `reply` schema's types, for a requestable topic. */
567
731
  readonly reply?: SchemaTypes<RIn, ROut>;
568
732
  };
569
733
  /** The type-only part of a Standard Schema V1. */
@@ -579,19 +743,51 @@ export type SchemaTypes<In, Out> = {
579
743
  export type TypedRecord<T> = Omit<BusRecord, "value"> & {
580
744
  value: T;
581
745
  };
582
- /** The parts of a topic definition that make up its `TopicConfig`. */
746
+ /**
747
+ * Describes a requestable topic as a tool for agents.
748
+ * A `tool` field alone exposes nothing: the app's kernel config lists what
749
+ * agents may call (`agents.expose`). It stays on the host and isn't part of
750
+ * the `TopicConfig` the bus sees.
751
+ * @experimental
752
+ */
753
+ export type ToolSpec = {
754
+ /** A short human-readable name. The tool's name is always the topic's name. */
755
+ readonly title?: string;
756
+ /** What the tool does, for the agent choosing it. */
757
+ readonly description: string;
758
+ /** Required: `true` if a call changes nothing. Maps to `readOnlyHint` in WebMCP and MCP. */
759
+ readonly readOnly: boolean;
760
+ /** The call has effects the user should confirm. WebMCP `consequentialHint`, MCP `destructiveHint`. Default `false`. */
761
+ readonly consequential?: boolean;
762
+ /** The reply can carry third-party text. WebMCP `untrustedContentHint`. Default `false`. */
763
+ readonly untrustedContent?: boolean;
764
+ };
765
+ /** A topic as the host reads it from the contracts: any `topic()` from `@isoloop/bus` fits. */
583
766
  export type TopicShape = {
767
+ /** The topic's name. */
584
768
  readonly name: string;
769
+ /**
770
+ * The topic's Standard Schema. The host reads it only to make a tool's
771
+ * JSON Schema; it never validates with it.
772
+ */
773
+ readonly schema?: unknown;
774
+ /** How long it keeps its records. */
585
775
  readonly retention: Retention;
776
+ /** The largest value it takes, in bytes. Default 256 KiB. */
586
777
  readonly maxRecordBytes?: number;
778
+ /** `persistent` topics keep their records across reloads, on disk. Default `memory`. */
587
779
  readonly durability?: "memory" | "persistent";
780
+ /** The `reply` schema, for a requestable topic. */
588
781
  readonly reply?: unknown;
782
+ /** The topic it's seeded from, and whether it keeps following it. */
589
783
  readonly seed?: {
590
784
  readonly from: {
591
785
  readonly name: string;
592
786
  };
593
787
  readonly follow?: boolean;
594
788
  };
789
+ /** The topic as a tool for agents. The host keeps it; the bus never sees it. */
790
+ readonly tool?: ToolSpec;
595
791
  };
596
792
  /** What `KernelConfig.contracts.list` holds: a `contracts()` list, seen structurally. */
597
793
  export type ContractsList = {
@@ -605,4 +801,490 @@ export type ContractsList = {
605
801
  export declare function topicConfigOf(t: TopicShape): TopicConfig;
606
802
  /** `"0.4.2"` → `"0.4"`. Anything that isn't `major.minor[.patch…]` gives `undefined`. */
607
803
  export declare function majorMinor(version: string): string | undefined;
608
- export declare function compareVersions(a: string, b: string): number;
804
+ export declare function compareVersions(a: string, b: string): number;
805
+ /**
806
+ * The vendor `unchecked()` in `@isoloop/bus` gives its schemas.
807
+ *
808
+ * @internal
809
+ */
810
+ export declare const UNCHECKED_VENDOR = "isoloop/unchecked";
811
+ /**
812
+ * The Standard JSON Schema V1 interface (https://standardschema.dev/json-schema),
813
+ * vendored like the bus's `StandardSchemaV1` so Isoloop depends on no schema
814
+ * library (ADR 0003, decision 21; ADR 0018, decision 1). Zod ≥ 4.2 implements
815
+ * it. Copied from the spec; keep it in step with it. Only the parts Isoloop
816
+ * reads are typed: the `jsonSchema` converter beside `validate`, without the
817
+ * spec's `Input`/`Output` type parameters, which Isoloop doesn't read.
818
+ *
819
+ * @internal
820
+ */
821
+ export interface StandardJSONSchemaV1 {
822
+ readonly "~standard": StandardJSONSchemaV1.Props;
823
+ }
824
+ /** @internal */
825
+ export declare namespace StandardJSONSchemaV1 {
826
+ export interface Props<Input = unknown, Output = Input> {
827
+ readonly version: 1;
828
+ readonly vendor: string;
829
+ readonly types?: {
830
+ readonly input: Input;
831
+ readonly output: Output;
832
+ } | undefined;
833
+ /** Methods that make the input and output JSON Schema. */
834
+ readonly jsonSchema: Converter;
835
+ }
836
+ export interface Converter {
837
+ /** The input type as JSON Schema. May throw if the target isn't supported. */
838
+ readonly input: (options: Options) => Record<string, unknown>;
839
+ /** The output type as JSON Schema. May throw if the target isn't supported. */
840
+ readonly output: (options: Options) => Record<string, unknown>;
841
+ }
842
+ export type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string);
843
+ export interface Options {
844
+ readonly target: Target;
845
+ readonly libraryOptions?: Record<string, unknown> | undefined;
846
+ }
847
+ }
848
+ /**
849
+ * A JSON Schema document (draft 2020-12), as the schema library made it.
850
+ *
851
+ * @internal
852
+ */
853
+ export type JsonSchema = {
854
+ [key: string]: unknown;
855
+ };
856
+ /**
857
+ * A schema's JSON Schema, for what it accepts (`input`) and what it gives
858
+ * (`output`).
859
+ *
860
+ * @internal
861
+ */
862
+ export type JsonSchemaPair = {
863
+ readonly input: JsonSchema;
864
+ readonly output: JsonSchema;
865
+ };
866
+ /**
867
+ * Why a schema has no JSON Schema:
868
+ * - `unchecked`: it came from `unchecked()`, so there's nothing to describe;
869
+ * - `unsupported`: it doesn't implement `~standard.jsonSchema`;
870
+ * - `failed`: the converter threw (for example, a transform or a type JSON
871
+ * Schema can't express).
872
+ *
873
+ * @internal
874
+ */
875
+ export type NotExportableReason = "unchecked" | "unsupported" | "failed";
876
+ /**
877
+ * The result of {@link jsonSchemaOf}. Never throws; a failure is a value.
878
+ *
879
+ * @internal
880
+ */
881
+ export type JsonSchemaResult = ({
882
+ readonly ok: true;
883
+ } & JsonSchemaPair) | {
884
+ readonly ok: false;
885
+ readonly reason: NotExportableReason;
886
+ readonly message: string;
887
+ };
888
+ /**
889
+ * The JSON Schema target Isoloop uses everywhere (ADR 0003, decision 21).
890
+ *
891
+ * @internal
892
+ */
893
+ export declare const JSON_SCHEMA_TARGET = "draft-2020-12";
894
+ /**
895
+ * True if the schema implements Standard JSON Schema (`~standard.jsonSchema`).
896
+ *
897
+ * @internal
898
+ */
899
+ export declare function hasJsonSchema(schema: unknown): schema is StandardJSONSchemaV1;
900
+ /**
901
+ * Makes a schema's input and output JSON Schema (draft 2020-12) through the
902
+ * Standard JSON Schema interface. Never throws: an `unchecked()` schema, one
903
+ * without the interface, or a converter that throws gives `{ ok: false }`
904
+ * with the reason, so callers decide (`not_exposable` for the kernel, a flag
905
+ * for `isoloop contracts export`).
906
+ *
907
+ * @internal Used by the kernel's agent tools and `isoloop contracts export`.
908
+ */
909
+ export declare function jsonSchemaOf(schema: unknown): JsonSchemaResult;
910
+ /**
911
+ * A topic's JSON Schemas: its record schema, and its `reply` if it has one.
912
+ *
913
+ * @internal
914
+ */
915
+ export type TopicJsonSchemas = {
916
+ readonly schema: JsonSchemaPair;
917
+ readonly reply?: JsonSchemaPair;
918
+ };
919
+ /**
920
+ * The result of {@link topicJsonSchemas}. `part` says which schema failed.
921
+ *
922
+ * @internal
923
+ */
924
+ export type TopicJsonSchemasResult = ({
925
+ readonly ok: true;
926
+ } & TopicJsonSchemas) | {
927
+ readonly ok: false;
928
+ readonly topic: string;
929
+ readonly part: "schema" | "reply";
930
+ readonly reason: NotExportableReason;
931
+ /** Names the topic, e.g. "markets.quote.v1: reply is unchecked()". */
932
+ readonly message: string;
933
+ };
934
+ /**
935
+ * Makes a topic's JSON Schemas: the topic schema's input and output, and the
936
+ * `reply` schema's when it has one. A tool's input schema is `schema.input`;
937
+ * its output schema is `reply.output` (ADR 0018, decision 1). Never throws.
938
+ *
939
+ * @internal Used by the kernel's agent tools and `isoloop contracts export`.
940
+ */
941
+ export declare function topicJsonSchemas(def: {
942
+ readonly name: string;
943
+ readonly schema: unknown;
944
+ readonly reply?: unknown;
945
+ }): TopicJsonSchemasResult;
946
+ /**
947
+ * An exposed tool as the page sends it: `kernel.tools()` without `topic`.
948
+ * @internal
949
+ */
950
+ export type DevMcpTool = {
951
+ readonly name: string;
952
+ readonly title?: string;
953
+ readonly description: string;
954
+ readonly readOnly: boolean;
955
+ readonly consequential: boolean;
956
+ readonly untrustedContent: boolean;
957
+ readonly inputSchema: {
958
+ readonly [key: string]: unknown;
959
+ };
960
+ readonly outputSchema: {
961
+ readonly [key: string]: unknown;
962
+ };
963
+ readonly timeoutMs: number;
964
+ };
965
+ /** A call's answer: the reply, or the error's code and message. @internal */
966
+ export type DevMcpResult = {
967
+ readonly ok: true;
968
+ readonly value: unknown;
969
+ } | {
970
+ readonly ok: false;
971
+ /** A `BusError` code, or `unknown_tool` for a name the page doesn't expose. */
972
+ readonly code: string;
973
+ readonly message: string;
974
+ readonly issues?: readonly Issue[];
975
+ };
976
+ /** `hello`'s payload: the pairing token, the page's URL and title, and its tools. @internal */
977
+ export type DevMcpHello = {
978
+ readonly token: string;
979
+ readonly url: string;
980
+ readonly title?: string;
981
+ readonly tools: readonly DevMcpTool[];
982
+ /**
983
+ * The page answers `op` messages through `kernel.inspect()` (M4a task 8): the
984
+ * CLI then offers it the `isoloop_*` reads, and with `--allow-write` the
985
+ * writes. Absent: only the page's own tools.
986
+ */
987
+ readonly inspect?: boolean;
988
+ };
989
+ /** `welcome`'s payload: the page's id, which agents pass as `page`. @internal */
990
+ export type DevMcpWelcome = {
991
+ readonly page: string;
992
+ };
993
+ /** `call`'s payload: the tool to request and its input. @internal */
994
+ export type DevMcpCall = {
995
+ readonly name: string;
996
+ readonly input: unknown;
997
+ };
998
+ /**
999
+ * Page → CLI: `hello` first, then a `result` per call (`re` = the call's `id`).
1000
+ * @internal
1001
+ */
1002
+ export type PageToCli = Envelope<"hello", DevMcpHello> | Envelope<"result", DevMcpResult>;
1003
+ /**
1004
+ * CLI → page: `welcome` once paired; `call` (an app tool) or `op` (one of the
1005
+ * dev MCP's own tools), each with an `id`; `cancel`, `re` = a call's `id`,
1006
+ * when the agent cancelled it (the page aborts its signal).
1007
+ * @internal
1008
+ */
1009
+ export type CliToPage = Envelope<"welcome", DevMcpWelcome> | Envelope<"call", DevMcpCall> | Envelope<"op", DevMcpOp> | Envelope<"cancel", DevMcpCancel>;
1010
+ /**
1011
+ * `op`'s payload: one of the dev MCP's own tools, answered by the page from
1012
+ * `kernel.inspect()` (ADR 0020) or the kernel (M4a decision 12). The page
1013
+ * answers with a `result`, `re` = the op's `id`. The writes (`restart`,
1014
+ * `kill`, `block`, `publish`, `request`) are sent only with `--allow-write`.
1015
+ * @internal
1016
+ */
1017
+ export type DevMcpOp = {
1018
+ readonly op: "isolates";
1019
+ } | {
1020
+ readonly op: "topics";
1021
+ } | {
1022
+ readonly op: "records";
1023
+ readonly topic: string;
1024
+ readonly last: number;
1025
+ } | {
1026
+ readonly op: "tap";
1027
+ readonly topics: readonly string[];
1028
+ readonly ms: number;
1029
+ readonly max: number;
1030
+ } | {
1031
+ readonly op: "events";
1032
+ readonly last: number;
1033
+ } | {
1034
+ readonly op: "restart" | "kill";
1035
+ readonly id: string;
1036
+ } | {
1037
+ readonly op: "block";
1038
+ readonly id: string;
1039
+ readonly ms: number;
1040
+ } | {
1041
+ readonly op: "publish";
1042
+ readonly topic: string;
1043
+ readonly key?: string;
1044
+ readonly value: unknown;
1045
+ } | {
1046
+ readonly op: "request";
1047
+ readonly topic: string;
1048
+ readonly key?: string;
1049
+ readonly value: unknown;
1050
+ readonly timeoutMs: number;
1051
+ };
1052
+ /** `DevMcpOp['op']`, as a list. @internal */
1053
+ export declare const DEV_MCP_OPS: readonly DevMcpOp["op"][];
1054
+ /** `cancel`'s payload: empty. @internal */
1055
+ export type DevMcpCancel = Record<string, never>;
1056
+ /** @internal */
1057
+ export declare const PAGE_TO_CLI: MessageTypes<PageToCli>;
1058
+ /** @internal */
1059
+ export declare const CLI_TO_PAGE: MessageTypes<CliToPage>;
1060
+ /** @internal */
1061
+ export declare const isPageToCli: (x: unknown) => x is PageToCli;
1062
+ /** @internal */
1063
+ export declare const isCliToPage: (x: unknown) => x is CliToPage;
1064
+ /**
1065
+ * WebSocket close codes the CLI uses (4000–4999 are the application's).
1066
+ * @internal
1067
+ */
1068
+ export declare const DEV_MCP_CLOSE: {
1069
+ /** The first message wasn't a well-formed `hello`, or its `v` differs. */
1070
+ readonly badHello: 4400;
1071
+ /** The token didn't match. */
1072
+ readonly badToken: 4401;
1073
+ /** The CLI is shutting down. */
1074
+ readonly shutdown: 4000;
1075
+ };
1076
+ /** The CLI's WebSocket port when `--port` isn't given. @internal */
1077
+ export declare const DEV_MCP_PORT = 4317;
1078
+ /**
1079
+ * One isolate in the feed, as `kernel.isolates()` has it.
1080
+ * `state` and `reason` are the kernel's `IsolateState` and `CrashReason`,
1081
+ * typed as strings here so a reader built against an older list still reads
1082
+ * a newer kernel's values.
1083
+ * @experimental
1084
+ */
1085
+ export type InspectIsolate = {
1086
+ /** The isolate's id. */
1087
+ id: string;
1088
+ /** Its `IsolateState`. */
1089
+ state: string;
1090
+ /** The pool it runs in; absent for a worker of its own. */
1091
+ pool?: string;
1092
+ /** `performance.now()` on the host when its last beat arrived. */
1093
+ lastBeatAt: number;
1094
+ /** How late its worker's last beat fired, past the heartbeat interval, in ms. */
1095
+ lagMs: number;
1096
+ /** Restarts after a crash since it was spawned. */
1097
+ restarts: number;
1098
+ /** The last crash's `CrashReason`, while restarting or failed. */
1099
+ reason?: string;
1100
+ /** The last crash's message, while restarting or failed. */
1101
+ error?: string;
1102
+ /** Compositor figures for a visual isolate (`SurfaceStats`). */
1103
+ surface?: {
1104
+ queued: number;
1105
+ applied: number;
1106
+ rejected: number;
1107
+ dropped: number;
1108
+ lastFrameMs: number;
1109
+ };
1110
+ /** Messages from its worker dropped because their version or type was unknown. */
1111
+ dropped: number;
1112
+ /** Open `ctx.keepAwake()` holds, from the last beat. */
1113
+ holds?: {
1114
+ ageMs: number;
1115
+ stack?: string;
1116
+ }[];
1117
+ /** Milliseconds its worker spent running its code during the last beat's interval. */
1118
+ busyMs?: number;
1119
+ /**
1120
+ * Its worker's memory, from the host's last measurement. Absent when the page isn't cross-origin isolated, in engines without
1121
+ * `performance.measureUserAgentSpecificMemory()` (Firefox, Safari), and
1122
+ * before the first measurement.
1123
+ */
1124
+ memory?: InspectMemory;
1125
+ };
1126
+ /**
1127
+ * One isolate's memory: the bytes the browser attributes to its worker. Coarse, and seconds old: Chromium answers a
1128
+ * measurement at its next garbage collection. A reader shows its age and
1129
+ * labels it "Chromium, cross-origin isolated".
1130
+ * @experimental
1131
+ */
1132
+ export type InspectMemory = {
1133
+ /** The bytes the browser attributes to the worker. */
1134
+ bytes: number;
1135
+ /** `performance.now()` on the host when the measurement came back. */
1136
+ at: number;
1137
+ /** True for a pool member: the figure is the whole pool's worker, shared by every member. */
1138
+ shared?: true;
1139
+ };
1140
+ /** One pool in the feed, as `kernel.pools()` has it. @experimental */
1141
+ export type InspectPool = {
1142
+ /** The pool's name. */
1143
+ name: string;
1144
+ /** Isolates naming this pool, not stopped, in spawn order. */
1145
+ members: string[];
1146
+ /** True while the pool's worker runs. */
1147
+ running: boolean;
1148
+ /** The union of its members' grants: what the pool can do in effect. */
1149
+ grants: Grants;
1150
+ /** True when a member has a surface: the visual members share one document. */
1151
+ sharesDocument: boolean;
1152
+ /** When `sharesDocument`: what that means for the members, in a sentence for people. */
1153
+ warning?: string;
1154
+ };
1155
+ /**
1156
+ * One kernel event, at once or from the ring buffer. `event` is a `KernelEvents` name (`isolate:crash`, `bus:restart`, …)
1157
+ * and `data` its payload. Beats and bus metrics come as their own messages.
1158
+ * @experimental
1159
+ */
1160
+ export type InspectEvent = {
1161
+ /** `performance.now()` on the host when it happened. */
1162
+ at: number;
1163
+ /** The event's name, a `KernelEvents` key. */
1164
+ event: string;
1165
+ /** The event's data, as `kernel.on` gives it. */
1166
+ data: Record<string, unknown>;
1167
+ };
1168
+ /** One isolate's latest beat in a `beats` message. @experimental */
1169
+ export type InspectBeat = {
1170
+ /** The isolate's id. */
1171
+ id: string;
1172
+ /** Its pool, when it's a pool member. */
1173
+ pool?: string;
1174
+ /** How late its worker's beat fired, past the heartbeat interval, in ms. */
1175
+ lagMs: number;
1176
+ /** Milliseconds its worker spent running its code during the beat's interval. */
1177
+ busyMs?: number;
1178
+ /** `performance.now()` on the host when it arrived. */
1179
+ at: number;
1180
+ };
1181
+ /**
1182
+ * The bus as the feed sees it. `state` is the bus supervisor's state
1183
+ * (`running`, `restarting`, `failed`, …), or `none` without contracts.
1184
+ * `restarts` counts bus restarts since the kernel started.
1185
+ * @experimental
1186
+ */
1187
+ export type InspectBus = {
1188
+ /** The bus supervisor's state, or `none`. */
1189
+ state: string;
1190
+ /** Bus restarts since the kernel started. */
1191
+ restarts: number;
1192
+ /** The last `bus:metrics`, once one has arrived. */
1193
+ metrics?: BusMetrics;
1194
+ };
1195
+ /** What a reader gets first: the feed's state at one moment. @experimental */
1196
+ export type InspectSnapshot = {
1197
+ /** `performance.now()` on the host when it was taken. */
1198
+ at: number;
1199
+ /** Every isolate not stopped. */
1200
+ isolates: InspectIsolate[];
1201
+ /** The named pools that have members. */
1202
+ pools: InspectPool[];
1203
+ /** The bus. */
1204
+ bus: InspectBus;
1205
+ /** The ring buffer: the last 200 events since the kernel started, oldest first. */
1206
+ events: InspectEvent[];
1207
+ };
1208
+ /**
1209
+ * The feed's messages, each `{ v, t, p }`: `t` names it and `p` carries it.
1210
+ * - `snapshot`, on request: an isolate's `ctx.inspector.snapshot()` gets it
1211
+ * over its `inspect` port, as the reply to its `snapshot` call;
1212
+ * - `event`, a kernel event as it happens;
1213
+ * - `beats`, each isolate's latest beat, coalesced to about one a second;
1214
+ * - `metrics`, the latest `bus:metrics`, at most one a second;
1215
+ * - `memory`, each isolate's memory after a measurement, at most one every
1216
+ * 5 s, and only where the page is cross-origin isolated.
1217
+ * @experimental
1218
+ */
1219
+ export type InspectMessage = Envelope<"snapshot", InspectSnapshot> | Envelope<"event", InspectEvent> | Envelope<"beats", {
1220
+ at: number;
1221
+ beats: InspectBeat[];
1222
+ }> | Envelope<"metrics", BusMetrics> | Envelope<"memory", {
1223
+ at: number;
1224
+ isolates: {
1225
+ id: string;
1226
+ memory: InspectMemory;
1227
+ }[];
1228
+ }>;
1229
+ /** @experimental */
1230
+ export declare const INSPECT_MESSAGES: MessageTypes<InspectMessage>;
1231
+ /**
1232
+ * True for an envelope of a feed message this build knows. A reader drops
1233
+ * anything else, which is how it ignores message types added later.
1234
+ * @experimental
1235
+ */
1236
+ export declare const isInspectMessage: (x: unknown) => x is InspectMessage;
1237
+ /** How many events the kernel keeps for late readers (ADR 0020, decision 5). */
1238
+ export declare const INSPECT_RING_SIZE = 200;
1239
+ /** How often beats and bus metrics are coalesced (ADR 0020, decision 2). */
1240
+ export declare const INSPECT_COALESCE_MS = 1e3;
1241
+ /** The shortest time between two memory measurements (ADR 0020, decision 4). */
1242
+ export declare const INSPECT_MEMORY_MS = 5e3;
1243
+ /**
1244
+ * One record from a tap or a read: its value cut to a 2 KB preview, with its
1245
+ * full size.
1246
+ * @experimental
1247
+ */
1248
+ export type InspectRecord = RecordPreview;
1249
+ /** What an isolate asks over its `inspect` port (ADR 0020, decision 6). @experimental */
1250
+ export type InspectControl = "restart" | "kill" | "block";
1251
+ /**
1252
+ * The `inspect` port: isolate → host (ADR 0020, decision 6). Each message with
1253
+ * an `id` gets a `result` (`snapshot` gets a `snapshot`) with `re` set to it.
1254
+ * - `listen` / `unlisten`: start and stop the feed's `event`, `beats` and
1255
+ * `metrics` messages on the port;
1256
+ * - `snapshot`: one `InspectSnapshot`;
1257
+ * - `records`: the last `last` records of `topic` (at most 100), as
1258
+ * `InspectRecord`s in the result's `value`;
1259
+ * - `tap` / `untap`: copy matching records onto the port as `record`
1260
+ * messages, `untap`'s `re` naming the tap's `id`;
1261
+ * - `control`: restart, kill or block (`ms`, at most 10 s) an isolate.
1262
+ * @experimental
1263
+ */
1264
+ export type IsolateToInspect = Envelope<"listen", Record<string, never>> | Envelope<"unlisten", Record<string, never>> | Envelope<"snapshot", Record<string, never>> | Envelope<"records", {
1265
+ topic: string;
1266
+ last: number;
1267
+ }> | Envelope<"tap", {
1268
+ topics: string[];
1269
+ maxPerSec?: number;
1270
+ }> | Envelope<"untap", Record<string, never>> | Envelope<"control", {
1271
+ action: InspectControl;
1272
+ id: string;
1273
+ ms?: number;
1274
+ }>;
1275
+ /**
1276
+ * The `inspect` port: host → isolate. The feed's own messages, a call's
1277
+ * `result`, and a tap's `record` and `skipped` (with `re` naming the tap).
1278
+ * @experimental
1279
+ */
1280
+ export type InspectToIsolate = InspectMessage | Envelope<"result", CallResult> | Envelope<"record", InspectRecord> | Envelope<"skipped", {
1281
+ count: number;
1282
+ }>;
1283
+ /** @experimental */
1284
+ export declare const ISOLATE_TO_INSPECT: MessageTypes<IsolateToInspect>;
1285
+ /** @experimental */
1286
+ export declare const INSPECT_TO_ISOLATE: MessageTypes<InspectToIsolate>;
1287
+ /** @experimental */
1288
+ export declare const isIsolateToInspect: (x: unknown) => x is IsolateToInspect;
1289
+ /** @experimental */
1290
+ export declare const isInspectToIsolate: (x: unknown) => x is InspectToIsolate;
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ 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
@@ -28,7 +28,7 @@ function assertNever(x, message = "Unexpected value") {
28
28
  throw new Error(`${message}: ${JSON.stringify(x)}`);
29
29
  }
30
30
  // src/errors.ts
31
- /** Every error code on the wire (design §3, §4.7, §6.1, §6.3; ADRs 0002, 0003, 0007, 0008). */
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",
@@ -86,12 +89,16 @@ function matchAny(patterns, topic) {
86
89
  return patterns.some((p) => matchTopic(p, topic));
87
90
  }
88
91
  // src/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,
@@ -104,6 +111,25 @@ const ISOLATE_TO_HOST = {
104
111
  const isHostToIsolate = envelopeGuard(HOST_TO_ISOLATE);
105
112
  const isIsolateToHost = envelopeGuard(ISOLATE_TO_HOST);
106
113
  // src/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,
@@ -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();
@@ -226,8 +279,11 @@ function createCommitter(o) {
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";
@@ -236,14 +292,30 @@ var BusError = class extends Error {
236
292
  }
237
293
  };
238
294
  // src/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,6 +327,10 @@ const BUS_TO_HOST = {
255
327
  };
256
328
  const isHostToBus = envelopeGuard(HOST_TO_BUS);
257
329
  const isBusToHost = envelopeGuard(BUS_TO_HOST);
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);
258
334
  // src/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) {
@@ -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/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/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/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.0",
4
- "description": "Wire protocol types and guards shared by every Isoloop package.",
3
+ "version": "0.1.0-next.10",
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,