@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +236 -26
- package/dist/agent-delete.d.ts +36 -12
- package/dist/agent-delete.js +213 -30
- package/dist/agents-store.d.ts +6 -2
- package/dist/agents-store.js +18 -5
- package/dist/agents.d.ts +8 -1
- package/dist/agents.js +14 -4
- package/dist/answer-json.d.ts +2 -2
- package/dist/answer-json.js +3 -4
- package/dist/api-only.d.ts +7 -10
- package/dist/api-only.js +9 -11
- package/dist/archil-routes.d.ts +1 -1
- package/dist/archil-routes.js +4 -3
- package/dist/browser-sessions.d.ts +56 -0
- package/dist/browser-sessions.js +117 -0
- package/dist/compute-cost.d.ts +101 -0
- package/dist/compute-cost.js +250 -0
- package/dist/computer-routes.d.ts +4 -15
- package/dist/computer-routes.js +6 -10
- package/dist/console/assets/index-D0mr9wfZ.css +1 -0
- package/dist/console/assets/index-D7G6o-1E.js +720 -0
- package/dist/console/index.html +2 -2
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +15 -5
- package/dist/eval-previous.d.ts +52 -0
- package/dist/eval-previous.js +164 -0
- package/dist/file-types.d.ts +2 -0
- package/dist/file-types.js +3 -1
- package/dist/harness.js +2 -1
- package/dist/import.js +4 -3
- package/dist/learn/check.d.ts +16 -4
- package/dist/learn/check.js +30 -26
- package/dist/learn/promote.d.ts +7 -1
- package/dist/learn/promote.js +47 -0
- package/dist/learn/repick.d.ts +43 -0
- package/dist/learn/repick.js +202 -0
- package/dist/learn/workflow-draft.d.ts +4 -0
- package/dist/learn/workflow-draft.js +10 -7
- package/dist/learned-workflow.d.ts +2 -0
- package/dist/learned-workflow.js +19 -2
- package/dist/learning-setting.d.ts +13 -0
- package/dist/learning-setting.js +23 -1
- package/dist/llms.txt +1 -1
- package/dist/openapi.js +180 -14
- package/dist/paid-calls.d.ts +17 -7
- package/dist/paid-calls.js +15 -9
- package/dist/run-launch.d.ts +2 -2
- package/dist/run-launch.js +2 -1
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/run-timeline-served.js +5 -3
- package/dist/run-usage.d.ts +125 -0
- package/dist/run-usage.js +394 -0
- package/dist/runner/adapter-loop.d.ts +4 -0
- package/dist/runner/adapter-loop.js +66 -21
- package/dist/runner/adapter-run-spec.d.ts +8 -3
- package/dist/runner/adapter-run-spec.js +13 -6
- package/dist/runner/big-writes.d.ts +33 -0
- package/dist/runner/big-writes.js +105 -0
- package/dist/runner/cli-run-spec.js +14 -6
- package/dist/runner/conformance/harness.d.ts +2 -0
- package/dist/runner/conformance/harness.js +18 -4
- package/dist/runner/feedback-round.d.ts +29 -1
- package/dist/runner/feedback-round.js +54 -3
- package/dist/runner/held.d.ts +4 -1
- package/dist/runner/journal-kinds.d.ts +3 -1
- package/dist/runner/learning-end.js +54 -18
- package/dist/runner/loop-contract.d.ts +3 -0
- package/dist/runner/metrics.d.ts +4 -0
- package/dist/runner/metrics.js +9 -0
- package/dist/runner/monid-run.js +2 -2
- package/dist/runner/promotion.js +8 -2
- package/dist/runner/reflect-hook.js +3 -2
- package/dist/runner/run-child-host.d.ts +15 -2
- package/dist/runner/run-child-host.js +24 -8
- package/dist/runner/run-child.js +3 -0
- package/dist/runner/save-slots.d.ts +9 -0
- package/dist/runner/save-slots.js +91 -0
- package/dist/runs-over-store.d.ts +3 -2
- package/dist/runs-over-store.js +9 -7
- package/dist/sdk/runs.d.ts +3 -4
- package/dist/sdk/runs.js +10 -7
- package/dist/sdk/runtimes.d.ts +19 -0
- package/dist/sdk/runtimes.js +23 -0
- package/dist/sdk/schema.d.ts +14 -8
- package/dist/sdk/schema.js +18 -6
- package/dist/server.d.ts +7 -3
- package/dist/server.js +223 -100
- package/dist/store/agent-body.d.ts +2 -3
- package/dist/store/agent-body.js +3 -2
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/journal/storage.js +1 -1
- package/dist/store/open.d.ts +1 -1
- package/dist/store/open.js +1 -1
- package/dist/store/postgres/migrations/0021_purged.sql +13 -0
- package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
- package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
- package/dist/store/schema.d.ts +20 -1
- package/dist/store/schema.js +60 -5
- package/dist/store/sqlite/connection.d.ts +4 -1
- package/dist/store/sqlite/connection.js +5 -0
- package/dist/store/sqlite/run-patch.d.ts +8 -3
- package/dist/store/sqlite/run-patch.js +15 -7
- package/dist/store/sqlite/store.d.ts +2 -1
- package/dist/store/sqlite/store.js +279 -68
- package/dist/store/sqlite/worker.d.ts +9 -0
- package/dist/store/sqlite/worker.js +18 -1
- package/dist/store/store.d.ts +149 -9
- package/dist/store/store.js +63 -0
- package/dist/store-reads/analytics.js +2 -1
- package/dist/store-reads/cap.d.ts +17 -7
- package/dist/store-reads/cap.js +54 -4
- package/dist/store-reads/decisions.d.ts +21 -0
- package/dist/store-reads/decisions.js +22 -0
- package/dist/store-reads/journal.d.ts +8 -2
- package/dist/store-reads/journal.js +27 -8
- package/dist/store-reads/learning.d.ts +1 -1
- package/dist/store-reads/learning.js +5 -2
- package/dist/store-reads/runs.js +2 -0
- package/dist/store-reads/stats.js +4 -2
- package/dist/store-view.d.ts +12 -1
- package/dist/store-view.js +98 -38
- package/dist/template-eval.d.ts +15 -1
- package/dist/template-eval.js +92 -13
- package/dist/templates.d.ts +1 -1
- package/dist/templates.js +4 -3
- package/dist/timeline/labels.js +17 -0
- package/dist/tool-list.js +1 -0
- package/dist/tools.d.ts +6 -2
- package/dist/tools.js +22 -1
- package/dist/trigger-targets.d.ts +28 -9
- package/dist/trigger-targets.js +19 -16
- package/dist/triggers.d.ts +2 -1
- package/dist/triggers.js +5 -2
- package/dist/validate.d.ts +4 -2
- package/dist/validate.js +13 -3
- package/dist/viewer-credential.d.ts +3 -4
- package/dist/viewer-credential.js +6 -4
- package/dist/web-fake.d.ts +25 -0
- package/dist/web-fake.js +38 -1
- package/dist/web-save.d.ts +75 -0
- package/dist/web-save.js +235 -0
- package/dist/workspace/archil-claim.d.ts +5 -2
- package/dist/workspace/archil-claim.js +5 -2
- package/dist/workspace/archil-disk.d.ts +10 -1
- package/dist/workspace/archil-disk.js +19 -1
- package/dist/workspace/archil.d.ts +3 -0
- package/dist/workspace/archil.js +101 -16
- package/dist/workspace/computer-for-claim.d.ts +19 -1
- package/dist/workspace/computer-for-claim.js +88 -20
- package/dist/workspace/computer-intervals.d.ts +26 -0
- package/dist/workspace/computer-intervals.js +58 -0
- package/dist/workspace/computer-janitor.d.ts +7 -3
- package/dist/workspace/computer-janitor.js +14 -6
- package/dist/workspace/computer-kept.d.ts +7 -2
- package/dist/workspace/computer-kept.js +9 -2
- package/dist/workspace/pieced.d.ts +14 -0
- package/dist/workspace/pieced.js +23 -0
- package/dist/workspace/resolve-computer.d.ts +7 -4
- package/dist/workspace/resolve-computer.js +21 -32
- package/dist/workspace/run-disk.js +32 -12
- package/dist/workspace/run-end-computers.d.ts +1 -0
- package/dist/workspace/run-end-computers.js +4 -1
- package/dist/workspace/run-workspace.d.ts +1 -1
- package/dist/workspace/run-workspace.js +11 -6
- package/package.json +10 -10
- package/templates/README.md +36 -7
- package/dist/console/assets/index-CTGegcKt.css +0 -1
- package/dist/console/assets/index-D1Se6mgG.js +0 -715
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { type BrowserSessionLine } from "./browser-sessions.js";
|
|
2
|
+
import { type CostBasis, type CostWords } from "./runner/metrics.js";
|
|
3
|
+
import type { RunLaunch } from "./run-launch.js";
|
|
4
|
+
import { type SignInReader } from "./run-view.js";
|
|
5
|
+
import { type ComputerIntervalRow, type Store } from "./store/index.js";
|
|
6
|
+
import { type ComputeResource, type ComputeUnit } from "./compute-cost.js";
|
|
7
|
+
import { type EntryLike } from "./timeline/index.js";
|
|
8
|
+
/** The meters a run's lines are on: the contract's `tokens` and `browser_time`, and this server's `tools` and
|
|
9
|
+
* `compute_time`. */
|
|
10
|
+
export type UsageMeter = "tokens" | "tools" | "browser_time" | "compute_time";
|
|
11
|
+
/** One line of a run's cost: one model, one charger or one browser provider on a meter. Which it is: `model` and
|
|
12
|
+
* `provider` on `tokens` (the model the requests were sent on; the provider they went to, named only when the server
|
|
13
|
+
* sent them there itself, null behind a gateway, whose upstream the server does not know), `charged_by` on `tools` (who
|
|
14
|
+
* charged for the calls) and `provider` beside it (the same name: the vendor that charges for a call is its provider),
|
|
15
|
+
* `provider` on `browser_time`; every other one null, and null where the record names none, never "". `quantity` in `unit`: tokens
|
|
16
|
+
* (input, cache read, cache write and output, as each request reported them), charges booked (one per paid call), or
|
|
17
|
+
* seconds of browser session time on this server's clock, unrounded; null when none was measured. `usd` and its words
|
|
18
|
+
* are the cost block's (CostWords): null when a charge is unknown, with `so_far_usd` and `unpriced` beside it;
|
|
19
|
+
* `upper_bound` when a cut request counts at its hold. Not the contract's UsageLine (GET /usage's, a sum over many
|
|
20
|
+
* runs by group): a line of one run. */
|
|
21
|
+
export type RunUsageLine = {
|
|
22
|
+
meter: UsageMeter;
|
|
23
|
+
model: string | null;
|
|
24
|
+
provider: string | null;
|
|
25
|
+
charged_by: string | null;
|
|
26
|
+
quantity: number | null;
|
|
27
|
+
unit: "token" | "call" | "second" | ComputeUnit;
|
|
28
|
+
basis: CostBasis;
|
|
29
|
+
/** On `compute_time`: the resource (vcpu, memory, gpu, disk), a GPU's type, the part of `quantity` no claim held (in
|
|
30
|
+
* no cost), and how many of its computers are still open, their time counted up to `measured_to`. */
|
|
31
|
+
resource?: ComputeResource;
|
|
32
|
+
gpu_type?: string | null;
|
|
33
|
+
unheld_quantity?: number | null;
|
|
34
|
+
open_computers?: number;
|
|
35
|
+
measured_to?: string;
|
|
36
|
+
requests?: number;
|
|
37
|
+
tokens?: {
|
|
38
|
+
input: number;
|
|
39
|
+
output: number;
|
|
40
|
+
cache_read: number;
|
|
41
|
+
cache_write: number;
|
|
42
|
+
};
|
|
43
|
+
unmetered_requests?: number;
|
|
44
|
+
not_metered_calls?: number;
|
|
45
|
+
} & CostWords;
|
|
46
|
+
/** Why a run has no lines: `running`, it is at work and its booking still moves; `not_booked`, its figure is not its
|
|
47
|
+
* booking's (an imported run's, a native or SDK run's harness's own, a CLI run whose model requests went past its proxy);
|
|
48
|
+
* `reopened`, a learning run a follow-up opened again, whose `cost.usd` is its first round's and whose booking can't be
|
|
49
|
+
* split by round. */
|
|
50
|
+
export type UsageReason = "running" | "not_booked" | "reopened";
|
|
51
|
+
export type RunUsage = {
|
|
52
|
+
run_id: string;
|
|
53
|
+
/** When the run ended: the moment its lines cover. Null while it is at work. A follow-up opens an ended run again
|
|
54
|
+
* (store/sqlite/run-patch.ts REOPEN_SET clears it), and its next end is a later one: a reader that keeps it beside the
|
|
55
|
+
* lines knows from a later read whether the run moved since. */
|
|
56
|
+
ended_at: string | null;
|
|
57
|
+
currency: "USD";
|
|
58
|
+
/** The lines joined by the one rule (costWordsOf): the run's `cost.usd`, with what is known of it when it is unknown
|
|
59
|
+
* (`so_far_usd`, `unpriced`) and `upper_bound` when it is a bound. Null with no lines. */
|
|
60
|
+
total: CostWords | null;
|
|
61
|
+
lines: RunUsageLine[] | null;
|
|
62
|
+
/** One record per browser session the run opened (browser-sessions.ts), for matching `browser_time` to the provider's
|
|
63
|
+
* own records by its session id; null exactly when `lines` is. */
|
|
64
|
+
browser_sessions: BrowserSessionLine[] | null;
|
|
65
|
+
/** One record per computer the run made (computerIntervalsOf), by when each was made; null exactly when `lines` is.
|
|
66
|
+
* Computer time is not priced: its cost is in no line and not in `total`. */
|
|
67
|
+
computer_intervals: ComputerIntervalLine[] | null;
|
|
68
|
+
reason: UsageReason | null;
|
|
69
|
+
};
|
|
70
|
+
/** One computer the run made through its provider (a sandbox, a desktop, a phone), as GET /runs/{run_id}/usage serves
|
|
71
|
+
* it: the provider (this server's id for it) and the provider's own id for the computer, its kind, what it was made with
|
|
72
|
+
* (its provider's own figures where it gave them, else what its create asked; null where neither says), when it was made,
|
|
73
|
+
* when its provider's delete answered ok (`ended_at`, null while none did: still running, or its delete failed or was
|
|
74
|
+
* never asked), whether the run's park kept it past its claim, and how much of its time a claim of the run booked
|
|
75
|
+
* (`booked_seconds`; the rest is time no claim held). */
|
|
76
|
+
export type ComputerIntervalLine = {
|
|
77
|
+
provider: string;
|
|
78
|
+
provider_id: string;
|
|
79
|
+
kind: string | null;
|
|
80
|
+
gpu: {
|
|
81
|
+
type: string | null;
|
|
82
|
+
count: number | null;
|
|
83
|
+
} | null;
|
|
84
|
+
cpus: number | null;
|
|
85
|
+
memory_mb: number | null;
|
|
86
|
+
disk_gb: number | null;
|
|
87
|
+
started_at: string;
|
|
88
|
+
ended_at: string | null;
|
|
89
|
+
kept: boolean;
|
|
90
|
+
booked_seconds: number;
|
|
91
|
+
};
|
|
92
|
+
/** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
|
|
93
|
+
export declare function computerIntervalsOf(rows: readonly ComputerIntervalRow[]): ComputerIntervalLine[];
|
|
94
|
+
/** A workflow decision's receipt as the lines read it (store-reads/decisions.ts): by its `decision_id`, which its
|
|
95
|
+
* request's booking names (`decision:<id>`), the model and provider that answered it, and how its cost was reached. */
|
|
96
|
+
export type DecisionReceiptLike = {
|
|
97
|
+
model?: unknown;
|
|
98
|
+
provider?: unknown;
|
|
99
|
+
cost_basis?: unknown;
|
|
100
|
+
usage?: unknown;
|
|
101
|
+
};
|
|
102
|
+
/** A run's lines from its journal `entries` (every conversation, in log order), its end-of-run turns already left out:
|
|
103
|
+
* its model requests and decisions by model (`tokens`), its paid calls by who charged (`tools`), its browser time by
|
|
104
|
+
* provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
|
|
105
|
+
* run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
|
|
106
|
+
* (its booking names the decision alone), which this server called itself. */
|
|
107
|
+
export declare function usageLinesOf(entries: readonly EntryLike[], launch?: Pick<RunLaunch, "model">, receipts?: ReadonlyMap<string, DecisionReceiptLike>, computers?: {
|
|
108
|
+
readonly rows: readonly ComputerIntervalRow[];
|
|
109
|
+
readonly at: number;
|
|
110
|
+
}): {
|
|
111
|
+
lines: RunUsageLine[];
|
|
112
|
+
total: CostWords;
|
|
113
|
+
};
|
|
114
|
+
/** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
|
|
115
|
+
* work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
|
|
116
|
+
* `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
|
|
117
|
+
* of the store (one moment): a follow-up that reopens the run between two reads can't put its requests under its end. */
|
|
118
|
+
export declare function runUsageOverStore(store: Store, runId: string): Promise<RunUsage | undefined>;
|
|
119
|
+
/** Run `runId`'s usage lines as served: each name taken from its record (a model, its provider, a tool's charger) through
|
|
120
|
+
* the run's cut, as its trace serves a model's name, since a decision provider or a tool names itself in what it
|
|
121
|
+
* returns. A run withheld (its sign-in can't be read back here) is refused (403), as its trace is. */
|
|
122
|
+
export declare function servedRunUsage(deps: {
|
|
123
|
+
serverSecrets: () => string[];
|
|
124
|
+
signIns?: SignInReader;
|
|
125
|
+
}, store: Store, runId: string): Promise<RunUsage | undefined>;
|
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
// A run's cost, line by line (GET /runs/{run_id}/usage): what one run used and what it cost, by the model its requests
|
|
2
|
+
// went to, by who charged for its paid tool calls, and by the browser provider whose session time it ran up. For the
|
|
3
|
+
// person who runs AgentRun and wants to know what a run cost and whose invoice each part lands on; anyone who accounts
|
|
4
|
+
// for runs reads the same lines. A quantity is as it was measured (tokens as reported, seconds unrounded), and its dollars
|
|
5
|
+
// are the figures the run's booking already holds, the ones `cost.usd` joins: nothing is priced here.
|
|
6
|
+
//
|
|
7
|
+
// Nothing is measured again. The lines are the run's booking (runner/metrics.ts bookedSpend) split by what each charge
|
|
8
|
+
// was: its model requests and its decisions by the model each was sent on (`tokens`), its paid tool calls by who charged
|
|
9
|
+
// for them (`tools`, with the calls that ran unpriced beside them; a decision Parallel answered on its own API is one,
|
|
10
|
+
// Parallel's, beside its web tools' calls), and its browser session time by its provider
|
|
11
|
+
// (`browser_time`, with the seconds its BROWSER_CHARGED records keep). Each part is read by bookedSpend itself, over the
|
|
12
|
+
// run's entries with only that part's requests left in, so a line's figure follows the one rule its sum does; and the
|
|
13
|
+
// lines join (costWordsOf) to `total`, which is the run's `cost.usd`: the same booking outside its end-of-run (learning)
|
|
14
|
+
// turn, as `cost.tools_usd` reads it (store-view.ts toolsUsdOverStore). That turn is the server's own work for the agent,
|
|
15
|
+
// not the run's task, and `cost.usd` leaves it out the same way. Unknown is never $0: a line whose charge is unknown says
|
|
16
|
+
// so (`usd` null, what is known beside it), and a run the server cannot split says why (`reason`) with no lines.
|
|
17
|
+
//
|
|
18
|
+
// Beside the lines, each computer the run made (`computer_intervals`, store computer_intervals): its provider's own id,
|
|
19
|
+
// what it was made with, when it was made and when its provider's delete answered ok (null while none did). Its time is on
|
|
20
|
+
// `compute_time` lines (compute-cost.ts), one per provider and resource (vCPU, memory, a GPU type, disk): the quantity is
|
|
21
|
+
// every second of each such computer of the run's at its figure (an open one's up to the read), and `usd` is what the
|
|
22
|
+
// run's ledger booked for it while a claim held it, so `total` stays the run's `cost.usd`. Time no claim held (a computer
|
|
23
|
+
// kept for a follow-up, one deleted after its run, one whose delete failed) is said apart (`unheld_quantity`) and costs
|
|
24
|
+
// nothing on the line or in `total`. A resource with no price is `unpriced`, its `usd` null.
|
|
25
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
26
|
+
import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
|
|
27
|
+
import { TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
28
|
+
import { browserSessionsOf } from "./browser-sessions.js";
|
|
29
|
+
import { BROWSER_CHARGED } from "./cap.js";
|
|
30
|
+
import { launchOf } from "./handed-values.js";
|
|
31
|
+
import { inReflect, reflectRanges } from "./runner/end-of-run.js";
|
|
32
|
+
import { journalRecords } from "./runner/journal-reader.js";
|
|
33
|
+
import { KINDS } from "./runner/journal-kinds.js";
|
|
34
|
+
import { bookedSpend, costBasisOf, costWordsOf } from "./runner/metrics.js";
|
|
35
|
+
import { unbookedCli } from "./store-reads/cap.js";
|
|
36
|
+
import { booksDecisions, chargedByParallel, decisionsOverStore, PARALLEL_CHARGER, receiptIdOf } from "./store-reads/decisions.js";
|
|
37
|
+
import { roundsOf } from "./store-reads/learning.js";
|
|
38
|
+
import { MODEL_PROVIDER } from "./model.js";
|
|
39
|
+
import { ApiError } from "./errors.js";
|
|
40
|
+
import { redacted } from "./key-refusal.js";
|
|
41
|
+
import { runCutValues } from "./run-cut.js";
|
|
42
|
+
import { WITHHELD_SIGN_IN } from "./run-view.js";
|
|
43
|
+
import { FINAL_STATES } from "./store/index.js";
|
|
44
|
+
import { COMPUTE_TOOL, COMPUTE_UNITS, computeTag, resourcesOf, unmetered } from "./compute-cost.js";
|
|
45
|
+
import { TOOL_UNMETERED } from "./timeline/index.js";
|
|
46
|
+
/** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
|
|
47
|
+
export function computerIntervalsOf(rows) {
|
|
48
|
+
return rows.map((row) => ({
|
|
49
|
+
provider: row.provider,
|
|
50
|
+
provider_id: row.providerId,
|
|
51
|
+
kind: row.kind,
|
|
52
|
+
gpu: row.gpuType === null && row.gpuCount === null ? null : { type: row.gpuType, count: row.gpuCount },
|
|
53
|
+
cpus: row.cpus,
|
|
54
|
+
memory_mb: row.memoryMb,
|
|
55
|
+
disk_gb: row.diskGb,
|
|
56
|
+
started_at: new Date(row.startedAt).toISOString(),
|
|
57
|
+
ended_at: row.endedAt === null ? null : new Date(row.endedAt).toISOString(),
|
|
58
|
+
kept: row.kept,
|
|
59
|
+
booked_seconds: row.bookedMs / 1000,
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
62
|
+
/** `entries` with the run's booked requests (runner.request and runner.turn) left in only where `keep` says so of its
|
|
63
|
+
* turn; every other entry (each session's key among them) kept, so bookedSpend reads that part alone. */
|
|
64
|
+
function onlyRequests(entries, turnOf, keep) {
|
|
65
|
+
return entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || keep(turnOf(e)));
|
|
66
|
+
}
|
|
67
|
+
/** Two bookings as one: their requests, tokens and figures summed; their cost parts kept for the join. */
|
|
68
|
+
function joined(parts) {
|
|
69
|
+
const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
70
|
+
const priced = { reported: 0, estimated: 0 };
|
|
71
|
+
let requests = 0;
|
|
72
|
+
let unmetered = 0;
|
|
73
|
+
for (const part of parts) {
|
|
74
|
+
requests += part.requests;
|
|
75
|
+
unmetered += part.unmetered;
|
|
76
|
+
priced.reported += part.priced.reported;
|
|
77
|
+
priced.estimated += part.priced.estimated;
|
|
78
|
+
for (const key of Object.keys(tokens))
|
|
79
|
+
tokens[key] += part.tokens[key];
|
|
80
|
+
}
|
|
81
|
+
return { parts: [...parts], requests, unmetered, tokens, priced };
|
|
82
|
+
}
|
|
83
|
+
const ORDER = { tokens: 0, tools: 1, browser_time: 2, compute_time: 3 };
|
|
84
|
+
const named = (value) => (typeof value === "string" && value !== "" ? value : null);
|
|
85
|
+
/** The provider a run's model requests on `model` went to, where this server sent them there itself: the run's own
|
|
86
|
+
* model's provider (its launch's), on a direct route. Null behind a gateway, whose upstream the server does not know,
|
|
87
|
+
* and for any other model (a workflow decision's), whose route the booking does not keep. */
|
|
88
|
+
function upstreamOf(model, launch) {
|
|
89
|
+
const pinned = launch?.model;
|
|
90
|
+
if (!pinned || !model || pinned.provider === MODEL_PROVIDER)
|
|
91
|
+
return null;
|
|
92
|
+
return model === pinned.modelId || model === `${pinned.provider}/${pinned.modelId}` ? pinned.provider : null;
|
|
93
|
+
}
|
|
94
|
+
/** A run's lines from its journal `entries` (every conversation, in log order), its end-of-run turns already left out:
|
|
95
|
+
* its model requests and decisions by model (`tokens`), its paid calls by who charged (`tools`), its browser time by
|
|
96
|
+
* provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
|
|
97
|
+
* run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
|
|
98
|
+
* (its booking names the decision alone), which this server called itself. */
|
|
99
|
+
export function usageLinesOf(entries, launch, receipts = new Map(), computers = { rows: [], at: 0 }) {
|
|
100
|
+
const conversation = (key) => entries.find((e) => e.kind === KINDS.sessionKey && e.data?.key === key)?.data;
|
|
101
|
+
const paidConv = Number(conversation(TOOL_SESSION)?.conversation ?? Number.NaN);
|
|
102
|
+
const conv = (e) => Number(e.conversationId);
|
|
103
|
+
const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
|
|
104
|
+
// A line is one meter, one name and, on `tokens`, one route: a model reached two ways (the run's own requests behind a
|
|
105
|
+
// gateway, a decision on its provider) is two lines, never one labelled with either's provider.
|
|
106
|
+
const keyOf = (group) => `${group.meter}\u0000${group.name ?? ""}\u0000${group.provider ?? ""}\u0000${group.tag ?? ""}`;
|
|
107
|
+
// Each booked request's group, by its turn: a model request's or a decision's, the model its runner.request was sent on;
|
|
108
|
+
// a paid charge's, who charged for it (`charged_by`), on browser_time when it is the browser's session time. A paid
|
|
109
|
+
// charge settled at its provider's own figure says so on its request (`reported`). A decision's request names the
|
|
110
|
+
// decision (`decision:<id>`): its receipt names the model and provider that answered it, and how its cost was reached.
|
|
111
|
+
// A decision Parallel answered on its own API (chargedByParallel) is a paid call Parallel charged at its list price, on
|
|
112
|
+
// Parallel's `tools` line beside its web tools' calls, not a model's tokens: it is on one line, never on both.
|
|
113
|
+
const groups = new Map();
|
|
114
|
+
const reported = new Set();
|
|
115
|
+
const estimated = new Set();
|
|
116
|
+
// A decision's tokens are its receipt's: its booking keeps its cost, with no usage (the cap books it at none).
|
|
117
|
+
const decisionTokens = new Map();
|
|
118
|
+
for (const e of entries) {
|
|
119
|
+
if (e.kind !== RUNNER_RECORDS.request)
|
|
120
|
+
continue;
|
|
121
|
+
const d = (e.data ?? {});
|
|
122
|
+
// A computer's time (compute-cost.ts) by its provider and resource (its tag); a browser's by its provider.
|
|
123
|
+
if (conv(e) === paidConv)
|
|
124
|
+
groups.set(turnOf(e), d.tool === COMPUTE_TOOL ? { meter: "compute_time", name: named(d.charged_by), tag: named(d.tag) } : { meter: d.tool === "browser" ? "browser_time" : "tools", name: named(d.charged_by) });
|
|
125
|
+
else if (named(d.model)?.startsWith("decision:")) {
|
|
126
|
+
const receipt = receipts.get(String(d.model).slice("decision:".length));
|
|
127
|
+
if (receipt && chargedByParallel(receipt)) {
|
|
128
|
+
groups.set(turnOf(e), { meter: "tools", name: PARALLEL_CHARGER });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
// A receipt that names no model leaves `model` null: its provider is said as the provider, never as a model.
|
|
132
|
+
groups.set(turnOf(e), receipt ? { meter: "tokens", name: named(receipt.model), provider: named(receipt.provider) } : { meter: "tokens", name: null, provider: null });
|
|
133
|
+
if (receipt?.cost_basis === "reported")
|
|
134
|
+
reported.add(turnOf(e));
|
|
135
|
+
else if (receipt?.cost_basis === "estimate")
|
|
136
|
+
estimated.add(turnOf(e));
|
|
137
|
+
const usage = (receipt?.usage ?? undefined);
|
|
138
|
+
const tokenCount = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
|
|
139
|
+
const [input, output] = [tokenCount(usage?.input_tokens), tokenCount(usage?.output_tokens)];
|
|
140
|
+
if (input !== undefined && output !== undefined)
|
|
141
|
+
decisionTokens.set(turnOf(e), { input, output });
|
|
142
|
+
}
|
|
143
|
+
else
|
|
144
|
+
groups.set(turnOf(e), { meter: "tokens", name: named(d.model), provider: upstreamOf(named(d.model), launch) });
|
|
145
|
+
if (d.reported === true)
|
|
146
|
+
reported.add(turnOf(e));
|
|
147
|
+
}
|
|
148
|
+
// A turn booked with no request of its own (an older record) is its session's: a model's with no name, a paid charge
|
|
149
|
+
// with no charger. A turn given back or never sent used nothing, and says nothing of how a line was priced.
|
|
150
|
+
const found = new Map();
|
|
151
|
+
const turnKeys = new Map();
|
|
152
|
+
const unused = new Set();
|
|
153
|
+
// Answered turns whose booking kept no usage: bookedSpend counts each among `unmetered`.
|
|
154
|
+
const noUsage = new Set();
|
|
155
|
+
for (const e of entries) {
|
|
156
|
+
if (e.kind !== RUNNER_RECORDS.request && e.kind !== RUNNER_RECORDS.turn)
|
|
157
|
+
continue;
|
|
158
|
+
const group = groups.get(turnOf(e)) ?? (conv(e) === paidConv ? { meter: "tools", name: null } : { meter: "tokens", name: null, provider: null });
|
|
159
|
+
if (!found.has(keyOf(group)))
|
|
160
|
+
found.set(keyOf(group), group);
|
|
161
|
+
turnKeys.set(turnOf(e), keyOf(group));
|
|
162
|
+
const d = (e.data ?? {});
|
|
163
|
+
if (e.kind === RUNNER_RECORDS.turn && (d.givenBack === true || d.unsent === true))
|
|
164
|
+
unused.add(turnOf(e));
|
|
165
|
+
else if (e.kind === RUNNER_RECORDS.turn && d.usage === undefined)
|
|
166
|
+
noUsage.add(turnOf(e));
|
|
167
|
+
}
|
|
168
|
+
// Browser seconds by provider, from the charges' own records on the root (BROWSER_CHARGED): the seconds each charge was
|
|
169
|
+
// for, as the browser_time meter of GET /usage counts them.
|
|
170
|
+
const seconds = new Map();
|
|
171
|
+
// Tool calls with no price, run outside the run's cost (an MCP tool its owner set none for, TOOL_UNMETERED), by who
|
|
172
|
+
// would charge for them, as GET /usage's `not_metered_calls` counts them.
|
|
173
|
+
const unpricedCalls = new Map();
|
|
174
|
+
for (const e of entries) {
|
|
175
|
+
const d = (e.data ?? {});
|
|
176
|
+
if (e.kind === TOOL_UNMETERED) {
|
|
177
|
+
const group = { meter: "tools", name: named(d.charged_by) };
|
|
178
|
+
unpricedCalls.set(keyOf(group), (unpricedCalls.get(keyOf(group)) ?? 0) + 1);
|
|
179
|
+
if (!found.has(keyOf(group)))
|
|
180
|
+
found.set(keyOf(group), group);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (e.kind !== BROWSER_CHARGED || d.tool !== "browser" || typeof d.seconds !== "number" || !Number.isFinite(d.seconds))
|
|
184
|
+
continue;
|
|
185
|
+
const group = { meter: "browser_time", name: named(d.charged_by) };
|
|
186
|
+
seconds.set(keyOf(group), (seconds.get(keyOf(group)) ?? 0) + d.seconds);
|
|
187
|
+
if (!found.has(keyOf(group)))
|
|
188
|
+
found.set(keyOf(group), group);
|
|
189
|
+
}
|
|
190
|
+
const lines = [];
|
|
191
|
+
/** What the ledger booked for each computer provider and resource (computeLinesOf), by its line's key. */
|
|
192
|
+
const computeBooked = new Map();
|
|
193
|
+
for (const group of found.values()) {
|
|
194
|
+
const key = keyOf(group);
|
|
195
|
+
const part = onlyRequests(entries, turnOf, (turn) => turnKeys.get(turn) === key);
|
|
196
|
+
// A `tools` line's part holds its charger's paid calls and, on Parallel's, the decisions Parallel charged.
|
|
197
|
+
const booked = joined(group.meter === "tokens" ? [bookedSpend(part, "model"), bookedSpend(part, "decisions")] : group.meter === "tools" ? [bookedSpend(part, "paid"), bookedSpend(part, "decisions")] : [bookedSpend(part, "paid")]);
|
|
198
|
+
if (group.meter === "compute_time") {
|
|
199
|
+
// A hold for a stretch names no resource (no tag) and books nothing: it is given back.
|
|
200
|
+
if (group.tag !== null && group.tag !== undefined)
|
|
201
|
+
computeBooked.set(computeKey(group.name ?? "", group.tag), booked);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const notMetered = unpricedCalls.get(key);
|
|
205
|
+
// A part whose every request was given back (never sent) used nothing: no line, unless calls ran on it unpriced.
|
|
206
|
+
if (booked.requests === 0 && group.meter !== "browser_time" && !notMetered)
|
|
207
|
+
continue;
|
|
208
|
+
const priced = booked.requests - booked.parts.reduce((sum, p) => sum + p.unpriced, 0);
|
|
209
|
+
const turns = [...turnKeys].filter(([turn, k]) => k === key && !unused.has(turn)).map(([turn]) => turn);
|
|
210
|
+
if (group.meter === "tokens") {
|
|
211
|
+
// A decision's tokens from its receipt, where it says them; the request then reported usage, so it is not unmetered.
|
|
212
|
+
const told = turns.filter((turn) => decisionTokens.has(turn));
|
|
213
|
+
const input = booked.tokens.input + told.reduce((sum, turn) => sum + decisionTokens.get(turn).input, 0);
|
|
214
|
+
const output = booked.tokens.output + told.reduce((sum, turn) => sum + decisionTokens.get(turn).output, 0);
|
|
215
|
+
const { cacheRead, cacheWrite } = booked.tokens;
|
|
216
|
+
const unmetered = Math.max(0, booked.unmetered - told.filter((turn) => noUsage.has(turn)).length);
|
|
217
|
+
// A decision's booking keeps no price table's mark: its receipt says how its cost was reached.
|
|
218
|
+
const priced = { reported: booked.priced.reported + turns.filter((turn) => reported.has(turn)).length, estimated: booked.priced.estimated + turns.filter((turn) => estimated.has(turn)).length };
|
|
219
|
+
lines.push({ meter: "tokens", model: group.name, provider: group.provider ?? null, charged_by: null, quantity: input + output + cacheRead + cacheWrite, unit: "token", basis: costBasisOf({ priced }), ...costWordsOf(booked.parts), requests: booked.requests, tokens: { input, output, cache_read: cacheRead, cache_write: cacheWrite }, unmetered_requests: unmetered });
|
|
220
|
+
}
|
|
221
|
+
else if (group.meter === "tools") {
|
|
222
|
+
// `reported` when every charge with a figure was settled at its provider's own (monid's answer says what it
|
|
223
|
+
// charged); `estimate` when any was settled at a price this server holds (an MCP tool's owner's, Parallel's, a
|
|
224
|
+
// Parallel decision's list price).
|
|
225
|
+
const basis = priced <= 0 ? "unpriced" : turns.every((turn) => reported.has(turn)) ? "reported" : "estimate";
|
|
226
|
+
// Calls that ran unpriced only: none booked, so nothing is charged on the line, by its owner's choice of no price.
|
|
227
|
+
const words = booked.requests === 0 ? { usd: 0 } : costWordsOf(booked.parts);
|
|
228
|
+
lines.push({ meter: "tools", model: null, provider: group.name, charged_by: group.name, quantity: booked.requests, unit: "call", basis, ...words, ...(notMetered ? { not_metered_calls: notMetered } : {}) });
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
const s = seconds.get(key);
|
|
232
|
+
// A browser's holds given back with no time charged (a call that held and used nothing, a provider priced at $0 with
|
|
233
|
+
// no charge record) used nothing: no line.
|
|
234
|
+
if (booked.requests === 0 && s === undefined)
|
|
235
|
+
continue;
|
|
236
|
+
// A browser provider whose time no charge booked (none, or each given back) still ran: its seconds with no figure.
|
|
237
|
+
const words = booked.requests === 0 ? { usd: null } : costWordsOf(booked.parts);
|
|
238
|
+
lines.push({ meter: "browser_time", model: null, provider: group.name, charged_by: null, quantity: s === undefined ? null : Math.round(s * 1e6) / 1e6, unit: "second", basis: priced > 0 ? "estimate" : "unpriced", ...words });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
lines.push(...computeLinesOf(computers.rows, computers.at, computeBooked));
|
|
242
|
+
// Each meter by its name (a model, a charger, a browser provider; none first), `tokens` then by its route's provider,
|
|
243
|
+
// `compute_time` then by its resource in compute-cost.ts's order and a GPU's type.
|
|
244
|
+
const sortKey = (line) => line.meter === "tokens"
|
|
245
|
+
? `${line.model ?? ""}\u0000${line.provider ?? ""}`
|
|
246
|
+
: line.meter === "tools"
|
|
247
|
+
? line.charged_by ?? ""
|
|
248
|
+
: line.meter === "compute_time"
|
|
249
|
+
? `${line.provider ?? ""}\u0000${RESOURCE_ORDER[line.resource ?? "vcpu"]}\u0000${line.gpu_type ?? ""}`
|
|
250
|
+
: line.provider ?? "";
|
|
251
|
+
lines.sort((a, b) => ORDER[a.meter] - ORDER[b.meter] || (sortKey(a) < sortKey(b) ? -1 : sortKey(a) > sortKey(b) ? 1 : 0));
|
|
252
|
+
// The join over the whole booking, never the lines' rounded figures: the same figure cost.usd is. A browser line whose
|
|
253
|
+
// time no charge booked is unknown beside it: the total is too, with the booking's figure as what is known.
|
|
254
|
+
const total = costWordsOf([bookedSpend(entries, "model"), bookedSpend(entries, "paid"), bookedSpend(entries, "decisions")]);
|
|
255
|
+
const unbooked = lines.filter((line) => line.usd === null && line.meter === "browser_time" && line.so_far_usd === undefined).length;
|
|
256
|
+
if (!unbooked)
|
|
257
|
+
return { lines, total };
|
|
258
|
+
const known = total.usd ?? total.so_far_usd ?? 0;
|
|
259
|
+
return { lines, total: { usd: null, so_far_usd: known, unpriced: (total.usd === null ? (total.unpriced ?? 0) : 0) + unbooked } };
|
|
260
|
+
}
|
|
261
|
+
/** A compute line's key: its provider and its resource's tag (computeTag). */
|
|
262
|
+
const computeKey = (provider, tag) => `${provider}\u0000${tag}`;
|
|
263
|
+
const RESOURCE_ORDER = { vcpu: 0, memory: 1, gpu: 2, disk: 3 };
|
|
264
|
+
/** Up to the millionth, as the browser's seconds are. */
|
|
265
|
+
const micro = (value) => Math.round(value * 1e6) / 1e6;
|
|
266
|
+
/** The run's `compute_time` lines: one per provider and resource of the computers it made (`rows`), each second of each at
|
|
267
|
+
* its figure, an open one's up to `at` (the read), and the part no claim held (its life less its booked time) apart in
|
|
268
|
+
* `unheld_quantity`. Its money is what the run's ledger booked for it (`booked`, by computeKey): `estimate` when any was;
|
|
269
|
+
* $0 for a provider that bills nothing; else `unpriced`, its usd null. A figure no one said makes its quantity null. */
|
|
270
|
+
function computeLinesOf(rows, at, booked) {
|
|
271
|
+
const sums = new Map();
|
|
272
|
+
for (const row of rows) {
|
|
273
|
+
const livedS = Math.max(0, (row.endedAt ?? at) - row.startedAt) / 1000;
|
|
274
|
+
const unheldS = Math.max(0, livedS - row.bookedMs / 1000);
|
|
275
|
+
for (const one of resourcesOf(row)) {
|
|
276
|
+
const key = computeKey(row.provider, computeTag(one));
|
|
277
|
+
const sum = sums.get(key) ?? { provider: row.provider, resource: one.resource, gpuType: one.gpuType, quantity: 0, unheld: 0, open: 0 };
|
|
278
|
+
sum.quantity = sum.quantity === null || one.perSecond === null ? null : sum.quantity + one.perSecond * livedS;
|
|
279
|
+
sum.unheld = sum.unheld === null || one.perSecond === null ? null : sum.unheld + one.perSecond * unheldS;
|
|
280
|
+
if (row.endedAt === null)
|
|
281
|
+
sum.open += 1;
|
|
282
|
+
sums.set(key, sum);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
// A booking whose computer has no row here (one made before this server kept them): its money, with no quantity.
|
|
286
|
+
for (const key of booked.keys()) {
|
|
287
|
+
if (sums.has(key))
|
|
288
|
+
continue;
|
|
289
|
+
const [provider = "", tag = ""] = key.split("\u0000");
|
|
290
|
+
const gpu = tag.startsWith("gpu:");
|
|
291
|
+
const resource = (gpu ? "gpu" : tag);
|
|
292
|
+
if (!Object.hasOwn(COMPUTE_UNITS, resource))
|
|
293
|
+
continue;
|
|
294
|
+
sums.set(key, { provider, resource, gpuType: gpu ? tag.slice("gpu:".length) : null, quantity: null, unheld: null, open: 0 });
|
|
295
|
+
}
|
|
296
|
+
return [...sums.entries()].map(([key, sum]) => {
|
|
297
|
+
const spend = booked.get(key);
|
|
298
|
+
const charged = spend !== undefined && spend.requests > 0;
|
|
299
|
+
const free = !charged && unmetered(sum.provider);
|
|
300
|
+
const words = charged ? costWordsOf(spend.parts) : free ? { usd: 0 } : { usd: null };
|
|
301
|
+
return {
|
|
302
|
+
meter: "compute_time", model: null, provider: sum.provider, charged_by: sum.provider,
|
|
303
|
+
quantity: sum.quantity === null ? null : micro(sum.quantity), unit: COMPUTE_UNITS[sum.resource], basis: charged || free ? "estimate" : "unpriced", ...words,
|
|
304
|
+
resource: sum.resource, gpu_type: sum.gpuType, unheld_quantity: sum.unheld === null ? null : micro(sum.unheld), open_computers: sum.open,
|
|
305
|
+
...(sum.open > 0 ? { measured_to: new Date(at).toISOString() } : {}),
|
|
306
|
+
};
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
/** The run's own browser sessions: those its job opened or charged (`job`, the journal less the end-of-run learning
|
|
310
|
+
* turn), each with its end read from the whole journal (`all`). The run's end lets its browsers go inside the learning
|
|
311
|
+
* turn's range (reflectRanges runs to the run's end), so an end read from `job` alone would be missing for a session
|
|
312
|
+
* released there. A session the learning turn opened is not the job's, as its cost is not. */
|
|
313
|
+
function jobSessions(job, all) {
|
|
314
|
+
const ends = new Map(browserSessionsOf(all).map((one) => [one.tag, one]));
|
|
315
|
+
return browserSessionsOf(job).map((one) => {
|
|
316
|
+
const whole = ends.get(one.tag);
|
|
317
|
+
if (one.ended_at !== null || !whole || whole.ended_at === null)
|
|
318
|
+
return one;
|
|
319
|
+
const { provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status } = whole;
|
|
320
|
+
return { ...one, provider: one.provider || whole.provider, provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status };
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
/** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
|
|
324
|
+
* work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
|
|
325
|
+
* `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
|
|
326
|
+
* of the store (one moment): a follow-up that reopens the run between two reads can't put its requests under its end. */
|
|
327
|
+
export async function runUsageOverStore(store, runId) {
|
|
328
|
+
return store.snapshot(async (snapshot) => {
|
|
329
|
+
const run = await snapshot.runs.get(runId);
|
|
330
|
+
if (!run)
|
|
331
|
+
return undefined;
|
|
332
|
+
const ended = FINAL_STATES.includes(run.state) && run.endedAt !== null ? new Date(run.endedAt).toISOString() : null;
|
|
333
|
+
const none = (reason) => ({ run_id: runId, ended_at: reason === "running" ? null : ended, currency: "USD", total: null, lines: null, browser_sessions: null, computer_intervals: null, reason });
|
|
334
|
+
if (!FINAL_STATES.includes(run.state))
|
|
335
|
+
return none("running");
|
|
336
|
+
const launch = await launchOf(snapshot, runId);
|
|
337
|
+
if (run.importedFrom || launch?.native || launch?.sdk)
|
|
338
|
+
return none("not_booked");
|
|
339
|
+
if ((await roundsOf(snapshot, runId)).length > 1)
|
|
340
|
+
return none("reopened");
|
|
341
|
+
const records = await journalRecords(snapshot.readJournal(runId), BACKGROUND_CONTEXT);
|
|
342
|
+
if (unbookedCli(records.entries))
|
|
343
|
+
return none("not_booked");
|
|
344
|
+
const turns = reflectRanges(records.submissions ?? [], records.entries);
|
|
345
|
+
const entries = records.entries.filter((entry) => !inReflect(turns, Number(entry.id)));
|
|
346
|
+
// A workflow's decision receipts, read only when it made a decision: the model and provider each was answered on.
|
|
347
|
+
const receipts = booksDecisions(entries) ? new Map((await decisionsOverStore(snapshot, runId, BACKGROUND_CONTEXT)).map((receipt) => [receiptIdOf(receipt), receipt])) : undefined;
|
|
348
|
+
// Its computers in the same snapshot, an open one's time counted up to now; a store that keeps none (a test's) reads
|
|
349
|
+
// as none made.
|
|
350
|
+
const rows = snapshot.computerIntervals ? await snapshot.computerIntervals.forRun(runId) : [];
|
|
351
|
+
const { lines, total } = usageLinesOf(entries, launch, receipts, { rows, at: Date.now() });
|
|
352
|
+
const computers = computerIntervalsOf(rows);
|
|
353
|
+
return { run_id: runId, ended_at: ended, currency: "USD", total, lines, browser_sessions: jobSessions(entries, records.entries), computer_intervals: computers, reason: null };
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/** Run `runId`'s usage lines as served: each name taken from its record (a model, its provider, a tool's charger) through
|
|
357
|
+
* the run's cut, as its trace serves a model's name, since a decision provider or a tool names itself in what it
|
|
358
|
+
* returns. A run withheld (its sign-in can't be read back here) is refused (403), as its trace is. */
|
|
359
|
+
export async function servedRunUsage(deps, store, runId) {
|
|
360
|
+
if ((await runCutValues(deps, store, runId)) === "unreadable")
|
|
361
|
+
throw new ApiError("forbidden", WITHHELD_SIGN_IN);
|
|
362
|
+
const usage = await runUsageOverStore(store, runId);
|
|
363
|
+
// The cut after the read: it only grows, so it holds every value the read could have seen.
|
|
364
|
+
const cut = await runCutValues(deps, store, runId);
|
|
365
|
+
if (cut === "unreadable")
|
|
366
|
+
throw new ApiError("forbidden", WITHHELD_SIGN_IN);
|
|
367
|
+
if (!usage?.lines)
|
|
368
|
+
return usage;
|
|
369
|
+
const said = (text) => (text === null ? null : redacted(text, cut.values));
|
|
370
|
+
// A browser session's words too, every one its records keep: its provider names it, and the provider's record says the rest.
|
|
371
|
+
const session = (one) => ({
|
|
372
|
+
...one,
|
|
373
|
+
provider: redacted(one.provider, cut.values),
|
|
374
|
+
tag: redacted(one.tag, cut.values),
|
|
375
|
+
provider_session_id: said(one.provider_session_id),
|
|
376
|
+
started_at: said(one.started_at),
|
|
377
|
+
ended_at: said(one.ended_at),
|
|
378
|
+
release_reason: said(one.release_reason),
|
|
379
|
+
provider_record: one.provider_record && { ...one.provider_record, started_at: said(one.provider_record.started_at), ended_at: said(one.provider_record.ended_at) },
|
|
380
|
+
});
|
|
381
|
+
return {
|
|
382
|
+
...usage,
|
|
383
|
+
lines: usage.lines.map((line) => ({ ...line, model: said(line.model), provider: said(line.provider), charged_by: said(line.charged_by), ...(line.gpu_type === undefined ? {} : { gpu_type: said(line.gpu_type) }) })),
|
|
384
|
+
browser_sessions: usage.browser_sessions && usage.browser_sessions.map(session),
|
|
385
|
+
// A computer's words too: its provider's id for it is the provider's, which a run's own tools can name.
|
|
386
|
+
computer_intervals: usage.computer_intervals && usage.computer_intervals.map((one) => ({
|
|
387
|
+
...one,
|
|
388
|
+
provider: redacted(one.provider, cut.values),
|
|
389
|
+
provider_id: redacted(one.provider_id, cut.values),
|
|
390
|
+
kind: said(one.kind),
|
|
391
|
+
gpu: one.gpu && { ...one.gpu, type: said(one.gpu.type) },
|
|
392
|
+
})),
|
|
393
|
+
};
|
|
394
|
+
}
|
|
@@ -319,6 +319,10 @@ export interface RunLedger {
|
|
|
319
319
|
/** The store's flush (what the runner's flush before a side effect runs): a record a tool writes during its call that
|
|
320
320
|
* must be on disk before the call's next step leaves the box (a browser session's open, before its vendor is asked). */
|
|
321
321
|
flush(): Promise<void>;
|
|
322
|
+
/** Whether the run's cap can judge a paid step now. False while the run's spec is built (its cap is the spec's): a paid
|
|
323
|
+
* step asked then waits for the spec, so a step the build itself waits on (a computer's hold before its create,
|
|
324
|
+
* compute-cost.ts) is not asked until this is true. Absent: it always can. */
|
|
325
|
+
judges?(): boolean;
|
|
322
326
|
}
|
|
323
327
|
/** pi's retry of a model request that failed in a way it retries (a provider's 429, overload or 5xx, a dropped connection,
|
|
324
328
|
* a stream cut mid-answer): up to 8 more attempts, 2s doubling to at most 30s apart (about two and a half minutes in all),
|