@wyattjoh/rfc 0.3.1 → 0.4.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/operations.ts CHANGED
@@ -8,13 +8,13 @@ import {
8
8
  type CitationVerificationRequest,
9
9
  type CitationVerificationResult,
10
10
  type ErrorEnvelope,
11
- type EvidenceBundle,
12
11
  type ResearchRequest,
12
+ type ResearchResult,
13
13
  type RfcClient,
14
14
  type RfcSourceCacheRemoveResult,
15
15
  type RfcSourceCacheStatus,
16
16
  } from "@wyattjoh/rfc-core";
17
- import { automaticAnswerActivationFor, readCliConfig } from "./config";
17
+ import { readCliConfig } from "./config";
18
18
  import {
19
19
  CredentialInputError,
20
20
  CredentialMissingError,
@@ -27,12 +27,14 @@ import {
27
27
  import type { UsageRecorder } from "./usage-store";
28
28
 
29
29
  export {
30
+ citationVerificationAgentJson,
30
31
  renderAuthStatus,
31
32
  renderCitationVerification,
32
33
  renderEstimatedUsd,
33
- renderEvidenceBundle,
34
+ renderResearchResult,
34
35
  renderSourceCacheRemove,
35
36
  renderSourceCacheStatus,
37
+ researchResultAgentJson,
36
38
  } from "./renderers";
37
39
 
38
40
  /**
@@ -51,6 +53,16 @@ export interface RfcOperationOptions {
51
53
  * Optional TypeSafe API URL selected by the process operator.
52
54
  */
53
55
  readonly typeSafeApiUrl: string | undefined;
56
+ /**
57
+ * Optional RFC full-text search API base URL selected by the process operator.
58
+ */
59
+ readonly rfcSearchApiUrl: string | undefined;
60
+ /**
61
+ * Optional search-only key enabling full-text topic discovery.
62
+ *
63
+ * Topic discovery stays on Datatracker titles and abstracts without it.
64
+ */
65
+ readonly rfcSearchApiKey: string | undefined;
54
66
  }
55
67
 
56
68
  /**
@@ -196,10 +208,10 @@ const createSemanticClient = async (
196
208
  cacheDirectory: options.cacheDirectory,
197
209
  datatrackerApiUrl: options.datatrackerApiUrl,
198
210
  modelAlias: cliConfig.modelAlias,
199
- policyPreset: cliConfig.policyPreset,
200
- automaticAnswerActivation: automaticAnswerActivationFor(cliConfig),
201
211
  typeSafeApiKey: apiKey,
202
212
  typeSafeApiUrl: options.typeSafeApiUrl,
213
+ rfcSearchApiUrl: options.rfcSearchApiUrl,
214
+ rfcSearchApiKey: options.rfcSearchApiKey,
203
215
  });
204
216
  };
205
217
 
@@ -226,18 +238,18 @@ export const toRfcOperationErrorEnvelope = (error: unknown): ErrorEnvelope =>
226
238
  credentialErrorEnvelope(error) ?? toErrorEnvelope(error);
227
239
 
228
240
  /**
229
- * Research one validated known-RFC or topic request.
241
+ * Research one validated request against named RFCs, topic terms, or both.
230
242
  *
231
- * @param request Unknown input decoded through the public version-two request schema.
243
+ * @param request Unknown input decoded through the public version-three request schema.
232
244
  * @param options Trusted process configuration.
233
245
  * @param dependencies Injectable operation boundaries.
234
- * @returns The evidence bundle and any non-fatal usage warning.
246
+ * @returns The research result and any non-fatal usage warning.
235
247
  */
236
248
  export const executeResearch = async (
237
249
  request: ResearchRequest | unknown,
238
250
  options: RfcOperationOptions,
239
251
  dependencies: RfcOperationDependencies,
240
- ): Promise<RfcOperationResult<EvidenceBundle>> => {
252
+ ): Promise<RfcOperationResult<ResearchResult>> => {
241
253
  const decoded = decodeResearchRequest(request);
242
254
  const value = await withClient(
243
255
  () => createSemanticClient(options, dependencies),
@@ -256,7 +268,7 @@ export const executeResearch = async (
256
268
  /**
257
269
  * Verify one validated factual claim against one exact RFC quotation.
258
270
  *
259
- * @param request Unknown input decoded through the public version-two citation schema.
271
+ * @param request Unknown input decoded through the public version-three citation schema.
260
272
  * @param options Trusted process configuration.
261
273
  * @param dependencies Injectable operation boundaries.
262
274
  * @returns The citation verdict and any non-fatal usage warning.
@@ -299,7 +311,6 @@ export const executeSourceCacheStatus = (
299
311
  dependencies.createClient({
300
312
  cacheDirectory: options.cacheDirectory,
301
313
  modelAlias: undefined,
302
- automaticAnswerActivation: undefined,
303
314
  typeSafeApiKey: undefined,
304
315
  typeSafeApiUrl: undefined,
305
316
  }),
@@ -324,7 +335,6 @@ export const executeSourceCacheRemove = (
324
335
  dependencies.createClient({
325
336
  cacheDirectory: options.cacheDirectory,
326
337
  modelAlias: undefined,
327
- automaticAnswerActivation: undefined,
328
338
  typeSafeApiKey: undefined,
329
339
  typeSafeApiUrl: undefined,
330
340
  }),
package/src/renderers.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import type {
2
2
  CitationVerificationResult,
3
- EvidenceBundle,
3
+ Passage,
4
+ ResearchAnswer,
5
+ ResearchHit,
6
+ ResearchResult,
4
7
  RfcSourceCacheRemoveResult,
5
8
  RfcSourceCacheStatus,
6
9
  } from "@wyattjoh/rfc-core";
@@ -18,49 +21,180 @@ export const renderEstimatedUsd = (value: number | null): string =>
18
21
  value === null ? "unavailable" : `$${value.toFixed(9)}`;
19
22
 
20
23
  /**
21
- * Render one evidence bundle for concise agent or human consumption.
22
- *
23
- * @param result Version-two evidence bundle.
24
- * @returns Multi-line text preserving statuses, qualifications, provenance, and cost.
24
+ * Who reads rendered text: a model through MCP or Pi, or a person at the CLI.
25
25
  */
26
- export const renderEvidenceBundle = (result: EvidenceBundle): string => {
27
- const lines = [`Status: ${result.status}`, `RFC: ${result.rfc?.identifier ?? "none discovered"}`];
28
- for (const context of result.contexts ?? []) {
29
- lines.push(`Context: ${context.role} ${context.document.identifier} (${context.state})`);
30
- }
31
- for (const passage of result.evidence) {
32
- lines.push(
33
- `Evidence RFC: ${passage.provenance.identifier} (${passage.context} context)`,
34
- `Section: ${passage.provenance.section ?? "unknown"}`,
35
- `Quote: ${passage.quote}`,
36
- `Source: ${passage.provenance.sourceUrl}`,
37
- `Offsets: ${passage.provenance.startOffset}-${passage.provenance.endOffset} (${passage.provenance.offsetUnit})`,
38
- );
39
- }
40
- for (const candidate of result.reviewCandidates ?? []) {
41
- lines.push(
42
- "Review candidate: not accepted evidence",
43
- `Candidate RFC: ${candidate.provenance.identifier} (${candidate.context} context)`,
44
- `Section: ${candidate.provenance.section ?? "unknown"}`,
45
- `Quote: ${candidate.quote}`,
46
- `Source: ${candidate.provenance.sourceUrl}`,
47
- `Offsets: ${candidate.provenance.startOffset}-${candidate.provenance.endOffset} (${candidate.provenance.offsetUnit})`,
48
- );
49
- }
50
- lines.push(
51
- `Input tokens: ${renderTokenCount(result.diagnostics.usage.inputTokens)}`,
52
- `Estimated input cost (USD): ${renderEstimatedUsd(result.diagnostics.inputCost.estimatedUsd)}`,
53
- );
54
- return lines.join("\n");
26
+ export type RenderAudience = "agent" | "human";
27
+
28
+ /**
29
+ * Options shared by the research and citation renderers.
30
+ */
31
+ export type RenderOptions = {
32
+ /**
33
+ * `agent` renders the compact layout; `human` adds source URLs and a usage
34
+ * and cost footer.
35
+ */
36
+ readonly audience: RenderAudience;
37
+ };
38
+
39
+ const humanAudience: RenderOptions = { audience: "human" };
40
+
41
+ /**
42
+ * Render a section heading as `§4.2 Title`, or the bare heading when unnumbered.
43
+ */
44
+ const renderSection = (section: string | null): string => {
45
+ if (section === null) return "front matter";
46
+ const heading = section.replace(/\s+/g, " ").trim();
47
+ const match = /^(?:Appendix )?((?:\d+|[A-Z])(?:\.\d+)*)\.? (.+)$/.exec(heading);
48
+ return match === null ? heading : `§${match[1]} ${match[2]}`;
55
49
  };
56
50
 
51
+ const renderPassage = (hit: ResearchHit, passage: Passage): ReadonlyArray<string> => [
52
+ [
53
+ `${hit.rfc.identifier} ${renderSection(passage.section)}`,
54
+ passage.verdict,
55
+ ...(hit.relevance === null ? [] : [`rel ${hit.relevance.toFixed(2)}`]),
56
+ ...(hit.role === "current" ? ["current successor"] : []),
57
+ ].join(" · "),
58
+ `Quote [${passage.provenance.startOffset}-${passage.provenance.endOffset}]: ${passage.quote}`,
59
+ ];
60
+
61
+ const renderNotFound = (answer: ResearchAnswer, result: ResearchResult): string =>
62
+ answer.searched.length > 0
63
+ ? `not found in ${answer.searched.join(", ")}`
64
+ : result.diagnostics.candidates.pool === 0
65
+ ? "not found: no RFC title or abstract matched the search terms"
66
+ : `not found: none of ${result.diagnostics.candidates.pool} candidate RFCs specifies this`;
67
+
68
+ const renderCurrency = (result: ResearchResult): ReadonlyArray<string> =>
69
+ (result.currency ?? []).flatMap((report) =>
70
+ report.complete && report.current.length === 1 && report.current[0] === report.requested
71
+ ? []
72
+ : [
73
+ `Currency: ${report.requested} → ${
74
+ report.current.length === 0 ? "current RFC unresolved" : report.current.join(", ")
75
+ }${report.complete ? "" : " (incomplete: some successors were not fetched)"}`,
76
+ ],
77
+ );
78
+
79
+ const sourceLines = (answer: ResearchAnswer): ReadonlyArray<string> => [
80
+ ...new Set(
81
+ answer.hits.flatMap((hit) =>
82
+ hit.passages.map(({ provenance }) => `Source: ${hit.rfc.identifier} ${provenance.sourceUrl}`),
83
+ ),
84
+ ),
85
+ ];
86
+
87
+ /**
88
+ * Render one research result: per question, one line per passage naming the
89
+ * RFC, section, verdict, and relevance, then the exact quote with its UTF-8
90
+ * byte range, or the RFCs that did not contain an answer.
91
+ *
92
+ * @param result Version-three research result.
93
+ * @param options Target audience; defaults to the human CLI format.
94
+ * @returns Multi-line text, plus source URLs, usage, and cost for a human reader.
95
+ */
96
+ export const renderResearchResult = (
97
+ result: ResearchResult,
98
+ options: RenderOptions = humanAudience,
99
+ ): string =>
100
+ [
101
+ ...renderCurrency(result),
102
+ ...result.answers.flatMap((answer, index) => [
103
+ `Q${index + 1}: ${answer.question}`,
104
+ ...(answer.found
105
+ ? answer.hits.flatMap((hit) =>
106
+ hit.passages.flatMap((passage) => renderPassage(hit, passage)),
107
+ )
108
+ : [renderNotFound(answer, result)]),
109
+ ...(options.audience === "human" ? sourceLines(answer) : []),
110
+ ]),
111
+ ...(options.audience === "human"
112
+ ? [
113
+ `Input tokens: ${renderTokenCount(result.diagnostics.usage.inputTokens)}`,
114
+ `Estimated input cost (USD): ${renderEstimatedUsd(result.diagnostics.inputCost.estimatedUsd)}`,
115
+ ]
116
+ : []),
117
+ ].join("\n");
118
+
119
+ /**
120
+ * Project a research result onto the compact JSON an agent reads.
121
+ *
122
+ * Keeps per-question hits, verdicts, sections, exact quotes, and UTF-8 byte
123
+ * ranges, plus any non-trivial currency report. Answers are positional:
124
+ * `answers[i]` answers the caller's `questions[i]`, so the question text the
125
+ * agent just sent is not echoed back. Diagnostics, source hashes,
126
+ * and retrieval traces stay in the full structured result.
127
+ *
128
+ * @param result Version-three research result.
129
+ * @returns Single-line JSON text.
130
+ */
131
+ export const researchResultAgentJson = (result: ResearchResult): string =>
132
+ JSON.stringify({
133
+ answers: result.answers.map((answer) => ({
134
+ found: answer.found,
135
+ ...(answer.found
136
+ ? {}
137
+ : {
138
+ searched: answer.searched,
139
+ ...(answer.searched.length === 0
140
+ ? { candidateRfcs: result.diagnostics.candidates.pool }
141
+ : {}),
142
+ }),
143
+ hits: answer.hits.map((hit) => ({
144
+ rfc: hit.rfc.identifier,
145
+ title: hit.rfc.title,
146
+ role: hit.role,
147
+ relevance: hit.relevance === null ? null : Number(hit.relevance.toFixed(2)),
148
+ verdict: hit.verdict,
149
+ passages: hit.passages.map((passage) => ({
150
+ section: renderSection(passage.section),
151
+ verdict: passage.verdict,
152
+ quote: passage.quote,
153
+ bytes: [passage.provenance.startOffset, passage.provenance.endOffset],
154
+ })),
155
+ })),
156
+ })),
157
+ ...(result.currency === undefined
158
+ ? {}
159
+ : {
160
+ currency: result.currency
161
+ .filter(
162
+ (report) =>
163
+ !report.complete ||
164
+ report.current.length !== 1 ||
165
+ report.current[0] !== report.requested,
166
+ )
167
+ .map(({ requested, current, complete }) => ({ requested, current, complete })),
168
+ }),
169
+ });
170
+
171
+ /**
172
+ * Project a citation verdict onto the compact JSON an agent reads.
173
+ *
174
+ * @param result Version-three citation verdict.
175
+ * @returns Single-line JSON text without diagnostics.
176
+ */
177
+ export const citationVerificationAgentJson = (result: CitationVerificationResult): string =>
178
+ JSON.stringify({
179
+ verdict: result.verdict,
180
+ rfc: result.rfc.identifier,
181
+ section: renderSection(result.provenance.section),
182
+ quote: result.quote,
183
+ bytes: [result.provenance.startOffset, result.provenance.endOffset],
184
+ });
185
+
57
186
  /**
58
187
  * Render one citation-verification result for concise agent or human consumption.
59
188
  *
60
- * @param result Version-two citation verdict.
61
- * @returns Multi-line text preserving verdict, provenance, and cost.
189
+ * @param result Version-three citation verdict.
190
+ * @param options Target audience; defaults to the human CLI format.
191
+ * @returns Multi-line text preserving verdict and provenance, plus usage and
192
+ * cost for a human reader.
62
193
  */
63
- export const renderCitationVerification = (result: CitationVerificationResult): string =>
194
+ export const renderCitationVerification = (
195
+ result: CitationVerificationResult,
196
+ options: RenderOptions = humanAudience,
197
+ ): string =>
64
198
  [
65
199
  `Verdict: ${result.verdict}`,
66
200
  `RFC: ${result.rfc.identifier}`,
@@ -68,14 +202,18 @@ export const renderCitationVerification = (result: CitationVerificationResult):
68
202
  `Offsets: ${result.provenance.startOffset ?? "unknown"}-${result.provenance.endOffset ?? "unknown"}`,
69
203
  `Section: ${result.provenance.section ?? "unknown"}`,
70
204
  `Source: ${result.provenance.sourceUrl}`,
71
- `Input tokens: ${renderTokenCount(result.diagnostics.usage.inputTokens)}`,
72
- `Estimated input cost (USD): ${renderEstimatedUsd(result.diagnostics.inputCost.estimatedUsd)}`,
205
+ ...(options.audience === "agent"
206
+ ? []
207
+ : [
208
+ `Input tokens: ${renderTokenCount(result.diagnostics.usage.inputTokens)}`,
209
+ `Estimated input cost (USD): ${renderEstimatedUsd(result.diagnostics.inputCost.estimatedUsd)}`,
210
+ ]),
73
211
  ].join("\n");
74
212
 
75
213
  /**
76
214
  * Render one local source-cache status.
77
215
  *
78
- * @param result Version-two source-cache status.
216
+ * @param result Version-three source-cache status.
79
217
  * @returns Concise multi-line status text.
80
218
  */
81
219
  export const renderSourceCacheStatus = (result: RfcSourceCacheStatus): string =>
@@ -84,7 +222,7 @@ export const renderSourceCacheStatus = (result: RfcSourceCacheStatus): string =>
84
222
  /**
85
223
  * Render one local source-cache removal result.
86
224
  *
87
- * @param result Version-two source-cache removal result.
225
+ * @param result Version-three source-cache removal result.
88
226
  * @returns Concise multi-line removal text.
89
227
  */
90
228
  export const renderSourceCacheRemove = (result: RfcSourceCacheRemoveResult): string =>
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import { runLiveEvaluation } from "./live-evaluation";
4
- import { toCliErrorEnvelope } from "./main";
5
-
6
- try {
7
- // Invoking this dedicated binary is the explicit live-evaluation opt-in.
8
- process.exitCode = await runLiveEvaluation({
9
- credentialStore: undefined,
10
- enable: true,
11
- });
12
- } catch (error) {
13
- process.stderr.write(`${JSON.stringify(toCliErrorEnvelope(error))}\n`);
14
- process.exitCode = 1;
15
- }
@@ -1,215 +0,0 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
- import { dirname } from "node:path";
3
- import {
4
- ConfigurationError,
5
- evaluationCorpus,
6
- evaluationCorpusDigest,
7
- evaluationModelAlias,
8
- evaluationPolicy,
9
- evaluationReleaseAttestation,
10
- failedEvaluationObservation,
11
- observationFromCitationResult,
12
- observationFromEvidenceBundle,
13
- pinnedJevModel,
14
- runEvaluation,
15
- type EvaluationCase,
16
- type EvaluationReportOptions,
17
- } from "@wyattjoh/rfc-core";
18
- import { readCliConfig } from "./config";
19
- import {
20
- makeDefaultCredentialStore,
21
- resolveStoredCredential,
22
- type CredentialStore,
23
- } from "./credentials";
24
- import {
25
- createRfcCalibrationClient,
26
- evaluateDeterministicRetrievalCase,
27
- } from "../../rfc-core/src/internal-calibration";
28
-
29
- const liveCorpus = {
30
- ...evaluationCorpus,
31
- cases: evaluationCorpus.cases.filter((evaluationCase) => evaluationCase.live),
32
- };
33
-
34
- const liveEvaluationIterations = 3;
35
-
36
- const timedCorpus = {
37
- ...liveCorpus,
38
- cases: liveCorpus.cases.flatMap((evaluationCase) =>
39
- Array.from({ length: liveEvaluationIterations }, (_, iteration) => ({
40
- ...evaluationCase,
41
- id: `${evaluationCase.id}:iteration-${iteration + 1}`,
42
- })),
43
- ),
44
- };
45
-
46
- const researchRequestFor = (evaluationCase: EvaluationCase) => {
47
- if (evaluationCase.question === null) {
48
- throw new Error(`Research case ${evaluationCase.id} is missing a question`);
49
- }
50
- return evaluationCase.rfc === null
51
- ? {
52
- schemaVersion: 2 as const,
53
- question: evaluationCase.question,
54
- rfc: null,
55
- searchTerms: evaluationCase.searchTerms ?? ["HTTP client request message"],
56
- }
57
- : {
58
- schemaVersion: 2 as const,
59
- question: evaluationCase.question,
60
- rfc: evaluationCase.rfc,
61
- searchTerms: undefined,
62
- };
63
- };
64
-
65
- const citationRequestFor = (evaluationCase: EvaluationCase) => {
66
- if (
67
- evaluationCase.rfc === null ||
68
- evaluationCase.claim === null ||
69
- evaluationCase.quote === null
70
- ) {
71
- throw new Error(`Citation case ${evaluationCase.id} is incomplete`);
72
- }
73
- return {
74
- schemaVersion: 2 as const,
75
- rfc: evaluationCase.rfc,
76
- claim: evaluationCase.claim,
77
- quote: evaluationCase.quote,
78
- offset: evaluationCase.offset,
79
- };
80
- };
81
-
82
- const errorKind = (error: unknown): string => {
83
- if (typeof error === "object" && error !== null && "_tag" in error) {
84
- const tag = (error as { readonly _tag: unknown | undefined })._tag;
85
- if (typeof tag === "string" && tag.length > 0) return tag;
86
- }
87
- return "EvaluationOperationError";
88
- };
89
-
90
- /**
91
- * Injectable dependencies for the opt-in live evaluator.
92
- */
93
- export interface LiveEvaluationOptions {
94
- /**
95
- * Credential boundary shared with ordinary research and citation commands.
96
- */
97
- readonly credentialStore: CredentialStore | undefined;
98
- /**
99
- * Explicit command-level opt-in for a live provider run.
100
- */
101
- readonly enable: boolean | undefined;
102
- }
103
-
104
- const defaultLiveEvaluationOptions: LiveEvaluationOptions = {
105
- credentialStore: undefined,
106
- enable: true,
107
- };
108
-
109
- /**
110
- * Run the opt-in live TypeSafe calibration against authoritative RFC Editor sources.
111
- *
112
- * An untimed pass over every live case warms request-local source entries before
113
- * three sequential timed iterations. This preserves a bounded provider call
114
- * order while excluding cache warming from both p95 gates. The provider key is
115
- * resolved from the same injectable Bun.secrets boundary used by the CLI.
116
- *
117
- * @param options Explicit live-run opt-in and credential boundary.
118
- * @returns Zero when every precision, safety, latency, and model gate passes;
119
- * otherwise two.
120
- */
121
- export const runLiveEvaluation = async (
122
- runtimeOptions: LiveEvaluationOptions = defaultLiveEvaluationOptions,
123
- ): Promise<number> => {
124
- let config: ReturnType<typeof readCliConfig>;
125
- try {
126
- config = readCliConfig({
127
- liveEvaluation: runtimeOptions.enable,
128
- automaticAnswerEnabled: undefined,
129
- evaluationCacheDirectory: undefined,
130
- evaluationOutput: undefined,
131
- });
132
- } catch (error) {
133
- throw new ConfigurationError({
134
- reason:
135
- error instanceof Error ? error.message : "Unable to validate live evaluation configuration",
136
- });
137
- }
138
- if (!config.liveEvaluation) {
139
- throw new ConfigurationError({
140
- reason: "Live evaluation is disabled; pass the explicit live-evaluation opt-in",
141
- });
142
- }
143
- if (
144
- config.policyPreset !== evaluationPolicy.policyVersion ||
145
- config.evaluationModel !== evaluationModelAlias ||
146
- config.pinnedModel !== pinnedJevModel ||
147
- config.modelAlias !== pinnedJevModel
148
- ) {
149
- throw new ConfigurationError({
150
- reason: "Live calibration must use the committed precision policy and exact Jev pin",
151
- });
152
- }
153
-
154
- const reportOptions: EvaluationReportOptions = {
155
- origin: "live",
156
- releaseBuildId: evaluationReleaseAttestation.buildId,
157
- corpusDigest: evaluationCorpusDigest,
158
- createdAt: new Date().toISOString(),
159
- expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1_000).toISOString(),
160
- authoritativeSourceHashes: undefined,
161
- policyVersion: evaluationPolicy.policyVersion,
162
- requestedModel: evaluationModelAlias,
163
- pinnedModel: pinnedJevModel,
164
- minimumSupportedClaimPrecision: undefined,
165
- maxKnownRfcP95LatencyMilliseconds: undefined,
166
- maxTopicP95LatencyMilliseconds: undefined,
167
- };
168
- const apiKey = await resolveStoredCredential(
169
- runtimeOptions.credentialStore ?? makeDefaultCredentialStore(),
170
- );
171
- const client = await createRfcCalibrationClient({
172
- cacheDirectory: config.evaluationCacheDirectory,
173
- modelAlias: config.evaluationModel,
174
- policyPreset: config.policyPreset,
175
- typeSafeApiKey: apiKey,
176
- typeSafeApiUrl: undefined,
177
- });
178
-
179
- try {
180
- const evaluateCase = async (evaluationCase: EvaluationCase) => {
181
- try {
182
- if (evaluationCase.kind === "research") {
183
- const result = await client.research(researchRequestFor(evaluationCase));
184
- return observationFromEvidenceBundle(evaluationCase, result);
185
- }
186
- const result = await client.verifyCitation(citationRequestFor(evaluationCase));
187
- return observationFromCitationResult(evaluationCase, result);
188
- } catch (error) {
189
- return failedEvaluationObservation(evaluationCase, reportOptions, errorKind(error));
190
- }
191
- };
192
- const warmupObservations = [];
193
- for (const evaluationCase of liveCorpus.cases) {
194
- warmupObservations.push(await evaluateCase(evaluationCase));
195
- }
196
- if (warmupObservations.some((observation) => observation.errorKind !== null)) {
197
- throw new ConfigurationError({
198
- reason: "Live evaluation warm-up did not complete every corpus case",
199
- });
200
- }
201
- const report = await runEvaluation(
202
- timedCorpus,
203
- evaluateCase,
204
- evaluateDeterministicRetrievalCase,
205
- reportOptions,
206
- );
207
- const output = `${JSON.stringify(report, null, 2)}\n`;
208
- await mkdir(dirname(config.evaluationOutput), { recursive: true });
209
- await writeFile(config.evaluationOutput, output, "utf8");
210
- process.stdout.write(output);
211
- return report.gate.passed ? 0 : 2;
212
- } finally {
213
- await client.close();
214
- }
215
- };