@nylorun/core 0.11.0-beta → 0.12.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,271 @@
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
+ import { ABORT_REASONS, HARNESS_API_VERSION, HARNESS_CLAIMS, HARNESS_ERROR_CODES, } from "./messages.js";
8
+ import { HarnessApiError } from "./errors.js";
9
+ import { SANDBOX_TOOL_NAMES } from "../utils/sandbox.js";
10
+ const id = z.string().min(1).max(512);
11
+ const runId = z.object({ runId: id });
12
+ const outcome = z.object({ value: z.unknown(), statePatch: z.record(z.string(), z.unknown()).optional() }).strict();
13
+ const update = z
14
+ .object({ keep: z.number().int().min(0), entries: z.array(z.unknown()), length: z.number().int().min(0) })
15
+ .strict();
16
+ export const FrameSchema = z.union([
17
+ z.object({ t: z.literal("req"), id: z.number().int().positive(), m: z.string().min(1), p: z.unknown() }).strict(),
18
+ z.object({ t: z.literal("res"), id: z.number().int().positive(), ok: z.literal(true), r: z.unknown() }).strict(),
19
+ z
20
+ .object({
21
+ t: z.literal("res"),
22
+ id: z.number().int().positive(),
23
+ ok: z.literal(false),
24
+ e: z.object({ code: z.enum(HARNESS_ERROR_CODES), message: z.string() }).strict(),
25
+ })
26
+ .strict(),
27
+ z.object({ t: z.literal("msg"), m: z.string().min(1), p: z.unknown() }).strict(),
28
+ z.object({ t: z.literal("abort"), id: z.number().int().positive() }).strict(),
29
+ z.object({ t: z.literal("ping") }).strict(),
30
+ ]);
31
+ export const EffectIntentSchema = z
32
+ .object({
33
+ effectId: id,
34
+ sessionId: id,
35
+ turnId: id,
36
+ agentId: id,
37
+ manifestHash: z.string(),
38
+ kind: z.enum(["model", "tool", "hook", "delegation", "agent", "fn", "verify"]),
39
+ agent: z.object({ id: z.string(), path: z.string(), delegationId: z.string().optional() }).strict().optional(),
40
+ capabilityId: z.string().optional(),
41
+ toolName: z.string().optional(),
42
+ hook: z
43
+ .object({
44
+ at: z.enum(["before", "after"]),
45
+ scope: z.enum(["turn", "step"]),
46
+ capabilityIds: z.array(z.string()),
47
+ })
48
+ .strict()
49
+ .optional(),
50
+ path: z.string().optional(),
51
+ key: z.string().optional(),
52
+ iterations: z.string().optional(),
53
+ input: z.unknown().optional(),
54
+ context: z.record(z.string(), z.unknown()),
55
+ })
56
+ .strict();
57
+ const workspaceRecord = z
58
+ .object({
59
+ key: z.string().min(1).max(512),
60
+ sessionId: id,
61
+ sandboxId: id.optional(),
62
+ backend: z.string(),
63
+ image: z.string(),
64
+ state: z.enum(["creating", "running", "stopped"]),
65
+ createdAt: z.string(),
66
+ updatedAt: z.string(),
67
+ })
68
+ .strict();
69
+ const workspaceCall = z
70
+ .object({
71
+ session: z
72
+ .object({ ownerId: id, sandboxId: id.optional(), activeTurnId: id.nullable() })
73
+ .strict(),
74
+ spec: z.unknown(),
75
+ tool: z.enum(SANDBOX_TOOL_NAMES),
76
+ input: z.unknown(),
77
+ })
78
+ .strict();
79
+ const workspaceBytes = z
80
+ .object({
81
+ session: workspaceCall.shape.session,
82
+ spec: z.unknown(),
83
+ bytes: z.object({ path: z.string().min(1), maxBytes: z.number().int().positive() }).strict(),
84
+ })
85
+ .strict();
86
+ const workspaceList = z
87
+ .object({
88
+ session: workspaceCall.shape.session,
89
+ spec: z.unknown(),
90
+ list: z.object({ dir: z.string().min(1), maxEntries: z.number().int().positive() }).strict(),
91
+ })
92
+ .strict();
93
+ const grant = z
94
+ .object({
95
+ runId: id,
96
+ sessionId: id,
97
+ turnId: id,
98
+ epoch: z.number().int(),
99
+ token: z.string().optional(),
100
+ tokenExpiresAt: z.string().optional(),
101
+ })
102
+ .strict();
103
+ export const TurnStartSchema = z
104
+ .object({
105
+ type: z.enum(["turn.start", "approval.answer"]),
106
+ engine: z.enum(["agent", "flow"]),
107
+ manifest: z.record(z.string(), z.unknown()),
108
+ checkpoint: z.record(z.string(), z.unknown()),
109
+ sessionTools: z.array(z.unknown()).optional(),
110
+ outcomes: z.array(z.object({ effectId: id, requestHash: z.string(), outcome }).strict()),
111
+ transcript: z.object({ cursor: z.number().int() }).strict(),
112
+ options: z
113
+ .object({
114
+ yieldAfter: z.object({ steps: z.number().optional(), ms: z.number().optional() }).strict().optional(),
115
+ flowLimits: z.unknown().optional(),
116
+ fixtureModel: z.boolean(),
117
+ holdMs: z.number().int().nonnegative().optional(),
118
+ })
119
+ .strict(),
120
+ routing: z
121
+ .object({
122
+ rootManifest: z.record(z.string(), z.unknown()),
123
+ pluginRoots: z.record(z.string(), z.string()),
124
+ mcpSnapshot: z.unknown().optional(),
125
+ sandbox: z
126
+ .object({ ownerId: id, sandboxId: id.optional(), spec: z.unknown().optional() })
127
+ .strict()
128
+ .optional(),
129
+ })
130
+ .strict(),
131
+ })
132
+ .strict();
133
+ export const TurnOutputSchema = z
134
+ .object({
135
+ runId: id,
136
+ status: z.enum(["completed", "paused", "yielded", "waiting", "uncertain", "failed", "cancelled"]).optional(),
137
+ state: z.unknown().optional(),
138
+ output: z.unknown().optional(),
139
+ pending: z.unknown().optional(),
140
+ error: z.unknown().optional(),
141
+ effectIds: z.array(z.string()).optional(),
142
+ cancelEffectIds: z.array(z.string()).optional(),
143
+ transcript: z.array(update).optional(),
144
+ thrown: z.object({ code: z.string().optional(), message: z.string() }).strict().optional(),
145
+ })
146
+ .strict();
147
+ const settled = z.object({ cursor: z.number().int().optional() }).strict();
148
+ const empty = z.object({}).strict();
149
+ const outcomeObject = z.record(z.string(), z.unknown());
150
+ const requests = {
151
+ hello: {
152
+ params: z
153
+ .object({
154
+ api: z.number().int(),
155
+ name: z.string(),
156
+ version: z.string(),
157
+ capabilities: z.object({ workspace: z.unknown().optional() }).strict(),
158
+ })
159
+ .strict(),
160
+ result: z
161
+ .object({
162
+ api: z.literal(HARNESS_API_VERSION),
163
+ tenantId: id,
164
+ sandbox: z.object({ backend: z.string().nullable() }).strict(),
165
+ renewEveryMs: z.number().int().positive(),
166
+ })
167
+ .strict(),
168
+ },
169
+ lease: {
170
+ params: z.object({ slots: z.number().int().positive().optional() }).strict(),
171
+ result: z.object({ run: grant, input: TurnStartSchema }).strict(),
172
+ },
173
+ "lease.renew": {
174
+ params: runId.strict(),
175
+ result: z.union([
176
+ z.object({ ok: z.literal(true), token: z.string().optional(), tokenExpiresAt: z.string().optional() }).strict(),
177
+ z.object({ ok: z.literal(false) }).strict(),
178
+ ]),
179
+ },
180
+ "lease.release": {
181
+ params: runId.extend({ reason: z.enum(["shutdown", "ownership.lost", "connection.lost"]) }).strict(),
182
+ result: empty,
183
+ },
184
+ "effect.intent": {
185
+ params: runId.extend({ effect: EffectIntentSchema, requestHash: z.string().regex(/^[0-9a-f]{64}$/) }).strict(),
186
+ result: z.union([
187
+ z.object({ status: z.literal("completed"), outcome }).strict(),
188
+ z.object({ status: z.enum(["pending", "uncertain"]) }).strict(),
189
+ z.object({ status: z.literal("execute"), rejoin: z.literal(true).optional() }).strict(),
190
+ ]),
191
+ },
192
+ "effect.outcome": {
193
+ params: z.union([
194
+ runId.extend({ effectId: id, value: z.unknown() }).strict(),
195
+ runId.extend({ effectId: id, error: z.string() }).strict(),
196
+ ]),
197
+ result: z.union([
198
+ z.object({ status: z.literal("completed"), outcome }).strict(),
199
+ z.object({ status: z.literal("uncertain") }).strict(),
200
+ ]),
201
+ },
202
+ "transcript.read": {
203
+ params: runId.strict(),
204
+ result: z.object({ cursor: z.number().int(), entries: z.array(z.unknown()) }).strict(),
205
+ },
206
+ event: {
207
+ params: z
208
+ .object({
209
+ runId: id.optional(),
210
+ sessionId: id,
211
+ turnId: id.nullable(),
212
+ type: z.enum(HARNESS_CLAIMS),
213
+ payload: z.unknown(),
214
+ record: workspaceRecord.optional(),
215
+ })
216
+ .strict(),
217
+ result: empty,
218
+ },
219
+ "session.mcp": {
220
+ params: runId.extend({ snapshot: z.unknown().optional(), diagnostics: z.array(z.unknown()) }).strict(),
221
+ result: z.object({ snapshot: z.unknown(), sessionTools: z.array(z.unknown()) }).strict(),
222
+ },
223
+ "turn.completed": { params: TurnOutputSchema, result: settled },
224
+ "turn.paused": { params: TurnOutputSchema, result: settled },
225
+ "turn.waiting": { params: TurnOutputSchema, result: settled },
226
+ "turn.failed": { params: TurnOutputSchema, result: settled },
227
+ checkpoint: { params: TurnOutputSchema, result: settled },
228
+ "workspace.read": { params: z.union([workspaceCall, workspaceBytes, workspaceList]), result: outcomeObject },
229
+ "workspace.write": { params: workspaceCall, result: outcomeObject },
230
+ "workspace.exec": { params: workspaceCall, result: outcomeObject },
231
+ "workspace.report": { params: empty, result: outcomeObject },
232
+ "workspace.sweep": {
233
+ params: z.object({ now: z.number().optional() }).strict(),
234
+ result: z.object({ workspaces: z.array(workspaceRecord) }).strict(),
235
+ },
236
+ "workspace.remove": {
237
+ params: z
238
+ .object({
239
+ keys: z.array(z.string().min(1)).optional(),
240
+ sandboxIds: z.array(id).optional(),
241
+ all: z.literal(true).optional(),
242
+ })
243
+ .strict(),
244
+ result: empty,
245
+ },
246
+ };
247
+ const messages = {
248
+ cancel: runId
249
+ .extend({ reason: z.enum(ABORT_REASONS), message: z.string().optional() })
250
+ .strict(),
251
+ "effect.resolved": runId.extend({ effectId: id, outcome }).strict(),
252
+ };
253
+ function check(schema, value, what) {
254
+ if (!schema)
255
+ throw new HarnessApiError("invalid", `Unknown ${what}`);
256
+ const parsed = schema.safeParse(value);
257
+ if (!parsed.success)
258
+ throw new HarnessApiError("invalid", `Invalid ${what}: ${parsed.error.issues[0]?.message ?? "malformed"}`);
259
+ }
260
+ export function validateFrame(frame) {
261
+ check(FrameSchema, frame, "frame");
262
+ }
263
+ export function validateParams(method, params) {
264
+ check(requests[method]?.params, params, `${method} request`);
265
+ }
266
+ export function validateResult(method, result) {
267
+ check(requests[method]?.result, result, `${method} answer`);
268
+ }
269
+ export function validateMessage(method, params) {
270
+ check(messages[method], params, `${method} message`);
271
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Transcript edits (blueprint P0.3): a segment's transcript changes are recorded as
3
+ * `transcript.updated` events, each an edit of the transcript before it. Shared by core, which
4
+ * records and folds them, and a harness, which computes them and keeps its cache with them.
5
+ */
6
+ /** The payload of one `transcript.updated` event. */
7
+ export interface TranscriptUpdate {
8
+ keep: number;
9
+ entries: unknown[];
10
+ length: number;
11
+ }
12
+ /** An edit's entries are split so each event stays well under S2's 1 MiB record limit. */
13
+ export declare const CHUNK_BYTES: number;
14
+ export declare class TranscriptFoldError extends Error {
15
+ constructor(message: string);
16
+ }
17
+ /** The engine state's transcript, or none. */
18
+ export declare function transcriptOf(state: unknown): unknown[];
19
+ /** `state` with `transcript` (what the engine runs on). */
20
+ export declare function withTranscript<T>(state: T, transcript: readonly unknown[]): T;
21
+ /**
22
+ * The edits from `before` to `after`, split into chunks of at most `CHUNK_BYTES` of entries.
23
+ * Empty when nothing changed.
24
+ */
25
+ export declare function transcriptUpdates(before: readonly unknown[], after: readonly unknown[], chunkBytes?: number): TranscriptUpdate[];
26
+ /** Applies one edit. Throws `TranscriptFoldError` when it does not fit the transcript. */
27
+ export declare function applyUpdate(transcript: readonly unknown[], update: TranscriptUpdate): unknown[];
28
+ /** Applies edits in order. */
29
+ export declare function applyUpdates(transcript: readonly unknown[], updates: readonly TranscriptUpdate[]): unknown[];
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Transcript edits (blueprint P0.3): a segment's transcript changes are recorded as
3
+ * `transcript.updated` events, each an edit of the transcript before it. Shared by core, which
4
+ * records and folds them, and a harness, which computes them and keeps its cache with them.
5
+ */
6
+ /** An edit's entries are split so each event stays well under S2's 1 MiB record limit. */
7
+ export const CHUNK_BYTES = 256 * 1024;
8
+ export class TranscriptFoldError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "TranscriptFoldError";
12
+ }
13
+ }
14
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
15
+ /** The engine state's transcript, or none. */
16
+ export function transcriptOf(state) {
17
+ const transcript = state?.transcript;
18
+ return Array.isArray(transcript) ? transcript : [];
19
+ }
20
+ /** `state` with `transcript` (what the engine runs on). */
21
+ export function withTranscript(state, transcript) {
22
+ if (!state)
23
+ return state;
24
+ return { ...state, transcript: [...transcript] };
25
+ }
26
+ /**
27
+ * The edits from `before` to `after`, split into chunks of at most `CHUNK_BYTES` of entries.
28
+ * Empty when nothing changed.
29
+ */
30
+ export function transcriptUpdates(before, after, chunkBytes = CHUNK_BYTES) {
31
+ let keep = 0;
32
+ while (keep < before.length && keep < after.length && same(before[keep], after[keep]))
33
+ keep += 1;
34
+ if (keep === before.length && keep === after.length)
35
+ return [];
36
+ const added = after.slice(keep);
37
+ if (added.length === 0)
38
+ return [{ keep, entries: [], length: keep }];
39
+ const updates = [];
40
+ let chunk = [];
41
+ let bytes = 0;
42
+ let base = keep;
43
+ const flush = () => {
44
+ updates.push({ keep: base, entries: chunk, length: base + chunk.length });
45
+ base += chunk.length;
46
+ chunk = [];
47
+ bytes = 0;
48
+ };
49
+ for (const entry of added) {
50
+ const size = JSON.stringify(entry).length;
51
+ if (chunk.length > 0 && bytes + size > chunkBytes)
52
+ flush();
53
+ chunk.push(entry);
54
+ bytes += size;
55
+ }
56
+ flush();
57
+ return updates;
58
+ }
59
+ /** Applies one edit. Throws `TranscriptFoldError` when it does not fit the transcript. */
60
+ export function applyUpdate(transcript, update) {
61
+ if (update.keep > transcript.length)
62
+ throw new TranscriptFoldError(`transcript.updated keeps ${update.keep} entries of ${transcript.length}`);
63
+ const next = [...transcript.slice(0, update.keep), ...update.entries];
64
+ if (next.length !== update.length)
65
+ throw new TranscriptFoldError(`transcript.updated should give ${update.length} entries, not ${next.length}`);
66
+ return next;
67
+ }
68
+ /** Applies edits in order. */
69
+ export function applyUpdates(transcript, updates) {
70
+ let next = [...transcript];
71
+ for (const update of updates)
72
+ next = applyUpdate(next, update);
73
+ return next;
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/core",
3
- "version": "0.11.0-beta",
3
+ "version": "0.12.0-beta",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Shared agent definitions and wire contracts",
@@ -35,7 +35,7 @@
35
35
  "devDependencies": {
36
36
  "@types/node": "^26.5.0",
37
37
  "typescript": "npm:@typescript/typescript6@^6.0.2",
38
- "vitest": "^5.0.1"
38
+ "vitest": "^5.0.2"
39
39
  },
40
40
  "exports": {
41
41
  ".": {
@@ -53,6 +53,10 @@
53
53
  "./compatibility": {
54
54
  "types": "./dist/compatibility.d.ts",
55
55
  "import": "./dist/compatibility.js"
56
+ },
57
+ "./harness-api": {
58
+ "types": "./dist/harness-api/index.d.ts",
59
+ "import": "./dist/harness-api/index.js"
56
60
  }
57
61
  },
58
62
  "peerDependencies": {