@cortexkit/common-auth 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,348 +1,32 @@
1
- import { createContext, createMemo, createSignal, For, Index, mergeProps, Show, useContext, } from 'solid-js';
1
+ import { SidebarFrame as Frame, } from '@cortexkit/opencode-sidebar';
2
+ import { mapArray, mergeProps } from 'solid-js';
2
3
  import { formatQuota, quotaWindowParts } from '../quota/format.js';
3
- const FrameContext = createContext();
4
- function frameContext() {
5
- const context = useContext(FrameContext);
6
- if (!context)
7
- throw new Error('Sidebar primitives must be inside SidebarFrame');
8
- return context;
9
- }
10
- function displayWidth(text) {
11
- const bun = globalThis.Bun;
12
- return bun?.stringWidth ? bun.stringWidth(text) : Array.from(text).length;
13
- }
14
- function fitText(text, columns) {
15
- if (displayWidth(text) <= columns)
16
- return text;
17
- if (columns < 1)
18
- return '';
19
- let kept = '';
20
- let used = 0;
21
- for (const char of text) {
22
- const width = displayWidth(char);
23
- if (used + width > columns - 1)
24
- break;
25
- kept += char;
26
- used += width;
27
- }
28
- return `${kept}\u2026`;
29
- }
30
- /** A heading and its plugin-owned rows, with the frame's section spacing. */
31
- export function SidebarSection(props) {
32
- const context = frameContext();
33
- return (<>
34
- <box width='100%' marginTop={1}>
35
- <text fg={context.theme.text}>
36
- <b>{props.title}</b>
37
- </text>
38
- </box>
39
- {props.children}
40
- </>);
41
- }
42
- /** Keep labels whole and reserve one blank cell before an ellipsized value. */
43
- export function SidebarStatRow(props) {
44
- const context = frameContext();
45
- const [width, setWidth] = createSignal(0);
46
- let row;
47
- const value = () => width() <= 0
48
- ? props.value
49
- : fitText(props.value, width() - displayWidth(props.label) - 1);
50
- return (<box ref={(element) => {
51
- row = element;
52
- }} onSizeChange={() => setWidth(row?.width ?? 0)} width='100%' flexDirection='row' justifyContent='space-between' columnGap={1}>
53
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
54
- {props.label}
55
- </text>
56
- <text fg={context.theme[props.tone ?? 'text']} wrapMode='none' flexShrink={1}>
57
- <b>{value()}</b>
58
- </text>
59
- </box>);
60
- }
61
- export function SidebarTextRow(props) {
62
- const context = frameContext();
63
- return (<text fg={context.theme[props.tone ?? 'textMuted']} wrapMode={props.wrapMode}>
64
- {props.text}
65
- </text>);
66
- }
67
- function usageTone(used, appearance) {
68
- if (used >= appearance.errorThreshold)
69
- return 'error';
70
- if (used >= appearance.warnThreshold)
71
- return 'warning';
72
- return 'success';
73
- }
74
- function barSegments(used, appearance, pace) {
75
- const width = appearance.barWidth;
76
- const cells = (pct) => Math.max(0, Math.min(Math.round((pct / 100) * width), width));
77
- const usedCells = cells(used);
78
- const tone = usageTone(used, appearance);
79
- // Keep the overlay's slot even when empty so live pacing changes reuse nodes.
80
- const plain = [
81
- { text: appearance.barFilledChar.repeat(usedCells), tone },
82
- { text: '', tone },
83
- { text: appearance.barEmptyChar.repeat(width - usedCells), tone },
84
- ];
85
- const overlay = pace?.overlay;
86
- if (!overlay)
87
- return plain;
88
- const paceCells = cells(overlay.percent);
89
- const lo = Math.min(usedCells, paceCells);
90
- const hi = Math.max(usedCells, paceCells);
91
- if (lo === hi)
92
- return plain;
93
- return [
94
- { text: appearance.barFilledChar.repeat(lo), tone },
95
- {
96
- text: (overlay.kind === 'deficit' ? '\u2593' : '\u2592').repeat(hi - lo),
97
- tone: overlay.kind === 'deficit' ? 'error' : 'success',
98
- },
99
- { text: appearance.barEmptyChar.repeat(width - hi), tone },
100
- ];
101
- }
102
- function QuotaRow(props) {
103
- const context = frameContext();
104
- const [columns, setColumns] = createSignal(0);
105
- let row;
106
- const label = () => props.part.name +
107
- ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)));
108
- const figure = () => ` ${props.part.kind === 'budget' && props.part.figure.startsWith(`${props.part.name} `) ? props.part.figure.slice(props.part.name.length + 1) : props.part.figure}`;
109
- const hasReading = () => props.part.reading === 'known';
110
- const used = () => 100 - (props.part.remainingPercent ?? 100);
111
- // Size notifications can recompute an unchanged fit after text has been flushed
112
- // for the frame. Keep equal segments, and update fixed slots in place when the
113
- // bar changes, rather than replacing text nodes during layout.
114
- const segments = createMemo(() => hasReading()
115
- ? barSegments(used(), { ...context.appearance, barWidth: props.barCells }, props.pace)
116
- : [], undefined, {
117
- equals: (previous, next) => previous.length === next.length &&
118
- previous.every((segment, index) => segment.text === next[index]?.text &&
119
- segment.tone === next[index]?.tone),
120
- });
121
- const paceLine = () => {
122
- const text = props.pace?.text;
123
- if (!text || columns() <= 0)
124
- return text;
125
- return fitText(text, columns() - props.labelWidth);
126
- };
127
- return (<>
128
- <box ref={(element) => {
129
- row = element;
130
- }} onSizeChange={() => setColumns(row?.width ?? 0)} width='100%' flexDirection='row' justifyContent='space-between'>
131
- <box flexDirection='row' flexShrink={props.part.resetSinceReading ? 1 : 0}>
132
- <Show when={props.labelWidth > 0}>
133
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
134
- {label()}
135
- </text>
136
- </Show>
137
- <Show when={hasReading()} fallback={<text fg={context.theme.textMuted} wrapMode='none'>
138
- no reading
139
- </text>}>
140
- <Show when={!props.part.resetSinceReading} fallback={<text fg={context.theme.textMuted} wrapMode='none'>
141
- reset since last check
142
- </text>}>
143
- <Show when={props.barCells > 0}>
144
- {/* Text nodes clear omitted theme colours; empty slots must not reserve a cell. */}
145
- <Index each={segments()}>
146
- {(segment) => (<text fg={context.theme[segment().tone]} wrapMode='none' width={segment().text ? undefined : 0}>
147
- {segment().text}
148
- </text>)}
149
- </Index>
150
- </Show>
151
- <text fg={context.theme[usageTone(used(), context.appearance)]} wrapMode='none'>
152
- {figure()}
153
- </text>
154
- </Show>
155
- </Show>
156
- </box>
157
- <Show when={hasReading() && props.showReset && !props.part.resetSinceReading}>
158
- <box width={props.resetWidth} flexShrink={0} flexDirection='row' justifyContent='flex-end'>
159
- <Show when={props.part.resetIn}>
160
- <text fg={context.theme.textMuted} wrapMode='none'>
161
- {props.part.resetIn}
162
- </text>
163
- </Show>
164
- </box>
165
- </Show>
166
- </box>
167
- {/* A changed fitted line needs a fresh text node to draw at its new width. */}
168
- <Show when={hasReading() && !props.part.resetSinceReading && paceLine()} keyed>
169
- {(line) => (<box width='100%' flexDirection='row'>
170
- <Show when={props.labelWidth > 0}>
171
- <text fg={context.theme.textMuted}>
172
- {''.padEnd(props.labelWidth)}
173
- </text>
174
- </Show>
175
- <text fg={context.theme[props.pace?.tone ?? 'textMuted']} wrapMode='none'>
176
- {line}
177
- </text>
178
- </box>)}
179
- </Show>
180
- </>);
181
- }
182
- function CollapsedAccountRow(props) {
183
- const context = frameContext();
184
- const [width, setWidth] = createSignal(0);
185
- let row;
186
- const hasQuota = () => quotaWindowParts(props.account.quota, { now: context.now }).windows.some((part) => part.reading === 'known');
187
- const text = () => hasQuota()
188
- ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
189
- : (props.account.emptyQuotaText?.collapsed ?? '\u2014');
190
- // Reserve an ellipsis, a separator and the trailing indicator before keeping quota.
191
- const showQuota = () => width() <= 0 || displayWidth(text()) + 4 <= width();
192
- const label = () => {
193
- if (width() <= 0)
194
- return props.account.label;
195
- return fitText(props.account.label, width() - (showQuota() ? displayWidth(text()) + 3 : 2));
196
- };
197
- const muted = () => props.account.collapsed?.muted ?? false;
198
- const quotaTone = () => muted() ? 'textMuted' : (props.account.collapsed?.quotaTone ?? 'success');
199
- return (<box ref={(element) => {
200
- row = element;
201
- }} onSizeChange={() => setWidth(row?.width ?? 0)} width='100%' flexDirection='row' justifyContent='space-between' columnGap={label() ? 1 : 0}>
202
- <Show when={label()}>
203
- <text fg={context.theme[muted() ? 'textMuted' : 'text']} wrapMode='none' flexShrink={1}>
204
- {label()}
205
- </text>
206
- </Show>
207
- <box flexDirection='row' flexShrink={0}>
208
- <Show when={showQuota()}>
209
- <Show when={hasQuota() && !muted()} fallback={<text fg={context.theme.textMuted}>{text()}</text>}>
210
- <text fg={context.theme[quotaTone()]}>
211
- <b>{text()}</b>
212
- </text>
213
- </Show>
214
- </Show>
215
- <text fg={context.theme[props.account.indicatorTone]}>
216
- {showQuota() ? ' ' : ''}
217
- {props.account.blocked ? '\u2298' : '\u25cf'}
218
- </text>
219
- </box>
220
- </box>);
221
- }
222
- function AccountBlock(props) {
223
- const context = frameContext();
224
- const [columns, setColumns] = createSignal(0);
225
- let block;
226
- const rows = () => props.account.groups.flatMap((group) => group.rows);
227
- const labelWidth = () => Math.max(0, ...rows().map(({ part }) => part.name ? Math.max(3, displayWidth(part.name) + 1) : 0));
228
- const resetWidth = () => Math.max(0, ...rows().map(({ part }) => part.reading === 'unknown' || part.resetSinceReading
229
- ? 0
230
- : displayWidth(part.resetIn ?? '')));
231
- const figureWidth = createMemo(() => Math.max(10, ...rows()
232
- .filter(({ part }) => part.reading === 'known' && !part.resetSinceReading)
233
- .map(({ part }) => displayWidth(` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`))));
234
- const fit = (rowLabelWidth) => {
235
- const desired = context.appearance.barWidth;
236
- // Four cells still distinguish quarters of a window without sacrificing its reset.
237
- const minimum = Math.min(4, desired);
238
- if (columns() <= 0)
239
- return { barCells: desired, showReset: resetWidth() > 0 };
240
- const room = columns() - rowLabelWidth - figureWidth();
241
- const withReset = room - resetWidth() - 1;
242
- const showReset = resetWidth() > 0 && withReset >= minimum;
243
- const available = showReset ? withReset : room;
244
- return {
245
- barCells: available >= minimum ? Math.min(desired, available) : 0,
246
- showReset,
247
- };
248
- };
249
- const label = () => {
250
- const full = `${props.account.label}${props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}`;
251
- return columns() <= 0
252
- ? full
253
- : fitText(full, columns() - displayWidth(props.account.status.text) - 1);
254
- };
255
- const age = () => quotaWindowParts(props.account.quota, { now: context.now }).age;
256
- const hasRows = () => props.account.groups.some((group) => group.rows.length > 0);
257
- return (<box ref={(element) => {
258
- block = element;
259
- }} onSizeChange={() => setColumns(block?.width ?? 0)} width='100%' flexDirection='column' marginTop={props.marginTop}>
260
- <box width='100%' flexDirection='row' justifyContent='space-between' columnGap={1}>
261
- <text fg={context.theme.text} wrapMode='none' flexShrink={1}>
262
- <b>{label()}</b>
263
- </text>
264
- <text fg={context.theme[props.account.status.tone]} wrapMode='none' flexShrink={0}>
265
- <b>{props.account.status.text}</b>
266
- </text>
267
- </box>
268
- {context.beforeQuota?.(props.account)}
269
- <Show when={hasRows()} fallback={<SidebarTextRow text={props.account.emptyQuotaText?.expanded ?? '\u2014'} wrapMode='none'/>}>
270
- <For each={props.account.groups}>
271
- {(group) => (<>
272
- <Show when={group.title}>
273
- <SidebarTextRow text={group.title ?? ''} tone='text' wrapMode='none'/>
274
- </Show>
275
- <For each={group.rows}>
276
- {(row) => {
277
- const rowLabelWidth = () => (row.part.name ? labelWidth() : 0);
278
- const rowFit = createMemo(() => fit(rowLabelWidth()));
279
- return (<QuotaRow part={row.part} pace={row.pace} labelWidth={rowLabelWidth()} barCells={rowFit().barCells} resetWidth={resetWidth()} showReset={rowFit().showReset}/>);
280
- }}
281
- </For>
282
- </>)}
283
- </For>
284
- </Show>
285
- <Show when={age()}>
286
- {(text) => (<SidebarTextRow text={text()} wrapMode='none'/>)}
287
- </Show>
288
- {context.afterQuota?.(props.account)}
289
- </box>);
290
- }
291
- /** Borderless, controlled presentation; host registration and provider policy stay in the plugin. */
4
+ export { SidebarSection, SidebarStatRow, SidebarTextRow, } from '@cortexkit/opencode-sidebar';
292
5
  export function SidebarFrame(props) {
293
- const hasData = () => props.accounts.length > 0;
294
- const headerLabel = () => !hasData()
295
- ? props.header.badge
296
- : `${props.collapsed ? '\u25b6' : '\u25bc'} ${props.header.badge}`;
297
- // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
298
- const context = mergeProps(props, {
299
- get theme() {
300
- const theme = props.theme;
301
- return {
302
- ...theme,
303
- textMuted: theme?.textMuted ?? theme?.text,
304
- accent: theme?.accent ?? theme?.text,
305
- success: theme?.success ?? theme?.text,
306
- warning: theme?.warning ?? theme?.text,
307
- error: theme?.error ?? theme?.text,
308
- };
309
- },
6
+ const sources = new WeakMap();
7
+ const accounts = mapArray(() => props.accounts, (account) => {
8
+ // Keep account identity and live getters while the frame reads the caller's clock.
9
+ const adapted = mergeProps(account, {
10
+ get hasQuota() {
11
+ return quotaWindowParts(account.quota, {
12
+ now: props.now,
13
+ }).windows.some((part) => part.reading === 'known');
14
+ },
15
+ get collapsedQuotaText() {
16
+ return formatQuota(account.quota, { now: props.now, form: 'narrow' });
17
+ },
18
+ get quotaAge() {
19
+ return quotaWindowParts(account.quota, { now: props.now }).age;
20
+ },
21
+ });
22
+ sources.set(adapted, account);
23
+ return adapted;
310
24
  });
311
- // Inverting an incomplete badge palette can put light text on a light background.
312
- const invertBadge = () => props.theme?.accent !== undefined && props.theme?.background !== undefined;
313
- return (<FrameContext.Provider value={context}>
314
- <box width='100%' flexDirection='column'>
315
- {/* Blocked accounts retain their own indicators; the header always keeps its version. */}
316
- {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI terminal widgets do not have DOM roles */}
317
- <box width='100%' flexDirection='row' justifyContent='space-between' alignItems='center' onMouseDown={() => {
318
- if (hasData())
319
- props.onToggle();
320
- }}>
321
- <box paddingLeft={1} paddingRight={1} backgroundColor={invertBadge() ? props.theme?.accent : undefined}>
322
- <text fg={invertBadge() ? props.theme?.background : context.theme.accent}>
323
- <b>{headerLabel()}</b>
324
- </text>
325
- </box>
326
- <Show when={props.header.version}>
327
- <text fg={context.theme.textMuted}>{props.header.version}</text>
328
- </Show>
329
- </box>
330
- <Show when={props.collapsed && hasData()}>
331
- <For each={props.accounts}>
332
- {(account) => <CollapsedAccountRow account={account}/>}
333
- </For>
334
- {props.collapsedSections?.()}
335
- </Show>
336
- <Show when={!props.collapsed || !hasData()}>
337
- <Show when={props.showQuota && hasData()}>
338
- <SidebarSection title='Quota'>
339
- <For each={props.accounts}>
340
- {(account, index) => (<AccountBlock account={account} marginTop={index() === 0 ? 0 : 1}/>)}
341
- </For>
342
- </SidebarSection>
343
- </Show>
344
- {props.sections?.()}
345
- </Show>
346
- </box>
347
- </FrameContext.Provider>);
25
+ return (<Frame {...props} accounts={accounts()} beforeQuota={(account) => {
26
+ const source = sources.get(account);
27
+ return source && props.beforeQuota?.(source);
28
+ }} afterQuota={(account) => {
29
+ const source = sources.get(account);
30
+ return source && props.afterQuota?.(source);
31
+ }}/>);
348
32
  }
@@ -14,6 +14,9 @@ export interface SessionToolWait {
14
14
  /** Epoch milliseconds when the oldest running plan tool started. */
15
15
  since: number;
16
16
  }
17
+ export declare const CACHE_WARM_STOP_REASONS: readonly ['cost-cap', 'count-cap', 'outside-hours', 'session-ended', 'unsupported'];
18
+ /** Billing rejects unknown stop reasons; omit them rather than guessing. */
19
+ export declare function isCacheWarmStopReason(value: unknown): value is (typeof CACHE_WARM_STOP_REASONS)[number];
17
20
  /**
18
21
  * The stop reasons the llm-runner contract defines today; any other string is
19
22
  * accepted too, for reasons that contract adds later.
@@ -1,4 +1,15 @@
1
1
  import { routingHandle } from './handle.js';
2
+ export const CACHE_WARM_STOP_REASONS = [
3
+ 'cost-cap',
4
+ 'count-cap',
5
+ 'outside-hours',
6
+ 'session-ended',
7
+ 'unsupported',
8
+ ];
9
+ /** Billing rejects unknown stop reasons; omit them rather than guessing. */
10
+ export function isCacheWarmStopReason(value) {
11
+ return CACHE_WARM_STOP_REASONS.some((reason) => reason === value);
12
+ }
2
13
  const warned = new Set();
3
14
  // Inspect descriptors rather than values so warning deduplication cannot invoke
4
15
  // a broken bridge's getters a second time. Do not print policy contents.
@@ -3,8 +3,9 @@
3
3
  * shaping. Account ids are vault account ids, not local pool rows. Nothing is
4
4
  * persisted here; plugins on routes the runner does not serve get no turn notes.
5
5
  */
6
+ import { type CacheWarmStopReason } from './cache-policy.js';
6
7
  export type { CacheTouchInput, CacheWarmStoppedInput, CacheWarmStopReason, SessionCacheHours, SessionCachePolicy, SessionCacheTtl, SessionKeepWarmMode, SessionToolWait, } from './cache-policy.js';
7
- export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
+ export { CACHE_WARM_STOP_REASONS, isCacheWarmStopReason, reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
9
  /** An eligible vault route, not a local pool row. */
9
10
  export interface RoutingCandidate {
10
11
  /** Vault account id, not the plugin's route id. */
@@ -42,6 +43,19 @@ interface RoutingReportIdentity {
42
43
  accountId: string;
43
44
  credentialId?: string;
44
45
  }
46
+ export type BillingRequestKind = 'primary' | 'title' | 'compaction' | 'generate' | 'keep_warm' | 'prime';
47
+ export type BillingOutcome = 'completed' | 'cut' | 'failed';
48
+ /** Omit unread counts; zero represents a measured count, not a default. */
49
+ export interface BillingUsage {
50
+ input?: number;
51
+ output?: number;
52
+ cacheRead?: number;
53
+ cacheWrite?: number;
54
+ cacheWrite5m?: number;
55
+ cacheWrite1h?: number;
56
+ reasoning?: number;
57
+ reasoningIncludedInOutput?: boolean;
58
+ }
45
59
  export type ReportRoutingInput = (RoutingReportIdentity & ({
46
60
  outcome: 'served';
47
61
  /**
@@ -73,6 +87,35 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
73
87
  kind: 'turn_note_skipped';
74
88
  after_tool_use_id: string;
75
89
  reason: 'anchor_missing' | 'before_user_message' | 'unsupported_model' | 'not_oauth';
90
+ } | {
91
+ sessionId: string;
92
+ kind: 'billing';
93
+ attemptId: string;
94
+ requestKind: BillingRequestKind;
95
+ credentialId: string;
96
+ accountId?: string;
97
+ provider: string;
98
+ model: string;
99
+ outcome: BillingOutcome;
100
+ providerRequestId?: string;
101
+ providerResponseId?: string;
102
+ userMessageId?: string;
103
+ status?: number;
104
+ attempt?: number;
105
+ chargeBasis?: 'subscription_included' | 'metered_api';
106
+ usage?: BillingUsage;
107
+ usageByModel?: readonly {
108
+ modelUsed: string;
109
+ usage: BillingUsage;
110
+ }[];
111
+ cache?: {
112
+ ttlMs?: number;
113
+ implicit?: true;
114
+ warming?: {
115
+ on: boolean;
116
+ stopReason?: CacheWarmStopReason;
117
+ };
118
+ };
76
119
  };
77
120
  /**
78
121
  * Read advisory input for request shaping, in landing order, without persisting
@@ -90,9 +133,9 @@ export declare function turnNotes(sessionId: string): readonly {
90
133
  */
91
134
  export declare function askRouting<Candidate extends RoutingCandidate>(input: AskRoutingInput<Candidate>): Promise<RoutingSelection<Candidate> | undefined>;
92
135
  /**
93
- * Report a vault request or turn-note event without waiting for routing. Only
94
- * contract fields are sent, and all accessor failures are ignored. Headers must
95
- * already be limited to rate-limit headers by the caller; values are not filtered
96
- * or redacted here.
136
+ * Report a vault request, billing result or turn-note event without waiting for
137
+ * routing. Only contract fields are sent, and all accessor failures are ignored.
138
+ * Headers must already be limited to rate-limit headers by the caller; values
139
+ * are not filtered or redacted here.
97
140
  */
98
141
  export declare function reportRouting(input: ReportRoutingInput): void;
@@ -3,11 +3,68 @@
3
3
  * shaping. Account ids are vault account ids, not local pool rows. Nothing is
4
4
  * persisted here; plugins on routes the runner does not serve get no turn notes.
5
5
  */
6
+ import { isCacheWarmStopReason, } from './cache-policy.js';
6
7
  import { routingHandle } from './handle.js';
7
- export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
+ export { CACHE_WARM_STOP_REASONS, isCacheWarmStopReason, reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
9
  function isObject(value) {
9
10
  return typeof value === 'object' && value !== null;
10
11
  }
12
+ function isNonEmptyString(value) {
13
+ return typeof value === 'string' && value.length > 0;
14
+ }
15
+ function billingCache(value) {
16
+ if (!isObject(value) || Array.isArray(value))
17
+ return;
18
+ const { ttlMs, implicit, warming } = value;
19
+ const cache = {};
20
+ // Conflicting lifetime claims cannot prove what the request cached.
21
+ if (!(ttlMs !== undefined && implicit !== undefined)) {
22
+ if (typeof ttlMs === 'number' && Number.isSafeInteger(ttlMs) && ttlMs > 0) {
23
+ cache.ttl_ms = ttlMs;
24
+ }
25
+ else if (implicit === true) {
26
+ cache.implicit = true;
27
+ }
28
+ }
29
+ if (isObject(warming) && !Array.isArray(warming)) {
30
+ const { on, stopReason } = warming;
31
+ if (typeof on === 'boolean') {
32
+ cache.warming = {
33
+ on,
34
+ ...(!on && isCacheWarmStopReason(stopReason)
35
+ ? { stop_reason: stopReason }
36
+ : {}),
37
+ };
38
+ }
39
+ }
40
+ return Object.keys(cache).length > 0 ? cache : undefined;
41
+ }
42
+ function billingUsage(value) {
43
+ if (!isObject(value) || Array.isArray(value))
44
+ return;
45
+ const usage = {};
46
+ for (const [inputKey, payloadKey] of [
47
+ ['input', 'input'],
48
+ ['output', 'output'],
49
+ ['cacheRead', 'cache_read'],
50
+ ['cacheWrite', 'cache_write'],
51
+ ['cacheWrite5m', 'cache_write_5m'],
52
+ ['cacheWrite1h', 'cache_write_1h'],
53
+ ['reasoning', 'reasoning'],
54
+ ]) {
55
+ const count = value[inputKey];
56
+ if (typeof count === 'number' &&
57
+ Number.isSafeInteger(count) &&
58
+ count >= 0) {
59
+ usage[payloadKey] = count;
60
+ }
61
+ }
62
+ const reasoningIncludedInOutput = value.reasoningIncludedInOutput;
63
+ if (typeof reasoningIncludedInOutput === 'boolean') {
64
+ usage.reasoning_included_in_output = reasoningIncludedInOutput;
65
+ }
66
+ return Object.keys(usage).length > 0 ? usage : undefined;
67
+ }
11
68
  /**
12
69
  * Read advisory input for request shaping, in landing order, without persisting
13
70
  * it. If no routing handle is available or the runner does not serve the route,
@@ -124,10 +181,10 @@ export async function askRouting(input) {
124
181
  }
125
182
  }
126
183
  /**
127
- * Report a vault request or turn-note event without waiting for routing. Only
128
- * contract fields are sent, and all accessor failures are ignored. Headers must
129
- * already be limited to rate-limit headers by the caller; values are not filtered
130
- * or redacted here.
184
+ * Report a vault request, billing result or turn-note event without waiting for
185
+ * routing. Only contract fields are sent, and all accessor failures are ignored.
186
+ * Headers must already be limited to rate-limit headers by the caller; values
187
+ * are not filtered or redacted here.
131
188
  */
132
189
  export function reportRouting(input) {
133
190
  try {
@@ -140,6 +197,80 @@ export function reportRouting(input) {
140
197
  let payload;
141
198
  if ('kind' in input) {
142
199
  switch (input.kind) {
200
+ case 'billing': {
201
+ const { attemptId, requestKind, credentialId, provider, model, outcome, accountId, providerRequestId, providerResponseId, userMessageId, status, attempt, chargeBasis, usage: inputUsage, usageByModel: inputUsageByModel, cache: inputCache, } = input;
202
+ if (!isNonEmptyString(attemptId) ||
203
+ !isNonEmptyString(credentialId) ||
204
+ !isNonEmptyString(provider) ||
205
+ !isNonEmptyString(model) ||
206
+ (requestKind !== 'primary' &&
207
+ requestKind !== 'title' &&
208
+ requestKind !== 'compaction' &&
209
+ requestKind !== 'generate' &&
210
+ requestKind !== 'keep_warm' &&
211
+ requestKind !== 'prime') ||
212
+ (outcome !== 'completed' &&
213
+ outcome !== 'cut' &&
214
+ outcome !== 'failed'))
215
+ return;
216
+ const usage = billingUsage(inputUsage);
217
+ const cache = billingCache(inputCache);
218
+ const usageByModel = [];
219
+ if (Array.isArray(inputUsageByModel)) {
220
+ for (const entry of inputUsageByModel) {
221
+ if (!isObject(entry) || Array.isArray(entry))
222
+ continue;
223
+ const modelUsed = entry.modelUsed;
224
+ if (!isNonEmptyString(modelUsed))
225
+ continue;
226
+ const modelUsage = billingUsage(entry.usage);
227
+ // Thalamus rejects the whole report when an entry has no usage
228
+ // object, so an entry without a valid reading is dropped.
229
+ if (!modelUsage)
230
+ continue;
231
+ usageByModel.push({ model_used: modelUsed, usage: modelUsage });
232
+ }
233
+ }
234
+ payload = {
235
+ kind: 'billing',
236
+ attempt_id: attemptId,
237
+ request_kind: requestKind,
238
+ credential_id: credentialId,
239
+ provider,
240
+ model,
241
+ outcome,
242
+ ...(isNonEmptyString(accountId) ? { account_id: accountId } : {}),
243
+ ...(isNonEmptyString(providerRequestId)
244
+ ? { provider_request_id: providerRequestId }
245
+ : {}),
246
+ ...(isNonEmptyString(providerResponseId)
247
+ ? { provider_response_id: providerResponseId }
248
+ : {}),
249
+ ...(isNonEmptyString(userMessageId)
250
+ ? { user_message_id: userMessageId }
251
+ : {}),
252
+ ...(typeof status === 'number' &&
253
+ Number.isInteger(status) &&
254
+ status >= 0
255
+ ? { status }
256
+ : {}),
257
+ ...(typeof attempt === 'number' &&
258
+ Number.isInteger(attempt) &&
259
+ attempt >= 1
260
+ ? { attempt }
261
+ : {}),
262
+ ...(chargeBasis === 'subscription_included' ||
263
+ chargeBasis === 'metered_api'
264
+ ? { charge_basis: chargeBasis }
265
+ : {}),
266
+ ...(usage ? { usage } : {}),
267
+ ...(usageByModel.length > 0
268
+ ? { usage_by_model: usageByModel }
269
+ : {}),
270
+ ...(cache ? { cache } : {}),
271
+ };
272
+ break;
273
+ }
143
274
  case 'turn_notes_supported': {
144
275
  const { model, supported } = input;
145
276
  if (typeof model !== 'string' ||
@@ -17,7 +17,7 @@ export declare class SetupCommandError extends Error {
17
17
  });
18
18
  }
19
19
  /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
20
- export declare function setupEnrollmentLine({ host, outcome, }: SetupHostEnrollment): string;
20
+ export declare function setupEnrollmentLine({ host, outcome, access, }: SetupHostEnrollment): string;
21
21
  /**
22
22
  * Remember which hosts a failed setup left connected to the vault, against the
23
23
  * thrown value. Only objects can carry a record; a thrown primitive is left as