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,302 @@
1
+ import { FAILURE_KINDS } from './events.js';
2
+ import { resolvePointer } from './jsonPointer.js';
3
+ import { patternLastMatchStart } from './pattern.js';
4
+ /**
5
+ * Maps the output of one harness's processes by the manifest's rules, for one job of the host.
6
+ * It holds the running usage total of the session being mapped, which a harness that reports
7
+ * cumulatively carries across the processes that continue that session, and restarts it for a
8
+ * process the host says starts a new session (see `forProcess`).
9
+ */
10
+ export function createSessionMapper(manifest) {
11
+ const usage = new SessionUsage(manifest.transport.usage);
12
+ return {
13
+ forProcess(stderrTail = () => '', continuesSession = manifest.transport.resumeArgs !== undefined) {
14
+ if (!continuesSession)
15
+ usage.restartTotals();
16
+ return new JsonlProcessMapper(manifest, usage, stderrTail);
17
+ },
18
+ };
19
+ }
20
+ class JsonlProcessMapper {
21
+ manifest;
22
+ usage;
23
+ stderrTail;
24
+ hasUsageSource;
25
+ seenProgress = new Set();
26
+ withheldTurnEnd;
27
+ sessionId;
28
+ usageEvents = 0;
29
+ reportWithoutCounts = false;
30
+ constructor(manifest, usage, stderrTail) {
31
+ this.manifest = manifest;
32
+ this.usage = usage;
33
+ this.stderrTail = stderrTail;
34
+ const { events: rules, usageFile } = manifest.transport;
35
+ this.hasUsageSource = usageFile !== undefined || rules.some((rule) => rule.emit.type === 'usage');
36
+ }
37
+ mapLine(rawLine) {
38
+ const line = parseObject(rawLine);
39
+ if (line === undefined)
40
+ return [];
41
+ const events = this.manifest.transport.events
42
+ .filter((rule) => ruleApplies(rule, line))
43
+ .flatMap((rule) => itemsOf(rule, line).flatMap((item) => this.toEvent(rule.emit, line, item) ?? []));
44
+ // Applied after the line's rules: a usage rule may follow the rule that ends the turn.
45
+ return events.flatMap((event) => (event.type === 'turn_end' ? this.settleTurnEnd(event) : [event]));
46
+ }
47
+ mapUsageFile(text) {
48
+ const { usageFile } = this.manifest.transport;
49
+ if (usageFile === undefined)
50
+ return [];
51
+ const document = text === undefined ? undefined : parseObject(text);
52
+ const usage = this.countUsage(this.usage.toEvent(usageFile.emit, document, undefined));
53
+ const events = usage === undefined ? [] : [usage];
54
+ if (this.withheldTurnEnd !== undefined) {
55
+ events.push({
56
+ ...this.withheldTurnEnd,
57
+ usageComplete: this.withheldTurnEnd.usageComplete && !this.usageUnreported(),
58
+ });
59
+ this.withheldTurnEnd = undefined;
60
+ }
61
+ return events;
62
+ }
63
+ usageUnreported() {
64
+ return this.usageEvents === 0 || this.reportWithoutCounts;
65
+ }
66
+ settleTurnEnd(event) {
67
+ if (this.manifest.transport.usageFile !== undefined) {
68
+ this.withheldTurnEnd = event;
69
+ return [];
70
+ }
71
+ return [this.reportWithoutCounts || !this.hasUsageSource ? { ...event, usageComplete: false } : event];
72
+ }
73
+ countUsage(event) {
74
+ if (event === undefined)
75
+ this.reportWithoutCounts = true;
76
+ else
77
+ this.usageEvents += 1;
78
+ return event;
79
+ }
80
+ toEvent(emit, line, item) {
81
+ const text = (spec) => textOf(resolveValue(spec, line, item));
82
+ switch (emit.type) {
83
+ case 'session': {
84
+ return this.toSessionEvent(emit, text);
85
+ }
86
+ case 'progress': {
87
+ return this.toProgressEvent(emit, text);
88
+ }
89
+ case 'usage': {
90
+ return this.countUsage(this.usage.toEvent(emit, line, item));
91
+ }
92
+ case 'log': {
93
+ const body = text(emit.text);
94
+ return body === undefined ? undefined : { type: 'log', level: emit.level, text: body };
95
+ }
96
+ case 'turn_end': {
97
+ return this.toTurnEndEvent(emit, text);
98
+ }
99
+ }
100
+ }
101
+ toSessionEvent(emit, text) {
102
+ const id = text(emit.id);
103
+ // Some harnesses name the session on every step.
104
+ if (id === undefined || id === '' || id === this.sessionId)
105
+ return undefined;
106
+ this.sessionId = id;
107
+ const model = text(emit.model);
108
+ const version = text(emit.harnessVersion);
109
+ return {
110
+ type: 'session',
111
+ id,
112
+ ...(model === undefined ? {} : { model }),
113
+ ...(version === undefined ? {} : { harness: { name: this.manifest.id, version } }),
114
+ };
115
+ }
116
+ toProgressEvent(emit, text) {
117
+ const body = text(emit.text);
118
+ // A response that only calls tools carries an empty message.
119
+ if (body === '' && (emit.kind === 'message' || emit.kind === 'thought'))
120
+ return undefined;
121
+ const key = text(emit.key);
122
+ if (key !== undefined) {
123
+ const seenKey = `${emit.kind}\0${key}`;
124
+ if (this.seenProgress.has(seenKey))
125
+ return undefined;
126
+ this.seenProgress.add(seenKey);
127
+ }
128
+ return { type: 'progress', kind: emit.kind, ...(body === undefined ? {} : { text: body }) };
129
+ }
130
+ toTurnEndEvent(emit, text) {
131
+ const status = text(emit.status);
132
+ if (status !== 'completed' && status !== 'failed')
133
+ return undefined;
134
+ const stopReason = text(emit.stopReason);
135
+ const finalText = text(emit.text);
136
+ const base = {
137
+ type: 'turn_end',
138
+ ...(stopReason === undefined ? {} : { stopReason }),
139
+ ...(finalText === undefined ? {} : { text: finalText }),
140
+ usageComplete: emit.usageComplete ?? true,
141
+ };
142
+ if (status === 'completed')
143
+ return { ...base, status };
144
+ const message = text(emit.failureMessage) ?? finalText ?? stopReason ?? 'the harness reported a failed turn';
145
+ const declared = text(emit.failureKind);
146
+ const kind = FAILURE_KINDS.includes(declared ?? '')
147
+ ? declared
148
+ : classifyFailure(this.manifest.failures, message, this.stderrTail());
149
+ return { ...base, status, failure: { kind, message } };
150
+ }
151
+ }
152
+ /** The running usage total of one session, carried across the processes that continue it. */
153
+ class SessionUsage {
154
+ semantics;
155
+ totals;
156
+ reports = 0;
157
+ constructor(semantics) {
158
+ this.semantics = semantics;
159
+ }
160
+ restartTotals() {
161
+ this.totals = undefined;
162
+ }
163
+ /**
164
+ * The usage event of one report, or undefined when none of the declared counts resolves to
165
+ * a number (a renamed field): that report is unreported usage, not zero tokens.
166
+ */
167
+ toEvent(emit, line, item) {
168
+ const specs = [emit.input, emit.output, emit.cacheRead, emit.cacheWrite, emit.reasoning];
169
+ if (!specs.some((spec) => typeof resolveValue(spec, line, item) === 'number'))
170
+ return undefined;
171
+ this.reports += 1;
172
+ const counts = this.nextCounts(emit, line, item);
173
+ const key = resolveValue(emit.key, line, item);
174
+ const model = resolveValue(emit.model, line, item);
175
+ const costUsd = resolveValue(emit.costUsd, line, item);
176
+ return {
177
+ type: 'usage',
178
+ key: typeof key === 'number' || (typeof key === 'string' && key !== '') ? String(key) : `report-${this.reports}`,
179
+ ...(typeof model === 'string' ? { model } : {}),
180
+ input: counts.input,
181
+ output: counts.output,
182
+ cacheRead: counts.cacheRead,
183
+ ...(emit.cacheWrite === undefined ? {} : { cacheWrite: counts.cacheWrite }),
184
+ ...(emit.reasoning === undefined ? {} : { reasoning: counts.reasoning }),
185
+ ...(typeof costUsd === 'number' && costUsd >= 0 ? { costUsd } : {}),
186
+ };
187
+ }
188
+ nextCounts(emit, line, item) {
189
+ const cumulative = this.semantics.mode === 'cumulative';
190
+ const previous = cumulative ? this.totals : undefined;
191
+ const count = (spec, name) => reportedCount(resolveValue(spec, line, item), previous?.[name]);
192
+ const reported = {
193
+ input: count(emit.input, 'input'),
194
+ output: count(emit.output, 'output'),
195
+ cacheRead: count(emit.cacheRead, 'cacheRead'),
196
+ cacheWrite: count(emit.cacheWrite, 'cacheWrite'),
197
+ reasoning: count(emit.reasoning, 'reasoning'),
198
+ };
199
+ // Normalized before the subtraction: a running total keeps the harness's own meaning.
200
+ const counts = normalizeCounts(reported, this.semantics);
201
+ if (!cumulative)
202
+ return counts;
203
+ this.totals = reported;
204
+ return previous === undefined ? counts : subtractCounts(counts, normalizeCounts(previous, this.semantics));
205
+ }
206
+ }
207
+ /**
208
+ * A count the report omits is unreported: a running total keeps its last value, so that the
209
+ * count's next report is not differenced from zero.
210
+ */
211
+ function reportedCount(value, previous) {
212
+ if (typeof value !== 'number')
213
+ return previous ?? 0;
214
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
215
+ }
216
+ function textOf(value) {
217
+ if (typeof value === 'string')
218
+ return value;
219
+ return value === undefined || value === null ? undefined : JSON.stringify(value);
220
+ }
221
+ /**
222
+ * The kind of a failure the harness did not classify: every pattern is tried on the failure
223
+ * message followed by the end of standard error, and the match that starts latest decides
224
+ * (the last thing reported is the failure that ended the turn); `unknown` when none matches.
225
+ */
226
+ export function classifyFailure(failures, message, stderrTail) {
227
+ const text = `${message}\n${stderrTail}`;
228
+ let best;
229
+ for (const { pattern, kind } of failures ?? []) {
230
+ const start = patternLastMatchStart(pattern, text);
231
+ if (start !== undefined && (best === undefined || start >= best.start))
232
+ best = { start, kind };
233
+ }
234
+ return best?.kind ?? 'unknown';
235
+ }
236
+ function parseObject(rawLine) {
237
+ const trimmed = rawLine.trim();
238
+ if (!trimmed.startsWith('{'))
239
+ return undefined;
240
+ try {
241
+ return JSON.parse(trimmed);
242
+ }
243
+ catch {
244
+ return undefined;
245
+ }
246
+ }
247
+ function ruleApplies(rule, line) {
248
+ return matches(rule.match, line) && (rule.unless === undefined || !matches(rule.unless, line));
249
+ }
250
+ function itemsOf(rule, line) {
251
+ if (rule.each === undefined)
252
+ return [undefined];
253
+ const list = resolvePointer(line, rule.each);
254
+ if (!Array.isArray(list))
255
+ return [];
256
+ return list.filter((item) => matches(rule.itemMatch, item));
257
+ }
258
+ function matches(match, document) {
259
+ for (const [pointer, expected] of Object.entries(match ?? {})) {
260
+ const actual = resolvePointer(document, pointer);
261
+ const allowed = Array.isArray(expected) ? expected : [expected];
262
+ if (!allowed.includes(actual))
263
+ return false;
264
+ }
265
+ return true;
266
+ }
267
+ function resolveValue(spec, line, item) {
268
+ if (spec === undefined)
269
+ return undefined;
270
+ if (spec === null || typeof spec !== 'object')
271
+ return spec;
272
+ const value = 'from' in spec ? resolvePointer(line, spec.from) : resolvePointer(item, spec.fromItem);
273
+ const scalar = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
274
+ if (spec.map !== undefined && scalar && Object.hasOwn(spec.map, String(value)))
275
+ return spec.map[String(value)];
276
+ // The default replaces what a map does not list (an object or array included) and an absent
277
+ // value, which JSON's null is too.
278
+ const unlisted = spec.map !== undefined || value === undefined || value === null;
279
+ return unlisted && spec.default !== undefined ? spec.default : value;
280
+ }
281
+ function subtractCounts(current, previous) {
282
+ return {
283
+ input: difference(current.input, previous.input),
284
+ output: difference(current.output, previous.output),
285
+ cacheRead: difference(current.cacheRead, previous.cacheRead),
286
+ cacheWrite: difference(current.cacheWrite, previous.cacheWrite),
287
+ reasoning: difference(current.reasoning, previous.reasoning),
288
+ };
289
+ }
290
+ function difference(now, before) {
291
+ return Math.max(0, now - before);
292
+ }
293
+ function normalizeCounts(counts, semantics) {
294
+ let { input, output } = counts;
295
+ if (semantics.inputIncludesCacheRead === true)
296
+ input -= counts.cacheRead;
297
+ if (semantics.inputIncludesCacheWrite === true)
298
+ input -= counts.cacheWrite;
299
+ if (semantics.outputIncludesReasoning === false)
300
+ output += counts.reasoning;
301
+ return { ...counts, input: Math.max(0, input), output };
302
+ }
@@ -0,0 +1,16 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * A manifest's regular expressions run against vendor output the manifest's author does not
4
+ * control, so they must match in linear time. RE2 guarantees that and has no backreferences
5
+ * or lookaround, so compiling a pattern with it is the whole check.
6
+ */
7
+ export declare const patternSchema: z.ZodString;
8
+ export declare function patternMatches(source: string, text: string): boolean;
9
+ /** The first capture group of the first match, or the whole match when the pattern has no group. */
10
+ export declare function patternCapture(source: string, text: string): string | undefined;
11
+ /**
12
+ * The latest position in the text at which the pattern matches, or undefined when it never
13
+ * matches. One match behind a greedy prefix finds it: repeating `find` would rescan the rest
14
+ * of the text after every match, which is quadratic.
15
+ */
16
+ export declare function patternLastMatchStart(source: string, text: string): number | undefined;
@@ -0,0 +1,49 @@
1
+ import { RE2JS } from 're2js';
2
+ import { z } from 'zod';
3
+ /**
4
+ * A manifest's regular expressions run against vendor output the manifest's author does not
5
+ * control, so they must match in linear time. RE2 guarantees that and has no backreferences
6
+ * or lookaround, so compiling a pattern with it is the whole check.
7
+ */
8
+ export const patternSchema = z
9
+ .string()
10
+ .min(1)
11
+ .superRefine((source, context) => {
12
+ try {
13
+ RE2JS.compile(source);
14
+ }
15
+ catch (error) {
16
+ context.addIssue({
17
+ code: 'custom',
18
+ message: `not a linear-time regular expression: ${error instanceof Error ? error.message : String(error)}`,
19
+ });
20
+ }
21
+ });
22
+ const compiled = new Map();
23
+ function compile(source) {
24
+ let pattern = compiled.get(source);
25
+ if (pattern === undefined) {
26
+ pattern = RE2JS.compile(source);
27
+ compiled.set(source, pattern);
28
+ }
29
+ return pattern;
30
+ }
31
+ export function patternMatches(source, text) {
32
+ return compile(source).matcher(text).find();
33
+ }
34
+ /** The first capture group of the first match, or the whole match when the pattern has no group. */
35
+ export function patternCapture(source, text) {
36
+ const matcher = compile(source).matcher(text);
37
+ if (!matcher.find())
38
+ return undefined;
39
+ return (matcher.groupCount() > 0 ? matcher.group(1) : matcher.group(0)) ?? undefined;
40
+ }
41
+ /**
42
+ * The latest position in the text at which the pattern matches, or undefined when it never
43
+ * matches. One match behind a greedy prefix finds it: repeating `find` would rescan the rest
44
+ * of the text after every match, which is quadratic.
45
+ */
46
+ export function patternLastMatchStart(source, text) {
47
+ const matcher = compile(`(?s:.*)(${source})`).matcher(text);
48
+ return matcher.find() ? matcher.start(1) : undefined;
49
+ }
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * The variables a manifest template may read. A manifest holds no code: a template only
4
+ * substitutes these, adds arguments when one has a value, expands a list, and applies the
5
+ * `json` and `toml` filters.
6
+ */
7
+ export declare const TEMPLATE_VARIABLES: readonly ['prompt', 'model', 'effort', 'sessionId', 'deadlineMinutes', 'logFile', 'scratchDir', 'tmpDir', 'writableDirs'];
8
+ export type TemplateVariable = (typeof TEMPLATE_VARIABLES)[number];
9
+ export interface TemplateValues {
10
+ prompt: string;
11
+ model?: string;
12
+ effort?: string;
13
+ sessionId?: string;
14
+ deadlineMinutes?: number;
15
+ logFile?: string;
16
+ scratchDir?: string;
17
+ /** The temporary directory a sandboxed harness may write: its `TMPDIR`. */
18
+ tmpDir?: string;
19
+ writableDirs?: readonly string[];
20
+ }
21
+ /** The variables that hold a list: only `each` or a filter renders one. */
22
+ declare const LIST_VARIABLES: readonly ["writableDirs"];
23
+ type ListVariable = (typeof LIST_VARIABLES)[number];
24
+ /**
25
+ * A string whose `{{var}}` and `{{var | filter}}` placeholders can be rendered: they name known
26
+ * variables and filters, and a list variable goes through a filter.
27
+ */
28
+ export declare const templateStringSchema: z.ZodType<string, unknown, z.core.$ZodTypeInternals<string, unknown>>;
29
+ export type ArgTemplate = string | {
30
+ when: TemplateVariable;
31
+ args: ArgTemplate[];
32
+ } | {
33
+ each: ListVariable;
34
+ args: ArgTemplate[];
35
+ };
36
+ /** Argument templates; `{{item}}` is the element of the enclosing `each` and is rejected outside one. */
37
+ export declare const argTemplateSchema: z.ZodType<ArgTemplate, unknown, z.core.$ZodTypeInternals<ArgTemplate, unknown>>;
38
+ /**
39
+ * Renders one template string. Throws when it reads a variable that has no value: an
40
+ * argument that depends on an optional variable belongs under `when`.
41
+ */
42
+ export declare function renderTemplate(template: string, values: TemplateValues, item?: string): string;
43
+ /** Expands argument templates into the argument vector, in order. */
44
+ export declare function renderArgs(templates: readonly ArgTemplate[], values: TemplateValues, item?: string): string[];
45
+ export {};
@@ -0,0 +1,112 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * The variables a manifest template may read. A manifest holds no code: a template only
4
+ * substitutes these, adds arguments when one has a value, expands a list, and applies the
5
+ * `json` and `toml` filters.
6
+ */
7
+ export const TEMPLATE_VARIABLES = [
8
+ 'prompt',
9
+ 'model',
10
+ 'effort',
11
+ 'sessionId',
12
+ 'deadlineMinutes',
13
+ 'logFile',
14
+ 'scratchDir',
15
+ 'tmpDir',
16
+ 'writableDirs',
17
+ ];
18
+ /** The variables that hold a list: only `each` or a filter renders one. */
19
+ const LIST_VARIABLES = ['writableDirs'];
20
+ const FILTERS = ['json', 'toml'];
21
+ const PLACEHOLDER = /\{\{\s*([A-Za-z]+)\s*(?:\|\s*([A-Za-z]+)\s*)?\}\}/g;
22
+ // Only the opening pair: JSON text closes nested objects with `}}` and never opens one with `{{`.
23
+ const UNMATCHED_OPENING = /\{\{/;
24
+ /**
25
+ * A string whose `{{var}}` and `{{var | filter}}` placeholders can be rendered: they name known
26
+ * variables and filters, and a list variable goes through a filter.
27
+ */
28
+ export const templateStringSchema = templateSchema(false);
29
+ const variableSchema = z.enum(TEMPLATE_VARIABLES);
30
+ /** Argument templates; `{{item}}` is the element of the enclosing `each` and is rejected outside one. */
31
+ export const argTemplateSchema = argSchema(false);
32
+ function argSchema(insideEach) {
33
+ const schema = z.lazy(() => z.union([
34
+ templateSchema(insideEach),
35
+ z.strictObject({ when: variableSchema, args: z.array(schema).min(1) }),
36
+ z.strictObject({ each: z.enum(LIST_VARIABLES), args: z.array(argSchema(true)).min(1) }),
37
+ ]));
38
+ return schema;
39
+ }
40
+ function templateSchema(allowItem) {
41
+ return z.string().superRefine((value, context) => {
42
+ for (const problem of templateProblems(value, allowItem))
43
+ context.addIssue({ code: 'custom', message: problem });
44
+ });
45
+ }
46
+ /**
47
+ * Renders one template string. Throws when it reads a variable that has no value: an
48
+ * argument that depends on an optional variable belongs under `when`.
49
+ */
50
+ export function renderTemplate(template, values, item) {
51
+ return template.replaceAll(PLACEHOLDER, (_match, name, filter) => {
52
+ const value = name === 'item' ? item : values[name];
53
+ if (value === undefined)
54
+ throw new Error(`the template reads "${name}", which has no value here`);
55
+ return applyFilter(value, filter);
56
+ });
57
+ }
58
+ /** Expands argument templates into the argument vector, in order. */
59
+ export function renderArgs(templates, values, item) {
60
+ return templates.flatMap((template) => {
61
+ if (typeof template === 'string')
62
+ return [renderTemplate(template, values, item)];
63
+ if ('when' in template) {
64
+ return hasValue(values[template.when]) ? renderArgs(template.args, values, item) : [];
65
+ }
66
+ const list = values[template.each];
67
+ if (list === undefined)
68
+ return [];
69
+ if (!Array.isArray(list))
70
+ throw new Error(`"each" needs a list, and "${template.each}" is not one`);
71
+ return list.flatMap((element) => renderArgs(template.args, values, element));
72
+ });
73
+ }
74
+ function hasValue(value) {
75
+ return value !== undefined && value !== '' && !(Array.isArray(value) && value.length === 0);
76
+ }
77
+ function applyFilter(value, filter) {
78
+ if (filter === 'json')
79
+ return JSON.stringify(value);
80
+ if (filter === 'toml')
81
+ return tomlValue(value);
82
+ if (Array.isArray(value))
83
+ throw new Error('a list is rendered through "each" or a filter');
84
+ return String(value);
85
+ }
86
+ // TOML basic strings share JSON's escapes for every character JSON.stringify escapes, and
87
+ // TOML arrays of strings and numbers are written as JSON writes them.
88
+ function tomlValue(value) {
89
+ return JSON.stringify(value);
90
+ }
91
+ function templateProblems(value, allowItem) {
92
+ const problems = [];
93
+ for (const match of value.matchAll(PLACEHOLDER)) {
94
+ const [, name, filter] = match;
95
+ if (name === 'item') {
96
+ if (!allowItem)
97
+ problems.push('"{{item}}" has a value only inside "each"');
98
+ }
99
+ else if (!TEMPLATE_VARIABLES.includes(name ?? '')) {
100
+ problems.push(`unknown template variable "${name}"`);
101
+ }
102
+ else if (filter === undefined && LIST_VARIABLES.includes(name ?? '')) {
103
+ problems.push(`the list "${name}" is rendered through "each" or a filter`);
104
+ }
105
+ if (filter !== undefined && !FILTERS.includes(filter)) {
106
+ problems.push(`unknown template filter "${filter}"`);
107
+ }
108
+ }
109
+ if (UNMATCHED_OPENING.test(value.replaceAll(PLACEHOLDER, '')))
110
+ problems.push('malformed template placeholder');
111
+ return problems;
112
+ }
package/package.json CHANGED
@@ -1,9 +1,43 @@
1
1
  {
2
2
  "name": "reviewer-protocol",
3
- "version": "0.0.1",
4
- "description": "Reviewer Protocol: the protocol, manifest format, and TypeScript SDK for connecting reviewer harnesses to review orchestrators.",
5
- "homepage": "https://reviewfixloop.com",
6
- "repository": { "type": "git", "url": "git+https://github.com/reviewfixloop/reviewer-protocol.git" },
3
+ "version": "1.0.0-beta.1",
4
+ "description": "Reviewer Protocol: events, manifest format, and an ACP extension for connecting reviewer harnesses to review orchestrators",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/reviewfixloop/reviewer-protocol.git"
8
+ },
7
9
  "license": "Apache-2.0",
8
- "files": ["README.md"]
10
+ "author": "WillBooster Inc.",
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "bun": "./src/index.ts",
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "src"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.build.json",
25
+ "prepublishOnly": "bun run build",
26
+ "test": "bun test",
27
+ "typecheck": "tsc --noEmit"
28
+ },
29
+ "dependencies": {
30
+ "jsonc-parser": "3.3.1",
31
+ "re2js": "2.8.7",
32
+ "zod": "4.6.7"
33
+ },
34
+ "devDependencies": {
35
+ "@tsconfig/bun": "1.0.11",
36
+ "@types/bun": "1.4.4",
37
+ "typescript": "7.0.2"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public",
41
+ "registry": "https://registry.npmjs.org/"
42
+ }
9
43
  }
