@cortexkit/pi-openai-auth 0.1.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 +37 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +167 -0
- package/dist/raw-ws-node.d.ts +27 -0
- package/dist/raw-ws-node.js +328 -0
- package/package.json +43 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ex Machina
|
|
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,37 @@
|
|
|
1
|
+
# @cortexkit/pi-openai-auth
|
|
2
|
+
|
|
3
|
+
Pi package for CortexKit OpenAI Codex OAuth support. It overrides Pi's built-in `openai-codex` provider with a CortexKit provider extension backed by Pi's OpenAI Codex Responses transport and OAuth primitives.
|
|
4
|
+
|
|
5
|
+
The Pi provider catalog includes `gpt-5.5`, `gpt-5.4`, `gpt-5.4-mini`, and `gpt-5.3-codex-spark`.
|
|
6
|
+
|
|
7
|
+
This package is part of the CortexKit OpenAI Auth monorepo, which supports both OpenCode (`@cortexkit/opencode-openai-auth`) and Pi (`@cortexkit/pi-openai-auth`).
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
Install with Pi's package manager:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pi install npm:@cortexkit/pi-openai-auth@0.1.0
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
For an unpinned install:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pi install npm:@cortexkit/pi-openai-auth
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
To try it for one run without changing Pi settings:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pi -e npm:@cortexkit/pi-openai-auth
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Restart Pi after installing, then authenticate through Pi's normal login flow:
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
/login openai-codex
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## License
|
|
36
|
+
|
|
37
|
+
MIT
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { createAssistantMessageEventStream, streamSimpleOpenAICodexResponses, } from '@earendil-works/pi-ai';
|
|
2
|
+
import { loginOpenAICodex, refreshOpenAICodexToken, } from '@earendil-works/pi-ai/oauth';
|
|
3
|
+
import { RawWebSocket } from "./raw-ws-node.js";
|
|
4
|
+
const BASE_URL = 'https://chatgpt.com/backend-api';
|
|
5
|
+
class PiRawCodexWebSocket extends RawWebSocket {
|
|
6
|
+
constructor(url, options) {
|
|
7
|
+
const headers = options && typeof options === 'object' && !Array.isArray(options)
|
|
8
|
+
? (options.headers ?? {})
|
|
9
|
+
: {};
|
|
10
|
+
super(String(url), headers);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
let rawWebSocketInstallCount = 0;
|
|
14
|
+
let originalWebSocket;
|
|
15
|
+
function installRawCodexWebSocket() {
|
|
16
|
+
const global = globalThis;
|
|
17
|
+
if (rawWebSocketInstallCount === 0) {
|
|
18
|
+
originalWebSocket = global.WebSocket;
|
|
19
|
+
global.WebSocket = PiRawCodexWebSocket;
|
|
20
|
+
}
|
|
21
|
+
rawWebSocketInstallCount++;
|
|
22
|
+
return () => {
|
|
23
|
+
rawWebSocketInstallCount = Math.max(0, rawWebSocketInstallCount - 1);
|
|
24
|
+
if (rawWebSocketInstallCount === 0) {
|
|
25
|
+
if (global.WebSocket === PiRawCodexWebSocket) {
|
|
26
|
+
global.WebSocket = originalWebSocket;
|
|
27
|
+
}
|
|
28
|
+
originalWebSocket = undefined;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const OPENAI_CODEX_MODELS = [
|
|
33
|
+
{
|
|
34
|
+
id: 'gpt-5.5',
|
|
35
|
+
name: 'GPT-5.5',
|
|
36
|
+
api: 'openai-codex-responses',
|
|
37
|
+
provider: 'openai-codex',
|
|
38
|
+
baseUrl: BASE_URL,
|
|
39
|
+
reasoning: true,
|
|
40
|
+
thinkingLevelMap: { xhigh: 'xhigh', minimal: 'low' },
|
|
41
|
+
input: ['text', 'image'],
|
|
42
|
+
cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0 },
|
|
43
|
+
contextWindow: 272_000,
|
|
44
|
+
maxTokens: 128_000,
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
id: 'gpt-5.4',
|
|
48
|
+
name: 'GPT-5.4',
|
|
49
|
+
api: 'openai-codex-responses',
|
|
50
|
+
provider: 'openai-codex',
|
|
51
|
+
baseUrl: BASE_URL,
|
|
52
|
+
reasoning: true,
|
|
53
|
+
thinkingLevelMap: { xhigh: 'xhigh', minimal: 'low' },
|
|
54
|
+
input: ['text', 'image'],
|
|
55
|
+
cost: { input: 2.5, output: 15, cacheRead: 0.25, cacheWrite: 0 },
|
|
56
|
+
contextWindow: 272_000,
|
|
57
|
+
maxTokens: 128_000,
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: 'gpt-5.4-mini',
|
|
61
|
+
name: 'GPT-5.4 mini',
|
|
62
|
+
api: 'openai-codex-responses',
|
|
63
|
+
provider: 'openai-codex',
|
|
64
|
+
baseUrl: BASE_URL,
|
|
65
|
+
reasoning: true,
|
|
66
|
+
thinkingLevelMap: { xhigh: 'xhigh', minimal: 'low' },
|
|
67
|
+
input: ['text', 'image'],
|
|
68
|
+
cost: { input: 0.75, output: 4.5, cacheRead: 0.075, cacheWrite: 0 },
|
|
69
|
+
contextWindow: 272_000,
|
|
70
|
+
maxTokens: 128_000,
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
id: 'gpt-5.3-codex-spark',
|
|
74
|
+
name: 'GPT-5.3 Codex Spark',
|
|
75
|
+
api: 'openai-codex-responses',
|
|
76
|
+
provider: 'openai-codex',
|
|
77
|
+
baseUrl: BASE_URL,
|
|
78
|
+
reasoning: true,
|
|
79
|
+
thinkingLevelMap: { xhigh: 'xhigh', minimal: 'low' },
|
|
80
|
+
input: ['text'],
|
|
81
|
+
cost: { input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 },
|
|
82
|
+
contextWindow: 128_000,
|
|
83
|
+
maxTokens: 128_000,
|
|
84
|
+
},
|
|
85
|
+
];
|
|
86
|
+
async function loginOpenAI(callbacks) {
|
|
87
|
+
return loginOpenAICodex({
|
|
88
|
+
onAuth: callbacks.onAuth,
|
|
89
|
+
onPrompt: callbacks.onPrompt,
|
|
90
|
+
onProgress: callbacks.onProgress,
|
|
91
|
+
onManualCodeInput: callbacks.onManualCodeInput,
|
|
92
|
+
originator: 'pi',
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
async function refreshOpenAI(credentials) {
|
|
96
|
+
return refreshOpenAICodexToken(credentials.refresh);
|
|
97
|
+
}
|
|
98
|
+
function streamOpenAI(model, context, options) {
|
|
99
|
+
const outer = createAssistantMessageEventStream();
|
|
100
|
+
const restoreWebSocket = installRawCodexWebSocket();
|
|
101
|
+
let inner;
|
|
102
|
+
try {
|
|
103
|
+
inner = streamSimpleOpenAICodexResponses(model, context, options);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
restoreWebSocket();
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
void (async () => {
|
|
110
|
+
try {
|
|
111
|
+
for await (const event of inner) {
|
|
112
|
+
outer.push(event);
|
|
113
|
+
}
|
|
114
|
+
outer.end();
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
outer.push({
|
|
118
|
+
type: 'error',
|
|
119
|
+
reason: 'error',
|
|
120
|
+
error: {
|
|
121
|
+
role: 'assistant',
|
|
122
|
+
content: [],
|
|
123
|
+
api: model.api,
|
|
124
|
+
provider: model.provider,
|
|
125
|
+
model: model.id,
|
|
126
|
+
usage: {
|
|
127
|
+
input: 0,
|
|
128
|
+
output: 0,
|
|
129
|
+
cacheRead: 0,
|
|
130
|
+
cacheWrite: 0,
|
|
131
|
+
totalTokens: 0,
|
|
132
|
+
cost: {
|
|
133
|
+
input: 0,
|
|
134
|
+
output: 0,
|
|
135
|
+
cacheRead: 0,
|
|
136
|
+
cacheWrite: 0,
|
|
137
|
+
total: 0,
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
stopReason: 'error',
|
|
141
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
142
|
+
timestamp: Date.now(),
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
outer.end();
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
restoreWebSocket();
|
|
149
|
+
}
|
|
150
|
+
})();
|
|
151
|
+
return outer;
|
|
152
|
+
}
|
|
153
|
+
export default function cortexKitPiOpenAIAuth(pi) {
|
|
154
|
+
pi.registerProvider('openai-codex', {
|
|
155
|
+
name: 'OpenAI Codex (CortexKit OAuth)',
|
|
156
|
+
baseUrl: BASE_URL,
|
|
157
|
+
api: 'openai-codex-responses',
|
|
158
|
+
models: OPENAI_CODEX_MODELS,
|
|
159
|
+
oauth: {
|
|
160
|
+
name: 'ChatGPT Plus/Pro (CortexKit)',
|
|
161
|
+
login: loginOpenAI,
|
|
162
|
+
refreshToken: refreshOpenAI,
|
|
163
|
+
getApiKey: (credentials) => credentials.access,
|
|
164
|
+
},
|
|
165
|
+
streamSimple: streamOpenAI,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
type Listener = (event: unknown) => void;
|
|
2
|
+
export declare class RawWebSocket {
|
|
3
|
+
url: string;
|
|
4
|
+
readyState: number;
|
|
5
|
+
private socket;
|
|
6
|
+
private listeners;
|
|
7
|
+
private rxBuffer;
|
|
8
|
+
private handshakeDone;
|
|
9
|
+
private expectedAccept;
|
|
10
|
+
private fragOpcode;
|
|
11
|
+
private fragChunks;
|
|
12
|
+
constructor(url: string, headers: Record<string, string>);
|
|
13
|
+
addEventListener(type: string, fn: Listener, _opts?: {
|
|
14
|
+
once?: boolean;
|
|
15
|
+
}): void;
|
|
16
|
+
removeEventListener(type: string, fn: Listener): void;
|
|
17
|
+
private emit;
|
|
18
|
+
private connect;
|
|
19
|
+
private onData;
|
|
20
|
+
private drainFrames;
|
|
21
|
+
private handleFrame;
|
|
22
|
+
send(data: string): void;
|
|
23
|
+
private writeFrame;
|
|
24
|
+
close(): void;
|
|
25
|
+
private log;
|
|
26
|
+
}
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
// Hand-rolled WebSocket client over raw TCP/TLS sockets.
|
|
2
|
+
//
|
|
3
|
+
// Purpose: native WebSocket implementations fix the HTTP upgrade header ORDER and
|
|
4
|
+
// own the RFC 6455 frame codec, so they cannot speak the wire the way Codex's
|
|
5
|
+
// Rust tokio-tungstenite client does. This client writes the upgrade bytes and
|
|
6
|
+
// frames by hand, giving full control of header order + framing, which surfaces
|
|
7
|
+
// Codex-style incremental streaming that native WebSocket implementations can
|
|
8
|
+
// suppress.
|
|
9
|
+
//
|
|
10
|
+
// Used by the Pi package for Codex only. permessage-deflate is intentionally NOT
|
|
11
|
+
// negotiated; plain text frames keep the codec simple.
|
|
12
|
+
//
|
|
13
|
+
// Implements only the subset of the WebSocket interface the plugin consumes:
|
|
14
|
+
// addEventListener/removeEventListener for "open"|"message"|"error"|"close",
|
|
15
|
+
// send(string), close(), and a `url` field. Text frames only on receive.
|
|
16
|
+
import { connect as netConnect } from 'node:net';
|
|
17
|
+
import { connect as tlsConnect } from 'node:tls';
|
|
18
|
+
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
19
|
+
// Codex (tokio-tungstenite) application-header order. WS control headers
|
|
20
|
+
// (host/connection/upgrade/sec-websocket-version/sec-websocket-key) are written
|
|
21
|
+
// first by us in Codex's exact order; Sec-WebSocket-Extensions would go last but
|
|
22
|
+
// we omit it (no permessage-deflate).
|
|
23
|
+
const CODEX_APP_HEADER_ORDER = [
|
|
24
|
+
'chatgpt-account-id',
|
|
25
|
+
'authorization',
|
|
26
|
+
'user-agent',
|
|
27
|
+
'originator',
|
|
28
|
+
'openai-beta',
|
|
29
|
+
'version',
|
|
30
|
+
'x-codex-beta-features',
|
|
31
|
+
'x-codex-turn-metadata',
|
|
32
|
+
'x-client-request-id',
|
|
33
|
+
'session-id',
|
|
34
|
+
'thread-id',
|
|
35
|
+
'x-codex-window-id',
|
|
36
|
+
];
|
|
37
|
+
export class RawWebSocket {
|
|
38
|
+
url;
|
|
39
|
+
readyState = 0; // CONNECTING
|
|
40
|
+
socket;
|
|
41
|
+
listeners = {
|
|
42
|
+
open: new Set(),
|
|
43
|
+
message: new Set(),
|
|
44
|
+
error: new Set(),
|
|
45
|
+
close: new Set(),
|
|
46
|
+
};
|
|
47
|
+
rxBuffer = new Uint8Array(0);
|
|
48
|
+
handshakeDone = false;
|
|
49
|
+
expectedAccept = '';
|
|
50
|
+
// message reassembly across fragmented frames
|
|
51
|
+
fragOpcode = 0;
|
|
52
|
+
fragChunks = [];
|
|
53
|
+
constructor(url, headers) {
|
|
54
|
+
this.url = url;
|
|
55
|
+
void this.connect(url, headers);
|
|
56
|
+
}
|
|
57
|
+
addEventListener(type, fn, _opts) {
|
|
58
|
+
this.listeners[type]?.add(fn);
|
|
59
|
+
}
|
|
60
|
+
removeEventListener(type, fn) {
|
|
61
|
+
this.listeners[type]?.delete(fn);
|
|
62
|
+
}
|
|
63
|
+
emit(type, event) {
|
|
64
|
+
for (const fn of [...(this.listeners[type] ?? [])]) {
|
|
65
|
+
try {
|
|
66
|
+
fn(event);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// listener errors must not crash the socket loop
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async connect(url, headers) {
|
|
74
|
+
const u = new URL(url.replace(/^ws:/, 'http:').replace(/^wss:/, 'https:'));
|
|
75
|
+
const host = u.hostname;
|
|
76
|
+
const port = u.port ? Number(u.port) : u.protocol === 'https:' ? 443 : 80;
|
|
77
|
+
const path = `${u.pathname}${u.search}`;
|
|
78
|
+
const keyBytes = crypto.getRandomValues(new Uint8Array(16));
|
|
79
|
+
const key = Buffer.from(keyBytes).toString('base64');
|
|
80
|
+
const acceptDigest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(key + WS_GUID));
|
|
81
|
+
this.expectedAccept = Buffer.from(new Uint8Array(acceptDigest)).toString('base64');
|
|
82
|
+
const lower = {};
|
|
83
|
+
for (const [k, v] of Object.entries(headers))
|
|
84
|
+
lower[k.toLowerCase()] = v;
|
|
85
|
+
// Build the upgrade in Codex's exact byte order.
|
|
86
|
+
const lines = [
|
|
87
|
+
`GET ${path} HTTP/1.1`,
|
|
88
|
+
`Host: ${host}`,
|
|
89
|
+
`Connection: Upgrade`,
|
|
90
|
+
`Upgrade: websocket`,
|
|
91
|
+
`Sec-WebSocket-Version: 13`,
|
|
92
|
+
`Sec-WebSocket-Key: ${key}`,
|
|
93
|
+
];
|
|
94
|
+
for (const name of CODEX_APP_HEADER_ORDER) {
|
|
95
|
+
if (lower[name] !== undefined)
|
|
96
|
+
lines.push(`${canonical(name)}: ${lower[name]}`);
|
|
97
|
+
}
|
|
98
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
99
|
+
if (!CODEX_APP_HEADER_ORDER.includes(k.toLowerCase()) &&
|
|
100
|
+
k.toLowerCase() !== 'content-length') {
|
|
101
|
+
lines.push(`${k}: ${v}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const request = `${lines.join('\r\n')}\r\n\r\n`;
|
|
105
|
+
try {
|
|
106
|
+
void this.log('connect_start', {
|
|
107
|
+
host,
|
|
108
|
+
port,
|
|
109
|
+
tls: u.protocol === 'https:',
|
|
110
|
+
});
|
|
111
|
+
const onOpen = () => {
|
|
112
|
+
this.socket?.write(request);
|
|
113
|
+
};
|
|
114
|
+
const socket = u.protocol === 'https:'
|
|
115
|
+
? tlsConnect({ host, port, servername: host }, onOpen)
|
|
116
|
+
: netConnect({ host, port }, onOpen);
|
|
117
|
+
this.socket = socket;
|
|
118
|
+
socket.on('data', (data) => {
|
|
119
|
+
this.onData(typeof data === 'string' ? Buffer.from(data, 'binary') : data);
|
|
120
|
+
});
|
|
121
|
+
socket.on('error', (e) => {
|
|
122
|
+
this.readyState = 3;
|
|
123
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
124
|
+
void this.log('socket_error', { message });
|
|
125
|
+
this.emit('error', { message });
|
|
126
|
+
});
|
|
127
|
+
socket.on('close', (hadError) => {
|
|
128
|
+
this.readyState = 3;
|
|
129
|
+
void this.log('socket_close', { hadError });
|
|
130
|
+
this.emit('close', { code: 1006, reason: 'socket closed' });
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
catch (e) {
|
|
134
|
+
this.readyState = 3;
|
|
135
|
+
void this.log('connect_exception', {
|
|
136
|
+
message: e instanceof Error ? e.message : String(e),
|
|
137
|
+
});
|
|
138
|
+
this.emit('error', {
|
|
139
|
+
message: e instanceof Error ? e.message : String(e),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
onData(d) {
|
|
144
|
+
this.rxBuffer = concat(this.rxBuffer, d);
|
|
145
|
+
if (!this.handshakeDone) {
|
|
146
|
+
const text = Buffer.from(this.rxBuffer).toString('latin1');
|
|
147
|
+
const idx = text.indexOf('\r\n\r\n');
|
|
148
|
+
if (idx === -1)
|
|
149
|
+
return;
|
|
150
|
+
const headerText = text.slice(0, idx);
|
|
151
|
+
const statusLine = headerText.split('\r\n')[0] ?? '';
|
|
152
|
+
const acceptMatch = headerText.match(/sec-websocket-accept:\s*(\S+)/i);
|
|
153
|
+
if (!statusLine.includes(' 101')) {
|
|
154
|
+
this.readyState = 3;
|
|
155
|
+
this.socket?.destroy?.();
|
|
156
|
+
void this.log('upgrade_failed', { statusLine });
|
|
157
|
+
this.emit('error', { message: `WS upgrade failed: ${statusLine}` });
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (!acceptMatch || acceptMatch[1] !== this.expectedAccept) {
|
|
161
|
+
this.readyState = 3;
|
|
162
|
+
this.socket?.destroy?.();
|
|
163
|
+
void this.log('accept_mismatch', { statusLine });
|
|
164
|
+
this.emit('error', {
|
|
165
|
+
message: 'WS upgrade Sec-WebSocket-Accept mismatch',
|
|
166
|
+
});
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
this.handshakeDone = true;
|
|
170
|
+
this.readyState = 1;
|
|
171
|
+
this.rxBuffer = this.rxBuffer.slice(idx + 4);
|
|
172
|
+
void this.log('open', { statusLine });
|
|
173
|
+
this.emit('open', {});
|
|
174
|
+
}
|
|
175
|
+
this.drainFrames();
|
|
176
|
+
}
|
|
177
|
+
drainFrames() {
|
|
178
|
+
// RFC 6455 frame parsing for server->client (never masked).
|
|
179
|
+
for (;;) {
|
|
180
|
+
const buf = this.rxBuffer;
|
|
181
|
+
if (buf.length < 2)
|
|
182
|
+
return;
|
|
183
|
+
const b0 = buf[0];
|
|
184
|
+
const b1 = buf[1];
|
|
185
|
+
const fin = (b0 & 0x80) !== 0;
|
|
186
|
+
const opcode = b0 & 0x0f;
|
|
187
|
+
const masked = (b1 & 0x80) !== 0;
|
|
188
|
+
let len = b1 & 0x7f;
|
|
189
|
+
let offset = 2;
|
|
190
|
+
if (len === 126) {
|
|
191
|
+
if (buf.length < 4)
|
|
192
|
+
return;
|
|
193
|
+
len = (buf[2] << 8) | buf[3];
|
|
194
|
+
offset = 4;
|
|
195
|
+
}
|
|
196
|
+
else if (len === 127) {
|
|
197
|
+
if (buf.length < 10)
|
|
198
|
+
return;
|
|
199
|
+
len = 0;
|
|
200
|
+
for (let i = 0; i < 8; i++)
|
|
201
|
+
len = len * 256 + buf[2 + i];
|
|
202
|
+
offset = 10;
|
|
203
|
+
}
|
|
204
|
+
if (masked)
|
|
205
|
+
offset += 4; // shouldn't happen server->client
|
|
206
|
+
if (buf.length < offset + len)
|
|
207
|
+
return;
|
|
208
|
+
const payload = buf.slice(offset, offset + len);
|
|
209
|
+
this.rxBuffer = buf.slice(offset + len);
|
|
210
|
+
this.handleFrame(fin, opcode, payload);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
handleFrame(fin, opcode, payload) {
|
|
214
|
+
if (opcode === 0x9) {
|
|
215
|
+
// ping -> pong (echo payload), masked
|
|
216
|
+
this.writeFrame(0xa, payload);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (opcode === 0xa)
|
|
220
|
+
return; // pong
|
|
221
|
+
if (opcode === 0x8) {
|
|
222
|
+
// close
|
|
223
|
+
let code = 1005;
|
|
224
|
+
let reason = '';
|
|
225
|
+
if (payload.length >= 2) {
|
|
226
|
+
code = (payload[0] << 8) | payload[1];
|
|
227
|
+
reason = Buffer.from(payload.slice(2)).toString('utf-8');
|
|
228
|
+
}
|
|
229
|
+
this.readyState = 3;
|
|
230
|
+
try {
|
|
231
|
+
this.socket?.end();
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
/* ignore */
|
|
235
|
+
}
|
|
236
|
+
this.emit('close', { code, reason });
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
// data frame: 0x1 text, 0x2 binary, 0x0 continuation
|
|
240
|
+
if (opcode === 0x1 || opcode === 0x2) {
|
|
241
|
+
this.fragOpcode = opcode;
|
|
242
|
+
this.fragChunks = [payload];
|
|
243
|
+
}
|
|
244
|
+
else if (opcode === 0x0) {
|
|
245
|
+
this.fragChunks.push(payload);
|
|
246
|
+
}
|
|
247
|
+
if (!fin)
|
|
248
|
+
return;
|
|
249
|
+
const full = concatAll(this.fragChunks);
|
|
250
|
+
this.fragChunks = [];
|
|
251
|
+
if (this.fragOpcode === 0x1) {
|
|
252
|
+
const text = Buffer.from(full).toString('utf-8');
|
|
253
|
+
this.emit('message', { data: text });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
send(data) {
|
|
257
|
+
if (this.readyState !== 1)
|
|
258
|
+
return;
|
|
259
|
+
this.writeFrame(0x1, new TextEncoder().encode(data));
|
|
260
|
+
}
|
|
261
|
+
writeFrame(opcode, payload) {
|
|
262
|
+
const len = payload.length;
|
|
263
|
+
const mask = crypto.getRandomValues(new Uint8Array(4));
|
|
264
|
+
let header;
|
|
265
|
+
if (len < 126)
|
|
266
|
+
header = [0x80 | opcode, 0x80 | len];
|
|
267
|
+
else if (len < 65536)
|
|
268
|
+
header = [0x80 | opcode, 0x80 | 126, (len >> 8) & 0xff, len & 0xff];
|
|
269
|
+
else {
|
|
270
|
+
header = [0x80 | opcode, 0x80 | 127];
|
|
271
|
+
for (let i = 7; i >= 0; i--)
|
|
272
|
+
header.push((len / 2 ** (8 * i)) & 0xff);
|
|
273
|
+
}
|
|
274
|
+
const masked = new Uint8Array(len);
|
|
275
|
+
for (let i = 0; i < len; i++)
|
|
276
|
+
masked[i] = payload[i] ^ mask[i % 4];
|
|
277
|
+
const frame = new Uint8Array(header.length + 4 + len);
|
|
278
|
+
frame.set(header, 0);
|
|
279
|
+
frame.set(mask, header.length);
|
|
280
|
+
frame.set(masked, header.length + 4);
|
|
281
|
+
try {
|
|
282
|
+
this.socket?.write(frame);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
/* socket gone */
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
close() {
|
|
289
|
+
if (this.readyState === 3)
|
|
290
|
+
return;
|
|
291
|
+
this.readyState = 2;
|
|
292
|
+
try {
|
|
293
|
+
this.writeFrame(0x8, new Uint8Array([0x03, 0xe8])); // 1000
|
|
294
|
+
this.socket?.end();
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
/* ignore */
|
|
298
|
+
}
|
|
299
|
+
this.readyState = 3;
|
|
300
|
+
}
|
|
301
|
+
log(event, data) {
|
|
302
|
+
void event;
|
|
303
|
+
void data;
|
|
304
|
+
return Promise.resolve();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
function canonical(lower) {
|
|
308
|
+
// Match Codex's header casing for the few that aren't all-lowercase on the wire.
|
|
309
|
+
return lower;
|
|
310
|
+
}
|
|
311
|
+
function concat(a, b) {
|
|
312
|
+
const out = new Uint8Array(a.length + b.length);
|
|
313
|
+
out.set(a, 0);
|
|
314
|
+
out.set(b, a.length);
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
function concatAll(parts) {
|
|
318
|
+
let total = 0;
|
|
319
|
+
for (const p of parts)
|
|
320
|
+
total += p.length;
|
|
321
|
+
const out = new Uint8Array(total);
|
|
322
|
+
let off = 0;
|
|
323
|
+
for (const p of parts) {
|
|
324
|
+
out.set(p, off);
|
|
325
|
+
off += p.length;
|
|
326
|
+
}
|
|
327
|
+
return out;
|
|
328
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cortexkit/pi-openai-auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/cortexkit/openai-auth.git",
|
|
9
|
+
"directory": "packages/pi"
|
|
10
|
+
},
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"import": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"keywords": [
|
|
25
|
+
"pi-package"
|
|
26
|
+
],
|
|
27
|
+
"pi": {
|
|
28
|
+
"extensions": [
|
|
29
|
+
"./dist/index.js"
|
|
30
|
+
]
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
34
|
+
"typecheck": "tsc",
|
|
35
|
+
"types": "tsc",
|
|
36
|
+
"prepublishOnly": "bun run build"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@earendil-works/pi-ai": "*",
|
|
40
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
41
|
+
"@earendil-works/pi-tui": "*"
|
|
42
|
+
}
|
|
43
|
+
}
|