@herbertgao/pi-extensions 2026.10.7 → 2026.10.9

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 (97) hide show
  1. package/README.md +4 -5
  2. package/THIRD_PARTY_NOTICES.md +2 -28
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +28 -27
  4. package/node_modules/@herbertgao/pi-cc-extensions/README.md +6 -6
  5. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +16 -27
  6. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +49 -48
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/compact-thinking.ts +2 -3
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +0 -60
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/reference/index.ts +2 -3
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer-layout.ts +105 -23
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +59 -43
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +96 -0
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/index.ts +6 -0
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +36 -34
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/default-mode.ts +7 -4
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +3 -2
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +23 -8
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/sticky-prompt.ts +2 -2
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +24 -12
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/codemode.ts +121 -6
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/diff-limits.ts +3 -2
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/diff-palette.ts +39 -8
  23. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/diff-presentation.ts +2 -2
  24. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +13 -13
  25. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/message-display.ts +3 -2
  26. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +49 -49
  27. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/result.ts +24 -0
  28. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/tool-state.ts +51 -2
  29. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  30. package/node_modules/@herbertgao/pi-cc-extensions/themes/cc-dark.json +71 -70
  31. package/node_modules/@herbertgao/pi-cc-extensions/themes/cc-light.json +71 -70
  32. package/node_modules/@tifan/pi-inline-skills/package.json +5 -1
  33. package/node_modules/@tifan/pi-inline-skills/src/index.ts +5 -2
  34. package/node_modules/pi-provider-qoder/dist/index.js +136 -31
  35. package/node_modules/pi-provider-qoder/package.json +1 -1
  36. package/node_modules/pi-typesafe/README.md +3 -3
  37. package/node_modules/pi-typesafe/dist/backends.d.ts +7 -2
  38. package/node_modules/pi-typesafe/dist/backends.js +42 -0
  39. package/node_modules/pi-typesafe/dist/batch.d.ts +10 -6
  40. package/node_modules/pi-typesafe/dist/batch.js +20 -9
  41. package/node_modules/pi-typesafe/dist/client.d.ts +4 -1
  42. package/node_modules/pi-typesafe/dist/client.js +5 -4
  43. package/node_modules/pi-typesafe/dist/index.d.ts +2 -2
  44. package/node_modules/pi-typesafe/dist/index.js +1 -1
  45. package/node_modules/pi-typesafe/dist/schema.d.ts +18 -3
  46. package/node_modules/pi-typesafe/dist/schema.js +29 -3
  47. package/node_modules/pi-typesafe/package.json +1 -1
  48. package/node_modules/pi-web-access/CHANGELOG.md +16 -0
  49. package/node_modules/pi-web-access/README.md +5 -2
  50. package/node_modules/pi-web-access/dist/index.js +13 -2
  51. package/node_modules/pi-web-access/dist/mcp-cli.js +14 -3
  52. package/node_modules/pi-web-access/extract.ts +4 -2
  53. package/node_modules/pi-web-access/package.json +1 -1
  54. package/node_modules/pi-web-access/searxng.ts +2 -1
  55. package/node_modules/pi-web-access/ssrf-protection.ts +11 -0
  56. package/package.json +6 -11
  57. package/node_modules/pi-multi-account/CHANGELOG.md +0 -1264
  58. package/node_modules/pi-multi-account/CONTRIBUTING.md +0 -61
  59. package/node_modules/pi-multi-account/LICENSE +0 -21
  60. package/node_modules/pi-multi-account/README.md +0 -277
  61. package/node_modules/pi-multi-account/SECURITY.md +0 -27
  62. package/node_modules/pi-multi-account/auth-file-transaction.ts +0 -56
  63. package/node_modules/pi-multi-account/child-usability.ts +0 -233
  64. package/node_modules/pi-multi-account/compaction-summary.ts +0 -32
  65. package/node_modules/pi-multi-account/completion-route-planner.ts +0 -224
  66. package/node_modules/pi-multi-account/config-file-transaction.ts +0 -42
  67. package/node_modules/pi-multi-account/context-guard.ts +0 -420
  68. package/node_modules/pi-multi-account/cursor/LICENSE +0 -21
  69. package/node_modules/pi-multi-account/cursor/NOTICE +0 -2
  70. package/node_modules/pi-multi-account/cursor/auth.ts +0 -165
  71. package/node_modules/pi-multi-account/cursor/bridge-handle.ts +0 -155
  72. package/node_modules/pi-multi-account/cursor/conversation-registry.ts +0 -104
  73. package/node_modules/pi-multi-account/cursor/cursor-models-raw.json +0 -611
  74. package/node_modules/pi-multi-account/cursor/cursor-shared.ts +0 -192
  75. package/node_modules/pi-multi-account/cursor/h2-bridge.mjs +0 -175
  76. package/node_modules/pi-multi-account/cursor/index.ts +0 -572
  77. package/node_modules/pi-multi-account/cursor/message-parsing.ts +0 -323
  78. package/node_modules/pi-multi-account/cursor/prompt-usage.ts +0 -53
  79. package/node_modules/pi-multi-account/cursor/proto/agent_pb.ts +0 -15294
  80. package/node_modules/pi-multi-account/cursor/proxy.ts +0 -2510
  81. package/node_modules/pi-multi-account/cursor/session-lifecycle.ts +0 -40
  82. package/node_modules/pi-multi-account/cursor/sse-keepalive.ts +0 -24
  83. package/node_modules/pi-multi-account/cursor/stream-lifecycle.ts +0 -193
  84. package/node_modules/pi-multi-account/cursor/upstream-watchdog.ts +0 -88
  85. package/node_modules/pi-multi-account/cursor-bridge.ts +0 -240
  86. package/node_modules/pi-multi-account/cursor-model-name.ts +0 -12
  87. package/node_modules/pi-multi-account/index.ts +0 -12340
  88. package/node_modules/pi-multi-account/model-catalog.ts +0 -354
  89. package/node_modules/pi-multi-account/model-pins.ts +0 -36
  90. package/node_modules/pi-multi-account/package.json +0 -104
  91. package/node_modules/pi-multi-account/pi-contract.ts +0 -281
  92. package/node_modules/pi-multi-account/provider-payload-stream.ts +0 -52
  93. package/node_modules/pi-multi-account/provider-priority.ts +0 -189
  94. package/node_modules/pi-multi-account/slot-proxy-auth.ts +0 -177
  95. package/node_modules/pi-multi-account/slot-proxy.ts +0 -366
  96. package/node_modules/pi-multi-account/state-file-transaction.ts +0 -67
  97. package/node_modules/pi-multi-account/usage.ts +0 -1128
