@niadra/sdk 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -29,8 +29,11 @@ type VerifyMethod = "otp_whatsapp" | "otp_sms" | "login" | "kba" | "network_atte
29
29
  * control group: the pack is intentionally empty and the SDK treats it as a normal answer.
30
30
  */
31
31
  type DeliveryPath = "t0" | "t1" | "t2" | "t3" | "t4" | "holdout" | "not_modified";
32
- /** Kinds of history items the navigation calls can filter on. */
33
- type HistoryItemKind = "episode" | "fact" | "open_item" | "action" | "system_event" | "object" | "trait";
32
+ /**
33
+ * Kinds of history items the navigation calls can filter on. A system event is never an item: it
34
+ * changes its object's state, so filter on `object`.
35
+ */
36
+ type HistoryItemKind = "episode" | "fact" | "open_item" | "action" | "object" | "trait";
34
37
  /**
35
38
  * The shape of the pack. Channel views (`voice`, `chat`) size it for the medium; `account`
36
39
  * and `partner` read an organization; `task:<name>` views serve internal agents.
@@ -271,6 +274,17 @@ interface TimelineRequest {
271
274
  verification?: Verification;
272
275
  conversation_id?: string | null;
273
276
  }
277
+ /**
278
+ * Body of `POST /v1/history/open`. A conversation id may be a phone number or an e-mail, and the
279
+ * customer is personal data, so neither goes in a URL.
280
+ */
281
+ interface OpenItemRequest {
282
+ item_id: string;
283
+ /** The customer the item must belong to; any other item answers 404. */
284
+ subject?: Handle | null;
285
+ verification?: Verification;
286
+ conversation_id?: string | null;
287
+ }
274
288
  interface TimelineResponse {
275
289
  items: HistoryItem[];
276
290
  next_cursor?: string | null;
@@ -295,7 +309,7 @@ interface OpenedItem {
295
309
  resolution?: string | null;
296
310
  derived: HistoryItem[];
297
311
  timeline: HistoryItem[];
298
- /** Literal transcript excerpt. Only returned to keys with an elevated scope. */
312
+ /** The server no longer sends a transcript excerpt; the field stays for code that reads it. */
299
313
  excerpt?: string | null;
300
314
  as_of?: string | null;
301
315
  }
@@ -470,6 +484,23 @@ interface ContextStamp {
470
484
  etag?: string | null;
471
485
  injected_at: string;
472
486
  }
487
+ /**
488
+ * What the model provider reported for the call behind an agent's turn. `wrap()` reads it from every
489
+ * call it sees; without `wrap()`, pass it with the turn: `agent(text, { usage: response })` takes an
490
+ * OpenAI or Anthropic response or a `ModelUsage`.
491
+ */
492
+ interface ModelUsage {
493
+ /** Who served the call, lowercase: `openai`, `anthropic`, a router or a cloud. */
494
+ provider: string;
495
+ /** The model the provider says answered, such as `gpt-4.1-2025-04-14`. */
496
+ model: string;
497
+ /** Every input token, cached ones included. */
498
+ prompt_tokens: number;
499
+ /** Input tokens read from the provider's prompt cache. */
500
+ cached_tokens?: number;
501
+ /** Input tokens written to the cache (Anthropic's cache creation). */
502
+ cache_write_tokens?: number;
503
+ }
473
504
  /** A message, a system event or an agent action, exactly as sent on the wire. */
474
505
  interface EventItem {
475
506
  type: "event";
@@ -496,6 +527,8 @@ interface EventItem {
496
527
  corrects_event_id?: string | null;
497
528
  voice?: VoiceInfo | null;
498
529
  context_stamp?: ContextStamp | null;
530
+ /** The model call behind an `ai_agent` message: tokens and prompt cache. */
531
+ usage?: ModelUsage | null;
499
532
  }
500
533
  /** States that several handles belong to the same subject. */
501
534
  interface IdentifyItem {
@@ -648,6 +681,8 @@ interface TrackEvent extends EventBase {
648
681
  fields?: Record<string, unknown>;
649
682
  /** Required for `action`, and only valid there. */
650
683
  action?: ActionInfo | null;
684
+ /** What the provider reported for the model call behind an `ai_agent` message; only valid there. */
685
+ usage?: ModelUsage | null;
651
686
  }
652
687
  /** An agent action for `action()`: what an agent did in a system of record. */
653
688
  interface ActionEvent extends EventBase {
@@ -807,6 +842,12 @@ interface TurnOptions {
807
842
  voice?: VoiceInfo;
808
843
  /** Overrides the stamp an agent turn would carry from `markInjected()`. */
809
844
  context_stamp?: ContextStamp;
845
+ /**
846
+ * Agent turns only: what the model provider reported for the call behind the answer, as the
847
+ * provider's response (OpenAI or Anthropic) or a `ModelUsage`. `wrap()` passes it for you. A
848
+ * response without usage is left out; the turn is recorded either way.
849
+ */
850
+ usage?: ModelUsage | object | null;
810
851
  }
811
852
  type ConversationEvent = Omit<TrackEvent, "channel" | "conversation_id"> & {
812
853
  channel?: string;
@@ -956,11 +997,15 @@ interface Timeouts {
956
997
  navigation: number;
957
998
  /** Navigation calls made through a voice conversation or voice-bound tools. */
958
999
  navigationVoice: number;
959
- /** Each attempt of a batch upload. Writes happen off the hot path, so this one is generous. */
1000
+ /**
1001
+ * The whole of a write the caller waits for: `identify()`, `verify()`, `handoff()`,
1002
+ * `feedback()` and the reservation in `uploadMedia()`, retries included. Also each attempt
1003
+ * of a background batch, which never holds a caller.
1004
+ */
960
1005
  write: number;
961
1006
  /** `subjectToken()`, usually called once when a session starts. */
962
1007
  token: number;
963
- /** Each attempt of sending media bytes to storage in `uploadMedia()`, off the hot path. */
1008
+ /** The whole of sending media bytes to storage in `uploadMedia()`, retries included. */
964
1009
  upload: number;
965
1010
  }
966
1011
  declare const DEFAULT_TIMEOUTS: Timeouts;
@@ -988,6 +1033,11 @@ interface QueueOptions {
988
1033
  flushAt: number;
989
1034
  /** Send whatever is waiting at least this often. */
990
1035
  flushIntervalMs: number;
1036
+ /**
1037
+ * Send a conversation turn (a message with a `conversation_id`) at most this long after it was
1038
+ * queued, with whatever else is waiting. It is what the other agents read in `live`.
1039
+ */
1040
+ turnFlushIntervalMs: number;
991
1041
  /** Items per request. The server accepts up to 500. */
992
1042
  maxBatchSize: number;
993
1043
  /** Items held in memory before new ones are dropped. Keeps a long outage from exhausting memory. */
@@ -1148,7 +1198,13 @@ type WriteResult = {
1148
1198
  interface OpenParams {
1149
1199
  verification?: Verification;
1150
1200
  conversation_id?: string;
1201
+ /** Kept for callers of 0.1.0; the server never read it on this route, so it is not sent. */
1151
1202
  task_id?: string;
1203
+ /**
1204
+ * The customer the item must belong to: the server opens it only when it is theirs, and answers
1205
+ * 404 otherwise. `tools()` passes the bound customer.
1206
+ */
1207
+ subject?: Handle;
1152
1208
  }
1153
1209
  /**
1154
1210
  * The Niadra client.
@@ -1199,12 +1255,12 @@ declare class Niadra {
1199
1255
  * topic and kind. The answer includes how often the same kind of issue came back.
1200
1256
  */
1201
1257
  search(params: SearchRequest, options?: RequestOptions): Promise<Result<SearchResponse>>;
1202
- /** The customer's history in chronological order, one line per item, paginated by cursor. */
1258
+ /** The customer's history, newest first, one line per item, paginated by cursor. */
1203
1259
  timeline(params: TimelineRequest, options?: RequestOptions): Promise<Result<TimelineResponse>>;
1204
1260
  /**
1205
1261
  * Opens one history item from `search()` or `timeline()`: summary, request, commitments,
1206
- * outcome and resolution. The literal transcript excerpt only comes back to keys with an
1207
- * elevated scope.
1262
+ * outcome and resolution. Sent as `POST /v1/history/open`: the conversation id and `subject` go
1263
+ * in the body, never in a URL.
1208
1264
  */
1209
1265
  open(id: string, params?: OpenParams, options?: RequestOptions): Promise<Result<OpenedItem>>;
1210
1266
  /**
@@ -1332,7 +1388,11 @@ declare class Niadra {
1332
1388
  * leading system or developer messages, and the suffix (deltas and live turns) as a system
1333
1389
  * message at the end. The pack goes after the caller's instructions because those are the same
1334
1390
  * for every customer: kept first, they stay the cacheable prefix of the prompt. The injection is
1335
- * stamped on the conversation, and the model's answer is recorded as the agent's turn.
1391
+ * stamped on the conversation, and the model's answer is recorded as the agent's turn, with the
1392
+ * usage the provider reported for the call: the prompt's tokens, the ones read from the provider's
1393
+ * prompt cache and the ones written to it (see `modelUsage()`). A stream reports its usage only when
1394
+ * the caller asks for it (`stream_options: { include_usage: true }`); the wrapper never changes the
1395
+ * request to get it.
1336
1396
  *
1337
1397
  * Nothing the wrapper does can fail the model call: a context that cannot be fetched is left
1338
1398
  * out, and a failure to record the answer is logged, without content, and swallowed.
@@ -1342,7 +1402,9 @@ declare class Niadra {
1342
1402
  interface WrapSession {
1343
1403
  context(): Promise<ContextResult>;
1344
1404
  markInjected(context?: ContextResult | null): void;
1345
- agent(text: string): string | null;
1405
+ agent(text: string, options?: {
1406
+ usage?: ModelUsage | null;
1407
+ }): string | null;
1346
1408
  readonly logger: Logger;
1347
1409
  }
1348
1410
  /** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */
@@ -1366,6 +1428,38 @@ declare function wrap<C extends object>(client: C, session: SessionSource): C;
1366
1428
  */
1367
1429
  declare function injectContext(context: ContextResult, messages: readonly unknown[]): unknown[];
1368
1430
 
1431
+ /**
1432
+ * Reads what a model provider reported for one call: every input token, the ones read from the
1433
+ * provider's prompt cache and the ones written to it.
1434
+ *
1435
+ * Two shapes are understood, from the response or its `usage` (plain objects or class instances):
1436
+ *
1437
+ * - OpenAI chat completions and compatible gateways: `usage.prompt_tokens` (cached tokens included)
1438
+ * and `usage.prompt_tokens_details.cached_tokens`; the Responses API's `input_tokens` with
1439
+ * `input_tokens_details.cached_tokens` too. Gateways that pass Anthropic's cache fields through
1440
+ * (`cache_read_input_tokens`, `cache_creation_input_tokens`) are read as well.
1441
+ * - Anthropic messages: `usage.input_tokens` counts only the uncached rest, so the prompt is
1442
+ * `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`.
1443
+ *
1444
+ * Nothing here throws: a response without usage gives `null`.
1445
+ */
1446
+
1447
+ /** `prompt_tokens`, `cached_tokens` and `cache_write_tokens` from a provider's usage, or `null`. */
1448
+ declare function tokenCounts(usage: unknown): Pick<ModelUsage, "prompt_tokens" | "cached_tokens" | "cache_write_tokens"> | null;
1449
+ /**
1450
+ * Who served the call: the router prefix of `vendor/model` names, else what the name or the usage
1451
+ * shape says, else `openai` (the client `wrap()` takes).
1452
+ */
1453
+ declare function providerOf(model: string, usage?: unknown): string;
1454
+ /**
1455
+ * The usage of an OpenAI or Anthropic response (or of its bare `usage`, with `options.model`), for
1456
+ * the agent's turn: `convo.agent(text, { usage: modelUsage(response) })`. `null` without usage.
1457
+ */
1458
+ declare function modelUsage(response: unknown, options?: {
1459
+ provider?: string;
1460
+ model?: string;
1461
+ }): ModelUsage | null;
1462
+
1369
1463
  interface HandleOptions {
1370
1464
  /** Overrides the subject kind the server would infer from the handle type. */
1371
1465
  subjectKind?: SubjectKind;
@@ -1410,7 +1504,7 @@ declare function toObjectRef(object: ObjectRef | string): ObjectRef;
1410
1504
  interface ParsedApiKey {
1411
1505
  /** `live` keys reach production spaces, `test` keys reach sandbox spaces. */
1412
1506
  mode: "live" | "test";
1413
- /** Data region, such as `sa-east-1`. */
1507
+ /** Data region, such as `us-east-2`. */
1414
1508
  region: string;
1415
1509
  /** The space (project and environment) the key belongs to. */
1416
1510
  space: string;
@@ -1436,6 +1530,6 @@ declare function baseURLFromKey(key: ParsedApiKey): string;
1436
1530
  */
1437
1531
  declare function uuidv7(now?: number): string;
1438
1532
 
1439
- declare const VERSION = "0.1.0";
1533
+ declare const VERSION = "0.1.1";
1440
1534
 
1441
- export { type ActionEvent, type ActionInfo, type AssertionMethod, type BatchItem, type BatchRequest, type BatchResponse, type BoundTools, type CacheDirectives, type CacheOptions, type ClientOptions, type Closes, type Commitment, type Content, type ContextOptions, type ContextParams, type ContextRequest, type ContextResponse, type ContextResult, type ContextSource, type ContextStamp, Conversation, type ConversationAction, type ConversationEndedItem, type ConversationEvent, type ConversationParams, DEFAULT_CACHE, DEFAULT_QUEUE, DEFAULT_TIMEOUTS, type DeliveryPath, type EventItem, type EventKind, type FeedbackAction, type FeedbackParams, type FeedbackRequest, type Handle, type HandleType, type HandoffItem, type HandoffParams, type HeartbeatItem, type HistoryFilters, type HistoryItem, type HistoryItemKind, type IdentifyItem, type IdentifyParams, type ItemError, type LiveTurn, type Logger, MAX_BATCH_ITEMS, MAX_EVENT_TEXT, MAX_MEDIA_BYTES, type MediaUpload, type MediaUploadRequest, type MediaUploadResponse, Niadra, NiadraAPIError, NiadraAbortError, NiadraAuthenticationError, NiadraConfigError, NiadraConnectionError, NiadraError, NiadraPermissionError, NiadraRateLimitError, NiadraTimeoutError, NiadraValidationError, type ObjectRef, type ObjectState, type ObjectTimeline, type ObjectTimelineParams, type OpenParams, type OpenedItem, type ParsedApiKey, type Problem, type QueueOptions, type Recurrence, type RequestOptions, type Result, type SearchRequest, type SearchResponse, type SessionSource, type SourceCoverage, type Speaker, type SpeakerRef, type Subject, type SubjectKind, type SubjectToken, type SubjectTokenRequest, TOOL_DEFINITIONS, TOOL_NAMES, type TargetModel, Task, type TaskAction, type TaskEndedItem, type TaskEvent, type TaskParams, type TimelineRequest, type TimelineResponse, type Timeouts, type Timestamp, type Timings, type ToolBinding, type ToolDefinition, type TrackEvent, type TurnOptions, type UploadParams, VERSION, type Verification, type VerificationResult, type VerifyItem, type VerifyMethod, type VerifyParams, type View, type Visibility, type VoiceInfo, type WrapSession, type WriteResult, baseURLFromKey, consoleLogger, handles, injectContext, parseApiKey, renderLive, renderSuffix, silentLogger, toObjectRef, uuidv7, wrap };
1535
+ export { type ActionEvent, type ActionInfo, type AssertionMethod, type BatchItem, type BatchRequest, type BatchResponse, type BoundTools, type CacheDirectives, type CacheOptions, type ClientOptions, type Closes, type Commitment, type Content, type ContextOptions, type ContextParams, type ContextRequest, type ContextResponse, type ContextResult, type ContextSource, type ContextStamp, Conversation, type ConversationAction, type ConversationEndedItem, type ConversationEvent, type ConversationParams, DEFAULT_CACHE, DEFAULT_QUEUE, DEFAULT_TIMEOUTS, type DeliveryPath, type EventItem, type EventKind, type FeedbackAction, type FeedbackParams, type FeedbackRequest, type Handle, type HandleType, type HandoffItem, type HandoffParams, type HeartbeatItem, type HistoryFilters, type HistoryItem, type HistoryItemKind, type IdentifyItem, type IdentifyParams, type ItemError, type LiveTurn, type Logger, MAX_BATCH_ITEMS, MAX_EVENT_TEXT, MAX_MEDIA_BYTES, type MediaUpload, type MediaUploadRequest, type MediaUploadResponse, type ModelUsage, Niadra, NiadraAPIError, NiadraAbortError, NiadraAuthenticationError, NiadraConfigError, NiadraConnectionError, NiadraError, NiadraPermissionError, NiadraRateLimitError, NiadraTimeoutError, NiadraValidationError, type ObjectRef, type ObjectState, type ObjectTimeline, type ObjectTimelineParams, type OpenItemRequest, type OpenParams, type OpenedItem, type ParsedApiKey, type Problem, type QueueOptions, type Recurrence, type RequestOptions, type Result, type SearchRequest, type SearchResponse, type SessionSource, type SourceCoverage, type Speaker, type SpeakerRef, type Subject, type SubjectKind, type SubjectToken, type SubjectTokenRequest, TOOL_DEFINITIONS, TOOL_NAMES, type TargetModel, Task, type TaskAction, type TaskEndedItem, type TaskEvent, type TaskParams, type TimelineRequest, type TimelineResponse, type Timeouts, type Timestamp, type Timings, type ToolBinding, type ToolDefinition, type TrackEvent, type TurnOptions, type UploadParams, VERSION, type Verification, type VerificationResult, type VerifyItem, type VerifyMethod, type VerifyParams, type View, type Visibility, type VoiceInfo, type WrapSession, type WriteResult, baseURLFromKey, consoleLogger, handles, injectContext, modelUsage, parseApiKey, providerOf, renderLive, renderSuffix, silentLogger, toObjectRef, tokenCounts, uuidv7, wrap };
package/dist/index.d.ts CHANGED
@@ -29,8 +29,11 @@ type VerifyMethod = "otp_whatsapp" | "otp_sms" | "login" | "kba" | "network_atte
29
29
  * control group: the pack is intentionally empty and the SDK treats it as a normal answer.
30
30
  */
31
31
  type DeliveryPath = "t0" | "t1" | "t2" | "t3" | "t4" | "holdout" | "not_modified";
32
- /** Kinds of history items the navigation calls can filter on. */
33
- type HistoryItemKind = "episode" | "fact" | "open_item" | "action" | "system_event" | "object" | "trait";
32
+ /**
33
+ * Kinds of history items the navigation calls can filter on. A system event is never an item: it
34
+ * changes its object's state, so filter on `object`.
35
+ */
36
+ type HistoryItemKind = "episode" | "fact" | "open_item" | "action" | "object" | "trait";
34
37
  /**
35
38
  * The shape of the pack. Channel views (`voice`, `chat`) size it for the medium; `account`
36
39
  * and `partner` read an organization; `task:<name>` views serve internal agents.
@@ -271,6 +274,17 @@ interface TimelineRequest {
271
274
  verification?: Verification;
272
275
  conversation_id?: string | null;
273
276
  }
277
+ /**
278
+ * Body of `POST /v1/history/open`. A conversation id may be a phone number or an e-mail, and the
279
+ * customer is personal data, so neither goes in a URL.
280
+ */
281
+ interface OpenItemRequest {
282
+ item_id: string;
283
+ /** The customer the item must belong to; any other item answers 404. */
284
+ subject?: Handle | null;
285
+ verification?: Verification;
286
+ conversation_id?: string | null;
287
+ }
274
288
  interface TimelineResponse {
275
289
  items: HistoryItem[];
276
290
  next_cursor?: string | null;
@@ -295,7 +309,7 @@ interface OpenedItem {
295
309
  resolution?: string | null;
296
310
  derived: HistoryItem[];
297
311
  timeline: HistoryItem[];
298
- /** Literal transcript excerpt. Only returned to keys with an elevated scope. */
312
+ /** The server no longer sends a transcript excerpt; the field stays for code that reads it. */
299
313
  excerpt?: string | null;
300
314
  as_of?: string | null;
301
315
  }
@@ -470,6 +484,23 @@ interface ContextStamp {
470
484
  etag?: string | null;
471
485
  injected_at: string;
472
486
  }
487
+ /**
488
+ * What the model provider reported for the call behind an agent's turn. `wrap()` reads it from every
489
+ * call it sees; without `wrap()`, pass it with the turn: `agent(text, { usage: response })` takes an
490
+ * OpenAI or Anthropic response or a `ModelUsage`.
491
+ */
492
+ interface ModelUsage {
493
+ /** Who served the call, lowercase: `openai`, `anthropic`, a router or a cloud. */
494
+ provider: string;
495
+ /** The model the provider says answered, such as `gpt-4.1-2025-04-14`. */
496
+ model: string;
497
+ /** Every input token, cached ones included. */
498
+ prompt_tokens: number;
499
+ /** Input tokens read from the provider's prompt cache. */
500
+ cached_tokens?: number;
501
+ /** Input tokens written to the cache (Anthropic's cache creation). */
502
+ cache_write_tokens?: number;
503
+ }
473
504
  /** A message, a system event or an agent action, exactly as sent on the wire. */
474
505
  interface EventItem {
475
506
  type: "event";
@@ -496,6 +527,8 @@ interface EventItem {
496
527
  corrects_event_id?: string | null;
497
528
  voice?: VoiceInfo | null;
498
529
  context_stamp?: ContextStamp | null;
530
+ /** The model call behind an `ai_agent` message: tokens and prompt cache. */
531
+ usage?: ModelUsage | null;
499
532
  }
500
533
  /** States that several handles belong to the same subject. */
501
534
  interface IdentifyItem {
@@ -648,6 +681,8 @@ interface TrackEvent extends EventBase {
648
681
  fields?: Record<string, unknown>;
649
682
  /** Required for `action`, and only valid there. */
650
683
  action?: ActionInfo | null;
684
+ /** What the provider reported for the model call behind an `ai_agent` message; only valid there. */
685
+ usage?: ModelUsage | null;
651
686
  }
652
687
  /** An agent action for `action()`: what an agent did in a system of record. */
653
688
  interface ActionEvent extends EventBase {
@@ -807,6 +842,12 @@ interface TurnOptions {
807
842
  voice?: VoiceInfo;
808
843
  /** Overrides the stamp an agent turn would carry from `markInjected()`. */
809
844
  context_stamp?: ContextStamp;
845
+ /**
846
+ * Agent turns only: what the model provider reported for the call behind the answer, as the
847
+ * provider's response (OpenAI or Anthropic) or a `ModelUsage`. `wrap()` passes it for you. A
848
+ * response without usage is left out; the turn is recorded either way.
849
+ */
850
+ usage?: ModelUsage | object | null;
810
851
  }
811
852
  type ConversationEvent = Omit<TrackEvent, "channel" | "conversation_id"> & {
812
853
  channel?: string;
@@ -956,11 +997,15 @@ interface Timeouts {
956
997
  navigation: number;
957
998
  /** Navigation calls made through a voice conversation or voice-bound tools. */
958
999
  navigationVoice: number;
959
- /** Each attempt of a batch upload. Writes happen off the hot path, so this one is generous. */
1000
+ /**
1001
+ * The whole of a write the caller waits for: `identify()`, `verify()`, `handoff()`,
1002
+ * `feedback()` and the reservation in `uploadMedia()`, retries included. Also each attempt
1003
+ * of a background batch, which never holds a caller.
1004
+ */
960
1005
  write: number;
961
1006
  /** `subjectToken()`, usually called once when a session starts. */
962
1007
  token: number;
963
- /** Each attempt of sending media bytes to storage in `uploadMedia()`, off the hot path. */
1008
+ /** The whole of sending media bytes to storage in `uploadMedia()`, retries included. */
964
1009
  upload: number;
965
1010
  }
966
1011
  declare const DEFAULT_TIMEOUTS: Timeouts;
@@ -988,6 +1033,11 @@ interface QueueOptions {
988
1033
  flushAt: number;
989
1034
  /** Send whatever is waiting at least this often. */
990
1035
  flushIntervalMs: number;
1036
+ /**
1037
+ * Send a conversation turn (a message with a `conversation_id`) at most this long after it was
1038
+ * queued, with whatever else is waiting. It is what the other agents read in `live`.
1039
+ */
1040
+ turnFlushIntervalMs: number;
991
1041
  /** Items per request. The server accepts up to 500. */
992
1042
  maxBatchSize: number;
993
1043
  /** Items held in memory before new ones are dropped. Keeps a long outage from exhausting memory. */
@@ -1148,7 +1198,13 @@ type WriteResult = {
1148
1198
  interface OpenParams {
1149
1199
  verification?: Verification;
1150
1200
  conversation_id?: string;
1201
+ /** Kept for callers of 0.1.0; the server never read it on this route, so it is not sent. */
1151
1202
  task_id?: string;
1203
+ /**
1204
+ * The customer the item must belong to: the server opens it only when it is theirs, and answers
1205
+ * 404 otherwise. `tools()` passes the bound customer.
1206
+ */
1207
+ subject?: Handle;
1152
1208
  }
1153
1209
  /**
1154
1210
  * The Niadra client.
@@ -1199,12 +1255,12 @@ declare class Niadra {
1199
1255
  * topic and kind. The answer includes how often the same kind of issue came back.
1200
1256
  */
1201
1257
  search(params: SearchRequest, options?: RequestOptions): Promise<Result<SearchResponse>>;
1202
- /** The customer's history in chronological order, one line per item, paginated by cursor. */
1258
+ /** The customer's history, newest first, one line per item, paginated by cursor. */
1203
1259
  timeline(params: TimelineRequest, options?: RequestOptions): Promise<Result<TimelineResponse>>;
1204
1260
  /**
1205
1261
  * Opens one history item from `search()` or `timeline()`: summary, request, commitments,
1206
- * outcome and resolution. The literal transcript excerpt only comes back to keys with an
1207
- * elevated scope.
1262
+ * outcome and resolution. Sent as `POST /v1/history/open`: the conversation id and `subject` go
1263
+ * in the body, never in a URL.
1208
1264
  */
1209
1265
  open(id: string, params?: OpenParams, options?: RequestOptions): Promise<Result<OpenedItem>>;
1210
1266
  /**
@@ -1332,7 +1388,11 @@ declare class Niadra {
1332
1388
  * leading system or developer messages, and the suffix (deltas and live turns) as a system
1333
1389
  * message at the end. The pack goes after the caller's instructions because those are the same
1334
1390
  * for every customer: kept first, they stay the cacheable prefix of the prompt. The injection is
1335
- * stamped on the conversation, and the model's answer is recorded as the agent's turn.
1391
+ * stamped on the conversation, and the model's answer is recorded as the agent's turn, with the
1392
+ * usage the provider reported for the call: the prompt's tokens, the ones read from the provider's
1393
+ * prompt cache and the ones written to it (see `modelUsage()`). A stream reports its usage only when
1394
+ * the caller asks for it (`stream_options: { include_usage: true }`); the wrapper never changes the
1395
+ * request to get it.
1336
1396
  *
1337
1397
  * Nothing the wrapper does can fail the model call: a context that cannot be fetched is left
1338
1398
  * out, and a failure to record the answer is logged, without content, and swallowed.
@@ -1342,7 +1402,9 @@ declare class Niadra {
1342
1402
  interface WrapSession {
1343
1403
  context(): Promise<ContextResult>;
1344
1404
  markInjected(context?: ContextResult | null): void;
1345
- agent(text: string): string | null;
1405
+ agent(text: string, options?: {
1406
+ usage?: ModelUsage | null;
1407
+ }): string | null;
1346
1408
  readonly logger: Logger;
1347
1409
  }
1348
1410
  /** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */
@@ -1366,6 +1428,38 @@ declare function wrap<C extends object>(client: C, session: SessionSource): C;
1366
1428
  */
1367
1429
  declare function injectContext(context: ContextResult, messages: readonly unknown[]): unknown[];
1368
1430
 
1431
+ /**
1432
+ * Reads what a model provider reported for one call: every input token, the ones read from the
1433
+ * provider's prompt cache and the ones written to it.
1434
+ *
1435
+ * Two shapes are understood, from the response or its `usage` (plain objects or class instances):
1436
+ *
1437
+ * - OpenAI chat completions and compatible gateways: `usage.prompt_tokens` (cached tokens included)
1438
+ * and `usage.prompt_tokens_details.cached_tokens`; the Responses API's `input_tokens` with
1439
+ * `input_tokens_details.cached_tokens` too. Gateways that pass Anthropic's cache fields through
1440
+ * (`cache_read_input_tokens`, `cache_creation_input_tokens`) are read as well.
1441
+ * - Anthropic messages: `usage.input_tokens` counts only the uncached rest, so the prompt is
1442
+ * `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`.
1443
+ *
1444
+ * Nothing here throws: a response without usage gives `null`.
1445
+ */
1446
+
1447
+ /** `prompt_tokens`, `cached_tokens` and `cache_write_tokens` from a provider's usage, or `null`. */
1448
+ declare function tokenCounts(usage: unknown): Pick<ModelUsage, "prompt_tokens" | "cached_tokens" | "cache_write_tokens"> | null;
1449
+ /**
1450
+ * Who served the call: the router prefix of `vendor/model` names, else what the name or the usage
1451
+ * shape says, else `openai` (the client `wrap()` takes).
1452
+ */
1453
+ declare function providerOf(model: string, usage?: unknown): string;
1454
+ /**
1455
+ * The usage of an OpenAI or Anthropic response (or of its bare `usage`, with `options.model`), for
1456
+ * the agent's turn: `convo.agent(text, { usage: modelUsage(response) })`. `null` without usage.
1457
+ */
1458
+ declare function modelUsage(response: unknown, options?: {
1459
+ provider?: string;
1460
+ model?: string;
1461
+ }): ModelUsage | null;
1462
+
1369
1463
  interface HandleOptions {
1370
1464
  /** Overrides the subject kind the server would infer from the handle type. */
1371
1465
  subjectKind?: SubjectKind;
@@ -1410,7 +1504,7 @@ declare function toObjectRef(object: ObjectRef | string): ObjectRef;
1410
1504
  interface ParsedApiKey {
1411
1505
  /** `live` keys reach production spaces, `test` keys reach sandbox spaces. */
1412
1506
  mode: "live" | "test";
1413
- /** Data region, such as `sa-east-1`. */
1507
+ /** Data region, such as `us-east-2`. */
1414
1508
  region: string;
1415
1509
  /** The space (project and environment) the key belongs to. */
1416
1510
  space: string;
@@ -1436,6 +1530,6 @@ declare function baseURLFromKey(key: ParsedApiKey): string;
1436
1530
  */
1437
1531
  declare function uuidv7(now?: number): string;
1438
1532
 
1439
- declare const VERSION = "0.1.0";
1533
+ declare const VERSION = "0.1.1";
1440
1534
 
1441
- export { type ActionEvent, type ActionInfo, type AssertionMethod, type BatchItem, type BatchRequest, type BatchResponse, type BoundTools, type CacheDirectives, type CacheOptions, type ClientOptions, type Closes, type Commitment, type Content, type ContextOptions, type ContextParams, type ContextRequest, type ContextResponse, type ContextResult, type ContextSource, type ContextStamp, Conversation, type ConversationAction, type ConversationEndedItem, type ConversationEvent, type ConversationParams, DEFAULT_CACHE, DEFAULT_QUEUE, DEFAULT_TIMEOUTS, type DeliveryPath, type EventItem, type EventKind, type FeedbackAction, type FeedbackParams, type FeedbackRequest, type Handle, type HandleType, type HandoffItem, type HandoffParams, type HeartbeatItem, type HistoryFilters, type HistoryItem, type HistoryItemKind, type IdentifyItem, type IdentifyParams, type ItemError, type LiveTurn, type Logger, MAX_BATCH_ITEMS, MAX_EVENT_TEXT, MAX_MEDIA_BYTES, type MediaUpload, type MediaUploadRequest, type MediaUploadResponse, Niadra, NiadraAPIError, NiadraAbortError, NiadraAuthenticationError, NiadraConfigError, NiadraConnectionError, NiadraError, NiadraPermissionError, NiadraRateLimitError, NiadraTimeoutError, NiadraValidationError, type ObjectRef, type ObjectState, type ObjectTimeline, type ObjectTimelineParams, type OpenParams, type OpenedItem, type ParsedApiKey, type Problem, type QueueOptions, type Recurrence, type RequestOptions, type Result, type SearchRequest, type SearchResponse, type SessionSource, type SourceCoverage, type Speaker, type SpeakerRef, type Subject, type SubjectKind, type SubjectToken, type SubjectTokenRequest, TOOL_DEFINITIONS, TOOL_NAMES, type TargetModel, Task, type TaskAction, type TaskEndedItem, type TaskEvent, type TaskParams, type TimelineRequest, type TimelineResponse, type Timeouts, type Timestamp, type Timings, type ToolBinding, type ToolDefinition, type TrackEvent, type TurnOptions, type UploadParams, VERSION, type Verification, type VerificationResult, type VerifyItem, type VerifyMethod, type VerifyParams, type View, type Visibility, type VoiceInfo, type WrapSession, type WriteResult, baseURLFromKey, consoleLogger, handles, injectContext, parseApiKey, renderLive, renderSuffix, silentLogger, toObjectRef, uuidv7, wrap };
1535
+ export { type ActionEvent, type ActionInfo, type AssertionMethod, type BatchItem, type BatchRequest, type BatchResponse, type BoundTools, type CacheDirectives, type CacheOptions, type ClientOptions, type Closes, type Commitment, type Content, type ContextOptions, type ContextParams, type ContextRequest, type ContextResponse, type ContextResult, type ContextSource, type ContextStamp, Conversation, type ConversationAction, type ConversationEndedItem, type ConversationEvent, type ConversationParams, DEFAULT_CACHE, DEFAULT_QUEUE, DEFAULT_TIMEOUTS, type DeliveryPath, type EventItem, type EventKind, type FeedbackAction, type FeedbackParams, type FeedbackRequest, type Handle, type HandleType, type HandoffItem, type HandoffParams, type HeartbeatItem, type HistoryFilters, type HistoryItem, type HistoryItemKind, type IdentifyItem, type IdentifyParams, type ItemError, type LiveTurn, type Logger, MAX_BATCH_ITEMS, MAX_EVENT_TEXT, MAX_MEDIA_BYTES, type MediaUpload, type MediaUploadRequest, type MediaUploadResponse, type ModelUsage, Niadra, NiadraAPIError, NiadraAbortError, NiadraAuthenticationError, NiadraConfigError, NiadraConnectionError, NiadraError, NiadraPermissionError, NiadraRateLimitError, NiadraTimeoutError, NiadraValidationError, type ObjectRef, type ObjectState, type ObjectTimeline, type ObjectTimelineParams, type OpenItemRequest, type OpenParams, type OpenedItem, type ParsedApiKey, type Problem, type QueueOptions, type Recurrence, type RequestOptions, type Result, type SearchRequest, type SearchResponse, type SessionSource, type SourceCoverage, type Speaker, type SpeakerRef, type Subject, type SubjectKind, type SubjectToken, type SubjectTokenRequest, TOOL_DEFINITIONS, TOOL_NAMES, type TargetModel, Task, type TaskAction, type TaskEndedItem, type TaskEvent, type TaskParams, type TimelineRequest, type TimelineResponse, type Timeouts, type Timestamp, type Timings, type ToolBinding, type ToolDefinition, type TrackEvent, type TurnOptions, type UploadParams, VERSION, type Verification, type VerificationResult, type VerifyItem, type VerifyMethod, type VerifyParams, type View, type Visibility, type VoiceInfo, type WrapSession, type WriteResult, baseURLFromKey, consoleLogger, handles, injectContext, modelUsage, parseApiKey, providerOf, renderLive, renderSuffix, silentLogger, toObjectRef, tokenCounts, uuidv7, wrap };