leakshield 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +2 -0
  3. package/README.md +39 -9
  4. package/README.zh-TW.md +38 -9
  5. package/dist/adapters/claude-code/capabilities.d.ts +14 -0
  6. package/dist/adapters/claude-code/capabilities.js +47 -0
  7. package/dist/adapters/claude-code/cli.d.ts +10 -0
  8. package/dist/adapters/claude-code/cli.js +51 -0
  9. package/dist/adapters/claude-code/doctor.d.ts +19 -0
  10. package/dist/adapters/claude-code/doctor.js +177 -0
  11. package/dist/adapters/claude-code/proxy.d.ts +47 -0
  12. package/dist/adapters/claude-code/proxy.js +348 -0
  13. package/dist/adapters/opencode/capabilities.d.ts +10 -0
  14. package/dist/adapters/opencode/capabilities.js +48 -0
  15. package/dist/adapters/opencode/doctor.d.ts +67 -0
  16. package/dist/{doctor.js → adapters/opencode/doctor.js} +16 -42
  17. package/dist/adapters/opencode/env-queries.d.ts +133 -0
  18. package/dist/adapters/opencode/env-tools.d.ts +20 -0
  19. package/dist/adapters/opencode/hooks.d.ts +4 -0
  20. package/dist/adapters/opencode/plugin.d.ts +12 -0
  21. package/dist/{opencode.js → adapters/opencode/plugin.js} +7 -7
  22. package/dist/adapters/opencode/tool-policy.d.ts +2 -0
  23. package/dist/adapters/opencode/tool-policy.js +23 -0
  24. package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
  25. package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
  26. package/dist/adapters/opencode/transparent.d.ts +66 -0
  27. package/dist/adapters/opencode/transparent.js +237 -0
  28. package/dist/adapters/opencode/v2.d.ts +20 -0
  29. package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
  30. package/dist/adapters/pi/capabilities.d.ts +10 -0
  31. package/dist/adapters/pi/capabilities.js +50 -0
  32. package/dist/adapters/pi/doctor.d.ts +26 -0
  33. package/dist/adapters/pi/doctor.js +276 -0
  34. package/dist/adapters/pi/extension.d.ts +28 -0
  35. package/dist/adapters/pi/extension.js +109 -0
  36. package/dist/adapters/pi/guard.d.ts +33 -0
  37. package/dist/adapters/pi/guard.js +154 -0
  38. package/dist/adapters/pi/persistence.d.ts +9 -0
  39. package/dist/adapters/pi/persistence.js +69 -0
  40. package/dist/adapters/pi/settings.d.ts +51 -0
  41. package/dist/adapters/pi/settings.js +136 -0
  42. package/dist/adapters/pi/tool-policy.d.ts +11 -0
  43. package/dist/adapters/pi/tool-policy.js +114 -0
  44. package/dist/cli.d.ts +18 -0
  45. package/dist/cli.js +17 -6
  46. package/dist/config/loader.d.ts +70 -0
  47. package/dist/config/plain-object.d.ts +2 -0
  48. package/dist/core/index.d.ts +9 -0
  49. package/dist/core/index.js +9 -0
  50. package/dist/core/session-guard.d.ts +61 -0
  51. package/dist/{opencode-transparent.js → core/session-guard.js} +55 -713
  52. package/dist/core/sse-recovery.d.ts +6 -0
  53. package/dist/core/tool-restore-policy.d.ts +153 -0
  54. package/dist/core/tool-restore-policy.js +453 -0
  55. package/dist/core/wire.d.ts +213 -0
  56. package/dist/{opencode-transparent-http.js → core/wire.js} +170 -50
  57. package/dist/core/ws.d.ts +26 -0
  58. package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
  59. package/dist/decision/deidentify.d.ts +63 -0
  60. package/dist/decision/ingress.d.ts +40 -0
  61. package/dist/decision/mapping-key.d.ts +91 -0
  62. package/dist/decision/mapping-store.d.ts +166 -0
  63. package/dist/decision/model.d.ts +41 -0
  64. package/dist/decision/pseudonymization.d.ts +176 -0
  65. package/dist/decision/redaction.d.ts +56 -0
  66. package/dist/decision/schema-strings.d.ts +23 -0
  67. package/dist/decision/schema-strings.js +2 -2
  68. package/dist/decision/value-search.d.ts +39 -0
  69. package/dist/doctor-capabilities.d.ts +21 -0
  70. package/dist/doctor-capabilities.js +58 -0
  71. package/dist/doctor-hosts.d.ts +18 -0
  72. package/dist/doctor-hosts.js +144 -0
  73. package/dist/doctor-report.d.ts +45 -0
  74. package/dist/doctor-report.js +111 -0
  75. package/dist/forget.d.ts +18 -0
  76. package/dist/guard-options.d.ts +45 -0
  77. package/dist/{plugin-options.js → guard-options.js} +4 -1
  78. package/dist/help.d.ts +2 -0
  79. package/dist/help.js +15 -1
  80. package/dist/i18n/en.d.ts +65 -0
  81. package/dist/i18n/index.d.ts +15 -0
  82. package/dist/i18n/zh-TW.d.ts +65 -0
  83. package/dist/index.d.ts +13 -0
  84. package/dist/index.js +1 -1
  85. package/dist/rules/builtin.d.ts +4 -0
  86. package/dist/rules/dynamic.d.ts +33 -0
  87. package/dist/scanner/allowlist.d.ts +22 -0
  88. package/dist/scanner/cidr.d.ts +39 -0
  89. package/dist/scanner/encoding.d.ts +87 -0
  90. package/dist/scanner/engine.d.ts +43 -0
  91. package/dist/scanner/exact-values.d.ts +11 -0
  92. package/dist/scanner/redaction-verifier.d.ts +24 -0
  93. package/dist/scanner/remotes.d.ts +29 -0
  94. package/dist/scanner/unicode.d.ts +57 -0
  95. package/dist/scanner/utils.d.ts +22 -0
  96. package/dist/transports/cli.d.ts +27 -0
  97. package/dist/transports/web-ui.d.ts +1 -0
  98. package/dist/transports/web-ui.js +1 -1
  99. package/dist/transports/web.d.ts +4 -0
  100. package/dist/types/capabilities.d.ts +67 -0
  101. package/dist/types/capabilities.js +133 -0
  102. package/dist/types.d.ts +149 -0
  103. package/dist/utils/files.d.ts +3 -0
  104. package/dist/utils/path-security.d.ts +18 -0
  105. package/dist/utils/win-encoding.d.ts +16 -0
  106. package/package.json +15 -5
  107. /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
  108. /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
  109. /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
  110. /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
