@qlairoslabs/acp-client 0.4.3 → 0.6.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.
- package/CHANGELOG-metering.md +288 -0
- package/README.md +15 -5
- package/package.json +6 -3
- package/src/agent-session.ts +431 -17
- package/src/client.ts +179 -50
- package/src/controller.ts +41 -0
- package/src/degraded/pty-client.ts +22 -14
- package/src/degraded/pty-transport.ts +54 -19
- package/src/index.ts +156 -0
- package/src/launcher.ts +86 -0
- package/src/metering/catalog/build.ts +285 -0
- package/src/metering/catalog/index.ts +243 -0
- package/src/metering/catalog/live.ts +171 -0
- package/src/metering/catalog/models-dev.catalog.json +8797 -0
- package/src/metering/catalog/models-dev.meta.json +6 -0
- package/src/metering/categories.ts +129 -0
- package/src/metering/certification.ts +86 -0
- package/src/metering/context.ts +134 -0
- package/src/metering/delta.ts +108 -0
- package/src/metering/engine.ts +991 -0
- package/src/metering/money.ts +356 -0
- package/src/metering/opencode/channel.ts +389 -0
- package/src/metering/opencode/index.ts +159 -0
- package/src/metering/opencode/plugin.js +90 -0
- package/src/metering/opencode/profile.ts +159 -0
- package/src/metering/pricing.ts +285 -0
- package/src/metering/provider.ts +121 -0
- package/src/metering/rating.ts +349 -0
- package/src/metering/record.ts +274 -0
- package/src/metering/state.ts +421 -0
- package/src/metering/usage.ts +72 -0
- package/src/transport/acp-transport.ts +78 -41
- package/src/types.ts +28 -5
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// Building the managed OpenCode profile that loads the metering plugin.
|
|
2
|
+
//
|
|
3
|
+
// `OPENCODE_CONFIG` points the harness at a single config file, and a config's `plugin`
|
|
4
|
+
// array accepts absolute paths — verified against opencode 1.18.29. That is what lets the
|
|
5
|
+
// plugin load without writing into the consumer's repository, which a library has no
|
|
6
|
+
// business doing.
|
|
7
|
+
//
|
|
8
|
+
// The managed config MERGES the user's existing config rather than replacing it.
|
|
9
|
+
// `OPENCODE_CONFIG` is a replacement, so a naive temp file would silently drop their model
|
|
10
|
+
// choice, custom providers, and everything else — metering must not change which model
|
|
11
|
+
// answers. Credentials are unaffected either way: OpenCode keeps them in its data
|
|
12
|
+
// directory, not its config.
|
|
13
|
+
|
|
14
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
15
|
+
import { tmpdir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
|
|
18
|
+
/** Where OpenCode looks for a user config, in the order it resolves them. */
|
|
19
|
+
function userConfigCandidates(): string[] {
|
|
20
|
+
const home = process.env.HOME ?? "";
|
|
21
|
+
const configHome = process.env.XDG_CONFIG_HOME ?? join(home, ".config");
|
|
22
|
+
return [
|
|
23
|
+
process.env.OPENCODE_CONFIG ?? "",
|
|
24
|
+
join(configHome, "opencode", "opencode.jsonc"),
|
|
25
|
+
join(configHome, "opencode", "opencode.json"),
|
|
26
|
+
].filter((path) => path.length > 0);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Parse a possibly-JSONC config.
|
|
31
|
+
*
|
|
32
|
+
* Plain JSON is tried first, because that is what most configs are and it needs no
|
|
33
|
+
* rewriting at all. Only if that fails are comments and trailing commas stripped, and the
|
|
34
|
+
* stripping is string-aware: a naive regex mangles `"path": "a//b"` and anything
|
|
35
|
+
* containing a comment marker inside a string value.
|
|
36
|
+
*/
|
|
37
|
+
function parseJsonc(text: string): Record<string, unknown> | null {
|
|
38
|
+
const accept = (value: unknown): Record<string, unknown> | null =>
|
|
39
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
40
|
+
? (value as Record<string, unknown>)
|
|
41
|
+
: null;
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
return accept(JSON.parse(text));
|
|
45
|
+
} catch {
|
|
46
|
+
// Fall through to comment stripping.
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let cleaned = "";
|
|
50
|
+
let inString = false;
|
|
51
|
+
let escaped = false;
|
|
52
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
53
|
+
const char = text[index]!;
|
|
54
|
+
if (inString) {
|
|
55
|
+
cleaned += char;
|
|
56
|
+
if (escaped) escaped = false;
|
|
57
|
+
else if (char === "\\") escaped = true;
|
|
58
|
+
else if (char === '"') inString = false;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (char === '"') {
|
|
62
|
+
inString = true;
|
|
63
|
+
cleaned += char;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (char === "/" && text[index + 1] === "/") {
|
|
67
|
+
while (index < text.length && text[index] !== "\n") index += 1;
|
|
68
|
+
cleaned += "\n";
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (char === "/" && text[index + 1] === "*") {
|
|
72
|
+
const end = text.indexOf("*/", index + 2);
|
|
73
|
+
index = end === -1 ? text.length : end + 1;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
cleaned += char;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
return accept(JSON.parse(cleaned.replace(/,(\s*[}\]])/g, "$1")));
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface ManagedProfile {
|
|
87
|
+
/** Absolute path to pass as OPENCODE_CONFIG. */
|
|
88
|
+
readonly configPath: string;
|
|
89
|
+
/** True when an existing user config was found and carried forward. */
|
|
90
|
+
readonly mergedUserConfig: boolean;
|
|
91
|
+
/** Remove the temporary profile directory. */
|
|
92
|
+
cleanup(): Promise<void>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface ManagedProfileOptions {
|
|
96
|
+
/**
|
|
97
|
+
* Called when a user config exists but could not be parsed.
|
|
98
|
+
*
|
|
99
|
+
* OPENCODE_CONFIG replaces the user's config, so proceeding without theirs silently
|
|
100
|
+
* changes which model answers. The caller decides whether that is acceptable.
|
|
101
|
+
*/
|
|
102
|
+
readonly onUnreadableConfig?: (path: string) => void;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Write a managed config that adds the metering plugin to the user's own settings.
|
|
107
|
+
*
|
|
108
|
+
* The plugin is appended to any existing `plugin` entries rather than replacing them: a
|
|
109
|
+
* consumer's plugins are theirs, and silently disabling them to meter would be a worse
|
|
110
|
+
* bug than not metering.
|
|
111
|
+
*/
|
|
112
|
+
export async function writeManagedProfile(
|
|
113
|
+
pluginPath: string,
|
|
114
|
+
options: ManagedProfileOptions = {},
|
|
115
|
+
): Promise<ManagedProfile> {
|
|
116
|
+
let base: Record<string, unknown> = {};
|
|
117
|
+
let mergedUserConfig = false;
|
|
118
|
+
|
|
119
|
+
for (const candidate of userConfigCandidates()) {
|
|
120
|
+
let text: string;
|
|
121
|
+
try {
|
|
122
|
+
text = await readFile(candidate, "utf8");
|
|
123
|
+
} catch {
|
|
124
|
+
continue; // Missing: a user with no config is normal.
|
|
125
|
+
}
|
|
126
|
+
const parsed = parseJsonc(text);
|
|
127
|
+
if (parsed) {
|
|
128
|
+
base = parsed;
|
|
129
|
+
mergedUserConfig = true;
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
// Present but unparseable. Dropping it silently would change which model answers,
|
|
133
|
+
// so the caller is told rather than left to wonder.
|
|
134
|
+
options.onUnreadableConfig?.(candidate);
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const existing = Array.isArray(base.plugin) ? (base.plugin as unknown[]) : [];
|
|
139
|
+
const config = {
|
|
140
|
+
...base,
|
|
141
|
+
$schema: base.$schema ?? "https://opencode.ai/config.json",
|
|
142
|
+
plugin: [...existing.filter((entry) => entry !== pluginPath), pluginPath],
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const directory = await mkdtemp(join(tmpdir(), "acp-opencode-profile-"));
|
|
146
|
+
const configPath = join(directory, "opencode.json");
|
|
147
|
+
await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
148
|
+
return {
|
|
149
|
+
configPath,
|
|
150
|
+
mergedUserConfig,
|
|
151
|
+
// The profile lives in the OS temp dir; leaving one behind per session is a slow leak.
|
|
152
|
+
cleanup: () => rm(directory, { recursive: true, force: true }),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Absolute path of the plugin file shipped with the library. */
|
|
157
|
+
export function meteringPluginPath(): string {
|
|
158
|
+
return join(import.meta.dir, "plugin.js");
|
|
159
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
// Pricing policy types and validation. See 9-6-SPEC-metering.md §7.
|
|
2
|
+
//
|
|
3
|
+
// A pricing POLICY is everything the library froze before dispatching a rating unit: the
|
|
4
|
+
// catalog identity it came from, which provider/model keys were actually matched, which
|
|
5
|
+
// categories that model even uses, and every schedule that could apply. Exactly one
|
|
6
|
+
// schedule is selected AFTER the operation, from recorded billing facts — never by
|
|
7
|
+
// fetching a new price, and never by picking arbitrarily when the choice is ambiguous.
|
|
8
|
+
|
|
9
|
+
import { TOKEN_CATEGORIES, type TokenCategory } from "./categories.ts";
|
|
10
|
+
import { isValidMoney, type TokenUnitPrice } from "./money.ts";
|
|
11
|
+
|
|
12
|
+
// The category set is defined in ./categories.ts so pricing, rating, state and the engine
|
|
13
|
+
// cannot drift apart. Re-exported here because it is part of this module's public surface.
|
|
14
|
+
export { TOKEN_CATEGORIES, type TokenCategory };
|
|
15
|
+
|
|
16
|
+
/** Applicability is independent from whether a price happens to be present. */
|
|
17
|
+
export type CategoryApplicability = "applicable" | "not_applicable" | "unknown";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Immutable identity of the price data. A record engraves this so its cost can be
|
|
21
|
+
* recomputed without consulting the library's current catalog.
|
|
22
|
+
*/
|
|
23
|
+
export type PricingSource =
|
|
24
|
+
| {
|
|
25
|
+
readonly kind: "models.dev";
|
|
26
|
+
/** Immutable upstream Git commit used to produce the artifact. */
|
|
27
|
+
readonly commit: string;
|
|
28
|
+
/** SHA-256 of the exact generated catalog artifact shipped by the library. */
|
|
29
|
+
readonly artifactSha256: string;
|
|
30
|
+
/** When the shipped artifact was generated (epoch ms). */
|
|
31
|
+
readonly generatedAt: number;
|
|
32
|
+
}
|
|
33
|
+
| {
|
|
34
|
+
/**
|
|
35
|
+
* Prices fetched at runtime rather than shipped.
|
|
36
|
+
*
|
|
37
|
+
* Distinct from `models.dev` because that shape promises an immutable upstream
|
|
38
|
+
* commit, and a live fetch has verified none — the digest and the fetch time are
|
|
39
|
+
* what this run can honestly assert about the prices it used.
|
|
40
|
+
*/
|
|
41
|
+
readonly kind: "models.dev_live";
|
|
42
|
+
/** SHA-256 of the catalog built from the fetched payload. */
|
|
43
|
+
readonly artifactSha256: string;
|
|
44
|
+
/** When the payload was fetched (epoch ms). */
|
|
45
|
+
readonly fetchedAt: number;
|
|
46
|
+
}
|
|
47
|
+
| {
|
|
48
|
+
readonly kind: "consumer_override";
|
|
49
|
+
/** Stable identifier meaningful to the consumer, not a mutable display label. */
|
|
50
|
+
readonly version: string;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* When the prices behind a source were captured, in epoch ms.
|
|
55
|
+
*
|
|
56
|
+
* A consumer asking "how old is this number" should not have to know which variant it is
|
|
57
|
+
* holding. Returns null for a consumer override, whose freshness only the consumer knows.
|
|
58
|
+
*/
|
|
59
|
+
export function pricingCapturedAt(source: PricingSource): number | null {
|
|
60
|
+
switch (source.kind) {
|
|
61
|
+
case "models.dev":
|
|
62
|
+
return source.generatedAt;
|
|
63
|
+
case "models.dev_live":
|
|
64
|
+
return source.fetchedAt;
|
|
65
|
+
case "consumer_override":
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface CacheInputConvention {
|
|
71
|
+
readonly cachedRead: "included_in_input" | "excluded_from_input";
|
|
72
|
+
readonly cachedWrite: "included_in_input" | "excluded_from_input";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* How a harness's separately-reported reasoning tokens are charged.
|
|
77
|
+
*
|
|
78
|
+
* The counterpart to `cacheInputConvention` for the output side, and the same trap: a
|
|
79
|
+
* harness can report `thoughtTokens` as a disjoint counter while the provider bills them
|
|
80
|
+
* at the ordinary output rate. Pricing them at a separate rate — or refusing to price
|
|
81
|
+
* them — both get the total wrong.
|
|
82
|
+
*
|
|
83
|
+
* `billed_as_output` applies the schedule's OUTPUT unit price to thought tokens, and
|
|
84
|
+
* engraves that price, so a record shows exactly what rate was applied.
|
|
85
|
+
*/
|
|
86
|
+
export type ThoughtConvention = "separate_price" | "billed_as_output";
|
|
87
|
+
|
|
88
|
+
export interface PricingSchedule {
|
|
89
|
+
/** Stable identifier for this schedule within its policy. */
|
|
90
|
+
readonly tier: string;
|
|
91
|
+
/** Machine-evaluable catalog conditions selecting this schedule. */
|
|
92
|
+
readonly conditions: readonly PricingCondition[];
|
|
93
|
+
/** Provider/harness counter convention used to avoid pricing cached input twice. */
|
|
94
|
+
readonly cacheInputConvention: CacheInputConvention;
|
|
95
|
+
/**
|
|
96
|
+
* How separately-reported reasoning tokens are charged. Defaults to `separate_price`,
|
|
97
|
+
* which requires a `thought` unit price and otherwise makes rating unavailable.
|
|
98
|
+
*/
|
|
99
|
+
readonly thoughtConvention?: ThoughtConvention;
|
|
100
|
+
readonly input: TokenUnitPrice;
|
|
101
|
+
readonly output: TokenUnitPrice;
|
|
102
|
+
readonly cachedRead?: TokenUnitPrice;
|
|
103
|
+
readonly cachedWrite?: TokenUnitPrice;
|
|
104
|
+
readonly thought?: TokenUnitPrice;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export type PricingCondition =
|
|
108
|
+
| { readonly kind: "default" }
|
|
109
|
+
| { readonly kind: "context_tokens_at_least"; readonly tokens: number }
|
|
110
|
+
| { readonly kind: "service_tier"; readonly value: string }
|
|
111
|
+
| { readonly kind: "batch"; readonly value: boolean }
|
|
112
|
+
| {
|
|
113
|
+
/** Versioned consumer condition for a schedule core does not model natively. */
|
|
114
|
+
readonly kind: "consumer";
|
|
115
|
+
readonly name: string;
|
|
116
|
+
readonly value: string;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export interface PricingPolicy {
|
|
120
|
+
readonly source: PricingSource;
|
|
121
|
+
/** Provider and model keys actually selected from the source. */
|
|
122
|
+
readonly providerId: string;
|
|
123
|
+
readonly modelId: string;
|
|
124
|
+
/** Applicability is independent from whether a price happens to be present. */
|
|
125
|
+
readonly categoryApplicability: Readonly<Record<TokenCategory, CategoryApplicability>>;
|
|
126
|
+
/**
|
|
127
|
+
* When this model's catalog entry was last changed upstream (ISO date, e.g.
|
|
128
|
+
* "2026-03-13"), when the source records it.
|
|
129
|
+
*
|
|
130
|
+
* Distinct from the source timestamp: that says when WE captured the catalog, this says
|
|
131
|
+
* how current the data itself is. A freshly fetched catalog can still carry a
|
|
132
|
+
* year-old price.
|
|
133
|
+
*/
|
|
134
|
+
readonly modelLastUpdated?: string;
|
|
135
|
+
readonly schedules: readonly PricingSchedule[];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface PricingContext {
|
|
139
|
+
readonly scope: "operation" | "inference";
|
|
140
|
+
readonly agentSessionId: string;
|
|
141
|
+
readonly internalSessionId: string | null;
|
|
142
|
+
readonly operationId: string;
|
|
143
|
+
readonly inferenceId?: string;
|
|
144
|
+
readonly adapterId: string;
|
|
145
|
+
readonly providerId: string | null;
|
|
146
|
+
readonly model: string | null;
|
|
147
|
+
readonly operationKind: string;
|
|
148
|
+
readonly at: number;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export type PricingResolver = (
|
|
152
|
+
context: PricingContext,
|
|
153
|
+
) => PricingPolicy | null | Promise<PricingPolicy | null>;
|
|
154
|
+
|
|
155
|
+
/** `false` means the consumer intentionally wants no local rating (§7). */
|
|
156
|
+
export type PricingConfiguration = PricingResolver | false;
|
|
157
|
+
|
|
158
|
+
export type PolicyValidation =
|
|
159
|
+
| { readonly ok: true }
|
|
160
|
+
| { readonly ok: false; readonly reason: string };
|
|
161
|
+
|
|
162
|
+
function isUnitPrice(value: unknown): value is TokenUnitPrice {
|
|
163
|
+
if (typeof value !== "object" || value === null) return false;
|
|
164
|
+
const price = value as TokenUnitPrice;
|
|
165
|
+
return (
|
|
166
|
+
// isValidMoney also enforces the canonical decimal form, so a syntactically
|
|
167
|
+
// string-shaped amount like "1e-6" is rejected at preflight rather than at rating.
|
|
168
|
+
isValidMoney(price) &&
|
|
169
|
+
Number.isSafeInteger(price.perTokens) &&
|
|
170
|
+
price.perTokens > 0
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The unit price a schedule applies to a category, or undefined when it has none.
|
|
176
|
+
*
|
|
177
|
+
* The single source of truth for that mapping. It used to be duplicated between
|
|
178
|
+
* validation and rating, and the copies drifted the moment `billed_as_output` was added.
|
|
179
|
+
*/
|
|
180
|
+
export function unitPriceFor(
|
|
181
|
+
schedule: PricingSchedule,
|
|
182
|
+
category: TokenCategory,
|
|
183
|
+
): TokenUnitPrice | undefined {
|
|
184
|
+
switch (category) {
|
|
185
|
+
case "input":
|
|
186
|
+
return schedule.input;
|
|
187
|
+
case "output":
|
|
188
|
+
return schedule.output;
|
|
189
|
+
case "cached_read":
|
|
190
|
+
return schedule.cachedRead;
|
|
191
|
+
case "cached_write":
|
|
192
|
+
return schedule.cachedWrite;
|
|
193
|
+
case "thought":
|
|
194
|
+
// Reasoning billed at the ordinary output rate is still priced — by the output
|
|
195
|
+
// price, which is what reproduces the provider's own figure.
|
|
196
|
+
if (schedule.thoughtConvention === "billed_as_output") return schedule.output;
|
|
197
|
+
return schedule.thought;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Categories a schedule carries a price for, in TokenCategory terms. */
|
|
202
|
+
export function pricedCategories(schedule: PricingSchedule): ReadonlySet<TokenCategory> {
|
|
203
|
+
const priced = new Set<TokenCategory>();
|
|
204
|
+
for (const category of TOKEN_CATEGORIES) {
|
|
205
|
+
if (unitPriceFor(schedule, category)) priced.add(category);
|
|
206
|
+
}
|
|
207
|
+
return priced;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Validate a resolved policy before it is frozen onto a rating unit.
|
|
212
|
+
*
|
|
213
|
+
* Enforces the invariants §7 states as hard errors rather than warnings: one currency per
|
|
214
|
+
* schedule, and every category the policy declares applicable actually carries a price. A
|
|
215
|
+
* schedule that silently omits an applicable category would drop real cost from the total.
|
|
216
|
+
*/
|
|
217
|
+
export function validatePricingPolicy(policy: PricingPolicy): PolicyValidation {
|
|
218
|
+
if (typeof policy?.providerId !== "string" || policy.providerId.length === 0) {
|
|
219
|
+
return { ok: false, reason: "policy has no providerId" };
|
|
220
|
+
}
|
|
221
|
+
if (typeof policy.modelId !== "string" || policy.modelId.length === 0) {
|
|
222
|
+
return { ok: false, reason: "policy has no modelId" };
|
|
223
|
+
}
|
|
224
|
+
if (!Array.isArray(policy.schedules) || policy.schedules.length === 0) {
|
|
225
|
+
return { ok: false, reason: `policy ${policy.providerId}/${policy.modelId} has no schedules` };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
for (const category of TOKEN_CATEGORIES) {
|
|
229
|
+
const applicability = policy.categoryApplicability?.[category];
|
|
230
|
+
if (applicability !== "applicable" && applicability !== "not_applicable" && applicability !== "unknown") {
|
|
231
|
+
return { ok: false, reason: `categoryApplicability.${category} is missing or invalid` };
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const seenTiers = new Set<string>();
|
|
236
|
+
for (const schedule of policy.schedules) {
|
|
237
|
+
if (typeof schedule?.tier !== "string" || schedule.tier.length === 0) {
|
|
238
|
+
return { ok: false, reason: "schedule has no tier identifier" };
|
|
239
|
+
}
|
|
240
|
+
if (seenTiers.has(schedule.tier)) {
|
|
241
|
+
return { ok: false, reason: `duplicate schedule tier ${schedule.tier}` };
|
|
242
|
+
}
|
|
243
|
+
seenTiers.add(schedule.tier);
|
|
244
|
+
|
|
245
|
+
if (!Array.isArray(schedule.conditions) || schedule.conditions.length === 0) {
|
|
246
|
+
return { ok: false, reason: `schedule ${schedule.tier} has no conditions` };
|
|
247
|
+
}
|
|
248
|
+
const convention = schedule.cacheInputConvention;
|
|
249
|
+
for (const key of ["cachedRead", "cachedWrite"] as const) {
|
|
250
|
+
const value = convention?.[key];
|
|
251
|
+
if (value !== "included_in_input" && value !== "excluded_from_input") {
|
|
252
|
+
return { ok: false, reason: `schedule ${schedule.tier} has no ${key} cache convention` };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const priced = pricedCategories(schedule);
|
|
257
|
+
for (const category of TOKEN_CATEGORIES) {
|
|
258
|
+
const price = unitPriceFor(schedule, category);
|
|
259
|
+
if (price !== undefined && !isUnitPrice(price)) {
|
|
260
|
+
return { ok: false, reason: `schedule ${schedule.tier} has an invalid ${category} unit price` };
|
|
261
|
+
}
|
|
262
|
+
// Applicable but unpriced would silently exclude the category from cost (§7).
|
|
263
|
+
if (policy.categoryApplicability[category] === "applicable" && !priced.has(category)) {
|
|
264
|
+
return {
|
|
265
|
+
ok: false,
|
|
266
|
+
reason: `schedule ${schedule.tier} declares ${category} applicable but carries no price`,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Mixed currency is invalid rather than partially summed (§7).
|
|
272
|
+
const currencies = new Set<string>();
|
|
273
|
+
for (const category of priced) {
|
|
274
|
+
currencies.add(unitPriceFor(schedule, category)!.currency);
|
|
275
|
+
}
|
|
276
|
+
if (currencies.size > 1) {
|
|
277
|
+
return {
|
|
278
|
+
ok: false,
|
|
279
|
+
reason: `schedule ${schedule.tier} mixes currencies: ${[...currencies].sort().join(", ")}`,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return { ok: true };
|
|
285
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Mapping an adapter to a models.dev provider key, and finding the active model.
|
|
2
|
+
// See 9-6-SPEC-metering.md §7.
|
|
3
|
+
//
|
|
4
|
+
// §7 forbids guessing a provider from a bare model string: two providers can serve the
|
|
5
|
+
// same model id at different prices, so a guess engraves a plausible wrong number instead
|
|
6
|
+
// of an honest "unavailable". Only single-provider adapters with a tested mapping appear
|
|
7
|
+
// here. A multiplexing harness such as OpenCode must report its selected provider through
|
|
8
|
+
// a certified integration; until then it resolves to null and stays unpriced.
|
|
9
|
+
|
|
10
|
+
import type { ConfigOptions } from "../config-options.ts";
|
|
11
|
+
|
|
12
|
+
const ADAPTER_PROVIDERS: Readonly<Record<string, string>> = Object.freeze({
|
|
13
|
+
claude: "anthropic",
|
|
14
|
+
claudeCode: "anthropic",
|
|
15
|
+
codex: "openai",
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/** The models.dev provider key for an adapter, or null when it cannot be established. */
|
|
19
|
+
export function providerIdForAdapter(adapterId: string): string | null {
|
|
20
|
+
return ADAPTER_PROVIDERS[adapterId] ?? null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Adapters whose advertised model string is `<models.dev provider>/<models.dev model>`.
|
|
25
|
+
*
|
|
26
|
+
* Verified for OpenCode: every one of the 69 models its Zen gateway advertises is
|
|
27
|
+
* `opencode/<key>`, and models.dev carries an `opencode` provider holding those same keys
|
|
28
|
+
* with Zen's own prices (which differ from the upstream provider's).
|
|
29
|
+
*
|
|
30
|
+
* Deliberately adapter-scoped rather than "split anything containing a slash". Other
|
|
31
|
+
* harnesses use the same shape with a first segment that is NOT a catalog provider —
|
|
32
|
+
* `openai-codex/gpt-5.5`, `kimi-code/kimi-for-coding` — and a first segment that merely
|
|
33
|
+
* LOOKED like a provider would price a proxied route at the upstream provider's rates.
|
|
34
|
+
* The split is also validated against the catalog before use, so a wrong guess resolves
|
|
35
|
+
* to nothing rather than to a wrong price.
|
|
36
|
+
*/
|
|
37
|
+
const COMPOSITE_MODEL_ADAPTERS: ReadonlySet<string> = new Set(["opencode"]);
|
|
38
|
+
|
|
39
|
+
export interface ModelReference {
|
|
40
|
+
/** models.dev provider key. */
|
|
41
|
+
readonly providerId: string;
|
|
42
|
+
/** models.dev model key. */
|
|
43
|
+
readonly modelId: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Resolve an adapter and its advertised model string to catalog lookup keys.
|
|
48
|
+
*
|
|
49
|
+
* Returns null when either half cannot be established — never a guess. The caller still
|
|
50
|
+
* validates the pair against the catalog, so this narrows candidates rather than
|
|
51
|
+
* asserting a match.
|
|
52
|
+
*/
|
|
53
|
+
export function resolveModelReference(
|
|
54
|
+
adapterId: string,
|
|
55
|
+
model: string | null,
|
|
56
|
+
): ModelReference | null {
|
|
57
|
+
if (!model) return null;
|
|
58
|
+
|
|
59
|
+
if (COMPOSITE_MODEL_ADAPTERS.has(adapterId)) {
|
|
60
|
+
const separator = model.indexOf("/");
|
|
61
|
+
if (separator <= 0 || separator === model.length - 1) return null;
|
|
62
|
+
return {
|
|
63
|
+
providerId: model.slice(0, separator),
|
|
64
|
+
modelId: model.slice(separator + 1),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const providerId = providerIdForAdapter(adapterId);
|
|
69
|
+
return providerId ? { providerId, modelId: model } : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Config option ids harnesses use for the active model, in preference order. */
|
|
73
|
+
const MODEL_OPTION_IDS = ["model", "model_id", "modelId"] as const;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The plain advertised model string from harness config, or null.
|
|
77
|
+
*
|
|
78
|
+
* Discovered, never hardcoded — the library does not know a harness's model catalog, and
|
|
79
|
+
* a stale guess would misprice every record it touched.
|
|
80
|
+
*/
|
|
81
|
+
export function activeModel(options: ConfigOptions): string | null {
|
|
82
|
+
for (const id of MODEL_OPTION_IDS) {
|
|
83
|
+
const value = options.get(id)?.currentValue;
|
|
84
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* How a harness's ACP token counters should be read.
|
|
91
|
+
*
|
|
92
|
+
* ACP does not say. The SDK documents `PromptResponse.usage` as usage "for this turn"
|
|
93
|
+
* while documenting the `Usage` fields as totals across the session, and exposes no
|
|
94
|
+
* discriminator — so this is adapter- and version-scoped EVIDENCE, never a runtime guess.
|
|
95
|
+
* §4 forbids switching interpretations mid-session, because a first report that happens
|
|
96
|
+
* to look like one shape would silently relabel every later record.
|
|
97
|
+
*/
|
|
98
|
+
export type CounterInterpretation = "cumulative" | "per_turn";
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Harnesses measured to report per-turn counters.
|
|
102
|
+
*
|
|
103
|
+
* OpenCode: three consecutive turns on opencode/big-pickle each satisfied
|
|
104
|
+
* `totalTokens === inputTokens + outputTokens + cachedReadTokens` within a SINGLE report,
|
|
105
|
+
* and `inputTokens` fell 5897 → 20 between turns. Totals still rose turn over turn
|
|
106
|
+
* (every turn re-reads the same cached context), which is why comparing totals is not a
|
|
107
|
+
* valid test and reported "cumulative" until the components were checked.
|
|
108
|
+
* See .res/somelogs.md/9-5+/9-6-harness-matrix-findings.md, Finding 5.
|
|
109
|
+
*/
|
|
110
|
+
const PER_TURN_ADAPTERS: ReadonlySet<string> = new Set(["opencode"]);
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The interpretation to apply for an adapter.
|
|
114
|
+
*
|
|
115
|
+
* Defaults to cumulative — the reading the field-level SDK docs describe and the only one
|
|
116
|
+
* that makes `totalTokens` ("sum of all token types across session") coherent. An adapter
|
|
117
|
+
* is moved out of the default only on measurement.
|
|
118
|
+
*/
|
|
119
|
+
export function counterInterpretationForAdapter(adapterId: string): CounterInterpretation {
|
|
120
|
+
return PER_TURN_ADAPTERS.has(adapterId) ? "per_turn" : "cumulative";
|
|
121
|
+
}
|