@daex-dev/sdk 0.0.0-stage → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +478 -2
- package/dist/client-DVZHOtg6.d.cts +2635 -0
- package/dist/client-DVZHOtg6.d.ts +2635 -0
- package/dist/connect/browser.cjs +209 -0
- package/dist/connect/browser.d.cts +81 -0
- package/dist/connect/browser.d.ts +81 -0
- package/dist/connect/browser.js +183 -0
- package/dist/connect/index.cjs +1954 -0
- package/dist/connect/index.d.cts +433 -0
- package/dist/connect/index.d.ts +433 -0
- package/dist/connect/index.js +1888 -0
- package/dist/electron/global.cjs +18 -0
- package/dist/electron/global.d.cts +35 -0
- package/dist/electron/global.d.ts +35 -0
- package/dist/electron/global.js +0 -0
- package/dist/electron/index.cjs +1133 -0
- package/dist/electron/index.d.cts +510 -0
- package/dist/electron/index.d.ts +510 -0
- package/dist/electron/index.js +1073 -0
- package/dist/electron/preload-auto.cjs +38 -0
- package/dist/electron/preload.cjs +66 -0
- package/dist/electron/preload.d.cts +46 -0
- package/dist/electron/preload.d.ts +46 -0
- package/dist/electron/preload.js +43 -0
- package/dist/electron/protocol-DXRtliy3.d.cts +904 -0
- package/dist/electron/protocol-DXRtliy3.d.ts +904 -0
- package/dist/electron/renderer.cjs +631 -0
- package/dist/electron/renderer.d.cts +508 -0
- package/dist/electron/renderer.d.ts +508 -0
- package/dist/electron/renderer.global.js +634 -0
- package/dist/electron/renderer.js +608 -0
- package/dist/index.cjs +6731 -0
- package/dist/index.d.cts +316 -0
- package/dist/index.d.ts +316 -0
- package/dist/index.js +6661 -0
- package/dist/server.cjs +1019 -0
- package/dist/server.d.cts +118 -0
- package/dist/server.d.ts +118 -0
- package/dist/server.js +989 -0
- package/dist/testing.cjs +815 -0
- package/dist/testing.d.cts +29 -0
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +787 -0
- package/dist/types-DUGv-9QF.d.cts +166 -0
- package/dist/types-DUGv-9QF.d.ts +166 -0
- package/package.json +109 -4
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/connect/browser.ts
|
|
21
|
+
var browser_exports = {};
|
|
22
|
+
__export(browser_exports, {
|
|
23
|
+
ConnectClientFailure: () => ConnectClientFailure,
|
|
24
|
+
createConnectClient: () => createConnectClient
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(browser_exports);
|
|
27
|
+
var ConnectClientFailure = class extends Error {
|
|
28
|
+
code;
|
|
29
|
+
detail;
|
|
30
|
+
/** The HTTP status of the failed call, when it came from a response. */
|
|
31
|
+
status;
|
|
32
|
+
constructor(detail, status) {
|
|
33
|
+
super(detail.message);
|
|
34
|
+
this.name = "ConnectClientFailure";
|
|
35
|
+
this.code = detail.code;
|
|
36
|
+
this.detail = detail;
|
|
37
|
+
this.status = status;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
function createConnectClient(options = {}) {
|
|
41
|
+
const base = (options.baseUrl ?? "/connect").replace(/\/$/, "");
|
|
42
|
+
const doFetch = options.fetch ?? fetch.bind(globalThis);
|
|
43
|
+
const headers = () => ({ ...typeof options.headers === "function" ? options.headers() : options.headers ?? {} });
|
|
44
|
+
const call = async (path, init = {}) => {
|
|
45
|
+
const response = await doFetch(`${base}${path}`, {
|
|
46
|
+
method: init.method ?? "GET",
|
|
47
|
+
headers: { ...headers(), Accept: "application/json", ...init.body !== void 0 ? { "Content-Type": "application/json" } : {} },
|
|
48
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
49
|
+
...init.signal ? { signal: init.signal } : {},
|
|
50
|
+
credentials: "include"
|
|
51
|
+
});
|
|
52
|
+
const value = await response.json().catch(() => ({}));
|
|
53
|
+
if (!response.ok) {
|
|
54
|
+
const error = value.error ?? { code: "http_error", message: `HTTP ${response.status}` };
|
|
55
|
+
throw new ConnectClientFailure(error, response.status);
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
};
|
|
59
|
+
const windowOpen = globalThis.open;
|
|
60
|
+
const reservePage = (signInOptions) => {
|
|
61
|
+
const reserved = signInOptions?.open ? null : windowOpen?.("about:blank", "_blank") ?? null;
|
|
62
|
+
return {
|
|
63
|
+
show(url) {
|
|
64
|
+
if (signInOptions?.open) return signInOptions.open(url);
|
|
65
|
+
if (reserved?.location) {
|
|
66
|
+
reserved.opener = null;
|
|
67
|
+
reserved.location.href = url;
|
|
68
|
+
return reserved;
|
|
69
|
+
}
|
|
70
|
+
return windowOpen?.(url, "_blank", "noopener");
|
|
71
|
+
},
|
|
72
|
+
discard() {
|
|
73
|
+
closePage(reserved);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
const closePage = (handle) => {
|
|
78
|
+
try {
|
|
79
|
+
handle?.close?.();
|
|
80
|
+
} catch {
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const cancelledFailure = (provider) => new ConnectClientFailure({ code: "sign_in_cancelled", message: "The sign-in was cancelled.", provider });
|
|
84
|
+
const signInWithCodex = async (signInOptions) => {
|
|
85
|
+
if (!signInOptions?.askForRedirectUrl) {
|
|
86
|
+
throw new ConnectClientFailure({ code: "invalid_request", message: "ChatGPT sign-in on the web needs askForRedirectUrl." });
|
|
87
|
+
}
|
|
88
|
+
const reserved = reservePage(signInOptions);
|
|
89
|
+
let started;
|
|
90
|
+
try {
|
|
91
|
+
started = await call("/codex/start", { method: "POST", body: {} });
|
|
92
|
+
} catch (error) {
|
|
93
|
+
reserved.discard();
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
const page = reserved.show(started.url);
|
|
97
|
+
const callbackUrl = await signInOptions.askForRedirectUrl();
|
|
98
|
+
closePage(page);
|
|
99
|
+
if (!callbackUrl) throw cancelledFailure("codex");
|
|
100
|
+
await call("/codex/complete", { method: "POST", body: { signInId: started.signInId, callbackUrl } });
|
|
101
|
+
};
|
|
102
|
+
const signInWithCursor = async (signInOptions) => {
|
|
103
|
+
const reserved = reservePage(signInOptions);
|
|
104
|
+
let started;
|
|
105
|
+
try {
|
|
106
|
+
started = await call("/cursor/start", { method: "POST", body: {} });
|
|
107
|
+
} catch (error) {
|
|
108
|
+
reserved.discard();
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
const page = reserved.show(started.url);
|
|
112
|
+
const pollMs = signInOptions?.pollMs ?? 2e3;
|
|
113
|
+
let failedPolls = 0;
|
|
114
|
+
try {
|
|
115
|
+
while (true) {
|
|
116
|
+
if (signInOptions?.signal?.aborted) throw cancelledFailure("cursor");
|
|
117
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
118
|
+
let status;
|
|
119
|
+
try {
|
|
120
|
+
status = await call(`/cursor/status?signInId=${encodeURIComponent(started.signInId)}`);
|
|
121
|
+
failedPolls = 0;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
const transient = !(error instanceof ConnectClientFailure) || (error.status ?? 0) >= 500;
|
|
124
|
+
if (!transient || ++failedPolls > 5) throw error;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (status.state === "done") return;
|
|
128
|
+
if (status.state === "failed") {
|
|
129
|
+
throw new ConnectClientFailure(status.error ?? { code: "sign_in_failed", message: "Cursor's sign-in did not finish.", provider: "cursor" });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
} finally {
|
|
133
|
+
closePage(page);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
const signInFlows = {
|
|
137
|
+
codex: signInWithCodex,
|
|
138
|
+
cursor: signInWithCursor
|
|
139
|
+
};
|
|
140
|
+
return {
|
|
141
|
+
providers: () => call("/providers"),
|
|
142
|
+
/** Run a provider's sign-in. Resolves when the server holds the sign-in. */
|
|
143
|
+
signIn: (provider, signInOptions) => signInFlows[provider](signInOptions),
|
|
144
|
+
/** `revoked`: whether the provider confirmed the sign-out (null when there was nothing to revoke). */
|
|
145
|
+
signOut: (provider) => call(`/${provider}/sign-out`, { method: "POST", body: {} }),
|
|
146
|
+
models: (provider) => call(`/models?provider=${provider}`),
|
|
147
|
+
/**
|
|
148
|
+
* Stream a reply. Throws `ConnectClientFailure` for sign-in, plan and
|
|
149
|
+
* provider errors, and for a reply cut off before it finished. Stopping
|
|
150
|
+
* early (`break`) closes the connection, so the server stops generating.
|
|
151
|
+
*/
|
|
152
|
+
async *respond(request) {
|
|
153
|
+
const { signal, ...payload } = request;
|
|
154
|
+
const response = await doFetch(`${base}/respond`, {
|
|
155
|
+
method: "POST",
|
|
156
|
+
headers: { ...headers(), "Content-Type": "application/json", Accept: "text/event-stream" },
|
|
157
|
+
body: JSON.stringify(payload),
|
|
158
|
+
credentials: "include",
|
|
159
|
+
...signal ? { signal } : {}
|
|
160
|
+
});
|
|
161
|
+
if (!response.ok || !response.body) {
|
|
162
|
+
const value = await response.json().catch(() => ({}));
|
|
163
|
+
throw new ConnectClientFailure(value.error ?? { code: "http_error", message: `HTTP ${response.status}` });
|
|
164
|
+
}
|
|
165
|
+
const reader = response.body.getReader();
|
|
166
|
+
const decoder = new TextDecoder();
|
|
167
|
+
let buffer = "";
|
|
168
|
+
let finished = false;
|
|
169
|
+
try {
|
|
170
|
+
while (!finished) {
|
|
171
|
+
const { value, done } = await reader.read();
|
|
172
|
+
if (done) {
|
|
173
|
+
throw new ConnectClientFailure({ code: "provider_error", message: "The reply was cut off before it finished.", retryable: true });
|
|
174
|
+
}
|
|
175
|
+
buffer += decoder.decode(value, { stream: true });
|
|
176
|
+
let boundary = buffer.indexOf("\n\n");
|
|
177
|
+
while (boundary !== -1 && !finished) {
|
|
178
|
+
const block = buffer.slice(0, boundary);
|
|
179
|
+
buffer = buffer.slice(boundary + 2);
|
|
180
|
+
const event = /^event: (.+)$/m.exec(block)?.[1];
|
|
181
|
+
const data = /^data: (.+)$/m.exec(block)?.[1];
|
|
182
|
+
const parsed = data ? JSON.parse(data) : {};
|
|
183
|
+
if (event === "text") yield { type: "text", delta: String(parsed.delta ?? "") };
|
|
184
|
+
else if (event === "raw") yield { type: "raw", provider: parsed.provider, event: parsed.event };
|
|
185
|
+
else if (event === "error") throw new ConnectClientFailure(parsed);
|
|
186
|
+
else if (event === "done") {
|
|
187
|
+
finished = true;
|
|
188
|
+
yield {
|
|
189
|
+
type: "done",
|
|
190
|
+
text: String(parsed.text ?? ""),
|
|
191
|
+
...typeof parsed.model === "string" ? { model: parsed.model } : {},
|
|
192
|
+
...parsed.usage === void 0 ? {} : { usage: parsed.usage },
|
|
193
|
+
...parsed.response === void 0 ? {} : { response: parsed.response }
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
boundary = buffer.indexOf("\n\n");
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
} finally {
|
|
200
|
+
await reader.cancel().catch(() => void 0);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
206
|
+
0 && (module.exports = {
|
|
207
|
+
ConnectClientFailure,
|
|
208
|
+
createConnectClient
|
|
209
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { C as ConnectProviderInfo, a as ConnectSignInStatus, b as ConnectProviderId, c as ConnectModel, d as ConnectBrowserRequest, e as ConnectEvent } from '../types-DUGv-9QF.cjs';
|
|
2
|
+
export { f as ConnectMessage, g as ConnectResponseFormat } from '../types-DUGv-9QF.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `@daex-dev/sdk/connect/browser`: the page side of `createConnectHandler`.
|
|
6
|
+
* No secrets live here; the page only talks to the app's own server. Types
|
|
7
|
+
* come from the shared `types.ts` with `import type`, so this bundle has no
|
|
8
|
+
* runtime import at all.
|
|
9
|
+
*
|
|
10
|
+
* const connect = createConnectClient({ baseUrl: "/connect" });
|
|
11
|
+
* const { providers } = await connect.providers();
|
|
12
|
+
* await connect.signIn("cursor");
|
|
13
|
+
* await connect.signIn("codex", { askForRedirectUrl: () => prompt("Paste the address you ended on") });
|
|
14
|
+
* for await (const event of connect.respond({ provider: "codex", prompt: "Hi" })) …
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
type ConnectProviderRow = ConnectProviderInfo & {
|
|
18
|
+
status: ConnectSignInStatus;
|
|
19
|
+
};
|
|
20
|
+
type ConnectClientError = {
|
|
21
|
+
code: string;
|
|
22
|
+
message: string;
|
|
23
|
+
provider?: string;
|
|
24
|
+
retryable?: boolean;
|
|
25
|
+
manageUrl?: string;
|
|
26
|
+
};
|
|
27
|
+
declare class ConnectClientFailure extends Error {
|
|
28
|
+
readonly code: string;
|
|
29
|
+
readonly detail: ConnectClientError;
|
|
30
|
+
/** The HTTP status of the failed call, when it came from a response. */
|
|
31
|
+
readonly status?: number;
|
|
32
|
+
constructor(detail: ConnectClientError, status?: number);
|
|
33
|
+
}
|
|
34
|
+
type ConnectClientOptions = {
|
|
35
|
+
/** Where `createConnectHandler` is mounted. Default `/connect`. */
|
|
36
|
+
baseUrl?: string;
|
|
37
|
+
/** Extra headers for every call (e.g. the app's own auth). */
|
|
38
|
+
headers?: Record<string, string> | (() => Record<string, string>);
|
|
39
|
+
fetch?: typeof fetch;
|
|
40
|
+
};
|
|
41
|
+
type SignInOptions = {
|
|
42
|
+
/**
|
|
43
|
+
* Opens the provider's page. Default: a tab reserved with `window.open`
|
|
44
|
+
* before any network call (so a popup blocker allows it), then pointed at the
|
|
45
|
+
* page. Return the window when you open one, so it can be closed at the end.
|
|
46
|
+
*/
|
|
47
|
+
open?: (url: string) => unknown;
|
|
48
|
+
/**
|
|
49
|
+
* ChatGPT only. OpenAI sends the browser back to `http://127.0.0.1:…`, which a
|
|
50
|
+
* web page cannot receive: ask the user to paste the address the tab ended on
|
|
51
|
+
* (it shows "can't connect", which is expected).
|
|
52
|
+
*/
|
|
53
|
+
askForRedirectUrl?: () => Promise<string | null | undefined> | string | null | undefined;
|
|
54
|
+
/** Cursor only: how often to check whether the user finished. Default 2 s. */
|
|
55
|
+
pollMs?: number;
|
|
56
|
+
signal?: AbortSignal;
|
|
57
|
+
};
|
|
58
|
+
declare function createConnectClient(options?: ConnectClientOptions): {
|
|
59
|
+
providers: () => Promise<{
|
|
60
|
+
providers: ConnectProviderRow[];
|
|
61
|
+
}>;
|
|
62
|
+
/** Run a provider's sign-in. Resolves when the server holds the sign-in. */
|
|
63
|
+
signIn: (provider: ConnectProviderId, signInOptions?: SignInOptions) => Promise<void>;
|
|
64
|
+
/** `revoked`: whether the provider confirmed the sign-out (null when there was nothing to revoke). */
|
|
65
|
+
signOut: (provider: ConnectProviderId) => Promise<{
|
|
66
|
+
ok: true;
|
|
67
|
+
revoked: boolean | null;
|
|
68
|
+
}>;
|
|
69
|
+
models: (provider: ConnectProviderId) => Promise<{
|
|
70
|
+
models: ConnectModel[];
|
|
71
|
+
}>;
|
|
72
|
+
/**
|
|
73
|
+
* Stream a reply. Throws `ConnectClientFailure` for sign-in, plan and
|
|
74
|
+
* provider errors, and for a reply cut off before it finished. Stopping
|
|
75
|
+
* early (`break`) closes the connection, so the server stops generating.
|
|
76
|
+
*/
|
|
77
|
+
respond(request: ConnectBrowserRequest): AsyncGenerator<ConnectEvent>;
|
|
78
|
+
};
|
|
79
|
+
type ConnectClient = ReturnType<typeof createConnectClient>;
|
|
80
|
+
|
|
81
|
+
export { ConnectBrowserRequest, type ConnectClient, type ConnectClientError, ConnectClientFailure, type ConnectClientOptions, ConnectEvent, ConnectModel, ConnectProviderId, ConnectProviderInfo, type ConnectProviderRow, ConnectSignInStatus, type SignInOptions, createConnectClient };
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { C as ConnectProviderInfo, a as ConnectSignInStatus, b as ConnectProviderId, c as ConnectModel, d as ConnectBrowserRequest, e as ConnectEvent } from '../types-DUGv-9QF.js';
|
|
2
|
+
export { f as ConnectMessage, g as ConnectResponseFormat } from '../types-DUGv-9QF.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `@daex-dev/sdk/connect/browser`: the page side of `createConnectHandler`.
|
|
6
|
+
* No secrets live here; the page only talks to the app's own server. Types
|
|
7
|
+
* come from the shared `types.ts` with `import type`, so this bundle has no
|
|
8
|
+
* runtime import at all.
|
|
9
|
+
*
|
|
10
|
+
* const connect = createConnectClient({ baseUrl: "/connect" });
|
|
11
|
+
* const { providers } = await connect.providers();
|
|
12
|
+
* await connect.signIn("cursor");
|
|
13
|
+
* await connect.signIn("codex", { askForRedirectUrl: () => prompt("Paste the address you ended on") });
|
|
14
|
+
* for await (const event of connect.respond({ provider: "codex", prompt: "Hi" })) …
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
type ConnectProviderRow = ConnectProviderInfo & {
|
|
18
|
+
status: ConnectSignInStatus;
|
|
19
|
+
};
|
|
20
|
+
type ConnectClientError = {
|
|
21
|
+
code: string;
|
|
22
|
+
message: string;
|
|
23
|
+
provider?: string;
|
|
24
|
+
retryable?: boolean;
|
|
25
|
+
manageUrl?: string;
|
|
26
|
+
};
|
|
27
|
+
declare class ConnectClientFailure extends Error {
|
|
28
|
+
readonly code: string;
|
|
29
|
+
readonly detail: ConnectClientError;
|
|
30
|
+
/** The HTTP status of the failed call, when it came from a response. */
|
|
31
|
+
readonly status?: number;
|
|
32
|
+
constructor(detail: ConnectClientError, status?: number);
|
|
33
|
+
}
|
|
34
|
+
type ConnectClientOptions = {
|
|
35
|
+
/** Where `createConnectHandler` is mounted. Default `/connect`. */
|
|
36
|
+
baseUrl?: string;
|
|
37
|
+
/** Extra headers for every call (e.g. the app's own auth). */
|
|
38
|
+
headers?: Record<string, string> | (() => Record<string, string>);
|
|
39
|
+
fetch?: typeof fetch;
|
|
40
|
+
};
|
|
41
|
+
type SignInOptions = {
|
|
42
|
+
/**
|
|
43
|
+
* Opens the provider's page. Default: a tab reserved with `window.open`
|
|
44
|
+
* before any network call (so a popup blocker allows it), then pointed at the
|
|
45
|
+
* page. Return the window when you open one, so it can be closed at the end.
|
|
46
|
+
*/
|
|
47
|
+
open?: (url: string) => unknown;
|
|
48
|
+
/**
|
|
49
|
+
* ChatGPT only. OpenAI sends the browser back to `http://127.0.0.1:…`, which a
|
|
50
|
+
* web page cannot receive: ask the user to paste the address the tab ended on
|
|
51
|
+
* (it shows "can't connect", which is expected).
|
|
52
|
+
*/
|
|
53
|
+
askForRedirectUrl?: () => Promise<string | null | undefined> | string | null | undefined;
|
|
54
|
+
/** Cursor only: how often to check whether the user finished. Default 2 s. */
|
|
55
|
+
pollMs?: number;
|
|
56
|
+
signal?: AbortSignal;
|
|
57
|
+
};
|
|
58
|
+
declare function createConnectClient(options?: ConnectClientOptions): {
|
|
59
|
+
providers: () => Promise<{
|
|
60
|
+
providers: ConnectProviderRow[];
|
|
61
|
+
}>;
|
|
62
|
+
/** Run a provider's sign-in. Resolves when the server holds the sign-in. */
|
|
63
|
+
signIn: (provider: ConnectProviderId, signInOptions?: SignInOptions) => Promise<void>;
|
|
64
|
+
/** `revoked`: whether the provider confirmed the sign-out (null when there was nothing to revoke). */
|
|
65
|
+
signOut: (provider: ConnectProviderId) => Promise<{
|
|
66
|
+
ok: true;
|
|
67
|
+
revoked: boolean | null;
|
|
68
|
+
}>;
|
|
69
|
+
models: (provider: ConnectProviderId) => Promise<{
|
|
70
|
+
models: ConnectModel[];
|
|
71
|
+
}>;
|
|
72
|
+
/**
|
|
73
|
+
* Stream a reply. Throws `ConnectClientFailure` for sign-in, plan and
|
|
74
|
+
* provider errors, and for a reply cut off before it finished. Stopping
|
|
75
|
+
* early (`break`) closes the connection, so the server stops generating.
|
|
76
|
+
*/
|
|
77
|
+
respond(request: ConnectBrowserRequest): AsyncGenerator<ConnectEvent>;
|
|
78
|
+
};
|
|
79
|
+
type ConnectClient = ReturnType<typeof createConnectClient>;
|
|
80
|
+
|
|
81
|
+
export { ConnectBrowserRequest, type ConnectClient, type ConnectClientError, ConnectClientFailure, type ConnectClientOptions, ConnectEvent, ConnectModel, ConnectProviderId, ConnectProviderInfo, type ConnectProviderRow, ConnectSignInStatus, type SignInOptions, createConnectClient };
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// src/connect/browser.ts
|
|
2
|
+
var ConnectClientFailure = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
detail;
|
|
5
|
+
/** The HTTP status of the failed call, when it came from a response. */
|
|
6
|
+
status;
|
|
7
|
+
constructor(detail, status) {
|
|
8
|
+
super(detail.message);
|
|
9
|
+
this.name = "ConnectClientFailure";
|
|
10
|
+
this.code = detail.code;
|
|
11
|
+
this.detail = detail;
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
function createConnectClient(options = {}) {
|
|
16
|
+
const base = (options.baseUrl ?? "/connect").replace(/\/$/, "");
|
|
17
|
+
const doFetch = options.fetch ?? fetch.bind(globalThis);
|
|
18
|
+
const headers = () => ({ ...typeof options.headers === "function" ? options.headers() : options.headers ?? {} });
|
|
19
|
+
const call = async (path, init = {}) => {
|
|
20
|
+
const response = await doFetch(`${base}${path}`, {
|
|
21
|
+
method: init.method ?? "GET",
|
|
22
|
+
headers: { ...headers(), Accept: "application/json", ...init.body !== void 0 ? { "Content-Type": "application/json" } : {} },
|
|
23
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
24
|
+
...init.signal ? { signal: init.signal } : {},
|
|
25
|
+
credentials: "include"
|
|
26
|
+
});
|
|
27
|
+
const value = await response.json().catch(() => ({}));
|
|
28
|
+
if (!response.ok) {
|
|
29
|
+
const error = value.error ?? { code: "http_error", message: `HTTP ${response.status}` };
|
|
30
|
+
throw new ConnectClientFailure(error, response.status);
|
|
31
|
+
}
|
|
32
|
+
return value;
|
|
33
|
+
};
|
|
34
|
+
const windowOpen = globalThis.open;
|
|
35
|
+
const reservePage = (signInOptions) => {
|
|
36
|
+
const reserved = signInOptions?.open ? null : windowOpen?.("about:blank", "_blank") ?? null;
|
|
37
|
+
return {
|
|
38
|
+
show(url) {
|
|
39
|
+
if (signInOptions?.open) return signInOptions.open(url);
|
|
40
|
+
if (reserved?.location) {
|
|
41
|
+
reserved.opener = null;
|
|
42
|
+
reserved.location.href = url;
|
|
43
|
+
return reserved;
|
|
44
|
+
}
|
|
45
|
+
return windowOpen?.(url, "_blank", "noopener");
|
|
46
|
+
},
|
|
47
|
+
discard() {
|
|
48
|
+
closePage(reserved);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
const closePage = (handle) => {
|
|
53
|
+
try {
|
|
54
|
+
handle?.close?.();
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
const cancelledFailure = (provider) => new ConnectClientFailure({ code: "sign_in_cancelled", message: "The sign-in was cancelled.", provider });
|
|
59
|
+
const signInWithCodex = async (signInOptions) => {
|
|
60
|
+
if (!signInOptions?.askForRedirectUrl) {
|
|
61
|
+
throw new ConnectClientFailure({ code: "invalid_request", message: "ChatGPT sign-in on the web needs askForRedirectUrl." });
|
|
62
|
+
}
|
|
63
|
+
const reserved = reservePage(signInOptions);
|
|
64
|
+
let started;
|
|
65
|
+
try {
|
|
66
|
+
started = await call("/codex/start", { method: "POST", body: {} });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
reserved.discard();
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
const page = reserved.show(started.url);
|
|
72
|
+
const callbackUrl = await signInOptions.askForRedirectUrl();
|
|
73
|
+
closePage(page);
|
|
74
|
+
if (!callbackUrl) throw cancelledFailure("codex");
|
|
75
|
+
await call("/codex/complete", { method: "POST", body: { signInId: started.signInId, callbackUrl } });
|
|
76
|
+
};
|
|
77
|
+
const signInWithCursor = async (signInOptions) => {
|
|
78
|
+
const reserved = reservePage(signInOptions);
|
|
79
|
+
let started;
|
|
80
|
+
try {
|
|
81
|
+
started = await call("/cursor/start", { method: "POST", body: {} });
|
|
82
|
+
} catch (error) {
|
|
83
|
+
reserved.discard();
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
const page = reserved.show(started.url);
|
|
87
|
+
const pollMs = signInOptions?.pollMs ?? 2e3;
|
|
88
|
+
let failedPolls = 0;
|
|
89
|
+
try {
|
|
90
|
+
while (true) {
|
|
91
|
+
if (signInOptions?.signal?.aborted) throw cancelledFailure("cursor");
|
|
92
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
93
|
+
let status;
|
|
94
|
+
try {
|
|
95
|
+
status = await call(`/cursor/status?signInId=${encodeURIComponent(started.signInId)}`);
|
|
96
|
+
failedPolls = 0;
|
|
97
|
+
} catch (error) {
|
|
98
|
+
const transient = !(error instanceof ConnectClientFailure) || (error.status ?? 0) >= 500;
|
|
99
|
+
if (!transient || ++failedPolls > 5) throw error;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (status.state === "done") return;
|
|
103
|
+
if (status.state === "failed") {
|
|
104
|
+
throw new ConnectClientFailure(status.error ?? { code: "sign_in_failed", message: "Cursor's sign-in did not finish.", provider: "cursor" });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
} finally {
|
|
108
|
+
closePage(page);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
const signInFlows = {
|
|
112
|
+
codex: signInWithCodex,
|
|
113
|
+
cursor: signInWithCursor
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
providers: () => call("/providers"),
|
|
117
|
+
/** Run a provider's sign-in. Resolves when the server holds the sign-in. */
|
|
118
|
+
signIn: (provider, signInOptions) => signInFlows[provider](signInOptions),
|
|
119
|
+
/** `revoked`: whether the provider confirmed the sign-out (null when there was nothing to revoke). */
|
|
120
|
+
signOut: (provider) => call(`/${provider}/sign-out`, { method: "POST", body: {} }),
|
|
121
|
+
models: (provider) => call(`/models?provider=${provider}`),
|
|
122
|
+
/**
|
|
123
|
+
* Stream a reply. Throws `ConnectClientFailure` for sign-in, plan and
|
|
124
|
+
* provider errors, and for a reply cut off before it finished. Stopping
|
|
125
|
+
* early (`break`) closes the connection, so the server stops generating.
|
|
126
|
+
*/
|
|
127
|
+
async *respond(request) {
|
|
128
|
+
const { signal, ...payload } = request;
|
|
129
|
+
const response = await doFetch(`${base}/respond`, {
|
|
130
|
+
method: "POST",
|
|
131
|
+
headers: { ...headers(), "Content-Type": "application/json", Accept: "text/event-stream" },
|
|
132
|
+
body: JSON.stringify(payload),
|
|
133
|
+
credentials: "include",
|
|
134
|
+
...signal ? { signal } : {}
|
|
135
|
+
});
|
|
136
|
+
if (!response.ok || !response.body) {
|
|
137
|
+
const value = await response.json().catch(() => ({}));
|
|
138
|
+
throw new ConnectClientFailure(value.error ?? { code: "http_error", message: `HTTP ${response.status}` });
|
|
139
|
+
}
|
|
140
|
+
const reader = response.body.getReader();
|
|
141
|
+
const decoder = new TextDecoder();
|
|
142
|
+
let buffer = "";
|
|
143
|
+
let finished = false;
|
|
144
|
+
try {
|
|
145
|
+
while (!finished) {
|
|
146
|
+
const { value, done } = await reader.read();
|
|
147
|
+
if (done) {
|
|
148
|
+
throw new ConnectClientFailure({ code: "provider_error", message: "The reply was cut off before it finished.", retryable: true });
|
|
149
|
+
}
|
|
150
|
+
buffer += decoder.decode(value, { stream: true });
|
|
151
|
+
let boundary = buffer.indexOf("\n\n");
|
|
152
|
+
while (boundary !== -1 && !finished) {
|
|
153
|
+
const block = buffer.slice(0, boundary);
|
|
154
|
+
buffer = buffer.slice(boundary + 2);
|
|
155
|
+
const event = /^event: (.+)$/m.exec(block)?.[1];
|
|
156
|
+
const data = /^data: (.+)$/m.exec(block)?.[1];
|
|
157
|
+
const parsed = data ? JSON.parse(data) : {};
|
|
158
|
+
if (event === "text") yield { type: "text", delta: String(parsed.delta ?? "") };
|
|
159
|
+
else if (event === "raw") yield { type: "raw", provider: parsed.provider, event: parsed.event };
|
|
160
|
+
else if (event === "error") throw new ConnectClientFailure(parsed);
|
|
161
|
+
else if (event === "done") {
|
|
162
|
+
finished = true;
|
|
163
|
+
yield {
|
|
164
|
+
type: "done",
|
|
165
|
+
text: String(parsed.text ?? ""),
|
|
166
|
+
...typeof parsed.model === "string" ? { model: parsed.model } : {},
|
|
167
|
+
...parsed.usage === void 0 ? {} : { usage: parsed.usage },
|
|
168
|
+
...parsed.response === void 0 ? {} : { response: parsed.response }
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
boundary = buffer.indexOf("\n\n");
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
} finally {
|
|
175
|
+
await reader.cancel().catch(() => void 0);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
export {
|
|
181
|
+
ConnectClientFailure,
|
|
182
|
+
createConnectClient
|
|
183
|
+
};
|