@mostra/protocol 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import "../spec.js";
@@ -0,0 +1,68 @@
1
+ //#region src/diagnostics/codes/host-core.ts
2
+ /** Their catalog entries. */
3
+ const coreHostDiagnostics = {
4
+ MOSTRA_HOST_MALFORMED: {
5
+ severity: "error",
6
+ phase: "host",
7
+ title: "Malformed protocol message",
8
+ hint: "Send each message as one line of JSON holding a single JSON-RPC 2.0 request or notification.",
9
+ docs: {
10
+ explanation: "Every message on a Mostra connection is one line of JSON with one JSON-RPC 2.0 object. This code means a line wasn't valid JSON, wasn't a JSON-RPC 2.0 request or response, or was a batch (a JSON array), which revision `2026-10-10` doesn't accept. A client also reports it when a response doesn't match the method's result schema.",
11
+ fix: "Encode one request per line with `\"jsonrpc\": \"2.0\"`, a `method`, an `id` for requests, and `params` as an object. Send several requests as separate lines instead of a batch."
12
+ }
13
+ },
14
+ MOSTRA_HOST_METHOD_UNKNOWN: {
15
+ severity: "error",
16
+ phase: "host",
17
+ title: "Unknown protocol method",
18
+ hint: "Call only the methods listed in `capabilities.methods` of the `mostra/initialize` result.",
19
+ docs: {
20
+ explanation: "The instance doesn't serve the method that was called. Either the name is misspelled, or the client is newer than the instance and calls a method the instance's release doesn't have.",
21
+ fix: "Check the method name against INTERFACES §6, and against `capabilities.methods` in the `mostra/initialize` result, which lists every method this instance serves. Upgrade the instance if the client needs a newer method."
22
+ }
23
+ },
24
+ MOSTRA_HOST_INVALID_PARAMS: {
25
+ severity: "error",
26
+ phase: "host",
27
+ title: "Invalid method params",
28
+ hint: "Fix the params named in the message so they match the method's schema.",
29
+ docs: {
30
+ explanation: "The request's `params` don't match the method's published schema: a required field is missing, a value has the wrong type, or a value is outside its allowed range. The message names the first problem found.",
31
+ fix: "Compare the request with the method's schema in `@mostra/protocol` (or the published JSON Schema) and correct the field named in the message."
32
+ }
33
+ },
34
+ MOSTRA_HOST_INTERNAL_ERROR: {
35
+ severity: "error",
36
+ phase: "host",
37
+ title: "Unexpected failure in the instance",
38
+ hint: "Retry the request with the same request ID; if it fails again, report it with the instance's log.",
39
+ docs: {
40
+ explanation: "The instance failed while handling the request, for a reason that isn't one of its known conditions. Durable state is unaffected: a request is acknowledged only after its ledger transaction commits. The details are in the instance's log (`logs/supervisor.log` in the home), not in the response.",
41
+ fix: "Retry the request with the same request ID; retries are idempotent. If the failure repeats, report it with the relevant lines of `logs/supervisor.log`."
42
+ }
43
+ },
44
+ MOSTRA_HOST_CONNECTION_CLOSED: {
45
+ severity: "error",
46
+ phase: "host",
47
+ title: "Connection closed",
48
+ hint: "Reconnect, then retry the request with the same request ID.",
49
+ docs: {
50
+ explanation: "The connection to the other side closed before a response arrived, for example because the instance exited or restarted. The request may or may not have taken effect.",
51
+ fix: "Reconnect and send `mostra/initialize` again, then retry the request with the same request ID. Mutating methods are idempotent by request ID, so a retry never applies twice."
52
+ }
53
+ },
54
+ MOSTRA_HOST_TIMEOUT: {
55
+ severity: "error",
56
+ phase: "host",
57
+ title: "Request timed out",
58
+ hint: "Retry the request with the same request ID, or allow it more time.",
59
+ docs: {
60
+ explanation: "No response arrived within the time the caller allowed. The other side may still be working on the request, and it may still take effect.",
61
+ fix: "Retry with the same request ID, which returns the recorded result if the first attempt completed. Allow a longer timeout for slow operations."
62
+ }
63
+ }
64
+ };
65
+ //#endregion
66
+ export { coreHostDiagnostics };
67
+
68
+ //# sourceMappingURL=host-core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-core.js","names":[],"sources":["../../../src/diagnostics/codes/host-core.ts"],"sourcesContent":["/**\n * The HOST-area codes the JSON-RPC core raises itself (D83): malformed messages, unknown methods,\n * invalid params, internal errors, closed connections and timeouts. They are defined here once\n * and spread into the HOST catalog, so a browser bundle that imports the core (the bridge,\n * `@mostra/react`, the shell) carries these six entries, not the whole area's text: a new HOST\n * code no longer grows them (#17).\n */\nimport type { AreaCatalog } from \"../spec.ts\";\n\n/** The codes the JSON-RPC core raises. */\nexport type CoreHostDiagnosticCode =\n | \"MOSTRA_HOST_MALFORMED\"\n | \"MOSTRA_HOST_METHOD_UNKNOWN\"\n | \"MOSTRA_HOST_INVALID_PARAMS\"\n | \"MOSTRA_HOST_INTERNAL_ERROR\"\n | \"MOSTRA_HOST_CONNECTION_CLOSED\"\n | \"MOSTRA_HOST_TIMEOUT\";\n\n/** Their catalog entries. */\nexport const coreHostDiagnostics: AreaCatalog<CoreHostDiagnosticCode> = {\n MOSTRA_HOST_MALFORMED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Malformed protocol message\",\n hint: \"Send each message as one line of JSON holding a single JSON-RPC 2.0 request or notification.\",\n docs: {\n explanation:\n \"Every message on a Mostra connection is one line of JSON with one JSON-RPC 2.0 object. This code means a line wasn't valid JSON, wasn't a JSON-RPC 2.0 request or response, or was a batch (a JSON array), which revision `2026-10-10` doesn't accept. A client also reports it when a response doesn't match the method's result schema.\",\n fix: 'Encode one request per line with `\"jsonrpc\": \"2.0\"`, a `method`, an `id` for requests, and `params` as an object. Send several requests as separate lines instead of a batch.',\n },\n },\n MOSTRA_HOST_METHOD_UNKNOWN: {\n severity: \"error\",\n phase: \"host\",\n title: \"Unknown protocol method\",\n hint: \"Call only the methods listed in `capabilities.methods` of the `mostra/initialize` result.\",\n docs: {\n explanation:\n \"The instance doesn't serve the method that was called. Either the name is misspelled, or the client is newer than the instance and calls a method the instance's release doesn't have.\",\n fix: \"Check the method name against INTERFACES \\u00a76, and against `capabilities.methods` in the `mostra/initialize` result, which lists every method this instance serves. Upgrade the instance if the client needs a newer method.\",\n },\n },\n MOSTRA_HOST_INVALID_PARAMS: {\n severity: \"error\",\n phase: \"host\",\n title: \"Invalid method params\",\n hint: \"Fix the params named in the message so they match the method's schema.\",\n docs: {\n explanation:\n \"The request's `params` don't match the method's published schema: a required field is missing, a value has the wrong type, or a value is outside its allowed range. The message names the first problem found.\",\n fix: \"Compare the request with the method's schema in `@mostra/protocol` (or the published JSON Schema) and correct the field named in the message.\",\n },\n },\n MOSTRA_HOST_INTERNAL_ERROR: {\n severity: \"error\",\n phase: \"host\",\n title: \"Unexpected failure in the instance\",\n hint: \"Retry the request with the same request ID; if it fails again, report it with the instance's log.\",\n docs: {\n explanation:\n \"The instance failed while handling the request, for a reason that isn't one of its known conditions. Durable state is unaffected: a request is acknowledged only after its ledger transaction commits. The details are in the instance's log (`logs/supervisor.log` in the home), not in the response.\",\n fix: \"Retry the request with the same request ID; retries are idempotent. If the failure repeats, report it with the relevant lines of `logs/supervisor.log`.\",\n },\n },\n MOSTRA_HOST_CONNECTION_CLOSED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Connection closed\",\n hint: \"Reconnect, then retry the request with the same request ID.\",\n docs: {\n explanation:\n \"The connection to the other side closed before a response arrived, for example because the instance exited or restarted. The request may or may not have taken effect.\",\n fix: \"Reconnect and send `mostra/initialize` again, then retry the request with the same request ID. Mutating methods are idempotent by request ID, so a retry never applies twice.\",\n },\n },\n MOSTRA_HOST_TIMEOUT: {\n severity: \"error\",\n phase: \"host\",\n title: \"Request timed out\",\n hint: \"Retry the request with the same request ID, or allow it more time.\",\n docs: {\n explanation:\n \"No response arrived within the time the caller allowed. The other side may still be working on the request, and it may still take effect.\",\n fix: \"Retry with the same request ID, which returns the recorded result if the first attempt completed. Allow a longer timeout for slow operations.\",\n },\n },\n};\n"],"mappings":";;AAmBA,MAAa,sBAA2D;CACtE,uBAAuB;EACrB,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,4BAA4B;EAC1B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,4BAA4B;EAC1B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,4BAA4B;EAC1B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,+BAA+B;EAC7B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,qBAAqB;EACnB,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/diagnostics/codes/host.ts"],"mappings":";;;qBAMa;;YAqBD,6BAA6B"}
1
+ {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/diagnostics/codes/host.ts"],"mappings":";;;qBAOa;;YAqBD,6BAA6B"}
@@ -1,3 +1,4 @@
1
+ import { coreHostDiagnostics } from "./host-core.js";
1
2
  //#region src/diagnostics/codes/host.ts
2
3
  /** The codes of the HOST area, in the order they were added. */
3
4
  const hostDiagnosticCodes = [
@@ -18,8 +19,12 @@ const hostDiagnosticCodes = [
18
19
  "MOSTRA_HOST_MESSAGE_TOO_LARGE",
19
20
  "MOSTRA_HOST_IDENTITY_UNAVAILABLE"
20
21
  ];
21
- /** The HOST area's catalog entries. */
22
+ /**
23
+ * The HOST area's catalog entries. The codes the JSON-RPC core raises live in `host-core.ts`, so
24
+ * browser bundles carry only theirs (#17).
25
+ */
22
26
  const hostDiagnostics = {
27
+ ...coreHostDiagnostics,
23
28
  MOSTRA_HOST_REVISION_UNSUPPORTED: {
24
29
  severity: "error",
25
30
  phase: "host",
@@ -30,46 +35,6 @@ const hostDiagnostics = {
30
35
  fix: "Restart the daemon so it runs the same release as the client: `mostra daemon restart`. Durable state survives the restart, and open views reconnect. A host that embeds Mostra updates its pinned Mostra runtime or its host library until both support a common revision."
31
36
  }
32
37
  },
33
- MOSTRA_HOST_MALFORMED: {
34
- severity: "error",
35
- phase: "host",
36
- title: "Malformed protocol message",
37
- hint: "Send each message as one line of JSON holding a single JSON-RPC 2.0 request or notification.",
38
- docs: {
39
- explanation: "Every message on a Mostra connection is one line of JSON with one JSON-RPC 2.0 object. This code means a line wasn't valid JSON, wasn't a JSON-RPC 2.0 request or response, or was a batch (a JSON array), which revision `2026-10-10` doesn't accept. A client also reports it when a response doesn't match the method's result schema.",
40
- fix: "Encode one request per line with `\"jsonrpc\": \"2.0\"`, a `method`, an `id` for requests, and `params` as an object. Send several requests as separate lines instead of a batch."
41
- }
42
- },
43
- MOSTRA_HOST_METHOD_UNKNOWN: {
44
- severity: "error",
45
- phase: "host",
46
- title: "Unknown protocol method",
47
- hint: "Call only the methods listed in `capabilities.methods` of the `mostra/initialize` result.",
48
- docs: {
49
- explanation: "The instance doesn't serve the method that was called. Either the name is misspelled, or the client is newer than the instance and calls a method the instance's release doesn't have.",
50
- fix: "Check the method name against INTERFACES §6, and against `capabilities.methods` in the `mostra/initialize` result, which lists every method this instance serves. Upgrade the instance if the client needs a newer method."
51
- }
52
- },
53
- MOSTRA_HOST_INVALID_PARAMS: {
54
- severity: "error",
55
- phase: "host",
56
- title: "Invalid method params",
57
- hint: "Fix the params named in the message so they match the method's schema.",
58
- docs: {
59
- explanation: "The request's `params` don't match the method's published schema: a required field is missing, a value has the wrong type, or a value is outside its allowed range. The message names the first problem found.",
60
- fix: "Compare the request with the method's schema in `@mostra/protocol` (or the published JSON Schema) and correct the field named in the message."
61
- }
62
- },
63
- MOSTRA_HOST_INTERNAL_ERROR: {
64
- severity: "error",
65
- phase: "host",
66
- title: "Unexpected failure in the instance",
67
- hint: "Retry the request with the same request ID; if it fails again, report it with the instance's log.",
68
- docs: {
69
- explanation: "The instance failed while handling the request, for a reason that isn't one of its known conditions. Durable state is unaffected: a request is acknowledged only after its ledger transaction commits. The details are in the instance's log (`logs/supervisor.log` in the home), not in the response.",
70
- fix: "Retry the request with the same request ID; retries are idempotent. If the failure repeats, report it with the relevant lines of `logs/supervisor.log`."
71
- }
72
- },
73
38
  MOSTRA_HOST_INITIALIZE_ORDER: {
74
39
  severity: "error",
75
40
  phase: "host",
@@ -90,26 +55,6 @@ const hostDiagnostics = {
90
55
  fix: "Register only the ports listed in `capabilities.ports` of the `mostra/initialize` result. If the host needs the port, upgrade the instance to a release that supports it."
91
56
  }
92
57
  },
93
- MOSTRA_HOST_CONNECTION_CLOSED: {
94
- severity: "error",
95
- phase: "host",
96
- title: "Connection closed",
97
- hint: "Reconnect, then retry the request with the same request ID.",
98
- docs: {
99
- explanation: "The connection to the other side closed before a response arrived, for example because the instance exited or restarted. The request may or may not have taken effect.",
100
- fix: "Reconnect and send `mostra/initialize` again, then retry the request with the same request ID. Mutating methods are idempotent by request ID, so a retry never applies twice."
101
- }
102
- },
103
- MOSTRA_HOST_TIMEOUT: {
104
- severity: "error",
105
- phase: "host",
106
- title: "Request timed out",
107
- hint: "Retry the request with the same request ID, or allow it more time.",
108
- docs: {
109
- explanation: "No response arrived within the time the caller allowed. The other side may still be working on the request, and it may still take effect.",
110
- fix: "Retry with the same request ID, which returns the recorded result if the first attempt completed. Allow a longer timeout for slow operations."
111
- }
112
- },
113
58
  MOSTRA_HOST_SHUTDOWN_REFUSED: {
114
59
  severity: "error",
115
60
  phase: "host",
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","names":[],"sources":["../../../src/diagnostics/codes/host.ts"],"sourcesContent":["/**\n * Diagnostic codes of the HOST area: the host protocol between clients and an instance.\n */\nimport type { AreaCatalog } from \"../spec.ts\";\n\n/** The codes of the HOST area, in the order they were added. */\nexport const hostDiagnosticCodes = [\n \"MOSTRA_HOST_REVISION_UNSUPPORTED\",\n \"MOSTRA_HOST_MALFORMED\",\n \"MOSTRA_HOST_METHOD_UNKNOWN\",\n \"MOSTRA_HOST_INVALID_PARAMS\",\n \"MOSTRA_HOST_INTERNAL_ERROR\",\n \"MOSTRA_HOST_INITIALIZE_ORDER\",\n \"MOSTRA_HOST_PORT_UNSUPPORTED\",\n \"MOSTRA_HOST_CONNECTION_CLOSED\",\n \"MOSTRA_HOST_TIMEOUT\",\n \"MOSTRA_HOST_SHUTDOWN_REFUSED\",\n \"MOSTRA_HOST_REQUEST_ID_REUSED\",\n \"MOSTRA_HOST_CURSOR_COMPACTED\",\n \"MOSTRA_HOST_SUBSCRIPTION_UNKNOWN\",\n \"MOSTRA_HOST_NOTIFICATION_UNSUPPORTED\",\n \"MOSTRA_HOST_MESSAGE_TOO_LARGE\",\n \"MOSTRA_HOST_IDENTITY_UNAVAILABLE\",\n // gen:codes\n] as const;\n\n/** The codes of the HOST area. */\nexport type HostDiagnosticCode = (typeof hostDiagnosticCodes)[number];\n\n/** The HOST area's catalog entries. */\nexport const hostDiagnostics: AreaCatalog<HostDiagnosticCode> = {\n MOSTRA_HOST_REVISION_UNSUPPORTED: {\n severity: \"error\",\n phase: \"host\",\n title: \"No common host protocol revision\",\n hint: \"Run the client and the instance from the same Mostra release, for example with `mostra daemon restart`.\",\n docs: {\n explanation:\n \"A client and a Mostra instance agree on a host protocol revision when they connect (`mostra/initialize`). The client offers the revisions it speaks, and the instance picks the newest one it also supports. This code means the two lists have nothing in common, usually because the client and the running daemon come from Mostra releases far apart.\",\n fix: \"Restart the daemon so it runs the same release as the client: `mostra daemon restart`. Durable state survives the restart, and open views reconnect. A host that embeds Mostra updates its pinned Mostra runtime or its host library until both support a common revision.\",\n },\n },\n MOSTRA_HOST_MALFORMED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Malformed protocol message\",\n hint: \"Send each message as one line of JSON holding a single JSON-RPC 2.0 request or notification.\",\n docs: {\n explanation:\n \"Every message on a Mostra connection is one line of JSON with one JSON-RPC 2.0 object. This code means a line wasn't valid JSON, wasn't a JSON-RPC 2.0 request or response, or was a batch (a JSON array), which revision `2026-10-10` doesn't accept. A client also reports it when a response doesn't match the method's result schema.\",\n fix: 'Encode one request per line with `\"jsonrpc\": \"2.0\"`, a `method`, an `id` for requests, and `params` as an object. Send several requests as separate lines instead of a batch.',\n },\n },\n MOSTRA_HOST_METHOD_UNKNOWN: {\n severity: \"error\",\n phase: \"host\",\n title: \"Unknown protocol method\",\n hint: \"Call only the methods listed in `capabilities.methods` of the `mostra/initialize` result.\",\n docs: {\n explanation:\n \"The instance doesn't serve the method that was called. Either the name is misspelled, or the client is newer than the instance and calls a method the instance's release doesn't have.\",\n fix: \"Check the method name against INTERFACES \\u00a76, and against `capabilities.methods` in the `mostra/initialize` result, which lists every method this instance serves. Upgrade the instance if the client needs a newer method.\",\n },\n },\n MOSTRA_HOST_INVALID_PARAMS: {\n severity: \"error\",\n phase: \"host\",\n title: \"Invalid method params\",\n hint: \"Fix the params named in the message so they match the method's schema.\",\n docs: {\n explanation:\n \"The request's `params` don't match the method's published schema: a required field is missing, a value has the wrong type, or a value is outside its allowed range. The message names the first problem found.\",\n fix: \"Compare the request with the method's schema in `@mostra/protocol` (or the published JSON Schema) and correct the field named in the message.\",\n },\n },\n MOSTRA_HOST_INTERNAL_ERROR: {\n severity: \"error\",\n phase: \"host\",\n title: \"Unexpected failure in the instance\",\n hint: \"Retry the request with the same request ID; if it fails again, report it with the instance's log.\",\n docs: {\n explanation:\n \"The instance failed while handling the request, for a reason that isn't one of its known conditions. Durable state is unaffected: a request is acknowledged only after its ledger transaction commits. The details are in the instance's log (`logs/supervisor.log` in the home), not in the response.\",\n fix: \"Retry the request with the same request ID; retries are idempotent. If the failure repeats, report it with the relevant lines of `logs/supervisor.log`.\",\n },\n },\n MOSTRA_HOST_INITIALIZE_ORDER: {\n severity: \"error\",\n phase: \"host\",\n title: \"Initialize first, and only once\",\n hint: \"Send `mostra/initialize` as the first request on the connection, and only once.\",\n docs: {\n explanation:\n \"Every connection starts with `mostra/initialize`, which agrees the protocol revision and registers the client's ports. The instance received another request before it, or a second `mostra/initialize` on the same connection.\",\n fix: \"Send `mostra/initialize` first and wait for its result before any other request. To renegotiate, open a new connection.\",\n },\n },\n MOSTRA_HOST_PORT_UNSUPPORTED: {\n severity: \"warning\",\n phase: \"host\",\n title: \"Port not supported by this instance\",\n hint: \"Leave the port out of `mostra/initialize`, or run a Mostra release that lists it in `capabilities.ports`.\",\n docs: {\n explanation:\n \"The client registered a port this instance doesn't call, so registering it has no effect. The port may be reserved for a later release (such as `ai`), or the client may be newer than the instance. The session continues without the port, and Mostra uses its standalone behavior instead.\",\n fix: \"Register only the ports listed in `capabilities.ports` of the `mostra/initialize` result. If the host needs the port, upgrade the instance to a release that supports it.\",\n },\n },\n MOSTRA_HOST_CONNECTION_CLOSED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Connection closed\",\n hint: \"Reconnect, then retry the request with the same request ID.\",\n docs: {\n explanation:\n \"The connection to the other side closed before a response arrived, for example because the instance exited or restarted. The request may or may not have taken effect.\",\n fix: \"Reconnect and send `mostra/initialize` again, then retry the request with the same request ID. Mutating methods are idempotent by request ID, so a retry never applies twice.\",\n },\n },\n MOSTRA_HOST_TIMEOUT: {\n severity: \"error\",\n phase: \"host\",\n title: \"Request timed out\",\n hint: \"Retry the request with the same request ID, or allow it more time.\",\n docs: {\n explanation:\n \"No response arrived within the time the caller allowed. The other side may still be working on the request, and it may still take effect.\",\n fix: \"Retry with the same request ID, which returns the recorded result if the first attempt completed. Allow a longer timeout for slow operations.\",\n },\n },\n MOSTRA_HOST_SHUTDOWN_REFUSED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Only the spawning host can stop this instance\",\n hint: \"Ask the host that started this instance to stop it, or end the connection you opened instead.\",\n docs: {\n explanation:\n \"An instance started by a host over stdio (`mostra host`) lives as long as that host's connection, so only the host may stop it with `mostra/shutdown`. A client that attached through the home's socket asked it to stop. A daemon (`mostra daemon`) accepts `mostra/shutdown` from every attached client (D87).\",\n fix: \"Close your own connection when you are done. To stop the instance, stop the host that spawned it, or have the host send `mostra/shutdown` or close its stdio.\",\n },\n },\n MOSTRA_HOST_REQUEST_ID_REUSED: {\n severity: \"error\",\n phase: \"host\",\n title: \"A requestId was reused with other parameters\",\n hint: \"Send a new `requestId` for a new request; repeat the exact parameters only to retry one.\",\n docs: {\n explanation:\n \"A mutating method recorded its result under this `requestId` for different parameters. Replaying that result would answer a request nobody made (a link for another artifact or with other scopes, another source's publish), so the instance refuses (H-03). Retries with the same parameters still return the recorded result.\",\n fix: \"Generate a fresh `requestId` for every new request, and reuse one only to retry the same request after a timeout or a lost connection.\",\n },\n },\n MOSTRA_HOST_CURSOR_COMPACTED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Events compacted\",\n hint: \"Read from the cursor in the message to receive the compaction summary, then continue from there.\",\n docs: {\n explanation:\n \"Events before a cursor were compacted on request (`mostra gc --compact-events`, DATA_MODEL §4): an artifact's old events were replaced by one `artifact.compacted` event that summarizes them. A reader asking for events after an earlier cursor would miss some, and Mostra never leaves a silent gap.\",\n fix: \"Read again with `after` set to the cursor the message names: the next event is the `artifact.compacted` summary. Rebuild what you track from it and continue as usual.\",\n },\n },\n MOSTRA_HOST_SUBSCRIPTION_UNKNOWN: {\n severity: \"error\",\n phase: \"host\",\n title: \"Unknown subscription\",\n hint: \"Subscribe again with `events/subscribe`, then use the ID it returns.\",\n docs: {\n explanation:\n \"The subscription ID belongs to no subscription on this connection: it was never created here, was ended with `events/unsubscribe`, or belonged to a connection that closed. Subscriptions live as long as their connection; a named subscriber's acknowledged cursor outlives it.\",\n fix: \"Call `events/subscribe` again on this connection. With the same `name`, delivery resumes after the last acknowledged cursor.\",\n },\n },\n MOSTRA_HOST_NOTIFICATION_UNSUPPORTED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Notification not accepted\",\n hint: \"List the notification in `capabilities.notifications` when you initialize.\",\n docs: {\n explanation:\n \"Mostra sends a client only the notifications it listed in `mostra/initialize` (D84). This method would send one the client didn't list, such as `events/notify` for `events/subscribe`.\",\n fix: 'Reconnect and initialize with `capabilities: { notifications: [\"events/notify\"] }`, or poll with `events/read` instead.',\n },\n },\n MOSTRA_HOST_MESSAGE_TOO_LARGE: {\n severity: \"error\",\n phase: \"host\",\n title: \"Message too large for the protocol\",\n hint: \"Ask for less at once: a specific submission, fewer events, or smaller values.\",\n docs: {\n explanation:\n \"One host-protocol message is one line of JSON, and a line holds at most 64 Mi characters (`MAX_LINE_LENGTH`), so neither side buffers without bound. Mostra checks every message before it writes it: an answer that would be longer is replaced by this error, and a delivery whose envelope would be longer is recorded as undeliverable instead of being sent and retried forever.\",\n fix: \"Read less per request (`events/read` with a smaller `limit`, `results/get` for one submission), and keep artifacts' values within the field and document limits.\",\n },\n },\n MOSTRA_HOST_IDENTITY_UNAVAILABLE: {\n severity: \"error\",\n phase: \"host\",\n title: \"The host that identifies viewers didn't answer\",\n hint: \"Start the host that serves this home's identity port, then open the link again.\",\n docs: {\n explanation:\n \"A host registered the `identity` port, so it decides who opens this home's links. When a link minted without a viewer was opened, that host failed, didn't answer within 5 seconds, gave an answer its schema refuses, or is expected (it lists `identity` in `HomeConfig.ports`) but not connected. Mostra refuses the link rather than let the session act as someone else.\",\n fix: \"Start or reconnect the host, then open the link again. A link minted with `view/url`'s `viewer` names its person itself and never needs the port. To return the home to Mostra's own identity, have the host register without the port and clear its expected ports (`HomeConfig.ports: []`).\",\n },\n },\n // gen:entries\n};\n"],"mappings":";;AAMA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAEF;;AAMA,MAAa,kBAAmD;CAC9D,kCAAkC;EAChC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,uBAAuB;EACrB,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,4BAA4B;EAC1B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,4BAA4B;EAC1B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,4BAA4B;EAC1B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,+BAA+B;EAC7B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,qBAAqB;EACnB,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,+BAA+B;EAC7B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,kCAAkC;EAChC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,sCAAsC;EACpC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,+BAA+B;EAC7B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,kCAAkC;EAChC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;AAEF"}
1
+ {"version":3,"file":"host.js","names":[],"sources":["../../../src/diagnostics/codes/host.ts"],"sourcesContent":["/**\n * Diagnostic codes of the HOST area: the host protocol between clients and an instance.\n */\nimport type { AreaCatalog } from \"../spec.ts\";\nimport { coreHostDiagnostics } from \"./host-core.ts\";\n\n/** The codes of the HOST area, in the order they were added. */\nexport const hostDiagnosticCodes = [\n \"MOSTRA_HOST_REVISION_UNSUPPORTED\",\n \"MOSTRA_HOST_MALFORMED\",\n \"MOSTRA_HOST_METHOD_UNKNOWN\",\n \"MOSTRA_HOST_INVALID_PARAMS\",\n \"MOSTRA_HOST_INTERNAL_ERROR\",\n \"MOSTRA_HOST_INITIALIZE_ORDER\",\n \"MOSTRA_HOST_PORT_UNSUPPORTED\",\n \"MOSTRA_HOST_CONNECTION_CLOSED\",\n \"MOSTRA_HOST_TIMEOUT\",\n \"MOSTRA_HOST_SHUTDOWN_REFUSED\",\n \"MOSTRA_HOST_REQUEST_ID_REUSED\",\n \"MOSTRA_HOST_CURSOR_COMPACTED\",\n \"MOSTRA_HOST_SUBSCRIPTION_UNKNOWN\",\n \"MOSTRA_HOST_NOTIFICATION_UNSUPPORTED\",\n \"MOSTRA_HOST_MESSAGE_TOO_LARGE\",\n \"MOSTRA_HOST_IDENTITY_UNAVAILABLE\",\n // gen:codes\n] as const;\n\n/** The codes of the HOST area. */\nexport type HostDiagnosticCode = (typeof hostDiagnosticCodes)[number];\n\n/**\n * The HOST area's catalog entries. The codes the JSON-RPC core raises live in `host-core.ts`, so\n * browser bundles carry only theirs (#17).\n */\nexport const hostDiagnostics: AreaCatalog<HostDiagnosticCode> = {\n ...coreHostDiagnostics,\n MOSTRA_HOST_REVISION_UNSUPPORTED: {\n severity: \"error\",\n phase: \"host\",\n title: \"No common host protocol revision\",\n hint: \"Run the client and the instance from the same Mostra release, for example with `mostra daemon restart`.\",\n docs: {\n explanation:\n \"A client and a Mostra instance agree on a host protocol revision when they connect (`mostra/initialize`). The client offers the revisions it speaks, and the instance picks the newest one it also supports. This code means the two lists have nothing in common, usually because the client and the running daemon come from Mostra releases far apart.\",\n fix: \"Restart the daemon so it runs the same release as the client: `mostra daemon restart`. Durable state survives the restart, and open views reconnect. A host that embeds Mostra updates its pinned Mostra runtime or its host library until both support a common revision.\",\n },\n },\n MOSTRA_HOST_INITIALIZE_ORDER: {\n severity: \"error\",\n phase: \"host\",\n title: \"Initialize first, and only once\",\n hint: \"Send `mostra/initialize` as the first request on the connection, and only once.\",\n docs: {\n explanation:\n \"Every connection starts with `mostra/initialize`, which agrees the protocol revision and registers the client's ports. The instance received another request before it, or a second `mostra/initialize` on the same connection.\",\n fix: \"Send `mostra/initialize` first and wait for its result before any other request. To renegotiate, open a new connection.\",\n },\n },\n MOSTRA_HOST_PORT_UNSUPPORTED: {\n severity: \"warning\",\n phase: \"host\",\n title: \"Port not supported by this instance\",\n hint: \"Leave the port out of `mostra/initialize`, or run a Mostra release that lists it in `capabilities.ports`.\",\n docs: {\n explanation:\n \"The client registered a port this instance doesn't call, so registering it has no effect. The port may be reserved for a later release (such as `ai`), or the client may be newer than the instance. The session continues without the port, and Mostra uses its standalone behavior instead.\",\n fix: \"Register only the ports listed in `capabilities.ports` of the `mostra/initialize` result. If the host needs the port, upgrade the instance to a release that supports it.\",\n },\n },\n MOSTRA_HOST_SHUTDOWN_REFUSED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Only the spawning host can stop this instance\",\n hint: \"Ask the host that started this instance to stop it, or end the connection you opened instead.\",\n docs: {\n explanation:\n \"An instance started by a host over stdio (`mostra host`) lives as long as that host's connection, so only the host may stop it with `mostra/shutdown`. A client that attached through the home's socket asked it to stop. A daemon (`mostra daemon`) accepts `mostra/shutdown` from every attached client (D87).\",\n fix: \"Close your own connection when you are done. To stop the instance, stop the host that spawned it, or have the host send `mostra/shutdown` or close its stdio.\",\n },\n },\n MOSTRA_HOST_REQUEST_ID_REUSED: {\n severity: \"error\",\n phase: \"host\",\n title: \"A requestId was reused with other parameters\",\n hint: \"Send a new `requestId` for a new request; repeat the exact parameters only to retry one.\",\n docs: {\n explanation:\n \"A mutating method recorded its result under this `requestId` for different parameters. Replaying that result would answer a request nobody made (a link for another artifact or with other scopes, another source's publish), so the instance refuses (H-03). Retries with the same parameters still return the recorded result.\",\n fix: \"Generate a fresh `requestId` for every new request, and reuse one only to retry the same request after a timeout or a lost connection.\",\n },\n },\n MOSTRA_HOST_CURSOR_COMPACTED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Events compacted\",\n hint: \"Read from the cursor in the message to receive the compaction summary, then continue from there.\",\n docs: {\n explanation:\n \"Events before a cursor were compacted on request (`mostra gc --compact-events`, DATA_MODEL §4): an artifact's old events were replaced by one `artifact.compacted` event that summarizes them. A reader asking for events after an earlier cursor would miss some, and Mostra never leaves a silent gap.\",\n fix: \"Read again with `after` set to the cursor the message names: the next event is the `artifact.compacted` summary. Rebuild what you track from it and continue as usual.\",\n },\n },\n MOSTRA_HOST_SUBSCRIPTION_UNKNOWN: {\n severity: \"error\",\n phase: \"host\",\n title: \"Unknown subscription\",\n hint: \"Subscribe again with `events/subscribe`, then use the ID it returns.\",\n docs: {\n explanation:\n \"The subscription ID belongs to no subscription on this connection: it was never created here, was ended with `events/unsubscribe`, or belonged to a connection that closed. Subscriptions live as long as their connection; a named subscriber's acknowledged cursor outlives it.\",\n fix: \"Call `events/subscribe` again on this connection. With the same `name`, delivery resumes after the last acknowledged cursor.\",\n },\n },\n MOSTRA_HOST_NOTIFICATION_UNSUPPORTED: {\n severity: \"error\",\n phase: \"host\",\n title: \"Notification not accepted\",\n hint: \"List the notification in `capabilities.notifications` when you initialize.\",\n docs: {\n explanation:\n \"Mostra sends a client only the notifications it listed in `mostra/initialize` (D84). This method would send one the client didn't list, such as `events/notify` for `events/subscribe`.\",\n fix: 'Reconnect and initialize with `capabilities: { notifications: [\"events/notify\"] }`, or poll with `events/read` instead.',\n },\n },\n MOSTRA_HOST_MESSAGE_TOO_LARGE: {\n severity: \"error\",\n phase: \"host\",\n title: \"Message too large for the protocol\",\n hint: \"Ask for less at once: a specific submission, fewer events, or smaller values.\",\n docs: {\n explanation:\n \"One host-protocol message is one line of JSON, and a line holds at most 64 Mi characters (`MAX_LINE_LENGTH`), so neither side buffers without bound. Mostra checks every message before it writes it: an answer that would be longer is replaced by this error, and a delivery whose envelope would be longer is recorded as undeliverable instead of being sent and retried forever.\",\n fix: \"Read less per request (`events/read` with a smaller `limit`, `results/get` for one submission), and keep artifacts' values within the field and document limits.\",\n },\n },\n MOSTRA_HOST_IDENTITY_UNAVAILABLE: {\n severity: \"error\",\n phase: \"host\",\n title: \"The host that identifies viewers didn't answer\",\n hint: \"Start the host that serves this home's identity port, then open the link again.\",\n docs: {\n explanation:\n \"A host registered the `identity` port, so it decides who opens this home's links. When a link minted without a viewer was opened, that host failed, didn't answer within 5 seconds, gave an answer its schema refuses, or is expected (it lists `identity` in `HomeConfig.ports`) but not connected. Mostra refuses the link rather than let the session act as someone else.\",\n fix: \"Start or reconnect the host, then open the link again. A link minted with `view/url`'s `viewer` names its person itself and never needs the port. To return the home to Mostra's own identity, have the host register without the port and clear its expected ports (`HomeConfig.ports: []`).\",\n },\n },\n // gen:entries\n};\n"],"mappings":";;;AAOA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAEF;;;;;AASA,MAAa,kBAAmD;CAC9D,GAAG;CACH,kCAAkC;EAChC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,+BAA+B;EAC7B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,8BAA8B;EAC5B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,kCAAkC;EAChC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,sCAAsC;EACpC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,+BAA+B;EAC7B,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;CACA,kCAAkC;EAChC,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;EACN,MAAM;GACJ,aACE;GACF,KAAK;EACP;CACF;AAEF"}
@@ -1,4 +1,3 @@
1
- import { hostDiagnosticCodes, hostDiagnostics } from "./host.js";
2
1
  import { buildDiagnostic } from "../spec.js";
3
2
  import { a11yDiagnosticCodes, a11yDiagnostics } from "./a11y.js";
4
3
  import { actionDiagnosticCodes, actionDiagnostics } from "./action.js";
@@ -10,6 +9,7 @@ import { depDiagnosticCodes, depDiagnostics } from "./dep.js";
10
9
  import { envDiagnosticCodes, envDiagnostics } from "./env.js";
11
10
  import { fieldDiagnosticCodes, fieldDiagnostics } from "./field.js";
12
11
  import { homeDiagnosticCodes, homeDiagnostics } from "./home.js";
12
+ import { hostDiagnosticCodes, hostDiagnostics } from "./host.js";
13
13
  import { hygieneDiagnosticCodes, hygieneDiagnostics } from "./hygiene.js";
14
14
  import { liveDiagnosticCodes, liveDiagnostics } from "./live.js";
15
15
  import { manifestDiagnosticCodes, manifestDiagnostics } from "./manifest.js";
package/dist/index.d.ts CHANGED
@@ -79,9 +79,10 @@ import { ViewLaunchParams, ViewLaunchResult, viewLaunchMethod } from "./methods/
79
79
  import { ViewRevokeParams, ViewRevokeResult, viewRevokeMethod } from "./methods/view/revoke.js";
80
80
  import { ViewRotateParams, ViewRotateResult, viewRotateMethod } from "./methods/view/rotate.js";
81
81
  import { WAIT_MAX_MS, WaitParams, WaitResult, waitMethod } from "./methods/wait/wait.js";
82
+ import { receivable } from "./receive.js";
82
83
  import { ClassifiedMessage, JsonRpcErrorObject, JsonRpcFailure, JsonRpcId, JsonRpcMessage, JsonRpcNotification, JsonRpcParams, JsonRpcRequest, JsonRpcResponse, JsonRpcSuccess, classifyMessage } from "./rpc/messages.js";
83
84
  import { JSON_RPC_ERROR_CODES, RpcError } from "./rpc/error.js";
84
85
  import { LineSplitter, MAX_LINE_LENGTH, encodeLine } from "./rpc/lines.js";
85
86
  import { RpcPeer, RpcPeerOptions, RpcRequestContext, RpcRequestOptions, parseParams } from "./rpc/peer.js";
86
87
  import { CallContext, DEFAULT_WORKER_LIMITS, LiveSourceInfo, ServerEmitParams, ServerLiveValueParams, ServerLogParams, ServerProgressParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ServerStatePatchResult, WORKER_CHANNEL_REVISION, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerCallParams, WorkerCancelParams, WorkerLimits, WorkerLiveParams, WorkerPingResult, WorkerStartParams, WorkerStartResult, WorkerVersionRef } from "./worker.js";
87
- export { type A11yDiagnosticCode, ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARGUMENT_BIGINT_DIGITS_MAX, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, type ActionDiagnosticCode, ActionError, Actor, AddedPackage, type AnyBridgeMessage, type AnyFunction, type AnyMethod, type AnyNotification, type AreaCatalog, type ArtifactCreateParams, type ArtifactCreateResult, ArtifactDetail, type ArtifactDiagnosticCode, type ArtifactFamily, type ArtifactGetParams, type ArtifactGetResult, ArtifactId, ArtifactLink, type ArtifactListFilter, type ArtifactListParams, type ArtifactListResult, ArtifactManifest, ArtifactProgressParams, type ArtifactPublishParams, type ArtifactPublishResult, ArtifactRef, ArtifactSummary, type ArtifactVerifyParams, type ArtifactVerifyResult, BRIDGE_FIELDS_MAX, BRIDGE_MESSAGES, BRIDGE_TEXT_MAX, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, BUNDLE_PLATFORMS, BUNDLE_SETUP_MARKER, Batches, type Bridge, type BridgeEvent, type BridgeHostContext, type BridgeImplementation, type BridgeMessage, type BridgeOptions, type BridgePeer, type BridgeReceiver, type BridgeRejection, type BridgeSide, type BuildDiagnosticCode, BundleAsset, BundleBrowser, BundleFileEntry, BundleFiles, BundleInfo, BundleLinkEntry, BundlePins, type BundlePlatform, BundlePlatformSchema, BundleSetup, CLI_CLIENT_NAME, CONTROL_LABEL_MAX, CSRF_HEADER, type CallContext, type CallLine, CallRequest, CapabilityLink, CapabilityScope, CarryOver, ChildProcessStatus, ChooseRequest, type ClassifiedMessage, type CliDiagnosticCode, ClientCapabilities, ClientInfo, CommentId, type CompareRequest, type CompareResult, type ConsoleDiagnosticCode, type ControlRequest, ControlsPolicy, type CreateDiagnosticOptions, Cursor, DEFAULT_DOCS_BASE, DEFAULT_VIEWPORTS, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DIAGNOSTIC_AREAS, DeliveryCounts, DeliveryId, type DeliveryState, DeliveryStatus, type DeliveryTarget, type DemoSpec, type DepDiagnosticCode, DependencyPolicy, type DepsAddParams, type DepsAddResult, type DevEventKind, DevNotifyParams, type DevStartParams, type DevStartResult, type DevStopParams, type DevStopResult, Diagnostic, type DiagnosticArea, type DiagnosticCode, type DiagnosticDetails, DiagnosticFix, DiagnosticLocation, DiagnosticPhase, DiagnosticSeverity, type DiagnosticSpec, DocumentRevision, DocumentSnapshot, DraftMirror, type DraftsMirrorResult, Duration, EVENTS_NOTIFY, EVENTS_READ_MAX, type EnvDiagnosticCode, type EphemeralMessage, EventFilter, EventRecord, EventTypePattern, type EventsAckParams, type EventsAckResult, EventsNotifyParams, type EventsReadParams, type EventsReadResult, type EventsSubscribeParams, type EventsSubscribeResult, type EventsUnsubscribeParams, type EventsUnsubscribeResult, FIELD_ID_MAX_LENGTH, FieldConflict, type FieldDiagnosticCode, FieldOp, type FieldRegistration, type FieldScope, FieldState, type FieldsParams, FieldsRequest, type FlushResult, FollowRequest, type Frame, FrameTicket, GatewayStatus, type GcCompactEvents, type GcCompacted, type GcCount, type GcRunParams, type GcRunResult, type GcVersion, type GeneratedIdKind, HOST_PROTOCOL_REVISIONS, HomeConfig, type HomeDiagnosticCode, type HostDiagnosticCode, type HygieneDiagnosticCode, type Id, type IdBody, type IdKind, type IdPrefix, type IdentityVia, InstanceCapabilities, type InstanceCheck, type InstanceCheckParams, type InstanceCheckResult, InstanceInfo, type InstanceStatusParams, type InstanceStatusResult, JSON_RPC_ERROR_CODES, JsonRpcErrorObject, JsonRpcFailure, type JsonRpcId, type JsonRpcMessage, JsonRpcNotification, type JsonRpcParams, JsonRpcRequest, type JsonRpcResponse, JsonRpcSuccess, type KnownDiagnosticCode, LIVE_KEY_PATTERN, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, type LiveDiagnosticCode, type LivePushParams, type LivePushResult, LiveRequest, type LiveSourceInfo, type LiveState, type LiveUpdate, MAX_LINE_LENGTH, MCP_APPS_PROTOCOL_VERSION, type ManifestDiagnosticCode, type MethodDefinition, type MethodDirection, type MostraInitializeParams, type MostraInitializeResult, type MostraShutdownParams, type MostraShutdownResult, MutationId, MutationResult, type NetworkDiagnosticCode, type NotificationDefinition, OPEN_LINK_SCHEMES, OrphanedField, type PlatformDiagnosticCode, PollResult, type PortIdentityResolveParams, type PortIdentityResolveResult, PortName, type PortSecretsGetParams, type PortSecretsGetResult, type PortTrustedControlsActivatedParams, type PortTrustedControlsActivatedResult, type PortTrustedControlsPolicyParams, type PortTrustedControlsPolicyResult, type ProbedField, type PublishDiagnosticCode, PublishReceipt, REVIEW_SET_ID_PATTERN, RUN_KEY_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RUN_STATUSES, type Rect, type Refusal, type RegressionDiagnosticCode, RemoteError, type RenderRequest, type RenderResult, type RequestFacts, type RequestIntent, type RequestPolicy, ResultComment, Results, type ResultsGetParams, type ResultsGetResult, ResultsMarkdown, Revision, type RevisionNegotiation, RpcError, RpcPeer, type RpcPeerOptions, type RpcRequestContext, type RpcRequestOptions, RunAttachRequest, RunCancelRequest, type RunDelta, RunId, RunProgress, type RunReason, RunRequest, RunState, type RunStatus, type RuntimeDiagnosticCode, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, type SaveState, ScreenshotPolicy, type SecretDeleteParams, type SecretDeleteResult, type SecretDiagnosticCode, SecretEntry, type SecretListParams, type SecretListResult, type SecretSetParams, type SecretSetResult, SerializationError, type SerializeMode, ServerEmitParams, ServerLiveValueParams, ServerLogParams, ServerProgressParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, type ServerStatePatchResult, ShellSubmitRequest, SignalRequest, type SmokeDiagnosticCode, SourceRef, type StateGetParams, type StateGetResult, type StatePatchParams, type StatePatchResult, StreamSnapshot, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmissionSummary, type SubmissionsDeliverResult, type SubmitBlocker, SubmitChannel, type SubmitDiagnosticCode, SubmitRequest, type TargetDiagnosticCode, type TerminalSpec, ThreadId, type TokenEstimate, TokenId, TrustedControl, type TypeDiagnosticCode, UNSERIALIZABLE_CODE, type UiInitializeParams, type UiInitializeResult, VERIFY_PROBE, VERIFY_REPORT, VERIFY_RUNNER_METHODS, ValueReader, type ValueReaderOptions, ValueWriter, type ValueWriterOptions, type VerdictAria, type VerdictScreenshot, type VerifyDiagnosticCode, VerifyVerdict, type VerifyViewport, type VersionAvailableParams, VersionId, type VersionIdKind, VersionRef, VersionSummary, ViewContext, ViewContextWire, type ViewDefaultParams, type ViewDefaultResult, ViewId, type ViewLaunchParams, type ViewLaunchResult, type ViewRevokeParams, type ViewRevokeResult, type ViewRotateParams, type ViewRotateResult, type ViewUrlParams, type ViewUrlResult, Viewer, ViewerId, type ViewerKind, ViewerSpec, type Viewport, WAIT_MAX_MS, WORKER_CHANNEL_REVISION, WORKER_METHODS, WaitCondition, type WaitParams, type WaitResult, type WireError, WorkerBatchParams, WorkerCallOutcome, WorkerCallParams, type WorkerCancelParams, type WorkerLimits, type WorkerLiveParams, WorkerPingResult, WorkerStartParams, WorkerStartResult, WorkerStatus, WorkerVersionRef, a11yDiagnosticCodes, actionDiagnosticCodes, ariaSummary, artifactCreateMethod, artifactDiagnosticCodes, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, buildDiagnosticCodes, bundleAssetName, canonicalJson, checkArgumentFrames, checkRequest, classifyMessage, cliDiagnosticCodes, connectBridge, consoleDiagnosticCodes, createDiagnostic, defineMethod, depDiagnosticCodes, depsAddMethod, deserializeAll, devStartMethod, devStopMethod, diagnosticCatalog, docsUrl, durationMs, encodeLine, envDiagnosticCodes, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fieldDiagnosticCodes, fromBase64, gcRunMethod, headerValue, homeDiagnosticCodes, hostDiagnosticCodes, hostMethods, hostNotifications, hygieneDiagnosticCodes, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, isJsonContentType, liveDiagnosticCodes, livePushMethod, manifestDiagnosticCodes, mostraControlsRequest, mostraFieldFocus, mostraFields, mostraFlush, mostraInitializeMethod, mostraPage, mostraReady, mostraShutdownMethod, mostraVersionAvailable, negotiateRevision, networkDiagnosticCodes, normalizeScopes, parseParams, platformDiagnosticCodes, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, publishDiagnosticCodes, readViewContext, refusal, regressionDiagnosticCodes, resultsGetMethod, runtimeDiagnosticCodes, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretDiagnosticCodes, secretListMethod, secretSetMethod, serializeAll, smokeDiagnosticCodes, stateGetMethod, statePatchMethod, submitDiagnosticCodes, targetDiagnosticCodes, toBase64, typeDiagnosticCodes, uiInitialize, uiInitialized, uiOpenLink, uiSizeChanged, verifyDiagnosticCodes, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod, wireError };
88
+ export { type A11yDiagnosticCode, ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARGUMENT_BIGINT_DIGITS_MAX, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, type ActionDiagnosticCode, ActionError, Actor, AddedPackage, type AnyBridgeMessage, type AnyFunction, type AnyMethod, type AnyNotification, type AreaCatalog, type ArtifactCreateParams, type ArtifactCreateResult, ArtifactDetail, type ArtifactDiagnosticCode, type ArtifactFamily, type ArtifactGetParams, type ArtifactGetResult, ArtifactId, ArtifactLink, type ArtifactListFilter, type ArtifactListParams, type ArtifactListResult, ArtifactManifest, ArtifactProgressParams, type ArtifactPublishParams, type ArtifactPublishResult, ArtifactRef, ArtifactSummary, type ArtifactVerifyParams, type ArtifactVerifyResult, BRIDGE_FIELDS_MAX, BRIDGE_MESSAGES, BRIDGE_TEXT_MAX, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, BUNDLE_PLATFORMS, BUNDLE_SETUP_MARKER, Batches, type Bridge, type BridgeEvent, type BridgeHostContext, type BridgeImplementation, type BridgeMessage, type BridgeOptions, type BridgePeer, type BridgeReceiver, type BridgeRejection, type BridgeSide, type BuildDiagnosticCode, BundleAsset, BundleBrowser, BundleFileEntry, BundleFiles, BundleInfo, BundleLinkEntry, BundlePins, type BundlePlatform, BundlePlatformSchema, BundleSetup, CLI_CLIENT_NAME, CONTROL_LABEL_MAX, CSRF_HEADER, type CallContext, type CallLine, CallRequest, CapabilityLink, CapabilityScope, CarryOver, ChildProcessStatus, ChooseRequest, type ClassifiedMessage, type CliDiagnosticCode, ClientCapabilities, ClientInfo, CommentId, type CompareRequest, type CompareResult, type ConsoleDiagnosticCode, type ControlRequest, ControlsPolicy, type CreateDiagnosticOptions, Cursor, DEFAULT_DOCS_BASE, DEFAULT_VIEWPORTS, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DIAGNOSTIC_AREAS, DeliveryCounts, DeliveryId, type DeliveryState, DeliveryStatus, type DeliveryTarget, type DemoSpec, type DepDiagnosticCode, DependencyPolicy, type DepsAddParams, type DepsAddResult, type DevEventKind, DevNotifyParams, type DevStartParams, type DevStartResult, type DevStopParams, type DevStopResult, Diagnostic, type DiagnosticArea, type DiagnosticCode, type DiagnosticDetails, DiagnosticFix, DiagnosticLocation, DiagnosticPhase, DiagnosticSeverity, type DiagnosticSpec, DocumentRevision, DocumentSnapshot, DraftMirror, type DraftsMirrorResult, Duration, EVENTS_NOTIFY, EVENTS_READ_MAX, type EnvDiagnosticCode, type EphemeralMessage, EventFilter, EventRecord, EventTypePattern, type EventsAckParams, type EventsAckResult, EventsNotifyParams, type EventsReadParams, type EventsReadResult, type EventsSubscribeParams, type EventsSubscribeResult, type EventsUnsubscribeParams, type EventsUnsubscribeResult, FIELD_ID_MAX_LENGTH, FieldConflict, type FieldDiagnosticCode, FieldOp, type FieldRegistration, type FieldScope, FieldState, type FieldsParams, FieldsRequest, type FlushResult, FollowRequest, type Frame, FrameTicket, GatewayStatus, type GcCompactEvents, type GcCompacted, type GcCount, type GcRunParams, type GcRunResult, type GcVersion, type GeneratedIdKind, HOST_PROTOCOL_REVISIONS, HomeConfig, type HomeDiagnosticCode, type HostDiagnosticCode, type HygieneDiagnosticCode, type Id, type IdBody, type IdKind, type IdPrefix, type IdentityVia, InstanceCapabilities, type InstanceCheck, type InstanceCheckParams, type InstanceCheckResult, InstanceInfo, type InstanceStatusParams, type InstanceStatusResult, JSON_RPC_ERROR_CODES, JsonRpcErrorObject, JsonRpcFailure, type JsonRpcId, type JsonRpcMessage, JsonRpcNotification, type JsonRpcParams, JsonRpcRequest, type JsonRpcResponse, JsonRpcSuccess, type KnownDiagnosticCode, LIVE_KEY_PATTERN, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, type LiveDiagnosticCode, type LivePushParams, type LivePushResult, LiveRequest, type LiveSourceInfo, type LiveState, type LiveUpdate, MAX_LINE_LENGTH, MCP_APPS_PROTOCOL_VERSION, type ManifestDiagnosticCode, type MethodDefinition, type MethodDirection, type MostraInitializeParams, type MostraInitializeResult, type MostraShutdownParams, type MostraShutdownResult, MutationId, MutationResult, type NetworkDiagnosticCode, type NotificationDefinition, OPEN_LINK_SCHEMES, OrphanedField, type PlatformDiagnosticCode, PollResult, type PortIdentityResolveParams, type PortIdentityResolveResult, PortName, type PortSecretsGetParams, type PortSecretsGetResult, type PortTrustedControlsActivatedParams, type PortTrustedControlsActivatedResult, type PortTrustedControlsPolicyParams, type PortTrustedControlsPolicyResult, type ProbedField, type PublishDiagnosticCode, PublishReceipt, REVIEW_SET_ID_PATTERN, RUN_KEY_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RUN_STATUSES, type Rect, type Refusal, type RegressionDiagnosticCode, RemoteError, type RenderRequest, type RenderResult, type RequestFacts, type RequestIntent, type RequestPolicy, ResultComment, Results, type ResultsGetParams, type ResultsGetResult, ResultsMarkdown, Revision, type RevisionNegotiation, RpcError, RpcPeer, type RpcPeerOptions, type RpcRequestContext, type RpcRequestOptions, RunAttachRequest, RunCancelRequest, type RunDelta, RunId, RunProgress, type RunReason, RunRequest, RunState, type RunStatus, type RuntimeDiagnosticCode, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, type SaveState, ScreenshotPolicy, type SecretDeleteParams, type SecretDeleteResult, type SecretDiagnosticCode, SecretEntry, type SecretListParams, type SecretListResult, type SecretSetParams, type SecretSetResult, SerializationError, type SerializeMode, ServerEmitParams, ServerLiveValueParams, ServerLogParams, ServerProgressParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, type ServerStatePatchResult, ShellSubmitRequest, SignalRequest, type SmokeDiagnosticCode, SourceRef, type StateGetParams, type StateGetResult, type StatePatchParams, type StatePatchResult, StreamSnapshot, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmissionSummary, type SubmissionsDeliverResult, type SubmitBlocker, SubmitChannel, type SubmitDiagnosticCode, SubmitRequest, type TargetDiagnosticCode, type TerminalSpec, ThreadId, type TokenEstimate, TokenId, TrustedControl, type TypeDiagnosticCode, UNSERIALIZABLE_CODE, type UiInitializeParams, type UiInitializeResult, VERIFY_PROBE, VERIFY_REPORT, VERIFY_RUNNER_METHODS, ValueReader, type ValueReaderOptions, ValueWriter, type ValueWriterOptions, type VerdictAria, type VerdictScreenshot, type VerifyDiagnosticCode, VerifyVerdict, type VerifyViewport, type VersionAvailableParams, VersionId, type VersionIdKind, VersionRef, VersionSummary, ViewContext, ViewContextWire, type ViewDefaultParams, type ViewDefaultResult, ViewId, type ViewLaunchParams, type ViewLaunchResult, type ViewRevokeParams, type ViewRevokeResult, type ViewRotateParams, type ViewRotateResult, type ViewUrlParams, type ViewUrlResult, Viewer, ViewerId, type ViewerKind, ViewerSpec, type Viewport, WAIT_MAX_MS, WORKER_CHANNEL_REVISION, WORKER_METHODS, WaitCondition, type WaitParams, type WaitResult, type WireError, WorkerBatchParams, WorkerCallOutcome, WorkerCallParams, type WorkerCancelParams, type WorkerLimits, type WorkerLiveParams, WorkerPingResult, WorkerStartParams, WorkerStartResult, WorkerStatus, WorkerVersionRef, a11yDiagnosticCodes, actionDiagnosticCodes, ariaSummary, artifactCreateMethod, artifactDiagnosticCodes, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, buildDiagnosticCodes, bundleAssetName, canonicalJson, checkArgumentFrames, checkRequest, classifyMessage, cliDiagnosticCodes, connectBridge, consoleDiagnosticCodes, createDiagnostic, defineMethod, depDiagnosticCodes, depsAddMethod, deserializeAll, devStartMethod, devStopMethod, diagnosticCatalog, docsUrl, durationMs, encodeLine, envDiagnosticCodes, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fieldDiagnosticCodes, fromBase64, gcRunMethod, headerValue, homeDiagnosticCodes, hostDiagnosticCodes, hostMethods, hostNotifications, hygieneDiagnosticCodes, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, isJsonContentType, liveDiagnosticCodes, livePushMethod, manifestDiagnosticCodes, mostraControlsRequest, mostraFieldFocus, mostraFields, mostraFlush, mostraInitializeMethod, mostraPage, mostraReady, mostraShutdownMethod, mostraVersionAvailable, negotiateRevision, networkDiagnosticCodes, normalizeScopes, parseParams, platformDiagnosticCodes, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, publishDiagnosticCodes, readViewContext, receivable, refusal, regressionDiagnosticCodes, resultsGetMethod, runtimeDiagnosticCodes, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretDiagnosticCodes, secretListMethod, secretSetMethod, serializeAll, smokeDiagnosticCodes, stateGetMethod, statePatchMethod, submitDiagnosticCodes, targetDiagnosticCodes, toBase64, typeDiagnosticCodes, uiInitialize, uiInitialized, uiOpenLink, uiSizeChanged, verifyDiagnosticCodes, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod, wireError };
package/dist/index.js CHANGED
@@ -2,11 +2,11 @@ import { ArtifactId, CommentId, Cursor, DeliveryId, MutationId, RunId, Submissio
2
2
  import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ActionError, Batches, CallRequest, LIVE_KEY_PATTERN, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LiveRequest, RUN_KEY_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RUN_STATUSES, RunAttachRequest, RunCancelRequest, RunProgress, RunRequest, RunState, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, isFinalRunStatus } from "./actions.js";
3
3
  import { ARTIFACT_MANIFEST_KEYS, ArtifactLink, ArtifactManifest, SubmissionPolicy } from "./manifest.js";
4
4
  import { ArtifactDetail, ArtifactRef, ArtifactSummary, PublishReceipt, SourceRef, VersionSummary } from "./artifact.js";
5
- import { hostDiagnosticCodes } from "./diagnostics/codes/host.js";
6
5
  import { DIAGNOSTIC_AREAS, Diagnostic, DiagnosticFix, DiagnosticLocation, DiagnosticPhase, DiagnosticSeverity } from "./diagnostics/diagnostic.js";
7
6
  import { DEFAULT_DOCS_BASE, docsUrl } from "./diagnostics/spec.js";
8
7
  import { JSON_RPC_ERROR_CODES, RpcError } from "./rpc/error.js";
9
8
  import { JsonRpcErrorObject, JsonRpcFailure, JsonRpcNotification, JsonRpcRequest, JsonRpcSuccess, classifyMessage } from "./rpc/messages.js";
9
+ import { receivable } from "./receive.js";
10
10
  import { RpcPeer, parseParams } from "./rpc/peer.js";
11
11
  import { ControlsPolicy, REVIEW_SET_ID_PATTERN, SubmitChannel, TrustedControl, VersionRef, ViewContext, ViewContextWire, readViewContext } from "./view.js";
12
12
  import { BRIDGE_FIELDS_MAX, BRIDGE_MESSAGES, BRIDGE_TEXT_MAX, CONTROL_LABEL_MAX, MCP_APPS_PROTOCOL_VERSION, OPEN_LINK_SCHEMES, connectBridge, mostraControlsRequest, mostraFieldFocus, mostraFields, mostraFlush, mostraPage, mostraReady, mostraVersionAvailable, uiInitialize, uiInitialized, uiOpenLink, uiSizeChanged } from "./bridge.js";
@@ -25,6 +25,7 @@ import { depDiagnosticCodes } from "./diagnostics/codes/dep.js";
25
25
  import { envDiagnosticCodes } from "./diagnostics/codes/env.js";
26
26
  import { fieldDiagnosticCodes } from "./diagnostics/codes/field.js";
27
27
  import { homeDiagnosticCodes } from "./diagnostics/codes/home.js";
28
+ import { hostDiagnosticCodes } from "./diagnostics/codes/host.js";
28
29
  import { hygieneDiagnosticCodes } from "./diagnostics/codes/hygiene.js";
29
30
  import { liveDiagnosticCodes } from "./diagnostics/codes/live.js";
30
31
  import { manifestDiagnosticCodes } from "./diagnostics/codes/manifest.js";
@@ -84,4 +85,4 @@ import { hostMethods, hostNotifications } from "./methods/index.js";
84
85
  import { LineSplitter, MAX_LINE_LENGTH, encodeLine } from "./rpc/lines.js";
85
86
  import { ARGUMENT_BIGINT_DIGITS_MAX, RemoteError, SerializationError, UNSERIALIZABLE_CODE, ValueReader, ValueWriter, checkArgumentFrames, deserializeAll, fromBase64, serializeAll, toBase64, wireError } from "./serializer.js";
86
87
  import { DEFAULT_WORKER_LIMITS, ServerEmitParams, ServerLiveValueParams, ServerLogParams, ServerProgressParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, WORKER_CHANNEL_REVISION, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerCallParams, WorkerPingResult, WorkerStartParams, WorkerStartResult, WorkerVersionRef } from "./worker.js";
87
- export { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARGUMENT_BIGINT_DIGITS_MAX, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ActionError, Actor, AddedPackage, ArtifactDetail, ArtifactId, ArtifactLink, ArtifactManifest, ArtifactProgressParams, ArtifactRef, ArtifactSummary, BRIDGE_FIELDS_MAX, BRIDGE_MESSAGES, BRIDGE_TEXT_MAX, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, BUNDLE_PLATFORMS, BUNDLE_SETUP_MARKER, Batches, BundleAsset, BundleBrowser, BundleFileEntry, BundleFiles, BundleInfo, BundleLinkEntry, BundlePins, BundlePlatformSchema, BundleSetup, CLI_CLIENT_NAME, CONTROL_LABEL_MAX, CSRF_HEADER, CallRequest, CapabilityLink, CapabilityScope, CarryOver, ChildProcessStatus, ChooseRequest, ClientCapabilities, ClientInfo, CommentId, ControlsPolicy, Cursor, DEFAULT_DOCS_BASE, DEFAULT_VIEWPORTS, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DIAGNOSTIC_AREAS, DeliveryCounts, DeliveryId, DeliveryStatus, DependencyPolicy, DevNotifyParams, Diagnostic, DiagnosticFix, DiagnosticLocation, DiagnosticPhase, DiagnosticSeverity, DocumentRevision, DocumentSnapshot, DraftMirror, Duration, EVENTS_NOTIFY, EVENTS_READ_MAX, EventFilter, EventRecord, EventTypePattern, EventsNotifyParams, FIELD_ID_MAX_LENGTH, FieldConflict, FieldOp, FieldState, FieldsRequest, FollowRequest, FrameTicket, GatewayStatus, HOST_PROTOCOL_REVISIONS, HomeConfig, InstanceCapabilities, InstanceInfo, JSON_RPC_ERROR_CODES, JsonRpcErrorObject, JsonRpcFailure, JsonRpcNotification, JsonRpcRequest, JsonRpcSuccess, LIVE_KEY_PATTERN, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MCP_APPS_PROTOCOL_VERSION, MutationId, MutationResult, OPEN_LINK_SCHEMES, OrphanedField, PollResult, PortName, PublishReceipt, REVIEW_SET_ID_PATTERN, RUN_KEY_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RUN_STATUSES, RemoteError, ResultComment, Results, ResultsMarkdown, Revision, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunProgress, RunRequest, RunState, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ScreenshotPolicy, SecretEntry, SerializationError, ServerEmitParams, ServerLiveValueParams, ServerLogParams, ServerProgressParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SourceRef, StreamSnapshot, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmissionSummary, SubmitChannel, SubmitRequest, ThreadId, TokenId, TrustedControl, UNSERIALIZABLE_CODE, VERIFY_PROBE, VERIFY_REPORT, VERIFY_RUNNER_METHODS, ValueReader, ValueWriter, VerifyVerdict, VersionId, VersionRef, VersionSummary, ViewContext, ViewContextWire, ViewId, Viewer, ViewerId, ViewerSpec, WAIT_MAX_MS, WORKER_CHANNEL_REVISION, WORKER_METHODS, WaitCondition, WorkerBatchParams, WorkerCallOutcome, WorkerCallParams, WorkerPingResult, WorkerStartParams, WorkerStartResult, WorkerStatus, WorkerVersionRef, a11yDiagnosticCodes, actionDiagnosticCodes, ariaSummary, artifactCreateMethod, artifactDiagnosticCodes, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, buildDiagnosticCodes, bundleAssetName, canonicalJson, checkArgumentFrames, checkRequest, classifyMessage, cliDiagnosticCodes, connectBridge, consoleDiagnosticCodes, createDiagnostic, defineMethod, depDiagnosticCodes, depsAddMethod, deserializeAll, devStartMethod, devStopMethod, diagnosticCatalog, docsUrl, durationMs, encodeLine, envDiagnosticCodes, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fieldDiagnosticCodes, fromBase64, gcRunMethod, headerValue, homeDiagnosticCodes, hostDiagnosticCodes, hostMethods, hostNotifications, hygieneDiagnosticCodes, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, isJsonContentType, liveDiagnosticCodes, livePushMethod, manifestDiagnosticCodes, mostraControlsRequest, mostraFieldFocus, mostraFields, mostraFlush, mostraInitializeMethod, mostraPage, mostraReady, mostraShutdownMethod, mostraVersionAvailable, negotiateRevision, networkDiagnosticCodes, normalizeScopes, parseParams, platformDiagnosticCodes, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, publishDiagnosticCodes, readViewContext, refusal, regressionDiagnosticCodes, resultsGetMethod, runtimeDiagnosticCodes, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretDiagnosticCodes, secretListMethod, secretSetMethod, serializeAll, smokeDiagnosticCodes, stateGetMethod, statePatchMethod, submitDiagnosticCodes, targetDiagnosticCodes, toBase64, typeDiagnosticCodes, uiInitialize, uiInitialized, uiOpenLink, uiSizeChanged, verifyDiagnosticCodes, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod, wireError };
88
+ export { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARGUMENT_BIGINT_DIGITS_MAX, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ActionError, Actor, AddedPackage, ArtifactDetail, ArtifactId, ArtifactLink, ArtifactManifest, ArtifactProgressParams, ArtifactRef, ArtifactSummary, BRIDGE_FIELDS_MAX, BRIDGE_MESSAGES, BRIDGE_TEXT_MAX, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, BUNDLE_PLATFORMS, BUNDLE_SETUP_MARKER, Batches, BundleAsset, BundleBrowser, BundleFileEntry, BundleFiles, BundleInfo, BundleLinkEntry, BundlePins, BundlePlatformSchema, BundleSetup, CLI_CLIENT_NAME, CONTROL_LABEL_MAX, CSRF_HEADER, CallRequest, CapabilityLink, CapabilityScope, CarryOver, ChildProcessStatus, ChooseRequest, ClientCapabilities, ClientInfo, CommentId, ControlsPolicy, Cursor, DEFAULT_DOCS_BASE, DEFAULT_VIEWPORTS, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DIAGNOSTIC_AREAS, DeliveryCounts, DeliveryId, DeliveryStatus, DependencyPolicy, DevNotifyParams, Diagnostic, DiagnosticFix, DiagnosticLocation, DiagnosticPhase, DiagnosticSeverity, DocumentRevision, DocumentSnapshot, DraftMirror, Duration, EVENTS_NOTIFY, EVENTS_READ_MAX, EventFilter, EventRecord, EventTypePattern, EventsNotifyParams, FIELD_ID_MAX_LENGTH, FieldConflict, FieldOp, FieldState, FieldsRequest, FollowRequest, FrameTicket, GatewayStatus, HOST_PROTOCOL_REVISIONS, HomeConfig, InstanceCapabilities, InstanceInfo, JSON_RPC_ERROR_CODES, JsonRpcErrorObject, JsonRpcFailure, JsonRpcNotification, JsonRpcRequest, JsonRpcSuccess, LIVE_KEY_PATTERN, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MCP_APPS_PROTOCOL_VERSION, MutationId, MutationResult, OPEN_LINK_SCHEMES, OrphanedField, PollResult, PortName, PublishReceipt, REVIEW_SET_ID_PATTERN, RUN_KEY_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RUN_STATUSES, RemoteError, ResultComment, Results, ResultsMarkdown, Revision, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunProgress, RunRequest, RunState, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ScreenshotPolicy, SecretEntry, SerializationError, ServerEmitParams, ServerLiveValueParams, ServerLogParams, ServerProgressParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SourceRef, StreamSnapshot, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmissionSummary, SubmitChannel, SubmitRequest, ThreadId, TokenId, TrustedControl, UNSERIALIZABLE_CODE, VERIFY_PROBE, VERIFY_REPORT, VERIFY_RUNNER_METHODS, ValueReader, ValueWriter, VerifyVerdict, VersionId, VersionRef, VersionSummary, ViewContext, ViewContextWire, ViewId, Viewer, ViewerId, ViewerSpec, WAIT_MAX_MS, WORKER_CHANNEL_REVISION, WORKER_METHODS, WaitCondition, WorkerBatchParams, WorkerCallOutcome, WorkerCallParams, WorkerPingResult, WorkerStartParams, WorkerStartResult, WorkerStatus, WorkerVersionRef, a11yDiagnosticCodes, actionDiagnosticCodes, ariaSummary, artifactCreateMethod, artifactDiagnosticCodes, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, buildDiagnosticCodes, bundleAssetName, canonicalJson, checkArgumentFrames, checkRequest, classifyMessage, cliDiagnosticCodes, connectBridge, consoleDiagnosticCodes, createDiagnostic, defineMethod, depDiagnosticCodes, depsAddMethod, deserializeAll, devStartMethod, devStopMethod, diagnosticCatalog, docsUrl, durationMs, encodeLine, envDiagnosticCodes, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fieldDiagnosticCodes, fromBase64, gcRunMethod, headerValue, homeDiagnosticCodes, hostDiagnosticCodes, hostMethods, hostNotifications, hygieneDiagnosticCodes, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, isJsonContentType, liveDiagnosticCodes, livePushMethod, manifestDiagnosticCodes, mostraControlsRequest, mostraFieldFocus, mostraFields, mostraFlush, mostraInitializeMethod, mostraPage, mostraReady, mostraShutdownMethod, mostraVersionAvailable, negotiateRevision, networkDiagnosticCodes, normalizeScopes, parseParams, platformDiagnosticCodes, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, publishDiagnosticCodes, readViewContext, receivable, refusal, regressionDiagnosticCodes, resultsGetMethod, runtimeDiagnosticCodes, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretDiagnosticCodes, secretListMethod, secretSetMethod, serializeAll, smokeDiagnosticCodes, stateGetMethod, statePatchMethod, submitDiagnosticCodes, targetDiagnosticCodes, toBase64, typeDiagnosticCodes, uiInitialize, uiInitialized, uiOpenLink, uiSizeChanged, verifyDiagnosticCodes, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod, wireError };
@@ -0,0 +1,24 @@
1
+ import * as z from "zod";
2
+ //#region src/receive.d.ts
3
+ /**
4
+ * `schema` as a receiver of a newer peer's messages checks it: every string enum and every union
5
+ * of string literals accepts any string (an enum's own checks still run, and an enum-keyed record
6
+ * still needs every key it names); a discriminated union accepts, besides its members, an object
7
+ * whose discriminator is a string none of them has, kept whole; strict objects drop unknown fields
8
+ * rather than refuse them. Everything else (fields, types, required members, limits) is checked as
9
+ * before, so a message a newer peer couldn't have sent still fails, and a message `schema` accepts
10
+ * reads exactly as `schema` reads it: a union tries its members as built before their opened
11
+ * copies, and a discriminated union's members keep their own tags.
12
+ *
13
+ * The result keeps `schema`'s TypeScript type, the shape this side was built for: a value the type
14
+ * doesn't name means a newer peer. Code that branches on such a field handles the other case, and
15
+ * a gate (a verdict, a check, a delivery) passes only on a value it knows means passing, never on
16
+ * the absence of the one it knows means failing.
17
+ *
18
+ * ```ts
19
+ * const parsed = receivable(definition.result).safeParse(raw);
20
+ * ```
21
+ */
22
+ export declare function receivable<T>(schema: z.ZodType<T>): z.ZodType<T>;
23
+ //#endregion
24
+ //# sourceMappingURL=receive.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receive.d.ts","names":[],"sources":["../src/receive.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAoCgB,WAAW,GAAG,QAAQ,EAAE,QAAQ,KAAK,EAAE,QAAQ"}
@@ -0,0 +1,137 @@
1
+ import * as z from "zod";
2
+ //#region src/receive.ts
3
+ /**
4
+ * Reading what a newer peer sends (HO-07, D32, #45). Within a revision a peer may add values to an
5
+ * enum and members to a union: the wire schemas' evolution rule counts both as additive
6
+ * (`tools/schemas/compat.ts`). A receiver checking such a message against the schemas it was built
7
+ * with would refuse the whole message for one value it doesn't know, so it checks it against
8
+ * {@link receivable}'s copy instead, as the Rust crate's wire types read an `Unknown` variant.
9
+ */
10
+ const opened = /* @__PURE__ */ new WeakMap();
11
+ /**
12
+ * `schema` as a receiver of a newer peer's messages checks it: every string enum and every union
13
+ * of string literals accepts any string (an enum's own checks still run, and an enum-keyed record
14
+ * still needs every key it names); a discriminated union accepts, besides its members, an object
15
+ * whose discriminator is a string none of them has, kept whole; strict objects drop unknown fields
16
+ * rather than refuse them. Everything else (fields, types, required members, limits) is checked as
17
+ * before, so a message a newer peer couldn't have sent still fails, and a message `schema` accepts
18
+ * reads exactly as `schema` reads it: a union tries its members as built before their opened
19
+ * copies, and a discriminated union's members keep their own tags.
20
+ *
21
+ * The result keeps `schema`'s TypeScript type, the shape this side was built for: a value the type
22
+ * doesn't name means a newer peer. Code that branches on such a field handles the other case, and
23
+ * a gate (a verdict, a check, a delivery) passes only on a value it knows means passing, never on
24
+ * the absence of the one it knows means failing.
25
+ *
26
+ * ```ts
27
+ * const parsed = receivable(definition.result).safeParse(raw);
28
+ * ```
29
+ */
30
+ function receivable(schema) {
31
+ return open(schema);
32
+ }
33
+ function open(schema) {
34
+ const known = opened.get(schema);
35
+ if (known) return known;
36
+ let result;
37
+ opened.set(schema, z.lazy(() => result ?? schema));
38
+ result = rebuild(schema);
39
+ opened.set(schema, result);
40
+ return result;
41
+ }
42
+ /** Any string, with the checks `schema` carries (an enum's `.refine`, say). */
43
+ function anyString(schema) {
44
+ const checks = defOf(schema)["checks"];
45
+ return checks?.length ? cloned(z.string(), { checks }) : z.string();
46
+ }
47
+ function defOf(schema) {
48
+ return schema._zod.def;
49
+ }
50
+ /** A copy of `schema` with some of its definition replaced; its checks and settings stay. */
51
+ function cloned(schema, changes) {
52
+ return schema.clone({
53
+ ...defOf(schema),
54
+ ...changes
55
+ });
56
+ }
57
+ /** The string values of a literal or enum node, or undefined when it has others. */
58
+ function strings(schema) {
59
+ const def = defOf(schema);
60
+ const values = def.type === "literal" ? def["values"] : def.type === "enum" ? Object.values(def["entries"]) : void 0;
61
+ return values?.every((value) => typeof value === "string") ? values : void 0;
62
+ }
63
+ function rebuild(schema) {
64
+ const def = defOf(schema);
65
+ switch (def.type) {
66
+ case "enum": return strings(schema) ? anyString(schema) : schema;
67
+ case "optional":
68
+ case "nullable":
69
+ case "readonly":
70
+ case "default":
71
+ case "prefault":
72
+ case "nonoptional":
73
+ case "catch": return cloned(schema, { innerType: open(def["innerType"]) });
74
+ case "array": return cloned(schema, { element: open(def["element"]) });
75
+ case "object": {
76
+ const shape = def["shape"];
77
+ const catchall = def["catchall"];
78
+ return cloned(schema, {
79
+ shape: Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, open(value)])),
80
+ catchall: catchall === void 0 || defOf(catchall).type === "never" ? void 0 : open(catchall)
81
+ });
82
+ }
83
+ case "record": {
84
+ const keyType = def["keyType"];
85
+ if (strings(keyType) && !def["partial"]) return cloned(schema, {
86
+ valueType: open(def["valueType"]),
87
+ mode: "loose"
88
+ });
89
+ return cloned(schema, {
90
+ keyType: open(keyType),
91
+ valueType: open(def["valueType"])
92
+ });
93
+ }
94
+ case "tuple": return cloned(schema, {
95
+ items: def["items"].map(open),
96
+ rest: def["rest"] ? open(def["rest"]) : def["rest"]
97
+ });
98
+ case "intersection": return cloned(schema, {
99
+ left: open(def["left"]),
100
+ right: open(def["right"])
101
+ });
102
+ case "pipe": return cloned(schema, { in: open(def["in"]) });
103
+ case "lazy": {
104
+ const getter = def["getter"];
105
+ return z.lazy(() => open(getter()));
106
+ }
107
+ case "union": return union(schema, def);
108
+ default: return schema;
109
+ }
110
+ }
111
+ function union(schema, def) {
112
+ const options = def["options"];
113
+ if (options.every((option) => strings(option) !== void 0)) return anyString(schema);
114
+ const anyOf = (members) => z.union([...options, ...members]);
115
+ const discriminator = def["discriminator"];
116
+ if (discriminator === void 0) return anyOf(options.map(open));
117
+ const tags = /* @__PURE__ */ new Set();
118
+ const members = [];
119
+ for (const option of options) {
120
+ const tag = defOf(option)["shape"]?.[discriminator];
121
+ const values = tag ? strings(tag) : void 0;
122
+ if (!tag || !values) return anyOf(options.map(open));
123
+ for (const value of values) tags.add(value);
124
+ const member = open(option);
125
+ const memberShape = defOf(member)["shape"];
126
+ members.push(cloned(member, { shape: {
127
+ ...memberShape,
128
+ [discriminator]: tag
129
+ } }));
130
+ }
131
+ const newer = z.looseObject({ [discriminator]: z.string().refine((value) => !tags.has(value)) });
132
+ return anyOf([...members, newer]);
133
+ }
134
+ //#endregion
135
+ export { receivable };
136
+
137
+ //# sourceMappingURL=receive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receive.js","names":[],"sources":["../src/receive.ts"],"sourcesContent":["/**\n * Reading what a newer peer sends (HO-07, D32, #45). Within a revision a peer may add values to an\n * enum and members to a union: the wire schemas' evolution rule counts both as additive\n * (`tools/schemas/compat.ts`). A receiver checking such a message against the schemas it was built\n * with would refuse the whole message for one value it doesn't know, so it checks it against\n * {@link receivable}'s copy instead, as the Rust crate's wire types read an `Unknown` variant.\n */\nimport * as z from \"zod\";\n\n/** A Zod node's definition, as far as {@link receivable} reads it. */\ninterface Def {\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\nconst opened = new WeakMap<z.ZodType, z.ZodType>();\n\n/**\n * `schema` as a receiver of a newer peer's messages checks it: every string enum and every union\n * of string literals accepts any string (an enum's own checks still run, and an enum-keyed record\n * still needs every key it names); a discriminated union accepts, besides its members, an object\n * whose discriminator is a string none of them has, kept whole; strict objects drop unknown fields\n * rather than refuse them. Everything else (fields, types, required members, limits) is checked as\n * before, so a message a newer peer couldn't have sent still fails, and a message `schema` accepts\n * reads exactly as `schema` reads it: a union tries its members as built before their opened\n * copies, and a discriminated union's members keep their own tags.\n *\n * The result keeps `schema`'s TypeScript type, the shape this side was built for: a value the type\n * doesn't name means a newer peer. Code that branches on such a field handles the other case, and\n * a gate (a verdict, a check, a delivery) passes only on a value it knows means passing, never on\n * the absence of the one it knows means failing.\n *\n * ```ts\n * const parsed = receivable(definition.result).safeParse(raw);\n * ```\n */\nexport function receivable<T>(schema: z.ZodType<T>): z.ZodType<T> {\n return open(schema) as z.ZodType<T>;\n}\n\nfunction open(schema: z.ZodType): z.ZodType {\n const known = opened.get(schema);\n if (known) return known;\n // A recursive schema (Zod's getter idiom) reaches itself while it is being opened: it finds this\n // stand-in, which reads the finished copy when a message is checked (Opus review of MT-01, 7).\n let result: z.ZodType | undefined;\n opened.set(\n schema,\n z.lazy(() => result ?? schema),\n );\n result = rebuild(schema);\n opened.set(schema, result);\n return result;\n}\n\n/** Any string, with the checks `schema` carries (an enum's `.refine`, say). */\nfunction anyString(schema: z.ZodType): z.ZodType {\n const checks = defOf(schema)[\"checks\"] as unknown[] | undefined;\n return checks?.length ? cloned(z.string(), { checks }) : z.string();\n}\n\nfunction defOf(schema: z.ZodType): Def {\n return (schema as unknown as { _zod: { def: Def } })._zod.def;\n}\n\n/** A copy of `schema` with some of its definition replaced; its checks and settings stay. */\nfunction cloned(schema: z.ZodType, changes: Record<string, unknown>): z.ZodType {\n return (schema as unknown as { clone(def: Def): z.ZodType }).clone({\n ...defOf(schema),\n ...changes,\n });\n}\n\n/** The string values of a literal or enum node, or undefined when it has others. */\nfunction strings(schema: z.ZodType): string[] | undefined {\n const def = defOf(schema);\n const values =\n def.type === \"literal\"\n ? (def[\"values\"] as unknown[])\n : def.type === \"enum\"\n ? Object.values(def[\"entries\"] as Record<string, unknown>)\n : undefined;\n return values?.every((value) => typeof value === \"string\") ? (values as string[]) : undefined;\n}\n\nfunction rebuild(schema: z.ZodType): z.ZodType {\n const def = defOf(schema);\n switch (def.type) {\n case \"enum\":\n return strings(schema) ? anyString(schema) : schema;\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"prefault\":\n case \"nonoptional\":\n case \"catch\":\n return cloned(schema, { innerType: open(def[\"innerType\"] as z.ZodType) });\n case \"array\":\n return cloned(schema, { element: open(def[\"element\"] as z.ZodType) });\n case \"object\": {\n const shape = def[\"shape\"] as Record<string, z.ZodType>;\n const catchall = def[\"catchall\"] as z.ZodType | undefined;\n return cloned(schema, {\n shape: Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, open(value)])),\n // A strict object (catchall `never`) would refuse a field a newer peer adds: it is dropped\n // instead. A loose object keeps passing its fields through, and a typed catchall keeps\n // checking them (GPT review of MT-01: the bridge's host context passes fields through).\n catchall:\n catchall === undefined || defOf(catchall).type === \"never\" ? undefined : open(catchall),\n });\n }\n case \"record\": {\n const keyType = def[\"keyType\"] as z.ZodType;\n // Keys from an enum: every one it names is still required, and a key a newer peer adds\n // passes through, as Zod's loose records do (Opus review of MT-01, 2).\n if (strings(keyType) && !def[\"partial\"]) {\n return cloned(schema, { valueType: open(def[\"valueType\"] as z.ZodType), mode: \"loose\" });\n }\n return cloned(schema, {\n keyType: open(keyType),\n valueType: open(def[\"valueType\"] as z.ZodType),\n });\n }\n case \"tuple\":\n return cloned(schema, {\n items: (def[\"items\"] as z.ZodType[]).map(open),\n rest: def[\"rest\"] ? open(def[\"rest\"] as z.ZodType) : def[\"rest\"],\n });\n case \"intersection\":\n return cloned(schema, {\n left: open(def[\"left\"] as z.ZodType),\n right: open(def[\"right\"] as z.ZodType),\n });\n case \"pipe\":\n return cloned(schema, { in: open(def[\"in\"] as z.ZodType) });\n case \"lazy\": {\n const getter = def[\"getter\"] as () => z.ZodType;\n return z.lazy(() => open(getter()));\n }\n case \"union\":\n return union(schema, def);\n default:\n return schema;\n }\n}\n\nfunction union(schema: z.ZodType, def: Def): z.ZodType {\n const options = def[\"options\"] as z.ZodType[];\n // A union of string literals is an enum written another way.\n if (options.every((option) => strings(option) !== undefined)) return anyString(schema);\n // The members as built come first, so whatever they accept reads as before; their opened copies\n // only take what none of them does (Opus review of MT-01, 1).\n const anyOf = (members: z.ZodType[]): z.ZodType =>\n z.union([...options, ...members] as [z.ZodType, ...z.ZodType[]]);\n const discriminator = def[\"discriminator\"] as string | undefined;\n if (discriminator === undefined) return anyOf(options.map(open));\n const tags = new Set<string>();\n const members: z.ZodType[] = [];\n for (const option of options) {\n const shape = defOf(option)[\"shape\"] as Record<string, z.ZodType> | undefined;\n const tag = shape?.[discriminator];\n const values = tag ? strings(tag) : undefined;\n // A member whose tag isn't a string literal: no newer member can be told from a broken one.\n if (!tag || !values) return anyOf(options.map(open));\n for (const value of values) tags.add(value);\n // An opened member keeps its own tag: widened, an enum tag would take every member's messages.\n const member = open(option);\n const memberShape = defOf(member)[\"shape\"] as Record<string, z.ZodType>;\n members.push(cloned(member, { shape: { ...memberShape, [discriminator]: tag } }));\n }\n const newer = z.looseObject({\n [discriminator]: z.string().refine((value) => !tags.has(value)),\n });\n return anyOf([...members, newer]);\n}\n"],"mappings":";;;;;;;;;AAeA,MAAM,yBAAS,IAAI,QAA8B;;;;;;;;;;;;;;;;;;;;AAqBjD,SAAgB,WAAc,QAAoC;CAChE,OAAO,KAAK,MAAM;AACpB;AAEA,SAAS,KAAK,QAA8B;CAC1C,MAAM,QAAQ,OAAO,IAAI,MAAM;CAC/B,IAAI,OAAO,OAAO;CAGlB,IAAI;CACJ,OAAO,IACL,QACA,EAAE,WAAW,UAAU,MAAM,CAC/B;CACA,SAAS,QAAQ,MAAM;CACvB,OAAO,IAAI,QAAQ,MAAM;CACzB,OAAO;AACT;;AAGA,SAAS,UAAU,QAA8B;CAC/C,MAAM,SAAS,MAAM,MAAM,CAAC,CAAC;CAC7B,OAAO,QAAQ,SAAS,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO;AACpE;AAEA,SAAS,MAAM,QAAwB;CACrC,OAAQ,OAA6C,KAAK;AAC5D;;AAGA,SAAS,OAAO,QAAmB,SAA6C;CAC9E,OAAQ,OAAqD,MAAM;EACjE,GAAG,MAAM,MAAM;EACf,GAAG;CACL,CAAC;AACH;;AAGA,SAAS,QAAQ,QAAyC;CACxD,MAAM,MAAM,MAAM,MAAM;CACxB,MAAM,SACJ,IAAI,SAAS,YACR,IAAI,YACL,IAAI,SAAS,SACX,OAAO,OAAO,IAAI,UAAqC,IACvD,KAAA;CACR,OAAO,QAAQ,OAAO,UAAU,OAAO,UAAU,QAAQ,IAAK,SAAsB,KAAA;AAC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,6 +1,6 @@
1
1
  import { Diagnostic } from "../diagnostics/diagnostic.js";
