@herbertgao/pi-extensions 2026.11.18 → 2026.11.20
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/CHANGELOG.md +18 -0
- package/README.md +5 -5
- package/THIRD_PARTY_NOTICES.md +3 -24
- package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
- package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
- package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
- package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
- package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
- package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
- package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
- package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
- package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
- package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
- package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
- package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
- package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
- package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
- package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
- package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
- package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
- package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
- package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
- package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
- package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
- package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
- package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
- package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
- package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
- package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
- package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
- package/node_modules/pi-commandcode-provider/README.md +3 -2
- package/node_modules/pi-commandcode-provider/index.ts +120 -13
- package/node_modules/pi-commandcode-provider/package.json +4 -3
- package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
- package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
- package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
- package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
- package/node_modules/pi-typesafe/README.md +1 -1
- package/node_modules/pi-typesafe/dist/ask.js +6 -3
- package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
- package/node_modules/pi-typesafe/dist/auth.js +159 -55
- package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
- package/node_modules/pi-typesafe/dist/batch.js +62 -22
- package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
- package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
- package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
- package/node_modules/pi-typesafe/dist/client.js +67 -27
- package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
- package/node_modules/pi-typesafe/dist/errors.js +105 -2
- package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
- package/node_modules/pi-typesafe/dist/extension.js +206 -106
- package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
- package/node_modules/pi-typesafe/dist/index.js +3 -3
- package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
- package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
- package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
- package/node_modules/pi-typesafe/dist/login.js +167 -13
- package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
- package/node_modules/pi-typesafe/dist/schema.js +47 -13
- package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
- package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
- package/node_modules/pi-typesafe/dist/usage.js +79 -40
- package/node_modules/pi-typesafe/package.json +3 -3
- package/package.json +12 -15
- package/node_modules/pi-antigravity/README.md +0 -298
- package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
- package/node_modules/pi-antigravity/package.json +0 -87
- package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
- package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
- package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
- package/node_modules/pi-antigravity/src/client/client.ts +0 -602
- package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
- package/node_modules/pi-antigravity/src/client/index.ts +0 -2
- package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
- package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
- package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
- package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
- package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
- package/node_modules/pi-antigravity/src/image/image.ts +0 -427
- package/node_modules/pi-antigravity/src/image/index.ts +0 -1
- package/node_modules/pi-antigravity/src/image/native.ts +0 -69
- package/node_modules/pi-antigravity/src/index.ts +0 -547
- package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
- package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
- package/node_modules/pi-antigravity/src/models/index.ts +0 -3
- package/node_modules/pi-antigravity/src/models/models.ts +0 -647
- package/node_modules/pi-antigravity/src/search/index.ts +0 -1
- package/node_modules/pi-antigravity/src/search/search.ts +0 -967
- package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
- package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
- package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
- package/node_modules/pi-antigravity/src/types/index.ts +0 -2
- package/node_modules/pi-antigravity/src/types/types.ts +0 -329
- package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
- package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
- package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
- package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
- package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
- package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
- package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
- package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
- package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
- package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
- package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
- package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
- package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
- package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
- package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
- package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
- package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
- package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
- package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
- package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
- package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
- package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
- package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
- package/node_modules/pi-antigravity/tsconfig.json +0 -21
|
@@ -20,7 +20,7 @@ export interface TemporaryPricing {
|
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
export const PRICING_SOURCE_URL = "https://commandcode.ai/docs/resources/pricing-limits"
|
|
23
|
-
export const PRICING_LAST_VERIFIED = "2026-11-
|
|
23
|
+
export const PRICING_LAST_VERIFIED = "2026-11-20"
|
|
24
24
|
|
|
25
25
|
export const ZERO_MODEL_COST: CommandCodeModelCost = {
|
|
26
26
|
input: 0,
|
|
@@ -57,6 +57,7 @@ export const MODEL_COSTS: Readonly<Record<string, CommandCodeModelCost>> = {
|
|
|
57
57
|
"inclusionai/ling-3.1-flash": { input: 0.3, output: 0.9, cacheRead: 0.06, cacheWrite: 0 },
|
|
58
58
|
"mistral/mistral-large-4": { input: 1.36, output: 4.18, cacheRead: 0.14, cacheWrite: 0 },
|
|
59
59
|
"tencent/hy3-paid": { input: 0.14, output: 0.58, cacheRead: 0.035, cacheWrite: 0 },
|
|
60
|
+
"tencent/hy4": { input: 0.834, output: 2.501, cacheRead: 0.042, cacheWrite: 0 },
|
|
60
61
|
"tencent/hy4-flash": { input: 0.07, output: 0.281, cacheRead: 0.003, cacheWrite: 0 },
|
|
61
62
|
"tencent/hy4-preview": { input: 0.834, output: 2.501, cacheRead: 0.042, cacheWrite: 0 },
|
|
62
63
|
"moonshotai/Kimi-K3.1-Pro": { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 0 },
|
|
@@ -265,6 +266,20 @@ export const MODEL_COSTS: Readonly<Record<string, CommandCodeModelCost>> = {
|
|
|
265
266
|
},
|
|
266
267
|
|
|
267
268
|
// OpenAI
|
|
269
|
+
"gpt-6.2-astra": {
|
|
270
|
+
input: 8,
|
|
271
|
+
output: 40,
|
|
272
|
+
cacheRead: 0.4,
|
|
273
|
+
cacheWrite: 10,
|
|
274
|
+
tiers: [{ inputTokensAbove: 272_000, input: 16, output: 60, cacheRead: 0.8, cacheWrite: 20 }],
|
|
275
|
+
},
|
|
276
|
+
"gpt-6.2-sol": {
|
|
277
|
+
input: 2,
|
|
278
|
+
output: 10,
|
|
279
|
+
cacheRead: 0.1,
|
|
280
|
+
cacheWrite: 2.5,
|
|
281
|
+
tiers: [{ inputTokensAbove: 272_000, input: 4, output: 15, cacheRead: 0.2, cacheWrite: 5 }],
|
|
282
|
+
},
|
|
268
283
|
"gpt-6-astra": {
|
|
269
284
|
input: 10,
|
|
270
285
|
output: 50,
|
|
@@ -337,6 +352,7 @@ export const MODEL_COSTS: Readonly<Record<string, CommandCodeModelCost>> = {
|
|
|
337
352
|
cacheRead: 0.15,
|
|
338
353
|
cacheWrite: 0.08334,
|
|
339
354
|
},
|
|
355
|
+
"google/gemini-4-neon": { input: 3, output: 15, cacheRead: 0.15, cacheWrite: 0 },
|
|
340
356
|
"google/gemini-4-carbon": { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 0 },
|
|
341
357
|
"google/gemini-4-argon": { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 0 },
|
|
342
358
|
"google/gemini-3.8-flash": {
|
|
@@ -25,7 +25,8 @@ interface QuotaCommandApi {
|
|
|
25
25
|
|
|
26
26
|
interface RegisterQuotaCommandOptions {
|
|
27
27
|
apiBase: string
|
|
28
|
-
|
|
28
|
+
/** A function is resolved per run so a header changed after startup (ZDR) is sent. */
|
|
29
|
+
headers?: Record<string, string> | (() => Record<string, string> | undefined)
|
|
29
30
|
getConfiguredKey?: () => string | undefined
|
|
30
31
|
fetchQuota?: typeof fetchCommandCodeQuota
|
|
31
32
|
}
|
|
@@ -54,7 +55,7 @@ export function registerCommandCodeQuota(
|
|
|
54
55
|
const result = await fetchQuota({
|
|
55
56
|
apiKey,
|
|
56
57
|
baseUrl: options.apiBase,
|
|
57
|
-
extraHeaders: options.headers,
|
|
58
|
+
extraHeaders: typeof options.headers === "function" ? options.headers() : options.headers,
|
|
58
59
|
})
|
|
59
60
|
if (!result.ok) {
|
|
60
61
|
ctx.ui.notify(redactValue(result.error.message), "error")
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Zero-data-retention opt-in, carried in settings.json for hosts where setting
|
|
2
|
+
// a process environment variable is inconvenient. Command Code documents the
|
|
3
|
+
// `x-cmd-zdr: 1` request header and the `CMD_ZDR=1` CLI environment variable.
|
|
4
|
+
import { randomUUID } from "node:crypto"
|
|
5
|
+
import { lstat, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises"
|
|
6
|
+
import { dirname } from "node:path"
|
|
7
|
+
|
|
8
|
+
/** Top-level settings.json section owned by this provider. */
|
|
9
|
+
export const ZDR_SETTINGS_SECTION = "commandcode"
|
|
10
|
+
export const ZDR_SETTING_KEY = "enableZDR"
|
|
11
|
+
|
|
12
|
+
export type ZdrSource = "off" | "settings" | "env"
|
|
13
|
+
export type ZdrEnvVar = "CMD_ZDR" | "COMMANDCODE_ZDR"
|
|
14
|
+
|
|
15
|
+
export interface ZdrState {
|
|
16
|
+
enabled: boolean
|
|
17
|
+
source: ZdrSource
|
|
18
|
+
/** Environment variable that enabled ZDR, when `source` is `env`. */
|
|
19
|
+
envVar?: ZdrEnvVar
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type Environment = Record<string, string | undefined>
|
|
23
|
+
|
|
24
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
25
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The host's own settings parser tolerates a leading UTF-8 BOM, so both the
|
|
30
|
+
* reader and the writer do too: a BOM must not silently drop a saved opt-in.
|
|
31
|
+
*/
|
|
32
|
+
function stripBom(text: string): string {
|
|
33
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Only a literal `true` enables ZDR, so a typo cannot silently weaken privacy. */
|
|
37
|
+
export function readZdrSetting(settings: unknown): boolean {
|
|
38
|
+
if (!isRecord(settings)) return false
|
|
39
|
+
const section = settings[ZDR_SETTINGS_SECTION]
|
|
40
|
+
return isRecord(section) && section[ZDR_SETTING_KEY] === true
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `CMD_ZDR` is the documented name; the legacy alias stays supported. */
|
|
44
|
+
export function zdrEnvVar(env: Environment = process.env): ZdrEnvVar | undefined {
|
|
45
|
+
if (env.CMD_ZDR === "1") return "CMD_ZDR"
|
|
46
|
+
if (env.COMMANDCODE_ZDR === "1") return "COMMANDCODE_ZDR"
|
|
47
|
+
return undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The environment wins so a shell export cannot be silently weakened by a settings file. */
|
|
51
|
+
export function resolveZdr(settings: unknown, env: Environment = process.env): ZdrState {
|
|
52
|
+
const envVar = zdrEnvVar(env)
|
|
53
|
+
if (envVar) return { enabled: true, source: "env", envVar }
|
|
54
|
+
if (readZdrSetting(settings)) return { enabled: true, source: "settings" }
|
|
55
|
+
return { enabled: false, source: "off" }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Read the opt-in from the agent settings file itself. Startup uses this instead
|
|
60
|
+
* of the host's merged global+project view: the opt-in is owned by the agent
|
|
61
|
+
* file that saveZdrSetting writes, so a project settings override cannot
|
|
62
|
+
* silently turn it off (or on) after a restart.
|
|
63
|
+
*
|
|
64
|
+
* A missing or unreadable file is "off"; a malformed file is left for the write
|
|
65
|
+
* path to report rather than failing the provider load.
|
|
66
|
+
*/
|
|
67
|
+
export async function loadZdrSettings(path: string): Promise<unknown> {
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(stripBom(await readFile(path, "utf8")))
|
|
70
|
+
} catch {
|
|
71
|
+
return undefined
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function zdrHeaders(state: ZdrState): Record<string, string> | undefined {
|
|
76
|
+
return state.enabled ? { "x-cmd-zdr": "1" } : undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function describeZdr(state: ZdrState): string {
|
|
80
|
+
if (state.source === "env") return `on (${state.envVar ?? "environment"})`
|
|
81
|
+
if (state.source === "settings") return "on (settings.json commandcode.enableZDR)"
|
|
82
|
+
return "off"
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A symlinked settings.json (e.g. a managed file) is updated through its target
|
|
87
|
+
* so the link survives; a dangling link is refused rather than replaced.
|
|
88
|
+
*/
|
|
89
|
+
async function resolveSettingsTarget(path: string): Promise<string> {
|
|
90
|
+
try {
|
|
91
|
+
return await realpath(path)
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
|
|
94
|
+
throw new Error("Could not read settings.json in the agent directory; check file permissions")
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const entry = await lstat(path).catch(() => undefined)
|
|
98
|
+
if (entry?.isSymbolicLink()) {
|
|
99
|
+
throw new Error("settings.json is a symlink to a missing file; refusing to replace the link")
|
|
100
|
+
}
|
|
101
|
+
return path
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Persist the opt-in into the agent settings file, preserving every other key.
|
|
106
|
+
*
|
|
107
|
+
* Returns the written settings object so the caller resolves the effective
|
|
108
|
+
* state without waiting for the host to reload the file. The host re-reads the
|
|
109
|
+
* file and merges only the fields it modified on each of its own saves, so this
|
|
110
|
+
* key survives later host writes; writes from separate processes are not
|
|
111
|
+
* coordinated. A malformed file is never overwritten, and an unreadable file is
|
|
112
|
+
* reported instead of replaced.
|
|
113
|
+
*/
|
|
114
|
+
export async function saveZdrSetting(settingsPath: string, enabled: boolean): Promise<unknown> {
|
|
115
|
+
const path = await resolveSettingsTarget(settingsPath)
|
|
116
|
+
let raw: string | undefined
|
|
117
|
+
try {
|
|
118
|
+
raw = await readFile(path, "utf8")
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
|
|
121
|
+
throw new Error("Could not read settings.json in the agent directory; check file permissions")
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let settings: Record<string, unknown> = {}
|
|
126
|
+
const text = raw === undefined ? undefined : stripBom(raw)
|
|
127
|
+
if (text !== undefined && text.trim() !== "") {
|
|
128
|
+
let parsed: unknown
|
|
129
|
+
try {
|
|
130
|
+
parsed = JSON.parse(text)
|
|
131
|
+
} catch {
|
|
132
|
+
throw new Error(
|
|
133
|
+
"Invalid settings.json in the agent directory; refusing to overwrite it. Fix the JSON or set commandcode.enableZDR by hand.",
|
|
134
|
+
)
|
|
135
|
+
}
|
|
136
|
+
if (!isRecord(parsed)) {
|
|
137
|
+
throw new Error("settings.json must contain a JSON object; refusing to overwrite it")
|
|
138
|
+
}
|
|
139
|
+
settings = { ...parsed }
|
|
140
|
+
}
|
|
141
|
+
const section = settings[ZDR_SETTINGS_SECTION]
|
|
142
|
+
settings[ZDR_SETTINGS_SECTION] = {
|
|
143
|
+
...(isRecord(section) ? section : {}),
|
|
144
|
+
[ZDR_SETTING_KEY]: enabled,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const temporary = `${path}.${randomUUID()}.tmp`
|
|
148
|
+
try {
|
|
149
|
+
await mkdir(dirname(path), { recursive: true })
|
|
150
|
+
await writeFile(temporary, `${JSON.stringify(settings, null, 2)}\n`, {
|
|
151
|
+
encoding: "utf8",
|
|
152
|
+
mode: 0o600,
|
|
153
|
+
flag: "wx",
|
|
154
|
+
})
|
|
155
|
+
await rename(temporary, path)
|
|
156
|
+
} catch {
|
|
157
|
+
throw new Error("Could not save settings.json in the agent directory; check file permissions")
|
|
158
|
+
} finally {
|
|
159
|
+
// Cleanup must not replace the sanitized error with an OS message containing local paths.
|
|
160
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
161
|
+
}
|
|
162
|
+
return settings
|
|
163
|
+
}
|
|
@@ -142,7 +142,7 @@ if (!answer.ok) return { skipped: answer.errorCode === "budget" }; // never thr
|
|
|
142
142
|
|
|
143
143
|
Your extension owns its own user consent and budget; `/typesafe enable` applies only to this package's tool. Check `authState()` rather than your own consent flag before you report that judgments are on.
|
|
144
144
|
|
|
145
|
-
Judgments can also go through OpenRouter: `createTypeSafe({ backend: "openrouter" })` sends them to `openrouter.ai` with the key from `OPENROUTER_API_KEY`. Command Code serves the same protocol: `createTypeSafe({ backend: "commandcode" })` sends them to `api.commandcode.ai` with the key from `COMMANDCODE_API_KEY` and the model `typesafe/jev`. So does Liquid AI: `createTypeSafe({ backend: "liquid" })` sends them to `api.liquid.ai` with the key from `LIQUID_API_KEY` and the model `d1:free`, which is free; pass `model: "d1"` for the paid model, priced at $0.040 per million input tokens. Liquid counts the state once per question, where TypeSafe counts it once per request, so a request with N questions costs about N times the state on Liquid. Speed, measured on 2026-10-03 with one request at a time: `d1:free` took a median of about 14 seconds and sometimes failed with HTTP 504 after about 46 seconds, while `d1` took about 0.5 seconds. With `d1:free`, raise `timeoutMs` above its 15-second default, or pass `model: "d1"`. SubQ too: `createTypeSafe({ backend: "subq" })` sends them to `api.subq.ai` with the key from `SUBQ_API_KEY` and the model `subq-snap-preview`, priced at $0.05 per million input tokens. SubQ takes at most 16 questions in one request, a Choice of at least 2 options, and a Score of at most 10 levels: `evaluate` refuses a larger request before it sends it, `evaluateAll` splits to 16, and `client.limits` tells you the limit without a request. Nace.AI serves Drex the same way: `createTypeSafe({ backend: "nace" })` sends judgments to `console.nace.ai` with the key from `NACE_API_KEY` and the model `drex-v2.0`, priced at $0.060 per million input tokens; `drex-v1.5` is $0.050, and `drex-max` and `drex-max-v1.1` are $0.030. Nace accepted every request shape the schema allows, so it declares no narrower limits. Drex holds a request for up to 55 seconds upstream, so raise `timeoutMs` above its 15-second default for a heavy request. Or pass a `BackendEndpoint` object as `backend` to name any host that serves the protocol: it brings its own key variable, never reads `TYPESAFE_API_KEY`, and `backendHost()` reports its destination host for your consent text. Each backend's key can also be stored with `/typesafe login <backend>`: it prompts once, proves the key with the backend's model list where that list checks the key and otherwise with one judge request, and saves it under that backend's name, so a key stored for one backend is never sent to another. A backend's own environment variable still wins over its stored key. Pass the same `backend` to `authState`, `keySituation`, and `ensureApiKey`, or the status you report describes the TypeSafe key while the requests use another one. The `/typesafe` commands and the `typesafe_evaluate` tool follow `PI_TYPESAFE_BACKEND` (`typesafe` by default) and name that backend's host, key variable, and model in their consent and status text — so the extension sends judgments where it says it sends them. A name the registry does not know is a `configuration` error at session start, not a silent fallback. `PI_TYPESAFE_MODEL` overrides the backend's default model, written as that backend's own id is written (`jev-1.14`; it is mapped to the backend's id form, so OpenRouter sends `typesafe/jev-1.14`). `/typesafe login [backend]` and `/typesafe logout [backend]` act on the backend they name, or on the session's own backend when they name none, and on a backend whose environment variable is set they say that the variable wins. Every export — the client, `ask`, batching, the usage ledger, auth state, the `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` readers, and the `pi-typesafe/calibrate` and `pi-typesafe/ui` entry points — is in [docs/api.md](docs/api.md).
|
|
145
|
+
Judgments can also go through OpenRouter: `createTypeSafe({ backend: "openrouter" })` sends them to `openrouter.ai` with the key from `OPENROUTER_API_KEY`. Command Code serves the same protocol: `createTypeSafe({ backend: "commandcode" })` sends them to `api.commandcode.ai` with the key from `COMMANDCODE_API_KEY` and the model `typesafe/jev`. So does Liquid AI: `createTypeSafe({ backend: "liquid" })` sends them to `api.liquid.ai` with the key from `LIQUID_API_KEY` and the model `d1:free`, which is free; pass `model: "d1"` for the paid model, priced at $0.040 per million input tokens. Liquid counts the state once per question, where TypeSafe counts it once per request, so a request with N questions costs about N times the state on Liquid. Speed, measured on 2026-10-03 with one request at a time: `d1:free` took a median of about 14 seconds and sometimes failed with HTTP 504 after about 46 seconds, while `d1` took about 0.5 seconds. With `d1:free`, raise `timeoutMs` above its 15-second default, or pass `model: "d1"`. SubQ too: `createTypeSafe({ backend: "subq" })` sends them to `api.subq.ai` with the key from `SUBQ_API_KEY` and the model `subq-snap-preview`, priced at $0.05 per million input tokens. SubQ takes at most 16 questions in one request, a Choice of at least 2 options, and a Score of at most 10 levels: `evaluate` refuses a larger request before it sends it, `evaluateAll` splits to 16, and `client.limits` tells you the limit without a request. Nace.AI serves Drex the same way: `createTypeSafe({ backend: "nace" })` sends judgments to `console.nace.ai` with the key from `NACE_API_KEY` and the model `drex-v2.0`, priced at $0.060 per million input tokens; `drex-v1.5` is $0.050, and `drex-max` and `drex-max-v1.1` are $0.030. Nace accepted every request shape the schema allows, so it declares no narrower limits. Drex holds a request for up to 55 seconds upstream, so raise `timeoutMs` above its 15-second default for a heavy request. Or pass a `BackendEndpoint` object as `backend` to name any host that serves the protocol: it brings its own key variable, never reads `TYPESAFE_API_KEY`, and `backendHost()` reports its destination host for your consent text. Each backend's key can also be stored with `/typesafe login <backend>`: it prompts once, proves the key with the backend's model list where that list checks the key and otherwise with one isolated judge request (without writing `usage.json`, hitting daily caps, or overwriting `auth-state.json` on a rejected candidate key), and saves it under that backend's name, so a key stored for one backend is never sent to another. A backend's own environment variable still wins over its stored key. Pass the same `backend` to `authState`, `keySituation`, and `ensureApiKey`, or the status you report describes the TypeSafe key while the requests use another one. The `/typesafe` commands and the `typesafe_evaluate` tool follow `PI_TYPESAFE_BACKEND` (`typesafe` by default) and name that backend's host, key variable, and model in their consent and status text — so the extension sends judgments where it says it sends them. A name the registry does not know is a `configuration` error at session start, not a silent fallback: `/typesafe login`, `logout`, `setup`, `enable`, `test`, and `playground` all decline until `PI_TYPESAFE_BACKEND` is fixed or unset. `PI_TYPESAFE_MODEL` overrides the backend's default model, written as that backend's own id is written (`jev-1.14`; it is mapped to the backend's id form, so OpenRouter sends `typesafe/jev-1.14`). `/typesafe login [backend]` and `/typesafe logout [backend]` act on the backend they name, or on the session's own backend when they name none, and on a backend whose environment variable is set they say that the variable wins. Every export — the client, `ask`, batching, the usage ledger, auth state, the `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` readers, and the `pi-typesafe/calibrate` and `pi-typesafe/ui` entry points — is in [docs/api.md](docs/api.md).
|
|
146
146
|
|
|
147
147
|
## Development
|
|
148
148
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TypeSafeIntegrationError } from "./errors.js";
|
|
1
|
+
import { TypeSafeIntegrationError, attachErrorDisposition } from "./errors.js";
|
|
2
2
|
/** Default per-ask deadline; matches the client's own request timeout. */
|
|
3
3
|
export const DEFAULT_ASK_TIMEOUT_MS = 15_000;
|
|
4
4
|
const FALLBACK_MESSAGE = "TypeSafe request failed.";
|
|
@@ -22,8 +22,11 @@ export async function ask(judge, request, options = {}) {
|
|
|
22
22
|
return { ok: true, answers: result.answers, model: result.model, usage: result.usage, elapsedMs: result.elapsedMs };
|
|
23
23
|
}
|
|
24
24
|
catch (error) {
|
|
25
|
-
if (error instanceof TypeSafeIntegrationError)
|
|
26
|
-
|
|
25
|
+
if (error instanceof TypeSafeIntegrationError) {
|
|
26
|
+
const failed = { ok: false, error: error.message, errorCode: error.code };
|
|
27
|
+
attachErrorDisposition(failed, error.disposition);
|
|
28
|
+
return failed;
|
|
29
|
+
}
|
|
27
30
|
return { ok: false, error: FALLBACK_MESSAGE };
|
|
28
31
|
}
|
|
29
32
|
finally {
|
|
@@ -20,6 +20,28 @@ export interface AuthFailure {
|
|
|
20
20
|
readonly message: string;
|
|
21
21
|
readonly at: string;
|
|
22
22
|
}
|
|
23
|
+
/** Explicit auth breaker state for one backend. */
|
|
24
|
+
export type AuthStatus = "missing" | "unusable" | "rejected" | "rejection_expired" | "unverified" | "verified";
|
|
25
|
+
/** Persisted per-backend auth record written through `transitionAuthRecord`. */
|
|
26
|
+
export interface AuthRecord {
|
|
27
|
+
readonly verifiedAt?: string;
|
|
28
|
+
readonly lastFailure?: AuthFailure;
|
|
29
|
+
}
|
|
30
|
+
export type AuthEvent = {
|
|
31
|
+
readonly type: "verified";
|
|
32
|
+
readonly at: string;
|
|
33
|
+
} | {
|
|
34
|
+
readonly type: "failed";
|
|
35
|
+
readonly failure: AuthFailure;
|
|
36
|
+
} | {
|
|
37
|
+
readonly type: "cleared";
|
|
38
|
+
};
|
|
39
|
+
export interface AuthWriteOptions {
|
|
40
|
+
readonly backend?: BackendSpec;
|
|
41
|
+
readonly path?: string;
|
|
42
|
+
}
|
|
43
|
+
/** Single-writer pure transition reducer for one backend's persisted auth record. */
|
|
44
|
+
export declare function transitionAuthRecord(record: AuthRecord, event: AuthEvent): AuthRecord;
|
|
23
45
|
/**
|
|
24
46
|
* The whole answer to "is Jev actually available right now": which key is in effect, whether it has been accepted, and
|
|
25
47
|
* the last failure that degraded it. Consumers must consult this instead of treating their own consent flag as proof
|
|
@@ -28,6 +50,8 @@ export interface AuthFailure {
|
|
|
28
50
|
export interface AuthState {
|
|
29
51
|
/** The judgment backend this state describes; each backend has its own key. Holds the value the caller passed. */
|
|
30
52
|
readonly backend: BackendSpec;
|
|
53
|
+
/** Explicit auth breaker state derived from key presence, persisted record, and the rejection window. */
|
|
54
|
+
readonly status: AuthStatus;
|
|
31
55
|
/** Same kinds as KeySituation: where the key in effect comes from. */
|
|
32
56
|
readonly kind: "environment" | "stored" | "missing" | "unusable";
|
|
33
57
|
readonly source?: KeySource;
|
|
@@ -39,8 +63,8 @@ export interface AuthState {
|
|
|
39
63
|
readonly keyName: string;
|
|
40
64
|
/**
|
|
41
65
|
* True when the key in effect was accepted by the backend (a login proves the backend it was asked for; a successful
|
|
42
|
-
* request proves any key). A 401 rejection younger than `AUTH_REJECTION_TTL_MS` clears it; a 403 never does.
|
|
43
|
-
*
|
|
66
|
+
* request proves any key). A 401 rejection younger than `AUTH_REJECTION_TTL_MS` clears it; a 403 never does. Each
|
|
67
|
+
* backend keeps its own record in `auth-state.json`.
|
|
44
68
|
*/
|
|
45
69
|
readonly verified: boolean;
|
|
46
70
|
readonly verifiedAt?: string;
|
|
@@ -64,11 +88,11 @@ export declare function authState(options?: {
|
|
|
64
88
|
backend?: BackendSpec;
|
|
65
89
|
}): AuthState;
|
|
66
90
|
/** Record that the key was accepted: login verification, or any successful request. Clears the last failure. */
|
|
67
|
-
export declare function recordAuthVerified(at?: Date): void;
|
|
68
|
-
/** Record the failure that degraded
|
|
69
|
-
export declare function recordAuthFailure(error: TypeSafeIntegrationError, at?: Date): void;
|
|
70
|
-
/** Forget verification and degradation:
|
|
71
|
-
export declare function clearAuthState(): void;
|
|
91
|
+
export declare function recordAuthVerified(at?: Date, options?: AuthWriteOptions): void;
|
|
92
|
+
/** Record the failure that degraded a backend. The verification timestamp is kept so a recovered key stays known. */
|
|
93
|
+
export declare function recordAuthFailure(error: TypeSafeIntegrationError, at?: Date, options?: AuthWriteOptions): void;
|
|
94
|
+
/** Forget verification and degradation: removes the whole file with no backend, or clears only that backend's entry. */
|
|
95
|
+
export declare function clearAuthState(options?: BackendSpec | AuthWriteOptions): void;
|
|
72
96
|
export interface AuthReport {
|
|
73
97
|
/**
|
|
74
98
|
* `error` when judgments will fail or the key was rejected, `warning` when the key is unverified or its rejection has
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { DEFAULT_BACKEND,
|
|
4
|
-
import { credentialsPath, keySituation, keySourceLabel, piTypesafeDir } from "./credentials.js";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { DEFAULT_BACKEND, resolveBackend } from "./backends.js";
|
|
4
|
+
import { credentialId, credentialsPath, keySituation, keySourceLabel, piTypesafeDir } from "./credentials.js";
|
|
5
5
|
import { TypeSafeIntegrationError } from "./errors.js";
|
|
6
6
|
const AUTH_VERSION = 1;
|
|
7
7
|
const CODES = new Set([
|
|
8
8
|
"configuration", "validation", "budget", "aborted", "timeout", "http", "connection", "response",
|
|
9
9
|
]);
|
|
10
|
+
function assertNever(value) {
|
|
11
|
+
throw new Error(`Unexpected auth state: ${String(value)}`);
|
|
12
|
+
}
|
|
10
13
|
/**
|
|
11
14
|
* How long a stored 401 vetoes the key. The next request proves the key again once the window passes, so one refusal
|
|
12
15
|
* cannot disable judgments for good. Fifteen minutes is a policy choice, not a measured provider constant.
|
|
@@ -20,47 +23,101 @@ export const AUTH_REJECTION_TTL_MS = 15 * 60 * 1000;
|
|
|
20
23
|
export function isKeyRejection(status) {
|
|
21
24
|
return status === 401;
|
|
22
25
|
}
|
|
26
|
+
/** Single-writer pure transition reducer for one backend's persisted auth record. */
|
|
27
|
+
export function transitionAuthRecord(record, event) {
|
|
28
|
+
switch (event.type) {
|
|
29
|
+
case "verified":
|
|
30
|
+
return { verifiedAt: event.at };
|
|
31
|
+
case "failed":
|
|
32
|
+
return {
|
|
33
|
+
...(record.verifiedAt === undefined ? {} : { verifiedAt: record.verifiedAt }),
|
|
34
|
+
lastFailure: event.failure,
|
|
35
|
+
};
|
|
36
|
+
case "cleared":
|
|
37
|
+
return {};
|
|
38
|
+
default:
|
|
39
|
+
return assertNever(event);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
23
42
|
/** `fresh` still vetoes the key, `expired` is only a record of what was refused when: no schema change, no manual reset. */
|
|
24
|
-
function rejectionOf(failure) {
|
|
43
|
+
function rejectionOf(failure, nowMs) {
|
|
25
44
|
if (failure === undefined || failure.code !== "http" || !isKeyRejection(failure.status))
|
|
26
45
|
return "none";
|
|
27
46
|
const at = Date.parse(failure.at);
|
|
28
47
|
// A timestamp this code cannot read cannot prove the rejection is current, so it counts as spent.
|
|
29
48
|
if (!Number.isFinite(at))
|
|
30
49
|
return "expired";
|
|
31
|
-
return
|
|
50
|
+
return nowMs - at < AUTH_REJECTION_TTL_MS ? "fresh" : "expired";
|
|
51
|
+
}
|
|
52
|
+
function evaluateAuth(situation, record, nowMs) {
|
|
53
|
+
const rejection = rejectionOf(record.lastFailure, nowMs);
|
|
54
|
+
const status = situation.kind === "missing" ? "missing"
|
|
55
|
+
: situation.kind === "unusable" ? "unusable"
|
|
56
|
+
: rejection === "fresh" ? "rejected"
|
|
57
|
+
: rejection === "expired" ? "rejection_expired"
|
|
58
|
+
: record.verifiedAt === undefined ? "unverified"
|
|
59
|
+
: "verified";
|
|
60
|
+
const usable = status !== "missing" && status !== "unusable" && status !== "rejected";
|
|
61
|
+
// Keeps `verified` aligned with `verifiedAt` whenever no fresh 401 stands against it (including expired 401s).
|
|
62
|
+
const verified = record.verifiedAt !== undefined && rejection !== "fresh";
|
|
63
|
+
return { status, usable, verified };
|
|
32
64
|
}
|
|
33
65
|
/** The auth-state file: one small, owner-only record that outlives the process that wrote it. */
|
|
34
66
|
export function authStatePath() {
|
|
35
67
|
return join(piTypesafeDir(), "auth-state.json");
|
|
36
68
|
}
|
|
37
|
-
function
|
|
69
|
+
function parseRecord(raw) {
|
|
70
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
71
|
+
return {};
|
|
72
|
+
const obj = raw;
|
|
73
|
+
const verifiedAt = typeof obj.verifiedAt === "string" && obj.verifiedAt.length <= 40 ? obj.verifiedAt : undefined;
|
|
74
|
+
const failure = obj.lastFailure && typeof obj.lastFailure === "object" && !Array.isArray(obj.lastFailure)
|
|
75
|
+
? obj.lastFailure
|
|
76
|
+
: undefined;
|
|
77
|
+
const code = typeof failure?.code === "string" && CODES.has(failure.code) ? failure.code : undefined;
|
|
78
|
+
const message = typeof failure?.message === "string" ? failure.message.slice(0, 300) : undefined;
|
|
79
|
+
const at = typeof failure?.at === "string" && failure.at.length <= 40 ? failure.at : undefined;
|
|
80
|
+
const status = typeof failure?.status === "number" && Number.isSafeInteger(failure.status) ? failure.status : undefined;
|
|
81
|
+
const lastFailure = code && message && at
|
|
82
|
+
? { code, message, at, ...(status === undefined ? {} : { status }) }
|
|
83
|
+
: undefined;
|
|
84
|
+
return { ...(verifiedAt === undefined ? {} : { verifiedAt }), ...(lastFailure === undefined ? {} : { lastFailure }) };
|
|
85
|
+
}
|
|
86
|
+
function isNonEmptyRecord(record) {
|
|
87
|
+
return record.verifiedAt !== undefined || record.lastFailure !== undefined;
|
|
88
|
+
}
|
|
89
|
+
function readStateMap(path) {
|
|
90
|
+
const map = Object.create(null);
|
|
38
91
|
try {
|
|
39
92
|
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
40
|
-
if (!parsed || typeof parsed !== "object")
|
|
41
|
-
return
|
|
93
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
94
|
+
return map;
|
|
42
95
|
const raw = parsed;
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
96
|
+
if (raw.backends && typeof raw.backends === "object" && !Array.isArray(raw.backends)) {
|
|
97
|
+
for (const [id, entry] of Object.entries(raw.backends)) {
|
|
98
|
+
const record = parseRecord(entry);
|
|
99
|
+
if (isNonEmptyRecord(record))
|
|
100
|
+
map[id] = record;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// Pre-per-backend files hold top-level verifiedAt/lastFailure; heal them into DEFAULT_BACKEND on read.
|
|
104
|
+
if (!(DEFAULT_BACKEND in map)) {
|
|
105
|
+
const legacy = parseRecord(raw);
|
|
106
|
+
if (isNonEmptyRecord(legacy))
|
|
107
|
+
map[DEFAULT_BACKEND] = legacy;
|
|
108
|
+
}
|
|
109
|
+
return map;
|
|
53
110
|
}
|
|
54
111
|
catch {
|
|
55
|
-
return
|
|
112
|
+
return map;
|
|
56
113
|
}
|
|
57
114
|
}
|
|
58
115
|
/** Owner-only, atomic, and best-effort: an unwritable auth record never changes how a request behaves. */
|
|
59
|
-
function
|
|
116
|
+
function writeStateMap(path, backends) {
|
|
60
117
|
const temporary = `${path}.${process.pid}.tmp`;
|
|
61
118
|
try {
|
|
62
|
-
mkdirSync(
|
|
63
|
-
writeFileSync(temporary, `${JSON.stringify({ version: AUTH_VERSION, ...
|
|
119
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
120
|
+
writeFileSync(temporary, `${JSON.stringify({ version: AUTH_VERSION, backends: { ...backends } }, null, 2)}\n`, { mode: 0o600, flag: "w" });
|
|
64
121
|
chmodSync(temporary, 0o600);
|
|
65
122
|
renameSync(temporary, path);
|
|
66
123
|
}
|
|
@@ -71,6 +128,9 @@ function writeState(path, state) {
|
|
|
71
128
|
catch { /* best-effort cleanup only */ }
|
|
72
129
|
}
|
|
73
130
|
}
|
|
131
|
+
function isBackendEndpoint(value) {
|
|
132
|
+
return "host" in value || "label" in value || "keyEnv" in value;
|
|
133
|
+
}
|
|
74
134
|
/**
|
|
75
135
|
* What the key situation, the last outcome, and the clock add up to for a valid backend; it never throws for one. An
|
|
76
136
|
* invalid backend throws the same `configuration` error as resolveBackend(), so validate a user-supplied endpoint
|
|
@@ -80,44 +140,87 @@ export function authState(options = {}) {
|
|
|
80
140
|
const path = options.path ?? authStatePath();
|
|
81
141
|
const backend = options.backend ?? DEFAULT_BACKEND;
|
|
82
142
|
const situation = keySituation(backend);
|
|
83
|
-
const stored =
|
|
143
|
+
const stored = readStateMap(path)[credentialId(backend)] ?? {};
|
|
84
144
|
const source = situation.kind === "environment" ? "environment" : situation.kind === "stored" ? "stored" : undefined;
|
|
85
|
-
const
|
|
86
|
-
const usable = source !== undefined && !rejected;
|
|
145
|
+
const { status, usable, verified } = evaluateAuth(situation, stored, Date.now());
|
|
87
146
|
return {
|
|
88
147
|
backend,
|
|
148
|
+
status,
|
|
89
149
|
kind: situation.kind,
|
|
90
150
|
...(source === undefined ? {} : { source }),
|
|
91
151
|
path: situation.kind === "unusable" ? situation.path : credentialsPath(),
|
|
92
152
|
...(situation.kind === "unusable" ? { reason: situation.reason } : {}),
|
|
93
153
|
keyName: keySourceLabel(situation),
|
|
94
|
-
verified
|
|
154
|
+
verified,
|
|
95
155
|
...(stored.verifiedAt === undefined ? {} : { verifiedAt: stored.verifiedAt }),
|
|
96
156
|
...(stored.lastFailure === undefined ? {} : { lastFailure: stored.lastFailure }),
|
|
97
157
|
usable,
|
|
98
158
|
};
|
|
99
159
|
}
|
|
100
160
|
/** Record that the key was accepted: login verification, or any successful request. Clears the last failure. */
|
|
101
|
-
export function recordAuthVerified(at = new Date()) {
|
|
102
|
-
|
|
161
|
+
export function recordAuthVerified(at = new Date(), options = {}) {
|
|
162
|
+
const path = options.path ?? authStatePath();
|
|
163
|
+
const id = credentialId(options.backend);
|
|
164
|
+
const map = readStateMap(path);
|
|
165
|
+
map[id] = transitionAuthRecord(map[id] ?? {}, { type: "verified", at: at.toISOString() });
|
|
166
|
+
writeStateMap(path, map);
|
|
103
167
|
}
|
|
104
|
-
/** Record the failure that degraded
|
|
105
|
-
export function recordAuthFailure(error, at = new Date()) {
|
|
106
|
-
const
|
|
168
|
+
/** Record the failure that degraded a backend. The verification timestamp is kept so a recovered key stays known. */
|
|
169
|
+
export function recordAuthFailure(error, at = new Date(), options = {}) {
|
|
170
|
+
const path = options.path ?? authStatePath();
|
|
171
|
+
const id = credentialId(options.backend);
|
|
172
|
+
const map = readStateMap(path);
|
|
107
173
|
const failure = {
|
|
108
174
|
code: error.code,
|
|
109
175
|
message: error.message,
|
|
110
176
|
at: at.toISOString(),
|
|
111
177
|
...(error.status === undefined ? {} : { status: error.status }),
|
|
112
178
|
};
|
|
113
|
-
|
|
179
|
+
map[id] = transitionAuthRecord(map[id] ?? {}, { type: "failed", failure });
|
|
180
|
+
writeStateMap(path, map);
|
|
114
181
|
}
|
|
115
|
-
/** Forget verification and degradation:
|
|
116
|
-
export function clearAuthState() {
|
|
117
|
-
|
|
118
|
-
|
|
182
|
+
/** Forget verification and degradation: removes the whole file with no backend, or clears only that backend's entry. */
|
|
183
|
+
export function clearAuthState(options) {
|
|
184
|
+
let backend;
|
|
185
|
+
let path = authStatePath();
|
|
186
|
+
if (typeof options === "string") {
|
|
187
|
+
backend = options;
|
|
188
|
+
}
|
|
189
|
+
else if (options !== undefined) {
|
|
190
|
+
if (isBackendEndpoint(options)) {
|
|
191
|
+
backend = options;
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
backend = options.backend;
|
|
195
|
+
if (options.path !== undefined)
|
|
196
|
+
path = options.path;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (backend === undefined) {
|
|
200
|
+
try {
|
|
201
|
+
rmSync(path, { force: true });
|
|
202
|
+
}
|
|
203
|
+
catch { /* nothing to clear */ }
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const id = credentialId(backend);
|
|
207
|
+
const map = readStateMap(path);
|
|
208
|
+
if (!(id in map))
|
|
209
|
+
return;
|
|
210
|
+
const next = transitionAuthRecord(map[id] ?? {}, { type: "cleared" });
|
|
211
|
+
if (!isNonEmptyRecord(next))
|
|
212
|
+
delete map[id];
|
|
213
|
+
else
|
|
214
|
+
map[id] = next;
|
|
215
|
+
if (Object.keys(map).length === 0) {
|
|
216
|
+
try {
|
|
217
|
+
rmSync(path, { force: true });
|
|
218
|
+
}
|
|
219
|
+
catch { /* nothing to clear */ }
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
writeStateMap(path, map);
|
|
119
223
|
}
|
|
120
|
-
catch { /* nothing to clear */ }
|
|
121
224
|
}
|
|
122
225
|
/**
|
|
123
226
|
* One line plus a level, so a status command, a headless log, or a consumer's own status line can call out a degraded
|
|
@@ -127,23 +230,24 @@ export function describeAuth(state = authState()) {
|
|
|
127
230
|
const config = resolveBackend(state.backend);
|
|
128
231
|
const label = `${config.label} key`;
|
|
129
232
|
const since = state.lastFailure ? ` Last failure: ${state.lastFailure.message}${state.lastFailure.at ? ` (${state.lastFailure.at})` : ""}` : "";
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
233
|
+
switch (state.status) {
|
|
234
|
+
case "missing": {
|
|
235
|
+
const how = `a key is configured (/typesafe login${config.name && config.name !== DEFAULT_BACKEND ? ` ${config.name}` : ""} or ${config.keyEnv})`;
|
|
236
|
+
return { level: "error", text: `${label}: missing — every Jev judgment will fail until ${how}.${since}` };
|
|
237
|
+
}
|
|
238
|
+
case "unusable":
|
|
239
|
+
return { level: "error", text: `${label}: unusable (${state.reason ?? "unknown reason"}) — judgments will fail until the key is fixed.${since}` };
|
|
240
|
+
case "rejected":
|
|
241
|
+
return { level: "error", text: `${label}: ${state.keyName} was rejected.${since}` };
|
|
242
|
+
case "rejection_expired": {
|
|
243
|
+
const at = state.lastFailure?.at;
|
|
244
|
+
return { level: "warning", text: `${label}: ${state.keyName} was rejected${at === undefined ? "" : ` at ${at}`}; that rejection expired, so the next request proves the key.` };
|
|
245
|
+
}
|
|
246
|
+
case "unverified":
|
|
247
|
+
return { level: "warning", text: `${label}: ${state.keyName} (not verified yet — the first request proves it).${since}` };
|
|
248
|
+
case "verified":
|
|
249
|
+
return { level: "ok", text: `${label}: ${state.keyName} (verified${state.verifiedAt ? ` ${state.verifiedAt}` : ""}).${since}` };
|
|
250
|
+
default:
|
|
251
|
+
return assertNever(state.status);
|
|
147
252
|
}
|
|
148
|
-
return { level: "ok", text: `${label}: ${state.keyName} (verified${state.verifiedAt ? ` ${state.verifiedAt}` : ""}).${since}` };
|
|
149
253
|
}
|