@mitralab.io/sdk-core 0.2.10 → 0.2.11-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -129,6 +129,9 @@ function isInteger(value) {
129
129
  function isNullableInteger(value) {
130
130
  return value === null || isInteger(value);
131
131
  }
132
+ function isFiniteNumber(value) {
133
+ return typeof value === "number" && Number.isFinite(value);
134
+ }
132
135
  function isStringRecord(value) {
133
136
  return isObject(value) && Object.values(value).every((item) => typeof item === "string");
134
137
  }
@@ -1016,7 +1019,69 @@ function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory)
1016
1019
  for (const field of ["id", "sender", "type", "content", "createdAt"]) {
1017
1020
  if (typeof message[field] !== "string") invalidField(context, field, errors);
1018
1021
  }
1019
- return message;
1022
+ if (message.usage === void 0) return message;
1023
+ const { usage: rawUsage, ...rest } = message;
1024
+ const usage = agentTurnUsageOf(rawUsage);
1025
+ return { ...rest, ...usage ? { usage } : {} };
1026
+ }
1027
+ var TURN_USAGE_COUNTS = [
1028
+ "reasoningTokens",
1029
+ "cacheReadTokens",
1030
+ "cacheCreationTokens",
1031
+ "requestCount",
1032
+ "durationMs"
1033
+ ];
1034
+ var TURN_USAGE_COSTS = ["costUsd", "costUsdRaw"];
1035
+ var TURN_USAGE_STRINGS = [
1036
+ "model",
1037
+ "provider",
1038
+ "costSource",
1039
+ "authMode",
1040
+ "requestMessageId"
1041
+ ];
1042
+ var TURN_USAGE_REQUEST_COUNTS = [
1043
+ "inputTokens",
1044
+ "outputTokens",
1045
+ "cacheReadTokens",
1046
+ "cacheCreationTokens"
1047
+ ];
1048
+ function isCount(value) {
1049
+ return isInteger(value) && value >= 0;
1050
+ }
1051
+ function agentTurnUsageOf(value) {
1052
+ if (!isObject(value)) return void 0;
1053
+ const { inputTokens, outputTokens } = value;
1054
+ if (!isCount(inputTokens) || !isCount(outputTokens)) return void 0;
1055
+ const usage = { inputTokens, outputTokens };
1056
+ for (const field of TURN_USAGE_COUNTS) {
1057
+ const item = value[field];
1058
+ if (isCount(item)) usage[field] = item;
1059
+ }
1060
+ for (const field of TURN_USAGE_COSTS) {
1061
+ const item = value[field];
1062
+ if (isFiniteNumber(item)) usage[field] = item;
1063
+ }
1064
+ for (const field of TURN_USAGE_STRINGS) {
1065
+ const item = value[field];
1066
+ if (typeof item === "string") usage[field] = item;
1067
+ }
1068
+ if (Array.isArray(value.requests)) {
1069
+ usage.requests = value.requests.flatMap((item) => {
1070
+ const request = agentTurnUsageRequestOf(item);
1071
+ return request ? [request] : [];
1072
+ });
1073
+ }
1074
+ return usage;
1075
+ }
1076
+ function agentTurnUsageRequestOf(value) {
1077
+ if (!isObject(value)) return void 0;
1078
+ const request = {};
1079
+ if (typeof value.model === "string") request.model = value.model;
1080
+ for (const field of TURN_USAGE_REQUEST_COUNTS) {
1081
+ const item = value[field];
1082
+ if (isCount(item)) request[field] = item;
1083
+ }
1084
+ return Object.keys(request).length > 0 ? request : void 0;
1020
1085
  }
1021
1086
  function expectAgentModel(value, context, errors = defaultSdkCoreErrorFactory) {
1022
1087
  const model = expectObject(value, context, errors);
@@ -1611,15 +1676,21 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1611
1676
  );
1612
1677
  },
