@qlairoslabs/acp-client 0.5.0 → 0.7.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.
Files changed (62) hide show
  1. package/CHANGELOG-metering.md +288 -0
  2. package/CONSUMER_GUIDE.md +579 -292
  3. package/README.md +25 -0
  4. package/package.json +6 -3
  5. package/src/agent-session.ts +2589 -96
  6. package/src/cli/index.ts +33 -5
  7. package/src/cli/managed.ts +220 -0
  8. package/src/client.ts +57 -1
  9. package/src/controller.ts +43 -0
  10. package/src/index.ts +379 -3
  11. package/src/metering/catalog/build.ts +285 -0
  12. package/src/metering/catalog/index.ts +243 -0
  13. package/src/metering/catalog/live.ts +171 -0
  14. package/src/metering/catalog/models-dev.catalog.json +8797 -0
  15. package/src/metering/catalog/models-dev.meta.json +6 -0
  16. package/src/metering/categories.ts +129 -0
  17. package/src/metering/certification.ts +86 -0
  18. package/src/metering/context.ts +134 -0
  19. package/src/metering/delta.ts +108 -0
  20. package/src/metering/engine.ts +999 -0
  21. package/src/metering/money.ts +356 -0
  22. package/src/metering/opencode/channel.ts +389 -0
  23. package/src/metering/opencode/index.ts +159 -0
  24. package/src/metering/opencode/plugin.js +90 -0
  25. package/src/metering/opencode/profile.ts +159 -0
  26. package/src/metering/pricing.ts +285 -0
  27. package/src/metering/provider.ts +121 -0
  28. package/src/metering/rating.ts +349 -0
  29. package/src/metering/record.ts +275 -0
  30. package/src/metering/state.ts +421 -0
  31. package/src/metering/usage.ts +72 -0
  32. package/src/persistence/activity-projection.ts +71 -0
  33. package/src/persistence/audit-log-reader.ts +506 -0
  34. package/src/persistence/audit-runtime.ts +162 -0
  35. package/src/persistence/checkpoint.ts +304 -0
  36. package/src/persistence/config.ts +538 -0
  37. package/src/persistence/configuration-state.ts +191 -0
  38. package/src/persistence/deletion.ts +227 -0
  39. package/src/persistence/file-registry-store.ts +740 -0
  40. package/src/persistence/integrity.ts +147 -0
  41. package/src/persistence/legacy-registry-import.ts +240 -0
  42. package/src/persistence/managed-checkpoint.ts +81 -0
  43. package/src/persistence/managed-creation.ts +456 -0
  44. package/src/persistence/managed-load.ts +172 -0
  45. package/src/persistence/managed-registry.ts +57 -0
  46. package/src/persistence/migration.ts +298 -0
  47. package/src/persistence/paths.ts +172 -0
  48. package/src/persistence/projection.ts +373 -0
  49. package/src/persistence/reconfiguration.ts +453 -0
  50. package/src/persistence/records.ts +873 -0
  51. package/src/persistence/reducer.ts +498 -0
  52. package/src/persistence/registry.ts +446 -0
  53. package/src/persistence/restoration.ts +689 -0
  54. package/src/persistence/session-log-writer.ts +480 -0
  55. package/src/persistence/state-runtime.ts +176 -0
  56. package/src/persistence/transcript-reader.ts +980 -0
  57. package/src/persistence/transcript-runtime.ts +667 -0
  58. package/src/persistence/transcript-scanner.ts +385 -0
  59. package/src/persistence/truncation.ts +276 -0
  60. package/src/session-manager.ts +257 -7
  61. package/src/transcript.ts +3 -3
  62. package/src/types.ts +28 -5
