@nylorun/core 0.11.0-beta → 0.13.0-beta

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,78 @@
1
+ /**
2
+ * The Harness API's channel: requests and answers both ways, and one-way messages, over a
3
+ * `Port` that carries frames. `memoryPorts` joins two ports in one process: by reference, or
4
+ * through JSON with every frame validated (`json: true`, what a socket will carry).
5
+ *
6
+ * Frames: `{t:"req",id,m,p}`, `{t:"res",id,ok,r|e:{code,message}}`, `{t:"msg",m,p}`,
7
+ * `{t:"abort",id}` (the requester gave up), `{t:"ping"}`.
8
+ */
9
+ import type { CoreMethod, HarnessErrorCode, HarnessMethod, ParamsOf, ResultOf } from "./messages.js";
10
+ export type Frame = {
11
+ readonly t: "req";
12
+ readonly id: number;
13
+ readonly m: string;
14
+ readonly p: unknown;
15
+ } | {
16
+ readonly t: "res";
17
+ readonly id: number;
18
+ readonly ok: true;
19
+ readonly r: unknown;
20
+ } | {
21
+ readonly t: "res";
22
+ readonly id: number;
23
+ readonly ok: false;
24
+ readonly e: {
25
+ readonly code: HarnessErrorCode;
26
+ readonly message: string;
27
+ };
28
+ } | {
29
+ readonly t: "msg";
30
+ readonly m: string;
31
+ readonly p: unknown;
32
+ } | {
33
+ readonly t: "abort";
34
+ readonly id: number;
35
+ } | {
36
+ readonly t: "ping";
37
+ };
38
+ /** One end of a connection. */
39
+ export interface Port {
40
+ send(frame: Frame): void;
41
+ onFrame(listener: (frame: Frame) => void): void;
42
+ onClose(listener: (reason: string) => void): void;
43
+ close(reason?: string): void;
44
+ }
45
+ export type RequestHandler = (method: string, params: unknown, signal: AbortSignal) => Promise<unknown>;
46
+ export type MessageListener = (method: string, params: unknown) => void;
47
+ export interface HarnessChannel {
48
+ /** A request to the other side: a harness asks core (`HarnessMethod`), core asks a harness (`CoreMethod`). */
49
+ request<M extends HarnessMethod | CoreMethod>(method: M, params: ParamsOf<M>, signal?: AbortSignal): Promise<ResultOf<M>>;
50
+ /** A one-way message. Dropped once the channel is closed. */
51
+ notify(method: string, params: unknown): void;
52
+ /** Answers the other side's requests. One handler per channel. */
53
+ handle(handler: RequestHandler): void;
54
+ listen(listener: MessageListener): void;
55
+ onClose(listener: (reason: string) => void): void;
56
+ close(reason?: string): void;
57
+ readonly closed: boolean;
58
+ }
59
+ /** Wraps a port. With `validate`, every request, answer and message is checked against its schema. */
60
+ export declare function createChannel(port: Port, options?: {
61
+ validate?: boolean;
62
+ }): HarnessChannel;
63
+ export interface MemoryPortsOptions {
64
+ /** Serialize every frame through JSON and validate it, as a socket would. */
65
+ json?: boolean;
66
+ /** Sees each frame as it crosses, with its size in JSON mode. For tests and benchmarks. */
67
+ tap?(frame: Frame, from: "harness" | "core", bytes?: number): void;
68
+ }
69
+ /** Two joined ports in one process: `harness` and `core`. Frames arrive in order, asynchronously. */
70
+ export declare function memoryPorts(options?: MemoryPortsOptions): {
71
+ harness: Port;
72
+ core: Port;
73
+ };
74
+ /** `memoryPorts` wrapped in channels; JSON mode validates on both ends. */
75
+ export declare function memoryChannels(options?: MemoryPortsOptions): {
76
+ harness: HarnessChannel;
77
+ core: HarnessChannel;
78
+ };
@@ -0,0 +1,240 @@
1
+ import { HARNESS_ERROR_CODES } from "./messages.js";
2
+ import { HarnessApiError } from "./errors.js";
3
+ import { validateFrame, validateMessage, validateParams, validateResult } from "./schema.js";
4
+ /** Wraps a port. With `validate`, every request, answer and message is checked against its schema. */
5
+ export function createChannel(port, options = {}) {
6
+ const validate = options.validate === true;
7
+ let nextId = 1;
8
+ let closed = false;
9
+ let handler;
10
+ const listeners = [];
11
+ const closers = [];
12
+ const pending = new Map();
13
+ const serving = new Map();
14
+ const answer = async (id, method, params) => {
15
+ const controller = new AbortController();
16
+ serving.set(id, controller);
17
+ try {
18
+ if (!handler)
19
+ throw new HarnessApiError("invalid", `No handler for ${method}`);
20
+ if (validate)
21
+ validateParams(method, params);
22
+ const result = await handler(method, params, controller.signal);
23
+ if (validate)
24
+ validateResult(method, result);
25
+ if (!closed)
26
+ port.send({ t: "res", id, ok: true, r: result ?? {} });
27
+ }
28
+ catch (error) {
29
+ if (!closed)
30
+ port.send({ t: "res", id, ok: false, e: wireError(error) });
31
+ }
32
+ finally {
33
+ serving.delete(id);
34
+ }
35
+ };
36
+ port.onFrame((frame) => {
37
+ if (validate)
38
+ try {
39
+ validateFrame(frame);
40
+ }
41
+ catch (error) {
42
+ // A peer that sends malformed frames is not one to keep talking to.
43
+ const id = frame.t === "req" ? frame.id : undefined;
44
+ if (typeof id === "number" && !closed)
45
+ port.send({ t: "res", id, ok: false, e: wireError(error) });
46
+ else {
47
+ const reason = `invalid frame: ${error.message}`;
48
+ port.close(reason);
49
+ shut(reason);
50
+ }
51
+ return;
52
+ }
53
+ switch (frame.t) {
54
+ case "req":
55
+ void answer(frame.id, frame.m, frame.p);
56
+ return;
57
+ case "res": {
58
+ const call = pending.get(frame.id);
59
+ if (!call)
60
+ return;
61
+ pending.delete(frame.id);
62
+ if (!frame.ok)
63
+ call.reject(new HarnessApiError(frame.e.code, frame.e.message));
64
+ else {
65
+ try {
66
+ if (validate)
67
+ validateResult(call.method, frame.r);
68
+ call.resolve(frame.r);
69
+ }
70
+ catch (error) {
71
+ call.reject(error);
72
+ }
73
+ }
74
+ return;
75
+ }
76
+ case "msg":
77
+ try {
78
+ if (validate)
79
+ validateMessage(frame.m, frame.p);
80
+ }
81
+ catch {
82
+ return;
83
+ }
84
+ for (const listener of listeners)
85
+ listener(frame.m, frame.p);
86
+ return;
87
+ case "abort":
88
+ serving.get(frame.id)?.abort(new HarnessApiError("unavailable", "The requester gave up"));
89
+ return;
90
+ case "ping":
91
+ return;
92
+ }
93
+ });
94
+ const shut = (reason) => {
95
+ if (closed)
96
+ return;
97
+ closed = true;
98
+ const error = new HarnessApiError("unavailable", `The Harness API connection closed: ${reason}`);
99
+ for (const call of pending.values())
100
+ call.reject(error);
101
+ pending.clear();
102
+ for (const controller of serving.values())
103
+ controller.abort(error);
104
+ serving.clear();
105
+ for (const closer of closers)
106
+ closer(reason);
107
+ };
108
+ port.onClose(shut);
109
+ return {
110
+ get closed() {
111
+ return closed;
112
+ },
113
+ request(method, params, signal) {
114
+ if (closed)
115
+ return Promise.reject(new HarnessApiError("unavailable", "The Harness API connection is closed"));
116
+ if (signal?.aborted)
117
+ return Promise.reject(signal.reason);
118
+ if (validate)
119
+ try {
120
+ validateParams(method, params);
121
+ }
122
+ catch (error) {
123
+ return Promise.reject(error);
124
+ }
125
+ const id = nextId++;
126
+ return new Promise((resolve, reject) => {
127
+ const onAbort = () => {
128
+ if (!pending.delete(id))
129
+ return;
130
+ if (!closed)
131
+ port.send({ t: "abort", id });
132
+ reject(signal.reason);
133
+ };
134
+ pending.set(id, {
135
+ method,
136
+ resolve: (value) => {
137
+ signal?.removeEventListener("abort", onAbort);
138
+ resolve(value);
139
+ },
140
+ reject: (error) => {
141
+ signal?.removeEventListener("abort", onAbort);
142
+ reject(error);
143
+ },
144
+ });
145
+ signal?.addEventListener("abort", onAbort, { once: true });
146
+ port.send({ t: "req", id, m: method, p: params });
147
+ });
148
+ },
149
+ notify(method, params) {
150
+ if (closed)
151
+ return;
152
+ if (validate)
153
+ validateMessage(method, params);
154
+ port.send({ t: "msg", m: method, p: params });
155
+ },
156
+ handle(next) {
157
+ handler = next;
158
+ },
159
+ listen(listener) {
160
+ listeners.push(listener);
161
+ },
162
+ onClose(listener) {
163
+ if (closed)
164
+ listener("closed");
165
+ else
166
+ closers.push(listener);
167
+ },
168
+ close(reason = "closed") {
169
+ if (closed)
170
+ return;
171
+ port.close(reason);
172
+ shut(reason);
173
+ },
174
+ };
175
+ }
176
+ function wireError(error) {
177
+ if (error instanceof HarnessApiError)
178
+ return { code: error.code, message: error.message };
179
+ const code = error?.code;
180
+ return {
181
+ code: HARNESS_ERROR_CODES.includes(code) ? code : "internal",
182
+ message: error instanceof Error ? error.message : String(error),
183
+ };
184
+ }
185
+ /** Two joined ports in one process: `harness` and `core`. Frames arrive in order, asynchronously. */
186
+ export function memoryPorts(options = {}) {
187
+ const encoder = options.json ? new TextEncoder() : undefined;
188
+ const end = (from) => {
189
+ const frames = [];
190
+ const closes = [];
191
+ return { from, frames, closes, closed: false };
192
+ };
193
+ const ends = { harness: end("harness"), core: end("core") };
194
+ const port = (self, peer) => ({
195
+ send(frame) {
196
+ if (self.closed || peer.closed)
197
+ return;
198
+ let sent = frame;
199
+ let bytes;
200
+ if (encoder) {
201
+ const text = JSON.stringify(frame);
202
+ bytes = encoder.encode(text).length;
203
+ sent = JSON.parse(text);
204
+ }
205
+ options.tap?.(frame, self.from, bytes);
206
+ queueMicrotask(() => {
207
+ if (!peer.closed)
208
+ for (const listener of peer.frames)
209
+ listener(sent);
210
+ });
211
+ },
212
+ onFrame(listener) {
213
+ self.frames.push(listener);
214
+ },
215
+ onClose(listener) {
216
+ self.closes.push(listener);
217
+ },
218
+ close(reason = "closed") {
219
+ for (const side of [self, peer]) {
220
+ if (side.closed)
221
+ continue;
222
+ side.closed = true;
223
+ queueMicrotask(() => {
224
+ for (const listener of side.closes)
225
+ listener(reason);
226
+ });
227
+ }
228
+ },
229
+ });
230
+ return { harness: port(ends.harness, ends.core), core: port(ends.core, ends.harness) };
231
+ }
232
+ /** `memoryPorts` wrapped in channels; JSON mode validates on both ends. */
233
+ export function memoryChannels(options = {}) {
234
+ const ports = memoryPorts(options);
235
+ const validate = options.json === true;
236
+ return {
237
+ harness: createChannel(ports.harness, { validate }),
238
+ core: createChannel(ports.core, { validate }),
239
+ };
240
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Schemas of the Harness API's frames and payloads. A socket validates every frame it
3
+ * receives; the in-process channel does in JSON mode (tests). Engine documents (manifests,
4
+ * checkpoints, outcomes) are checked by the engine and the record, not here.
5
+ */
6
+ import { z } from "zod";
7
+ export declare const FrameSchema: z.ZodUnion<readonly [z.ZodObject<{
8
+ t: z.ZodLiteral<"req">;
9
+ id: z.ZodNumber;
10
+ m: z.ZodString;
11
+ p: z.ZodUnknown;
12
+ }, z.core.$strict>, z.ZodObject<{
13
+ t: z.ZodLiteral<"res">;
14
+ id: z.ZodNumber;
15
+ ok: z.ZodLiteral<true>;
16
+ r: z.ZodUnknown;
17
+ }, z.core.$strict>, z.ZodObject<{
18
+ t: z.ZodLiteral<"res">;
19
+ id: z.ZodNumber;
20
+ ok: z.ZodLiteral<false>;
21
+ e: z.ZodObject<{
22
+ code: z.ZodEnum<{
23
+ effect_drift: "effect_drift";
24
+ internal: "internal";
25
+ invalid: "invalid";
26
+ ownership_lost: "ownership_lost";
27
+ run_not_held: "run_not_held";
28
+ turn_cancelled: "turn_cancelled";
29
+ unavailable: "unavailable";
30
+ }>;
31
+ message: z.ZodString;
32
+ }, z.core.$strict>;
33
+ }, z.core.$strict>, z.ZodObject<{
34
+ t: z.ZodLiteral<"msg">;
35
+ m: z.ZodString;
36
+ p: z.ZodUnknown;
37
+ }, z.core.$strict>, z.ZodObject<{
38
+ t: z.ZodLiteral<"abort">;
39
+ id: z.ZodNumber;
40
+ }, z.core.$strict>, z.ZodObject<{
41
+ t: z.ZodLiteral<"ping">;
42
+ }, z.core.$strict>]>;
43
+ export declare const EffectIntentSchema: z.ZodObject<{
44
+ effectId: z.ZodString;
45
+ sessionId: z.ZodString;
46
+ turnId: z.ZodString;
47
+ agentId: z.ZodString;
48
+ manifestHash: z.ZodString;
49
+ kind: z.ZodEnum<{
50
+ agent: "agent";
51
+ delegation: "delegation";
52
+ fn: "fn";
53
+ hook: "hook";
54
+ model: "model";
55
+ tool: "tool";
56
+ verify: "verify";
57
+ }>;
58
+ agent: z.ZodOptional<z.ZodObject<{
59
+ id: z.ZodString;
60
+ path: z.ZodString;
61
+ delegationId: z.ZodOptional<z.ZodString>;
62
+ }, z.core.$strict>>;
63
+ capabilityId: z.ZodOptional<z.ZodString>;
64
+ toolName: z.ZodOptional<z.ZodString>;
65
+ hook: z.ZodOptional<z.ZodObject<{
66
+ at: z.ZodEnum<{
67
+ after: "after";
68
+ before: "before";
69
+ }>;
70
+ scope: z.ZodEnum<{
71
+ step: "step";
72
+ turn: "turn";
73
+ }>;
74
+ capabilityIds: z.ZodArray<z.ZodString>;
75
+ }, z.core.$strict>>;
76
+ path: z.ZodOptional<z.ZodString>;
77
+ key: z.ZodOptional<z.ZodString>;
78
+ iterations: z.ZodOptional<z.ZodString>;
79
+ input: z.ZodOptional<z.ZodUnknown>;
80
+ context: z.ZodRecord<z.ZodString, z.ZodUnknown>;
81
+ }, z.core.$strict>;
82
+ export declare const TurnStartSchema: z.ZodObject<{
83
+ type: z.ZodEnum<{
84
+ "approval.answer": "approval.answer";
85
+ "turn.start": "turn.start";
86
+ }>;
87
+ engine: z.ZodEnum<{
88
+ agent: "agent";
89
+ flow: "flow";
90
+ }>;
91
+ manifest: z.ZodRecord<z.ZodString, z.ZodUnknown>;
92
+ checkpoint: z.ZodRecord<z.ZodString, z.ZodUnknown>;
93
+ sessionTools: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
94
+ outcomes: z.ZodArray<z.ZodObject<{
95
+ effectId: z.ZodString;
96
+ requestHash: z.ZodString;
97
+ outcome: z.ZodObject<{
98
+ value: z.ZodUnknown;
99
+ statePatch: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
100
+ }, z.core.$strict>;
101
+ }, z.core.$strict>>;
102
+ transcript: z.ZodObject<{
103
+ cursor: z.ZodNumber;
104
+ }, z.core.$strict>;
105
+ options: z.ZodObject<{
106
+ yieldAfter: z.ZodOptional<z.ZodObject<{
107
+ steps: z.ZodOptional<z.ZodNumber>;
108
+ ms: z.ZodOptional<z.ZodNumber>;
109
+ }, z.core.$strict>>;
110
+ flowLimits: z.ZodOptional<z.ZodUnknown>;
111
+ fixtureModel: z.ZodBoolean;
112
+ holdMs: z.ZodOptional<z.ZodNumber>;
113
+ }, z.core.$strict>;
114
+ routing: z.ZodObject<{
115
+ rootManifest: z.ZodRecord<z.ZodString, z.ZodUnknown>;
116
+ pluginRoots: z.ZodRecord<z.ZodString, z.ZodString>;
117
+ mcpSnapshot: z.ZodOptional<z.ZodUnknown>;
118
+ sandbox: z.ZodOptional<z.ZodObject<{
119
+ ownerId: z.ZodString;
120
+ sandboxId: z.ZodOptional<z.ZodString>;
121
+ spec: z.ZodOptional<z.ZodUnknown>;
122
+ }, z.core.$strict>>;
123
+ }, z.core.$strict>;
124
+ }, z.core.$strict>;
125
+ export declare const TurnOutputSchema: z.ZodObject<{
126
+ runId: z.ZodString;
127
+ status: z.ZodOptional<z.ZodEnum<{
128
+ cancelled: "cancelled";
129
+ completed: "completed";
130
+ failed: "failed";
131
+ paused: "paused";
132
+ uncertain: "uncertain";
133
+ waiting: "waiting";
134
+ yielded: "yielded";
135
+ }>>;
136
+ state: z.ZodOptional<z.ZodUnknown>;
137
+ output: z.ZodOptional<z.ZodUnknown>;
138
+ pending: z.ZodOptional<z.ZodUnknown>;
139
+ error: z.ZodOptional<z.ZodUnknown>;
140
+ effectIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
141
+ cancelEffectIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
142
+ transcript: z.ZodOptional<z.ZodArray<z.ZodObject<{
143
+ keep: z.ZodNumber;
144
+ entries: z.ZodArray<z.ZodUnknown>;
145
+ length: z.ZodNumber;
146
+ }, z.core.$strict>>>;
147
+ thrown: z.ZodOptional<z.ZodObject<{
148
+ code: z.ZodOptional<z.ZodString>;
149
+ message: z.ZodString;
150
+ }, z.core.$strict>>;
151
+ }, z.core.$strict>;
152
+ export declare function validateFrame(frame: unknown): void;
153
+ export declare function validateParams(method: string, params: unknown): void;
154
+ export declare function validateResult(method: string, result: unknown): void;
155
+ export declare function validateMessage(method: string, params: unknown): void;