@tangle-network/agent-app 0.45.33 → 0.45.35

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.
@@ -8,7 +8,7 @@ export { InteractionData, InteractionOutcome, InteractionRequest } from '@tangle
8
8
  import { e as ChatMentionPart, a as ChatAttachmentPart } from '../parts-BqIHMdyu.js';
9
9
  export { s as attachmentInputToPart, t as attachmentKindForMime, u as attachmentPartsFromMessageParts, x as isChatAttachmentPart, H as mentionInputToPart, I as mentionPartsFromMessageParts } from '../parts-BqIHMdyu.js';
10
10
  import { E as EvidenceEntry, g as ExceptionEntry, b as WorkProductProvenance, P as ProfileBacktestSummary, Q as QualityCheck, W as WorkProductPersistedPart, h as WorkProductStatus } from '../types-CCeYywdS.js';
11
- export { a as AgentSessionControls, A as AgentSessionControlsProps, C as ComposerMentionProp, D as DEFAULT_MENTION_EMPTY_TEXT, b as DEFAULT_MENTION_LIMIT, I as INDEX_REFRESH_AFTER_MS, M as MentionItem, c as UseFileMentionsOptions, U as UseFileMentionsResult, r as rankFileMentions, u as useFileMentions } from '../agent-session-controls-BwImzYKC.js';
11
+ export { a as AgentSessionControls, A as AgentSessionControlsProps, C as ComposerMentionProp, D as DEFAULT_EFFORT_LEVELS, b as DEFAULT_MENTION_EMPTY_TEXT, c as DEFAULT_MENTION_LIMIT, E as EFFORT_METER_SEGMENTS, d as EffortLevel, e as EffortMeter, f as EffortPicker, g as EffortPickerProps, I as INDEX_REFRESH_AFTER_MS, M as MentionItem, h as ModelPicker, i as ModelPickerProps, O as OVERLAY_SHADOW, j as UseFileMentionsOptions, U as UseFileMentionsResult, k as effortMeterFill, r as rankFileMentions, u as useFileMentions, l as usePending, m as usePopover } from '../agent-session-controls-1q1XR3j8.js';
12
12
  import { a as ChatAttachmentKind, b as ChatAttachmentInput } from '../wire-DOZ-O6hD.js';
13
13
  export { C as ChatMentionKind, e as ChatTurnFilePartInput, d as ChatTurnPartInput, c as ChatTurnRequestPayload, D as DISPATCH_MAX_MEDIA_PARTS, i as DISPATCH_MAX_PARTS, j as DISPATCH_REQUEST_MAX_BYTES, k as DISPATCH_STRUCTURAL_RESERVE_BYTES, F as FileMention, P as ProducerErrorEvent, m as ProducerNoticeEvent, n as ProducerPassthroughEvent, o as ProducerPassthroughEventType, p as ProducerReasoningEvent, q as ProducerTextEvent, r as ProducerToolCallEvent, s as ProducerToolResultEvent, t as ProducerUsageEvent, u as ProducerWireEvent, w as base64WireLen, x as buildMentionPromptBlock, y as chatTurnRequestInit, z as fileMentionsToParts, B as mediaTypeForMentionPath, E as mentionKindForPath } from '../wire-DOZ-O6hD.js';
14
14
  import { Harness } from '../harness/index.js';