@@ -0,0 +1,109 @@
1
+ /**
2
+ * pi extension: the in-process LeakShield boundary.
3
+ *
4
+ * Loaded by pi from an extension path (`-e <path>` or `settings.extensions`),
5
+ * it wraps `globalThis.fetch` before any provider client is built, so every
6
+ * model request on the three supported wire APIs is masked by the shared core
7
+ * and assistant text is restored in the reply. Tool arguments are restored at
8
+ * `tool_call`, and unknown tools are refused instead of receiving placeholders.
9
+ *
10
+ * There is no launcher: pi keeps its own provider configuration and credential.
11
+ * Load order matters, because an extension loaded earlier can hold the raw
12
+ * fetch; the doctor reports when LeakShield is not first.
13
+ */
14
+ import { loadConfig } from "../../config/loader.js";
15
+ import { createPiGuard, PROTECT_FAILED } from "./guard.js";
16
+ import { piPersistenceOptions } from "./persistence.js";
17
+ const GUARD_KEY = Symbol.for("leakshield.pi.guard");
18
+ export const PI_EXTENSION_ID = "leakshield-pi";
19
+ export const UNPROTECTED_NOTICE = "LeakShield blocked this run: provider requests for the selected model cannot be protected in-process.";
20
+ function guardConfig() {
21
+ const config = loadConfig(process.env.LEAKSHIELD_CONFIG, process.cwd());
22
+ return { ...config, settings: { ...config.settings, encoding_detection: true } };
23
+ }
24
+ function notice(ctx, message) {
25
+ if (ctx?.ui)
26
+ ctx.ui.notify(message, "error");
27
+ else
28
+ console.error(`[${PI_EXTENSION_ID}] ${message}`);
29
+ }
30
+ function refusalText(error) {
31
+ if (error instanceof Error && error.message.startsWith("LeakShield "))
32
+ return error.message;
33
+ return PROTECT_FAILED;
34
+ }
35
+ function installGuard() {
36
+ const existing = globalThis[GUARD_KEY];
37
+ if (existing !== undefined)
38
+ return existing;
39
+ const guard = createPiGuard({ config: guardConfig(), persistence: piPersistenceOptions(process.env) });
40
+ guard.install();
41
+ Object.defineProperty(globalThis, GUARD_KEY, { value: guard, configurable: true });
42
+ return guard;
43
+ }
44
+ export default function leakshieldPiExtension(pi) {
45
+ const guard = installGuard();
46
+ let refusal = guard.refusal;
47
+ let announced = null;
48
+ const announce = (ctx, reason) => {
49
+ if (announced === reason)
50
+ return;
51
+ announced = reason;
52
+ notice(ctx, reason);
53
+ };
54
+ const applyModel = (model, ctx) => {
55
+ guard.setModel(model ?? null);
56
+ refusal = guard.refusal;
57
+ if (refusal === null)
58
+ announced = null;
59
+ else
60
+ announce(ctx, refusal);
61
+ };
62
+ pi.on("session_start", (_event, ctx) => {
63
+ guard.setSession(ctx.sessionManager.getSessionId());
64
+ applyModel(ctx.model, ctx);
65
+ });
66
+ pi.on("model_select", (event, ctx) => {
67
+ applyModel(event.model, ctx);
68
+ });
69
+ // The model is re-read at each run so a switch that skipped `model_select`
70
+ // cannot leave the guard bound to a previous provider.
71
+ pi.on("before_agent_start", (_event, ctx) => {
72
+ applyModel(ctx.model, ctx);
73
+ });
74
+ const cancelIfRefused = (ctx) => {
75
+ if (refusal === null)
76
+ return undefined;
77
+ announce(ctx, refusal);
78
+ return { cancel: true };
79
+ };
80
+ pi.on("input", (_event, ctx) => {
81
+ // Re-read the model here too: this is the last hook before a run starts,
82
+ // and `before_agent_start` cannot cancel one. Extension-authored input is
83
+ // refused as well, because it can start a request on an API the guard
84
+ // cannot see.
85
+ applyModel(ctx.model, ctx);
86
+ if (refusal === null)
87
+ return { action: "continue" };
88
+ announce(ctx, refusal);
89
+ return { action: "handled" };
90
+ });
91
+ // Manual compaction and /tree summarization invoke the model without an
92
+ // input or before_agent_start event, so they need their own refusal gate.
93
+ pi.on("session_before_compact", (_event, ctx) => cancelIfRefused(ctx));
94
+ pi.on("session_before_tree", (_event, ctx) => cancelIfRefused(ctx));
95
+ pi.on("tool_call", (event, _ctx) => {
96
+ const toolEvent = event;
97
+ if (refusal !== null)
98
+ return { block: true, reason: refusal, terminate: true };
99
+ try {
100
+ const restored = guard.restoreTool(toolEvent.toolName, toolEvent.input);
101
+ if (restored !== toolEvent.input)
102
+ toolEvent.input = restored;
103
+ }
104
+ catch (error) {
105
+ return { block: true, reason: refusalText(error), terminate: true };
106
+ }
107
+ return undefined;
108
+ });
109
+ }
@@ -0,0 +1,33 @@
1
+ import { createGuardCore, type GuardPersistenceOptions } from "../../core/session-guard.js";
2
+ import type { GuardConfig } from "../../types.js";
3
+ export { SUPPORTED_PI_APIS } from "./settings.js";
4
+ export declare const PROTECT_FAILED = "LeakShield could not protect this provider request. [protect]";
5
+ export declare const UNSUPPORTED_ROUTE = "LeakShield refused a provider request on a route it cannot mask. [route]";
6
+ export declare const UNSUPPORTED_MODEL = "LeakShield cannot protect the selected model: pi's transport for this API does not go through fetch. Use an openai-completions, openai-responses or anthropic-messages model.";
7
+ export declare const MISSING_SESSION = "LeakShield refused a provider request before a session was active. [session]";
8
+ export interface PiGuardModel {
9
+ api: string;
10
+ provider: string;
11
+ id: string;
12
+ baseUrl: string;
13
+ }
14
+ export interface PiGuard {
15
+ /** The reason the current model cannot be protected, or null. */
16
+ readonly refusal: string | null;
17
+ setSession(sessionID: string | null): void;
18
+ setModel(model: PiGuardModel | null): void;
19
+ /** Handles one fetch call: provider traffic is guarded, everything else passes through. */
20
+ handle(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
21
+ /** Restores placeholders in a pi tool call, refusing unknown tools. */
22
+ restoreTool(tool: string, input: unknown): unknown;
23
+ /** Points globalThis.fetch at this guard. */
24
+ install(): void;
25
+ }
26
+ export interface PiGuardOptions {
27
+ config: GuardConfig;
28
+ /** Encrypted mapping store; omitted means process-lifetime mappings. */
29
+ persistence?: GuardPersistenceOptions;
30
+ fetchImpl?: typeof fetch;
31
+ createCore?: typeof createGuardCore;
32
+ }
33
+ export declare function createPiGuard(options: PiGuardOptions): PiGuard;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * In-process provider boundary for pi.
3
+ *
4
+ * pi's provider SDKs resolve `fetch` when they issue a request, so an
5
+ * extension that replaces `globalThis.fetch` sees every model request on the
6
+ * three supported wire APIs. The wrapper sends those requests through the
7
+ * shared guard core, which masks them and restores the assistant text of the
8
+ * reply. Anything that is not provider traffic passes through untouched.
9
+ *
10
+ * The boundary is only as wide as this process: transports that do not use
11
+ * `fetch` (OpenAI Codex over WebSocket, Bedrock, Google service-account auth)
12
+ * are refused by model/API check rather than guarded here.
13
+ */
14
+ import { classifyModelRoute } from "../../core/wire.js";
15
+ import { createGuardCore } from "../../core/session-guard.js";
16
+ import { isSupportedPiApi } from "./settings.js";
17
+ import { assertPiToolBoundary, piToolPolicy } from "./tool-policy.js";
18
+ export { SUPPORTED_PI_APIS } from "./settings.js";
19
+ export const PROTECT_FAILED = "LeakShield could not protect this provider request. [protect]";
20
+ export const UNSUPPORTED_ROUTE = "LeakShield refused a provider request on a route it cannot mask. [route]";
21
+ export const UNSUPPORTED_MODEL = "LeakShield cannot protect the selected model: pi's transport for this API does not go through fetch. Use an openai-completions, openai-responses or anthropic-messages model.";
22
+ export const MISSING_SESSION = "LeakShield refused a provider request before a session was active. [session]";
23
+ function urlOf(input) {
24
+ if (typeof input === "string")
25
+ return input;
26
+ if (input instanceof URL)
27
+ return input.href;
28
+ return input.url;
29
+ }
30
+ function methodOf(input, init) {
31
+ if (typeof init?.method === "string")
32
+ return init.method.toUpperCase();
33
+ if (input instanceof Request)
34
+ return input.method.toUpperCase();
35
+ return "GET";
36
+ }
37
+ function originOf(baseUrl) {
38
+ try {
39
+ const url = new URL(baseUrl);
40
+ if (url.protocol !== "http:" && url.protocol !== "https:")
41
+ return null;
42
+ return url.hostname.length > 0 ? url.origin : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ function refusalText(error) {
49
+ if (error instanceof Error && error.message.startsWith("LeakShield "))
50
+ return error.message;
51
+ return PROTECT_FAILED;
52
+ }
53
+ function refusalResponse(message) {
54
+ return new Response(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message } }), {
55
+ status: 400,
56
+ headers: { "content-type": "application/json" },
57
+ });
58
+ }
59
+ export function createPiGuard(options) {
60
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
61
+ const core = (options.createCore ?? createGuardCore)(options.config, "block", true, options.persistence, { anthropicThinking: "mask" }, piToolPolicy);
62
+ let sessionID = null;
63
+ let model = null;
64
+ let origin = null;
65
+ let invalidBase = false;
66
+ const refusal = () => {
67
+ if (core === null)
68
+ return PROTECT_FAILED;
69
+ if (model === null)
70
+ return UNSUPPORTED_MODEL;
71
+ if (invalidBase || !isSupportedPiApi(model.api))
72
+ return UNSUPPORTED_MODEL;
73
+ return null;
74
+ };
75
+ const guard = {
76
+ get refusal() {
77
+ return refusal();
78
+ },
79
+ setSession(next) {
80
+ sessionID = next !== null && next.length > 0 ? next : null;
81
+ },
82
+ setModel(next) {
83
+ model = next;
84
+ origin = next === null ? null : originOf(next.baseUrl);
85
+ invalidBase = next !== null && origin === null;
86
+ },
87
+ async handle(input, init) {
88
+ const url = urlOf(input);
89
+ const route = classifyModelRoute(url);
90
+ // A model-shaped POST is guarded wherever it goes: a missed or skipped
91
+ // model switch must not fail open just because the origin changed.
92
+ // Other provider-origin routes are classified below (GET passes, an
93
+ // unknown POST is refused).
94
+ let isProvider = route !== null;
95
+ if (!isProvider && origin !== null) {
96
+ try {
97
+ isProvider = new URL(url).origin === origin;
98
+ }
99
+ catch {
100
+ // An unparsable URL cannot be sent by fetch either; let it surface
101
+ // the native error instead of masking it as a guard refusal.
102
+ return fetchImpl(input, init);
103
+ }
104
+ }
105
+ if (!isProvider)
106
+ return fetchImpl(input, init);
107
+ // Model catalogs and response lookups are read-only and carry no
108
+ // conversation. They also keep features like OpenRouter's key catalog.
109
+ const method = methodOf(input, init);
110
+ if (method === "GET" || method === "HEAD")
111
+ return fetchImpl(input, init);
112
+ const reason = refusal() ?? (sessionID === null ? MISSING_SESSION : null);
113
+ if (reason !== null)
114
+ return refusalResponse(reason);
115
+ if (route === null)
116
+ return refusalResponse(UNSUPPORTED_ROUTE);
117
+ let request;
118
+ try {
119
+ request = input instanceof Request && init === undefined ? input : new Request(input, init);
120
+ }
121
+ catch {
122
+ return refusalResponse(PROTECT_FAILED);
123
+ }
124
+ const masked = { sessionID, request };
125
+ try {
126
+ await core.onHttpRequest(masked);
127
+ }
128
+ catch (error) {
129
+ return refusalResponse(refusalText(error));
130
+ }
131
+ const sent = masked.request;
132
+ // Network errors and aborts are not masking failures: propagate them so
133
+ // the SDK keeps its retry/cancel semantics. The request is already masked.
134
+ const response = await fetchImpl(sent);
135
+ const reply = { sessionID, request: sent, response };
136
+ await core.onHttpResponse(reply);
137
+ return reply.response;
138
+ },
139
+ restoreTool(tool, input) {
140
+ if (core === null)
141
+ throw new Error(PROTECT_FAILED);
142
+ if (sessionID === null)
143
+ throw new Error(MISSING_SESSION);
144
+ assertPiToolBoundary(tool, input);
145
+ const event = { sessionID, tool, input };
146
+ core.onToolBefore(event);
147
+ return event.input;
148
+ },
149
+ install() {
150
+ globalThis.fetch = (input, init) => guard.handle(input, init);
151
+ },
152
+ };
153
+ return guard;
154
+ }
@@ -0,0 +1,9 @@
1
+ import type { GuardPersistenceOptions } from "../../core/session-guard.js";
2
+ export declare const PI_PERSIST_ENV = "LEAKSHIELD_PI_PERSIST";
3
+ export declare const PI_PERSIST_TTL_ENV = "LEAKSHIELD_PI_PERSIST_TTL_DAYS";
4
+ export declare const PI_PERSIST_PATH_ENV = "LEAKSHIELD_PI_PERSIST_PATH";
5
+ export declare const PI_PERSIST_KEYFILE_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE";
6
+ export declare const PI_PERSIST_KEYFILE_PATH_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE_PATH";
7
+ export declare const DEFAULT_PERSIST_TTL_DAYS = 7;
8
+ export declare const MAX_PERSIST_TTL_DAYS = 3650;
9
+ export declare function piPersistenceOptions(env: Readonly<Record<string, string | undefined>>): GuardPersistenceOptions | undefined;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Opt-in mapping persistence for the pi extension.
3
+ *
4
+ * pi has no plugin-options channel, so the store is configured with
5
+ * environment variables. The defaults match the OpenCode plugin: off unless
6
+ * enabled, a 7-day session TTL, the default store path, and the same key
7
+ * custody ladder (OS keychain -> explicit keyfile -> memory-only).
8
+ *
9
+ * An invalid value refuses to load the extension instead of silently running
10
+ * without the store the user asked for.
11
+ */
12
+ import { defaultStorePath } from "../../decision/mapping-key.js";
13
+ import { PERSISTENCE_TTL_DEFAULT_DAYS, PERSISTENCE_TTL_MAX_DAYS } from "../../guard-options.js";
14
+ export const PI_PERSIST_ENV = "LEAKSHIELD_PI_PERSIST";
15
+ export const PI_PERSIST_TTL_ENV = "LEAKSHIELD_PI_PERSIST_TTL_DAYS";
16
+ export const PI_PERSIST_PATH_ENV = "LEAKSHIELD_PI_PERSIST_PATH";
17
+ export const PI_PERSIST_KEYFILE_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE";
18
+ export const PI_PERSIST_KEYFILE_PATH_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE_PATH";
19
+ export const DEFAULT_PERSIST_TTL_DAYS = PERSISTENCE_TTL_DEFAULT_DAYS;
20
+ export const MAX_PERSIST_TTL_DAYS = PERSISTENCE_TTL_MAX_DAYS;
21
+ const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
22
+ const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
23
+ function invalid(name, expected) {
24
+ throw new Error(`LeakShield: ${name} ${expected}`);
25
+ }
26
+ function parseFlag(raw, name) {
27
+ if (raw === undefined)
28
+ return undefined;
29
+ const value = raw.trim().toLowerCase();
30
+ if (value.length === 0)
31
+ return undefined;
32
+ if (TRUE_VALUES.has(value))
33
+ return true;
34
+ if (FALSE_VALUES.has(value))
35
+ return false;
36
+ return invalid(name, "must be 1/true/yes or 0/false/no");
37
+ }
38
+ function nonEmpty(raw, name) {
39
+ if (raw === undefined)
40
+ return undefined;
41
+ const value = raw.trim();
42
+ if (value.length === 0)
43
+ return undefined;
44
+ if (value.length > 4096)
45
+ return invalid(name, "is too long");
46
+ return value;
47
+ }
48
+ function parseTtl(raw) {
49
+ const value = nonEmpty(raw, PI_PERSIST_TTL_ENV);
50
+ if (value === undefined)
51
+ return DEFAULT_PERSIST_TTL_DAYS;
52
+ if (!/^\d+$/.test(value))
53
+ return invalid(PI_PERSIST_TTL_ENV, "must be a whole number of days");
54
+ const days = Number(value);
55
+ if (!Number.isSafeInteger(days) || days > MAX_PERSIST_TTL_DAYS) {
56
+ return invalid(PI_PERSIST_TTL_ENV, `must be between 0 and ${MAX_PERSIST_TTL_DAYS}`);
57
+ }
58
+ return days;
59
+ }
60
+ export function piPersistenceOptions(env) {
61
+ if (parseFlag(env[PI_PERSIST_ENV], PI_PERSIST_ENV) !== true)
62
+ return undefined;
63
+ return {
64
+ ttlDays: parseTtl(env[PI_PERSIST_TTL_ENV]),
65
+ path: nonEmpty(env[PI_PERSIST_PATH_ENV], PI_PERSIST_PATH_ENV) ?? defaultStorePath(),
66
+ keyFile: parseFlag(env[PI_PERSIST_KEYFILE_ENV], PI_PERSIST_KEYFILE_ENV) === true,
67
+ keyfilePath: nonEmpty(env[PI_PERSIST_KEYFILE_PATH_ENV], PI_PERSIST_KEYFILE_PATH_ENV),
68
+ };
69
+ }
@@ -0,0 +1,51 @@
1
+ interface PiModelEntry {
2
+ id?: string;
3
+ api?: string;
4
+ baseUrl?: string;
5
+ name?: string;
6
+ [key: string]: unknown;
7
+ }
8
+ interface PiProviderEntry {
9
+ baseUrl?: string;
10
+ api?: string;
11
+ apiKey?: string;
12
+ headers?: Record<string, string>;
13
+ models?: PiModelEntry[];
14
+ [key: string]: unknown;
15
+ }
16
+ interface PiUserSettings {
17
+ defaultModel?: string;
18
+ defaultProvider?: string;
19
+ sessionDir?: string;
20
+ extensions?: unknown[];
21
+ packages?: unknown[];
22
+ [key: string]: unknown;
23
+ }
24
+ export interface PiUserAgent {
25
+ agentDir: string;
26
+ settings: PiUserSettings;
27
+ providers: Record<string, PiProviderEntry>;
28
+ }
29
+ export declare const SUPPORTED_PI_APIS: ReadonlySet<string>;
30
+ export type PiApi = "openai-completions" | "openai-responses" | "anthropic-messages";
31
+ export declare function isSupportedPiApi(value: string): value is PiApi;
32
+ /** pi's default agent directory for a home path. */
33
+ export declare function defaultPiAgentDir(home: string): string;
34
+ /** Reads the user's pi agent configuration. Throws on malformed JSON. */
35
+ export declare function loadPiUserAgent(agentDir: string, readFile: (filePath: string) => string | null): PiUserAgent;
36
+ export interface PiSelectedModel {
37
+ provider: string;
38
+ model?: string;
39
+ api?: string;
40
+ baseUrl?: string;
41
+ }
42
+ /**
43
+ * The provider/model pi would start with. With a configured provider,
44
+ * `defaultModel` is a model id and may itself contain slashes. Without one it
45
+ * may be provider/id; like pi's resolver, the longest declared provider id
46
+ * followed by "/" wins.
47
+ */
48
+ export declare function resolvePiSelectedModel(agent: PiUserAgent, env: Readonly<Record<string, string | undefined>>): PiSelectedModel | null;
49
+ /** Resolves an extension entry against the working directory, the agent directory and as given. */
50
+ export declare function resolveExtensionEntry(entry: string, cwd: string, agentDir: string): string[];
51
+ export {};
@@ -0,0 +1,136 @@
1
+ /**
2
+ * pi user settings as inputs to the extension and the doctor.
3
+ *
4
+ * The extension protects the process it runs in; it never rewrites pi's agent
5
+ * directory. This module only reads that configuration to answer what the
6
+ * doctor needs: which provider and model are selected, which wire API they
7
+ * use, and where the extension has to be registered.
8
+ */
9
+ import path from "node:path";
10
+ export const SUPPORTED_PI_APIS = new Set([
11
+ "openai-completions",
12
+ "openai-responses",
13
+ "anthropic-messages",
14
+ ]);
15
+ export function isSupportedPiApi(value) {
16
+ return SUPPORTED_PI_APIS.has(value);
17
+ }
18
+ function isRecord(value) {
19
+ return value !== null && typeof value === "object" && !Array.isArray(value);
20
+ }
21
+ function parseJsonFile(raw, label) {
22
+ if (raw === null)
23
+ return undefined;
24
+ try {
25
+ return JSON.parse(raw);
26
+ }
27
+ catch {
28
+ throw new Error(`${label} is not valid JSON`);
29
+ }
30
+ }
31
+ function stringField(record, key, label) {
32
+ const value = record[key];
33
+ if (value === undefined)
34
+ return undefined;
35
+ if (typeof value !== "string" || value.length === 0)
36
+ throw new Error(`${label}.${key} must be a non-empty string`);
37
+ return value;
38
+ }
39
+ /** pi's default agent directory for a home path. */
40
+ export function defaultPiAgentDir(home) {
41
+ return path.join(home, ".pi", "agent");
42
+ }
43
+ /** Reads the user's pi agent configuration. Throws on malformed JSON. */
44
+ export function loadPiUserAgent(agentDir, readFile) {
45
+ const settingsRaw = readFile(path.join(agentDir, "settings.json"));
46
+ const settingsValue = parseJsonFile(settingsRaw, "pi settings.json");
47
+ if (settingsValue !== undefined && !isRecord(settingsValue))
48
+ throw new Error("pi settings.json must be a JSON object");
49
+ const settings = {};
50
+ if (settingsValue !== undefined) {
51
+ const model = stringField(settingsValue, "defaultModel", "pi settings.json");
52
+ const defaultProvider = stringField(settingsValue, "defaultProvider", "pi settings.json");
53
+ const sessionDir = stringField(settingsValue, "sessionDir", "pi settings.json");
54
+ if (model !== undefined)
55
+ settings.defaultModel = model;
56
+ if (defaultProvider !== undefined)
57
+ settings.defaultProvider = defaultProvider;
58
+ if (sessionDir !== undefined)
59
+ settings.sessionDir = sessionDir;
60
+ if (settingsValue.extensions !== undefined) {
61
+ if (!Array.isArray(settingsValue.extensions))
62
+ throw new Error("pi settings.json.extensions must be an array");
63
+ settings.extensions = settingsValue.extensions;
64
+ }
65
+ if (settingsValue.packages !== undefined) {
66
+ if (!Array.isArray(settingsValue.packages))
67
+ throw new Error("pi settings.json.packages must be an array");
68
+ settings.packages = settingsValue.packages;
69
+ }
70
+ }
71
+ const modelsRaw = readFile(path.join(agentDir, "models.json"));
72
+ const modelsValue = parseJsonFile(modelsRaw, "pi models.json");
73
+ if (modelsValue !== undefined && !isRecord(modelsValue))
74
+ throw new Error("pi models.json must be a JSON object");
75
+ const providers = {};
76
+ if (modelsValue !== undefined && modelsValue.providers !== undefined) {
77
+ if (!isRecord(modelsValue.providers))
78
+ throw new Error("pi models.json.providers must be an object");
79
+ for (const [id, entry] of Object.entries(modelsValue.providers)) {
80
+ if (!isRecord(entry))
81
+ throw new Error(`pi models.json.providers.${id} must be an object`);
82
+ if (entry.models !== undefined && !Array.isArray(entry.models)) {
83
+ throw new Error(`pi models.json.providers.${id}.models must be an array`);
84
+ }
85
+ if (entry.headers !== undefined) {
86
+ if (!isRecord(entry.headers) || Object.values(entry.headers).some((value) => typeof value !== "string")) {
87
+ throw new Error(`pi models.json.providers.${id}.headers must be a string map`);
88
+ }
89
+ }
90
+ providers[id] = entry;
91
+ }
92
+ }
93
+ return { agentDir, settings, providers };
94
+ }
95
+ /**
96
+ * The provider/model pi would start with. With a configured provider,
97
+ * `defaultModel` is a model id and may itself contain slashes. Without one it
98
+ * may be provider/id; like pi's resolver, the longest declared provider id
99
+ * followed by "/" wins.
100
+ */
101
+ export function resolvePiSelectedModel(agent, env) {
102
+ const configured = env.PI_PROVIDER ?? agent.settings.defaultProvider;
103
+ const providerConfigured = configured !== undefined && configured.length > 0;
104
+ let provider = providerConfigured ? configured : undefined;
105
+ let model = agent.settings.defaultModel;
106
+ if (!providerConfigured && model !== undefined) {
107
+ let best;
108
+ for (const id of Object.keys(agent.providers)) {
109
+ if (id.length === 0 || !model.toLowerCase().startsWith(`${id.toLowerCase()}/`))
110
+ continue;
111
+ if (best === undefined || id.length > best.length)
112
+ best = id;
113
+ }
114
+ if (best !== undefined) {
115
+ provider = best;
116
+ model = model.slice(best.length + 1);
117
+ }
118
+ }
119
+ if (provider === undefined || provider.length === 0)
120
+ return null;
121
+ const entry = agent.providers[provider];
122
+ if (entry === undefined)
123
+ return { provider, model };
124
+ const declared = entry.models?.find((candidate) => candidate.id === model);
125
+ return {
126
+ provider,
127
+ model,
128
+ api: declared?.api ?? entry.api,
129
+ baseUrl: declared?.baseUrl ?? entry.baseUrl,
130
+ };
131
+ }
132
+ /** Resolves an extension entry against the working directory, the agent directory and as given. */
133
+ export function resolveExtensionEntry(entry, cwd, agentDir) {
134
+ const candidates = [path.resolve(cwd, entry), path.resolve(agentDir, entry), entry];
135
+ return [...new Set(candidates)];
136
+ }
@@ -0,0 +1,11 @@
1
+ import type { HostToolPolicy } from "../../core/session-guard.js";
2
+ export declare function piUnknownToolError(rawTool: string): string;
3
+ /**
4
+ * Unknown and extension tools cannot be classified, so a placeholder must not
5
+ * reach them: their arguments may be forwarded to a remote service that never
6
+ * saw the pseudonymized session. Known pi built-ins go through the core, and
7
+ * `codemode` inherits the core's Code Mode handling.
8
+ * This deliberately overrides ADR-0001 for the pi host; see ADR-0006/ADR-0007.
9
+ */
10
+ export declare function assertPiToolBoundary(rawTool: string, input: unknown): void;
11
+ export declare const piToolPolicy: HostToolPolicy;