@@ -0,0 +1,389 @@
1
+ // The loopback channel the OpenCode metering plugin reports to.
2
+ //
3
+ // Deliberately narrow: it accepts telemetry and nothing else. It does not proxy model
4
+ // traffic, hold credentials, or see prompt or response content — the plugin sends token
5
+ // counts and cost, never message text.
6
+ //
7
+ // Binds to 127.0.0.1 on an ephemeral port and requires a per-session token, because
8
+ // anything on the loopback interface can otherwise post fabricated usage into a billing
9
+ // ledger.
10
+
11
+ import type { TokenUsage } from "../../types.ts";
12
+ import { disjointTokenUsage, isTokenCount } from "../categories.ts";
13
+
14
+ /** One model inference, as OpenCode itself accounted for it. */
15
+ export interface ProviderInference {
16
+ /** Per-session counter assigned by the plugin, used to detect dropped reports. */
17
+ readonly sequence: number | null;
18
+ readonly messageID: string;
19
+ readonly sessionID: string;
20
+ readonly providerID: string;
21
+ readonly modelID: string;
22
+ /** True for compaction summaries: an inference no user prompt asked for. */
23
+ readonly summary: boolean;
24
+ readonly completedAt: number;
25
+ /** OpenCode's own cost figure, or null when it reported none. Never a fabricated zero. */
26
+ readonly cost: number | null;
27
+ readonly tokens: TokenUsage;
28
+ }
29
+
30
+ export interface ChannelHandshake {
31
+ readonly pid: number;
32
+ readonly directory: string | null;
33
+ readonly at: number;
34
+ }
35
+
36
+ interface RawInference {
37
+ sequence?: unknown;
38
+ messageID?: unknown;
39
+ sessionID?: unknown;
40
+ providerID?: unknown;
41
+ modelID?: unknown;
42
+ summary?: unknown;
43
+ completedAt?: unknown;
44
+ cost?: unknown;
45
+ tokens?: {
46
+ input?: unknown;
47
+ output?: unknown;
48
+ reasoning?: unknown;
49
+ cache?: { read?: unknown; write?: unknown };
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Compare a shared secret without leaking length or prefix through timing.
55
+ *
56
+ * The channel is loopback-only with a random token, so this is defence in depth rather
57
+ * than a live threat — but it is an auth check, and auth checks compare in constant time.
58
+ */
59
+ function timingSafeEquals(candidate: string | null, expected: string): boolean {
60
+ if (candidate === null || candidate.length !== expected.length) return false;
61
+ let difference = 0;
62
+ for (let index = 0; index < expected.length; index += 1) {
63
+ difference |= candidate.charCodeAt(index) ^ expected.charCodeAt(index);
64
+ }
65
+ return difference === 0;
66
+ }
67
+
68
+ /** `isTokenCount` in null-returning form: the raw shape is unvalidated JSON. */
69
+ function counter(value: unknown): number | null {
70
+ return isTokenCount(value) ? value : null;
71
+ }
72
+
73
+ /**
74
+ * Normalize OpenCode's token shape into the library's.
75
+ *
76
+ * The categories are disjoint — measured across five providers, `input + output +
77
+ * reasoning + cache.read + cache.write` equals the reported total exactly — so
78
+ * `totalTokens` is their sum rather than a separately reported figure.
79
+ */
80
+ function normalizeInference(raw: RawInference): ProviderInference | null {
81
+ const messageID = typeof raw.messageID === "string" ? raw.messageID : null;
82
+ const sessionID = typeof raw.sessionID === "string" ? raw.sessionID : null;
83
+ const providerID = typeof raw.providerID === "string" ? raw.providerID : null;
84
+ const modelID = typeof raw.modelID === "string" ? raw.modelID : null;
85
+ const completedAt = counter(raw.completedAt);
86
+ if (!messageID || !sessionID || !providerID || !modelID || completedAt === null) return null;
87
+
88
+ const input = counter(raw.tokens?.input);
89
+ const output = counter(raw.tokens?.output);
90
+ if (input === null || output === null) return null;
91
+ const reasoning = counter(raw.tokens?.reasoning);
92
+ const cacheRead = counter(raw.tokens?.cache?.read);
93
+ const cacheWrite = counter(raw.tokens?.cache?.write);
94
+
95
+ const tokens = disjointTokenUsage({
96
+ input,
97
+ output,
98
+ cachedRead: cacheRead,
99
+ cachedWrite: cacheWrite,
100
+ thought: reasoning,
101
+ });
102
+
103
+ // A malformed cost is NOT zero. Coercing it would put a fabricated zero into a billing
104
+ // ledger, which is the exact failure this design refuses everywhere else.
105
+ if (raw.cost !== undefined && raw.cost !== null) {
106
+ if (typeof raw.cost !== "number" || !Number.isFinite(raw.cost) || raw.cost < 0) return null;
107
+ }
108
+
109
+ return Object.freeze({
110
+ sequence: counter(raw.sequence),
111
+ messageID,
112
+ sessionID,
113
+ providerID,
114
+ modelID,
115
+ summary: raw.summary === true,
116
+ completedAt,
117
+ // Absent cost is genuinely unknown; the record still carries its tokens.
118
+ cost: typeof raw.cost === "number" ? raw.cost : null,
119
+ tokens: Object.freeze(tokens),
120
+ });
121
+ }
122
+
123
+ export interface MeteringChannelOptions {
124
+ /** Emitted on malformed or unauthorized posts; never thrown at the harness. */
125
+ readonly onWarning?: (message: string) => void;
126
+ /**
127
+ * Maximum undrained records held. Default 10,000.
128
+ *
129
+ * Reached only when operations stop closing — a stalled session drains nothing. Overflow
130
+ * counts toward lost reports so it cannot pass unnoticed.
131
+ */
132
+ readonly maxPendingRecords?: number;
133
+ }
134
+
135
+ /**
136
+ * A loopback endpoint collecting per-inference records from the harness.
137
+ *
138
+ * Attribution is drain-based: `AgentSession` serializes operations, so everything drained
139
+ * at the end of one operation belongs to it. That is simpler and more robust than
140
+ * timestamp windows, which would misattribute an inference that completed while the next
141
+ * operation was already opening.
142
+ */
143
+ export class OpencodeMeteringChannel {
144
+ private server: ReturnType<typeof Bun.serve> | null = null;
145
+ /**
146
+ * Bounded on purpose. An unbounded buffer is a promise that cannot be kept, and silently
147
+ * dropping on overflow would be the same under-reporting bug in another organ. Overflow
148
+ * is counted as permanently lost, so exceeding capacity degrades attribution to
149
+ * partial rather than losing records quietly.
150
+ */
151
+ private readonly pending = new Map<string, ProviderInference>();
152
+ private readonly capacity: number;
153
+ private _handshake: ChannelHandshake | null = null;
154
+ private _rejected = 0;
155
+ /** Highest sequence seen per session, and how many were skipped. */
156
+ /**
157
+ * Per-session sequence ledger.
158
+ *
159
+ * A high-water mark could say "seen up to N" but never "missing 3 and 7", so it could not
160
+ * RETRACT a loss claim: out-of-order arrival on loopback recorded a permanent phantom
161
+ * gap, which under billing_required blocked a working session. An outstanding set is
162
+ * discharged when the late report lands.
163
+ */
164
+ private readonly sequences = new Map<string, { highest: number; outstanding: Set<number> }>();
165
+ /**
166
+ * Message ids accepted at any point, not just those still pending.
167
+ *
168
+ * `pending` alone is not a dedupe scope: once an operation drains it, a repeat report for
169
+ * the same completed message would be taken as fresh work and charged to the NEXT
170
+ * operation. The plugin suppresses repeats too; this is the defensive half, because a
171
+ * double-charge must not depend on a component running inside the harness.
172
+ */
173
+ private readonly seenMessageIds = new Set<string>();
174
+ /** Refused for capacity — permanently lost, unlike a gap that may still be filled. */
175
+ private _permanentlyLost = 0;
176
+ private _duplicatesRefused = 0;
177
+
178
+ readonly token: string = crypto.randomUUID();
179
+
180
+ constructor(private readonly options: MeteringChannelOptions = {}) {
181
+ this.capacity = options.maxPendingRecords ?? 10_000;
182
+ }
183
+
184
+ /** True once the plugin has announced itself: "loaded" versus "silent" are different. */
185
+ get handshake(): ChannelHandshake | null {
186
+ return this._handshake;
187
+ }
188
+ /**
189
+ * Repeat reports for a message already drained.
190
+ *
191
+ * Non-zero usually means the plugin is loaded twice — harmless now that it is refused,
192
+ * but worth surfacing because it also indicates the harness config has two entries.
193
+ */
194
+ get duplicatesRefusedCount(): number {
195
+ return this._duplicatesRefused;
196
+ }
197
+ /** Posts refused for a bad token or malformed body. Non-zero means something is wrong. */
198
+ get rejectedCount(): number {
199
+ return this._rejected;
200
+ }
201
+ /**
202
+ * Sequence numbers seen skipped and not yet filled, for one session or all of them.
203
+ *
204
+ * RETRACTABLE: a report arriving out of order discharges its own number, so this count
205
+ * FALLS. Treating a gap as permanent is what let a benign reorder block billing.
206
+ *
207
+ * LIMITATION: a gap is only visible once a LATER report arrives, so a lost FINAL report
208
+ * is undetectable. Sequence numbers detect observed discontinuities; they do not prove
209
+ * delivery. Closing that needs a plugin-to-parent finalization fence, which this version
210
+ * does not have.
211
+ */
212
+ outstandingReports(sessionId?: string | null): number {
213
+ if (sessionId) return this.sequences.get(sessionId)?.outstanding.size ?? 0;
214
+ let total = 0;
215
+ for (const ledger of this.sequences.values()) total += ledger.outstanding.size;
216
+ return total;
217
+ }
218
+
219
+ /**
220
+ * Records this channel refused and can therefore never receive.
221
+ *
222
+ * Distinct from an outstanding gap: this usage is unaccounted ANYWHERE, which is the one
223
+ * condition that should stop a billing session.
224
+ */
225
+ get permanentlyLostCount(): number {
226
+ return this._permanentlyLost;
227
+ }
228
+
229
+ /** Highest sequence recorded for a session, used to recognise a late arrival. */
230
+ sequenceHighWater(sessionId: string | null): number {
231
+ return sessionId ? (this.sequences.get(sessionId)?.highest ?? 0) : 0;
232
+ }
233
+
234
+ get url(): string {
235
+ if (!this.server) throw new Error("metering channel is not started");
236
+ return `http://127.0.0.1:${this.server.port}/inference`;
237
+ }
238
+
239
+ start(): void {
240
+ if (this.server) return;
241
+ this.server = Bun.serve({
242
+ hostname: "127.0.0.1",
243
+ port: 0,
244
+ fetch: async (request) => {
245
+ if (request.method !== "POST") return new Response("method not allowed", { status: 405 });
246
+ if (!timingSafeEquals(request.headers.get("x-acp-meter-token"), this.token)) {
247
+ this._rejected += 1;
248
+ this.options.onWarning?.("rejected a post with a bad token");
249
+ return new Response("forbidden", { status: 403 });
250
+ }
251
+ let body: unknown;
252
+ try {
253
+ body = await request.json();
254
+ } catch {
255
+ this._rejected += 1;
256
+ return new Response("bad json", { status: 400 });
257
+ }
258
+ const payload = body as { type?: unknown } & RawInference & Partial<ChannelHandshake>;
259
+
260
+ if (payload.type === "hello") {
261
+ this._handshake = Object.freeze({
262
+ pid: typeof payload.pid === "number" ? payload.pid : -1,
263
+ directory: typeof payload.directory === "string" ? payload.directory : null,
264
+ at: typeof payload.at === "number" ? payload.at : Date.now(),
265
+ });
266
+ return new Response("ok");
267
+ }
268
+
269
+ if (payload.type === "inference") {
270
+ const inference = normalizeInference(payload);
271
+ if (!inference) {
272
+ this._rejected += 1;
273
+ this.options.onWarning?.("rejected a malformed inference record");
274
+ return new Response("bad record", { status: 400 });
275
+ }
276
+ // Sequence bookkeeping runs BEFORE any refusal below. A duplicate consumes its
277
+ // number whatever we do with the payload, and skipping it left the ledger behind
278
+ // so the next legitimate record looked like a gap.
279
+ if (inference.sequence !== null) this.recordSequence(inference);
280
+
281
+ // Keyed by messageID across the channel's whole life, not just what is pending:
282
+ // the same inference counted twice would inflate a bill.
283
+ const everSeen = this.seenMessageIds.has(inference.messageID);
284
+ if (everSeen && !this.pending.has(inference.messageID)) {
285
+ // Already drained into a completed operation. Accepting it again would charge
286
+ // the work twice.
287
+ this._duplicatesRefused += 1;
288
+ return new Response("duplicate", { status: 409 });
289
+ }
290
+ if (!everSeen && this.pending.size >= this.capacity) {
291
+ // Full. Refuse rather than evict: dropping the oldest would silently lose a
292
+ // record already counted as delivered. This one is PERMANENTLY lost — unlike a
293
+ // sequence gap it will never arrive, because we rejected it.
294
+ this._permanentlyLost += 1;
295
+ this.options.onWarning?.(
296
+ `metering channel is full at ${this.capacity} undrained records; ` +
297
+ `refusing further records until an operation closes`,
298
+ );
299
+ return new Response("full", { status: 503 });
300
+ }
301
+ this.pending.set(inference.messageID, inference);
302
+ this.seenMessageIds.add(inference.messageID);
303
+ return new Response("ok");
304
+ }
305
+
306
+ this._rejected += 1;
307
+ return new Response("unknown type", { status: 400 });
308
+ },
309
+ });
310
+ }
311
+
312
+ /**
313
+ * Fold a sequence number into its session's ledger.
314
+ *
315
+ * Advancing opens gaps for anything skipped; EVERY arrival — in order, late, or a
316
+ * duplicate — discharges its own number, so a reorder resolves itself rather than
317
+ * standing as a permanent loss.
318
+ */
319
+ private recordSequence(inference: ProviderInference): void {
320
+ const sequence = inference.sequence!;
321
+ let ledger = this.sequences.get(inference.sessionID);
322
+ if (!ledger) {
323
+ ledger = { highest: 0, outstanding: new Set<number>() };
324
+ this.sequences.set(inference.sessionID, ledger);
325
+ }
326
+ if (sequence > ledger.highest) {
327
+ for (let missing = ledger.highest + 1; missing < sequence; missing += 1) {
328
+ ledger.outstanding.add(missing);
329
+ }
330
+ ledger.highest = sequence;
331
+ }
332
+ ledger.outstanding.delete(sequence);
333
+ if (ledger.outstanding.size > 0) {
334
+ this.options.onWarning?.(
335
+ `metering channel is missing ${ledger.outstanding.size} report(s) for session ` +
336
+ `${inference.sessionID}; they may still arrive`,
337
+ );
338
+ }
339
+ }
340
+
341
+
342
+ /**
343
+ * Take the records collected for one provider thread since the last drain.
344
+ *
345
+ * Scoped deliberately. An unscoped drain charges the next operation for anything the
346
+ * harness did elsewhere — background work, or a late inference from a thread a handoff
347
+ * already replaced. Records for other threads stay pending and surface through
348
+ * `drainAll()` as unallocated rather than being attributed to work that did not cause
349
+ * them.
350
+ */
351
+ drain(sessionId?: string | null): readonly ProviderInference[] {
352
+ const drained: ProviderInference[] = [];
353
+ for (const [messageId, inference] of this.pending) {
354
+ if (sessionId && inference.sessionID !== sessionId) continue;
355
+ drained.push(inference);
356
+ this.pending.delete(messageId);
357
+ }
358
+ return Object.freeze(drained);
359
+ }
360
+
361
+ /** Take records belonging to any thread OTHER than the one named. */
362
+ drainForeign(sessionId: string | null): readonly ProviderInference[] {
363
+ if (!sessionId) return Object.freeze([]);
364
+ const drained: ProviderInference[] = [];
365
+ for (const [messageId, inference] of this.pending) {
366
+ if (inference.sessionID === sessionId) continue;
367
+ drained.push(inference);
368
+ this.pending.delete(messageId);
369
+ }
370
+ return Object.freeze(drained);
371
+ }
372
+
373
+ /** Take everything still pending, whatever thread it belongs to. */
374
+ drainAll(): readonly ProviderInference[] {
375
+ const drained = Object.freeze([...this.pending.values()]);
376
+ this.pending.clear();
377
+ return drained;
378
+ }
379
+
380
+ /** Records collected but not yet drained. */
381
+ get pendingCount(): number {
382
+ return this.pending.size;
383
+ }
384
+
385
+ async stop(): Promise<void> {
386
+ await this.server?.stop(true);
387
+ this.server = null;
388
+ }
389
+ }
@@ -0,0 +1,159 @@
1
+ // Certified OpenCode metering: one call that wires the plugin, the channel, and the
2
+ // managed profile together.
3
+ //
4
+ // Why this exists, in one measurement: on `opencode-go/kimi-k2.6`, a turn with tool calls
5
+ // billed 0.00708081 while ACP's `PromptResponse.usage` reported 0.00281687 — the last of
6
+ // two inferences. The plugin observed both, and their costs summed to the provider's own
7
+ // figure exactly. ACP alone undercounts any tool-using turn, which is every real turn for
8
+ // a coding agent.
9
+
10
+ import { OpencodeMeteringChannel, type ProviderInference } from "./channel.ts";
11
+ import { meteringPluginPath, writeManagedProfile, type ManagedProfile } from "./profile.ts";
12
+ import { OPENCODE_PLUGIN_CERTIFICATION } from "../certification.ts";
13
+ import type { InferenceSource } from "../engine.ts";
14
+
15
+ export interface OpencodeMeteringOptions {
16
+ /** Diagnostics sink for rejected posts and version mismatches. */
17
+ readonly onWarning?: (message: string) => void;
18
+ /**
19
+ * Skip the harness version check.
20
+ *
21
+ * The certification names the versions actually exercised; running outside them means
22
+ * the plugin API may differ. Only set this to explore a new version deliberately.
23
+ */
24
+ readonly allowUnverifiedVersion?: boolean;
25
+ /**
26
+ * Proceed even when the user's OpenCode config cannot be parsed.
27
+ *
28
+ * Off by default: OPENCODE_CONFIG replaces that config, so continuing without it changes
29
+ * which model answers — and a metering channel must not alter what it meters.
30
+ */
31
+ readonly allowUnreadableConfig?: boolean;
32
+ }
33
+
34
+ export interface OpencodeMetering {
35
+ /** Merge into `AgentSessionConfig.env` so the harness loads the plugin and can report. */
36
+ readonly env: Readonly<Record<string, string>>;
37
+ /** Pass as `MeteringConfig.inferenceSource`. */
38
+ readonly inferenceSource: InferenceSource;
39
+ /** True once the plugin has announced itself. */
40
+ isReady(): boolean;
41
+ /**
42
+ * Wait for the plugin handshake.
43
+ *
44
+ * Resolves false on timeout, which is the signal that the plugin did not load — a
45
+ * different fact from "no inferences happened", and the one billing depends on.
46
+ */
47
+ waitForPlugin(timeoutMs?: number): Promise<boolean>;
48
+ readonly profile: ManagedProfile;
49
+ /** Inferences observed but never attributed to an operation. */
50
+ drainUnattributed(): readonly ProviderInference[];
51
+ stop(): Promise<void>;
52
+ }
53
+
54
+ /** Best-effort harness version, or null when it cannot be determined. */
55
+ async function opencodeVersion(): Promise<string | null> {
56
+ try {
57
+ const process_ = Bun.spawn(["opencode", "--version"], { stdout: "pipe", stderr: "ignore" });
58
+ const text = (await new Response(process_.stdout).text()).trim();
59
+ return /^\d+\.\d+/.test(text) ? text : null;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Start a certified metering channel for OpenCode.
67
+ *
68
+ * Call before `AgentSession.create`, merge `env` into the session config, and pass
69
+ * `inferenceSource` to `MeteringConfig`. Await `waitForPlugin()` before relying on it in a
70
+ * strict mode: a channel that never handshook reports every operation unavailable rather
71
+ * than falling back to a backend known to undercount.
72
+ */
73
+ export async function createOpencodeMetering(
74
+ options: OpencodeMeteringOptions = {},
75
+ ): Promise<OpencodeMetering> {
76
+ const version = await opencodeVersion();
77
+ const supported = OPENCODE_PLUGIN_CERTIFICATION.supportedHarnessVersions;
78
+ const verified = version !== null && supported.some((prefix) => version.startsWith(prefix));
79
+ if (!verified && !options.allowUnverifiedVersion) {
80
+ throw new Error(
81
+ `opencode ${version ?? "(version unknown)"} is outside the versions this metering ` +
82
+ `integration was verified against (${supported.join(", ")}). The plugin API differs ` +
83
+ `across majors. Pass allowUnverifiedVersion to proceed anyway.`,
84
+ );
85
+ }
86
+ if (!verified) options.onWarning?.(`running against unverified opencode ${version ?? "?"}`);
87
+
88
+ // Profile FIRST. It can fail closed on an unreadable config, and a channel started
89
+ // before that throw would leave a bound loopback socket with no object to stop it —
90
+ // the caller never receives the return value an exception skips past.
91
+ //
92
+ // Fail closed: proceeding without the user's config would silently change which model
93
+ // answers, and a certified metering channel that alters what it is metering is worse
94
+ // than no metering. `allowUnreadableConfig` is the deliberate override.
95
+ const profile = await writeManagedProfile(meteringPluginPath(), {
96
+ onUnreadableConfig: (path) => {
97
+ if (options.allowUnreadableConfig) {
98
+ options.onWarning?.(
99
+ `could not parse ${path}; proceeding WITHOUT your OpenCode config, so the model ` +
100
+ `and providers it selects will not apply`,
101
+ );
102
+ return;
103
+ }
104
+ throw new Error(
105
+ `could not parse your OpenCode config at ${path}. Metering would have to run ` +
106
+ `without it, which changes the model and providers in use. Fix the config, or ` +
107
+ `pass allowUnreadableConfig to proceed anyway.`,
108
+ );
109
+ },
110
+ });
111
+
112
+ const channel = new OpencodeMeteringChannel({ onWarning: options.onWarning });
113
+ try {
114
+ channel.start();
115
+ } catch (error) {
116
+ // Nothing else has been handed out yet, so this is the only chance to clean up.
117
+ await profile.cleanup();
118
+ throw error;
119
+ }
120
+
121
+ const inferenceSource: InferenceSource = {
122
+ certificationId: OPENCODE_PLUGIN_CERTIFICATION.certificationId,
123
+ isHealthy: () => channel.handshake !== null,
124
+ drain: (internalSessionId) => channel.drain(internalSessionId),
125
+ drainForeign: (internalSessionId) => channel.drainForeign(internalSessionId),
126
+ outstandingReports: (internalSessionId) => channel.outstandingReports(internalSessionId),
127
+ permanentlyLostCount: () => channel.permanentlyLostCount,
128
+ sequenceHighWater: (internalSessionId) => channel.sequenceHighWater(internalSessionId),
129
+ };
130
+
131
+ return {
132
+ env: Object.freeze({
133
+ OPENCODE_CONFIG: profile.configPath,
134
+ ACP_METER_URL: channel.url,
135
+ ACP_METER_TOKEN: channel.token,
136
+ }),
137
+ inferenceSource,
138
+ profile,
139
+ isReady: () => channel.handshake !== null,
140
+ async waitForPlugin(timeoutMs = 15_000) {
141
+ const deadline = Date.now() + timeoutMs;
142
+ while (Date.now() < deadline) {
143
+ if (channel.handshake) return true;
144
+ await new Promise((resolve) => setTimeout(resolve, 50));
145
+ }
146
+ return false;
147
+ },
148
+ drainUnattributed: () => channel.drainAll(),
149
+ stop: async () => {
150
+ await channel.stop();
151
+ await profile.cleanup();
152
+ },
153
+ };
154
+ }
155
+
156
+ export { OpencodeMeteringChannel } from "./channel.ts";
157
+ export type { ProviderInference, ChannelHandshake } from "./channel.ts";
158
+ export { meteringPluginPath, writeManagedProfile } from "./profile.ts";
159
+ export type { ManagedProfile } from "./profile.ts";
@@ -0,0 +1,90 @@
1
+ // The metering plugin acp-lib installs into a managed OpenCode profile.
2
+ //
3
+ // Ships as plain JS because OpenCode loads it, not us: it runs inside the harness process
4
+ // and must not depend on this library's build.
5
+ //
6
+ // Why it exists: ACP reports ONE model inference per prompt, while a turn with tool calls
7
+ // runs several and the provider bills all of them. Measured on opencode-go/kimi-k2.6, a
8
+ // three-tool-call turn billed 3.43x what ACP reported. OpenCode emits one assistant
9
+ // message per inference, each carrying its own cost and normalized token counts, so
10
+ // observing them here recovers exactly what ACP hides.
11
+ //
12
+ // Configured entirely through env vars set by the parent at spawn time:
13
+ // ACP_METER_URL loopback endpoint to POST to
14
+ // ACP_METER_TOKEN shared secret, echoed in a header
15
+ // ACP_METER_DEBUG optional; log delivery failures to stderr
16
+
17
+ const URL_ = process.env.ACP_METER_URL;
18
+ const TOKEN = process.env.ACP_METER_TOKEN;
19
+ const DEBUG = process.env.ACP_METER_DEBUG === "1";
20
+
21
+ function warn(message, error) {
22
+ if (DEBUG) process.stderr.write(`[acp-meter] ${message}: ${String(error)}\n`);
23
+ }
24
+
25
+ async function post(body) {
26
+ if (!URL_ || !TOKEN) return;
27
+ try {
28
+ await fetch(URL_, {
29
+ method: "POST",
30
+ headers: { "content-type": "application/json", "x-acp-meter-token": TOKEN },
31
+ body: JSON.stringify(body),
32
+ });
33
+ } catch (error) {
34
+ // Never throw into the harness: a metering channel that breaks the agent is worse
35
+ // than one that goes quiet. The parent detects silence through its own handshake.
36
+ warn("delivery failed", error);
37
+ }
38
+ }
39
+
40
+ // A per-session counter so the parent can tell a quiet channel from a lossy one. Without
41
+ // it a dropped POST is indistinguishable from an inference that never happened, and the
42
+ // operation would still be reported as completely attributed.
43
+ const sequence = new Map();
44
+
45
+ // Message ids already reported, for this plugin instance's lifetime.
46
+ //
47
+ // The sequence must advance once per INFERENCE, not once per event. If a completed message
48
+ // is seen twice — OpenCode loads plugins from both `.opencode/plugin/` and the config
49
+ // `plugin` array, so a project-local copy alongside ours double-loads — incrementing again
50
+ // makes the parent see a gap where none exists, and a phantom lost report blocks a working
51
+ // billing session.
52
+ const reported = new Set();
53
+
54
+ export const AcpMeteringPlugin = async ({ directory, worktree }) => {
55
+ // Announced at startup so the parent can tell "plugin never loaded" from "no inferences
56
+ // happened yet" — the distinction billing-grade metering depends on.
57
+ await post({ type: "hello", pid: process.pid, directory, worktree, at: Date.now() });
58
+
59
+ return {
60
+ event: async ({ event }) => {
61
+ if (event?.type !== "message.updated") return;
62
+ const info = event.properties?.info;
63
+ if (!info || info.role !== "assistant") return;
64
+ // `message.updated` fires repeatedly while a message streams; only the completed
65
+ // state carries final token counts. Earlier ones report zeros and would understate.
66
+ if (!info.time?.completed) return;
67
+
68
+ if (reported.has(info.id)) return;
69
+ reported.add(info.id);
70
+
71
+ const next = (sequence.get(info.sessionID) ?? 0) + 1;
72
+ sequence.set(info.sessionID, next);
73
+
74
+ await post({
75
+ type: "inference",
76
+ sequence: next,
77
+ messageID: info.id,
78
+ sessionID: info.sessionID,
79
+ providerID: info.providerID,
80
+ modelID: info.modelID,
81
+ // True for compaction summaries — an inference no user prompt asked for, and
82
+ // exactly the kind ACP never surfaces.
83
+ summary: info.summary === true,
84
+ completedAt: info.time.completed,
85
+ cost: info.cost,
86
+ tokens: info.tokens,
87
+ });
88
+ },
89
+ };
90
+ };