@@ -1947,124 +1947,6 @@ interface RecordGridProps {
1947
1947
  */
1948
1948
  declare function RecordGrid({ columns, caption, state, empty, onCreate, onUpdate, onDelete, newRowDefaults, addLabel, locale, toolbar, loadingRowCount, className, }: RecordGridProps): react.JSX.Element;
1949
1949
 
1950
- /**
1951
- * Keyboard + pointer model for a trigger-and-popover pair, dependency-free.
1952
- * Outside-mousedown and Escape both close; Escape also returns focus to the
1953
- * trigger so keyboard users aren't dropped at the top of the document. The
1954
- * returned `triggerProps` carry the ARIA contract (`aria-haspopup`/
1955
- * `aria-expanded`); spread them onto the trigger button.
1956
- */
1957
- declare function usePopover(open: boolean, setOpen: (open: boolean) => void): {
1958
- containerRef: react.RefObject<HTMLDivElement | null>;
1959
- triggerRef: react.RefObject<HTMLButtonElement | null>;
1960
- triggerProps: {
1961
- ref: react.RefObject<HTMLButtonElement | null>;
1962
- 'aria-haspopup': true;
1963
- 'aria-expanded': boolean;
1964
- };
1965
- };
1966
- /**
1967
- * The one overlay elevation for floating surfaces — picker menus, popovers,
1968
- * drawers, modals. The theme's `shadow-overlay` utility is landing with the
1969
- * token work; until it does, this is the composer's raised-card literal kept
1970
- * in a single place so every overlay paints the same shadow and the later
1971
- * token swap is a one-line edit (`shadow-overlay` here, `shadow-raised` on
1972
- * the composer card).
1973
- * TODO(theme): swap to `shadow-overlay` once the preset ships it.
1974
- */
1975
- declare const OVERLAY_SHADOW = "shadow-[0_1px_2px_hsl(var(--foreground)/0.05),0_12px_28px_hsl(var(--foreground)/0.07)] dark:shadow-[0_1px_2px_hsl(var(--foreground)/0.14),0_12px_28px_hsl(var(--foreground)/0.22)]";
1976
- /**
1977
- * Guard an async action against double-submit. `run` ignores re-entrant calls
1978
- * while a promise is in flight and flips `pending` so the caller can disable
1979
- * the control — the fix for double-charge / double-approve on a slow network.
1980
- * Settles (success or throw) before clearing, and no-ops state updates after
1981
- * unmount.
1982
- */
1983
- declare function usePending(): {
1984
- pending: boolean;
1985
- run: (action: () => void | Promise<void>) => void;
1986
- };
1987
- interface ModelPickerProps {
1988
- value: string;
1989
- onChange: (id: string) => void;
1990
- /** Catalogue models — from `GET`ing the app's catalogue route (see
1991
- * `runtime/model-catalog`), plus any product-specific entries appended. */
1992
- models: CatalogModel[];
1993
- loading?: boolean;
1994
- /** Render a provider logo/badge; default is a generic sparkle. */
1995
- renderProviderBadge?: (provider: string) => ReactNode;
1996
- /** Section label for `featured` models. */
1997
- recommendedLabel?: string;
1998
- /** Pin a labeled section to the TOP of the list (above Recommended) for the
1999
- * models a product wants surfaced first — e.g. a tuner app's own fine-tuned
2000
- * models (`{ label: 'Your Fine-Tuned Models', match: (m) => m.provider === 'tuner' }`).
2001
- * Matching models are shown only in this section, not duplicated below. */
2002
- priorityGroup?: {
2003
- label: string;
2004
- match: (model: CatalogModel) => boolean;
2005
- };
2006
- }
2007
- /**
2008
- * Searchable model picker pill + popover: a featured/recommended section
2009
- * first, then per-provider groups in catalogue order (the server already
2010
- * sorts providers by tier).
2011
- *
2012
- * This is the CANONICAL ecosystem model picker (see "UI chrome ownership
2013
- * (picker canon)" in AGENTS.md). sandbox-ui's `dashboard/ModelPicker` is
2014
- * legacy — deprecated, frozen, removed at sandbox-ui's next major; new code
2015
- * belongs here.
2016
- */
2017
- declare function ModelPicker({ value, onChange, models, loading, renderProviderBadge, recommendedLabel, priorityGroup }: ModelPickerProps): react.JSX.Element;
2018
- /** One reasoning-budget level: the engine `id` is unchanged (the value the
2019
- * product sends to the loop); only the user-facing `label` is renamed to the
2020
- * plainer "how hard should it think" vocabulary from docs/product-surfaces.md.
2021
- * `low`→Quick, `medium`→Standard, `high`→Extended. The mapping is overridable
2022
- * via `EffortPickerProps.levels`, so a product can relabel without losing the
2023
- * ids the runtime expects. */
2024
- interface EffortLevel {
2025
- id: string;
2026
- label: string;
2027
- }
2028
- declare const DEFAULT_EFFORT_LEVELS: readonly EffortLevel[];
2029
- /** Segments the meter draws — fixed geometry so the ladder stays tabular
2030
- * across levels (and across the trigger and its menu rows). */
2031
- declare const EFFORT_METER_SEGMENTS = 4;
2032
- /**
2033
- * Filled-segment count for a level: 0 for off/none (or an id the levels list
2034
- * does not carry); otherwise the level's position among the non-off choices
2035
- * scaled onto the meter, so the ladder reads low < medium < high and the top
2036
- * level fills the whole scale. The canonical four levels land 0 / 1 / 2 / 4.
2037
- */
2038
- declare function effortMeterFill(levelId: string, levels?: readonly EffortLevel[]): number;
2039
- /**
2040
- * The thinking-strength meter: four 12px bars, filled count = level, filled
2041
- * opacity ramping 25→100% left to right (unfilled at a faint ghost). Purely
2042
- * decorative — the level name is always rendered as text beside it, so the
2043
- * meter is `aria-hidden` and adds no second accessible name.
2044
- */
2045
- declare function EffortMeter({ fill, className }: {
2046
- fill: number;
2047
- className?: string;
2048
- }): react.JSX.Element;
2049
- interface EffortPickerProps {
2050
- value: string;
2051
- onChange: (id: string) => void;
2052
- /** Selectable levels (engine id + user-facing label). Defaults to the plain
2053
- * "Thinking" vocabulary; override to relabel without changing the ids the
2054
- * runtime receives. */
2055
- levels?: readonly EffortLevel[];
2056
- /** Prefix shown before the active level on the pill — the "what is this"
2057
- * context the bare value lacked. Default "Thinking". Pass '' to hide it. */
2058
- label?: string;
2059
- }
2060
- /** Thinking-budget selector pill, styled to match {@link ModelPicker}. Show
2061
- * it only when the selected model `supportsReasoning`. "Thinking" is the
2062
- * plain-English name for what was internally called "effort".
2063
- *
2064
- * The CANONICAL ecosystem effort picker — sandbox-ui's reasoning menu (inside
2065
- * its `chat/AgentSessionControls`) is legacy and frozen. */
2066
- declare function EffortPicker({ value, onChange, levels, label }: EffortPickerProps): react.JSX.Element;
2067
-
2068
1950
  /** Describe metrics related to a chat message including model, token counts, and duration */
2069
1951
  interface ChatMessageMetrics {
2070
1952
  modelUsed?: string;
@@ -2260,4 +2142,4 @@ declare function useThinkingSeconds(active: boolean): number;
2260
2142
  */
2261
2143
  declare function ChatMessages({ messages, messageSize, chrome, models, renderMarkdown, renderExtras, durableCards, userLabel, agentLabel, loading, approval, onToolCallClick, toolRenderers, error, onRetry, renderEmpty, emptyState, header, resolveAttachmentUrl, workProductCards, }: ChatMessagesProps): react.JSX.Element;
2262
2144
 
2263
- export { type ActivityTone, type AgentActivityPage, AgentActivityPanel, type AgentActivityPanelProps, type AgentActivityRecord, type AttachmentFileResult, CatalogModel, ChatAttachmentInput, ChatAttachmentKind, ChatAttachmentPart, ChatComposer, type ChatComposerProps, type ChatEmptyDoor, ChatEmptyState, type ChatEmptyStateProps, ChatInteraction, ChatInteractionField, type ChatInteractionRestoreMode, ChatInteractionStatus, ChatMentionPart, type ChatMessageMetrics, type ChatMessageSegment, ChatMessages, type ChatMessagesProps, ChatSelectField, type ChatStreamCallbacks, type ChatStreamToolCall, type ChatStreamToolResult, type ChatToolCallInfo, type ChatUiMessage, type ComposerFile, type ComposerFilePart, type ComposerSendFailure, type ComposerSendHandler, type ComposerSendOutcome, type ComposerSendPartsHandler, type ComposerSendRejected, type ComposerSendResult, type ConsumeChatStreamResult, DEFAULT_EFFORT_LEVELS, DEFAULT_PROVENANCE_CONFIDENCE_POLICY, type DurableChatCard, DurableChatCards, type DurableChatCardsProps, type DurableInteractionAnswerSubmitterOptions, DurablePlanCard, type DurablePlanCardProps, DurablePlanClientError, type DurablePlanCurrentInput, type DurablePlanDecision, type DurablePlanDecisionClient, type DurablePlanDecisionClientOptions, type DurablePlanDecisionInput, type DurablePlanDecisionResult, type DurablePlanFollowUpReceipt, EFFORT_METER_SEGMENTS, EMPTY_RECORD_GRID_OVERLAY, type EffortLevel, EffortMeter, EffortPicker, type EffortPickerProps, EvidenceLineageTable, type EvidenceLineageTableProps, ExceptionList, type ExceptionListProps, type FetchSessionPage, type FieldValues, FlowWaterfall, type FlowWaterfallProps, HarnessGlyph, type HarnessGlyphProps, INTERACTION_SUBMIT_TIMEOUT_MESSAGE, INTERACTION_SUBMIT_TIMEOUT_MS, InteractionActionButton, type InteractionAnswerSubmission, type InteractionAnswerSubmitterOptions, InteractionAnswers, type InteractionAttemptStore, InteractionBadge, type InteractionBadgeVariant, InteractionCancelData, InteractionPlanCard, type InteractionPlanCardProps, InteractionQuestionCard, type InteractionQuestionCardProps, InteractionRequestWire, type InteractionSubmitResult, type LinkLikeComponent, type LinkLikeProps, type MentionTextSegment, MessageAttachments, type MessageAttachmentsProps, MissionActivityLane, type MissionActivityLaneProps, ModelPicker, type ModelPickerProps, OVERLAY_SHADOW, PROVENANCE_BASES, type ProposalApprovalHandlers, type ProvenanceBasis, type ProvenanceBasisMeta, type ProvenanceConfidencePolicy, type ProvenanceGap, type ProvenanceGapKind, ProvenanceLegend, type ProvenanceLegendProps, type ProvenanceRecord, type ProvenanceSource, type ProvenanceSourceStatus, ProvenanceStamp, type ProvenanceStampProps, type ProvenanceStanding, type ProvenanceStandingMeta, ProvenanceValue, type ProvenanceValueProps, ProviderLogo, type ProviderLogoProps, QualityCheckList, type QualityCheckListProps, QuestionOptionList, type QuestionOptionListProps, RecordGrid, type RecordGridBooleanColumn, type RecordGridCellChange, type RecordGridCellOutcome, type RecordGridCellSource, type RecordGridColumn, type RecordGridColumnBase, type RecordGridCreateOutcome, type RecordGridCurrencyColumn, type RecordGridDateColumn, type RecordGridDependency, type RecordGridNumberColumn, type RecordGridOverlay, type RecordGridProps, type RecordGridRow, type RecordGridRowOutcome, type RecordGridSelectColumn, type RecordGridSelectOption, type RecordGridSourceBasis, type RecordGridTextColumn, type RecordGridValue, type RecordGridWriteOutcome, type RestoreChatInteractionsOptions, ReviewQueueItem, type ReviewQueuePage, ReviewQueuePanel, type ReviewQueuePanelProps, ReviewQueueState, RunDrillIn, type RunDrillInProps, SeatPaywall, type SeatPaywallProps, type SessionActionLabels, type SessionActions, type SessionActionsOptions, type SessionBulkAction, SessionHistoryPanel, type SessionHistoryPanelProps, type SessionHistoryState, type SessionPageQuery, type SmoothRevealOptions, type StreamChatOptions, type SubmitInteractionAnswer, type ToolDetailRenderers, type ToolRunRecord, type ToolRunStep, type UseChatInteractionsOptions, type UseChatInteractionsResult, type UseComposerAttachmentsOptions, type UseComposerAttachmentsResult, type UseDurablePlanFlowOptions, type UseDurablePlanFlowResult, type UseInfiniteScrollOptions, type UseSessionHistoryOptions, type WaterfallRow, WorkProductCard, type WorkProductCardProps, __resetAttachmentFileCacheForTests, activityTone, buildAnswerData, cancelChatInteraction, consumeChatStream, createDurableInteractionAnswerSubmitter, createDurablePlanDecisionClient, createInteractionAnswerSubmitter, createMemoryInteractionAttemptStore, createSessionInteractionAttemptStore, describeProvenance, describeProvenanceSourceStatus, dispatchChatStreamLine, durableChatCardsFromParts, effortMeterFill, fieldAnswer, fieldValuesFromAnswers, formatActivityCost, formatActivityDuration, formatModelCost, formatRecordGridValue, formatSessionTimestamp, formatTokensPerSecond, hasSecretField, hydrateChatInteractions, interactionStatusLabels, interactionSubmissionSignature, interactionTerminalNotes, isLateAnswerableStatus, isRecordGridCellApplicable, lateAnswerMessage, loadAttachmentFile, loadingProvenanceSources, mergeActivityPages, mergeReviewQueuePages, nextRevealCount, parseRecordGridInput, pendingApprovalOf, projectRecordGridRows, provenanceBasisMeta, provenanceGaps, provenanceNextMove, provenanceStandingMeta, provenanceTriggerLabel, pruneRecordGridOverlay, readRecordGridCell, recordGridEditorText, recordGridFail, recordGridOk, recordGridRowLabel, resolveChatInteraction, resolveProvenanceStanding, responseErrorMessage, restoreChatInteractions, reviewQueueStateLabel, rollUpProvenanceStanding, sameRecordGridValue, segmentMentionContent, settleInteractionSubmit, standingFromConfidence, streamChatTurn, sumRecordGridColumn, terminalizePendingChatInteractions, triggerAttachmentDownload, upsertChatInteraction, useChatInteractions, useComposerAttachments, useDurablePlanFlow, useInfiniteScroll, usePending, usePopover, useSessionActions, useSessionHistory, useSmoothText, useThinkingSeconds, validateRecordGridCell, validateRecordGridRow, waterfallLayout, weakerProvenanceStanding, withRecordGridCreated, withRecordGridRemoved, withRecordGridServerRow, withRecordGridUpdate, withoutRecordGridCreated, withoutRecordGridRemoved, withoutRecordGridUpdate, workProductPartsFromMessageParts, workProductStatusLabel };
2145
+ export { type ActivityTone, type AgentActivityPage, AgentActivityPanel, type AgentActivityPanelProps, type AgentActivityRecord, type AttachmentFileResult, CatalogModel, ChatAttachmentInput, ChatAttachmentKind, ChatAttachmentPart, ChatComposer, type ChatComposerProps, type ChatEmptyDoor, ChatEmptyState, type ChatEmptyStateProps, ChatInteraction, ChatInteractionField, type ChatInteractionRestoreMode, ChatInteractionStatus, ChatMentionPart, type ChatMessageMetrics, type ChatMessageSegment, ChatMessages, type ChatMessagesProps, ChatSelectField, type ChatStreamCallbacks, type ChatStreamToolCall, type ChatStreamToolResult, type ChatToolCallInfo, type ChatUiMessage, type ComposerFile, type ComposerFilePart, type ComposerSendFailure, type ComposerSendHandler, type ComposerSendOutcome, type ComposerSendPartsHandler, type ComposerSendRejected, type ComposerSendResult, type ConsumeChatStreamResult, DEFAULT_PROVENANCE_CONFIDENCE_POLICY, type DurableChatCard, DurableChatCards, type DurableChatCardsProps, type DurableInteractionAnswerSubmitterOptions, DurablePlanCard, type DurablePlanCardProps, DurablePlanClientError, type DurablePlanCurrentInput, type DurablePlanDecision, type DurablePlanDecisionClient, type DurablePlanDecisionClientOptions, type DurablePlanDecisionInput, type DurablePlanDecisionResult, type DurablePlanFollowUpReceipt, EMPTY_RECORD_GRID_OVERLAY, EvidenceLineageTable, type EvidenceLineageTableProps, ExceptionList, type ExceptionListProps, type FetchSessionPage, type FieldValues, FlowWaterfall, type FlowWaterfallProps, HarnessGlyph, type HarnessGlyphProps, INTERACTION_SUBMIT_TIMEOUT_MESSAGE, INTERACTION_SUBMIT_TIMEOUT_MS, InteractionActionButton, type InteractionAnswerSubmission, type InteractionAnswerSubmitterOptions, InteractionAnswers, type InteractionAttemptStore, InteractionBadge, type InteractionBadgeVariant, InteractionCancelData, InteractionPlanCard, type InteractionPlanCardProps, InteractionQuestionCard, type InteractionQuestionCardProps, InteractionRequestWire, type InteractionSubmitResult, type LinkLikeComponent, type LinkLikeProps, type MentionTextSegment, MessageAttachments, type MessageAttachmentsProps, MissionActivityLane, type MissionActivityLaneProps, PROVENANCE_BASES, type ProposalApprovalHandlers, type ProvenanceBasis, type ProvenanceBasisMeta, type ProvenanceConfidencePolicy, type ProvenanceGap, type ProvenanceGapKind, ProvenanceLegend, type ProvenanceLegendProps, type ProvenanceRecord, type ProvenanceSource, type ProvenanceSourceStatus, ProvenanceStamp, type ProvenanceStampProps, type ProvenanceStanding, type ProvenanceStandingMeta, ProvenanceValue, type ProvenanceValueProps, ProviderLogo, type ProviderLogoProps, QualityCheckList, type QualityCheckListProps, QuestionOptionList, type QuestionOptionListProps, RecordGrid, type RecordGridBooleanColumn, type RecordGridCellChange, type RecordGridCellOutcome, type RecordGridCellSource, type RecordGridColumn, type RecordGridColumnBase, type RecordGridCreateOutcome, type RecordGridCurrencyColumn, type RecordGridDateColumn, type RecordGridDependency, type RecordGridNumberColumn, type RecordGridOverlay, type RecordGridProps, type RecordGridRow, type RecordGridRowOutcome, type RecordGridSelectColumn, type RecordGridSelectOption, type RecordGridSourceBasis, type RecordGridTextColumn, type RecordGridValue, type RecordGridWriteOutcome, type RestoreChatInteractionsOptions, ReviewQueueItem, type ReviewQueuePage, ReviewQueuePanel, type ReviewQueuePanelProps, ReviewQueueState, RunDrillIn, type RunDrillInProps, SeatPaywall, type SeatPaywallProps, type SessionActionLabels, type SessionActions, type SessionActionsOptions, type SessionBulkAction, SessionHistoryPanel, type SessionHistoryPanelProps, type SessionHistoryState, type SessionPageQuery, type SmoothRevealOptions, type StreamChatOptions, type SubmitInteractionAnswer, type ToolDetailRenderers, type ToolRunRecord, type ToolRunStep, type UseChatInteractionsOptions, type UseChatInteractionsResult, type UseComposerAttachmentsOptions, type UseComposerAttachmentsResult, type UseDurablePlanFlowOptions, type UseDurablePlanFlowResult, type UseInfiniteScrollOptions, type UseSessionHistoryOptions, type WaterfallRow, WorkProductCard, type WorkProductCardProps, __resetAttachmentFileCacheForTests, activityTone, buildAnswerData, cancelChatInteraction, consumeChatStream, createDurableInteractionAnswerSubmitter, createDurablePlanDecisionClient, createInteractionAnswerSubmitter, createMemoryInteractionAttemptStore, createSessionInteractionAttemptStore, describeProvenance, describeProvenanceSourceStatus, dispatchChatStreamLine, durableChatCardsFromParts, fieldAnswer, fieldValuesFromAnswers, formatActivityCost, formatActivityDuration, formatModelCost, formatRecordGridValue, formatSessionTimestamp, formatTokensPerSecond, hasSecretField, hydrateChatInteractions, interactionStatusLabels, interactionSubmissionSignature, interactionTerminalNotes, isLateAnswerableStatus, isRecordGridCellApplicable, lateAnswerMessage, loadAttachmentFile, loadingProvenanceSources, mergeActivityPages, mergeReviewQueuePages, nextRevealCount, parseRecordGridInput, pendingApprovalOf, projectRecordGridRows, provenanceBasisMeta, provenanceGaps, provenanceNextMove, provenanceStandingMeta, provenanceTriggerLabel, pruneRecordGridOverlay, readRecordGridCell, recordGridEditorText, recordGridFail, recordGridOk, recordGridRowLabel, resolveChatInteraction, resolveProvenanceStanding, responseErrorMessage, restoreChatInteractions, reviewQueueStateLabel, rollUpProvenanceStanding, sameRecordGridValue, segmentMentionContent, settleInteractionSubmit, standingFromConfidence, streamChatTurn, sumRecordGridColumn, terminalizePendingChatInteractions, triggerAttachmentDownload, upsertChatInteraction, useChatInteractions, useComposerAttachments, useDurablePlanFlow, useInfiniteScroll, useSessionActions, useSessionHistory, useSmoothText, useThinkingSeconds, validateRecordGridCell, validateRecordGridRow, waterfallLayout, weakerProvenanceStanding, withRecordGridCreated, withRecordGridRemoved, withRecordGridServerRow, withRecordGridUpdate, withoutRecordGridCreated, withoutRecordGridRemoved, withoutRecordGridUpdate, workProductPartsFromMessageParts, workProductStatusLabel };
@@ -110,7 +110,7 @@ import {
110
110
  withoutRecordGridCreated,
111
111
  withoutRecordGridRemoved,
112
112
  withoutRecordGridUpdate
113
- } from "../chunk-XHD4Y54K.js";
113
+ } from "../chunk-AIHKKLKY.js";
114
114
  import "../chunk-FBVLEGEG.js";
115
115
  import {
116
116
  EvidenceLineageTable,
@@ -141,7 +141,7 @@ import {
141
141
  useComposerAttachments,
142
142
  usePending,
143
143
  usePopover
144
- } from "../chunk-SFSR3CAH.js";
144
+ } from "../chunk-MIZMWCKW.js";
145
145
  import {
146
146
  tabTerminalConnectionId,
147
147
  useSandboxTerminalConnection
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.45.33",
3
+ "version": "0.45.35",
4
4
  "packageManager": "pnpm@11.17.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1,129 +0,0 @@
1
- import * as react from 'react';
2
- import { ReactNode } from 'react';
3
- import { F as FileMention } from './wire-DOZ-O6hD.js';
4
- import { Harness } from './harness/index.js';
5
- import { CatalogModel } from './catalog/index.js';
6
-
7
- /**
8
- * `useFileMentions` — the glue a host passes straight into `AgentComposer`'s
9
- * `mention` prop (`@tangle-network/sandbox-ui#184`) to wire up `@`-file
10
- * mentions against `createSandboxFileIndexRoute` (`/chat-routes`).
11
- *
12
- * Fetches the index once per session from `indexUrl`, refreshes it in the
13
- * background whenever the popover opens (a `fetchItems` call) if the cached
14
- * copy has aged past `refreshAfterMs`, and answers every keystroke from an
15
- * in-memory fuzzy filter — no per-keystroke network round trip. The returned
16
- * `refresh()` lets a caller force a re-fetch immediately instead of waiting
17
- * on `refreshAfterMs` — e.g. right after the agent creates a file mid-session.
18
- *
19
- * `MentionItem`/the `mention` prop shape mirror the FROZEN contract from
20
- * sandbox-ui#184 structurally (no import: `/web-react` stays dependency-free
21
- * beyond React, and `@tangle-network/sandbox-ui` is an optional peer).
22
- */
23
-
24
- /** Mirrors sandbox-ui#184's `MentionItem` — the atomic pill's payload. For a
25
- * file mention, `id` is the workspace-relative path (the pill's stable
26
- * identity and the `@<id>` serialization sandbox-ui uses to round-trip
27
- * `value`), `label` is the display name, and `detail` carries the full path
28
- * for the popover row's secondary line. */
29
- interface MentionItem {
30
- id: string;
31
- label: string;
32
- detail?: string;
33
- kind?: string;
34
- }
35
- /** Mirrors sandbox-ui#184's `AgentComposerProps['mention']` shape — plug the
36
- * hook's `mention` return value straight into that prop. */
37
- interface ComposerMentionProp {
38
- trigger?: string;
39
- fetchItems(query: string): Promise<MentionItem[]>;
40
- onMentionsChange?(mentions: MentionItem[]): void;
41
- renderItem?(item: MentionItem): ReactNode;
42
- emptyText?: string;
43
- }
44
- /**
45
- * Ranks `files` against `query` (case-insensitive), capped to `limit`:
46
- * name-prefix matches first, then name-substring, then path-substring.
47
- * Within a tier, shorter names sort first (the more specific match), then
48
- * alphabetically by path for a stable order. An empty query returns the
49
- * first `limit` entries unranked — the popover's default list before typing.
50
- * Pure and dependency-free (no fuzzy-match library) so it's cheap enough to
51
- * re-run on every keystroke against a 10k-entry index.
52
- */
53
- declare function rankFileMentions(files: readonly FileMention[], query: string, limit: number): FileMention[];
54
- /** Max popover results per query — enough to show a useful spread of matches
55
- * without pushing the fuzzy-filtered list past what a popover can usefully
56
- * render in one screen. */
57
- declare const DEFAULT_MENTION_LIMIT = 20;
58
- /** How long a `ready` index is served before a background refetch — long
59
- * enough that a full session's worth of popover opens don't repeatedly hit
60
- * the index endpoint, short enough that a stale listing doesn't linger too
61
- * far past workspace file changes. Callers who need the index current right
62
- * now (e.g. just after the agent creates a file) call `refresh()` instead of
63
- * waiting on this window. */
64
- declare const INDEX_REFRESH_AFTER_MS: number;
65
- /** Popover empty-state copy for a `ready` index whose query matched nothing.
66
- * Loading/warming/error states have their own copy — see `emptyTextFor`. */
67
- declare const DEFAULT_MENTION_EMPTY_TEXT = "No matching files";
68
- /** Define options for configuring file mention fetching, caching, and display behavior */
69
- interface UseFileMentionsOptions {
70
- /** GET endpoint returning `FileIndexResponse` (a `createSandboxFileIndexRoute`). */
71
- indexUrl: string;
72
- /** Max popover results per query. Default {@link DEFAULT_MENTION_LIMIT}. */
73
- limit?: number;
74
- /** How long a `ready` index is served without a background refetch.
75
- * Default {@link INDEX_REFRESH_AFTER_MS}. */
76
- refreshAfterMs?: number;
77
- /** `fetch` override for tests / non-global-fetch hosts. Default `fetch`. */
78
- fetchImpl?: typeof fetch;
79
- /** Text shown in the popover's empty state once the index is loaded and
80
- * the query matched nothing. Default {@link DEFAULT_MENTION_EMPTY_TEXT}. */
81
- emptyText?: string;
82
- }
83
- /** Provide properties and methods to manage and refresh file mentions in a composer interface */
84
- interface UseFileMentionsResult {
85
- /** Spread straight into `AgentComposer`'s `mention` prop. */
86
- mention: ComposerMentionProp;
87
- /** The files currently referenced by mentions in the composer's value —
88
- * the send-body list (map through `fileMentionsToParts`). */
89
- mentions: FileMention[];
90
- /** Drop all currently-referenced mentions (e.g. after a successful send). */
91
- clearMentions: () => void;
92
- /** Force a re-fetch of the index right now, ignoring `refreshAfterMs` — for
93
- * example right after the agent creates a file mid-session, so the next
94
- * popover open sees it. Dedupes against an already-in-flight load rather
95
- * than firing a second request. */
96
- refresh: () => Promise<void>;
97
- }
98
- /** Resolve and manage file mention data with configurable fetching and state handling */
99
- declare function useFileMentions(options: UseFileMentionsOptions): UseFileMentionsResult;
100
-
101
- interface AgentSessionControlsProps {
102
- /** Catalog models — canonical provider-prefixed ids. */
103
- models: CatalogModel[];
104
- modelsLoading?: boolean;
105
- /** Selected canonical model id. */
106
- model: string;
107
- onModelChange(modelId: string): void;
108
- /** Current harness; harness↔model coherence is enforced on every change. */
109
- harness: Harness;
110
- onHarnessChange(harness: Harness): void;
111
- /** Harnesses to offer; defaults to the labeled set. */
112
- availableHarnesses?: ReadonlyArray<Harness>;
113
- /** Reasoning-effort value + setter. Shown only when the selected model
114
- * `supportsReasoning`, matching `EffortPicker`'s guidance. */
115
- effort: string;
116
- onEffortChange(effort: string): void;
117
- /**
118
- * `inline` (default): model, harness, effort side by side — the prior
119
- * behavior. `compact`: model inline, harness + effort behind a gear popover.
120
- */
121
- layout?: 'inline' | 'compact';
122
- /** Hide the harness control entirely (single-harness products). */
123
- showHarness?: boolean;
124
- renderProviderBadge?: (provider: string) => ReactNode;
125
- className?: string;
126
- }
127
- declare function AgentSessionControls(props: AgentSessionControlsProps): react.JSX.Element;
128
-
129
- export { type AgentSessionControlsProps as A, type ComposerMentionProp as C, DEFAULT_MENTION_EMPTY_TEXT as D, INDEX_REFRESH_AFTER_MS as I, type MentionItem as M, type UseFileMentionsResult as U, AgentSessionControls as a, DEFAULT_MENTION_LIMIT as b, type UseFileMentionsOptions as c, rankFileMentions as r, useFileMentions as u };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/spend/types.ts","../src/spend/ownership.ts","../src/spend/ceiling.ts","../src/spend/reference.ts","../src/spend/reconcile.ts","../src/spend/report.ts"],"sourcesContent":["/**\n * The vocabulary of consumer-side spend verification.\n *\n * Kept in its own module with ZERO imports so a product can type its storage\n * rows and its reconciliation config without pulling in `node:fs` through the\n * CLI half.\n *\n * The model in one paragraph: the platform's ledger is authoritative about what\n * was CHARGED. A product knows something the ledger does not — what it ASKED\n * for. Recording that second view, and diffing it against the first, is what\n * turns a platform billing defect from silent money into an alert. Nothing here\n * lets a product self-certify a charge away; the output is a discrepancy a human\n * disputes.\n */\n\n// ── the product's own view of a box's life ────────────────────────────────────\n\n/**\n * One box, as the PRODUCT understands it. Folded, not an append-only log: a\n * product runs one row per sandbox, and every field below is derived by a\n * monotonic fold (see `foldSpendBoxRecord`) so two concurrent writers cannot\n * produce a wrong answer, only a stale one.\n *\n * Timestamps are epoch ms throughout, matching the platform's own\n * `sandbox_meta.last_started_at`.\n */\nexport interface SpendBoxRecord {\n /** The platform's sandbox id — the join key to every settlement row. */\n readonly sandboxId: string\n /** The product's own tenancy unit, which the platform does not model. */\n readonly workspaceId: string\n /** First moment the product knew this box existed. */\n readonly createdAt: number\n /**\n * The idle timeout the product ASKED the platform for, seconds. This is the\n * width of the grace window between the last thing the product saw and the\n * moment the platform should have stopped billing.\n */\n readonly idleTimeoutSeconds: number\n /**\n * The maximum lifetime the product asked for, seconds, when it asked for one.\n * This is the strongest bound a product holds: the platform destroys the box\n * at `createdAt + maxLifetimeSeconds` regardless of what the product observed,\n * so it caps the ceiling even when nothing else can (see `computeExpectedCeiling`).\n */\n readonly maxLifetimeSeconds: number | null\n /** Latest moment the product OBSERVED the box doing work. */\n readonly lastActivityAt: number\n /**\n * Detached runs dispatched but never observed to finish, by run id.\n *\n * Non-empty means the product genuinely cannot bound this box from its own\n * observations: it handed the platform work and disconnected. The ceiling\n * degrades accordingly rather than pretending to a tightness it did not earn.\n */\n readonly openDetachedRunIds: readonly string[]\n /** When the product knows the box stopped. Cleared by later activity. */\n readonly stoppedAt: number | null\n /** When the product knows the box was deleted. Set once — a deleted id never returns. */\n readonly deletedAt: number | null\n /** Opaque product-column values, written verbatim and never read here. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * A fold step. Every field states its own merge rule, so a SQL implementation\n * can apply it in one statement and reach the same record an in-memory\n * read-modify-write reaches.\n */\nexport interface SpendBoxPatch {\n /** Advance `lastActivityAt` to the max of stored and this. Never moves backward. */\n readonly observedActivityAt?: number\n /** Add a run id to `openDetachedRunIds` (set semantics — re-adding is a no-op). */\n readonly openDetachedRunAdd?: string\n /** Remove a run id from `openDetachedRunIds`. Removing an absent id is a no-op. */\n readonly openDetachedRunRemove?: string\n /**\n * Latest-wins. Activity observed AFTER a recorded stop clears it: a box that\n * worked after we thought it stopped is running again, and a stale stop would\n * make the ceiling too tight.\n */\n readonly stoppedAt?: number\n /** Set-once. A later delete observation does not move the first one. */\n readonly deletedAt?: number\n}\n\n// ── what bounds a box's billable time ─────────────────────────────────────────\n\n/** Which fact bounds a box's billable time, weakest last. */\nexport type CeilingBasis =\n /** The product observed deletion. Billing cannot run past a box that is gone. */\n | 'deleted'\n /** The product observed a stop. Billing should have closed there. */\n | 'stopped'\n /** No stop seen, but the platform destroys the box at its max lifetime. */\n | 'max-lifetime'\n /** No stop seen; the platform's idle timer is what should have closed billing. */\n | 'idle-timeout'\n /**\n * An unfinished detached run and no max lifetime — the product cannot bound\n * this box at all, so the ceiling degrades to the reconciliation instant.\n * A finding on this basis is weak evidence and says so.\n */\n | 'open-detached-run'\n\n/** The upper bound on one box's billable duration, and what earned it. */\nexport interface ExpectedCeiling {\n readonly sandboxId: string\n readonly basis: CeilingBasis\n /** The latest instant this box could still have been billable, epoch ms. */\n readonly horizonAt: number\n /** `horizonAt - createdAt + toleranceMs`. The upper bound on billable ms. */\n readonly ceilingMs: number\n readonly toleranceMs: number\n /**\n * False when the basis is `open-detached-run` — the ceiling then rests on the\n * reconciliation instant rather than on anything the product observed, so an\n * overage means the platform billed outside the box's own lifetime, not merely\n * longer than expected.\n */\n readonly bounded: boolean\n}\n\n// ── what the platform actually emitted ────────────────────────────────────────\n\n/**\n * One settled ledger row, in the shape the platform's `credit_transactions`\n * table stores it. The product supplies these through its own fetch (the\n * platform's credit-history API, an export, a mirror) — this package never\n * reaches for them, because the ledger is the counterparty's record and reading\n * it is the product's authenticated business.\n *\n * The rows a product can fetch are scoped to the BILLING OWNER, not to the\n * product: `product: 'sandbox'` is the platform's service taxonomy and every\n * consumer app's compute wears it. So a wallet running two of our products\n * returns both products' settlements, and telling them apart is\n * {@link SpendOwnershipRule}'s job.\n */\nexport interface SettlementRow {\n /** The ledger row id, for the dispute. */\n readonly id: string\n /**\n * `sandbox:<kind>:<sandboxId>:<intervalStartMs>` — the platform's idempotency\n * key, and the only place the billed interval's START is recorded.\n */\n readonly referenceId: string | null\n /**\n * Signed nanodollars, exactly as the ledger stores it: negative is a charge,\n * positive is a credit or refund.\n */\n readonly amountNanoUsd: number\n /** `compute` | `refund` | `inference` | … */\n readonly type: string\n /** `sandbox` | `router` | … */\n readonly product: string | null\n /** `sandbox:<sandboxId>` — the platform's aggregation unit. */\n readonly groupKey: string | null\n /** Settlement instant, epoch ms. The product normalizes the stored text. */\n readonly createdAt: number\n readonly description: string | null\n /** Provider at-cost basis, unsigned nanodollars. Null when unattributed. */\n readonly costBasisNanoUsd: number | null\n /**\n * The billed duration, when the product's ledger view exposes it directly.\n * Null is the common case: the platform does not store duration on the row.\n */\n readonly billedMs: number | null\n /**\n * The platform API key the charge was triggered by — `credit_transactions.key_id`,\n * stamped from the box's own creation metadata at settlement time and exposed\n * by `/v1/billing/transactions` (which also filters on it).\n *\n * This is the ONLY field on a settlement row that can be attributed back to a\n * PRODUCT rather than to a wallet or to the platform's service taxonomy, which\n * is why {@link SpendOwnershipRule}'s shipped constructor is built on it. The\n * sandbox id cannot do the job: the platform mints it as `sandbox-<12 hex>`\n * from a hash of (owner, idempotency key), so a product's own box naming never\n * reaches the ledger row.\n *\n * Optional, and `null` is a real answer: the platform leaves it null on legacy\n * rows and an export may not carry the column at all. A missing key is\n * `undecidable`, never `foreign` — see {@link SpendOwnershipVerdict}.\n */\n readonly keyId?: string | null\n}\n\n// ── whose box is this? ────────────────────────────────────────────────────────\n\n/**\n * What one settlement is attributable to, from inside ONE product.\n *\n * The distinction this type exists for: a sibling product's box and a charge\n * that is not ours at all look identical from inside a single product, because\n * both arrive as a settlement naming a sandbox this product's expectation ledger\n * has never heard of. Dropping both loses the check's whole purpose; reporting\n * both makes it noise. Only a platform-stamped attribution field separates them.\n */\nexport type SpendOwnershipVerdict =\n /** Attributable to THIS product. An unrecorded one is a phantom-charge candidate. */\n | 'mine'\n /** Attributable to a DIFFERENT product on the same wallet. Reported, never a finding. */\n | 'foreign'\n /**\n * The row carries nothing that decides it. Counted as `mine` — FAIL CLOSED.\n * An unattributable charge on a shared wallet is precisely the shape of the\n * thing this module exists to catch, so the ambiguous case costs a human five\n * minutes rather than costing the product the detection.\n */\n | 'undecidable'\n\n/** One settlement, presented to an ownership rule. */\nexport interface SpendOwnershipCandidate {\n readonly row: SettlementRow\n /** The sandbox the row is attributable to, or null for a row naming none. */\n readonly sandboxId: string | null\n}\n\n/**\n * The product's declaration of which settlements are its own.\n *\n * The one hard constraint on `decide`: it must answer from PROPERTIES OF THE\n * ROW. A rule that answers by looking the sandbox up in the product's own\n * expectation ledger deletes `unknown-box` entirely — every unrecorded box would\n * be `foreign` by construction, and \"we were billed for a box we never asked\n * for\" would become unrepresentable. The ledger already decides recorded-ness;\n * this decides ATTRIBUTION, and the two must stay independent.\n *\n * `decide` must not throw. If it does, the throw propagates and the whole pass\n * fails — a reconciliation whose ownership rule is broken has no verdict worth\n * printing, and swallowing it would turn a broken rule into a clean bill.\n */\nexport interface SpendOwnershipRule {\n /** Named in the report and on every finding, so a reader knows what was excluded. */\n readonly label: string\n decide(candidate: SpendOwnershipCandidate): SpendOwnershipVerdict\n}\n\n/**\n * What this pass scoped itself to — present on every report, including a clean\n * one, because \"nothing fired\" and \"nothing was looked at\" are different\n * answers and a report that cannot tell them apart is the failure this closes.\n */\nexport interface SpendOwnershipSummary {\n /**\n * False when the caller declared no rule. The pass then treats every box as\n * its own — today's behaviour, which over-reports rather than under-reports —\n * and every `unknown-box` finding says on its face that a sibling product's\n * box is indistinguishable from a charge that is not ours.\n */\n readonly declared: boolean\n /** The rule's label, or null when none was declared. */\n readonly label: string | null\n /** Boxes this pass treated as this product's, and what they were charged. */\n readonly ownedBoxes: number\n readonly ownedNanoUsd: number\n /**\n * Of those, the boxes no rule could decide. Counted as owned (fail-closed) and\n * reported separately so a product can see how much of its own verdict rests\n * on rows that carried no attribution.\n */\n readonly undecidableBoxes: number\n /** Boxes attributed to another product on the same wallet. Never findings. */\n readonly foreignBoxes: number\n readonly foreignNanoUsd: number\n /**\n * Their ids, in full — an exclusion a reader cannot audit is an exclusion\n * they have to trust, and this module's whole posture is that nothing about\n * money is taken on trust.\n */\n readonly foreignSandboxIds: readonly string[]\n}\n\n/** The parts of a settlement reference id, once parsed. */\nexport interface SettlementReference {\n /** `stop` | `compute` | `egress` | `gpu-lease` | anything the platform adds. */\n readonly kind: string\n /** For compute kinds, the sandbox id. For `gpu-lease`, the lease id. */\n readonly resourceId: string\n /** The interval's start, epoch ms. Null for kinds that carry no interval. */\n readonly intervalStartMs: number | null\n}\n\n/** How a settled duration was arrived at — every duration finding carries one. */\nexport type BilledDurationBasis =\n /** The ledger row carried the duration. Exact. */\n | 'reported'\n /** `amount ÷ the product's stated hourly rate`. Exact when the rate is right. */\n | 'rate'\n /**\n * `settledAt - intervalStart`. An UPPER bound, not the billed duration: a\n * correct settlement posted late by the platform's durable settlement queue\n * reads longer here than it billed. Findings on this basis say so.\n */\n | 'reference-span'\n /** No basis available — duration rules are skipped for this row. */\n | 'unknown'\n\n// ── findings ──────────────────────────────────────────────────────────────────\n\n/** The checks this reconciler runs. Each is individually skippable, by name. */\nexport type SpendCheckId =\n /** A settlement against a box the product has no record of ever asking for. */\n | 'unknown-box'\n /** A settled duration longer than the product's own upper bound allows. */\n | 'over-ceiling'\n /** A spend window far above the trailing median — the burst shape of a defect. */\n | 'velocity'\n /** The balance the product observes has gone below its floor. */\n | 'negative-balance'\n\nexport const SPEND_CHECKS: readonly SpendCheckId[] = [\n 'unknown-box',\n 'over-ceiling',\n 'velocity',\n 'negative-balance',\n]\n\n/**\n * One discrepancy, with every number the rule compared.\n *\n * Nullable fields are per-check and deliberately present-but-null rather than\n * absent: a reader scanning a JSON dump can tell \"this rule does not measure\n * that\" from \"that measurement is missing\".\n */\nexport interface SpendFinding {\n readonly check: SpendCheckId\n /** What is wrong, in one sentence, with the numbers in it. */\n readonly message: string\n /** What to do about it. A finding without a remedy is a complaint. */\n readonly remedy: string\n readonly sandboxId: string | null\n readonly workspaceId: string | null\n /** The ledger rows that evidence this finding — the dispute's exhibit list. */\n readonly referenceIds: readonly string[]\n /** Nanodollars this finding puts in question, unsigned. */\n readonly settledNanoUsd: number\n /** `over-ceiling` — the duration actually settled, and how that was derived. */\n readonly settledMs: number | null\n readonly durationBasis: BilledDurationBasis | null\n /** `over-ceiling` — the bound it broke, and what earned that bound. */\n readonly ceilingMs: number | null\n readonly overageMs: number | null\n readonly ceilingBasis: CeilingBasis | null\n /** `velocity` — the window, its trailing median, and the ratio between them. */\n readonly windowNanoUsd: number | null\n readonly trailingMedianNanoUsd: number | null\n readonly velocityRatio: number | null\n readonly windowStartAt: number | null\n /** `negative-balance` — the observed balance and the floor it broke. */\n readonly balanceNanoUsd: number | null\n readonly balanceFloorNanoUsd: number | null\n}\n\n/** What one reconciliation pass concluded. */\nexport interface SpendReport {\n /** True when nothing fired. `ok === findings.length === 0`. */\n readonly ok: boolean\n readonly findings: readonly SpendFinding[]\n readonly checksRun: readonly SpendCheckId[]\n /** Rows the pass read, including the ones no rule looked at. */\n readonly rowsExamined: number\n /** Distinct boxes those rows settled against. */\n readonly boxesExamined: number\n /** Total charged across every examined row, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** Total credited back across every examined row, unsigned nanodollars. */\n readonly creditedNanoUsd: number\n /** What this pass claimed as its own, and what it excluded as another product's. */\n readonly ownership: SpendOwnershipSummary\n /** The instant the pass treated as \"now\". */\n readonly asOf: number\n}\n","import type {\n SettlementRow,\n SpendOwnershipRule,\n SpendOwnershipVerdict,\n} from './types'\n\n/**\n * Which settlements belong to the product running the reconciliation.\n *\n * ## The problem this module is the answer to\n *\n * A product fetches its settled rows from `/v1/billing/transactions`, scoped to\n * the BILLING OWNER — the wallet whose key paid. `product: 'sandbox'` narrows\n * that to compute, but `sandbox` is the PLATFORM's service taxonomy: every\n * consumer app's box compute wears it. So a Tangle account running two of our\n * products hands each product's reconciliation the other product's boxes, and\n * `unknown-box` — correctly, by its own rule — reports one finding per sibling\n * box. Two products on one wallet make each other's spend check useless.\n *\n * ## Why the obvious fix is the wrong fix\n *\n * The obvious fix is to reconcile only the boxes already in the product's\n * expectation ledger. That removes the false findings and removes the check:\n * `unknown-box` exists to catch \"we were billed for a box we never asked for\",\n * which is the 2026-08-05 incident's day-one signature and the ONLY thing a\n * product with no lifecycle bookkeeping can catch at all. Filtering to the\n * ledger makes a phantom charge unrepresentable — the ledger's own contents\n * would define the answer.\n *\n * So the residue — settlements against boxes with no ledger record — has to be\n * SPLIT, not dropped. A sibling's box and a phantom charge are indistinguishable\n * unless something outside the product's own bookkeeping tells them apart.\n *\n * ## What can tell them apart\n *\n * Exactly one field on a settlement row, and it is not the sandbox id. The\n * platform mints that id as `sandbox-<12 hex>` — a hash of (owner, idempotency\n * key) — so a product's own box naming never reaches the ledger row, and the\n * charge's `description` carries only the resource spec. What does survive is\n * `credit_transactions.key_id`: the platform API key the box was created under,\n * stamped from the box's own creation metadata at settlement and filterable on\n * the transactions endpoint. Each product deploys with its own key, so the key\n * is the product's billing identity as the PLATFORM recorded it — not as the\n * product asserts it after the fact.\n *\n * That asymmetry is what makes the split safe. A product cannot widen its own\n * claim by claiming; it can only recognise a stamp the platform already wrote.\n *\n * ## The three rules that keep the detection intact\n *\n * 1. **A recorded box is never excluded.** Ownership is consulted only for\n * boxes with no ledger record. A rule that is wrong or over-narrow therefore\n * cannot hide an `over-ceiling` finding on a box the product recorded — the\n * incident's own 23 findings survive any rule at all.\n * 2. **Undecidable fails closed.** A row with no key attribution is `mine`, so\n * an unattributable charge on a shared wallet is reported. Silence is never\n * the answer to \"I don't know.\"\n * 3. **A box is claimed if ANY of its rows claims it.** The fold is\n * `mine > undecidable > foreign`, which is the module's standing asymmetry:\n * every derivation error pushes toward a false alarm, never toward a missed\n * charge.\n */\n\n/**\n * Claim every settlement the platform stamped with one of these API keys.\n *\n * The shipped rule, because it is the only one built on a field the PLATFORM\n * writes. Give each product its own platform key and this separates them\n * exactly; give two products the same key and no consumer-side rule can tell\n * them apart, because after settlement there is nothing left that differs — the\n * fix then is a second key, not a cleverer predicate.\n *\n * A row with no `keyId` (a legacy row, or an export that drops the column) is\n * `undecidable`, never `foreign`: the absence of an attribution is not evidence\n * that the charge is someone else's.\n *\n * @param keyIds The product's own platform API key ids. Must be non-empty — a\n * rule that owns nothing would classify every settlement as another product's\n * and report a clean bill for an account nobody is checking.\n */\nexport function ownedByBillingKeys(keyIds: readonly string[]): SpendOwnershipRule {\n const owned = new Set(keyIds.map((id) => id.trim()).filter(Boolean))\n if (owned.size === 0) {\n throw new Error(\n 'ownedByBillingKeys needs at least one key id: a rule that owns no key classifies every ' +\n 'settlement as another product\\'s and reports a clean bill for an unchecked account.',\n )\n }\n const label = `billing key ${[...owned].join(', ')}`\n return {\n label,\n decide({ row }) {\n const keyId = row.keyId?.trim()\n if (!keyId) return 'undecidable'\n return owned.has(keyId) ? 'mine' : 'foreign'\n },\n }\n}\n\n/**\n * One box's verdict, folded over every row that settled against it.\n *\n * `mine` wins over `undecidable`, which wins over `foreign`: it takes one row\n * attributable to this product to make the box this product's problem, and one\n * unattributable row to stop the box being excluded. Both directions push\n * toward reporting, which is the only direction that cannot lose money.\n *\n * Exported because a product auditing its own scoping wants the same answer the\n * reconciler reached, not a re-derivation of it.\n */\nexport function decideBoxOwnership(\n rule: SpendOwnershipRule,\n sandboxId: string,\n rows: readonly SettlementRow[],\n): SpendOwnershipVerdict {\n let verdict: SpendOwnershipVerdict = 'foreign'\n for (const row of rows) {\n const rowVerdict = rule.decide({ row, sandboxId })\n if (rowVerdict === 'mine') return 'mine'\n if (rowVerdict === 'undecidable') verdict = 'undecidable'\n }\n return verdict\n}\n","import type { CeilingBasis, ExpectedCeiling, SpendBoxRecord } from './types'\n\n/**\n * Slack allowed between the product's bound and what the platform settled,\n * before an overage is called a discrepancy. 15 minutes.\n *\n * Not a guess: it is the platform's OWN staleness threshold for compute\n * settlement. Its runbook clears an incident when\n * `/health computeSettlement.oldestAgeSeconds` is \"back under 900\" — so 900 s is\n * the age the platform itself treats as normal settlement lag, and anything\n * inside it is drift the platform has already declared acceptable. Below that a\n * product would alert on the platform's ordinary queue behaviour; far above it\n * the tolerance starts eating the signal, because the idle window it must stay\n * well under is 3600 s in every shipped product.\n *\n * It is a caller parameter because a product that asks for a shorter idle\n * timeout must shrink this with it.\n */\nexport const DEFAULT_CEILING_TOLERANCE_MS = 900_000\n\nexport interface ComputeExpectedCeilingOptions {\n /** The instant the reconciliation treats as \"now\", epoch ms. */\n readonly asOf: number\n /** Slack before an overage counts. Default {@link DEFAULT_CEILING_TOLERANCE_MS}. */\n readonly toleranceMs?: number\n}\n\n/**\n * The upper bound on how long one box could honestly have been billable.\n *\n * The whole design constraint is that this must stay an UPPER bound under\n * everything the product cannot see. Three such blind spots exist, and they\n * pull in different directions:\n *\n * - **Platform-side suspends.** The platform can park a box the product never\n * hears about. That only ever REDUCES real billable time, so an upper bound\n * is unaffected and nothing here widens for it.\n * - **Detached runs.** The product dispatches work and disconnects. The box\n * keeps working — and billing — after the last activity the product saw, so\n * `lastActivityAt` understates the truth. An unfinished detached run\n * therefore abandons the activity-based bound entirely rather than reporting\n * a bound it cannot support.\n * - **Reconnects.** A browser or worker re-attaches and work resumes. This\n * needs no special case: a reconnect is recorded as activity, the fold takes\n * the max, and the horizon moves out on its own.\n *\n * The bound that rescues the detached case is `maxLifetimeSeconds`. The platform\n * destroys the box at `createdAt + maxLifetimeSeconds` no matter what anyone\n * observed, so a product that asks for one holds a hard bound that survives\n * every blind spot above. Both shipped products ask for 86 400 s, which is why\n * the incident — 124 to 268 hours settled against boxes with a 24-hour\n * lifetime — is detectable with no lifecycle bookkeeping at all.\n */\nexport function computeExpectedCeiling(\n record: SpendBoxRecord,\n options: ComputeExpectedCeilingOptions,\n): ExpectedCeiling {\n const toleranceMs = options.toleranceMs ?? DEFAULT_CEILING_TOLERANCE_MS\n const { asOf } = options\n\n let basis: CeilingBasis\n let horizonAt: number\n\n if (record.deletedAt !== null) {\n basis = 'deleted'\n horizonAt = record.deletedAt\n } else if (record.stoppedAt !== null) {\n basis = 'stopped'\n horizonAt = record.stoppedAt\n } else if (record.openDetachedRunIds.length > 0) {\n // Nothing the product observed bounds this box. Fall back to the\n // reconciliation instant, and say so through `bounded: false`.\n basis = 'open-detached-run'\n horizonAt = asOf\n } else {\n basis = 'idle-timeout'\n horizonAt = record.lastActivityAt + record.idleTimeoutSeconds * 1000\n }\n\n // The hard platform bound wins whenever it is tighter — including over an\n // unfinished detached run, which is what turns an unbounded box back into a\n // bounded one.\n if (record.maxLifetimeSeconds !== null) {\n const lifetimeHorizon = record.createdAt + record.maxLifetimeSeconds * 1000\n if (lifetimeHorizon < horizonAt) {\n basis = 'max-lifetime'\n horizonAt = lifetimeHorizon\n }\n }\n\n // Time that has not elapsed cannot have been billed, so an idle window\n // reaching into the future does not widen the bound. This only ever tightens\n // the ceiling, so it cannot mask a charge.\n if (horizonAt > asOf) horizonAt = asOf\n // A horizon before creation would produce a negative ceiling; a box is at\n // minimum billable for the instant it existed.\n if (horizonAt < record.createdAt) horizonAt = record.createdAt\n\n return {\n sandboxId: record.sandboxId,\n basis,\n horizonAt,\n ceilingMs: horizonAt - record.createdAt + toleranceMs,\n toleranceMs,\n bounded: basis !== 'open-detached-run',\n }\n}\n","import type { SettlementReference, SettlementRow } from './types'\n\n/**\n * Parse the platform's settlement idempotency key.\n *\n * The platform mints it as `sandbox:<kind>:<resourceId>:<intervalStart>`\n * (`d1-usage-service.ts`), where `intervalStart` is the interval cursor in epoch\n * ms — the SAME `last_started_at` the settlement subtracts from to get its\n * billed duration. That makes this string the only place a consumer can read the\n * billed interval's start, because the ledger row itself stores no duration.\n *\n * Kinds seen in production: `stop` (an interval closing), `compute` (a heartbeat\n * claim), `egress`, `gpu-lease`. `stop` deliberately covers both a settle and a\n * late stop racing over the same claim, so the two derive one reference id and\n * the ledger's uniqueness constraint makes the overlap safe.\n *\n * Returns null for anything that is not a sandbox reference — a router\n * inference row, a grant, a refund — rather than guessing.\n */\nexport function parseSettlementReference(referenceId: string | null | undefined): SettlementReference | null {\n if (!referenceId) return null\n const parts = referenceId.split(':')\n if (parts.length < 3 || parts[0] !== 'sandbox') return null\n const kind = parts[1]\n if (!kind) return null\n\n // The trailing segment is the interval cursor ONLY when it reads as an epoch\n // instant. `sandbox:gpu-lease:<leaseId>` has no cursor, and a resource id that\n // happened to contain a colon must not have its tail eaten as one.\n const tail = parts[parts.length - 1] as string\n const tailMs = /^\\d+$/.test(tail) ? Number(tail) : Number.NaN\n const hasCursor = parts.length >= 4 && Number.isSafeInteger(tailMs) && tailMs > 0\n\n const resourceId = hasCursor ? parts.slice(2, -1).join(':') : parts.slice(2).join(':')\n if (!resourceId) return null\n\n return { kind, resourceId, intervalStartMs: hasCursor ? tailMs : null }\n}\n\n/**\n * Read the sandbox id out of the platform's aggregation key, `sandbox:<id>`.\n *\n * Distinct from the reference id: `groupKey` is the unit a billing statement\n * groups by and is deliberately NOT unique per row, while `referenceId` is\n * unique per interval. A null group key means \"do not aggregate\" (grants,\n * top-ups, refunds, transfers) and is not an error.\n */\nexport function parseSandboxGroupKey(groupKey: string | null | undefined): string | null {\n if (!groupKey) return null\n const parts = groupKey.split(':')\n if (parts.length < 2 || parts[0] !== 'sandbox') return null\n const id = parts.slice(1).join(':')\n return id || null\n}\n\n/**\n * The sandbox a settlement row is attributable to.\n *\n * The reference id wins over the group key because it is the field the platform\n * dedups on, so it is the one guaranteed present and correct on a compute\n * settlement; the group key is the fallback for rows written before a producer\n * stamped a reference, and for kinds whose reference names something else (a GPU\n * lease id, not a box).\n */\nexport function settlementSandboxId(row: SettlementRow): string | null {\n const reference = parseSettlementReference(row.referenceId)\n if (reference && reference.intervalStartMs !== null) return reference.resourceId\n return parseSandboxGroupKey(row.groupKey) ?? (reference ? reference.resourceId : null)\n}\n\n/** True when a row is a charge (the ledger stores charges as negative amounts). */\nexport function isCharge(row: SettlementRow): boolean {\n return row.amountNanoUsd < 0\n}\n\n/** A charge's magnitude in unsigned nanodollars; 0 for credits. */\nexport function chargeNanoUsd(row: SettlementRow): number {\n return row.amountNanoUsd < 0 ? -row.amountNanoUsd : 0\n}\n","import { DEFAULT_CEILING_TOLERANCE_MS, computeExpectedCeiling } from './ceiling'\nimport { decideBoxOwnership } from './ownership'\nimport { chargeNanoUsd, parseSettlementReference, settlementSandboxId } from './reference'\nimport type { SpendLedgerStorePort } from './store'\nimport {\n SPEND_CHECKS,\n type BilledDurationBasis,\n type CeilingBasis,\n type SettlementRow,\n type SpendBoxRecord,\n type SpendCheckId,\n type SpendFinding,\n type SpendOwnershipRule,\n type SpendOwnershipSummary,\n type SpendOwnershipVerdict,\n type SpendReport,\n} from './types'\n\n/** How many nanodollars in one US dollar. The ledger's unit. */\nconst NANO_PER_USD = 1_000_000_000\nconst MS_PER_HOUR = 3_600_000\n\nexport interface VelocityOptions {\n /** Bucket width for a spend window, ms. Default 24 h. */\n readonly windowMs?: number\n /** Fire when a window exceeds this multiple of the trailing median. Default 5. */\n readonly multiple?: number\n /**\n * Windows of history required before a median means anything. Default 3.\n * Below this the rule stays silent, so a product's genuine first days of\n * usage are not reported as an anomaly.\n */\n readonly minTrailingWindows?: number\n /**\n * A window under this never fires, whatever the ratio. Default $1.00.\n *\n * Without a floor the rule is useless: a trailing median of a tenth of a cent\n * makes every ordinary day a 5x outlier. $1.00 is set from the incident's own\n * distribution — the smallest of the eight affected wallets took $1.98, and\n * the two rows in the same window that were GENUINE were sub-cent. So the\n * floor sits above the noise and below every real finding.\n */\n readonly minAbsoluteNanoUsd?: number\n}\n\nconst DEFAULT_VELOCITY: Required<VelocityOptions> = {\n windowMs: 86_400_000,\n multiple: 5,\n minTrailingWindows: 3,\n minAbsoluteNanoUsd: NANO_PER_USD,\n}\n\n/** The balance the product observes, and the floor it must not cross. */\nexport interface ObservedBalance {\n /** Signed nanodollars, as the platform reports it. */\n readonly nanoUsd: number\n /** Below this is a finding. Default 0. */\n readonly floorNanoUsd?: number\n}\n\n/**\n * A box's price, nanodollars per hour, used to derive an EXACT billed duration\n * from a charge. Return null when the product does not know the box's rate; the\n * reconciler then falls back to the reference span.\n */\nexport type BoxRateResolver = (record: SpendBoxRecord | null, sandboxId: string) => number | null | undefined\n\nexport interface ReconcileSpendOptions {\n /**\n * Settled ledger rows, supplied by the product's own authenticated fetch.\n *\n * The fetch can only scope to a WALLET — `product: 'sandbox'` is the\n * platform's service taxonomy, not this product's — so on an account running\n * more than one of our products these rows carry the siblings' boxes too.\n * {@link ReconcileSpendOptions.ownership} is what separates them.\n */\n readonly rows: readonly SettlementRow[]\n /** The product's expectation ledger. */\n readonly store: SpendLedgerStorePort\n /**\n * Which of those rows are THIS product's — see {@link SpendOwnershipRule} and\n * the shipped `ownedByBillingKeys`.\n *\n * Omitting it is safe and changes nothing: the pass claims every box, which is\n * the behaviour that shipped, and the direction that over-reports rather than\n * under-reports. It is not silent about it — `report.ownership.declared` is\n * `false`, `formatSpendReport` says so above the findings, and every\n * `unknown-box` finding states on its face that a sibling product's box is\n * indistinguishable from a charge that is not ours.\n *\n * Declaring it never weakens the ledger-backed checks: ownership is consulted\n * ONLY for boxes with no expectation record, so `over-ceiling` on a recorded\n * box fires whatever the rule says.\n */\n readonly ownership?: SpendOwnershipRule\n /** Treated as \"now\". Default `Date.now()`. */\n readonly asOf?: number\n /** Ceiling slack. Default {@link DEFAULT_CEILING_TOLERANCE_MS}. */\n readonly toleranceMs?: number\n /** Box price, for the exact duration basis. A number applies to every box. */\n readonly nanoUsdPerHour?: number | BoxRateResolver\n /** Velocity tuning, or `false` to skip the rule. */\n readonly velocity?: VelocityOptions | false\n /** The workspace balance, when the product can see one. Omitted skips the rule. */\n readonly balance?: ObservedBalance\n /** Stamped onto findings so an alert names the tenant. */\n readonly workspaceId?: string\n /** Checks to leave out of this pass. */\n readonly skip?: readonly SpendCheckId[]\n}\n\nfunction usd(nano: number): string {\n return `$${(nano / NANO_PER_USD).toFixed(2)}`\n}\n\nfunction hours(ms: number): string {\n return `${(ms / MS_PER_HOUR).toFixed(1)}h`\n}\n\n/** Trust order, least trustworthy first — a mixed aggregate reports the weakest. */\nconst BASIS_TRUST: readonly BilledDurationBasis[] = ['unknown', 'reference-span', 'rate', 'reported']\n\nfunction weakestBasis(a: BilledDurationBasis, b: BilledDurationBasis): BilledDurationBasis {\n return BASIS_TRUST.indexOf(a) <= BASIS_TRUST.indexOf(b) ? a : b\n}\n\n/**\n * How long one settlement billed for, and how confidently we know it.\n *\n * The ledger row does not store a duration — this is the whole reason the check\n * is subtle. Three ways to recover it, best first:\n *\n * 1. `reported` — the product's ledger view exposed it. Exact.\n * 2. `rate` — `charge / pricePerHour`. Exact, because the platform computes the\n * charge as `(durationMs / 3_600_000) * costPerHour` and nothing else enters\n * it. Requires the product to know its box's price.\n * 3. `reference-span` — `settledAt - intervalStart`, both read off the row. An\n * UPPER bound, not the duration: a correct settlement delayed by the\n * platform's durable settlement queue reads longer here than it billed. It is\n * exact for the failure this module exists to catch, because billing \"up to\n * now\" makes the settlement instant and the interval end the same moment.\n */\nfunction resolveBilledMs(\n row: SettlementRow,\n ratePerHourNano: number | null,\n): { ms: number; basis: BilledDurationBasis } {\n if (row.billedMs !== null) return { ms: row.billedMs, basis: 'reported' }\n\n const charge = chargeNanoUsd(row)\n if (ratePerHourNano !== null && ratePerHourNano > 0 && charge > 0) {\n return { ms: (charge / ratePerHourNano) * MS_PER_HOUR, basis: 'rate' }\n }\n\n const reference = parseSettlementReference(row.referenceId)\n if (reference?.intervalStartMs != null && row.createdAt > reference.intervalStartMs) {\n return { ms: row.createdAt - reference.intervalStartMs, basis: 'reference-span' }\n }\n\n return { ms: 0, basis: 'unknown' }\n}\n\nfunction median(values: readonly number[]): number {\n if (values.length === 0) return 0\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n if (sorted.length % 2 === 1) return sorted[mid] as number\n return (((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2)\n}\n\n/**\n * What an `unknown-box` finding can honestly claim about WHOSE box it is.\n *\n * Three different statements, because the reader's next action differs: chase a\n * charge inside our own billing identity, chase a charge nothing attributes,\n * or first go and declare an ownership rule so the question can be answered at\n * all. A single message covering all three would be the vaguest of the three.\n */\nfunction unknownBoxAttribution(\n ownership: SpendOwnershipRule | null,\n verdict: SpendOwnershipVerdict,\n): string {\n if (!ownership) {\n return (\n ' No ownership rule was declared for this pass, so a sibling product\\'s box on the same ' +\n 'wallet reads exactly like a charge that is not ours — this finding could be either.'\n )\n }\n if (verdict === 'undecidable') {\n return (\n ` The ownership rule (${ownership.label}) could not decide it: the settlement carries no ` +\n 'billing-key attribution to exclude it by, so it is reported rather than dropped.'\n )\n }\n return ` The ownership rule (${ownership.label}) attributes it to THIS product.`\n}\n\nfunction unknownBoxRemedy(\n ownership: SpendOwnershipRule | null,\n verdict: SpendOwnershipVerdict,\n sandboxId: string,\n): string {\n const lookup = `Look up ${sandboxId} on the platform before disputing.`\n if (!ownership) {\n return (\n 'Declare `ownership` (see `ownedByBillingKeys`) so a sibling product\\'s box stops reading as ' +\n 'a discrepancy — without it this check cannot tell one from a charge that is not ours. ' +\n 'Until then, treat this as one of three things: a sibling product on the same wallet, a box ' +\n `provisioned outside the recorded seam, or a box that is not ours at all. ${lookup}`\n )\n }\n if (verdict === 'undecidable') {\n return (\n 'An unattributable charge on a shared wallet is exactly what a phantom charge looks like, so ' +\n 'it is reported by design rather than excluded. Confirm the row genuinely predates key ' +\n `attribution before dismissing it. ${lookup}`\n )\n }\n return (\n 'This box is inside this product\\'s own billing attribution and the product never recorded it, ' +\n 'so it is either a provision that bypassed the recorded seam or a charge that is not ours. ' +\n `${lookup}`\n )\n}\n\nfunction emptyFinding(check: SpendCheckId): Omit<SpendFinding, 'message' | 'remedy'> {\n return {\n check,\n sandboxId: null,\n workspaceId: null,\n referenceIds: [],\n settledNanoUsd: 0,\n settledMs: null,\n durationBasis: null,\n ceilingMs: null,\n overageMs: null,\n ceilingBasis: null,\n windowNanoUsd: null,\n trailingMedianNanoUsd: null,\n velocityRatio: null,\n windowStartAt: null,\n balanceNanoUsd: null,\n balanceFloorNanoUsd: null,\n }\n}\n\n/**\n * Diff what the platform charged against what the product believes it asked for.\n *\n * Never disputes anything and never writes: the output is a report a human acts\n * on. The platform's ledger stays authoritative — this only ever produces the\n * evidence for a conversation with it.\n */\nexport async function reconcileSpend(options: ReconcileSpendOptions): Promise<SpendReport> {\n const asOf = options.asOf ?? Date.now()\n const toleranceMs = options.toleranceMs ?? DEFAULT_CEILING_TOLERANCE_MS\n const workspaceId = options.workspaceId ?? null\n const skip = new Set(options.skip ?? [])\n const checksRun = SPEND_CHECKS.filter((check) => !skip.has(check))\n const runs = (check: SpendCheckId): boolean => !skip.has(check)\n\n const ownership = options.ownership ?? null\n\n const findings: SpendFinding[] = []\n let settledNanoUsd = 0\n let creditedNanoUsd = 0\n let ownedBoxes = 0\n let ownedNanoUsd = 0\n let undecidableBoxes = 0\n let foreignNanoUsd = 0\n const foreignSandboxIds: string[] = []\n\n // ── group charges by the box they are attributable to ──────────────────────\n const byBox = new Map<string, SettlementRow[]>()\n for (const row of options.rows) {\n if (row.amountNanoUsd < 0) settledNanoUsd += -row.amountNanoUsd\n else creditedNanoUsd += row.amountNanoUsd\n if (row.amountNanoUsd >= 0) continue\n const sandboxId = settlementSandboxId(row)\n if (!sandboxId) continue\n const bucket = byBox.get(sandboxId)\n if (bucket) bucket.push(row)\n else byBox.set(sandboxId, [row])\n }\n\n const rateOf = (record: SpendBoxRecord | null, sandboxId: string): number | null => {\n const rate = options.nanoUsdPerHour\n if (rate === undefined) return null\n if (typeof rate === 'number') return rate\n return rate(record, sandboxId) ?? null\n }\n\n for (const [sandboxId, rows] of byBox) {\n const record = await options.store.load(sandboxId)\n const referenceIds = rows.map((row) => row.referenceId ?? row.id)\n const charged = rows.reduce((sum, row) => sum + chargeNanoUsd(row), 0)\n\n // A box the product RECORDED is this product's by construction, and no\n // ownership rule may un-own it. That is what stops a wrong or over-narrow\n // rule from hiding an over-ceiling finding: the ledger decides recorded-ness,\n // the rule decides attribution, and the rule only ever gets a say about the\n // residue neither of them has claimed.\n const verdict: SpendOwnershipVerdict = record\n ? 'mine'\n : ownership\n ? decideBoxOwnership(ownership, sandboxId, rows)\n : 'mine'\n\n if (verdict === 'foreign') {\n foreignSandboxIds.push(sandboxId)\n foreignNanoUsd += charged\n continue\n }\n ownedBoxes += 1\n ownedNanoUsd += charged\n if (verdict === 'undecidable') undecidableBoxes += 1\n\n // ── unknown-box ──────────────────────────────────────────────────────────\n if (!record) {\n if (runs('unknown-box')) {\n findings.push({\n ...emptyFinding('unknown-box'),\n sandboxId,\n workspaceId,\n referenceIds,\n settledNanoUsd: charged,\n message:\n `${usd(charged)} settled across ${rows.length} row(s) against sandbox ${sandboxId}, ` +\n 'which this product has no record of ever asking for.' +\n unknownBoxAttribution(ownership, verdict),\n remedy: unknownBoxRemedy(ownership, verdict, sandboxId),\n })\n }\n continue\n }\n\n // ── over-ceiling ─────────────────────────────────────────────────────────\n if (!runs('over-ceiling')) continue\n\n const ceiling = computeExpectedCeiling(record, { asOf, toleranceMs })\n const ratePerHourNano = rateOf(record, sandboxId)\n\n let settledMs = 0\n let basis: BilledDurationBasis = 'reported'\n let anyMeasured = false\n for (const row of rows) {\n const resolved = resolveBilledMs(row, ratePerHourNano)\n if (resolved.basis === 'unknown') {\n basis = weakestBasis(basis, 'unknown')\n continue\n }\n anyMeasured = true\n settledMs += resolved.ms\n basis = weakestBasis(basis, resolved.basis)\n }\n if (!anyMeasured) continue\n if (settledMs <= ceiling.ceilingMs) continue\n\n const overageMs = settledMs - ceiling.ceilingMs\n const confidence = ceiling.bounded\n ? ''\n : ' The product could not bound this box from its own observations (an unfinished detached ' +\n 'run, and no max lifetime), so the ceiling rests on the reconciliation instant: this ' +\n 'settlement bills time outside the box\\'s own life, not merely more than expected.'\n const spanCaveat =\n basis === 'reference-span'\n ? ' Duration is derived from the settlement instant minus the interval start, which ' +\n 'overstates a settlement the platform merely posted late — confirm before disputing.'\n : ''\n\n findings.push({\n ...emptyFinding('over-ceiling'),\n sandboxId,\n workspaceId: record.workspaceId || workspaceId,\n referenceIds,\n settledNanoUsd: charged,\n settledMs,\n durationBasis: basis,\n ceilingMs: ceiling.ceilingMs,\n overageMs,\n ceilingBasis: ceiling.basis,\n message:\n `Sandbox ${sandboxId} settled ${hours(settledMs)} (${usd(charged)}) across ${rows.length} ` +\n `row(s), against an expected ceiling of ${hours(ceiling.ceilingMs)} — over by ` +\n `${hours(overageMs)}. Ceiling basis: ${ceiling.basis}; duration basis: ${basis}.` +\n confidence +\n spanCaveat,\n remedy:\n `Dispute ${referenceIds.join(', ')} against the platform ledger with both numbers. ` +\n (ceiling.basis === 'stopped' || ceiling.basis === 'deleted'\n ? 'The product recorded this box as no longer running before the billed time ended, so ' +\n 'either the stop did not take or the interval was settled at the wrong boundary.'\n : 'Freeze the open interval before anything deletes this box — deleting a box with an ' +\n 'open compute interval settles the whole gap at once.'),\n })\n }\n\n // ── velocity ───────────────────────────────────────────────────────────────\n if (runs('velocity') && options.velocity !== false) {\n const cfg = { ...DEFAULT_VELOCITY, ...(options.velocity ?? {}) }\n const buckets = new Map<number, { nano: number; references: string[] }>()\n for (const row of options.rows) {\n const charge = chargeNanoUsd(row)\n if (charge === 0) continue\n // Velocity is decided per ROW, not per box, because a row naming no\n // sandbox at all still counts toward what this product spent. A sibling's\n // burst is excluded rather than paged on: a product cannot dispute a\n // charge it did not incur, and leaving them in makes one product's\n // incident wake every product on the wallet.\n if (ownership && ownership.decide({ row, sandboxId: settlementSandboxId(row) }) === 'foreign') {\n continue\n }\n const bucketStart = Math.floor(row.createdAt / cfg.windowMs) * cfg.windowMs\n const bucket = buckets.get(bucketStart)\n if (bucket) {\n bucket.nano += charge\n bucket.references.push(row.referenceId ?? row.id)\n } else {\n buckets.set(bucketStart, { nano: charge, references: [row.referenceId ?? row.id] })\n }\n }\n\n const ordered = [...buckets.entries()].sort((a, b) => a[0] - b[0])\n for (let i = 0; i < ordered.length; i++) {\n const entry = ordered[i]\n if (!entry) continue\n const [windowStartAt, bucket] = entry\n if (i < cfg.minTrailingWindows) continue\n const trailing = ordered.slice(0, i).map(([, prior]) => prior.nano)\n const trailingMedian = median(trailing)\n const threshold = Math.max(trailingMedian * cfg.multiple, cfg.minAbsoluteNanoUsd)\n if (bucket.nano <= threshold) continue\n const ratio = trailingMedian > 0 ? bucket.nano / trailingMedian : Number.POSITIVE_INFINITY\n\n findings.push({\n ...emptyFinding('velocity'),\n workspaceId,\n referenceIds: bucket.references,\n settledNanoUsd: bucket.nano,\n windowNanoUsd: bucket.nano,\n trailingMedianNanoUsd: trailingMedian,\n velocityRatio: ratio,\n windowStartAt,\n message:\n `${usd(bucket.nano)} settled in the window starting ${new Date(windowStartAt).toISOString()} ` +\n `across ${bucket.references.length} row(s), against a trailing median of ` +\n `${usd(trailingMedian)} over ${trailing.length} prior window(s) — ` +\n `${Number.isFinite(ratio) ? `${ratio.toFixed(1)}x` : 'no prior spend to compare against'}, ` +\n `over the ${cfg.multiple}x threshold.` +\n (ownership\n ? ` Counted over this product's own rows only (${ownership.label}); the wallet total ` +\n 'for the window is higher when a sibling product settled into it.'\n : ' Counted over every row on the wallet, which on a shared account includes any ' +\n 'sibling product\\'s spend.'),\n remedy:\n 'A burst of this shape is what a settlement defect looks like from the consumer side: ' +\n 'long-dormant intervals cashed out at once. Check whether these rows carry interval ' +\n 'starts far older than the settlement instant before treating it as real usage.',\n })\n }\n }\n\n // ── negative-balance ───────────────────────────────────────────────────────\n if (runs('negative-balance') && options.balance) {\n const floor = options.balance.floorNanoUsd ?? 0\n if (options.balance.nanoUsd < floor) {\n findings.push({\n ...emptyFinding('negative-balance'),\n workspaceId,\n settledNanoUsd: Math.max(0, floor - options.balance.nanoUsd),\n balanceNanoUsd: options.balance.nanoUsd,\n balanceFloorNanoUsd: floor,\n message:\n `Observed balance ${usd(options.balance.nanoUsd)} is below the floor ${usd(floor)}.`,\n remedy:\n 'Stop provisioning new compute for this owner until the balance is explained. A negative ' +\n 'balance that nobody is watching is how a billing defect becomes settled money.',\n })\n }\n }\n\n const ownershipSummary: SpendOwnershipSummary = {\n declared: ownership !== null,\n label: ownership?.label ?? null,\n ownedBoxes,\n ownedNanoUsd,\n undecidableBoxes,\n foreignBoxes: foreignSandboxIds.length,\n foreignNanoUsd,\n foreignSandboxIds,\n }\n\n return {\n ok: findings.length === 0,\n findings,\n checksRun,\n rowsExamined: options.rows.length,\n boxesExamined: byBox.size,\n settledNanoUsd,\n creditedNanoUsd,\n ownership: ownershipSummary,\n asOf,\n }\n}\n","import type { SpendFinding, SpendOwnershipSummary, SpendReport } from './types'\n\nconst NANO_PER_USD = 1_000_000_000\n\nfunction usd(nano: number | null): string {\n return nano === null ? '—' : `$${(nano / NANO_PER_USD).toFixed(2)}`\n}\n\n/**\n * Render a reconciliation for a human deciding whether to open a dispute.\n *\n * Every finding prints its numbers, not a summary of them: the reader's next\n * action is a conversation with the platform about specific reference ids, and a\n * report that made them re-derive the durations would just be re-read alongside\n * the raw rows anyway.\n */\nexport function formatSpendReport(report: SpendReport): string {\n const lines: string[] = []\n lines.push(\n `spend reconciliation — ${report.rowsExamined} row(s), ${report.boxesExamined} box(es), ` +\n `${usd(report.settledNanoUsd)} charged, ${usd(report.creditedNanoUsd)} credited, ` +\n `as of ${new Date(report.asOf).toISOString()}`,\n )\n lines.push(`checks: ${report.checksRun.join(', ') || '(none)'}`)\n for (const line of ownershipLines(report.ownership)) lines.push(line)\n\n if (report.ok) {\n lines.push('')\n lines.push('OK — no discrepancy between the product\\'s expectations and the settled ledger.')\n return lines.join('\\n')\n }\n\n lines.push('')\n lines.push(`${report.findings.length} finding(s):`)\n for (const finding of report.findings) {\n lines.push('')\n lines.push(` [${finding.check}] ${finding.message}`)\n for (const [label, value] of measuredFields(finding)) lines.push(` ${label}: ${value}`)\n if (finding.referenceIds.length > 0) {\n lines.push(` rows: ${finding.referenceIds.join(', ')}`)\n }\n lines.push(` → ${finding.remedy}`)\n }\n return lines.join('\\n')\n}\n\n/**\n * What the pass claimed and what it set aside — printed on EVERY report,\n * clean ones included.\n *\n * A clean report that does not say what it looked at is the failure this\n * closes: an over-narrow ownership rule and a genuinely quiet account produce\n * the same \"OK\" line, and only the excluded numbers tell them apart. The\n * excluded box ids are printed in full for the same reason — an exclusion a\n * reader cannot audit is one they have to take on trust.\n */\nfunction ownershipLines(ownership: SpendOwnershipSummary): string[] {\n if (!ownership.declared) {\n return [\n `scope: NOT DECLARED — all ${ownership.ownedBoxes} settled box(es) claimed as this ` +\n 'product\\'s. A sibling product\\'s box on this wallet is reported as unknown-box; pass ' +\n '`ownership` (see `ownedByBillingKeys`) to tell the two apart.',\n ]\n }\n const lines = [\n `scope: ${ownership.label} — ${ownership.ownedBoxes} box(es) ${usd(ownership.ownedNanoUsd)} ` +\n `owned, ${ownership.foreignBoxes} box(es) ${usd(ownership.foreignNanoUsd)} excluded as ` +\n 'another product\\'s',\n ]\n if (ownership.undecidableBoxes > 0) {\n lines.push(\n ` ${ownership.undecidableBoxes} of the owned box(es) carried no billing-key ` +\n 'attribution and were claimed fail-closed',\n )\n }\n if (ownership.foreignSandboxIds.length > 0) {\n lines.push(` excluded: ${ownership.foreignSandboxIds.join(', ')}`)\n }\n return lines\n}\n\n/** Every measured field a finding carries, including the ones it left null. */\nfunction measuredFields(finding: SpendFinding): Array<[string, string]> {\n const ms = (value: number | null): string =>\n value === null ? '—' : `${(value / 3_600_000).toFixed(2)}h`\n return [\n ['sandbox', finding.sandboxId ?? '—'],\n ['workspace', finding.workspaceId ?? '—'],\n ['amount', usd(finding.settledNanoUsd)],\n ['settled', ms(finding.settledMs)],\n ['ceiling', ms(finding.ceilingMs)],\n ['overage', ms(finding.overageMs)],\n ['ceiling basis', finding.ceilingBasis ?? '—'],\n ['duration basis', finding.durationBasis ?? '—'],\n ['window', finding.windowStartAt === null ? '—' : new Date(finding.windowStartAt).toISOString()],\n ['window spend', usd(finding.windowNanoUsd)],\n ['trailing median', usd(finding.trailingMedianNanoUsd)],\n ['ratio', finding.velocityRatio === null ? '—' : `${finding.velocityRatio.toFixed(1)}x`],\n ['balance', usd(finding.balanceNanoUsd)],\n ['balance floor', usd(finding.balanceFloorNanoUsd)],\n ]\n}\n\n/** The report as a plain JSON value, for an alerting pipeline. */\nexport function spendReportToJson(report: SpendReport): string {\n return JSON.stringify(report, null, 2)\n}\n"],"mappings":";AAsTO,IAAM,eAAwC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AC3OO,SAAS,mBAAmB,QAA+C;AAChF,QAAM,QAAQ,IAAI,IAAI,OAAO,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE,OAAO,OAAO,CAAC;AACnE,MAAI,MAAM,SAAS,GAAG;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,QAAM,QAAQ,eAAe,CAAC,GAAG,KAAK,EAAE,KAAK,IAAI,CAAC;AAClD,SAAO;AAAA,IACL;AAAA,IACA,OAAO,EAAE,IAAI,GAAG;AACd,YAAM,QAAQ,IAAI,OAAO,KAAK;AAC9B,UAAI,CAAC,MAAO,QAAO;AACnB,aAAO,MAAM,IAAI,KAAK,IAAI,SAAS;AAAA,IACrC;AAAA,EACF;AACF;AAaO,SAAS,mBACd,MACA,WACA,MACuB;AACvB,MAAI,UAAiC;AACrC,aAAW,OAAO,MAAM;AACtB,UAAM,aAAa,KAAK,OAAO,EAAE,KAAK,UAAU,CAAC;AACjD,QAAI,eAAe,OAAQ,QAAO;AAClC,QAAI,eAAe,cAAe,WAAU;AAAA,EAC9C;AACA,SAAO;AACT;;;ACxGO,IAAM,+BAA+B;AAmCrC,SAAS,uBACd,QACA,SACiB;AACjB,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,EAAE,KAAK,IAAI;AAEjB,MAAI;AACJ,MAAI;AAEJ,MAAI,OAAO,cAAc,MAAM;AAC7B,YAAQ;AACR,gBAAY,OAAO;AAAA,EACrB,WAAW,OAAO,cAAc,MAAM;AACpC,YAAQ;AACR,g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