@granular-software/sdk 0.4.50 → 0.4.51

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.
@@ -256,6 +256,13 @@ interface ConnectOptions extends OpenEnvironmentOptions {
256
256
  interface CreateSessionOptions {
257
257
  /** Optional stable client ID. Defaults to `client_${Date.now()}`. */
258
258
  clientId?: string;
259
+ /**
260
+ * Optional application-owned history scope for this conversation.
261
+ *
262
+ * Use the same value when listing sessions or reading the materialized user
263
+ * environment state so unrelated product surfaces never share history.
264
+ */
265
+ sessionScope?: string;
259
266
  /**
260
267
  * Optional session heap seed. Each item uses application record identity:
261
268
  * class name plus the record id from the customer's own system. Granular
@@ -285,6 +292,23 @@ interface ConversationSessionInfo {
285
292
  jobCount?: number;
286
293
  toolCallCount?: number;
287
294
  }
295
+ type ConversationSessionListStatus = ConversationSessionInfo["status"] | "all";
296
+ /**
297
+ * Bounded filters for indexed conversation history.
298
+ *
299
+ * At least one ownership filter (`environmentId`, `sandboxId`, or
300
+ * `subjectId`) is required by the SDK. Results are newest-first and default to
301
+ * 100 rows; use `offset` to request the next page.
302
+ */
303
+ interface ConversationSessionListOptions {
304
+ environmentId?: string;
305
+ sandboxId?: string;
306
+ subjectId?: string;
307
+ sessionScope?: string | null;
308
+ status?: ConversationSessionListStatus;
309
+ limit?: number;
310
+ offset?: number;
311
+ }
288
312
  type SpendLineItemType = "llm_tokens" | "granular_session_time" | string;
289
313
  type QuotaScopeType = "tenant" | "sandbox" | "permission_profile" | "subject";
290
314
  type QuotaPeriod = "hour" | "day" | "week" | "month";
@@ -893,6 +917,10 @@ interface Job {
893
917
  }
894
918
  interface Prompt {
895
919
  id: string;
920
+ /** Job that owns this prompt, when it was opened by a running job. */
921
+ jobId?: string;
922
+ /** Harness turn that owns this prompt. */
923
+ turnId?: string;
896
924
  type: "confirm" | "choice" | "input";
897
925
  title: string;
898
926
  message: string;
@@ -913,6 +941,33 @@ interface ConversationMessageShowRefs {
913
941
  fileIds?: string[];
914
942
  sessionArtifactIds?: string[];
915
943
  actionSuggestions?: ConversationActionSuggestion[];
944
+ tables?: ConversationTableProjection[];
945
+ }
946
+ type ConversationTableCell = string | number | boolean | null | {
947
+ kind: "relative_time" | "date";
948
+ value: string | number;
949
+ };
950
+ interface ConversationTableColumn {
951
+ id: string;
952
+ label: string;
953
+ }
954
+ interface ConversationTableRowReference {
955
+ entryPath?: string;
956
+ className?: string;
957
+ id?: string;
958
+ label?: string;
959
+ }
960
+ interface ConversationTableRow {
961
+ id: string;
962
+ reference?: ConversationTableRowReference;
963
+ cells: ConversationTableCell[];
964
+ }
965
+ interface ConversationTableProjection {
966
+ id: string;
967
+ label?: string;
968
+ source?: string;
969
+ columns: ConversationTableColumn[];
970
+ rows: ConversationTableRow[];
916
971
  }
917
972
  interface ConversationActionSuggestion {
918
973
  suggestionId?: string;
@@ -922,13 +977,35 @@ interface ConversationActionSuggestion {
922
977
  target?: Record<string, unknown> | null;
923
978
  metadata?: Record<string, unknown>;
924
979
  }
980
+ /** A normalized action embedded in an ordered assistant message stream. */
981
+ interface ConversationMessageAction {
982
+ kind: "frontend" | "backend" | "system";
983
+ label: string;
984
+ status?: "done" | "queued" | "failed";
985
+ }
986
+ /**
987
+ * A durable assistant message segment in the order it reached the client.
988
+ *
989
+ * `content` and `actions` remain the canonical compatibility fields on the
990
+ * message. Parts only preserve their interleaving for capable clients.
991
+ */
992
+ type ConversationMessagePart = {
993
+ type: "text";
994
+ text: string;
995
+ } | {
996
+ type: "action";
997
+ action: ConversationMessageAction;
998
+ };
925
999
  interface ConversationMessageInput {
1000
+ /** Optional caller-owned id used to correlate optimistic and durable turns. */
1001
+ id?: string;
926
1002
  role: "user" | "assistant";
927
1003
  content?: string;
928
1004
  show?: ConversationMessageShowRefs;
929
1005
  reasoningLines?: string[];
930
1006
  reasoningDurationMs?: number;
931
1007
  actions?: Array<Record<string, unknown>>;
1008
+ parts?: ConversationMessagePart[];
932
1009
  target?: Record<string, unknown>;
933
1010
  jobId?: string;
934
1011
  promptId?: string;
@@ -949,6 +1026,7 @@ interface SessionConversationMessage {
949
1026
  reasoningLines?: string[];
950
1027
  reasoningDurationMs?: number;
951
1028
  actions?: Array<Record<string, unknown>>;
1029
+ parts?: ConversationMessagePart[];
952
1030
  target?: Record<string, unknown>;
953
1031
  jobId?: string;
954
1032
  promptId?: string;
@@ -998,6 +1076,25 @@ interface SessionFileRecord {
998
1076
  }
999
1077
  type SessionArtifactStatus = "draft" | "ready" | "needs_edit" | "blocked" | "running" | "awaiting_human" | "completed" | "partially_completed" | "failed" | "canceled" | "stale";
1000
1078
  type SessionArtifactKind = "effect" | "batch" | "state_path";
1079
+ /**
1080
+ * Declarative impact metadata consumed by deterministic clients before an
1081
+ * artifact can execute. Missing metadata must be treated conservatively.
1082
+ */
1083
+ interface SessionArtifactAutonomyPolicy {
1084
+ sideEffect?: "read" | "readonly" | "read_only" | "ui" | "write" | "delete" | "destructive" | "irreversible";
1085
+ scope?: "internal" | "bulk" | "external" | "financial" | "permission";
1086
+ risk?: "low" | "medium" | "high";
1087
+ targetCount?: number;
1088
+ reversible?: boolean;
1089
+ destructive?: boolean;
1090
+ external?: boolean;
1091
+ financial?: boolean;
1092
+ permissionChange?: boolean;
1093
+ reverse?: string | Record<string, unknown>;
1094
+ undo?: string | Record<string, unknown>;
1095
+ rollback?: string | Record<string, unknown>;
1096
+ [key: string]: unknown;
1097
+ }
1001
1098
  interface SessionArtifactRecord {
1002
1099
  artifactId: string;
1003
1100
  sessionId?: string | null;
@@ -1023,8 +1120,10 @@ interface SessionArtifactRecord {
1023
1120
  } | null;
1024
1121
  relationships?: Record<string, string | string[] | null>;
1025
1122
  validation?: Record<string, unknown> | null;
1026
- policy?: Record<string, unknown> | null;
1027
- metadata?: Record<string, unknown>;
1123
+ policy?: SessionArtifactAutonomyPolicy | null;
1124
+ metadata?: Record<string, unknown> & {
1125
+ autonomy?: SessionArtifactAutonomyPolicy;
1126
+ };
1028
1127
  parentArtifactId?: string | null;
1029
1128
  subArtifactIds?: string[];
1030
1129
  createdAt: number;
@@ -1274,6 +1373,8 @@ interface SessionTranscriptEntry {
1274
1373
  jobResultPreview?: string;
1275
1374
  error?: string;
1276
1375
  show?: ConversationMessageShowRefs;
1376
+ actions?: ConversationMessageAction[];
1377
+ parts?: ConversationMessagePart[];
1277
1378
  historyContent?: string;
1278
1379
  source: "conversation" | "job_code" | "job_result" | "job_prompt" | "job_agent_message";
1279
1380
  }
@@ -1344,6 +1445,8 @@ interface SessionDocumentResult {
1344
1445
  interface SessionCollectionListOptions {
1345
1446
  limit?: number;
1346
1447
  cursor?: string | null;
1448
+ /** Return only the newest page, in chronological order. */
1449
+ latest?: boolean | null;
1347
1450
  }
1348
1451
  interface SessionJobListOptions extends SessionCollectionListOptions {
1349
1452
  status?: string | null;
@@ -1393,6 +1496,8 @@ interface UserEnvironmentState {
1393
1496
  tenantId?: string;
1394
1497
  sessionScope?: string | null;
1395
1498
  updatedAt: number;
1499
+ /** Monotonic materialized-index revision used for conditional refreshes. */
1500
+ revision?: number;
1396
1501
  stateSource?: "user_environment_snapshot" | "live_session_aggregate";
1397
1502
  stale?: boolean;
1398
1503
  snapshotUpdatedAt?: number | null;
@@ -1434,6 +1539,7 @@ interface WSClientOptions {
1434
1539
  url: string;
1435
1540
  sessionId: string;
1436
1541
  token: string;
1542
+ initialDocumentSnapshot?: Record<string, unknown> | Uint8Array | null;
1437
1543
  tokenProvider?: AccessTokenProvider;
1438
1544
  WebSocketCtor?: any;
1439
1545
  maxReconnectAttempts?: number;
@@ -2082,13 +2188,23 @@ interface OpenAIModelPricing {
2082
2188
  currency: "USD";
2083
2189
  inputUsdPerMillion: number;
2084
2190
  cachedInputUsdPerMillion: number;
2191
+ cacheWriteUsdPerMillion?: number | null;
2085
2192
  outputUsdPerMillion: number;
2193
+ contextTier?: "short" | "long";
2194
+ longContextThresholdTokens?: number | null;
2195
+ longContextPricing?: {
2196
+ inputUsdPerMillion: number;
2197
+ cachedInputUsdPerMillion: number;
2198
+ cacheWriteUsdPerMillion?: number | null;
2199
+ outputUsdPerMillion: number;
2200
+ };
2086
2201
  sourceUrl: string;
2087
2202
  effectiveDate: string;
2088
2203
  }
2089
2204
  interface NormalizedOpenAIUsage {
2090
2205
  inputTokens: number;
2091
2206
  cachedInputTokens: number;
2207
+ cacheWriteTokens: number;
2092
2208
  uncachedInputTokens: number;
2093
2209
  outputTokens: number;
2094
2210
  reasoningTokens: number;
@@ -2099,6 +2215,7 @@ interface OpenAITokenSpend {
2099
2215
  model: string;
2100
2216
  inputTokens: number;
2101
2217
  cachedInputTokens: number;
2218
+ cacheWriteTokens: number;
2102
2219
  uncachedInputTokens: number;
2103
2220
  outputTokens: number;
2104
2221
  reasoningTokens: number;
@@ -2107,13 +2224,17 @@ interface OpenAITokenSpend {
2107
2224
  currency: "USD";
2108
2225
  inputPricePerMillionMicros: number;
2109
2226
  cachedInputPricePerMillionMicros: number;
2227
+ cacheWritePricePerMillionMicros: number | null;
2228
+ cacheWriteCostMicros: number;
2110
2229
  outputPricePerMillionMicros: number;
2230
+ pricingContextTier: "short" | "long";
2231
+ longContextThresholdTokens: number | null;
2111
2232
  pricingSource: string;
2112
2233
  pricingEffectiveAt: string;
2113
2234
  usage: NormalizedOpenAIUsage;
2114
2235
  }
2115
2236
  declare const OPENAI_MODEL_PRICING_USD_PER_MILLION: Record<string, OpenAIModelPricing>;
2116
- declare function getOpenAIModelPricing(model: string): OpenAIModelPricing | null;
2237
+ declare function getOpenAIModelPricing(model: string, inputTokens?: number): OpenAIModelPricing | null;
2117
2238
  declare function normalizeOpenAIUsage(rawUsage: unknown): NormalizedOpenAIUsage;
2118
2239
  declare function calculateOpenAITokenSpend(model: string, rawUsage: unknown): OpenAITokenSpend | null;
2119
2240
 
@@ -2151,4 +2272,4 @@ declare function toGranularHttpBase(apiUrl: string): string;
2151
2272
  declare function buildOpenAISpendEventId(usage: Pick<OpenAIUsageSpendEvent, "requestId">, context?: GranularSpendContext): string | undefined;
2152
2273
  declare function recordOpenAIUsageSpend(options: RecordOpenAIUsageSpendOptions): Promise<RecordOpenAIUsageSpendResult>;
2153
2274
 
2154
- export { type GranularQuotaProgress as $, type AccessTokenProvider as A, type RecordUserOptions as B, type ConditionIR as C, type DomainState as D, type EndpointMode as E, type Subject as F, type GranularSpendContext as G, type OpenEnvironmentOptions as H, type InstanceToolHandler as I, type ConnectOptions as J, type CreateSessionOptions as K, type ConversationSessionInfo as L, type ManifestEffectMetamodelSpec as M, type NormalizedOpenAIUsage as N, type OpenAIModelPricing as O, type Prompt as P, type SpendLineItemType as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type QuotaScopeType as V, type QuotaPeriod as W, type QuotaStatus as X, type SpendSummary as Y, type QuotaLineItemFilter as Z, type GranularQuotaPolicy as _, type EffectHandlerContext as a, type SessionArtifactExecutionResult as a$, type Sandbox as a0, type CreateSandboxData as a1, type SandboxListResponse as a2, type PermissionRules as a3, type PermissionProfile as a4, type CreatePermissionProfileData as a5, type PermissionProfileListResponse as a6, type Assignment as a7, type AssignmentListResponse as a8, type BuildPolicy as a9, type EffectsChangedEvent as aA, type EffectHandler as aB, type InstanceEffectHandler as aC, type JobStatus as aD, type JobFeedbackSentiment as aE, type JobFeedbackToolCall as aF, type JobFeedbackMetadata as aG, type JobFeedbackInput as aH, type JobFeedbackRecord as aI, type EnvironmentFeedbackRecord as aJ, type JobSubmitResult as aK, type Job as aL, type ConversationMessageShowRefs as aM, type ConversationActionSuggestion as aN, type ConversationMessageInput as aO, type ConversationAppendResult as aP, type SessionConversationMessage as aQ, type SessionTimelineEvent as aR, type SessionFileSource as aS, type SessionFileKind as aT, type SessionFileStatus as aU, type SessionFileRecord as aV, type SessionArtifactStatus as aW, type SessionArtifactKind as aX, type SessionArtifactRecord as aY, type SessionArtifactListOptions as aZ, type SessionArtifactValidationResult as a_, type VersionTracking as aa, type VersionTag as ab, type EnvironmentData as ac, type CreateEnvironmentData as ad, type EnvironmentListResponse as ae, type Manifest as af, type ManifestListResponse as ag, type BuildStatus as ah, type Build as ai, type Version as aj, type BuildListResponse as ak, type SemanticVersionDiffEntry as al, type SemanticVersionDiff as am, type ResolvedEffectPostCondition as an, type ResolvedEffectDryRun as ao, type ResolvedEffectReverse as ap, type ResolvedEffectApprovalRequired as aq, type EffectInvocationMode as ar, type EffectInvocationMetadata as as, type EffectSchema as at, type EffectWithHandler as au, type PublishEffectsResult as av, type EffectVersionSelector as aw, type ToolInfo as ax, type EffectInfo as ay, type ToolsChangedEvent as az, type SessionHeapList as b, type RecordImport as b$, type SessionArtifactExecutionOptions as b0, type SessionArtifactApprovalOptions as b1, type ArtifactApprovalTaskStatus as b2, type ArtifactApprovalTask as b3, type ArtifactApprovalTaskListOptions as b4, type ArtifactApprovalDecisionInput as b5, type ArtifactApprovalDecisionResult as b6, type ManualActionStatus as b7, type ManualActionSource as b8, type ManualActionTarget as b9, type WSReconnectErrorInfo as bA, type WSClientOptions as bB, type RPCRequest as bC, type RPCResponse as bD, type SyncMessage as bE, type RPCRequestFromServer as bF, type ToolInvokeParams as bG, type ToolResultParams as bH, type ModelRef as bI, type RelationshipInfo as bJ, type DefineRelationshipOptions as bK, type RecordObjectOptions as bL, type RecordObjectStateValue as bM, type EnvironmentStateTarget as bN, type EnvironmentStateObservationInput as bO, type EnvironmentStateUpdateInput as bP, type EnvironmentStateMachineProxy as bQ, type EnvironmentStateProxy as bR, type RecordObjectResult as bS, type RecordObjectsChunkInfo as bT, type RecordObjectsOptions as bU, type RecordImportWriteMode as bV, type RecordImportOptions as bW, type RecordImportStatus as bX, type RecordImportItemStatus as bY, type RecordImportStats as bZ, type RecordImportItem as b_, type ManualActionRelatedRecord as ba, type RecordManualActionInput as bb, type ManualActionOccurrence as bc, type ManualActionRecordResult as bd, type ManualActionListOptions as be, type ManualActionSuggestion as bf, type ManualActionSuggestionOptions as bg, type SessionFileUploadOptions as bh, type SessionJobRecord as bi, type SessionHeapFieldType as bj, type SessionHeapFieldValue as bk, type SessionHeapVariable as bl, type RecordSearchResult as bm, type RecordSearchOptions as bn, type RecordMentionInput as bo, type SessionDocumentResult as bp, type SessionCollectionListOptions as bq, type SessionJobListOptions as br, type SessionCollectionListResult as bs, type UserEnvironmentPrompt as bt, type UserEnvironmentMessagePreview as bu, type UserEnvironmentSessionState as bv, type UserEnvironmentState as bw, type UserEnvironmentStateOptions as bx, type MarkUserEnvironmentReadOptions as by, type WSDisconnectInfo as bz, type SessionHeapSnapshot as c, type EnvironmentRecordImportSummary as c0, type EnvironmentSetupTriggerReason as c1, type RunEnvironmentImporterOptions as c2, type EnvironmentSetupLifecycleStatus as c3, type EnvironmentSetupSummary as c4, type EnvironmentImporterImportOptions as c5, type EnvironmentImporter as c6, type ManifestPropertySpec as c7, type ManifestValidationOperator as c8, type ManifestEnumRuleSpec as c9, type GraphQLResult as cA, type APIError as cB, type DeleteResponse as cC, type StreamEvent as cD, type StreamSubscription as cE, type StreamStats as cF, type ManifestFilterBySpec as ca, type ManifestValidationRuleSpec as cb, type ManifestStateMachineStateSpec as cc, type ManifestStateTransitionInputBinding as cd, type ManifestStateTransitionActionSpec as ce, type ManifestStateTransitionAssigneeSpec as cf, type ManifestStateTransitionRelatedStateRequirementSpec as cg, type ManifestStateTransitionRequirementsSpec as ch, type ManifestStateTransitionPermissionSpec as ci, type ManifestStateTransitionExpectedOutcomeSpec as cj, type ManifestStateMachineTransitionSpec as ck, type ManifestStateMachineSpec as cl, type ManifestPostConditionSpec as cm, type ManifestDryRunSpec as cn, type ManifestReverseSpec as co, type ManifestApprovalRequiredSpec as cp, type ManifestCreatesSpec as cq, type ManifestRelationshipDef as cr, type ManifestEffectSchema as cs, type ManifestEffectDeclaration as ct, type ManifestEventTypeDef as cu, type ManifestEventStreamDef as cv, type ManifestOperation as cw, type ManifestImport as cx, type ManifestVolume as cy, type ManifestContent as cz, type SessionTranscriptEntry as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type OpenAITokenSpend as h, OPENAI_MODEL_PRICING_USD_PER_MILLION as i, getOpenAIModelPricing as j, calculateOpenAITokenSpend as k, type OpenAIUsageSpendEvent as l, type RecordOpenAIUsageSpendOptions as m, normalizeOpenAIUsage as n, type RecordOpenAIUsageSpendResult as o, buildOpenAISpendEventId as p, type PolicySource as q, recordOpenAIUsageSpend as r, type PolicyPredicateSource as s, toGranularHttpBase as t, type PolicyOperator as u, type PolicyOrigin as v, type PolicyRuleIR as w, type MatchedPolicy as x, type GranularOptions as y, type GranularAuth as z };
2275
+ export { type QuotaLineItemFilter as $, type AccessTokenProvider as A, type RecordUserOptions as B, type ConditionIR as C, type DomainState as D, type EndpointMode as E, type Subject as F, type GranularSpendContext as G, type OpenEnvironmentOptions as H, type InstanceToolHandler as I, type ConnectOptions as J, type CreateSessionOptions as K, type ConversationSessionInfo as L, type ManifestEffectMetamodelSpec as M, type NormalizedOpenAIUsage as N, type OpenAIModelPricing as O, type Prompt as P, type ConversationSessionListStatus as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type ConversationSessionListOptions as V, type SpendLineItemType as W, type QuotaScopeType as X, type QuotaPeriod as Y, type QuotaStatus as Z, type SpendSummary as _, type EffectHandlerContext as a, type SessionFileSource as a$, type GranularQuotaPolicy as a0, type GranularQuotaProgress as a1, type Sandbox as a2, type CreateSandboxData as a3, type SandboxListResponse as a4, type PermissionRules as a5, type PermissionProfile as a6, type CreatePermissionProfileData as a7, type PermissionProfileListResponse as a8, type Assignment as a9, type EffectInfo as aA, type ToolsChangedEvent as aB, type EffectsChangedEvent as aC, type EffectHandler as aD, type InstanceEffectHandler as aE, type JobStatus as aF, type JobFeedbackSentiment as aG, type JobFeedbackToolCall as aH, type JobFeedbackMetadata as aI, type JobFeedbackInput as aJ, type JobFeedbackRecord as aK, type EnvironmentFeedbackRecord as aL, type JobSubmitResult as aM, type Job as aN, type ConversationMessageShowRefs as aO, type ConversationTableCell as aP, type ConversationTableColumn as aQ, type ConversationTableRowReference as aR, type ConversationTableRow as aS, type ConversationTableProjection as aT, type ConversationActionSuggestion as aU, type ConversationMessageAction as aV, type ConversationMessagePart as aW, type ConversationMessageInput as aX, type ConversationAppendResult as aY, type SessionConversationMessage as aZ, type SessionTimelineEvent as a_, type AssignmentListResponse as aa, type BuildPolicy as ab, type VersionTracking as ac, type VersionTag as ad, type EnvironmentData as ae, type CreateEnvironmentData as af, type EnvironmentListResponse as ag, type Manifest as ah, type ManifestListResponse as ai, type BuildStatus as aj, type Build as ak, type Version as al, type BuildListResponse as am, type SemanticVersionDiffEntry as an, type SemanticVersionDiff as ao, type ResolvedEffectPostCondition as ap, type ResolvedEffectDryRun as aq, type ResolvedEffectReverse as ar, type ResolvedEffectApprovalRequired as as, type EffectInvocationMode as at, type EffectInvocationMetadata as au, type EffectSchema as av, type EffectWithHandler as aw, type PublishEffectsResult as ax, type EffectVersionSelector as ay, type ToolInfo as az, type SessionHeapList as b, type EnvironmentStateProxy as b$, type SessionFileKind as b0, type SessionFileStatus as b1, type SessionFileRecord as b2, type SessionArtifactStatus as b3, type SessionArtifactKind as b4, type SessionArtifactAutonomyPolicy as b5, type SessionArtifactRecord as b6, type SessionArtifactListOptions as b7, type SessionArtifactValidationResult as b8, type SessionArtifactExecutionResult as b9, type SessionCollectionListOptions as bA, type SessionJobListOptions as bB, type SessionCollectionListResult as bC, type UserEnvironmentPrompt as bD, type UserEnvironmentMessagePreview as bE, type UserEnvironmentSessionState as bF, type UserEnvironmentState as bG, type UserEnvironmentStateOptions as bH, type MarkUserEnvironmentReadOptions as bI, type WSDisconnectInfo as bJ, type WSReconnectErrorInfo as bK, type WSClientOptions as bL, type RPCRequest as bM, type RPCResponse as bN, type SyncMessage as bO, type RPCRequestFromServer as bP, type ToolInvokeParams as bQ, type ToolResultParams as bR, type ModelRef as bS, type RelationshipInfo as bT, type DefineRelationshipOptions as bU, type RecordObjectOptions as bV, type RecordObjectStateValue as bW, type EnvironmentStateTarget as bX, type EnvironmentStateObservationInput as bY, type EnvironmentStateUpdateInput as bZ, type EnvironmentStateMachineProxy as b_, type SessionArtifactExecutionOptions as ba, type SessionArtifactApprovalOptions as bb, type ArtifactApprovalTaskStatus as bc, type ArtifactApprovalTask as bd, type ArtifactApprovalTaskListOptions as be, type ArtifactApprovalDecisionInput as bf, type ArtifactApprovalDecisionResult as bg, type ManualActionStatus as bh, type ManualActionSource as bi, type ManualActionTarget as bj, type ManualActionRelatedRecord as bk, type RecordManualActionInput as bl, type ManualActionOccurrence as bm, type ManualActionRecordResult as bn, type ManualActionListOptions as bo, type ManualActionSuggestion as bp, type ManualActionSuggestionOptions as bq, type SessionFileUploadOptions as br, type SessionJobRecord as bs, type SessionHeapFieldType as bt, type SessionHeapFieldValue as bu, type SessionHeapVariable as bv, type RecordSearchResult as bw, type RecordSearchOptions as bx, type RecordMentionInput as by, type SessionDocumentResult as bz, type SessionHeapSnapshot as c, type RecordObjectResult as c0, type RecordObjectsChunkInfo as c1, type RecordObjectsOptions as c2, type RecordImportWriteMode as c3, type RecordImportOptions as c4, type RecordImportStatus as c5, type RecordImportItemStatus as c6, type RecordImportStats as c7, type RecordImportItem as c8, type RecordImport as c9, type ManifestCreatesSpec as cA, type ManifestRelationshipDef as cB, type ManifestEffectSchema as cC, type ManifestEffectDeclaration as cD, type ManifestEventTypeDef as cE, type ManifestEventStreamDef as cF, type ManifestOperation as cG, type ManifestImport as cH, type ManifestVolume as cI, type ManifestContent as cJ, type GraphQLResult as cK, type APIError as cL, type DeleteResponse as cM, type StreamEvent as cN, type StreamSubscription as cO, type StreamStats as cP, type EnvironmentRecordImportSummary as ca, type EnvironmentSetupTriggerReason as cb, type RunEnvironmentImporterOptions as cc, type EnvironmentSetupLifecycleStatus as cd, type EnvironmentSetupSummary as ce, type EnvironmentImporterImportOptions as cf, type EnvironmentImporter as cg, type ManifestPropertySpec as ch, type ManifestValidationOperator as ci, type ManifestEnumRuleSpec as cj, type ManifestFilterBySpec as ck, type ManifestValidationRuleSpec as cl, type ManifestStateMachineStateSpec as cm, type ManifestStateTransitionInputBinding as cn, type ManifestStateTransitionActionSpec as co, type ManifestStateTransitionAssigneeSpec as cp, type ManifestStateTransitionRelatedStateRequirementSpec as cq, type ManifestStateTransitionRequirementsSpec as cr, type ManifestStateTransitionPermissionSpec as cs, type ManifestStateTransitionExpectedOutcomeSpec as ct, type ManifestStateMachineTransitionSpec as cu, type ManifestStateMachineSpec as cv, type ManifestPostConditionSpec as cw, type ManifestDryRunSpec as cx, type ManifestReverseSpec as cy, type ManifestApprovalRequiredSpec as cz, type SessionTranscriptEntry as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type OpenAITokenSpend as h, OPENAI_MODEL_PRICING_USD_PER_MILLION as i, getOpenAIModelPricing as j, calculateOpenAITokenSpend as k, type OpenAIUsageSpendEvent as l, type RecordOpenAIUsageSpendOptions as m, normalizeOpenAIUsage as n, type RecordOpenAIUsageSpendResult as o, buildOpenAISpendEventId as p, type PolicySource as q, recordOpenAIUsageSpend as r, type PolicyPredicateSource as s, toGranularHttpBase as t, type PolicyOperator as u, type PolicyOrigin as v, type PolicyRuleIR as w, type MatchedPolicy as x, type GranularOptions as y, type GranularAuth as z };
@@ -256,6 +256,13 @@ interface ConnectOptions extends OpenEnvironmentOptions {
256
256
  interface CreateSessionOptions {
257
257
  /** Optional stable client ID. Defaults to `client_${Date.now()}`. */
258
258
  clientId?: string;
259
+ /**
260
+ * Optional application-owned history scope for this conversation.
261
+ *
262
+ * Use the same value when listing sessions or reading the materialized user
263
+ * environment state so unrelated product surfaces never share history.
264
+ */
265
+ sessionScope?: string;
259
266
  /**
260
267
  * Optional session heap seed. Each item uses application record identity:
261
268
  * class name plus the record id from the customer's own system. Granular
@@ -285,6 +292,23 @@ interface ConversationSessionInfo {
285
292
  jobCount?: number;
286
293
  toolCallCount?: number;
287
294
  }
295
+ type ConversationSessionListStatus = ConversationSessionInfo["status"] | "all";
296
+ /**
297
+ * Bounded filters for indexed conversation history.
298
+ *
299
+ * At least one ownership filter (`environmentId`, `sandboxId`, or
300
+ * `subjectId`) is required by the SDK. Results are newest-first and default to
301
+ * 100 rows; use `offset` to request the next page.
302
+ */
303
+ interface ConversationSessionListOptions {
304
+ environmentId?: string;
305
+ sandboxId?: string;
306
+ subjectId?: string;
307
+ sessionScope?: string | null;
308
+ status?: ConversationSessionListStatus;
309
+ limit?: number;
310
+ offset?: number;
311
+ }
288
312
  type SpendLineItemType = "llm_tokens" | "granular_session_time" | string;
289
313
  type QuotaScopeType = "tenant" | "sandbox" | "permission_profile" | "subject";
290
314
  type QuotaPeriod = "hour" | "day" | "week" | "month";
@@ -893,6 +917,10 @@ interface Job {
893
917
  }
894
918
  interface Prompt {
895
919
  id: string;
920
+ /** Job that owns this prompt, when it was opened by a running job. */
921
+ jobId?: string;
922
+ /** Harness turn that owns this prompt. */
923
+ turnId?: string;
896
924
  type: "confirm" | "choice" | "input";
897
925
  title: string;
898
926
  message: string;
@@ -913,6 +941,33 @@ interface ConversationMessageShowRefs {
913
941
  fileIds?: string[];
914
942
  sessionArtifactIds?: string[];
915
943
  actionSuggestions?: ConversationActionSuggestion[];
944
+ tables?: ConversationTableProjection[];
945
+ }
946
+ type ConversationTableCell = string | number | boolean | null | {
947
+ kind: "relative_time" | "date";
948
+ value: string | number;
949
+ };
950
+ interface ConversationTableColumn {
951
+ id: string;
952
+ label: string;
953
+ }
954
+ interface ConversationTableRowReference {
955
+ entryPath?: string;
956
+ className?: string;
957
+ id?: string;
958
+ label?: string;
959
+ }
960
+ interface ConversationTableRow {
961
+ id: string;
962
+ reference?: ConversationTableRowReference;
963
+ cells: ConversationTableCell[];
964
+ }
965
+ interface ConversationTableProjection {
966
+ id: string;
967
+ label?: string;
968
+ source?: string;
969
+ columns: ConversationTableColumn[];
970
+ rows: ConversationTableRow[];
916
971
  }
917
972
  interface ConversationActionSuggestion {
918
973
  suggestionId?: string;
@@ -922,13 +977,35 @@ interface ConversationActionSuggestion {
922
977
  target?: Record<string, unknown> | null;
923
978
  metadata?: Record<string, unknown>;
924
979
  }
980
+ /** A normalized action embedded in an ordered assistant message stream. */
981
+ interface ConversationMessageAction {
982
+ kind: "frontend" | "backend" | "system";
983
+ label: string;
984
+ status?: "done" | "queued" | "failed";
985
+ }
986
+ /**
987
+ * A durable assistant message segment in the order it reached the client.
988
+ *
989
+ * `content` and `actions` remain the canonical compatibility fields on the
990
+ * message. Parts only preserve their interleaving for capable clients.
991
+ */
992
+ type ConversationMessagePart = {
993
+ type: "text";
994
+ text: string;
995
+ } | {
996
+ type: "action";
997
+ action: ConversationMessageAction;
998
+ };
925
999
  interface ConversationMessageInput {
1000
+ /** Optional caller-owned id used to correlate optimistic and durable turns. */
1001
+ id?: string;
926
1002
  role: "user" | "assistant";
927
1003
  content?: string;
928
1004
  show?: ConversationMessageShowRefs;
929
1005
  reasoningLines?: string[];
930
1006
  reasoningDurationMs?: number;
931
1007
  actions?: Array<Record<string, unknown>>;
1008
+ parts?: ConversationMessagePart[];
932
1009
  target?: Record<string, unknown>;
933
1010
  jobId?: string;
934
1011
  promptId?: string;
@@ -949,6 +1026,7 @@ interface SessionConversationMessage {
949
1026
  reasoningLines?: string[];
950
1027
  reasoningDurationMs?: number;
951
1028
  actions?: Array<Record<string, unknown>>;
1029
+ parts?: ConversationMessagePart[];
952
1030
  target?: Record<string, unknown>;
953
1031
  jobId?: string;
954
1032
  promptId?: string;
@@ -998,6 +1076,25 @@ interface SessionFileRecord {
998
1076
  }
999
1077
  type SessionArtifactStatus = "draft" | "ready" | "needs_edit" | "blocked" | "running" | "awaiting_human" | "completed" | "partially_completed" | "failed" | "canceled" | "stale";
1000
1078
  type SessionArtifactKind = "effect" | "batch" | "state_path";
1079
+ /**
1080
+ * Declarative impact metadata consumed by deterministic clients before an
1081
+ * artifact can execute. Missing metadata must be treated conservatively.
1082
+ */
1083
+ interface SessionArtifactAutonomyPolicy {
1084
+ sideEffect?: "read" | "readonly" | "read_only" | "ui" | "write" | "delete" | "destructive" | "irreversible";
1085
+ scope?: "internal" | "bulk" | "external" | "financial" | "permission";
1086
+ risk?: "low" | "medium" | "high";
1087
+ targetCount?: number;
1088
+ reversible?: boolean;
1089
+ destructive?: boolean;
1090
+ external?: boolean;
1091
+ financial?: boolean;
1092
+ permissionChange?: boolean;
1093
+ reverse?: string | Record<string, unknown>;
1094
+ undo?: string | Record<string, unknown>;
1095
+ rollback?: string | Record<string, unknown>;
1096
+ [key: string]: unknown;
1097
+ }
1001
1098
  interface SessionArtifactRecord {
1002
1099
  artifactId: string;
1003
1100
  sessionId?: string | null;
@@ -1023,8 +1120,10 @@ interface SessionArtifactRecord {
1023
1120
  } | null;
1024
1121
  relationships?: Record<string, string | string[] | null>;
1025
1122
  validation?: Record<string, unknown> | null;
1026
- policy?: Record<string, unknown> | null;
1027
- metadata?: Record<string, unknown>;
1123
+ policy?: SessionArtifactAutonomyPolicy | null;
1124
+ metadata?: Record<string, unknown> & {
1125
+ autonomy?: SessionArtifactAutonomyPolicy;
1126
+ };
1028
1127
  parentArtifactId?: string | null;
1029
1128
  subArtifactIds?: string[];
1030
1129
  createdAt: number;
@@ -1274,6 +1373,8 @@ interface SessionTranscriptEntry {
1274
1373
  jobResultPreview?: string;
1275
1374
  error?: string;
1276
1375
  show?: ConversationMessageShowRefs;
1376
+ actions?: ConversationMessageAction[];
1377
+ parts?: ConversationMessagePart[];
1277
1378
  historyContent?: string;
1278
1379
  source: "conversation" | "job_code" | "job_result" | "job_prompt" | "job_agent_message";
1279
1380
  }
@@ -1344,6 +1445,8 @@ interface SessionDocumentResult {
1344
1445
  interface SessionCollectionListOptions {
1345
1446
  limit?: number;
1346
1447
  cursor?: string | null;
1448
+ /** Return only the newest page, in chronological order. */
1449
+ latest?: boolean | null;
1347
1450
  }
1348
1451
  interface SessionJobListOptions extends SessionCollectionListOptions {
1349
1452
  status?: string | null;
@@ -1393,6 +1496,8 @@ interface UserEnvironmentState {
1393
1496
  tenantId?: string;
1394
1497
  sessionScope?: string | null;
1395
1498
  updatedAt: number;
1499
+ /** Monotonic materialized-index revision used for conditional refreshes. */
1500
+ revision?: number;
1396
1501
  stateSource?: "user_environment_snapshot" | "live_session_aggregate";
1397
1502
  stale?: boolean;
1398
1503
  snapshotUpdatedAt?: number | null;
@@ -1434,6 +1539,7 @@ interface WSClientOptions {
1434
1539
  url: string;
1435
1540
  sessionId: string;
1436
1541
  token: string;
1542
+ initialDocumentSnapshot?: Record<string, unknown> | Uint8Array | null;
1437
1543
  tokenProvider?: AccessTokenProvider;
1438
1544
  WebSocketCtor?: any;
1439
1545
  maxReconnectAttempts?: number;
@@ -2082,13 +2188,23 @@ interface OpenAIModelPricing {
2082
2188
  currency: "USD";
2083
2189
  inputUsdPerMillion: number;
2084
2190
  cachedInputUsdPerMillion: number;
2191
+ cacheWriteUsdPerMillion?: number | null;
2085
2192
  outputUsdPerMillion: number;
2193
+ contextTier?: "short" | "long";
2194
+ longContextThresholdTokens?: number | null;
2195
+ longContextPricing?: {
2196
+ inputUsdPerMillion: number;
2197
+ cachedInputUsdPerMillion: number;
2198
+ cacheWriteUsdPerMillion?: number | null;
2199
+ outputUsdPerMillion: number;
2200
+ };
2086
2201
  sourceUrl: string;
2087
2202
  effectiveDate: string;
2088
2203
  }
2089
2204
  interface NormalizedOpenAIUsage {
2090
2205
  inputTokens: number;
2091
2206
  cachedInputTokens: number;
2207
+ cacheWriteTokens: number;
2092
2208
  uncachedInputTokens: number;
2093
2209
  outputTokens: number;
2094
2210
  reasoningTokens: number;
@@ -2099,6 +2215,7 @@ interface OpenAITokenSpend {
2099
2215
  model: string;
2100
2216
  inputTokens: number;
2101
2217
  cachedInputTokens: number;
2218
+ cacheWriteTokens: number;
2102
2219
  uncachedInputTokens: number;
2103
2220
  outputTokens: number;
2104
2221
  reasoningTokens: number;
@@ -2107,13 +2224,17 @@ interface OpenAITokenSpend {
2107
2224
  currency: "USD";
2108
2225
  inputPricePerMillionMicros: number;
2109
2226
  cachedInputPricePerMillionMicros: number;
2227
+ cacheWritePricePerMillionMicros: number | null;
2228
+ cacheWriteCostMicros: number;
2110
2229
  outputPricePerMillionMicros: number;
2230
+ pricingContextTier: "short" | "long";
2231
+ longContextThresholdTokens: number | null;
2111
2232
  pricingSource: string;
2112
2233
  pricingEffectiveAt: string;
2113
2234
  usage: NormalizedOpenAIUsage;
2114
2235
  }
2115
2236
  declare const OPENAI_MODEL_PRICING_USD_PER_MILLION: Record<string, OpenAIModelPricing>;
2116
- declare function getOpenAIModelPricing(model: string): OpenAIModelPricing | null;
2237
+ declare function getOpenAIModelPricing(model: string, inputTokens?: number): OpenAIModelPricing | null;
2117
2238
  declare function normalizeOpenAIUsage(rawUsage: unknown): NormalizedOpenAIUsage;
2118
2239
  declare function calculateOpenAITokenSpend(model: string, rawUsage: unknown): OpenAITokenSpend | null;
2119
2240
 
@@ -2151,4 +2272,4 @@ declare function toGranularHttpBase(apiUrl: string): string;
2151
2272
  declare function buildOpenAISpendEventId(usage: Pick<OpenAIUsageSpendEvent, "requestId">, context?: GranularSpendContext): string | undefined;
2152
2273
  declare function recordOpenAIUsageSpend(options: RecordOpenAIUsageSpendOptions): Promise<RecordOpenAIUsageSpendResult>;
2153
2274
 
2154
- export { type GranularQuotaProgress as $, type AccessTokenProvider as A, type RecordUserOptions as B, type ConditionIR as C, type DomainState as D, type EndpointMode as E, type Subject as F, type GranularSpendContext as G, type OpenEnvironmentOptions as H, type InstanceToolHandler as I, type ConnectOptions as J, type CreateSessionOptions as K, type ConversationSessionInfo as L, type ManifestEffectMetamodelSpec as M, type NormalizedOpenAIUsage as N, type OpenAIModelPricing as O, type Prompt as P, type SpendLineItemType as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type QuotaScopeType as V, type QuotaPeriod as W, type QuotaStatus as X, type SpendSummary as Y, type QuotaLineItemFilter as Z, type GranularQuotaPolicy as _, type EffectHandlerContext as a, type SessionArtifactExecutionResult as a$, type Sandbox as a0, type CreateSandboxData as a1, type SandboxListResponse as a2, type PermissionRules as a3, type PermissionProfile as a4, type CreatePermissionProfileData as a5, type PermissionProfileListResponse as a6, type Assignment as a7, type AssignmentListResponse as a8, type BuildPolicy as a9, type EffectsChangedEvent as aA, type EffectHandler as aB, type InstanceEffectHandler as aC, type JobStatus as aD, type JobFeedbackSentiment as aE, type JobFeedbackToolCall as aF, type JobFeedbackMetadata as aG, type JobFeedbackInput as aH, type JobFeedbackRecord as aI, type EnvironmentFeedbackRecord as aJ, type JobSubmitResult as aK, type Job as aL, type ConversationMessageShowRefs as aM, type ConversationActionSuggestion as aN, type ConversationMessageInput as aO, type ConversationAppendResult as aP, type SessionConversationMessage as aQ, type SessionTimelineEvent as aR, type SessionFileSource as aS, type SessionFileKind as aT, type SessionFileStatus as aU, type SessionFileRecord as aV, type SessionArtifactStatus as aW, type SessionArtifactKind as aX, type SessionArtifactRecord as aY, type SessionArtifactListOptions as aZ, type SessionArtifactValidationResult as a_, type VersionTracking as aa, type VersionTag as ab, type EnvironmentData as ac, type CreateEnvironmentData as ad, type EnvironmentListResponse as ae, type Manifest as af, type ManifestListResponse as ag, type BuildStatus as ah, type Build as ai, type Version as aj, type BuildListResponse as ak, type SemanticVersionDiffEntry as al, type SemanticVersionDiff as am, type ResolvedEffectPostCondition as an, type ResolvedEffectDryRun as ao, type ResolvedEffectReverse as ap, type ResolvedEffectApprovalRequired as aq, type EffectInvocationMode as ar, type EffectInvocationMetadata as as, type EffectSchema as at, type EffectWithHandler as au, type PublishEffectsResult as av, type EffectVersionSelector as aw, type ToolInfo as ax, type EffectInfo as ay, type ToolsChangedEvent as az, type SessionHeapList as b, type RecordImport as b$, type SessionArtifactExecutionOptions as b0, type SessionArtifactApprovalOptions as b1, type ArtifactApprovalTaskStatus as b2, type ArtifactApprovalTask as b3, type ArtifactApprovalTaskListOptions as b4, type ArtifactApprovalDecisionInput as b5, type ArtifactApprovalDecisionResult as b6, type ManualActionStatus as b7, type ManualActionSource as b8, type ManualActionTarget as b9, type WSReconnectErrorInfo as bA, type WSClientOptions as bB, type RPCRequest as bC, type RPCResponse as bD, type SyncMessage as bE, type RPCRequestFromServer as bF, type ToolInvokeParams as bG, type ToolResultParams as bH, type ModelRef as bI, type RelationshipInfo as bJ, type DefineRelationshipOptions as bK, type RecordObjectOptions as bL, type RecordObjectStateValue as bM, type EnvironmentStateTarget as bN, type EnvironmentStateObservationInput as bO, type EnvironmentStateUpdateInput as bP, type EnvironmentStateMachineProxy as bQ, type EnvironmentStateProxy as bR, type RecordObjectResult as bS, type RecordObjectsChunkInfo as bT, type RecordObjectsOptions as bU, type RecordImportWriteMode as bV, type RecordImportOptions as bW, type RecordImportStatus as bX, type RecordImportItemStatus as bY, type RecordImportStats as bZ, type RecordImportItem as b_, type ManualActionRelatedRecord as ba, type RecordManualActionInput as bb, type ManualActionOccurrence as bc, type ManualActionRecordResult as bd, type ManualActionListOptions as be, type ManualActionSuggestion as bf, type ManualActionSuggestionOptions as bg, type SessionFileUploadOptions as bh, type SessionJobRecord as bi, type SessionHeapFieldType as bj, type SessionHeapFieldValue as bk, type SessionHeapVariable as bl, type RecordSearchResult as bm, type RecordSearchOptions as bn, type RecordMentionInput as bo, type SessionDocumentResult as bp, type SessionCollectionListOptions as bq, type SessionJobListOptions as br, type SessionCollectionListResult as bs, type UserEnvironmentPrompt as bt, type UserEnvironmentMessagePreview as bu, type UserEnvironmentSessionState as bv, type UserEnvironmentState as bw, type UserEnvironmentStateOptions as bx, type MarkUserEnvironmentReadOptions as by, type WSDisconnectInfo as bz, type SessionHeapSnapshot as c, type EnvironmentRecordImportSummary as c0, type EnvironmentSetupTriggerReason as c1, type RunEnvironmentImporterOptions as c2, type EnvironmentSetupLifecycleStatus as c3, type EnvironmentSetupSummary as c4, type EnvironmentImporterImportOptions as c5, type EnvironmentImporter as c6, type ManifestPropertySpec as c7, type ManifestValidationOperator as c8, type ManifestEnumRuleSpec as c9, type GraphQLResult as cA, type APIError as cB, type DeleteResponse as cC, type StreamEvent as cD, type StreamSubscription as cE, type StreamStats as cF, type ManifestFilterBySpec as ca, type ManifestValidationRuleSpec as cb, type ManifestStateMachineStateSpec as cc, type ManifestStateTransitionInputBinding as cd, type ManifestStateTransitionActionSpec as ce, type ManifestStateTransitionAssigneeSpec as cf, type ManifestStateTransitionRelatedStateRequirementSpec as cg, type ManifestStateTransitionRequirementsSpec as ch, type ManifestStateTransitionPermissionSpec as ci, type ManifestStateTransitionExpectedOutcomeSpec as cj, type ManifestStateMachineTransitionSpec as ck, type ManifestStateMachineSpec as cl, type ManifestPostConditionSpec as cm, type ManifestDryRunSpec as cn, type ManifestReverseSpec as co, type ManifestApprovalRequiredSpec as cp, type ManifestCreatesSpec as cq, type ManifestRelationshipDef as cr, type ManifestEffectSchema as cs, type ManifestEffectDeclaration as ct, type ManifestEventTypeDef as cu, type ManifestEventStreamDef as cv, type ManifestOperation as cw, type ManifestImport as cx, type ManifestVolume as cy, type ManifestContent as cz, type SessionTranscriptEntry as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type OpenAITokenSpend as h, OPENAI_MODEL_PRICING_USD_PER_MILLION as i, getOpenAIModelPricing as j, calculateOpenAITokenSpend as k, type OpenAIUsageSpendEvent as l, type RecordOpenAIUsageSpendOptions as m, normalizeOpenAIUsage as n, type RecordOpenAIUsageSpendResult as o, buildOpenAISpendEventId as p, type PolicySource as q, recordOpenAIUsageSpend as r, type PolicyPredicateSource as s, toGranularHttpBase as t, type PolicyOperator as u, type PolicyOrigin as v, type PolicyRuleIR as w, type MatchedPolicy as x, type GranularOptions as y, type GranularAuth as z };
2275
+ export { type QuotaLineItemFilter as $, type AccessTokenProvider as A, type RecordUserOptions as B, type ConditionIR as C, type DomainState as D, type EndpointMode as E, type Subject as F, type GranularSpendContext as G, type OpenEnvironmentOptions as H, type InstanceToolHandler as I, type ConnectOptions as J, type CreateSessionOptions as K, type ConversationSessionInfo as L, type ManifestEffectMetamodelSpec as M, type NormalizedOpenAIUsage as N, type OpenAIModelPricing as O, type Prompt as P, type ConversationSessionListStatus as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type ConversationSessionListOptions as V, type SpendLineItemType as W, type QuotaScopeType as X, type QuotaPeriod as Y, type QuotaStatus as Z, type SpendSummary as _, type EffectHandlerContext as a, type SessionFileSource as a$, type GranularQuotaPolicy as a0, type GranularQuotaProgress as a1, type Sandbox as a2, type CreateSandboxData as a3, type SandboxListResponse as a4, type PermissionRules as a5, type PermissionProfile as a6, type CreatePermissionProfileData as a7, type PermissionProfileListResponse as a8, type Assignment as a9, type EffectInfo as aA, type ToolsChangedEvent as aB, type EffectsChangedEvent as aC, type EffectHandler as aD, type InstanceEffectHandler as aE, type JobStatus as aF, type JobFeedbackSentiment as aG, type JobFeedbackToolCall as aH, type JobFeedbackMetadata as aI, type JobFeedbackInput as aJ, type JobFeedbackRecord as aK, type EnvironmentFeedbackRecord as aL, type JobSubmitResult as aM, type Job as aN, type ConversationMessageShowRefs as aO, type ConversationTableCell as aP, type ConversationTableColumn as aQ, type ConversationTableRowReference as aR, type ConversationTableRow as aS, type ConversationTableProjection as aT, type ConversationActionSuggestion as aU, type ConversationMessageAction as aV, type ConversationMessagePart as aW, type ConversationMessageInput as aX, type ConversationAppendResult as aY, type SessionConversationMessage as aZ, type SessionTimelineEvent as a_, type AssignmentListResponse as aa, type BuildPolicy as ab, type VersionTracking as ac, type VersionTag as ad, type EnvironmentData as ae, type CreateEnvironmentData as af, type EnvironmentListResponse as ag, type Manifest as ah, type ManifestListResponse as ai, type BuildStatus as aj, type Build as ak, type Version as al, type BuildListResponse as am, type SemanticVersionDiffEntry as an, type SemanticVersionDiff as ao, type ResolvedEffectPostCondition as ap, type ResolvedEffectDryRun as aq, type ResolvedEffectReverse as ar, type ResolvedEffectApprovalRequired as as, type EffectInvocationMode as at, type EffectInvocationMetadata as au, type EffectSchema as av, type EffectWithHandler as aw, type PublishEffectsResult as ax, type EffectVersionSelector as ay, type ToolInfo as az, type SessionHeapList as b, type EnvironmentStateProxy as b$, type SessionFileKind as b0, type SessionFileStatus as b1, type SessionFileRecord as b2, type SessionArtifactStatus as b3, type SessionArtifactKind as b4, type SessionArtifactAutonomyPolicy as b5, type SessionArtifactRecord as b6, type SessionArtifactListOptions as b7, type SessionArtifactValidationResult as b8, type SessionArtifactExecutionResult as b9, type SessionCollectionListOptions as bA, type SessionJobListOptions as bB, type SessionCollectionListResult as bC, type UserEnvironmentPrompt as bD, type UserEnvironmentMessagePreview as bE, type UserEnvironmentSessionState as bF, type UserEnvironmentState as bG, type UserEnvironmentStateOptions as bH, type MarkUserEnvironmentReadOptions as bI, type WSDisconnectInfo as bJ, type WSReconnectErrorInfo as bK, type WSClientOptions as bL, type RPCRequest as bM, type RPCResponse as bN, type SyncMessage as bO, type RPCRequestFromServer as bP, type ToolInvokeParams as bQ, type ToolResultParams as bR, type ModelRef as bS, type RelationshipInfo as bT, type DefineRelationshipOptions as bU, type RecordObjectOptions as bV, type RecordObjectStateValue as bW, type EnvironmentStateTarget as bX, type EnvironmentStateObservationInput as bY, type EnvironmentStateUpdateInput as bZ, type EnvironmentStateMachineProxy as b_, type SessionArtifactExecutionOptions as ba, type SessionArtifactApprovalOptions as bb, type ArtifactApprovalTaskStatus as bc, type ArtifactApprovalTask as bd, type ArtifactApprovalTaskListOptions as be, type ArtifactApprovalDecisionInput as bf, type ArtifactApprovalDecisionResult as bg, type ManualActionStatus as bh, type ManualActionSource as bi, type ManualActionTarget as bj, type ManualActionRelatedRecord as bk, type RecordManualActionInput as bl, type ManualActionOccurrence as bm, type ManualActionRecordResult as bn, type ManualActionListOptions as bo, type ManualActionSuggestion as bp, type ManualActionSuggestionOptions as bq, type SessionFileUploadOptions as br, type SessionJobRecord as bs, type SessionHeapFieldType as bt, type SessionHeapFieldValue as bu, type SessionHeapVariable as bv, type RecordSearchResult as bw, type RecordSearchOptions as bx, type RecordMentionInput as by, type SessionDocumentResult as bz, type SessionHeapSnapshot as c, type RecordObjectResult as c0, type RecordObjectsChunkInfo as c1, type RecordObjectsOptions as c2, type RecordImportWriteMode as c3, type RecordImportOptions as c4, type RecordImportStatus as c5, type RecordImportItemStatus as c6, type RecordImportStats as c7, type RecordImportItem as c8, type RecordImport as c9, type ManifestCreatesSpec as cA, type ManifestRelationshipDef as cB, type ManifestEffectSchema as cC, type ManifestEffectDeclaration as cD, type ManifestEventTypeDef as cE, type ManifestEventStreamDef as cF, type ManifestOperation as cG, type ManifestImport as cH, type ManifestVolume as cI, type ManifestContent as cJ, type GraphQLResult as cK, type APIError as cL, type DeleteResponse as cM, type StreamEvent as cN, type StreamSubscription as cO, type StreamStats as cP, type EnvironmentRecordImportSummary as ca, type EnvironmentSetupTriggerReason as cb, type RunEnvironmentImporterOptions as cc, type EnvironmentSetupLifecycleStatus as cd, type EnvironmentSetupSummary as ce, type EnvironmentImporterImportOptions as cf, type EnvironmentImporter as cg, type ManifestPropertySpec as ch, type ManifestValidationOperator as ci, type ManifestEnumRuleSpec as cj, type ManifestFilterBySpec as ck, type ManifestValidationRuleSpec as cl, type ManifestStateMachineStateSpec as cm, type ManifestStateTransitionInputBinding as cn, type ManifestStateTransitionActionSpec as co, type ManifestStateTransitionAssigneeSpec as cp, type ManifestStateTransitionRelatedStateRequirementSpec as cq, type ManifestStateTransitionRequirementsSpec as cr, type ManifestStateTransitionPermissionSpec as cs, type ManifestStateTransitionExpectedOutcomeSpec as ct, type ManifestStateMachineTransitionSpec as cu, type ManifestStateMachineSpec as cv, type ManifestPostConditionSpec as cw, type ManifestDryRunSpec as cx, type ManifestReverseSpec as cy, type ManifestApprovalRequiredSpec as cz, type SessionTranscriptEntry as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type OpenAITokenSpend as h, OPENAI_MODEL_PRICING_USD_PER_MILLION as i, getOpenAIModelPricing as j, calculateOpenAITokenSpend as k, type OpenAIUsageSpendEvent as l, type RecordOpenAIUsageSpendOptions as m, normalizeOpenAIUsage as n, type RecordOpenAIUsageSpendResult as o, buildOpenAISpendEventId as p, type PolicySource as q, recordOpenAIUsageSpend as r, type PolicyPredicateSource as s, toGranularHttpBase as t, type PolicyOperator as u, type PolicyOrigin as v, type PolicyRuleIR as w, type MatchedPolicy as x, type GranularOptions as y, type GranularAuth as z };
package/dist/spend.d.mts CHANGED
@@ -1 +1 @@
1
- export { G as GranularSpendContext, l as OpenAIUsageSpendEvent, m as RecordOpenAIUsageSpendOptions, o as RecordOpenAIUsageSpendResult, p as buildOpenAISpendEventId, r as recordOpenAIUsageSpend, t as toGranularHttpBase } from './spend-RpJikX9w.mjs';
1
+ export { G as GranularSpendContext, l as OpenAIUsageSpendEvent, m as RecordOpenAIUsageSpendOptions, o as RecordOpenAIUsageSpendResult, p as buildOpenAISpendEventId, r as recordOpenAIUsageSpend, t as toGranularHttpBase } from './spend-BA-jZwZ0.mjs';
package/dist/spend.d.ts CHANGED
@@ -1 +1 @@
1
- export { G as GranularSpendContext, l as OpenAIUsageSpendEvent, m as RecordOpenAIUsageSpendOptions, o as RecordOpenAIUsageSpendResult, p as buildOpenAISpendEventId, r as recordOpenAIUsageSpend, t as toGranularHttpBase } from './spend-RpJikX9w.js';
1
+ export { G as GranularSpendContext, l as OpenAIUsageSpendEvent, m as RecordOpenAIUsageSpendOptions, o as RecordOpenAIUsageSpendResult, p as buildOpenAISpendEventId, r as recordOpenAIUsageSpend, t as toGranularHttpBase } from './spend-BA-jZwZ0.js';
package/dist/spend.js CHANGED
@@ -52,7 +52,12 @@ async function recordOpenAIUsageSpend(options) {
52
52
  const metadata = {
53
53
  ...options.metadata || {},
54
54
  ...options.usage.rawUsage !== void 0 ? { openaiUsage: options.usage.rawUsage } : {},
55
- usageContext: context
55
+ usageContext: context,
56
+ pricingContextTier: options.usage.pricingContextTier,
57
+ cacheWritePricePerMillionMicros: options.usage.cacheWritePricePerMillionMicros,
58
+ cacheWriteTokens: options.usage.cacheWriteTokens,
59
+ cacheWriteCostMicros: options.usage.cacheWriteCostMicros,
60
+ longContextThresholdTokens: options.usage.longContextThresholdTokens
56
61
  };
57
62
  const response = await fetch(
58
63
  `${toGranularHttpBase(options.apiUrl)}/control/spend/events`,
package/dist/spend.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/spend.ts"],"names":[],"mappings":";;;AAqCO,SAAS,mBAAmB,MAAA,EAAwB;AACzD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,MAAM,CAAA;AAC1B,EAAA,IAAI,GAAA,CAAI,aAAa,KAAA,EAAO;AAC1B,IAAA,GAAA,CAAI,QAAA,GAAW,OAAA;AAAA,EACjB,CAAA,MAAA,IAAW,GAAA,CAAI,QAAA,KAAa,MAAA,EAAQ;AAClC,IAAA,GAAA,CAAI,QAAA,GAAW,QAAA;AAAA,EACjB;AAEA,EAAA,GAAA,CAAI,QAAA,GAAW,IAAI,QAAA,CAChB,OAAA,CAAQ,kBAAkB,EAAE,CAAA,CAC5B,OAAA,CAAQ,OAAA,EAAS,EAAE,CAAA;AACtB,EAAA,IAAI,CAAC,GAAA,CAAI,QAAA,IAAY,GAAA,CAAI,aAAa,GAAA,EAAK;AACzC,IAAA,GAAA,CAAI,QAAA,GAAW,WAAA;AAAA,EACjB;AACA,EAAA,GAAA,CAAI,MAAA,GAAS,EAAA;AACb,EAAA,GAAA,CAAI,IAAA,GAAO,EAAA;AACX,EAAA,OAAO,GAAA,CAAI,QAAA,EAAS,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AACzC;AAEA,SAAS,YAAY,KAAA,EAAuB;AAC1C,EAAA,OAAO,MAAM,OAAA,CAAQ,kBAAA,EAAoB,GAAG,CAAA,CAAE,OAAA,CAAQ,YAAY,EAAE,CAAA;AACtE;AAEO,SAAS,uBAAA,CACd,KAAA,EACA,OAAA,GAAgC,EAAC,EACb;AACpB,EAAA,MAAM,SAAA,GAAY,KAAA,CAAM,SAAA,EAAW,IAAA,EAAK;AACxC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AAEvB,EAAA,MAAM,KAAA,GACJ,QAAQ,SAAA,IACR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c,QAAQ,KAAA,CAAM,YAAA;AAAA,QAC5B,iBAAA,EAAmB,QAAQ,KAAA,CAAM,iBAAA;AAAA,QACjC,eAAA,EAAiB,QAAQ,KAAA,CAAM,eAAA;AAAA,QAC/B,QAAA,EAAU,QAAQ,KAAA,CAAM,WAAA;AAAA,QACxB,YAAA,EAAc,QAAA;AAAA,QACd,0BAAA,EAA4B,QAAQ,KAAA,CAAM,0BAAA;AAAA,QAC1C,gCAAA,EACE,QAAQ,KAAA,CAAM,gCAAA;AAAA,QAChB,2BAAA,EAA6B,QAAQ,KAAA,CAAM,2BAAA;AAAA,QAC3C,YAAA,EAAc,QAAQ,KAAA,CAAM,YAAA;AAAA,QAC5B,QAAA,EAAU,QAAQ,KAAA,CAAM,QAAA;AAAA,QACxB,aAAA,EAAe,QAAQ,KAAA,CAAM,aAAA;AAAA,QAC7B,kBAAA,EAAoB,yBAAA;AAAA,UAClB,QAAQ,KAAA,CAAM;AAAA,SAChB;AAAA,QACA,SAAA,EAAW,KAAA;AAAA,QACX;AAAA,OACD;AAAA;AACH,GACF;AAEA,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,gCAAgC,QAAA,CAAS,MAAM,MAAM,MAAM,QAAA,CAAS,MAAM,CAAA;AAAA,KAC5E;AAAA,EACF;AAEA,EAAA,OAAO,SAAS,IAAA,EAAK;AACvB","file":"spend.js","sourcesContent":["import type { OpenAITokenSpend } from \"./openai-usage\";\nimport type { GranularQuotaProgress } from \"./types\";\n\nexport interface GranularSpendContext {\n tenantId?: string | null;\n sandboxId?: string | null;\n environmentId?: string | null;\n sessionId?: string | null;\n subjectId?: string | null;\n permissionProfileId?: string | null;\n [key: string]: string | null | undefined;\n}\n\nexport interface OpenAIUsageSpendEvent extends OpenAITokenSpend {\n spendEventId?: string;\n source?: \"openai\";\n lineItemType?: \"llm_tokens\";\n operation?: string;\n requestId?: string | null;\n usageContext?: GranularSpendContext;\n rawUsage?: unknown;\n}\n\nexport interface RecordOpenAIUsageSpendOptions {\n apiUrl: string;\n token: string;\n usage: OpenAIUsageSpendEvent;\n context?: GranularSpendContext | null;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface RecordOpenAIUsageSpendResult {\n spendEventId: string;\n inserted: boolean;\n quota: GranularQuotaProgress | null;\n}\n\nexport function toGranularHttpBase(apiUrl: string): string {\n const url = new URL(apiUrl);\n if (url.protocol === \"ws:\") {\n url.protocol = \"http:\";\n } else if (url.protocol === \"wss:\") {\n url.protocol = \"https:\";\n }\n\n url.pathname = url.pathname\n .replace(/\\/ws\\/connect$/, \"\")\n .replace(/\\/ws$/, \"\");\n if (!url.pathname || url.pathname === \"/\") {\n url.pathname = \"/granular\";\n }\n url.search = \"\";\n url.hash = \"\";\n return url.toString().replace(/\\/$/, \"\");\n}\n\nfunction cleanIdPart(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]+/g, \"_\").replace(/^_+|_+$/g, \"\");\n}\n\nexport function buildOpenAISpendEventId(\n usage: Pick<OpenAIUsageSpendEvent, \"requestId\">,\n context: GranularSpendContext = {},\n): string | undefined {\n const requestId = usage.requestId?.trim();\n if (!requestId) return undefined;\n\n const scope =\n context.sessionId ||\n context.environmentId ||\n context.subjectId ||\n context.sandboxId ||\n \"global\";\n return [\"spend\", \"openai\", scope, requestId].map(cleanIdPart).join(\"_\");\n}\n\nfunction pricingEffectiveAtSeconds(value: string | null | undefined) {\n if (!value) return null;\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : null;\n}\n\nfunction compactContext(context: GranularSpendContext): GranularSpendContext {\n return Object.fromEntries(\n Object.entries(context).filter(\n ([, value]) => value != null && value !== \"\",\n ),\n ) as GranularSpendContext;\n}\n\nfunction omitTenantId(context: GranularSpendContext): GranularSpendContext {\n const scopedContext = { ...context };\n delete scopedContext.tenantId;\n return scopedContext;\n}\n\nexport async function recordOpenAIUsageSpend(\n options: RecordOpenAIUsageSpendOptions,\n): Promise<RecordOpenAIUsageSpendResult> {\n const usageContext = compactContext({\n ...(options.usage.usageContext || {}),\n ...(options.context || {}),\n });\n const context = omitTenantId(usageContext);\n const spendEventId =\n options.usage.spendEventId ||\n buildOpenAISpendEventId(options.usage, context);\n const metadata = {\n ...(options.metadata || {}),\n ...(options.usage.rawUsage !== undefined\n ? { openaiUsage: options.usage.rawUsage }\n : {}),\n usageContext: context,\n };\n\n const response = await fetch(\n `${toGranularHttpBase(options.apiUrl)}/control/spend/events`,\n {\n method: \"POST\",\n cache: \"no-store\",\n headers: {\n Authorization: `Bearer ${options.token}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...(spendEventId ? { spendEventId } : {}),\n sandboxId: context.sandboxId || null,\n environmentId: context.environmentId || null,\n sessionId: context.sessionId || null,\n subjectId: context.subjectId || null,\n permissionProfileId: context.permissionProfileId || null,\n source: \"openai\",\n lineItemType: \"llm_tokens\",\n provider: options.usage.provider,\n model: options.usage.model,\n operation: options.usage.operation || \"chat.completions\",\n requestId: options.usage.requestId || null,\n inputTokens: options.usage.inputTokens,\n outputTokens: options.usage.outputTokens,\n cachedInputTokens: options.usage.cachedInputTokens,\n reasoningTokens: options.usage.reasoningTokens,\n quantity: options.usage.totalTokens,\n quantityUnit: \"tokens\",\n inputPricePerMillionMicros: options.usage.inputPricePerMillionMicros,\n cachedInputPricePerMillionMicros:\n options.usage.cachedInputPricePerMillionMicros,\n outputPricePerMillionMicros: options.usage.outputPricePerMillionMicros,\n amountMicros: options.usage.amountMicros,\n currency: options.usage.currency,\n pricingSource: options.usage.pricingSource,\n pricingEffectiveAt: pricingEffectiveAtSeconds(\n options.usage.pricingEffectiveAt,\n ),\n estimated: false,\n metadata,\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Granular spend event failed (${response.status}): ${await response.text()}`,\n );\n }\n\n return response.json() as Promise<RecordOpenAIUsageSpendResult>;\n}\n"]}
1
+ {"version":3,"sources":["../src/spend.ts"],"names":[],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QACtC,SAAA,EAAW,OAAA,CAAQ,KAAA,CAAM,SAAA,IAAa,IAAA;AAAA,QACtC,WAAA,EAAa,QAAQ,KAAA,CAAM,WAAA;AAAA,QAC3B,YAAA,EAAc,QAAQ,KAAA,CAAM,YAAA;AAAA,QAC5B,iBAAA,EAAmB,QAAQ,KAAA,CAAM,iBAAA;AAAA,QACjC,eAAA,EAAiB,QAAQ,KAAA,CAAM,eAAA;AAAA,QAC/B,QAAA,EAAU,QAAQ,KAAA,CAAM,WAAA;AAAA,QACxB,YAAA,EAAc,QAAA;AAAA,QACd,0BAAA,EAA4B,QAAQ,KAAA,CAAM,0BAAA;AAAA,QAC1C,gCAAA,EACE,QAAQ,KAAA,CAAM,gCAAA;AAAA,QAChB,2BAAA,EAA6B,QAAQ,KAAA,CAAM,2BAAA;AAAA,QAC3C,YAAA,EAAc,QAAQ,KAAA,CAAM,YAAA;AAAA,QAC5B,QAAA,EAAU,QAAQ,KAAA,CAAM,QAAA;AAAA,QACxB,aAAA,EAAe,QAAQ,KAAA,CAAM,aAAA;AAAA,QAC7B,kBAAA,EAAoB,yBAAA;AAAA,UAClB,QAAQ,KAAA,CAAM;AAAA,SAChB;AAAA,QACA,SAAA,EAAW,KAAA;AAAA,QACX;AAAA,OACD;AAAA;AACH,GACF;AAEA,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,gCAAgC,QAAA,CAAS,MAAM,MAAM,MAAM,QAAA,CAAS,MAAM,CAAA;AAAA,KAC5E;AAAA,EACF;AAEA,EAAA,OAAO,SAAS,IAAA,EAAK;AACvB","file":"spend.js","sourcesContent":["import type { OpenAITokenSpend } from \"./openai-usage\";\nimport type { GranularQuotaProgress } from \"./types\";\n\nexport interface GranularSpendContext {\n tenantId?: string | null;\n sandboxId?: string | null;\n environmentId?: string | null;\n sessionId?: string | null;\n subjectId?: string | null;\n permissionProfileId?: string | null;\n [key: string]: string | null | undefined;\n}\n\nexport interface OpenAIUsageSpendEvent extends OpenAITokenSpend {\n spendEventId?: string;\n source?: \"openai\";\n lineItemType?: \"llm_tokens\";\n operation?: string;\n requestId?: string | null;\n usageContext?: GranularSpendContext;\n rawUsage?: unknown;\n}\n\nexport interface RecordOpenAIUsageSpendOptions {\n apiUrl: string;\n token: string;\n usage: OpenAIUsageSpendEvent;\n context?: GranularSpendContext | null;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface RecordOpenAIUsageSpendResult {\n spendEventId: string;\n inserted: boolean;\n quota: GranularQuotaProgress | null;\n}\n\nexport function toGranularHttpBase(apiUrl: string): string {\n const url = new URL(apiUrl);\n if (url.protocol === \"ws:\") {\n url.protocol = \"http:\";\n } else if (url.protocol === \"wss:\") {\n url.protocol = \"https:\";\n }\n\n url.pathname = url.pathname\n .replace(/\\/ws\\/connect$/, \"\")\n .replace(/\\/ws$/, \"\");\n if (!url.pathname || url.pathname === \"/\") {\n url.pathname = \"/granular\";\n }\n url.search = \"\";\n url.hash = \"\";\n return url.toString().replace(/\\/$/, \"\");\n}\n\nfunction cleanIdPart(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]+/g, \"_\").replace(/^_+|_+$/g, \"\");\n}\n\nexport function buildOpenAISpendEventId(\n usage: Pick<OpenAIUsageSpendEvent, \"requestId\">,\n context: GranularSpendContext = {},\n): string | undefined {\n const requestId = usage.requestId?.trim();\n if (!requestId) return undefined;\n\n const scope =\n context.sessionId ||\n context.environmentId ||\n context.subjectId ||\n context.sandboxId ||\n \"global\";\n return [\"spend\", \"openai\", scope, requestId].map(cleanIdPart).join(\"_\");\n}\n\nfunction pricingEffectiveAtSeconds(value: string | null | undefined) {\n if (!value) return null;\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : null;\n}\n\nfunction compactContext(context: GranularSpendContext): GranularSpendContext {\n return Object.fromEntries(\n Object.entries(context).filter(\n ([, value]) => value != null && value !== \"\",\n ),\n ) as GranularSpendContext;\n}\n\nfunction omitTenantId(context: GranularSpendContext): GranularSpendContext {\n const scopedContext = { ...context };\n delete scopedContext.tenantId;\n return scopedContext;\n}\n\nexport async function recordOpenAIUsageSpend(\n options: RecordOpenAIUsageSpendOptions,\n): Promise<RecordOpenAIUsageSpendResult> {\n const usageContext = compactContext({\n ...(options.usage.usageContext || {}),\n ...(options.context || {}),\n });\n const context = omitTenantId(usageContext);\n const spendEventId =\n options.usage.spendEventId ||\n buildOpenAISpendEventId(options.usage, context);\n const metadata = {\n ...(options.metadata || {}),\n ...(options.usage.rawUsage !== undefined\n ? { openaiUsage: options.usage.rawUsage }\n : {}),\n usageContext: context,\n pricingContextTier: options.usage.pricingContextTier,\n cacheWritePricePerMillionMicros:\n options.usage.cacheWritePricePerMillionMicros,\n cacheWriteTokens: options.usage.cacheWriteTokens,\n cacheWriteCostMicros: options.usage.cacheWriteCostMicros,\n longContextThresholdTokens: options.usage.longContextThresholdTokens,\n };\n\n const response = await fetch(\n `${toGranularHttpBase(options.apiUrl)}/control/spend/events`,\n {\n method: \"POST\",\n cache: \"no-store\",\n headers: {\n Authorization: `Bearer ${options.token}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...(spendEventId ? { spendEventId } : {}),\n sandboxId: context.sandboxId || null,\n environmentId: context.environmentId || null,\n sessionId: context.sessionId || null,\n subjectId: context.subjectId || null,\n permissionProfileId: context.permissionProfileId || null,\n source: \"openai\",\n lineItemType: \"llm_tokens\",\n provider: options.usage.provider,\n model: options.usage.model,\n operation: options.usage.operation || \"chat.completions\",\n requestId: options.usage.requestId || null,\n inputTokens: options.usage.inputTokens,\n outputTokens: options.usage.outputTokens,\n cachedInputTokens: options.usage.cachedInputTokens,\n reasoningTokens: options.usage.reasoningTokens,\n quantity: options.usage.totalTokens,\n quantityUnit: \"tokens\",\n inputPricePerMillionMicros: options.usage.inputPricePerMillionMicros,\n cachedInputPricePerMillionMicros:\n options.usage.cachedInputPricePerMillionMicros,\n outputPricePerMillionMicros: options.usage.outputPricePerMillionMicros,\n amountMicros: options.usage.amountMicros,\n currency: options.usage.currency,\n pricingSource: options.usage.pricingSource,\n pricingEffectiveAt: pricingEffectiveAtSeconds(\n options.usage.pricingEffectiveAt,\n ),\n estimated: false,\n metadata,\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Granular spend event failed (${response.status}): ${await response.text()}`,\n );\n }\n\n return response.json() as Promise<RecordOpenAIUsageSpendResult>;\n}\n"]}