@starcite/sdk 0.0.3 → 0.0.5

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.d.ts CHANGED
@@ -1,48 +1,60 @@
1
1
  import { z } from 'zod';
2
2
 
3
- /**
4
- * Request payload for creating a session.
5
- */
6
- declare const CreateSessionInputSchema: z.ZodObject<{
7
- id: z.ZodOptional<z.ZodString>;
8
- title: z.ZodOptional<z.ZodString>;
9
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
10
- creator_principal: z.ZodOptional<z.ZodObject<{
11
- tenant_id: z.ZodString;
12
- id: z.ZodString;
13
- type: z.ZodUnion<[z.ZodLiteral<"user">, z.ZodLiteral<"agent">]>;
14
- }, "strip", z.ZodTypeAny, {
15
- type: "user" | "agent";
16
- tenant_id: string;
17
- id: string;
18
- }, {
19
- type: "user" | "agent";
20
- tenant_id: string;
21
- id: string;
22
- }>>;
3
+ declare const PrincipalTypeSchema: z.ZodEnum<["user", "agent"]>;
4
+ type PrincipalType = z.infer<typeof PrincipalTypeSchema>;
5
+ declare const SessionCreatorPrincipalSchema: z.ZodObject<{
6
+ tenant_id: z.ZodString;
7
+ id: z.ZodString;
8
+ type: z.ZodEnum<["user", "agent"]>;
23
9
  }, "strip", z.ZodTypeAny, {
24
- id?: string | undefined;
25
- title?: string | undefined;
26
- metadata?: Record<string, unknown> | undefined;
27
- creator_principal?: {
28
- type: "user" | "agent";
29
- tenant_id: string;
30
- id: string;
31
- } | undefined;
10
+ type: "user" | "agent";
11
+ tenant_id: string;
12
+ id: string;
32
13
  }, {
33
- id?: string | undefined;
34
- title?: string | undefined;
35
- metadata?: Record<string, unknown> | undefined;
36
- creator_principal?: {
37
- type: "user" | "agent";
38
- tenant_id: string;
39
- id: string;
40
- } | undefined;
14
+ type: "user" | "agent";
15
+ tenant_id: string;
16
+ id: string;
17
+ }>;
18
+ type SessionCreatorPrincipal = z.infer<typeof SessionCreatorPrincipalSchema>;
19
+ declare const SessionTokenPrincipalSchema: z.ZodObject<{
20
+ type: z.ZodEnum<["user", "agent"]>;
21
+ id: z.ZodString;
22
+ }, "strip", z.ZodTypeAny, {
23
+ type: "user" | "agent";
24
+ id: string;
25
+ }, {
26
+ type: "user" | "agent";
27
+ id: string;
41
28
  }>;
29
+ type SessionTokenPrincipal = z.infer<typeof SessionTokenPrincipalSchema>;
42
30
  /**
43
- * Inferred TypeScript type for {@link CreateSessionInputSchema}.
31
+ * Represents a resolved caller identity with tenant, principal id, and type.
44
32
  */
45
- type CreateSessionInput = z.infer<typeof CreateSessionInputSchema>;
33
+ declare class StarciteIdentity {
34
+ readonly tenantId: string;
35
+ readonly id: string;
36
+ readonly type: PrincipalType;
37
+ constructor(options: {
38
+ tenantId: string;
39
+ id: string;
40
+ type: PrincipalType;
41
+ });
42
+ /**
43
+ * Serializes to the `creator_principal` wire format expected by the API.
44
+ */
45
+ toCreatorPrincipal(): SessionCreatorPrincipal;
46
+ /**
47
+ * Serializes to the `principal` wire format used in session token requests.
48
+ */
49
+ toTokenPrincipal(): SessionTokenPrincipal;
50
+ /**
51
+ * Returns the actor string derived from this identity (e.g. `agent:planner`, `user:alice`).
52
+ */
53
+ toActor(): string;
54
+ }
55
+
56
+ declare const SessionTokenScopeSchema: z.ZodEnum<["session:read", "session:append"]>;
57
+ type SessionTokenScope = z.infer<typeof SessionTokenScopeSchema>;
46
58
  /**
47
59
  * Session record returned by the Starcite API.
48
60
  */
@@ -143,7 +155,7 @@ type SessionListPage = z.infer<typeof SessionListPageSchema>;
143
155
  declare const AppendEventRequestSchema: z.ZodObject<{
144
156
  type: z.ZodString;
145
157
  payload: z.ZodRecord<z.ZodString, z.ZodUnknown>;
146
- actor: z.ZodString;
158
+ actor: z.ZodOptional<z.ZodString>;
147
159
  producer_id: z.ZodString;
148
160
  producer_seq: z.ZodNumber;
149
161
  source: z.ZodOptional<z.ZodString>;
@@ -154,10 +166,10 @@ declare const AppendEventRequestSchema: z.ZodObject<{
154
166
  }, "strip", z.ZodTypeAny, {
155
167
  type: string;
156
168
  payload: Record<string, unknown>;
157
- actor: string;
158
169
  producer_id: string;
159
170
  producer_seq: number;
160
171
  metadata?: Record<string, unknown> | undefined;
172
+ actor?: string | undefined;
161
173
  source?: string | undefined;
162
174
  refs?: Record<string, unknown> | undefined;
163
175
  idempotency_key?: string | undefined;
@@ -165,10 +177,10 @@ declare const AppendEventRequestSchema: z.ZodObject<{
165
177
  }, {
166
178
  type: string;
167
179
  payload: Record<string, unknown>;
168
- actor: string;
169
180
  producer_id: string;
170
181
  producer_seq: number;
171
182
  metadata?: Record<string, unknown> | undefined;
183
+ actor?: string | undefined;
172
184
  source?: string | undefined;
173
185
  refs?: Record<string, unknown> | undefined;
174
186
  idempotency_key?: string | undefined;
@@ -198,6 +210,13 @@ declare const AppendEventResponseSchema: z.ZodObject<{
198
210
  * Inferred TypeScript type for {@link AppendEventResponseSchema}.
199
211
  */
200
212
  type AppendEventResponse = z.infer<typeof AppendEventResponseSchema>;
213
+ /**
214
+ * High-level append result returned by `session.append()`.
215
+ */
216
+ interface AppendResult {
217
+ seq: number;
218
+ deduped: boolean;
219
+ }
201
220
  /**
202
221
  * Raw event frame shape emitted by the Starcite tail stream.
203
222
  */
@@ -243,117 +262,113 @@ declare const TailEventSchema: z.ZodObject<{
243
262
  */
244
263
  type TailEvent = z.infer<typeof TailEventSchema>;
245
264
  /**
246
- * Convenience tail event shape with SDK-derived fields (`agent`, `text`).
265
+ * Canonical session event surfaced by the SDK.
247
266
  */
248
- declare const SessionEventInternalSchema: z.ZodObject<{
249
- seq: z.ZodNumber;
250
- type: z.ZodString;
251
- payload: z.ZodRecord<z.ZodString, z.ZodUnknown>;
252
- actor: z.ZodString;
253
- producer_id: z.ZodString;
254
- producer_seq: z.ZodNumber;
255
- source: z.ZodOptional<z.ZodString>;
256
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
257
- refs: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
258
- idempotency_key: z.ZodOptional<z.ZodNullable<z.ZodString>>;
259
- inserted_at: z.ZodOptional<z.ZodString>;
260
- } & {
261
- agent: z.ZodOptional<z.ZodString>;
262
- text: z.ZodOptional<z.ZodString>;
263
- }, "strip", z.ZodTypeAny, {
264
- type: string;
265
- payload: Record<string, unknown>;
266
- actor: string;
267
- producer_id: string;
268
- producer_seq: number;
269
- seq: number;
270
- agent?: string | undefined;
271
- metadata?: Record<string, unknown> | undefined;
272
- source?: string | undefined;
273
- refs?: Record<string, unknown> | undefined;
274
- idempotency_key?: string | null | undefined;
275
- inserted_at?: string | undefined;
276
- text?: string | undefined;
277
- }, {
278
- type: string;
279
- payload: Record<string, unknown>;
280
- actor: string;
281
- producer_id: string;
282
- producer_seq: number;
283
- seq: number;
284
- agent?: string | undefined;
285
- metadata?: Record<string, unknown> | undefined;
286
- source?: string | undefined;
287
- refs?: Record<string, unknown> | undefined;
288
- idempotency_key?: string | null | undefined;
289
- inserted_at?: string | undefined;
290
- text?: string | undefined;
291
- }>;
267
+ type SessionEvent = TailEvent;
268
+ /**
269
+ * Raw tail event batch grouped by a single WebSocket frame.
270
+ */
271
+ type TailEventBatch = TailEvent[];
272
+ /**
273
+ * Retention options for a session's in-memory canonical log.
274
+ */
275
+ interface SessionLogOptions {
276
+ /**
277
+ * Maximum number of events retained in memory.
278
+ *
279
+ * When omitted, the log keeps all applied events for the current runtime.
280
+ */
281
+ maxEvents?: number;
282
+ }
283
+ /**
284
+ * Snapshot of a session's canonical in-memory log state.
285
+ */
286
+ interface SessionSnapshot {
287
+ /**
288
+ * Ordered events currently retained in memory.
289
+ */
290
+ events: TailEvent[];
291
+ /**
292
+ * Highest contiguous sequence applied to the log.
293
+ */
294
+ lastSeq: number;
295
+ /**
296
+ * Indicates whether the session is actively streaming tail updates.
297
+ */
298
+ syncing: boolean;
299
+ }
300
+ /**
301
+ * Serializable persisted state for one session log.
302
+ */
303
+ interface SessionStoreState {
304
+ /**
305
+ * Highest contiguous sequence applied for this session.
306
+ */
307
+ cursor: number;
308
+ /**
309
+ * Retained events snapshot used for immediate replay.
310
+ */
311
+ events: TailEvent[];
312
+ }
292
313
  /**
293
- * Inferred TypeScript type for the SDK-level enriched tail event.
314
+ * Persistence interface for session cursor + retained events.
294
315
  */
295
- type SessionEvent = z.infer<typeof SessionEventInternalSchema>;
316
+ interface SessionStore {
317
+ load(sessionId: string): SessionStoreState | undefined;
318
+ save(sessionId: string, state: SessionStoreState): void;
319
+ clear?(sessionId: string): void;
320
+ }
296
321
  /**
297
322
  * High-level `session.append()` input.
298
323
  *
299
- * You must provide producer identity (`producerId`, `producerSeq`) and either
300
- * `text` or `payload`.
324
+ * The SDK manages `actor`, `producer_id`, and `producer_seq` automatically.
325
+ * Just provide `text` or `payload`.
301
326
  */
302
327
  declare const SessionAppendInputSchema: z.ZodEffects<z.ZodObject<{
303
- agent: z.ZodString;
304
- producerId: z.ZodString;
305
- producerSeq: z.ZodNumber;
306
328
  text: z.ZodOptional<z.ZodString>;
307
329
  payload: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
308
330
  type: z.ZodOptional<z.ZodString>;
331
+ actor: z.ZodOptional<z.ZodString>;
309
332
  source: z.ZodOptional<z.ZodString>;
310
333
  metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
311
334
  refs: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
312
335
  idempotencyKey: z.ZodOptional<z.ZodString>;
313
336
  expectedSeq: z.ZodOptional<z.ZodNumber>;
314
337
  }, "strip", z.ZodTypeAny, {
315
- agent: string;
316
- producerId: string;
317
- producerSeq: number;
318
338
  type?: string | undefined;
319
339
  metadata?: Record<string, unknown> | undefined;
320
340
  payload?: Record<string, unknown> | undefined;
341
+ actor?: string | undefined;
321
342
  source?: string | undefined;
322
343
  refs?: Record<string, unknown> | undefined;
323
344
  text?: string | undefined;
324
345
  idempotencyKey?: string | undefined;
325
346
  expectedSeq?: number | undefined;
326
347
  }, {
327
- agent: string;
328
- producerId: string;
329
- producerSeq: number;
330
348
  type?: string | undefined;
331
349
  metadata?: Record<string, unknown> | undefined;
332
350
  payload?: Record<string, unknown> | undefined;
351
+ actor?: string | undefined;
333
352
  source?: string | undefined;
334
353
  refs?: Record<string, unknown> | undefined;
335
354
  text?: string | undefined;
336
355
  idempotencyKey?: string | undefined;
337
356
  expectedSeq?: number | undefined;
338
357
  }>, {
339
- agent: string;
340
- producerId: string;
341
- producerSeq: number;
342
358
  type?: string | undefined;
343
359
  metadata?: Record<string, unknown> | undefined;
344
360
  payload?: Record<string, unknown> | undefined;
361
+ actor?: string | undefined;
345
362
  source?: string | undefined;
346
363
  refs?: Record<string, unknown> | undefined;
347
364
  text?: string | undefined;
348
365
  idempotencyKey?: string | undefined;
349
366
  expectedSeq?: number | undefined;
350
367
  }, {
351
- agent: string;
352
- producerId: string;
353
- producerSeq: number;
354
368
  type?: string | undefined;
355
369
  metadata?: Record<string, unknown> | undefined;
356
370
  payload?: Record<string, unknown> | undefined;
371
+ actor?: string | undefined;
357
372
  source?: string | undefined;
358
373
  refs?: Record<string, unknown> | undefined;
359
374
  text?: string | undefined;
@@ -372,10 +387,22 @@ interface SessionTailOptions {
372
387
  * Starting cursor (inclusive) in the event stream.
373
388
  */
374
389
  cursor?: number;
390
+ /**
391
+ * Tail frame batch size (`1..1000`).
392
+ *
393
+ * When greater than `1`, Starcite may emit batched WebSocket frames.
394
+ */
395
+ batchSize?: number;
375
396
  /**
376
397
  * Optional filter for `agent:<name>` events.
377
398
  */
378
399
  agent?: string;
400
+ /**
401
+ * Idle window in milliseconds used for replay-only tails (`follow=false`) before auto-close.
402
+ *
403
+ * Defaults to `1000`.
404
+ */
405
+ catchUpIdleMs?: number;
379
406
  /**
380
407
  * Automatically reconnect on transport failures and continue from the last observed sequence.
381
408
  *
@@ -383,11 +410,9 @@ interface SessionTailOptions {
383
410
  */
384
411
  reconnect?: boolean;
385
412
  /**
386
- * Delay between reconnect attempts in milliseconds.
387
- *
388
- * Defaults to `3000`.
413
+ * Reconnect policy for transport failures.
389
414
  */
390
- reconnectDelayMs?: number;
415
+ reconnectPolicy?: TailReconnectPolicy;
391
416
  /**
392
417
  * When `false`, exit after replaying stored events instead of streaming live.
393
418
  *
@@ -398,49 +423,183 @@ interface SessionTailOptions {
398
423
  * Optional abort signal to close the stream.
399
424
  */
400
425
  signal?: AbortSignal;
426
+ /**
427
+ * Maximum number of tail batches buffered in-memory while the consumer is busy.
428
+ *
429
+ * Defaults to `1024`. When exceeded, the stream fails with `StarciteTailError`.
430
+ */
431
+ maxBufferedBatches?: number;
432
+ /**
433
+ * Optional lifecycle callback invoked for reconnect/drop/terminal stream state changes.
434
+ */
435
+ onLifecycleEvent?: (event: TailLifecycleEvent) => void;
436
+ /**
437
+ * Maximum time to wait for websocket handshake/open before reconnecting or failing.
438
+ *
439
+ * Defaults to `4000`.
440
+ */
441
+ connectionTimeoutMs?: number;
442
+ /**
443
+ * Optional inactivity watchdog. When set, the stream reconnects when no messages
444
+ * arrive within this duration.
445
+ */
446
+ inactivityTimeoutMs?: number;
401
447
  }
402
448
  /**
403
- * Options for listing sessions.
449
+ * Tail reconnect tuning knobs.
450
+ */
451
+ interface TailReconnectPolicy {
452
+ /**
453
+ * Reconnect mode. `fixed` retries at the same delay, `exponential` increases delay after repeated failures.
454
+ *
455
+ * Defaults to `exponential`.
456
+ */
457
+ mode?: "fixed" | "exponential";
458
+ /**
459
+ * Initial reconnect delay in milliseconds.
460
+ *
461
+ * Defaults to `500`.
462
+ */
463
+ initialDelayMs?: number;
464
+ /**
465
+ * Maximum reconnect delay in milliseconds.
466
+ *
467
+ * Defaults to `15000`.
468
+ */
469
+ maxDelayMs?: number;
470
+ /**
471
+ * Exponential growth factor applied after each failed reconnect attempt.
472
+ *
473
+ * Defaults to `2`.
474
+ */
475
+ multiplier?: number;
476
+ /**
477
+ * Optional jitter ratio (`0..1`) applied around the computed delay.
478
+ *
479
+ * Defaults to `0.2`.
480
+ */
481
+ jitterRatio?: number;
482
+ /**
483
+ * Maximum number of reconnect attempts before failing.
484
+ *
485
+ * Defaults to unlimited retries.
486
+ */
487
+ maxAttempts?: number;
488
+ }
489
+ /**
490
+ * Stream lifecycle event emitted by `tail*()` APIs.
491
+ */
492
+ type TailLifecycleEvent = {
493
+ type: "connect_attempt";
494
+ sessionId: string;
495
+ attempt: number;
496
+ cursor: number;
497
+ } | {
498
+ type: "reconnect_scheduled";
499
+ sessionId: string;
500
+ attempt: number;
501
+ delayMs: number;
502
+ trigger: "connect_failed" | "dropped";
503
+ closeCode?: number;
504
+ closeReason?: string;
505
+ } | {
506
+ type: "stream_dropped";
507
+ sessionId: string;
508
+ attempt: number;
509
+ closeCode?: number;
510
+ closeReason?: string;
511
+ } | {
512
+ type: "stream_ended";
513
+ sessionId: string;
514
+ reason: "aborted" | "caught_up" | "graceful";
515
+ };
516
+ /**
517
+ * Storage adapter used by `session.consume*()` to persist the last processed cursor.
518
+ */
519
+ interface SessionCursorStore {
520
+ /**
521
+ * Loads the last processed cursor for a session.
522
+ *
523
+ * Return `undefined` when no cursor has been stored yet.
524
+ */
525
+ load(sessionId: string): number | undefined | Promise<number | undefined>;
526
+ /**
527
+ * Persists the last processed cursor for a session.
528
+ */
529
+ save(sessionId: string, cursor: number): void | Promise<void>;
530
+ }
531
+ /**
532
+ * Durable tail consumption options with automatic cursor checkpointing.
404
533
  */
405
- interface SessionListOptions {
534
+ interface SessionConsumeOptions extends Omit<SessionTailOptions, "cursor"> {
406
535
  /**
407
- * Maximum rows to return. Must be a positive integer.
536
+ * Optional explicit starting cursor. When omitted, the SDK loads it from `cursorStore`.
408
537
  */
409
- limit?: number;
538
+ cursor?: number;
410
539
  /**
411
- * Optional cursor from the previous response.
540
+ * Cursor storage adapter used for resume-safe processing.
412
541
  */
413
- cursor?: string;
542
+ cursorStore: SessionCursorStore;
414
543
  /**
415
- * Optional flat metadata exact-match filters.
544
+ * Event handler. The cursor is checkpointed only after this handler succeeds.
416
545
  */
417
- metadata?: Record<string, string>;
546
+ handler: (event: TailEvent) => void | Promise<void>;
418
547
  }
548
+ /**
549
+ * Options for listing sessions.
550
+ */
551
+ declare const SessionListOptionsSchema: z.ZodObject<{
552
+ limit: z.ZodOptional<z.ZodNumber>;
553
+ cursor: z.ZodOptional<z.ZodString>;
554
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
555
+ }, "strip", z.ZodTypeAny, {
556
+ metadata?: Record<string, string> | undefined;
557
+ cursor?: string | undefined;
558
+ limit?: number | undefined;
559
+ }, {
560
+ metadata?: Record<string, string> | undefined;
561
+ cursor?: string | undefined;
562
+ limit?: number | undefined;
563
+ }>;
564
+ type SessionListOptions = z.input<typeof SessionListOptionsSchema>;
419
565
  /**
420
566
  * Minimal WebSocket contract required by the SDK.
421
567
  */
568
+ interface StarciteWebSocketMessageEvent {
569
+ data: unknown;
570
+ }
571
+ interface StarciteWebSocketCloseEvent {
572
+ code?: number;
573
+ reason?: string;
574
+ }
575
+ interface StarciteWebSocketEventMap {
576
+ open: unknown;
577
+ message: StarciteWebSocketMessageEvent;
578
+ error: unknown;
579
+ close: StarciteWebSocketCloseEvent;
580
+ }
422
581
  interface StarciteWebSocket {
423
- addEventListener(type: string, listener: (event: unknown) => void): void;
424
- removeEventListener(type: string, listener: (event: unknown) => void): void;
582
+ addEventListener<TType extends keyof StarciteWebSocketEventMap>(type: TType, listener: (event: StarciteWebSocketEventMap[TType]) => void): void;
583
+ removeEventListener<TType extends keyof StarciteWebSocketEventMap>(type: TType, listener: (event: StarciteWebSocketEventMap[TType]) => void): void;
425
584
  close(code?: number, reason?: string): void;
426
585
  }
427
586
  /**
428
587
  * Factory used to create the WebSocket connection for `tail`.
429
588
  */
430
- interface StarciteWebSocketConnectOptions {
589
+ type StarciteWebSocketFactory = (url: string) => StarciteWebSocket;
590
+ /**
591
+ * Options forwarded to individual HTTP requests.
592
+ */
593
+ interface RequestOptions {
431
594
  /**
432
- * Headers to include with the WebSocket handshake request.
595
+ * Optional abort signal to cancel the request.
433
596
  */
434
- headers?: HeadersInit;
597
+ signal?: AbortSignal;
435
598
  }
436
- /**
437
- * Factory used to create the WebSocket connection for `tail`.
438
- */
439
- type StarciteWebSocketFactory = (url: string, options?: StarciteWebSocketConnectOptions) => StarciteWebSocket;
440
599
  /**
441
600
  * Client construction options.
442
601
  */
443
- interface StarciteClientOptions {
602
+ interface StarciteOptions {
444
603
  /**
445
604
  * Base API URL. Defaults to `process.env.STARCITE_BASE_URL` or `http://localhost:4000`.
446
605
  */
@@ -455,143 +614,369 @@ interface StarciteClientOptions {
455
614
  headers?: HeadersInit;
456
615
  /**
457
616
  * Service key / JWT token. When set, the SDK automatically sends
458
- * `Authorization: Bearer <token>` for HTTP requests and WebSocket upgrades.
617
+ * `Authorization: Bearer <token>` for HTTP requests.
459
618
  */
460
619
  apiKey?: string;
620
+ /**
621
+ * Auth issuer URL used to mint session tokens. When omitted, the SDK derives
622
+ * this from API key JWT `iss` (issuer authority) or `STARCITE_AUTH_URL`.
623
+ */
624
+ authUrl?: string;
461
625
  /**
462
626
  * Custom WebSocket factory for non-browser runtimes.
463
627
  */
464
628
  websocketFactory?: StarciteWebSocketFactory;
629
+ /**
630
+ * Session store used for cursor + retained event persistence.
631
+ *
632
+ * Defaults to an in-memory store.
633
+ */
634
+ store?: SessionStore;
465
635
  }
466
636
  /**
467
637
  * Error payload shape returned by non-2xx API responses.
468
638
  */
469
- declare const StarciteErrorPayloadSchema: z.ZodObject<{
470
- error: z.ZodOptional<z.ZodString>;
471
- message: z.ZodOptional<z.ZodString>;
472
- }, "strip", z.ZodUnknown, z.objectOutputType<{
473
- error: z.ZodOptional<z.ZodString>;
474
- message: z.ZodOptional<z.ZodString>;
475
- }, z.ZodUnknown, "strip">, z.objectInputType<{
476
- error: z.ZodOptional<z.ZodString>;
477
- message: z.ZodOptional<z.ZodString>;
478
- }, z.ZodUnknown, "strip">>;
639
+ type StarciteErrorPayload = Record<string, unknown>;
640
+
641
+ /**
642
+ * Base error type for SDK-level failures.
643
+ */
644
+ declare class StarciteError extends Error {
645
+ constructor(message: string);
646
+ }
647
+ /**
648
+ * Thrown when the Starcite API responds with a non-2xx status code.
649
+ */
650
+ declare class StarciteApiError extends StarciteError {
651
+ /** HTTP status code returned by the API. */
652
+ readonly status: number;
653
+ /** Stable API error code (or synthesized `http_<status>` fallback). */
654
+ readonly code: string;
655
+ /** Parsed API error payload when available. */
656
+ readonly payload: StarciteErrorPayload | null;
657
+ constructor(message: string, status: number, code: string, payload: StarciteErrorPayload | null);
658
+ }
659
+ /**
660
+ * Thrown when the SDK cannot reach Starcite or receives invalid transport payloads.
661
+ */
662
+ declare class StarciteConnectionError extends StarciteError {
663
+ constructor(message: string);
664
+ }
665
+ type StarciteTailErrorStage = "connect" | "stream" | "retry_limit" | "consumer_backpressure";
666
+ /**
667
+ * Thrown for tail-stream failures with structured stage/context fields.
668
+ */
669
+ declare class StarciteTailError extends StarciteConnectionError {
670
+ /** Session id tied to this tail stream. */
671
+ readonly sessionId: string;
672
+ /** Failure stage in the tail lifecycle. */
673
+ readonly stage: StarciteTailErrorStage;
674
+ /** Reconnect attempts observed before failing. */
675
+ readonly attempts: number;
676
+ /** WebSocket close code when available. */
677
+ readonly closeCode?: number;
678
+ /** WebSocket close reason when available. */
679
+ readonly closeReason?: string;
680
+ constructor(message: string, options: {
681
+ sessionId: string;
682
+ stage: StarciteTailErrorStage;
683
+ attempts?: number;
684
+ closeCode?: number;
685
+ closeReason?: string;
686
+ });
687
+ }
688
+ /**
689
+ * Thrown when the tail WebSocket is closed with code 4001 (token expired).
690
+ *
691
+ * Callers should re-issue a session token and reconnect from the last cursor.
692
+ */
693
+ declare class StarciteTokenExpiredError extends StarciteTailError {
694
+ constructor(message: string, options: {
695
+ sessionId: string;
696
+ attempts?: number;
697
+ closeCode?: number;
698
+ closeReason?: string;
699
+ });
700
+ }
701
+ /**
702
+ * Thrown when the tail consumer falls behind and exceeds the buffered batch limit.
703
+ */
704
+ declare class StarciteBackpressureError extends StarciteTailError {
705
+ constructor(message: string, options: {
706
+ sessionId: string;
707
+ attempts?: number;
708
+ });
709
+ }
710
+ /**
711
+ * Thrown when tail reconnect attempts exceed the configured limit.
712
+ */
713
+ declare class StarciteRetryLimitError extends StarciteTailError {
714
+ constructor(message: string, options: {
715
+ sessionId: string;
716
+ attempts: number;
717
+ closeCode?: number;
718
+ closeReason?: string;
719
+ });
720
+ }
721
+
722
+ declare class SessionLogGapError extends StarciteError {
723
+ constructor(message: string);
724
+ }
725
+ declare class SessionLogConflictError extends StarciteError {
726
+ constructor(message: string);
727
+ }
479
728
  /**
480
- * Inferred TypeScript type for {@link StarciteErrorPayloadSchema}.
729
+ * Canonical in-memory log for one session.
730
+ *
731
+ * Invariants:
732
+ * - Applies events in strict contiguous `seq` order.
733
+ * - Treats repeated identical events as idempotent no-ops.
734
+ * - Rejects conflicting duplicates and sequence gaps.
735
+ */
736
+ declare class SessionLog {
737
+ private readonly history;
738
+ private readonly emitter;
739
+ private readonly canonicalBySeq;
740
+ private maxEvents;
741
+ private appliedSeq;
742
+ constructor(options?: SessionLogOptions);
743
+ setMaxEvents(maxEvents: number | undefined): void;
744
+ applyBatch(batch: TailEvent[]): TailEvent[];
745
+ hydrate(state: SessionStoreState): void;
746
+ subscribe(listener: (event: TailEvent) => void, options?: {
747
+ replay?: boolean;
748
+ }): () => void;
749
+ private apply;
750
+ getSnapshot(syncing: boolean): SessionSnapshot;
751
+ get events(): readonly TailEvent[];
752
+ get cursor(): number;
753
+ get lastSeq(): number;
754
+ private enforceRetention;
755
+ }
756
+
757
+ /**
758
+ * Shared HTTP + WebSocket transport configuration.
759
+ *
760
+ * Both `Starcite` (API-key auth) and `StarciteSession` (session-token auth)
761
+ * hold their own `TransportConfig` and pass it to the free functions below.
481
762
  */
482
- type StarciteErrorPayload = z.infer<typeof StarciteErrorPayloadSchema>;
763
+ interface TransportConfig {
764
+ readonly baseUrl: string;
765
+ readonly websocketBaseUrl: string;
766
+ readonly authorization: string | null;
767
+ readonly fetchFn: typeof fetch;
768
+ readonly headers: Headers;
769
+ readonly websocketFactory: (url: string) => StarciteWebSocket;
770
+ }
483
771
 
484
772
  /**
485
- * Normalizes a Starcite base URL to the `/v1` API root used by this SDK.
773
+ * Construction options for a `StarciteSession`.
486
774
  */
487
- declare function normalizeBaseUrl(baseUrl: string): string;
775
+ interface StarciteSessionOptions {
776
+ id: string;
777
+ token: string;
778
+ identity: StarciteIdentity;
779
+ transport: TransportConfig;
780
+ store: SessionStore;
781
+ record?: SessionRecord;
782
+ logOptions?: SessionLogOptions;
783
+ }
784
+ type SessionEventListener = (event: SessionEvent) => void;
488
785
  /**
489
- * Session-scoped helper for append and tail operations.
786
+ * Session-scoped client bound to a specific identity and session token.
787
+ *
788
+ * All operations use the session token for auth — not the parent client's API key.
490
789
  */
491
790
  declare class StarciteSession {
492
791
  /** Session identifier. */
493
792
  readonly id: string;
793
+ /** The session JWT used for auth. Extract this for frontend handoff. */
794
+ readonly token: string;
795
+ /** Identity bound to this session. */
796
+ readonly identity: StarciteIdentity;
494
797
  /** Optional session record captured at creation time. */
495
798
  readonly record?: SessionRecord;
496
- private readonly client;
497
- constructor(client: StarciteClient, id: string, record?: SessionRecord);
799
+ private readonly transport;
800
+ private readonly producerId;
801
+ private producerSeq;
802
+ readonly log: SessionLog;
803
+ private readonly store;
804
+ private readonly lifecycle;
805
+ private readonly eventSubscriptions;
806
+ private liveSyncController;
807
+ private liveSyncTask;
808
+ constructor(options: StarciteSessionOptions);
498
809
  /**
499
- * Appends a high-level agent event to this session.
810
+ * Appends an event to this session.
500
811
  *
501
- * Automatically prefixes `agent` as `agent:<name>` when needed.
812
+ * The SDK manages `actor`, `producer_id`, and `producer_seq` automatically.
502
813
  */
503
- append(input: SessionAppendInput): Promise<AppendEventResponse>;
814
+ append(input: SessionAppendInput, options?: RequestOptions): Promise<AppendResult>;
504
815
  /**
505
- * Appends a raw event payload as-is.
816
+ * Appends a raw event payload as-is. Caller manages all fields.
506
817
  */
507
- appendRaw(input: AppendEventRequest): Promise<AppendEventResponse>;
818
+ appendRaw(input: AppendEventRequest, options?: RequestOptions): Promise<AppendEventResponse>;
508
819
  /**
509
- * Streams transformed session events with SDK convenience fields (`agent`, `text`).
820
+ * Subscribes to canonical session events and lifecycle errors.
510
821
  */
511
- tail(options?: SessionTailOptions): AsyncIterable<SessionEvent>;
822
+ on(eventName: "event", listener: SessionEventListener): () => void;
823
+ on(eventName: "error", listener: (error: Error) => void): () => void;
512
824
  /**
513
- * Streams raw tail events returned by the API.
825
+ * Removes a previously registered listener.
514
826
  */
515
- tailRaw(options?: SessionTailOptions): AsyncIterable<TailEvent>;
516
- }
517
- /**
518
- * Starcite API client for HTTP and WebSocket session operations.
519
- */
520
- declare class StarciteClient {
521
- /** Normalized API base URL ending with `/v1`. */
522
- readonly baseUrl: string;
523
- private readonly inferredCreatorPrincipal?;
524
- private readonly websocketBaseUrl;
525
- private readonly fetchFn;
526
- private readonly headers;
527
- private readonly websocketFactory;
827
+ off(eventName: "event", listener: SessionEventListener): void;
828
+ off(eventName: "error", listener: (error: Error) => void): void;
528
829
  /**
529
- * Creates a new client instance.
830
+ * Stops live syncing and removes listeners registered via `on()`.
530
831
  */
531
- constructor(options?: StarciteClientOptions);
832
+ disconnect(): void;
532
833
  /**
533
- * Returns a session helper bound to an existing session id.
834
+ * Backwards-compatible alias for `disconnect()`.
534
835
  */
535
- session(sessionId: string, record?: SessionRecord): StarciteSession;
836
+ close(): void;
536
837
  /**
537
- * Creates a new session and returns a bound `StarciteSession` helper.
838
+ * Updates in-memory session log retention.
538
839
  */
539
- create(input?: CreateSessionInput): Promise<StarciteSession>;
840
+ setLogOptions(options: SessionLogOptions): void;
540
841
  /**
541
- * Creates a new session and returns the raw session record.
842
+ * Returns a stable snapshot of the current canonical in-memory log.
542
843
  */
543
- createSession(input?: CreateSessionInput): Promise<SessionRecord>;
844
+ getSnapshot(): SessionSnapshot;
544
845
  /**
545
- * Lists sessions from the archive-backed catalog.
846
+ * Streams tail events one at a time via callback.
847
+ */
848
+ tail(onEvent: (event: TailEvent) => void | Promise<void>, options?: SessionTailOptions): Promise<void>;
849
+ /**
850
+ * Streams tail event batches grouped by incoming frame via callback.
851
+ */
852
+ tailBatches(onBatch: (batch: TailEvent[]) => void | Promise<void>, options?: SessionTailOptions): Promise<void>;
853
+ /**
854
+ * Durably consumes events and checkpoints `event.seq` after each successful handler invocation.
855
+ */
856
+ consume(options: SessionConsumeOptions): Promise<void>;
857
+ private emitStreamError;
858
+ private ensureLiveSync;
859
+ private runLiveSync;
860
+ private persistLogState;
861
+ }
862
+
863
+ /**
864
+ * Tenant-scoped Starcite client.
865
+ *
866
+ * Create identities with {@link user} / {@link agent}, then bind them to
867
+ * sessions with {@link session}.
868
+ */
869
+ declare class Starcite {
870
+ /** Normalized API base URL ending with `/v1`. */
871
+ readonly baseUrl: string;
872
+ private readonly transport;
873
+ private readonly authBaseUrl?;
874
+ private readonly inferredIdentity?;
875
+ private readonly store;
876
+ constructor(options?: StarciteOptions);
877
+ /**
878
+ * Creates a user identity bound to this client's tenant.
546
879
  */
547
- listSessions(options?: SessionListOptions): Promise<SessionListPage>;
880
+ user(options: {
881
+ id: string;
882
+ }): StarciteIdentity;
548
883
  /**
549
- * Appends a raw event payload to a specific session.
884
+ * Creates an agent identity bound to this client's tenant.
550
885
  */
551
- appendEvent(sessionId: string, input: AppendEventRequest): Promise<AppendEventResponse>;
886
+ agent(options: {
887
+ id: string;
888
+ }): StarciteIdentity;
552
889
  /**
553
- * Opens a WebSocket tail stream and yields raw events.
890
+ * Creates or binds to a session.
891
+ *
892
+ * **With identity** (backend): creates a new session and/or mints a session
893
+ * token for the given identity. Pass `id` to bind to an existing session.
894
+ *
895
+ * **With token** (frontend): wraps an existing session token. The identity
896
+ * and session id are decoded from the JWT.
554
897
  */
555
- tailRawEvents(sessionId: string, options?: SessionTailOptions): AsyncGenerator<TailEvent>;
898
+ session(input: {
899
+ token: string;
900
+ logOptions?: SessionLogOptions;
901
+ }): StarciteSession;
902
+ session(input: {
903
+ identity: StarciteIdentity;
904
+ id?: string;
905
+ title?: string;
906
+ metadata?: Record<string, unknown>;
907
+ logOptions?: SessionLogOptions;
908
+ }): Promise<StarciteSession>;
556
909
  /**
557
- * Opens a WebSocket tail stream and yields transformed session events.
910
+ * Lists sessions from the archive-backed catalog.
558
911
  */
559
- tailEvents(sessionId: string, options?: SessionTailOptions): AsyncGenerator<SessionEvent>;
560
- private request;
912
+ listSessions(options?: SessionListOptions, requestOptions?: RequestOptions): Promise<SessionListPage>;
913
+ private sessionFromIdentity;
914
+ private sessionFromToken;
915
+ private buildSessionTransport;
916
+ private createSession;
917
+ private issueSessionToken;
918
+ private requireTenantId;
561
919
  }
562
920
 
563
921
  /**
564
- * Base error type for SDK-level failures.
922
+ * Minimal Web Storage contract used by {@link WebStorageCursorStore}.
565
923
  */
566
- declare class StarciteError extends Error {
567
- constructor(message: string);
924
+ interface StarciteWebStorage {
925
+ getItem(key: string): string | null;
926
+ setItem(key: string, value: string): void;
568
927
  }
569
928
  /**
570
- * Thrown when the Starcite API responds with a non-2xx status code.
929
+ * Key customization options for storage-backed cursor stores.
571
930
  */
572
- declare class StarciteApiError extends StarciteError {
573
- /** HTTP status code returned by the API. */
574
- readonly status: number;
575
- /** Stable API error code (or synthesized `http_<status>` fallback). */
576
- readonly code: string;
577
- /** Parsed API error payload when available. */
578
- readonly payload: StarciteErrorPayload | null;
579
- constructor(message: string, status: number, code: string, payload: StarciteErrorPayload | null);
931
+ interface CursorStoreOptions {
932
+ /**
933
+ * Prefix used when deriving storage keys.
934
+ *
935
+ * Defaults to `"starcite"`.
936
+ */
937
+ keyPrefix?: string;
938
+ /**
939
+ * Custom key resolver. When provided it overrides `keyPrefix`.
940
+ */
941
+ keyForSession?: (sessionId: string) => string;
580
942
  }
581
943
  /**
582
- * Thrown when the SDK cannot reach Starcite or receives invalid transport payloads.
944
+ * In-memory cursor store (useful for workers/tests).
583
945
  */
584
- declare class StarciteConnectionError extends StarciteError {
585
- constructor(message: string);
946
+ declare class InMemoryCursorStore implements SessionCursorStore {
947
+ private readonly cursors;
948
+ constructor(initial?: Record<string, number>);
949
+ load(sessionId: string): number | undefined;
950
+ save(sessionId: string, cursor: number): void;
586
951
  }
587
-
588
952
  /**
589
- * Creates a new {@link StarciteClient} instance.
953
+ * Cursor store backed by a Web Storage-compatible object.
590
954
  */
591
- declare function createStarciteClient(options?: StarciteClientOptions): StarciteClient;
955
+ declare class WebStorageCursorStore implements SessionCursorStore {
956
+ private readonly storage;
957
+ private readonly keyForSession;
958
+ constructor(storage: StarciteWebStorage, options?: CursorStoreOptions);
959
+ load(sessionId: string): number | undefined;
960
+ save(sessionId: string, cursor: number): void;
961
+ }
592
962
  /**
593
- * Default singleton client using environment/default configuration.
963
+ * Cursor store backed by `globalThis.localStorage`.
594
964
  */
595
- declare const starcite: StarciteClient;
965
+ declare class LocalStorageCursorStore extends WebStorageCursorStore {
966
+ constructor(options?: CursorStoreOptions);
967
+ }
968
+
969
+ /**
970
+ * Default in-memory session store.
971
+ *
972
+ * Persists both cursor and retained events for each session so late subscribers
973
+ * can replay immediately after process-local reconnect/rebind.
974
+ */
975
+ declare class MemoryStore implements SessionStore {
976
+ private readonly sessions;
977
+ load(sessionId: string): SessionStoreState | undefined;
978
+ save(sessionId: string, state: SessionStoreState): void;
979
+ clear(sessionId: string): void;
980
+ }
596
981
 
597
- export { type AppendEventRequest, type AppendEventResponse, type CreateSessionInput, type SessionAppendInput, type SessionEvent, type SessionListItem, type SessionListOptions, type SessionListPage, type SessionRecord, type SessionTailOptions, StarciteApiError, StarciteClient, type StarciteClientOptions, StarciteConnectionError, StarciteError, type StarciteErrorPayload, StarciteSession, type StarciteWebSocket, type StarciteWebSocketConnectOptions, type StarciteWebSocketFactory, type TailEvent, createStarciteClient, normalizeBaseUrl, starcite };
982
+ export { type AppendEventRequest, type AppendEventResponse, type AppendResult, type CursorStoreOptions, InMemoryCursorStore, LocalStorageCursorStore, MemoryStore, type PrincipalType, type RequestOptions, type SessionAppendInput, type SessionConsumeOptions, type SessionCursorStore, type SessionEvent, type SessionListItem, type SessionListOptions, type SessionListPage, SessionLogConflictError, SessionLogGapError, type SessionLogOptions, type SessionRecord, type SessionSnapshot, type SessionStore, type SessionStoreState, type SessionTailOptions, type SessionTokenScope, Starcite, StarciteApiError, StarciteBackpressureError, StarciteConnectionError, StarciteError, StarciteIdentity, type StarciteOptions, StarciteRetryLimitError, StarciteSession, StarciteTailError, type StarciteTailErrorStage, StarciteTokenExpiredError, type StarciteWebSocket, type StarciteWebSocketCloseEvent, type StarciteWebSocketEventMap, type StarciteWebSocketFactory, type StarciteWebSocketMessageEvent, type StarciteWebStorage, type TailEvent, type TailEventBatch, type TailLifecycleEvent, type TailReconnectPolicy, WebStorageCursorStore };