pi-codex-accounts 0.0.0 → 0.1.1

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -2
  3. package/package.json +33 -2
  4. package/src/index.ts +143 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tiago Peixoto
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 CHANGED
@@ -1,4 +1,59 @@
1
1
  # pi-codex-accounts
2
2
 
3
- This version only reserves the package name.
4
- Install 0.1.0 or later: https://github.com/tiago-peixoto/pi-codex-accounts
3
+ Use more than one ChatGPT (Codex) subscription in [pi](https://pi.dev), each with its own login and its own entries in `/model`.
4
+
5
+ pi's built-in OpenAI Codex provider holds one login.
6
+ This extension adds providers that work exactly like it, so a second (or third) ChatGPT account can stay signed in next to the first:
7
+
8
+ ```text
9
+ gpt-5.6-sol [openai-codex]
10
+ gpt-5.6-sol [openai-codex-2]
11
+ ```
12
+
13
+ It never switches accounts on its own.
14
+ You choose the account whenever you choose a model.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ pi install npm:pi-codex-accounts
20
+ ```
21
+
22
+ Then run `/login`, choose **Sign in with an account**, pick **OpenAI Codex (2)**, and sign in with your other ChatGPT account.
23
+ Your browser may reuse the ChatGPT account it is already signed into, so use a private window or the device-code option.
24
+
25
+ ## More accounts or other names
26
+
27
+ Create `~/.pi/agent/codex-accounts.json` and restart pi:
28
+
29
+ ```json
30
+ { "accounts": ["Work", "Personal"] }
31
+ ```
32
+
33
+ Each label becomes a provider: `Work` shows up as **OpenAI Codex (Work)** with the id `openai-codex-work`.
34
+ Without the file you get one extra account, `openai-codex-2`.
35
+ An empty list adds none.
36
+ pi stores logins under the provider id, so renaming a label means signing in again.
37
+
38
+ ## How it works
39
+
40
+ Each account reuses pi's own Codex login flow, model list, and request code, so it behaves like the built-in provider and picks up new Codex models when pi updates.
41
+ pi keeps each login in `~/.pi/agent/auth.json` under the account's provider id, and requests use that login's token.
42
+
43
+ Two details keep accounts apart:
44
+
45
+ - pi-ai's Codex code keeps Responses tool-call ids intact only for the provider id `openai-codex`, so requests go out under that id and replies are relabelled with the account's id.
46
+ - Replies from a different Codex account in the same session count as another provider's, so their encrypted reasoning is dropped instead of being sent to this account.
47
+
48
+ The extension never copies tokens into environment variables, so commands the agent runs cannot read them.
49
+
50
+ Tested with pi 0.85.1.
51
+
52
+ ## Development
53
+
54
+ ```sh
55
+ npm install
56
+ npm test
57
+ ```
58
+
59
+ Releases are built by GitHub Actions and published with npm trusted publishing, so every version on npm links back to the commit it was built from.
package/package.json CHANGED
@@ -1,10 +1,41 @@
1
1
  {
2
2
  "name": "pi-codex-accounts",
3
- "version": "0.0.0",
4
- "description": "Placeholder that reserves the package name. Install 0.1.0 or later.",
3
+ "version": "0.1.1",
4
+ "description": "Use more than one ChatGPT (Codex) subscription in pi, each with its own login and its own entries in /model.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "pi-extension",
9
+ "codex",
10
+ "openai",
11
+ "chatgpt"
12
+ ],
5
13
  "license": "MIT",
14
+ "author": "Tiago Peixoto",
6
15
  "repository": {
7
16
  "type": "git",
8
17
  "url": "git+https://github.com/tiago-peixoto/pi-codex-accounts.git"
18
+ },
19
+ "type": "module",
20
+ "files": [
21
+ "src"
22
+ ],
23
+ "pi": {
24
+ "extensions": [
25
+ "./src/index.ts"
26
+ ]
27
+ },
28
+ "scripts": {
29
+ "test": "tsc && node --test test/index.test.ts && sh scripts/smoke.sh"
30
+ },
31
+ "peerDependencies": {
32
+ "@earendil-works/pi-ai": "*",
33
+ "@earendil-works/pi-coding-agent": "*"
34
+ },
35
+ "devDependencies": {
36
+ "@earendil-works/pi-ai": "0.85.1",
37
+ "@earendil-works/pi-coding-agent": "0.85.1",
38
+ "@types/node": "22.20.2",
39
+ "typescript": "7.0.2"
9
40
  }
10
41
  }
package/src/index.ts ADDED
@@ -0,0 +1,143 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import {
4
+ type AssistantMessageEvent,
5
+ type AssistantMessageEventStream,
6
+ type Context,
7
+ createAssistantMessageEventStream,
8
+ type Model,
9
+ type Provider,
10
+ } from "@earendil-works/pi-ai";
11
+ import { builtinProviders } from "@earendil-works/pi-ai/providers/all";
12
+ import { type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
13
+
14
+ const CODEX = "openai-codex";
15
+ const CONFIG_FILE = "codex-accounts.json";
16
+
17
+ type CodexApi = "openai-codex-responses";
18
+
19
+ export interface Account {
20
+ id: string;
21
+ name: string;
22
+ }
23
+
24
+ export default function codexAccounts(pi: ExtensionAPI) {
25
+ const path = join(getAgentDir(), CONFIG_FILE);
26
+ let accounts: Account[];
27
+ try {
28
+ accounts = parseAccounts(readConfig(path));
29
+ } catch (error) {
30
+ throw new Error(`${path}: ${error instanceof Error ? error.message : String(error)}`);
31
+ }
32
+ const codex = builtinCodexProvider();
33
+ for (const account of accounts) pi.registerProvider(createAccountProvider(codex, account));
34
+ }
35
+
36
+ /** pi lets extensions import only a few pi-ai entry points; providers/all is the one with the built-in providers. */
37
+ export function builtinCodexProvider(): Provider<CodexApi> {
38
+ const codex = builtinProviders().find((provider) => provider.id === CODEX);
39
+ if (!codex) throw new Error("pi no longer ships a built-in OpenAI Codex provider");
40
+ return codex as Provider<CodexApi>;
41
+ }
42
+
43
+ /** The config file's text, or undefined when there is no config file. */
44
+ function readConfig(path: string): string | undefined {
45
+ try {
46
+ return readFileSync(path, "utf8");
47
+ } catch (error) {
48
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ /** Without a config file there is one extra account, labelled "2". */
54
+ export function parseAccounts(json: string | undefined): Account[] {
55
+ const labels = json === undefined ? ["2"] : readLabels(json);
56
+ const accounts = labels.map((label) => ({ id: `${CODEX}-${slug(label)}`, name: `OpenAI Codex (${label.trim()})` }));
57
+ const seen = new Set<string>();
58
+ for (const { id } of accounts) {
59
+ if (seen.has(id)) throw new Error(`two labels turn into the same provider id "${id}"`);
60
+ seen.add(id);
61
+ }
62
+ return accounts;
63
+ }
64
+
65
+ function readLabels(json: string): string[] {
66
+ const labels = (JSON.parse(json) as { accounts?: unknown } | null)?.accounts;
67
+ if (!Array.isArray(labels) || !labels.every((label) => typeof label === "string" && slug(label) !== "")) {
68
+ throw new Error('expected {"accounts": ["Work", "Personal"]}, with an ASCII letter or digit in each label');
69
+ }
70
+ return labels;
71
+ }
72
+
73
+ function slug(label: string): string {
74
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
75
+ }
76
+
77
+ /**
78
+ * The built-in Codex provider under another id, so pi keeps a separate login for it
79
+ * and lists its models separately in /model.
80
+ */
81
+ export function createAccountProvider(codex: Provider<CodexApi>, account: Account): Provider<CodexApi> {
82
+ const oauth = codex.auth.oauth;
83
+ if (!oauth) throw new Error("pi's built-in OpenAI Codex provider no longer offers a ChatGPT login");
84
+ const models = codex.getModels().map((model) => ({ ...model, provider: account.id }));
85
+ return {
86
+ id: account.id,
87
+ name: account.name,
88
+ baseUrl: codex.baseUrl,
89
+ headers: codex.headers,
90
+ // Only the login: any other auth the built-in provider may gain (an environment variable, say)
91
+ // would resolve to the built-in account instead of this one.
92
+ auth: { oauth: { ...oauth, name: account.name } },
93
+ getModels: () => models,
94
+ // pi-ai's Codex API keeps Responses tool-call ids ("call|item") intact only when the model's
95
+ // provider is "openai-codex", so requests go out under that id and replies are relabelled.
96
+ stream: (model, context, options) =>
97
+ withProvider(codex.stream(asCodex(model), asCodexContext(context, account.id), options), account.id),
98
+ streamSimple: (model, context, options) =>
99
+ withProvider(codex.streamSimple(asCodex(model), asCodexContext(context, account.id), options), account.id),
100
+ };
101
+ }
102
+
103
+ function asCodex<T extends CodexApi>(model: Model<T>): Model<T> {
104
+ return { ...model, provider: CODEX };
105
+ }
106
+
107
+ /**
108
+ * Marks this account's earlier replies as "openai-codex" so the Codex API treats them as the same
109
+ * conversation. Replies from every other Codex account, the built-in one included, get a different id,
110
+ * so their encrypted reasoning is dropped instead of being sent to this account.
111
+ */
112
+ export function asCodexContext(context: Context, accountId: string): Context {
113
+ return {
114
+ ...context,
115
+ messages: context.messages.map((message) => {
116
+ if (message.role !== "assistant") return message;
117
+ if (message.provider === accountId) return { ...message, provider: CODEX };
118
+ if (message.provider === CODEX) return { ...message, provider: `${CODEX} (another account)` };
119
+ return message;
120
+ }),
121
+ };
122
+ }
123
+
124
+ /** Copies each event with the account's id. The Codex API keeps using its own message objects, so they stay untouched. */
125
+ export function withProvider(inner: AssistantMessageEventStream, provider: string): AssistantMessageEventStream {
126
+ const outer = createAssistantMessageEventStream();
127
+ void (async () => {
128
+ for await (const event of inner) outer.push(relabel(event, provider));
129
+ outer.end();
130
+ })();
131
+ return outer;
132
+ }
133
+
134
+ function relabel(event: AssistantMessageEvent, provider: string): AssistantMessageEvent {
135
+ switch (event.type) {
136
+ case "done":
137
+ return { ...event, message: { ...event.message, provider } };
138
+ case "error":
139
+ return { ...event, error: { ...event.error, provider } };
140
+ default:
141
+ return { ...event, partial: { ...event.partial, provider } };
142
+ }
143
+ }