2
2
  import "../diagnostics/spec.js";
3
- import "../diagnostics/codes/host.js";
3
+ import "../diagnostics/codes/host-core.js";
4
4
  import { JsonRpcErrorObject } from "./messages.js";
5
5
  //#region src/rpc/error.d.ts
6
6
  /** The JSON-RPC 2.0 error codes Mostra uses (INTERFACES §6). */
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.ts","names":[],"sources":["../../src/rpc/error.ts"],"mappings":";;;;;;qBAUa;;WAEF;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;;;;;;;;qBAoCE,iBAAiB;;WAEnB;;WAEA,YAAY;EAErB,YAAY,YAAY,YAAY;;EAQpC,iBAAiB;;;;;SAQV,gBAAgB,OAAO,oBAAoB,oBAAoB"}
1
+ {"version":3,"file":"error.d.ts","names":[],"sources":["../../src/rpc/error.ts"],"mappings":";;;;;;qBAaa;;WAEF;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;;;;;;;;qBAoCE,iBAAiB;;WAEnB;;WAEA,YAAY;EAErB,YAAY,YAAY,YAAY;;EAQpC,iBAAiB;;;;;SAQV,gBAAgB,OAAO,oBAAoB,oBAAoB"}
package/dist/rpc/error.js CHANGED
@@ -1,4 +1,4 @@
1
- import { hostDiagnostics } from "../diagnostics/codes/host.js";
1
+ import { coreHostDiagnostics } from "../diagnostics/codes/host-core.js";
2
2
  import { Diagnostic } from "../diagnostics/diagnostic.js";
