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.
@@ -0,0 +1,58 @@
1
+ /** What went wrong with a session. */
2
+ export declare class SdkError extends Error {
3
+ constructor(message: string);
4
+ /** A fresh error equal to this one: a cause shared by many waiters is
5
+ * thrown as its own instance in each, with the waiter's stack. */
6
+ clone(): SdkError;
7
+ }
8
+ /** No harness binary could be found or obtained (R12). */
9
+ export declare class BinaryUnavailable extends SdkError {
10
+ readonly why: string;
11
+ constructor(why: string);
12
+ }
13
+ /** The session did not start: no `init` in time, or one this SDK cannot
14
+ * speak to (R6.2). The text names what arrived. */
15
+ export declare class HandshakeError extends SdkError {
16
+ readonly why: string;
17
+ constructor(why: string);
18
+ }
19
+ /** What is known about a session that ended unexpectedly. */
20
+ export interface Diagnostics {
21
+ /** The exit code, when the session exited with one. */
22
+ readonly exitStatus: number | null;
23
+ /** The signal that ended the session, when one did. */
24
+ readonly signal: NodeJS.Signals | null;
25
+ /** The last lines (at most 200) of the session's error output. */
26
+ readonly stderrTail: readonly string[];
27
+ }
28
+ /** The session ended without being asked to. */
29
+ export declare class SessionEnded extends SdkError {
30
+ readonly diagnostics?: Diagnostics | undefined;
31
+ constructor(diagnostics?: Diagnostics | undefined);
32
+ }
33
+ /** A line from the session that is not JSON, or misses a field its type
34
+ * requires (R6.3). */
35
+ export declare class ProtocolError extends SdkError {
36
+ readonly why: string;
37
+ constructor(why: string);
38
+ }
39
+ /** The session refused a command, or the options it was started with: the
40
+ * protocol's error `code` and its `message`. */
41
+ export declare class Refused extends SdkError {
42
+ readonly code: string;
43
+ constructor(code: string, message: string);
44
+ toString(): string;
45
+ }
46
+ /** A turn is still running: one turn at a time, until its `result`. */
47
+ export declare class TurnInProgress extends SdkError {
48
+ constructor();
49
+ }
50
+ /** The program left more than 10,000 events of a turn unread; the session
51
+ * was ended rather than stop reading (R8.5.5). */
52
+ export declare class SlowConsumer extends SdkError {
53
+ constructor();
54
+ }
55
+ /** The command does not fit the session's 8 MiB line limit (R8.5.2). */
56
+ export declare class TooLarge extends SdkError {
57
+ constructor();
58
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,97 @@
1
+ // The one error type and its cases (spec slice-ar R8.6.1). Each message is
2
+ // the Rust SDK's (`sdk/rust/src/error.rs`), so a program sees one text in
3
+ // every language.
4
+ import { constants } from "node:os";
5
+ /** What went wrong with a session. */
6
+ export class SdkError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = new.target.name;
10
+ }
11
+ /** A fresh error equal to this one: a cause shared by many waiters is
12
+ * thrown as its own instance in each, with the waiter's stack. */
13
+ clone() {
14
+ const copy = Object.create(Object.getPrototypeOf(this));
15
+ Object.assign(copy, this);
16
+ Object.defineProperty(copy, "message", { value: this.message, writable: true, configurable: true });
17
+ Error.captureStackTrace(copy, SdkError.prototype.clone);
18
+ return copy;
19
+ }
20
+ }
21
+ /** No harness binary could be found or obtained (R12). */
22
+ export class BinaryUnavailable extends SdkError {
23
+ why;
24
+ constructor(why) {
25
+ super(`no harness binary: ${why}`);
26
+ this.why = why;
27
+ }
28
+ }
29
+ /** The session did not start: no `init` in time, or one this SDK cannot
30
+ * speak to (R6.2). The text names what arrived. */
31
+ export class HandshakeError extends SdkError {
32
+ why;
33
+ constructor(why) {
34
+ super(`the session did not start: ${why}`);
35
+ this.why = why;
36
+ }
37
+ }
38
+ /** The session ended without being asked to. */
39
+ export class SessionEnded extends SdkError {
40
+ diagnostics;
41
+ constructor(diagnostics) {
42
+ let text = "the session ended unexpectedly";
43
+ if (diagnostics !== undefined) {
44
+ if (diagnostics.exitStatus !== null)
45
+ text += ` (exit ${diagnostics.exitStatus})`;
46
+ if (diagnostics.signal !== null)
47
+ text += ` (signal ${constants.signals[diagnostics.signal] ?? diagnostics.signal})`;
48
+ const last = diagnostics.stderrTail[diagnostics.stderrTail.length - 1];
49
+ if (last !== undefined)
50
+ text += `: ${last}`;
51
+ }
52
+ super(text);
53
+ this.diagnostics = diagnostics;
54
+ }
55
+ }
56
+ /** A line from the session that is not JSON, or misses a field its type
57
+ * requires (R6.3). */
58
+ export class ProtocolError extends SdkError {
59
+ why;
60
+ constructor(why) {
61
+ super(`protocol error: ${why}`);
62
+ this.why = why;
63
+ }
64
+ }
65
+ /** The session refused a command, or the options it was started with: the
66
+ * protocol's error `code` and its `message`. */
67
+ export class Refused extends SdkError {
68
+ code;
69
+ constructor(code, message) {
70
+ super(`refused (${code}): ${message}`);
71
+ this.code = code;
72
+ // `message` is the session's own explanation, as the Rust SDK's field.
73
+ Object.defineProperty(this, "message", { value: message, writable: true, configurable: true, enumerable: true });
74
+ }
75
+ toString() {
76
+ return `${this.name}: refused (${this.code}): ${this.message}`;
77
+ }
78
+ }
79
+ /** A turn is still running: one turn at a time, until its `result`. */
80
+ export class TurnInProgress extends SdkError {
81
+ constructor() {
82
+ super("a turn is still running");
83
+ }
84
+ }
85
+ /** The program left more than 10,000 events of a turn unread; the session
86
+ * was ended rather than stop reading (R8.5.5). */
87
+ export class SlowConsumer extends SdkError {
88
+ constructor() {
89
+ super("the session was ended: more than 10,000 events of a turn were left unread");
90
+ }
91
+ }
92
+ /** The command does not fit the session's 8 MiB line limit (R8.5.2). */
93
+ export class TooLarge extends SdkError {
94
+ constructor() {
95
+ super("the command is over the session's 8 MiB line limit");
96
+ }
97
+ }
@@ -0,0 +1,52 @@
1
+ import { setInitTimeoutMs } from "./client.js";
2
+ import { checkArguments, debugQuoted, errorLine, resultLine } from "./tools.js";
3
+ import { type ConsumedLine, type Event, type State } from "./wire.js";
4
+ import { cacheRootFrom, locate, pinned, Release, setPins, targetFor } from "./binary/index.js";
5
+ export { VERSION } from "./version.js";
6
+ export { Client, Events, TurnStream, query, type Compaction } from "./client.js";
7
+ export { SdkError, BinaryUnavailable, HandshakeError, SessionEnded, ProtocolError, Refused, TurnInProgress, SlowConsumer, TooLarge, type Diagnostics, } from "./errors.js";
8
+ export { plain, type Options, type SystemPrompt } from "./options.js";
9
+ export type { Tool, ToolContext, ToolOutput } from "./tools.js";
10
+ export type { ApprovalDecision, ApprovalEvent, ApprovalKind, ApprovalRequest, AssistantEvent, Choice, Compacted, Cost, Decision, Denied, Disposition, Escape, Event, Info, InitEvent, Outcome, ReasoningEvent, Result, State, ToolResultEvent, ToolStatus, ToolUseEvent, Usage, UserEvent, UserKind, } from "./wire.js";
11
+ /** Test support for this package's own suites. Not part of the API: it may
12
+ * change or go in any release. */
13
+ export declare const __testing: {
14
+ /** Sets the wait for `init` (60 s by default). */
15
+ setInitTimeoutMs: typeof setInitTimeoutMs;
16
+ /** The wait for `init` the SDK starts with. */
17
+ INIT_TIMEOUT_MS: number;
18
+ /** Reads one line strictly as the session does: an event, a consumed line
19
+ * (`response`, `client_tool_call`, `client_tool_cancel`; their types are
20
+ * internal, reached as `ReturnType<typeof __testing.parseLine>`), or `null` for a
21
+ * type the SDK does not read; a known type missing a required field
22
+ * throws `ProtocolError`. */
23
+ parseLine(line: string): Event | ConsumedLine | null;
24
+ /** Reads a `get_state` response's `data` as `Client.state` does; malformed
25
+ * data throws `ProtocolError`. */
26
+ stateFrom(data: unknown): State;
27
+ /** The tool call's pieces: the arguments' check, the name quoting, the
28
+ * result lines and their limits, the depth an `input` is too deep at. */
29
+ tools: {
30
+ checkArguments: typeof checkArguments;
31
+ debugQuoted: typeof debugQuoted;
32
+ resultLine: typeof resultLine;
33
+ errorLine: typeof errorLine;
34
+ RESULT_LIMIT: number;
35
+ REASON_LIMIT: number;
36
+ INPUT_DEPTH_LIMIT: number;
37
+ };
38
+ /** The binary download and cache (R12): a `Release` with an explicit
39
+ * base, cache root and pins; `locate` (R12.1's order); `setPins` replaces
40
+ * the pins `locate` reads (no arguments restore them); the whole-download
41
+ * deadline (no argument restores 120 s); the archive reader. */
42
+ binary: {
43
+ Release: typeof Release;
44
+ locate: typeof locate;
45
+ targetFor: typeof targetFor;
46
+ cacheRootFrom: typeof cacheRootFrom;
47
+ pinned: typeof pinned;
48
+ setPins: typeof setPins;
49
+ setWholeDownloadMs: typeof import("./binary/download.js").setWholeDownloadMs;
50
+ readArchive: (gz: Uint8Array) => Promise<Buffer>;
51
+ };
52
+ };
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ // Drive a MEGA harness agent session from a TypeScript program (spec
2
+ // slice-ar R8, R11). A `Client` holds one session: `Client.start` (or
3
+ // `Client.resume`) begins it, `send` runs one turn and returns its events,
4
+ // and the other methods steer, abort, compact or inspect it while a turn's
5
+ // events are read. `query` is one prompt, one turn, then the end.
6
+ import { INIT_TIMEOUT_MS, setInitTimeoutMs } from "./client.js";
7
+ import { checkArguments, debugQuoted, errorLine, RESULT_LIMIT, resultLine } from "./tools.js";
8
+ import { decode, INPUT_DEPTH_LIMIT, REASON_LIMIT, stateFrom } from "./wire.js";
9
+ import { cacheRootFrom, locate, pinned, readArchive, Release, setPins, setWholeDownloadMs, targetFor } from "./binary/index.js";
10
+ export { VERSION } from "./version.js";
11
+ export { Client, Events, TurnStream, query } from "./client.js";
12
+ export { SdkError, BinaryUnavailable, HandshakeError, SessionEnded, ProtocolError, Refused, TurnInProgress, SlowConsumer, TooLarge, } from "./errors.js";
13
+ export { plain } from "./options.js";
14
+ /** Test support for this package's own suites. Not part of the API: it may
15
+ * change or go in any release. */
16
+ export const __testing = {
17
+ /** Sets the wait for `init` (60 s by default). */
18
+ setInitTimeoutMs,
19
+ /** The wait for `init` the SDK starts with. */
20
+ INIT_TIMEOUT_MS,
21
+ /** Reads one line strictly as the session does: an event, a consumed line
22
+ * (`response`, `client_tool_call`, `client_tool_cancel`; their types are
23
+ * internal, reached as `ReturnType<typeof __testing.parseLine>`), or `null` for a
24
+ * type the SDK does not read; a known type missing a required field
25
+ * throws `ProtocolError`. */
26
+ parseLine(line) {
27
+ return decode(line).line;
28
+ },
29
+ /** Reads a `get_state` response's `data` as `Client.state` does; malformed
30
+ * data throws `ProtocolError`. */
31
+ stateFrom(data) {
32
+ return stateFrom(data);
33
+ },
34
+ /** The tool call's pieces: the arguments' check, the name quoting, the
35
+ * result lines and their limits, the depth an `input` is too deep at. */
36
+ tools: { checkArguments, debugQuoted, resultLine, errorLine, RESULT_LIMIT, REASON_LIMIT, INPUT_DEPTH_LIMIT },
37
+ /** The binary download and cache (R12): a `Release` with an explicit
38
+ * base, cache root and pins; `locate` (R12.1's order); `setPins` replaces
39
+ * the pins `locate` reads (no arguments restore them); the whole-download
40
+ * deadline (no argument restores 120 s); the archive reader. */
41
+ binary: { Release, locate, targetFor, cacheRootFrom, pinned, setPins, setWholeDownloadMs, readArchive },
42
+ };
@@ -0,0 +1,48 @@
1
+ import type { Tool } from "./tools.js";
2
+ import type { ApprovalRequest, Decision } from "./wire.js";
3
+ /** The system prompt: `replace` harness's own (R2.3.1), or `append` to it (R2.3.2). */
4
+ export type SystemPrompt = {
5
+ readonly replace: string;
6
+ } | {
7
+ readonly append: string;
8
+ };
9
+ /**
10
+ * The options a session starts (or resumes) with. Every field left out takes
11
+ * R2.2's default, which switches off everything personal.
12
+ *
13
+ * `approvalTimeoutMs` is sent rounded up to whole seconds; `null` waits for
14
+ * ever ("off"); left out, harness's default (15 minutes) applies. `env` is
15
+ * added to the session's environment. `binary` names the harness to run
16
+ * (else `MEGACODE_AGENT_SDK_BINARY`); `mock` answers the model from a mock
17
+ * file, with no key and no network (R5).
18
+ */
19
+ export interface Options {
20
+ readonly model?: string;
21
+ readonly thinking?: string;
22
+ readonly mode?: "manual" | "auto" | "plan";
23
+ readonly sandbox?: "on" | "off" | "external";
24
+ readonly builtinTools?: readonly string[];
25
+ readonly systemPrompt?: SystemPrompt;
26
+ readonly projectInstructions?: boolean;
27
+ readonly userConfig?: boolean;
28
+ readonly skills?: boolean;
29
+ readonly agents?: boolean;
30
+ readonly hooks?: boolean;
31
+ readonly mcpServers?: Readonly<Record<string, unknown>>;
32
+ readonly approvalTimeoutMs?: number | null;
33
+ readonly allowEscapes?: boolean;
34
+ readonly maxIterations?: number;
35
+ readonly tools?: readonly Tool[];
36
+ readonly onApproval?: (request: ApprovalRequest) => Promise<Decision>;
37
+ readonly cwd?: string;
38
+ readonly env?: Readonly<Record<string, string>>;
39
+ readonly binary?: string;
40
+ readonly mock?: string;
41
+ }
42
+ /** An agent that is not a coding agent (R4): no built-in tools, and
43
+ * `systemPrompt` in place of harness's own. */
44
+ export declare function plain(systemPrompt: string, more?: Options): Options;
45
+ /** The options file's object. A resume sends only what R2.5.3 lets a resume
46
+ * give, and the session's tools when there are any (harness checks them
47
+ * against the log); never `mcpServers`, which harness restores from the log. */
48
+ export declare function fileJson(o: Options, resume: boolean): Record<string, unknown>;
@@ -0,0 +1,49 @@
1
+ import { definition, wholeSeconds } from "./tools.js";
2
+ /** An agent that is not a coding agent (R4): no built-in tools, and
3
+ * `systemPrompt` in place of harness's own. */
4
+ export function plain(systemPrompt, more = {}) {
5
+ return { builtinTools: [], ...more, systemPrompt: { replace: systemPrompt } };
6
+ }
7
+ /** The options file's object. A resume sends only what R2.5.3 lets a resume
8
+ * give, and the session's tools when there are any (harness checks them
9
+ * against the log); never `mcpServers`, which harness restores from the log. */
10
+ export function fileJson(o, resume) {
11
+ const m = {};
12
+ if (o.model !== undefined)
13
+ m["model"] = o.model;
14
+ if (o.thinking !== undefined)
15
+ m["thinking"] = o.thinking;
16
+ if (o.maxIterations !== undefined)
17
+ m["max_iterations"] = o.maxIterations;
18
+ if (o.approvalTimeoutMs !== undefined) {
19
+ m["approval_timeout"] = o.approvalTimeoutMs === null ? "off" : `${wholeSeconds(o.approvalTimeoutMs)}s`;
20
+ }
21
+ if (o.allowEscapes !== undefined)
22
+ m["allow_escapes"] = o.allowEscapes;
23
+ if (o.tools !== undefined && o.tools.length > 0)
24
+ m["client_tools"] = o.tools.map(definition);
25
+ if (resume)
26
+ return m;
27
+ if (o.mcpServers !== undefined && Object.keys(o.mcpServers).length > 0)
28
+ m["mcp_servers"] = { ...o.mcpServers };
29
+ if (o.mode !== undefined)
30
+ m["mode"] = o.mode;
31
+ if (o.sandbox !== undefined)
32
+ m["sandbox"] = o.sandbox;
33
+ if (o.builtinTools !== undefined)
34
+ m["builtin_tools"] = [...o.builtinTools];
35
+ if (o.systemPrompt !== undefined) {
36
+ m["system_prompt"] = "replace" in o.systemPrompt ? { replace: o.systemPrompt.replace } : { append: o.systemPrompt.append };
37
+ }
38
+ const switches = [
39
+ ["project_instructions", o.projectInstructions],
40
+ ["user_config", o.userConfig],
41
+ ["skills", o.skills],
42
+ ["agents", o.agents],
43
+ ["hooks", o.hooks],
44
+ ];
45
+ for (const [name, v] of switches)
46
+ if (v !== undefined)
47
+ m[name] = v;
48
+ return m;
49
+ }
package/dist/pins.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export declare const PINS_VERSION: string;
2
+ export declare const PINS: Readonly<Record<string, {
3
+ archiveSha256: string;
4
+ executableSha256: string;
5
+ }>>;
package/dist/pins.js ADDED
@@ -0,0 +1,22 @@
1
+ // The pinned digests of this SDK's harness release (spec slice-ar R12.5),
2
+ // written by `scripts/sdk/pin.sh` from the signed release; empty until a
3
+ // release is pinned. `scripts/sdk/package.sh` refuses to package empty or
4
+ // malformed pins.
5
+ // The harness version the pins are for; a package of another version has no pins.
6
+ export const PINS_VERSION = "0.32.0";
7
+ // target -> SHA-256 of the release archive and of the executable inside it,
8
+ // 64 lowercase hex characters each.
9
+ export const PINS = {
10
+ "x86_64-unknown-linux-musl": {
11
+ archiveSha256: "ceb8b615db2fcecad4e03225056d1b6617bb63dd523947092f90a32f3405db22",
12
+ executableSha256: "0e1fbbcd6e1f978ac5ff8b3c013b3c2a6c2d3092a204d5361a40b34b1a58bf61",
13
+ },
14
+ "aarch64-apple-darwin": {
15
+ archiveSha256: "cb03669d1ddc597c1ed55923a52e059c72efbed5ee9c2d9dfb92426d0da56fa3",
16
+ executableSha256: "3d107df15245a556903ad0491d29664887beed00ecaad122fa3a265c6b3abce9",
17
+ },
18
+ "x86_64-apple-darwin": {
19
+ archiveSha256: "1c0e607526d18496774dd464ac0e5d2a16c04de7f8e0242c08cb167ca2867a74",
20
+ executableSha256: "5e1effda774874c0d4142718cfe8a1e0542f97472d684ac49c4bc1f39e4f9d32",
21
+ },
22
+ };
@@ -0,0 +1,72 @@
1
+ import { type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { type Diagnostics } from "./errors.js";
3
+ /** The lines of stderr kept for diagnostics (R1.4). */
4
+ export declare const STDERR_TAIL = 200;
5
+ /** The options file in its own private folder (R2.1): removed, file then
6
+ * folder, at `init` or at the process's exit, whichever is first. */
7
+ export declare class OptionsFile {
8
+ readonly dir: string;
9
+ readonly file: string;
10
+ private removed;
11
+ private constructor();
12
+ /** Writes `body` to `options.json` in a new folder (mode 0700, from
13
+ * `mkdtemp`) under the temporary folder; the file is created exclusively,
14
+ * mode 0600. */
15
+ static write(body: string): OptionsFile;
16
+ /** Removes the file and its folder; later calls do nothing. */
17
+ remove(): void;
18
+ }
19
+ /** How the process ended. */
20
+ export interface Exit {
21
+ readonly code: number | null;
22
+ readonly signal: NodeJS.Signals | null;
23
+ }
24
+ /** Splits a byte stream at `\n` only (never U+2028, U+2029 or a lone `\r`),
25
+ * handing each whole line on as bytes, so a character split across chunks is
26
+ * decoded whole (Review Focus 1). A `\r` before the `\n` is dropped. */
27
+ export declare class LineSplitter {
28
+ private parts;
29
+ push(chunk: Buffer, onLine: (line: Buffer) => void): void;
30
+ /** At the stream's end: an unterminated last line is a line too. */
31
+ end(onLine: (line: Buffer) => void): void;
32
+ }
33
+ /** What to start. */
34
+ export interface Launch {
35
+ readonly binary: string;
36
+ readonly resume: string | null;
37
+ readonly mock: string | undefined;
38
+ readonly cwd: string | undefined;
39
+ readonly env: Readonly<Record<string, string>> | undefined;
40
+ readonly options: OptionsFile;
41
+ }
42
+ /** A started process: its pipes, its exit, its stderr tail. */
43
+ export declare class Proc {
44
+ readonly child: ChildProcessWithoutNullStreams;
45
+ exit: Exit | null;
46
+ readonly stderrTail: string[];
47
+ stderrDone: boolean;
48
+ private readonly exitWaiters;
49
+ private readonly stderrWaiters;
50
+ constructor(child: ChildProcessWithoutNullStreams);
51
+ get pid(): number | undefined;
52
+ /** Calls `wake` once the process was reaped (at once if it was). */
53
+ onExit(wake: () => void): void;
54
+ /** Waits until the process was reaped, at most `ms`; `true` if it was. */
55
+ waitExit(ms: number): Promise<boolean>;
56
+ waitStderr(ms: number): Promise<boolean>;
57
+ /** Signals a child not yet reaped. */
58
+ signal(sig: NodeJS.Signals): void;
59
+ /** The stop (R8.6.2), after the caller sent `quit` or closed stdin: up to
60
+ * `firstWaitMs` for the exit, then SIGTERM and up to 5 s, then SIGKILL;
61
+ * reaped. */
62
+ stop(firstWaitMs: number): Promise<void>;
63
+ /** The diagnostics of an ended process: its exit and stderr tail, each
64
+ * waited for briefly. Once the process was reaped and its stderr waited
65
+ * for, stdin and stderr are destroyed: a descendant holding them open
66
+ * never keeps Node alive. */
67
+ diagnostics(): Promise<Diagnostics>;
68
+ }
69
+ /** Starts `harness run|resume <id> [--mock <file>] --input-format
70
+ * stream-json --options <file>` (R1.1), with `env` added to this process's
71
+ * environment. */
72
+ export declare function spawn(launch: Launch): Promise<Proc>;