pi-windsurf-beta 0.1.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 khanhdeptraivaicachuong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # pi-windsurf-beta
2
+
package/auth.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Mint short-lived user_jwt for chat RPCs.
3
+ *
4
+ * POST https://server.codeium.com/exa.auth_pb.AuthService/GetUserJwt
5
+ */
6
+ import * as crypto from "crypto";
7
+ import { encodeMessage, iterFields } from "./wire";
8
+ import { buildMetadata } from "./metadata";
9
+
10
+ const DEFAULT_HOST = "https://server.codeium.com";
11
+
12
+ function anySignal(signals: AbortSignal[]): AbortSignal {
13
+ const builtin = (AbortSignal as unknown as { any?: (s: AbortSignal[]) => AbortSignal }).any;
14
+ if (typeof builtin === "function") return builtin(signals);
15
+ const controller = new AbortController();
16
+ const onAbort = (reason: unknown): void => {
17
+ if (!controller.signal.aborted) controller.abort(reason);
18
+ };
19
+ for (const s of signals) {
20
+ if (s.aborted) { onAbort(s.reason); break; }
21
+ s.addEventListener("abort", () => onAbort(s.reason), { once: true });
22
+ }
23
+ return controller.signal;
24
+ }
25
+
26
+ export interface MintedUserJwt {
27
+ jwt: string;
28
+ expiresAt: number;
29
+ }
30
+
31
+ export class CloudAuthError extends Error {
32
+ constructor(message: string, public readonly status?: number) {
33
+ super(message);
34
+ this.name = "CloudAuthError";
35
+ }
36
+ }
37
+
38
+ export async function mintUserJwt(
39
+ apiKey: string,
40
+ host: string = DEFAULT_HOST,
41
+ signal?: AbortSignal,
42
+ ): Promise<MintedUserJwt> {
43
+ const metadata = buildMetadata({
44
+ apiKey,
45
+ sessionId: crypto.randomUUID(),
46
+ requestId: BigInt(Date.now()),
47
+ triggerId: crypto.randomUUID(),
48
+ });
49
+ const req = encodeMessage(1, metadata);
50
+
51
+ const timeoutSignal = AbortSignal.timeout(30_000);
52
+ const combinedSignal: AbortSignal = signal ? anySignal([signal, timeoutSignal]) : timeoutSignal;
53
+
54
+ const resp = await fetch(`${host.replace(/\/$/, "")}/exa.auth_pb.AuthService/GetUserJwt`, {
55
+ method: "POST",
56
+ headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
57
+ body: req,
58
+ signal: combinedSignal,
59
+ });
60
+ const buf = Buffer.from(await resp.arrayBuffer());
61
+
62
+ if (!resp.ok) {
63
+ const text = buf.toString("utf8");
64
+ throw new CloudAuthError(`GetUserJwt HTTP ${resp.status}: ${text.slice(0, 400)}`, resp.status);
65
+ }
66
+
67
+ let jwt: string | null = null;
68
+ for (const f of iterFields(buf)) {
69
+ if (f.num === 1 && f.wire === 2 && Buffer.isBuffer(f.value)) {
70
+ const s = (f.value as Buffer).toString("utf8");
71
+ if (/^eyJ[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}$/.test(s)) {
72
+ jwt = s;
73
+ break;
74
+ }
75
+ }
76
+ }
77
+ if (!jwt) {
78
+ throw new CloudAuthError(`GetUserJwt 200 but no field-1 JWT found (${buf.length} bytes)`);
79
+ }
80
+
81
+ let expiresAt = Math.floor(Date.now() / 1000) + 600;
82
+ try {
83
+ const parts = jwt.split(".");
84
+ const pad = (s: string) => s + "=".repeat((4 - (s.length % 4)) % 4);
85
+ const payload = JSON.parse(
86
+ Buffer.from(pad(parts[1]).replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"),
87
+ );
88
+ if (typeof payload.exp === "number") expiresAt = payload.exp;
89
+ } catch { /* fall back to default */ }
90
+
91
+ return { jwt, expiresAt };
92
+ }
93
+
94
+ // ----------------------------------------------------------------------------
95
+ // In-memory cache
96
+ // ----------------------------------------------------------------------------
97
+
98
+ interface CacheEntry {
99
+ jwt: string;
100
+ expiresAt: number;
101
+ apiKey: string;
102
+ host: string;
103
+ }
104
+
105
+ let cache: CacheEntry | null = null;
106
+ const inFlight = new Map<string, Promise<MintedUserJwt>>();
107
+ let cacheEpoch = 0;
108
+
109
+ function flightKey(apiKey: string, host: string): string {
110
+ return `${host}\x1f${apiKey}`;
111
+ }
112
+
113
+ export async function getCachedUserJwt(apiKey: string, host: string = DEFAULT_HOST, signal?: AbortSignal): Promise<string> {
114
+ const now = Math.floor(Date.now() / 1000);
115
+ if (cache && cache.apiKey === apiKey && cache.host === host && cache.expiresAt > now + 60) {
116
+ return cache.jwt;
117
+ }
118
+ const key = flightKey(apiKey, host);
119
+ const existing = inFlight.get(key);
120
+ if (existing) return (await existing).jwt;
121
+ const promise = mintUserJwt(apiKey, host, signal);
122
+ inFlight.set(key, promise);
123
+ const epochAtStart = cacheEpoch;
124
+ try {
125
+ const minted = await promise;
126
+ if (cacheEpoch === epochAtStart) {
127
+ cache = { jwt: minted.jwt, expiresAt: minted.expiresAt, apiKey, host };
128
+ }
129
+ return minted.jwt;
130
+ } finally {
131
+ inFlight.delete(key);
132
+ }
133
+ }
134
+
135
+ export function clearCachedUserJwt(): void {
136
+ cache = null;
137
+ inFlight.clear();
138
+ cacheEpoch++;
139
+ }
package/catalog.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Per-account model catalog from Cognition's GetCascadeModelConfigs.
3
+ *
4
+ * Fetches live model list at startup and after login. Used for:
5
+ * 1. Dynamic model registration (new models appear automatically)
6
+ * 2. Pre-flight availability check (reject disabled models before wasting a roundtrip)
7
+ */
8
+ import * as crypto from "crypto";
9
+ import { buildMetadata } from "./metadata";
10
+ import { getCachedUserJwt, clearCachedUserJwt } from "./auth";
11
+ import { encodeMessage, iterFields } from "./wire";
12
+ import { clearSessionIds } from "./chat";
13
+
14
+ const CATALOG_TTL_MS = 10 * 60 * 1000;
15
+ const CATALOG_FETCH_TIMEOUT_MS = 10_000;
16
+
17
+ export interface ModelCatalogEntry {
18
+ modelUid: string;
19
+ label: string;
20
+ disabled: boolean;
21
+ }
22
+
23
+ interface CacheEntry {
24
+ byUid: Map<string, ModelCatalogEntry>;
25
+ fetchedAt: number;
26
+ apiKey: string;
27
+ host: string;
28
+ }
29
+
30
+ let cached: CacheEntry | null = null;
31
+ let inFlight: Promise<CacheEntry> | null = null;
32
+ let inFlightKey: string | null = null;
33
+
34
+ function flightKey(apiKey: string, host: string): string {
35
+ return `${host}\x1f${apiKey}`;
36
+ }
37
+
38
+ async function fetchCatalog(apiKey: string, host: string, signal?: AbortSignal): Promise<CacheEntry> {
39
+ const userJwt = await getCachedUserJwt(apiKey, host, signal);
40
+
41
+ const metadata = buildMetadata({
42
+ apiKey, userJwt,
43
+ sessionId: crypto.randomUUID(),
44
+ requestId: BigInt(Date.now()),
45
+ triggerId: crypto.randomUUID(),
46
+ });
47
+ const reqBody = encodeMessage(1, metadata);
48
+
49
+ const ac = new AbortController();
50
+ const timer = setTimeout(() => ac.abort(new Error(`catalog fetch timeout (${CATALOG_FETCH_TIMEOUT_MS}ms)`)), CATALOG_FETCH_TIMEOUT_MS);
51
+ let resp: Response;
52
+ try {
53
+ resp = await fetch(`${host}/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs`, {
54
+ method: "POST",
55
+ headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
56
+ body: reqBody,
57
+ signal: ac.signal,
58
+ });
59
+ } finally {
60
+ clearTimeout(timer);
61
+ }
62
+
63
+ if (!resp.ok) {
64
+ const text = await resp.text();
65
+ throw new Error(`GetCascadeModelConfigs HTTP ${resp.status}: ${text.slice(0, 200)}`);
66
+ }
67
+ const buf = Buffer.from(await resp.arrayBuffer());
68
+
69
+ const byUid = new Map<string, ModelCatalogEntry>();
70
+ for (const f of iterFields(buf)) {
71
+ if (f.num !== 1 || f.wire !== 2 || !Buffer.isBuffer(f.value)) continue;
72
+ let label = "";
73
+ let modelUid = "";
74
+ let disabled = false;
75
+ for (const sf of iterFields(f.value as Buffer)) {
76
+ if (sf.num === 1 && sf.wire === 2 && Buffer.isBuffer(sf.value)) {
77
+ label = (sf.value as Buffer).toString("utf8");
78
+ } else if (sf.num === 4 && sf.wire === 0) {
79
+ disabled = sf.value === 1n;
80
+ } else if (sf.num === 22 && sf.wire === 2 && Buffer.isBuffer(sf.value)) {
81
+ modelUid = (sf.value as Buffer).toString("utf8");
82
+ }
83
+ }
84
+ if (modelUid.length > 0) {
85
+ byUid.set(modelUid, { modelUid, label: label || modelUid, disabled });
86
+ }
87
+ }
88
+
89
+ return { byUid, fetchedAt: Date.now(), apiKey, host };
90
+ }
91
+
92
+ export async function getCachedCatalog(
93
+ apiKey: string,
94
+ host: string,
95
+ signal?: AbortSignal,
96
+ ): Promise<CacheEntry | null> {
97
+ if (cached && cached.apiKey === apiKey && cached.host === host) {
98
+ if (Date.now() - cached.fetchedAt < CATALOG_TTL_MS) return cached;
99
+ }
100
+
101
+ const key = flightKey(apiKey, host);
102
+ if (inFlight && inFlightKey === key) {
103
+ try { return await inFlight; } catch { return null; }
104
+ }
105
+
106
+ const promise = fetchCatalog(apiKey, host, signal);
107
+ inFlight = promise;
108
+ inFlightKey = key;
109
+ try {
110
+ const result = await promise;
111
+ cached = result;
112
+ return result;
113
+ } catch {
114
+ return null;
115
+ } finally {
116
+ if (inFlight === promise) { inFlight = null; inFlightKey = null; }
117
+ }
118
+ }
119
+
120
+ export function clearCachedCatalog(): void {
121
+ cached = null;
122
+ inFlight = null;
123
+ inFlightKey = null;
124
+ }
125
+
126
+ export class ModelNotAvailableError extends Error {
127
+ constructor(
128
+ public readonly modelUid: string,
129
+ public readonly label: string,
130
+ public readonly reason: "disabled" | "not_listed",
131
+ ) {
132
+ super(
133
+ reason === "disabled"
134
+ ? `Model "${label}" (uid=${modelUid}) is not enabled for your Cognition account. Check https://codeium.com/account.`
135
+ : `Model uid "${modelUid}" is not listed in the Cognition catalog for your account.`,
136
+ );
137
+ this.name = "ModelNotAvailableError";
138
+ }
139
+ }