megacode-agent-sdk 0.0.0-stage → 0.32.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/LICENSE-APACHE +176 -0
- package/LICENSE-MIT +23 -0
- package/README.md +38 -2
- package/dist/binary/archive.d.ts +7 -0
- package/dist/binary/archive.js +215 -0
- package/dist/binary/cache.d.ts +21 -0
- package/dist/binary/cache.js +256 -0
- package/dist/binary/download.d.ts +16 -0
- package/dist/binary/download.js +174 -0
- package/dist/binary/index.d.ts +49 -0
- package/dist/binary/index.js +160 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +868 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.js +97 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +42 -0
- package/dist/options.d.ts +48 -0
- package/dist/options.js +49 -0
- package/dist/pins.d.ts +5 -0
- package/dist/pins.js +22 -0
- package/dist/process.d.ts +72 -0
- package/dist/process.js +255 -0
- package/dist/tools.d.ts +74 -0
- package/dist/tools.js +256 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/dist/wire.d.ts +241 -0
- package/dist/wire.js +620 -0
- package/package.json +33 -4
package/dist/wire.js
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
// The conversation's lines (spec slice-ar R8.5, `docs/headless.md` "A
|
|
2
|
+
// conversation", `docs/protocol/stream-json.schema.json`): the typed events a
|
|
3
|
+
// program reads, and the commands the SDK writes.
|
|
4
|
+
//
|
|
5
|
+
// Reading is lenient (R6.3): an unknown line type is skipped and an unknown
|
|
6
|
+
// field ignored; a known type missing a field it requires, or holding one of
|
|
7
|
+
// the wrong type, is a protocol error. Optional fields read as `null` when
|
|
8
|
+
// absent.
|
|
9
|
+
import { ProtocolError, TooLarge } from "./errors.js";
|
|
10
|
+
/** harness's limit on one command line, newline included (`cli/rpc.rs`'s `LINE_CAP`). */
|
|
11
|
+
export const LINE_LIMIT = 8 * 1024 * 1024;
|
|
12
|
+
/** The most bytes an approval's reason, or a tool's error message, carries (R8.5.2). */
|
|
13
|
+
export const REASON_LIMIT = 64 * 1024;
|
|
14
|
+
/** The faults one line's fields hold; the first in serde's order is
|
|
15
|
+
* reported. A muted sink keeps none (the fields under a fault). */
|
|
16
|
+
class Faults {
|
|
17
|
+
muted;
|
|
18
|
+
found = [];
|
|
19
|
+
constructor(muted = false) {
|
|
20
|
+
this.muted = muted;
|
|
21
|
+
}
|
|
22
|
+
add(at, error) {
|
|
23
|
+
if (!this.muted)
|
|
24
|
+
this.found.push({ at, seq: this.found.length, error });
|
|
25
|
+
}
|
|
26
|
+
first() {
|
|
27
|
+
let best = null;
|
|
28
|
+
for (const f of this.found)
|
|
29
|
+
if (best === null || before(f.at, f.seq, best.at, best.seq))
|
|
30
|
+
best = f;
|
|
31
|
+
return best?.error ?? null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Whether step `a` precedes `b` at one level. */
|
|
35
|
+
function stepBefore(a, b) {
|
|
36
|
+
if (typeof a === "string" && typeof b === "string") {
|
|
37
|
+
const x = Array.from(a, (c) => c.codePointAt(0));
|
|
38
|
+
const y = Array.from(b, (c) => c.codePointAt(0));
|
|
39
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
40
|
+
if (x[i] !== y[i])
|
|
41
|
+
return x[i] < y[i];
|
|
42
|
+
}
|
|
43
|
+
return x.length < y.length;
|
|
44
|
+
}
|
|
45
|
+
if (typeof a === "number" && typeof b === "number")
|
|
46
|
+
return a < b;
|
|
47
|
+
return typeof a === "string"; // a key precedes a missing field
|
|
48
|
+
}
|
|
49
|
+
function before(a, sa, b, sb) {
|
|
50
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) {
|
|
51
|
+
if (a[i] !== b[i])
|
|
52
|
+
return stepBefore(a[i], b[i]);
|
|
53
|
+
}
|
|
54
|
+
return a.length !== b.length ? a.length < b.length : sa < sb;
|
|
55
|
+
}
|
|
56
|
+
/** serde_json's `Unexpected` for a JSON value. */
|
|
57
|
+
function unexpected(v) {
|
|
58
|
+
if (v === null)
|
|
59
|
+
return "null";
|
|
60
|
+
if (typeof v === "boolean")
|
|
61
|
+
return `boolean \`${v}\``;
|
|
62
|
+
if (typeof v === "number")
|
|
63
|
+
return Number.isInteger(v) ? `integer \`${v}\`` : `floating point \`${v}\``;
|
|
64
|
+
if (typeof v === "string")
|
|
65
|
+
return `string ${JSON.stringify(v)}`;
|
|
66
|
+
if (Array.isArray(v))
|
|
67
|
+
return "sequence";
|
|
68
|
+
return "map";
|
|
69
|
+
}
|
|
70
|
+
/** What serde_json expects of each kind, as the Rust SDK reports it. */
|
|
71
|
+
const EXPECTED = {
|
|
72
|
+
str: "a string",
|
|
73
|
+
bool: "a boolean",
|
|
74
|
+
u64: "u64",
|
|
75
|
+
f64: "f64",
|
|
76
|
+
list: "a sequence",
|
|
77
|
+
map: "a map",
|
|
78
|
+
};
|
|
79
|
+
/** The fields of one object of a line of type `ty`, read as serde reads them:
|
|
80
|
+
* a field that fails is recorded and a stand-in returned, and `done` throws
|
|
81
|
+
* the fault serde meets first (fields in sorted key order, a missing one
|
|
82
|
+
* after the object's present ones). */
|
|
83
|
+
class Fields {
|
|
84
|
+
ty;
|
|
85
|
+
o;
|
|
86
|
+
faults;
|
|
87
|
+
at;
|
|
88
|
+
label;
|
|
89
|
+
constructor(ty, o, faults = new Faults(), at = [],
|
|
90
|
+
/** What a fault's text names: the line, or `get_state`'s response. */
|
|
91
|
+
label = `a \`${ty}\` line`) {
|
|
92
|
+
this.ty = ty;
|
|
93
|
+
this.o = o;
|
|
94
|
+
this.faults = faults;
|
|
95
|
+
this.at = at;
|
|
96
|
+
this.label = label;
|
|
97
|
+
}
|
|
98
|
+
/** Throws the line's first fault, if any. */
|
|
99
|
+
done() {
|
|
100
|
+
const e = this.faults.first();
|
|
101
|
+
if (e !== null)
|
|
102
|
+
throw e;
|
|
103
|
+
}
|
|
104
|
+
where(name, more = []) {
|
|
105
|
+
return [...this.at, name, ...more];
|
|
106
|
+
}
|
|
107
|
+
fault(at, why) {
|
|
108
|
+
this.faults.add(at, new ProtocolError(`${this.label}: ${why}`));
|
|
109
|
+
}
|
|
110
|
+
/** Records `why` as the fault of the present field `name`. */
|
|
111
|
+
refuse(name, why) {
|
|
112
|
+
this.fault(this.where(name), why);
|
|
113
|
+
}
|
|
114
|
+
/** serde's type error for `v`, expected as `kind`. */
|
|
115
|
+
wrong(at, v, kind) {
|
|
116
|
+
if (kind === "u64" && typeof v === "number" && Number.isInteger(v))
|
|
117
|
+
this.fault(at, `invalid value: ${unexpected(v)}, expected u64`);
|
|
118
|
+
else
|
|
119
|
+
this.fault(at, `invalid type: ${unexpected(v)}, expected ${EXPECTED[kind]}`);
|
|
120
|
+
}
|
|
121
|
+
has(name) {
|
|
122
|
+
return Object.prototype.hasOwnProperty.call(this.o, name);
|
|
123
|
+
}
|
|
124
|
+
/** The field, or `undefined` (a fault recorded) when it is missing. */
|
|
125
|
+
need(name) {
|
|
126
|
+
if (!this.has(name)) {
|
|
127
|
+
this.fault([...this.at, Infinity], `missing field \`${name}\``);
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
return this.o[name];
|
|
131
|
+
}
|
|
132
|
+
/** Whether present `v` is of `kind`; a fault is recorded when not. */
|
|
133
|
+
is(name, v, kind, ok) {
|
|
134
|
+
if (!ok && v !== undefined)
|
|
135
|
+
this.wrong(this.where(name), v, kind);
|
|
136
|
+
return ok;
|
|
137
|
+
}
|
|
138
|
+
str(name) {
|
|
139
|
+
const v = this.need(name);
|
|
140
|
+
return this.is(name, v, "str", typeof v === "string") ? v : "";
|
|
141
|
+
}
|
|
142
|
+
optStr(name) {
|
|
143
|
+
const v = this.o[name];
|
|
144
|
+
if (v === undefined || v === null)
|
|
145
|
+
return null;
|
|
146
|
+
return this.is(name, v, "str", typeof v === "string") ? v : null;
|
|
147
|
+
}
|
|
148
|
+
bool(name) {
|
|
149
|
+
const v = this.need(name);
|
|
150
|
+
return this.is(name, v, "bool", typeof v === "boolean") ? v : false;
|
|
151
|
+
}
|
|
152
|
+
boolOr(name, otherwise) {
|
|
153
|
+
const v = this.o[name];
|
|
154
|
+
if (v === undefined)
|
|
155
|
+
return otherwise;
|
|
156
|
+
return this.is(name, v, "bool", typeof v === "boolean") ? v : otherwise;
|
|
157
|
+
}
|
|
158
|
+
/** A whole number, at least 0 (serde's `u64`). */
|
|
159
|
+
count(name) {
|
|
160
|
+
const v = this.need(name);
|
|
161
|
+
return this.is(name, v, "u64", isCount(v)) ? v : 0;
|
|
162
|
+
}
|
|
163
|
+
optCount(name) {
|
|
164
|
+
const v = this.o[name];
|
|
165
|
+
if (v === undefined || v === null)
|
|
166
|
+
return null;
|
|
167
|
+
return this.is(name, v, "u64", isCount(v)) ? v : null;
|
|
168
|
+
}
|
|
169
|
+
optNumber(name) {
|
|
170
|
+
const v = this.o[name];
|
|
171
|
+
if (v === undefined || v === null)
|
|
172
|
+
return null;
|
|
173
|
+
return this.is(name, v, "f64", typeof v === "number") ? v : null;
|
|
174
|
+
}
|
|
175
|
+
/** Any JSON value; present, `null` included. */
|
|
176
|
+
value(name) {
|
|
177
|
+
return this.need(name);
|
|
178
|
+
}
|
|
179
|
+
strings(name) {
|
|
180
|
+
const v = this.need(name);
|
|
181
|
+
if (!this.is(name, v, "list", Array.isArray(v)))
|
|
182
|
+
return [];
|
|
183
|
+
const list = v;
|
|
184
|
+
list.forEach((s, i) => {
|
|
185
|
+
if (typeof s !== "string")
|
|
186
|
+
this.wrong(this.where(name, [i]), s, "str");
|
|
187
|
+
});
|
|
188
|
+
return list;
|
|
189
|
+
}
|
|
190
|
+
stringsOr(name) {
|
|
191
|
+
return this.has(name) ? this.strings(name) : [];
|
|
192
|
+
}
|
|
193
|
+
/** The object at `name`, already known to be one, read in place. */
|
|
194
|
+
sub(name, v) {
|
|
195
|
+
return new Fields(this.ty, v, this.faults, this.where(name), this.label);
|
|
196
|
+
}
|
|
197
|
+
/** Fields read under a fault: none of their own is reported. */
|
|
198
|
+
none() {
|
|
199
|
+
return new Fields(this.ty, {}, new Faults(true), [], this.label);
|
|
200
|
+
}
|
|
201
|
+
object(name) {
|
|
202
|
+
const v = this.need(name);
|
|
203
|
+
return this.is(name, v, "map", isObject(v)) ? this.sub(name, v) : this.none();
|
|
204
|
+
}
|
|
205
|
+
optObject(name) {
|
|
206
|
+
const v = this.o[name];
|
|
207
|
+
if (v === undefined || v === null)
|
|
208
|
+
return null;
|
|
209
|
+
return this.is(name, v, "map", isObject(v)) ? this.sub(name, v) : this.none();
|
|
210
|
+
}
|
|
211
|
+
objects(name) {
|
|
212
|
+
const v = this.need(name);
|
|
213
|
+
if (!this.is(name, v, "list", Array.isArray(v)))
|
|
214
|
+
return [];
|
|
215
|
+
return v.map((o, i) => {
|
|
216
|
+
if (isObject(o))
|
|
217
|
+
return new Fields(this.ty, o, this.faults, this.where(name, [i]), this.label);
|
|
218
|
+
this.wrong(this.where(name, [i]), o, "map");
|
|
219
|
+
return this.none();
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function isObject(v) {
|
|
224
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
225
|
+
}
|
|
226
|
+
function isCount(v) {
|
|
227
|
+
return typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
228
|
+
}
|
|
229
|
+
/** `init`'s data (R6.1). */
|
|
230
|
+
function infoFrom(f) {
|
|
231
|
+
return {
|
|
232
|
+
sessionId: f.str("session_id"),
|
|
233
|
+
model: f.optStr("model"),
|
|
234
|
+
mode: f.optStr("mode"),
|
|
235
|
+
cwd: f.optStr("cwd"),
|
|
236
|
+
harnessVersion: f.str("harness_version"),
|
|
237
|
+
commands: f.stringsOr("commands"),
|
|
238
|
+
resumed: f.boolOr("resumed", false),
|
|
239
|
+
clientTools: f.stringsOr("client_tools"),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
const unanswerable = () => Promise.reject(new Error("unreachable"));
|
|
243
|
+
function approvalRequest(f, responder) {
|
|
244
|
+
const escape = f.optObject("escape");
|
|
245
|
+
const request = {
|
|
246
|
+
type: "approval_request",
|
|
247
|
+
id: f.str("id"),
|
|
248
|
+
toolUseId: f.str("tool_use_id"),
|
|
249
|
+
tool: f.str("tool"),
|
|
250
|
+
kind: f.str("kind"),
|
|
251
|
+
reason: f.optStr("reason"),
|
|
252
|
+
escape: escape === null ? null : { kind: escape.str("kind"), reason: escape.str("reason") },
|
|
253
|
+
summary: f.str("summary"),
|
|
254
|
+
input: shallow(f.value("input")),
|
|
255
|
+
choices: f.strings("choices"),
|
|
256
|
+
turnGrantSkipsKind: f.bool("turn_grant_skips_kind"),
|
|
257
|
+
session: f.optStr("session"),
|
|
258
|
+
agent: f.optStr("agent"),
|
|
259
|
+
};
|
|
260
|
+
// Not enumerable: two requests compare by their fields.
|
|
261
|
+
Object.defineProperty(request, "respond", {
|
|
262
|
+
value: (decision) => responder(request.id, decision),
|
|
263
|
+
enumerable: false,
|
|
264
|
+
});
|
|
265
|
+
return request;
|
|
266
|
+
}
|
|
267
|
+
/** `result`'s fields, read in `TurnResult`'s declaration order: missing
|
|
268
|
+
* fields are reported in the order they are read. */
|
|
269
|
+
function result(f) {
|
|
270
|
+
const head = {
|
|
271
|
+
sessionId: f.str("session_id"),
|
|
272
|
+
outcome: f.optStr("outcome"),
|
|
273
|
+
isError: f.bool("is_error"),
|
|
274
|
+
result: f.optStr("result"),
|
|
275
|
+
error: f.optStr("error"),
|
|
276
|
+
model: f.optStr("model"),
|
|
277
|
+
durationMs: f.count("duration_ms"),
|
|
278
|
+
modelCalls: f.count("model_calls"),
|
|
279
|
+
};
|
|
280
|
+
const usage = f.object("usage");
|
|
281
|
+
const counts = {
|
|
282
|
+
inputTokens: usage.count("input_tokens"),
|
|
283
|
+
outputTokens: usage.count("output_tokens"),
|
|
284
|
+
cachedInputTokens: usage.optCount("cached_input_tokens"),
|
|
285
|
+
reasoningTokens: usage.count("reasoning_tokens"),
|
|
286
|
+
};
|
|
287
|
+
const denied = f.objects("denied").map((d) => ({ tool: d.str("tool"), summary: d.str("summary") }));
|
|
288
|
+
const turnId = f.optStr("turn_id");
|
|
289
|
+
const promptId = f.optStr("prompt_id");
|
|
290
|
+
const cost = f.optObject("cost");
|
|
291
|
+
return {
|
|
292
|
+
type: "result",
|
|
293
|
+
...head,
|
|
294
|
+
usage: counts,
|
|
295
|
+
denied,
|
|
296
|
+
turnId,
|
|
297
|
+
promptId,
|
|
298
|
+
cost: cost === null
|
|
299
|
+
? null
|
|
300
|
+
: {
|
|
301
|
+
usd: cost.optNumber("usd"),
|
|
302
|
+
priced: cost.count("priced"),
|
|
303
|
+
unpriced: cost.count("unpriced"),
|
|
304
|
+
free: cost.count("free"),
|
|
305
|
+
bound: cost.optStr("bound"),
|
|
306
|
+
basis: cost.optStr("basis"),
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/** A `compacted` object (a line's, or an idle `compact`'s `data.compacted`). */
|
|
311
|
+
function compactedFrom(f) {
|
|
312
|
+
return { type: "compacted", trigger: f.optStr("trigger"), preTokens: f.optCount("pre_tokens") };
|
|
313
|
+
}
|
|
314
|
+
/** `get_state`'s data, typed. */
|
|
315
|
+
export function stateFrom(data) {
|
|
316
|
+
if (!isObject(data))
|
|
317
|
+
throw new ProtocolError("a `get_state` response with no `data`");
|
|
318
|
+
const f = new Fields("get_state", data, undefined, undefined, "a `get_state` response");
|
|
319
|
+
// `State`'s declaration order: missing fields are reported in the order they are read.
|
|
320
|
+
const sessionId = f.str("session_id");
|
|
321
|
+
const model = f.optStr("model");
|
|
322
|
+
const thinking = f.optStr("thinking");
|
|
323
|
+
const mode = f.optStr("mode");
|
|
324
|
+
const away = f.bool("away");
|
|
325
|
+
const turn = turnState(f, f.value("turn"));
|
|
326
|
+
const openRequests = f.strings("open_requests");
|
|
327
|
+
const queued = f.count("queued");
|
|
328
|
+
const context = f.object("context");
|
|
329
|
+
const state = {
|
|
330
|
+
sessionId,
|
|
331
|
+
model,
|
|
332
|
+
thinking,
|
|
333
|
+
mode,
|
|
334
|
+
away,
|
|
335
|
+
turn,
|
|
336
|
+
openRequests,
|
|
337
|
+
queued,
|
|
338
|
+
context: {
|
|
339
|
+
lastPromptTokens: context.optCount("last_prompt_tokens"),
|
|
340
|
+
window: context.optCount("window"),
|
|
341
|
+
percent: context.optCount("percent"),
|
|
342
|
+
autoCompactAtPercent: context.optCount("auto_compact_at_percent"),
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
f.done();
|
|
346
|
+
return state;
|
|
347
|
+
}
|
|
348
|
+
/** `get_state.turn` as Rust's `TurnState` reads it: `"idle"`, or a running
|
|
349
|
+
* turn given as an object or a two-element list of its optional `id` and
|
|
350
|
+
* `prompt_id`; any other value is a fault at `turn` (`null` when missing,
|
|
351
|
+
* which `f` has recorded). */
|
|
352
|
+
function turnState(f, turn) {
|
|
353
|
+
if (turn === undefined || turn === "idle")
|
|
354
|
+
return null;
|
|
355
|
+
if (typeof turn === "string") {
|
|
356
|
+
f.refuse("turn", `unknown turn state ${debugQuoted(turn)}`);
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
const optional = (v) => v === undefined || v === null || typeof v === "string";
|
|
360
|
+
let pair = null;
|
|
361
|
+
if (isObject(turn))
|
|
362
|
+
pair = [turn["id"], turn["prompt_id"]];
|
|
363
|
+
else if (Array.isArray(turn) && turn.length === 2)
|
|
364
|
+
pair = turn;
|
|
365
|
+
if (pair !== null && pair.every(optional)) {
|
|
366
|
+
return { id: pair[0] ?? null, promptId: pair[1] ?? null };
|
|
367
|
+
}
|
|
368
|
+
f.refuse("turn", "data did not match any variant of untagged enum Raw");
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
/** An idle `compact`'s own compaction, from its `response.data` (Built as R8 a). */
|
|
372
|
+
export function compactedOf(data) {
|
|
373
|
+
if (!isObject(data) || !isObject(data["compacted"]))
|
|
374
|
+
return null;
|
|
375
|
+
try {
|
|
376
|
+
const f = new Fields("compacted", data["compacted"]);
|
|
377
|
+
const compacted = compactedFrom(f);
|
|
378
|
+
f.done();
|
|
379
|
+
return compacted;
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** Parses one line (without its newline). `respond` answers the
|
|
386
|
+
* `approval_request` events it yields. */
|
|
387
|
+
export function decode(text, respond = unanswerable) {
|
|
388
|
+
let value;
|
|
389
|
+
try {
|
|
390
|
+
// V8's JSON.parse is iterative: a line nested however deep parses
|
|
391
|
+
// without a RangeError, and its depth is judged afterwards.
|
|
392
|
+
value = JSON.parse(text);
|
|
393
|
+
}
|
|
394
|
+
catch (e) {
|
|
395
|
+
const why = e instanceof Error ? e.message : String(e);
|
|
396
|
+
throw new ProtocolError(`a line that is not JSON (${why}): ${snippet(Buffer.from(text, "utf8"))}`);
|
|
397
|
+
}
|
|
398
|
+
if (pastSerde(value)) {
|
|
399
|
+
throw new ProtocolError(`a line that is not JSON (recursion limit exceeded): ${snippet(Buffer.from(text, "utf8"))}`);
|
|
400
|
+
}
|
|
401
|
+
if (!isObject(value))
|
|
402
|
+
throw new ProtocolError("a line that is not a JSON object");
|
|
403
|
+
const ty = value["type"];
|
|
404
|
+
if (typeof ty !== "string")
|
|
405
|
+
throw new ProtocolError("a line with no string `type`");
|
|
406
|
+
const f = new Fields(ty, value);
|
|
407
|
+
const decoded = read(f, ty, value, respond);
|
|
408
|
+
f.done();
|
|
409
|
+
return decoded;
|
|
410
|
+
}
|
|
411
|
+
/** The line of type `ty`, its faults left in `f`. */
|
|
412
|
+
function read(f, ty, value, respond) {
|
|
413
|
+
switch (ty) {
|
|
414
|
+
case "init": {
|
|
415
|
+
const v = value["v"];
|
|
416
|
+
if (!isCount(v))
|
|
417
|
+
throw new ProtocolError("an `init` line with no `v`");
|
|
418
|
+
return { line: { type: "init", ...infoFrom(f) }, v };
|
|
419
|
+
}
|
|
420
|
+
case "user":
|
|
421
|
+
return { line: { type: "user", text: f.str("text"), kind: f.str("kind") } };
|
|
422
|
+
case "reasoning":
|
|
423
|
+
return { line: { type: "reasoning", text: f.str("text") } };
|
|
424
|
+
case "assistant":
|
|
425
|
+
return { line: { type: "assistant", text: f.str("text") } };
|
|
426
|
+
case "tool_use":
|
|
427
|
+
return { line: { type: "tool_use", id: f.str("id"), tool: f.str("tool"), input: shallow(f.value("input")) } };
|
|
428
|
+
case "tool_result":
|
|
429
|
+
return {
|
|
430
|
+
line: {
|
|
431
|
+
type: "tool_result",
|
|
432
|
+
id: f.str("id"),
|
|
433
|
+
tool: f.str("tool"),
|
|
434
|
+
status: f.str("status"),
|
|
435
|
+
output: value["output"] ?? null,
|
|
436
|
+
error: f.optStr("error"),
|
|
437
|
+
},
|
|
438
|
+
};
|
|
439
|
+
case "approval":
|
|
440
|
+
return {
|
|
441
|
+
line: {
|
|
442
|
+
type: "approval",
|
|
443
|
+
id: f.str("id"),
|
|
444
|
+
tool: f.str("tool"),
|
|
445
|
+
decision: f.str("decision"),
|
|
446
|
+
reason: f.optStr("reason"),
|
|
447
|
+
session: f.optStr("session"),
|
|
448
|
+
agent: f.optStr("agent"),
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
case "approval_request":
|
|
452
|
+
return { line: approvalRequest(f, respond) };
|
|
453
|
+
case "compacted":
|
|
454
|
+
return { line: compactedFrom(f) };
|
|
455
|
+
case "result":
|
|
456
|
+
return { line: result(f) };
|
|
457
|
+
case "client_tool_call": {
|
|
458
|
+
const id = f.str("id");
|
|
459
|
+
const name = f.str("name");
|
|
460
|
+
const input = f.value("input");
|
|
461
|
+
if (nestedAtLeast(input, INPUT_DEPTH_LIMIT))
|
|
462
|
+
return { line: { type: "client_tool_call", id, name, input: null, tooDeep: true } };
|
|
463
|
+
return { line: { type: "client_tool_call", id, name, input } };
|
|
464
|
+
}
|
|
465
|
+
case "client_tool_cancel":
|
|
466
|
+
return { line: { type: "client_tool_cancel", id: f.str("id") } };
|
|
467
|
+
case "response": {
|
|
468
|
+
const error = f.optObject("error");
|
|
469
|
+
const id = value["id"];
|
|
470
|
+
return {
|
|
471
|
+
line: {
|
|
472
|
+
type: "response",
|
|
473
|
+
id: typeof id === "string" ? id : null,
|
|
474
|
+
command: f.str("command"),
|
|
475
|
+
ok: f.bool("ok"),
|
|
476
|
+
disposition: f.optStr("disposition"),
|
|
477
|
+
data: value["data"] ?? null,
|
|
478
|
+
error: error === null ? null : { code: error.str("code"), message: error.str("message") },
|
|
479
|
+
},
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
default:
|
|
483
|
+
return { line: null };
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
/** The shallowest `input` nesting read as too deep: serde_json reads at
|
|
487
|
+
* most 127 levels in a line, and the line's own object is one of them, so
|
|
488
|
+
* the Rust SDK reads such an `input` as `null` (Built as R8 g). */
|
|
489
|
+
export const INPUT_DEPTH_LIMIT = 127;
|
|
490
|
+
/** Whether the Rust SDK refuses the line `value` was read from as not
|
|
491
|
+
* JSON: nested 128 deep or more (serde_json's limit) once its top-level
|
|
492
|
+
* `input`, which it skips, is left out. */
|
|
493
|
+
function pastSerde(value) {
|
|
494
|
+
if (!isObject(value))
|
|
495
|
+
return nestedAtLeast(value, INPUT_DEPTH_LIMIT + 1);
|
|
496
|
+
return Object.entries(value).some(([k, v]) => k !== "input" && nestedAtLeast(v, INPUT_DEPTH_LIMIT));
|
|
497
|
+
}
|
|
498
|
+
/** `input`, or `null` when it is nested `INPUT_DEPTH_LIMIT` deep. */
|
|
499
|
+
function shallow(input) {
|
|
500
|
+
return nestedAtLeast(input, INPUT_DEPTH_LIMIT) ? null : input;
|
|
501
|
+
}
|
|
502
|
+
/** Whether `value` holds containers nested `limit` deep (a container
|
|
503
|
+
* alone is one level). Walks with its own stack, so no depth overflows it. */
|
|
504
|
+
export function nestedAtLeast(value, limit) {
|
|
505
|
+
const stack = [[value, 0]];
|
|
506
|
+
while (stack.length > 0) {
|
|
507
|
+
const [v, above] = stack.pop();
|
|
508
|
+
if (typeof v !== "object" || v === null)
|
|
509
|
+
continue;
|
|
510
|
+
const depth = above + 1;
|
|
511
|
+
if (depth >= limit)
|
|
512
|
+
return true;
|
|
513
|
+
for (const child of Array.isArray(v) ? v : Object.values(v)) {
|
|
514
|
+
if (typeof child === "object" && child !== null)
|
|
515
|
+
stack.push([child, depth]);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
/** A line's first 200 bytes as a diagnostic shows them, a character cut
|
|
521
|
+
* at the end replaced (Rust's `from_utf8_lossy`). */
|
|
522
|
+
export function snippet(line) {
|
|
523
|
+
return Buffer.from(line.buffer, line.byteOffset, line.byteLength).subarray(0, 200).toString("utf8");
|
|
524
|
+
}
|
|
525
|
+
const UNPAIRED = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
|
|
526
|
+
/** `text` with each unpaired surrogate replaced by U+FFFD: harness's JSON
|
|
527
|
+
* parser refuses one, escaped or not, before it reads the line's `id`. */
|
|
528
|
+
export function wellFormed(text) {
|
|
529
|
+
return text.replace(UNPAIRED, "\ufffd");
|
|
530
|
+
}
|
|
531
|
+
const HAS_UNPAIRED = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
|
|
532
|
+
/** `value` as JSON text, every string in it well-formed, keys included. An
|
|
533
|
+
* object is copied only when a key needs mending, and one object always
|
|
534
|
+
* becomes the same copy, so `JSON.stringify` still meets a cycle as the same
|
|
535
|
+
* object and throws its `TypeError`. */
|
|
536
|
+
export function wellFormedJson(value) {
|
|
537
|
+
const copies = new Map();
|
|
538
|
+
return JSON.stringify(value, (_key, v) => {
|
|
539
|
+
if (typeof v === "string")
|
|
540
|
+
return wellFormed(v);
|
|
541
|
+
if (typeof v !== "object" || v === null || Array.isArray(v))
|
|
542
|
+
return v;
|
|
543
|
+
const made = copies.get(v);
|
|
544
|
+
if (made !== undefined)
|
|
545
|
+
return made;
|
|
546
|
+
if (!Object.keys(v).some((k) => HAS_UNPAIRED.test(k)))
|
|
547
|
+
return v;
|
|
548
|
+
const copy = Object.fromEntries(Object.entries(v).map(([k, x]) => [wellFormed(k), x]));
|
|
549
|
+
copies.set(v, copy);
|
|
550
|
+
return copy;
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
/** `value` as one UTF-8 JSON line, as `wellFormedJson` writes it. */
|
|
554
|
+
export function jsonLine(value) {
|
|
555
|
+
return Buffer.from(wellFormedJson(value) + "\n", "utf8");
|
|
556
|
+
}
|
|
557
|
+
/** A command's line, measured against harness's limit (R8.5.2): the encoded
|
|
558
|
+
* line with its newline must fit, else `TooLarge`. */
|
|
559
|
+
export function encode(command) {
|
|
560
|
+
const line = jsonLine(command);
|
|
561
|
+
if (line.length > LINE_LIMIT)
|
|
562
|
+
throw new TooLarge();
|
|
563
|
+
return line;
|
|
564
|
+
}
|
|
565
|
+
/** `text` cut to at most `limit` UTF-8 bytes, on a character boundary. */
|
|
566
|
+
export function cut(text, limit) {
|
|
567
|
+
const bytes = Buffer.from(text, "utf8");
|
|
568
|
+
if (bytes.length <= limit)
|
|
569
|
+
return text;
|
|
570
|
+
let end = limit;
|
|
571
|
+
// Back off continuation bytes (0b10xxxxxx) to the start of a character.
|
|
572
|
+
while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80)
|
|
573
|
+
end -= 1;
|
|
574
|
+
return bytes.subarray(0, end).toString("utf8");
|
|
575
|
+
}
|
|
576
|
+
// Grapheme_Extend as Rust's `char::escape_debug` reads it (Rust 1.97,
|
|
577
|
+
// Unicode 16): the Mn and Me categories less `NOT_EXTEND`, plus these.
|
|
578
|
+
const EXTEND = [
|
|
579
|
+
[0x09be, 0x09be], [0x09d7, 0x09d7], [0x0b3e, 0x0b3e], [0x0b57, 0x0b57], [0x0bbe, 0x0bbe],
|
|
580
|
+
[0x0bd7, 0x0bd7], [0x0cc0, 0x0cc0], [0x0cc2, 0x0cc2], [0x0cc7, 0x0cc8], [0x0cca, 0x0ccb],
|
|
581
|
+
[0x0cd5, 0x0cd6], [0x0d3e, 0x0d3e], [0x0d57, 0x0d57], [0x0dcf, 0x0dcf], [0x0ddf, 0x0ddf],
|
|
582
|
+
[0x1715, 0x1715], [0x1734, 0x1734], [0x1b35, 0x1b35], [0x1b3b, 0x1b3b], [0x1b3d, 0x1b3d],
|
|
583
|
+
[0x1b43, 0x1b44], [0x1baa, 0x1baa], [0x1bf2, 0x1bf3], [0x200c, 0x200c], [0x302e, 0x302f],
|
|
584
|
+
[0xa953, 0xa953], [0xa9c0, 0xa9c0], [0xff9e, 0xff9f], [0x111c0, 0x111c0], [0x11235, 0x11235],
|
|
585
|
+
[0x1133e, 0x1133e], [0x1134d, 0x1134d], [0x11357, 0x11357], [0x114b0, 0x114b0], [0x114bd, 0x114bd],
|
|
586
|
+
[0x115af, 0x115af], [0x116b6, 0x116b6], [0x11930, 0x11930], [0x1193d, 0x1193d], [0x11f41, 0x11f41],
|
|
587
|
+
[0x16ff0, 0x16ff1], [0x1d165, 0x1d166], [0x1d16d, 0x1d172], [0xe0020, 0xe007f],
|
|
588
|
+
];
|
|
589
|
+
const NOT_EXTEND = new Set([0x1171e]);
|
|
590
|
+
const ESCAPES = {
|
|
591
|
+
"\0": "\\0", "\t": "\\t", "\r": "\\r", "\n": "\\n", "\\": "\\\\", '"': '\\"',
|
|
592
|
+
};
|
|
593
|
+
const MARK = /^[\p{Mn}\p{Me}]$/u;
|
|
594
|
+
/** The categories Python's `isprintable` (and Rust's `is_printable`)
|
|
595
|
+
* exclude: Other and Separator, the ASCII space aside. */
|
|
596
|
+
const UNPRINTABLE = /^[\p{C}\p{Z}]$/u;
|
|
597
|
+
function graphemeExtend(c, n) {
|
|
598
|
+
if (MARK.test(c))
|
|
599
|
+
return !NOT_EXTEND.has(n);
|
|
600
|
+
return EXTEND.some(([lo, hi]) => lo <= n && n <= hi);
|
|
601
|
+
}
|
|
602
|
+
/** `text` quoted as Rust's `{:?}` prints a `str`, so a name reads the same
|
|
603
|
+
* from every SDK: `\0 \t \r \n \\ \"` escaped, a grapheme-extending or
|
|
604
|
+
* non-printable character as `\u{hex}`, anything else as it is. It agrees
|
|
605
|
+
* with Rust 1.97 on every character this runtime's Unicode data assigns; one
|
|
606
|
+
* assigned only in a later Unicode is escaped here, printed there. */
|
|
607
|
+
export function debugQuoted(text) {
|
|
608
|
+
let out = '"';
|
|
609
|
+
for (const c of text) {
|
|
610
|
+
const n = c.codePointAt(0);
|
|
611
|
+
const esc = ESCAPES[c];
|
|
612
|
+
if (esc !== undefined)
|
|
613
|
+
out += esc;
|
|
614
|
+
else if (c !== " " && (graphemeExtend(c, n) || UNPRINTABLE.test(c)))
|
|
615
|
+
out += `\\u{${n.toString(16)}}`;
|
|
616
|
+
else
|
|
617
|
+
out += c;
|
|
618
|
+
}
|
|
619
|
+
return out + '"';
|
|
620
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "megacode-agent-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.32.0",
|
|
4
|
+
"description": "Build agents on harness's loop from TypeScript: start a verified harness binary and drive it over its conversation protocol.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist/**/*.js",
|
|
16
|
+
"dist/**/*.d.ts",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE-MIT",
|
|
19
|
+
"LICENSE-APACHE"
|
|
20
|
+
],
|
|
21
|
+
"homepage": "https://megacode-harness.vercel.app/docs/sdk.html",
|
|
22
|
+
"repository": "https://megacode-harness.vercel.app/docs/",
|
|
23
|
+
"private": false,
|
|
24
|
+
"license": "MIT OR Apache-2.0",
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=20"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -p tsconfig.json"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "20.19.43",
|
|
33
|
+
"typescript": "6.0.3"
|
|
34
|
+
}
|
|
35
|
+
}
|