@granular-software/sdk 0.4.37 → 0.4.38
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/agent-evals.d.mts +16 -3
- package/dist/agent-evals.d.ts +16 -3
- package/dist/agent-evals.js +341 -105
- package/dist/agent-evals.js.map +1 -1
- package/dist/agent-evals.mjs +340 -105
- package/dist/agent-evals.mjs.map +1 -1
- package/dist/cli/index.js +129 -3
- package/dist/client-BNbWA9jQ.d.ts +1064 -0
- package/dist/client-HDJgcJC5.d.mts +1064 -0
- package/dist/index.d.mts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +231 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +225 -4
- package/dist/index.mjs.map +1 -1
- package/dist/spend-rzS1rlFr.d.mts +1559 -0
- package/dist/spend-rzS1rlFr.d.ts +1559 -0
- package/dist/spend.d.mts +2 -0
- package/dist/spend.d.ts +2 -0
- package/dist/spend.js +111 -0
- package/dist/spend.js.map +1 -0
- package/dist/spend.mjs +107 -0
- package/dist/spend.mjs.map +1 -0
- package/package.json +7 -1
- package/dist/client-eE9nTfvp.d.mts +0 -2483
- package/dist/client-eE9nTfvp.d.ts +0 -2483
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
export { E as Environment, a as EnvironmentSession, G as Granular, O as OntologyHandle, S as Session, W as WSClient } from './client-HDJgcJC5.mjs';
|
|
2
|
+
import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt, d as SessionTranscriptEntry } from './spend-rzS1rlFr.mjs';
|
|
3
|
+
export { bJ as APIError, A as AccessTokenProvider, a0 as Assignment, a1 as AssignmentListResponse, ab as Build, ad as BuildListResponse, a2 as BuildPolicy, aa as BuildStatus, C as ConnectOptions, aH as ConversationAppendResult, aG as ConversationMessageInput, aF as ConversationMessageShowRefs, y as ConversationSessionInfo, a6 as CreateEnvironmentData, _ as CreatePermissionProfileData, W as CreateSandboxData, x as CreateSessionOptions, b4 as DefineRelationshipOptions, bK as DeleteResponse, D as DomainState, au as EffectHandler, ar as EffectInfo, al as EffectInvocationMetadata, ak as EffectInvocationMode, am as EffectSchema, ap as EffectVersionSelector, an as EffectWithHandler, at as EffectsChangedEvent, a5 as EnvironmentData, aC as EnvironmentFeedbackRecord, bm as EnvironmentImporter, bl as EnvironmentImporterImportOptions, a7 as EnvironmentListResponse, bg as EnvironmentRecordImportSummary, bj as EnvironmentSetupLifecycleStatus, bk as EnvironmentSetupSummary, bh as EnvironmentSetupTriggerReason, s as GranularAuth, q as GranularOptions, K as GranularQuotaPolicy, L as GranularQuotaProgress, G as GranularSpendContext, bI as GraphQLResult, av as InstanceEffectHandler, I as InstanceToolHandler, aE as Job, aA as JobFeedbackInput, az as JobFeedbackMetadata, aB as JobFeedbackRecord, ax as JobFeedbackSentiment, ay as JobFeedbackToolCall, aw as JobStatus, aD as JobSubmitResult, a8 as Manifest, by as ManifestApprovalRequiredSpec, bH as ManifestContent, bw as ManifestDryRunSpec, bB as ManifestEffectDeclaration, bA as ManifestEffectSchema, bp as ManifestEnumRuleSpec, bD as ManifestEventStreamDef, bC as ManifestEventTypeDef, bq as ManifestFilterBySpec, bF as ManifestImport, a9 as ManifestListResponse, bE as ManifestOperation, bv as ManifestPostConditionSpec, bn as ManifestPropertySpec, bz as ManifestRelationshipDef, bx as ManifestReverseSpec, bu as ManifestStateMachineSpec, bs as ManifestStateMachineStateSpec, bt as ManifestStateMachineTransitionSpec, bo as ManifestValidationOperator, br as ManifestValidationRuleSpec, bG as ManifestVolume, b2 as ModelRef, N as NormalizedOpenAIUsage, i as OPENAI_MODEL_PRICING_USD_PER_MILLION, O as OpenAIModelPricing, h as OpenAITokenSpend, l as OpenAIUsageSpendEvent, w as OpenEnvironmentOptions, Z as PermissionProfile, $ as PermissionProfileListResponse, Y as PermissionRules, ao as PublishEffectsResult, f as PublishToolsResult, J as QuotaLineItemFilter, B as QuotaPeriod, Q as QuotaScopeType, F as QuotaStatus, aY as RPCRequest, a$ as RPCRequestFromServer, aZ as RPCResponse, bf as RecordImport, be as RecordImportItem, bc as RecordImportItemStatus, ba as RecordImportOptions, bd as RecordImportStats, bb as RecordImportStatus, b9 as RecordImportWriteMode, aQ as RecordMentionInput, b5 as RecordObjectOptions, b6 as RecordObjectResult, b7 as RecordObjectsChunkInfo, b8 as RecordObjectsOptions, m as RecordOpenAIUsageSpendOptions, o as RecordOpenAIUsageSpendResult, aP as RecordSearchOptions, aO as RecordSearchResult, u as RecordUserOptions, b3 as RelationshipInfo, aj as ResolvedEffectApprovalRequired, ah as ResolvedEffectDryRun, ag as ResolvedEffectPostCondition, ai as ResolvedEffectReverse, bi as RunEnvironmentImporterOptions, V as Sandbox, X as SandboxListResponse, af as SemanticVersionDiff, ae as SemanticVersionDiffEntry, aS as SessionCollectionListOptions, aU as SessionCollectionListResult, aI as SessionConversationMessage, aR as SessionDocumentResult, aL as SessionHeapFieldType, aM as SessionHeapFieldValue, aN as SessionHeapVariable, aT as SessionJobListOptions, aK as SessionJobRecord, aJ as SessionTimelineEvent, z as SpendLineItemType, H as SpendSummary, bL as StreamEvent, bN as StreamStats, bM as StreamSubscription, v as Subject, a_ as SyncMessage, g as ToolHandler, aq as ToolInfo, b0 as ToolInvokeParams, b1 as ToolResultParams, e as ToolSchema, as as ToolsChangedEvent, U as User, ac as Version, a4 as VersionTag, a3 as VersionTracking, aX as WSClientOptions, aV as WSDisconnectInfo, aW as WSReconnectErrorInfo, p as buildOpenAISpendEventId, k as calculateOpenAITokenSpend, j as getOpenAIModelPricing, n as normalizeOpenAIUsage, r as recordOpenAIUsageSpend, t as toGranularHttpBase } from './spend-rzS1rlFr.mjs';
|
|
3
4
|
export { ConditionIR, ConditionalPolicySpec, LimitPolicySpec, MatchedPolicy, PermissionActionSpec, PermissionPolicySpec, PermissionProfileFile, PolicyDecision, PolicyEvaluationContext, PolicyOutcome, PolicyRuleIR } from '@granular-software/policy-engine';
|
|
4
5
|
export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentPromptCapabilities, GranularAgentReferentFocus, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, GranularReasoningTraceChunkResult, GranularReasoningTraceOptions, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, ReviewGeneratedJobCodeOptions, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentReferentBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode, stripGranularReasoningTrace } from './agent-harness.mjs';
|
|
5
6
|
import '@automerge/automerge';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
export { E as Environment, a as EnvironmentSession, G as Granular, O as OntologyHandle, S as Session, W as WSClient } from './client-BNbWA9jQ.js';
|
|
2
|
+
import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt, d as SessionTranscriptEntry } from './spend-rzS1rlFr.js';
|
|
3
|
+
export { bJ as APIError, A as AccessTokenProvider, a0 as Assignment, a1 as AssignmentListResponse, ab as Build, ad as BuildListResponse, a2 as BuildPolicy, aa as BuildStatus, C as ConnectOptions, aH as ConversationAppendResult, aG as ConversationMessageInput, aF as ConversationMessageShowRefs, y as ConversationSessionInfo, a6 as CreateEnvironmentData, _ as CreatePermissionProfileData, W as CreateSandboxData, x as CreateSessionOptions, b4 as DefineRelationshipOptions, bK as DeleteResponse, D as DomainState, au as EffectHandler, ar as EffectInfo, al as EffectInvocationMetadata, ak as EffectInvocationMode, am as EffectSchema, ap as EffectVersionSelector, an as EffectWithHandler, at as EffectsChangedEvent, a5 as EnvironmentData, aC as EnvironmentFeedbackRecord, bm as EnvironmentImporter, bl as EnvironmentImporterImportOptions, a7 as EnvironmentListResponse, bg as EnvironmentRecordImportSummary, bj as EnvironmentSetupLifecycleStatus, bk as EnvironmentSetupSummary, bh as EnvironmentSetupTriggerReason, s as GranularAuth, q as GranularOptions, K as GranularQuotaPolicy, L as GranularQuotaProgress, G as GranularSpendContext, bI as GraphQLResult, av as InstanceEffectHandler, I as InstanceToolHandler, aE as Job, aA as JobFeedbackInput, az as JobFeedbackMetadata, aB as JobFeedbackRecord, ax as JobFeedbackSentiment, ay as JobFeedbackToolCall, aw as JobStatus, aD as JobSubmitResult, a8 as Manifest, by as ManifestApprovalRequiredSpec, bH as ManifestContent, bw as ManifestDryRunSpec, bB as ManifestEffectDeclaration, bA as ManifestEffectSchema, bp as ManifestEnumRuleSpec, bD as ManifestEventStreamDef, bC as ManifestEventTypeDef, bq as ManifestFilterBySpec, bF as ManifestImport, a9 as ManifestListResponse, bE as ManifestOperation, bv as ManifestPostConditionSpec, bn as ManifestPropertySpec, bz as ManifestRelationshipDef, bx as ManifestReverseSpec, bu as ManifestStateMachineSpec, bs as ManifestStateMachineStateSpec, bt as ManifestStateMachineTransitionSpec, bo as ManifestValidationOperator, br as ManifestValidationRuleSpec, bG as ManifestVolume, b2 as ModelRef, N as NormalizedOpenAIUsage, i as OPENAI_MODEL_PRICING_USD_PER_MILLION, O as OpenAIModelPricing, h as OpenAITokenSpend, l as OpenAIUsageSpendEvent, w as OpenEnvironmentOptions, Z as PermissionProfile, $ as PermissionProfileListResponse, Y as PermissionRules, ao as PublishEffectsResult, f as PublishToolsResult, J as QuotaLineItemFilter, B as QuotaPeriod, Q as QuotaScopeType, F as QuotaStatus, aY as RPCRequest, a$ as RPCRequestFromServer, aZ as RPCResponse, bf as RecordImport, be as RecordImportItem, bc as RecordImportItemStatus, ba as RecordImportOptions, bd as RecordImportStats, bb as RecordImportStatus, b9 as RecordImportWriteMode, aQ as RecordMentionInput, b5 as RecordObjectOptions, b6 as RecordObjectResult, b7 as RecordObjectsChunkInfo, b8 as RecordObjectsOptions, m as RecordOpenAIUsageSpendOptions, o as RecordOpenAIUsageSpendResult, aP as RecordSearchOptions, aO as RecordSearchResult, u as RecordUserOptions, b3 as RelationshipInfo, aj as ResolvedEffectApprovalRequired, ah as ResolvedEffectDryRun, ag as ResolvedEffectPostCondition, ai as ResolvedEffectReverse, bi as RunEnvironmentImporterOptions, V as Sandbox, X as SandboxListResponse, af as SemanticVersionDiff, ae as SemanticVersionDiffEntry, aS as SessionCollectionListOptions, aU as SessionCollectionListResult, aI as SessionConversationMessage, aR as SessionDocumentResult, aL as SessionHeapFieldType, aM as SessionHeapFieldValue, aN as SessionHeapVariable, aT as SessionJobListOptions, aK as SessionJobRecord, aJ as SessionTimelineEvent, z as SpendLineItemType, H as SpendSummary, bL as StreamEvent, bN as StreamStats, bM as StreamSubscription, v as Subject, a_ as SyncMessage, g as ToolHandler, aq as ToolInfo, b0 as ToolInvokeParams, b1 as ToolResultParams, e as ToolSchema, as as ToolsChangedEvent, U as User, ac as Version, a4 as VersionTag, a3 as VersionTracking, aX as WSClientOptions, aV as WSDisconnectInfo, aW as WSReconnectErrorInfo, p as buildOpenAISpendEventId, k as calculateOpenAITokenSpend, j as getOpenAIModelPricing, n as normalizeOpenAIUsage, r as recordOpenAIUsageSpend, t as toGranularHttpBase } from './spend-rzS1rlFr.js';
|
|
3
4
|
export { ConditionIR, ConditionalPolicySpec, LimitPolicySpec, MatchedPolicy, PermissionActionSpec, PermissionPolicySpec, PermissionProfileFile, PolicyDecision, PolicyEvaluationContext, PolicyOutcome, PolicyRuleIR } from '@granular-software/policy-engine';
|
|
4
5
|
export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentPromptCapabilities, GranularAgentReferentFocus, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, GranularReasoningTraceChunkResult, GranularReasoningTraceOptions, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, ReviewGeneratedJobCodeOptions, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentReferentBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode, stripGranularReasoningTrace } from './agent-harness.js';
|
|
5
6
|
import '@automerge/automerge';
|
package/dist/index.js
CHANGED
|
@@ -4638,6 +4638,7 @@ function withPromptTranscriptTimeout(promise) {
|
|
|
4638
4638
|
var Session = class {
|
|
4639
4639
|
client;
|
|
4640
4640
|
clientId;
|
|
4641
|
+
initialQuota;
|
|
4641
4642
|
jobsMap = /* @__PURE__ */ new Map();
|
|
4642
4643
|
pendingAgentMessagesByJobId = /* @__PURE__ */ new Map();
|
|
4643
4644
|
eventListeners = /* @__PURE__ */ new Map();
|
|
@@ -4653,9 +4654,10 @@ var Session = class {
|
|
|
4653
4654
|
promptCache = /* @__PURE__ */ new Map();
|
|
4654
4655
|
/** Prompt ids locally answered before the document sync catches up. */
|
|
4655
4656
|
hiddenPromptIds = /* @__PURE__ */ new Set();
|
|
4656
|
-
constructor(client, clientId) {
|
|
4657
|
+
constructor(client, clientId, options = {}) {
|
|
4657
4658
|
this.client = client;
|
|
4658
4659
|
this.clientId = clientId || `client_${Date.now()}`;
|
|
4660
|
+
this.initialQuota = options.initialQuota || null;
|
|
4659
4661
|
this.setupEventHandlers();
|
|
4660
4662
|
this.setupToolInvokeHandler();
|
|
4661
4663
|
}
|
|
@@ -4704,6 +4706,16 @@ var Session = class {
|
|
|
4704
4706
|
get document() {
|
|
4705
4707
|
return this.client.doc;
|
|
4706
4708
|
}
|
|
4709
|
+
get quota() {
|
|
4710
|
+
return this.getQuota();
|
|
4711
|
+
}
|
|
4712
|
+
getQuota() {
|
|
4713
|
+
const quota = this.client.doc.billing?.quota;
|
|
4714
|
+
if (quota && typeof quota === "object") {
|
|
4715
|
+
return quota;
|
|
4716
|
+
}
|
|
4717
|
+
return this.initialQuota;
|
|
4718
|
+
}
|
|
4707
4719
|
get sessionId() {
|
|
4708
4720
|
return this.client.currentSessionId;
|
|
4709
4721
|
}
|
|
@@ -11326,6 +11338,110 @@ async function invokeRegisteredEffect(effectMap, request) {
|
|
|
11326
11338
|
return resolved.handler(request.input, context);
|
|
11327
11339
|
}
|
|
11328
11340
|
|
|
11341
|
+
// src/spend.ts
|
|
11342
|
+
function toGranularHttpBase(apiUrl) {
|
|
11343
|
+
const url = new URL(apiUrl);
|
|
11344
|
+
if (url.protocol === "ws:") {
|
|
11345
|
+
url.protocol = "http:";
|
|
11346
|
+
} else if (url.protocol === "wss:") {
|
|
11347
|
+
url.protocol = "https:";
|
|
11348
|
+
}
|
|
11349
|
+
url.pathname = url.pathname.replace(/\/ws\/connect$/, "").replace(/\/ws$/, "");
|
|
11350
|
+
if (!url.pathname || url.pathname === "/") {
|
|
11351
|
+
url.pathname = "/granular";
|
|
11352
|
+
}
|
|
11353
|
+
url.search = "";
|
|
11354
|
+
url.hash = "";
|
|
11355
|
+
return url.toString().replace(/\/$/, "");
|
|
11356
|
+
}
|
|
11357
|
+
function cleanIdPart(value) {
|
|
11358
|
+
return value.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
|
|
11359
|
+
}
|
|
11360
|
+
function buildOpenAISpendEventId(usage, context = {}) {
|
|
11361
|
+
const requestId = usage.requestId?.trim();
|
|
11362
|
+
if (!requestId) return void 0;
|
|
11363
|
+
const scope = context.sessionId || context.environmentId || context.subjectId || context.sandboxId || "global";
|
|
11364
|
+
return ["spend", "openai", scope, requestId].map(cleanIdPart).join("_");
|
|
11365
|
+
}
|
|
11366
|
+
function pricingEffectiveAtSeconds(value) {
|
|
11367
|
+
if (!value) return null;
|
|
11368
|
+
const parsed = Date.parse(value);
|
|
11369
|
+
return Number.isFinite(parsed) ? Math.floor(parsed / 1e3) : null;
|
|
11370
|
+
}
|
|
11371
|
+
function compactContext(context) {
|
|
11372
|
+
return Object.fromEntries(
|
|
11373
|
+
Object.entries(context).filter(
|
|
11374
|
+
([, value]) => value != null && value !== ""
|
|
11375
|
+
)
|
|
11376
|
+
);
|
|
11377
|
+
}
|
|
11378
|
+
function omitTenantId(context) {
|
|
11379
|
+
const scopedContext = { ...context };
|
|
11380
|
+
delete scopedContext.tenantId;
|
|
11381
|
+
return scopedContext;
|
|
11382
|
+
}
|
|
11383
|
+
async function recordOpenAIUsageSpend(options) {
|
|
11384
|
+
const usageContext = compactContext({
|
|
11385
|
+
...options.usage.usageContext || {},
|
|
11386
|
+
...options.context || {}
|
|
11387
|
+
});
|
|
11388
|
+
const context = omitTenantId(usageContext);
|
|
11389
|
+
const spendEventId = options.usage.spendEventId || buildOpenAISpendEventId(options.usage, context);
|
|
11390
|
+
const metadata = {
|
|
11391
|
+
...options.metadata || {},
|
|
11392
|
+
...options.usage.rawUsage !== void 0 ? { openaiUsage: options.usage.rawUsage } : {},
|
|
11393
|
+
usageContext: context
|
|
11394
|
+
};
|
|
11395
|
+
const response = await fetch(
|
|
11396
|
+
`${toGranularHttpBase(options.apiUrl)}/control/spend/events`,
|
|
11397
|
+
{
|
|
11398
|
+
method: "POST",
|
|
11399
|
+
cache: "no-store",
|
|
11400
|
+
headers: {
|
|
11401
|
+
Authorization: `Bearer ${options.token}`,
|
|
11402
|
+
"Content-Type": "application/json"
|
|
11403
|
+
},
|
|
11404
|
+
body: JSON.stringify({
|
|
11405
|
+
...spendEventId ? { spendEventId } : {},
|
|
11406
|
+
sandboxId: context.sandboxId || null,
|
|
11407
|
+
environmentId: context.environmentId || null,
|
|
11408
|
+
sessionId: context.sessionId || null,
|
|
11409
|
+
subjectId: context.subjectId || null,
|
|
11410
|
+
permissionProfileId: context.permissionProfileId || null,
|
|
11411
|
+
source: "openai",
|
|
11412
|
+
lineItemType: "llm_tokens",
|
|
11413
|
+
provider: options.usage.provider,
|
|
11414
|
+
model: options.usage.model,
|
|
11415
|
+
operation: options.usage.operation || "chat.completions",
|
|
11416
|
+
requestId: options.usage.requestId || null,
|
|
11417
|
+
inputTokens: options.usage.inputTokens,
|
|
11418
|
+
outputTokens: options.usage.outputTokens,
|
|
11419
|
+
cachedInputTokens: options.usage.cachedInputTokens,
|
|
11420
|
+
reasoningTokens: options.usage.reasoningTokens,
|
|
11421
|
+
quantity: options.usage.totalTokens,
|
|
11422
|
+
quantityUnit: "tokens",
|
|
11423
|
+
inputPricePerMillionMicros: options.usage.inputPricePerMillionMicros,
|
|
11424
|
+
cachedInputPricePerMillionMicros: options.usage.cachedInputPricePerMillionMicros,
|
|
11425
|
+
outputPricePerMillionMicros: options.usage.outputPricePerMillionMicros,
|
|
11426
|
+
amountMicros: options.usage.amountMicros,
|
|
11427
|
+
currency: options.usage.currency,
|
|
11428
|
+
pricingSource: options.usage.pricingSource,
|
|
11429
|
+
pricingEffectiveAt: pricingEffectiveAtSeconds(
|
|
11430
|
+
options.usage.pricingEffectiveAt
|
|
11431
|
+
),
|
|
11432
|
+
estimated: false,
|
|
11433
|
+
metadata
|
|
11434
|
+
})
|
|
11435
|
+
}
|
|
11436
|
+
);
|
|
11437
|
+
if (!response.ok) {
|
|
11438
|
+
throw new Error(
|
|
11439
|
+
`Granular spend event failed (${response.status}): ${await response.text()}`
|
|
11440
|
+
);
|
|
11441
|
+
}
|
|
11442
|
+
return response.json();
|
|
11443
|
+
}
|
|
11444
|
+
|
|
11329
11445
|
// ../metamodel-enum/src/index.ts
|
|
11330
11446
|
function renderInlineStringUnion(values) {
|
|
11331
11447
|
return values.map((value) => JSON.stringify(value)).join(" | ");
|
|
@@ -14108,7 +14224,7 @@ var EnvironmentSession = class extends Session {
|
|
|
14108
14224
|
/** The last known graph container status, updated by checkReadiness() or on heartbeat */
|
|
14109
14225
|
graphContainerStatus = null;
|
|
14110
14226
|
constructor(client, environment, clientId, options = {}) {
|
|
14111
|
-
super(client, clientId);
|
|
14227
|
+
super(client, clientId, { initialQuota: options.initialQuota });
|
|
14112
14228
|
this.environment = environment;
|
|
14113
14229
|
this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
|
|
14114
14230
|
}
|
|
@@ -14907,6 +15023,15 @@ var Granular = class _Granular {
|
|
|
14907
15023
|
const environment = this.bindEnvironmentHandle(envData);
|
|
14908
15024
|
return this.bindWebSocketEnvironmentSession(environment, clientId, minted);
|
|
14909
15025
|
}
|
|
15026
|
+
async recordOpenAIUsageSpend(usage, context, options) {
|
|
15027
|
+
return recordOpenAIUsageSpend({
|
|
15028
|
+
apiUrl: this.apiUrl,
|
|
15029
|
+
token: this.apiKey,
|
|
15030
|
+
usage,
|
|
15031
|
+
context,
|
|
15032
|
+
metadata: options?.metadata
|
|
15033
|
+
});
|
|
15034
|
+
}
|
|
14910
15035
|
/**
|
|
14911
15036
|
* Mark a session closed in the control plane. If `environment` is the connected handle for that
|
|
14912
15037
|
* `sessionId`, disconnects the WebSocket so the runtime tears down cleanly.
|
|
@@ -15061,7 +15186,8 @@ var Granular = class _Granular {
|
|
|
15061
15186
|
const environmentSession = new EnvironmentSession(
|
|
15062
15187
|
client,
|
|
15063
15188
|
environment,
|
|
15064
|
-
clientId
|
|
15189
|
+
clientId,
|
|
15190
|
+
{ initialQuota: session.quota || null }
|
|
15065
15191
|
);
|
|
15066
15192
|
await environmentSession.hello();
|
|
15067
15193
|
return environmentSession;
|
|
@@ -17600,9 +17726,105 @@ ${knownFactsBlock}
|
|
|
17600
17726
|
${input.request?.trim() || "Use the latest user message in the conversation."}`;
|
|
17601
17727
|
}
|
|
17602
17728
|
|
|
17729
|
+
// src/openai-usage.ts
|
|
17730
|
+
var OPENAI_PRICING_SOURCE_URL = "https://developers.openai.com/api/docs/models/gpt-5.4/";
|
|
17731
|
+
var OPENAI_PRICING_EFFECTIVE_DATE = "2026-05-19";
|
|
17732
|
+
var OPENAI_MODEL_PRICING_USD_PER_MILLION = {
|
|
17733
|
+
"gpt-5.4": {
|
|
17734
|
+
provider: "openai",
|
|
17735
|
+
model: "gpt-5.4",
|
|
17736
|
+
currency: "USD",
|
|
17737
|
+
inputUsdPerMillion: 2.5,
|
|
17738
|
+
cachedInputUsdPerMillion: 0.25,
|
|
17739
|
+
outputUsdPerMillion: 15,
|
|
17740
|
+
sourceUrl: OPENAI_PRICING_SOURCE_URL,
|
|
17741
|
+
effectiveDate: OPENAI_PRICING_EFFECTIVE_DATE
|
|
17742
|
+
}
|
|
17743
|
+
};
|
|
17744
|
+
function asRecord5(value) {
|
|
17745
|
+
return value && typeof value === "object" ? value : null;
|
|
17746
|
+
}
|
|
17747
|
+
function numberField(record, key) {
|
|
17748
|
+
const value = record?.[key];
|
|
17749
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
17750
|
+
}
|
|
17751
|
+
function microsPerMillion(usdPerMillion) {
|
|
17752
|
+
return Math.round(usdPerMillion * 1e6);
|
|
17753
|
+
}
|
|
17754
|
+
function getOpenAIModelPricing(model) {
|
|
17755
|
+
return OPENAI_MODEL_PRICING_USD_PER_MILLION[model] || null;
|
|
17756
|
+
}
|
|
17757
|
+
function normalizeOpenAIUsage(rawUsage) {
|
|
17758
|
+
const usage = asRecord5(rawUsage);
|
|
17759
|
+
if (!usage) {
|
|
17760
|
+
return {
|
|
17761
|
+
inputTokens: 0,
|
|
17762
|
+
cachedInputTokens: 0,
|
|
17763
|
+
uncachedInputTokens: 0,
|
|
17764
|
+
outputTokens: 0,
|
|
17765
|
+
reasoningTokens: 0,
|
|
17766
|
+
totalTokens: 0
|
|
17767
|
+
};
|
|
17768
|
+
}
|
|
17769
|
+
const inputTokens = numberField(usage, "prompt_tokens") || numberField(usage, "input_tokens");
|
|
17770
|
+
const outputTokens = numberField(usage, "completion_tokens") || numberField(usage, "output_tokens");
|
|
17771
|
+
const totalTokens = numberField(usage, "total_tokens") || inputTokens + outputTokens;
|
|
17772
|
+
const inputDetails = asRecord5(usage.prompt_tokens_details) || asRecord5(usage.input_tokens_details);
|
|
17773
|
+
const outputDetails = asRecord5(usage.completion_tokens_details) || asRecord5(usage.output_tokens_details);
|
|
17774
|
+
const cachedInputTokens = Math.min(
|
|
17775
|
+
inputTokens,
|
|
17776
|
+
numberField(inputDetails, "cached_tokens") || numberField(inputDetails, "cached_input_tokens")
|
|
17777
|
+
);
|
|
17778
|
+
const reasoningTokens = numberField(outputDetails, "reasoning_tokens") || numberField(outputDetails, "reasoning_output_tokens");
|
|
17779
|
+
return {
|
|
17780
|
+
inputTokens,
|
|
17781
|
+
cachedInputTokens,
|
|
17782
|
+
uncachedInputTokens: Math.max(inputTokens - cachedInputTokens, 0),
|
|
17783
|
+
outputTokens,
|
|
17784
|
+
reasoningTokens,
|
|
17785
|
+
totalTokens
|
|
17786
|
+
};
|
|
17787
|
+
}
|
|
17788
|
+
function calculateOpenAITokenSpend(model, rawUsage) {
|
|
17789
|
+
const pricing = getOpenAIModelPricing(model);
|
|
17790
|
+
if (!pricing) return null;
|
|
17791
|
+
const usage = normalizeOpenAIUsage(rawUsage);
|
|
17792
|
+
const inputPricePerMillionMicros = microsPerMillion(
|
|
17793
|
+
pricing.inputUsdPerMillion
|
|
17794
|
+
);
|
|
17795
|
+
const cachedInputPricePerMillionMicros = microsPerMillion(
|
|
17796
|
+
pricing.cachedInputUsdPerMillion
|
|
17797
|
+
);
|
|
17798
|
+
const outputPricePerMillionMicros = microsPerMillion(
|
|
17799
|
+
pricing.outputUsdPerMillion
|
|
17800
|
+
);
|
|
17801
|
+
const amountMicros = Math.round(
|
|
17802
|
+
(usage.uncachedInputTokens * inputPricePerMillionMicros + usage.cachedInputTokens * cachedInputPricePerMillionMicros + usage.outputTokens * outputPricePerMillionMicros) / 1e6
|
|
17803
|
+
);
|
|
17804
|
+
return {
|
|
17805
|
+
provider: "openai",
|
|
17806
|
+
model,
|
|
17807
|
+
inputTokens: usage.inputTokens,
|
|
17808
|
+
cachedInputTokens: usage.cachedInputTokens,
|
|
17809
|
+
uncachedInputTokens: usage.uncachedInputTokens,
|
|
17810
|
+
outputTokens: usage.outputTokens,
|
|
17811
|
+
reasoningTokens: usage.reasoningTokens,
|
|
17812
|
+
totalTokens: usage.totalTokens,
|
|
17813
|
+
amountMicros,
|
|
17814
|
+
currency: "USD",
|
|
17815
|
+
inputPricePerMillionMicros,
|
|
17816
|
+
cachedInputPricePerMillionMicros,
|
|
17817
|
+
outputPricePerMillionMicros,
|
|
17818
|
+
pricingSource: pricing.sourceUrl,
|
|
17819
|
+
pricingEffectiveAt: pricing.effectiveDate,
|
|
17820
|
+
usage
|
|
17821
|
+
};
|
|
17822
|
+
}
|
|
17823
|
+
|
|
17603
17824
|
exports.Environment = Environment;
|
|
17604
17825
|
exports.EnvironmentSession = EnvironmentSession;
|
|
17605
17826
|
exports.Granular = Granular;
|
|
17827
|
+
exports.OPENAI_MODEL_PRICING_USD_PER_MILLION = OPENAI_MODEL_PRICING_USD_PER_MILLION;
|
|
17606
17828
|
exports.OntologyHandle = OntologyHandle;
|
|
17607
17829
|
exports.Session = Session;
|
|
17608
17830
|
exports.WSClient = WSClient;
|
|
@@ -17616,7 +17838,9 @@ exports.buildGranularAgentSessionBlock = buildGranularAgentSessionBlock;
|
|
|
17616
17838
|
exports.buildGranularAgentSystemPrompt = buildGranularAgentSystemPrompt;
|
|
17617
17839
|
exports.buildGranularAgentToolBlock = buildGranularAgentToolBlock;
|
|
17618
17840
|
exports.buildGranularAgentWorkflowBlock = buildGranularAgentWorkflowBlock;
|
|
17841
|
+
exports.buildOpenAISpendEventId = buildOpenAISpendEventId;
|
|
17619
17842
|
exports.buildSessionTranscript = buildSessionTranscript;
|
|
17843
|
+
exports.calculateOpenAITokenSpend = calculateOpenAITokenSpend;
|
|
17620
17844
|
exports.consumeGranularReasoningOnlyChunk = consumeGranularReasoningOnlyChunk;
|
|
17621
17845
|
exports.consumeGranularReasoningTraceChunk = consumeGranularReasoningTraceChunk;
|
|
17622
17846
|
exports.createHarnessVerifierSnapshot = createHarnessVerifierSnapshot;
|
|
@@ -17624,10 +17848,12 @@ exports.evaluateContinuation = evaluateContinuation;
|
|
|
17624
17848
|
exports.extractPromptTokens = extractPromptTokens;
|
|
17625
17849
|
exports.getCurrentClosureId = getCurrentClosureId;
|
|
17626
17850
|
exports.getExclusivePromptTarget = getExclusivePromptTarget;
|
|
17851
|
+
exports.getOpenAIModelPricing = getOpenAIModelPricing;
|
|
17627
17852
|
exports.hasOpenPrompt = hasOpenPrompt;
|
|
17628
17853
|
exports.invokeRegisteredEffect = invokeRegisteredEffect;
|
|
17629
17854
|
exports.isLocalApiUrl = isLocalApiUrl;
|
|
17630
17855
|
exports.normalizeEffectBehaviors = normalizeEffectBehaviors;
|
|
17856
|
+
exports.normalizeOpenAIUsage = normalizeOpenAIUsage;
|
|
17631
17857
|
exports.normalizePrompt = normalizePrompt;
|
|
17632
17858
|
exports.normalizePromptChoiceOption = normalizePromptChoiceOption;
|
|
17633
17859
|
exports.normalizePromptText = normalizePromptText;
|
|
@@ -17638,6 +17864,7 @@ exports.projectHeapSummary = projectHeapSummary;
|
|
|
17638
17864
|
exports.projectLoopSummary = projectLoopSummary;
|
|
17639
17865
|
exports.projectWorkflowFocus = projectWorkflowFocus;
|
|
17640
17866
|
exports.projectWorkflowSummary = projectWorkflowSummary;
|
|
17867
|
+
exports.recordOpenAIUsageSpend = recordOpenAIUsageSpend;
|
|
17641
17868
|
exports.resolveApiUrl = resolveApiUrl;
|
|
17642
17869
|
exports.resolveAuthTokenForApiUrl = resolveAuthTokenForApiUrl;
|
|
17643
17870
|
exports.resolveJobPresentation = resolveJobPresentation;
|
|
@@ -17645,5 +17872,6 @@ exports.resolvePromptAnswer = resolvePromptAnswer;
|
|
|
17645
17872
|
exports.reviewGeneratedJobCode = reviewGeneratedJobCode;
|
|
17646
17873
|
exports.scorePromptChoiceMatch = scorePromptChoiceMatch;
|
|
17647
17874
|
exports.stripGranularReasoningTrace = stripGranularReasoningTrace;
|
|
17875
|
+
exports.toGranularHttpBase = toGranularHttpBase;
|
|
17648
17876
|
//# sourceMappingURL=index.js.map
|
|
17649
17877
|
//# sourceMappingURL=index.js.map
|