@wyattjoh/rfc 0.1.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/main.ts ADDED
@@ -0,0 +1,783 @@
1
+ import {
2
+ InvalidInputError,
3
+ createRfcClient,
4
+ decodeCitationVerificationRequest,
5
+ decodeResearchRequest,
6
+ defaultCacheDirectory,
7
+ schemaVersion,
8
+ } from "@wyattjoh/rfc-core";
9
+ import { NodeServices } from "@effect/platform-node";
10
+ import { Console, Effect, Option } from "effect";
11
+ import { CliError, Command, Flag } from "effect/unstable/cli";
12
+ import { runRfcMcpServer } from "./mcp";
13
+ import {
14
+ executeAuthStatus,
15
+ executeCitationVerification,
16
+ executeResearch,
17
+ executeSourceCacheRemove,
18
+ executeSourceCacheStatus,
19
+ renderAuthStatus,
20
+ renderCitationVerification,
21
+ renderEvidenceBundle,
22
+ renderEstimatedUsd,
23
+ renderSourceCacheRemove,
24
+ renderSourceCacheStatus,
25
+ toRfcOperationErrorEnvelope,
26
+ type RfcOperationOptions,
27
+ type RfcOperationWarning,
28
+ } from "./operations";
29
+ import {
30
+ makeUsageReader,
31
+ makeUsageRecorder,
32
+ type UsageReader,
33
+ type UsageRecorder,
34
+ type UsageTotals,
35
+ } from "./usage-store";
36
+ import {
37
+ CredentialInputError,
38
+ addStoredCredential,
39
+ makeDefaultCredentialStore,
40
+ removeStoredCredential,
41
+ type CredentialStore,
42
+ } from "./credentials";
43
+
44
+ /**
45
+ * Injectable side effects used by the CLI composition root.
46
+ *
47
+ * Production uses process streams and Bun.secrets. Tests replace every
48
+ * boundary so they never touch the operator's credential manager or terminal.
49
+ */
50
+ export interface RfcCliDependencies {
51
+ /**
52
+ * Credential boundary used for provider construction and auth commands.
53
+ */
54
+ readonly credentialStore: CredentialStore;
55
+ /**
56
+ * Read the process standard input when a command explicitly permits it.
57
+ */
58
+ readonly readStandardInput: () => Promise<string>;
59
+ /**
60
+ * Read one credential through a masked interactive prompt.
61
+ */
62
+ readonly promptCredential: () => Promise<string>;
63
+ /**
64
+ * Write one already-rendered value to standard output.
65
+ */
66
+ readonly writeStdout: (value: string) => void;
67
+ /**
68
+ * Write one already-rendered value to standard error.
69
+ */
70
+ readonly writeStderr: (value: string) => void;
71
+ /**
72
+ * Read the cumulative per-user usage totals.
73
+ */
74
+ readonly readUsage: UsageReader;
75
+ /**
76
+ * Persist one successful operation in the per-user usage totals.
77
+ */
78
+ readonly recordUsage: UsageRecorder;
79
+ /**
80
+ * Construct the RFC client for one command invocation.
81
+ *
82
+ * Process-protocol tests substitute a stub here so they can assert decoding,
83
+ * rendering, and exit status without reproducing retrieval internals.
84
+ */
85
+ readonly createClient: typeof createRfcClient;
86
+ }
87
+
88
+ const format = Flag.Literals("format", ["json", "human"] as const).pipe(
89
+ Flag.withDescription("Output format; JSON is the automation default"),
90
+ Flag.withDefault("json" as const),
91
+ );
92
+
93
+ const cacheDirectory = Flag.String("cache-directory").pipe(
94
+ Flag.withDescription("Directory containing cached canonical RFC sources"),
95
+ Flag.withDefault(defaultCacheDirectory),
96
+ );
97
+
98
+ const datatrackerApiUrl = Flag.String("datatracker-api-url").pipe(
99
+ Flag.withDescription("Datatracker API base URL used for live discovery"),
100
+ Flag.optional,
101
+ );
102
+
103
+ const question = Flag.String("question").pipe(
104
+ Flag.withDescription("Short question used when standard input is not supplied"),
105
+ Flag.optional,
106
+ );
107
+
108
+ const rfc = Flag.String("rfc").pipe(
109
+ Flag.withDescription("Known RFC identifier for a short interactive request"),
110
+ Flag.optional,
111
+ );
112
+
113
+ const cacheRfc = Flag.String("rfc").pipe(Flag.withDescription("Named RFC source cache entry"));
114
+
115
+ const searchTerms = Flag.String("search-term").pipe(
116
+ Flag.withDescription("Ordered topic-discovery term; repeat one to four times"),
117
+ Flag.between(0, 4),
118
+ );
119
+
120
+ const typeSafeApiUrl = Flag.String("typesafe-api-url").pipe(
121
+ Flag.withDescription("TypeSafe API URL used for deterministic or self-hosted providers"),
122
+ Flag.optional,
123
+ );
124
+
125
+ const claim = Flag.String("claim").pipe(
126
+ Flag.withDescription("Factual claim to verify when standard input is not supplied"),
127
+ Flag.optional,
128
+ );
129
+
130
+ const quote = Flag.String("quote").pipe(
131
+ Flag.withDescription("Exact RFC quotation to verify when standard input is not supplied"),
132
+ Flag.optional,
133
+ );
134
+
135
+ const offset = Flag.String("offset").pipe(
136
+ Flag.withDescription("Absolute UTF-8 byte offset for a repeated quotation"),
137
+ Flag.optional,
138
+ );
139
+
140
+ const credentialFromStdin = Flag.Boolean("stdin").pipe(
141
+ Flag.withDescription("Read the TypeSafe API key from standard input; never use an argv value"),
142
+ Flag.withDefault(false),
143
+ );
144
+
145
+ const credentialFromStdinAlias = Flag.Boolean("from-stdin").pipe(
146
+ Flag.withDescription("Alias for --stdin"),
147
+ Flag.withDefault(false),
148
+ );
149
+
150
+ /**
151
+ * Maximum bytes accepted from standard input for one request.
152
+ *
153
+ * Every other reader in the CLI is bounded; leaving this one open let a piped
154
+ * stream grow the process heap without limit. A request carries a question or
155
+ * a claim and one quotation, so a megabyte is far above any real input.
156
+ */
157
+ const standardInputMaximumBytes = 1024 * 1024;
158
+
159
+ const readProcessStandardInput = async (): Promise<string> => {
160
+ if (process.stdin.isTTY) return "";
161
+ const chunks: Array<string> = [];
162
+ let bytes = 0;
163
+ for await (const chunk of process.stdin) {
164
+ const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
165
+ bytes += Buffer.byteLength(text, "utf8");
166
+ if (bytes > standardInputMaximumBytes) {
167
+ throw new InvalidInputError({
168
+ reason: `Standard input exceeds ${standardInputMaximumBytes} bytes`,
169
+ });
170
+ }
171
+ chunks.push(text);
172
+ }
173
+ return chunks.join("");
174
+ };
175
+
176
+ const readMaskedCredential = async (): Promise<string> => {
177
+ if (!process.stdin.isTTY || typeof process.stdin.setRawMode !== "function") {
178
+ throw new CredentialInputError({
179
+ reason: "Interactive credential input requires a TTY; use --stdin for automation",
180
+ });
181
+ }
182
+
183
+ process.stderr.write("TypeSafe API key: ");
184
+ return new Promise<string>((resolve, reject) => {
185
+ let value = "";
186
+ const finish = (result: string | Error): void => {
187
+ process.stdin.setRawMode(false);
188
+ process.stdin.pause();
189
+ process.stdin.off("data", onData);
190
+ process.stderr.write("\n");
191
+ if (result instanceof Error) reject(result);
192
+ else resolve(result);
193
+ };
194
+ const onData = (chunk: Buffer | string): void => {
195
+ for (const character of chunk.toString()) {
196
+ if (character === "\r" || character === "\n") {
197
+ finish(value);
198
+ return;
199
+ }
200
+ if (character === "\u0003") {
201
+ finish(
202
+ new CredentialInputError({
203
+ reason: "Interactive credential input was cancelled",
204
+ }),
205
+ );
206
+ return;
207
+ }
208
+ if (character === "\u007f" || character === "\b") {
209
+ if (value.length > 0) value = value.slice(0, -1);
210
+ continue;
211
+ }
212
+ if (character < " ") continue;
213
+ // Nothing is echoed. Writing one mask character per keystroke put the
214
+ // exact key length on screen, which a recording or a shared screen
215
+ // then carries off the machine.
216
+ value += character;
217
+ }
218
+ };
219
+ process.stdin.setRawMode(true);
220
+ process.stdin.resume();
221
+ process.stdin.on("data", onData);
222
+ });
223
+ };
224
+
225
+ /**
226
+ * Construct the production CLI side-effect boundary.
227
+ *
228
+ * @returns Dependencies backed by process streams and Bun's native credential manager.
229
+ */
230
+ export const makeDefaultCliDependencies = (): RfcCliDependencies => ({
231
+ credentialStore: makeDefaultCredentialStore(),
232
+ readStandardInput: readProcessStandardInput,
233
+ promptCredential: readMaskedCredential,
234
+ writeStdout: (value) => process.stdout.write(value),
235
+ writeStderr: (value) => process.stderr.write(value),
236
+ readUsage: makeUsageReader(),
237
+ recordUsage: makeUsageRecorder(),
238
+ createClient: createRfcClient,
239
+ });
240
+
241
+ /**
242
+ * Map a CLI or core failure to a safe versioned process envelope.
243
+ *
244
+ * @param error Rejected operation value.
245
+ * @returns An envelope that never contains credential values or platform error text.
246
+ */
247
+ export const toCliErrorEnvelope = (error: unknown): object => toRfcOperationErrorEnvelope(error);
248
+
249
+ /**
250
+ * Hosts for which cleartext is not a downgrade, so a local test double works.
251
+ */
252
+ const loopbackHosts = new Set(["localhost", "127.0.0.1", "[::1]"]);
253
+
254
+ /**
255
+ * Require an operator-supplied endpoint override to be encrypted in transit.
256
+ *
257
+ * `--typesafe-api-url http://…` sends the stored key as a bearer credential
258
+ * over cleartext on every call, and a cleartext Datatracker endpoint lets a
259
+ * network position rewrite the metadata that currency decisions rest on.
260
+ * Neither flag is reachable by the model, so this closes an operator footgun
261
+ * rather than a model escape.
262
+ *
263
+ * @param flag Flag name as the operator spelled it, used in the refusal.
264
+ * @param value Operator-supplied URL, or undefined when the flag is absent.
265
+ * @returns The value unchanged when it is safe to use.
266
+ * @throws InvalidInputError when the URL is malformed or cleartext off-host.
267
+ */
268
+ const secureEndpointOverride = (flag: string, value: string | undefined): string | undefined => {
269
+ if (value === undefined) return undefined;
270
+ const url = URL.parse(value);
271
+ if (url === null) throw new InvalidInputError({ reason: `${flag} must be an absolute URL` });
272
+ if (url.protocol === "https:") return value;
273
+ if (url.protocol === "http:" && loopbackHosts.has(url.hostname)) return value;
274
+ throw new InvalidInputError({
275
+ reason: `${flag} must use https, or http on a loopback host`,
276
+ });
277
+ };
278
+
279
+ const decodeResearchInput = (input: string) => {
280
+ let parsed: unknown;
281
+ try {
282
+ parsed = JSON.parse(input);
283
+ } catch {
284
+ throw new InvalidInputError({ reason: "Research input must be valid JSON" });
285
+ }
286
+
287
+ return decodeResearchRequest(parsed);
288
+ };
289
+
290
+ const decodeCitationRequest = (input: unknown) => {
291
+ try {
292
+ return decodeCitationVerificationRequest(input);
293
+ } catch {
294
+ throw new InvalidInputError({ reason: "Citation input must use schema version 2" });
295
+ }
296
+ };
297
+
298
+ const decodeCitationInput = (input: string) => {
299
+ let parsed: unknown;
300
+ try {
301
+ parsed = JSON.parse(input);
302
+ } catch {
303
+ throw new InvalidInputError({ reason: "Citation input must be valid JSON" });
304
+ }
305
+
306
+ return decodeCitationRequest(parsed);
307
+ };
308
+
309
+ const parseCitationOffset = (value: string): number => {
310
+ const parsed = Number(value);
311
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
312
+ throw new InvalidInputError({ reason: "Citation offset must be a non-negative integer" });
313
+ }
314
+ return parsed;
315
+ };
316
+
317
+ const renderUsageTotals = (totals: UsageTotals): string =>
318
+ [
319
+ `Updated: ${totals.updatedAt}`,
320
+ `Operations: ${totals.operations}`,
321
+ `Priced operations: ${totals.pricedOperations}`,
322
+ `Unpriced operations: ${totals.unpricedOperations}`,
323
+ `Operations without input tokens: ${totals.operationsWithoutInputTokens}`,
324
+ `Input tokens: ${totals.inputTokens}`,
325
+ `Priced input tokens: ${totals.pricedInputTokens}`,
326
+ `Unpriced input tokens: ${totals.unpricedInputTokens}`,
327
+ `Estimated input cost (USD): ${renderEstimatedUsd(totals.estimatedInputCostUsd)}`,
328
+ ].join("\n");
329
+
330
+ const makeApplication = (dependencies: RfcCliDependencies) => {
331
+ const writeStdout = (value: string): Effect.Effect<void> =>
332
+ Effect.sync(() => dependencies.writeStdout(`${value}\n`));
333
+
334
+ const writeWarnings = (warnings: ReadonlyArray<RfcOperationWarning>): Effect.Effect<void> =>
335
+ Effect.sync(() => {
336
+ for (const warning of warnings) {
337
+ dependencies.writeStderr(`${JSON.stringify(warning)}\n`);
338
+ }
339
+ });
340
+
341
+ const operationOptions = (
342
+ selectedCacheDirectory: string,
343
+ selectedDatatrackerApiUrl: Option.Option<string>,
344
+ selectedTypeSafeApiUrl: Option.Option<string>,
345
+ ): RfcOperationOptions => ({
346
+ cacheDirectory: selectedCacheDirectory,
347
+ datatrackerApiUrl: secureEndpointOverride(
348
+ "--datatracker-api-url",
349
+ Option.getOrUndefined(selectedDatatrackerApiUrl),
350
+ ),
351
+ typeSafeApiUrl: secureEndpointOverride(
352
+ "--typesafe-api-url",
353
+ Option.getOrUndefined(selectedTypeSafeApiUrl),
354
+ ),
355
+ });
356
+
357
+ const sourceCacheStatusCommand = Command.make(
358
+ "status",
359
+ {
360
+ cacheDirectory,
361
+ format,
362
+ rfc: cacheRfc,
363
+ },
364
+ Effect.fn(function* ({ cacheDirectory, format, rfc }) {
365
+ const status = yield* Effect.tryPromise({
366
+ try: () =>
367
+ executeSourceCacheStatus(
368
+ rfc,
369
+ operationOptions(cacheDirectory, Option.none(), Option.none()),
370
+ dependencies,
371
+ ),
372
+ catch: (error) => error,
373
+ });
374
+ yield* writeStdout(
375
+ format === "human" ? renderSourceCacheStatus(status) : JSON.stringify(status),
376
+ );
377
+ }),
378
+ ).pipe(Command.withDescription("Inspect one RFC source cache entry without network access"));
379
+
380
+ const sourceCacheRemoveCommand = Command.make(
381
+ "remove",
382
+ {
383
+ cacheDirectory,
384
+ format,
385
+ rfc: cacheRfc,
386
+ },
387
+ Effect.fn(function* ({ cacheDirectory, format, rfc }) {
388
+ const result = yield* Effect.tryPromise({
389
+ try: () =>
390
+ executeSourceCacheRemove(
391
+ rfc,
392
+ operationOptions(cacheDirectory, Option.none(), Option.none()),
393
+ dependencies,
394
+ ),
395
+ catch: (error) => error,
396
+ });
397
+ yield* writeStdout(
398
+ format === "human" ? renderSourceCacheRemove(result) : JSON.stringify(result),
399
+ );
400
+ }),
401
+ ).pipe(Command.withDescription("Remove one RFC source cache entry without network access"));
402
+
403
+ const sourceCacheCommand = Command.make("cache").pipe(
404
+ Command.withDescription("Manage individually requested RFC source text"),
405
+ Command.withSubcommands([sourceCacheStatusCommand, sourceCacheRemoveCommand]),
406
+ );
407
+
408
+ const verifyCitationCommand = Command.make(
409
+ "verify-citation",
410
+ {
411
+ cacheDirectory,
412
+ datatrackerApiUrl,
413
+ format,
414
+ rfc,
415
+ claim,
416
+ quote,
417
+ offset,
418
+ typeSafeApiUrl,
419
+ },
420
+ Effect.fn(function* (flags) {
421
+ const standardInput = yield* Effect.tryPromise({
422
+ try: dependencies.readStandardInput,
423
+ catch: () => new InvalidInputError({ reason: "Unable to read citation input" }),
424
+ });
425
+
426
+ const request =
427
+ standardInput.trim().length > 0
428
+ ? decodeCitationInput(standardInput)
429
+ : (() => {
430
+ if (
431
+ Option.isNone(flags.rfc) ||
432
+ Option.isNone(flags.claim) ||
433
+ Option.isNone(flags.quote)
434
+ ) {
435
+ throw new InvalidInputError({
436
+ reason:
437
+ "Citation verification requires JSON standard input or --rfc, --claim, and --quote",
438
+ });
439
+ }
440
+ return decodeCitationRequest({
441
+ schemaVersion: 2,
442
+ rfc: flags.rfc.value,
443
+ claim: flags.claim.value,
444
+ quote: flags.quote.value,
445
+ offset: Option.isSome(flags.offset)
446
+ ? parseCitationOffset(flags.offset.value)
447
+ : null,
448
+ });
449
+ })();
450
+
451
+ const result = yield* Effect.tryPromise({
452
+ try: () =>
453
+ executeCitationVerification(
454
+ request,
455
+ operationOptions(flags.cacheDirectory, flags.datatrackerApiUrl, flags.typeSafeApiUrl),
456
+ dependencies,
457
+ ),
458
+ catch: (error) => error,
459
+ });
460
+ yield* writeWarnings(result.warnings);
461
+ yield* writeStdout(
462
+ flags.format === "human"
463
+ ? renderCitationVerification(result.value)
464
+ : JSON.stringify(result.value),
465
+ );
466
+ }),
467
+ ).pipe(
468
+ Command.withDescription("Verify an RFC quotation against a factual claim"),
469
+ Command.withExamples([
470
+ {
471
+ command: "rfc verify-citation < citation.json",
472
+ description: "Verify canonical JSON from standard input",
473
+ },
474
+ {
475
+ command:
476
+ 'rfc verify-citation --rfc RFC9110 --claim "The client sends a request" --quote "The client MUST send a request"',
477
+ description: "Verify a short interactive citation",
478
+ },
479
+ ]),
480
+ );
481
+
482
+ const researchCommand = Command.make(
483
+ "research",
484
+ {
485
+ cacheDirectory,
486
+ datatrackerApiUrl,
487
+ format,
488
+ question,
489
+ rfc,
490
+ searchTerms,
491
+ typeSafeApiUrl,
492
+ },
493
+ Effect.fn(function* (flags) {
494
+ const standardInput = yield* Effect.tryPromise({
495
+ try: dependencies.readStandardInput,
496
+ catch: () => new InvalidInputError({ reason: "Unable to read research input" }),
497
+ });
498
+
499
+ const request =
500
+ standardInput.trim().length > 0
501
+ ? decodeResearchInput(standardInput)
502
+ : Option.isSome(flags.question)
503
+ ? Option.isSome(flags.rfc)
504
+ ? decodeResearchRequest({
505
+ schemaVersion,
506
+ question: flags.question.value,
507
+ rfc: flags.rfc.value,
508
+ searchTerms: flags.searchTerms.length === 0 ? undefined : flags.searchTerms,
509
+ })
510
+ : decodeResearchRequest({
511
+ schemaVersion,
512
+ question: flags.question.value,
513
+ rfc: null,
514
+ searchTerms: flags.searchTerms,
515
+ })
516
+ : (() => {
517
+ throw new InvalidInputError({
518
+ reason: "Research requires JSON standard input or --question",
519
+ });
520
+ })();
521
+
522
+ const result = yield* Effect.tryPromise({
523
+ try: () =>
524
+ executeResearch(
525
+ request,
526
+ operationOptions(flags.cacheDirectory, flags.datatrackerApiUrl, flags.typeSafeApiUrl),
527
+ dependencies,
528
+ ),
529
+ catch: (error) => error,
530
+ });
531
+ yield* writeWarnings(result.warnings);
532
+ yield* writeStdout(
533
+ flags.format === "human"
534
+ ? renderEvidenceBundle(result.value)
535
+ : JSON.stringify(result.value),
536
+ );
537
+ }),
538
+ ).pipe(
539
+ Command.withDescription("Research an RFC question from versioned JSON input"),
540
+ Command.withExamples([
541
+ {
542
+ command: "rfc research < question.json",
543
+ description: "Use canonical JSON from standard input",
544
+ },
545
+ {
546
+ command: 'rfc research --question "What does RFC 9110 require?" --rfc RFC9110',
547
+ description: "Use convenience flags when standard input is empty",
548
+ },
549
+ ]),
550
+ );
551
+
552
+ const authAddCommand = Command.make(
553
+ "add",
554
+ {
555
+ format,
556
+ stdin: credentialFromStdin,
557
+ fromStdin: credentialFromStdinAlias,
558
+ },
559
+ Effect.fn(function* ({ format, stdin, fromStdin }) {
560
+ const input = yield* Effect.tryPromise({
561
+ try: stdin || fromStdin ? dependencies.readStandardInput : dependencies.promptCredential,
562
+ catch: (error) => error,
563
+ });
564
+ const result = yield* Effect.tryPromise({
565
+ try: () => addStoredCredential(dependencies.credentialStore, input),
566
+ catch: (error) => error,
567
+ });
568
+
569
+ if (format === "human") {
570
+ yield* writeStdout(
571
+ result.replaced
572
+ ? "TypeSafe API key replaced in the platform credential store"
573
+ : "TypeSafe API key stored in the platform credential store",
574
+ );
575
+ yield* writeStdout(`Service: ${result.service}`);
576
+ yield* writeStdout(`Name: ${result.name}`);
577
+ return;
578
+ }
579
+
580
+ yield* writeStdout(JSON.stringify(result));
581
+ }),
582
+ ).pipe(Command.withDescription("Store or replace the TypeSafe API key"));
583
+
584
+ const authStatusCommand = Command.make(
585
+ "status",
586
+ { format },
587
+ Effect.fn(function* ({ format }) {
588
+ const result = yield* Effect.tryPromise({
589
+ try: () => executeAuthStatus(dependencies),
590
+ catch: (error) => error,
591
+ });
592
+ yield* writeStdout(format === "human" ? renderAuthStatus(result) : JSON.stringify(result));
593
+ }),
594
+ ).pipe(Command.withDescription("Inspect TypeSafe credential configuration without revealing it"));
595
+
596
+ const authRemoveCommand = Command.make(
597
+ "remove",
598
+ { format },
599
+ Effect.fn(function* ({ format }) {
600
+ const result = yield* Effect.tryPromise({
601
+ try: () => removeStoredCredential(dependencies.credentialStore),
602
+ catch: (error) => error,
603
+ });
604
+ if (format === "human") {
605
+ yield* writeStdout(
606
+ result.removed
607
+ ? "TypeSafe API key removed from the platform credential store"
608
+ : "No TypeSafe API key was configured",
609
+ );
610
+ yield* writeStdout(`Service: ${result.service}`);
611
+ yield* writeStdout(`Name: ${result.name}`);
612
+ return;
613
+ }
614
+ yield* writeStdout(JSON.stringify(result));
615
+ }),
616
+ ).pipe(Command.withDescription("Remove the stored TypeSafe API key"));
617
+
618
+ const authCommand = Command.make("auth").pipe(
619
+ Command.withDescription("Manage the TypeSafe API key in the OS credential manager"),
620
+ Command.withSubcommands([authAddCommand, authStatusCommand, authRemoveCommand]),
621
+ );
622
+
623
+ const costsCommand = Command.make(
624
+ "costs",
625
+ { format },
626
+ Effect.fn(function* ({ format }) {
627
+ const totals = yield* Effect.tryPromise({
628
+ try: dependencies.readUsage,
629
+ catch: (error) => error,
630
+ });
631
+ yield* writeStdout(format === "human" ? renderUsageTotals(totals) : JSON.stringify(totals));
632
+ }),
633
+ ).pipe(Command.withDescription("Print cumulative per-user RFC usage costs"));
634
+
635
+ const mcpCommand = Command.make(
636
+ "mcp",
637
+ { cacheDirectory, datatrackerApiUrl, typeSafeApiUrl },
638
+ Effect.fn(function* (flags) {
639
+ yield* Effect.tryPromise({
640
+ try: () =>
641
+ runRfcMcpServer(
642
+ operationOptions(flags.cacheDirectory, flags.datatrackerApiUrl, flags.typeSafeApiUrl),
643
+ dependencies,
644
+ (error) =>
645
+ dependencies.writeStderr(`${JSON.stringify(toRfcOperationErrorEnvelope(error))}\n`),
646
+ ),
647
+ catch: (error) => error,
648
+ });
649
+ }),
650
+ ).pipe(
651
+ Command.withDescription(
652
+ "Serve the self-describing RFC agent surface over the Model Context Protocol on stdio",
653
+ ),
654
+ );
655
+
656
+ return Command.make("rfc").pipe(
657
+ Command.withDescription("TypeSafe RFC evidence engine"),
658
+ Command.withSubcommands([
659
+ authCommand,
660
+ sourceCacheCommand,
661
+ costsCommand,
662
+ researchCommand,
663
+ verifyCitationCommand,
664
+ mcpCommand,
665
+ ]),
666
+ );
667
+ };
668
+
669
+ /**
670
+ * Flag names that may carry a secret. Matched against the name only, so both
671
+ * `--api-token=value` and a separated `--api-token value` are refused, and a
672
+ * near miss of the documented `--api-key` spelling cannot slip through into
673
+ * the process argument vector.
674
+ */
675
+ const forbiddenCredentialFlagPattern =
676
+ /^--[^=]*(?:key|token|secret|password|passwd|credential)[^=]*(?:=|$)/i;
677
+
678
+ const hasForbiddenCredentialArgument = (argv: ReadonlyArray<string>): boolean =>
679
+ argv.some((argument) => forbiddenCredentialFlagPattern.test(argument));
680
+
681
+ /**
682
+ * Describe a CLI parse failure without copying any argument text.
683
+ *
684
+ * Effect renders argument values inside its `CliError` messages — `InvalidValue`
685
+ * embeds the rejected value verbatim — so the envelope reason is derived from
686
+ * the failure tag alone. Callers who need specifics run the command with
687
+ * `--help`, which is rendered to the terminal rather than into the envelope.
688
+ *
689
+ * @param error A CLI parse or validation failure.
690
+ * @returns A fixed reason string that contains no argv-derived text.
691
+ */
692
+ const safeCliErrorReason = (error: CliError.CliError): string => {
693
+ switch (error._tag) {
694
+ case "ShowHelp":
695
+ return error.errors.length > 0 ? safeCliErrorReason(error.errors[0]!) : "Help requested";
696
+ case "UnrecognizedOption":
697
+ return "The command received an unrecognized flag";
698
+ case "DuplicateOption":
699
+ return "The command received the same flag more than once";
700
+ case "MissingOption":
701
+ return "The command is missing a required flag";
702
+ case "MissingArgument":
703
+ return "The command is missing a required argument";
704
+ case "UnexpectedArgument":
705
+ return "The command received an unexpected positional argument";
706
+ case "InvalidValue":
707
+ return "The command received an invalid flag or argument value";
708
+ case "UnknownSubcommand":
709
+ return "The command is not a known rfc subcommand";
710
+ default:
711
+ return "The command could not be parsed";
712
+ }
713
+ };
714
+
715
+ const application = makeApplication(makeDefaultCliDependencies());
716
+
717
+ /**
718
+ * Run the RFC CLI with a supplied argument vector and injectable side effects.
719
+ *
720
+ * @param argv Arguments after the binary name.
721
+ * @param dependencies Process and credential boundaries for this invocation.
722
+ * @returns Zero for a valid command result and one for a protocol or runtime failure.
723
+ */
724
+ export const run = async (
725
+ argv: ReadonlyArray<string>,
726
+ dependencies: RfcCliDependencies = makeDefaultCliDependencies(),
727
+ ): Promise<number> => {
728
+ if (hasForbiddenCredentialArgument(argv)) {
729
+ dependencies.writeStderr(
730
+ `${JSON.stringify({
731
+ schemaVersion,
732
+ kind: "error",
733
+ error: {
734
+ code: "invalid_input",
735
+ message: "The TypeSafe API key must be supplied through --stdin or an interactive prompt",
736
+ },
737
+ })}\n`,
738
+ );
739
+ return 1;
740
+ }
741
+
742
+ const renderCliOutput = argv.some(
743
+ (argument) => argument === "--help" || argument === "-h" || argument === "--version",
744
+ );
745
+ const hostConsole = globalThis.console;
746
+ const cliConsole = Object.assign(Object.create(hostConsole), {
747
+ log: (...args: Parameters<typeof hostConsole.log>) => {
748
+ if (renderCliOutput) hostConsole.log(...args);
749
+ },
750
+ error: (...args: Parameters<typeof hostConsole.error>) => {
751
+ if (renderCliOutput) hostConsole.error(...args);
752
+ },
753
+ }) as Console.Console;
754
+
755
+ try {
756
+ const program = Command.runWith(makeApplication(dependencies), {
757
+ version: "0.1.0",
758
+ renderErrors: false,
759
+ })(argv);
760
+
761
+ await Effect.runPromise(
762
+ program.pipe(
763
+ Effect.provide(NodeServices.layer),
764
+ Effect.provideService(Console.Console, cliConsole),
765
+ ),
766
+ );
767
+ return 0;
768
+ } catch (error) {
769
+ const protocolError =
770
+ CliError.isCliError(error) &&
771
+ error._tag !== "UserError" &&
772
+ (error._tag !== "ShowHelp" || error.errors.length > 0)
773
+ ? new InvalidInputError({ reason: safeCliErrorReason(error) })
774
+ : error;
775
+ dependencies.writeStderr(`${JSON.stringify(toCliErrorEnvelope(protocolError))}\n`);
776
+ return 1;
777
+ }
778
+ };
779
+
780
+ /**
781
+ * The production command tree used by package consumers and the process entrypoint.
782
+ */
783
+ export const command = application;