@ponbac/token-ledger 0.7.0 → 0.9.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 (3) hide show
  1. package/README.md +76 -22
  2. package/dist/main.js +367 -71
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -101,12 +101,42 @@ node packages/cli/dist/main.js report
101
101
  | Grok Build | `~/.grok/sessions/**/updates.jsonl` | Saved completed turns and their model breakdowns |
102
102
  | Copilot CLI / VS Code Chat | `~/.copilot/otel` or `COPILOT_OTEL_FILE_EXPORTER_PATH` | JSONL request spans, VS Code inference events, and SQLite span exports |
103
103
  | Pi | `~/.pi/agent/sessions` or `PI_CODING_AGENT_SESSION_DIR` | Assistant messages on every branch, plus usage, compaction, and summary entries |
104
+ | OpenCode | `~/.local/share/opencode` | Assistant messages in `opencode*.db` and legacy `storage/message` files |
104
105
 
105
106
  `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `GROK_HOME`, `COPILOT_HOME`, and `PI_CODING_AGENT_DIR`
106
- override the usual homes. Configuration supports additional accounts, machines' exported histories,
107
+ override the usual homes. OpenCode keeps its data under `$XDG_DATA_HOME/opencode` on every
108
+ platform, Windows and macOS included, so an absolute `XDG_DATA_HOME` moves it, and
109
+ `OPENCODE_DB` names a database file in place of `opencode.db`, relative to that directory.
110
+ Configuration supports additional accounts, machines' exported histories,
107
111
  and arbitrary source directories. Histories are opened read-only, including work
108
112
  performed outside T3 Code.
109
113
 
114
+ ### OpenCode
115
+
116
+ Token Ledger reads OpenCode's SQLite database read-only, and every release channel's
117
+ `opencode-<channel>.db` beside it, selecting only accounting fields: message and session
118
+ IDs, timestamps, route, model, token counts, recorded cost, and working directory. Prompts,
119
+ responses, and tool output stay in the database; they are in tables and columns it never
120
+ selects. Under an `opencode` source, wherever it is rooted, every `opencode*.db` is read
121
+ as a database, every `msg_*.json` as a legacy message, and every `ses_*.json` as a legacy
122
+ session, of which only its ID and start time are read. Directories that never hold history
123
+ are skipped: snapshots, logs, cloned repositories, binaries, and the legacy store's parts,
124
+ diffs, shares, and to-do lists. Credentials and other files are never read. A file a source
125
+ names directly, such as an `OPENCODE_DB` override with any extension, is opened as SQLite
126
+ unless it is legacy JSON; one that cannot be opened counts as unreadable history, so `sync`
127
+ keeps the server's stored OpenCode usage. A source directory holding no OpenCode history at
128
+ all is reported as `missing`, which keeps stored usage too. Working directories
129
+ OpenCode stored on Windows with forward slashes are matched as native paths.
130
+
131
+ Models are reported under the ID OpenCode recorded, such as `claude-opus-4.5`, and priced
132
+ by the public rate table; GitHub Copilot's dotted Claude IDs are not in it and stay unpriced
133
+ unless configured under `prices`. OpenCode's own recorded costs are not used for estimates.
134
+
135
+ `sync` names the subscription that paid for a request from the route OpenCode recorded:
136
+ `github-copilot` requests bill to Copilot, and `openai` requests with a recorded cost of
137
+ exactly zero to Codex, because OpenCode's ChatGPT sign-in clears every OpenAI model's
138
+ rates. Other routes, OpenCode Zen and API keys among them, are API-equivalent estimates.
139
+
110
140
  ### Enable Copilot's usage export
111
141
 
112
142
  Copilot writes no usage log until a local OpenTelemetry file export is switched on,
@@ -460,7 +490,7 @@ telemetry has none.
460
490
 
461
491
  `sync` uploads this machine's usage to a [toki2](https://github.com/ponbac/toki2)
462
492
  server, which combines every developer's machines for team reporting and billing.
463
- Run it on **every machine** where you use a coding agent, and schedule it daily.
493
+ Run it on **every machine** where you use a coding agent, and schedule it.
464
494
 
465
495
  ### Set up
466
496
 
@@ -507,24 +537,31 @@ If you map projects in a `token-ledger.json`, pass it with `--config`; scheduled
507
537
  do not run in your project directory. Days follow the system time zone; add
508
538
  `--time-zone Europe/Stockholm` when a scheduler's environment may lack one.
509
539
 
510
- ### Schedule a daily sync
540
+ ### Schedule a sync
511
541
 
512
- Schedule a daily sync to upload history before providers prune it:
542
+ Schedule a sync to upload history regularly, and before providers prune it:
513
543
 
514
544
  ```sh
515
545
  npx @ponbac/token-ledger@latest schedule install
