pi-devin-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.
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Drive a browser-based Windsurf sign-in via pi's `OAuthLoginCallbacks`.
3
+ *
4
+ * Flow:
5
+ * 1. Build an Auth0 implicit-grant URL (`response_type=token`) pointing at
6
+ * Windsurf's SPA sign-in page with `redirect_uri=show-auth-token`. That
7
+ * special redirect tells the SPA to render the resulting access token in
8
+ * a `<code>` block on screen instead of redirecting away — the user
9
+ * copies it manually.
10
+ * 2. `callbacks.onAuth({ url })` opens the browser.
11
+ * 3. `callbacks.onPrompt(...)` collects the pasted token. That pasted value
12
+ * IS the Firebase ID token (the `access_token` from the OAuth fragment).
13
+ * 4. `registerUser(pasted, region)` exchanges it for a long-lived API key.
14
+ * 5. We wrap the key in `OAuthCredentials` and return it.
15
+ *
16
+ * Why manual paste instead of a loopback redirect? pi's `OAuthLoginCallbacks`
17
+ * surface no way to spin up a local HTTP server or read a redirect — the only
18
+ * inputs we get back are `onPrompt` (free text) and `onSelect` (pick from a
19
+ * list). The `show-auth-token` redirect + manual paste is the same trick the
20
+ * opencode-windsurf-auth CLI uses for headless / SSH environments, and it is
21
+ * the only shape that fits pi's callback contract.
22
+ */
23
+
24
+ import * as crypto from 'crypto';
25
+ import type { OAuthCredentials, OAuthLoginCallbacks } from '@earendil-works/pi-ai';
26
+ import { registerUser } from './register-user.js';
27
+ import { DEFAULT_REGION, type WindsurfRegion } from './types.js';
28
+
29
+ /** One year in milliseconds — the API key is effectively non-expiring. */
30
+ const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;
31
+
32
+ /**
33
+ * Build the Auth0 implicit-grant URL for Windsurf's SPA sign-in page.
34
+ *
35
+ * Mirrors the params the opencode-windsurf-auth flow sends:
36
+ * - `response_type=token` -> Auth0 returns the access token in the URL
37
+ * fragment (implicit grant, no client secret).
38
+ * - `redirect_uri=show-auth-token` -> the SPA's special route that renders
39
+ * the token on-screen for manual copy instead of bouncing elsewhere.
40
+ * - `state` -> random UUID, guards CSRF on the browser round-trip. We do
41
+ * not validate it server-side (we never receive the redirect), but
42
+ * Auth0 requires it and echoing it back is good hygiene.
43
+ * - `prompt=login` -> force a fresh Auth0 login screen even if the user
44
+ * has an SSO session, so they can pick a different account.
45
+ */
46
+ function buildSignInUrl(region: WindsurfRegion): string {
47
+ const params = new URLSearchParams({
48
+ response_type: 'token',
49
+ client_id: region.oauthClientId,
50
+ redirect_uri: 'show-auth-token',
51
+ state: crypto.randomUUID(),
52
+ prompt: 'login',
53
+ });
54
+ return `${region.website}/windsurf/signin?${params.toString()}`;
55
+ }
56
+
57
+ /**
58
+ * Run the full Windsurf OAuth login through pi's `OAuthLoginCallbacks`.
59
+ *
60
+ * The returned `OAuthCredentials.access` is the Windsurf API key (not the
61
+ * short-lived Firebase token — that is consumed by `registerUser` and
62
+ * discarded). `refresh` is empty because Windsurf API keys do not expire;
63
+ * `expires` is set one year out as a soft sentinel, not a hard expiry.
64
+ *
65
+ * `WindsurfRegistrationError` thrown by `registerUser` is allowed to
66
+ * propagate — pi surfaces it to the user.
67
+ */
68
+ export async function loginDevin(
69
+ callbacks: OAuthLoginCallbacks,
70
+ region: WindsurfRegion = DEFAULT_REGION,
71
+ ): Promise<OAuthCredentials> {
72
+ const url = buildSignInUrl(region);
73
+
74
+ // Open the browser to the Auth0 sign-in page.
75
+ callbacks.onAuth({ url });
76
+
77
+ // Block until the user pastes the token rendered on the sign-in page.
78
+ // This is the Firebase ID token (OAuth `access_token` from the fragment).
79
+ const firebaseIdToken = await callbacks.onPrompt({
80
+ message: 'Paste the token from the sign-in page:',
81
+ });
82
+
83
+ if (!firebaseIdToken) {
84
+ throw new Error('No token pasted; cannot complete sign-in.');
85
+ }
86
+
87
+ // Exchange the Firebase token for a long-lived Windsurf API key.
88
+ const result = await registerUser(firebaseIdToken.trim(), region);
89
+
90
+ return {
91
+ refresh: '',
92
+ access: result.apiKey,
93
+ expires: Date.now() + ONE_YEAR_MS,
94
+ };
95
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Exchange a Firebase ID token for a long-lived Windsurf API key.
3
+ *
4
+ * This calls the same Connect-RPC endpoint the Windsurf desktop extension uses
5
+ * after the browser sign-in completes:
6
+ *
7
+ * POST https://register.windsurf.com/exa.seat_management_pb.SeatManagementService/RegisterUser
8
+ * Content-Type: application/json
9
+ * Body: { "firebase_id_token": "<jwt>" }
10
+ *
11
+ * Connect-RPC happily accepts plain JSON over HTTPS (no gRPC framing required),
12
+ * so we skip @connectrpc/connect entirely and use `fetch`. The response shape
13
+ * matches `exa.seat_management_pb.RegisterUserResponse`:
14
+ *
15
+ * { api_key, name, api_server_url, redirect_url, team_options[] }
16
+ *
17
+ * Endpoint verified live (returns `{code:"unauthenticated",message:"invalid token ..."}`
18
+ * for a fake token, 200 with the response body for a valid one).
19
+ */
20
+
21
+ import type { OAuthLoginResult, WindsurfRegion } from './types.js';
22
+
23
+ /**
24
+ * Polyfill for `AbortSignal.any` — composes multiple signals so the result
25
+ * aborts when ANY input aborts. Built-in in Node ≥20.3 / Bun ≥1.0; we
26
+ * implement the fallback ourselves so the timeout/caller-signal merge
27
+ * works on every runtime our `engines` field permits (Node 18+).
28
+ */
29
+ function anySignal(signals: AbortSignal[]): AbortSignal {
30
+ const builtin = (AbortSignal as unknown as { any?: (s: AbortSignal[]) => AbortSignal }).any;
31
+ if (typeof builtin === 'function') return builtin(signals);
32
+ const controller = new AbortController();
33
+ const onAbort = (reason: unknown): void => {
34
+ if (!controller.signal.aborted) controller.abort(reason);
35
+ };
36
+ for (const s of signals) {
37
+ if (s.aborted) {
38
+ onAbort(s.reason);
39
+ break;
40
+ }
41
+ s.addEventListener('abort', () => onAbort(s.reason), { once: true });
42
+ }
43
+ return controller.signal;
44
+ }
45
+
46
+ interface RegisterUserResponseJson {
47
+ api_key?: string;
48
+ name?: string;
49
+ api_server_url?: string;
50
+ redirect_url?: string;
51
+ team_options?: unknown[];
52
+ }
53
+
54
+ interface ConnectErrorJson {
55
+ code?: string;
56
+ message?: string;
57
+ }
58
+
59
+ export class WindsurfRegistrationError extends Error {
60
+ readonly status: number;
61
+ readonly connectCode?: string;
62
+ readonly traceId?: string;
63
+
64
+ constructor(message: string, status: number, connectCode?: string, traceId?: string) {
65
+ super(message);
66
+ this.name = 'WindsurfRegistrationError';
67
+ this.status = status;
68
+ this.connectCode = connectCode;
69
+ this.traceId = traceId;
70
+ }
71
+ }
72
+
73
+ const TRACE_ID_RE = /\(trace ID: ([0-9a-f]+)\)/i;
74
+
75
+ /**
76
+ * Exchange the Firebase ID token for a Windsurf API key.
77
+ *
78
+ * `firebaseIdToken` is the `access_token` (or `firebase_id_token`) value the
79
+ * Windsurf sign-in page returns in the OAuth callback URL — we treat it as
80
+ * opaque.
81
+ */
82
+ export async function registerUser(
83
+ firebaseIdToken: string,
84
+ region: WindsurfRegion,
85
+ abortSignal?: AbortSignal,
86
+ ): Promise<OAuthLoginResult> {
87
+ if (!firebaseIdToken) {
88
+ throw new WindsurfRegistrationError('Empty firebase_id_token', 0, 'invalid_argument');
89
+ }
90
+
91
+ const url = `${region.registerApiServerUrl.replace(/\/$/, '')}/exa.seat_management_pb.SeatManagementService/RegisterUser`;
92
+
93
+ // 30s internal timeout — RegisterUser responds in ~200ms in steady state.
94
+ // CLI users on flaky networks need bounded waits or the sign-in command
95
+ // hangs forever. Compose with the caller's signal via a small polyfill
96
+ // (`anySignal`) because Node 18 / older Bun lack AbortSignal.any; the
97
+ // previous fallback `combinedSignal = abortSignal` would drop the
98
+ // timeout entirely on those runtimes.
99
+ const timeoutSignal = AbortSignal.timeout(30_000);
100
+ const combinedSignal: AbortSignal = abortSignal
101
+ ? anySignal([abortSignal, timeoutSignal])
102
+ : timeoutSignal;
103
+
104
+ const response = await fetch(url, {
105
+ method: 'POST',
106
+ headers: {
107
+ 'Content-Type': 'application/json',
108
+ // Connect protocol version header — not strictly required for JSON, but
109
+ // matches what the official Connect clients send and avoids accidental
110
+ // routing into a non-Connect HTTP handler.
111
+ 'Connect-Protocol-Version': '1',
112
+ },
113
+ body: JSON.stringify({ firebase_id_token: firebaseIdToken }),
114
+ signal: combinedSignal,
115
+ });
116
+
117
+ const text = await response.text();
118
+
119
+ if (!response.ok) {
120
+ let connectCode: string | undefined;
121
+ let message = text || `RegisterUser failed with HTTP ${response.status}`;
122
+ try {
123
+ const errJson = JSON.parse(text) as ConnectErrorJson;
124
+ connectCode = errJson.code;
125
+ if (errJson.message) message = errJson.message;
126
+ } catch {
127
+ // non-JSON error body — keep raw text in `message`
128
+ }
129
+ const traceMatch = message.match(TRACE_ID_RE);
130
+ throw new WindsurfRegistrationError(message, response.status, connectCode, traceMatch?.[1]);
131
+ }
132
+
133
+ let parsed: RegisterUserResponseJson;
134
+ try {
135
+ parsed = JSON.parse(text) as RegisterUserResponseJson;
136
+ } catch {
137
+ throw new WindsurfRegistrationError(
138
+ `RegisterUser returned 200 but body is not JSON: ${text.slice(0, 200)}`,
139
+ response.status,
140
+ 'internal',
141
+ );
142
+ }
143
+
144
+ const apiKey = parsed.api_key;
145
+ const name = parsed.name;
146
+ // Empty `api_server_url` is normal for single-tenant accounts — the desktop
147
+ // extension's `getApiServerUrl` helper falls back to the configured default
148
+ // when this is empty/missing. We mirror that behavior here.
149
+ const apiServerUrl = parsed.api_server_url && parsed.api_server_url.length > 0
150
+ ? parsed.api_server_url
151
+ : 'https://server.codeium.com';
152
+
153
+ if (!apiKey) {
154
+ throw new WindsurfRegistrationError(
155
+ 'RegisterUser returned 200 but api_key was empty',
156
+ response.status,
157
+ 'malformed_response',
158
+ );
159
+ }
160
+ if (!name) {
161
+ throw new WindsurfRegistrationError(
162
+ 'RegisterUser returned 200 but name was empty',
163
+ response.status,
164
+ 'malformed_response',
165
+ );
166
+ }
167
+
168
+ return {
169
+ apiKey,
170
+ name,
171
+ apiServerUrl,
172
+ redirectUrl: parsed.redirect_url,
173
+ };
174
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Shared types for the OAuth login flow + persisted credentials.
3
+ *
4
+ * Two distinct token shapes appear in this codebase:
5
+ *
6
+ * - `firebaseIdToken` — the short-lived JWT minted by Auth0 / Firebase Auth
7
+ * during browser sign-in. Lives in the OAuth callback URL fragment/query.
8
+ * Treated as opaque and discarded once exchanged.
9
+ *
10
+ * - `apiKey` — the long-lived credential returned by
11
+ * `SeatManagementService.RegisterUser`. Used inside every Cascade RPC's
12
+ * `Metadata.api_key` field. Format is provider-defined:
13
+ * * Cognition era: `devin-session-token$<JWT>`
14
+ * * Codeium classic: bare UUID v4
15
+ * * Older Windsurf: `sk-ws-01-<...>` / `cog_<...>`
16
+ * The plugin treats it as an opaque string — only the cloud cares about format.
17
+ */
18
+
19
+ export interface OAuthLoginResult {
20
+ /** The opaque API key used as `Metadata.api_key` in every Cascade RPC. */
21
+ apiKey: string;
22
+ /** Human-readable account name (`Satvik Kapoor`). */
23
+ name: string;
24
+ /**
25
+ * Cloud API server (`https://server.codeium.com`, `https://eu.windsurf.com/_route/api_server`,
26
+ * `https://windsurf.fedstart.com/_route/api_server`). Driven by the user's
27
+ * tenant — language_server needs this as `--api_server_url`.
28
+ */
29
+ apiServerUrl: string;
30
+ /** Optional cleanup redirect URL returned by RegisterUser. Informational. */
31
+ redirectUrl?: string;
32
+ }
33
+
34
+ export interface PersistedCredentials extends OAuthLoginResult {
35
+ /** ISO timestamp the credentials were minted at — purely informational. */
36
+ issuedAt: string;
37
+ /** Optional tag tracking the OAuth client id used (so a future client rotation can invalidate). */
38
+ oauthClientId: string;
39
+ /**
40
+ * True when these credentials were written as part of the
41
+ * `opencode auth login` → authorize() flow (so opencode's auth.json is the
42
+ * authoritative copy and `opencode auth logout windsurf` should mirror-clear
43
+ * this file). False / absent for credentials written by our standalone
44
+ * `opencode-windsurf-auth login` CLI; those survive opencode auth state
45
+ * changes.
46
+ */
47
+ syncedViaOpencodeAuth?: boolean;
48
+ }
49
+
50
+ export interface WindsurfRegion {
51
+ /** Where to send users for browser sign-in. */
52
+ website: string;
53
+ /** Where to POST RegisterUser. */
54
+ registerApiServerUrl: string;
55
+ /** Auth0 client id passed in the OAuth URL. */
56
+ oauthClientId: string;
57
+ }
58
+
59
+ /**
60
+ * The single tenant (free / personal) configuration. EU, FedStart, and arbitrary
61
+ * portal URLs override `website` + `registerApiServerUrl` at runtime when the
62
+ * user passes `--portal-url` to the login command.
63
+ */
64
+ export const DEFAULT_REGION: WindsurfRegion = {
65
+ website: 'https://windsurf.com',
66
+ registerApiServerUrl: 'https://register.windsurf.com',
67
+ // From /Applications/Windsurf.app/.../extension.js — the public Windsurf
68
+ // Auth0 client. If Windsurf rotates this, sign-in will start failing until
69
+ // we re-extract it.
70
+ oauthClientId: '3GUryQ7ldAeKEuD2obYnppsnmj58eP5u',
71
+ };
package/src/stream.ts ADDED
@@ -0,0 +1,341 @@
1
+ /**
2
+ * pi `streamSimple` implementation for the Devin/Cognition provider.
3
+ *
4
+ * Calls the cloud-direct gRPC streaming layer (`streamChatEvents`) and
5
+ * translates the resulting `CloudChatEvent` stream into pi's
6
+ * `AssistantMessageEventStream` events.
7
+ *
8
+ * The async-IIFE pattern is the standard pi `streamSimple` shape: the
9
+ * function returns a `AssistantMessageEventStream` synchronously and drives
10
+ * the upstream async iterator inside an IIFE, pushing events as they
11
+ * arrive.
12
+ */
13
+ import {
14
+ type Api,
15
+ type AssistantMessage,
16
+ type AssistantMessageEventStream,
17
+ type Context,
18
+ type Model,
19
+ type SimpleStreamOptions,
20
+ calculateCost,
21
+ createAssistantMessageEventStream,
22
+ } from '@earendil-works/pi-ai';
23
+ import { streamChatEvents, type CloudChatEvent } from './cloud-direct/index.js';
24
+ import { mapContextToChat } from './context-map.js';
25
+
26
+ /**
27
+ * Stream a Devin/Cognition chat completion into pi's assistant-message
28
+ * event stream.
29
+ *
30
+ * @param model pi model descriptor (id, api, provider, cost, ...).
31
+ * @param context pi conversation context (systemPrompt, messages, tools).
32
+ * @param options streaming options (apiKey, maxTokens, signal, ...).
33
+ * @returns an {@link AssistantMessageEventStream} that receives events
34
+ * as the upstream gRPC stream progresses.
35
+ */
36
+ export function streamDevin(
37
+ model: Model<Api>,
38
+ context: Context,
39
+ options?: SimpleStreamOptions,
40
+ ): AssistantMessageEventStream {
41
+ const stream = createAssistantMessageEventStream();
42
+
43
+ // Drive the upstream async iterator inside an IIFE so the returned
44
+ // stream is populated asynchronously.
45
+ void (async () => {
46
+ const output: AssistantMessage = {
47
+ role: 'assistant',
48
+ content: [],
49
+ api: model.api,
50
+ provider: model.provider,
51
+ model: model.id,
52
+ usage: {
53
+ input: 0,
54
+ output: 0,
55
+ cacheRead: 0,
56
+ cacheWrite: 0,
57
+ totalTokens: 0,
58
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
59
+ },
60
+ stopReason: 'stop',
61
+ timestamp: Date.now(),
62
+ };
63
+
64
+ // Block-tracking state. Cognition's wire format has no
65
+ // `tool_call_end` event, so the end of a tool call is implicit:
66
+ // a new `tool_call_start` or stream `finish` closes the prior call.
67
+ let textBlockOpen = false;
68
+ let thinkingBlockOpen = false;
69
+ let currentToolCallIndex = -1;
70
+ let partialJson = '';
71
+ let currentToolCallId = '';
72
+ let currentToolCallName = '';
73
+
74
+ try {
75
+ const apiKey = options?.apiKey;
76
+ if (!apiKey) throw new Error('No Devin API key. Run /login devin');
77
+
78
+ const { messages, tools } = mapContextToChat(context);
79
+ stream.push({ type: 'start', partial: output });
80
+
81
+ for await (const ev of streamChatEvents({
82
+ apiKey,
83
+ modelUid: model.id,
84
+ messages,
85
+ tools: tools.length > 0 ? tools : undefined,
86
+ signal: options?.signal,
87
+ completionOpts: {
88
+ maxOutputTokens: options?.maxTokens,
89
+ },
90
+ })) {
91
+ handleEvent(ev);
92
+ }
93
+
94
+ // Safety: close any still-open blocks at stream end.
95
+ closeTextBlock();
96
+ closeThinkingBlock();
97
+ if (currentToolCallIndex >= 0) {
98
+ closeToolCall(
99
+ stream,
100
+ output,
101
+ currentToolCallIndex,
102
+ partialJson,
103
+ currentToolCallId,
104
+ currentToolCallName,
105
+ );
106
+ currentToolCallIndex = -1;
107
+ }
108
+
109
+ stream.push({
110
+ type: 'done',
111
+ reason: output.stopReason as 'stop' | 'length' | 'toolUse',
112
+ message: output,
113
+ });
114
+ stream.end();
115
+ } catch (error) {
116
+ output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
117
+ output.errorMessage = error instanceof Error ? error.message : String(error);
118
+ stream.push({
119
+ type: 'error',
120
+ reason: output.stopReason as 'aborted' | 'error',
121
+ error: output,
122
+ });
123
+ stream.end();
124
+ }
125
+
126
+ /**
127
+ * Dispatch a single {@link CloudChatEvent} to the appropriate
128
+ * pi event(s), mutating `output` and the block-tracking state.
129
+ */
130
+ function handleEvent(ev: CloudChatEvent): void {
131
+ switch (ev.kind) {
132
+ case 'text': {
133
+ // A text delta ends any open thinking block.
134
+ closeThinkingBlock();
135
+ if (!textBlockOpen) {
136
+ output.content.push({ type: 'text', text: '' });
137
+ stream.push({
138
+ type: 'text_start',
139
+ contentIndex: output.content.length - 1,
140
+ partial: output,
141
+ });
142
+ textBlockOpen = true;
143
+ }
144
+ const idx = output.content.length - 1;
145
+ const block = output.content[idx];
146
+ if (block.type === 'text') {
147
+ block.text += ev.text;
148
+ stream.push({
149
+ type: 'text_delta',
150
+ contentIndex: idx,
151
+ delta: ev.text,
152
+ partial: output,
153
+ });
154
+ }
155
+ break;
156
+ }
157
+
158
+ case 'reasoning': {
159
+ // A reasoning delta ends any open text block.
160
+ closeTextBlock();
161
+ if (!thinkingBlockOpen) {
162
+ output.content.push({ type: 'thinking', thinking: '' });
163
+ stream.push({
164
+ type: 'thinking_start',
165
+ contentIndex: output.content.length - 1,
166
+ partial: output,
167
+ });
168
+ thinkingBlockOpen = true;
169
+ }
170
+ const idx = output.content.length - 1;
171
+ const block = output.content[idx];
172
+ if (block.type === 'thinking') {
173
+ block.thinking += ev.text;
174
+ stream.push({
175
+ type: 'thinking_delta',
176
+ contentIndex: idx,
177
+ delta: ev.text,
178
+ partial: output,
179
+ });
180
+ }
181
+ break;
182
+ }
183
+
184
+ case 'tool_call_start': {
185
+ // A new tool call ends any open text/thinking block,
186
+ // and implicitly closes the previous tool call.
187
+ closeTextBlock();
188
+ closeThinkingBlock();
189
+ if (currentToolCallIndex >= 0) {
190
+ closeToolCall(
191
+ stream,
192
+ output,
193
+ currentToolCallIndex,
194
+ partialJson,
195
+ currentToolCallId,
196
+ currentToolCallName,
197
+ );
198
+ }
199
+ currentToolCallId = ev.id;
200
+ currentToolCallName = ev.name;
201
+ partialJson = '';
202
+ output.content.push({
203
+ type: 'toolCall',
204
+ id: ev.id,
205
+ name: ev.name,
206
+ arguments: {},
207
+ });
208
+ currentToolCallIndex = output.content.length - 1;
209
+ stream.push({
210
+ type: 'toolcall_start',
211
+ contentIndex: currentToolCallIndex,
212
+ partial: output,
213
+ });
214
+ break;
215
+ }
216
+
217
+ case 'tool_call_args': {
218
+ // Defensive: args without a preceding start should not
219
+ // happen on Cognition's wire format — ignore them.
220
+ if (currentToolCallIndex < 0) break;
221
+ partialJson += ev.argsDelta;
222
+ const block = output.content[currentToolCallIndex];
223
+ if (block.type === 'toolCall') {
224
+ try {
225
+ block.arguments = JSON.parse(partialJson);
226
+ } catch {
227
+ // Incomplete JSON — keep accumulating deltas.
228
+ }
229
+ }
230
+ stream.push({
231
+ type: 'toolcall_delta',
232
+ contentIndex: currentToolCallIndex,
233
+ delta: ev.argsDelta,
234
+ partial: output,
235
+ });
236
+ break;
237
+ }
238
+
239
+ case 'finish': {
240
+ closeTextBlock();
241
+ closeThinkingBlock();
242
+ if (currentToolCallIndex >= 0) {
243
+ closeToolCall(
244
+ stream,
245
+ output,
246
+ currentToolCallIndex,
247
+ partialJson,
248
+ currentToolCallId,
249
+ currentToolCallName,
250
+ );
251
+ currentToolCallIndex = -1;
252
+ }
253
+ output.stopReason =
254
+ ev.reason === 'tool_calls'
255
+ ? 'toolUse'
256
+ : ev.reason === 'length'
257
+ ? 'length'
258
+ : 'stop';
259
+ break;
260
+ }
261
+
262
+ case 'usage': {
263
+ output.usage.input = ev.promptTokens ?? 0;
264
+ output.usage.output = ev.completionTokens ?? 0;
265
+ output.usage.cacheRead = ev.cachedInputTokens ?? 0;
266
+ output.usage.cacheWrite = ev.cacheCreationInputTokens ?? 0;
267
+ output.usage.totalTokens =
268
+ ev.totalTokens ?? output.usage.input + output.usage.output;
269
+ // calculateCost mutates output.usage.cost in place.
270
+ calculateCost(model, output.usage);
271
+ break;
272
+ }
273
+ }
274
+ }
275
+
276
+ /** Close the open text block, if any, emitting `text_end`. */
277
+ function closeTextBlock(): void {
278
+ if (!textBlockOpen) return;
279
+ const idx = output.content.length - 1;
280
+ const block = output.content[idx];
281
+ if (block.type === 'text') {
282
+ stream.push({
283
+ type: 'text_end',
284
+ contentIndex: idx,
285
+ content: block.text,
286
+ partial: output,
287
+ });
288
+ }
289
+ textBlockOpen = false;
290
+ }
291
+
292
+ /** Close the open thinking block, if any, emitting `thinking_end`. */
293
+ function closeThinkingBlock(): void {
294
+ if (!thinkingBlockOpen) return;
295
+ const idx = output.content.length - 1;
296
+ const block = output.content[idx];
297
+ if (block.type === 'thinking') {
298
+ stream.push({
299
+ type: 'thinking_end',
300
+ contentIndex: idx,
301
+ content: block.thinking,
302
+ partial: output,
303
+ });
304
+ }
305
+ thinkingBlockOpen = false;
306
+ }
307
+ })();
308
+
309
+ return stream;
310
+ }
311
+
312
+ /**
313
+ * Close a tool-call block: attempt a final JSON parse of the accumulated
314
+ * args delta and emit `toolcall_end` with the resolved {@link ToolCall}.
315
+ *
316
+ * Defined at module scope so it is hoisted and usable from the IIFE
317
+ * closure without forward-reference concerns.
318
+ */
319
+ function closeToolCall(
320
+ stream: AssistantMessageEventStream,
321
+ output: AssistantMessage,
322
+ index: number,
323
+ partialJson: string,
324
+ id: string,
325
+ name: string,
326
+ ): void {
327
+ const block = output.content[index];
328
+ if (block.type !== 'toolCall') return;
329
+ // One last parse attempt in case the final delta completed the JSON.
330
+ try {
331
+ block.arguments = JSON.parse(partialJson);
332
+ } catch {
333
+ // Leave arguments as the last successfully-parsed value (or `{}`).
334
+ }
335
+ stream.push({
336
+ type: 'toolcall_end',
337
+ contentIndex: index,
338
+ toolCall: { type: 'toolCall', id, name, arguments: block.arguments },
339
+ partial: output,
340
+ });
341
+ }