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.
- package/LICENSE +202 -0
- package/README.md +136 -3
- package/dist/acp.d.ts +65 -0
- package/dist/acp.js +43 -0
- package/dist/canonicalJson.d.ts +8 -0
- package/dist/canonicalJson.js +29 -0
- package/dist/events.d.ts +194 -0
- package/dist/events.js +95 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +9 -0
- package/dist/jsonPointer.d.ts +5 -0
- package/dist/jsonPointer.js +24 -0
- package/dist/launch.d.ts +44 -0
- package/dist/launch.js +56 -0
- package/dist/manifest.d.ts +822 -0
- package/dist/manifest.js +332 -0
- package/dist/mapping.d.ts +58 -0
- package/dist/mapping.js +302 -0
- package/dist/pattern.d.ts +16 -0
- package/dist/pattern.js +49 -0
- package/dist/template.d.ts +45 -0
- package/dist/template.js +112 -0
- package/package.json +39 -5
- package/src/acp.ts +52 -0
- package/src/canonicalJson.ts +27 -0
- package/src/events.ts +117 -0
- package/src/index.ts +9 -0
- package/src/jsonPointer.ts +22 -0
- package/src/launch.ts +90 -0
- package/src/manifest.ts +368 -0
- package/src/mapping.ts +357 -0
- package/src/pattern.ts +53 -0
- package/src/template.ts +138 -0
package/src/mapping.ts
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import type { FailureKind, ReviewerEvent, TurnEndEvent, UsageEvent } from './events.ts';
|
|
2
|
+
import { FAILURE_KINDS } from './events.ts';
|
|
3
|
+
import { resolvePointer } from './jsonPointer.ts';
|
|
4
|
+
import type { EmitSpec, Manifest, MappingRule, Scalar, UsageSemantics, ValueSpec } from './manifest.ts';
|
|
5
|
+
import { patternLastMatchStart } from './pattern.ts';
|
|
6
|
+
|
|
7
|
+
type JsonlTransport = Extract<Manifest['transport'], { type: 'jsonl' }>;
|
|
8
|
+
|
|
9
|
+
export interface ProcessMapper {
|
|
10
|
+
/**
|
|
11
|
+
* The events one line of the process's standard output maps to; a line that is not a JSON
|
|
12
|
+
* object maps to none. With a manifest that names a usage file, a `turn_end` is withheld
|
|
13
|
+
* until `mapUsageFile`, so that the turn's usage precedes it.
|
|
14
|
+
*/
|
|
15
|
+
mapLine(line: string): ReviewerEvent[];
|
|
16
|
+
/**
|
|
17
|
+
* Called once after the process exited, with the text of the manifest's usage file or
|
|
18
|
+
* nothing when the file is missing: the usage event it maps to, then the withheld
|
|
19
|
+
* `turn_end`, whose usage is incomplete when the file gave none (it is missing, is not a
|
|
20
|
+
* JSON object, or holds none of the declared counts). Empty for a manifest that names no
|
|
21
|
+
* usage file.
|
|
22
|
+
*/
|
|
23
|
+
mapUsageFile(text?: string): ReviewerEvent[];
|
|
24
|
+
/**
|
|
25
|
+
* Whether the process's usage is unreported: it has produced no usage event (the manifest
|
|
26
|
+
* maps none, the harness died first, the usage file is missing), or one of its reports held
|
|
27
|
+
* none of the declared counts. It is final once the process has exited and the usage file
|
|
28
|
+
* is mapped, and the host decides with it then: a turn's usage is complete when its
|
|
29
|
+
* `turn_end` says so and this is false. A `turn_end` mapped from a line cannot know what
|
|
30
|
+
* follows it, so it carries only what is already settled (a report without counts so far,
|
|
31
|
+
* a manifest without any usage source).
|
|
32
|
+
*/
|
|
33
|
+
usageUnreported(): boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface SessionMapper {
|
|
37
|
+
/**
|
|
38
|
+
* The mapper of one process of the session. `stderrTail` supplies the end of that process's
|
|
39
|
+
* standard error when a failed turn needs its failure classified. `continuesSession` says
|
|
40
|
+
* whether the process was launched to continue the harness's session (with `resumeArgs` and
|
|
41
|
+
* a session id): one that starts a new session counts its running usage total from zero.
|
|
42
|
+
* It defaults to whether the manifest can continue sessions at all.
|
|
43
|
+
*/
|
|
44
|
+
forProcess(stderrTail?: () => string, continuesSession?: boolean): ProcessMapper;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface TokenCounts {
|
|
48
|
+
input: number;
|
|
49
|
+
output: number;
|
|
50
|
+
cacheRead: number;
|
|
51
|
+
cacheWrite: number;
|
|
52
|
+
reasoning: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
type UsageEmit = Extract<EmitSpec, { type: 'usage' }>;
|
|
56
|
+
type SessionEmit = Extract<EmitSpec, { type: 'session' }>;
|
|
57
|
+
type ProgressEmit = Extract<EmitSpec, { type: 'progress' }>;
|
|
58
|
+
type TurnEndEmit = Extract<EmitSpec, { type: 'turn_end' }>;
|
|
59
|
+
type MappedManifest = Pick<Manifest, 'id' | 'failures'> & { transport: JsonlTransport };
|
|
60
|
+
type TextOf = (spec: ValueSpec | undefined) => string | undefined;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Maps the output of one harness's processes by the manifest's rules, for one job of the host.
|
|
64
|
+
* It holds the running usage total of the session being mapped, which a harness that reports
|
|
65
|
+
* cumulatively carries across the processes that continue that session, and restarts it for a
|
|
66
|
+
* process the host says starts a new session (see `forProcess`).
|
|
67
|
+
*/
|
|
68
|
+
export function createSessionMapper(manifest: MappedManifest): SessionMapper {
|
|
69
|
+
const usage = new SessionUsage(manifest.transport.usage);
|
|
70
|
+
return {
|
|
71
|
+
forProcess(stderrTail = () => '', continuesSession = manifest.transport.resumeArgs !== undefined) {
|
|
72
|
+
if (!continuesSession) usage.restartTotals();
|
|
73
|
+
return new JsonlProcessMapper(manifest, usage, stderrTail);
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
class JsonlProcessMapper implements ProcessMapper {
|
|
79
|
+
private readonly hasUsageSource: boolean;
|
|
80
|
+
private readonly seenProgress = new Set<string>();
|
|
81
|
+
private withheldTurnEnd: TurnEndEvent | undefined;
|
|
82
|
+
private sessionId: string | undefined;
|
|
83
|
+
private usageEvents = 0;
|
|
84
|
+
private reportWithoutCounts = false;
|
|
85
|
+
|
|
86
|
+
constructor(
|
|
87
|
+
private readonly manifest: MappedManifest,
|
|
88
|
+
private readonly usage: SessionUsage,
|
|
89
|
+
private readonly stderrTail: () => string
|
|
90
|
+
) {
|
|
91
|
+
const { events: rules, usageFile } = manifest.transport;
|
|
92
|
+
this.hasUsageSource = usageFile !== undefined || rules.some((rule) => rule.emit.type === 'usage');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
mapLine(rawLine: string): ReviewerEvent[] {
|
|
96
|
+
const line = parseObject(rawLine);
|
|
97
|
+
if (line === undefined) return [];
|
|
98
|
+
const events = this.manifest.transport.events
|
|
99
|
+
.filter((rule) => ruleApplies(rule, line))
|
|
100
|
+
.flatMap((rule) => itemsOf(rule, line).flatMap((item) => this.toEvent(rule.emit, line, item) ?? []));
|
|
101
|
+
// Applied after the line's rules: a usage rule may follow the rule that ends the turn.
|
|
102
|
+
return events.flatMap((event) => (event.type === 'turn_end' ? this.settleTurnEnd(event) : [event]));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
mapUsageFile(text?: string): ReviewerEvent[] {
|
|
106
|
+
const { usageFile } = this.manifest.transport;
|
|
107
|
+
if (usageFile === undefined) return [];
|
|
108
|
+
const document = text === undefined ? undefined : parseObject(text);
|
|
109
|
+
const usage = this.countUsage(this.usage.toEvent(usageFile.emit, document, undefined));
|
|
110
|
+
const events: ReviewerEvent[] = usage === undefined ? [] : [usage];
|
|
111
|
+
if (this.withheldTurnEnd !== undefined) {
|
|
112
|
+
events.push({
|
|
113
|
+
...this.withheldTurnEnd,
|
|
114
|
+
usageComplete: this.withheldTurnEnd.usageComplete && !this.usageUnreported(),
|
|
115
|
+
});
|
|
116
|
+
this.withheldTurnEnd = undefined;
|
|
117
|
+
}
|
|
118
|
+
return events;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
usageUnreported(): boolean {
|
|
122
|
+
return this.usageEvents === 0 || this.reportWithoutCounts;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private settleTurnEnd(event: TurnEndEvent): ReviewerEvent[] {
|
|
126
|
+
if (this.manifest.transport.usageFile !== undefined) {
|
|
127
|
+
this.withheldTurnEnd = event;
|
|
128
|
+
return [];
|
|
129
|
+
}
|
|
130
|
+
return [this.reportWithoutCounts || !this.hasUsageSource ? { ...event, usageComplete: false } : event];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private countUsage(event: UsageEvent | undefined): UsageEvent | undefined {
|
|
134
|
+
if (event === undefined) this.reportWithoutCounts = true;
|
|
135
|
+
else this.usageEvents += 1;
|
|
136
|
+
return event;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private toEvent(emit: EmitSpec, line: unknown, item: unknown): ReviewerEvent | undefined {
|
|
140
|
+
const text: TextOf = (spec) => textOf(resolveValue(spec, line, item));
|
|
141
|
+
switch (emit.type) {
|
|
142
|
+
case 'session': {
|
|
143
|
+
return this.toSessionEvent(emit, text);
|
|
144
|
+
}
|
|
145
|
+
case 'progress': {
|
|
146
|
+
return this.toProgressEvent(emit, text);
|
|
147
|
+
}
|
|
148
|
+
case 'usage': {
|
|
149
|
+
return this.countUsage(this.usage.toEvent(emit, line, item));
|
|
150
|
+
}
|
|
151
|
+
case 'log': {
|
|
152
|
+
const body = text(emit.text);
|
|
153
|
+
return body === undefined ? undefined : { type: 'log', level: emit.level, text: body };
|
|
154
|
+
}
|
|
155
|
+
case 'turn_end': {
|
|
156
|
+
return this.toTurnEndEvent(emit, text);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private toSessionEvent(emit: SessionEmit, text: TextOf): ReviewerEvent | undefined {
|
|
162
|
+
const id = text(emit.id);
|
|
163
|
+
// Some harnesses name the session on every step.
|
|
164
|
+
if (id === undefined || id === '' || id === this.sessionId) return undefined;
|
|
165
|
+
this.sessionId = id;
|
|
166
|
+
const model = text(emit.model);
|
|
167
|
+
const version = text(emit.harnessVersion);
|
|
168
|
+
return {
|
|
169
|
+
type: 'session',
|
|
170
|
+
id,
|
|
171
|
+
...(model === undefined ? {} : { model }),
|
|
172
|
+
...(version === undefined ? {} : { harness: { name: this.manifest.id, version } }),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private toProgressEvent(emit: ProgressEmit, text: TextOf): ReviewerEvent | undefined {
|
|
177
|
+
const body = text(emit.text);
|
|
178
|
+
// A response that only calls tools carries an empty message.
|
|
179
|
+
if (body === '' && (emit.kind === 'message' || emit.kind === 'thought')) return undefined;
|
|
180
|
+
const key = text(emit.key);
|
|
181
|
+
if (key !== undefined) {
|
|
182
|
+
const seenKey = `${emit.kind}\0${key}`;
|
|
183
|
+
if (this.seenProgress.has(seenKey)) return undefined;
|
|
184
|
+
this.seenProgress.add(seenKey);
|
|
185
|
+
}
|
|
186
|
+
return { type: 'progress', kind: emit.kind, ...(body === undefined ? {} : { text: body }) };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
private toTurnEndEvent(emit: TurnEndEmit, text: TextOf): TurnEndEvent | undefined {
|
|
190
|
+
const status = text(emit.status);
|
|
191
|
+
if (status !== 'completed' && status !== 'failed') return undefined;
|
|
192
|
+
const stopReason = text(emit.stopReason);
|
|
193
|
+
const finalText = text(emit.text);
|
|
194
|
+
const base = {
|
|
195
|
+
type: 'turn_end' as const,
|
|
196
|
+
...(stopReason === undefined ? {} : { stopReason }),
|
|
197
|
+
...(finalText === undefined ? {} : { text: finalText }),
|
|
198
|
+
usageComplete: emit.usageComplete ?? true,
|
|
199
|
+
};
|
|
200
|
+
if (status === 'completed') return { ...base, status };
|
|
201
|
+
const message = text(emit.failureMessage) ?? finalText ?? stopReason ?? 'the harness reported a failed turn';
|
|
202
|
+
const declared = text(emit.failureKind);
|
|
203
|
+
const kind = (FAILURE_KINDS as readonly string[]).includes(declared ?? '')
|
|
204
|
+
? (declared as FailureKind)
|
|
205
|
+
: classifyFailure(this.manifest.failures, message, this.stderrTail());
|
|
206
|
+
return { ...base, status, failure: { kind, message } };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The running usage total of one session, carried across the processes that continue it. */
|
|
211
|
+
class SessionUsage {
|
|
212
|
+
private totals: TokenCounts | undefined;
|
|
213
|
+
private reports = 0;
|
|
214
|
+
|
|
215
|
+
constructor(private readonly semantics: UsageSemantics) {}
|
|
216
|
+
|
|
217
|
+
restartTotals(): void {
|
|
218
|
+
this.totals = undefined;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The usage event of one report, or undefined when none of the declared counts resolves to
|
|
223
|
+
* a number (a renamed field): that report is unreported usage, not zero tokens.
|
|
224
|
+
*/
|
|
225
|
+
toEvent(emit: UsageEmit, line: unknown, item: unknown): UsageEvent | undefined {
|
|
226
|
+
const specs = [emit.input, emit.output, emit.cacheRead, emit.cacheWrite, emit.reasoning];
|
|
227
|
+
if (!specs.some((spec) => typeof resolveValue(spec, line, item) === 'number')) return undefined;
|
|
228
|
+
this.reports += 1;
|
|
229
|
+
const counts = this.nextCounts(emit, line, item);
|
|
230
|
+
const key = resolveValue(emit.key, line, item);
|
|
231
|
+
const model = resolveValue(emit.model, line, item);
|
|
232
|
+
const costUsd = resolveValue(emit.costUsd, line, item);
|
|
233
|
+
return {
|
|
234
|
+
type: 'usage',
|
|
235
|
+
key: typeof key === 'number' || (typeof key === 'string' && key !== '') ? String(key) : `report-${this.reports}`,
|
|
236
|
+
...(typeof model === 'string' ? { model } : {}),
|
|
237
|
+
input: counts.input,
|
|
238
|
+
output: counts.output,
|
|
239
|
+
cacheRead: counts.cacheRead,
|
|
240
|
+
...(emit.cacheWrite === undefined ? {} : { cacheWrite: counts.cacheWrite }),
|
|
241
|
+
...(emit.reasoning === undefined ? {} : { reasoning: counts.reasoning }),
|
|
242
|
+
...(typeof costUsd === 'number' && costUsd >= 0 ? { costUsd } : {}),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private nextCounts(emit: UsageEmit, line: unknown, item: unknown): TokenCounts {
|
|
247
|
+
const cumulative = this.semantics.mode === 'cumulative';
|
|
248
|
+
const previous = cumulative ? this.totals : undefined;
|
|
249
|
+
const count = (spec: ValueSpec | undefined, name: keyof TokenCounts): number =>
|
|
250
|
+
reportedCount(resolveValue(spec, line, item), previous?.[name]);
|
|
251
|
+
const reported: TokenCounts = {
|
|
252
|
+
input: count(emit.input, 'input'),
|
|
253
|
+
output: count(emit.output, 'output'),
|
|
254
|
+
cacheRead: count(emit.cacheRead, 'cacheRead'),
|
|
255
|
+
cacheWrite: count(emit.cacheWrite, 'cacheWrite'),
|
|
256
|
+
reasoning: count(emit.reasoning, 'reasoning'),
|
|
257
|
+
};
|
|
258
|
+
// Normalized before the subtraction: a running total keeps the harness's own meaning.
|
|
259
|
+
const counts = normalizeCounts(reported, this.semantics);
|
|
260
|
+
if (!cumulative) return counts;
|
|
261
|
+
this.totals = reported;
|
|
262
|
+
return previous === undefined ? counts : subtractCounts(counts, normalizeCounts(previous, this.semantics));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* A count the report omits is unreported: a running total keeps its last value, so that the
|
|
268
|
+
* count's next report is not differenced from zero.
|
|
269
|
+
*/
|
|
270
|
+
function reportedCount(value: unknown, previous: number | undefined): number {
|
|
271
|
+
if (typeof value !== 'number') return previous ?? 0;
|
|
272
|
+
return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function textOf(value: unknown): string | undefined {
|
|
276
|
+
if (typeof value === 'string') return value;
|
|
277
|
+
return value === undefined || value === null ? undefined : JSON.stringify(value);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The kind of a failure the harness did not classify: every pattern is tried on the failure
|
|
282
|
+
* message followed by the end of standard error, and the match that starts latest decides
|
|
283
|
+
* (the last thing reported is the failure that ended the turn); `unknown` when none matches.
|
|
284
|
+
*/
|
|
285
|
+
export function classifyFailure(failures: Manifest['failures'], message: string, stderrTail: string): FailureKind {
|
|
286
|
+
const text = `${message}\n${stderrTail}`;
|
|
287
|
+
let best: { start: number; kind: FailureKind } | undefined;
|
|
288
|
+
for (const { pattern, kind } of failures ?? []) {
|
|
289
|
+
const start = patternLastMatchStart(pattern, text);
|
|
290
|
+
if (start !== undefined && (best === undefined || start >= best.start)) best = { start, kind };
|
|
291
|
+
}
|
|
292
|
+
return best?.kind ?? 'unknown';
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function parseObject(rawLine: string): unknown {
|
|
296
|
+
const trimmed = rawLine.trim();
|
|
297
|
+
if (!trimmed.startsWith('{')) return undefined;
|
|
298
|
+
try {
|
|
299
|
+
return JSON.parse(trimmed) as unknown;
|
|
300
|
+
} catch {
|
|
301
|
+
return undefined;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function ruleApplies(rule: MappingRule, line: unknown): boolean {
|
|
306
|
+
return matches(rule.match, line) && (rule.unless === undefined || !matches(rule.unless, line));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function itemsOf(rule: MappingRule, line: unknown): unknown[] {
|
|
310
|
+
if (rule.each === undefined) return [undefined];
|
|
311
|
+
const list = resolvePointer(line, rule.each);
|
|
312
|
+
if (!Array.isArray(list)) return [];
|
|
313
|
+
return list.filter((item: unknown) => matches(rule.itemMatch, item));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function matches(match: MappingRule['match'], document: unknown): boolean {
|
|
317
|
+
for (const [pointer, expected] of Object.entries(match ?? {})) {
|
|
318
|
+
const actual = resolvePointer(document, pointer);
|
|
319
|
+
const allowed: readonly Scalar[] = Array.isArray(expected) ? expected : [expected as Scalar];
|
|
320
|
+
if (!allowed.includes(actual as Scalar)) return false;
|
|
321
|
+
}
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function resolveValue(spec: ValueSpec | undefined, line: unknown, item: unknown): unknown {
|
|
326
|
+
if (spec === undefined) return undefined;
|
|
327
|
+
if (spec === null || typeof spec !== 'object') return spec;
|
|
328
|
+
const value = 'from' in spec ? resolvePointer(line, spec.from) : resolvePointer(item, spec.fromItem);
|
|
329
|
+
const scalar = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
|
|
330
|
+
if (spec.map !== undefined && scalar && Object.hasOwn(spec.map, String(value))) return spec.map[String(value)];
|
|
331
|
+
// The default replaces what a map does not list (an object or array included) and an absent
|
|
332
|
+
// value, which JSON's null is too.
|
|
333
|
+
const unlisted = spec.map !== undefined || value === undefined || value === null;
|
|
334
|
+
return unlisted && spec.default !== undefined ? spec.default : value;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function subtractCounts(current: TokenCounts, previous: TokenCounts): TokenCounts {
|
|
338
|
+
return {
|
|
339
|
+
input: difference(current.input, previous.input),
|
|
340
|
+
output: difference(current.output, previous.output),
|
|
341
|
+
cacheRead: difference(current.cacheRead, previous.cacheRead),
|
|
342
|
+
cacheWrite: difference(current.cacheWrite, previous.cacheWrite),
|
|
343
|
+
reasoning: difference(current.reasoning, previous.reasoning),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function difference(now: number, before: number): number {
|
|
348
|
+
return Math.max(0, now - before);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function normalizeCounts(counts: TokenCounts, semantics: UsageSemantics): TokenCounts {
|
|
352
|
+
let { input, output } = counts;
|
|
353
|
+
if (semantics.inputIncludesCacheRead === true) input -= counts.cacheRead;
|
|
354
|
+
if (semantics.inputIncludesCacheWrite === true) input -= counts.cacheWrite;
|
|
355
|
+
if (semantics.outputIncludesReasoning === false) output += counts.reasoning;
|
|
356
|
+
return { ...counts, input: Math.max(0, input), output };
|
|
357
|
+
}
|
package/src/pattern.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { RE2JS } from 're2js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A manifest's regular expressions run against vendor output the manifest's author does not
|
|
6
|
+
* control, so they must match in linear time. RE2 guarantees that and has no backreferences
|
|
7
|
+
* or lookaround, so compiling a pattern with it is the whole check.
|
|
8
|
+
*/
|
|
9
|
+
export const patternSchema = z
|
|
10
|
+
.string()
|
|
11
|
+
.min(1)
|
|
12
|
+
.superRefine((source, context) => {
|
|
13
|
+
try {
|
|
14
|
+
RE2JS.compile(source);
|
|
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
|
+
|
|
23
|
+
const compiled = new Map<string, RE2JS>();
|
|
24
|
+
|
|
25
|
+
function compile(source: string): RE2JS {
|
|
26
|
+
let pattern = compiled.get(source);
|
|
27
|
+
if (pattern === undefined) {
|
|
28
|
+
pattern = RE2JS.compile(source);
|
|
29
|
+
compiled.set(source, pattern);
|
|
30
|
+
}
|
|
31
|
+
return pattern;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function patternMatches(source: string, text: string): boolean {
|
|
35
|
+
return compile(source).matcher(text).find();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The first capture group of the first match, or the whole match when the pattern has no group. */
|
|
39
|
+
export function patternCapture(source: string, text: string): string | undefined {
|
|
40
|
+
const matcher = compile(source).matcher(text);
|
|
41
|
+
if (!matcher.find()) return undefined;
|
|
42
|
+
return (matcher.groupCount() > 0 ? matcher.group(1) : matcher.group(0)) ?? undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The latest position in the text at which the pattern matches, or undefined when it never
|
|
47
|
+
* matches. One match behind a greedy prefix finds it: repeating `find` would rescan the rest
|
|
48
|
+
* of the text after every match, which is quadratic.
|
|
49
|
+
*/
|
|
50
|
+
export function patternLastMatchStart(source: string, text: string): number | undefined {
|
|
51
|
+
const matcher = compile(`(?s:.*)(${source})`).matcher(text);
|
|
52
|
+
return matcher.find() ? matcher.start(1) : undefined;
|
|
53
|
+
}
|
package/src/template.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The variables a manifest template may read. A manifest holds no code: a template only
|
|
5
|
+
* substitutes these, adds arguments when one has a value, expands a list, and applies the
|
|
6
|
+
* `json` and `toml` filters.
|
|
7
|
+
*/
|
|
8
|
+
export const TEMPLATE_VARIABLES = [
|
|
9
|
+
'prompt',
|
|
10
|
+
'model',
|
|
11
|
+
'effort',
|
|
12
|
+
'sessionId',
|
|
13
|
+
'deadlineMinutes',
|
|
14
|
+
'logFile',
|
|
15
|
+
'scratchDir',
|
|
16
|
+
'tmpDir',
|
|
17
|
+
'writableDirs',
|
|
18
|
+
] as const;
|
|
19
|
+
export type TemplateVariable = (typeof TEMPLATE_VARIABLES)[number];
|
|
20
|
+
|
|
21
|
+
export interface TemplateValues {
|
|
22
|
+
prompt: string;
|
|
23
|
+
model?: string;
|
|
24
|
+
effort?: string;
|
|
25
|
+
sessionId?: string;
|
|
26
|
+
deadlineMinutes?: number;
|
|
27
|
+
logFile?: string;
|
|
28
|
+
scratchDir?: string;
|
|
29
|
+
/** The temporary directory a sandboxed harness may write: its `TMPDIR`. */
|
|
30
|
+
tmpDir?: string;
|
|
31
|
+
writableDirs?: readonly string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The variables that hold a list: only `each` or a filter renders one. */
|
|
35
|
+
const LIST_VARIABLES = ['writableDirs'] as const satisfies readonly TemplateVariable[];
|
|
36
|
+
type ListVariable = (typeof LIST_VARIABLES)[number];
|
|
37
|
+
|
|
38
|
+
const FILTERS = ['json', 'toml'] as const;
|
|
39
|
+
type Filter = (typeof FILTERS)[number];
|
|
40
|
+
|
|
41
|
+
const PLACEHOLDER = /\{\{\s*([A-Za-z]+)\s*(?:\|\s*([A-Za-z]+)\s*)?\}\}/g;
|
|
42
|
+
// Only the opening pair: JSON text closes nested objects with `}}` and never opens one with `{{`.
|
|
43
|
+
const UNMATCHED_OPENING = /\{\{/;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A string whose `{{var}}` and `{{var | filter}}` placeholders can be rendered: they name known
|
|
47
|
+
* variables and filters, and a list variable goes through a filter.
|
|
48
|
+
*/
|
|
49
|
+
export const templateStringSchema = templateSchema(false);
|
|
50
|
+
|
|
51
|
+
const variableSchema = z.enum(TEMPLATE_VARIABLES);
|
|
52
|
+
|
|
53
|
+
export type ArgTemplate =
|
|
54
|
+
| string
|
|
55
|
+
| { when: TemplateVariable; args: ArgTemplate[] }
|
|
56
|
+
| { each: ListVariable; args: ArgTemplate[] };
|
|
57
|
+
|
|
58
|
+
/** Argument templates; `{{item}}` is the element of the enclosing `each` and is rejected outside one. */
|
|
59
|
+
export const argTemplateSchema = argSchema(false);
|
|
60
|
+
|
|
61
|
+
function argSchema(insideEach: boolean): z.ZodType<ArgTemplate> {
|
|
62
|
+
const schema: z.ZodType<ArgTemplate> = z.lazy(() =>
|
|
63
|
+
z.union([
|
|
64
|
+
templateSchema(insideEach),
|
|
65
|
+
z.strictObject({ when: variableSchema, args: z.array(schema).min(1) }),
|
|
66
|
+
z.strictObject({ each: z.enum(LIST_VARIABLES), args: z.array(argSchema(true)).min(1) }),
|
|
67
|
+
])
|
|
68
|
+
);
|
|
69
|
+
return schema;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function templateSchema(allowItem: boolean): z.ZodType<string> {
|
|
73
|
+
return z.string().superRefine((value, context) => {
|
|
74
|
+
for (const problem of templateProblems(value, allowItem)) context.addIssue({ code: 'custom', message: problem });
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Renders one template string. Throws when it reads a variable that has no value: an
|
|
80
|
+
* argument that depends on an optional variable belongs under `when`.
|
|
81
|
+
*/
|
|
82
|
+
export function renderTemplate(template: string, values: TemplateValues, item?: string): string {
|
|
83
|
+
return template.replaceAll(PLACEHOLDER, (_match, name: string, filter: string | undefined) => {
|
|
84
|
+
const value = name === 'item' ? item : (values as unknown as Record<string, unknown>)[name];
|
|
85
|
+
if (value === undefined) throw new Error(`the template reads "${name}", which has no value here`);
|
|
86
|
+
return applyFilter(value, filter as Filter | undefined);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Expands argument templates into the argument vector, in order. */
|
|
91
|
+
export function renderArgs(templates: readonly ArgTemplate[], values: TemplateValues, item?: string): string[] {
|
|
92
|
+
return templates.flatMap((template) => {
|
|
93
|
+
if (typeof template === 'string') return [renderTemplate(template, values, item)];
|
|
94
|
+
if ('when' in template) {
|
|
95
|
+
return hasValue(values[template.when]) ? renderArgs(template.args, values, item) : [];
|
|
96
|
+
}
|
|
97
|
+
const list = values[template.each];
|
|
98
|
+
if (list === undefined) return [];
|
|
99
|
+
if (!Array.isArray(list)) throw new Error(`"each" needs a list, and "${template.each}" is not one`);
|
|
100
|
+
return (list as readonly string[]).flatMap((element) => renderArgs(template.args, values, element));
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function hasValue(value: unknown): boolean {
|
|
105
|
+
return value !== undefined && value !== '' && !(Array.isArray(value) && value.length === 0);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function applyFilter(value: unknown, filter: Filter | undefined): string {
|
|
109
|
+
if (filter === 'json') return JSON.stringify(value);
|
|
110
|
+
if (filter === 'toml') return tomlValue(value);
|
|
111
|
+
if (Array.isArray(value)) throw new Error('a list is rendered through "each" or a filter');
|
|
112
|
+
return String(value);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// TOML basic strings share JSON's escapes for every character JSON.stringify escapes, and
|
|
116
|
+
// TOML arrays of strings and numbers are written as JSON writes them.
|
|
117
|
+
function tomlValue(value: unknown): string {
|
|
118
|
+
return JSON.stringify(value);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function templateProblems(value: string, allowItem: boolean): string[] {
|
|
122
|
+
const problems: string[] = [];
|
|
123
|
+
for (const match of value.matchAll(PLACEHOLDER)) {
|
|
124
|
+
const [, name, filter] = match;
|
|
125
|
+
if (name === 'item') {
|
|
126
|
+
if (!allowItem) problems.push('"{{item}}" has a value only inside "each"');
|
|
127
|
+
} else if (!(TEMPLATE_VARIABLES as readonly string[]).includes(name ?? '')) {
|
|
128
|
+
problems.push(`unknown template variable "${name}"`);
|
|
129
|
+
} else if (filter === undefined && (LIST_VARIABLES as readonly string[]).includes(name ?? '')) {
|
|
130
|
+
problems.push(`the list "${name}" is rendered through "each" or a filter`);
|
|
131
|
+
}
|
|
132
|
+
if (filter !== undefined && !(FILTERS as readonly string[]).includes(filter)) {
|
|
133
|
+
problems.push(`unknown template filter "${filter}"`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (UNMATCHED_OPENING.test(value.replaceAll(PLACEHOLDER, ''))) problems.push('malformed template placeholder');
|
|
137
|
+
return problems;
|
|
138
|
+
}
|