516
546
  ```
517
547
 
518
- This registers a daily job with the operating system's own scheduler; token-ledger
519
- does not keep a process running. Run it again to change the job.
548
+ This registers a job with the operating system's own scheduler that syncs every two
549
+ hours, at 00:30, 02:30, and so on; token-ledger does not keep a process running. Run
550
+ it again with other flags to change the job: the new schedule replaces the old one.
551
+
552
+ ```sh
553
+ npx @ponbac/token-ledger@latest schedule install --every 1h # hourly, at :30
554
+ npx @ponbac/token-ledger@latest schedule install --every 24h --at 07:30 # once a day
555
+ ```
520
556
 
521
- | Flag | Effect |
522
- | ----------------------- | ------------------------------------------------------- |
523
- | `--at 07:30` | Daily local time; the default is `12:30` |
524
- | `--config <file>` | Project mappings for the job, saved as an absolute path |
525
- | `--time-zone <zone>` | Pass a time zone when the scheduler may not have one |
526
- | `--provider <provider>` | Sync one provider only |
527
- | `--dry-run` | Print the files and commands, and change nothing |
557
+ | Flag | Effect |
558
+ | ----------------------- | ------------------------------------------------------------------------ |
559
+ | `--every 1h` | `1h`, `2h`, `3h`, `4h`, `6h`, `8h`, `12h`, or `24h`; the default is `2h` |
560
+ | `--at 07:30` | A local time a sync runs at; the default is `12:30` |
561
+ | `--config <file>` | Project mappings for the job, saved as an absolute path |
562
+ | `--time-zone <zone>` | Pass a time zone when the scheduler may not have one |
563
+ | `--provider <provider>` | Sync one provider only |
564
+ | `--dry-run` | Print the files and commands, and change nothing |
528
565
 
529
566
  `schedule status` shows the scheduler's own report, including the last run, and
530
567
  `schedule uninstall` removes the job and keeps your settings. A run's output is in
@@ -537,7 +574,7 @@ launcher in your token-ledger settings directory waits for sync to finish and
537
574
  passes its exit code back to Task Scheduler. Windows Script Host must be enabled.
538
575
  To update a task installed by an older CLI version, run
539
576
  `npx.cmd --yes @ponbac/token-ledger@latest schedule install` again, including any
540
- `--at`, `--config`, `--time-zone`, or `--provider` options you used before. This
577
+ `--every`, `--at`, `--config`, `--time-zone`, or `--provider` options you used before. This
541
578
  replaces the existing task; your saved server and token are kept.
542
579
 
543
580
  | Platform | Scheduler | A missed run |
@@ -563,8 +600,8 @@ Without one, as on Alpine or in WSL with systemd disabled, use the cron entry be
563
600
  <details>
564
601
  <summary>Scheduling by hand</summary>
565
602
 
566
- `schedule install --dry-run` prints the exact files and commands for your machine.
567
- The examples below do the same with a login shell finding `npx`; if it is not on the
603
+ `schedule install --dry-run` prints the exact files and commands for your machine,
604
+ with the times for any `--every`. The examples below sync once a day. They do the same with a login shell finding `npx`; if it is not on the
568
605
  scheduler's `PATH`, use its absolute path or install the CLI globally with
569
606
  `npm install -g @ponbac/token-ledger` and run `token-ledger sync`.
570
607
 
@@ -670,8 +707,9 @@ Provider histories stay on the machine. `sync` uploads only aggregates, and only
670
707
  you run it:
671
708
 
672
709
  - **Uploaded:** hourly totals per session, project, provider, and model: input,
673
- cache, and output tokens, request counts, and API-equivalent cost. Also the window,
674
- your time zone name, the machine ID and label, the CLI version, per-provider
710
+ cache, and output tokens, request counts, and API-equivalent cost, with the
711
+ subscription that paid when a request's route or a billing hint shows it. Also the
712
+ window, your time zone name, the machine ID and label, the CLI version, per-provider
675
713
  coverage counts, pricing provenance, and billing plans Codex reports.
676
714
  - **Hashed:** session identities. Some providers use a transcript's file path as its
677
715
  session, so no raw session ID is sent.
@@ -734,9 +772,9 @@ refused, `5` unsupported payload version (upgrade token-ledger), `6` payload rej
734
772
  - JSONL files are streamed, while Copilot buffers accounting records and span links
735
773
  per source for attribution; SQLite imports read the selected accounting rows. Each
736
774
  run rescans its sources, and memory grows with observed usage records.
737
- - Transcripts are append-only, so a Codex, Claude Code, Grok, or Pi file last modified more
738
- than 36 hours before the window starts is not opened; coverage counts these as
739
- `filesBeforeWindow`. This trusts modification times: a history restored with times
775
+ - Transcripts are append-only, so a Codex, Claude Code, Grok, Pi, or legacy OpenCode file
776
+ last modified more than 36 hours before the window starts is not opened; coverage counts
777
+ these as `filesBeforeWindow`. This trusts modification times: a history restored with times
740
778
  earlier than its last events is missed, so name such a file as the source itself,
741
779
  which is always read. Copilot exports are always read too, because requests are
742
780
  correlated across files and a live SQLite database's modification time lags its rows.
@@ -754,6 +792,22 @@ refused, `5` unsupported payload version (upgrade token-ledger), `6` payload rej
754
792
  `unknown` and stay unpriced. Pi's own recorded costs are not used.
755
793
  - A Pi `sessionDir` setting is not read; when sessions live outside the default
756
794
  directory, set `PI_CODING_AGENT_SESSION_DIR` or configure a `pi` source.
795
+ - OpenCode keeps each request's usage on its assistant message. Its newer store repeats
796
+ those messages under the same IDs, and legacy files repeat them too; each request is
797
+ counted once. A fork copies its parent's messages under new IDs with their timestamps
798
+ and usage, so a copy, a message older than its session, is matched to its original by
799
+ timestamp, route, model, and tokens in any OpenCode database or legacy file read, and
800
+ counted for the fork only when no original is read. Legacy copies are recognised only
801
+ when their session's file in `storage/session` is read too, by any source. Reverting a session deletes the reverted messages, and their usage with them, as
802
+ in OpenCode's own totals. A summary's usage is counted from its compaction message; a
803
+ failed one names no model and is reported under `unknown`, unpriced. Title generation,
804
+ which OpenCode's newest runtime records only in session totals, is not counted.
805
+ - An OpenCode database is always read, because its modification time lags rows in its
806
+ write-ahead log; only its messages created in the window are selected, so its rows
807
+ outside the window are not diagnosed. Legacy session files are always read, and legacy
808
+ message files follow the modification-time rule above.
809
+ - An `openai` request made with an API key for a model whose listed rates are zero would
810
+ also be billed to Codex: a recorded cost of zero is the only sign of the ChatGPT sign-in.
757
811
  - A truncated or malformed JSONL line is skipped and counted. No prompts are printed
758
812
  in diagnostics. An active session can change during a scan; this is not a transactional snapshot.
759
813
  - Coverage diagnostics describe every opened file, including its events outside the
@@ -775,7 +829,7 @@ For manual publication:
775
829
  1. Log in with `npm login` using an account with publish access to `@ponbac/token-ledger`.
776
830
  2. Run `bun run check`. The CLI test packs the package, installs it offline outside
777
831
  the repository with lifecycle scripts disabled, and exercises the installed CLI.
778
- 3. Run `bun run pack` to create `dist/ponbac-token-ledger-0.7.0.tgz` (filename follows version).
832
+ 3. Run `bun run pack` to create `dist/ponbac-token-ledger-0.9.0.tgz` (filename follows version).
779
833
  4. Inspect `npm publish ./dist/npm --dry-run`.
780
834
  5. Publish with `npm publish ./dist/npm --access public`; complete npm's authentication
781
835
  prompt if requested.
package/dist/main.js CHANGED
@@ -32733,7 +32733,7 @@ var readBillingHints = exports_Effect.fn("BillingHints.read")(function* (locatio
32733
32733
  });
32734
32734
 
32735
32735
  // packages/core/src/model.ts
32736
- var Provider = exports_Schema.Literals(["codex", "claude", "grok", "copilot", "pi"]);
32736
+ var Provider = exports_Schema.Literals(["codex", "claude", "grok", "copilot", "pi", "opencode"]);
32737
32737
  var BillingProvider = exports_Schema.Literals(["codex", "claude", "grok", "copilot"]);
32738
32738
  var Tokens = exports_Schema.Struct({
32739
32739
  input: exports_Schema.Natural,
@@ -34478,6 +34478,7 @@ var projectResolver = exports_Effect.fn("Projects.resolver")(function* (mappings
34478
34478
  var empty14 = {
34479
34479
  records: [],
34480
34480
  inherited: [],
34481
+ deferred: [],
34481
34482
  hints: [],
34482
34483
  malformed: 0,
34483
34484
  skipped: 0,
@@ -34976,6 +34977,208 @@ function grokParser(file2) {
34976
34977
  };
34977
34978
  }
34978
34979
 
34980
+ // packages/core/src/providers/opencode-db.ts
34981
+ class OpencodeDatabaseError extends exports_Schema.TaggedError()("OpencodeDatabaseError", { message: exports_Schema.String }) {
34982
+ }
34983
+ var opencodeDatabaseName = /^opencode(?:-[A-Za-z0-9._-]+)?\.db$/;
34984
+ var Names = exports_Schema.Array(exports_Schema.Struct({ name: exports_Schema.String }));
34985
+ var Lines = exports_Schema.Array(exports_Schema.Struct({ line: exports_Schema.String }));
34986
+ var databaseError2 = () => new OpencodeDatabaseError({ message: "Cannot read the OpenCode database." });
34987
+ var tokens = (data) => `json_object(
34988
+ 'input', json_extract(${data}, '$.tokens.input'),
34989
+ 'output', json_extract(${data}, '$.tokens.output'),
34990
+ 'reasoning', json_extract(${data}, '$.tokens.reasoning'),
34991
+ 'cache', json_object(
34992
+ 'read', json_extract(${data}, '$.tokens.cache.read'),
34993
+ 'write', json_extract(${data}, '$.tokens.cache.write')))`;
34994
+ var opencodeDatabaseLines = exports_Effect.fn("Opencode.readDatabase")(function* (file2, since, until) {
34995
+ return yield* exports_Effect.gen(function* () {
34996
+ const { DatabaseSync } = yield* exports_Effect.tryPromise({
34997
+ try: () => import("node:sqlite"),
34998
+ catch: databaseError2
34999
+ });
35000
+ const db = yield* exports_Effect.acquireRelease(exports_Effect.try({
35001
+ try: () => new DatabaseSync(file2, { readOnly: true, timeout: 5000 }),
35002
+ catch: databaseError2
35003
+ }), (connection) => exports_Effect.sync(() => connection.close()));
35004
+ const columns = yield* exports_Effect.try({
35005
+ try: () => db.prepare("SELECT t.name || '.' || c.name AS name FROM sqlite_master t, pragma_table_info(t.name) c WHERE t.type = 'table'").all(),
35006
+ catch: databaseError2
35007
+ }).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(Names)), exports_Effect.mapError(databaseError2), exports_Effect.map((rows2) => new Set(rows2.map((row) => row.name))));
35008
+ const has5 = (table2, ...names) => names.every((name) => columns.has(`${table2}.${name}`));
35009
+ const messages = has5("message", "id", "session_id", "time_created", "data");
35010
+ const v2 = has5("session_message", "id", "session_id", "type", "time_created", "data");
35011
+ if (!messages && !v2)
35012
+ return yield* new OpencodeDatabaseError({
35013
+ message: "The OpenCode database has no message table."
35014
+ });
35015
+ const sessions = (alias) => (alias === "v" ? ["session_v2", "session"] : ["session", "session_v2"]).filter((table2) => has5(table2, "id", "directory", "time_created"));
35016
+ const joins = (alias) => sessions(alias).map((table2, index2) => `LEFT JOIN ${table2} s${index2} ON s${index2}.id = ${alias}.session_id`).join(" ");
35017
+ const sessionField = (alias, field) => `COALESCE(${[...sessions(alias).map((_, index2) => `s${index2}.${field}`), "NULL"].join(", ")})`;
35018
+ const line = (alias, role, provider, model, cwd) => `json_object(
35019
+ 'id', ${alias}.id,
35020
+ 'sessionID', ${alias}.session_id,
35021
+ 'role', ${role},
35022
+ 'providerID', json_extract(${alias}.data, '${provider}'),
35023
+ 'modelID', json_extract(${alias}.data, '${model}'),
35024
+ 'time', json_object('created', ${alias}.time_created),
35025
+ 'cost', json_extract(${alias}.data, '$.cost'),
35026
+ 'tokens', ${tokens(`${alias}.data`)},
35027
+ 'path', json_object('cwd', ${cwd}),
35028
+ 'directory', ${sessionField(alias, "directory")},
35029
+ 'forked', json(CASE WHEN ${alias}.time_created < ${sessionField(alias, "time_created")} THEN 'true' ELSE 'false' END)
35030
+ ) AS line, ${alias}.time_created AS created, ${alias}.id AS id`;
35031
+ const queries = [
35032
+ ...messages ? [
35033
+ `SELECT ${line("m", "json_extract(m.data, '$.role')", "$.providerID", "$.modelID", "json_extract(m.data, '$.path.cwd')")}
35034
+ FROM message m ${joins("m")}
35035
+ WHERE m.time_created >= ? AND m.time_created < ?
35036
+ AND (json_extract(m.data, '$.role') = 'assistant' OR json_type(m.data, '$.tokens') IS NOT NULL)`
35037
+ ] : [],
35038
+ ...v2 ? [
35039
+ `SELECT ${line("v", "v.type", "$.model.providerID", "$.model.id", "NULL")}
35040
+ FROM session_message v ${joins("v")}
35041
+ WHERE v.time_created >= ? AND v.time_created < ?
35042
+ AND (v.type = 'assistant' OR json_type(v.data, '$.tokens') IS NOT NULL)
35043
+ ${messages ? "AND NOT EXISTS (SELECT 1 FROM message m WHERE m.id = v.id)" : ""}`
35044
+ ] : []
35045
+ ];
35046
+ const rows = yield* exports_Effect.try({
35047
+ try: () => db.prepare(`${queries.join(" UNION ALL ")} ORDER BY created, id`).all(...queries.flatMap(() => [since, until])),
35048
+ catch: databaseError2
35049
+ });
35050
+ const decoded = yield* exports_Schema.decodeUnknownEffect(Lines)(rows).pipe(exports_Effect.mapError(databaseError2));
35051
+ return decoded.map((row) => row.line);
35052
+ }).pipe(exports_Effect.scoped);
35053
+ });
35054
+
35055
+ // packages/core/src/providers/opencode.ts
35056
+ var decodeCarrier = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
35057
+ role: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.String)),
35058
+ tokens: exports_Schema.optionalKey(exports_Schema.Unknown)
35059
+ }));
35060
+ var Count = exports_Schema.Natural;
35061
+ var unattributedModel = "unknown";
35062
+ var decodeSession = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
35063
+ id: exports_Schema.NonEmptyString,
35064
+ time: exports_Schema.Struct({ created: exports_Schema.Number.check(exports_Schema.isFinite()) })
35065
+ }));
35066
+ var decodeMessage = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
35067
+ id: exports_Schema.NonEmptyString,
35068
+ sessionID: exports_Schema.NonEmptyString,
35069
+ providerID: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.NonEmptyString)),
35070
+ modelID: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.NonEmptyString)),
35071
+ time: exports_Schema.Struct({ created: exports_Schema.Number.check(exports_Schema.isFinite()) }),
35072
+ tokens: exports_Schema.Struct({
35073
+ input: Count,
35074
+ output: Count,
35075
+ reasoning: Count,
35076
+ cache: exports_Schema.Struct({ read: Count, write: Count })
35077
+ }),
35078
+ cost: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.Number.check(exports_Schema.isFinite(), exports_Schema.isGreaterThanOrEqualTo(0)))),
35079
+ path: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.Struct({ cwd: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.String)) }))),
35080
+ directory: exports_Schema.optionalKey(exports_Schema.NullOr(exports_Schema.String)),
35081
+ forked: exports_Schema.optionalKey(exports_Schema.Boolean)
35082
+ }));
35083
+ function payer(providerID, cost) {
35084
+ if (providerID === "github-copilot")
35085
+ return "copilot";
35086
+ if (providerID === "openai" && cost === 0)
35087
+ return "codex";
35088
+ return;
35089
+ }
35090
+ function opencodeHistory(nativePath) {
35091
+ const sessions = new Map;
35092
+ const originals = new Map;
35093
+ const copied = new Set;
35094
+ const pending = new Map;
35095
+ const native = (value5) => value5 === undefined || value5 === null || value5 === "" ? null : nativePath(value5);
35096
+ const sessionParser = {
35097
+ parse(line) {
35098
+ const raw2 = exports_Option.getOrNull(decodeJson(line));
35099
+ const session = raw2 === null ? null : exports_Option.getOrNull(decodeSession(raw2));
35100
+ if (session === null)
35101
+ return malformed;
35102
+ sessions.set(session.id, session.time.created);
35103
+ return empty14;
35104
+ }
35105
+ };
35106
+ const messageParser = {
35107
+ parse(line) {
35108
+ const raw2 = exports_Option.getOrNull(decodeJson(line));
35109
+ if (raw2 === null)
35110
+ return malformed;
35111
+ const carrier = exports_Option.getOrNull(decodeCarrier(raw2));
35112
+ if (carrier === null)
35113
+ return malformed;
35114
+ const assistant = carrier.role === "assistant";
35115
+ if (carrier.tokens === undefined || carrier.tokens === null)
35116
+ return assistant ? skipped : empty14;
35117
+ if (!assistant && carrier.role !== "compaction")
35118
+ return skipped;
35119
+ const message = exports_Option.getOrNull(decodeMessage(raw2));
35120
+ if (message === null || assistant && (!message.providerID || !message.modelID))
35121
+ return skipped;
35122
+ const { tokens: tokens2 } = message;
35123
+ const counts = {
35124
+ input: tokens2.input,
35125
+ cacheRead: tokens2.cache.read,
35126
+ cacheWrite: tokens2.cache.write,
35127
+ output: tokens2.output + tokens2.reasoning
35128
+ };
35129
+ const billingProvider = totalTokens(counts) > 0 ? payer(message.providerID, message.cost) : undefined;
35130
+ const own = {
35131
+ provider: "opencode",
35132
+ id: message.id,
35133
+ session: message.sessionID,
35134
+ timestamp: message.time.created,
35135
+ model: message.modelID ?? unattributedModel,
35136
+ cwd: native(message.path?.cwd) ?? native(message.directory),
35137
+ repository: null,
35138
+ tokens: counts
35139
+ };
35140
+ const record3 = billingProvider === undefined ? own : { ...own, billingProvider };
35141
+ const copyId = `fork:${JSON.stringify([
35142
+ message.time.created,
35143
+ message.providerID,
35144
+ message.modelID,
35145
+ tokens2.input,
35146
+ tokens2.output,
35147
+ tokens2.reasoning,
35148
+ tokens2.cache.read,
35149
+ tokens2.cache.write
35150
+ ])}`;
35151
+ const warnings = message.modelID === undefined || message.modelID === null ? [
35152
+ "OpenCode compactions that failed name no model; these tokens remain unpriced unless an explicit rate is supplied."
35153
+ ] : [];
35154
+ if (message.forked === undefined) {
35155
+ pending.set(record3, copyId);
35156
+ return { ...empty14, deferred: [record3], warnings };
35157
+ }
35158
+ if (message.forked) {
35159
+ copied.add(message.id);
35160
+ return { ...empty14, inherited: [{ ...record3, id: copyId }], warnings };
35161
+ }
35162
+ if (!originals.has(copyId))
35163
+ originals.set(copyId, message.id);
35164
+ return { ...empty14, records: [record3], warnings };
35165
+ }
35166
+ };
35167
+ return {
35168
+ parser: (file2) => file2 === "session" ? sessionParser : messageParser,
35169
+ classify: (record3) => {
35170
+ const copyId = pending.get(record3) ?? record3.id;
35171
+ const started = sessions.get(record3.session);
35172
+ if (copied.has(record3.id) || started !== undefined && record3.timestamp < started)
35173
+ return { record: { ...record3, id: copyId }, copy: true };
35174
+ if (!originals.has(copyId))
35175
+ originals.set(copyId, record3.id);
35176
+ return { record: record3, copy: false };
35177
+ },
35178
+ settle: (record3) => record3.provider === "opencode" ? { ...record3, id: originals.get(record3.id) ?? record3.id } : record3
35179
+ };
35180
+ }
35181
+
34979
35182
  // packages/core/src/providers/pi.ts
34980
35183
  var decodeKind = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ type: exports_Schema.String }));
34981
35184
  var decodeHeader = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
@@ -34985,7 +35188,7 @@ var decodeHeader = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
34985
35188
  parentSession: exports_Schema.optionalKey(exports_Schema.String)
34986
35189
  }));
34987
35190
  var decodeWrapper = exports_Schema.decodeUnknownOption(exports_Schema.Struct({ message: exports_Schema.Unknown }));
34988
- var decodeCarrier = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
35191
+ var decodeCarrier2 = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
34989
35192
  role: exports_Schema.optionalKey(exports_Schema.String),
34990
35193
  usage: exports_Schema.optionalKey(exports_Schema.Unknown)
34991
35194
  }));
@@ -35001,7 +35204,7 @@ var decodeCounts = exports_Schema.decodeUnknownOption(exports_Schema.Struct({
35001
35204
  cacheRead: exports_Schema.Natural,
35002
35205
  cacheWrite: exports_Schema.Natural
35003
35206
  }));
35004
- var unattributedModel = "unknown";
35207
+ var unattributedModel2 = "unknown";
35005
35208
  var chatGptSignIn = "openai-codex";
35006
35209
  function piParser(file2) {
35007
35210
  let session = file2;
@@ -35027,7 +35230,7 @@ function piParser(file2) {
35027
35230
  return empty14;
35028
35231
  }
35029
35232
  const wrapper = type3 === "message" ? exports_Option.getOrNull(decodeWrapper(raw2)) : { message: raw2 };
35030
- const carrier = wrapper === null ? null : exports_Option.getOrNull(decodeCarrier(wrapper.message));
35233
+ const carrier = wrapper === null ? null : exports_Option.getOrNull(decodeCarrier2(wrapper.message));
35031
35234
  if (wrapper === null || carrier === null)
35032
35235
  return type3 === "message" ? malformed : empty14;
35033
35236
  const assistant = type3 === "message" && carrier.role === "assistant";
@@ -35050,7 +35253,7 @@ function piParser(file2) {
35050
35253
  id: stamp.id === undefined ? `${file2}:${lineNumber}` : `${stamp.id}:${stamp.timestamp}`,
35051
35254
  session,
35052
35255
  timestamp: ms,
35053
- model: model ?? unattributedModel,
35256
+ model: model ?? unattributedModel2,
35054
35257
  cwd,
35055
35258
  repository: null,
35056
35259
  tokens: count2
@@ -35284,7 +35487,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35284
35487
  }
35285
35488
  return request3;
35286
35489
  });
35287
- const scan2 = exports_Effect.fn("Ledger.scan")(function* (request3, start, locate, collect2, notice, onWarning) {
35490
+ const scan2 = exports_Effect.fn("Ledger.scan")(function* (request3, range3, locate, collect2, notice, onWarning) {
35288
35491
  const hints = yield* (notice !== undefined && request3.billingHints !== undefined && request3.sources.some((source) => source.provider === "copilot") ? readBillingHints(request3.billingHints).pipe(exports_Effect.provideService(exports_FileSystem.FileSystem, fs), exports_Effect.provideService(exports_Path.Path, path)) : exports_Effect.succeed(new Map)).pipe(exports_Effect.result);
35289
35492
  const chatgptRequests = exports_Result.isSuccess(hints) ? hints.success : new Map;
35290
35493
  if (exports_Result.isFailure(hints))
@@ -35295,6 +35498,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35295
35498
  const settledFiles = new Set;
35296
35499
  const coverage = [];
35297
35500
  const inherited = [];
35501
+ const deferred = [];
35502
+ const opencode = opencodeHistory((value5) => path.normalize(value5));
35298
35503
  for (const source of request3.sources) {
35299
35504
  let files = 0;
35300
35505
  let filesBeforeWindow = 0;
@@ -35331,13 +35536,23 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35331
35536
  for (const record3 of result6.inherited) {
35332
35537
  const slot = locate(record3.timestamp);
35333
35538
  if (slot !== undefined && totalTokens(record3.tokens) > 0)
35334
- inherited.push(place(record3, slot));
35539
+ inherited.push(exports_Effect.suspend(() => place(opencode.settle(record3), slot)));
35540
+ }
35541
+ for (const record3 of result6.deferred) {
35542
+ const slot = locate(record3.timestamp);
35543
+ if (slot !== undefined && totalTokens(record3.tokens) > 0)
35544
+ deferred.push(exports_Effect.suspend(() => {
35545
+ const classified = opencode.classify(record3);
35546
+ return classified.copy ? exports_Effect.sync(() => {
35547
+ inherited.push(exports_Effect.suspend(() => place(opencode.settle(classified.record), slot)));
35548
+ }) : place(classified.record, slot);
35549
+ }));
35335
35550
  }
35336
35551
  });
35337
35552
  const scanFile = exports_Effect.fn("Ledger.scanFile")(function* (file2, info2) {
35338
35553
  const canonical = yield* fs.realPath(file2);
35339
35554
  const identity3 = `${source.provider}:${canonical}`;
35340
- const settled = settledBefore(source, file2, info2, start - modifiedSlack);
35555
+ const settled = settledBefore(path, source, file2, info2, range3.start - modifiedSlack);
35341
35556
  if (visitedFiles.has(identity3) || settled && settledFiles.has(identity3)) {
35342
35557
  warnings.add("An overlapping source was counted once; the first source's project override wins.");
35343
35558
  return;
@@ -35348,10 +35563,10 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35348
35563
  return;
35349
35564
  }
35350
35565
  visitedFiles.add(identity3);
35351
- const parser = exports_Match.value(source.provider).pipe(exports_Match.when("codex", () => codexParser(canonical)), exports_Match.when("claude", () => claudeParser(canonical)), exports_Match.when("grok", () => grokParser(canonical)), exports_Match.when("copilot", () => copilot ?? copilotParser(canonical)), exports_Match.when("pi", () => piParser(canonical)), exports_Match.exhaustive);
35566
+ const parser = exports_Match.value(source.provider).pipe(exports_Match.when("codex", () => codexParser(canonical)), exports_Match.when("claude", () => claudeParser(canonical)), exports_Match.when("grok", () => grokParser(canonical)), exports_Match.when("copilot", () => copilot ?? copilotParser(canonical)), exports_Match.when("pi", () => piParser(canonical)), exports_Match.when("opencode", () => opencode.parser(opencodeFile(path, canonical))), exports_Match.exhaustive);
35352
35567
  let lineNumber = 0;
35353
35568
  files++;
35354
- const lines = source.provider === "copilot" && canonical.endsWith(".db") ? exports_Stream.fromIterableEffect(copilotDatabaseLines(canonical)) : fs.stream(canonical).pipe(exports_Stream.decodeText, exports_Stream.splitLines);
35569
+ const lines = source.provider === "copilot" && canonical.endsWith(".db") ? exports_Stream.fromIterableEffect(copilotDatabaseLines(canonical)) : source.provider === "opencode" ? opencodeFile(path, canonical) === "database" ? exports_Stream.fromIterableEffect(opencodeDatabaseLines(canonical, range3.start, range3.end)) : exports_Stream.fromEffect(fs.readFileString(canonical)) : fs.stream(canonical).pipe(exports_Stream.decodeText, exports_Stream.splitLines);
35355
35570
  yield* lines.pipe(exports_Stream.runForEach(exports_Effect.fn("Ledger.line")(function* (line) {
35356
35571
  lineNumber++;
35357
35572
  if (!line.trim())
@@ -35370,6 +35585,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35370
35585
  const result6 = yield* exports_Effect.gen(function* () {
35371
35586
  const stat3 = yield* fs.stat(entry);
35372
35587
  if (stat3.type === "Directory") {
35588
+ if (!descends(path, source, entry))
35589
+ return;
35373
35590
  const canonical = yield* fs.realPath(entry);
35374
35591
  if (visitedDirectories.has(canonical))
35375
35592
  return;
@@ -35377,7 +35594,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35377
35594
  const children = yield* fs.readDirectory(entry);
35378
35595
  for (const child of children.toSorted().toReversed())
35379
35596
  pending.push(path.join(entry, child));
35380
- } else if (stat3.type === "File" && acceptsFile(source, entry)) {
35597
+ } else if (stat3.type === "File" && acceptsFile(path, source, entry)) {
35381
35598
  yield* scanFile(entry, stat3);
35382
35599
  }
35383
35600
  }).pipe(exports_Effect.result);
@@ -35393,7 +35610,10 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35393
35610
  const hintsFailed = source.provider === "copilot" && exports_Result.isFailure(hints);
35394
35611
  if (hintsFailed)
35395
35612
  warnings.add("Billing hints could not be read; stored Copilot usage will be kept.");
35396
- const status = hintsFailed ? "failed" : missingRoot ? "missing" : failedFiles > 0 && files === 0 ? "failed" : failedFiles > 0 || malformedLines > 0 || skippedRecords > 0 ? "partial" : "ok";
35613
+ const unrecognised = source.provider === "opencode" && !missingRoot && failedFiles === 0 && files === 0 && filesBeforeWindow === 0;
35614
+ if (unrecognised)
35615
+ warnings.add("No OpenCode database or legacy message or session was found here.");
35616
+ const status = hintsFailed ? "failed" : missingRoot || unrecognised ? "missing" : failedFiles > 0 && files === 0 ? "failed" : failedFiles > 0 || malformedLines > 0 || skippedRecords > 0 ? "partial" : "ok";
35397
35617
  coverage.push(() => ({
35398
35618
  provider: source.provider,
35399
35619
  source: source.path,
@@ -35407,6 +35627,8 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35407
35627
  warnings: [...warnings]
35408
35628
  }));
35409
35629
  }
35630
+ for (const legacy of deferred)
35631
+ yield* legacy;
35410
35632
  for (const copy4 of inherited)
35411
35633
  yield* copy4;
35412
35634
  return coverage.map((summarize) => summarize());
@@ -35415,7 +35637,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35415
35637
  const request3 = yield* decode5(input);
35416
35638
  const window = dayWindow(request3.since, request3.until, request3.timeZone);
35417
35639
  const rows = new Map;
35418
- const coverage = yield* scan2(request3, window.start, window.dayOf, (record3, { project }, day) => {
35640
+ const coverage = yield* scan2(request3, window, window.dayOf, (record3, { project }, day) => {
35419
35641
  const key = JSON.stringify([project, day, record3.provider, record3.model]);
35420
35642
  const price = lookupPrice(request3.pricing, record3.model);
35421
35643
  rows.set(key, {
@@ -35454,7 +35676,7 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35454
35676
  const hints = planHints();
35455
35677
  let earliest = requested.start;
35456
35678
  const snapshotAt = yield* exports_Clock.currentTimeMillis;
35457
- const coverage = yield* scan2(request3, from, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
35679
+ const coverage = yield* scan2(request3, { start: from, end: requested.end }, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
35458
35680
  earliest = Math.min(earliest, timestamp2);
35459
35681
  buckets.add(record3, attribution.shareable ? attribution.project : unattributed);
35460
35682
  }, (plan) => {
@@ -35498,15 +35720,39 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35498
35720
  });
35499
35721
  }));
35500
35722
  }
35501
- function acceptsFile(source, file2) {
35723
+ function acceptsFile(path, source, file2) {
35502
35724
  if (source.path === file2)
35503
35725
  return true;
35504
35726
  if (source.provider === "grok")
35505
35727
  return file2.endsWith("/updates.jsonl") || file2.endsWith("\\updates.jsonl");
35728
+ if (source.provider === "opencode")
35729
+ return opencodeFile(path, file2) !== "database" || opencodeDatabaseName.test(path.basename(file2));
35506
35730
  return file2.endsWith(".jsonl") || source.provider === "copilot" && file2.endsWith(".db");
35507
35731
  }
35508
- function settledBefore(source, file2, info2, cutoff) {
35509
- if (source.path === file2 || source.provider === "copilot")
35732
+ function opencodeFile(path, file2) {
35733
+ const name = path.basename(file2);
35734
+ if (!name.endsWith(".json"))
35735
+ return "database";
35736
+ return name.startsWith("msg_") ? "message" : name.startsWith("ses_") ? "session" : "database";
35737
+ }
35738
+ var opencodeElsewhere = new Set([
35739
+ "bin",
35740
+ "log",
35741
+ "part",
35742
+ "repos",
35743
+ "session_diff",
35744
+ "session_share",
35745
+ "share",
35746
+ "shell",
35747
+ "snapshot",
35748
+ "todo",
35749
+ "tool-output"
35750
+ ]);
35751
+ function descends(path, source, directory) {
35752
+ return source.provider !== "opencode" || directory === source.path || !opencodeElsewhere.has(path.basename(directory));
35753
+ }
35754
+ function settledBefore(path, source, file2, info2, cutoff) {
35755
+ if (source.path === file2 || source.provider === "copilot" || source.provider === "opencode" && opencodeFile(path, file2) !== "message")
35510
35756
  return false;
35511
35757
  return exports_Option.isSome(info2.mtime) && info2.mtime.value.getTime() < cutoff;
35512
35758
  }
@@ -41627,10 +41873,10 @@ function lex(argv) {
41627
41873
  }
41628
41874
  var negativeNumberRegex = /^-(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
41629
41875
  var lexTokens = (args2) => {
41630
- const tokens = [];
41876
+ const tokens2 = [];
41631
41877
  for (const arg of args2) {
41632
41878
  if (!arg.startsWith("-") || negativeNumberRegex.test(arg)) {
41633
- tokens.push({
41879
+ tokens2.push({
41634
41880
  _tag: "Value",
41635
41881
  value: arg
41636
41882
  });
@@ -41639,14 +41885,14 @@ var lexTokens = (args2) => {
41639
41885
  if (equalIndex !== -1) {
41640
41886
  const name = arg.slice(2, equalIndex);
41641
41887
  const value5 = arg.slice(equalIndex + 1);
41642
- tokens.push({
41888
+ tokens2.push({
41643
41889
  _tag: "LongOption",
41644
41890
  name,
41645
41891
  raw: arg,
41646
41892
  value: value5
41647
41893
  });
41648
41894
  } else {
41649
- tokens.push({
41895
+ tokens2.push({
41650
41896
  _tag: "LongOption",
41651
41897
  name: arg.slice(2),
41652
41898
  raw: arg
@@ -41658,7 +41904,7 @@ var lexTokens = (args2) => {
41658
41904
  if (equalIndex !== -1) {
41659
41905
  const flag = flags.slice(0, equalIndex);
41660
41906
  const value5 = flags.slice(equalIndex + 1);
41661
- tokens.push({
41907
+ tokens2.push({
41662
41908
  _tag: "ShortOption",
41663
41909
  flag,
41664
41910
  raw: `-${flag}`,
@@ -41666,7 +41912,7 @@ var lexTokens = (args2) => {
41666
41912
  });
41667
41913
  } else {
41668
41914
  for (const ch of flags) {
41669
- tokens.push({
41915
+ tokens2.push({
41670
41916
  _tag: "ShortOption",
41671
41917
  flag: ch,
41672
41918
  raw: `-${ch}`
@@ -41674,13 +41920,13 @@ var lexTokens = (args2) => {
41674
41920
  }
41675
41921
  }
41676
41922
  } else {
41677
- tokens.push({
41923
+ tokens2.push({
41678
41924
  _tag: "Value",
41679
41925
  value: arg
41680
41926
  });
41681
41927
  }
41682
41928
  }
41683
- return tokens;
41929
+ return tokens2;
41684
41930
  };
41685
41931
 
41686
41932
  // node_modules/.bun/effect@4.0.0/node_modules/effect/dist/cli/internal/auto-suggest.js
@@ -41717,7 +41963,7 @@ var getCommandPath = (parsedInput) => match(parsedInput.subcommand, {
41717
41963
  });
41718
41964
  var parseArgs = (lexResult, command, commandPath = []) => gen4(function* () {
41719
41965
  const {
41720
- tokens,
41966
+ tokens: tokens2,
41721
41967
  trailingOperands: afterEndOfOptions
41722
41968
  } = lexResult;
41723
41969
  const newCommandPath = [...commandPath, command.name];
@@ -41736,7 +41982,7 @@ var parseArgs = (lexResult, command, commandPath = []) => gen4(function* () {
41736
41982
  inheritedFlagRegistry,
41737
41983
  localFlagNames: flagParams.filter((param) => !inheritedNames.has(param.name)).map((param) => param.name)
41738
41984
  };
41739
- const result6 = scanCommandLevel(tokens, context3);
41985
+ const result6 = scanCommandLevel(tokens2, context3);
41740
41986
  if (result6._tag === "Leaf") {
41741
41987
  return {
41742
41988
  flags: result6.flags,
@@ -41765,12 +42011,12 @@ var parseArgs = (lexResult, command, commandPath = []) => gen4(function* () {
41765
42011
  }
41766
42012
  };
41767
42013
  });
41768
- var makeCursor = (tokens) => {
42014
+ var makeCursor = (tokens2) => {
41769
42015
  let i = 0;
41770
42016
  return {
41771
- peek: () => tokens[i],
41772
- take: () => tokens[i++],
41773
- rest: () => tokens.slice(i)
42017
+ peek: () => tokens2[i],
42018
+ take: () => tokens2[i++],
42019
+ rest: () => tokens2.slice(i)
41774
42020
  };
41775
42021
  };
41776
42022
  var createFlagRegistry = (params) => {
@@ -41947,11 +42193,11 @@ var consumeFlagValueWithTokens = (cursor, token, spec, negated = false) => {
41947
42193
  tokens: []
41948
42194
  };
41949
42195
  };
41950
- var consumeKnownFlags = (tokens, registry) => {
42196
+ var consumeKnownFlags = (tokens2, registry) => {
41951
42197
  const flagMap = createEmptyFlagMap(registry.params);
41952
42198
  const remainder2 = [];
41953
42199
  const errors = [];
41954
- const cursor = makeCursor(tokens);
42200
+ const cursor = makeCursor(tokens2);
41955
42201
  for (let t = cursor.take();t; t = cursor.take()) {
41956
42202
  if (!isFlagToken(t)) {
41957
42203
  remainder2.push(t);
@@ -42018,14 +42264,14 @@ var localFlagWouldPrecedeSubcommand = (token, remainingTokens, resolved, subInde
42018
42264
  }
42019
42265
  return false;
42020
42266
  };
42021
- var consumeGlobalFlags = (tokens, command, registry) => {
42267
+ var consumeGlobalFlags = (tokens2, command, registry) => {
42022
42268
  const flagMap = createEmptyFlagMap(registry.params);
42023
42269
  const errors = [];
42024
- const consumeLevel = (tokens2, command2, ignoredRegistries) => {
42270
+ const consumeLevel = (tokens3, command2, ignoredRegistries) => {
42025
42271
  const localRegistry = createFlagRegistry(extractFlagParams(command2));
42026
42272
  const inheritedRegistry = createFlagRegistry(extractContextFlagParams(command2));
42027
42273
  const subIndex = buildSubcommandIndex(command2.subcommands);
42028
- const cursor = makeCursor(tokens2);
42274
+ const cursor = makeCursor(tokens3);
42029
42275
  const remainder2 = [];
42030
42276
  let awaitingFirstValue = true;
42031
42277
  for (let token = cursor.take();token; token = cursor.take()) {
@@ -42077,7 +42323,7 @@ var consumeGlobalFlags = (tokens, command, registry) => {
42077
42323
  };
42078
42324
  return {
42079
42325
  flagMap,
42080
- remainder: consumeLevel(tokens, command, []),
42326
+ remainder: consumeLevel(tokens2, command, []),
42081
42327
  errors
42082
42328
  };
42083
42329
  };
@@ -42200,8 +42446,8 @@ var processValue = (value5, cursor, context3, state) => {
42200
42446
  state.arguments.push(value5);
42201
42447
  return;
42202
42448
  };
42203
- var scanCommandLevel = (tokens, context3) => {
42204
- const cursor = makeCursor(tokens);
42449
+ var scanCommandLevel = (tokens2, context3) => {
42450
+ const cursor = makeCursor(tokens2);
42205
42451
  const state = createParseState(context3.flagRegistry);
42206
42452
  for (let token = cursor.take();token; token = cursor.take()) {
42207
42453
  if (isFlagToken(token)) {
@@ -42704,7 +42950,7 @@ var runWith2 = (command, config) => {
42704
42950
  builtIns
42705
42951
  } = yield* CliConfig;
42706
42952
  const {
42707
- tokens,
42953
+ tokens: tokens2,
42708
42954
  trailingOperands
42709
42955
  } = lex(args2);
42710
42956
  const allFlags = getGlobalFlagsForCommandTree(command, builtIns);
@@ -42714,7 +42960,7 @@ var runWith2 = (command, config) => {
42714
42960
  flagMap,
42715
42961
  remainder: remainder2,
42716
42962
  errors: globalFlagErrors
42717
- } = consumeGlobalFlags(tokens, command, globalRegistry);
42963
+ } = consumeGlobalFlags(tokens2, command, globalRegistry);
42718
42964
  const emptyArgs = {
42719
42965
  flags: flagMap,
42720
42966
  arguments: []
@@ -42809,7 +43055,7 @@ var runWith2 = (command, config) => {
42809
43055
  // packages/cli/package.json
42810
43056
  var package_default = {
42811
43057
  name: "@ponbac/token-ledger",
42812
- version: "0.7.0",
43058
+ version: "0.9.0",
42813
43059
  private: true,
42814
43060
  type: "module",
42815
43061
  bin: {
@@ -43981,6 +44227,22 @@ class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
43981
44227
  }) {
43982
44228
  }
43983
44229
  var TimeOfDay = exports_Schema.String.check(exports_Schema.isPattern(/^(?:[01]\d|2[0-3]):[0-5]\d$/));
44230
+ var intervals = [
44231
+ ["1h", 1],
44232
+ ["2h", 2],
44233
+ ["3h", 3],
44234
+ ["4h", 4],
44235
+ ["6h", 6],
44236
+ ["8h", 8],
44237
+ ["12h", 12],
44238
+ ["24h", 24]
44239
+ ];
44240
+ function syncTimes(job) {
44241
+ const hour2 = Number(job.at.slice(0, 2));
44242
+ const minute = job.at.slice(3);
44243
+ return Array.from({ length: 24 / job.every }, (_, index2) => `${String(hour2 % job.every + index2 * job.every).padStart(2, "0")}:${minute}`);
44244
+ }
44245
+ var describeTimes = (job) => job.every === 24 ? `daily at ${job.at}` : `every ${job.every === 1 ? "hour" : `${job.every} hours`}, at ${syncTimes(job).join(", ")}`;
43984
44246
  var Action3 = exports_Data.taggedEnum();
43985
44247
  var unit = "token-ledger-sync";
43986
44248
  var label = "com.github.ponbac.token-ledger.sync";
@@ -44038,10 +44300,10 @@ ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
44038
44300
  Action3.Write({
44039
44301
  file: timer,
44040
44302
  contents: `[Unit]
