@buildanagent/protocol 0.0.0-bootstrap.0 → 0.1.0-alpha.28
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/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +86 -0
- package/dist/entries.d.ts +328 -0
- package/dist/entries.js +83 -0
- package/dist/entries.js.map +1 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.js +21 -0
- package/dist/errors.js.map +1 -0
- package/dist/framer.d.ts +35 -0
- package/dist/framer.js +124 -0
- package/dist/framer.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/jsonrpc.d.ts +58 -0
- package/dist/jsonrpc.js +141 -0
- package/dist/jsonrpc.js.map +1 -0
- package/dist/messages.d.ts +305 -0
- package/dist/messages.js +2 -0
- package/dist/messages.js.map +1 -0
- package/llms.txt +88 -0
- package/package.json +42 -5
package/dist/framer.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a byte stream into JSON messages, one per line, on `\n` only. It never uses Node's `readline`, which also ends
|
|
3
|
+
* a line at a lone `\r`. Some line readers also end one at U+2028 or U+2029, characters that may sit inside a JSON
|
|
4
|
+
* string, so only `\n` is safe.
|
|
5
|
+
*/
|
|
6
|
+
import { ProtocolError } from "./errors.js";
|
|
7
|
+
import { ErrorCodes } from "./jsonrpc.js";
|
|
8
|
+
/** The default bound on one line, in bytes. */
|
|
9
|
+
export const DEFAULT_MAX_LINE_BYTES = 8 * 1024 * 1024;
|
|
10
|
+
const NEWLINE = 0x0a;
|
|
11
|
+
/** Spaces, tabs and carriage returns only: nothing a message could be made of. */
|
|
12
|
+
const isBlank = (bytes) => bytes.every((byte) => byte === 0x20 || byte === 0x09 || byte === 0x0d);
|
|
13
|
+
function join(parts, total) {
|
|
14
|
+
const bytes = new Uint8Array(total);
|
|
15
|
+
let at = 0;
|
|
16
|
+
for (const part of parts) {
|
|
17
|
+
bytes.set(part, at);
|
|
18
|
+
at += part.length;
|
|
19
|
+
}
|
|
20
|
+
return bytes;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Feed it chunks as they arrive. `push()` returns one `FramedMessage` for each complete line the chunk finished, in
|
|
24
|
+
* order, and keeps the rest of a half-received line for the next chunk. A character split across two chunks is whole
|
|
25
|
+
* again once its line is, because a line is decoded only when it is complete. A blank line is skipped, a trailing `\r`
|
|
26
|
+
* is dropped, and a line that isn't UTF-8 or isn't JSON comes back as an error and doesn't stop the lines after it.
|
|
27
|
+
*/
|
|
28
|
+
export class JsonlFramer {
|
|
29
|
+
#maxLineBytes;
|
|
30
|
+
#parts = [];
|
|
31
|
+
#bytes = 0;
|
|
32
|
+
// True while the rest of an over-long line is being thrown away, up to its newline.
|
|
33
|
+
#skipping = false;
|
|
34
|
+
constructor(options = {}) {
|
|
35
|
+
this.#maxLineBytes = options.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
|
|
36
|
+
}
|
|
37
|
+
/** Takes the next chunk of the stream and returns a result for each line it finished, in order. */
|
|
38
|
+
push(chunk) {
|
|
39
|
+
const out = [];
|
|
40
|
+
let start = 0;
|
|
41
|
+
for (let at = chunk.indexOf(NEWLINE, start); at >= 0; at = chunk.indexOf(NEWLINE, start)) {
|
|
42
|
+
this.#add(chunk.subarray(start, at), out);
|
|
43
|
+
this.#finishLine(out);
|
|
44
|
+
start = at + 1;
|
|
45
|
+
}
|
|
46
|
+
this.#add(chunk.subarray(start), out);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
/** Ends the stream. An unfinished last line comes back as an error, because its writer may have died mid-message. */
|
|
50
|
+
end() {
|
|
51
|
+
const out = [];
|
|
52
|
+
const leftover = join(this.#parts, this.#bytes);
|
|
53
|
+
// Spaces, tabs and a \r are not a message, so a stream that ends after them was not cut.
|
|
54
|
+
if (this.#bytes > 0 && !isBlank(leftover) && !this.#skipping) {
|
|
55
|
+
out.push({
|
|
56
|
+
ok: false,
|
|
57
|
+
error: new ProtocolError("unterminated_line", "the stream ended in the middle of a line", {
|
|
58
|
+
rpcCode: ErrorCodes.ParseError,
|
|
59
|
+
requestId: null,
|
|
60
|
+
}),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
this.#parts = [];
|
|
64
|
+
this.#bytes = 0;
|
|
65
|
+
this.#skipping = false;
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
#tooLong() {
|
|
69
|
+
return {
|
|
70
|
+
ok: false,
|
|
71
|
+
error: new ProtocolError("line_too_long", `a line went over the bound of ${this.#maxLineBytes} bytes`, {
|
|
72
|
+
rpcCode: ErrorCodes.InvalidRequest,
|
|
73
|
+
requestId: null,
|
|
74
|
+
}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
#add(part, out) {
|
|
78
|
+
if (part.length === 0 || this.#skipping)
|
|
79
|
+
return;
|
|
80
|
+
// One byte over the bound is let in for a trailing \r, which the bound does not count; the whole line is checked again
|
|
81
|
+
// once it is complete.
|
|
82
|
+
if (this.#bytes + part.length > this.#maxLineBytes + 1) {
|
|
83
|
+
out.push(this.#tooLong());
|
|
84
|
+
this.#parts = [];
|
|
85
|
+
this.#bytes = 0;
|
|
86
|
+
this.#skipping = true;
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
// A copy, because a Buffer's slice() is a view, and a transport may reuse the memory of the chunk it passed.
|
|
90
|
+
this.#parts.push(new Uint8Array(part));
|
|
91
|
+
this.#bytes += part.length;
|
|
92
|
+
}
|
|
93
|
+
#finishLine(out) {
|
|
94
|
+
const wasSkipping = this.#skipping;
|
|
95
|
+
const bytes = join(this.#parts, this.#bytes);
|
|
96
|
+
this.#parts = [];
|
|
97
|
+
this.#bytes = 0;
|
|
98
|
+
this.#skipping = false;
|
|
99
|
+
if (wasSkipping)
|
|
100
|
+
return;
|
|
101
|
+
const end = bytes.at(-1) === 0x0d ? bytes.length - 1 : bytes.length;
|
|
102
|
+
const line = bytes.subarray(0, end);
|
|
103
|
+
if (isBlank(line))
|
|
104
|
+
return;
|
|
105
|
+
out.push(line.length > this.#maxLineBytes ? this.#tooLong() : parseLine(line));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function parseLine(line) {
|
|
109
|
+
try {
|
|
110
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(line);
|
|
111
|
+
return { ok: true, value: JSON.parse(text) };
|
|
112
|
+
}
|
|
113
|
+
catch (cause) {
|
|
114
|
+
return {
|
|
115
|
+
ok: false,
|
|
116
|
+
error: new ProtocolError("invalid_json", "a line is not valid UTF-8 JSON", {
|
|
117
|
+
cause,
|
|
118
|
+
rpcCode: ErrorCodes.ParseError,
|
|
119
|
+
requestId: null,
|
|
120
|
+
}),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
//# sourceMappingURL=framer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"framer.js","sourceRoot":"","sources":["../src/framer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,+CAA+C;AAC/C,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAWtD,MAAM,OAAO,GAAG,IAAI,CAAC;AAErB,kFAAkF;AAClF,MAAM,OAAO,GAAG,CAAC,KAAiB,EAAW,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC;AAEvH,SAAS,IAAI,CAAC,KAA4B,EAAE,KAAa;IACvD,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC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,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO;YACL,EAAE,EAAE,KAAK;YACT,KAAK,EAAE,IAAI,aAAa,CAAC,cAAc,EAAE,gCAAgC,EAAE;gBACzE,KAAK;gBACL,OAAO,EAAE,UAAU,CAAC,UAAU;gBAC9B,SAAS,EAAE,IAAI;aAChB,CAAC;SACH,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/**\n * Splits a byte stream into JSON messages, one per line, on `\\n` only. It never uses Node's `readline`, which also ends\n * a line at a lone `\\r`. Some line readers also end one at U+2028 or U+2029, characters that may sit inside a JSON\n * string, so only `\\n` is safe.\n */\nimport { ProtocolError } from \"./errors.js\";\nimport { ErrorCodes } from \"./jsonrpc.js\";\n\n/** The default bound on one line, in bytes. */\nexport const DEFAULT_MAX_LINE_BYTES = 8 * 1024 * 1024;\n\n/** One line of the stream: its parsed JSON, or why it could not be read. A bad line never ends the stream. */\nexport type FramedMessage = { ok: true; value: unknown } | { ok: false; error: ProtocolError };\n\n/** The options of `JsonlFramer`. */\nexport interface JsonlFramerOptions {\n /** The most bytes one line may hold, newline excluded. A longer line is skipped and reported once. Default 8 MiB. */\n readonly maxLineBytes?: number;\n}\n\nconst NEWLINE = 0x0a;\n\n/** Spaces, tabs and carriage returns only: nothing a message could be made of. */\nconst isBlank = (bytes: Uint8Array): boolean => bytes.every((byte) => byte === 0x20 || byte === 0x09 || byte === 0x0d);\n\nfunction join(parts: readonly Uint8Array[], total: number): Uint8Array {\n const bytes = new Uint8Array(total);\n let at = 0;\n for (const part of parts) {\n bytes.set(part, at);\n at += part.length;\n }\n return bytes;\n}\n\n/**\n * Feed it chunks as they arrive. `push()` returns one `FramedMessage` for each complete line the chunk finished, in\n * order, and keeps the rest of a half-received line for the next chunk. A character split across two chunks is whole\n * again once its line is, because a line is decoded only when it is complete. A blank line is skipped, a trailing `\\r`\n * is dropped, and a line that isn't UTF-8 or isn't JSON comes back as an error and doesn't stop the lines after it.\n */\nexport class JsonlFramer {\n readonly #maxLineBytes: number;\n #parts: Uint8Array[] = [];\n #bytes = 0;\n // True while the rest of an over-long line is being thrown away, up to its newline.\n #skipping = false;\n\n constructor(options: JsonlFramerOptions = {}) {\n this.#maxLineBytes = options.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;\n }\n\n /** Takes the next chunk of the stream and returns a result for each line it finished, in order. */\n push(chunk: Uint8Array): FramedMessage[] {\n const out: FramedMessage[] = [];\n let start = 0;\n for (let at = chunk.indexOf(NEWLINE, start); at >= 0; at = chunk.indexOf(NEWLINE, start)) {\n this.#add(chunk.subarray(start, at), out);\n this.#finishLine(out);\n start = at + 1;\n }\n this.#add(chunk.subarray(start), out);\n return out;\n }\n\n /** Ends the stream. An unfinished last line comes back as an error, because its writer may have died mid-message. */\n end(): FramedMessage[] {\n const out: FramedMessage[] = [];\n const leftover = join(this.#parts, this.#bytes);\n // Spaces, tabs and a \\r are not a message, so a stream that ends after them was not cut.\n if (this.#bytes > 0 && !isBlank(leftover) && !this.#skipping) {\n out.push({\n ok: false,\n error: new ProtocolError(\"unterminated_line\", \"the stream ended in the middle of a line\", {\n rpcCode: ErrorCodes.ParseError,\n requestId: null,\n }),\n });\n }\n this.#parts = [];\n this.#bytes = 0;\n this.#skipping = false;\n return out;\n }\n\n #tooLong(): FramedMessage {\n return {\n ok: false,\n error: new ProtocolError(\"line_too_long\", `a line went over the bound of ${this.#maxLineBytes} bytes`, {\n rpcCode: ErrorCodes.InvalidRequest,\n requestId: null,\n }),\n };\n }\n\n #add(part: Uint8Array, out: FramedMessage[]): void {\n if (part.length === 0 || this.#skipping) return;\n // One byte over the bound is let in for a trailing \\r, which the bound does not count; the whole line is checked again\n // once it is complete.\n if (this.#bytes + part.length > this.#maxLineBytes + 1) {\n out.push(this.#tooLong());\n this.#parts = [];\n this.#bytes = 0;\n this.#skipping = true;\n return;\n }\n // A copy, because a Buffer's slice() is a view, and a transport may reuse the memory of the chunk it passed.\n this.#parts.push(new Uint8Array(part));\n this.#bytes += part.length;\n }\n\n #finishLine(out: FramedMessage[]): void {\n const wasSkipping = this.#skipping;\n const bytes = join(this.#parts, this.#bytes);\n this.#parts = [];\n this.#bytes = 0;\n this.#skipping = false;\n if (wasSkipping) return;\n const end = bytes.at(-1) === 0x0d ? bytes.length - 1 : bytes.length;\n const line = bytes.subarray(0, end);\n if (isBlank(line)) return;\n out.push(line.length > this.#maxLineBytes ? this.#tooLong() : parseLine(line));\n }\n}\n\nfunction parseLine(line: Uint8Array): FramedMessage {\n try {\n const text = new TextDecoder(\"utf-8\", { fatal: true }).decode(line);\n return { ok: true, value: JSON.parse(text) };\n } catch (cause) {\n return {\n ok: false,\n error: new ProtocolError(\"invalid_json\", \"a line is not valid UTF-8 JSON\", {\n cause,\n rpcCode: ErrorCodes.ParseError,\n requestId: null,\n }),\n };\n }\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** `@buildanagent/protocol`, the wire types of the buildanagent harness: the session entry union, the client and server messages and their JSONL framing. */
|
|
2
|
+
export type { ApprovalPolicy, CheckoutEntry, CodeCallEntry, CompactionEntry, CompletionCheckEntry, EntryBase, EnvStampEntry, ExtensionLoadedEntry, LoadoutEntry, McpServerRecord, MessageBlockEntry, MessageEndEntry, Origin, PermissionDecisionEntry, PermissionMode, ProductRecordEntry, SandboxTier, SessionEntry, SessionHeaderEntry, ShadowCallEntry, SkillLoadedEntry, SubagentLinkEntry, ToolResultEntry, TurnEndEntry, TurnStartEntry, UsageEntry, } from "./entries.js";
|
|
3
|
+
export { FORMAT_VERSION, parseEntry, SESSION_ENTRY_TYPES } from "./entries.js";
|
|
4
|
+
export type { ProtocolErrorCode, ProtocolErrorOptions } from "./errors.js";
|
|
5
|
+
export { isProtocolError, ProtocolError } from "./errors.js";
|
|
6
|
+
export type { FramedMessage, JsonlFramerOptions } from "./framer.js";
|
|
7
|
+
export { DEFAULT_MAX_LINE_BYTES, JsonlFramer } from "./framer.js";
|
|
8
|
+
export type { JsonRpcMessage } from "./jsonrpc.js";
|
|
9
|
+
export { CLIENT_METHODS, decode, ErrorCodes, EXPERIMENTAL_METHODS, encode, SERVER_NOTIFICATION_METHODS, SERVER_REQUEST_METHODS, } from "./jsonrpc.js";
|
|
10
|
+
export type { ApprovalList, BranchResult, ClientCommand, ClientInfo, ClientMessage, ClientResultMap, Disposition, HarnessEvent, Id, InitializeResult, InterruptResult, ProtocolMessage, ResponseMessage, RpcError, ServerMessage, ServerNotification, ServerRequest, ServerResultMap, SessionList, SessionListItem, SessionOpened, TurnResultSummary, } from "./messages.js";
|
|
11
|
+
/** The package's name. */
|
|
12
|
+
export declare const PACKAGE_NAME = "@buildanagent/protocol";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { FORMAT_VERSION, parseEntry, SESSION_ENTRY_TYPES } from "./entries.js";
|
|
2
|
+
export { isProtocolError, ProtocolError } from "./errors.js";
|
|
3
|
+
export { DEFAULT_MAX_LINE_BYTES, JsonlFramer } from "./framer.js";
|
|
4
|
+
export { CLIENT_METHODS, decode, ErrorCodes, EXPERIMENTAL_METHODS, encode, SERVER_NOTIFICATION_METHODS, SERVER_REQUEST_METHODS, } from "./jsonrpc.js";
|
|
5
|
+
/** The package's name. */
|
|
6
|
+
export const PACKAGE_NAME = "@buildanagent/protocol";
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA6BA,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAE/E,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG7D,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAElE,OAAO,EACL,cAAc,EACd,MAAM,EACN,UAAU,EACV,oBAAoB,EACpB,MAAM,EACN,2BAA2B,EAC3B,sBAAsB,GACvB,MAAM,cAAc,CAAC;AA0BtB,0BAA0B;AAC1B,MAAM,CAAC,MAAM,YAAY,GAAG,wBAAwB,CAAC","sourcesContent":["/** `@buildanagent/protocol`, the wire types of the buildanagent harness: the session entry union, the client and server messages and their JSONL framing. */\nexport type {\n ApprovalPolicy,\n CheckoutEntry,\n CodeCallEntry,\n CompactionEntry,\n CompletionCheckEntry,\n EntryBase,\n EnvStampEntry,\n ExtensionLoadedEntry,\n LoadoutEntry,\n McpServerRecord,\n MessageBlockEntry,\n MessageEndEntry,\n Origin,\n PermissionDecisionEntry,\n PermissionMode,\n ProductRecordEntry,\n SandboxTier,\n SessionEntry,\n SessionHeaderEntry,\n ShadowCallEntry,\n SkillLoadedEntry,\n SubagentLinkEntry,\n ToolResultEntry,\n TurnEndEntry,\n TurnStartEntry,\n UsageEntry,\n} from \"./entries.js\";\nexport { FORMAT_VERSION, parseEntry, SESSION_ENTRY_TYPES } from \"./entries.js\";\nexport type { ProtocolErrorCode, ProtocolErrorOptions } from \"./errors.js\";\nexport { isProtocolError, ProtocolError } from \"./errors.js\";\n\nexport type { FramedMessage, JsonlFramerOptions } from \"./framer.js\";\nexport { DEFAULT_MAX_LINE_BYTES, JsonlFramer } from \"./framer.js\";\nexport type { JsonRpcMessage } from \"./jsonrpc.js\";\nexport {\n CLIENT_METHODS,\n decode,\n ErrorCodes,\n EXPERIMENTAL_METHODS,\n encode,\n SERVER_NOTIFICATION_METHODS,\n SERVER_REQUEST_METHODS,\n} from \"./jsonrpc.js\";\nexport type {\n ApprovalList,\n BranchResult,\n ClientCommand,\n ClientInfo,\n ClientMessage,\n ClientResultMap,\n Disposition,\n HarnessEvent,\n Id,\n InitializeResult,\n InterruptResult,\n ProtocolMessage,\n ResponseMessage,\n RpcError,\n ServerMessage,\n ServerNotification,\n ServerRequest,\n ServerResultMap,\n SessionList,\n SessionListItem,\n SessionOpened,\n TurnResultSummary,\n} from \"./messages.js\";\n\n/** The package's name. */\nexport const PACKAGE_NAME = \"@buildanagent/protocol\";\n"]}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Id, ProtocolMessage } from "./messages.js";
|
|
2
|
+
/** The JSON-RPC error codes the protocol uses: the standard ones, and three of its own in the server-error range. */
|
|
3
|
+
export declare const ErrorCodes: {
|
|
4
|
+
readonly ParseError: -32700;
|
|
5
|
+
readonly InvalidRequest: -32600;
|
|
6
|
+
readonly MethodNotFound: -32601;
|
|
7
|
+
readonly InvalidParams: -32602;
|
|
8
|
+
readonly InternalError: -32603;
|
|
9
|
+
/** The dispatcher's queue is full, so the command was not taken. */
|
|
10
|
+
readonly QueueFull: -32001;
|
|
11
|
+
/** Another writer holds the session. */
|
|
12
|
+
readonly SessionLocked: -32002;
|
|
13
|
+
/** The client used an experimental method it did not opt into. */
|
|
14
|
+
readonly NotOptedIn: -32003;
|
|
15
|
+
};
|
|
16
|
+
/** The methods a client may call. `$/cancelRequest` is a notification, and the others are requests. */
|
|
17
|
+
export declare const CLIENT_METHODS: readonly ["initialize", "session/create", "session/open", "session/list", "turn/start", "turn/steer", "turn/followUp", "turn/interrupt", "approval/list", "session/checkout", "session/fork", "$/cancelRequest"];
|
|
18
|
+
/** The requests the server sends. */
|
|
19
|
+
export declare const SERVER_REQUEST_METHODS: readonly ["approval/request", "clarification/request", "tool/call"];
|
|
20
|
+
/** The notifications the server sends. `$/cancelRequest` withdraws one of the server's own requests. */
|
|
21
|
+
export declare const SERVER_NOTIFICATION_METHODS: readonly ["event", "turn/settled", "$/cancelRequest"];
|
|
22
|
+
/** The client methods that need an opt-in, because they may change before a client other than ours uses them. */
|
|
23
|
+
export declare const EXPERIMENTAL_METHODS: readonly ["session/checkout", "session/fork"];
|
|
24
|
+
/** A JSON-RPC message as `decode()` reads it: the envelope is checked, and `params` and `result` are not. */
|
|
25
|
+
export type JsonRpcMessage = {
|
|
26
|
+
jsonrpc: "2.0";
|
|
27
|
+
id: Id;
|
|
28
|
+
method: string;
|
|
29
|
+
params?: Record<string, unknown>;
|
|
30
|
+
} | {
|
|
31
|
+
jsonrpc: "2.0";
|
|
32
|
+
method: string;
|
|
33
|
+
params?: Record<string, unknown>;
|
|
34
|
+
} | {
|
|
35
|
+
jsonrpc: "2.0";
|
|
36
|
+
id: Id;
|
|
37
|
+
result: unknown;
|
|
38
|
+
} | {
|
|
39
|
+
jsonrpc: "2.0";
|
|
40
|
+
id: Id | null;
|
|
41
|
+
error: {
|
|
42
|
+
code: number;
|
|
43
|
+
message: string;
|
|
44
|
+
data?: unknown;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Reads one message from a line of JSON text or a parsed value, and checks its envelope. A batch (an array) is not
|
|
49
|
+
* supported. Throws a `ProtocolError`: `invalid_json` with the parse-error code for text that is not JSON, and
|
|
50
|
+
* `invalid_request` with the invalid-request code for anything else wrong, such as a missing `jsonrpc`.
|
|
51
|
+
*/
|
|
52
|
+
export declare function decode(input: unknown): JsonRpcMessage;
|
|
53
|
+
/**
|
|
54
|
+
* Turns a message into one line of JSON ending in `\n`, after the same envelope check `decode()` makes. JSON text has no
|
|
55
|
+
* raw newline in it, so the line can't be split by accident. U+2028 and U+2029 stay as they are, which is why a reader
|
|
56
|
+
* must split on `\n` only.
|
|
57
|
+
*/
|
|
58
|
+
export declare function encode(message: ProtocolMessage | JsonRpcMessage): string;
|
package/dist/jsonrpc.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON-RPC 2.0 framing, strictly: `encode()` and `decode()` refuse a message without `"jsonrpc": "2.0"`. They check the
|
|
3
|
+
* envelope only, because a method's params are the dispatcher's to check against the schema; a message that fails
|
|
4
|
+
* throws a `ProtocolError` that carries the JSON-RPC code and the request's id, so a server can answer it.
|
|
5
|
+
*/
|
|
6
|
+
import { ProtocolError } from "./errors.js";
|
|
7
|
+
/** The JSON-RPC error codes the protocol uses: the standard ones, and three of its own in the server-error range. */
|
|
8
|
+
export const ErrorCodes = {
|
|
9
|
+
ParseError: -32700,
|
|
10
|
+
InvalidRequest: -32600,
|
|
11
|
+
MethodNotFound: -32601,
|
|
12
|
+
InvalidParams: -32602,
|
|
13
|
+
InternalError: -32603,
|
|
14
|
+
/** The dispatcher's queue is full, so the command was not taken. */
|
|
15
|
+
QueueFull: -32001,
|
|
16
|
+
/** Another writer holds the session. */
|
|
17
|
+
SessionLocked: -32002,
|
|
18
|
+
/** The client used an experimental method it did not opt into. */
|
|
19
|
+
NotOptedIn: -32003,
|
|
20
|
+
};
|
|
21
|
+
/** The methods a client may call. `$/cancelRequest` is a notification, and the others are requests. */
|
|
22
|
+
export const CLIENT_METHODS = [
|
|
23
|
+
"initialize",
|
|
24
|
+
"session/create",
|
|
25
|
+
"session/open",
|
|
26
|
+
"session/list",
|
|
27
|
+
"turn/start",
|
|
28
|
+
"turn/steer",
|
|
29
|
+
"turn/followUp",
|
|
30
|
+
"turn/interrupt",
|
|
31
|
+
"approval/list",
|
|
32
|
+
"session/checkout",
|
|
33
|
+
"session/fork",
|
|
34
|
+
"$/cancelRequest",
|
|
35
|
+
];
|
|
36
|
+
/** The requests the server sends. */
|
|
37
|
+
export const SERVER_REQUEST_METHODS = ["approval/request", "clarification/request", "tool/call"];
|
|
38
|
+
/** The notifications the server sends. `$/cancelRequest` withdraws one of the server's own requests. */
|
|
39
|
+
export const SERVER_NOTIFICATION_METHODS = ["event", "turn/settled", "$/cancelRequest"];
|
|
40
|
+
/** The client methods that need an opt-in, because they may change before a client other than ours uses them. */
|
|
41
|
+
export const EXPERIMENTAL_METHODS = ["session/checkout", "session/fork"];
|
|
42
|
+
function invalid(why, id = null) {
|
|
43
|
+
throw new ProtocolError("invalid_request", why, { rpcCode: ErrorCodes.InvalidRequest, requestId: id });
|
|
44
|
+
}
|
|
45
|
+
const isId = (value) => typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
|
|
46
|
+
function checkError(error, id) {
|
|
47
|
+
const value = error;
|
|
48
|
+
if (typeof value !== "object" ||
|
|
49
|
+
value === null ||
|
|
50
|
+
!Number.isInteger(value.code) ||
|
|
51
|
+
typeof value.message !== "string") {
|
|
52
|
+
invalid("an error response needs an integer code and a string message", id);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** A request or notification has a method and no result or error; a response has exactly one of `result` and `error`. */
|
|
56
|
+
function checkShape(value, id) {
|
|
57
|
+
// A member counts only when it has a value, because JSON.stringify drops one that is undefined.
|
|
58
|
+
const has = (name) => value[name] !== undefined;
|
|
59
|
+
const hasMethod = has("method");
|
|
60
|
+
const answers = (has("result") ? 1 : 0) + (has("error") ? 1 : 0);
|
|
61
|
+
if (hasMethod && answers > 0)
|
|
62
|
+
invalid("a message with a method can't also carry a result or an error", id);
|
|
63
|
+
if (!hasMethod && answers !== 1)
|
|
64
|
+
invalid("a response must carry exactly one of result and error", id);
|
|
65
|
+
if (hasMethod && (typeof value.method !== "string" || value.method === ""))
|
|
66
|
+
invalid("a method must be a string", id);
|
|
67
|
+
if (!hasMethod && value.id === undefined)
|
|
68
|
+
invalid("a response needs an id", null);
|
|
69
|
+
if (has("error"))
|
|
70
|
+
checkError(value.error, value.id);
|
|
71
|
+
}
|
|
72
|
+
function checkEnvelope(value) {
|
|
73
|
+
// The id is read first, so that every later refusal can name the request it is about.
|
|
74
|
+
const id = isId(value.id) ? value.id : null;
|
|
75
|
+
if (value.jsonrpc !== "2.0")
|
|
76
|
+
invalid('a message must carry "jsonrpc": "2.0"', id);
|
|
77
|
+
// Only an error response may have a null id, because the request it answers could not be read.
|
|
78
|
+
if (value.id !== undefined && !isId(value.id) && !(value.id === null && value.error !== undefined)) {
|
|
79
|
+
invalid("an id must be a number or a string", null);
|
|
80
|
+
}
|
|
81
|
+
checkShape(value, id);
|
|
82
|
+
const { params } = value;
|
|
83
|
+
if (params !== undefined && (typeof params !== "object" || params === null || Array.isArray(params))) {
|
|
84
|
+
invalid("params must be an object", id);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** The value as an object that can be an envelope, after the envelope check. */
|
|
88
|
+
function checkObject(value) {
|
|
89
|
+
if (typeof value !== "object" || value === null)
|
|
90
|
+
invalid("a message must be a JSON object");
|
|
91
|
+
if (Array.isArray(value))
|
|
92
|
+
invalid("a batch is not supported, so each message goes on its own line");
|
|
93
|
+
checkEnvelope(value);
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Reads one message from a line of JSON text or a parsed value, and checks its envelope. A batch (an array) is not
|
|
98
|
+
* supported. Throws a `ProtocolError`: `invalid_json` with the parse-error code for text that is not JSON, and
|
|
99
|
+
* `invalid_request` with the invalid-request code for anything else wrong, such as a missing `jsonrpc`.
|
|
100
|
+
*/
|
|
101
|
+
export function decode(input) {
|
|
102
|
+
let value = input;
|
|
103
|
+
if (typeof input === "string") {
|
|
104
|
+
try {
|
|
105
|
+
value = JSON.parse(input);
|
|
106
|
+
}
|
|
107
|
+
catch (cause) {
|
|
108
|
+
throw new ProtocolError("invalid_json", "a line is not valid JSON", {
|
|
109
|
+
cause,
|
|
110
|
+
rpcCode: ErrorCodes.ParseError,
|
|
111
|
+
requestId: null,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return checkObject(value);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Turns a message into one line of JSON ending in `\n`, after the same envelope check `decode()` makes. JSON text has no
|
|
119
|
+
* raw newline in it, so the line can't be split by accident. U+2028 and U+2029 stay as they are, which is why a reader
|
|
120
|
+
* must split on `\n` only.
|
|
121
|
+
*/
|
|
122
|
+
export function encode(message) {
|
|
123
|
+
checkObject(message);
|
|
124
|
+
try {
|
|
125
|
+
const text = JSON.stringify(message);
|
|
126
|
+
if (text === undefined)
|
|
127
|
+
invalid("a message must be JSON");
|
|
128
|
+
return `${text}\n`;
|
|
129
|
+
}
|
|
130
|
+
catch (cause) {
|
|
131
|
+
if (cause instanceof ProtocolError)
|
|
132
|
+
throw cause;
|
|
133
|
+
// A bigint or a circular value in params or result. It is the sender's bug, so it is an internal error.
|
|
134
|
+
throw new ProtocolError("invalid_request", "a message can't be written as JSON", {
|
|
135
|
+
cause,
|
|
136
|
+
rpcCode: ErrorCodes.InternalError,
|
|
137
|
+
requestId: null,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=jsonrpc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonrpc.js","sourceRoot":"","sources":["../src/jsonrpc.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,qHAAqH;AACrH,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,UAAU,EAAE,CAAC,KAAK;IAClB,cAAc,EAAE,CAAC,KAAK;IACtB,cAAc,EAAE,CAAC,KAAK;IACtB,aAAa,EAAE,CAAC,KAAK;IACrB,aAAa,EAAE,CAAC,KAAK;IACrB,oEAAoE;IACpE,SAAS,EAAE,CAAC,KAAK;IACjB,wCAAwC;IACxC,aAAa,EAAE,CAAC,KAAK;IACrB,kEAAkE;IAClE,UAAU,EAAE,CAAC,KAAK;CACV,CAAC;AAEX,uGAAuG;AACvG,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,YAAY;IACZ,gBAAgB;IAChB,cAAc;IACd,cAAc;IACd,YAAY;IACZ,YAAY;IACZ,eAAe;IACf,gBAAgB;IAChB,eAAe;IACf,kBAAkB;IAClB,cAAc;IACd,iBAAiB;CACT,CAAC;AAEX,qCAAqC;AACrC,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,kBAAkB,EAAE,uBAAuB,EAAE,WAAW,CAAU,CAAC;AAE1G,wGAAwG;AACxG,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,OAAO,EA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OAAO,CAAC,wBAAwB,CAAC,CAAC;QAC1D,OAAO,GAAG,IAAI,IAAI,CAAC;IACrB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,aAAa;YAAE,MAAM,KAAK,CAAC;QAChD,wGAAwG;QACxG,MAAM,IAAI,aAAa,CAAC,iBAAiB,EAAE,oCAAoC,EAAE;YAC/E,KAAK;YACL,OAAO,EAAE,UAAU,CAAC,aAAa;YACjC,SAAS,EAAE,IAAI;SAChB,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["/**\n * JSON-RPC 2.0 framing, strictly: `encode()` and `decode()` refuse a message without `\"jsonrpc\": \"2.0\"`. They check the\n * envelope only, because a method's params are the dispatcher's to check against the schema; a message that fails\n * throws a `ProtocolError` that carries the JSON-RPC code and the request's id, so a server can answer it.\n */\nimport { ProtocolError } from \"./errors.js\";\nimport type { Id, ProtocolMessage } from \"./messages.js\";\n\n/** The JSON-RPC error codes the protocol uses: the standard ones, and three of its own in the server-error range. */\nexport const ErrorCodes = {\n ParseError: -32700,\n InvalidRequest: -32600,\n MethodNotFound: -32601,\n InvalidParams: -32602,\n InternalError: -32603,\n /** The dispatcher's queue is full, so the command was not taken. */\n QueueFull: -32001,\n /** Another writer holds the session. */\n SessionLocked: -32002,\n /** The client used an experimental method it did not opt into. */\n NotOptedIn: -32003,\n} as const;\n\n/** The methods a client may call. `$/cancelRequest` is a notification, and the others are requests. */\nexport const CLIENT_METHODS = [\n \"initialize\",\n \"session/create\",\n \"session/open\",\n \"session/list\",\n \"turn/start\",\n \"turn/steer\",\n \"turn/followUp\",\n \"turn/interrupt\",\n \"approval/list\",\n \"session/checkout\",\n \"session/fork\",\n \"$/cancelRequest\",\n] as const;\n\n/** The requests the server sends. */\nexport const SERVER_REQUEST_METHODS = [\"approval/request\", \"clarification/request\", \"tool/call\"] as const;\n\n/** The notifications the server sends. `$/cancelRequest` withdraws one of the server's own requests. */\nexport const SERVER_NOTIFICATION_METHODS = [\"event\", \"turn/settled\", \"$/cancelRequest\"] as const;\n\n/** The client methods that need an opt-in, because they may change before a client other than ours uses them. */\nexport const EXPERIMENTAL_METHODS = [\"session/checkout\", \"session/fork\"] as const;\n\n/** A JSON-RPC message as `decode()` reads it: the envelope is checked, and `params` and `result` are not. */\nexport type JsonRpcMessage =\n | { jsonrpc: \"2.0\"; id: Id; method: string; params?: Record<string, unknown> }\n | { jsonrpc: \"2.0\"; method: string; params?: Record<string, unknown> }\n | { jsonrpc: \"2.0\"; id: Id; result: unknown }\n | { jsonrpc: \"2.0\"; id: Id | null; error: { code: number; message: string; data?: unknown } };\n\nfunction invalid(why: string, id: Id | null = null): never {\n throw new ProtocolError(\"invalid_request\", why, { rpcCode: ErrorCodes.InvalidRequest, requestId: id });\n}\n\nconst isId = (value: unknown): value is Id =>\n typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n\nfunction checkError(error: unknown, id: Id | null): void {\n const value = error as { code?: unknown; message?: unknown } | null;\n if (\n typeof value !== \"object\" ||\n value === null ||\n !Number.isInteger(value.code) ||\n typeof value.message !== \"string\"\n ) {\n invalid(\"an error response needs an integer code and a string message\", id);\n }\n}\n\n/** A request or notification has a method and no result or error; a response has exactly one of `result` and `error`. */\nfunction checkShape(value: Record<string, unknown>, id: Id | null): void {\n // A member counts only when it has a value, because JSON.stringify drops one that is undefined.\n const has = (name: string) => value[name] !== undefined;\n const hasMethod = has(\"method\");\n const answers = (has(\"result\") ? 1 : 0) + (has(\"error\") ? 1 : 0);\n if (hasMethod && answers > 0) invalid(\"a message with a method can't also carry a result or an error\", id);\n if (!hasMethod && answers !== 1) invalid(\"a response must carry exactly one of result and error\", id);\n if (hasMethod && (typeof value.method !== \"string\" || value.method === \"\")) invalid(\"a method must be a string\", id);\n if (!hasMethod && value.id === undefined) invalid(\"a response needs an id\", null);\n if (has(\"error\")) checkError(value.error, value.id as Id | null);\n}\n\nfunction checkEnvelope(value: Record<string, unknown>): void {\n // The id is read first, so that every later refusal can name the request it is about.\n const id = isId(value.id) ? value.id : null;\n if (value.jsonrpc !== \"2.0\") invalid('a message must carry \"jsonrpc\": \"2.0\"', id);\n // Only an error response may have a null id, because the request it answers could not be read.\n if (value.id !== undefined && !isId(value.id) && !(value.id === null && value.error !== undefined)) {\n invalid(\"an id must be a number or a string\", null);\n }\n checkShape(value, id);\n const { params } = value;\n if (params !== undefined && (typeof params !== \"object\" || params === null || Array.isArray(params))) {\n invalid(\"params must be an object\", id);\n }\n}\n\n/** The value as an object that can be an envelope, after the envelope check. */\nfunction checkObject(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) invalid(\"a message must be a JSON object\");\n if (Array.isArray(value)) invalid(\"a batch is not supported, so each message goes on its own line\");\n checkEnvelope(value as Record<string, unknown>);\n return value as Record<string, unknown>;\n}\n\n/**\n * Reads one message from a line of JSON text or a parsed value, and checks its envelope. A batch (an array) is not\n * supported. Throws a `ProtocolError`: `invalid_json` with the parse-error code for text that is not JSON, and\n * `invalid_request` with the invalid-request code for anything else wrong, such as a missing `jsonrpc`.\n */\nexport function decode(input: unknown): JsonRpcMessage {\n let value = input;\n if (typeof input === \"string\") {\n try {\n value = JSON.parse(input);\n } catch (cause) {\n throw new ProtocolError(\"invalid_json\", \"a line is not valid JSON\", {\n cause,\n rpcCode: ErrorCodes.ParseError,\n requestId: null,\n });\n }\n }\n return checkObject(value) as unknown as JsonRpcMessage;\n}\n\n/**\n * Turns a message into one line of JSON ending in `\\n`, after the same envelope check `decode()` makes. JSON text has no\n * raw newline in it, so the line can't be split by accident. U+2028 and U+2029 stay as they are, which is why a reader\n * must split on `\\n` only.\n */\nexport function encode(message: ProtocolMessage | JsonRpcMessage): string {\n checkObject(message);\n try {\n const text = JSON.stringify(message);\n if (text === undefined) invalid(\"a message must be JSON\");\n return `${text}\\n`;\n } catch (cause) {\n if (cause instanceof ProtocolError) throw cause;\n // A bigint or a circular value in params or result. It is the sender's bug, so it is an internal error.\n throw new ProtocolError(\"invalid_request\", \"a message can't be written as JSON\", {\n cause,\n rpcCode: ErrorCodes.InternalError,\n requestId: null,\n });\n }\n}\n"]}
|