@ai-accounts/ts-core 0.3.0-alpha.2 → 0.3.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.
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AiAccountsClient: () => AiAccountsClient,
24
+ PtySocket: () => PtySocket,
24
25
  WIRE_PROTOCOL_VERSION: () => WIRE_PROTOCOL_VERSION,
25
26
  createAccountWizard: () => createAccountWizard,
26
27
  createOnboardingFlow: () => createOnboardingFlow,
@@ -37,6 +38,7 @@ async function* parseSseLoginEvents(response) {
37
38
  const reader = response.body.getReader();
38
39
  const decoder = new TextDecoder();
39
40
  let buffer = "";
41
+ let consecutiveParseErrors = 0;
40
42
  try {
41
43
  while (true) {
42
44
  const { value, done } = await reader.read();
@@ -51,8 +53,25 @@ async function* parseSseLoginEvents(response) {
51
53
  if (!dataLine) continue;
52
54
  const payload = dataLine.slice(6);
53
55
  try {
54
- yield JSON.parse(payload);
56
+ const parsed = JSON.parse(payload);
57
+ if (parsed && typeof parsed === "object" && typeof parsed.type === "string") {
58
+ consecutiveParseErrors = 0;
59
+ yield parsed;
60
+ } else {
61
+ console.warn("[ai-accounts] SSE frame missing type field:", payload.slice(0, 200));
62
+ consecutiveParseErrors++;
63
+ }
55
64
  } catch {
65
+ console.warn("[ai-accounts] malformed SSE frame:", payload.slice(0, 200));
66
+ consecutiveParseErrors++;
67
+ }
68
+ if (consecutiveParseErrors >= 3) {
69
+ yield {
70
+ type: "failed",
71
+ code: "stream_corrupt",
72
+ message: "Multiple malformed SSE frames received"
73
+ };
74
+ return;
56
75
  }
57
76
  }
58
77
  }
@@ -61,6 +80,97 @@ async function* parseSseLoginEvents(response) {
61
80
  }
62
81
  }
63
82
 
83
+ // src/client/sse-parser.ts
84
+ async function* parseSseFrames(response) {
85
+ if (!response.body) {
86
+ throw new Error("[ai-accounts] SSE response has no body");
87
+ }
88
+ const reader = response.body.getReader();
89
+ const decoder = new TextDecoder();
90
+ let buf = "";
91
+ function* drain(flush) {
92
+ while (true) {
93
+ const boundary = findBoundary(buf);
94
+ if (boundary === null) {
95
+ if (!flush) return;
96
+ if (!buf.trim()) return;
97
+ const tail = buf;
98
+ buf = "";
99
+ const payload2 = extractDataPayload(tail);
100
+ if (payload2 !== null) yield payload2;
101
+ return;
102
+ }
103
+ const frame = buf.slice(0, boundary.index);
104
+ buf = buf.slice(boundary.index + boundary.length);
105
+ const payload = extractDataPayload(frame);
106
+ if (payload !== null) yield payload;
107
+ }
108
+ }
109
+ try {
110
+ while (true) {
111
+ const { done, value } = await reader.read();
112
+ if (done) {
113
+ buf += decoder.decode();
114
+ yield* drain(true);
115
+ return;
116
+ }
117
+ buf += decoder.decode(value, { stream: true });
118
+ yield* drain(false);
119
+ }
120
+ } finally {
121
+ try {
122
+ reader.releaseLock();
123
+ } catch {
124
+ }
125
+ }
126
+ }
127
+ function findBoundary(buf) {
128
+ let best = null;
129
+ const candidates = ["\r\n\r\n", "\n\n", "\r\r"];
130
+ for (const sep of candidates) {
131
+ const i = buf.indexOf(sep);
132
+ if (i === -1) continue;
133
+ if (!best || i < best.index) best = { index: i, length: sep.length };
134
+ }
135
+ return best;
136
+ }
137
+ function extractDataPayload(frame) {
138
+ const dataLines = [];
139
+ for (const rawLine of frame.split(/\r?\n/)) {
140
+ if (!rawLine.startsWith("data:")) continue;
141
+ const rest = rawLine.slice(5);
142
+ dataLines.push(rest.startsWith(" ") ? rest.slice(1) : rest);
143
+ }
144
+ if (dataLines.length === 0) return null;
145
+ return dataLines.join("\n");
146
+ }
147
+
148
+ // src/client/chat-stream.ts
149
+ async function* parseSseChatEvents(response) {
150
+ for await (const payload of parseSseFrames(response)) {
151
+ const trimmed = payload.trim();
152
+ if (!trimmed) continue;
153
+ try {
154
+ yield JSON.parse(trimmed);
155
+ } catch {
156
+ console.warn("[ai-accounts] malformed SSE chat frame dropped:", trimmed.slice(0, 200));
157
+ }
158
+ }
159
+ }
160
+
161
+ // src/client/smart-chat-stream.ts
162
+ async function* parseSseSmartChatEvents(response) {
163
+ for await (const payload of parseSseFrames(response)) {
164
+ const trimmed = payload.trim();
165
+ if (!trimmed) continue;
166
+ try {
167
+ yield JSON.parse(trimmed);
168
+ } catch {
169
+ console.warn("[ai-accounts] malformed smart chat SSE frame dropped:", trimmed.slice(0, 200));
170
+ }
171
+ }
172
+ }
173
+
64
174
  // src/client/index.ts
65
175
  async function toError(r) {
66
176
  let code = "http_error";
@@ -296,6 +406,126 @@ var AiAccountsClient = class {
296
406
  if (!r.ok) throw await toError(r);
297
407
  return await r.json();
298
408
  }
409
+ // --- CLIProxyAPI Server Lifecycle ---
410
+ async cliproxyServerStart(port = 8317, apiKey = "not-needed") {
411
+ const r = await this._fetch(`${this.baseUrl}/api/v1/cliproxy/server/start`, {
412
+ method: "POST",
413
+ headers: this.headers(),
414
+ body: JSON.stringify({ port, api_key: apiKey })
415
+ });
416
+ if (!r.ok) throw await toError(r);
417
+ return await r.json();
418
+ }
419
+ async cliproxyServerStop() {
420
+ const r = await this._fetch(`${this.baseUrl}/api/v1/cliproxy/server/stop`, {
421
+ method: "POST",
422
+ headers: this.headers()
423
+ });
424
+ if (!r.ok) throw await toError(r);
425
+ return await r.json();
426
+ }
427
+ async cliproxyServerStatus() {
428
+ const r = await this._fetch(`${this.baseUrl}/api/v1/cliproxy/server/status`, {
429
+ headers: this.headers()
430
+ });
431
+ if (!r.ok) throw await toError(r);
432
+ return await r.json();
433
+ }
434
+ // --- Conversations / Chat ---
435
+ async createConversation(input) {
436
+ const r = await this._fetch(`${this.baseUrl}/api/v1/conversations/`, {
437
+ method: "POST",
438
+ headers: this.headers(),
439
+ body: JSON.stringify(input)
440
+ });
441
+ if (!r.ok) throw await toError(r);
442
+ return await r.json();
443
+ }
444
+ async listConversations(backendId) {
445
+ const qs = backendId ? `?backend_id=${encodeURIComponent(backendId)}` : "";
446
+ const r = await this._fetch(`${this.baseUrl}/api/v1/conversations/${qs}`, { headers: this.headers() });
447
+ if (!r.ok) throw await toError(r);
448
+ return await r.json();
449
+ }
450
+ async getConversation(id) {
451
+ const r = await this._fetch(`${this.baseUrl}/api/v1/conversations/${encodeURIComponent(id)}`, { headers: this.headers() });
452
+ if (!r.ok) throw await toError(r);
453
+ return await r.json();
454
+ }
455
+ async *streamChat(sessionId, content) {
456
+ const url = `${this.baseUrl}/api/v1/conversations/${encodeURIComponent(sessionId)}/messages`;
457
+ const headers = { ...this.headers(), Accept: "text/event-stream" };
458
+ const r = await this._fetch(url, { method: "POST", headers, body: JSON.stringify({ content }) });
459
+ if (!r.ok) throw await toError(r);
460
+ yield* parseSseChatEvents(r);
461
+ }
462
+ // --- Scheduler ---
463
+ async getSchedulerHealth() {
464
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/health`, { headers: this.headers() });
465
+ if (!r.ok) throw await toError(r);
466
+ return await r.json();
467
+ }
468
+ async getAccountHealth(id) {
469
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/health/${encodeURIComponent(id)}`, { headers: this.headers() });
470
+ if (!r.ok) throw await toError(r);
471
+ return await r.json();
472
+ }
473
+ async schedulerPick(kind) {
474
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/pick`, {
475
+ method: "POST",
476
+ headers: this.headers(),
477
+ body: JSON.stringify(kind ? { kind } : {})
478
+ });
479
+ if (r.status === 204) return null;
480
+ if (!r.ok) throw await toError(r);
481
+ return await r.json();
482
+ }
483
+ async getChain() {
484
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/chain`, { headers: this.headers() });
485
+ if (!r.ok) throw await toError(r);
486
+ return await r.json();
487
+ }
488
+ async setChain(entries) {
489
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/chain`, {
490
+ method: "PUT",
491
+ headers: this.headers(),
492
+ body: JSON.stringify({ entries })
493
+ });
494
+ if (!r.ok) throw await toError(r);
495
+ }
496
+ async markRateLimited(backendId, seconds, reason) {
497
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/mark-limited`, {
498
+ method: "POST",
499
+ headers: this.headers(),
500
+ body: JSON.stringify({ backend_id: backendId, cooldown_seconds: seconds, reason })
501
+ });
502
+ if (!r.ok) throw await toError(r);
503
+ }
504
+ // --- Smart Chat ---
505
+ async *sendChat(request, opts = {}) {
506
+ const url = `${this.baseUrl}/api/v1/chat/send`;
507
+ const headers = {
508
+ ...this.headers(),
509
+ Accept: "text/event-stream"
510
+ };
511
+ if (opts.lastEventId && opts.lastEventId > 0) {
512
+ headers["Last-Event-ID"] = String(opts.lastEventId);
513
+ }
514
+ const r = await this._fetch(url, {
515
+ method: "POST",
516
+ headers,
517
+ body: JSON.stringify(request),
518
+ ...opts.signal ? { signal: opts.signal } : {}
519
+ });
520
+ if (!r.ok) throw await toError(r);
521
+ yield* parseSseSmartChatEvents(r);
522
+ }
523
+ async createChatSession(backendId, model) {
524
+ return this.createConversation({ backend_id: backendId, model });
525
+ }
526
+ async listChatSessions(backendId) {
527
+ return this.listConversations(backendId);
528
+ }
299
529
  async postAction(id, action, body) {
300
530
  const r = await this._fetch(
301
531
  `${this.baseUrl}/api/v1/backends/${encodeURIComponent(id)}/${action}`,
@@ -322,6 +552,46 @@ var AiAccountsClient = class {
322
552
  }
323
553
  };
324
554
 
555
+ // src/client/pty-socket.ts
556
+ var PtySocket = class {
557
+ ws = null;
558
+ opts;
559
+ closed = false;
560
+ constructor(opts) {
561
+ this.opts = opts;
562
+ this.connect();
563
+ }
564
+ connect() {
565
+ if (this.closed) return;
566
+ this.ws = new WebSocket(this.opts.url);
567
+ this.ws.binaryType = "arraybuffer";
568
+ this.ws.onmessage = (event) => {
569
+ if (event.data instanceof ArrayBuffer) {
570
+ this.opts.onData(new Uint8Array(event.data));
571
+ }
572
+ };
573
+ this.ws.onclose = () => {
574
+ if (!this.closed && this.opts.reconnectMs) {
575
+ setTimeout(() => this.connect(), this.opts.reconnectMs);
576
+ }
577
+ this.opts.onClose?.();
578
+ };
579
+ this.ws.onerror = (e) => {
580
+ this.opts.onError?.(e);
581
+ };
582
+ }
583
+ send(data) {
584
+ if (this.ws?.readyState === WebSocket.OPEN) {
585
+ this.ws.send(data);
586
+ }
587
+ }
588
+ close() {
589
+ this.closed = true;
590
+ this.ws?.close();
591
+ this.ws = null;
592
+ }
593
+ };
594
+
325
595
  // src/machines/accountWizard.ts
326
596
  function createAccountWizard(opts) {
327
597
  const listeners = /* @__PURE__ */ new Set();
@@ -622,6 +892,7 @@ var version = "0.0.0";
622
892
  // Annotate the CommonJS export names for ESM import in node:
623
893
  0 && (module.exports = {
624
894
  AiAccountsClient,
895
+ PtySocket,
625
896
  WIRE_PROTOCOL_VERSION,
626
897
  createAccountWizard,
627
898
  createOnboardingFlow,
package/dist/index.d.cts CHANGED
@@ -73,6 +73,17 @@ type TextPrompt = {
73
73
  prompt: string;
74
74
  hidden: boolean;
75
75
  };
76
+ type MenuOptionDTO = {
77
+ number: number;
78
+ label: string;
79
+ description?: string | null;
80
+ };
81
+ type MenuPrompt = {
82
+ type: 'menu_prompt';
83
+ prompt_id: string;
84
+ prompt: string;
85
+ options: MenuOptionDTO[];
86
+ };
76
87
  type StdoutChunk = {
77
88
  type: 'stdout';
78
89
  text: string;
@@ -92,13 +103,94 @@ type LoginFailed = {
92
103
  code: string;
93
104
  message: string;
94
105
  };
95
- type LoginEvent = UrlPrompt | TextPrompt | StdoutChunk | ProgressUpdate | LoginComplete | LoginFailed;
106
+ type LoginEvent = UrlPrompt | TextPrompt | MenuPrompt | StdoutChunk | ProgressUpdate | LoginComplete | LoginFailed;
96
107
  type PromptAnswer = {
97
108
  prompt_id: string;
98
109
  answer: string;
99
110
  };
100
111
  type LoginFlowKind = 'api_key' | 'oauth_device' | 'cli_browser';
101
112
 
113
+ interface BackendResponse {
114
+ backend: string;
115
+ content: string;
116
+ status: 'streaming' | 'complete' | 'error' | 'timeout';
117
+ error?: string;
118
+ }
119
+ interface SynthesisState {
120
+ status: 'waiting' | 'streaming' | 'complete' | 'error';
121
+ content: string;
122
+ primaryBackend: string;
123
+ backendsCollected: string[];
124
+ error?: string;
125
+ }
126
+ interface BackendOption {
127
+ kind: string;
128
+ displayName: string;
129
+ accounts: string[];
130
+ models: string[];
131
+ }
132
+ type ProcessGroupType = 'tool_call' | 'reasoning' | 'code_execution';
133
+ interface ToolCallDelta {
134
+ id: string;
135
+ name?: string;
136
+ arguments?: string;
137
+ group_type?: ProcessGroupType;
138
+ }
139
+ type _WithSeq<T> = T & {
140
+ _seq?: number;
141
+ };
142
+ type SmartChatEvent = _WithSeq<{
143
+ kind: 'token';
144
+ payload: string;
145
+ } | {
146
+ kind: 'done';
147
+ payload: Record<string, unknown>;
148
+ } | {
149
+ kind: 'error';
150
+ payload: string;
151
+ } | {
152
+ kind: 'backend_delta';
153
+ backend: string;
154
+ text: string;
155
+ } | {
156
+ kind: 'backend_complete';
157
+ backend: string;
158
+ } | {
159
+ kind: 'backend_error';
160
+ backend: string;
161
+ error: string;
162
+ } | {
163
+ kind: 'backend_timeout';
164
+ backend: string;
165
+ } | {
166
+ kind: 'synthesis_start';
167
+ primary_backend: string;
168
+ backends_collected: string[];
169
+ } | {
170
+ kind: 'synthesis_delta';
171
+ text: string;
172
+ } | {
173
+ kind: 'synthesis_complete';
174
+ } | {
175
+ kind: 'synthesis_error';
176
+ error: string;
177
+ } | {
178
+ kind: 'tool_call';
179
+ id: string;
180
+ name?: string;
181
+ arguments?: string;
182
+ group_type?: ProcessGroupType;
183
+ }>;
184
+ type ChatMode = 'single' | 'all' | 'compound';
185
+ interface SendChatRequest {
186
+ session_id: string;
187
+ content: string;
188
+ mode?: ChatMode;
189
+ backend_kind?: string;
190
+ account_id?: string;
191
+ model?: string;
192
+ }
193
+
102
194
  type InstallCheck = {
103
195
  command: string[];
104
196
  version_regex: string;
@@ -170,6 +262,61 @@ type CliproxyCallbackForwardResponse = {
170
262
  message: string;
171
263
  };
172
264
 
265
+ interface ChatSessionDTO {
266
+ id: string;
267
+ backend_id: string;
268
+ model: string | null;
269
+ title: string | null;
270
+ created_at: string;
271
+ }
272
+ interface ChatMessageDTO {
273
+ id: string;
274
+ role: 'system' | 'user' | 'assistant' | 'tool';
275
+ content: string;
276
+ created_at: string;
277
+ model: string | null;
278
+ tokens_in: number | null;
279
+ tokens_out: number | null;
280
+ }
281
+ interface ChatSessionDetailDTO extends ChatSessionDTO {
282
+ messages: ChatMessageDTO[];
283
+ }
284
+ interface ChatDelta {
285
+ kind: 'token' | 'done' | 'error';
286
+ text: string | null;
287
+ finish_reason: string | null;
288
+ model: string | null;
289
+ tokens_in: number | null;
290
+ tokens_out: number | null;
291
+ }
292
+
293
+ interface UsageWindowDTO {
294
+ window_type: string;
295
+ usage_percent: number;
296
+ resets_at: string | null;
297
+ tokens_used: number | null;
298
+ tokens_limit: number | null;
299
+ }
300
+ interface AccountHealthDTO {
301
+ backend_id: string;
302
+ kind: string;
303
+ windows: UsageWindowDTO[];
304
+ rate_limited_until: string | null;
305
+ rate_limit_reason: string | null;
306
+ last_used_at: string | null;
307
+ last_polled_at: string | null;
308
+ }
309
+ interface PickResultDTO {
310
+ backend_id: string;
311
+ kind: string;
312
+ isolation_dir: string;
313
+ retry_after: string | null;
314
+ }
315
+ interface FallbackChainEntryDTO {
316
+ backend_id: string;
317
+ priority: number;
318
+ }
319
+
173
320
  /**
174
321
  * This file was auto-generated by openapi-typescript.
175
322
  * Do not make direct changes to the file.
@@ -1121,6 +1268,7 @@ interface BackendDTO {
1121
1268
  display_name: string;
1122
1269
  status: string;
1123
1270
  config: Record<string, unknown>;
1271
+ config_dir: string | null;
1124
1272
  last_error: string | null;
1125
1273
  }
1126
1274
  interface DetectResultDTO {
@@ -1204,6 +1352,50 @@ declare class AiAccountsClient {
1204
1352
  cliproxyInstall(): Promise<CliproxyInstallResult>;
1205
1353
  cliproxyLoginBegin(backendKind: string, configDir?: string): Promise<CliproxyLoginBeginResponse>;
1206
1354
  cliproxyCallbackForward(callbackUrl: string): Promise<CliproxyCallbackForwardResponse>;
1355
+ cliproxyServerStart(port?: number, apiKey?: string): Promise<{
1356
+ status: string;
1357
+ port: number;
1358
+ pid: number | null;
1359
+ message: string;
1360
+ }>;
1361
+ cliproxyServerStop(): Promise<{
1362
+ status: string;
1363
+ message: string;
1364
+ }>;
1365
+ cliproxyServerStatus(): Promise<{
1366
+ installed: boolean;
1367
+ running: boolean;
1368
+ port: number;
1369
+ version: string | null;
1370
+ }>;
1371
+ createConversation(input: {
1372
+ backend_id: string;
1373
+ model: string;
1374
+ title?: string;
1375
+ }): Promise<ChatSessionDTO>;
1376
+ listConversations(backendId?: string): Promise<{
1377
+ items: ChatSessionDTO[];
1378
+ }>;
1379
+ getConversation(id: string): Promise<ChatSessionDetailDTO>;
1380
+ streamChat(sessionId: string, content: string): AsyncIterable<ChatDelta>;
1381
+ getSchedulerHealth(): Promise<{
1382
+ items: AccountHealthDTO[];
1383
+ }>;
1384
+ getAccountHealth(id: string): Promise<AccountHealthDTO>;
1385
+ schedulerPick(kind?: string): Promise<PickResultDTO | null>;
1386
+ getChain(): Promise<{
1387
+ entries: FallbackChainEntryDTO[];
1388
+ }>;
1389
+ setChain(entries: FallbackChainEntryDTO[]): Promise<void>;
1390
+ markRateLimited(backendId: string, seconds: number, reason: string): Promise<void>;
1391
+ sendChat(request: SendChatRequest, opts?: {
1392
+ signal?: AbortSignal;
1393
+ lastEventId?: number;
1394
+ }): AsyncIterable<SmartChatEvent>;
1395
+ createChatSession(backendId: string, model: string): Promise<ChatSessionDTO>;
1396
+ listChatSessions(backendId?: string): Promise<{
1397
+ items: ChatSessionDTO[];
1398
+ }>;
1207
1399
  private postAction;
1208
1400
  private onboardingAction;
1209
1401
  }
@@ -1231,7 +1423,7 @@ type AiAccountsEvent = {
1231
1423
  } | {
1232
1424
  type: 'login.prompt';
1233
1425
  sessionId: string;
1234
- promptKind: 'url' | 'text';
1426
+ promptKind: 'url' | 'text' | 'menu';
1235
1427
  } | {
1236
1428
  type: 'login.completed';
1237
1429
  sessionId: string;
@@ -1248,6 +1440,33 @@ type AiAccountsEvent = {
1248
1440
  };
1249
1441
  type AiAccountsEventHandler = (event: AiAccountsEvent) => void;
1250
1442
 
1443
+ interface PtySessionDTO {
1444
+ session_id: string;
1445
+ }
1446
+ interface PtySpawnRequest {
1447
+ backend_id: string;
1448
+ command: string[];
1449
+ cols?: number;
1450
+ rows?: number;
1451
+ }
1452
+
1453
+ interface PtySocketOptions {
1454
+ url: string;
1455
+ onData: (data: Uint8Array) => void;
1456
+ onClose?: () => void;
1457
+ onError?: (error: Event) => void;
1458
+ reconnectMs?: number;
1459
+ }
1460
+ declare class PtySocket {
1461
+ private ws;
1462
+ private readonly opts;
1463
+ private closed;
1464
+ constructor(opts: PtySocketOptions);
1465
+ private connect;
1466
+ send(data: Uint8Array): void;
1467
+ close(): void;
1468
+ }
1469
+
1251
1470
  type WizardState = 'idle' | 'picking_kind' | 'detecting' | 'entering_credential' | 'validating' | 'done' | 'error';
1252
1471
  interface AccountWizard {
1253
1472
  readonly state: WizardState;
@@ -1297,4 +1516,4 @@ declare function createOnboardingFlow(opts: CreateOnboardingFlowOptions): Onboar
1297
1516
 
1298
1517
  declare const version = "0.0.0";
1299
1518
 
1300
- export { type AccountWizard, type paths as AiAccountsApiPaths, AiAccountsClient, type AiAccountsEvent, type AiAccountsEventHandler, type ApiError, type BackendDTO, type BackendMetadata, type ChatDoneEvent, type ChatTokenEvent, type ChatToolCallEvent, type ClientOptions, type CliproxyCallbackForwardResponse, type CliproxyInstallResult, type CliproxyLoginBeginResponse, type CliproxyStatus, type CreateAccountWizardOptions, type CreateOnboardingFlowOptions, type DetectResultDTO, type DetectResultsDTO, type ErrorEvent, type InputSpec, type InstallCheck, type InstallResult, type LoginComplete, type LoginEvent, type LoginFailed, type LoginFlowKind, type LoginFlowSpec, type LoginResponseDTO, type OAuthDeviceLoginDTO, type OnboardingFlowMachine, type OnboardingMachineState, type OnboardingStateDTO, type PlanOption, type ProgressUpdate, type PromptAnswer, type PtyExitEvent, type PtyOutputEvent, type PtyResizeEvent, type SessionEndEvent, type SessionStartEvent, type StdoutChunk, type TextPrompt, type UrlPrompt, WIRE_PROTOCOL_VERSION, type WireEvent, type WizardState, createAccountWizard, createOnboardingFlow, version };
1519
+ export { type AccountHealthDTO, type AccountWizard, type paths as AiAccountsApiPaths, AiAccountsClient, type AiAccountsEvent, type AiAccountsEventHandler, type ApiError, type BackendDTO, type BackendMetadata, type BackendOption, type BackendResponse, type ChatDelta, type ChatDoneEvent, type ChatMessageDTO, type ChatMode, type ChatSessionDTO, type ChatSessionDetailDTO, type ChatTokenEvent, type ChatToolCallEvent, type ClientOptions, type CliproxyCallbackForwardResponse, type CliproxyInstallResult, type CliproxyLoginBeginResponse, type CliproxyStatus, type CreateAccountWizardOptions, type CreateOnboardingFlowOptions, type DetectResultDTO, type DetectResultsDTO, type ErrorEvent, type FallbackChainEntryDTO, type InputSpec, type InstallCheck, type InstallResult, type LoginComplete, type LoginEvent, type LoginFailed, type LoginFlowKind, type LoginFlowSpec, type LoginResponseDTO, type MenuOptionDTO, type MenuPrompt, type OAuthDeviceLoginDTO, type OnboardingFlowMachine, type OnboardingMachineState, type OnboardingStateDTO, type PickResultDTO, type PlanOption, type ProcessGroupType, type ProgressUpdate, type PromptAnswer, type PtyExitEvent, type PtyOutputEvent, type PtyResizeEvent, type PtySessionDTO, PtySocket, type PtySocketOptions, type PtySpawnRequest, type SendChatRequest, type SessionEndEvent, type SessionStartEvent, type SmartChatEvent, type StdoutChunk, type SynthesisState, type TextPrompt, type ToolCallDelta, type UrlPrompt, type UsageWindowDTO, WIRE_PROTOCOL_VERSION, type WireEvent, type WizardState, createAccountWizard, createOnboardingFlow, version };
package/dist/index.d.ts CHANGED
@@ -73,6 +73,17 @@ type TextPrompt = {
73
73
  prompt: string;
74
74
  hidden: boolean;
75
75
  };
76
+ type MenuOptionDTO = {
77
+ number: number;
78
+ label: string;
79
+ description?: string | null;
80
+ };
81
+ type MenuPrompt = {
82
+ type: 'menu_prompt';
83
+ prompt_id: string;
84
+ prompt: string;
85
+ options: MenuOptionDTO[];
86
+ };
76
87
  type StdoutChunk = {
77
88
  type: 'stdout';
78
89
  text: string;
@@ -92,13 +103,94 @@ type LoginFailed = {
92
103
  code: string;
93
104
  message: string;
94
105
  };
95
- type LoginEvent = UrlPrompt | TextPrompt | StdoutChunk | ProgressUpdate | LoginComplete | LoginFailed;
106
+ type LoginEvent = UrlPrompt | TextPrompt | MenuPrompt | StdoutChunk | ProgressUpdate | LoginComplete | LoginFailed;
96
107
  type PromptAnswer = {
97
108
  prompt_id: string;
98
109
  answer: string;
99
110
  };
100
111
  type LoginFlowKind = 'api_key' | 'oauth_device' | 'cli_browser';
101
112
 
113
+ interface BackendResponse {
114
+ backend: string;
115
+ content: string;
116
+ status: 'streaming' | 'complete' | 'error' | 'timeout';
117
+ error?: string;
118
+ }
119
+ interface SynthesisState {
120
+ status: 'waiting' | 'streaming' | 'complete' | 'error';
121
+ content: string;
122
+ primaryBackend: string;
123
+ backendsCollected: string[];
124
+ error?: string;
125
+ }
126
+ interface BackendOption {
127
+ kind: string;
128
+ displayName: string;
129
+ accounts: string[];
130
+ models: string[];
131
+ }
132
+ type ProcessGroupType = 'tool_call' | 'reasoning' | 'code_execution';
133
+ interface ToolCallDelta {
134
+ id: string;
135
+ name?: string;
136
+ arguments?: string;
137
+ group_type?: ProcessGroupType;
138
+ }
139
+ type _WithSeq<T> = T & {
140
+ _seq?: number;
141
+ };
142
+ type SmartChatEvent = _WithSeq<{
143
+ kind: 'token';
144
+ payload: string;
145
+ } | {
146
+ kind: 'done';
147
+ payload: Record<string, unknown>;
148
+ } | {
149
+ kind: 'error';
150
+ payload: string;
151
+ } | {
152
+ kind: 'backend_delta';
153
+ backend: string;
154
+ text: string;
155
+ } | {
156
+ kind: 'backend_complete';
157
+ backend: string;
158
+ } | {
159
+ kind: 'backend_error';
160
+ backend: string;
161
+ error: string;
162
+ } | {
163
+ kind: 'backend_timeout';
164
+ backend: string;
165
+ } | {
166
+ kind: 'synthesis_start';
167
+ primary_backend: string;
168
+ backends_collected: string[];
169
+ } | {
170
+ kind: 'synthesis_delta';
171
+ text: string;
172
+ } | {
173
+ kind: 'synthesis_complete';
174
+ } | {
175
+ kind: 'synthesis_error';
176
+ error: string;
177
+ } | {
178
+ kind: 'tool_call';
179
+ id: string;
180
+ name?: string;
181
+ arguments?: string;
182
+ group_type?: ProcessGroupType;
183
+ }>;
184
+ type ChatMode = 'single' | 'all' | 'compound';
185
+ interface SendChatRequest {
186
+ session_id: string;
187
+ content: string;
188
+ mode?: ChatMode;
189
+ backend_kind?: string;
190
+ account_id?: string;
191
+ model?: string;
192
+ }
193
+
102
194
  type InstallCheck = {
103
195
  command: string[];
104
196
  version_regex: string;
@@ -170,6 +262,61 @@ type CliproxyCallbackForwardResponse = {
170
262
  message: string;
171
263
  };
172
264
 
265
+ interface ChatSessionDTO {
266
+ id: string;
267
+ backend_id: string;
268
+ model: string | null;
269
+ title: string | null;
270
+ created_at: string;
271
+ }
272
+ interface ChatMessageDTO {
273
+ id: string;
274
+ role: 'system' | 'user' | 'assistant' | 'tool';
275
+ content: string;
276
+ created_at: string;
277
+ model: string | null;
278
+ tokens_in: number | null;
279
+ tokens_out: number | null;
280
+ }
281
+ interface ChatSessionDetailDTO extends ChatSessionDTO {
282
+ messages: ChatMessageDTO[];
283
+ }
284
+ interface ChatDelta {
285
+ kind: 'token' | 'done' | 'error';
286
+ text: string | null;
287
+ finish_reason: string | null;
288
+ model: string | null;
289
+ tokens_in: number | null;
290
+ tokens_out: number | null;
291
+ }
292
+
293
+ interface UsageWindowDTO {
294
+ window_type: string;
295
+ usage_percent: number;
296
+ resets_at: string | null;
297
+ tokens_used: number | null;
298
+ tokens_limit: number | null;
299
+ }
300
+ interface AccountHealthDTO {
301
+ backend_id: string;
302
+ kind: string;
303
+ windows: UsageWindowDTO[];
304
+ rate_limited_until: string | null;
305
+ rate_limit_reason: string | null;
306
+ last_used_at: string | null;
307
+ last_polled_at: string | null;
308
+ }
309
+ interface PickResultDTO {
310
+ backend_id: string;
311
+ kind: string;
312
+ isolation_dir: string;
313
+ retry_after: string | null;
314
+ }
315
+ interface FallbackChainEntryDTO {
316
+ backend_id: string;
317
+ priority: number;
318
+ }
319
+
173
320
  /**
174
321
  * This file was auto-generated by openapi-typescript.
175
322
  * Do not make direct changes to the file.
@@ -1121,6 +1268,7 @@ interface BackendDTO {
1121
1268
  display_name: string;
1122
1269
  status: string;
1123
1270
  config: Record<string, unknown>;
1271
+ config_dir: string | null;
1124
1272
  last_error: string | null;
1125
1273
  }
1126
1274
  interface DetectResultDTO {
@@ -1204,6 +1352,50 @@ declare class AiAccountsClient {
1204
1352
  cliproxyInstall(): Promise<CliproxyInstallResult>;
1205
1353
  cliproxyLoginBegin(backendKind: string, configDir?: string): Promise<CliproxyLoginBeginResponse>;
1206
1354
  cliproxyCallbackForward(callbackUrl: string): Promise<CliproxyCallbackForwardResponse>;
1355
+ cliproxyServerStart(port?: number, apiKey?: string): Promise<{
1356
+ status: string;
1357
+ port: number;
1358
+ pid: number | null;
1359
+ message: string;
1360
+ }>;
1361
+ cliproxyServerStop(): Promise<{
1362
+ status: string;
1363
+ message: string;
1364
+ }>;
1365
+ cliproxyServerStatus(): Promise<{
1366
+ installed: boolean;
1367
+ running: boolean;
1368
+ port: number;
1369
+ version: string | null;
1370
+ }>;
1371
+ createConversation(input: {
1372
+ backend_id: string;
1373
+ model: string;
1374
+ title?: string;
1375
+ }): Promise<ChatSessionDTO>;
1376
+ listConversations(backendId?: string): Promise<{
1377
+ items: ChatSessionDTO[];
1378
+ }>;
1379
+ getConversation(id: string): Promise<ChatSessionDetailDTO>;
1380
+ streamChat(sessionId: string, content: string): AsyncIterable<ChatDelta>;
1381
+ getSchedulerHealth(): Promise<{
1382
+ items: AccountHealthDTO[];
1383
+ }>;
1384
+ getAccountHealth(id: string): Promise<AccountHealthDTO>;
1385
+ schedulerPick(kind?: string): Promise<PickResultDTO | null>;
1386
+ getChain(): Promise<{
1387
+ entries: FallbackChainEntryDTO[];
1388
+ }>;
1389
+ setChain(entries: FallbackChainEntryDTO[]): Promise<void>;
1390
+ markRateLimited(backendId: string, seconds: number, reason: string): Promise<void>;
1391
+ sendChat(request: SendChatRequest, opts?: {
1392
+ signal?: AbortSignal;
1393
+ lastEventId?: number;
1394
+ }): AsyncIterable<SmartChatEvent>;
1395
+ createChatSession(backendId: string, model: string): Promise<ChatSessionDTO>;
1396
+ listChatSessions(backendId?: string): Promise<{
1397
+ items: ChatSessionDTO[];
1398
+ }>;
1207
1399
  private postAction;
1208
1400
  private onboardingAction;
1209
1401
  }
@@ -1231,7 +1423,7 @@ type AiAccountsEvent = {
1231
1423
  } | {
1232
1424
  type: 'login.prompt';
1233
1425
  sessionId: string;
1234
- promptKind: 'url' | 'text';
1426
+ promptKind: 'url' | 'text' | 'menu';
1235
1427
  } | {
1236
1428
  type: 'login.completed';
1237
1429
  sessionId: string;
@@ -1248,6 +1440,33 @@ type AiAccountsEvent = {
1248
1440
  };
1249
1441
  type AiAccountsEventHandler = (event: AiAccountsEvent) => void;
1250
1442
 
1443
+ interface PtySessionDTO {
1444
+ session_id: string;
1445
+ }
1446
+ interface PtySpawnRequest {
1447
+ backend_id: string;
1448
+ command: string[];
1449
+ cols?: number;
1450
+ rows?: number;
1451
+ }
1452
+
1453
+ interface PtySocketOptions {
1454
+ url: string;
1455
+ onData: (data: Uint8Array) => void;
1456
+ onClose?: () => void;
1457
+ onError?: (error: Event) => void;
1458
+ reconnectMs?: number;
1459
+ }
1460
+ declare class PtySocket {
1461
+ private ws;
1462
+ private readonly opts;
1463
+ private closed;
1464
+ constructor(opts: PtySocketOptions);
1465
+ private connect;
1466
+ send(data: Uint8Array): void;
1467
+ close(): void;
1468
+ }
1469
+
1251
1470
  type WizardState = 'idle' | 'picking_kind' | 'detecting' | 'entering_credential' | 'validating' | 'done' | 'error';
1252
1471
  interface AccountWizard {
1253
1472
  readonly state: WizardState;
@@ -1297,4 +1516,4 @@ declare function createOnboardingFlow(opts: CreateOnboardingFlowOptions): Onboar
1297
1516
 
1298
1517
  declare const version = "0.0.0";
1299
1518
 
1300
- export { type AccountWizard, type paths as AiAccountsApiPaths, AiAccountsClient, type AiAccountsEvent, type AiAccountsEventHandler, type ApiError, type BackendDTO, type BackendMetadata, type ChatDoneEvent, type ChatTokenEvent, type ChatToolCallEvent, type ClientOptions, type CliproxyCallbackForwardResponse, type CliproxyInstallResult, type CliproxyLoginBeginResponse, type CliproxyStatus, type CreateAccountWizardOptions, type CreateOnboardingFlowOptions, type DetectResultDTO, type DetectResultsDTO, type ErrorEvent, type InputSpec, type InstallCheck, type InstallResult, type LoginComplete, type LoginEvent, type LoginFailed, type LoginFlowKind, type LoginFlowSpec, type LoginResponseDTO, type OAuthDeviceLoginDTO, type OnboardingFlowMachine, type OnboardingMachineState, type OnboardingStateDTO, type PlanOption, type ProgressUpdate, type PromptAnswer, type PtyExitEvent, type PtyOutputEvent, type PtyResizeEvent, type SessionEndEvent, type SessionStartEvent, type StdoutChunk, type TextPrompt, type UrlPrompt, WIRE_PROTOCOL_VERSION, type WireEvent, type WizardState, createAccountWizard, createOnboardingFlow, version };
1519
+ export { type AccountHealthDTO, type AccountWizard, type paths as AiAccountsApiPaths, AiAccountsClient, type AiAccountsEvent, type AiAccountsEventHandler, type ApiError, type BackendDTO, type BackendMetadata, type BackendOption, type BackendResponse, type ChatDelta, type ChatDoneEvent, type ChatMessageDTO, type ChatMode, type ChatSessionDTO, type ChatSessionDetailDTO, type ChatTokenEvent, type ChatToolCallEvent, type ClientOptions, type CliproxyCallbackForwardResponse, type CliproxyInstallResult, type CliproxyLoginBeginResponse, type CliproxyStatus, type CreateAccountWizardOptions, type CreateOnboardingFlowOptions, type DetectResultDTO, type DetectResultsDTO, type ErrorEvent, type FallbackChainEntryDTO, type InputSpec, type InstallCheck, type InstallResult, type LoginComplete, type LoginEvent, type LoginFailed, type LoginFlowKind, type LoginFlowSpec, type LoginResponseDTO, type MenuOptionDTO, type MenuPrompt, type OAuthDeviceLoginDTO, type OnboardingFlowMachine, type OnboardingMachineState, type OnboardingStateDTO, type PickResultDTO, type PlanOption, type ProcessGroupType, type ProgressUpdate, type PromptAnswer, type PtyExitEvent, type PtyOutputEvent, type PtyResizeEvent, type PtySessionDTO, PtySocket, type PtySocketOptions, type PtySpawnRequest, type SendChatRequest, type SessionEndEvent, type SessionStartEvent, type SmartChatEvent, type StdoutChunk, type SynthesisState, type TextPrompt, type ToolCallDelta, type UrlPrompt, type UsageWindowDTO, WIRE_PROTOCOL_VERSION, type WireEvent, type WizardState, createAccountWizard, createOnboardingFlow, version };
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ async function* parseSseLoginEvents(response) {
7
7
  const reader = response.body.getReader();
8
8
  const decoder = new TextDecoder();
9
9
  let buffer = "";
10
+ let consecutiveParseErrors = 0;
10
11
  try {
11
12
  while (true) {
12
13
  const { value, done } = await reader.read();
@@ -21,8 +22,25 @@ async function* parseSseLoginEvents(response) {
21
22
  if (!dataLine) continue;
22
23
  const payload = dataLine.slice(6);
23
24
  try {
24
- yield JSON.parse(payload);
25
+ const parsed = JSON.parse(payload);
26
+ if (parsed && typeof parsed === "object" && typeof parsed.type === "string") {
27
+ consecutiveParseErrors = 0;
28
+ yield parsed;
29
+ } else {
30
+ console.warn("[ai-accounts] SSE frame missing type field:", payload.slice(0, 200));
31
+ consecutiveParseErrors++;
32
+ }
25
33
  } catch {
34
+ console.warn("[ai-accounts] malformed SSE frame:", payload.slice(0, 200));
35
+ consecutiveParseErrors++;
36
+ }
37
+ if (consecutiveParseErrors >= 3) {
38
+ yield {
39
+ type: "failed",
40
+ code: "stream_corrupt",
41
+ message: "Multiple malformed SSE frames received"
42
+ };
43
+ return;
26
44
  }
27
45
  }
28
46
  }
@@ -31,6 +49,97 @@ async function* parseSseLoginEvents(response) {
31
49
  }
32
50
  }
33
51
 
52
+ // src/client/sse-parser.ts
53
+ async function* parseSseFrames(response) {
54
+ if (!response.body) {
55
+ throw new Error("[ai-accounts] SSE response has no body");
56
+ }
57
+ const reader = response.body.getReader();
58
+ const decoder = new TextDecoder();
59
+ let buf = "";
60
+ function* drain(flush) {
61
+ while (true) {
62
+ const boundary = findBoundary(buf);
63
+ if (boundary === null) {
64
+ if (!flush) return;
65
+ if (!buf.trim()) return;
66
+ const tail = buf;
67
+ buf = "";
68
+ const payload2 = extractDataPayload(tail);
69
+ if (payload2 !== null) yield payload2;
70
+ return;
71
+ }
72
+ const frame = buf.slice(0, boundary.index);
73
+ buf = buf.slice(boundary.index + boundary.length);
74
+ const payload = extractDataPayload(frame);
75
+ if (payload !== null) yield payload;
76
+ }
77
+ }
78
+ try {
79
+ while (true) {
80
+ const { done, value } = await reader.read();
81
+ if (done) {
82
+ buf += decoder.decode();
83
+ yield* drain(true);
84
+ return;
85
+ }
86
+ buf += decoder.decode(value, { stream: true });
87
+ yield* drain(false);
88
+ }
89
+ } finally {
90
+ try {
91
+ reader.releaseLock();
92
+ } catch {
93
+ }
94
+ }
95
+ }
96
+ function findBoundary(buf) {
97
+ let best = null;
98
+ const candidates = ["\r\n\r\n", "\n\n", "\r\r"];
99
+ for (const sep of candidates) {
100
+ const i = buf.indexOf(sep);
101
+ if (i === -1) continue;
102
+ if (!best || i < best.index) best = { index: i, length: sep.length };
103
+ }
104
+ return best;
105
+ }
106
+ function extractDataPayload(frame) {
107
+ const dataLines = [];
108
+ for (const rawLine of frame.split(/\r?\n/)) {
109
+ if (!rawLine.startsWith("data:")) continue;
110
+ const rest = rawLine.slice(5);
111
+ dataLines.push(rest.startsWith(" ") ? rest.slice(1) : rest);
112
+ }
113
+ if (dataLines.length === 0) return null;
114
+ return dataLines.join("\n");
115
+ }
116
+
117
+ // src/client/chat-stream.ts
118
+ async function* parseSseChatEvents(response) {
119
+ for await (const payload of parseSseFrames(response)) {
120
+ const trimmed = payload.trim();
121
+ if (!trimmed) continue;
122
+ try {
123
+ yield JSON.parse(trimmed);
124
+ } catch {
125
+ console.warn("[ai-accounts] malformed SSE chat frame dropped:", trimmed.slice(0, 200));
126
+ }
127
+ }
128
+ }
129
+
130
+ // src/client/smart-chat-stream.ts
131
+ async function* parseSseSmartChatEvents(response) {
132
+ for await (const payload of parseSseFrames(response)) {
133
+ const trimmed = payload.trim();
134
+ if (!trimmed) continue;
135
+ try {
136
+ yield JSON.parse(trimmed);
137
+ } catch {
138
+ console.warn("[ai-accounts] malformed smart chat SSE frame dropped:", trimmed.slice(0, 200));
139
+ }
140
+ }
141
+ }
142
+
34
143
  // src/client/index.ts
35
144
  async function toError(r) {
36
145
  let code = "http_error";
@@ -266,6 +375,126 @@ var AiAccountsClient = class {
266
375
  if (!r.ok) throw await toError(r);
267
376
  return await r.json();
268
377
  }
378
+ // --- CLIProxyAPI Server Lifecycle ---
379
+ async cliproxyServerStart(port = 8317, apiKey = "not-needed") {
380
+ const r = await this._fetch(`${this.baseUrl}/api/v1/cliproxy/server/start`, {
381
+ method: "POST",
382
+ headers: this.headers(),
383
+ body: JSON.stringify({ port, api_key: apiKey })
384
+ });
385
+ if (!r.ok) throw await toError(r);
386
+ return await r.json();
387
+ }
388
+ async cliproxyServerStop() {
389
+ const r = await this._fetch(`${this.baseUrl}/api/v1/cliproxy/server/stop`, {
390
+ method: "POST",
391
+ headers: this.headers()
392
+ });
393
+ if (!r.ok) throw await toError(r);
394
+ return await r.json();
395
+ }
396
+ async cliproxyServerStatus() {
397
+ const r = await this._fetch(`${this.baseUrl}/api/v1/cliproxy/server/status`, {
398
+ headers: this.headers()
399
+ });
400
+ if (!r.ok) throw await toError(r);
401
+ return await r.json();
402
+ }
403
+ // --- Conversations / Chat ---
404
+ async createConversation(input) {
405
+ const r = await this._fetch(`${this.baseUrl}/api/v1/conversations/`, {
406
+ method: "POST",
407
+ headers: this.headers(),
408
+ body: JSON.stringify(input)
409
+ });
410
+ if (!r.ok) throw await toError(r);
411
+ return await r.json();
412
+ }
413
+ async listConversations(backendId) {
414
+ const qs = backendId ? `?backend_id=${encodeURIComponent(backendId)}` : "";
415
+ const r = await this._fetch(`${this.baseUrl}/api/v1/conversations/${qs}`, { headers: this.headers() });
416
+ if (!r.ok) throw await toError(r);
417
+ return await r.json();
418
+ }
419
+ async getConversation(id) {
420
+ const r = await this._fetch(`${this.baseUrl}/api/v1/conversations/${encodeURIComponent(id)}`, { headers: this.headers() });
421
+ if (!r.ok) throw await toError(r);
422
+ return await r.json();
423
+ }
424
+ async *streamChat(sessionId, content) {
425
+ const url = `${this.baseUrl}/api/v1/conversations/${encodeURIComponent(sessionId)}/messages`;
426
+ const headers = { ...this.headers(), Accept: "text/event-stream" };
427
+ const r = await this._fetch(url, { method: "POST", headers, body: JSON.stringify({ content }) });
428
+ if (!r.ok) throw await toError(r);
429
+ yield* parseSseChatEvents(r);
430
+ }
431
+ // --- Scheduler ---
432
+ async getSchedulerHealth() {
433
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/health`, { headers: this.headers() });
434
+ if (!r.ok) throw await toError(r);
435
+ return await r.json();
436
+ }
437
+ async getAccountHealth(id) {
438
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/health/${encodeURIComponent(id)}`, { headers: this.headers() });
439
+ if (!r.ok) throw await toError(r);
440
+ return await r.json();
441
+ }
442
+ async schedulerPick(kind) {
443
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/pick`, {
444
+ method: "POST",
445
+ headers: this.headers(),
446
+ body: JSON.stringify(kind ? { kind } : {})
447
+ });
448
+ if (r.status === 204) return null;
449
+ if (!r.ok) throw await toError(r);
450
+ return await r.json();
451
+ }
452
+ async getChain() {
453
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/chain`, { headers: this.headers() });
454
+ if (!r.ok) throw await toError(r);
455
+ return await r.json();
456
+ }
457
+ async setChain(entries) {
458
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/chain`, {
459
+ method: "PUT",
460
+ headers: this.headers(),
461
+ body: JSON.stringify({ entries })
462
+ });
463
+ if (!r.ok) throw await toError(r);
464
+ }
465
+ async markRateLimited(backendId, seconds, reason) {
466
+ const r = await this._fetch(`${this.baseUrl}/api/v1/scheduler/mark-limited`, {
467
+ method: "POST",
468
+ headers: this.headers(),
469
+ body: JSON.stringify({ backend_id: backendId, cooldown_seconds: seconds, reason })
470
+ });
471
+ if (!r.ok) throw await toError(r);
472
+ }
473
+ // --- Smart Chat ---
474
+ async *sendChat(request, opts = {}) {
475
+ const url = `${this.baseUrl}/api/v1/chat/send`;
476
+ const headers = {
477
+ ...this.headers(),
478
+ Accept: "text/event-stream"
479
+ };
480
+ if (opts.lastEventId && opts.lastEventId > 0) {
481
+ headers["Last-Event-ID"] = String(opts.lastEventId);
482
+ }
483
+ const r = await this._fetch(url, {
484
+ method: "POST",
485
+ headers,
486
+ body: JSON.stringify(request),
487
+ ...opts.signal ? { signal: opts.signal } : {}
488
+ });
489
+ if (!r.ok) throw await toError(r);
490
+ yield* parseSseSmartChatEvents(r);
491
+ }
492
+ async createChatSession(backendId, model) {
493
+ return this.createConversation({ backend_id: backendId, model });
494
+ }
495
+ async listChatSessions(backendId) {
496
+ return this.listConversations(backendId);
497
+ }
269
498
  async postAction(id, action, body) {
270
499
  const r = await this._fetch(
271
500
  `${this.baseUrl}/api/v1/backends/${encodeURIComponent(id)}/${action}`,
@@ -292,6 +521,46 @@ var AiAccountsClient = class {
292
521
  }
293
522
  };
294
523
 
524
+ // src/client/pty-socket.ts
525
+ var PtySocket = class {
526
+ ws = null;
527
+ opts;
528
+ closed = false;
529
+ constructor(opts) {
530
+ this.opts = opts;
531
+ this.connect();
532
+ }
533
+ connect() {
534
+ if (this.closed) return;
535
+ this.ws = new WebSocket(this.opts.url);
536
+ this.ws.binaryType = "arraybuffer";
537
+ this.ws.onmessage = (event) => {
538
+ if (event.data instanceof ArrayBuffer) {
539
+ this.opts.onData(new Uint8Array(event.data));
540
+ }
541
+ };
542
+ this.ws.onclose = () => {
543
+ if (!this.closed && this.opts.reconnectMs) {
544
+ setTimeout(() => this.connect(), this.opts.reconnectMs);
545
+ }
546
+ this.opts.onClose?.();
547
+ };
548
+ this.ws.onerror = (e) => {
549
+ this.opts.onError?.(e);
550
+ };
551
+ }
552
+ send(data) {
553
+ if (this.ws?.readyState === WebSocket.OPEN) {
554
+ this.ws.send(data);
555
+ }
556
+ }
557
+ close() {
558
+ this.closed = true;
559
+ this.ws?.close();
560
+ this.ws = null;
561
+ }
562
+ };
563
+
295
564
  // src/machines/accountWizard.ts
296
565
  function createAccountWizard(opts) {
297
566
  const listeners = /* @__PURE__ */ new Set();
@@ -591,6 +860,7 @@ function createOnboardingFlow(opts) {
591
860
  var version = "0.0.0";
592
861
  export {
593
862
  AiAccountsClient,
863
+ PtySocket,
594
864
  WIRE_PROTOCOL_VERSION,
595
865
  createAccountWizard,
596
866
  createOnboardingFlow,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-accounts/ts-core",
3
- "version": "0.3.0-alpha.2",
3
+ "version": "0.3.1",
4
4
  "description": "Framework-agnostic TypeScript client and protocol for ai-accounts",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",