reviewer-protocol 0.0.1 → 1.0.0-beta.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/src/events.ts ADDED
@@ -0,0 +1,117 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * The protocol's major version. Optional fields and failure kinds are added without raising
5
+ * it: every schema here ignores unknown fields and reads an unknown failure kind as `unknown`,
6
+ * so an older host keeps accepting a newer reviewer.
7
+ */
8
+ export const REVIEWER_PROTOCOL_VERSION = 1;
9
+
10
+ /**
11
+ * Why a turn failed, classified by the host's vocabulary: few vendors classify their own
12
+ * failures, and those that do disagree on the names. Timeouts, crashes and cancellations are
13
+ * not kinds: the host observes them itself, since no vendor reports them reliably.
14
+ */
15
+ export const FAILURE_KINDS = [
16
+ 'authentication',
17
+ 'quota',
18
+ 'rate_limit',
19
+ 'overloaded',
20
+ 'context_overflow',
21
+ 'max_output',
22
+ 'refusal',
23
+ 'model_not_found',
24
+ 'transport',
25
+ 'harness_error',
26
+ 'unknown',
27
+ ] as const;
28
+ export type FailureKind = (typeof FAILURE_KINDS)[number];
29
+
30
+ // oxlint-disable-next-line unicorn/prefer-top-level-await -- zod's `catch` supplies a fallback value; it is no promise chain.
31
+ export const failureKindSchema = z.enum(FAILURE_KINDS).catch('unknown');
32
+
33
+ export const failureSchema = z.object({
34
+ kind: failureKindSchema,
35
+ message: z.string(),
36
+ /** When the vendor says the request may be retried (epoch milliseconds). */
37
+ retryAt: z.number().int().nonnegative().optional(),
38
+ });
39
+ export type Failure = z.infer<typeof failureSchema>;
40
+
41
+ export const sessionEventSchema = z.object({
42
+ type: z.literal('session'),
43
+ /** The harness's own session id: what a later turn passes to continue this session. */
44
+ id: z.string().min(1),
45
+ harness: z.object({ name: z.string().min(1), version: z.string().optional() }).optional(),
46
+ model: z.string().optional(),
47
+ });
48
+ export type SessionEvent = z.infer<typeof sessionEventSchema>;
49
+
50
+ export const PROGRESS_KINDS = ['message', 'thought', 'tool_start', 'tool_end', 'model_call'] as const;
51
+ export type ProgressKind = (typeof PROGRESS_KINDS)[number];
52
+
53
+ export const progressEventSchema = z.object({
54
+ type: z.literal('progress'),
55
+ kind: z.enum(PROGRESS_KINDS),
56
+ text: z.string().optional(),
57
+ });
58
+ export type ProgressEvent = z.infer<typeof progressEventSchema>;
59
+
60
+ const tokenCountSchema = z.number().int().nonnegative();
61
+
62
+ /**
63
+ * Tokens spent since the previous usage event, in the host's unified meaning: `input`
64
+ * excludes cache reads and writes, `output` includes reasoning, and `reasoning` is the part
65
+ * of `output` spent on reasoning. Tokens are authoritative; `costUsd` is a reference value,
66
+ * since few harnesses report it and some estimate it.
67
+ */
68
+ export const usageEventSchema = z.object({
69
+ type: z.literal('usage'),
70
+ /** Identifies this report within its session, so a report delivered twice counts once. */
71
+ key: z.string().min(1),
72
+ model: z.string().optional(),
73
+ input: tokenCountSchema,
74
+ output: tokenCountSchema,
75
+ cacheRead: tokenCountSchema,
76
+ cacheWrite: tokenCountSchema.optional(),
77
+ reasoning: tokenCountSchema.optional(),
78
+ costUsd: z.number().nonnegative().optional(),
79
+ /**
80
+ * The model calls since the previous usage event that each upstream provider served, by the name the endpoint
81
+ * gave it: a gateway such as OpenRouter routes the same model to several providers, which may serve it differently.
82
+ * Absent when no endpoint named one.
83
+ */
84
+ servedBy: z.record(z.string().min(1), tokenCountSchema).optional(),
85
+ });
86
+ export type UsageEvent = z.infer<typeof usageEventSchema>;
87
+
88
+ export const LOG_LEVELS = ['debug', 'info', 'warn', 'error'] as const;
89
+
90
+ export const logEventSchema = z.object({
91
+ type: z.literal('log'),
92
+ level: z.enum(LOG_LEVELS),
93
+ text: z.string(),
94
+ });
95
+ export type LogEvent = z.infer<typeof logEventSchema>;
96
+
97
+ export const turnEndEventSchema = z.object({
98
+ type: z.literal('turn_end'),
99
+ status: z.enum(['completed', 'failed']),
100
+ /** The harness's own stop reason, kept for diagnosis. */
101
+ stopReason: z.string().optional(),
102
+ /** The final assistant text of the turn. */
103
+ text: z.string().optional(),
104
+ failure: failureSchema.optional(),
105
+ /** False when some of the turn's usage is known to be unreported. */
106
+ usageComplete: z.boolean(),
107
+ });
108
+ export type TurnEndEvent = z.infer<typeof turnEndEventSchema>;
109
+
110
+ export const reviewerEventSchema = z.discriminatedUnion('type', [
111
+ sessionEventSchema,
112
+ progressEventSchema,
113
+ usageEventSchema,
114
+ logEventSchema,
115
+ turnEndEventSchema,
116
+ ]);
117
+ export type ReviewerEvent = z.infer<typeof reviewerEventSchema>;
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export * from './acp.ts';
2
+ export * from './canonicalJson.ts';
3
+ export * from './events.ts';
4
+ export * from './jsonPointer.ts';
5
+ export * from './launch.ts';
6
+ export * from './manifest.ts';
7
+ export * from './mapping.ts';
8
+ export * from './pattern.ts';
9
+ export * from './template.ts';
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+
3
+ /** An RFC 6901 JSON Pointer: the empty string (the whole document) or `/`-prefixed reference tokens. */
4
+ export const jsonPointerSchema = z.string().regex(/^(?:\/(?:[^~/]|~[01])*)*$/, 'not a JSON Pointer (RFC 6901)');
5
+
6
+ /** The value the pointer names, or undefined when the document has none there. */
7
+ export function resolvePointer(document: unknown, pointer: string): unknown {
8
+ if (pointer === '') return document;
9
+ let current = document;
10
+ for (const token of pointer.slice(1).split('/')) {
11
+ const key = token.replaceAll('~1', '/').replaceAll('~0', '~');
12
+ if (Array.isArray(current)) {
13
+ if (!/^(?:0|[1-9]\d*)$/.test(key)) return undefined;
14
+ current = current[Number(key)];
15
+ } else if (current !== null && typeof current === 'object' && Object.hasOwn(current, key)) {
16
+ current = (current as Record<string, unknown>)[key];
17
+ } else {
18
+ return undefined;
19
+ }
20
+ }
21
+ return current;
22
+ }
package/src/launch.ts ADDED
@@ -0,0 +1,90 @@
1
+ import type { Manifest, ManifestRole } from './manifest.ts';
2
+ import type { TemplateValues } from './template.ts';
3
+ import { renderArgs, renderTemplate } from './template.ts';
4
+
5
+ /** Everything the host does to launch the harness: what a user is shown before trusting a manifest. */
6
+ export interface LaunchPlan {
7
+ command: string;
8
+ args: string[];
9
+ /** Text written to standard input, which is then closed. */
10
+ stdin?: string;
11
+ /** No variable is in both. */
12
+ env: { set: Record<string, string>; unset: string[] };
13
+ /** Files written before the launch. */
14
+ files: { path: string; content: string }[];
15
+ /**
16
+ * The JSON file the harness's usage is read from once the process exits. The host removes it
17
+ * before the launch: a process that writes none would otherwise report the file an earlier
18
+ * process of the session left.
19
+ */
20
+ usageFilePath?: string;
21
+ /** What a sandboxed launch lets through; present only when the launch is sandboxed. */
22
+ sandbox?: { passEnv: string[]; domains: string[] };
23
+ }
24
+
25
+ export interface LaunchOptions {
26
+ role: ManifestRole;
27
+ values: TemplateValues;
28
+ platform: 'darwin' | 'linux';
29
+ /** Whether the host runs the harness in its sandbox: the manifest's `sandbox` then applies, and the launch throws without one. */
30
+ sandboxed?: boolean;
31
+ }
32
+
33
+ /**
34
+ * Resolves the manifest's templates into the launch of one process: the one that continues
35
+ * the session `values.sessionId` when the manifest can continue sessions and the id is
36
+ * given, else the one that starts a session. An ACP harness starts one server per session
37
+ * and takes its prompts over the protocol, so its plan carries no prompt.
38
+ */
39
+ export function resolveLaunch(manifest: Manifest, options: LaunchOptions): LaunchPlan {
40
+ const { role, values, platform } = options;
41
+ const override = role === 'resolver' ? manifest.resolver : undefined;
42
+ const { transport } = manifest;
43
+ const resumes = transport.type === 'jsonl' && transport.resumeArgs !== undefined && values.sessionId !== undefined;
44
+ const baseArgs = resumes
45
+ ? (override?.resumeArgs ?? (transport.type === 'jsonl' ? transport.resumeArgs : undefined) ?? [])
46
+ : (override?.args ?? transport.args);
47
+ // The override's instruction for a variable replaces the manifest's opposite one.
48
+ const overrideSet = override?.env?.set ?? {};
49
+ const overrideUnset = override?.env?.unset ?? [];
50
+ const sandbox = options.sandboxed === true ? manifest.sandbox : undefined;
51
+ if (options.sandboxed === true && sandbox === undefined) {
52
+ throw new Error(`The manifest "${manifest.id}" declares no "sandbox", so its harness cannot run in a sandbox.`);
53
+ }
54
+ const set = {
55
+ ...Object.fromEntries(Object.entries(manifest.env?.set ?? {}).filter(([name]) => !overrideUnset.includes(name))),
56
+ ...overrideSet,
57
+ ...sandbox?.setEnv,
58
+ };
59
+ return {
60
+ command: manifest.command,
61
+ args: renderArgs([...baseArgs, ...(transport.platformArgs?.[platform] ?? [])], values),
62
+ ...(transport.type === 'jsonl' && transport.stdin !== undefined
63
+ ? { stdin: renderTemplate(transport.stdin, values) }
64
+ : {}),
65
+ env: {
66
+ set: Object.fromEntries(Object.entries(set).map(([name, value]) => [name, renderTemplate(value, values)])),
67
+ unset: [
68
+ ...new Set([
69
+ ...(manifest.env?.unset ?? []).filter((name) => !Object.hasOwn(overrideSet, name)),
70
+ ...overrideUnset,
71
+ ]),
72
+ ].filter(
73
+ (name) =>
74
+ !Object.hasOwn(sandbox?.setEnv ?? {}, name) &&
75
+ !(sandbox?.passEnv ?? []).includes(name) &&
76
+ !(sandbox?.signInEnv ?? []).includes(name)
77
+ ),
78
+ },
79
+ files: (manifest.files ?? []).map((file) => ({
80
+ path: renderTemplate(file.path, values),
81
+ content: renderTemplate(file.content, values),
82
+ })),
83
+ ...(transport.type === 'jsonl' && transport.usageFile !== undefined
84
+ ? { usageFilePath: renderTemplate(transport.usageFile.path, values) }
85
+ : {}),
86
+ ...(sandbox === undefined
87
+ ? {}
88
+ : { sandbox: { passEnv: [...(sandbox.passEnv ?? []), ...(sandbox.signInEnv ?? [])], domains: sandbox.domains } }),
89
+ };
90
+ }
@@ -0,0 +1,368 @@
1
+ import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
2
+ import type { ParseError } from 'jsonc-parser';
3
+ import { z } from 'zod';
4
+
5
+ import { canonicalJson, sha256Hex } from './canonicalJson.ts';
6
+ import { FAILURE_KINDS, LOG_LEVELS, PROGRESS_KINDS } from './events.ts';
7
+ import { jsonPointerSchema } from './jsonPointer.ts';
8
+ import { patternSchema } from './pattern.ts';
9
+ import { argTemplateSchema, templateStringSchema } from './template.ts';
10
+
11
+ /**
12
+ * The manifest schema's major version. The schema rejects unknown keys, so adding a key
13
+ * raises it; a host refuses a manifest newer than itself and asks to be updated.
14
+ */
15
+ export const MANIFEST_SCHEMA_VERSION = 1;
16
+
17
+ export const MANIFEST_ROLES = ['reviewer', 'resolver'] as const;
18
+ export type ManifestRole = (typeof MANIFEST_ROLES)[number];
19
+
20
+ const scalarSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
21
+ export type Scalar = z.infer<typeof scalarSchema>;
22
+
23
+ /**
24
+ * Where a mapped event's field comes from: a literal, or a JSON Pointer into the output line
25
+ * (`from`) or into the element `each` iterates (`fromItem`), optionally translated through
26
+ * `map` (a value `map` does not list becomes `default`, or stays itself without one). An
27
+ * absent or null value becomes `default` too.
28
+ */
29
+ export const valueSpecSchema = z.union([
30
+ scalarSchema,
31
+ z.strictObject({
32
+ from: jsonPointerSchema,
33
+ map: z.record(z.string(), scalarSchema).optional(),
34
+ default: scalarSchema.optional(),
35
+ }),
36
+ z.strictObject({
37
+ fromItem: jsonPointerSchema,
38
+ map: z.record(z.string(), scalarSchema).optional(),
39
+ default: scalarSchema.optional(),
40
+ }),
41
+ ]);
42
+ export type ValueSpec = z.infer<typeof valueSpecSchema>;
43
+
44
+ const matchSchema = z.record(jsonPointerSchema, z.union([scalarSchema, z.array(scalarSchema).min(1)]));
45
+
46
+ const usageEmitSchema = z.strictObject({
47
+ type: z.literal('usage'),
48
+ /** Defaults to the report's position among the session's reports. */
49
+ key: valueSpecSchema.optional(),
50
+ model: valueSpecSchema.optional(),
51
+ input: valueSpecSchema.optional(),
52
+ output: valueSpecSchema.optional(),
53
+ cacheRead: valueSpecSchema.optional(),
54
+ cacheWrite: valueSpecSchema.optional(),
55
+ reasoning: valueSpecSchema.optional(),
56
+ costUsd: valueSpecSchema.optional(),
57
+ });
58
+
59
+ const emitSchema = z.discriminatedUnion('type', [
60
+ z.strictObject({
61
+ type: z.literal('session'),
62
+ id: valueSpecSchema,
63
+ model: valueSpecSchema.optional(),
64
+ harnessVersion: valueSpecSchema.optional(),
65
+ }),
66
+ z.strictObject({
67
+ type: z.literal('progress'),
68
+ kind: z.enum(PROGRESS_KINDS),
69
+ text: valueSpecSchema.optional(),
70
+ /**
71
+ * Identifies what the line reports when the harness repeats it over several lines (one
72
+ * model response split across lines): a kind's key emits its event once per process.
73
+ */
74
+ key: valueSpecSchema.optional(),
75
+ }),
76
+ usageEmitSchema,
77
+ z.strictObject({
78
+ type: z.literal('log'),
79
+ level: z.enum(LOG_LEVELS),
80
+ text: valueSpecSchema,
81
+ }),
82
+ z.strictObject({
83
+ type: z.literal('turn_end'),
84
+ /** Must resolve to `completed` or `failed`. */
85
+ status: valueSpecSchema,
86
+ stopReason: valueSpecSchema.optional(),
87
+ text: valueSpecSchema.optional(),
88
+ /** The failure's text, which the failure patterns classify unless `failureKind` resolves to a kind. */
89
+ failureMessage: valueSpecSchema.optional(),
90
+ failureKind: valueSpecSchema.optional(),
91
+ usageComplete: z.boolean().optional(),
92
+ }),
93
+ ]);
94
+ export type EmitSpec = z.infer<typeof emitSchema>;
95
+
96
+ /**
97
+ * One rule of the output mapping: a line that satisfies `match` (every pointer equals its
98
+ * value, or one of its values) and does not satisfy `unless` emits one event, or with
99
+ * `each` one event per element of the array it names that satisfies `itemMatch`.
100
+ */
101
+ export const mappingRuleSchema = z
102
+ .strictObject({
103
+ match: matchSchema.optional(),
104
+ unless: matchSchema.optional(),
105
+ each: jsonPointerSchema.optional(),
106
+ itemMatch: matchSchema.optional(),
107
+ emit: emitSchema,
108
+ })
109
+ .superRefine((rule, context) => {
110
+ if (rule.each !== undefined) return;
111
+ if (rule.itemMatch !== undefined) context.addIssue({ code: 'custom', message: '"itemMatch" needs "each"' });
112
+ if (readsItem(rule.emit)) context.addIssue({ code: 'custom', message: '"fromItem" needs "each"' });
113
+ });
114
+ export type MappingRule = z.infer<typeof mappingRuleSchema>;
115
+
116
+ function readsItem(emit: EmitSpec): boolean {
117
+ return Object.values(emit).some((value) => typeof value === 'object' && value !== null && 'fromItem' in value);
118
+ }
119
+
120
+ /**
121
+ * How the harness reports token usage, so the host can bring it to the protocol's meaning
122
+ * (`input` without cache reads and writes, `output` including reasoning) as deltas.
123
+ */
124
+ export const usageSemanticsSchema = z.strictObject({
125
+ /** `cumulative`: each report is the session's running total, which the host turns into deltas. */
126
+ mode: z.enum(['delta', 'cumulative']),
127
+ inputIncludesCacheRead: z.boolean().optional(),
128
+ inputIncludesCacheWrite: z.boolean().optional(),
129
+ /** False when the harness reports reasoning tokens apart from its output tokens. */
130
+ outputIncludesReasoning: z.boolean().optional(),
131
+ });
132
+ export type UsageSemantics = z.infer<typeof usageSemanticsSchema>;
133
+
134
+ const envNameSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
135
+
136
+ const environmentSchema = z
137
+ .strictObject({
138
+ set: z.record(envNameSchema, templateStringSchema).optional(),
139
+ unset: z.array(envNameSchema).optional(),
140
+ })
141
+ .refine((env) => !(env.unset ?? []).some((name) => Object.hasOwn(env.set ?? {}, name)), {
142
+ message: '"env" both sets and unsets a variable',
143
+ });
144
+
145
+ /**
146
+ * A path the host writes, removes or reads on the manifest's word, so it lies in the scratch
147
+ * directory the host made for the harness. The host also refuses a rendered path that leaves
148
+ * that directory, which a variable's value could make it do.
149
+ */
150
+ const scratchPathSchema = templateStringSchema.refine(
151
+ (path) => /^\{\{\s*scratchDir\s*\}\}\/./.test(path) && !path.split('/').includes('..'),
152
+ { message: 'the path must start with "{{scratchDir}}/" and hold no ".." segment' }
153
+ );
154
+
155
+ /** A file the host writes before launching. */
156
+ const fileSchema = z.strictObject({ path: scratchPathSchema, content: templateStringSchema });
157
+
158
+ /** Arguments appended to a transport's `args` (and `resumeArgs`) on one operating system. */
159
+ const platformArgsSchema = z.strictObject({
160
+ darwin: z.array(argTemplateSchema).optional(),
161
+ linux: z.array(argTemplateSchema).optional(),
162
+ });
163
+
164
+ const jsonlTransportSchema = z.strictObject({
165
+ type: z.literal('jsonl'),
166
+ /** Arguments of the process that takes a session's first prompt. */
167
+ args: z.array(argTemplateSchema),
168
+ platformArgs: platformArgsSchema.optional(),
169
+ /**
170
+ * Arguments of a process that continues the session `{{sessionId}}` with another prompt.
171
+ * A harness without them cannot continue a session: the host gives each later prompt, made
172
+ * self-contained, to a new process started with `args`.
173
+ */
174
+ resumeArgs: z.array(argTemplateSchema).optional(),
175
+ /** Text written to the process's standard input, which is then closed. */
176
+ stdin: templateStringSchema.optional(),
177
+ usage: usageSemanticsSchema,
178
+ /**
179
+ * A JSON file the harness writes its usage to instead of its output: the host reads it once
180
+ * the process exits and maps it with `emit`, whose `from` pointers address the file. The
181
+ * host removes it before each launch, so that what it reads is that process's own. The
182
+ * turn's `turn_end` follows that usage event.
183
+ */
184
+ usageFile: z
185
+ .strictObject({ path: scratchPathSchema, emit: usageEmitSchema })
186
+ .refine((usageFile) => !readsItem(usageFile.emit), {
187
+ message: '"fromItem" needs "each", which a usage file has not',
188
+ })
189
+ .optional(),
190
+ /**
191
+ * The output mapping. A process that ends without a mapped `turn_end` ends its turn by its
192
+ * exit status: completed with its last message on zero, failed otherwise.
193
+ */
194
+ events: z.array(mappingRuleSchema).min(1),
195
+ });
196
+
197
+ const acpTransportSchema = z.strictObject({
198
+ type: z.literal('acp'),
199
+ /**
200
+ * Arguments that start the harness's ACP (Agent Client Protocol v1) server on stdio. The
201
+ * host selects the model and effort through the session's config options of the categories
202
+ * `model` and `thought_level`.
203
+ */
204
+ args: z.array(argTemplateSchema),
205
+ platformArgs: platformArgsSchema.optional(),
206
+ /**
207
+ * True for a harness that speaks the Reviewer Protocol extension itself
208
+ * (`_meta["reviewer-protocol/v1"]`: it receives the revision, deadline, model and effort
209
+ * there and reports usage and failures there). False for a vendor's stock ACP server, whose
210
+ * per-turn usage the host reads from the prompt response when it carries one.
211
+ */
212
+ native: z.boolean(),
213
+ });
214
+
215
+ /** A host name the harness connects to, or `*.` and a domain for every host under it. */
216
+ const domainSchema = z.string().regex(/^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/, {
217
+ message: 'must be a host name or "*." and a domain',
218
+ });
219
+
220
+ /**
221
+ * What the harness needs when the host runs it in a sandbox, which lets it read only the
222
+ * working copy and the tools on PATH, write only the working copy and its scratch, see only
223
+ * the variables the host passes, and connect only to the hosts allowed. A host refuses to
224
+ * sandbox a harness whose manifest has no `sandbox`.
225
+ */
226
+ const sandboxSchema = z.strictObject({
227
+ /** Variables passed from the user's environment as they are: the ones the harness is configured with. */
228
+ passEnv: z.array(envNameSchema).optional(),
229
+ /**
230
+ * Variables passed like `passEnv`, any one of which the harness signs in with in the sandbox,
231
+ * where its saved login is out of reach: a host leaves the harness out of a sandboxed run while
232
+ * none is set.
233
+ */
234
+ signInEnv: z.array(envNameSchema).min(1).optional(),
235
+ /** Variables set in the sandbox alone, after `env`. */
236
+ setEnv: z.record(envNameSchema, templateStringSchema).optional(),
237
+ /** The hosts the harness reaches: its model's API and its sign-in. */
238
+ domains: z.array(domainSchema).min(1),
239
+ });
240
+
241
+ /** What launching the harness as a resolver changes: it needs to edit, commit and push. */
242
+ const resolverOverrideSchema = z.strictObject({
243
+ args: z.array(argTemplateSchema).optional(),
244
+ resumeArgs: z.array(argTemplateSchema).optional(),
245
+ env: environmentSchema.optional(),
246
+ });
247
+
248
+ export const manifestSchema = z
249
+ .strictObject({
250
+ schema: z.literal(MANIFEST_SCHEMA_VERSION),
251
+ /** The harness's name within its registry namespace. */
252
+ id: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/),
253
+ /** Shown to people only: it takes no part in the manifest's hash, so rewording it changes no identity. */
254
+ display: z
255
+ .strictObject({
256
+ name: z.string().min(1),
257
+ description: z.string().optional(),
258
+ homepage: z.url().optional(),
259
+ /** Where the vendor explains the usage limits a user should set their own limits by. */
260
+ usageLimitsUrl: z.url().optional(),
261
+ })
262
+ .optional(),
263
+ /** The executable's name, resolved on PATH: the user's own installation, which the host never ships. */
264
+ command: z.string().regex(/^[A-Za-z0-9._-]+$/),
265
+ /** How to read the installed harness's version. */
266
+ version: z.strictObject({ args: z.array(z.string()), pattern: patternSchema }).optional(),
267
+ models: z
268
+ .strictObject({
269
+ default: z.string().min(1).optional(),
270
+ efforts: z.array(z.string().min(1)).optional(),
271
+ defaultEffort: z.string().min(1).optional(),
272
+ })
273
+ .optional(),
274
+ env: environmentSchema.optional(),
275
+ files: z.array(fileSchema).optional(),
276
+ transport: z.discriminatedUnion('type', [jsonlTransportSchema, acpTransportSchema]),
277
+ /**
278
+ * Classifies a failure the harness did not classify itself: each pattern is tried on the
279
+ * failure message followed by the tail of standard error, and the match that starts
280
+ * latest decides.
281
+ */
282
+ failures: z.array(z.strictObject({ pattern: patternSchema, kind: z.enum(FAILURE_KINDS) })).optional(),
283
+ resolver: resolverOverrideSchema.optional(),
284
+ sandbox: sandboxSchema.optional(),
285
+ })
286
+ .superRefine((manifest, context) => {
287
+ const { resolver, transport } = manifest;
288
+ const transportResumes = transport.type === 'jsonl' && transport.resumeArgs !== undefined;
289
+ if (resolver?.resumeArgs !== undefined && !transportResumes) {
290
+ context.addIssue({ code: 'custom', message: '"resolver.resumeArgs" needs the transport\'s "resumeArgs"' });
291
+ }
292
+ if (transportResumes && (resolver?.args === undefined) !== (resolver?.resumeArgs === undefined)) {
293
+ context.addIssue({
294
+ code: 'custom',
295
+ message:
296
+ '"resolver.args" and "resolver.resumeArgs" come together: one process of a resolver session would launch as a reviewer',
297
+ });
298
+ }
299
+ if (transport.type === 'jsonl') checkUsageDeclarations(transport, context);
300
+ const { models } = manifest;
301
+ if (
302
+ models?.defaultEffort !== undefined &&
303
+ models.efforts !== undefined &&
304
+ !models.efforts.includes(models.defaultEffort)
305
+ ) {
306
+ context.addIssue({ code: 'custom', message: '"defaultEffort" is not one of "efforts"' });
307
+ }
308
+ });
309
+ export type Manifest = z.infer<typeof manifestSchema>;
310
+
311
+ function checkUsageDeclarations(transport: z.infer<typeof jsonlTransportSchema>, context: z.RefinementCtx): void {
312
+ const usageEmits = [
313
+ ...transport.events.flatMap((rule) => (rule.emit.type === 'usage' ? [rule.emit] : [])),
314
+ ...(transport.usageFile === undefined ? [] : [transport.usageFile.emit]),
315
+ ];
316
+ if (transport.usageFile !== undefined && usageEmits.length > 1) {
317
+ context.addIssue({
318
+ code: 'custom',
319
+ message: '"usageFile" and a usage rule in "events" would report the same turn twice: declare one',
320
+ });
321
+ }
322
+ // A declaration about a count the manifest never reads would silently change nothing.
323
+ for (const [flag, declared, field] of [
324
+ ['inputIncludesCacheRead', true, 'cacheRead'],
325
+ ['inputIncludesCacheWrite', true, 'cacheWrite'],
326
+ ['outputIncludesReasoning', false, 'reasoning'],
327
+ ] as const) {
328
+ if (transport.usage[flag] !== declared) continue;
329
+ if (usageEmits.length > 0 && usageEmits.every((emit) => emit[field] !== undefined)) continue;
330
+ context.addIssue({
331
+ code: 'custom',
332
+ message: `"${flag}": ${declared} has no effect unless the manifest maps usage and every usage emit maps "${field}"`,
333
+ });
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Parses a manifest file (JSON with comments). Throws naming every problem; a manifest of a
339
+ * newer schema version is refused with advice to update the host.
340
+ */
341
+ export function parseManifest(text: string): Manifest {
342
+ const errors: ParseError[] = [];
343
+ const document: unknown = parseJsonc(text, errors, { allowTrailingComma: true });
344
+ if (errors.length > 0) {
345
+ const first = errors[0];
346
+ throw new Error(
347
+ `the manifest is not valid JSONC: ${first === undefined ? 'unknown error' : printParseErrorCode(first.error)} at offset ${first?.offset ?? 0}`
348
+ );
349
+ }
350
+ const declared = (document as { schema?: unknown } | null)?.schema;
351
+ if (typeof declared === 'number' && declared > MANIFEST_SCHEMA_VERSION) {
352
+ throw new Error(
353
+ `the manifest uses schema ${declared}, newer than this host's ${MANIFEST_SCHEMA_VERSION}: update the host`
354
+ );
355
+ }
356
+ const result = manifestSchema.safeParse(document);
357
+ if (!result.success) throw new Error(`invalid manifest:\n${z.prettifyError(result.error)}`);
358
+ return result.data;
359
+ }
360
+
361
+ /**
362
+ * The manifest's identity: SHA-256 of its validated content canonicalized by RFC 8785,
363
+ * without `display`. Formatting, comments and display wording therefore never change it.
364
+ */
365
+ export async function manifestHash(manifest: Manifest): Promise<string> {
366
+ const { display: _display, ...identity } = manifest;
367
+ return sha256Hex(canonicalJson(identity));
368
+ }