package/src/acp.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { z } from 'zod';
2
+
3
+ import { failureSchema, usageEventSchema } from './events.ts';
4
+ import { MANIFEST_ROLES } from './manifest.ts';
5
+
6
+ /**
7
+ * The Reviewer Protocol's extension of ACP (Agent Client Protocol) v1. ACP carries custom
8
+ * data only under `_meta`, so everything the protocol adds travels under this key: the
9
+ * agent advertises it in `initialize`, the host sends the session's conditions with
10
+ * `session/new`, and the agent reports each turn's usage and failure with its
11
+ * `session/prompt` response.
12
+ */
13
+ export const ACP_META_KEY = 'reviewer-protocol/v1';
14
+
15
+ /** In `agentCapabilities._meta` of the `initialize` response: the agent speaks the extension. */
16
+ export const acpCapabilityMetaSchema = z.object({ version: z.literal(1) });
17
+ export type AcpCapabilityMeta = z.infer<typeof acpCapabilityMetaSchema>;
18
+
19
+ /** In `_meta` of the `session/new` request: what ACP itself has no field for. */
20
+ export const acpSessionMetaSchema = z.object({
21
+ role: z.enum(MANIFEST_ROLES),
22
+ /** The revision under review: a commit SHA. */
23
+ revision: z.string().min(1),
24
+ /** Minutes until the host cancels the session's turn. */
25
+ deadlineMinutes: z.number().positive().optional(),
26
+ model: z.string().min(1).optional(),
27
+ effort: z.string().min(1).optional(),
28
+ });
29
+ export type AcpSessionMeta = z.infer<typeof acpSessionMetaSchema>;
30
+
31
+ /**
32
+ * In `_meta` of the `session/prompt` response: the turn's usage in the protocol's unified
33
+ * meaning (see usageEventSchema) and, for a turn the agent could not finish, its failure.
34
+ */
35
+ export const acpTurnMetaSchema = z.object({
36
+ usage: usageEventSchema.omit({ type: true, key: true }).optional(),
37
+ usageComplete: z.boolean().optional(),
38
+ failure: failureSchema.optional(),
39
+ });
40
+ export type AcpTurnMeta = z.infer<typeof acpTurnMetaSchema>;
41
+
42
+ /** The extension's part of an ACP `_meta` object, validated by `schema`; undefined when absent or malformed. */
43
+ export function readAcpMeta<Schema extends z.ZodType>(meta: unknown, schema: Schema): z.infer<Schema> | undefined {
44
+ if (meta === null || typeof meta !== 'object') return undefined;
45
+ const result = schema.safeParse((meta as Record<string, unknown>)[ACP_META_KEY]);
46
+ return result.success ? result.data : undefined;
47
+ }
48
+
49
+ /** An ACP `_meta` object carrying the extension's part. */
50
+ export function acpMeta<Value>(value: Value): Record<typeof ACP_META_KEY, Value> {
51
+ return { [ACP_META_KEY]: value };
52
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Serializes a JSON value by RFC 8785 (JSON Canonicalization Scheme): object members sorted
3
+ * by their names' UTF-16 code units, no insignificant whitespace, and ECMAScript's number and
4
+ * string serialization. `Array.prototype.sort` without a comparator and `JSON.stringify` are
5
+ * exactly those orderings and serializations.
6
+ */
7
+ export function canonicalJson(value: unknown): string {
8
+ if (value === null || typeof value !== 'object') {
9
+ if (typeof value === 'number' && !Number.isFinite(value)) throw new Error('JSON has no non-finite numbers');
10
+ const text = JSON.stringify(value);
11
+ if (text === undefined) throw new Error(`not a JSON value: ${typeof value}`);
12
+ return text;
13
+ }
14
+ if (Array.isArray(value)) return `[${value.map((element) => canonicalJson(element)).join(',')}]`;
15
+ const members = Object.keys(value)
16
+ .toSorted()
17
+ .flatMap((name) => {
18
+ const member = (value as Record<string, unknown>)[name];
19
+ return member === undefined ? [] : [`${JSON.stringify(name)}:${canonicalJson(member)}`];
20
+ });
21
+ return `{${members.join(',')}}`;
22
+ }
23
+
24
+ export async function sha256Hex(text: string): Promise<string> {
25
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
26
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
27
+ }