@mostra/protocol 0.3.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.
- package/dist/diagnostics/codes/env.js +2 -2
- package/dist/diagnostics/codes/env.js.map +1 -1
- package/dist/diagnostics/codes/home.js +1 -1
- package/dist/diagnostics/codes/home.js.map +1 -1
- package/dist/diagnostics/codes/host-core.d.ts +1 -0
- package/dist/diagnostics/codes/host-core.js +68 -0
- package/dist/diagnostics/codes/host-core.js.map +1 -0
- package/dist/diagnostics/codes/host.d.ts.map +1 -1
- package/dist/diagnostics/codes/host.js +6 -61
- package/dist/diagnostics/codes/host.js.map +1 -1
- package/dist/diagnostics/codes/index.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +3 -2
- package/dist/receive.d.ts +24 -0
- package/dist/receive.d.ts.map +1 -0
- package/dist/receive.js +137 -0
- package/dist/receive.js.map +1 -0
- package/dist/rpc/error.d.ts +1 -1
- package/dist/rpc/error.d.ts.map +1 -1
- package/dist/rpc/error.js +4 -4
- package/dist/rpc/error.js.map +1 -1
- package/dist/rpc/peer.d.ts +3 -1
- package/dist/rpc/peer.d.ts.map +1 -1
- package/dist/rpc/peer.js +5 -2
- package/dist/rpc/peer.js.map +1 -1
- package/package.json +4 -4
- package/src/diagnostics/codes/env.ts +2 -2
- package/src/diagnostics/codes/home.ts +1 -1
- package/src/diagnostics/codes/host-core.ts +87 -0
- package/src/diagnostics/codes/host.ts +6 -67
- package/src/index.ts +1 -0
- package/src/receive.ts +176 -0
- package/src/rpc/error.ts +8 -5
- package/src/rpc/peer.ts +5 -2
package/dist/receive.js
ADDED
|
@@ -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;AACtF;AAEA,SAAS,QAAQ,QAA8B;CAC7C,MAAM,MAAM,MAAM,MAAM;CACxB,QAAQ,IAAI,MA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nostic.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). */
|
package/dist/rpc/error.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.d.ts","names":[],"sources":["../../src/rpc/error.ts"],"mappings":";;;;;;
|
|
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 {
|
|
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
|
|
69
|
-
*
|
|
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,
|
|
72
|
+
return buildDiagnostic(code, coreHostDiagnostics[code], details, docsBase);
|
|
73
73
|
}
|
|
74
74
|
//#endregion
|
|
75
75
|
export { JSON_RPC_ERROR_CODES, RpcError, hostDiagnostic };
|
package/dist/rpc/error.js.map
CHANGED
|
@@ -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 {
|
|
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"}
|
package/dist/rpc/peer.d.ts
CHANGED
|
@@ -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. */
|
package/dist/rpc/peer.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"peer.d.ts","names":[],"sources":["../../src/rpc/peer.ts"],"mappings":";;;;;
|
|
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
|
}
|
package/dist/rpc/peer.js.map
CHANGED
|
@@ -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"],"mappings":";;;;AAwEA,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,IAAI,KAAK,SAAS;EAClB,MAAM,aAAa,gBAAgB,KAAK;EACxC,QAAQ,WAAW,MAAnB;GACE,KAAK;IACH,KAAK,eACH,WAAW,QAAQ,IACnB,WAAW,QAAQ,QACnB,WAAW,QAAQ,MACrB;IACA;GACF,KAAK;IACH,KAAK,oBAAoB,WAAW,QAAQ,QAAQ,WAAW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AU,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;CACh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B;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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mostra/protocol",
|
|
3
|
-
"version": "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.
|
|
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": "
|
|
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": "
|
|
96
|
+
"limit": "7.5 kB"
|
|
97
97
|
},
|
|
98
98
|
{
|
|
99
99
|
"name": "@mostra/protocol server-function serializer (D54)",
|
|
@@ -76,8 +76,8 @@ export const envDiagnostics: AreaCatalog<EnvDiagnosticCode> = {
|
|
|
76
76
|
hint: "Read the message, fix what it names, and run the install again.",
|
|
77
77
|
docs: {
|
|
78
78
|
explanation:
|
|
79
|
-
"`mostra daemon install` couldn't register the home's daemon as a login service: writing the launchd agent
|
|
80
|
-
fix: "Check the named file's directory permissions
|
|
79
|
+
"`mostra daemon install` couldn't register the home's daemon as a login service: writing the launchd agent, systemd user unit or Task Scheduler task failed, or `launchctl`, `systemctl --user` or `schtasks` refused it.",
|
|
80
|
+
fix: "Check the named file's directory permissions; on Linux, that a systemd user session is running (`systemctl --user status`); on Windows, that Task Scheduler runs and your account may create tasks (`schtasks /Query`). On a machine without one, start the daemon from your own login scripts with `mostra daemon start`.",
|
|
81
81
|
},
|
|
82
82
|
},
|
|
83
83
|
MOSTRA_ENV_BROWSER_MISSING: {
|
|
@@ -132,7 +132,7 @@ export const homeDiagnostics: AreaCatalog<HomeDiagnosticCode> = {
|
|
|
132
132
|
docs: {
|
|
133
133
|
explanation:
|
|
134
134
|
"The home has artifacts with submission policy `none`, which are meant to stay open (dashboards, task managers, D63), but no login service runs its daemon. Without one, the daemon exits after 30 idle minutes and their links stop answering until a command starts it again.",
|
|
135
|
-
fix: "Run `mostra daemon install`. It registers a launchd
|
|
135
|
+
fix: "Run `mostra daemon install`. It registers a login service (a launchd agent, a systemd user service or a Task Scheduler task) that keeps the home's daemon running; `mostra daemon uninstall` removes it.",
|
|
136
136
|
},
|
|
137
137
|
},
|
|
138
138
|
MOSTRA_HOME_GC_INCOMPLETE: {
|
|
@@ -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
|
-
/**
|
|
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",
|