@wyattjoh/rfc-pi 0.2.2 → 0.3.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/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # `@wyattjoh/rfc-pi`
2
2
 
3
- Native [Pi](https://pi.dev) integration for the RFC Evidence Engine. The package registers the six `rfc_*` tools, adds the bounded RFC lookup workflow to the system prompt, and includes the `/rfc-lookup` skill.
3
+ Native [Pi](https://pi.dev) integration for the RFC Evidence Engine. The package registers the `rfc_research` and `rfc_verify_citation` tools, adds the RFC lookup workflow to the system prompt, and includes the `/rfc-lookup` skill.
4
+
5
+ Tool results reach the model as compact JSON: per question, `found`, and ranked hits with RFC, title, role, relevance, verdict, and passages (`section`, `verdict`, exact `quote`, and UTF-8 `bytes` range). The complete version-three result, including diagnostics and provenance, stays in the tool result details.
4
6
 
5
7
  ## Install
6
8
 
@@ -17,6 +19,24 @@ bunx @wyattjoh/rfc@latest auth login
17
19
  bunx @wyattjoh/rfc@latest auth
18
20
  ```
19
21
 
20
- The extension runs `bunx @wyattjoh/rfc@latest` for each tool call. Credentials remain in the OS credential manager and are never exposed to Pi or accepted through tool input.
22
+ Each tool call runs the CLI through `bunx`, pinned to the exact `@wyattjoh/rfc` version this package depends on rather than a dist-tag, so a call never re-resolves against the registry and never runs a CLI this package was not tested against. Credentials remain in the OS credential manager and are never exposed to Pi or accepted through tool input.
23
+
24
+ ## Local cache and credential tools
25
+
26
+ `rfc_source_cache_status`, `rfc_source_cache_remove`, and `rfc_auth_status` are not registered by default, because research never needs them and every registered tool is resent to the model on each request. Set `RFC_PI_LOCAL_TOOLS=1` before starting Pi to register them:
27
+
28
+ ```sh
29
+ export RFC_PI_LOCAL_TOOLS=1
30
+ ```
31
+
32
+ ## Running a local CLI
33
+
34
+ Set `RFC_CLI_COMMAND` to exercise a working-tree CLI without publishing it. Accepts a JSON array for a command with arguments, or a bare executable path:
35
+
36
+ ```sh
37
+ export RFC_CLI_COMMAND='["bun","/path/to/rfc/packages/rfc/src/bin.ts"]'
38
+ ```
39
+
40
+ Unset, the pinned published package is used. The variable chooses an executable, so treat it the way you treat `PATH`.
21
41
 
22
42
  Review the package before installation: Pi extensions execute with the user's full system permissions.
package/extensions/rfc.ts CHANGED
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import type {
4
4
  CitationVerificationResult,
5
- EvidenceBundle,
5
+ ResearchResult,
6
6
  RfcSourceCacheRemoveResult,
7
7
  RfcSourceCacheStatus,
8
8
  } from "@wyattjoh/rfc-core";
@@ -10,42 +10,97 @@ import type { AuthStatus } from "@wyattjoh/rfc";
10
10
  import {
11
11
  datatrackerTopicSearchTermLimit,
12
12
  datatrackerTopicSearchTermMaximumCharacters,
13
- renderAuthStatus,
14
- renderCitationVerification,
15
- renderEvidenceBundle,
16
- renderSourceCacheRemove,
17
- renderSourceCacheStatus,
13
+ citationVerificationAgentJson,
14
+ researchResultAgentJson,
15
+ rfcAgentParameterDescriptions as descriptions,
18
16
  rfcAgentToolMetadata,
19
- rfcMcpInstructions,
17
+ rfcPiInstructions,
20
18
  schemaVersion,
21
19
  } from "@wyattjoh/rfc/agent";
20
+ import { retrievalPolicy } from "@wyattjoh/rfc-core";
22
21
  import { Type } from "typebox";
22
+ import rfcPiPackage from "../package.json" with { type: "json" };
23
23
 
24
- const rfcPackageSpec = "@wyattjoh/rfc@latest";
24
+ /**
25
+ * The CLI is pinned to the exact version this package depends on.
26
+ *
27
+ * A dist-tag would re-resolve against the registry on every tool call and could
28
+ * run a CLI this package was never tested against. `release-please`'s
29
+ * `node-workspace` plugin rewrites this dependency whenever the CLI is
30
+ * released, so the pin follows the published version without manual edits.
31
+ */
32
+ const rfcPackageSpec = `@wyattjoh/rfc@${rfcPiPackage.dependencies["@wyattjoh/rfc"]}`;
25
33
  const commandTimeoutMilliseconds = 180_000;
26
34
  const commandOutputMaximumBytes = 1024 * 1024;
35
+ const commandStderrMaximumCharacters = 2_000;
36
+ const commandFailureRetentionLimit = 32;
27
37
 
28
- const nonEmptyString = (description: string) => Type.String({ description, minLength: 1 });
38
+ /**
39
+ * Raw diagnostics from an RFC CLI process that exited non-zero.
40
+ */
41
+ type RfcCommandFailureDiagnostics = {
42
+ /**
43
+ * Process exit code, or null when the process was terminated by a signal.
44
+ */
45
+ readonly exitCode: number | null;
46
+ /**
47
+ * Bounded stderr text exactly as the CLI wrote it.
48
+ */
49
+ readonly stderr: string;
50
+ };
29
51
 
30
- const knownRfcResearchParameters = Type.Object(
31
- {
32
- question: nonEmptyString("One independently answerable RFC question"),
33
- rfc: nonEmptyString("Exact published RFC identifier, for example RFC9110"),
34
- },
35
- { additionalProperties: false },
36
- );
52
+ /**
53
+ * A non-zero RFC CLI exit, carrying the diagnostics that name its cause.
54
+ */
55
+ class RfcCommandFailure extends Error {
56
+ readonly diagnostics: RfcCommandFailureDiagnostics;
37
57
 
38
- const topicResearchParameters = Type.Object(
58
+ constructor(message: string, diagnostics: RfcCommandFailureDiagnostics) {
59
+ super(message);
60
+ this.name = "RfcCommandFailure";
61
+ this.diagnostics = diagnostics;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Diagnostics awaiting the `tool_result` hook, keyed by tool call.
67
+ *
68
+ * Pi replaces a thrown tool error with a result whose `details` is `{}`, so a
69
+ * throw alone destroys the exit code and stderr at the point of failure. The
70
+ * hook reattaches them to the recorded result without turning the failure into
71
+ * an apparent success.
72
+ */
73
+ const commandFailures = new Map<string, RfcCommandFailureDiagnostics>();
74
+
75
+ const nonEmptyString = (description: string) => Type.String({ description, minLength: 1 });
76
+
77
+ const researchParameters = Type.Object(
39
78
  {
40
- question: nonEmptyString("One independently answerable topic question"),
41
- searchTerms: Type.Array(
42
- Type.String({
43
- description:
44
- "Deliberate topic-discovery term sent verbatim in Datatracker query URLs and upstream logs",
45
- minLength: 1,
46
- maxLength: datatrackerTopicSearchTermMaximumCharacters,
79
+ questions: Type.Array(nonEmptyString(descriptions.question), {
80
+ description: descriptions.questions,
81
+ minItems: 1,
82
+ maxItems: retrievalPolicy.maxQuestions,
83
+ }),
84
+ rfcs: Type.Optional(
85
+ Type.Array(nonEmptyString(descriptions.rfc), {
86
+ description: descriptions.rfcs,
87
+ minItems: 1,
88
+ maxItems: retrievalPolicy.maxRequestedRfcs,
47
89
  }),
48
- { minItems: 1, maxItems: datatrackerTopicSearchTermLimit },
90
+ ),
91
+ searchTerms: Type.Optional(
92
+ Type.Array(
93
+ Type.String({
94
+ description: descriptions.searchTerm,
95
+ minLength: 1,
96
+ maxLength: datatrackerTopicSearchTermMaximumCharacters,
97
+ }),
98
+ {
99
+ description: descriptions.searchTerms,
100
+ minItems: 1,
101
+ maxItems: datatrackerTopicSearchTermLimit,
102
+ },
103
+ ),
49
104
  ),
50
105
  },
51
106
  { additionalProperties: false },
@@ -53,33 +108,25 @@ const topicResearchParameters = Type.Object(
53
108
 
54
109
  const citationParameters = Type.Object(
55
110
  {
56
- rfc: nonEmptyString("Exact published RFC identifier containing the quotation"),
57
- claim: nonEmptyString("One factual claim to check"),
58
- quote: nonEmptyString("Exact unchanged RFC quotation"),
59
- offset: Type.Optional(
60
- Type.Integer({
61
- description:
62
- "Absolute UTF-8 byte offset copied from research provenance; omit for a unique quotation",
63
- minimum: 0,
64
- }),
65
- ),
111
+ rfc: nonEmptyString(descriptions.citationRfc),
112
+ claim: nonEmptyString(descriptions.claim),
113
+ quote: nonEmptyString(descriptions.quote),
114
+ offset: Type.Optional(Type.Integer({ description: descriptions.offset, minimum: 0 })),
66
115
  },
67
116
  { additionalProperties: false },
68
117
  );
69
118
 
70
119
  const rfcParameters = Type.Object(
71
120
  {
72
- rfc: nonEmptyString("Exact named RFC source-cache entry, for example RFC9110"),
121
+ rfc: nonEmptyString(descriptions.cacheRfc),
73
122
  },
74
123
  { additionalProperties: false },
75
124
  );
76
125
 
77
126
  const sourceCacheRemoveParameters = Type.Object(
78
127
  {
79
- rfc: nonEmptyString("Exact named RFC source-cache entry, for example RFC9110"),
80
- confirm: Type.Literal(true, {
81
- description: "Must be true to confirm removal of the named cache entry",
82
- }),
128
+ rfc: nonEmptyString(descriptions.cacheRfc),
129
+ confirm: Type.Literal(true, { description: descriptions.confirm }),
83
130
  },
84
131
  { additionalProperties: false },
85
132
  );
@@ -108,6 +155,74 @@ const successResult = (
108
155
  details: { structuredContent, warnings } satisfies RfcToolDetails,
109
156
  });
110
157
 
158
+ /**
159
+ * Environment variable that replaces the published CLI for a session.
160
+ */
161
+ const rfcCliCommandVariable = "RFC_CLI_COMMAND";
162
+
163
+ /**
164
+ * Environment variable that opts in to the local cache and credential tools.
165
+ *
166
+ * Research never needs them, and every registered tool's description and schema
167
+ * is resent to the model on each request, so they stay unregistered unless the
168
+ * session sets this to `1`. Read once when the extension loads and registers
169
+ * its tools.
170
+ */
171
+ const rfcLocalToolsVariable = "RFC_PI_LOCAL_TOOLS";
172
+
173
+ /**
174
+ * The executable and leading arguments used to run the RFC CLI.
175
+ */
176
+ type RfcCliInvocation = {
177
+ /**
178
+ * Executable resolved through PATH, or an absolute path.
179
+ */
180
+ readonly command: string;
181
+ /**
182
+ * Arguments placed before the per-tool arguments.
183
+ */
184
+ readonly prefixArguments: ReadonlyArray<string>;
185
+ };
186
+
187
+ /**
188
+ * Resolve how to run the RFC CLI, honouring a development override.
189
+ *
190
+ * `RFC_CLI_COMMAND` accepts a JSON array for a command with arguments, for
191
+ * example `["bun","/path/to/packages/rfc/src/bin.ts"]`, or a bare executable
192
+ * path. It exists so a working-tree CLI can be exercised without publishing;
193
+ * unset, the pinned published package is used. The variable selects an
194
+ * executable, which is no more exposure than PATH already carries for `bunx`.
195
+ *
196
+ * Read per call rather than at module load so a session can set it late.
197
+ *
198
+ * @returns The command and leading arguments to spawn.
199
+ */
200
+ const resolveRfcInvocation = (): RfcCliInvocation => {
201
+ const override = process.env[rfcCliCommandVariable]?.trim();
202
+ if (override === undefined || override.length === 0) {
203
+ return { command: "bunx", prefixArguments: [rfcPackageSpec] };
204
+ }
205
+ if (!override.startsWith("[")) return { command: override, prefixArguments: [] };
206
+
207
+ const parsed: unknown = ((): unknown => {
208
+ try {
209
+ return JSON.parse(override);
210
+ } catch {
211
+ return undefined;
212
+ }
213
+ })();
214
+ if (
215
+ !Array.isArray(parsed) ||
216
+ parsed.length === 0 ||
217
+ !parsed.every((entry) => typeof entry === "string" && entry.length > 0)
218
+ ) {
219
+ throw new Error(
220
+ `${rfcCliCommandVariable} must be a non-empty executable path or a JSON array of non-empty strings`,
221
+ );
222
+ }
223
+ return { command: parsed[0] as string, prefixArguments: (parsed as Array<string>).slice(1) };
224
+ };
225
+
111
226
  const parseJsonObject = (value: string): object | undefined => {
112
227
  try {
113
228
  const parsed: unknown = JSON.parse(value);
@@ -127,7 +242,8 @@ const runRfcCommand = <A extends object>(
127
242
  new Promise((resolve, reject) => {
128
243
  signal?.throwIfAborted();
129
244
 
130
- const child = spawn("bunx", [rfcPackageSpec, ...args], {
245
+ const invocation = resolveRfcInvocation();
246
+ const child = spawn(invocation.command, [...invocation.prefixArguments, ...args], {
131
247
  stdio: ["pipe", "pipe", "pipe"],
132
248
  });
133
249
  const stdout: Array<Buffer> = [];
@@ -188,11 +304,15 @@ const runRfcCommand = <A extends object>(
188
304
 
189
305
  if (code !== 0) {
190
306
  const envelope = stderrObjects.find((entry) => "kind" in entry && entry.kind === "error");
307
+ const stderrText = stderrLines.join(" | ").slice(0, commandStderrMaximumCharacters);
191
308
  finishWithError(
192
- new Error(
309
+ new RfcCommandFailure(
193
310
  envelope === undefined
194
- ? "RFC CLI failed without a versioned error envelope"
311
+ ? `RFC CLI failed without a versioned error envelope (exit ${String(code)}); stderr: ${
312
+ stderrText.length === 0 ? "<empty>" : stderrText
313
+ }`
195
314
  : JSON.stringify(envelope),
315
+ { exitCode: code, stderr: stderrText },
196
316
  ),
197
317
  );
198
318
  return;
@@ -213,45 +333,71 @@ const runRfcCommand = <A extends object>(
213
333
  child.stdin.end(input === undefined ? undefined : `${JSON.stringify(input)}\n`);
214
334
  });
215
335
 
336
+ /**
337
+ * Run one RFC CLI command, retaining the diagnostics of a non-zero exit so the
338
+ * `tool_result` hook can record them against this tool call.
339
+ *
340
+ * @param toolCallId Pi tool call the command belongs to.
341
+ * @param args Command arguments appended to the RFC CLI package spec.
342
+ * @param input Structured standard input, when the command reads one.
343
+ * @param signal Cancellation signal for the tool call.
344
+ * @returns The decoded CLI result and any warnings it emitted.
345
+ */
346
+ const runToolCommand = <A extends object>(
347
+ toolCallId: string,
348
+ args: ReadonlyArray<string>,
349
+ input: object | undefined,
350
+ signal: AbortSignal | undefined,
351
+ ): Promise<RfcCommandResult<A>> =>
352
+ runRfcCommand<A>(args, input, signal).catch((error: unknown) => {
353
+ if (error instanceof RfcCommandFailure) {
354
+ if (commandFailures.size >= commandFailureRetentionLimit) {
355
+ const oldest = commandFailures.keys().next();
356
+ if (oldest.done !== true) commandFailures.delete(oldest.value);
357
+ }
358
+ commandFailures.set(toolCallId, error.diagnostics);
359
+ }
360
+ throw error;
361
+ });
362
+
216
363
  /**
217
364
  * Register the RFC evidence engine as native Pi tools with the MCP surface's names and metadata.
218
365
  *
366
+ * The cache and credential tools register only when `RFC_PI_LOCAL_TOOLS=1`.
367
+ *
219
368
  * @param pi Pi extension API used to register tools and prompt guidance.
220
369
  */
221
370
  export default function rfcExtension(pi: ExtensionAPI): void {
222
371
  pi.on("before_agent_start", (event) => {
223
- event.systemPromptOptions.sections.rfc_evidence_engine = rfcMcpInstructions;
372
+ event.systemPromptOptions.sections.rfc_evidence_engine = rfcPiInstructions;
224
373
  });
225
374
 
226
- pi.registerTool({
227
- name: rfcAgentToolMetadata.researchKnownRfc.name,
228
- label: rfcAgentToolMetadata.researchKnownRfc.title,
229
- description: rfcAgentToolMetadata.researchKnownRfc.description,
230
- promptSnippet: rfcAgentToolMetadata.researchKnownRfc.title,
231
- parameters: knownRfcResearchParameters,
232
- async execute(_toolCallId, { question, rfc }, signal) {
233
- const result = await runRfcCommand<EvidenceBundle>(
234
- ["research"],
235
- { schemaVersion, question, rfc },
236
- signal,
237
- );
238
- return successResult(result.value, renderEvidenceBundle(result.value), result.warnings);
239
- },
375
+ pi.on("tool_result", (event) => {
376
+ const diagnostics = commandFailures.get(event.toolCallId);
377
+ if (diagnostics === undefined) return undefined;
378
+ commandFailures.delete(event.toolCallId);
379
+ return { details: diagnostics };
240
380
  });
241
381
 
242
382
  pi.registerTool({
243
- name: rfcAgentToolMetadata.researchTopic.name,
244
- label: rfcAgentToolMetadata.researchTopic.title,
245
- description: rfcAgentToolMetadata.researchTopic.description,
246
- promptSnippet: rfcAgentToolMetadata.researchTopic.title,
247
- parameters: topicResearchParameters,
248
- async execute(_toolCallId, { question, searchTerms }, signal) {
249
- const result = await runRfcCommand<EvidenceBundle>(
383
+ name: rfcAgentToolMetadata.research.name,
384
+ label: rfcAgentToolMetadata.research.title,
385
+ description: rfcAgentToolMetadata.research.description,
386
+ promptSnippet: rfcAgentToolMetadata.research.title,
387
+ parameters: researchParameters,
388
+ async execute(toolCallId, { questions, rfcs, searchTerms }, signal) {
389
+ const result = await runToolCommand<ResearchResult>(
390
+ toolCallId,
250
391
  ["research"],
251
- { schemaVersion, question, rfc: null, searchTerms },
392
+ {
393
+ schemaVersion,
394
+ questions,
395
+ ...(rfcs === undefined ? {} : { rfcs }),
396
+ ...(searchTerms === undefined ? {} : { searchTerms }),
397
+ },
252
398
  signal,
253
399
  );
254
- return successResult(result.value, renderEvidenceBundle(result.value), result.warnings);
400
+ return successResult(result.value, researchResultAgentJson(result.value), result.warnings);
255
401
  },
256
402
  });
257
403
 
@@ -261,29 +407,37 @@ export default function rfcExtension(pi: ExtensionAPI): void {
261
407
  description: rfcAgentToolMetadata.verifyCitation.description,
262
408
  promptSnippet: rfcAgentToolMetadata.verifyCitation.title,
263
409
  parameters: citationParameters,
264
- async execute(_toolCallId, { rfc, claim, quote, offset }, signal) {
265
- const result = await runRfcCommand<CitationVerificationResult>(
410
+ async execute(toolCallId, { rfc, claim, quote, offset }, signal) {
411
+ const result = await runToolCommand<CitationVerificationResult>(
412
+ toolCallId,
266
413
  ["verify-citation"],
267
414
  { schemaVersion, rfc, claim, quote, offset: offset ?? null },
268
415
  signal,
269
416
  );
270
- return successResult(result.value, renderCitationVerification(result.value), result.warnings);
417
+ return successResult(
418
+ result.value,
419
+ citationVerificationAgentJson(result.value),
420
+ result.warnings,
421
+ );
271
422
  },
272
423
  });
273
424
 
425
+ if (process.env[rfcLocalToolsVariable] !== "1") return;
426
+
274
427
  pi.registerTool({
275
428
  name: rfcAgentToolMetadata.sourceCacheStatus.name,
276
429
  label: rfcAgentToolMetadata.sourceCacheStatus.title,
277
430
  description: rfcAgentToolMetadata.sourceCacheStatus.description,
278
431
  promptSnippet: rfcAgentToolMetadata.sourceCacheStatus.title,
279
432
  parameters: rfcParameters,
280
- async execute(_toolCallId, { rfc }, signal) {
281
- const result = await runRfcCommand<RfcSourceCacheStatus>(
433
+ async execute(toolCallId, { rfc }, signal) {
434
+ const result = await runToolCommand<RfcSourceCacheStatus>(
435
+ toolCallId,
282
436
  ["cache", "status", "--rfc", rfc, "--format", "json"],
283
437
  undefined,
284
438
  signal,
285
439
  );
286
- return successResult(result.value, renderSourceCacheStatus(result.value), result.warnings);
440
+ return successResult(result.value, JSON.stringify(result.value), result.warnings);
287
441
  },
288
442
  });
289
443
 
@@ -293,13 +447,14 @@ export default function rfcExtension(pi: ExtensionAPI): void {
293
447
  description: rfcAgentToolMetadata.sourceCacheRemove.description,
294
448
  promptSnippet: rfcAgentToolMetadata.sourceCacheRemove.title,
295
449
  parameters: sourceCacheRemoveParameters,
296
- async execute(_toolCallId, { rfc }, signal) {
297
- const result = await runRfcCommand<RfcSourceCacheRemoveResult>(
450
+ async execute(toolCallId, { rfc }, signal) {
451
+ const result = await runToolCommand<RfcSourceCacheRemoveResult>(
452
+ toolCallId,
298
453
  ["cache", "remove", "--rfc", rfc, "--format", "json"],
299
454
  undefined,
300
455
  signal,
301
456
  );
302
- return successResult(result.value, renderSourceCacheRemove(result.value), result.warnings);
457
+ return successResult(result.value, JSON.stringify(result.value), result.warnings);
303
458
  },
304
459
  });
305
460
 
@@ -309,13 +464,15 @@ export default function rfcExtension(pi: ExtensionAPI): void {
309
464
  description: rfcAgentToolMetadata.authStatus.description,
310
465
  promptSnippet: rfcAgentToolMetadata.authStatus.title,
311
466
  parameters: emptyParameters,
312
- async execute(_toolCallId, _params, signal) {
313
- const result = await runRfcCommand<AuthStatus>(
314
- ["auth", "status", "--format", "json"],
467
+ async execute(toolCallId, _params, signal) {
468
+ const result = await runToolCommand<AuthStatus>(
469
+ toolCallId,
470
+ // `auth` reports status itself; its only subcommands are login and remove.
471
+ ["auth", "--format", "json"],
315
472
  undefined,
316
473
  signal,
317
474
  );
318
- return successResult(result.value, renderAuthStatus(result.value), result.warnings);
475
+ return successResult(result.value, JSON.stringify(result.value), result.warnings);
319
476
  },
320
477
  });
321
478
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wyattjoh/rfc-pi",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Native Pi extension and lookup skill for evidence-grounded IETF RFC research.",
5
5
  "keywords": [
6
6
  "ietf",
@@ -28,8 +28,8 @@
28
28
  "typecheck": "tsc --noEmit -p tsconfig.json"
29
29
  },
30
30
  "dependencies": {
31
- "@wyattjoh/rfc": "0.3.2",
32
- "@wyattjoh/rfc-core": "0.1.2"
31
+ "@wyattjoh/rfc": "0.4.0",
32
+ "@wyattjoh/rfc-core": "0.2.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/bun": "1.4.2",
@@ -1,31 +1,31 @@
1
1
  ---
2
2
  name: rfc-lookup
3
- description: Answer questions about published IETF RFCs from exact authoritative source text through the self-describing RFC MCP or linked typed `rfc` CLI. Use for RFC requirements, definitions, procedures, updates, obsoletions, or citations. For one atomic question, never exceed two research calls and two citation calls, never loop by rephrasing a valid result, and preserve the status of qualified review candidates.
3
+ description: Answer questions about published IETF RFCs from exact authoritative source text through the self-describing RFC MCP or linked typed `rfc` CLI. Use for RFC requirements, definitions, procedures, updates, obsoletions, or citations. Make one rfc_research call per user request with each fact as its own question, answer from the returned passages, and make at most one follow-up call when a question is not found.
4
4
  argument-hint: "[RFC number or question]"
5
5
  ---
6
6
 
7
7
  # RFC lookup
8
8
 
9
9
  Use the RFC MCP when its tools are available; otherwise use the linked `rfc`
10
- binary. Both are complete RFC research backends and own live RFC discovery,
11
- source retrieval, evidence selection, RFC currency, and citation verification.
12
- Compose only a short answer from returned canonical passages, preserving whether
13
- each passage is accepted evidence or a qualified review candidate; never answer
10
+ binary. Both are complete RFC retrieval backends: they own live RFC discovery,
11
+ RFC currency, canonical source retrieval, relevance ranking, passage selection,
12
+ and citation verification. The tool finds the RFCs and exact paragraphs that
13
+ bear on each question; you do the reasoning and write the answer. Never answer
14
14
  from memory or a second provider.
15
15
 
16
16
  ## Self-describing MCP surface
17
17
 
18
18
  Launch the local stdio server with `rfc mcp`. A model connected through MCP does
19
19
  not need this skill or direct CLI access: initialization instructions contain the
20
- bounded workflow, and `rfc://docs/agent-workflow` contains the complete agent
21
- reference. The typed tools are `rfc_research_known_rfc`, `rfc_research_topic`,
22
- `rfc_verify_citation`, `rfc_source_cache_status`, `rfc_source_cache_remove`, and
23
- `rfc_auth_status`.
20
+ workflow, and `rfc://docs/agent-workflow` contains the complete agent reference.
21
+ The typed tools are `rfc_research`, `rfc_verify_citation`,
22
+ `rfc_source_cache_status`, `rfc_source_cache_remove`, and `rfc_auth_status`.
24
23
 
25
- Successful calls return concise text plus complete version-two structured
24
+ Successful calls return concise text plus complete version-three structured
26
25
  content. Operational failures are MCP tool errors containing the same safe error
27
- envelope as the CLI. Research status and citation verdict remain domain results,
28
- not tool failures. `rfc_source_cache_remove` requires `confirm: true`.
26
+ envelope as the CLI. A question that was not found and a citation verdict are
27
+ domain results, not tool failures. `rfc_source_cache_remove` requires
28
+ `confirm: true`.
29
29
 
30
30
  The MCP deliberately excludes credential mutation and per-call cache or upstream
31
31
  URL overrides. If `rfc_auth_status` or a tool error reports a missing credential, ask
@@ -33,45 +33,64 @@ the human operator to run `rfc auth login`; never solicit a key through MCP. Tru
33
33
  cache and upstream overrides may be set only when the operator launches
34
34
  `rfc mcp`.
35
35
 
36
- ## Bounded agent workflow
36
+ ## Workflow
37
37
 
38
38
  Use the typed MCP tools directly when available. Otherwise use `rfc` directly;
39
39
  do not resolve its installation path, invoke its TypeScript entrypoint with
40
40
  `bun`, read source-cache internals, or use shell loops to probe wording and
41
41
  offsets.
42
42
 
43
- For each simple atomic user question, use this hard budget:
44
-
45
- 1. Call `rfc_research_known_rfc` or `rfc_research_topic` once, or run one
46
- `rfc research --format human` fallback call.
47
- 2. Only when that result has no usable evidence, run at most one targeted
48
- follow-up research call. Do not repeatedly rephrase a valid result to chase
49
- `answered` or a higher confidence.
50
- 3. If the result includes accepted evidence, quote it directly with provenance.
51
- If it includes a review candidate, quote it only as qualified, unaccepted
52
- evidence. Verify at most two paraphrased claims once each; exact reproduction
53
- of a returned passage does not require duplicate verification.
54
- 4. Stop after the budget. Do not say that no source passage was found when the
55
- backend returned a review candidate; report its status and qualification.
56
- Keep nearby protocol categories distinct rather than substituting one for
57
- another.
58
-
59
- A direct quote-verification request starts with one `rfc_verify_citation` tool call
60
- or `rfc verify-citation` fallback call and needs no research preflight. If the
61
- quote is `fabricated`, use at most one research call to locate current wording
62
- and at most one verification call for the replacement. Never guess or
63
- brute-force byte offsets: copy an offset from research provenance, or omit it
64
- when the quote occurs only once. If replacement research returns a review
65
- candidate, report that exact candidate and its qualification instead of
66
- re-querying for a higher score.
43
+ 1. Make one `rfc_research` call, or one `rfc research` fallback call, per user
44
+ request. Put each fact you need in `questions` as its own entry, up to four.
45
+ Each question is answered independently against the same candidate RFCs, so
46
+ split a compound request yourself rather than sending it as one question.
47
+ 2. Pass `rfcs` when you know the RFC numbers and `searchTerms` when you do not;
48
+ both may be combined. Named RFCs, their current successors, and topic hits
49
+ form one candidate pool.
50
+ 3. Answer from the returned passages. Cite only the RFC and section shown with
51
+ each passage; do not attribute a passage to a section or RFC it did not come
52
+ from.
53
+ 4. When a question is not found, you may make one follow-up call with other
54
+ `rfcs` or `searchTerms`; RFC titles often differ from common names. Then
55
+ stop and report what was searched.
56
+ 5. Never re-research or re-verify returned passages. Reproducing or paraphrasing
57
+ a returned passage needs no citation call.
58
+
59
+ A passage from a hit whose role is `current` comes from the RFC that replaced
60
+ the one named. Say so rather than attributing it to the named RFC, and never
61
+ silently substitute a successor. `currency` reports, per named RFC, `requested`,
62
+ its `current` successors, `complete`, and the relationship `paths` that led to
63
+ them. When `complete` is false, a successor was unresolved or cut off by a
64
+ traversal bound (the concise text says "incomplete: some successors were not
65
+ fetched"); say that the successor list may be partial rather than presenting it
66
+ as final.
67
67
 
68
68
  Use MCP's concise text content for agent-facing calls; the complete result also
69
- remains available as structured content. For the CLI fallback, use
70
- `--format human`. Both include status, accepted quotes, qualified review
71
- candidates, source URLs, byte offsets, input tokens, and estimated cost without
72
- dumping full model diagnostics into the conversation. Use CLI JSON only when
73
- code needs to extract a specific field, and summarize it before returning it to
74
- model context.
69
+ remains available as structured content. For the CLI fallback, argument-based
70
+ invocations already print the concise human layout. Use CLI JSON only when code
71
+ needs to extract a specific field, and summarize it before returning it to model
72
+ context.
73
+
74
+ ## Search-term privacy
75
+
76
+ Search terms are transmitted verbatim in Datatracker query URLs, and to the IETF
77
+ RFC search service when the operator enabled it, and may appear in diagnostics,
78
+ errors, and upstream access logs. Never put private or user-specific details in
79
+ a term, derive hidden terms, or send the full question as a term unless the user
80
+ explicitly chose it. Standard technical terms, including title words of an RFC
81
+ you expect to match, are fine. Preserve the caller's order.
82
+
83
+ Datatracker matches each term as a literal case-insensitive substring of an RFC
84
+ title or abstract. A short noun phrase such as `DNS over TLS` finds documents; a
85
+ sentence fragment such as `DNS over TLS default port` matches nothing, because
86
+ no title or abstract contains that exact string.
87
+
88
+ If the operator enabled optional full-text search, terms additionally match RFC
89
+ keywords and body text, so a term naming a protocol element such as
90
+ `Retry-After` also resolves. Write terms that work under either configuration.
91
+ When `retrieval.topicSearchFallback` is true, full-text search was configured but
92
+ failed and discovery ran on titles and abstracts alone, so an empty result is
93
+ less conclusive than usual.
75
94
 
76
95
  ## Install and link the CLI
77
96
 
@@ -104,91 +123,81 @@ single-line key through `rfc auth login --stdin`. If the credential store is
104
123
  unavailable or denied, report the typed error; do not bypass `Bun.secrets` with
105
124
  a plaintext fallback.
106
125
 
107
- ## Version-two semantic protocol
126
+ ## Version-three CLI protocol
108
127
 
109
- Use human output for normal agent work and JSON standard input only when a
110
- multiline quote or programmatic extraction requires it. Non-whitespace standard
111
- input is authoritative over convenience flags and positional arguments, and it
112
- defaults to JSON output. Argument-based invocations default to human output;
113
- pass `--format json` only for programmatic extraction. A valid research status
114
- is a successful process result even when it is not `answered`.
128
+ Use flags for normal agent work and JSON standard input only when programmatic
129
+ extraction or a multiline quote requires it. Non-whitespace standard input is
130
+ authoritative over flags and positional arguments, and it defaults to JSON
131
+ output. Argument-based invocations default to human output; pass
132
+ `--format json` only for programmatic extraction.
115
133
 
116
- ### Research one known RFC
134
+ ### Research
135
+
136
+ Repeat `-q`/`--question` once per fact, and add `-r`/`--rfc` or
137
+ `--search-term` up to four times each:
117
138
 
118
139
  ```sh
119
- cat <<'JSON' | rfc research --format human
120
- {
121
- "schemaVersion": 2,
122
- "question": "What does RFC 9110 require a client to send?",
123
- "rfc": "RFC9110"
124
- }
125
- JSON
140
+ rfc research \
141
+ -q "What does the 429 status code mean?" \
142
+ -q "Which header says how long to wait?" \
143
+ -r RFC6585 -r RFC9110
144
+
145
+ rfc research \
146
+ -q "Which port does DNS over TLS use by default?" \
147
+ --search-term "DNS over TLS"
126
148
  ```
127
149
 
128
- Known-RFC research retrieves only the requested RFC's metadata and the bounded
129
- successor relationships needed for RFC currency.
130
-
131
- ### Discover RFCs for a topic
132
-
133
- A topic request sets `rfc` to `null` and supplies one to four ordered, non-empty
134
- search terms. Supply the technical phrases intentionally; they are transmitted
135
- verbatim in Datatracker query URLs and may appear in upstream access logs. The
136
- full natural-language question is not sent to Datatracker.
150
+ The same request as JSON on standard input:
137
151
 
138
152
  ```sh
139
153
  cat <<'JSON' | rfc research --format human
140
154
  {
141
- "schemaVersion": 2,
142
- "question": "Which published RFC defines HTTP caching requirements?",
143
- "rfc": null,
144
- "searchTerms": ["HTTP caching", "cache control"]
155
+ "schemaVersion": 3,
156
+ "questions": [
157
+ "What does the 429 status code mean?",
158
+ "Which header says how long to wait?"
159
+ ],
160
+ "rfcs": ["RFC6585", "RFC9110"]
145
161
  }
146
162
  JSON
147
163
  ```
148
164
 
149
- The short form accepts the question positionally or through `--question`, then
150
- uses repeatable `--search-term` flags. Preserve the caller's order. Do not generate hidden terms, rewrite phrases, infer a broad
151
- query from the question, or run a catalog preflight: each supplied term appears
152
- in Datatracker query URLs and can be retained in upstream access logs.
153
-
154
- The result is a version-two `evidence_bundle` containing `status`, exact
155
- `evidence`, optional exact `reviewCandidates`, optional requested/current
156
- `contexts`, and bounded `diagnostics`. Review candidates are canonical source
157
- passages surfaced only for bounded review; they are never accepted evidence and
158
- must be labeled as qualified when quoted. Each human-rendered passage names its
159
- RFC and whether it came from the requested or a current context. Do not answer a
160
- question about the requested RFC with a current-context passage unless you
161
- explicitly explain the distinction.
165
+ `questions` holds one to four entries; at least one of `rfcs` or `searchTerms`
166
+ is required, each with one to four entries.
167
+
168
+ The result is a version-three `research_result`. For each question, `answers`
169
+ reports `found`, the `searched` RFCs, and ranked `hits`. Each hit names its
170
+ `rfc`, its `role` (`requested`, `current`, or `discovered`), its `relevance`,
171
+ a `verdict`, and one to three exact `passages`. Verdicts are:
172
+
173
+ - `supports`: the passage states the answer or directly implies it.
174
+ - `partial`: the passage answers only part of the question.
175
+ - `says_nothing`: the passage does not address the question.
176
+ - `contradicts`: the passage states the opposite of what the question presumes.
177
+
178
+ Each passage includes an unchanged quote, its nullable section, and provenance
179
+ with the canonical source URL, source hash, `offsetUnit`, and UTF-8 byte
180
+ offsets. `found: false` means none of the `searched` RFCs contained an answer;
181
+ it is a successful result, not a failure.
182
+
162
183
  `diagnostics.usage.inputTokens` reports the provider-observed input tokens, while
163
184
  `diagnostics.inputCost` reports the estimated USD charge and its per-million-token
164
185
  rate. Treat a null estimate as unavailable rather than zero cost. Each successful
165
186
  research or citation operation atomically updates the per-user running total in
166
187
  `~/.config/rfc/usage.json`; its unpriced and missing-usage counters qualify the
167
- cumulative estimate. Each evidence passage includes an unchanged quote and
168
- provenance with RFC identity, nullable section, canonical URLs, source hash,
169
- `offsetUnit`, and UTF-8 byte offsets.
170
- Metadata, relationships, candidate collections, questions, and model responses
171
- are request-local and are not persisted.
172
-
173
- When the user supplies up to two explicit, independently answerable questions,
174
- run one `rfc research` process per atomic question. For example, “Can the server
175
- issue this?” and “What protections are required?” are two atomic questions even
176
- when they share a topic. Keep each input and output separate. Do not merge
177
- questions, split into more than two parts, or invent a split for an ambiguous
178
- request.
179
-
180
- ### Verify accepted claims once
181
-
182
- Keep a simple answer to at most two factual claims. Exact reproduction of a
183
- returned passage with its status and provenance needs no duplicate citation
184
- call. For a paraphrased claim, make one citation request, once, using the exact
185
- returned quote and byte offset. Do not split one claim into multiple paraphrased
186
- verification attempts:
188
+ cumulative estimate. Metadata, relationships, candidate pools, questions, and
189
+ model responses are request-local and are not persisted.
190
+
191
+ ### Verify a supplied quotation
192
+
193
+ Use `rfc_verify_citation` or `rfc verify-citation` only for a quotation the user
194
+ supplied or a check the user explicitly requested; it needs no research
195
+ preflight. Never verify passages research already returned.
187
196
 
188
197
  ```sh
189
198
  cat <<'JSON' | rfc verify-citation --format human
190
199
  {
191
- "schemaVersion": 2,
200
+ "schemaVersion": 3,
192
201
  "rfc": "RFC9110",
193
202
  "claim": "The client sends a request containing the target resource.",
194
203
  "quote": "The client MUST send a request containing the target resource.",
@@ -197,15 +206,12 @@ cat <<'JSON' | rfc verify-citation --format human
197
206
  JSON
198
207
  ```
199
208
 
200
- Only accepted research evidence or a `verified` citation supports an
201
- unqualified factual claim. A verified citation is an independent acceptance
202
- path even when discovery was fail-closed. A review candidate may be reproduced
203
- exactly only when explicitly labeled unaccepted or `needs_review`; do not turn it
204
- into an unqualified paraphrase. Remove or qualify claims whose verdict is
205
- `unsupported`, `contradicted`, or `fabricated`. Present each accepted normative
206
- claim with its unchanged quote, RFC identifier, section when available, byte
207
- offsets, and canonical source URL. Never repair quote wording, retry with guessed
208
- offsets, or replace an evidence gap with recall.
209
+ Verify at most two paraphrased claims, once each. Never guess or brute-force
210
+ byte offsets: copy an offset from research provenance, or omit it when the quote
211
+ occurs only once. If the quote is `fabricated`, use at most one research call to
212
+ locate current wording and at most one verification call for the replacement.
213
+ Remove or qualify claims whose verdict is `unsupported`, `contradicted`, or
214
+ `fabricated`; never repair quote wording or replace a gap with recall.
209
215
 
210
216
  ## RFC source-cache operations
211
217
 
@@ -222,58 +228,45 @@ operation. Fresh entries are reused; stale entries are conditionally revalidated
222
228
  A revalidation failure is an operational error, never permission to serve stale
223
229
  text.
224
230
 
225
- ## Fail-closed statuses and failures
226
-
227
- Report research status exactly:
228
-
229
- - `answered`: accepted direct evidence with no disqualifying uncertainty.
230
- - `partial`: only part of the question or currency coverage is established.
231
- - `unsupported`: bounded research found no accepted answering evidence.
232
- - `needs_review`: confidence is low, evidence conflicts, discovery is empty, or
233
- RFC currency is uncertain.
234
- - `needs_split`: the question is compound and requires atomic questions.
235
-
236
- Keep requested and current RFC contexts distinct. Follow returned
237
- `relationshipPath`, `isCurrent`, and currency diagnostics; never silently
238
- substitute a successor for the requested RFC.
231
+ ## Failures
239
232
 
240
- On a nonzero exit, parse the version-two JSON error envelope from standard error
241
- and stop. Common recovery actions:
233
+ Tool errors are final. On a nonzero exit, parse the version-three JSON error
234
+ envelope from standard error, report the code, and stop; never substitute memory
235
+ or another provider. Never retry a successful paid call over a
236
+ `usage_accounting_failed` warning. Common recovery actions:
242
237
 
243
- | Code | Recovery |
244
- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
245
- | `invalid_input` | Correct the version-two JSON, RFC, or ordered search terms. |
246
- | `credential_missing` | Run `rfc auth login` or `rfc auth login --stdin`. |
247
- | `credential_store_unavailable` / `credential_access_denied` | Unlock or authorize the OS store; never use plaintext fallback. |
248
- | `discovery_failed` | Report the Datatracker failure and URL; do not use stale or invented metadata. |
249
- | `source_cache_failed` / `source_fetch_failed` / `source_revalidation_failed` | Retry the authoritative source operation; do not substitute another representation or stale text. |
250
- | `rfc_not_found` | Correct the exact RFC identifier or make a topic request with explicit search terms. |
251
- | `decision_model_failed` | Report provider failure after bounded retries; do not switch providers or models. |
252
- | `citation_quote_ambiguous` / `citation_offset_mismatch` | Never guess. Copy the exact UTF-8 byte offset from research provenance, or stop if none exists. |
253
- | `internal_error` / `configuration_error` | Report an operational failure instead of asserting an answer. |
238
+ | Code | Recovery |
239
+ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
240
+ | `invalid_input` | Correct the version-three JSON, RFC identifiers, or ordered search terms. |
241
+ | `credential_missing` | Ask the human operator to run `rfc auth login`; never request or accept the secret. |
242
+ | `credential_store_unavailable` / `credential_access_denied` | Unlock or authorize the OS store; never use plaintext fallback. |
243
+ | `discovery_failed` | Report the Datatracker failure and URL; do not use stale or invented metadata. |
244
+ | `source_cache_failed` / `source_fetch_failed` / `source_revalidation_failed` | Report the authoritative source failure; do not substitute another representation or stale text. |
245
+ | `rfc_not_found` | Correct the exact RFC identifier or use `searchTerms`. |
246
+ | `decision_model_failed` | Report provider failure after bounded retries; do not switch providers or models. |
247
+ | `citation_quote_ambiguous` / `citation_offset_mismatch` | Never guess. Copy the exact UTF-8 byte offset from research provenance, or stop if none exists. |
248
+ | `internal_error` / `configuration_error` | Report an operational failure instead of asserting an answer. |
254
249
 
255
- Never turn an operational failure into a research status or unverified
256
- fail-closed evidence into an affirmative answer. A valid non-answer result is
257
- not an operational failure and must not trigger a rephrasing loop.
250
+ A question that was not found is not an operational failure and must not
251
+ trigger a rephrasing loop beyond the one follow-up call.
258
252
 
259
253
  ## Verification boundaries
260
254
 
261
255
  Normal repository gates are deterministic and offline. They inject Datatracker,
262
256
  RFC Editor, DecisionModel, clock, and credential behavior at public boundaries.
263
- Live provider evaluation is opt-in and uses the same `Bun.secrets` boundary as
264
- production.
265
257
 
266
258
  ## Required scenarios
267
259
 
268
- 1. **Known RFC:** pass an RFC hint, preserve exact evidence, and verify each claim.
269
- 2. **Topic discovery:** pass one to four explicit search terms and report evidence
270
- only when the returned status permits it.
271
- 3. **Compound request:** split only explicit independent subquestions; otherwise
272
- preserve `needs_split`.
273
- 4. **Updated RFC:** show requested and current contexts and relationship paths.
274
- 5. **Unsupported question:** report the evidence gap without recall.
275
- 6. **Provider or upstream failure:** preserve the typed nonzero error and stop.
276
- 7. **Citation rejection:** remove or qualify rejected claims and retain only exact
277
- verified citations.
260
+ 1. **Known RFC:** pass `rfcs`, answer from the returned passages, and cite the
261
+ RFC and section shown.
262
+ 2. **Topic discovery:** pass one to four explicit `searchTerms` and answer only
263
+ from returned passages.
264
+ 3. **Several facts:** put each fact in its own entry in `questions` in one call.
265
+ 4. **Updated RFC:** keep `current` hits distinct from the named RFC and report
266
+ the currency path.
267
+ 5. **Not found:** make at most one follow-up call, then report what was searched
268
+ without recall.
269
+ 6. **Provider or upstream failure:** preserve the typed error and stop.
270
+ 7. **Supplied quotation:** verify it once and remove or qualify rejected claims.
278
271
 
279
272
  The linked typed CLI and this skill are the supported RFC workflow.