@qlairoslabs/acp-client 0.12.1 → 0.13.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG-consumer-fixes.md +17 -10
- package/CHANGELOG-controller-interface.md +258 -0
- package/CHANGELOG-metering.md +29 -0
- package/CHANGELOG-operation-lifecycle.md +15 -1
- package/CONSUMER_GUIDE.md +984 -6
- package/MIGRATION-0.10-to-0.12.md +4 -1
- package/MIGRATION-0.12-to-0.13.md +288 -0
- package/README.md +17 -16
- package/package.json +11 -2
- package/src/acp-client-handlers.ts +48 -0
- package/src/activity.ts +3 -0
- package/src/adapters.ts +25 -0
- package/src/agent/adoption/provider-attachment.ts +33 -0
- package/src/agent/adoption/provider-session-delete.ts +1 -1
- package/src/agent/adoption/provider-sessions.ts +3 -2
- package/src/agent/append-assistant-message.ts +91 -0
- package/src/agent/config.ts +54 -6
- package/src/agent/conversation-manager.ts +95 -158
- package/src/agent/manager-settings.ts +1 -0
- package/src/agent/native-channel-lifecycle.ts +111 -0
- package/src/agent/native-operations.ts +39 -0
- package/src/agent/persisted-lifecycle.ts +44 -4
- package/src/agent/persistence-policy/context.ts +13 -0
- package/src/agent/persistence-policy/resolver.ts +7 -0
- package/src/agent/persistence-policy/types.ts +1 -0
- package/src/agent/record-capture.ts +1 -0
- package/src/agent-adapter-registry.ts +33 -7
- package/src/agent-conversation-contracts.ts +14 -1
- package/src/agent-conversation-errors.ts +8 -0
- package/src/agent-conversation-owner.ts +9 -4
- package/src/agent-session-config.ts +137 -0
- package/src/agent-session.ts +440 -934
- package/src/agent.ts +168 -0
- package/src/capabilities.ts +2 -0
- package/src/checkpointing/recovery.ts +3 -0
- package/src/cli/index.ts +3 -3
- package/src/cli/managed.ts +2 -2
- package/src/client.ts +56 -96
- package/src/connection-attempt.ts +95 -0
- package/src/controller-connection.ts +115 -0
- package/src/controller.ts +158 -148
- package/src/conversation-controller/capabilities.ts +88 -0
- package/src/conversation-controller/contracts.ts +208 -0
- package/src/conversation-controller/factory.ts +39 -0
- package/src/conversation-controller/guards.ts +98 -0
- package/src/conversation-controller/index.ts +20 -0
- package/src/conversation-startup.ts +35 -0
- package/src/conversation-turns/backend-turns.ts +373 -0
- package/src/conversation-turns/clear-operations.ts +37 -0
- package/src/conversation-turns/context.ts +135 -0
- package/src/conversation-turns/index.ts +4 -0
- package/src/conversation-turns/record-helpers.ts +75 -0
- package/src/conversation-turns/recording.ts +235 -0
- package/src/conversation-turns/run-turn.ts +367 -0
- package/src/conversation-turns/turn-run.ts +57 -0
- package/src/errors.ts +41 -0
- package/src/handoff-options.ts +81 -0
- package/src/identity/checkpoint-backed.ts +1 -1
- package/src/index.ts +59 -3
- package/src/internal-inference/coordination/manager.ts +11 -0
- package/src/internal-inference/runtime/harness-runtime.ts +4 -4
- package/src/launcher.ts +37 -2
- package/src/media/parts.ts +5 -0
- package/src/message-status.ts +83 -0
- package/src/metering/engine.ts +39 -64
- package/src/metering/measurement-provenance.ts +36 -0
- package/src/metering/native/durability.ts +115 -0
- package/src/metering/native/ledger.ts +104 -0
- package/src/metering/native/operation.ts +85 -0
- package/src/metering/native/projection.ts +114 -0
- package/src/metering/native/proof.ts +51 -0
- package/src/metering/native/requirements.ts +10 -0
- package/src/metering/native/retirement.ts +92 -0
- package/src/metering/native/source.ts +90 -0
- package/src/metering/record.ts +38 -1
- package/src/metering/state.ts +13 -3
- package/src/native/approvals.ts +186 -0
- package/src/native/capabilities.ts +17 -0
- package/src/native/channel-changes.ts +211 -0
- package/src/native/connection.ts +56 -0
- package/src/native/controller.ts +592 -0
- package/src/native/delegation-sender.ts +26 -0
- package/src/native/errors.ts +35 -0
- package/src/native/functions.ts +156 -0
- package/src/native/host-config.ts +59 -0
- package/src/native/host.ts +978 -0
- package/src/native/item-receipts.ts +15 -0
- package/src/native/metering.ts +12 -0
- package/src/native/records.ts +166 -0
- package/src/native/recovery.ts +186 -0
- package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
- package/src/native/reminders/idle.ts +70 -0
- package/src/native/reminders/limits.ts +19 -0
- package/src/native/reminders/notifications.ts +29 -0
- package/src/native/reminders/routine-guard.ts +66 -0
- package/src/native/reminders/routine-schedule.ts +25 -0
- package/src/native/reminders/routine-wire.ts +21 -0
- package/src/native/reminders/schedule.ts +97 -0
- package/src/native/reminders/service.ts +280 -0
- package/src/native/reminders/supervisor.ts +91 -0
- package/src/native/reminders/sync.ts +301 -0
- package/src/native/reminders/wire.ts +197 -0
- package/src/native/submission-withdrawal.ts +65 -0
- package/src/native/usage.ts +15 -0
- package/src/native/worker-delivery.ts +61 -0
- package/src/native-harness/README.md +726 -0
- package/src/native-harness/package.json +24 -0
- package/src/native-harness/scripts/build-routine-zones.py +47 -0
- package/src/native-harness/src/capabilities/context/build.ts +59 -0
- package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
- package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
- package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
- package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
- package/src/native-harness/src/capabilities/context/session.ts +93 -0
- package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
- package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
- package/src/native-harness/src/capabilities/model/runner.ts +116 -0
- package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
- package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
- package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
- package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
- package/src/native-harness/src/capabilities/model/usage.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
- package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
- package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
- package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
- package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
- package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
- package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
- package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
- package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
- package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
- package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
- package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
- package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
- package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
- package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
- package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
- package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
- package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
- package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
- package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
- package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
- package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
- package/src/native-harness/src/client.ts +18 -0
- package/src/native-harness/src/contracts/agent.ts +105 -0
- package/src/native-harness/src/contracts/config-permissions.ts +49 -0
- package/src/native-harness/src/contracts/context.ts +112 -0
- package/src/native-harness/src/contracts/events.ts +47 -0
- package/src/native-harness/src/contracts/input-limits.ts +7 -0
- package/src/native-harness/src/contracts/inspection.ts +22 -0
- package/src/native-harness/src/contracts/loop.ts +31 -0
- package/src/native-harness/src/contracts/model-execution.ts +83 -0
- package/src/native-harness/src/contracts/operator-controls.ts +106 -0
- package/src/native-harness/src/contracts/output.ts +13 -0
- package/src/native-harness/src/contracts/protocol.ts +320 -0
- package/src/native-harness/src/contracts/reminders.ts +134 -0
- package/src/native-harness/src/contracts/routines.ts +20 -0
- package/src/native-harness/src/contracts/scenario.ts +42 -0
- package/src/native-harness/src/contracts/session-file.ts +20 -0
- package/src/native-harness/src/contracts/session.ts +184 -0
- package/src/native-harness/src/contracts/storage.ts +597 -0
- package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
- package/src/native-harness/src/contracts/tools.ts +133 -0
- package/src/native-harness/src/governance/permissions/gate.ts +129 -0
- package/src/native-harness/src/governance/policy/resolve.ts +32 -0
- package/src/native-harness/src/index.ts +322 -0
- package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
- package/src/native-harness/src/interfaces/cli/development.ts +145 -0
- package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
- package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
- package/src/native-harness/src/interfaces/cli/main.ts +47 -0
- package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
- package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
- package/src/native-harness/src/interfaces/cli/start.ts +106 -0
- package/src/native-harness/src/interfaces/client.ts +225 -0
- package/src/native-harness/src/interfaces/inspector/index.html +283 -0
- package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
- package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
- package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
- package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
- package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
- package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
- package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
- package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
- package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
- package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
- package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
- package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
- package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
- package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
- package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
- package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
- package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
- package/src/native-harness/src/kernel/channels.ts +409 -0
- package/src/native-harness/src/kernel/loop.ts +45 -0
- package/src/native-harness/src/runtime/config/development.ts +23 -0
- package/src/native-harness/src/runtime/config/managed.ts +2 -0
- package/src/native-harness/src/runtime/config/paths.ts +33 -0
- package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
- package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
- package/src/native-harness/src/runtime/reminders.ts +66 -0
- package/src/native-harness/src/state/storage/archive.ts +257 -0
- package/src/native-harness/src/state/storage/engine.ts +1204 -0
- package/src/native-harness/src/state/storage/inference.ts +124 -0
- package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
- package/src/native-harness/src/state/storage/memory.ts +354 -0
- package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
- package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
- package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
- package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
- package/src/native-harness/src/state/storage/retrieval.ts +122 -0
- package/src/native-harness/src/state/storage/routine-row.ts +25 -0
- package/src/native-harness/src/state/storage/script-identity.ts +7 -0
- package/src/native-harness/src/state/storage/session-file.ts +85 -0
- package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
- package/src/native-harness/src/state/storage/sqlite.ts +632 -0
- package/src/native-harness/src/testing.ts +190 -0
- package/src/native-harness/src/util/config.ts +66 -0
- package/src/native-harness/src/util/intake.ts +7 -0
- package/src/native-harness/src/util/json.ts +41 -0
- package/src/native-harness/src/util/message-position.ts +3 -0
- package/src/native-harness/src/util/reminder-schedule.ts +44 -0
- package/src/native-harness/src/util/schema.ts +40 -0
- package/src/native-harness/src/util/timeline-text.ts +72 -0
- package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
- package/src/native-harness/tsconfig.json +20 -0
- package/src/observation/agent-event-bus.ts +44 -18
- package/src/observation/index.ts +1 -0
- package/src/operations/contracts.ts +11 -3
- package/src/operations/errors.ts +5 -0
- package/src/operations/stale-policy.ts +1 -1
- package/src/operations/supervisor.ts +34 -10
- package/src/orchestrator/acp-delivery.ts +68 -0
- package/src/orchestrator/assignments.ts +27 -0
- package/src/orchestrator/busy.ts +15 -0
- package/src/orchestrator/config.ts +41 -0
- package/src/orchestrator/consumer-api.ts +24 -0
- package/src/orchestrator/contracts.ts +71 -0
- package/src/orchestrator/durable-assignments.ts +111 -0
- package/src/orchestrator/native-delegation.ts +103 -0
- package/src/orchestrator/orchestrator.ts +318 -0
- package/src/orchestrator/permissions.ts +28 -0
- package/src/orchestrator/policy.ts +44 -0
- package/src/orchestrator/pool.ts +123 -0
- package/src/orchestrator/tool-descriptions.ts +11 -0
- package/src/permissions/acp.ts +18 -0
- package/src/permissions/arrival.ts +13 -0
- package/src/permissions/consumer-config.ts +19 -0
- package/src/permissions/conversation.ts +288 -0
- package/src/permissions/matcher.ts +87 -0
- package/src/permissions/outcome.ts +26 -0
- package/src/permissions/policy.ts +86 -0
- package/src/permissions/request.ts +26 -0
- package/src/persistence/activity-projection.ts +1 -0
- package/src/persistence/backend.ts +34 -1
- package/src/persistence/channels.ts +23 -0
- package/src/persistence/index.ts +4 -0
- package/src/persistence/protocol-method.ts +5 -0
- package/src/persistence/reminder-wake.ts +49 -0
- package/src/persistence/reminders.ts +385 -0
- package/src/persistence/sqlite-backend.ts +84 -6
- package/src/persistence/sqlite-channels.ts +65 -0
- package/src/persistence/sqlite-reminders.ts +85 -0
- package/src/persistence/sqlite-schema.ts +108 -3
- package/src/persistence/sqlite-worker-delivery.ts +374 -0
- package/src/persistence/sqlite-workers.ts +59 -0
- package/src/persistence/worker-delivery-contract.ts +104 -0
- package/src/persistence/worker-terminal-reason.ts +29 -0
- package/src/persistence/workers.ts +19 -0
- package/src/provider-notices.ts +137 -0
- package/src/repl/commands.ts +2 -2
- package/src/steering/combine.ts +3 -1
- package/src/steering/contracts.ts +11 -2
- package/src/steering/controller.ts +3 -2
- package/src/terminals.ts +9 -6
- package/src/transport/acp-transport.ts +24 -14
- package/src/types.ts +15 -12
- package/src/updates.ts +14 -2
- package/src/wire-log.ts +1 -1
package/src/metering/engine.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { requireNativeMeteringCapability } from "./native/requirements.ts";
|
|
1
2
|
// Per-operation metering. See §7 (rating units), §8, §9, §11, §12.
|
|
2
3
|
//
|
|
3
4
|
// The engine owns one rating unit per ACP operation: resolve and freeze a pricing policy
|
|
@@ -18,14 +19,10 @@ import {
|
|
|
18
19
|
MeteringPreflightError,
|
|
19
20
|
type MeteredOperationKind,
|
|
20
21
|
type MeteringEnforcement,
|
|
21
|
-
type MeteringPricingStatus,
|
|
22
|
-
type MeteringProvenance,
|
|
23
22
|
type MeteringUsageResult,
|
|
24
23
|
type OperationMeteringRecord,
|
|
25
24
|
type OperationOutcome,
|
|
26
25
|
type CostReconciliation,
|
|
27
|
-
acpProvenance,
|
|
28
|
-
UNAVAILABLE_PROVENANCE,
|
|
29
26
|
} from "./record.ts";
|
|
30
27
|
import type {
|
|
31
28
|
CategoryApplicability,
|
|
@@ -38,6 +35,9 @@ import type {
|
|
|
38
35
|
import { validatePricingPolicy } from "./pricing.ts";
|
|
39
36
|
import { counterInterpretationForAdapter, type CounterInterpretation } from "./provider.ts";
|
|
40
37
|
import { billingRefusalReason, certificationFor } from "./certification.ts";
|
|
38
|
+
import { measurementPricingStatus, measurementProvenance } from "./measurement-provenance.ts";
|
|
39
|
+
import { advanceNativeCursor, measureNativeOperation, nativeRouteUnavailable } from "./native/operation.ts";
|
|
40
|
+
import { UNVERIFIED_NATIVE_SOURCE, type NativeTurnMetering } from "./native/source.ts";
|
|
41
41
|
import type { ProviderInference } from "./opencode/channel.ts";
|
|
42
42
|
|
|
43
43
|
/**
|
|
@@ -123,6 +123,7 @@ export interface MeteringEngineOptions {
|
|
|
123
123
|
readonly counterInterpretation?: CounterInterpretation;
|
|
124
124
|
/** When present and healthy, replaces ACP usage as the measurement. */
|
|
125
125
|
readonly inferenceSource?: InferenceSource;
|
|
126
|
+
readonly native?: boolean;
|
|
126
127
|
}
|
|
127
128
|
|
|
128
129
|
/** A rating unit opened before dispatch and closed after the operation finishes. */
|
|
@@ -145,6 +146,7 @@ export interface OpenOperation {
|
|
|
145
146
|
* charged to whichever operation happens to be draining.
|
|
146
147
|
*/
|
|
147
148
|
readonly sequenceHighWaterAtOpen: number;
|
|
149
|
+
readonly nativeChannel?: string;
|
|
148
150
|
}
|
|
149
151
|
|
|
150
152
|
export interface CloseOperationInput {
|
|
@@ -155,6 +157,7 @@ export interface CloseOperationInput {
|
|
|
155
157
|
readonly contextAfter: ContextWindowStatus | null;
|
|
156
158
|
readonly providerCostAfter: ProviderCostSnapshot | null;
|
|
157
159
|
readonly billingFacts?: BillingFacts;
|
|
160
|
+
readonly nativeMetering?: NativeTurnMetering;
|
|
158
161
|
}
|
|
159
162
|
|
|
160
163
|
export interface OpenDetachedOperation {
|
|
@@ -180,12 +183,16 @@ export class MeteringEngine {
|
|
|
180
183
|
private trustedZeroBaseline: boolean;
|
|
181
184
|
private baseline: MeteringBaseline | null;
|
|
182
185
|
private readonly interpretation: CounterInterpretation;
|
|
186
|
+
private readonly inferenceSource: InferenceSource | undefined;
|
|
183
187
|
/** Provider cumulative cost as of the previous close, for per-operation deltas. */
|
|
184
188
|
private lastProviderCost: Money | null = null;
|
|
185
189
|
/** Records drained this close that belong to an operation already finished. */
|
|
186
190
|
private lateArrivals: readonly ProviderInference[] = [];
|
|
187
191
|
|
|
188
192
|
constructor(private readonly options: MeteringEngineOptions) {
|
|
193
|
+
if (options.native) requireNativeMeteringCapability(options.enforcement);
|
|
194
|
+
const source = options.inferenceSource;
|
|
195
|
+
this.inferenceSource = source?.certificationId === UNVERIFIED_NATIVE_SOURCE ? undefined : source;
|
|
189
196
|
const restoration = restoreMeteringState(options.initialState, options.agentSessionId);
|
|
190
197
|
this._restoration = restoration;
|
|
191
198
|
this.state =
|
|
@@ -205,7 +212,7 @@ export class MeteringEngine {
|
|
|
205
212
|
const certification = certificationFor(options.adapterId);
|
|
206
213
|
if (
|
|
207
214
|
options.enforcement === "billing_required" &&
|
|
208
|
-
(!certification ||
|
|
215
|
+
(!certification || this.inferenceSource?.certificationId !== certification.certificationId)
|
|
209
216
|
) {
|
|
210
217
|
// Refused at construction rather than at the first prompt: a consumer asking for
|
|
211
218
|
// billing-grade metering should learn it is unavailable before any work is queued,
|
|
@@ -234,7 +241,7 @@ export class MeteringEngine {
|
|
|
234
241
|
}
|
|
235
242
|
/** Reports the certified source is still missing for a thread; retractable. */
|
|
236
243
|
outstandingReports(internalSessionId: string | null): number {
|
|
237
|
-
return this.
|
|
244
|
+
return this.inferenceSource?.outstandingReports?.(internalSessionId) ?? 0;
|
|
238
245
|
}
|
|
239
246
|
get counterInterpretation(): CounterInterpretation {
|
|
240
247
|
return this.interpretation;
|
|
@@ -280,6 +287,7 @@ export class MeteringEngine {
|
|
|
280
287
|
providerId: string | null;
|
|
281
288
|
model: string | null;
|
|
282
289
|
degraded: boolean;
|
|
290
|
+
native?: { readonly host: { readonly sessionId: string }; readonly channelId: string };
|
|
283
291
|
}): Promise<OpenOperation> {
|
|
284
292
|
const strict = this.options.enforcement !== "best_effort";
|
|
285
293
|
|
|
@@ -296,7 +304,7 @@ export class MeteringEngine {
|
|
|
296
304
|
// A certified source that is already unhealthy must fail BEFORE the provider is paid.
|
|
297
305
|
// Checking only afterwards let the first operation through, which defeats the point of
|
|
298
306
|
// a preflight in the one mode that exists to guarantee measurement.
|
|
299
|
-
if (strict && this.
|
|
307
|
+
if (strict && this.inferenceSource && !this.inferenceSource.isHealthy()) {
|
|
300
308
|
throw new MeteringPreflightError(
|
|
301
309
|
"certified metering channel is not healthy; refusing to dispatch billable work",
|
|
302
310
|
);
|
|
@@ -317,7 +325,9 @@ export class MeteringEngine {
|
|
|
317
325
|
let policy: PricingPolicy | null = null;
|
|
318
326
|
let pricingFailureReason: string | null = null;
|
|
319
327
|
|
|
320
|
-
if (
|
|
328
|
+
if (input.native) {
|
|
329
|
+
pricingFailureReason = nativeRouteUnavailable;
|
|
330
|
+
} else if (this.options.pricing === false) {
|
|
321
331
|
if (strict) {
|
|
322
332
|
throw new MeteringPreflightError("pricing is disabled but this mode requires rating");
|
|
323
333
|
}
|
|
@@ -347,14 +357,15 @@ export class MeteringEngine {
|
|
|
347
357
|
operationId: input.operationId,
|
|
348
358
|
operationKind: input.operationKind,
|
|
349
359
|
startedAt,
|
|
350
|
-
internalSessionId: input.internalSessionId,
|
|
351
|
-
providerId: input.providerId,
|
|
352
|
-
model: input.model,
|
|
360
|
+
internalSessionId: input.native ? `${input.native.host.sessionId}/${input.native.channelId}` : input.internalSessionId,
|
|
361
|
+
providerId: input.native ? null : input.providerId,
|
|
362
|
+
model: input.native ? null : input.model,
|
|
363
|
+
...(input.native ? { nativeChannel: input.native.channelId } : {}),
|
|
353
364
|
policy,
|
|
354
365
|
pricingFailureReason,
|
|
355
|
-
permanentlyLostAtOpen: this.
|
|
366
|
+
permanentlyLostAtOpen: this.inferenceSource?.permanentlyLostCount?.() ?? 0,
|
|
356
367
|
sequenceHighWaterAtOpen:
|
|
357
|
-
this.
|
|
368
|
+
this.inferenceSource?.sequenceHighWater?.(input.internalSessionId) ?? 0,
|
|
358
369
|
});
|
|
359
370
|
}
|
|
360
371
|
|
|
@@ -427,31 +438,15 @@ export class MeteringEngine {
|
|
|
427
438
|
*/
|
|
428
439
|
async close(open: OpenOperation, input: CloseOperationInput): Promise<OperationMeteringRecord> {
|
|
429
440
|
const strict = this.options.enforcement !== "best_effort";
|
|
430
|
-
const
|
|
441
|
+
const nativeRead = measureNativeOperation(open, input, this.state);
|
|
442
|
+
const native = nativeRead ? await nativeRead : undefined;
|
|
443
|
+
const source = native ? undefined : this.inferenceSource;
|
|
431
444
|
const certified = source ? await this.measureCertified(source, open, input) : null;
|
|
432
445
|
const { usage, attributable, applicability, nextBaseline, ratingFailureReason, ratingComplete } =
|
|
433
|
-
certified ?? this.measure(open, input);
|
|
434
|
-
|
|
435
|
-
let pricingStatus: MeteringPricingStatus;
|
|
436
|
-
// A post-operation rating failure is more specific than a preflight one, so it wins.
|
|
437
|
-
let pricingFailureReason = ratingFailureReason ?? open.pricingFailureReason ?? undefined;
|
|
446
|
+
native ? { ...native, nextBaseline: this.baseline } : certified ?? this.measure(open, input);
|
|
438
447
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
// as the "was this priced" signal marked fully-rated multi-model operations
|
|
442
|
-
// pricing_unavailable and blocked strict mode on correctly priced work.
|
|
443
|
-
if (usage.status !== "metered") {
|
|
444
|
-
pricingStatus = "not_attributable";
|
|
445
|
-
} else if (this.options.pricing === false) {
|
|
446
|
-
pricingStatus = "not_configured";
|
|
447
|
-
} else if (ratingComplete && attributable && isTotalComplete(attributable.ratedTotal)) {
|
|
448
|
-
// Completeness is read off the DATA, not from a flag travelling beside it. The two
|
|
449
|
-
// could drift, and did: a fully rated multi-model operation was once reported
|
|
450
|
-
// pricing_unavailable because a separate signal disagreed with the total.
|
|
451
|
-
pricingStatus = "priced";
|
|
452
|
-
} else {
|
|
453
|
-
pricingStatus = "pricing_unavailable";
|
|
454
|
-
}
|
|
448
|
+
const pricingFailureReason = ratingFailureReason ?? open.pricingFailureReason ?? undefined;
|
|
449
|
+
const pricingStatus = measurementPricingStatus(usage, this.options.pricing === false && !native, ratingComplete, attributable);
|
|
455
450
|
|
|
456
451
|
// Swept before provenance so the attribution claim and the blocking decision are made
|
|
457
452
|
// from the same facts, not from two separate reads of a moving source.
|
|
@@ -462,43 +457,22 @@ export class MeteringEngine {
|
|
|
462
457
|
const permanentlyLost =
|
|
463
458
|
(source?.permanentlyLostCount?.() ?? 0) > open.permanentlyLostAtOpen;
|
|
464
459
|
|
|
465
|
-
const provenance
|
|
466
|
-
|
|
467
|
-
? UNAVAILABLE_PROVENANCE
|
|
468
|
-
: certified
|
|
469
|
-
? Object.freeze({
|
|
470
|
-
source: "certified" as const,
|
|
471
|
-
measurement: "provider_normalized" as const,
|
|
472
|
-
// Still "observed", never "enforced": the plugin reports what the harness
|
|
473
|
-
// ran, but a library cannot prove no model call bypassed it.
|
|
474
|
-
routing: "observed" as const,
|
|
475
|
-
// "complete" has to be EARNED. If the source lost a report while this
|
|
476
|
-
// operation ran, some inference happened that we never saw, and claiming
|
|
477
|
-
// complete attribution would be exactly the overstatement this design
|
|
478
|
-
// refuses everywhere else.
|
|
479
|
-
attribution:
|
|
480
|
-
outstanding > 0 || permanentlyLost || foreign.length > 0
|
|
481
|
-
? ("partial" as const)
|
|
482
|
-
: ("complete" as const),
|
|
483
|
-
certificationId: source!.certificationId,
|
|
484
|
-
})
|
|
485
|
-
: acpProvenance(this.interpretation);
|
|
460
|
+
const provenance = native?.provenance ?? measurementProvenance(usage, this.interpretation,
|
|
461
|
+
certified ? source?.certificationId : undefined, outstanding > 0 || permanentlyLost || foreign.length > 0);
|
|
486
462
|
|
|
487
463
|
this.state = accrueOperation(this.state, {
|
|
488
464
|
attributable,
|
|
489
465
|
applicability,
|
|
490
466
|
baseline: nextBaseline,
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
],
|
|
497
|
-
}
|
|
498
|
-
: {}),
|
|
467
|
+
partial: native?.partial,
|
|
468
|
+
unallocated: native?.unallocated ?? [
|
|
469
|
+
...foreign.map((inference) => toUnallocated(inference, "foreign")),
|
|
470
|
+
...this.lateArrivals.map((inference) => toUnallocated(inference, "late")),
|
|
471
|
+
],
|
|
499
472
|
});
|
|
500
473
|
this.baseline = nextBaseline;
|
|
501
474
|
if (nextBaseline) this.trustedZeroBaseline = false;
|
|
475
|
+
this.state = advanceNativeCursor(this.state, open.internalSessionId, native?.accountedThrough);
|
|
502
476
|
|
|
503
477
|
const record: OperationMeteringRecord = Object.freeze({
|
|
504
478
|
operationId: open.operationId,
|
|
@@ -515,6 +489,7 @@ export class MeteringEngine {
|
|
|
515
489
|
}),
|
|
516
490
|
provenance,
|
|
517
491
|
usage,
|
|
492
|
+
...(native ? { nativeUsage: native.evidence } : {}),
|
|
518
493
|
pricingStatus,
|
|
519
494
|
...(pricingFailureReason ? { pricingFailureReason } : {}),
|
|
520
495
|
contextAfter: input.contextAfter,
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { isTotalComplete } from "./money.ts";
|
|
2
|
+
import type { AttributableUsage } from "./rating.ts";
|
|
3
|
+
import type { MeteringPricingStatus } from "./record.ts";
|
|
4
|
+
import type { CounterInterpretation } from "./provider.ts";
|
|
5
|
+
import { acpProvenance, UNAVAILABLE_PROVENANCE, type MeteringProvenance, type MeteringUsageResult } from "./record.ts";
|
|
6
|
+
|
|
7
|
+
export function measurementProvenance(
|
|
8
|
+
usage: MeteringUsageResult,
|
|
9
|
+
interpretation: CounterInterpretation,
|
|
10
|
+
certificationId: string | undefined,
|
|
11
|
+
incomplete: boolean,
|
|
12
|
+
): MeteringProvenance {
|
|
13
|
+
if (usage.status !== "metered") return UNAVAILABLE_PROVENANCE;
|
|
14
|
+
if (certificationId === undefined) return acpProvenance(interpretation);
|
|
15
|
+
return Object.freeze({
|
|
16
|
+
source: "certified",
|
|
17
|
+
measurement: "provider_normalized",
|
|
18
|
+
// The integration observes the route but cannot establish that no traffic bypassed it.
|
|
19
|
+
routing: "observed",
|
|
20
|
+
attribution: incomplete ? "partial" : "complete",
|
|
21
|
+
certificationId,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
export function measurementPricingStatus(
|
|
27
|
+
usage: MeteringUsageResult,
|
|
28
|
+
disabled: boolean,
|
|
29
|
+
complete: boolean | undefined,
|
|
30
|
+
attributable: AttributableUsage | null,
|
|
31
|
+
): MeteringPricingStatus {
|
|
32
|
+
if (usage.status !== "metered") return "not_attributable";
|
|
33
|
+
if (disabled) return "not_configured";
|
|
34
|
+
// Multi-model pricing has no top-level source, so use completeness of the rated total.
|
|
35
|
+
return complete && attributable && isTotalComplete(attributable.ratedTotal) ? "priced" : "pricing_unavailable";
|
|
36
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { AgentConversationId } from "../../agent-ids.ts";
|
|
2
|
+
import type { MeteringOperationIdentity, PersistenceBackend } from "../../persistence/backend.ts";
|
|
3
|
+
import type { MeteringEngine, OpenOperation } from "../engine.ts";
|
|
4
|
+
import type { OperationMeteringRecord } from "../record.ts";
|
|
5
|
+
import { accountedNativeAttempts } from "./retirement.ts";
|
|
6
|
+
import type { NativeTurnMetering } from "./source.ts";
|
|
7
|
+
import { emptyMeteringState, type AgentSessionMeteringState } from "../state.ts";
|
|
8
|
+
|
|
9
|
+
export interface NativeMeteringRecovery {
|
|
10
|
+
readonly supportsEarlierProof?: boolean;
|
|
11
|
+
restore(): Promise<AgentSessionMeteringState>;
|
|
12
|
+
find(operationId: string): Promise<OperationMeteringRecord | MeteringOperationIdentity | null>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Persist one write-ahead record in the existing metering state, then commit it normally. */
|
|
16
|
+
export class DurableNativeMetering implements NativeMeteringRecovery {
|
|
17
|
+
constructor(
|
|
18
|
+
private readonly persistence: PersistenceBackend,
|
|
19
|
+
private readonly conversationId: AgentConversationId,
|
|
20
|
+
private readonly agentId: string,
|
|
21
|
+
private readonly commit: (record: OperationMeteringRecord) => Promise<void>,
|
|
22
|
+
) {}
|
|
23
|
+
|
|
24
|
+
get supportsEarlierProof(): boolean { return this.persistence.metering.operationIdentity !== undefined; }
|
|
25
|
+
|
|
26
|
+
async restore(): Promise<AgentSessionMeteringState> {
|
|
27
|
+
const before = await this.persistence.metering.state(this.conversationId);
|
|
28
|
+
if (!before?.state.pendingNativeMetering) return before?.state ?? emptyMeteringState(this.agentId);
|
|
29
|
+
const record = before.state.pendingNativeMetering;
|
|
30
|
+
validatePendingNativeMetering(before.state, record);
|
|
31
|
+
await this.commit(record);
|
|
32
|
+
return (await this.persistence.metering.state(this.conversationId))!.state;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
find(operationId: string): Promise<OperationMeteringRecord | MeteringOperationIdentity | null> {
|
|
36
|
+
return this.#find(this.persistence.metering, operationId);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async record(record: OperationMeteringRecord): Promise<void> {
|
|
40
|
+
const staged = await this.persistence.transaction(async ({ metering }) => {
|
|
41
|
+
if (await this.#find(metering, record.operationId)) return null;
|
|
42
|
+
const persisted = await metering.state(this.conversationId);
|
|
43
|
+
const state = persisted?.state ?? emptyMeteringState(this.agentId);
|
|
44
|
+
const pending = state.pendingNativeMetering;
|
|
45
|
+
if (pending && pending.operationId !== record.operationId) {
|
|
46
|
+
throw new Error("a different native metering operation is awaiting commit");
|
|
47
|
+
}
|
|
48
|
+
const candidate = pending ?? record;
|
|
49
|
+
validatePendingNativeMetering(state, candidate);
|
|
50
|
+
if (!pending) await metering.saveState(this.conversationId, { ...state, pendingNativeMetering: candidate });
|
|
51
|
+
return candidate;
|
|
52
|
+
});
|
|
53
|
+
if (staged) await this.commit(staged);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async #find(metering: PersistenceBackend["metering"], operationId: string) {
|
|
57
|
+
const record = await metering.get(this.conversationId, operationId);
|
|
58
|
+
if (record) return record;
|
|
59
|
+
return await metering.operationIdentity?.(this.conversationId, operationId) ?? null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Restore only committed accounting before touching the turn's ledger or accruing usage. */
|
|
64
|
+
export async function recoverNativeClose(
|
|
65
|
+
recovery: NativeMeteringRecovery | undefined,
|
|
66
|
+
engine: MeteringEngine,
|
|
67
|
+
open: OpenOperation,
|
|
68
|
+
): Promise<OperationMeteringRecord | null> {
|
|
69
|
+
if (!recovery) return null;
|
|
70
|
+
const state = await recovery.restore();
|
|
71
|
+
engine.adoptAccounting(state);
|
|
72
|
+
const existing = await recovery.find(open.operationId);
|
|
73
|
+
if (existing === null || "usage" in existing) return existing;
|
|
74
|
+
return {
|
|
75
|
+
operationId: open.operationId, operationKind: open.operationKind, outcome: existing.outcome,
|
|
76
|
+
startedAt: existing.completedAt, completedAt: existing.completedAt, agentSessionId: state.agentSessionId,
|
|
77
|
+
internalSessionId: open.internalSessionId, provider: { adapterId: existing.adapterId, providerId: null, model: null },
|
|
78
|
+
nativeUsage: { channel: open.nativeChannel!, turnId: null, status: "unavailable", reason: "metering detail was pruned",
|
|
79
|
+
...(existing.unaccountedEarlierCalls ? { unaccountedEarlierCalls: existing.unaccountedEarlierCalls } : {}),
|
|
80
|
+
...(existing.unaccountedEarlierSummary ? { unaccountedEarlierSummary: existing.unaccountedEarlierSummary } : {}) },
|
|
81
|
+
provenance: { source: "none", measurement: "unavailable", routing: "unknown", attribution: "unavailable" },
|
|
82
|
+
usage: { status: "usage_unavailable", reason: "native metering was already committed and its detail was pruned" },
|
|
83
|
+
pricingStatus: "not_attributable", contextAfter: null, providerCostAfter: null,
|
|
84
|
+
costReconciliation: { status: "unavailable", reason: "metering record detail was pruned" }, nextState: state,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function withNativeAccounting(
|
|
89
|
+
turn: NativeTurnMetering | undefined,
|
|
90
|
+
recovery: NativeMeteringRecovery | undefined,
|
|
91
|
+
): NativeTurnMetering | undefined {
|
|
92
|
+
if (!turn || !recovery) return turn;
|
|
93
|
+
return {
|
|
94
|
+
...turn,
|
|
95
|
+
terminalEarlierTurns: recovery.supportsEarlierProof ? turn.terminalEarlierTurns : undefined,
|
|
96
|
+
async accountedAttempts(turnId) {
|
|
97
|
+
const found = await recovery.find(`native-turn-${turnId}`);
|
|
98
|
+
if (!found) return null;
|
|
99
|
+
if (!("usage" in found)) {
|
|
100
|
+
const ids = found.nativeAccountedAttemptIds;
|
|
101
|
+
return ids && { ids, truncated: found.nativeAccountedAttemptsTruncated };
|
|
102
|
+
}
|
|
103
|
+
const ids = accountedNativeAttempts(found);
|
|
104
|
+
return ids && { ids };
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function validatePendingNativeMetering(state: AgentSessionMeteringState, record: OperationMeteringRecord): void {
|
|
110
|
+
if (!record.nativeUsage || record.agentSessionId !== state.agentSessionId ||
|
|
111
|
+
record.nextState?.agentSessionId !== state.agentSessionId ||
|
|
112
|
+
record.nextState.operationCount !== state.operationCount + 1 || record.nextState.pendingNativeMetering) {
|
|
113
|
+
throw new Error("Invalid pending native metering operation");
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { untilAborted } from "../../connection-attempt.ts";
|
|
2
|
+
import type { ModelCallSummary } from "../../native-harness/src/client.ts";
|
|
3
|
+
|
|
4
|
+
type LedgerPage = { readonly calls: readonly ModelCallSummary[]; readonly next?: string };
|
|
5
|
+
type ReadPage = (query: { readonly after?: string }, signal: AbortSignal) => Promise<LedgerPage>;
|
|
6
|
+
|
|
7
|
+
interface LedgerBounds {
|
|
8
|
+
readonly timeoutMs: number;
|
|
9
|
+
readonly maxPages: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface NativeLedgerPosition {
|
|
13
|
+
/** An accounted prefix supplied by the caller. A scan never advances it by itself. */
|
|
14
|
+
readonly after?: string;
|
|
15
|
+
readonly signal?: AbortSignal;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface NativeLedgerRead {
|
|
19
|
+
readonly calls: readonly ModelCallSummary[];
|
|
20
|
+
readonly lastSeenCallId?: string;
|
|
21
|
+
/** Same-channel rows in ledger order, through the last call of the requested turn. */
|
|
22
|
+
readonly prefix: readonly ModelCallSummary[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const defaultBounds: LedgerBounds = { timeoutMs: 15_000, maxPages: 1_000 };
|
|
26
|
+
|
|
27
|
+
/** A shared, stateless reader. A stalled pull owns only its own deadline. */
|
|
28
|
+
export class NativeUsageLedger {
|
|
29
|
+
constructor(
|
|
30
|
+
private readonly openRead: () => ReadPage,
|
|
31
|
+
private readonly bounds: LedgerBounds = defaultBounds,
|
|
32
|
+
) {}
|
|
33
|
+
|
|
34
|
+
async readTurn(channel: string, turnId: string, position: NativeLedgerPosition = {}): Promise<NativeLedgerRead> {
|
|
35
|
+
const timeout = new AbortController();
|
|
36
|
+
const signal = position.signal ? AbortSignal.any([position.signal, timeout.signal]) : timeout.signal;
|
|
37
|
+
let after = position.after;
|
|
38
|
+
const seenIds = new Set(after === undefined ? [] : [after]);
|
|
39
|
+
const calls: ModelCallSummary[] = [];
|
|
40
|
+
const channelCalls: ModelCallSummary[] = [];
|
|
41
|
+
|
|
42
|
+
// Keep one timer even when consecutive pages briefly have no abort listeners.
|
|
43
|
+
const timer = setTimeout(() => timeout.abort(new DOMException("Native usage ledger read timed out", "TimeoutError")), this.bounds.timeoutMs);
|
|
44
|
+
try {
|
|
45
|
+
const readPage = this.openRead();
|
|
46
|
+
for (let count = 0; count < this.bounds.maxPages; count++) {
|
|
47
|
+
signal.throwIfAborted();
|
|
48
|
+
const page = await untilAborted(readPage(after === undefined ? {} : { after }, signal), signal);
|
|
49
|
+
signal.throwIfAborted();
|
|
50
|
+
const seenThrough = collectPage(page, channel, turnId, seenIds, calls, channelCalls);
|
|
51
|
+
if (page.next === undefined) {
|
|
52
|
+
return { calls, lastSeenCallId: seenThrough ?? after, prefix: turnPrefix(channelCalls, turnId) };
|
|
53
|
+
}
|
|
54
|
+
after = page.next;
|
|
55
|
+
}
|
|
56
|
+
throw new Error("Native usage ledger exceeded its page budget");
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (timeout.signal.aborted) throw new Error("Native usage ledger read timed out", { cause: error });
|
|
59
|
+
if (position.signal?.aborted) throw new Error("Native usage ledger read cancelled", { cause: error });
|
|
60
|
+
throw error;
|
|
61
|
+
} finally {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function turnPrefix(calls: readonly ModelCallSummary[], turnId: string): readonly ModelCallSummary[] {
|
|
68
|
+
const lastOwn = calls.findLastIndex(call => call.turnId === turnId);
|
|
69
|
+
if (lastOwn >= 0) return calls.slice(0, lastOwn + 1);
|
|
70
|
+
// Harness v1 allocates positive decimal turn IDs. With no target row, stop at the first
|
|
71
|
+
// same-channel row that cannot be proved to precede the target.
|
|
72
|
+
if (!/^[1-9]\d*$/.test(turnId)) return [];
|
|
73
|
+
const target = BigInt(turnId);
|
|
74
|
+
const firstUnproven = calls.findIndex(call => !/^[1-9]\d*$/.test(call.turnId) || BigInt(call.turnId) >= target);
|
|
75
|
+
return firstUnproven < 0 ? calls : calls.slice(0, firstUnproven);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function collectPage(
|
|
79
|
+
page: LedgerPage,
|
|
80
|
+
channel: string,
|
|
81
|
+
turnId: string,
|
|
82
|
+
seenIds: Set<string>,
|
|
83
|
+
selected: ModelCallSummary[],
|
|
84
|
+
channelCalls: ModelCallSummary[],
|
|
85
|
+
): string | undefined {
|
|
86
|
+
if (!Array.isArray(page?.calls)) throw new Error("Invalid native usage ledger page");
|
|
87
|
+
const seenThrough = page.calls.at(-1)?.callId;
|
|
88
|
+
if (page.next !== undefined && (!seenThrough || page.next !== seenThrough)) {
|
|
89
|
+
throw new Error("Native usage ledger cursor did not advance to the last call");
|
|
90
|
+
}
|
|
91
|
+
for (const call of page.calls) {
|
|
92
|
+
if (typeof call?.callId !== "string" || !call.callId || seenIds.has(call.callId)) {
|
|
93
|
+
throw new Error("Native usage ledger returned an invalid or repeated call ID");
|
|
94
|
+
}
|
|
95
|
+
if (typeof call.channel !== "string" || !call.channel || typeof call.turnId !== "string" || !call.turnId) {
|
|
96
|
+
throw new Error("Native usage ledger returned a call without channel or turn ownership");
|
|
97
|
+
}
|
|
98
|
+
seenIds.add(call.callId);
|
|
99
|
+
if (call.channel !== channel) continue;
|
|
100
|
+
channelCalls.push(call);
|
|
101
|
+
if (call.turnId === turnId) selected.push(call);
|
|
102
|
+
}
|
|
103
|
+
return seenThrough;
|
|
104
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { CloseOperationInput, OpenOperation } from "../engine.ts";
|
|
2
|
+
import type { AgentSessionMeteringState, UnallocatedUsageAccrual } from "../state.ts";
|
|
3
|
+
import { sumNativeTokens, evaluateNativeRetirement } from "./retirement.ts";
|
|
4
|
+
import { UNAVAILABLE_PROVENANCE, type MeteringProvenance, type MeteringUsageResult, type NativeOperationUsage } from "../record.ts";
|
|
5
|
+
import { unpricedUsage, type AttributableUsage } from "../rating.ts";
|
|
6
|
+
import type { NativeTurnMetering } from "./source.ts";
|
|
7
|
+
|
|
8
|
+
export const nativeRouteUnavailable = "native model-call records do not identify the provider or model";
|
|
9
|
+
|
|
10
|
+
interface NativeMeasurement {
|
|
11
|
+
readonly usage: MeteringUsageResult;
|
|
12
|
+
readonly attributable: AttributableUsage | null;
|
|
13
|
+
readonly provenance: MeteringProvenance;
|
|
14
|
+
readonly evidence: NativeOperationUsage;
|
|
15
|
+
readonly applicability: null;
|
|
16
|
+
readonly ratingComplete: false;
|
|
17
|
+
readonly ratingFailureReason: string;
|
|
18
|
+
readonly accountedThrough?: string;
|
|
19
|
+
readonly partial?: boolean;
|
|
20
|
+
readonly unallocated?: readonly UnallocatedUsageAccrual[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const observedProvenance: MeteringProvenance = Object.freeze({
|
|
24
|
+
source: "native_ledger",
|
|
25
|
+
measurement: "provider_normalized",
|
|
26
|
+
routing: "unknown",
|
|
27
|
+
attribution: "partial",
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export function measureNativeOperation(open: OpenOperation, input: CloseOperationInput, state: AgentSessionMeteringState) {
|
|
31
|
+
if (open.nativeChannel === undefined) return undefined;
|
|
32
|
+
const cursor = state.nativeCursor;
|
|
33
|
+
return measureNativeTurn(open.nativeChannel, input.nativeMetering,
|
|
34
|
+
cursor?.channelKey === open.internalSessionId ? cursor?.after : undefined);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function advanceNativeCursor(state: AgentSessionMeteringState, channelKey: string | null, through?: string) {
|
|
38
|
+
return through && channelKey ? Object.freeze({ ...state, nativeCursor: { channelKey, after: through } }) : state;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Called once from operation close. A read failure becomes evidence without discarding the turn. */
|
|
42
|
+
export async function measureNativeTurn(channel: string, metering?: NativeTurnMetering, after?: string): Promise<NativeMeasurement> {
|
|
43
|
+
const identity = { channel, turnId: metering?.turnId ?? null };
|
|
44
|
+
const base = { applicability: null, ratingComplete: false, ratingFailureReason: nativeRouteUnavailable } as const;
|
|
45
|
+
const unavailable = (reason: string, evidence: NativeOperationUsage, accountedThrough?: string,
|
|
46
|
+
unallocated?: readonly UnallocatedUsageAccrual[]): NativeMeasurement => ({
|
|
47
|
+
...base, usage: { status: "usage_unavailable", reason }, attributable: null,
|
|
48
|
+
provenance: UNAVAILABLE_PROVENANCE, evidence, accountedThrough, unallocated,
|
|
49
|
+
});
|
|
50
|
+
if (!metering) {
|
|
51
|
+
const reason = "the native turn was not prepared";
|
|
52
|
+
return unavailable(reason, { ...identity, status: "unavailable", reason });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
try {
|
|
56
|
+
const read = await metering.read({ after });
|
|
57
|
+
const { calls, unmeasured, inferences } = read;
|
|
58
|
+
const terminal = metering.isTerminal?.() === true;
|
|
59
|
+
const { through, earlier, unallocated, pendingEarlier } = await evaluateNativeRetirement(metering, read, terminal);
|
|
60
|
+
const evidence: NativeOperationUsage = { ...identity, status: "observed", calls, unmeasured,
|
|
61
|
+
...(inferences.length ? { accountedAttemptIds: inferences.map(inference => inference.attemptId) } : {}),
|
|
62
|
+
...(earlier.length ? { unaccountedEarlierCalls: earlier } : {}),
|
|
63
|
+
...(pendingEarlier ? { earlierEvidencePending: true } : {}),
|
|
64
|
+
};
|
|
65
|
+
if (!inferences.length) {
|
|
66
|
+
return unavailable(calls.length ? "native model-call usage is incomplete" : "native ledger has no calls for this turn", evidence, through, unallocated);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const summed = sumNativeTokens(inferences);
|
|
70
|
+
const attributable = unpricedUsage(summed);
|
|
71
|
+
const reason = unmeasured > 0 ? "some native model-call attempts could not be measured"
|
|
72
|
+
: !terminal ? "the native turn's terminal outcome was not confirmed"
|
|
73
|
+
: pendingEarlier ? "earlier native model-call evidence is awaiting retirement"
|
|
74
|
+
: earlier.length ? "earlier native model-call evidence is recorded separately from this turn's total"
|
|
75
|
+
: undefined;
|
|
76
|
+
return {
|
|
77
|
+
...base, evidence, provenance: observedProvenance, attributable, accountedThrough: through, partial: !!reason, unallocated,
|
|
78
|
+
usage: { status: "metered", reportedCumulative: summed, attributable,
|
|
79
|
+
...(reason ? { reason } : {}) },
|
|
80
|
+
};
|
|
81
|
+
} catch (error) {
|
|
82
|
+
const reason = `native ledger unavailable: ${String(error)}`;
|
|
83
|
+
return unavailable(reason, { ...identity, status: "unavailable", reason });
|
|
84
|
+
}
|
|
85
|
+
}
|