@phantomcodes/cli 1.6.3 → 1.7.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 (140) hide show
  1. package/LICENSE +1 -2
  2. package/README.md +139 -118
  3. package/bin/phantom.mjs +37 -2
  4. package/dist/agents/command.d.mts +8 -27
  5. package/dist/agents/command.mjs +323 -59
  6. package/dist/agents/login.d.mts +3 -0
  7. package/dist/agents/login.mjs +97 -0
  8. package/dist/agents/opencode-check.d.mts +15 -0
  9. package/dist/agents/opencode-check.mjs +193 -0
  10. package/dist/agents/phantom-key.d.mts +7 -0
  11. package/dist/agents/phantom-key.mjs +40 -0
  12. package/dist/agents/proxy.d.mts +26 -28
  13. package/dist/agents/proxy.mjs +225 -33
  14. package/dist/chatgpt/command.d.mts +2 -0
  15. package/dist/chatgpt/command.mjs +119 -0
  16. package/dist/chatgpt/session.d.mts +87 -0
  17. package/dist/chatgpt/session.mjs +253 -0
  18. package/dist/cli/accounts.d.mts +21 -0
  19. package/dist/cli/accounts.mjs +96 -0
  20. package/dist/cli/app.d.mts +4 -24
  21. package/dist/cli/app.mjs +224 -139
  22. package/dist/cli/commands.d.mts +1 -16
  23. package/dist/cli/commands.mjs +144 -239
  24. package/dist/cli/help.d.mts +0 -19
  25. package/dist/cli/help.mjs +30 -55
  26. package/dist/cli/run.mjs +35 -79
  27. package/dist/cli/start.d.mts +2 -31
  28. package/dist/cli/start.mjs +13 -116
  29. package/dist/core/brand.d.mts +0 -7
  30. package/dist/core/brand.mjs +0 -8
  31. package/dist/core/errors.d.mts +0 -16
  32. package/dist/core/errors.mjs +0 -16
  33. package/dist/core/helpers.d.mts +0 -46
  34. package/dist/core/helpers.mjs +1 -64
  35. package/dist/core/node-trust.d.mts +0 -5
  36. package/dist/core/node-trust.mjs +0 -6
  37. package/dist/core/pick.d.mts +7 -55
  38. package/dist/core/pick.mjs +49 -106
  39. package/dist/core/request.d.mts +0 -46
  40. package/dist/core/request.mjs +1 -60
  41. package/dist/core/secrets.d.mts +0 -4
  42. package/dist/core/secrets.mjs +0 -10
  43. package/dist/core/state.d.mts +3 -1
  44. package/dist/core/state.mjs +147 -4
  45. package/dist/core/style.d.mts +0 -27
  46. package/dist/core/style.mjs +0 -20
  47. package/dist/core/version.d.mts +1 -2
  48. package/dist/core/version.mjs +1 -2
  49. package/dist/local/accounts.d.mts +25 -0
  50. package/dist/local/accounts.mjs +40 -0
  51. package/dist/local/agent-headers.d.mts +7 -0
  52. package/dist/local/agent-headers.mjs +44 -0
  53. package/dist/local/chatgpt-plan.d.mts +147 -0
  54. package/dist/local/chatgpt-plan.mjs +384 -0
  55. package/dist/local/command.d.mts +24 -0
  56. package/dist/local/command.mjs +211 -0
  57. package/dist/local/config.d.mts +49 -0
  58. package/dist/local/config.mjs +168 -0
  59. package/dist/local/decide.d.mts +37 -0
  60. package/dist/local/decide.mjs +201 -0
  61. package/dist/local/failure-signs.d.mts +4 -0
  62. package/dist/local/failure-signs.mjs +99 -0
  63. package/dist/local/keys.d.mts +32 -0
  64. package/dist/local/keys.mjs +239 -0
  65. package/dist/local/models.d.mts +53 -0
  66. package/dist/local/models.mjs +117 -0
  67. package/dist/local/replay.d.mts +59 -0
  68. package/dist/local/replay.mjs +143 -0
  69. package/dist/local/report.d.mts +43 -0
  70. package/dist/local/report.mjs +153 -0
  71. package/dist/local/request-log.d.mts +53 -0
  72. package/dist/local/request-log.mjs +69 -0
  73. package/dist/local/retry-after.d.mts +3 -0
  74. package/dist/local/retry-after.mjs +28 -0
  75. package/dist/local/rust-router.d.mts +39 -0
  76. package/dist/local/rust-router.mjs +54 -0
  77. package/dist/local/server.d.mts +27 -0
  78. package/dist/local/server.mjs +449 -0
  79. package/dist/local/status-line.d.mts +17 -0
  80. package/dist/local/status-line.mjs +81 -0
  81. package/dist/local/tiers.d.mts +3 -0
  82. package/dist/local/tiers.mjs +137 -0
  83. package/dist/local/traces.d.mts +69 -0
  84. package/dist/local/traces.mjs +341 -0
  85. package/dist/phantom.d.mts +0 -37
  86. package/dist/phantom.mjs +0 -31
  87. package/package.json +15 -9
  88. package/skills/phantom-ai/SKILL.md +28 -97
  89. package/dist/cli/screens.d.mts +0 -177
  90. package/dist/cli/screens.mjs +0 -398
  91. package/dist/core/free.d.mts +0 -13
  92. package/dist/core/free.mjs +0 -14
  93. package/dist/core/motion.d.mts +0 -47
  94. package/dist/core/motion.mjs +0 -156
  95. package/dist/core/shapes.d.mts +0 -13
  96. package/dist/core/shapes.mjs +0 -1
  97. package/dist/keys/command.d.mts +0 -16
  98. package/dist/keys/command.mjs +0 -143
  99. package/dist/keys/saved.d.mts +0 -96
  100. package/dist/keys/saved.mjs +0 -169
  101. package/dist/models/choice.d.mts +0 -7
  102. package/dist/models/choice.mjs +0 -27
  103. package/dist/models/command.d.mts +0 -8
  104. package/dist/models/command.mjs +0 -66
  105. package/dist/models/list.d.mts +0 -39
  106. package/dist/models/list.mjs +0 -39
  107. package/dist/receipts/command.d.mts +0 -7
  108. package/dist/receipts/command.mjs +0 -41
  109. package/dist/receipts/receipts.d.mts +0 -76
  110. package/dist/receipts/receipts.mjs +0 -118
  111. package/dist/setup/agents.d.mts +0 -149
  112. package/dist/setup/agents.mjs +0 -886
  113. package/dist/setup/apply.d.mts +0 -85
  114. package/dist/setup/apply.mjs +0 -301
  115. package/dist/setup/command.d.mts +0 -12
  116. package/dist/setup/command.mjs +0 -307
  117. package/dist/setup/editors.d.mts +0 -108
  118. package/dist/setup/editors.mjs +0 -500
  119. package/dist/setup/legacy.d.mts +0 -13
  120. package/dist/setup/legacy.mjs +0 -36
  121. package/dist/setup/plan.d.mts +0 -104
  122. package/dist/setup/plan.mjs +0 -132
  123. package/dist/setup/screen.d.mts +0 -30
  124. package/dist/setup/screen.mjs +0 -260
  125. package/dist/setup/shared.d.mts +0 -141
  126. package/dist/setup/shared.mjs +0 -88
  127. package/dist/setup/was.d.mts +0 -42
  128. package/dist/setup/was.mjs +0 -91
  129. package/dist/spend/command.d.mts +0 -5
  130. package/dist/spend/command.mjs +0 -235
  131. package/dist/spend/lineup.d.mts +0 -61
  132. package/dist/spend/lineup.mjs +0 -39
  133. package/dist/spend/reason.d.mts +0 -5
  134. package/dist/spend/reason.mjs +0 -60
  135. package/dist/spend/report.d.mts +0 -105
  136. package/dist/spend/report.mjs +0 -68
  137. package/dist/spend/routing.d.mts +0 -74
  138. package/dist/spend/routing.mjs +0 -57
  139. package/dist/workspace/command.d.mts +0 -59
  140. package/dist/workspace/command.mjs +0 -871
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Agents speak Chat Completions to phantom-1 on this computer. The ChatGPT plan takes
3
+ * only the Responses API at api.openai.com/v1/responses, with rules of its
4
+ * own: https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations
5
+ *
6
+ * agent --Chat body--> chatToPlanRequest --Responses request--> plan
7
+ * agent <--Chat chunks-- planStreamToChat <--Responses events--- plan
8
+ * agent <--one chat.completion-- chunksToCompletion (when it sent stream:false)
9
+ * a plan answer that is not 200 --> classifyPlanError --> what the router does
10
+ *
11
+ * Field names come from the openai SDK's types (openai 7.57.0):
12
+ * resources/responses/responses.d.ts for the Responses side and
13
+ * resources/chat/completions/completions.d.ts for the Chat side.
14
+ */
15
+ /**
16
+ * The namespace the agent's function tools go in: the plan takes function
17
+ * tools only inside one. The model's calls come back with `namespace` set; the
18
+ * agent gets them without it, under the names it sent.
19
+ */
20
+ export declare const TOOL_NAMESPACE: {
21
+ name: string;
22
+ description: string;
23
+ };
24
+ type Json = Record<string, unknown>;
25
+ export declare function chatToPlanRequest(body: Json, model: string): Json;
26
+ type FinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter';
27
+ type ToolCallDelta = {
28
+ index: number;
29
+ id?: string;
30
+ type?: 'function';
31
+ function: {
32
+ name?: string;
33
+ arguments: string;
34
+ };
35
+ };
36
+ type ChatDelta = {
37
+ role?: 'assistant';
38
+ content?: string;
39
+ refusal?: string;
40
+ tool_calls?: ToolCallDelta[];
41
+ };
42
+ type ChatUsage = {
43
+ prompt_tokens: number;
44
+ completion_tokens: number;
45
+ total_tokens: number;
46
+ prompt_tokens_details?: {
47
+ cached_tokens: number;
48
+ };
49
+ completion_tokens_details?: {
50
+ reasoning_tokens: number;
51
+ };
52
+ };
53
+ export type ChatChunk = {
54
+ id: string;
55
+ object: 'chat.completion.chunk';
56
+ created: number;
57
+ model: string;
58
+ choices: Array<{
59
+ index: number;
60
+ delta: ChatDelta;
61
+ finish_reason: FinishReason | null;
62
+ }>;
63
+ usage?: ChatUsage;
64
+ };
65
+ export type StreamStep = {
66
+ state: 'streaming' | 'done';
67
+ chunks: ChatChunk[];
68
+ } | {
69
+ state: 'failed';
70
+ chunks: ChatChunk[];
71
+ error: PlanError | null;
72
+ };
73
+ export declare function planStreamToChat(opts: {
74
+ model: string;
75
+ includeUsage: boolean;
76
+ created?: number;
77
+ }): {
78
+ feed(text: string): StreamStep;
79
+ end(): StreamStep;
80
+ };
81
+ type ChatToolCall = {
82
+ id: string;
83
+ type: 'function';
84
+ function: {
85
+ name: string;
86
+ arguments: string;
87
+ };
88
+ };
89
+ type ChatCompletion = {
90
+ id: string;
91
+ object: 'chat.completion';
92
+ created: number;
93
+ model: string;
94
+ choices: Array<{
95
+ index: number;
96
+ message: {
97
+ role: 'assistant';
98
+ content: string | null;
99
+ refusal: string | null;
100
+ tool_calls?: ChatToolCall[];
101
+ };
102
+ finish_reason: FinishReason | null;
103
+ logprobs: null;
104
+ }>;
105
+ usage?: ChatUsage;
106
+ };
107
+ export declare function chunksToCompletion(chunks: ChatChunk[]): ChatCompletion;
108
+ export declare function readPlan(answer: Response, model: string, onChunk: (chunk: ChatChunk) => void): Promise<{
109
+ done: boolean;
110
+ code: string | undefined;
111
+ tokens: {
112
+ in: number;
113
+ out: number;
114
+ } | null;
115
+ }>;
116
+ /**
117
+ * What the router does with a plan answer that failed. `status` is the plan's
118
+ * own (200 for a failure inside a stream); `code` is its `error.code`, when it
119
+ * sent one. Never the message: the docs call it diagnostic text.
120
+ *
121
+ * - `next-entry`: this account can't serve now (usage limit, rate limit,
122
+ * server trouble). Try the next entry.
123
+ * - `sign-in`: the plan did not accept this sign-in or this account (401/403).
124
+ * - `refused`: the plan can't take this request. The same body will fail
125
+ * again; the account is fine.
126
+ * - `pass-through`: anything else. Hand the agent the plan's answer.
127
+ *
128
+ * https://developers.openai.com/siwc/token-sharing-open-source/errors-and-recovery
129
+ */
130
+ type PlanError = {
131
+ kind: 'next-entry' | 'sign-in' | 'refused' | 'pass-through';
132
+ status: number;
133
+ code: string | null;
134
+ };
135
+ export declare function classifyPlanError(status: number, body: unknown): PlanError;
136
+ export declare function signInAdvice(error: {
137
+ status: number;
138
+ code: string | null;
139
+ }): string;
140
+ type UnusableSession = {
141
+ kind: 'signed-out' | 'plan-off' | 'expired';
142
+ } | {
143
+ kind: 'refresh-failed';
144
+ reason: string;
145
+ };
146
+ export declare function sessionProblem(session: UnusableSession): string;
147
+ export {};
@@ -0,0 +1,384 @@
1
+ // docs: Translates between the Chat Completions requests phantom-1 on this computer takes and the Responses API the ChatGPT plan speaks: a Chat body to a plan request, the plan's streamed events to Chat chunks or one chat.completion, a plan's whole streamed answer read to its end (readPlan, shared by the server and the routing evals), a plan error to what the router does with that account, and the sentences that tell the person about a refused or missing sign-in. Sends nothing and reads no files
2
+ import { groupLooseTools } from "../agents/proxy.mjs";
3
+ /**
4
+ * Agents speak Chat Completions to phantom-1 on this computer. The ChatGPT plan takes
5
+ * only the Responses API at api.openai.com/v1/responses, with rules of its
6
+ * own: https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations
7
+ *
8
+ * agent --Chat body--> chatToPlanRequest --Responses request--> plan
9
+ * agent <--Chat chunks-- planStreamToChat <--Responses events--- plan
10
+ * agent <--one chat.completion-- chunksToCompletion (when it sent stream:false)
11
+ * a plan answer that is not 200 --> classifyPlanError --> what the router does
12
+ *
13
+ * Field names come from the openai SDK's types (openai 7.57.0):
14
+ * resources/responses/responses.d.ts for the Responses side and
15
+ * resources/chat/completions/completions.d.ts for the Chat side.
16
+ */
17
+ /**
18
+ * The namespace the agent's function tools go in: the plan takes function
19
+ * tools only inside one. The model's calls come back with `namespace` set; the
20
+ * agent gets them without it, under the names it sent.
21
+ */
22
+ export const TOOL_NAMESPACE = { name: 'agent', description: 'The tools of the coding agent that sent this request.' };
23
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ const str = (value) => (typeof value === 'string' ? value : undefined);
25
+ function pick(from, keys) {
26
+ return Object.fromEntries(keys.filter((key) => from[key] !== undefined).map((key) => [key, from[key]]));
27
+ }
28
+ export function chatToPlanRequest(body, model) {
29
+ const tools = functionTools(body.tools);
30
+ const request = { model, input: inputItems(body.messages, new Set(tools.map((tool) => tool.name))) };
31
+ const { offered, choice } = toolChoice(body.tool_choice, tools);
32
+ if (offered.length)
33
+ request.tools = groupLooseTools(offered, TOOL_NAMESPACE).tools;
34
+ if (choice)
35
+ request.tool_choice = choice;
36
+ if (typeof body.parallel_tool_calls === 'boolean')
37
+ request.parallel_tool_calls = body.parallel_tool_calls;
38
+ if (typeof body.reasoning_effort === 'string')
39
+ request.reasoning = { effort: body.reasoning_effort };
40
+ const text = { ...textFormat(body.response_format), ...pick(body, ['verbosity']) };
41
+ if (Object.keys(text).length)
42
+ request.text = text;
43
+ if (typeof body.prompt_cache_key === 'string')
44
+ request.prompt_cache_key = body.prompt_cache_key;
45
+ return { ...request, store: false, stream: true };
46
+ }
47
+ function functionTools(tools) {
48
+ const out = [];
49
+ for (const tool of Array.isArray(tools) ? tools : []) {
50
+ const fn = isObject(tool) && tool.type === 'function' && isObject(tool.function) ? tool.function : undefined;
51
+ const name = str(fn?.name);
52
+ if (fn && name)
53
+ out.push({ type: 'function', name, ...pick(fn, ['description', 'parameters', 'strict']) });
54
+ }
55
+ return out;
56
+ }
57
+ /**
58
+ * The tools to offer and the Responses `tool_choice`. `auto`, `none` and
59
+ * `required` mean the same in both APIs. Responses names a forced function by
60
+ * `name` alone, with no field for its namespace, so a Chat choice that names
61
+ * one function (or an allowed_tools list) offers only those functions and sets
62
+ * `required` (or the list's mode) instead.
63
+ */
64
+ function toolChoice(choice, tools) {
65
+ if (choice === 'auto' || choice === 'none' || choice === 'required')
66
+ return { offered: tools, choice };
67
+ const only = (names) => tools.filter((tool) => names.includes(tool.name));
68
+ const nameOf = (ref) => (isObject(ref) && isObject(ref.function) ? ref.function.name : undefined);
69
+ if (isObject(choice) && choice.type === 'function' && typeof nameOf(choice) === 'string')
70
+ return { offered: only([nameOf(choice)]), choice: 'required' };
71
+ const allowed = isObject(choice) && choice.type === 'allowed_tools' && isObject(choice.allowed_tools) ? choice.allowed_tools : {};
72
+ if ((allowed.mode === 'auto' || allowed.mode === 'required') && Array.isArray(allowed.tools))
73
+ return { offered: only(allowed.tools.map(nameOf)), choice: allowed.mode };
74
+ return { offered: tools };
75
+ }
76
+ function inputItems(messages, agentTools) {
77
+ const items = [];
78
+ for (const message of Array.isArray(messages) ? messages : []) {
79
+ if (!isObject(message))
80
+ continue;
81
+ switch (message.role) {
82
+ case 'system':
83
+ case 'developer':
84
+ items.push({ type: 'message', role: 'developer', content: inputContent(message.content) });
85
+ break;
86
+ case 'user':
87
+ items.push({ type: 'message', role: 'user', content: inputContent(message.content) });
88
+ break;
89
+ case 'assistant': {
90
+ const text = textOf(message.content);
91
+ if (text)
92
+ items.push({ type: 'message', role: 'assistant', content: text });
93
+ for (const raw of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
94
+ const call = isObject(raw) ? raw : {};
95
+ const fn = isObject(call.function) ? call.function : {};
96
+ const name = str(fn.name) ?? '';
97
+ items.push({ type: 'function_call', call_id: str(call.id) ?? '', name, ...(agentTools.has(name) && { namespace: TOOL_NAMESPACE.name }), arguments: str(fn.arguments) ?? '' });
98
+ }
99
+ break;
100
+ }
101
+ case 'tool':
102
+ items.push({ type: 'function_call_output', call_id: str(message.tool_call_id) ?? '', output: textOf(message.content) });
103
+ break;
104
+ }
105
+ }
106
+ return items;
107
+ }
108
+ function inputContent(content) {
109
+ if (!Array.isArray(content))
110
+ return str(content) ?? '';
111
+ const parts = [];
112
+ for (const part of content) {
113
+ const kind = isObject(part) ? part.type : undefined;
114
+ if (kind === 'text')
115
+ parts.push({ type: 'input_text', text: str(part.text) ?? '' });
116
+ else if (kind === 'image_url' && isObject(part.image_url))
117
+ parts.push({ type: 'input_image', image_url: part.image_url.url, detail: part.image_url.detail ?? 'auto' });
118
+ else if (kind === 'file' && isObject(part.file))
119
+ parts.push({ type: 'input_file', ...pick(part.file, ['file_data', 'file_id', 'filename']) });
120
+ }
121
+ return parts;
122
+ }
123
+ function textOf(content) {
124
+ if (!Array.isArray(content))
125
+ return str(content) ?? '';
126
+ return content.map((part) => (isObject(part) ? (str(part.text) ?? str(part.refusal) ?? '') : '')).join('');
127
+ }
128
+ function textFormat(format) {
129
+ if (isObject(format) && (format.type === 'text' || format.type === 'json_object'))
130
+ return { format: { type: format.type } };
131
+ if (isObject(format) && format.type === 'json_schema' && isObject(format.json_schema)) {
132
+ return { format: { type: 'json_schema', ...pick(format.json_schema, ['name', 'schema', 'strict', 'description']) } };
133
+ }
134
+ return {};
135
+ }
136
+ export function planStreamToChat(opts) {
137
+ const head = { id: 'chatcmpl-phantom-local', created: opts.created ?? Math.floor(Date.now() / 1000), model: opts.model };
138
+ let pending = '';
139
+ let state = 'streaming';
140
+ let error = null;
141
+ let out = [];
142
+ let started = false;
143
+ const calls = new Map();
144
+ function adopt(response) {
145
+ if (started || !isObject(response))
146
+ return;
147
+ if (typeof response.id === 'string')
148
+ head.id = `chatcmpl-${response.id}`;
149
+ if (typeof response.created_at === 'number')
150
+ head.created = response.created_at;
151
+ if (typeof response.model === 'string')
152
+ head.model = response.model;
153
+ }
154
+ function send(delta, finish = null) {
155
+ out.push({ ...head, object: 'chat.completion.chunk', choices: [{ index: 0, delta: started ? delta : { role: 'assistant', ...delta }, finish_reason: finish }] });
156
+ started = true;
157
+ }
158
+ function addArguments(call, delta) {
159
+ call.sent += delta;
160
+ send({ tool_calls: [{ index: call.index, function: { arguments: delta } }] });
161
+ }
162
+ function seeCall(outputIndex, item) {
163
+ let call = calls.get(outputIndex);
164
+ if (!call) {
165
+ call = { index: calls.size, sent: '' };
166
+ calls.set(outputIndex, call);
167
+ send({ tool_calls: [{ index: call.index, id: str(item.call_id) ?? '', type: 'function', function: { name: str(item.name) ?? '', arguments: '' } }] });
168
+ }
169
+ const full = str(item.arguments) ?? '';
170
+ if (full.length > call.sent.length && full.startsWith(call.sent))
171
+ addArguments(call, full.slice(call.sent.length));
172
+ }
173
+ function finish(reason, response) {
174
+ adopt(response);
175
+ send({}, reason);
176
+ const usage = isObject(response) ? chatUsage(response.usage) : undefined;
177
+ if (opts.includeUsage && usage)
178
+ out.push({ ...head, object: 'chat.completion.chunk', choices: [], usage });
179
+ state = 'done';
180
+ }
181
+ function fail(planError) {
182
+ state = 'failed';
183
+ error = classifyPlanError(200, { error: planError });
184
+ }
185
+ function handle(event) {
186
+ const outputIndex = typeof event.output_index === 'number' ? event.output_index : -1;
187
+ const response = isObject(event.response) ? event.response : {};
188
+ switch (event.type) {
189
+ case 'response.created':
190
+ case 'response.in_progress':
191
+ return adopt(response);
192
+ case 'response.output_text.delta':
193
+ return send({ content: str(event.delta) ?? '' });
194
+ case 'response.refusal.delta':
195
+ return send({ refusal: str(event.delta) ?? '' });
196
+ case 'response.output_item.added':
197
+ case 'response.output_item.done':
198
+ if (isObject(event.item) && event.item.type === 'function_call')
199
+ seeCall(outputIndex, event.item);
200
+ return;
201
+ case 'response.function_call_arguments.delta': {
202
+ const call = calls.get(outputIndex);
203
+ if (call)
204
+ addArguments(call, str(event.delta) ?? '');
205
+ return;
206
+ }
207
+ case 'response.completed':
208
+ return finish(calls.size ? 'tool_calls' : 'stop', response);
209
+ case 'response.incomplete':
210
+ return finish(isObject(response.incomplete_details) && response.incomplete_details.reason === 'content_filter' ? 'content_filter' : 'length', response);
211
+ case 'response.failed':
212
+ return fail(response.error);
213
+ case 'error':
214
+ return fail(isObject(event.error) ? event.error : event);
215
+ }
216
+ }
217
+ function read(block) {
218
+ const data = block.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).replace(/^ /, '')).join('\n');
219
+ let event;
220
+ try {
221
+ event = JSON.parse(data);
222
+ }
223
+ catch {
224
+ return;
225
+ }
226
+ if (isObject(event))
227
+ handle(event);
228
+ }
229
+ const step = () => (state === 'failed' ? { state, chunks: out, error } : { state, chunks: out });
230
+ return {
231
+ feed(text) {
232
+ out = [];
233
+ pending = (pending + text).replace(/\r\n/g, '\n');
234
+ let end = pending.indexOf('\n\n');
235
+ while (end >= 0 && state === 'streaming') {
236
+ read(pending.slice(0, end));
237
+ pending = pending.slice(end + 2);
238
+ end = pending.indexOf('\n\n');
239
+ }
240
+ return step();
241
+ },
242
+ end() {
243
+ out = [];
244
+ if (state === 'streaming')
245
+ read(pending);
246
+ pending = '';
247
+ if (state === 'streaming')
248
+ state = 'failed';
249
+ return step();
250
+ },
251
+ };
252
+ }
253
+ function chatUsage(usage) {
254
+ if (!isObject(usage) || typeof usage.input_tokens !== 'number' || typeof usage.output_tokens !== 'number')
255
+ return undefined;
256
+ const cached = isObject(usage.input_tokens_details) ? usage.input_tokens_details.cached_tokens : undefined;
257
+ const reasoning = isObject(usage.output_tokens_details) ? usage.output_tokens_details.reasoning_tokens : undefined;
258
+ return {
259
+ prompt_tokens: usage.input_tokens,
260
+ completion_tokens: usage.output_tokens,
261
+ total_tokens: typeof usage.total_tokens === 'number' ? usage.total_tokens : usage.input_tokens + usage.output_tokens,
262
+ ...(typeof cached === 'number' && { prompt_tokens_details: { cached_tokens: cached } }),
263
+ ...(typeof reasoning === 'number' && { completion_tokens_details: { reasoning_tokens: reasoning } }),
264
+ };
265
+ }
266
+ export function chunksToCompletion(chunks) {
267
+ let content = '';
268
+ let refusal = '';
269
+ let finish = null;
270
+ let usage;
271
+ const calls = [];
272
+ for (const chunk of chunks) {
273
+ if (chunk.usage)
274
+ usage = chunk.usage;
275
+ for (const { delta, finish_reason } of chunk.choices) {
276
+ content += delta.content ?? '';
277
+ refusal += delta.refusal ?? '';
278
+ finish = finish_reason ?? finish;
279
+ for (const part of delta.tool_calls ?? []) {
280
+ const call = (calls[part.index] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
281
+ call.id = part.id ?? call.id;
282
+ call.function.name = part.function.name ?? call.function.name;
283
+ call.function.arguments += part.function.arguments;
284
+ }
285
+ }
286
+ }
287
+ const { id, created, model } = chunks[0];
288
+ return {
289
+ id,
290
+ object: 'chat.completion',
291
+ created,
292
+ model,
293
+ choices: [{
294
+ index: 0,
295
+ message: { role: 'assistant', content: content === '' && calls.length ? null : content, refusal: refusal || null, ...(calls.length && { tool_calls: calls }) },
296
+ finish_reason: finish,
297
+ logprobs: null,
298
+ }],
299
+ ...(usage && { usage }),
300
+ };
301
+ }
302
+ export async function readPlan(answer, model, onChunk) {
303
+ const translate = planStreamToChat({ model, includeUsage: true });
304
+ const decoder = new TextDecoder();
305
+ let tokens = null;
306
+ const take = (step) => {
307
+ for (const chunk of step.chunks) {
308
+ if (chunk.usage)
309
+ tokens = { in: chunk.usage.prompt_tokens, out: chunk.usage.completion_tokens };
310
+ onChunk(chunk);
311
+ }
312
+ return step;
313
+ };
314
+ let step = { state: 'streaming', chunks: [] };
315
+ try {
316
+ for await (const piece of (answer.body ?? [])) {
317
+ step = take(translate.feed(decoder.decode(piece, { stream: true })));
318
+ if (step.state !== 'streaming')
319
+ break;
320
+ }
321
+ if (step.state === 'streaming')
322
+ step = take(translate.end());
323
+ }
324
+ catch {
325
+ step = { state: 'failed', chunks: [], error: null };
326
+ }
327
+ return { done: step.state === 'done', code: step.state === 'failed' ? (step.error?.code ?? undefined) : undefined, tokens };
328
+ }
329
+ /**
330
+ * Codes that mean "try another account". The first three are the plan's
331
+ * (errors-and-recovery); `rate_limit_exceeded` and `insufficient_quota` are the
332
+ * general API's, in case the plan sends them.
333
+ */
334
+ const NEXT_ENTRY_CODES = new Set(['subscription_sharing_usage_limit_exceeded', 'subscription_sharing_usage_unavailable', 'subscription_sharing_user_unavailable', 'rate_limit_exceeded', 'insufficient_quota']);
335
+ /** The plan's codes for a sign-in, grant or account it did not accept (errors-and-recovery). They can also arrive inside a stream. */
336
+ const SIGN_IN_CODES = new Set(['subscription_sharing_invalid_user', 'subscription_sharing_user_not_eligible', 'chatpass_v2_scope_not_authorized', 'chatpass_v2_invalid_authorization_context']);
337
+ const REFUSED_CODE = 'subscription_sharing_unsupported_capability';
338
+ export function classifyPlanError(status, body) {
339
+ const error = errorOf(body);
340
+ const code = str(error.code)?.replace(/[\u0000-\u001f\u007f-\u009f]/g, '') || null;
341
+ if (code === REFUSED_CODE)
342
+ return { kind: 'refused', status, code };
343
+ if (NEXT_ENTRY_CODES.has(code ?? '') || status === 429 || status >= 500)
344
+ return { kind: 'next-entry', status, code };
345
+ if (SIGN_IN_CODES.has(code ?? '') || status === 401 || status === 403)
346
+ return { kind: 'sign-in', status, code };
347
+ return { kind: 'pass-through', status, code };
348
+ }
349
+ function errorOf(body) {
350
+ let parsed = body;
351
+ if (typeof body === 'string') {
352
+ try {
353
+ parsed = JSON.parse(body);
354
+ }
355
+ catch {
356
+ return {};
357
+ }
358
+ }
359
+ return isObject(parsed) && isObject(parsed.error) ? parsed.error : {};
360
+ }
361
+ export function signInAdvice(error) {
362
+ const what = `${error.status}${error.code ? ` ${error.code}` : ''}`;
363
+ if (error.code === 'subscription_sharing_user_not_eligible') {
364
+ return `ChatGPT says plan use isn't available for this account, workspace or policy (${what}). Signing in again won't fix this; check the plan at https://chatgpt.com/settings.`;
365
+ }
366
+ if (error.code?.startsWith('chatpass_v2_')) {
367
+ return `ChatGPT's permission check refused Phantom CLI's grant (${what}). Signing in again won't fix this; it is a problem in Phantom CLI, so report it.`;
368
+ }
369
+ if (error.status === 403)
370
+ return `ChatGPT blocked plan use by a policy or region check (${what}). Signing in again won't fix this.`;
371
+ return `ChatGPT did not accept the sign-in (${what}). Run phantom config chatgpt login.`;
372
+ }
373
+ export function sessionProblem(session) {
374
+ switch (session.kind) {
375
+ case 'signed-out':
376
+ return 'Not signed in with ChatGPT. Run phantom config chatgpt login.';
377
+ case 'plan-off':
378
+ return 'Signed in with ChatGPT, but without plan use. Run phantom config chatgpt login and allow plan use.';
379
+ case 'expired':
380
+ return 'The ChatGPT sign-in is being refreshed by another phantom process. Try again in a moment.';
381
+ case 'refresh-failed':
382
+ return `The ChatGPT sign-in could not be used: ${session.reason}.`;
383
+ }
384
+ }
@@ -0,0 +1,24 @@
1
+ import { type CommandInput } from '../core/helpers.mts';
2
+ import type { Env } from '../core/state.mts';
3
+ import { type LocalConfig } from './config.mts';
4
+ import { type RequestRecord } from './request-log.mts';
5
+ export declare function configCommand(input: CommandInput): Promise<number>;
6
+ export declare function reportCommand(input: CommandInput): Promise<number>;
7
+ export declare function replayCommand(input: CommandInput): Promise<number>;
8
+ type Router = {
9
+ url: string;
10
+ config: LocalConfig;
11
+ logFile: string | null;
12
+ tracesFolder: string | null;
13
+ close(): Promise<void>;
14
+ };
15
+ export declare function startRouter(opts: {
16
+ env: Env;
17
+ port: number;
18
+ token?: string;
19
+ notify: (line: string) => void;
20
+ log: (line: string) => void;
21
+ warn: (line: string) => void;
22
+ onRequest?: (record: RequestRecord) => void;
23
+ }): Promise<Router>;
24
+ export {};