reviewer-protocol 0.0.1 → 1.0.0-beta.1

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,332 @@
1
+ import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
2
+ import { z } from 'zod';
3
+ import { canonicalJson, sha256Hex } from './canonicalJson.js';
4
+ import { FAILURE_KINDS, LOG_LEVELS, PROGRESS_KINDS } from './events.js';
5
+ import { jsonPointerSchema } from './jsonPointer.js';
6
+ import { patternSchema } from './pattern.js';
7
+ import { argTemplateSchema, templateStringSchema } from './template.js';
8
+ /**
9
+ * The manifest schema's major version. The schema rejects unknown keys, so adding a key
10
+ * raises it; a host refuses a manifest newer than itself and asks to be updated.
11
+ */
12
+ export const MANIFEST_SCHEMA_VERSION = 1;
13
+ export const MANIFEST_ROLES = ['reviewer', 'resolver'];
14
+ const scalarSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
15
+ /**
16
+ * Where a mapped event's field comes from: a literal, or a JSON Pointer into the output line
17
+ * (`from`) or into the element `each` iterates (`fromItem`), optionally translated through
18
+ * `map` (a value `map` does not list becomes `default`, or stays itself without one). An
19
+ * absent or null value becomes `default` too.
20
+ */
21
+ export const valueSpecSchema = z.union([
22
+ scalarSchema,
23
+ z.strictObject({
24
+ from: jsonPointerSchema,
25
+ map: z.record(z.string(), scalarSchema).optional(),
26
+ default: scalarSchema.optional(),
27
+ }),
28
+ z.strictObject({
29
+ fromItem: jsonPointerSchema,
30
+ map: z.record(z.string(), scalarSchema).optional(),
31
+ default: scalarSchema.optional(),
32
+ }),
33
+ ]);
34
+ const matchSchema = z.record(jsonPointerSchema, z.union([scalarSchema, z.array(scalarSchema).min(1)]));
35
+ const usageEmitSchema = z.strictObject({
36
+ type: z.literal('usage'),
37
+ /** Defaults to the report's position among the session's reports. */
38
+ key: valueSpecSchema.optional(),
39
+ model: valueSpecSchema.optional(),
40
+ input: valueSpecSchema.optional(),
41
+ output: valueSpecSchema.optional(),
42
+ cacheRead: valueSpecSchema.optional(),
43
+ cacheWrite: valueSpecSchema.optional(),
44
+ reasoning: valueSpecSchema.optional(),
45
+ costUsd: valueSpecSchema.optional(),
46
+ });
47
+ const emitSchema = z.discriminatedUnion('type', [
48
+ z.strictObject({
49
+ type: z.literal('session'),
50
+ id: valueSpecSchema,
51
+ model: valueSpecSchema.optional(),
52
+ harnessVersion: valueSpecSchema.optional(),
53
+ }),
54
+ z.strictObject({
55
+ type: z.literal('progress'),
56
+ kind: z.enum(PROGRESS_KINDS),
57
+ text: valueSpecSchema.optional(),
58
+ /**
59
+ * Identifies what the line reports when the harness repeats it over several lines (one
60
+ * model response split across lines): a kind's key emits its event once per process.
61
+ */
62
+ key: valueSpecSchema.optional(),
63
+ }),
64
+ usageEmitSchema,
65
+ z.strictObject({
66
+ type: z.literal('log'),
67
+ level: z.enum(LOG_LEVELS),
68
+ text: valueSpecSchema,
69
+ }),
70
+ z.strictObject({
71
+ type: z.literal('turn_end'),
72
+ /** Must resolve to `completed` or `failed`. */
73
+ status: valueSpecSchema,
74
+ stopReason: valueSpecSchema.optional(),
75
+ text: valueSpecSchema.optional(),
76
+ /** The failure's text, which the failure patterns classify unless `failureKind` resolves to a kind. */
77
+ failureMessage: valueSpecSchema.optional(),
78
+ failureKind: valueSpecSchema.optional(),
79
+ usageComplete: z.boolean().optional(),
80
+ }),
81
+ ]);
82
+ /**
83
+ * One rule of the output mapping: a line that satisfies `match` (every pointer equals its
84
+ * value, or one of its values) and does not satisfy `unless` emits one event, or with
85
+ * `each` one event per element of the array it names that satisfies `itemMatch`.
86
+ */
87
+ export const mappingRuleSchema = z
88
+ .strictObject({
89
+ match: matchSchema.optional(),
90
+ unless: matchSchema.optional(),
91
+ each: jsonPointerSchema.optional(),
92
+ itemMatch: matchSchema.optional(),
93
+ emit: emitSchema,
94
+ })
95
+ .superRefine((rule, context) => {
96
+ if (rule.each !== undefined)
97
+ return;
98
+ if (rule.itemMatch !== undefined)
99
+ context.addIssue({ code: 'custom', message: '"itemMatch" needs "each"' });
100
+ if (readsItem(rule.emit))
101
+ context.addIssue({ code: 'custom', message: '"fromItem" needs "each"' });
102
+ });
103
+ function readsItem(emit) {
104
+ return Object.values(emit).some((value) => typeof value === 'object' && value !== null && 'fromItem' in value);
105
+ }
106
+ /**
107
+ * How the harness reports token usage, so the host can bring it to the protocol's meaning
108
+ * (`input` without cache reads and writes, `output` including reasoning) as deltas.
109
+ */
110
+ export const usageSemanticsSchema = z.strictObject({
111
+ /** `cumulative`: each report is the session's running total, which the host turns into deltas. */
112
+ mode: z.enum(['delta', 'cumulative']),
113
+ inputIncludesCacheRead: z.boolean().optional(),
114
+ inputIncludesCacheWrite: z.boolean().optional(),
115
+ /** False when the harness reports reasoning tokens apart from its output tokens. */
116
+ outputIncludesReasoning: z.boolean().optional(),
117
+ });
118
+ const envNameSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
119
+ const environmentSchema = z
120
+ .strictObject({
121
+ set: z.record(envNameSchema, templateStringSchema).optional(),
122
+ unset: z.array(envNameSchema).optional(),
123
+ })
124
+ .refine((env) => !(env.unset ?? []).some((name) => Object.hasOwn(env.set ?? {}, name)), {
125
+ message: '"env" both sets and unsets a variable',
126
+ });
127
+ /**
128
+ * A path the host writes, removes or reads on the manifest's word, so it lies in the scratch
129
+ * directory the host made for the harness. The host also refuses a rendered path that leaves
130
+ * that directory, which a variable's value could make it do.
131
+ */
132
+ const scratchPathSchema = templateStringSchema.refine((path) => /^\{\{\s*scratchDir\s*\}\}\/./.test(path) && !path.split('/').includes('..'), { message: 'the path must start with "{{scratchDir}}/" and hold no ".." segment' });
133
+ /** A file the host writes before launching. */
134
+ const fileSchema = z.strictObject({ path: scratchPathSchema, content: templateStringSchema });
135
+ /** Arguments appended to a transport's `args` (and `resumeArgs`) on one operating system. */
136
+ const platformArgsSchema = z.strictObject({
137
+ darwin: z.array(argTemplateSchema).optional(),
138
+ linux: z.array(argTemplateSchema).optional(),
139
+ });
140
+ const jsonlTransportSchema = z.strictObject({
141
+ type: z.literal('jsonl'),
142
+ /** Arguments of the process that takes a session's first prompt. */
143
+ args: z.array(argTemplateSchema),
144
+ platformArgs: platformArgsSchema.optional(),
145
+ /**
146
+ * Arguments of a process that continues the session `{{sessionId}}` with another prompt.
147
+ * A harness without them cannot continue a session: the host gives each later prompt, made
148
+ * self-contained, to a new process started with `args`.
149
+ */
150
+ resumeArgs: z.array(argTemplateSchema).optional(),
151
+ /** Text written to the process's standard input, which is then closed. */
152
+ stdin: templateStringSchema.optional(),
153
+ usage: usageSemanticsSchema,
154
+ /**
155
+ * A JSON file the harness writes its usage to instead of its output: the host reads it once
156
+ * the process exits and maps it with `emit`, whose `from` pointers address the file. The
157
+ * host removes it before each launch, so that what it reads is that process's own. The
158
+ * turn's `turn_end` follows that usage event.
159
+ */
160
+ usageFile: z
161
+ .strictObject({ path: scratchPathSchema, emit: usageEmitSchema })
162
+ .refine((usageFile) => !readsItem(usageFile.emit), {
163
+ message: '"fromItem" needs "each", which a usage file has not',
164
+ })
165
+ .optional(),
166
+ /**
167
+ * The output mapping. A process that ends without a mapped `turn_end` ends its turn by its
168
+ * exit status: completed with its last message on zero, failed otherwise.
169
+ */
170
+ events: z.array(mappingRuleSchema).min(1),
171
+ });
172
+ const acpTransportSchema = z.strictObject({
173
+ type: z.literal('acp'),
174
+ /**
175
+ * Arguments that start the harness's ACP (Agent Client Protocol v1) server on stdio. The
176
+ * host selects the model and effort through the session's config options of the categories
177
+ * `model` and `thought_level`.
178
+ */
179
+ args: z.array(argTemplateSchema),
180
+ platformArgs: platformArgsSchema.optional(),
181
+ /**
182
+ * True for a harness that speaks the Reviewer Protocol extension itself
183
+ * (`_meta["reviewer-protocol/v1"]`: it receives the revision, deadline, model and effort
184
+ * there and reports usage and failures there). False for a vendor's stock ACP server, whose
185
+ * per-turn usage the host reads from the prompt response when it carries one.
186
+ */
187
+ native: z.boolean(),
188
+ });
189
+ /** A host name the harness connects to, or `*.` and a domain for every host under it. */
190
+ const domainSchema = z.string().regex(/^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/, {
191
+ message: 'must be a host name or "*." and a domain',
192
+ });
193
+ /**
194
+ * What the harness needs when the host runs it in a sandbox, which lets it read only the
195
+ * working copy and the tools on PATH, write only the working copy and its scratch, see only
196
+ * the variables the host passes, and connect only to the hosts allowed. A host refuses to
197
+ * sandbox a harness whose manifest has no `sandbox`.
198
+ */
199
+ const sandboxSchema = z.strictObject({
200
+ /** Variables passed from the user's environment as they are: the ones the harness is configured with. */
201
+ passEnv: z.array(envNameSchema).optional(),
202
+ /**
203
+ * Variables passed like `passEnv`, any one of which the harness signs in with in the sandbox,
204
+ * where its saved login is out of reach: a host leaves the harness out of a sandboxed run while
205
+ * none is set.
206
+ */
207
+ signInEnv: z.array(envNameSchema).min(1).optional(),
208
+ /** Variables set in the sandbox alone, after `env`. */
209
+ setEnv: z.record(envNameSchema, templateStringSchema).optional(),
210
+ /** The hosts the harness reaches: its model's API and its sign-in. */
211
+ domains: z.array(domainSchema).min(1),
212
+ });
213
+ /** What launching the harness as a resolver changes: it needs to edit, commit and push. */
214
+ const resolverOverrideSchema = z.strictObject({
215
+ args: z.array(argTemplateSchema).optional(),
216
+ resumeArgs: z.array(argTemplateSchema).optional(),
217
+ env: environmentSchema.optional(),
218
+ });
219
+ export const manifestSchema = z
220
+ .strictObject({
221
+ schema: z.literal(MANIFEST_SCHEMA_VERSION),
222
+ /** The harness's name within its registry namespace. */
223
+ id: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/),
224
+ /** Shown to people only: it takes no part in the manifest's hash, so rewording it changes no identity. */
225
+ display: z
226
+ .strictObject({
227
+ name: z.string().min(1),
228
+ description: z.string().optional(),
229
+ homepage: z.url().optional(),
230
+ /** Where the vendor explains the usage limits a user should set their own limits by. */
231
+ usageLimitsUrl: z.url().optional(),
232
+ })
233
+ .optional(),
234
+ /** The executable's name, resolved on PATH: the user's own installation, which the host never ships. */
235
+ command: z.string().regex(/^[A-Za-z0-9._-]+$/),
236
+ /** How to read the installed harness's version. */
237
+ version: z.strictObject({ args: z.array(z.string()), pattern: patternSchema }).optional(),
238
+ models: z
239
+ .strictObject({
240
+ default: z.string().min(1).optional(),
241
+ efforts: z.array(z.string().min(1)).optional(),
242
+ defaultEffort: z.string().min(1).optional(),
243
+ })
244
+ .optional(),
245
+ env: environmentSchema.optional(),
246
+ files: z.array(fileSchema).optional(),
247
+ transport: z.discriminatedUnion('type', [jsonlTransportSchema, acpTransportSchema]),
248
+ /**
249
+ * Classifies a failure the harness did not classify itself: each pattern is tried on the
250
+ * failure message followed by the tail of standard error, and the match that starts
251
+ * latest decides.
252
+ */
253
+ failures: z.array(z.strictObject({ pattern: patternSchema, kind: z.enum(FAILURE_KINDS) })).optional(),
254
+ resolver: resolverOverrideSchema.optional(),
255
+ sandbox: sandboxSchema.optional(),
256
+ })
257
+ .superRefine((manifest, context) => {
258
+ const { resolver, transport } = manifest;
259
+ const transportResumes = transport.type === 'jsonl' && transport.resumeArgs !== undefined;
260
+ if (resolver?.resumeArgs !== undefined && !transportResumes) {
261
+ context.addIssue({ code: 'custom', message: '"resolver.resumeArgs" needs the transport\'s "resumeArgs"' });
262
+ }
263
+ if (transportResumes && (resolver?.args === undefined) !== (resolver?.resumeArgs === undefined)) {
264
+ context.addIssue({
265
+ code: 'custom',
266
+ message: '"resolver.args" and "resolver.resumeArgs" come together: one process of a resolver session would launch as a reviewer',
267
+ });
268
+ }
269
+ if (transport.type === 'jsonl')
270
+ checkUsageDeclarations(transport, context);
271
+ const { models } = manifest;
272
+ if (models?.defaultEffort !== undefined &&
273
+ models.efforts !== undefined &&
274
+ !models.efforts.includes(models.defaultEffort)) {
275
+ context.addIssue({ code: 'custom', message: '"defaultEffort" is not one of "efforts"' });
276
+ }
277
+ });
278
+ function checkUsageDeclarations(transport, context) {
279
+ const usageEmits = [
280
+ ...transport.events.flatMap((rule) => (rule.emit.type === 'usage' ? [rule.emit] : [])),
281
+ ...(transport.usageFile === undefined ? [] : [transport.usageFile.emit]),
282
+ ];
283
+ if (transport.usageFile !== undefined && usageEmits.length > 1) {
284
+ context.addIssue({
285
+ code: 'custom',
286
+ message: '"usageFile" and a usage rule in "events" would report the same turn twice: declare one',
287
+ });
288
+ }
289
+ // A declaration about a count the manifest never reads would silently change nothing.
290
+ for (const [flag, declared, field] of [
291
+ ['inputIncludesCacheRead', true, 'cacheRead'],
292
+ ['inputIncludesCacheWrite', true, 'cacheWrite'],
293
+ ['outputIncludesReasoning', false, 'reasoning'],
294
+ ]) {
295
+ if (transport.usage[flag] !== declared)
296
+ continue;
297
+ if (usageEmits.length > 0 && usageEmits.every((emit) => emit[field] !== undefined))
298
+ continue;
299
+ context.addIssue({
300
+ code: 'custom',
301
+ message: `"${flag}": ${declared} has no effect unless the manifest maps usage and every usage emit maps "${field}"`,
302
+ });
303
+ }
304
+ }
305
+ /**
306
+ * Parses a manifest file (JSON with comments). Throws naming every problem; a manifest of a
307
+ * newer schema version is refused with advice to update the host.
308
+ */
309
+ export function parseManifest(text) {
310
+ const errors = [];
311
+ const document = parseJsonc(text, errors, { allowTrailingComma: true });
312
+ if (errors.length > 0) {
313
+ const first = errors[0];
314
+ throw new Error(`the manifest is not valid JSONC: ${first === undefined ? 'unknown error' : printParseErrorCode(first.error)} at offset ${first?.offset ?? 0}`);
315
+ }
316
+ const declared = document?.schema;
317
+ if (typeof declared === 'number' && declared > MANIFEST_SCHEMA_VERSION) {
318
+ throw new Error(`the manifest uses schema ${declared}, newer than this host's ${MANIFEST_SCHEMA_VERSION}: update the host`);
319
+ }
320
+ const result = manifestSchema.safeParse(document);
321
+ if (!result.success)
322
+ throw new Error(`invalid manifest:\n${z.prettifyError(result.error)}`);
323
+ return result.data;
324
+ }
325
+ /**
326
+ * The manifest's identity: SHA-256 of its validated content canonicalized by RFC 8785,
327
+ * without `display`. Formatting, comments and display wording therefore never change it.
328
+ */
329
+ export async function manifestHash(manifest) {
330
+ const { display: _display, ...identity } = manifest;
331
+ return sha256Hex(canonicalJson(identity));
332
+ }
@@ -0,0 +1,58 @@
1
+ import type { FailureKind, ReviewerEvent } from './events.ts';
2
+ import type { Manifest } from './manifest.ts';
3
+ type JsonlTransport = Extract<Manifest['transport'], {
4
+ type: 'jsonl';
5
+ }>;
6
+ export interface ProcessMapper {
7
+ /**
8
+ * The events one line of the process's standard output maps to; a line that is not a JSON
9
+ * object maps to none. With a manifest that names a usage file, a `turn_end` is withheld
10
+ * until `mapUsageFile`, so that the turn's usage precedes it.
11
+ */
12
+ mapLine(line: string): ReviewerEvent[];
13
+ /**
14
+ * Called once after the process exited, with the text of the manifest's usage file or
15
+ * nothing when the file is missing: the usage event it maps to, then the withheld
16
+ * `turn_end`, whose usage is incomplete when the file gave none (it is missing, is not a
17
+ * JSON object, or holds none of the declared counts). Empty for a manifest that names no
18
+ * usage file.
19
+ */
20
+ mapUsageFile(text?: string): ReviewerEvent[];
21
+ /**
22
+ * Whether the process's usage is unreported: it has produced no usage event (the manifest
23
+ * maps none, the harness died first, the usage file is missing), or one of its reports held
24
+ * none of the declared counts. It is final once the process has exited and the usage file
25
+ * is mapped, and the host decides with it then: a turn's usage is complete when its
26
+ * `turn_end` says so and this is false. A `turn_end` mapped from a line cannot know what
27
+ * follows it, so it carries only what is already settled (a report without counts so far,
28
+ * a manifest without any usage source).
29
+ */
30
+ usageUnreported(): boolean;
31
+ }
32
+ export interface SessionMapper {
33
+ /**
34
+ * The mapper of one process of the session. `stderrTail` supplies the end of that process's
35
+ * standard error when a failed turn needs its failure classified. `continuesSession` says
36
+ * whether the process was launched to continue the harness's session (with `resumeArgs` and
37
+ * a session id): one that starts a new session counts its running usage total from zero.
38
+ * It defaults to whether the manifest can continue sessions at all.
39
+ */
40
+ forProcess(stderrTail?: () => string, continuesSession?: boolean): ProcessMapper;
41
+ }
42
+ type MappedManifest = Pick<Manifest, 'id' | 'failures'> & {
43
+ transport: JsonlTransport;
44
+ };
45
+ /**
46
+ * Maps the output of one harness's processes by the manifest's rules, for one job of the host.
47
+ * It holds the running usage total of the session being mapped, which a harness that reports
48
+ * cumulatively carries across the processes that continue that session, and restarts it for a
49
+ * process the host says starts a new session (see `forProcess`).
50
+ */
51
+ export declare function createSessionMapper(manifest: MappedManifest): SessionMapper;
52
+ /**
53
+ * The kind of a failure the harness did not classify: every pattern is tried on the failure
54
+ * message followed by the end of standard error, and the match that starts latest decides
55
+ * (the last thing reported is the failure that ended the turn); `unknown` when none matches.
56
+ */
57
+ export declare function classifyFailure(failures: Manifest['failures'], message: string, stderrTail: string): FailureKind;
58
+ export {};