44041
- Description=Daily AI usage sync
44303
+ Description=AI usage sync ${job2.every === 24 ? "once a day" : `every ${job2.every}h`}
44042
44304
 
44043
44305
  [Timer]
44044
- OnCalendar=*-*-* ${job2.at}:00
44306
+ OnCalendar=*-*-* ${syncTimes(job2).map((time2) => time2.slice(0, 2)).join(",")}:${job2.at.slice(3)}:00
44045
44307
  Persistent=true
44046
44308
  RandomizedDelaySec=10m
44047
44309
 
@@ -44075,7 +44337,16 @@ function launchAgent(home, uid) {
44075
44337
  return {
44076
44338
  name: "launchd agent",
44077
44339
  install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => {
44078
- const [hour2, minute] = job2.at.split(":").map(Number);
44340
+ const times = syncTimes(job2).map((time2) => {
44341
+ const [hour2, minute] = time2.split(":").map(Number);
44342
+ return ` <dict>
44343
+ <key>Hour</key>
44344
+ <integer>${hour2}</integer>
44345
+ <key>Minute</key>
44346
+ <integer>${minute}</integer>
44347
+ </dict>`;
44348
+ }).join(`
44349
+ `);
44079
44350
  return [
44080
44351
  Action3.Write({
44081
44352
  file: plist,
@@ -44094,12 +44365,9 @@ function launchAgent(home, uid) {
44094
44365
  <key>RunAtLoad</key>
44095
44366
  <true/>
44096
44367
  <key>StartCalendarInterval</key>
44097
- <dict>
44098
- <key>Hour</key>
44099
- <integer>${hour2}</integer>
44100
- <key>Minute</key>
44101
- <integer>${minute}</integer>
44102
- </dict>
44368
+ <array>
44369
+ ${times}
44370
+ </array>
44103
44371
  <key>StandardOutPath</key>
44104
44372
  <string>${xmlText(log3)}</string>
44105
44373
  <key>StandardErrorPath</key>
@@ -44141,7 +44409,10 @@ function taskScheduler(file2) {
44141
44409
  "$ErrorActionPreference = 'Stop'",
44142
44410
  "$ProgressPreference = 'SilentlyContinue'",
44143
44411
  `$action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ${powershellString(`//B //Nologo //E:JScript "${file2}"`)}`,
44144
- `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
44412
+ `$trigger = New-ScheduledTaskTrigger -Daily -At '${syncTimes(job2)[0]}'`,
44413
+ ...job2.every === 24 ? [] : [
44414
+ `$trigger.Repetition = (New-ScheduledTaskTrigger -Once -At '${syncTimes(job2)[0]}' -RepetitionInterval (New-TimeSpan -Hours ${job2.every}) -RepetitionDuration (New-TimeSpan -Hours ${24 - job2.every})).Repetition`
44415
+ ],
44145
44416
  "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44146
44417
  `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44147
44418
  ].join(`
@@ -45156,21 +45427,21 @@ var getWidth = (string4) => {
45156
45427
  return getStringWidth(plainText);
45157
45428
  };
45158
45429
  var getTokens = (string4) => {
45159
- const tokens = [];
45430
+ const tokens2 = [];
45160
45431
  forEachSegment(string4, (plainText) => {
45161
45432
  if (ASCII_PRINTABLE_REGEX.test(plainText)) {
45162
45433
  for (const character of plainText) {
45163
- tokens.push({ value: character, width: 1 });
45434
+ tokens2.push({ value: character, width: 1 });
45164
45435
  }
45165
45436
  return;
45166
45437
  }
45167
45438
  for (const { segment } of segmenter2.segment(plainText)) {
45168
- tokens.push({ value: segment, width: getStringWidth(segment) });
45439
+ tokens2.push({ value: segment, width: getStringWidth(segment) });
45169
45440
  }
45170
45441
  }, (escape2) => {
45171
- tokens.push({ value: escape2, width: 0 });
45442
+ tokens2.push({ value: escape2, width: 0 });
45172
45443
  });
45173
- return tokens;
45444
+ return tokens2;
45174
45445
  };
45175
45446
  var splitWords = (string4) => {
45176
45447
  let currentWord = { value: "", plainText: "" };
@@ -45361,17 +45632,17 @@ var applyLeadingSgrResets = (string4, startIndex, activeStyles) => {
45361
45632
  var getClosingSgrSequence = (activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join("");
45362
45633
  var getOpeningSgrSequence = (activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join("");
45363
45634
  var wrapWord = (rows, word, columns, rowWidth) => {
45364
- const tokens = getTokens(word);
45635
+ const tokens2 = getTokens(word);
45365
45636
  let visible = rowWidth;
45366
- for (let index2 = 0;index2 < tokens.length; index2++) {
45367
- const token = tokens[index2];
45637
+ for (let index2 = 0;index2 < tokens2.length; index2++) {
45638
+ const token = tokens2[index2];
45368
45639
  if (token.width > 0 && visible > 0 && visible + token.width > columns) {
45369
45640
  rows.push("");
45370
45641
  visible = 0;
45371
45642
  }
45372
45643
  rows[rows.length - 1] += token.value;
45373
45644
  visible += token.width;
45374
- if (visible === columns && index2 < tokens.length - 1) {
45645
+ if (visible === columns && index2 < tokens2.length - 1) {
45375
45646
  rows.push("");
45376
45647
  visible = 0;
45377
45648
  }
@@ -45818,7 +46089,15 @@ function usageFlags(sinceDefault, strict) {
45818
46089
  since: exports_Flag.String("since").pipe(exports_Flag.withSchema(Day), exports_Flag.optional, exports_Flag.withDescription(`First local day, inclusive; defaults to ${sinceDefault}`)),
45819
46090
  until: exports_Flag.String("until").pipe(exports_Flag.withSchema(Day), exports_Flag.optional, exports_Flag.withDescription("Last local day, inclusive; defaults to today")),
45820
46091
  timeZone: exports_Flag.String("time-zone").pipe(exports_Flag.withSchema(exports_Schema.TimeZoneNamedFromString), exports_Flag.optional, exports_Flag.withDescription("IANA time zone for days and the window, such as Europe/Stockholm; defaults to the system zone")),
45821
- provider: exports_Flag.Literals("provider", ["all", "codex", "claude", "grok", "copilot", "pi"]).pipe(exports_Flag.withDefault("all")),
46092
+ provider: exports_Flag.Literals("provider", [
46093
+ "all",
46094
+ "codex",
46095
+ "claude",
46096
+ "grok",
46097
+ "copilot",
46098
+ "pi",
46099
+ "opencode"
46100
+ ]).pipe(exports_Flag.withDefault("all")),
45822
46101
  project: exports_Flag.String("project").pipe(exports_Flag.withSchema(ProjectName), exports_Flag.optional, exports_Flag.withDescription("Assign all selected usage to this project")),
45823
46102
  config: exports_Flag.String("config").pipe(exports_Flag.optional, exports_Flag.withDescription("JSON config; otherwise reads ./token-ledger.json when present")),
45824
46103
  offline: exports_Flag.Boolean("offline").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Use only cached and configured prices")),
@@ -45845,6 +46124,8 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
45845
46124
  const copilotFile = yield* exports_Config.String("COPILOT_OTEL_FILE_EXPORTER_PATH").pipe(exports_Config.option);
45846
46125
  const piHome = yield* exports_Config.String("PI_CODING_AGENT_DIR").pipe(exports_Config.withDefault(path.join(home, ".pi", "agent")));
45847
46126
  const piSessions = yield* exports_Config.String("PI_CODING_AGENT_SESSION_DIR").pipe(exports_Config.option);
46127
+ const opencodeData = path.join(exports_Option.getOrElse(yield* dataHome, () => path.join(home, ".local", "share")), "opencode");
46128
+ const opencodeDatabase = exports_Option.map(exports_Option.filter(yield* exports_Config.String("OPENCODE_DB").pipe(exports_Config.option), (value5) => value5 !== "" && value5 !== ":memory:"), (value5) => path.resolve(opencodeData, value5));
45848
46129
  const defaults2 = [
45849
46130
  { provider: "codex", path: path.join(expand(codexHome), "sessions") },
45850
46131
  { provider: "codex", path: path.join(expand(codexHome), "archived_sessions") },
@@ -45857,7 +46138,12 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
45857
46138
  onNone: () => path.join(expand(piHome), "sessions"),
45858
46139
  onSome: (value5) => expand(value5)
45859
46140
  })
45860
- }
46141
+ },
46142
+ { provider: "opencode", path: opencodeData },
46143
+ ...exports_Option.match(opencodeDatabase, {
46144
+ onNone: () => [],
46145
+ onSome: (file2) => path.dirname(file2) === opencodeData && opencodeDatabaseName.test(path.basename(file2)) ? [] : [{ provider: "opencode", path: file2 }]
46146
+ })
45861
46147
  ];
45862
46148
  let sources = configuration.sources === undefined ? defaults2 : configuration.sources.map((source) => ({
45863
46149
  ...source,
@@ -45868,7 +46154,7 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
45868
46154
  if (exports_Option.isSome(flags.source)) {
45869
46155
  if (flags.provider === "all")
45870
46156
  return yield* new CliError2({
45871
- message: "--source requires --provider codex, claude, grok, copilot, or pi."
46157
+ message: "--source requires --provider codex, claude, grok, copilot, pi, or opencode."
45872
46158
  });
45873
46159
  sources = [{ provider: flags.provider, path: expand(flags.source.value) }];
45874
46160
  }
@@ -46039,10 +46325,19 @@ var login = exports_Command.make("login", {
46039
46325
  Next: token-ledger sync --dry-run, then token-ledger schedule install.`);
46040
46326
  })).pipe(exports_Command.withDescription("Save the toki2 server and API token in sync.json for sync and scheduled syncs"));
46041
46327
  var scheduleInstall = exports_Command.make("install", {
46042
- at: exports_Flag.String("at").pipe(exports_Flag.withDefault("12:30"), exports_Flag.withSchema(TimeOfDay), exports_Flag.withDescription("Daily local time as HH:MM; defaults to 12:30")),
46328
+ every: exports_Flag.ChoiceWithValue("every", intervals).pipe(exports_Flag.withDefault(2), exports_Flag.withDescription("Time between syncs; defaults to 2h")),
46329
+ at: exports_Flag.String("at").pipe(exports_Flag.withDefault("12:30"), exports_Flag.withSchema(TimeOfDay), exports_Flag.withDescription("A local time, as HH:MM, that a sync runs at; defaults to 12:30")),
46043
46330
  config: exports_Flag.String("config").pipe(exports_Flag.optional, exports_Flag.withDescription("JSON config for the scheduled sync; ./token-ledger.json is not read")),
46044
46331
  timeZone: exports_Flag.String("time-zone").pipe(exports_Flag.withSchema(exports_Schema.TimeZoneNamedFromString), exports_Flag.optional, exports_Flag.withDescription("IANA time zone for the scheduled sync; defaults to the system zone")),
46045
- provider: exports_Flag.Literals("provider", ["all", "codex", "claude", "grok", "copilot", "pi"]).pipe(exports_Flag.withDefault("all")),
46332
+ provider: exports_Flag.Literals("provider", [
46333
+ "all",
46334
+ "codex",
46335
+ "claude",
46336
+ "grok",
46337
+ "copilot",
46338
+ "pi",
46339
+ "opencode"
46340
+ ]).pipe(exports_Flag.withDefault("all")),
46046
46341
  dryRun: exports_Flag.Boolean("dry-run").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Print the files and commands; change nothing"))
46047
46342
  }, exports_Effect.fn("CLI.scheduleInstall")(function* (flags) {
46048
46343
  const fs = yield* exports_FileSystem.FileSystem;
@@ -46053,6 +46348,7 @@ var scheduleInstall = exports_Command.make("install", {
46053
46348
  return yield* new CliError2({ message: `Cannot find the configuration ${config.value}.` });
46054
46349
  const actions = yield* scheduler.install({
46055
46350
  at: flags.at,
46351
+ every: flags.every,
46056
46352
  nodeDirectory: path.dirname(process.execPath),
46057
46353
  configHome: yield* configHome,
46058
46354
  dataHome: yield* dataHome,
@@ -46074,18 +46370,18 @@ var scheduleInstall = exports_Command.make("install", {
46074
46370
  message: "No saved server and API token. Run token-ledger login first: a scheduled sync cannot read --token or your shell's environment."
46075
46371
  });
46076
46372
  yield* perform(actions);
46077
- yield* exports_Console.log(`Scheduled a daily sync at ${flags.at} as a ${scheduler.name}. Inspect it with token-ledger schedule status.`);
46078
- })).pipe(exports_Command.withDescription("Install or replace the daily sync; it needs the server and token saved by login"));
46373
+ yield* exports_Console.log(`Scheduled a sync ${describeTimes(flags)} as a ${scheduler.name}, replacing any earlier schedule. Inspect it with token-ledger schedule status.`);
46374
+ })).pipe(exports_Command.withDescription("Install or replace the scheduled sync; it needs the server and token saved by login"));
46079
46375
  var scheduleStatus = exports_Command.make("status", {}, exports_Effect.fn("CLI.scheduleStatus")(function* () {
46080
46376
  const scheduler = yield* hostScheduler;
46081
46377
  yield* perform(scheduler.status);
46082
- })).pipe(exports_Command.withDescription("Show the scheduler's own report of the daily sync"));
46378
+ })).pipe(exports_Command.withDescription("Show the scheduler's own report of the scheduled sync"));
46083
46379
  var scheduleUninstall = exports_Command.make("uninstall", {}, exports_Effect.fn("CLI.scheduleUninstall")(function* () {
46084
46380
  const scheduler = yield* hostScheduler;
46085
46381
  yield* perform(scheduler.uninstall);
46086
46382
  yield* exports_Console.log(`Removed the ${scheduler.name}. Saved settings were kept.`);
46087
- })).pipe(exports_Command.withDescription("Remove the daily sync; saved settings stay"));
46088
- var schedule4 = exports_Command.make("schedule").pipe(exports_Command.withDescription("Run sync daily with systemd, launchd, or Task Scheduler"), exports_Command.withSubcommands([scheduleInstall, scheduleStatus, scheduleUninstall]));
46383
+ })).pipe(exports_Command.withDescription("Remove the scheduled sync; saved settings stay"));
46384
+ var schedule4 = exports_Command.make("schedule").pipe(exports_Command.withDescription("Run sync every few hours with systemd, launchd, or Task Scheduler"), exports_Command.withSubcommands([scheduleInstall, scheduleStatus, scheduleUninstall]));
46089
46385
  var copilotEnable = exports_Command.make("enable", {
46090
46386
  cli: exports_Flag.Boolean("cli").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Copilot CLI: export its usage from every new terminal")),
46091
46387
  vscode: exports_Flag.Boolean("vscode").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("VS Code Copilot Chat: set its export in the user settings.json")),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ponbac/token-ledger",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Local AI token usage and API-equivalent cost reports by project",
5
5
  "license": "MIT",
6
6
  "engines": {