@@ -1,177 +0,0 @@
1
- /**
2
- * How an OAuth slot is shown to an extension-free child without dropping the
3
- * subscription token the parent still needs.
4
- *
5
- * ## Why this exists
6
- *
7
- * Pi's `resolveProviderAuth` keys off the stored credential *type* first. For a models.json-only
8
- * provider (numbered `*-account-N` slots, and Cursor — which is not a Pi built-in) that means:
9
- *
10
- * stored OAuth + no OAuth method on the provider → undefined → "No API key found"
11
- *
12
- * A published placeholder in models.json is never consulted. The empty-auth.json canary hid this,
13
- * because there was no stored blob to win. On a real machine the blob is there — that is the
14
- * subprocess failure for memory review/consolidation. Measured again 2026-08-30 after restart:
15
- * the parent session was on `cursor/cursor-grok-4.6`, and
16
- * `pi -p --no-extensions --model cursor/cursor-grok-4.6` died with `No API key found for cursor`
17
- * while `anthropic/claude-opus-5` through the new loopback returned OK.
18
- *
19
- * The parent still needs the OAuth blob (refresh, identity headers, upstream). So while the
20
- * matching parent-owned proxy is listening the child-facing `auth.json` entry becomes a
21
- * non-secret api_key placeholder, and the OAuth blob lives in a sidecar only the parent reads.
22
- * On stop, the blob is written back. Base `anthropic` is not shadowed: Pi already has an OAuth
23
- * method for it, and the child presents the real token to the loopback, which admits it.
24
- */
25
- import {
26
- CURSOR_PROXY_PLACEHOLDER_KEY,
27
- isCursorProviderId,
28
- } from "./cursor-bridge.ts";
29
- import {
30
- needsChildFacingApiKey,
31
- isPlaceholderFor,
32
- placeholderKeyFor,
33
- proxyFamilyFor,
34
- type ProxyFamily,
35
- } from "./slot-proxy.ts";
36
-
37
- export type AuthBlob = {
38
- type?: string;
39
- access?: string;
40
- refresh?: string;
41
- expires?: number;
42
- key?: string;
43
- accountId?: string;
44
- };
45
-
46
- /** The non-secret api_key a child must see, or undefined if this slot is not shadowed. */
47
- export function childFacingPlaceholderKey(slotId: string): string | undefined {
48
- if (isCursorProviderId(slotId)) return CURSOR_PROXY_PLACEHOLDER_KEY;
49
- if (!needsChildFacingApiKey(slotId)) return undefined;
50
- const family = proxyFamilyFor(slotId);
51
- return family ? placeholderKeyFor(family) : undefined;
52
- }
53
-
54
- export function needsAuthShadow(slotId: string): boolean {
55
- return childFacingPlaceholderKey(slotId) !== undefined;
56
- }
57
-
58
- export function childFacingAuthEntry(family: ProxyFamily): AuthBlob {
59
- return { type: "api_key", key: placeholderKeyFor(family) };
60
- }
61
-
62
- export function childFacingAuthEntryForSlot(slotId: string): AuthBlob | undefined {
63
- const key = childFacingPlaceholderKey(slotId);
64
- return key ? { type: "api_key", key } : undefined;
65
- }
66
-
67
- export function isChildFacingPlaceholder(
68
- entry: AuthBlob | undefined,
69
- family: ProxyFamily,
70
- ): boolean {
71
- return entry?.type === "api_key" && isPlaceholderFor(family, entry.key);
72
- }
73
-
74
- export function isChildFacingPlaceholderForSlot(
75
- entry: AuthBlob | undefined,
76
- slotId: string,
77
- ): boolean {
78
- const key = childFacingPlaceholderKey(slotId);
79
- const family = proxyFamilyFor(slotId);
80
- return !!key && entry?.type === "api_key" &&
81
- (family ? isPlaceholderFor(family, entry.key) : entry.key === key);
82
- }
83
-
84
- /** What the parent should use for refresh/upstream: sidecar OAuth wins over a child-facing placeholder. */
85
- export function mergeParentAuth(
86
- auth: Readonly<Record<string, AuthBlob>>,
87
- sidecar: Readonly<Record<string, AuthBlob>>,
88
- ): Record<string, AuthBlob> {
89
- const out: Record<string, AuthBlob> = { ...auth };
90
- for (const [slotId, hidden] of Object.entries(sidecar)) {
91
- if (hidden?.type !== "oauth") continue;
92
- if (isChildFacingPlaceholderForSlot(out[slotId], slotId)) out[slotId] = hidden;
93
- }
94
- return out;
95
- }
96
-
97
- export function applyShadowPlan(
98
- slotId: string,
99
- auth: Readonly<Record<string, AuthBlob>>,
100
- sidecar: Readonly<Record<string, AuthBlob>>,
101
- ): { auth: Record<string, AuthBlob>; sidecar: Record<string, AuthBlob>; changed: boolean } {
102
- const facing = childFacingAuthEntryForSlot(slotId);
103
- if (!facing) {
104
- return { auth: { ...auth }, sidecar: { ...sidecar }, changed: false };
105
- }
106
- const entry = auth[slotId];
107
- const hidden = sidecar[slotId];
108
- if (isChildFacingPlaceholderForSlot(entry, slotId) && entry?.key !== facing.key &&
109
- hidden?.type === "oauth" && typeof hidden.access === "string" && hidden.access.length > 0) {
110
- // Upgrade only a publication backed by the parent's actual OAuth blob. Never rewrite a
111
- // user's real API key or replace the hidden credential with a placeholder during migration.
112
- return { auth: { ...auth, [slotId]: facing }, sidecar: { ...sidecar }, changed: true };
113
- }
114
- if (entry?.type === "oauth" && typeof entry.access === "string" && entry.access.length > 0) {
115
- return {
116
- auth: { ...auth, [slotId]: facing },
117
- sidecar: { ...sidecar, [slotId]: entry },
118
- changed: true,
119
- };
120
- }
121
- return { auth: { ...auth }, sidecar: { ...sidecar }, changed: false };
122
- }
123
-
124
- export function applyRestorePlan(
125
- slotId: string,
126
- auth: Readonly<Record<string, AuthBlob>>,
127
- sidecar: Readonly<Record<string, AuthBlob>>,
128
- ): { auth: Record<string, AuthBlob>; sidecar: Record<string, AuthBlob>; changed: boolean } {
129
- const hidden = sidecar[slotId];
130
- const nextSidecar = { ...sidecar };
131
- if (!hidden || hidden.type !== "oauth") {
132
- return { auth: { ...auth }, sidecar: nextSidecar, changed: false };
133
- }
134
- delete nextSidecar[slotId];
135
- if (isChildFacingPlaceholderForSlot(auth[slotId], slotId)) {
136
- return {
137
- auth: { ...auth, [slotId]: hidden },
138
- sidecar: nextSidecar,
139
- changed: true,
140
- };
141
- }
142
- // Auth already holds a real OAuth blob (re-login while shadowed). Drop the stale copy.
143
- return { auth: { ...auth }, sidecar: nextSidecar, changed: true };
144
- }
145
-
146
- export function applyShadowAll(
147
- slotIds: readonly string[],
148
- auth: Readonly<Record<string, AuthBlob>>,
149
- sidecar: Readonly<Record<string, AuthBlob>>,
150
- ): { auth: Record<string, AuthBlob>; sidecar: Record<string, AuthBlob>; changed: boolean } {
151
- let nextAuth = { ...auth };
152
- let nextSidecar = { ...sidecar };
153
- let changed = false;
154
- for (const slotId of slotIds) {
155
- const step = applyShadowPlan(slotId, nextAuth, nextSidecar);
156
- nextAuth = step.auth;
157
- nextSidecar = step.sidecar;
158
- changed = changed || step.changed;
159
- }
160
- return { auth: nextAuth, sidecar: nextSidecar, changed };
161
- }
162
-
163
- export function applyRestoreAll(
164
- auth: Readonly<Record<string, AuthBlob>>,
165
- sidecar: Readonly<Record<string, AuthBlob>>,
166
- ): { auth: Record<string, AuthBlob>; sidecar: Record<string, AuthBlob>; changed: boolean } {
167
- let nextAuth = { ...auth };
168
- let nextSidecar = { ...sidecar };
169
- let changed = false;
170
- for (const slotId of Object.keys(sidecar)) {
171
- const step = applyRestorePlan(slotId, nextAuth, nextSidecar);
172
- nextAuth = step.auth;
173
- nextSidecar = step.sidecar;
174
- changed = changed || step.changed;
175
- }
176
- return { auth: nextAuth, sidecar: nextSidecar, changed };
177
- }
@@ -1,366 +0,0 @@
1
- /**
2
- * A parent-owned loopback route that lets a child run on the account the rotation chose.
3
- *
4
- * ## The problem this exists for
5
- *
6
- * A process spawned without this extension — a memory consolidation, external CLI, or bare
7
- * `pi -p --no-extensions` call — either receives an explicit model or inherits Pi's saved global
8
- * default. Since Pi 0.84.3 that saved value intentionally does not track every live session
9
- * switch. In either case, publishing a rotation slot's *name* into `models.json` is not enough:
10
- * measured 2026-08-24, a
11
- * published slot carrying an OAuth credential fails with `No API key found`, because Pi honours
12
- * an OAuth credential only for a provider definition that declares the flow, and a `models.json`
13
- * entry declares none. The child then falls through to Pi's own first-available provider — a
14
- * different account, usually a different vendor, silently.
15
- *
16
- * The Cursor slots already solve this, and the shape is the answer for every OAuth family:
17
- * publish the slot against a route the parent serves on `127.0.0.1`, with a deliberately
18
- * non-secret placeholder as its `apiKey`. Pi sees a credential and admits the provider; the child
19
- * authenticates to this machine with a string worth nothing; the parent swaps in the real token
20
- * and adds whatever the family needs. The credential never leaves the parent.
21
- *
22
- * ## What lives here
23
- *
24
- * Only the decisions — routing, admission, and the exact shape of the upstream request. No
25
- * socket, no credential store, no file. That keeps the security-relevant rules (the placeholder is
26
- * never forwarded, an unknown caller is never served, a token never reaches a diagnostic) testable
27
- * exhaustively and without a network.
28
- */
29
-
30
- /**
31
- * The `apiKey` published into `models.json` for a proxied slot.
32
- *
33
- * Deliberately not a secret and deliberately recognisable: it exists so Pi will admit the
34
- * provider, and so this proxy can tell "a child we published a route for" from anything else that
35
- * found the port. It is also the admission token — see {@link admitRequest}.
36
- */
37
- export const PROXY_PLACEHOLDER_KEY = "pi-multi-account-proxy";
38
-
39
- /**
40
- * Non-secret Anthropic placeholder with the shape Pi's native transport recognizes as OAuth.
41
- * Request identity, tool-name conversion and response mapping all depend on this marker; adding
42
- * a Bearer header at the proxy is too late. The proxy replaces it with the real token on egress.
43
- * The legacy generic placeholder remains recognizable for restoration during an upgrade.
44
- */
45
- export const ANTHROPIC_PROXY_PLACEHOLDER_KEY = "sk-ant-oat01-pi-multi-account-proxy";
46
-
47
- /**
48
- * The `apiKey` published for a **Codex** slot.
49
- *
50
- * Pi's Codex API does not merely pass the key along: before any request it splits it on `.`,
51
- * base64-decodes the middle segment and reads `chatgpt_account_id` out of it, failing with
52
- * "Failed to extract accountId from token" if that does not work (measured 2026-08-24 against a
53
- * real `pi -p --no-extensions` child). So the placeholder for that family has to be shaped like a
54
- * token even though it is not one.
55
- *
56
- * Nothing here is secret and nothing here is real: the algorithm is `none`, there is no signature,
57
- * and the account id is the placeholder string rather than the user's — the proxy replaces both
58
- * the authorization header and the account id with the genuine values on the way out, so the
59
- * published file never carries either.
60
- */
61
- export const PROXY_PLACEHOLDER_JWT = [
62
- Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64"),
63
- Buffer.from(
64
- JSON.stringify({
65
- "https://api.openai.com/auth": { chatgpt_account_id: PROXY_PLACEHOLDER_KEY },
66
- }),
67
- ).toString("base64"),
68
- "",
69
- ].join(".");
70
-
71
- /** Current or legacy published placeholder — none is a real credential. */
72
- export function isPublishedPlaceholder(value: string | undefined): boolean {
73
- return value === PROXY_PLACEHOLDER_KEY || value === PROXY_PLACEHOLDER_JWT ||
74
- value === ANTHROPIC_PROXY_PLACEHOLDER_KEY;
75
- }
76
-
77
- export type ProxyFamily = "anthropic" | "codex";
78
-
79
- /**
80
- * Which family, if any, this parent-owned loopback can serve.
81
- *
82
- * Base `anthropic` is included because a bare child on a subscription token is refused as a
83
- * third-party app (measured 2026-08-30). Base `openai-codex` is not: the same child reached the
84
- * network on Pi's built-in provider. Numbered Codex/Anthropic slots are included because a
85
- * models.json entry has no OAuth method, so Pi never consults a published placeholder while an
86
- * OAuth blob sits under the same key.
87
- */
88
- export function proxyFamilyFor(slotId: string): ProxyFamily | undefined {
89
- if (slotId === "anthropic" || /^anthropic-account-\d+$/.test(slotId)) return "anthropic";
90
- if (/^openai-codex-account-\d+$/.test(slotId)) return "codex";
91
- return undefined;
92
- }
93
-
94
- /** Numbered slots have no built-in OAuth method; the child-facing credential must be an API key. */
95
- export function needsChildFacingApiKey(slotId: string): boolean {
96
- return /(?:-account-\d+)$/.test(slotId) && proxyFamilyFor(slotId) !== undefined;
97
- }
98
-
99
- /** Where each family's traffic really goes. */
100
- export const UPSTREAM_BASE: Readonly<Record<ProxyFamily, string>> = Object.freeze({
101
- anthropic: "https://api.anthropic.com",
102
- codex: "https://chatgpt.com/backend-api",
103
- });
104
-
105
- export interface ProxyRoute {
106
- slotId: string;
107
- family: ProxyFamily;
108
- }
109
-
110
- export interface ProxyCredential {
111
- type?: string;
112
- access?: string;
113
- key?: string;
114
- accountId?: string;
115
- }
116
-
117
- /**
118
- * Headers a proxy must never copy from the incoming request to the outgoing one.
119
- *
120
- * The hop-by-hop set is per RFC 9110; `host` and `content-length` are recomputed by the client;
121
- * `authorization`/`x-api-key` are dropped because replacing them is the entire point of this
122
- * proxy and forwarding the placeholder would authenticate nothing.
123
- */
124
- const DROPPED_HEADERS = new Set([
125
- "authorization",
126
- "x-api-key",
127
- "host",
128
- "content-length",
129
- "connection",
130
- "keep-alive",
131
- "transfer-encoding",
132
- "te",
133
- "trailer",
134
- "upgrade",
135
- "proxy-authorization",
136
- "proxy-authenticate",
137
- "accept-encoding",
138
- ]);
139
-
140
- /**
141
- * Split `/slot-id/v1/messages` into the slot and the path to forward.
142
- *
143
- * Returns `undefined` for anything that is not that shape, including a path that tries to climb
144
- * out of its slot. A loopback port is reachable by every process on the machine, so the parsing
145
- * here is the first of the two gates — the second is {@link admitRequest}.
146
- */
147
- export function parseProxyPath(
148
- rawUrl: string,
149
- ): { slotId: string; rest: string } | undefined {
150
- if (typeof rawUrl !== "string" || !rawUrl.startsWith("/")) return undefined;
151
- const [pathname] = rawUrl.split("#");
152
- const separator = pathname.indexOf("/", 1);
153
- const slotId = decodeURIComponent(
154
- separator === -1 ? pathname.slice(1) : pathname.slice(1, separator),
155
- ).split("?")[0];
156
- if (!slotId || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slotId)) return undefined;
157
- const rest = separator === -1 ? "/" : pathname.slice(separator);
158
- // `..` in any form is refused rather than normalised: there is no legitimate caller that needs
159
- // it, and normalising is where path-traversal bugs live.
160
- if (rest.includes("..") || rest.includes("%2e%2e") || rest.includes("%2E%2E")) {
161
- return undefined;
162
- }
163
- return { slotId, rest };
164
- }
165
-
166
- /** The credential the caller presented, from either header a Pi provider might use. */
167
- export function presentedCredential(
168
- headers: Readonly<Record<string, string | string[] | undefined>>,
169
- ): string | undefined {
170
- const pick = (name: string) => {
171
- const value = headers[name];
172
- const first = Array.isArray(value) ? value[0] : value;
173
- return typeof first === "string" ? first.trim() : undefined;
174
- };
175
- const bearer = pick("authorization");
176
- if (bearer) return bearer.replace(/^Bearer\s+/i, "").trim();
177
- return pick("x-api-key");
178
- }
179
-
180
- export type Admission =
181
- | { ok: true; route: ProxyRoute }
182
- | { ok: false; status: number; message: string };
183
-
184
- /**
185
- * Decide whether to serve a request at all.
186
- *
187
- * Two gates, and both matter. The slot has to be one we published — otherwise the port becomes a
188
- * way to reach any upstream through the user's tokens. And the caller has to present either the
189
- * published placeholder or the current access token for that slot — otherwise every process on
190
- * this machine can spend the user's subscription just by finding the port. The placeholder is not
191
- * a secret; the access token is, and a refusal never echoes either. The access-token path exists
192
- * because a built-in Anthropic child still presents OAuth: Pi ignores a models.json apiKey when
193
- * the stored credential is OAuth, and the request only becomes shapable if this proxy accepts it.
194
- */
195
- export function admitRequest(args: {
196
- rawUrl: string;
197
- headers: Readonly<Record<string, string | string[] | undefined>>;
198
- routes: ReadonlyMap<string, ProxyRoute>;
199
- /** Current access tokens for this slot. Never logged; compared only. */
200
- acceptedSecrets?: readonly string[];
201
- }): Admission & { rest?: string } {
202
- const parsed = parseProxyPath(args.rawUrl);
203
- if (!parsed) return { ok: false, status: 404, message: "not a slot route" };
204
- const route = args.routes.get(parsed.slotId);
205
- if (!route) return { ok: false, status: 404, message: "unknown slot" };
206
- const presented = presentedCredential(args.headers);
207
- const accepted =
208
- isPublishedPlaceholder(presented) ||
209
- (!!presented && !!args.acceptedSecrets?.includes(presented));
210
- if (!accepted) {
211
- // Never echo what was presented: it may be a real credential belonging to whoever called.
212
- return { ok: false, status: 401, message: "this route serves published slots only" };
213
- }
214
- return { ok: true, route, rest: parsed.rest };
215
- }
216
-
217
- export type UpstreamRequest =
218
- | { ok: true; url: string; headers: Record<string, string> }
219
- | { ok: false; status: number; message: string };
220
-
221
- /**
222
- * Build the request that actually goes out.
223
- *
224
- * The real credential enters here and leaves only in the returned headers — never in a message,
225
- * because these messages are logged and shown.
226
- */
227
- export function shapeUpstreamRequest(args: {
228
- route: ProxyRoute;
229
- rest: string;
230
- headers: Readonly<Record<string, string | string[] | undefined>>;
231
- credential: ProxyCredential | undefined;
232
- }): UpstreamRequest {
233
- const { route, rest, credential } = args;
234
- const base = UPSTREAM_BASE[route.family];
235
- if (!base) return { ok: false, status: 500, message: `no upstream for ${route.family}` };
236
- if (!credential) {
237
- return {
238
- ok: false,
239
- status: 401,
240
- message: `no credential held for ${route.slotId} — run /login for that account`,
241
- };
242
- }
243
-
244
- const headers: Record<string, string> = {};
245
- for (const [name, value] of Object.entries(args.headers)) {
246
- const lower = name.toLowerCase();
247
- if (DROPPED_HEADERS.has(lower)) continue;
248
- const first = Array.isArray(value) ? value.join(", ") : value;
249
- if (typeof first === "string") headers[lower] = first;
250
- }
251
-
252
- if (credential.type === "api_key" || (!credential.access && credential.key)) {
253
- const key = credential.key;
254
- if (!key) {
255
- return {
256
- ok: false,
257
- status: 401,
258
- message: `no API key held for ${route.slotId} — run /login for that account`,
259
- };
260
- }
261
- if (route.family === "anthropic") headers["x-api-key"] = key;
262
- else headers.authorization = `Bearer ${key}`;
263
- } else {
264
- if (!credential.access) {
265
- return {
266
- ok: false,
267
- status: 401,
268
- message: `the credential for ${route.slotId} has no access token — run /login for that account`,
269
- };
270
- }
271
- headers.authorization = `Bearer ${credential.access}`;
272
- if (route.family === "anthropic") {
273
- // The header Anthropic requires before it will accept a subscription token at all.
274
- headers["anthropic-beta"] = mergeBeta(headers["anthropic-beta"], "oauth-2025-04-20");
275
- } else if (route.family === "codex") {
276
- // Codex routes a subscription request by account. Pi fills this header in from the
277
- // placeholder it was given, so it must be overwritten here — not defaulted — or the
278
- // request goes upstream naming an account that does not exist.
279
- if (credential.accountId) headers["chatgpt-account-id"] = credential.accountId;
280
- else delete headers["chatgpt-account-id"];
281
- headers.originator = headers.originator ?? "pi";
282
- }
283
- }
284
-
285
- // Image tools append these endpoints directly to the slot base; chat already sends /codex.
286
- // Leave all other paths and families intact, including usage requests.
287
- const upstreamRest =
288
- route.family === "codex" && /^\/images\/(?:generations|edits)(?:\?.*)?$/.test(rest)
289
- ? `/codex${rest}`
290
- : rest;
291
-
292
- return { ok: true, url: `${base}${upstreamRest}`, headers };
293
- }
294
-
295
- /** Keep any beta flags the caller asked for, and add ours once. */
296
- function mergeBeta(existing: string | undefined, required: string): string {
297
- if (!existing) return required;
298
- const parts = existing
299
- .split(",")
300
- .map((part) => part.trim())
301
- .filter(Boolean);
302
- if (!parts.includes(required)) parts.push(required);
303
- return parts.join(",");
304
- }
305
-
306
- /** The `apiKey` to publish for a slot of this family. */
307
- export function placeholderKeyFor(family: ProxyFamily): string {
308
- return family === "codex" ? PROXY_PLACEHOLDER_JWT : ANTHROPIC_PROXY_PLACEHOLDER_KEY;
309
- }
310
-
311
- /** Recognize the previous Anthropic publication without mistaking real tokens for placeholders. */
312
- export function isPlaceholderFor(family: ProxyFamily, value: unknown): boolean {
313
- return value === placeholderKeyFor(family) ||
314
- (family === "anthropic" && value === PROXY_PLACEHOLDER_KEY);
315
- }
316
-
317
- /** The `models.json` route to publish for a slot served by this proxy. */
318
- export function publishedRouteFor(port: number, slotId: string): string {
319
- return `http://127.0.0.1:${port}/${slotId}`;
320
- }
321
-
322
- /** True when this models.json entry is a loopback we published, not a user's own provider. */
323
- export function isOwnLoopbackPublication(
324
- existing: unknown,
325
- family: ProxyFamily,
326
- ): boolean {
327
- if (!existing || typeof existing !== "object") return false;
328
- const rec = existing as Record<string, unknown>;
329
- return (
330
- isPlaceholderFor(family, rec.apiKey) &&
331
- typeof rec.baseUrl === "string" &&
332
- rec.baseUrl.startsWith("http://127.0.0.1:")
333
- );
334
- }
335
-
336
- /** Return the user-authored model override layer from a provider entry, if present. */
337
- export function preservedModelOverrides(
338
- existing: unknown,
339
- ): Record<string, unknown> | undefined {
340
- if (!existing || typeof existing !== "object" || Array.isArray(existing)) return undefined;
341
- const overrides = (existing as Record<string, unknown>).modelOverrides;
342
- if (!overrides || typeof overrides !== "object" || Array.isArray(overrides)) return undefined;
343
- if (Object.keys(overrides).length === 0) return undefined;
344
- return overrides as Record<string, unknown>;
345
- }
346
-
347
- /**
348
- * Drop loopback publications this proxy wrote. Cursor and user entries stay. A user's
349
- * modelOverrides remain as a valid built-in-provider overlay after the generated route is gone.
350
- * Pass slot ids to drop only those; omit to drop every own loopback (a dead port left behind).
351
- */
352
- export function dropOwnLoopbackPublications(
353
- providers: Readonly<Record<string, unknown>>,
354
- slotIds?: readonly string[],
355
- ): Record<string, unknown> {
356
- const next: Record<string, unknown> = { ...providers };
357
- const ids = slotIds ?? Object.keys(next);
358
- for (const id of ids) {
359
- const family = proxyFamilyFor(id);
360
- if (!family || !isOwnLoopbackPublication(next[id], family)) continue;
361
- const modelOverrides = preservedModelOverrides(next[id]);
362
- if (modelOverrides) next[id] = { modelOverrides };
363
- else delete next[id];
364
- }
365
- return next;
366
- }
@@ -1,67 +0,0 @@
1
- /** Shared cooldown/cache state: lock before reading, merge local deltas, publish atomically. */
2
- import { randomUUID } from "node:crypto";
3
- import { createRequire } from "node:module";
4
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
- import { dirname } from "node:path";
6
-
7
- const require = createRequire(import.meta.url);
8
- const pause = new Int32Array(new SharedArrayBuffer(4));
9
- const MAP_FIELDS = ["exhaustedUntilByProvider", "exhaustedUntilByModel", "invalidatedByProvider",
10
- "usageUntrustedUntilByProvider", "usageByProvider", "codexModelCatalogByProvider", "lastProbeAtByProvider"];
11
- type State = Record<string, any>;
12
-
13
- export function mergeStateDeltas<T extends State>(base: T, local: T, disk: T): T {
14
- const merged = { ...local };
15
- for (const field of MAP_FIELDS) {
16
- const before = base[field] ?? {}, after = local[field] ?? {};
17
- const values = { ...(disk[field] ?? {}) };
18
- for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
19
- if (JSON.stringify(before[key]) === JSON.stringify(after[key])) continue;
20
- if (Object.hasOwn(after, key)) {
21
- // A slower fetch must not overwrite a newer observation of the same credential.
22
- const newer = values[key], candidate = after[key];
23
- if ((field === "usageByProvider" || field === "codexModelCatalogByProvider") &&
24
- newer?.credentialHash === candidate?.credentialHash && newer?.fetchedAt > candidate?.fetchedAt) continue;
25
- values[key] = candidate;
26
- } else delete values[key];
27
- }
28
- (merged as State)[field] = values;
29
- }
30
- return merged;
31
- }
32
-
33
- export function mutateStateFile<T extends State>(path: string, transform: (disk: T) => T): T {
34
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
35
- if (!existsSync(path)) {
36
- try { writeFileSync(path, "{}\n", { mode: 0o600, flag: "wx" }); }
37
- catch (error: any) { if (error?.code !== "EEXIST") throw error; }
38
- }
39
- const lockfile = require("proper-lockfile") as { lockSync(path: string, options: object): () => void };
40
- let release: (() => void) | undefined;
41
- // Writes are synchronous and short. Bound contention rather than hanging the Pi event loop.
42
- const deadline = Date.now() + 250;
43
- while (!release) {
44
- try { release = lockfile.lockSync(path, { realpath: false }); }
45
- catch (error: any) {
46
- if (error?.code !== "ELOCKED" || Date.now() >= deadline) throw error;
47
- Atomics.wait(pause, 0, 0, 5);
48
- }
49
- }
50
- const temp = `${path}.${process.pid}.${randomUUID()}.tmp`;
51
- try {
52
- let disk: T;
53
- try {
54
- disk = JSON.parse(readFileSync(path, "utf8"));
55
- if (!disk || typeof disk !== "object" || Array.isArray(disk)) disk = {} as T;
56
- } catch (error) {
57
- if (!(error instanceof SyntaxError)) throw error;
58
- disk = {} as T; // Derived state is recoverable; credentials never enter this file.
59
- }
60
- const next = transform(disk);
61
- writeFileSync(temp, `${JSON.stringify(next, null, "\t")}\n`, { mode: 0o600, flag: "wx" });
62
- renameSync(temp, path);
63
- return next;
64
- } finally {
65
- try { rmSync(temp, { force: true }); } finally { release(); }
66
- }
67
- }