1613
1678
  async listMessages(id, options = {}) {
1614
- return expectPage(
1679
+ const context = "Agent message page response";
1680
+ const page = expectPage(
1615
1681
  await transport.request(`${path(id)}/messages`, {
1616
1682
  method: "GET",
1617
1683
  params: { page: options.page, size: options.size, sort: options.sort }
1618
1684
  }),
1619
- "Agent message page response",
1620
- errors,
1621
- expectAgentMessage
1685
+ context,
1686
+ errors
1622
1687
  );
1688
+ return {
1689
+ ...page,
1690
+ content: page.content.map(
1691
+ (message, position) => expectAgentMessage(message, `${context} item ${position}`, errors)
1692
+ )
1693
+ };
1623
1694
  },
1624
1695
  async channel(id) {
1625
1696
  return expectAgentTaskChannel(
@@ -3975,7 +4046,8 @@ function toAgentTimelineItem(message) {
3975
4046
  id: message.id,
3976
4047
  kind: message.sender === "USER" ? "user" : "agent",
3977
4048
  text: message.content,
3978
- at: message.createdAt
4049
+ at: message.createdAt,
4050
+ ...message.usage ? { usage: message.usage } : {}
3979
4051
  };
3980
4052
  }
3981
4053
  function createAgentTaskSessionManager(options) {
@@ -4038,6 +4110,7 @@ var CoreAgentTaskSession = class {
4038
4110
  recoveryPromise = null;
4039
4111
  recoveryGeneration = 0;
4040
4112
  recoveredTerminalReason;
4113
+ recoveredTerminalUsage;
4041
4114
  cancelTimer = null;
4042
4115
  queueSequence = 0;
4043
4116
  activeWaiter;
@@ -4235,6 +4308,7 @@ var CoreAgentTaskSession = class {
4235
4308
  this._content = "";
4236
4309
  this.recoveryUsed = false;
4237
4310
  this.recoveredTerminalReason = void 0;
4311
+ this.recoveredTerminalUsage = void 0;
4238
4312
  this.recoveryGeneration += 1;
4239
4313
  this.activeWaiter = waiter;
4240
4314
  this.setStatus("streaming");
@@ -4350,7 +4424,7 @@ var CoreAgentTaskSession = class {
4350
4424
  return true;
4351
4425
  }
4352
4426
  this._content = recovered.content;
4353
- this.finishTurn(reason);
4427
+ this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
4354
4428
  return true;
4355
4429
  }
4356
4430
  /** True once the server took the input; false when the box refused it on the stream. */
@@ -4392,15 +4466,17 @@ var CoreAgentTaskSession = class {
4392
4466
  case "stepFinish": {
4393
4467
  const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
4394
4468
  const lifecycle = payload?.lifecycle;
4469
+ const usage = agentTurnUsageOf(payload?.usage);
4395
4470
  if (reason === "interrupted" || lifecycle?.interruptTerminal === true) {
4396
4471
  this.rememberFinishedTurn(lifecycle);
4397
- this.finishTurn("interrupted");
4472
+ this.finishTurn("interrupted", usage);
4398
4473
  break;
4399
4474
  }
4400
4475
  if (reason === "stop" || reason === "endTurn") {
4401
4476
  this.rememberFinishedTurn(lifecycle);
4402
4477
  if (this.recoveryUsed) {
4403
4478
  this.recoveredTerminalReason = reason;
4479
+ this.recoveredTerminalUsage = usage;
4404
4480
  if (!this.recoveryPromise) {
4405
4481
  const generation = this.recoveryGeneration;
4406
4482
  this.recoveryPromise = this.recoverTurn(generation).finally(() => {
@@ -4408,7 +4484,7 @@ var CoreAgentTaskSession = class {
4408
4484
  });
4409
4485
  }
4410
4486
  } else {
4411
- this.finishTurn(reason);
4487
+ this.finishTurn(reason, usage);
4412
4488
  }
4413
4489
  }
4414
4490
  break;
@@ -4456,7 +4532,7 @@ var CoreAgentTaskSession = class {
4456
4532
  ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4457
4533
  });
4458
4534
  }
4459
- finishTurn(reason) {
4535
+ finishTurn(reason, usage) {
4460
4536
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4461
4537
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
4462
4538
  this.cancelTimer = null;
@@ -4470,7 +4546,12 @@ var CoreAgentTaskSession = class {
4470
4546
  this.setStatus("error");
4471
4547
  return;
4472
4548
  }
4473
- const result = { task, content: this._content, reason };
4549
+ const result = {
4550
+ task,
4551
+ content: this._content,
4552
+ reason,
4553
+ ...usage ? { usage } : {}
4554
+ };
4474
4555
  this.emit("turnEnd", result);
4475
4556
  this.activeWaiter?.resolve(result);
4476
4557
  this.activeWaiter = void 0;
package/dist/index.d.cts CHANGED
@@ -1095,12 +1095,57 @@ interface AgentTaskChannel {
1095
1095
  /** Last sequence in the box log, 0 when the box reported none. */
1096
1096
  lastSequence: number;
1097
1097
  }
1098
+ /** One call to the provider inside a turn, or one model's total when the source gives only that. */
1099
+ interface AgentTurnUsageRequest {
1100
+ model?: string;
1101
+ inputTokens?: number;
1102
+ outputTokens?: number;
1103
+ cacheReadTokens?: number;
1104
+ cacheCreationTokens?: number;
1105
+ }
1106
+ /**
1107
+ * What one Agent turn consumed. `inputTokens` is the input without cache, as in the legacy
1108
+ * platform: cache reads and writes are counted apart in `cacheReadTokens` and
1109
+ * `cacheCreationTokens`. Codex sends no cost and no cache writes.
1110
+ */
1111
+ interface AgentTurnUsage {
1112
+ inputTokens: number;
1113
+ outputTokens: number;
1114
+ reasoningTokens?: number;
1115
+ cacheReadTokens?: number;
1116
+ cacheCreationTokens?: number;
1117
+ model?: string;
1118
+ provider?: string;
1119
+ /** Cost of this turn in USD. */
1120
+ costUsd?: number;
1121
+ /** Cost the provider reported for its whole session so far, in USD. */
1122
+ costUsdRaw?: number;
1123
+ costSource?: string;
1124
+ /** Provider calls made in the turn. */
1125
+ requestCount?: number;
1126
+ requests?: AgentTurnUsageRequest[];
1127
+ /**
1128
+ * How the turn's credential was billed. Open to other strings so a mode the Copilot adds later
1129
+ * reaches the caller instead of being dropped. Only the Copilot's record has it, so it shows
1130
+ * in the history and in a recovered turn, never in the live `turnEnd`.
1131
+ */
1132
+ authMode?: "subscription" | "api_key" | "included_ai" | "custom" | "unknown" | (string & {});
1133
+ /** Provider time, sent by the box in `stepFinish`: live in `turnEnd` and in the history. */
1134
+ durationMs?: number;
1135
+ /**
1136
+ * The person's message that opened the turn. Only the Copilot's record has it, so it shows in
1137
+ * the history and in a recovered turn, never in the live `turnEnd`.
1138
+ */
1139
+ requestMessageId?: string;
1140
+ }
1098
1141
  interface AgentMessage {
1099
1142
  id: string;
1100
1143
  sender: string;
1101
1144
  type: string;
1102
1145
  content: string;
1103
1146
  createdAt: string;
1147
+ /** Present on the Agent message that closed a turn, when the Copilot recorded its usage. */
1148
+ usage?: AgentTurnUsage;
1104
1149
  }
1105
1150
  interface AgentModel {
1106
1151
  model: string;
@@ -1945,6 +1990,8 @@ type AgentTimelineItem = {
1945
1990
  kind: "user" | "agent";
1946
1991
  text: string;
1947
1992
  at: string;
1993
+ /** Only on the `agent` item that closed a turn, when the Copilot recorded its usage. */
1994
+ usage?: AgentTurnUsage;
1948
1995
  } | {
1949
1996
  id: string;
1950
1997
  kind: "tool";
@@ -1955,6 +2002,8 @@ interface AgentTurnResult {
1955
2002
  task: AgentTask;
1956
2003
  content: string;
1957
2004
  reason: string;
2005
+ /** What the turn consumed, from the box's `stepFinish`; absent when the turn reported none. */
2006
+ usage?: AgentTurnUsage;
1958
2007
  }
1959
2008
  interface AgentTaskSessionEventMap {
1960
2009
  statusChange: {
@@ -2091,4 +2140,4 @@ declare function expectPage<T extends object>(value: unknown, context: string, e
2091
2140
  declare function expectLegacyPage<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory, validateItem?: (value: unknown, context: string, errors: SdkCoreErrorFactory) => T): LegacyPage<T>;
2092
2141
  declare function expectEmpty(value: unknown, context: string, errors?: SdkCoreErrorFactory): void;
2093
2142
 
2094
- export { API_KEY_EXCHANGE_PATH, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentInput, type AgentMessage, type AgentModel, type AgentProviderUsage, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
2143
+ export { API_KEY_EXCHANGE_PATH, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentInput, type AgentMessage, type AgentModel, type AgentProviderUsage, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentTurnUsage, type AgentTurnUsageRequest, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
package/dist/index.d.ts CHANGED
@@ -1095,12 +1095,57 @@ interface AgentTaskChannel {
1095
1095
  /** Last sequence in the box log, 0 when the box reported none. */
1096
1096
  lastSequence: number;
1097
1097
  }
1098
+ /** One call to the provider inside a turn, or one model's total when the source gives only that. */
1099
+ interface AgentTurnUsageRequest {
1100
+ model?: string;
1101
+ inputTokens?: number;
1102
+ outputTokens?: number;
1103
+ cacheReadTokens?: number;
1104
+ cacheCreationTokens?: number;
1105
+ }
1106
+ /**
1107
+ * What one Agent turn consumed. `inputTokens` is the input without cache, as in the legacy
1108
+ * platform: cache reads and writes are counted apart in `cacheReadTokens` and
1109
+ * `cacheCreationTokens`. Codex sends no cost and no cache writes.
1110
+ */
1111
+ interface AgentTurnUsage {
1112
+ inputTokens: number;
1113
+ outputTokens: number;
1114
+ reasoningTokens?: number;
1115
+ cacheReadTokens?: number;
1116
+ cacheCreationTokens?: number;
1117
+ model?: string;
1118
+ provider?: string;
1119
+ /** Cost of this turn in USD. */
1120
+ costUsd?: number;
1121
+ /** Cost the provider reported for its whole session so far, in USD. */
1122
+ costUsdRaw?: number;
1123
+ costSource?: string;
1124
+ /** Provider calls made in the turn. */
1125
+ requestCount?: number;
1126
+ requests?: AgentTurnUsageRequest[];
1127
+ /**
1128
+ * How the turn's credential was billed. Open to other strings so a mode the Copilot adds later
1129
+ * reaches the caller instead of being dropped. Only the Copilot's record has it, so it shows
1130
+ * in the history and in a recovered turn, never in the live `turnEnd`.
1131
+ */
1132
+ authMode?: "subscription" | "api_key" | "included_ai" | "custom" | "unknown" | (string & {});
1133
+ /** Provider time, sent by the box in `stepFinish`: live in `turnEnd` and in the history. */
1134
+ durationMs?: number;
1135
+ /**
1136
+ * The person's message that opened the turn. Only the Copilot's record has it, so it shows in
1137
+ * the history and in a recovered turn, never in the live `turnEnd`.
1138
+ */
1139
+ requestMessageId?: string;
1140
+ }
1098
1141
  interface AgentMessage {
1099
1142
  id: string;
1100
1143
  sender: string;
1101
1144
  type: string;
1102
1145
  content: string;
1103
1146
  createdAt: string;
1147
+ /** Present on the Agent message that closed a turn, when the Copilot recorded its usage. */
1148
+ usage?: AgentTurnUsage;
1104
1149
  }
1105
1150
  interface AgentModel {
1106
1151
  model: string;
@@ -1945,6 +1990,8 @@ type AgentTimelineItem = {
1945
1990
  kind: "user" | "agent";
1946
1991
  text: string;
1947
1992
  at: string;
1993
+ /** Only on the `agent` item that closed a turn, when the Copilot recorded its usage. */
1994
+ usage?: AgentTurnUsage;
1948
1995
  } | {
1949
1996
  id: string;
1950
1997
  kind: "tool";
@@ -1955,6 +2002,8 @@ interface AgentTurnResult {
1955
2002
  task: AgentTask;
1956
2003
  content: string;
1957
2004
  reason: string;
2005
+ /** What the turn consumed, from the box's `stepFinish`; absent when the turn reported none. */
2006
+ usage?: AgentTurnUsage;
1958
2007
  }
1959
2008
  interface AgentTaskSessionEventMap {
1960
2009
  statusChange: {
@@ -2091,4 +2140,4 @@ declare function expectPage<T extends object>(value: unknown, context: string, e
2091
2140
  declare function expectLegacyPage<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory, validateItem?: (value: unknown, context: string, errors: SdkCoreErrorFactory) => T): LegacyPage<T>;
2092
2141
  declare function expectEmpty(value: unknown, context: string, errors?: SdkCoreErrorFactory): void;
2093
2142
 
2094
- export { API_KEY_EXCHANGE_PATH, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentInput, type AgentMessage, type AgentModel, type AgentProviderUsage, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
2143
+ export { API_KEY_EXCHANGE_PATH, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentInput, type AgentMessage, type AgentModel, type AgentProviderUsage, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentTurnUsage, type AgentTurnUsageRequest, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
package/dist/index.js CHANGED
@@ -57,6 +57,9 @@ function isInteger(value) {
57
57
  function isNullableInteger(value) {
58
58
  return value === null || isInteger(value);
59
59
  }
60
+ function isFiniteNumber(value) {
61
+ return typeof value === "number" && Number.isFinite(value);
62
+ }
60
63
  function isStringRecord(value) {
61
64
  return isObject(value) && Object.values(value).every((item) => typeof item === "string");
62
65
  }
@@ -944,7 +947,69 @@ function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory)
944
947
  for (const field of ["id", "sender", "type", "content", "createdAt"]) {
945
948
  if (typeof message[field] !== "string") invalidField(context, field, errors);
946
949
  }
947
- return message;
950
+ if (message.usage === void 0) return message;
951
+ const { usage: rawUsage, ...rest } = message;
952
+ const usage = agentTurnUsageOf(rawUsage);
953
+ return { ...rest, ...usage ? { usage } : {} };
954
+ }
955
+ var TURN_USAGE_COUNTS = [
956
+ "reasoningTokens",
957
+ "cacheReadTokens",
958
+ "cacheCreationTokens",
959
+ "requestCount",
960
+ "durationMs"
961
+ ];
962
+ var TURN_USAGE_COSTS = ["costUsd", "costUsdRaw"];
963
+ var TURN_USAGE_STRINGS = [
964
+ "model",
965
+ "provider",
966
+ "costSource",
967
+ "authMode",
968
+ "requestMessageId"
969
+ ];
970
+ var TURN_USAGE_REQUEST_COUNTS = [
971
+ "inputTokens",
972
+ "outputTokens",
973
+ "cacheReadTokens",
974
+ "cacheCreationTokens"
975
+ ];
976
+ function isCount(value) {
977
+ return isInteger(value) && value >= 0;
978
+ }
979
+ function agentTurnUsageOf(value) {
980
+ if (!isObject(value)) return void 0;
981
+ const { inputTokens, outputTokens } = value;
982
+ if (!isCount(inputTokens) || !isCount(outputTokens)) return void 0;
983
+ const usage = { inputTokens, outputTokens };
984
+ for (const field of TURN_USAGE_COUNTS) {
985
+ const item = value[field];
986
+ if (isCount(item)) usage[field] = item;
987
+ }
988
+ for (const field of TURN_USAGE_COSTS) {
989
+ const item = value[field];
990
+ if (isFiniteNumber(item)) usage[field] = item;
991
+ }
992
+ for (const field of TURN_USAGE_STRINGS) {
993
+ const item = value[field];
994
+ if (typeof item === "string") usage[field] = item;
995
+ }
996
+ if (Array.isArray(value.requests)) {
997
+ usage.requests = value.requests.flatMap((item) => {
998
+ const request = agentTurnUsageRequestOf(item);
999
+ return request ? [request] : [];
1000
+ });
1001
+ }
1002
+ return usage;
1003
+ }
1004
+ function agentTurnUsageRequestOf(value) {
1005
+ if (!isObject(value)) return void 0;
1006
+ const request = {};
1007
+ if (typeof value.model === "string") request.model = value.model;
1008
+ for (const field of TURN_USAGE_REQUEST_COUNTS) {
1009
+ const item = value[field];
1010
+ if (isCount(item)) request[field] = item;
1011
+ }
1012
+ return Object.keys(request).length > 0 ? request : void 0;
948
1013
  }
949
1014
  function expectAgentModel(value, context, errors = defaultSdkCoreErrorFactory) {
950
1015
  const model = expectObject(value, context, errors);
@@ -1539,15 +1604,21 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1539
1604
  );
1540
1605
  },
1541
1606
  async listMessages(id, options = {}) {
1542
- return expectPage(
1607
+ const context = "Agent message page response";
1608
+ const page = expectPage(
1543
1609
  await transport.request(`${path(id)}/messages`, {
1544
1610
  method: "GET",
1545
1611
  params: { page: options.page, size: options.size, sort: options.sort }
1546
1612
  }),
1547
- "Agent message page response",
1548
- errors,
1549
- expectAgentMessage
1613
+ context,
1614
+ errors
1550
1615
  );
1616
+ return {
1617
+ ...page,
1618
+ content: page.content.map(
1619
+ (message, position) => expectAgentMessage(message, `${context} item ${position}`, errors)
1620
+ )
1621
+ };
1551
1622
  },
1552
1623
  async channel(id) {
1553
1624
  return expectAgentTaskChannel(
@@ -3903,7 +3974,8 @@ function toAgentTimelineItem(message) {
3903
3974
  id: message.id,
3904
3975
  kind: message.sender === "USER" ? "user" : "agent",
3905
3976
  text: message.content,
3906
- at: message.createdAt
3977
+ at: message.createdAt,
3978
+ ...message.usage ? { usage: message.usage } : {}
3907
3979
  };
3908
3980
  }
3909
3981
  function createAgentTaskSessionManager(options) {
@@ -3966,6 +4038,7 @@ var CoreAgentTaskSession = class {
3966
4038
  recoveryPromise = null;
3967
4039
  recoveryGeneration = 0;
3968
4040
  recoveredTerminalReason;
4041
+ recoveredTerminalUsage;
3969
4042
  cancelTimer = null;
3970
4043
  queueSequence = 0;
3971
4044
  activeWaiter;
@@ -4163,6 +4236,7 @@ var CoreAgentTaskSession = class {
4163
4236
  this._content = "";
4164
4237
  this.recoveryUsed = false;
4165
4238
  this.recoveredTerminalReason = void 0;
4239
+ this.recoveredTerminalUsage = void 0;
4166
4240
  this.recoveryGeneration += 1;
4167
4241
  this.activeWaiter = waiter;
4168
4242
  this.setStatus("streaming");
@@ -4278,7 +4352,7 @@ var CoreAgentTaskSession = class {
4278
4352
  return true;
4279
4353
  }
4280
4354
  this._content = recovered.content;
4281
- this.finishTurn(reason);
4355
+ this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
4282
4356
  return true;
4283
4357
  }
4284
4358
  /** True once the server took the input; false when the box refused it on the stream. */
@@ -4320,15 +4394,17 @@ var CoreAgentTaskSession = class {
4320
4394
  case "stepFinish": {
4321
4395
  const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
4322
4396
  const lifecycle = payload?.lifecycle;
4397
+ const usage = agentTurnUsageOf(payload?.usage);
4323
4398
  if (reason === "interrupted" || lifecycle?.interruptTerminal === true) {
4324
4399
  this.rememberFinishedTurn(lifecycle);
4325
- this.finishTurn("interrupted");
4400
+ this.finishTurn("interrupted", usage);
4326
4401
  break;
4327
4402
  }
4328
4403
  if (reason === "stop" || reason === "endTurn") {
4329
4404
  this.rememberFinishedTurn(lifecycle);
4330
4405
  if (this.recoveryUsed) {
4331
4406
  this.recoveredTerminalReason = reason;
4407
+ this.recoveredTerminalUsage = usage;
4332
4408
  if (!this.recoveryPromise) {
4333
4409
  const generation = this.recoveryGeneration;
4334
4410
  this.recoveryPromise = this.recoverTurn(generation).finally(() => {
@@ -4336,7 +4412,7 @@ var CoreAgentTaskSession = class {
4336
4412
  });
4337
4413
  }
4338
4414
  } else {
4339
- this.finishTurn(reason);
4415
+ this.finishTurn(reason, usage);
4340
4416
  }
4341
4417
  }
4342
4418
  break;
@@ -4384,7 +4460,7 @@ var CoreAgentTaskSession = class {
4384
4460
  ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4385
4461
  });
4386
4462
  }
4387
- finishTurn(reason) {
4463
+ finishTurn(reason, usage) {
4388
4464
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4389
4465
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
4390
4466
  this.cancelTimer = null;
@@ -4398,7 +4474,12 @@ var CoreAgentTaskSession = class {
4398
4474
  this.setStatus("error");
4399
4475
  return;
4400
4476
  }
4401
- const result = { task, content: this._content, reason };
4477
+ const result = {
4478
+ task,
4479
+ content: this._content,
4480
+ reason,
4481
+ ...usage ? { usage } : {}
4482
+ };
4402
4483
  this.emit("turnEnd", result);
4403
4484
  this.activeWaiter?.resolve(result);
4404
4485
  this.activeWaiter = void 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.2.10",
3
+ "version": "0.2.11-beta.0",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,