@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/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # `@wyattjoh/rfc`
2
+
3
+ This package exposes the RFC evidence engine through an agent-facing CLI and a self-describing local MCP server. It is the reference for the process protocol, the MCP surface, credential handling, and configuration; start from the [repository README](../../README.md) for what the tool is, how to install it, and what it sends where.
4
+
5
+ ## MCP server
6
+
7
+ Run the MCP server over stdio:
8
+
9
+ ```sh
10
+ rfc mcp
11
+ ```
12
+
13
+ An MCP host should launch that command directly and treat standard output as protocol traffic. The server advertises the complete bounded workflow in its initialization instructions and exposes the full Markdown reference at `rfc://docs/agent-workflow`, so a connected model does not need this repository's skill or direct CLI access.
14
+
15
+ The model-facing tools are:
16
+
17
+ - `research_known_rfc`
18
+ - `research_topic`
19
+ - `verify_citation`
20
+ - `source_cache_status`
21
+ - `source_cache_remove`
22
+ - `auth_status`
23
+
24
+ Each successful tool call returns concise text plus the complete version-two result as validated structured content. Operational failures are MCP tool errors containing the same safe version-two error envelope as the CLI. Valid fail-closed research statuses and citation verdicts remain successful domain results. `source_cache_remove` requires `confirm: true` and is marked destructive and idempotent.
25
+
26
+ Provider credentials are intentionally outside the model-facing mutation surface. The MCP can inspect safe credential status but can never accept, reveal, add, or remove a key. Configure the credential through `rfc auth add` before launching the server. The stored key is resolved separately for every semantic tool call.
27
+
28
+ Trusted operators may select the same deterministic test or self-hosted boundaries at process startup:
29
+
30
+ ```sh
31
+ rfc mcp \
32
+ --cache-directory /path/to/cache \
33
+ --datatracker-api-url https://datatracker.example/api/v1 \
34
+ --typesafe-api-url https://typesafe.example/api
35
+ ```
36
+
37
+ Those values are fixed for the MCP process and never appear in tool input schemas. This prevents a model from redirecting credential-bearing provider traffic, issuing arbitrary metadata requests, or selecting arbitrary filesystem paths. Each call creates and closes its own RFC client, preserving CLI isolation and allowing credential rotation while the server remains running.
38
+
39
+ ## Process protocol
40
+
41
+ Research uses the version-two public protocol and accepts canonical JSON on standard input. A known-RFC request supplies an RFC identifier:
42
+
43
+ ```json
44
+ {
45
+ "schemaVersion": 2,
46
+ "question": "What does HTTP require of a client?",
47
+ "rfc": "RFC9110"
48
+ }
49
+ ```
50
+
51
+ A topic request sets `rfc` to `null` and supplies one to four ordered search terms:
52
+
53
+ ```json
54
+ {
55
+ "schemaVersion": 2,
56
+ "question": "What does HTTP require of a client?",
57
+ "rfc": null,
58
+ "searchTerms": ["HTTP semantics", "client request"]
59
+ }
60
+ ```
61
+
62
+ When standard input contains non-whitespace input, it is authoritative and convenience flags are ignored. When standard input is empty, use `--question` with either `--rfc` or one to four repeatable `--search-term` flags. `--cache-directory`, `--datatracker-api-url`, and `--typesafe-api-url` are available for deterministic preflight and local testing. JSON is always the automation default; human rendering is an explicit opt-in. Corpus-wide metadata management and bulk source operations are not part of the public client or CLI. Removed version-one `catalog status`, `catalog refresh`, and source-prefetch commands are rejected rather than emulated.
63
+
64
+ Known-RFC research fetches exact request-local metadata and recursively follows only bounded updating or obsoleting successors. Topic research issues one bounded title query and one bounded abstract query for each caller-supplied term, deterministically merges candidates in term order, and uses TypeSafe native multi-question scoring before source retrieval. Empty discovery returns `needs_review` without invoking TypeSafe and reports `atomicity: null` because no semantic judgment was made. Datatracker response bodies are streamed through a 1 MiB cap and decoded with bounded field lengths before any metadata reaches TypeSafe. Only the explicit search terms are sent to Datatracker; the natural-language question is not. Search terms appear in full Datatracker request URLs and can therefore appear in retrieval diagnostics, errors, and upstream access logs.
65
+
66
+ Requested RFC Editor plain text is cached individually with its canonical URL, integrity hash, ETag, and HTTP freshness deadline. Fresh text is reused without a network request. Stale text is conditionally revalidated and is never used when authoritative revalidation fails. `rfc cache status --rfc RFC9110` reports a local hit or miss, while `rfc cache remove --rfc RFC9110` removes only that named entry; neither command performs network access, and no bulk cache command is provided. Source retrieval accepts only a `200` body with an explicit `text/plain` Content-Type or a `304` conditional response, enforces one ten-second deadline across the complete operation, and rejects bodies above 8 MiB while streaming. Each evidence passage contains an exact quote, absolute UTF-8 byte offsets into the SHA-256 source, the declared `offsetUnit: "utf8-byte"`, canonical URLs, and a nullable best-effort section label. When a request ends without accepted evidence, the result can also include one request-local entry in `reviewCandidates`: the strongest semantically qualifying passage, falling back to the highest-ranked deterministic lexical passage, with exact canonical provenance and its semantic selection probability. The candidate is explicitly unaccepted and exists only to support bounded human or agent review without re-query loops. Human output labels them `Review candidate: not accepted evidence`. Version-two bundle diagnostics use `metadataMs` and `discoveredDocuments`, report full upstream URLs, attempts and statuses, request-local timings and counts, candidate or traversal bounds, explicit bounded traversal exits, and the source-cache outcome. Topic traces distinguish `upstreamRows`, all deduplicated `uniqueCandidates`, the 32-document `mergeLimit`, `semanticCandidates` sent to TypeSafe, and `selectedSources` advanced to RFC Editor retrieval. Public RFC documents omit relationship fields; currency paths and diagnostics carry only the relationships actually fetched. Topic discovery accepts each bounded first page and reports `topicTruncated: true` when Datatracker advertises additional rows or the deterministic merge reaches its cap; it never follows unbounded pagination.
67
+
68
+ Known-RFC currency research never silently replaces the requested RFC: update and obsoletion relationships are traversed deterministically with bounded, cycle-safe paths, and terminal current RFC contexts are researched independently. Requested/current evidence retains context-aware provenance and diagnostics. Incomplete successor coverage is reported as `partial` or `needs_review`; changed or ambiguous normative wording is not accepted as compatible.
69
+
70
+ Citation verification accepts canonical JSON with an RFC identifier, factual claim, exact quotation, and optional offset:
71
+
72
+ ```json
73
+ {
74
+ "schemaVersion": 2,
75
+ "rfc": "RFC9110",
76
+ "claim": "The client must send a request.",
77
+ "quote": "The client MUST send a request.",
78
+ "offset": null
79
+ }
80
+ ```
81
+
82
+ The optional `offset` is an absolute UTF-8 byte offset into the exact authoritative RFC Editor source identified by the returned SHA-256 `sourceHash`; it is not a JavaScript UTF-16 string index. Results declare this unit as `provenance.offsetUnit: "utf8-byte"`, and `startOffset`/`endOffset` can be used to slice the hashed source bytes and recover the exact returned quote. Use it with `rfc verify-citation < citation.json`, or provide `--rfc`, `--claim`, `--quote`, and optional `--offset` convenience flags. The verifier performs one request-local exact Datatracker document lookup without successor traversal, loads the live source, locates the quote before making a semantic request, returns `fabricated` for absent text without calling TypeSafe, and rejects ambiguous repeated quotes unless an exact offset selects one occurrence. Present quotes receive version-two `verified`, `unsupported`, or `contradicted` results with exact provenance, probabilities, confidence, model identity, usage, timings, and retrieval traces including source-cache outcomes.
83
+
84
+ Errors are versioned JSON envelopes on standard error and return a nonzero exit code. Valid domain outcomes, including `fabricated`, use standard output and a zero exit code.
85
+
86
+ Research and citation results report provider usage in `diagnostics.usage`. They also include `diagnostics.inputCost.estimatedUsd` and the `rateUsdPerMillionTokens` used for the estimate. Jev 1.13 input is priced at $0.042 per million tokens; output tokens are free. Missing usage or an unknown provider-resolved model leaves the estimate null rather than applying an assumed price. Human output prints the input-token count and estimated USD cost directly.
87
+
88
+ Every successful research or citation operation also updates the per-user running total at `~/.config/rfc/usage.json`. The versioned JSON file separates priced tokens, unpriced tokens, and operations with no provider-reported usage so `estimatedInputCostUsd` is never mistaken for a complete estimate when pricing is unavailable. Updates use a lock and atomic rename to preserve concurrent CLI invocations. A persistence failure leaves the successful result on standard output and emits a version-two `usage_accounting_failed` warning on standard error instead of encouraging a retry that could incur the provider charge again.
89
+
90
+ Run `rfc costs` to read those cumulative global totals without changing them. JSON output uses the same validated `rfc_usage_totals` document stored on disk. `rfc costs --format human` prints the update timestamp, operation and token coverage, and estimated USD total. When the usage file does not exist yet, the command reports zero totals and does not create it.
91
+
92
+ The opt-in `bun run benchmark:topic` command performs a normal topic research warm-up and then repeats the same schema-version-two request; it has no prefetch-only path. Set `RFC_TOPIC_BENCHMARK=1`, `RFC_CACHE_DIRECTORY`, and optionally `RFC_TOPIC_BENCHMARK_SEARCH_TERMS` as a JSON array of ordered terms. The JSON report separates live RFC discovery, RFC source-cache, document-selection, lexical, passage-selection, relation, semantic, and total p95 timings and includes the warm-up and measured retrieval traces. The current latency target is reported only as provisional while `precision-v2` is uncalibrated, so this explicit benchmark does not claim a release pass and never runs in the normal test suite.
93
+
94
+ ## Provider credentials
95
+
96
+ The TypeSafe API key is stored by Bun's experimental `Bun.secrets` API under this stable identity:
97
+
98
+ - service: `com.wyattjoh.rfc`
99
+ - name: `typesafe-api-key`
100
+
101
+ Add it interactively with a masked prompt:
102
+
103
+ ```sh
104
+ rfc auth add
105
+ ```
106
+
107
+ For automation, explicitly pipe the key through standard input. It is never accepted as an argv value:
108
+
109
+ ```sh
110
+ cat /path/to/a-protected-key-input | rfc auth add --stdin
111
+ ```
112
+
113
+ `auth status` reports only whether a key is configured and the service/name identity. `auth remove` is deterministic: its versioned result reports `removed: true` when a key existed and `removed: false` when it was already absent. JSON is the default; add `--format human` only for human-readable output. The key is not included in command output, diagnostics, snapshots, or error envelopes.
114
+
115
+ Bun maps the store to the host credential service: macOS Keychain, Linux Secret Service (libsecret, such as GNOME Keyring or KWallet), or Windows Credential Manager. Linux requires a running and unlocked Secret Service daemon; macOS requires Keychain access; Windows requires Credential Manager. This repository pins Bun `1.4.2` in `package.json` and tests against that version because `Bun.secrets` is experimental and may change.
116
+
117
+ To migrate an existing setup, run `rfc auth add`, verify with `rfc auth status`, then delete the obsolete plaintext, `.env`, Varlock, dotenv, or 1Password-backed TypeSafe API-key configuration. Research, citation verification, and live evaluation all resolve this same credential lazily before constructing the provider.
118
+
119
+ ## Precision calibration
120
+
121
+ Automatic answering is off. `answered` requires a locally present calibration report proving a passing release gate, a recorded human acceptance, and explicit runtime enablement; anything weaker fails closed to `needs_review`. The most recent calibration was **rejected**, so a published install returns evidence, provenance, and a non-answer status.
122
+
123
+ Run a calibration against the live provider only through the explicit evaluator, after storing a credential. It costs money and reaches the network:
124
+
125
+ ```sh
126
+ rfc auth status
127
+ bun run evaluate:live
128
+ ```
129
+
130
+ It writes a sanitized report to `.scratch/rfc-evaluation-report.json`, exiting zero for a passing gate and two for a complete report that fails review. The report never contains credentials, prompts, questions beyond the committed corpus, or provider reasoning.
131
+
132
+ What the corpus measures, what the report contains, and the recorded 2026-09-21 rejection are in [ADR 0004](../../docs/adr/0004-gate-automatic-answers-on-a-reviewed-calibration.md). The durable decision itself is committed in `packages/rfc-core/src/precision-v2-release-decision.ts`.
133
+
134
+ ## Configuration
135
+
136
+ Non-secret model, policy, evaluation, cache, output, and automatic-answer settings use typed defaults in the CLI composition root. They are not loaded from Varlock, dotenv, `.env` files, or ordinary environment variables. `bunfig.toml` disables Bun dotenv loading. Use explicit CLI flags for command-specific values such as cache and provider URLs; the credential store is the only authority for the TypeSafe API key. After a release attestation is reviewed and accepted, automatic answering must still be explicitly enabled and the local report must match every release-bound identity; rejected, pending, missing, stale, or tampered artifacts remain fail-closed and report `needs_review`.
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@wyattjoh/rfc",
3
+ "version": "0.1.0",
4
+ "description": "Agent-facing CLI and MCP server for evidence-grounded IETF RFC research.",
5
+ "keywords": [
6
+ "cli",
7
+ "ietf",
8
+ "mcp",
9
+ "model-context-protocol",
10
+ "rfc"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "Wyatt Johnson",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/wyattjoh/rfc.git",
17
+ "directory": "packages/rfc"
18
+ },
19
+ "bin": {
20
+ "rfc": "./src/bin.ts"
21
+ },
22
+ "files": [
23
+ "src"
24
+ ],
25
+ "type": "module",
26
+ "main": "./src/index.ts",
27
+ "types": "./src/index.ts",
28
+ "exports": {
29
+ ".": "./src/index.ts"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "scripts": {
35
+ "build": "bun build src/bin.ts --outdir dist --target bun",
36
+ "test": "bun test",
37
+ "evaluate:live": "cd ../.. && bun run packages/rfc/src/live-evaluation-bin.ts",
38
+ "typecheck": "tsc --noEmit -p tsconfig.json"
39
+ },
40
+ "dependencies": {
41
+ "@effect/platform-node": "4.0.0-rc.116",
42
+ "@modelcontextprotocol/server": "2.0.0",
43
+ "@wyattjoh/rfc-core": "0.1.0",
44
+ "effect": "4.0.0-rc.116"
45
+ },
46
+ "devDependencies": {
47
+ "@modelcontextprotocol/client": "2.0.0",
48
+ "@types/bun": "1.4.2",
49
+ "typescript": "5.9.3"
50
+ },
51
+ "engines": {
52
+ "bun": ">=1.4.2"
53
+ }
54
+ }
package/src/bin.ts ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { run } from "./main";
4
+
5
+ process.exitCode = await run(process.argv.slice(2));
package/src/config.ts ADDED
@@ -0,0 +1,114 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { Schema } from "effect";
3
+ import {
4
+ automaticAnswerActivationFromReport,
5
+ evaluationModelAlias,
6
+ evaluationPolicy,
7
+ pinnedJevModel,
8
+ } from "@wyattjoh/rfc-core";
9
+ import type { AutomaticAnswerActivation } from "@wyattjoh/rfc-core";
10
+
11
+ /**
12
+ * Schema for non-secret configuration consumed by the CLI composition root.
13
+ */
14
+ export const RfcCliConfigSchema = Schema.Struct({
15
+ modelAlias: Schema.Literal(pinnedJevModel),
16
+ policyPreset: Schema.Literal(evaluationPolicy.policyVersion),
17
+ evaluationModel: Schema.Literal(evaluationModelAlias),
18
+ pinnedModel: Schema.Literal(pinnedJevModel),
19
+ liveEvaluation: Schema.Boolean,
20
+ automaticAnswerEnabled: Schema.Boolean,
21
+ evaluationCacheDirectory: Schema.NonEmptyString,
22
+ evaluationOutput: Schema.NonEmptyString,
23
+ });
24
+
25
+ /**
26
+ * Configuration needed by the CLI composition root after typed defaults are
27
+ * applied. It contains no provider credential.
28
+ */
29
+ export type RfcCliConfig = Schema.Schema.Type<typeof RfcCliConfigSchema>;
30
+
31
+ /**
32
+ * Explicit non-secret configuration overrides used by the live evaluator and
33
+ * deterministic callers. Every field is intentionally typed and non-secret.
34
+ */
35
+ export interface RfcCliConfigOverrides {
36
+ /**
37
+ * Whether the caller explicitly enabled the live evaluator.
38
+ */
39
+ readonly liveEvaluation: boolean | undefined;
40
+ /**
41
+ * Whether a reviewed calibration report may activate answered results.
42
+ */
43
+ readonly automaticAnswerEnabled: boolean | undefined;
44
+ /**
45
+ * Directory used for evaluation source caches.
46
+ */
47
+ readonly evaluationCacheDirectory: string | undefined;
48
+ /**
49
+ * Path used for the sanitized evaluation report.
50
+ */
51
+ readonly evaluationOutput: string | undefined;
52
+ }
53
+
54
+ const defaultConfigValue = {
55
+ modelAlias: pinnedJevModel,
56
+ policyPreset: evaluationPolicy.policyVersion,
57
+ evaluationModel: evaluationModelAlias,
58
+ pinnedModel: pinnedJevModel,
59
+ liveEvaluation: false,
60
+ automaticAnswerEnabled: false,
61
+ evaluationCacheDirectory: ".scratch/rfc-evaluation-cache",
62
+ evaluationOutput: ".scratch/rfc-evaluation-report.json",
63
+ } satisfies RfcCliConfig;
64
+
65
+ const noOverrides: RfcCliConfigOverrides = {
66
+ liveEvaluation: undefined,
67
+ automaticAnswerEnabled: undefined,
68
+ evaluationCacheDirectory: undefined,
69
+ evaluationOutput: undefined,
70
+ };
71
+
72
+ /**
73
+ * The typed non-secret defaults used by ordinary CLI commands.
74
+ */
75
+ export const defaultCliConfig: RfcCliConfig = Object.freeze(
76
+ Schema.decodeUnknownSync(RfcCliConfigSchema)(defaultConfigValue),
77
+ );
78
+
79
+ /**
80
+ * Read typed non-secret CLI configuration without consulting environment
81
+ * variables, dotenv files, or a credential store.
82
+ *
83
+ * @param overrides Explicit non-secret values supplied by a command or test.
84
+ * @returns Schema-validated CLI configuration.
85
+ */
86
+ export const readCliConfig = (overrides: RfcCliConfigOverrides = noOverrides): RfcCliConfig =>
87
+ Schema.decodeUnknownSync(RfcCliConfigSchema)({
88
+ ...defaultCliConfig,
89
+ liveEvaluation: overrides.liveEvaluation ?? defaultCliConfig.liveEvaluation,
90
+ automaticAnswerEnabled:
91
+ overrides.automaticAnswerEnabled ?? defaultCliConfig.automaticAnswerEnabled,
92
+ evaluationCacheDirectory:
93
+ overrides.evaluationCacheDirectory ?? defaultCliConfig.evaluationCacheDirectory,
94
+ evaluationOutput: overrides.evaluationOutput ?? defaultCliConfig.evaluationOutput,
95
+ });
96
+
97
+ /**
98
+ * Resolve automatic-answer activation from an explicit opt-in and a passing
99
+ * calibration artifact with the current release attestation.
100
+ *
101
+ * @param config Validated non-secret CLI configuration.
102
+ * @returns An opaque activation proof, or undefined when activation fails closed.
103
+ */
104
+ export const automaticAnswerActivationFor = (
105
+ config: RfcCliConfig,
106
+ ): AutomaticAnswerActivation | undefined => {
107
+ if (!config.automaticAnswerEnabled) return undefined;
108
+ try {
109
+ const report = JSON.parse(readFileSync(config.evaluationOutput, "utf8")) as unknown;
110
+ return automaticAnswerActivationFromReport(report);
111
+ } catch {
112
+ return undefined;
113
+ }
114
+ };
@@ -0,0 +1,372 @@
1
+ import { Schema } from "effect";
2
+
3
+ /**
4
+ * The stable Bun credential-store service used by the RFC CLI.
5
+ */
6
+ export const credentialStoreService = "com.wyattjoh.rfc" as const;
7
+
8
+ /**
9
+ * The stable Bun credential-store name used for the TypeSafe API key.
10
+ */
11
+ export const credentialStoreName = "typesafe-api-key" as const;
12
+
13
+ /**
14
+ * The version shared by authentication command responses.
15
+ */
16
+ export const authSchemaVersion = 2 as const;
17
+
18
+ /**
19
+ * The operation being performed against the platform credential manager.
20
+ */
21
+ export const CredentialStoreOperationSchema = Schema.Literals(["get", "set", "delete"]);
22
+
23
+ /**
24
+ * A platform credential-manager operation.
25
+ */
26
+ export type CredentialStoreOperation = Schema.Schema.Type<typeof CredentialStoreOperationSchema>;
27
+
28
+ /**
29
+ * The safe categories used to classify platform credential-manager failures.
30
+ */
31
+ export const CredentialStoreFailureKindSchema = Schema.Literals([
32
+ "unavailable",
33
+ "denied",
34
+ "storage",
35
+ "deletion",
36
+ ]);
37
+
38
+ /**
39
+ * A safe platform credential-manager failure category.
40
+ */
41
+ export type CredentialStoreFailureKind = Schema.Schema.Type<
42
+ typeof CredentialStoreFailureKindSchema
43
+ >;
44
+
45
+ /**
46
+ * A credential-manager error that deliberately contains no provider secret or
47
+ * platform error message.
48
+ */
49
+ export class CredentialStoreError extends Schema.TaggedError<CredentialStoreError>()(
50
+ "CredentialStoreError",
51
+ {
52
+ operation: CredentialStoreOperationSchema,
53
+ kind: CredentialStoreFailureKindSchema,
54
+ },
55
+ ) {}
56
+
57
+ /**
58
+ * Signals that no TypeSafe API key is configured in the credential manager.
59
+ */
60
+ export class CredentialMissingError extends Schema.TaggedError<CredentialMissingError>()(
61
+ "CredentialMissingError",
62
+ {},
63
+ ) {}
64
+
65
+ /**
66
+ * Signals that authentication input was not a single non-empty credential.
67
+ */
68
+ export class CredentialInputError extends Schema.TaggedError<CredentialInputError>()(
69
+ "CredentialInputError",
70
+ {
71
+ reason: Schema.String,
72
+ },
73
+ ) {}
74
+
75
+ /**
76
+ * The options identifying one native Bun secret.
77
+ */
78
+ export interface BunSecretsOptions {
79
+ /**
80
+ * Stable service identifier.
81
+ */
82
+ readonly service: string;
83
+ /**
84
+ * Stable account/name identifier.
85
+ */
86
+ readonly name: string;
87
+ }
88
+
89
+ /**
90
+ * The narrow native Bun.secrets surface required by the CLI.
91
+ *
92
+ * Keeping this interface separate from Bun.secrets makes the credential
93
+ * boundary replaceable in deterministic tests and embedded callers.
94
+ */
95
+ export interface BunSecretsApi {
96
+ /**
97
+ * Retrieve a stored value, or null when it is absent.
98
+ */
99
+ readonly get: (options: BunSecretsOptions) => Promise<string | null>;
100
+ /**
101
+ * Store or overwrite a value.
102
+ */
103
+ readonly set: (options: BunSecretsOptions & { readonly value: string }) => Promise<void>;
104
+ /**
105
+ * Delete a value and report whether it existed.
106
+ */
107
+ readonly delete: (options: BunSecretsOptions) => Promise<boolean>;
108
+ }
109
+
110
+ /**
111
+ * The deep credential-store interface used by authentication and provider
112
+ * construction. It intentionally does not expose service or name parameters:
113
+ * every operation targets the one documented TypeSafe credential identity.
114
+ */
115
+ export interface CredentialStore {
116
+ /**
117
+ * Retrieve the TypeSafe API key, or null when absent.
118
+ */
119
+ readonly get: () => Promise<string | null>;
120
+ /**
121
+ * Store or overwrite the TypeSafe API key.
122
+ */
123
+ readonly set: (value: string) => Promise<void>;
124
+ /**
125
+ * Delete the TypeSafe API key and report whether it existed.
126
+ */
127
+ readonly delete: () => Promise<boolean>;
128
+ }
129
+
130
+ /**
131
+ * The public identity of the credential used by auth status and mutation
132
+ * results. It contains no credential value or derivative.
133
+ */
134
+ export interface CredentialStoreIdentity {
135
+ /**
136
+ * Stable service identifier.
137
+ */
138
+ readonly service: typeof credentialStoreService;
139
+ /**
140
+ * Stable name identifier.
141
+ */
142
+ readonly name: typeof credentialStoreName;
143
+ }
144
+
145
+ /**
146
+ * The documented credential-store identity.
147
+ */
148
+ export const credentialStoreIdentity: CredentialStoreIdentity = Object.freeze({
149
+ service: credentialStoreService,
150
+ name: credentialStoreName,
151
+ });
152
+
153
+ const nativeOptions: BunSecretsOptions = credentialStoreIdentity;
154
+
155
+ const errorText = (error: unknown): string => {
156
+ if (typeof error !== "object" || error === null) return "";
157
+ const candidate = error as {
158
+ readonly code?: unknown;
159
+ readonly name?: unknown;
160
+ readonly message?: unknown;
161
+ };
162
+ return [candidate.code, candidate.name, candidate.message]
163
+ .filter((value): value is string => typeof value === "string")
164
+ .join(" ")
165
+ .toLowerCase();
166
+ };
167
+
168
+ const failureKindFor = (
169
+ operation: CredentialStoreOperation,
170
+ error: unknown,
171
+ ): CredentialStoreFailureKind => {
172
+ const text = errorText(error);
173
+ if (
174
+ /access.?denied|permission|not authorized|unauthori[sz]ed|forbidden|eacces|eperm/.test(text)
175
+ ) {
176
+ return "denied";
177
+ }
178
+ if (
179
+ /unavailable|not found|not running|unsupported|not implemented|keychain.*(?:unavailable|not found|not running)|secret service.*(?:unavailable|not found|not running)|credential manager.*(?:unavailable|not found|not running)|libsecret.*(?:unavailable|not found|not running)|no such service/.test(
180
+ text,
181
+ )
182
+ ) {
183
+ return "unavailable";
184
+ }
185
+ return operation === "delete" ? "deletion" : operation === "set" ? "storage" : "unavailable";
186
+ };
187
+
188
+ const runStoreOperation = async <A>(
189
+ operation: CredentialStoreOperation,
190
+ action: () => Promise<A>,
191
+ ): Promise<A> => {
192
+ try {
193
+ return await action();
194
+ } catch (error) {
195
+ if (error instanceof CredentialStoreError) throw error;
196
+ throw new CredentialStoreError({
197
+ operation,
198
+ kind: failureKindFor(operation, error),
199
+ });
200
+ }
201
+ };
202
+
203
+ /**
204
+ * Construct the RFC credential boundary over an injectable Bun.secrets-like
205
+ * implementation.
206
+ *
207
+ * @param secrets Native Bun.secrets or a deterministic replacement.
208
+ * @returns A credential store scoped to the documented service/name pair.
209
+ */
210
+ export const makeCredentialStore = (secrets: BunSecretsApi = Bun.secrets): CredentialStore => ({
211
+ get: () => runStoreOperation("get", () => secrets.get(nativeOptions)),
212
+ set: (value) => runStoreOperation("set", () => secrets.set({ ...nativeOptions, value })),
213
+ delete: () => runStoreOperation("delete", () => secrets.delete(nativeOptions)),
214
+ });
215
+
216
+ /**
217
+ * Construct the production credential boundary backed by Bun's OS credential
218
+ * manager.
219
+ *
220
+ * @returns A Bun.secrets-backed TypeSafe credential store.
221
+ */
222
+ export const makeDefaultCredentialStore = (): CredentialStore => makeCredentialStore();
223
+
224
+ /**
225
+ * Validate and normalize a credential received from an explicit input source.
226
+ *
227
+ * @param value Raw interactive or standard-input content.
228
+ * @returns The single-line credential without its terminal line ending.
229
+ * @throws CredentialInputError when input is empty or contains another line.
230
+ */
231
+ export const normalizeCredentialInput = (value: string): string => {
232
+ const normalized = value.replace(/\r?\n$/, "").trim();
233
+ if (normalized.length === 0 || /[\r\n]/.test(normalized)) {
234
+ throw new CredentialInputError({
235
+ reason: "The TypeSafe API key must be a non-empty single line",
236
+ });
237
+ }
238
+ return normalized;
239
+ };
240
+
241
+ /**
242
+ * Read the stored key without returning it in a public result.
243
+ *
244
+ * @param store Injectable credential boundary.
245
+ * @returns Whether a non-empty credential is configured.
246
+ */
247
+ export const hasStoredCredential = async (store: CredentialStore): Promise<boolean> => {
248
+ const value = await runStoreOperation("get", store.get);
249
+ return value !== null && value.length > 0;
250
+ };
251
+
252
+ /**
253
+ * Resolve the stored TypeSafe API key immediately before provider creation.
254
+ *
255
+ * @param store Injectable credential boundary.
256
+ * @returns The secret value for the provider constructor.
257
+ * @throws CredentialMissingError when no non-empty key is configured.
258
+ */
259
+ export const resolveStoredCredential = async (store: CredentialStore): Promise<string> => {
260
+ const value = await runStoreOperation("get", store.get);
261
+ if (value === null || value.length === 0) {
262
+ throw new CredentialMissingError({});
263
+ }
264
+ return value;
265
+ };
266
+
267
+ /**
268
+ * Store or overwrite a TypeSafe API key and return only safe metadata.
269
+ *
270
+ * @param store Injectable credential boundary.
271
+ * @param value Raw credential input.
272
+ * @returns Versioned metadata indicating whether an existing value was replaced.
273
+ */
274
+ export const addStoredCredential = async (
275
+ store: CredentialStore,
276
+ value: string,
277
+ ): Promise<AuthAddResult> => {
278
+ const normalized = normalizeCredentialInput(value);
279
+ const existed = await hasStoredCredential(store);
280
+ await runStoreOperation("set", () => store.set(normalized));
281
+ return Schema.decodeUnknownSync(AuthAddResultSchema)({
282
+ schemaVersion: authSchemaVersion,
283
+ kind: "auth_add",
284
+ configured: true,
285
+ replaced: existed,
286
+ service: credentialStoreService,
287
+ name: credentialStoreName,
288
+ });
289
+ };
290
+
291
+ /**
292
+ * Return safe status information for the stored TypeSafe API key.
293
+ *
294
+ * @param store Injectable credential boundary.
295
+ * @returns Whether a credential is configured and its stable store identity.
296
+ */
297
+ export const storedCredentialStatus = async (store: CredentialStore): Promise<AuthStatus> =>
298
+ Schema.decodeUnknownSync(AuthStatusSchema)({
299
+ schemaVersion: authSchemaVersion,
300
+ kind: "auth_status",
301
+ configured: await hasStoredCredential(store),
302
+ service: credentialStoreService,
303
+ name: credentialStoreName,
304
+ });
305
+
306
+ /**
307
+ * Delete the stored TypeSafe API key without exposing its value.
308
+ *
309
+ * @param store Injectable credential boundary.
310
+ * @returns A deterministic result for both existing and already-absent keys.
311
+ */
312
+ export const removeStoredCredential = async (store: CredentialStore): Promise<AuthRemoveResult> => {
313
+ const removed = await runStoreOperation("delete", store.delete);
314
+ return Schema.decodeUnknownSync(AuthRemoveResultSchema)({
315
+ schemaVersion: authSchemaVersion,
316
+ kind: "auth_remove",
317
+ removed,
318
+ configured: false,
319
+ service: credentialStoreService,
320
+ name: credentialStoreName,
321
+ });
322
+ };
323
+
324
+ /**
325
+ * Versioned result emitted after storing a credential.
326
+ */
327
+ export const AuthAddResultSchema = Schema.Struct({
328
+ schemaVersion: Schema.Literal(authSchemaVersion),
329
+ kind: Schema.Literal("auth_add"),
330
+ configured: Schema.Boolean,
331
+ replaced: Schema.Boolean,
332
+ service: Schema.Literal(credentialStoreService),
333
+ name: Schema.Literal(credentialStoreName),
334
+ });
335
+
336
+ /**
337
+ * Versioned metadata emitted after storing a credential.
338
+ */
339
+ export type AuthAddResult = Schema.Schema.Type<typeof AuthAddResultSchema>;
340
+
341
+ /**
342
+ * Versioned result emitted by auth status.
343
+ */
344
+ export const AuthStatusSchema = Schema.Struct({
345
+ schemaVersion: Schema.Literal(authSchemaVersion),
346
+ kind: Schema.Literal("auth_status"),
347
+ configured: Schema.Boolean,
348
+ service: Schema.Literal(credentialStoreService),
349
+ name: Schema.Literal(credentialStoreName),
350
+ });
351
+
352
+ /**
353
+ * Versioned safe credential status metadata.
354
+ */
355
+ export type AuthStatus = Schema.Schema.Type<typeof AuthStatusSchema>;
356
+
357
+ /**
358
+ * Versioned result emitted after removing a credential.
359
+ */
360
+ export const AuthRemoveResultSchema = Schema.Struct({
361
+ schemaVersion: Schema.Literal(authSchemaVersion),
362
+ kind: Schema.Literal("auth_remove"),
363
+ removed: Schema.Boolean,
364
+ configured: Schema.Boolean,
365
+ service: Schema.Literal(credentialStoreService),
366
+ name: Schema.Literal(credentialStoreName),
367
+ });
368
+
369
+ /**
370
+ * Versioned safe credential-removal metadata.
371
+ */
372
+ export type AuthRemoveResult = Schema.Schema.Type<typeof AuthRemoveResultSchema>;