3
3
  import { buildDiagnostic } from "../diagnostics/spec.js";
4
4
  //#region src/rpc/error.ts
@@ -65,11 +65,11 @@ var RpcError = class RpcError extends Error {
65
65
  }
66
66
  };
67
67
  /**
68
- * Builds a HOST-area diagnostic from that area's catalog alone, so the JSON-RPC core doesn't pull
69
- * every area's text into browser bundles (D83).
68
+ * Builds one of the HOST-area diagnostics the JSON-RPC core raises, from their own catalog, so the
69
+ * core pulls neither the other areas' text nor the rest of HOST's into browser bundles (D83, #17).
70
70
  */
71
71
  function hostDiagnostic(code, details, docsBase) {
72
- return buildDiagnostic(code, hostDiagnostics[code], details, docsBase);
72
+ return buildDiagnostic(code, coreHostDiagnostics[code], details, docsBase);
73
73
  }
74
74
  //#endregion
75
75
  export { JSON_RPC_ERROR_CODES, RpcError, hostDiagnostic };
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","names":[],"sources":["../../src/rpc/error.ts"],"sourcesContent":["/**\n * Errors on a JSON-RPC connection. Every error carries a diagnostic (INTERFACES §1, §6): the\n * JSON-RPC `error.code` says which kind of failure it is, and `error.data` is the diagnostic.\n */\nimport { type HostDiagnosticCode, hostDiagnostics } from \"../diagnostics/codes/host.ts\";\nimport { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport { buildDiagnostic, type DiagnosticDetails } from \"../diagnostics/spec.ts\";\nimport type { JsonRpcErrorObject } from \"./messages.ts\";\n\n/** The JSON-RPC 2.0 error codes Mostra uses (INTERFACES §6). */\nexport const JSON_RPC_ERROR_CODES: {\n /** The line wasn't valid JSON. */\n readonly parseError: -32700;\n /** The message wasn't a valid request, or was a batch. */\n readonly invalidRequest: -32600;\n /** The method doesn't exist on this side. */\n readonly methodNotFound: -32601;\n /** The params failed the method's schema. */\n readonly invalidParams: -32602;\n /** An unexpected failure. */\n readonly internalError: -32603;\n /** Every other diagnostic. */\n readonly diagnostic: -32000;\n} = {\n parseError: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internalError: -32603,\n diagnostic: -32000,\n};\n\nfunction codeFor(diagnostic: Diagnostic): number {\n switch (diagnostic.code) {\n case \"MOSTRA_HOST_MALFORMED\":\n return JSON_RPC_ERROR_CODES.invalidRequest;\n case \"MOSTRA_HOST_METHOD_UNKNOWN\":\n return JSON_RPC_ERROR_CODES.methodNotFound;\n case \"MOSTRA_HOST_INVALID_PARAMS\":\n return JSON_RPC_ERROR_CODES.invalidParams;\n case \"MOSTRA_HOST_INTERNAL_ERROR\":\n return JSON_RPC_ERROR_CODES.internalError;\n default:\n return JSON_RPC_ERROR_CODES.diagnostic;\n }\n}\n\n/**\n * An error that crosses a connection as a JSON-RPC error. Throw it from a request handler to\n * answer with this diagnostic; a request's promise rejects with it when the other side answers\n * with an error, the connection closes or the request times out.\n *\n * ```ts\n * throw new RpcError(\n * createDiagnostic(\"MOSTRA_HOME_MISMATCH\", { message: \"This instance serves /a, not /b.\" }),\n * );\n * ```\n */\nexport class RpcError extends Error {\n /** The JSON-RPC error code. */\n readonly code: number;\n /** The diagnostic: what happened and what to do. */\n readonly diagnostic: Diagnostic;\n\n constructor(diagnostic: Diagnostic, code: number = codeFor(diagnostic)) {\n super(diagnostic.message);\n this.name = \"RpcError\";\n this.code = code;\n this.diagnostic = diagnostic;\n }\n\n /** The JSON-RPC error object for a response. */\n toErrorObject(): JsonRpcErrorObject {\n return { code: this.code, message: this.diagnostic.message, data: this.diagnostic };\n }\n\n /**\n * Reads a received error object. When its `data` isn't a diagnostic (a peer that isn't Mostra),\n * the result is a `MOSTRA_HOST_MALFORMED` diagnostic that keeps the peer's message.\n */\n static fromErrorObject(error: JsonRpcErrorObject, docsBase?: string): RpcError {\n const parsed = Diagnostic.safeParse(error.data);\n if (parsed.success) return new RpcError(parsed.data, error.code);\n return new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n {\n message: `The other side answered with error ${error.code} without a diagnostic: ${error.message.slice(0, 200)}`,\n },\n docsBase,\n ),\n error.code,\n );\n }\n}\n\n/**\n * Builds a HOST-area diagnostic from that area's catalog alone, so the JSON-RPC core doesn't pull\n * every area's text into browser bundles (D83).\n */\nexport function hostDiagnostic(\n code: HostDiagnosticCode,\n details: DiagnosticDetails,\n docsBase?: string,\n): Diagnostic {\n return buildDiagnostic(code, hostDiagnostics[code], details, docsBase);\n}\n"],"mappings":";;;;;;;;;AAUA,MAAa,uBAaT;CACF,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,YAAY;AACd;AAEA,SAAS,QAAQ,YAAgC;CAC/C,QAAQ,WAAW,MAAnB;EACE,KAAK,yBACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,SACE,OAAO,qBAAqB;CAChC;AACF;;;;;;;;;;;;AAaA,IAAa,WAAb,MAAa,iBAAiB,MAAM;;CAElC;;CAEA;CAEA,YAAY,YAAwB,OAAe,QAAQ,UAAU,GAAG;EACtE,MAAM,WAAW,OAAO;EACxB,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;;CAGA,gBAAoC;EAClC,OAAO;GAAE,MAAM,KAAK;GAAM,SAAS,KAAK,WAAW;GAAS,MAAM,KAAK;EAAW;CACpF;;;;;CAMA,OAAO,gBAAgB,OAA2B,UAA6B;EAC7E,MAAM,SAAS,WAAW,UAAU,MAAM,IAAI;EAC9C,IAAI,OAAO,SAAS,OAAO,IAAI,SAAS,OAAO,MAAM,MAAM,IAAI;EAC/D,OAAO,IAAI,SACT,eACE,yBACA,EACE,SAAS,sCAAsC,MAAM,KAAK,yBAAyB,MAAM,QAAQ,MAAM,GAAG,GAAG,IAC/G,GACA,QACF,GACA,MAAM,IACR;CACF;AACF;;;;;AAMA,SAAgB,eACd,MACA,SACA,UACY;CACZ,OAAO,gBAAgB,MAAM,gBAAgB,OAAO,SAAS,QAAQ;AACvE"}
1
+ {"version":3,"file":"error.js","names":[],"sources":["../../src/rpc/error.ts"],"sourcesContent":["/**\n * Errors on a JSON-RPC connection. Every error carries a diagnostic (INTERFACES §1, §6): the\n * JSON-RPC `error.code` says which kind of failure it is, and `error.data` is the diagnostic.\n */\nimport {\n type CoreHostDiagnosticCode,\n coreHostDiagnostics,\n} from \"../diagnostics/codes/host-core.ts\";\nimport { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport { buildDiagnostic, type DiagnosticDetails } from \"../diagnostics/spec.ts\";\nimport type { JsonRpcErrorObject } from \"./messages.ts\";\n\n/** The JSON-RPC 2.0 error codes Mostra uses (INTERFACES §6). */\nexport const JSON_RPC_ERROR_CODES: {\n /** The line wasn't valid JSON. */\n readonly parseError: -32700;\n /** The message wasn't a valid request, or was a batch. */\n readonly invalidRequest: -32600;\n /** The method doesn't exist on this side. */\n readonly methodNotFound: -32601;\n /** The params failed the method's schema. */\n readonly invalidParams: -32602;\n /** An unexpected failure. */\n readonly internalError: -32603;\n /** Every other diagnostic. */\n readonly diagnostic: -32000;\n} = {\n parseError: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internalError: -32603,\n diagnostic: -32000,\n};\n\nfunction codeFor(diagnostic: Diagnostic): number {\n switch (diagnostic.code) {\n case \"MOSTRA_HOST_MALFORMED\":\n return JSON_RPC_ERROR_CODES.invalidRequest;\n case \"MOSTRA_HOST_METHOD_UNKNOWN\":\n return JSON_RPC_ERROR_CODES.methodNotFound;\n case \"MOSTRA_HOST_INVALID_PARAMS\":\n return JSON_RPC_ERROR_CODES.invalidParams;\n case \"MOSTRA_HOST_INTERNAL_ERROR\":\n return JSON_RPC_ERROR_CODES.internalError;\n default:\n return JSON_RPC_ERROR_CODES.diagnostic;\n }\n}\n\n/**\n * An error that crosses a connection as a JSON-RPC error. Throw it from a request handler to\n * answer with this diagnostic; a request's promise rejects with it when the other side answers\n * with an error, the connection closes or the request times out.\n *\n * ```ts\n * throw new RpcError(\n * createDiagnostic(\"MOSTRA_HOME_MISMATCH\", { message: \"This instance serves /a, not /b.\" }),\n * );\n * ```\n */\nexport class RpcError extends Error {\n /** The JSON-RPC error code. */\n readonly code: number;\n /** The diagnostic: what happened and what to do. */\n readonly diagnostic: Diagnostic;\n\n constructor(diagnostic: Diagnostic, code: number = codeFor(diagnostic)) {\n super(diagnostic.message);\n this.name = \"RpcError\";\n this.code = code;\n this.diagnostic = diagnostic;\n }\n\n /** The JSON-RPC error object for a response. */\n toErrorObject(): JsonRpcErrorObject {\n return { code: this.code, message: this.diagnostic.message, data: this.diagnostic };\n }\n\n /**\n * Reads a received error object. When its `data` isn't a diagnostic (a peer that isn't Mostra),\n * the result is a `MOSTRA_HOST_MALFORMED` diagnostic that keeps the peer's message.\n */\n static fromErrorObject(error: JsonRpcErrorObject, docsBase?: string): RpcError {\n const parsed = Diagnostic.safeParse(error.data);\n if (parsed.success) return new RpcError(parsed.data, error.code);\n return new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n {\n message: `The other side answered with error ${error.code} without a diagnostic: ${error.message.slice(0, 200)}`,\n },\n docsBase,\n ),\n error.code,\n );\n }\n}\n\n/**\n * Builds one of the HOST-area diagnostics the JSON-RPC core raises, from their own catalog, so the\n * core pulls neither the other areas' text nor the rest of HOST's into browser bundles (D83, #17).\n */\nexport function hostDiagnostic(\n code: CoreHostDiagnosticCode,\n details: DiagnosticDetails,\n docsBase?: string,\n): Diagnostic {\n return buildDiagnostic(code, coreHostDiagnostics[code], details, docsBase);\n}\n"],"mappings":";;;;;;;;;AAaA,MAAa,uBAaT;CACF,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,YAAY;AACd;AAEA,SAAS,QAAQ,YAAgC;CAC/C,QAAQ,WAAW,MAAnB;EACE,KAAK,yBACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,SACE,OAAO,qBAAqB;CAChC;AACF;;;;;;;;;;;;AAaA,IAAa,WAAb,MAAa,iBAAiB,MAAM;;CAElC;;CAEA;CAEA,YAAY,YAAwB,OAAe,QAAQ,UAAU,GAAG;EACtE,MAAM,WAAW,OAAO;EACxB,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;;CAGA,gBAAoC;EAClC,OAAO;GAAE,MAAM,KAAK;GAAM,SAAS,KAAK,WAAW;GAAS,MAAM,KAAK;EAAW;CACpF;;;;;CAMA,OAAO,gBAAgB,OAA2B,UAA6B;EAC7E,MAAM,SAAS,WAAW,UAAU,MAAM,IAAI;EAC9C,IAAI,OAAO,SAAS,OAAO,IAAI,SAAS,OAAO,MAAM,MAAM,IAAI;EAC/D,OAAO,IAAI,SACT,eACE,yBACA,EACE,SAAS,sCAAsC,MAAM,KAAK,yBAAyB,MAAM,QAAQ,MAAM,GAAG,GAAG,IAC/G,GACA,QACF,GACA,MAAM,IACR;CACF;AACF;;;;;AAMA,SAAgB,eACd,MACA,SACA,UACY;CACZ,OAAO,gBAAgB,MAAM,oBAAoB,OAAO,SAAS,QAAQ;AAC3E"}
@@ -60,7 +60,9 @@ export declare class RpcPeer {
60
60
  request(method: string, params?: JsonRpcParams, options?: RpcRequestOptions): Promise<unknown>;
61
61
  /**
62
62
  * Calls a protocol method: validates the params before sending and the result on arrival. A
63
- * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`.
63
+ * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`. The result is
64
+ * read as {@link receivable} reads it, so an enum value or union member a newer peer added
65
+ * within the revision arrives as sent (#45).
64
66
  */
65
67
  call<P, R>(definition: MethodDefinition<P, R>, params: P, options?: RpcRequestOptions): Promise<R>;
66
68
  /** Sends a notification. Does nothing once the peer is closed. */
@@ -1 +1 @@
1
- {"version":3,"file":"peer.d.ts","names":[],"sources":["../../src/rpc/peer.ts"],"mappings":";;;;;iBA0BiB;;WAEN,IAAI;;WAEJ;;;iBAIM;;;;;EAKf,KAAK,SAAS;;;;;;;EAOd,WAAW,gBAAgB,iBAAiB,SAAS;;EAErD,gBAAgB,gBAAgB;;EAEhC,iBAAiB,gBAAgB;;WAExB;;;iBAIM;;;;;WAKN;;;qBAWE;;EAMX,YAAY,SAAS;;MAKjB;;MAKA;;;;;EAQJ,YAAY;;EAkBZ,QAAQ;;;;;EAwCR,QACE,gBACA,SAAS,eACT,UAAS,oBACR;;;;;EA+BH,KAAW,GAAG,GACZ,YAAY,iBAAiB,GAAG,IAChC,QAAQ,GACR,UAAS,oBACR,QAAQ;;EAcX,OAAO,gBAAgB,SAAS;;;;;EAWhC,MAAM,aAAa;;;;;;;wBA4GL,YAAY,GAAG,GAC7B,YAAY,iBAAiB,GAAG,IAChC,iBACA,oBACC"}
1
+ {"version":3,"file":"peer.d.ts","names":[],"sources":["../../src/rpc/peer.ts"],"mappings":";;;;;iBA2BiB;;WAEN,IAAI;;WAEJ;;;iBAIM;;;;;EAKf,KAAK,SAAS;;;;;;;EAOd,WAAW,gBAAgB,iBAAiB,SAAS;;EAErD,gBAAgB,gBAAgB;;EAEhC,iBAAiB,gBAAgB;;WAExB;;;iBAIM;;;;;WAKN;;;qBAWE;;EAMX,YAAY,SAAS;;MAKjB;;MAKA;;;;;EAQJ,YAAY;;EAkBZ,QAAQ;;;;;EAwCR,QACE,gBACA,SAAS,eACT,UAAS,oBACR;;;;;;;EAiCH,KAAW,GAAG,GACZ,YAAY,iBAAiB,GAAG,IAChC,QAAQ,GACR,UAAS,oBACR,QAAQ;;EAcX,OAAO,gBAAgB,SAAS;;;;;EAWhC,MAAM,aAAa;;;;;;;wBA4GL,YAAY,GAAG,GAC7B,YAAY,iBAAiB,GAAG,IAChC,iBACA,oBACC"}
package/dist/rpc/peer.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { JSON_RPC_ERROR_CODES, RpcError, hostDiagnostic } from "./error.js";
2
2
  import { classifyMessage } from "./messages.js";
3
+ import { receivable } from "../receive.js";
3
4
  //#region src/rpc/peer.ts
4
5
  /** One end of a JSON-RPC 2.0 connection. */
5
6
  var RpcPeer = class {
@@ -89,12 +90,14 @@ var RpcPeer = class {
89
90
  }
90
91
  /**
91
92
  * Calls a protocol method: validates the params before sending and the result on arrival. A
92
- * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`.
93
+ * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`. The result is
94
+ * read as {@link receivable} reads it, so an enum value or union member a newer peer added
95
+ * within the revision arrives as sent (#45).
93
96
  */
94
97
  async call(definition, params, options = {}) {
95
98
  const checked = parseParams(definition, params, this.#options.docsBase);
96
99
  const raw = await this.request(definition.method, checked, options);
97
- const parsed = definition.result.safeParse(raw);
100
+ const parsed = receivable(definition.result).safeParse(raw);
98
101
  if (parsed.success) return parsed.data;
99
102
  throw new RpcError(this.#diagnostic("MOSTRA_HOST_MALFORMED", `The result of ${definition.method} doesn't match its schema: ${describeIssue(parsed.error.issues)}`));
100
103
  }
@@ -1 +1 @@
1
- {"version":3,"file":"peer.js","names":[],"sources":["../../src/rpc/peer.ts"],"sourcesContent":["/**\n * One end of a JSON-RPC 2.0 connection (D83): it matches responses to requests, dispatches\n * incoming requests and notifications, and turns every failure into a diagnostic. It has no I/O.\n * The transport hands it parsed messages (or raw lines) and sends what it gives back, so the same\n * peer serves stdio, Unix sockets, Node IPC and `postMessage`.\n *\n * ```ts\n * const peer = new RpcPeer({\n * send: (message) => socket.write(encodeLine(message)),\n * onRequest: (method, params) => handlers[method](params),\n * });\n * splitter.push(chunk).forEach((line) => peer.receiveLine(line));\n * const result = await peer.call(mostraInitializeMethod, params);\n * ```\n */\nimport type { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport type { MethodDefinition } from \"../method.ts\";\nimport { hostDiagnostic, JSON_RPC_ERROR_CODES, RpcError } from \"./error.ts\";\nimport {\n classifyMessage,\n type JsonRpcId,\n type JsonRpcMessage,\n type JsonRpcParams,\n} from \"./messages.ts\";\n\n/** What a request handler learns about the request besides its params. */\nexport interface RpcRequestContext {\n /** The request's ID. */\n readonly id: JsonRpcId;\n /** The method name. */\n readonly method: string;\n}\n\n/** Options for {@link RpcPeer}. */\nexport interface RpcPeerOptions {\n /**\n * Sends one message. The transport serializes it (`encodeLine` for newline-delimited streams).\n * Throwing means the transport is gone: the peer closes.\n */\n send(message: JsonRpcMessage): void;\n /**\n * Answers an incoming request. Return the result, or throw an {@link RpcError} to answer with\n * its diagnostic. Any other exception is answered with `MOSTRA_HOST_INTERNAL_ERROR`, without\n * its details, and reported to `onInternalError`. Without a handler, every request is answered\n * with `MOSTRA_HOST_METHOD_UNKNOWN`.\n */\n onRequest?(method: string, params: unknown, context: RpcRequestContext): unknown;\n /** Receives an incoming notification. Exceptions are reported to `onInternalError`. */\n onNotification?(method: string, params: unknown): void;\n /** Reports an unexpected exception from a handler, for logging. */\n onInternalError?(error: unknown, method: string): void;\n /** The docs base URL for diagnostics the peer creates. Default `DEFAULT_DOCS_BASE`. */\n readonly docsBase?: string;\n}\n\n/** Options for one outgoing request. */\nexport interface RpcRequestOptions {\n /**\n * Gives up after this many milliseconds with `MOSTRA_HOST_TIMEOUT`. A late response is\n * ignored. Default: no timeout (FAILURE_MODEL §9).\n */\n readonly timeoutMs?: number;\n}\n\ninterface Pending {\n readonly method: string;\n resolve(result: unknown): void;\n reject(error: RpcError): void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/** One end of a JSON-RPC 2.0 connection. */\nexport class RpcPeer {\n readonly #options: RpcPeerOptions;\n readonly #pending = new Map<JsonRpcId, Pending>();\n #nextId = 1;\n #closed: Diagnostic | undefined;\n\n constructor(options: RpcPeerOptions) {\n this.#options = options;\n }\n\n /** Whether the peer has closed. A closed peer sends nothing and rejects new requests. */\n get closed(): boolean {\n return this.#closed !== undefined;\n }\n\n /** How many outgoing requests are waiting for a response. */\n get pendingRequests(): number {\n return this.#pending.size;\n }\n\n /**\n * Receives one line of a newline-delimited stream. Blank lines are skipped; a line that isn't\n * JSON is answered with a parse error (-32700).\n */\n receiveLine(line: string): void {\n if (line.trim() === \"\") return;\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch {\n this.#reply(null, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", \"A line wasn't valid JSON.\"),\n JSON_RPC_ERROR_CODES.parseError,\n ),\n });\n return;\n }\n this.receive(value);\n }\n\n /** Receives one parsed message. */\n receive(value: unknown): void {\n if (this.#closed) return;\n const classified = classifyMessage(value);\n switch (classified.kind) {\n case \"request\":\n this.#handleRequest(\n classified.message.id,\n classified.message.method,\n classified.message.params,\n );\n return;\n case \"notification\":\n this.#handleNotification(classified.message.method, classified.message.params);\n return;\n case \"success\":\n this.#settle(classified.message.id, (pending) =>\n pending.resolve(classified.message.result),\n );\n return;\n case \"failure\": {\n const { id, error } = classified.message;\n if (id !== null) {\n this.#settle(id, (pending) =>\n pending.reject(RpcError.fromErrorObject(error, this.#options.docsBase)),\n );\n }\n return;\n }\n case \"invalid\":\n this.#reply(classified.id, {\n rpc: new RpcError(this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", classified.reason)),\n });\n return;\n }\n }\n\n /**\n * Sends a request and resolves with its result, or rejects with an {@link RpcError}: the\n * other side's diagnostic, `MOSTRA_HOST_TIMEOUT` or `MOSTRA_HOST_CONNECTION_CLOSED`.\n */\n request(\n method: string,\n params?: JsonRpcParams,\n options: RpcRequestOptions = {},\n ): Promise<unknown> {\n if (this.#closed) return Promise.reject(new RpcError(this.#closed));\n const id = this.#nextId++;\n return new Promise<unknown>((resolve, reject) => {\n const pending: Pending = { method, resolve, reject };\n if (options.timeoutMs !== undefined) {\n pending.timer = setTimeout(() => {\n this.#pending.delete(id);\n reject(\n new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_TIMEOUT\",\n `No response to ${method} within ${options.timeoutMs} ms.`,\n ),\n ),\n );\n }, options.timeoutMs);\n }\n this.#pending.set(id, pending);\n this.#send(\n params === undefined\n ? { jsonrpc: \"2.0\", id, method }\n : { jsonrpc: \"2.0\", id, method, params },\n );\n });\n }\n\n /**\n * Calls a protocol method: validates the params before sending and the result on arrival. A\n * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`.\n */\n async call<P, R>(\n definition: MethodDefinition<P, R>,\n params: P,\n options: RpcRequestOptions = {},\n ): Promise<R> {\n const checked = parseParams(definition, params, this.#options.docsBase);\n const raw = await this.request(definition.method, checked as JsonRpcParams, options);\n const parsed = definition.result.safeParse(raw);\n if (parsed.success) return parsed.data;\n throw new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n `The result of ${definition.method} doesn't match its schema: ${describeIssue(parsed.error.issues)}`,\n ),\n );\n }\n\n /** Sends a notification. Does nothing once the peer is closed. */\n notify(method: string, params?: JsonRpcParams): void {\n if (this.#closed) return;\n this.#send(\n params === undefined ? { jsonrpc: \"2.0\", method } : { jsonrpc: \"2.0\", method, params },\n );\n }\n\n /**\n * Closes the peer: every waiting request rejects with `diagnostic` (by default\n * `MOSTRA_HOST_CONNECTION_CLOSED`), and later messages are ignored. Idempotent.\n */\n close(diagnostic?: Diagnostic): void {\n if (this.#closed) return;\n const reason =\n diagnostic ??\n this.#diagnostic(\n \"MOSTRA_HOST_CONNECTION_CLOSED\",\n \"The connection closed before a response arrived.\",\n );\n this.#closed = reason;\n const pending = [...this.#pending.values()];\n this.#pending.clear();\n for (const entry of pending) {\n if (entry.timer !== undefined) clearTimeout(entry.timer);\n entry.reject(new RpcError(reason));\n }\n }\n\n #handleRequest(id: JsonRpcId, method: string, params: unknown): void {\n const handler = this.#options.onRequest;\n if (!handler) {\n this.#reply(id, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_METHOD_UNKNOWN\", `This side serves no method ${method}.`),\n ),\n });\n return;\n }\n let outcome: unknown;\n try {\n outcome = handler(method, params, { id, method });\n } catch (error) {\n this.#reply(id, { rpc: this.#asRpcError(error, method) });\n return;\n }\n Promise.resolve(outcome).then(\n (result) => this.#reply(id, { result: result === undefined ? null : result }),\n (error: unknown) => this.#reply(id, { rpc: this.#asRpcError(error, method) }),\n );\n }\n\n #handleNotification(method: string, params: unknown): void {\n try {\n this.#options.onNotification?.(method, params);\n } catch (error) {\n this.#options.onInternalError?.(error, method);\n }\n }\n\n #asRpcError(error: unknown, method: string): RpcError {\n if (error instanceof RpcError) return error;\n this.#options.onInternalError?.(error, method);\n return new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", `${method} failed unexpectedly.`),\n );\n }\n\n #settle(id: JsonRpcId, action: (pending: Pending) => void): void {\n const pending = this.#pending.get(id);\n if (!pending) return;\n this.#pending.delete(id);\n if (pending.timer !== undefined) clearTimeout(pending.timer);\n action(pending);\n }\n\n #reply(id: JsonRpcId | null, outcome: { result: unknown } | { rpc: RpcError }): void {\n if (this.#closed) return;\n if (\"rpc\" in outcome) {\n this.#send({ jsonrpc: \"2.0\", id, error: outcome.rpc.toErrorObject() });\n } else if (id !== null) {\n this.#send({ jsonrpc: \"2.0\", id, result: outcome.result });\n }\n }\n\n #send(message: JsonRpcMessage): void {\n try {\n this.#options.send(message);\n } catch {\n this.close();\n }\n }\n\n #diagnostic(\n code:\n | \"MOSTRA_HOST_MALFORMED\"\n | \"MOSTRA_HOST_METHOD_UNKNOWN\"\n | \"MOSTRA_HOST_INTERNAL_ERROR\"\n | \"MOSTRA_HOST_TIMEOUT\"\n | \"MOSTRA_HOST_CONNECTION_CLOSED\",\n message: string,\n ): Diagnostic {\n return hostDiagnostic(code, { message }, this.#options.docsBase);\n }\n}\n\nfunction describeIssue(\n issues: readonly { readonly path: readonly PropertyKey[]; readonly message: string }[],\n): string {\n const [first] = issues;\n if (!first) return \"unknown problem\";\n const path = first.path.map(String).join(\".\");\n return `${path === \"\" ? \"(root)\" : path}: ${first.message}`;\n}\n\n/**\n * Validates a method's params against its schema and returns the parsed value. Throws an\n * {@link RpcError} with `MOSTRA_HOST_INVALID_PARAMS` naming the first problem; the message\n * describes types and paths, never the values sent.\n */\nexport function parseParams<P, R>(\n definition: MethodDefinition<P, R>,\n params: unknown,\n docsBase?: string,\n): P {\n const parsed = definition.params.safeParse(params ?? {});\n if (parsed.success) return parsed.data;\n throw new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_INVALID_PARAMS\",\n { message: `Invalid params for ${definition.method}: ${describeIssue(parsed.error.issues)}` },\n docsBase,\n ),\n );\n}\n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,KAAA,GAAW,aAAa,QAAQ,KAAK;EAC3D,OAAO,OAAO;CAChB;CAEA,OAAO,IAAsB,SAAwD;EACnF,IAAI,KAAK,SAAS;EAClB,IAAI,SAAS,SACX,KAAK,MAAM;GAAE,SAAS;GAAO;GAAI,OAAO,QAAQ,IAAI,cAAc;EAAE,CAAC;OAChE,IAAI,OAAO,MAChB,KAAK,MAAM;GAAE,SAAS;GAAO;GAAI,QAAQ,QAAQ;EAAO,CAAC;CAE7D;CAEA,MAAM,SAA+B;EACnC,IAAI;GACF,KAAK,SAAS,KAAK,OAAO;EAC5B,QAAQ;GACN,KAAK,MAAM;EACb;CACF;CAEA,YACE,MAMA,SACY;EACZ,OAAO,eAAe,MAAM,EAAE,QAAQ,GAAG,KAAK,SAAS,QAAQ;CACjE;AACF;AAEA,SAAS,cACP,QACQ;CACR,MAAM,CAAC,SAAS;CAChB,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,OAAO,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,KAAK,GAAG;CAC5C,OAAO,GAAG,SAAS,KAAK,WAAW,KAAK,IAAI,MAAM;AACpD;;;;;;AAOA,SAAgB,YACd,YACA,QACA,UACG;CACH,MAAM,SAAS,WAAW,OAAO,UAAU,UAAU,CAAC,CAAC;CACvD,IAAI,OAAO,SAAS,OAAO,OAAO;CAClC,MAAM,IAAI,SACR,eACE,8BACA,EAAE,SAAS,sBAAsB,WAAW,OAAO,IAAI,cAAc,OAAO,MAAM,MAAM,IAAI,GAC5F,QACF,CACF;AACF"}
1
+ {"version":3,"file":"peer.js","names":[],"sources":["../../src/rpc/peer.ts"],"sourcesContent":["/**\n * One end of a JSON-RPC 2.0 connection (D83): it matches responses to requests, dispatches\n * incoming requests and notifications, and turns every failure into a diagnostic. It has no I/O.\n * The transport hands it parsed messages (or raw lines) and sends what it gives back, so the same\n * peer serves stdio, Unix sockets, Node IPC and `postMessage`.\n *\n * ```ts\n * const peer = new RpcPeer({\n * send: (message) => socket.write(encodeLine(message)),\n * onRequest: (method, params) => handlers[method](params),\n * });\n * splitter.push(chunk).forEach((line) => peer.receiveLine(line));\n * const result = await peer.call(mostraInitializeMethod, params);\n * ```\n */\nimport type { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport type { MethodDefinition } from \"../method.ts\";\nimport { receivable } from \"../receive.ts\";\nimport { hostDiagnostic, JSON_RPC_ERROR_CODES, RpcError } from \"./error.ts\";\nimport {\n classifyMessage,\n type JsonRpcId,\n type JsonRpcMessage,\n type JsonRpcParams,\n} from \"./messages.ts\";\n\n/** What a request handler learns about the request besides its params. */\nexport interface RpcRequestContext {\n /** The request's ID. */\n readonly id: JsonRpcId;\n /** The method name. */\n readonly method: string;\n}\n\n/** Options for {@link RpcPeer}. */\nexport interface RpcPeerOptions {\n /**\n * Sends one message. The transport serializes it (`encodeLine` for newline-delimited streams).\n * Throwing means the transport is gone: the peer closes.\n */\n send(message: JsonRpcMessage): void;\n /**\n * Answers an incoming request. Return the result, or throw an {@link RpcError} to answer with\n * its diagnostic. Any other exception is answered with `MOSTRA_HOST_INTERNAL_ERROR`, without\n * its details, and reported to `onInternalError`. Without a handler, every request is answered\n * with `MOSTRA_HOST_METHOD_UNKNOWN`.\n */\n onRequest?(method: string, params: unknown, context: RpcRequestContext): unknown;\n /** Receives an incoming notification. Exceptions are reported to `onInternalError`. */\n onNotification?(method: string, params: unknown): void;\n /** Reports an unexpected exception from a handler, for logging. */\n onInternalError?(error: unknown, method: string): void;\n /** The docs base URL for diagnostics the peer creates. Default `DEFAULT_DOCS_BASE`. */\n readonly docsBase?: string;\n}\n\n/** Options for one outgoing request. */\nexport interface RpcRequestOptions {\n /**\n * Gives up after this many milliseconds with `MOSTRA_HOST_TIMEOUT`. A late response is\n * ignored. Default: no timeout (FAILURE_MODEL §9).\n */\n readonly timeoutMs?: number;\n}\n\ninterface Pending {\n readonly method: string;\n resolve(result: unknown): void;\n reject(error: RpcError): void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/** One end of a JSON-RPC 2.0 connection. */\nexport class RpcPeer {\n readonly #options: RpcPeerOptions;\n readonly #pending = new Map<JsonRpcId, Pending>();\n #nextId = 1;\n #closed: Diagnostic | undefined;\n\n constructor(options: RpcPeerOptions) {\n this.#options = options;\n }\n\n /** Whether the peer has closed. A closed peer sends nothing and rejects new requests. */\n get closed(): boolean {\n return this.#closed !== undefined;\n }\n\n /** How many outgoing requests are waiting for a response. */\n get pendingRequests(): number {\n return this.#pending.size;\n }\n\n /**\n * Receives one line of a newline-delimited stream. Blank lines are skipped; a line that isn't\n * JSON is answered with a parse error (-32700).\n */\n receiveLine(line: string): void {\n if (line.trim() === \"\") return;\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch {\n this.#reply(null, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", \"A line wasn't valid JSON.\"),\n JSON_RPC_ERROR_CODES.parseError,\n ),\n });\n return;\n }\n this.receive(value);\n }\n\n /** Receives one parsed message. */\n receive(value: unknown): void {\n if (this.#closed) return;\n const classified = classifyMessage(value);\n switch (classified.kind) {\n case \"request\":\n this.#handleRequest(\n classified.message.id,\n classified.message.method,\n classified.message.params,\n );\n return;\n case \"notification\":\n this.#handleNotification(classified.message.method, classified.message.params);\n return;\n case \"success\":\n this.#settle(classified.message.id, (pending) =>\n pending.resolve(classified.message.result),\n );\n return;\n case \"failure\": {\n const { id, error } = classified.message;\n if (id !== null) {\n this.#settle(id, (pending) =>\n pending.reject(RpcError.fromErrorObject(error, this.#options.docsBase)),\n );\n }\n return;\n }\n case \"invalid\":\n this.#reply(classified.id, {\n rpc: new RpcError(this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", classified.reason)),\n });\n return;\n }\n }\n\n /**\n * Sends a request and resolves with its result, or rejects with an {@link RpcError}: the\n * other side's diagnostic, `MOSTRA_HOST_TIMEOUT` or `MOSTRA_HOST_CONNECTION_CLOSED`.\n */\n request(\n method: string,\n params?: JsonRpcParams,\n options: RpcRequestOptions = {},\n ): Promise<unknown> {\n if (this.#closed) return Promise.reject(new RpcError(this.#closed));\n const id = this.#nextId++;\n return new Promise<unknown>((resolve, reject) => {\n const pending: Pending = { method, resolve, reject };\n if (options.timeoutMs !== undefined) {\n pending.timer = setTimeout(() => {\n this.#pending.delete(id);\n reject(\n new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_TIMEOUT\",\n `No response to ${method} within ${options.timeoutMs} ms.`,\n ),\n ),\n );\n }, options.timeoutMs);\n }\n this.#pending.set(id, pending);\n this.#send(\n params === undefined\n ? { jsonrpc: \"2.0\", id, method }\n : { jsonrpc: \"2.0\", id, method, params },\n );\n });\n }\n\n /**\n * Calls a protocol method: validates the params before sending and the result on arrival. A\n * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`. The result is\n * read as {@link receivable} reads it, so an enum value or union member a newer peer added\n * within the revision arrives as sent (#45).\n */\n async call<P, R>(\n definition: MethodDefinition<P, R>,\n params: P,\n options: RpcRequestOptions = {},\n ): Promise<R> {\n const checked = parseParams(definition, params, this.#options.docsBase);\n const raw = await this.request(definition.method, checked as JsonRpcParams, options);\n const parsed = receivable(definition.result).safeParse(raw);\n if (parsed.success) return parsed.data;\n throw new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n `The result of ${definition.method} doesn't match its schema: ${describeIssue(parsed.error.issues)}`,\n ),\n );\n }\n\n /** Sends a notification. Does nothing once the peer is closed. */\n notify(method: string, params?: JsonRpcParams): void {\n if (this.#closed) return;\n this.#send(\n params === undefined ? { jsonrpc: \"2.0\", method } : { jsonrpc: \"2.0\", method, params },\n );\n }\n\n /**\n * Closes the peer: every waiting request rejects with `diagnostic` (by default\n * `MOSTRA_HOST_CONNECTION_CLOSED`), and later messages are ignored. Idempotent.\n */\n close(diagnostic?: Diagnostic): void {\n if (this.#closed) return;\n const reason =\n diagnostic ??\n this.#diagnostic(\n \"MOSTRA_HOST_CONNECTION_CLOSED\",\n \"The connection closed before a response arrived.\",\n );\n this.#closed = reason;\n const pending = [...this.#pending.values()];\n this.#pending.clear();\n for (const entry of pending) {\n if (entry.timer !== undefined) clearTimeout(entry.timer);\n entry.reject(new RpcError(reason));\n }\n }\n\n #handleRequest(id: JsonRpcId, method: string, params: unknown): void {\n const handler = this.#options.onRequest;\n if (!handler) {\n this.#reply(id, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_METHOD_UNKNOWN\", `This side serves no method ${method}.`),\n ),\n });\n return;\n }\n let outcome: unknown;\n try {\n outcome = handler(method, params, { id, method });\n } catch (error) {\n this.#reply(id, { rpc: this.#asRpcError(error, method) });\n return;\n }\n Promise.resolve(outcome).then(\n (result) => this.#reply(id, { result: result === undefined ? null : result }),\n (error: unknown) => this.#reply(id, { rpc: this.#asRpcError(error, method) }),\n );\n }\n\n #handleNotification(method: string, params: unknown): void {\n try {\n this.#options.onNotification?.(method, params);\n } catch (error) {\n this.#options.onInternalError?.(error, method);\n }\n }\n\n #asRpcError(error: unknown, method: string): RpcError {\n if (error instanceof RpcError) return error;\n this.#options.onInternalError?.(error, method);\n return new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", `${method} failed unexpectedly.`),\n );\n }\n\n #settle(id: JsonRpcId, action: (pending: Pending) => void): void {\n const pending = this.#pending.get(id);\n if (!pending) return;\n this.#pending.delete(id);\n if (pending.timer !== undefined) clearTimeout(pending.timer);\n action(pending);\n }\n\n #reply(id: JsonRpcId | null, outcome: { result: unknown } | { rpc: RpcError }): void {\n if (this.#closed) return;\n if (\"rpc\" in outcome) {\n this.#send({ jsonrpc: \"2.0\", id, error: outcome.rpc.toErrorObject() });\n } else if (id !== null) {\n this.#send({ jsonrpc: \"2.0\", id, result: outcome.result });\n }\n }\n\n #send(message: JsonRpcMessage): void {\n try {\n this.#options.send(message);\n } catch {\n this.close();\n }\n }\n\n #diagnostic(\n code:\n | \"MOSTRA_HOST_MALFORMED\"\n | \"MOSTRA_HOST_METHOD_UNKNOWN\"\n | \"MOSTRA_HOST_INTERNAL_ERROR\"\n | \"MOSTRA_HOST_TIMEOUT\"\n | \"MOSTRA_HOST_CONNECTION_CLOSED\",\n message: string,\n ): Diagnostic {\n return hostDiagnostic(code, { message }, this.#options.docsBase);\n }\n}\n\nfunction describeIssue(\n issues: readonly { readonly path: readonly PropertyKey[]; readonly message: string }[],\n): string {\n const [first] = issues;\n if (!first) return \"unknown problem\";\n const path = first.path.map(String).join(\".\");\n return `${path === \"\" ? \"(root)\" : path}: ${first.message}`;\n}\n\n/**\n * Validates a method's params against its schema and returns the parsed value. Throws an\n * {@link RpcError} with `MOSTRA_HOST_INVALID_PARAMS` naming the first problem; the message\n * describes types and paths, never the values sent.\n */\nexport function parseParams<P, R>(\n definition: MethodDefinition<P, R>,\n params: unknown,\n docsBase?: string,\n): P {\n const parsed = definition.params.safeParse(params ?? {});\n if (parsed.success) return parsed.data;\n throw new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_INVALID_PARAMS\",\n { message: `Invalid params for ${definition.method}: ${describeIssue(parsed.error.issues)}` },\n docsBase,\n ),\n );\n}\n"],"mappings":";;;;;AAyEA,IAAa,UAAb,MAAqB;CACnB;CACA,2BAAoB,IAAI,IAAwB;CAChD,UAAU;CACV;CAEA,YAAY,SAAyB;EACnC,KAAK,WAAW;CAClB;;CAGA,IAAI,SAAkB;EACpB,OAAO,KAAK,YAAY,KAAA;CAC1B;;CAGA,IAAI,kBAA0B;EAC5B,OAAO,KAAK,SAAS;CACvB;;;;;CAMA,YAAY,MAAoB;EAC9B,IAAI,KAAK,KAAK,MAAM,IAAI;EACxB,IAAI;EACJ,IAAI;GACF,QAAQ,KAAK,MAAM,IAAI;EACzB,QAAQ;GACN,KAAK,OAAO,MAAM,EAChB,KAAK,IAAI,SACP,KAAK,YAAY,yBAAyB,2BAA2B,GACrE,qBAAqB,UACvB,EACF,CAAC;GACD;EACF;EACA,KAAK,QAAQ,KAAK;CACpB;;CAGA,QAAQ,OAAsB;EAC5B,I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,CAAC,SAAS;CAChB,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,OAAO,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,KAAK,GAAG;CAC5C,OAAO,GAAG,SAAS,KAAK,WAAW,KAAK,IAAI,MAAM;AACpD;;;;;;AAOA,SAAgB,YACd,YACA,QACA,UACG;CACH,MAAM,SAAS,WAAW,OAAO,UAAU,UAAU,CAAC,CAAC;CACvD,IAAI,OAAO,SAAS,OAAO,OAAO;CAClC,MAAM,IAAI,SACR,eACE,8BACA,EAAE,SAAS,sBAAsB,WAAW,OAAO,IAAI,cAAc,OAAO,MAAM,MAAM,IAAI,GAC5F,QACF,CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/protocol",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Mostra's shared protocol vocabulary: IDs, dated revisions and diagnostics, with Zod schemas and generated JSON Schema.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -43,7 +43,7 @@
43
43
  "provenance": true
44
44
  },
45
45
  "dependencies": {
46
- "zod": "4.6.5"
46
+ "zod": "4.6.6"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@mostra/tools": "0.0.0",
@@ -75,7 +75,7 @@
75
75
  "ignore": [
76
76
  "zod"
77
77
  ],
78
- "limit": "6 kB"
78
+ "limit": "5 kB"
79
79
  },
80
80
  {
81
81
  "name": "@mostra/protocol IDs alone (zod excluded)",
@@ -93,7 +93,7 @@
93
93
  "ignore": [
94
94
  "zod"
95
95
  ],
96
- "limit": "8.75 kB"
96
+ "limit": "7.5 kB"
97
97
  },
98
98
  {
99
99
  "name": "@mostra/protocol server-function serializer (D54)",
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The HOST-area codes the JSON-RPC core raises itself (D83): malformed messages, unknown methods,
3
+ * invalid params, internal errors, closed connections and timeouts. They are defined here once
4
+ * and spread into the HOST catalog, so a browser bundle that imports the core (the bridge,
5
+ * `@mostra/react`, the shell) carries these six entries, not the whole area's text: a new HOST
6
+ * code no longer grows them (#17).
7
+ */
8
+ import type { AreaCatalog } from "../spec.ts";
9
+
10
+ /** The codes the JSON-RPC core raises. */
11
+ export type CoreHostDiagnosticCode =
12
+ | "MOSTRA_HOST_MALFORMED"
13
+ | "MOSTRA_HOST_METHOD_UNKNOWN"
14
+ | "MOSTRA_HOST_INVALID_PARAMS"
15
+ | "MOSTRA_HOST_INTERNAL_ERROR"
16
+ | "MOSTRA_HOST_CONNECTION_CLOSED"
17
+ | "MOSTRA_HOST_TIMEOUT";
18
+
19
+ /** Their catalog entries. */
20
+ export const coreHostDiagnostics: AreaCatalog<CoreHostDiagnosticCode> = {
21
+ MOSTRA_HOST_MALFORMED: {
22
+ severity: "error",
23
+ phase: "host",
24
+ title: "Malformed protocol message",
25
+ hint: "Send each message as one line of JSON holding a single JSON-RPC 2.0 request or notification.",
26
+ docs: {
27
+ explanation:
28
+ "Every message on a Mostra connection is one line of JSON with one JSON-RPC 2.0 object. This code means a line wasn't valid JSON, wasn't a JSON-RPC 2.0 request or response, or was a batch (a JSON array), which revision `2026-10-10` doesn't accept. A client also reports it when a response doesn't match the method's result schema.",
29
+ fix: 'Encode one request per line with `"jsonrpc": "2.0"`, a `method`, an `id` for requests, and `params` as an object. Send several requests as separate lines instead of a batch.',
30
+ },
31
+ },
32
+ MOSTRA_HOST_METHOD_UNKNOWN: {
33
+ severity: "error",
34
+ phase: "host",
35
+ title: "Unknown protocol method",
36
+ hint: "Call only the methods listed in `capabilities.methods` of the `mostra/initialize` result.",
37
+ docs: {
38
+ explanation:
39
+ "The instance doesn't serve the method that was called. Either the name is misspelled, or the client is newer than the instance and calls a method the instance's release doesn't have.",
40
+ fix: "Check the method name against INTERFACES \u00a76, and against `capabilities.methods` in the `mostra/initialize` result, which lists every method this instance serves. Upgrade the instance if the client needs a newer method.",
41
+ },
42
+ },
43
+ MOSTRA_HOST_INVALID_PARAMS: {
44
+ severity: "error",
45
+ phase: "host",
46
+ title: "Invalid method params",
47
+ hint: "Fix the params named in the message so they match the method's schema.",
48
+ docs: {
49
+ explanation:
50
+ "The request's `params` don't match the method's published schema: a required field is missing, a value has the wrong type, or a value is outside its allowed range. The message names the first problem found.",
51
+ fix: "Compare the request with the method's schema in `@mostra/protocol` (or the published JSON Schema) and correct the field named in the message.",
52
+ },
53
+ },
54
+ MOSTRA_HOST_INTERNAL_ERROR: {
55
+ severity: "error",
56
+ phase: "host",
57
+ title: "Unexpected failure in the instance",
58
+ hint: "Retry the request with the same request ID; if it fails again, report it with the instance's log.",
59
+ docs: {
60
+ explanation:
61
+ "The instance failed while handling the request, for a reason that isn't one of its known conditions. Durable state is unaffected: a request is acknowledged only after its ledger transaction commits. The details are in the instance's log (`logs/supervisor.log` in the home), not in the response.",
62
+ fix: "Retry the request with the same request ID; retries are idempotent. If the failure repeats, report it with the relevant lines of `logs/supervisor.log`.",
63
+ },
64
+ },
65
+ MOSTRA_HOST_CONNECTION_CLOSED: {
66
+ severity: "error",
67
+ phase: "host",
68
+ title: "Connection closed",
69
+ hint: "Reconnect, then retry the request with the same request ID.",
70
+ docs: {
71
+ explanation:
72
+ "The connection to the other side closed before a response arrived, for example because the instance exited or restarted. The request may or may not have taken effect.",
73
+ fix: "Reconnect and send `mostra/initialize` again, then retry the request with the same request ID. Mutating methods are idempotent by request ID, so a retry never applies twice.",
74
+ },
75
+ },
76
+ MOSTRA_HOST_TIMEOUT: {
77
+ severity: "error",
78
+ phase: "host",
79
+ title: "Request timed out",
80
+ hint: "Retry the request with the same request ID, or allow it more time.",
81
+ docs: {
82
+ explanation:
83
+ "No response arrived within the time the caller allowed. The other side may still be working on the request, and it may still take effect.",
84
+ fix: "Retry with the same request ID, which returns the recorded result if the first attempt completed. Allow a longer timeout for slow operations.",
85
+ },
86
+ },
87
+ };
@@ -2,6 +2,7 @@
2
2
  * Diagnostic codes of the HOST area: the host protocol between clients and an instance.
3
3
  */
4
4
  import type { AreaCatalog } from "../spec.ts";
5
+ import { coreHostDiagnostics } from "./host-core.ts";
5
6
 
6
7
  /** The codes of the HOST area, in the order they were added. */
7
8
  export const hostDiagnosticCodes = [
@@ -27,8 +28,12 @@ export const hostDiagnosticCodes = [
27
28
  /** The codes of the HOST area. */
28
29
  export type HostDiagnosticCode = (typeof hostDiagnosticCodes)[number];
29
30
 
30
- /** The HOST area's catalog entries. */
31
+ /**
32
+ * The HOST area's catalog entries. The codes the JSON-RPC core raises live in `host-core.ts`, so
33
+ * browser bundles carry only theirs (#17).
34
+ */
31
35
  export const hostDiagnostics: AreaCatalog<HostDiagnosticCode> = {
36
+ ...coreHostDiagnostics,
32
37
  MOSTRA_HOST_REVISION_UNSUPPORTED: {
33
38
  severity: "error",
34
39
  phase: "host",
@@ -40,50 +45,6 @@ export const hostDiagnostics: AreaCatalog<HostDiagnosticCode> = {
40
45
  fix: "Restart the daemon so it runs the same release as the client: `mostra daemon restart`. Durable state survives the restart, and open views reconnect. A host that embeds Mostra updates its pinned Mostra runtime or its host library until both support a common revision.",
41
46
  },
42
47
  },
43
- MOSTRA_HOST_MALFORMED: {
44
- severity: "error",
45
- phase: "host",
46
- title: "Malformed protocol message",
47
- hint: "Send each message as one line of JSON holding a single JSON-RPC 2.0 request or notification.",
48
- docs: {
49
- explanation:
50
- "Every message on a Mostra connection is one line of JSON with one JSON-RPC 2.0 object. This code means a line wasn't valid JSON, wasn't a JSON-RPC 2.0 request or response, or was a batch (a JSON array), which revision `2026-10-10` doesn't accept. A client also reports it when a response doesn't match the method's result schema.",
51
- fix: 'Encode one request per line with `"jsonrpc": "2.0"`, a `method`, an `id` for requests, and `params` as an object. Send several requests as separate lines instead of a batch.',
52
- },
53
- },
54
- MOSTRA_HOST_METHOD_UNKNOWN: {
55
- severity: "error",
56
- phase: "host",
57
- title: "Unknown protocol method",
58
- hint: "Call only the methods listed in `capabilities.methods` of the `mostra/initialize` result.",
59
- docs: {
60
- explanation:
61
- "The instance doesn't serve the method that was called. Either the name is misspelled, or the client is newer than the instance and calls a method the instance's release doesn't have.",
62
- fix: "Check the method name against INTERFACES \u00a76, and against `capabilities.methods` in the `mostra/initialize` result, which lists every method this instance serves. Upgrade the instance if the client needs a newer method.",
63
- },
64
- },
65
- MOSTRA_HOST_INVALID_PARAMS: {
66
- severity: "error",
67
- phase: "host",
68
- title: "Invalid method params",
69
- hint: "Fix the params named in the message so they match the method's schema.",
70
- docs: {
71
- explanation:
72
- "The request's `params` don't match the method's published schema: a required field is missing, a value has the wrong type, or a value is outside its allowed range. The message names the first problem found.",
73
- fix: "Compare the request with the method's schema in `@mostra/protocol` (or the published JSON Schema) and correct the field named in the message.",
74
- },
75
- },
76
- MOSTRA_HOST_INTERNAL_ERROR: {
77
- severity: "error",
78
- phase: "host",
79
- title: "Unexpected failure in the instance",
80
- hint: "Retry the request with the same request ID; if it fails again, report it with the instance's log.",
81
- docs: {
82
- explanation:
83
- "The instance failed while handling the request, for a reason that isn't one of its known conditions. Durable state is unaffected: a request is acknowledged only after its ledger transaction commits. The details are in the instance's log (`logs/supervisor.log` in the home), not in the response.",
84
- fix: "Retry the request with the same request ID; retries are idempotent. If the failure repeats, report it with the relevant lines of `logs/supervisor.log`.",
85
- },
86
- },
87
48
  MOSTRA_HOST_INITIALIZE_ORDER: {
88
49
  severity: "error",
89
50
  phase: "host",
@@ -106,28 +67,6 @@ export const hostDiagnostics: AreaCatalog<HostDiagnosticCode> = {
106
67
  fix: "Register only the ports listed in `capabilities.ports` of the `mostra/initialize` result. If the host needs the port, upgrade the instance to a release that supports it.",
107
68
  },
108
69
  },
109
- MOSTRA_HOST_CONNECTION_CLOSED: {
110
- severity: "error",
111
- phase: "host",
112
- title: "Connection closed",
113
- hint: "Reconnect, then retry the request with the same request ID.",
114
- docs: {
115
- explanation:
116
- "The connection to the other side closed before a response arrived, for example because the instance exited or restarted. The request may or may not have taken effect.",
117
- fix: "Reconnect and send `mostra/initialize` again, then retry the request with the same request ID. Mutating methods are idempotent by request ID, so a retry never applies twice.",
118
- },
119
- },
120
- MOSTRA_HOST_TIMEOUT: {
121
- severity: "error",
122
- phase: "host",
123
- title: "Request timed out",
124
- hint: "Retry the request with the same request ID, or allow it more time.",
125
- docs: {
126
- explanation:
127
- "No response arrived within the time the caller allowed. The other side may still be working on the request, and it may still take effect.",
128
- fix: "Retry with the same request ID, which returns the recorded result if the first attempt completed. Allow a longer timeout for slow operations.",
129
- },
130
- },
131
70
  MOSTRA_HOST_SHUTDOWN_REFUSED: {
132
71
  severity: "error",
133
72
  phase: "host",
package/src/index.ts CHANGED
@@ -485,6 +485,7 @@ export {
485
485
  type WaitResult,
486
486
  waitMethod,
487
487
  } from "./methods/wait/wait.ts";
488
+ export { receivable } from "./receive.ts";
488
489
  export {
489
490
  HOST_PROTOCOL_REVISIONS,
490
491
  negotiateRevision,
package/src/receive.ts ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Reading what a newer peer sends (HO-07, D32, #45). Within a revision a peer may add values to an
3
+ * enum and members to a union: the wire schemas' evolution rule counts both as additive
4
+ * (`tools/schemas/compat.ts`). A receiver checking such a message against the schemas it was built
5
+ * with would refuse the whole message for one value it doesn't know, so it checks it against
6
+ * {@link receivable}'s copy instead, as the Rust crate's wire types read an `Unknown` variant.
7
+ */
8
+ import * as z from "zod";
9
+
10
+ /** A Zod node's definition, as far as {@link receivable} reads it. */
11
+ interface Def {
12
+ readonly type: string;
13
+ readonly [key: string]: unknown;
14
+ }
15
+
16
+ const opened = new WeakMap<z.ZodType, z.ZodType>();
17
+
18
+ /**
19
+ * `schema` as a receiver of a newer peer's messages checks it: every string enum and every union
20
+ * of string literals accepts any string (an enum's own checks still run, and an enum-keyed record
21
+ * still needs every key it names); a discriminated union accepts, besides its members, an object
22
+ * whose discriminator is a string none of them has, kept whole; strict objects drop unknown fields
23
+ * rather than refuse them. Everything else (fields, types, required members, limits) is checked as
24
+ * before, so a message a newer peer couldn't have sent still fails, and a message `schema` accepts
25
+ * reads exactly as `schema` reads it: a union tries its members as built before their opened
26
+ * copies, and a discriminated union's members keep their own tags.
27
+ *
28
+ * The result keeps `schema`'s TypeScript type, the shape this side was built for: a value the type
29
+ * doesn't name means a newer peer. Code that branches on such a field handles the other case, and
30
+ * a gate (a verdict, a check, a delivery) passes only on a value it knows means passing, never on
31
+ * the absence of the one it knows means failing.
32
+ *
33
+ * ```ts
34
+ * const parsed = receivable(definition.result).safeParse(raw);
35
+ * ```
36
+ */
37
+ export function receivable<T>(schema: z.ZodType<T>): z.ZodType<T> {
38
+ return open(schema) as z.ZodType<T>;
39
+ }
40
+
41
+ function open(schema: z.ZodType): z.ZodType {
42
+ const known = opened.get(schema);
43
+ if (known) return known;
44
+ // A recursive schema (Zod's getter idiom) reaches itself while it is being opened: it finds this
45
+ // stand-in, which reads the finished copy when a message is checked (Opus review of MT-01, 7).
46
+ let result: z.ZodType | undefined;
47
+ opened.set(
48
+ schema,
49
+ z.lazy(() => result ?? schema),
50
+ );
51
+ result = rebuild(schema);
52
+ opened.set(schema, result);
53
+ return result;
54
+ }
55
+
56
+ /** Any string, with the checks `schema` carries (an enum's `.refine`, say). */
57
+ function anyString(schema: z.ZodType): z.ZodType {
58
+ const checks = defOf(schema)["checks"] as unknown[] | undefined;
59
+ return checks?.length ? cloned(z.string(), { checks }) : z.string();
60
+ }
61
+
62
+ function defOf(schema: z.ZodType): Def {
63
+ return (schema as unknown as { _zod: { def: Def } })._zod.def;
64
+ }
65
+
66
+ /** A copy of `schema` with some of its definition replaced; its checks and settings stay. */
67
+ function cloned(schema: z.ZodType, changes: Record<string, unknown>): z.ZodType {
68
+ return (schema as unknown as { clone(def: Def): z.ZodType }).clone({
69
+ ...defOf(schema),
70
+ ...changes,
71
+ });
72
+ }
73
+
74
+ /** The string values of a literal or enum node, or undefined when it has others. */
75
+ function strings(schema: z.ZodType): string[] | undefined {
76
+ const def = defOf(schema);
77
+ const values =
78
+ def.type === "literal"
79
+ ? (def["values"] as unknown[])
80
+ : def.type === "enum"
81
+ ? Object.values(def["entries"] as Record<string, unknown>)
82
+ : undefined;
83
+ return values?.every((value) => typeof value === "string") ? (values as string[]) : undefined;
84
+ }
85
+
86
+ function rebuild(schema: z.ZodType): z.ZodType {
87
+ const def = defOf(schema);
88
+ switch (def.type) {
89
+ case "enum":
90
+ return strings(schema) ? anyString(schema) : schema;
91
+ case "optional":
92
+ case "nullable":
93
+ case "readonly":
94
+ case "default":
95
+ case "prefault":
96
+ case "nonoptional":
97
+ case "catch":
98
+ return cloned(schema, { innerType: open(def["innerType"] as z.ZodType) });
99
+ case "array":
100
+ return cloned(schema, { element: open(def["element"] as z.ZodType) });
101
+ case "object": {
102
+ const shape = def["shape"] as Record<string, z.ZodType>;
103
+ const catchall = def["catchall"] as z.ZodType | undefined;
104
+ return cloned(schema, {
105
+ shape: Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, open(value)])),
106
+ // A strict object (catchall `never`) would refuse a field a newer peer adds: it is dropped
107
+ // instead. A loose object keeps passing its fields through, and a typed catchall keeps
108
+ // checking them (GPT review of MT-01: the bridge's host context passes fields through).
109
+ catchall:
110
+ catchall === undefined || defOf(catchall).type === "never" ? undefined : open(catchall),
111
+ });
112
+ }
113
+ case "record": {
114
+ const keyType = def["keyType"] as z.ZodType;
115
+ // Keys from an enum: every one it names is still required, and a key a newer peer adds
116
+ // passes through, as Zod's loose records do (Opus review of MT-01, 2).
117
+ if (strings(keyType) && !def["partial"]) {
118
+ return cloned(schema, { valueType: open(def["valueType"] as z.ZodType), mode: "loose" });
119
+ }
120
+ return cloned(schema, {
121
+ keyType: open(keyType),
122
+ valueType: open(def["valueType"] as z.ZodType),
123
+ });
124
+ }
125
+ case "tuple":
126
+ return cloned(schema, {
127
+ items: (def["items"] as z.ZodType[]).map(open),
128
+ rest: def["rest"] ? open(def["rest"] as z.ZodType) : def["rest"],
129
+ });
130
+ case "intersection":
131
+ return cloned(schema, {
132
+ left: open(def["left"] as z.ZodType),
133
+ right: open(def["right"] as z.ZodType),
134
+ });
135
+ case "pipe":
136
+ return cloned(schema, { in: open(def["in"] as z.ZodType) });
137
+ case "lazy": {
138
+ const getter = def["getter"] as () => z.ZodType;
139
+ return z.lazy(() => open(getter()));
140
+ }
141
+ case "union":
142
+ return union(schema, def);
143
+ default:
144
+ return schema;
145
+ }
146
+ }
147
+
148
+ function union(schema: z.ZodType, def: Def): z.ZodType {
149
+ const options = def["options"] as z.ZodType[];
150
+ // A union of string literals is an enum written another way.
151
+ if (options.every((option) => strings(option) !== undefined)) return anyString(schema);
152
+ // The members as built come first, so whatever they accept reads as before; their opened copies
153
+ // only take what none of them does (Opus review of MT-01, 1).
154
+ const anyOf = (members: z.ZodType[]): z.ZodType =>
155
+ z.union([...options, ...members] as [z.ZodType, ...z.ZodType[]]);
156
+ const discriminator = def["discriminator"] as string | undefined;
157
+ if (discriminator === undefined) return anyOf(options.map(open));
158
+ const tags = new Set<string>();
159
+ const members: z.ZodType[] = [];
160
+ for (const option of options) {
161
+ const shape = defOf(option)["shape"] as Record<string, z.ZodType> | undefined;
162
+ const tag = shape?.[discriminator];
163
+ const values = tag ? strings(tag) : undefined;
164
+ // A member whose tag isn't a string literal: no newer member can be told from a broken one.
165
+ if (!tag || !values) return anyOf(options.map(open));
166
+ for (const value of values) tags.add(value);
167
+ // An opened member keeps its own tag: widened, an enum tag would take every member's messages.
168
+ const member = open(option);
169
+ const memberShape = defOf(member)["shape"] as Record<string, z.ZodType>;
170
+ members.push(cloned(member, { shape: { ...memberShape, [discriminator]: tag } }));
171
+ }
172
+ const newer = z.looseObject({
173
+ [discriminator]: z.string().refine((value) => !tags.has(value)),
174
+ });
175
+ return anyOf([...members, newer]);
176
+ }
package/src/rpc/error.ts CHANGED
@@ -2,7 +2,10 @@
2
2
  * Errors on a JSON-RPC connection. Every error carries a diagnostic (INTERFACES §1, §6): the
3
3
  * JSON-RPC `error.code` says which kind of failure it is, and `error.data` is the diagnostic.
4
4
  */
5
- import { type HostDiagnosticCode, hostDiagnostics } from "../diagnostics/codes/host.ts";
5
+ import {
6
+ type CoreHostDiagnosticCode,
7
+ coreHostDiagnostics,
8
+ } from "../diagnostics/codes/host-core.ts";
6
9
  import { Diagnostic } from "../diagnostics/diagnostic.ts";
7
10
  import { buildDiagnostic, type DiagnosticDetails } from "../diagnostics/spec.ts";
8
11
  import type { JsonRpcErrorObject } from "./messages.ts";
@@ -95,13 +98,13 @@ export class RpcError extends Error {
95
98
  }
96
99
 
97
100
  /**
98
- * Builds a HOST-area diagnostic from that area's catalog alone, so the JSON-RPC core doesn't pull
99
- * every area's text into browser bundles (D83).
101
+ * Builds one of the HOST-area diagnostics the JSON-RPC core raises, from their own catalog, so the
102
+ * core pulls neither the other areas' text nor the rest of HOST's into browser bundles (D83, #17).
100
103
  */
101
104
  export function hostDiagnostic(
102
- code: HostDiagnosticCode,
105
+ code: CoreHostDiagnosticCode,
103
106
  details: DiagnosticDetails,
104
107
  docsBase?: string,
105
108
  ): Diagnostic {
106
- return buildDiagnostic(code, hostDiagnostics[code], details, docsBase);
109
+ return buildDiagnostic(code, coreHostDiagnostics[code], details, docsBase);
107
110
  }
package/src/rpc/peer.ts CHANGED
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import type { Diagnostic } from "../diagnostics/diagnostic.ts";
17
17
  import type { MethodDefinition } from "../method.ts";
18
+ import { receivable } from "../receive.ts";
18
19
  import { hostDiagnostic, JSON_RPC_ERROR_CODES, RpcError } from "./error.ts";
19
20
  import {
20
21
  classifyMessage,
@@ -185,7 +186,9 @@ export class RpcPeer {
185
186
 
186
187
  /**
187
188
  * Calls a protocol method: validates the params before sending and the result on arrival. A
188
- * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`.
189
+ * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`. The result is
190
+ * read as {@link receivable} reads it, so an enum value or union member a newer peer added
191
+ * within the revision arrives as sent (#45).
189
192
  */
190
193
  async call<P, R>(
191
194
  definition: MethodDefinition<P, R>,
@@ -194,7 +197,7 @@ export class RpcPeer {
194
197
  ): Promise<R> {
195
198
  const checked = parseParams(definition, params, this.#options.docsBase);
196
199
  const raw = await this.request(definition.method, checked as JsonRpcParams, options);
197
- const parsed = definition.result.safeParse(raw);
200
+ const parsed = receivable(definition.result).safeParse(raw);
198
201
  if (parsed.success) return parsed.data;
199
202
  throw new RpcError(
200
203
  this.#diagnostic(