@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
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session log's entry union: every line of a session file is one `SessionEntry`. The log is an append-only tree,
|
|
3
|
+
* so each entry names its parent. `EntryBase`, the entry type names and `formatVersion` are the stable surface that a
|
|
4
|
+
* tool you write may rely on; every other field is documented but may change with a `formatVersion` bump, which ships
|
|
5
|
+
* with a migration that writes a new file. The JSON Schema of the union is `schema/session-entry.schema.json`.
|
|
6
|
+
*/
|
|
7
|
+
import type { AssistantMessage, ContentBlock, Cost, ModelContent, ModelRef, Usage } from "@buildanagent/gateway";
|
|
8
|
+
import type { Resolution, RunResult, SignedPendingRequest } from "@buildanagent/sdk";
|
|
9
|
+
/** The format version of every entry this package writes and reads. A session file's header carries it. */
|
|
10
|
+
export declare const FORMAT_VERSION = 1;
|
|
11
|
+
/** Who produced an entry's content. One label per entry, so one block of a message has one origin. */
|
|
12
|
+
export type Origin = "user" | "operator" | "model" | "tool" | "harness";
|
|
13
|
+
/** How tool calls are decided: `shadow` records what would have happened without doing it. */
|
|
14
|
+
export type PermissionMode = "default" | "accept_edits" | "read_only" | "bypass" | "shadow";
|
|
15
|
+
/** When a sandboxed call may ask a person: on request, by granular rule, or never. */
|
|
16
|
+
export type ApprovalPolicy = "on-request" | "granular" | "never";
|
|
17
|
+
/** How strongly a sandbox isolates a run, from none to a micro-VM. */
|
|
18
|
+
export type SandboxTier = "none" | "os" | "container" | "gvisor" | "microvm";
|
|
19
|
+
/** The fields every entry has, with its `type`. All six are stable, and each carries a `@stable` tag. */
|
|
20
|
+
export interface EntryBase {
|
|
21
|
+
/** The entry's id, unique within its session. Appending the same id twice changes nothing. @stable */
|
|
22
|
+
id: string;
|
|
23
|
+
/** The entry this one follows, or `null` for the first entry of a session. @stable */
|
|
24
|
+
parentId: string | null;
|
|
25
|
+
/** Position in the file, from 0 and rising by 1. @stable */
|
|
26
|
+
seq: number;
|
|
27
|
+
/** When the entry was written, as an ISO 8601 string. @stable */
|
|
28
|
+
timestamp: string;
|
|
29
|
+
/** Who produced the content. @stable */
|
|
30
|
+
origin: Origin;
|
|
31
|
+
}
|
|
32
|
+
/** The first entry of a session file: what ran the session, and which session it came from. */
|
|
33
|
+
export interface SessionHeaderEntry {
|
|
34
|
+
/** The entry type name. @stable */
|
|
35
|
+
type: "session_header";
|
|
36
|
+
/** `FORMAT_VERSION`. A reader refuses a file with another value. @stable */
|
|
37
|
+
formatVersion: 1;
|
|
38
|
+
harnessVersion: string;
|
|
39
|
+
sdkVersion: string;
|
|
40
|
+
/** The SDK's `DEFAULTS_HASH` for the run, so a change in behavior shows whether defaults moved. */
|
|
41
|
+
defaultsHash: string;
|
|
42
|
+
/** The SDK's capability strings. */
|
|
43
|
+
capabilities: string[];
|
|
44
|
+
/** A hash of the ablation switches this session ran with. */
|
|
45
|
+
ablationHash: string;
|
|
46
|
+
/**
|
|
47
|
+
* The session and entry this one was forked from, or, when `spawn` is present, the session and `subagent_link` entry
|
|
48
|
+
* that started it. A forked session continues its parent's log up to that entry, and a spawned one does not.
|
|
49
|
+
*/
|
|
50
|
+
parent?: {
|
|
51
|
+
session: string;
|
|
52
|
+
entryId: string;
|
|
53
|
+
};
|
|
54
|
+
/** Set on the log of a subagent or a workflow step: the tool call or the step that started it, never both. */
|
|
55
|
+
spawn?: {
|
|
56
|
+
spawningCallId: string;
|
|
57
|
+
stepId?: never;
|
|
58
|
+
} | {
|
|
59
|
+
stepId: string;
|
|
60
|
+
spawningCallId?: never;
|
|
61
|
+
};
|
|
62
|
+
/** The product that owns the session, when one does. Outside the stable surface. */
|
|
63
|
+
product?: {
|
|
64
|
+
name: string;
|
|
65
|
+
version: string;
|
|
66
|
+
bundleHash: string;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** A turn began. `system` is the frozen system prompt, byte for byte, so a rebuilt context carries it. */
|
|
70
|
+
export interface TurnStartEntry {
|
|
71
|
+
/** The entry type name. @stable */
|
|
72
|
+
type: "turn_start";
|
|
73
|
+
runId: string;
|
|
74
|
+
mode: "run" | "continue";
|
|
75
|
+
system: string;
|
|
76
|
+
}
|
|
77
|
+
/** One content block of a message. A message is several of these, in `index` order, closed by a `message_end`. */
|
|
78
|
+
export interface MessageBlockEntry {
|
|
79
|
+
/** The entry type name. @stable */
|
|
80
|
+
type: "message_block";
|
|
81
|
+
messageId: string;
|
|
82
|
+
role: "user" | "assistant";
|
|
83
|
+
index: number;
|
|
84
|
+
block: ContentBlock;
|
|
85
|
+
/** How a user message reached the run, when it did not start it. */
|
|
86
|
+
delivery?: "input" | "steer" | "follow_up";
|
|
87
|
+
}
|
|
88
|
+
/** A message is complete: which model wrote it and why it stopped. */
|
|
89
|
+
export interface MessageEndEntry {
|
|
90
|
+
/** The entry type name. @stable */
|
|
91
|
+
type: "message_end";
|
|
92
|
+
messageId: string;
|
|
93
|
+
model: ModelRef;
|
|
94
|
+
stopReason: AssistantMessage["stopReason"];
|
|
95
|
+
error?: AssistantMessage["error"];
|
|
96
|
+
}
|
|
97
|
+
/** What a tool call returned to the model. */
|
|
98
|
+
export interface ToolResultEntry {
|
|
99
|
+
/** The entry type name. @stable */
|
|
100
|
+
type: "tool_result";
|
|
101
|
+
callId: string;
|
|
102
|
+
tool: string;
|
|
103
|
+
content: ModelContent[];
|
|
104
|
+
isError: boolean;
|
|
105
|
+
details?: unknown;
|
|
106
|
+
/** Where the full output went when it was too large to keep in the entry. */
|
|
107
|
+
spill?: {
|
|
108
|
+
path: string;
|
|
109
|
+
bytes: number;
|
|
110
|
+
};
|
|
111
|
+
/** Whether the tool's output may carry instructions an attacker wrote. */
|
|
112
|
+
trust: "trusted" | "untrusted";
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* A tool call that the host's own code chose to make, with no model step. It is written before the permission pipeline
|
|
116
|
+
* decides the call, and its id is the call's id, so the call's effect key can be derived from it before the tool runs.
|
|
117
|
+
* The model never reads a code call or its result.
|
|
118
|
+
*/
|
|
119
|
+
export interface CodeCallEntry {
|
|
120
|
+
/** The entry type name. @stable */
|
|
121
|
+
type: "code_call";
|
|
122
|
+
/** The call's id, which the call's `permission_decision`, `approval_requested` and `tool_result` entries name. */
|
|
123
|
+
callId: string;
|
|
124
|
+
/** The tool's canonical name. */
|
|
125
|
+
tool: string;
|
|
126
|
+
/** The input the call runs with. */
|
|
127
|
+
input: unknown;
|
|
128
|
+
/** `canonicalInputHash()` of `input`, which a resume checks before the call runs. */
|
|
129
|
+
inputHash: string;
|
|
130
|
+
/** The id of the earlier code call this one compensates, when it undoes one. */
|
|
131
|
+
compensates?: string;
|
|
132
|
+
}
|
|
133
|
+
/** The permission pipeline's decision on one tool call, written for every decision. */
|
|
134
|
+
export interface PermissionDecisionEntry {
|
|
135
|
+
/** The entry type name. @stable */
|
|
136
|
+
type: "permission_decision";
|
|
137
|
+
callId: string;
|
|
138
|
+
tool: string;
|
|
139
|
+
decision: "allow" | "deny" | "ask";
|
|
140
|
+
/** The rule that decided, when one did. */
|
|
141
|
+
rule?: string;
|
|
142
|
+
/** Who decided, when a person or a hook did. */
|
|
143
|
+
by?: string;
|
|
144
|
+
policyVersion: string;
|
|
145
|
+
/** The hash of the input the decision covers. */
|
|
146
|
+
inputHash: string;
|
|
147
|
+
}
|
|
148
|
+
/** The tokens and cost of one model call, a summary or a judge call. `cost.total` is `null` when the price is unknown. */
|
|
149
|
+
export interface UsageEntry {
|
|
150
|
+
/** The entry type name. @stable */
|
|
151
|
+
type: "usage";
|
|
152
|
+
source: "model_call" | "summary" | "judge";
|
|
153
|
+
usage: Usage;
|
|
154
|
+
/** The usage of the last attempt alone, when a retry made `usage` a sum. A rebuilt message carries it back. */
|
|
155
|
+
lastAttemptUsage?: Usage;
|
|
156
|
+
cost: Cost;
|
|
157
|
+
}
|
|
158
|
+
/** A turn ended, with the stop reason of its run. */
|
|
159
|
+
export interface TurnEndEntry {
|
|
160
|
+
/** The entry type name. @stable */
|
|
161
|
+
type: "turn_end";
|
|
162
|
+
runId: string;
|
|
163
|
+
stopReason: RunResult<unknown>["stopReason"];
|
|
164
|
+
steps: number;
|
|
165
|
+
}
|
|
166
|
+
/** HEAD moved to another entry. The log persists HEAD as an entry, so a restart finds it. */
|
|
167
|
+
export interface CheckoutEntry {
|
|
168
|
+
/** The entry type name. @stable */
|
|
169
|
+
type: "checkout";
|
|
170
|
+
headId: string;
|
|
171
|
+
}
|
|
172
|
+
/** A summary replaced older entries in the context a rebuilt run sends. */
|
|
173
|
+
export interface CompactionEntry {
|
|
174
|
+
/** The entry type name. @stable */
|
|
175
|
+
type: "compaction";
|
|
176
|
+
layer: "summarize" | "mid_turn" | "overflow_retry";
|
|
177
|
+
summary: string;
|
|
178
|
+
firstKeptEntryId: string;
|
|
179
|
+
tokensBefore: number;
|
|
180
|
+
tokensAfter: number;
|
|
181
|
+
model: ModelRef;
|
|
182
|
+
promptVersion: string;
|
|
183
|
+
/** The `usage` entry that records the summary call's cost. */
|
|
184
|
+
usageEntryId: string;
|
|
185
|
+
focus?: string;
|
|
186
|
+
}
|
|
187
|
+
/** The environment a session ran in. */
|
|
188
|
+
export interface EnvStampEntry {
|
|
189
|
+
/** The entry type name. @stable */
|
|
190
|
+
type: "env_stamp";
|
|
191
|
+
cwd: string;
|
|
192
|
+
permissionMode: PermissionMode;
|
|
193
|
+
approvalPolicy: ApprovalPolicy;
|
|
194
|
+
sandbox: SandboxTier;
|
|
195
|
+
model: ModelRef;
|
|
196
|
+
effort?: string;
|
|
197
|
+
}
|
|
198
|
+
/** The tools and model in force changed. */
|
|
199
|
+
export interface LoadoutEntry {
|
|
200
|
+
/** The entry type name. @stable */
|
|
201
|
+
type: "loadout";
|
|
202
|
+
tools: string[];
|
|
203
|
+
model?: ModelRef;
|
|
204
|
+
effort?: string;
|
|
205
|
+
}
|
|
206
|
+
/** The commands that checked a finished task, and whether they passed. */
|
|
207
|
+
export interface CompletionCheckEntry {
|
|
208
|
+
/** The entry type name. @stable */
|
|
209
|
+
type: "completion_check";
|
|
210
|
+
checks: Array<{
|
|
211
|
+
command: string;
|
|
212
|
+
exitCode: number;
|
|
213
|
+
}>;
|
|
214
|
+
passed: boolean;
|
|
215
|
+
flagged: string[];
|
|
216
|
+
}
|
|
217
|
+
/** A skill's instructions entered the context. */
|
|
218
|
+
export interface SkillLoadedEntry {
|
|
219
|
+
/** The entry type name. @stable */
|
|
220
|
+
type: "skill_loaded";
|
|
221
|
+
name: string;
|
|
222
|
+
path: string;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* What an `extension_loaded` entry of tier `mcp` records about the server that connected. It holds hashes, never the
|
|
226
|
+
* command's arguments or any environment value, because either can carry a secret.
|
|
227
|
+
*/
|
|
228
|
+
export interface McpServerRecord {
|
|
229
|
+
/** How the harness reached the server. */
|
|
230
|
+
transport: "stdio" | "in_process";
|
|
231
|
+
/**
|
|
232
|
+
* For a stdio server: `sha256:` and the hex digest of the canonical JSON (RFC 8785) of `[command, ...args]`. It is not
|
|
233
|
+
* salted, so a reader of the log can confirm a guessed argument by hashing it; a secret never belongs in the args.
|
|
234
|
+
*/
|
|
235
|
+
commandHash?: string;
|
|
236
|
+
/** The protocol era the server negotiated. */
|
|
237
|
+
era: "2026-07-28" | "legacy";
|
|
238
|
+
/**
|
|
239
|
+
* `sha256:` and the hex digest of the canonical JSON of the tool list the server sent, sorted by name, each as
|
|
240
|
+
* `{ name, description, inputSchema }`, before the harness strips regular-expression keywords from the schemas.
|
|
241
|
+
*/
|
|
242
|
+
toolsHash: string;
|
|
243
|
+
}
|
|
244
|
+
/** An extension was loaded, with the hash of what ran. */
|
|
245
|
+
export interface ExtensionLoadedEntry {
|
|
246
|
+
/** The entry type name. @stable */
|
|
247
|
+
type: "extension_loaded";
|
|
248
|
+
/** The extension's name, or the MCP server's name for tier `mcp`. */
|
|
249
|
+
name: string;
|
|
250
|
+
tier: "in_process" | "mcp" | "skill";
|
|
251
|
+
/** `sha256:` and a hex digest. For tier `mcp`, the digest of the canonical JSON of `mcp`. */
|
|
252
|
+
contentHash: string;
|
|
253
|
+
/** Set for tier `mcp` only. */
|
|
254
|
+
mcp?: McpServerRecord;
|
|
255
|
+
}
|
|
256
|
+
/** A child session exists. It names the tool call or workflow step that started it, one of the two. */
|
|
257
|
+
export interface SubagentLinkEntry {
|
|
258
|
+
/** The entry type name. @stable */
|
|
259
|
+
type: "subagent_link";
|
|
260
|
+
childSession: string;
|
|
261
|
+
spawningCallId?: string;
|
|
262
|
+
stepId?: string;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* A tool call waits for a person. `request` is the SDK's signed record, unchanged, and `input` is the input the call
|
|
266
|
+
* would run with once approved, which the approver is shown and the resume passes back with the signature. The harness
|
|
267
|
+
* writes this entry before its own observers see the request. It holds no key bytes: the signature names the key by id.
|
|
268
|
+
*/
|
|
269
|
+
export interface ApprovalRequestedEntry {
|
|
270
|
+
/** The entry type name. @stable */
|
|
271
|
+
type: "approval_requested";
|
|
272
|
+
request: SignedPendingRequest;
|
|
273
|
+
input: unknown;
|
|
274
|
+
}
|
|
275
|
+
/** A person's answer to a pending request, written before the run that applies it starts. */
|
|
276
|
+
export interface ApprovalResolvedEntry {
|
|
277
|
+
/** The entry type name. @stable */
|
|
278
|
+
type: "approval_resolved";
|
|
279
|
+
resolution: Resolution;
|
|
280
|
+
/** Set on an allow that also covers the same call later: for this run (the turn and its resumes) or this session. */
|
|
281
|
+
sticky?: "run" | "session";
|
|
282
|
+
/** What a sticky allowance matches: the tool and the call's input hash, or a command prefix for a shell tool. */
|
|
283
|
+
allowance?: {
|
|
284
|
+
tool: string;
|
|
285
|
+
inputHash?: string;
|
|
286
|
+
commandPrefix?: string[];
|
|
287
|
+
policyVersion?: string;
|
|
288
|
+
};
|
|
289
|
+
/** Set when one answer covered several requests of one step that share a tool and an input. */
|
|
290
|
+
groupId?: string;
|
|
291
|
+
/** Set on an answer that a quorum still waits on, which no run has been given yet. */
|
|
292
|
+
quorum?: "pending";
|
|
293
|
+
}
|
|
294
|
+
/** A call that shadow mode recorded and did not run. */
|
|
295
|
+
export interface ShadowCallEntry {
|
|
296
|
+
/** The entry type name. @stable */
|
|
297
|
+
type: "shadow_call";
|
|
298
|
+
callId: string;
|
|
299
|
+
tool: string;
|
|
300
|
+
inputHash: string;
|
|
301
|
+
}
|
|
302
|
+
/** A record that the product owns. `name` is namespaced, such as `triage.record`. Outside the stable surface. */
|
|
303
|
+
export interface ProductRecordEntry {
|
|
304
|
+
/** The entry type name. @stable */
|
|
305
|
+
type: "product_record";
|
|
306
|
+
name: string;
|
|
307
|
+
data: unknown;
|
|
308
|
+
}
|
|
309
|
+
/** One line of a session file. */
|
|
310
|
+
export type SessionEntry = EntryBase & (SessionHeaderEntry | TurnStartEntry | MessageBlockEntry | MessageEndEntry | ToolResultEntry | CodeCallEntry | PermissionDecisionEntry | UsageEntry | TurnEndEntry | CheckoutEntry | CompactionEntry | EnvStampEntry | LoadoutEntry | CompletionCheckEntry | SkillLoadedEntry | ExtensionLoadedEntry | SubagentLinkEntry | ApprovalRequestedEntry | ApprovalResolvedEntry | ShadowCallEntry | ProductRecordEntry);
|
|
311
|
+
/** The `type` of every entry in the union, in the order the union lists them. */
|
|
312
|
+
export declare const SESSION_ENTRY_TYPES: readonly ["session_header", "turn_start", "message_block", "message_end", "tool_result", "code_call", "permission_decision", "usage", "turn_end", "checkout", "compaction", "env_stamp", "loadout", "completion_check", "skill_loaded", "extension_loaded", "subagent_link", "approval_requested", "approval_resolved", "shadow_call", "product_record"];
|
|
313
|
+
/**
|
|
314
|
+
* The shape of an ISO 8601 date and time with a zone, such as `2026-11-22T03:00:00.000Z`: what `timestamp` holds. The
|
|
315
|
+
* schema checks only this shape; `parseEntry()` also refuses a date that does not exist.
|
|
316
|
+
*/
|
|
317
|
+
export declare const TIMESTAMP_PATTERN: RegExp;
|
|
318
|
+
/**
|
|
319
|
+
* Reads one session entry from a JSON line or an already parsed value, and checks what every reader relies on: it
|
|
320
|
+
* is an object with valid base fields, its `type` is in the union, and a `session_header` has this package's
|
|
321
|
+
* `formatVersion`. It does not check each type's own fields; validate those against
|
|
322
|
+
* `schema/session-entry.schema.json`.
|
|
323
|
+
*
|
|
324
|
+
* Throws a `ProtocolError` with code `unsupported_format_version` for a header from another format, so a reader never
|
|
325
|
+
* misreads a newer file, and with code `invalid_entry` for text that is not JSON, a value that is not an object, a
|
|
326
|
+
* bad base field or an unknown `type`.
|
|
327
|
+
*/
|
|
328
|
+
export declare function parseEntry(input: unknown): SessionEntry;
|
package/dist/entries.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { ProtocolError } from "./errors.js";
|
|
2
|
+
/** The format version of every entry this package writes and reads. A session file's header carries it. */
|
|
3
|
+
export const FORMAT_VERSION = 1;
|
|
4
|
+
/** The `type` of every entry in the union, in the order the union lists them. */
|
|
5
|
+
export const SESSION_ENTRY_TYPES = [
|
|
6
|
+
"session_header",
|
|
7
|
+
"turn_start",
|
|
8
|
+
"message_block",
|
|
9
|
+
"message_end",
|
|
10
|
+
"tool_result",
|
|
11
|
+
"code_call",
|
|
12
|
+
"permission_decision",
|
|
13
|
+
"usage",
|
|
14
|
+
"turn_end",
|
|
15
|
+
"checkout",
|
|
16
|
+
"compaction",
|
|
17
|
+
"env_stamp",
|
|
18
|
+
"loadout",
|
|
19
|
+
"completion_check",
|
|
20
|
+
"skill_loaded",
|
|
21
|
+
"extension_loaded",
|
|
22
|
+
"subagent_link",
|
|
23
|
+
"approval_requested",
|
|
24
|
+
"approval_resolved",
|
|
25
|
+
"shadow_call",
|
|
26
|
+
"product_record",
|
|
27
|
+
];
|
|
28
|
+
/**
|
|
29
|
+
* The shape of an ISO 8601 date and time with a zone, such as `2026-11-22T03:00:00.000Z`: what `timestamp` holds. The
|
|
30
|
+
* schema checks only this shape; `parseEntry()` also refuses a date that does not exist.
|
|
31
|
+
*/
|
|
32
|
+
export const TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
33
|
+
const ORIGINS = ["user", "operator", "model", "tool", "harness"];
|
|
34
|
+
function reject(message) {
|
|
35
|
+
throw new ProtocolError("invalid_entry", message);
|
|
36
|
+
}
|
|
37
|
+
function checkBase(value) {
|
|
38
|
+
if (typeof value.id !== "string" || value.id === "")
|
|
39
|
+
reject("an entry needs a non-empty string id");
|
|
40
|
+
if (value.parentId !== null && typeof value.parentId !== "string")
|
|
41
|
+
reject("parentId must be a string or null");
|
|
42
|
+
if (!Number.isSafeInteger(value.seq) || value.seq < 0)
|
|
43
|
+
reject("seq must be a safe whole number, 0 or more");
|
|
44
|
+
if (typeof value.timestamp !== "string" ||
|
|
45
|
+
!TIMESTAMP_PATTERN.test(value.timestamp) ||
|
|
46
|
+
Number.isNaN(Date.parse(value.timestamp))) {
|
|
47
|
+
reject("timestamp must be an ISO 8601 date and time with a zone");
|
|
48
|
+
}
|
|
49
|
+
if (typeof value.origin !== "string" || !ORIGINS.includes(value.origin))
|
|
50
|
+
reject(`origin must be one of ${ORIGINS.join(", ")}`);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Reads one session entry from a JSON line or an already parsed value, and checks what every reader relies on: it
|
|
54
|
+
* is an object with valid base fields, its `type` is in the union, and a `session_header` has this package's
|
|
55
|
+
* `formatVersion`. It does not check each type's own fields; validate those against
|
|
56
|
+
* `schema/session-entry.schema.json`.
|
|
57
|
+
*
|
|
58
|
+
* Throws a `ProtocolError` with code `unsupported_format_version` for a header from another format, so a reader never
|
|
59
|
+
* misreads a newer file, and with code `invalid_entry` for text that is not JSON, a value that is not an object, a
|
|
60
|
+
* bad base field or an unknown `type`.
|
|
61
|
+
*/
|
|
62
|
+
export function parseEntry(input) {
|
|
63
|
+
let value = input;
|
|
64
|
+
if (typeof input === "string") {
|
|
65
|
+
try {
|
|
66
|
+
value = JSON.parse(input);
|
|
67
|
+
}
|
|
68
|
+
catch (cause) {
|
|
69
|
+
throw new ProtocolError("invalid_entry", "an entry line is not valid JSON", { cause });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
73
|
+
reject("an entry must be a JSON object");
|
|
74
|
+
const entry = value;
|
|
75
|
+
if (entry.type === "session_header" && entry.formatVersion !== FORMAT_VERSION) {
|
|
76
|
+
throw new ProtocolError("unsupported_format_version", `this reader supports formatVersion ${FORMAT_VERSION}, and the session header says ${String(entry.formatVersion)}`);
|
|
77
|
+
}
|
|
78
|
+
if (!SESSION_ENTRY_TYPES.includes(entry.type))
|
|
79
|
+
reject(`unknown entry type ${String(entry.type)}`);
|
|
80
|
+
checkBase(entry);
|
|
81
|
+
return entry;
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=entries.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entries.js","sourceRoot":"","sources":["../src/entries.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * The session log's entry union: every line of a session file is one `SessionEntry`. The log is an append-only tree,\n * so each entry names its parent. `EntryBase`, the entry type names and `formatVersion` are the stable surface that a\n * tool you write may rely on; every other field is documented but may change with a `formatVersion` bump, which ships\n * with a migration that writes a new file. The JSON Schema of the union is `schema/session-entry.schema.json`.\n */\nimport type { AssistantMessage, ContentBlock, Cost, ModelContent, ModelRef, Usage } from \"@buildanagent/gateway\";\nimport type { Resolution, RunResult, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { ProtocolError } from \"./errors.js\";\n\n/** The format version of every entry this package writes and reads. A session file's header carries it. */\nexport const FORMAT_VERSION = 1;\n\n/** Who produced an entry's content. One label per entry, so one block of a message has one origin. */\nexport type Origin = \"user\" | \"operator\" | \"model\" | \"tool\" | \"harness\";\n\n/** How tool calls are decided: `shadow` records what would have happened without doing it. */\nexport type PermissionMode = \"default\" | \"accept_edits\" | \"read_only\" | \"bypass\" | \"shadow\";\n\n/** When a sandboxed call may ask a person: on request, by granular rule, or never. */\nexport type ApprovalPolicy = \"on-request\" | \"granular\" | \"never\";\n\n/** How strongly a sandbox isolates a run, from none to a micro-VM. */\nexport type SandboxTier = \"none\" | \"os\" | \"container\" | \"gvisor\" | \"microvm\";\n\n/** The fields every entry has, with its `type`. All six are stable, and each carries a `@stable` tag. */\nexport interface EntryBase {\n /** The entry's id, unique within its session. Appending the same id twice changes nothing. @stable */\n id: string;\n /** The entry this one follows, or `null` for the first entry of a session. @stable */\n parentId: string | null;\n /** Position in the file, from 0 and rising by 1. @stable */\n seq: number;\n /** When the entry was written, as an ISO 8601 string. @stable */\n timestamp: string;\n /** Who produced the content. @stable */\n origin: Origin;\n}\n\n/** The first entry of a session file: what ran the session, and which session it came from. */\nexport interface SessionHeaderEntry {\n /** The entry type name. @stable */\n type: \"session_header\";\n /** `FORMAT_VERSION`. A reader refuses a file with another value. @stable */\n formatVersion: 1;\n harnessVersion: string;\n sdkVersion: string;\n /** The SDK's `DEFAULTS_HASH` for the run, so a change in behavior shows whether defaults moved. */\n defaultsHash: string;\n /** The SDK's capability strings. */\n capabilities: string[];\n /** A hash of the ablation switches this session ran with. */\n ablationHash: string;\n /**\n * The session and entry this one was forked from, or, when `spawn` is present, the session and `subagent_link` entry\n * that started it. A forked session continues its parent's log up to that entry, and a spawned one does not.\n */\n parent?: { session: string; entryId: string };\n /** Set on the log of a subagent or a workflow step: the tool call or the step that started it, never both. */\n spawn?: { spawningCallId: string; stepId?: never } | { stepId: string; spawningCallId?: never };\n /** The product that owns the session, when one does. Outside the stable surface. */\n product?: { name: string; version: string; bundleHash: string };\n}\n\n/** A turn began. `system` is the frozen system prompt, byte for byte, so a rebuilt context carries it. */\nexport interface TurnStartEntry {\n /** The entry type name. @stable */\n type: \"turn_start\";\n runId: string;\n mode: \"run\" | \"continue\";\n system: string;\n}\n\n/** One content block of a message. A message is several of these, in `index` order, closed by a `message_end`. */\nexport interface MessageBlockEntry {\n /** The entry type name. @stable */\n type: \"message_block\";\n messageId: string;\n role: \"user\" | \"assistant\";\n index: number;\n block: ContentBlock;\n /** How a user message reached the run, when it did not start it. */\n delivery?: \"input\" | \"steer\" | \"follow_up\";\n}\n\n/** A message is complete: which model wrote it and why it stopped. */\nexport interface MessageEndEntry {\n /** The entry type name. @stable */\n type: \"message_end\";\n messageId: string;\n model: ModelRef;\n stopReason: AssistantMessage[\"stopReason\"];\n error?: AssistantMessage[\"error\"];\n}\n\n/** What a tool call returned to the model. */\nexport interface ToolResultEntry {\n /** The entry type name. @stable */\n type: \"tool_result\";\n callId: string;\n tool: string;\n content: ModelContent[];\n isError: boolean;\n details?: unknown;\n /** Where the full output went when it was too large to keep in the entry. */\n spill?: { path: string; bytes: number };\n /** Whether the tool's output may carry instructions an attacker wrote. */\n trust: \"trusted\" | \"untrusted\";\n}\n\n/**\n * A tool call that the host's own code chose to make, with no model step. It is written before the permission pipeline\n * decides the call, and its id is the call's id, so the call's effect key can be derived from it before the tool runs.\n * The model never reads a code call or its result.\n */\nexport interface CodeCallEntry {\n /** The entry type name. @stable */\n type: \"code_call\";\n /** The call's id, which the call's `permission_decision`, `approval_requested` and `tool_result` entries name. */\n callId: string;\n /** The tool's canonical name. */\n tool: string;\n /** The input the call runs with. */\n input: unknown;\n /** `canonicalInputHash()` of `input`, which a resume checks before the call runs. */\n inputHash: string;\n /** The id of the earlier code call this one compensates, when it undoes one. */\n compensates?: string;\n}\n\n/** The permission pipeline's decision on one tool call, written for every decision. */\nexport interface PermissionDecisionEntry {\n /** The entry type name. @stable */\n type: \"permission_decision\";\n callId: string;\n tool: string;\n decision: \"allow\" | \"deny\" | \"ask\";\n /** The rule that decided, when one did. */\n rule?: string;\n /** Who decided, when a person or a hook did. */\n by?: string;\n policyVersion: string;\n /** The hash of the input the decision covers. */\n inputHash: string;\n}\n\n/** The tokens and cost of one model call, a summary or a judge call. `cost.total` is `null` when the price is unknown. */\nexport interface UsageEntry {\n /** The entry type name. @stable */\n type: \"usage\";\n source: \"model_call\" | \"summary\" | \"judge\";\n usage: Usage;\n /** The usage of the last attempt alone, when a retry made `usage` a sum. A rebuilt message carries it back. */\n lastAttemptUsage?: Usage;\n cost: Cost;\n}\n\n/** A turn ended, with the stop reason of its run. */\nexport interface TurnEndEntry {\n /** The entry type name. @stable */\n type: \"turn_end\";\n runId: string;\n stopReason: RunResult<unknown>[\"stopReason\"];\n steps: number;\n}\n\n/** HEAD moved to another entry. The log persists HEAD as an entry, so a restart finds it. */\nexport interface CheckoutEntry {\n /** The entry type name. @stable */\n type: \"checkout\";\n headId: string;\n}\n\n/** A summary replaced older entries in the context a rebuilt run sends. */\nexport interface CompactionEntry {\n /** The entry type name. @stable */\n type: \"compaction\";\n layer: \"summarize\" | \"mid_turn\" | \"overflow_retry\";\n summary: string;\n firstKeptEntryId: string;\n tokensBefore: number;\n tokensAfter: number;\n model: ModelRef;\n promptVersion: string;\n /** The `usage` entry that records the summary call's cost. */\n usageEntryId: string;\n focus?: string;\n}\n\n/** The environment a session ran in. */\nexport interface EnvStampEntry {\n /** The entry type name. @stable */\n type: \"env_stamp\";\n cwd: string;\n permissionMode: PermissionMode;\n approvalPolicy: ApprovalPolicy;\n sandbox: SandboxTier;\n model: ModelRef;\n effort?: string;\n}\n\n/** The tools and model in force changed. */\nexport interface LoadoutEntry {\n /** The entry type name. @stable */\n type: \"loadout\";\n tools: string[];\n model?: ModelRef;\n effort?: string;\n}\n\n/** The commands that checked a finished task, and whether they passed. */\nexport interface CompletionCheckEntry {\n /** The entry type name. @stable */\n type: \"completion_check\";\n checks: Array<{ command: string; exitCode: number }>;\n passed: boolean;\n flagged: string[];\n}\n\n/** A skill's instructions entered the context. */\nexport interface SkillLoadedEntry {\n /** The entry type name. @stable */\n type: \"skill_loaded\";\n name: string;\n path: string;\n}\n\n/**\n * What an `extension_loaded` entry of tier `mcp` records about the server that connected. It holds hashes, never the\n * command's arguments or any environment value, because either can carry a secret.\n */\nexport interface McpServerRecord {\n /** How the harness reached the server. */\n transport: \"stdio\" | \"in_process\";\n /**\n * For a stdio server: `sha256:` and the hex digest of the canonical JSON (RFC 8785) of `[command, ...args]`. It is not\n * salted, so a reader of the log can confirm a guessed argument by hashing it; a secret never belongs in the args.\n */\n commandHash?: string;\n /** The protocol era the server negotiated. */\n era: \"2026-07-28\" | \"legacy\";\n /**\n * `sha256:` and the hex digest of the canonical JSON of the tool list the server sent, sorted by name, each as\n * `{ name, description, inputSchema }`, before the harness strips regular-expression keywords from the schemas.\n */\n toolsHash: string;\n}\n\n/** An extension was loaded, with the hash of what ran. */\nexport interface ExtensionLoadedEntry {\n /** The entry type name. @stable */\n type: \"extension_loaded\";\n /** The extension's name, or the MCP server's name for tier `mcp`. */\n name: string;\n tier: \"in_process\" | \"mcp\" | \"skill\";\n /** `sha256:` and a hex digest. For tier `mcp`, the digest of the canonical JSON of `mcp`. */\n contentHash: string;\n /** Set for tier `mcp` only. */\n mcp?: McpServerRecord;\n}\n\n/** A child session exists. It names the tool call or workflow step that started it, one of the two. */\nexport interface SubagentLinkEntry {\n /** The entry type name. @stable */\n type: \"subagent_link\";\n childSession: string;\n spawningCallId?: string;\n stepId?: string;\n}\n\n/**\n * A tool call waits for a person. `request` is the SDK's signed record, unchanged, and `input` is the input the call\n * would run with once approved, which the approver is shown and the resume passes back with the signature. The harness\n * writes this entry before its own observers see the request. It holds no key bytes: the signature names the key by id.\n */\nexport interface ApprovalRequestedEntry {\n /** The entry type name. @stable */\n type: \"approval_requested\";\n request: SignedPendingRequest;\n input: unknown;\n}\n\n/** A person's answer to a pending request, written before the run that applies it starts. */\nexport interface ApprovalResolvedEntry {\n /** The entry type name. @stable */\n type: \"approval_resolved\";\n resolution: Resolution;\n /** Set on an allow that also covers the same call later: for this run (the turn and its resumes) or this session. */\n sticky?: \"run\" | \"session\";\n /** What a sticky allowance matches: the tool and the call's input hash, or a command prefix for a shell tool. */\n allowance?: { tool: string; inputHash?: string; commandPrefix?: string[]; policyVersion?: string };\n /** Set when one answer covered several requests of one step that share a tool and an input. */\n groupId?: string;\n /** Set on an answer that a quorum still waits on, which no run has been given yet. */\n quorum?: \"pending\";\n}\n\n/** A call that shadow mode recorded and did not run. */\nexport interface ShadowCallEntry {\n /** The entry type name. @stable */\n type: \"shadow_call\";\n callId: string;\n tool: string;\n inputHash: string;\n}\n\n/** A record that the product owns. `name` is namespaced, such as `triage.record`. Outside the stable surface. */\nexport interface ProductRecordEntry {\n /** The entry type name. @stable */\n type: \"product_record\";\n name: string;\n data: unknown;\n}\n\n/** One line of a session file. */\nexport type SessionEntry = EntryBase &\n (\n | SessionHeaderEntry\n | TurnStartEntry\n | MessageBlockEntry\n | MessageEndEntry\n | ToolResultEntry\n | CodeCallEntry\n | PermissionDecisionEntry\n | UsageEntry\n | TurnEndEntry\n | CheckoutEntry\n | CompactionEntry\n | EnvStampEntry\n | LoadoutEntry\n | CompletionCheckEntry\n | SkillLoadedEntry\n | ExtensionLoadedEntry\n | SubagentLinkEntry\n | ApprovalRequestedEntry\n | ApprovalResolvedEntry\n | ShadowCallEntry\n | ProductRecordEntry\n );\n\n/** The `type` of every entry in the union, in the order the union lists them. */\nexport const SESSION_ENTRY_TYPES = [\n \"session_header\",\n \"turn_start\",\n \"message_block\",\n \"message_end\",\n \"tool_result\",\n \"code_call\",\n \"permission_decision\",\n \"usage\",\n \"turn_end\",\n \"checkout\",\n \"compaction\",\n \"env_stamp\",\n \"loadout\",\n \"completion_check\",\n \"skill_loaded\",\n \"extension_loaded\",\n \"subagent_link\",\n \"approval_requested\",\n \"approval_resolved\",\n \"shadow_call\",\n \"product_record\",\n] as const satisfies readonly SessionEntry[\"type\"][];\n\n/**\n * The shape of an ISO 8601 date and time with a zone, such as `2026-11-22T03:00:00.000Z`: what `timestamp` holds. The\n * schema checks only this shape; `parseEntry()` also refuses a date that does not exist.\n */\nexport const TIMESTAMP_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nconst ORIGINS: readonly string[] = [\"user\", \"operator\", \"model\", \"tool\", \"harness\"];\n\nfunction reject(message: string): never {\n throw new ProtocolError(\"invalid_entry\", message);\n}\n\nfunction checkBase(value: Record<string, unknown>): void {\n if (typeof value.id !== \"string\" || value.id === \"\") reject(\"an entry needs a non-empty string id\");\n if (value.parentId !== null && typeof value.parentId !== \"string\") reject(\"parentId must be a string or null\");\n if (!Number.isSafeInteger(value.seq) || (value.seq as number) < 0)\n reject(\"seq must be a safe whole number, 0 or more\");\n if (\n typeof value.timestamp !== \"string\" ||\n !TIMESTAMP_PATTERN.test(value.timestamp) ||\n Number.isNaN(Date.parse(value.timestamp))\n ) {\n reject(\"timestamp must be an ISO 8601 date and time with a zone\");\n }\n if (typeof value.origin !== \"string\" || !ORIGINS.includes(value.origin))\n reject(`origin must be one of ${ORIGINS.join(\", \")}`);\n}\n\n/**\n * Reads one session entry from a JSON line or an already parsed value, and checks what every reader relies on: it\n * is an object with valid base fields, its `type` is in the union, and a `session_header` has this package's\n * `formatVersion`. It does not check each type's own fields; validate those against\n * `schema/session-entry.schema.json`.\n *\n * Throws a `ProtocolError` with code `unsupported_format_version` for a header from another format, so a reader never\n * misreads a newer file, and with code `invalid_entry` for text that is not JSON, a value that is not an object, a\n * bad base field or an unknown `type`.\n */\nexport function parseEntry(input: unknown): SessionEntry {\n let value = input;\n if (typeof input === \"string\") {\n try {\n value = JSON.parse(input);\n } catch (cause) {\n throw new ProtocolError(\"invalid_entry\", \"an entry line is not valid JSON\", { cause });\n }\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) reject(\"an entry must be a JSON object\");\n const entry = value as Record<string, unknown>;\n if (entry.type === \"session_header\" && entry.formatVersion !== FORMAT_VERSION) {\n throw new ProtocolError(\n \"unsupported_format_version\",\n `this reader supports formatVersion ${FORMAT_VERSION}, and the session header says ${String(entry.formatVersion)}`,\n );\n }\n if (!(SESSION_ENTRY_TYPES as readonly unknown[]).includes(entry.type))\n reject(`unknown entry type ${String(entry.type)}`);\n checkBase(entry);\n return entry as unknown as SessionEntry;\n}\n"]}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why something was refused. `invalid_entry`: a session entry's `type` or base fields are wrong. `unsupported_format_version`:
|
|
3
|
+
* an entry is from a format this reader lacks. `invalid_json`: a line is not valid UTF-8 JSON. `invalid_request`: a
|
|
4
|
+
* JSON value is not a JSON-RPC 2.0 message. `line_too_long`: a line went over the framer's bound. `unterminated_line`:
|
|
5
|
+
* the stream ended in the middle of a line.
|
|
6
|
+
*/
|
|
7
|
+
export type ProtocolErrorCode = "invalid_entry" | "unsupported_format_version" | "invalid_json" | "invalid_request" | "line_too_long" | "unterminated_line";
|
|
8
|
+
/** What a `ProtocolError` carries when it is also a JSON-RPC error a peer can be answered with. */
|
|
9
|
+
export interface ProtocolErrorOptions extends ErrorOptions {
|
|
10
|
+
/** The JSON-RPC error code to reply with, such as -32600 for an invalid request. */
|
|
11
|
+
readonly rpcCode?: number;
|
|
12
|
+
/** The id of the message that failed, when it could be read, or `null` when it could not. */
|
|
13
|
+
readonly requestId?: number | string | null;
|
|
14
|
+
}
|
|
15
|
+
/** The error every `@buildanagent/protocol` function throws. Read `code` to tell the causes apart. */
|
|
16
|
+
export declare class ProtocolError extends Error {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly code: ProtocolErrorCode;
|
|
19
|
+
readonly rpcCode: number | undefined;
|
|
20
|
+
readonly requestId: number | string | null | undefined;
|
|
21
|
+
constructor(code: ProtocolErrorCode, message: string, options?: ProtocolErrorOptions);
|
|
22
|
+
}
|
|
23
|
+
/** True for a `ProtocolError`, including one from another copy of the package. */
|
|
24
|
+
export declare function isProtocolError(error: unknown): error is ProtocolError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** The error every `@buildanagent/protocol` function throws. Read `code` to tell the causes apart. */
|
|
2
|
+
export class ProtocolError extends Error {
|
|
3
|
+
name = "ProtocolError";
|
|
4
|
+
code;
|
|
5
|
+
rpcCode;
|
|
6
|
+
requestId;
|
|
7
|
+
constructor(code, message, options) {
|
|
8
|
+
super(message, options);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.rpcCode = options?.rpcCode;
|
|
11
|
+
this.requestId = options?.requestId;
|
|
12
|
+
Object.defineProperty(this, PROTOCOL_ERROR, { value: true });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
// A symbol marker, as the SDK's error class uses, so a copy of this package from another bundle still matches.
|
|
16
|
+
const PROTOCOL_ERROR = Symbol.for("@buildanagent/protocol/ProtocolError");
|
|
17
|
+
/** True for a `ProtocolError`, including one from another copy of the package. */
|
|
18
|
+
export function isProtocolError(error) {
|
|
19
|
+
return typeof error === "object" && error !== null && error[PROTOCOL_ERROR] === true;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAsBA,sGAAsG;AACtG,MAAM,OAAO,aAAc,SAAQ,KAAK;IACpB,IAAI,GAAW,eAAe,CAAC;IACxC,IAAI,CAAoB;IACxB,OAAO,CAAqB;IAC5B,SAAS,CAAqC;IAEvD,YAAY,IAAuB,EAAE,OAAe,EAAE,OAA8B;QAClF,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,EAAE,OAAO,CAAC;QAChC,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,SAAS,CAAC;QACpC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,cAAc,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC/D,CAAC;CACF;AAED,+GAA+G;AAC/G,MAAM,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;AAE1E,kFAAkF;AAClF,MAAM,UAAU,eAAe,CAAC,KAAc;IAC5C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,cAAc,CAAC,KAAK,IAAI,CAAC;AACpH,CAAC","sourcesContent":["/**\n * Why something was refused. `invalid_entry`: a session entry's `type` or base fields are wrong. `unsupported_format_version`:\n * an entry is from a format this reader lacks. `invalid_json`: a line is not valid UTF-8 JSON. `invalid_request`: a\n * JSON value is not a JSON-RPC 2.0 message. `line_too_long`: a line went over the framer's bound. `unterminated_line`:\n * the stream ended in the middle of a line.\n */\nexport type ProtocolErrorCode =\n | \"invalid_entry\"\n | \"unsupported_format_version\"\n | \"invalid_json\"\n | \"invalid_request\"\n | \"line_too_long\"\n | \"unterminated_line\";\n\n/** What a `ProtocolError` carries when it is also a JSON-RPC error a peer can be answered with. */\nexport interface ProtocolErrorOptions extends ErrorOptions {\n /** The JSON-RPC error code to reply with, such as -32600 for an invalid request. */\n readonly rpcCode?: number;\n /** The id of the message that failed, when it could be read, or `null` when it could not. */\n readonly requestId?: number | string | null;\n}\n\n/** The error every `@buildanagent/protocol` function throws. Read `code` to tell the causes apart. */\nexport class ProtocolError extends Error {\n override readonly name: string = \"ProtocolError\";\n readonly code: ProtocolErrorCode;\n readonly rpcCode: number | undefined;\n readonly requestId: number | string | null | undefined;\n\n constructor(code: ProtocolErrorCode, message: string, options?: ProtocolErrorOptions) {\n super(message, options);\n this.code = code;\n this.rpcCode = options?.rpcCode;\n this.requestId = options?.requestId;\n Object.defineProperty(this, PROTOCOL_ERROR, { value: true });\n }\n}\n\n// A symbol marker, as the SDK's error class uses, so a copy of this package from another bundle still matches.\nconst PROTOCOL_ERROR = Symbol.for(\"@buildanagent/protocol/ProtocolError\");\n\n/** True for a `ProtocolError`, including one from another copy of the package. */\nexport function isProtocolError(error: unknown): error is ProtocolError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[PROTOCOL_ERROR] === true;\n}\n"]}
|
package/dist/framer.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
/** The default bound on one line, in bytes. */
|
|
8
|
+
export declare const DEFAULT_MAX_LINE_BYTES: number;
|
|
9
|
+
/** One line of the stream: its parsed JSON, or why it could not be read. A bad line never ends the stream. */
|
|
10
|
+
export type FramedMessage = {
|
|
11
|
+
ok: true;
|
|
12
|
+
value: unknown;
|
|
13
|
+
} | {
|
|
14
|
+
ok: false;
|
|
15
|
+
error: ProtocolError;
|
|
16
|
+
};
|
|
17
|
+
/** The options of `JsonlFramer`. */
|
|
18
|
+
export interface JsonlFramerOptions {
|
|
19
|
+
/** The most bytes one line may hold, newline excluded. A longer line is skipped and reported once. Default 8 MiB. */
|
|
20
|
+
readonly maxLineBytes?: number;
|
|
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 declare class JsonlFramer {
|
|
29
|
+
#private;
|
|
30
|
+
constructor(options?: JsonlFramerOptions);
|
|
31
|
+
/** Takes the next chunk of the stream and returns a result for each line it finished, in order. */
|
|
32
|
+
push(chunk: Uint8Array): FramedMessage[];
|
|
33
|
+
/** Ends the stream. An unfinished last line comes back as an error, because its writer may have died mid-message. */
|
|
34
|
+
end(): FramedMessage[];
|
|
35
|
+
}
|