@jive-sh/skill-sync 0.4.15-latest-darwin-arm64 → 0.4.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -0
- package/bin/package.json +1 -0
- package/bin/skill-sync +576 -0
- package/bin/skill-sync-daemon +576 -0
- package/dist/daemons/skill-sync-daemon.js +500 -0
- package/dist/daemons/skill-sync-daemon.js.map +1 -0
- package/dist/entrypoints/skill-sync.js +153 -0
- package/dist/entrypoints/skill-sync.js.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/config.js +157 -0
- package/dist/internal/config.js.map +1 -0
- package/dist/internal/control.js +101 -0
- package/dist/internal/control.js.map +1 -0
- package/dist/internal/folders.js +46 -0
- package/dist/internal/folders.js.map +1 -0
- package/dist/internal/path.js +36 -0
- package/dist/internal/path.js.map +1 -0
- package/dist/internal/server.js +32 -0
- package/dist/internal/server.js.map +1 -0
- package/dist/internal/skill-check.js +83 -0
- package/dist/internal/skill-check.js.map +1 -0
- package/dist/internal/sync.js +162 -0
- package/dist/internal/sync.js.map +1 -0
- package/dist/internal/usage.js +419 -0
- package/dist/internal/usage.js.map +1 -0
- package/dist/internal/wire.js +24 -0
- package/dist/internal/wire.js.map +1 -0
- package/install.cjs +576 -0
- package/package.json +39 -11
- package/src/daemons/skill-sync-daemon.ts +493 -0
- package/src/entrypoints/skill-sync.ts +156 -0
- package/src/index.ts +15 -0
- package/src/internal/config.ts +198 -0
- package/src/internal/control.ts +140 -0
- package/src/internal/folders.ts +49 -0
- package/src/internal/path.ts +32 -0
- package/src/internal/server.ts +34 -0
- package/src/internal/skill-check.ts +97 -0
- package/src/internal/sync.ts +197 -0
- package/src/internal/usage.ts +457 -0
- package/src/internal/wire.ts +241 -0
- package/multi-call-binary +0 -4
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { hashBytes, isLock, listLocalFiles, type Config, type State } from "./config";
|
|
4
|
+
import { invalidPathReason } from "./path";
|
|
5
|
+
import { fetchServer } from "./server";
|
|
6
|
+
import { skillOf, type ListFilesResponse, type PutFileRequest } from "./wire";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* One sync cycle: take every newer edit the server has, then send every newer edit this folder has.
|
|
10
|
+
*
|
|
11
|
+
* The latest edit wins, always. Every file carries the time it was last edited: here, the file's
|
|
12
|
+
* modification time; on the server, the edit time of the version it holds. When this folder and the
|
|
13
|
+
* server disagree about a file, whichever was edited later is kept, on both sides. Nothing is merged and
|
|
14
|
+
* nothing is set aside, so every folder converges on the same bytes.
|
|
15
|
+
*
|
|
16
|
+
* A pulled file is given the server's edit time as its modification time, so the next cycle does not
|
|
17
|
+
* mistake the pull for a local edit.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export interface Report {
|
|
21
|
+
readonly pulled: string[];
|
|
22
|
+
readonly pushed: string[];
|
|
23
|
+
readonly deletedLocally: string[];
|
|
24
|
+
/** Paths the server offered that this machine refused to write. */
|
|
25
|
+
readonly rejected: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** True when a report has nothing in it worth telling anyone. */
|
|
29
|
+
export function isQuiet(report: Report): boolean {
|
|
30
|
+
return [report.pulled, report.pushed, report.deletedLocally, report.rejected].every((list) => list.length === 0);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* `skills` is the synced list. Every other skill in the folder is local to it: never pushed, never
|
|
35
|
+
* overwritten, never deleted by a sync.
|
|
36
|
+
*/
|
|
37
|
+
export async function syncOnce(config: Config, folder: string, state: State, skills: ReadonlySet<string>): Promise<Report> {
|
|
38
|
+
const report: Report = { pulled: [], pushed: [], deletedLocally: [], rejected: [] };
|
|
39
|
+
mkdirSync(folder, { recursive: true });
|
|
40
|
+
|
|
41
|
+
// A skill added to the list since last cycle may have server files older than the cursor; re-read from the start.
|
|
42
|
+
if ([...skills].some((skill) => !(state.skills ?? []).includes(skill))) state.cursor = 0;
|
|
43
|
+
state.skills = [...skills].sort();
|
|
44
|
+
// A skill removed from the list stops being tracked here. Left in `known`, its files would look deleted
|
|
45
|
+
// from this folder and the push would delete them on every machine.
|
|
46
|
+
for (const path of Object.keys(state.known)) {
|
|
47
|
+
if (!skills.has(skillOf(path)) || path.split("/").some(isLock)) delete state.known[path];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const present = new Set(listLocalFiles(folder, config.exclude).filter((path) => skills.has(skillOf(path))));
|
|
51
|
+
// Files deleted here since the last cycle. When they were deleted is not recorded anywhere, so the
|
|
52
|
+
// deletion counts as an edit made now: the pull leaves these paths alone and the push deletes them.
|
|
53
|
+
const deletedHere = new Set(Object.keys(state.known).filter((path) => !present.has(path)));
|
|
54
|
+
|
|
55
|
+
const ctx: Cycle = { config, folder, state, report, skills };
|
|
56
|
+
await pull(ctx, deletedHere, present);
|
|
57
|
+
await push(ctx, present);
|
|
58
|
+
return report;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface Cycle {
|
|
62
|
+
readonly config: Config;
|
|
63
|
+
readonly folder: string;
|
|
64
|
+
readonly state: State;
|
|
65
|
+
readonly report: Report;
|
|
66
|
+
readonly skills: ReadonlySet<string>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** When this file was last edited here, to the millisecond the server stores. */
|
|
70
|
+
const editedAt = (file: string): number => Math.floor(statSync(file).mtimeMs);
|
|
71
|
+
|
|
72
|
+
async function pull(ctx: Cycle, deletedHere: ReadonlySet<string>, present: Set<string>): Promise<void> {
|
|
73
|
+
const { config, folder, state, report } = ctx;
|
|
74
|
+
const body = await (await call(config, `/files?since=${state.cursor}`)).json() as ListFilesResponse;
|
|
75
|
+
|
|
76
|
+
for (const file of body.files) {
|
|
77
|
+
// The server is not trusted to supply a path either: one bad row would otherwise write outside the
|
|
78
|
+
// skills directory on every machine that syncs.
|
|
79
|
+
const badPath = invalidPathReason(file.path);
|
|
80
|
+
if (badPath) {
|
|
81
|
+
report.rejected.push(`${file.path} (${badPath})`);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (!ctx.skills.has(skillOf(file.path))) continue;
|
|
85
|
+
// Never written here: the file listing skips lock names, so a pulled one would read as deleted next cycle.
|
|
86
|
+
if (file.path.split("/").some(isLock)) continue;
|
|
87
|
+
// Deleted here, which is newer than anything the server has; the push sends the deletion.
|
|
88
|
+
if (deletedHere.has(file.path)) continue;
|
|
89
|
+
|
|
90
|
+
const local = join(folder, file.path);
|
|
91
|
+
const exists = existsSync(local);
|
|
92
|
+
const localHash = exists ? hashBytes(readFileSync(local)) : undefined;
|
|
93
|
+
if (localHash === (file.hash ?? undefined)) {
|
|
94
|
+
if (file.hash === null) delete state.known[file.path];
|
|
95
|
+
else state.known[file.path] = file.hash;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
// Edited here since this folder last agreed with the server, and later than the server's version:
|
|
99
|
+
// this folder's edit wins, and the push sends it.
|
|
100
|
+
if (exists && localHash !== state.known[file.path] && editedAt(local) > file.editedAt) continue;
|
|
101
|
+
|
|
102
|
+
await apply(ctx, file, present);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
state.cursor = body.cursor;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function push(ctx: Cycle, present: Set<string>): Promise<void> {
|
|
109
|
+
const { config, folder, state, report } = ctx;
|
|
110
|
+
for (const path of [...present]) {
|
|
111
|
+
const file = join(folder, path);
|
|
112
|
+
const bytes = readFileSync(file);
|
|
113
|
+
const hash = hashBytes(bytes);
|
|
114
|
+
if (state.known[path] === hash) continue;
|
|
115
|
+
const later = await put(config, { path, hash, content: Buffer.from(bytes).toString("base64"), editedAt: editedAt(file) });
|
|
116
|
+
if (later === undefined) {
|
|
117
|
+
state.known[path] = hash;
|
|
118
|
+
report.pushed.push(path);
|
|
119
|
+
} else {
|
|
120
|
+
await apply(ctx, { path, ...later }, present);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// A path this folder agreed on that is no longer on disk was deleted here. The server keeps the
|
|
125
|
+
// deletion, or the next machine to sync would upload the file again.
|
|
126
|
+
for (const path of Object.keys(state.known)) {
|
|
127
|
+
if (present.has(path)) continue;
|
|
128
|
+
const later = await put(config, { path, hash: null, content: null, editedAt: Date.now() });
|
|
129
|
+
if (later === undefined) {
|
|
130
|
+
delete state.known[path];
|
|
131
|
+
report.pushed.push(`${path} (deleted)`);
|
|
132
|
+
} else {
|
|
133
|
+
await apply(ctx, { path, ...later }, present);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The server's version of a file, as it answers a refused write. */
|
|
139
|
+
interface ServerVersion {
|
|
140
|
+
readonly hash: string | null;
|
|
141
|
+
readonly editedAt: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Writes the server's version of a file here: its bytes with its edit time, or a deletion. Used by the
|
|
146
|
+
* pull, and by the push when the server refuses a write because it holds a later edit, so a refused write
|
|
147
|
+
* settles at once rather than waiting for a pull that may never list the file again.
|
|
148
|
+
*/
|
|
149
|
+
async function apply(ctx: Cycle, file: ServerVersion & { readonly path: string }, present: Set<string>): Promise<void> {
|
|
150
|
+
const { config, folder, state, report } = ctx;
|
|
151
|
+
const local = join(folder, file.path);
|
|
152
|
+
if (file.hash === null) {
|
|
153
|
+
rmSync(local, { force: true });
|
|
154
|
+
removeEmptyParents(folder, local);
|
|
155
|
+
present.delete(file.path);
|
|
156
|
+
delete state.known[file.path];
|
|
157
|
+
report.deletedLocally.push(file.path);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const content = new Uint8Array(await (await call(config, `/content/${file.hash}`)).arrayBuffer());
|
|
161
|
+
mkdirSync(dirname(local), { recursive: true });
|
|
162
|
+
writeFileSync(local, content);
|
|
163
|
+
utimesSync(local, new Date(), new Date(file.editedAt));
|
|
164
|
+
state.known[file.path] = file.hash;
|
|
165
|
+
present.add(file.path);
|
|
166
|
+
report.pulled.push(file.path);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** A deleted skill leaves no empty directory behind, which would still show up as a skill. */
|
|
170
|
+
function removeEmptyParents(folder: string, file: string): void {
|
|
171
|
+
for (let dir = dirname(file); dir !== folder && dir.startsWith(folder); dir = dirname(dir)) {
|
|
172
|
+
if (readdirSync(dir).length > 0) return;
|
|
173
|
+
rmdirSync(dir);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Undefined when the server took the write; otherwise the later version it holds instead. */
|
|
178
|
+
async function put(config: Config, body: Omit<PutFileRequest, "machine">): Promise<ServerVersion | undefined> {
|
|
179
|
+
const request: PutFileRequest = { ...body, machine: config.machine };
|
|
180
|
+
const response = await fetchServer(config, "/files", {
|
|
181
|
+
method: "PUT",
|
|
182
|
+
headers: { "content-type": "application/json" },
|
|
183
|
+
body: JSON.stringify(request),
|
|
184
|
+
});
|
|
185
|
+
if (response.status === 409) {
|
|
186
|
+
const current = await response.json() as { currentHash: string | null; currentEditedAt: number };
|
|
187
|
+
return { hash: current.currentHash, editedAt: current.currentEditedAt };
|
|
188
|
+
}
|
|
189
|
+
if (!response.ok) throw new Error(`PUT /files ${body.path}: ${response.status} ${await response.text()}`);
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function call(config: Config, path: string): Promise<Response> {
|
|
194
|
+
const response = await fetchServer(config, path);
|
|
195
|
+
if (!response.ok) throw new Error(`GET ${path}: ${response.status} ${await response.text()}`);
|
|
196
|
+
return response;
|
|
197
|
+
}
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join, sep } from "node:path";
|
|
4
|
+
import { Result, Schema, SchemaIssue } from "effect";
|
|
5
|
+
import { isLock } from "./config";
|
|
6
|
+
import type { AccountUsage, Money, UsageWindow } from "./wire";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* How much of its limits each Claude and Codex account on this machine has used, for the dashboard.
|
|
10
|
+
*
|
|
11
|
+
* Read only from files each tool already writes for itself, never from its credentials, so nothing secret
|
|
12
|
+
* is read and nothing is sent anywhere but the numbers. The price is that a reading is only as fresh as
|
|
13
|
+
* the tool's last write, so every reading carries the time it was taken, and that neither file format is
|
|
14
|
+
* a published contract: a shape this code does not recognise is reported as `unknown`, not guessed at.
|
|
15
|
+
*
|
|
16
|
+
* - Claude: each account is a `CLAUDE_CONFIG_DIR` (`~/.claude`, `~/.claude-<name>`). Claude Code keeps
|
|
17
|
+
* the last plan usage it fetched in the account's `.claude.json` under `cachedUsageUtilization`, and
|
|
18
|
+
* refreshes it about every five minutes while a session runs on that account. It is what `/usage`
|
|
19
|
+
* shows when the usage endpoint is rate limited.
|
|
20
|
+
* - Claude without plan limits (Amazon Bedrock, an API key): Claude Code computes each session's cost
|
|
21
|
+
* locally from token counts at list price, the figure `/usage` shows as the Session block's total cost
|
|
22
|
+
* (https://code.claude.com/docs/en/costs), and saves it as a `cost-state` line in the session's file under
|
|
23
|
+
* `projects/`. An account with a plan cache keeps showing its limits, unless its settings turn Bedrock on.
|
|
24
|
+
* - Codex: each account is a `CODEX_HOME` (`~/.codex`, `~/.codex-<name>`). Codex records the rate limits
|
|
25
|
+
* its backend reports with every turn, as a `token_count` event in that turn's session file under
|
|
26
|
+
* `sessions/`. The fields are Codex's `RateLimitSnapshot` (codex-rs/protocol/src/protocol.rs).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export interface Account {
|
|
30
|
+
readonly tool: AccountUsage["tool"];
|
|
31
|
+
/** Absolute path of the account's folder. */
|
|
32
|
+
readonly path: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What the readers learn about one account; `readAccountUsage` adds which account it is. */
|
|
36
|
+
export type Reading = DistributiveOmit<AccountUsage, "tool" | "home">;
|
|
37
|
+
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
|
|
38
|
+
|
|
39
|
+
/** `~/.claude`, `~/.claude-<name>`, `~/.codex` and `~/.codex-<name>`: every account folder in `home`. */
|
|
40
|
+
export function detectAccounts(home: string = homedir()): Account[] {
|
|
41
|
+
return readdirSync(home)
|
|
42
|
+
.filter((entry) => !isLock(entry))
|
|
43
|
+
.flatMap((entry): Account[] => {
|
|
44
|
+
const tool = entry === ".claude" || entry.startsWith(".claude-") ? "claude"
|
|
45
|
+
: entry === ".codex" || entry.startsWith(".codex-") ? "codex"
|
|
46
|
+
: undefined;
|
|
47
|
+
if (tool === undefined) return [];
|
|
48
|
+
const path = join(home, entry);
|
|
49
|
+
return isDirectory(path) ? [{ tool, path }] : [];
|
|
50
|
+
})
|
|
51
|
+
.sort((a, b) => a.path.localeCompare(b.path));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Every account on this machine with its usage. One account's unreadable file never hides another's. */
|
|
55
|
+
export function readUsage(home: string = homedir(), now: number = Date.now()): AccountUsage[] {
|
|
56
|
+
return detectAccounts(home).map((account) => {
|
|
57
|
+
const name = account.path.slice(home.length).replace(/^[\\/]/, "");
|
|
58
|
+
let reading: Reading;
|
|
59
|
+
try {
|
|
60
|
+
reading = account.tool === "claude" ? readClaude(account.path, home, now) : readCodex(account.path);
|
|
61
|
+
} catch (cause) {
|
|
62
|
+
reading = { state: "unknown", reason: `could not read: ${cause instanceof Error ? cause.message : String(cause)}` };
|
|
63
|
+
}
|
|
64
|
+
return { tool: account.tool, home: name, ...reading };
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isDirectory(path: string): boolean {
|
|
69
|
+
try {
|
|
70
|
+
return statSync(path).isDirectory();
|
|
71
|
+
} catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const formatIssue = SchemaIssue.makeFormatterDefault();
|
|
77
|
+
|
|
78
|
+
/** A record that failed to decode: what failed, on one line, so the dashboard can say why it shows nothing. */
|
|
79
|
+
const unknown = (what: string, issue: SchemaIssue.Issue): Reading =>
|
|
80
|
+
({ state: "unknown", reason: `${what} changed shape: ${formatIssue(issue).replace(/\s+/g, " ").slice(0, 160)}` });
|
|
81
|
+
|
|
82
|
+
// ── Claude ──────────────────────────────────────────────────────────────────────────────────────────
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The default account keeps its state in `~/.claude.json`, beside its folder rather than in it; an
|
|
86
|
+
* account given its own `CLAUDE_CONFIG_DIR` keeps it inside that folder.
|
|
87
|
+
*/
|
|
88
|
+
export function claudeStatePath(accountPath: string, home: string): string {
|
|
89
|
+
return accountPath === join(home, ".claude") ? join(home, ".claude.json") : join(accountPath, ".claude.json");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A subscription account's plan limits, else what its recent sessions cost. A Bedrock account can still
|
|
94
|
+
* hold a plan cache from before it switched, so its settings saying Bedrock outrank the cache.
|
|
95
|
+
*/
|
|
96
|
+
function readClaude(accountPath: string, home: string, now: number): Reading {
|
|
97
|
+
const statePath = claudeStatePath(accountPath, home);
|
|
98
|
+
const plan: Reading = existsSync(statePath) ? parseClaudeState(readFileSync(statePath, "utf-8")) : { state: "none" };
|
|
99
|
+
const settingsPath = join(accountPath, "settings.json");
|
|
100
|
+
const bedrockSetting = existsSync(settingsPath) && settingsUseBedrock(readFileSync(settingsPath, "utf-8"));
|
|
101
|
+
if (plan.state !== "none" && !bedrockSetting) return plan;
|
|
102
|
+
const projects = join(accountPath, "projects");
|
|
103
|
+
const files = [...sessionFilesSince(projects, now - CLAUDE_PERIOD_DAYS * DAY_MS)];
|
|
104
|
+
forgetOtherSessionFiles(projects, new Set(files.map((file) => file.path)));
|
|
105
|
+
return estimateSpend({ sessions: files.map(latestSessionCost), bedrockSetting, now });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ── Claude without plan limits ──────────────────────────────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
/** Claude Code deletes session files older than `cleanupPeriodDays`, 30 by default, so this is as far back as they reach. */
|
|
111
|
+
export const CLAUDE_PERIOD_DAYS = 30;
|
|
112
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
113
|
+
/** How far back from its end a session file is searched for its cost. Claude Code writes it last, on leaving the session. */
|
|
114
|
+
const CLAUDE_TAIL_BYTES = 16 * 1024 * 1024;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* True when the account's `settings.json` turns on Bedrock: the `/setup-bedrock` wizard writes
|
|
118
|
+
* `CLAUDE_CODE_USE_BEDROCK` to its `env` block (https://code.claude.com/docs/en/amazon-bedrock), and
|
|
119
|
+
* `CLAUDE_CODE_USE_MANTLE` selects Bedrock's Mantle endpoint. Set only in a shell, it is invisible here;
|
|
120
|
+
* the model IDs in the account's sessions then say Bedrock instead.
|
|
121
|
+
*/
|
|
122
|
+
export function settingsUseBedrock(text: string): boolean {
|
|
123
|
+
let settings: unknown;
|
|
124
|
+
try {
|
|
125
|
+
settings = JSON.parse(text);
|
|
126
|
+
} catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
const env = Schema.decodeUnknownOption(Schema.Struct({ env: Schema.Record(Schema.String, Schema.Unknown) }))(settings);
|
|
130
|
+
if (env._tag === "None") return false;
|
|
131
|
+
return [env.value.env.CLAUDE_CODE_USE_BEDROCK, env.value.env.CLAUDE_CODE_USE_MANTLE]
|
|
132
|
+
.some((value) => value === true || (typeof value === "string" && /^(1|true)$/i.test(value.trim())));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Bedrock's model IDs: a cross-region inference profile (`us.anthropic.claude-opus-4-8`, with `us-gov.`, `eu.`,
|
|
137
|
+
* `apac.`, `jp.`, `au.` or `global.`), a Mantle or foundation model ID (`anthropic.claude-haiku-4-5`), or an
|
|
138
|
+
* application inference profile ARN (`arn:aws:bedrock:…`), per https://code.claude.com/docs/en/amazon-bedrock.
|
|
139
|
+
* An Anthropic API model ID (`claude-opus-5-5`) has no `anthropic.` prefix.
|
|
140
|
+
*/
|
|
141
|
+
export const isBedrockModelId = (model: string): boolean =>
|
|
142
|
+
/^(?:(?:us|us-gov|eu|apac|jp|au|global)\.)?anthropic\./.test(model) || /^arn:aws[a-z-]*:bedrock:/.test(model);
|
|
143
|
+
|
|
144
|
+
/** What one session file says the session cost, as of its last save. */
|
|
145
|
+
export type SessionCost =
|
|
146
|
+
| { readonly kind: "cost"; readonly sessionId: string; readonly costUsd: number; readonly lastActiveAt: number; readonly partial: boolean; readonly models: ReadonlyArray<string> }
|
|
147
|
+
| { readonly kind: "none" }
|
|
148
|
+
| { readonly kind: "changed"; readonly issue: SchemaIssue.Issue };
|
|
149
|
+
|
|
150
|
+
/** Session files written to since `since`: `projects/<project>/<session id>.jsonl`. Subagents' files are a level deeper and hold no cost. */
|
|
151
|
+
function* sessionFilesSince(projects: string, since: number): Generator<{ readonly path: string; readonly modifiedAt: number }> {
|
|
152
|
+
if (!isDirectory(projects)) return;
|
|
153
|
+
for (const project of readdirSync(projects)) {
|
|
154
|
+
const dir = join(projects, project);
|
|
155
|
+
if (!isDirectory(dir)) continue;
|
|
156
|
+
for (const entry of readdirSync(dir)) {
|
|
157
|
+
if (!entry.endsWith(".jsonl")) continue;
|
|
158
|
+
const path = join(dir, entry);
|
|
159
|
+
const modifiedAt = statSync(path).mtimeMs;
|
|
160
|
+
if (modifiedAt >= since) yield { path, modifiedAt };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const CostState = Schema.Struct({
|
|
166
|
+
type: Schema.Literal("cost-state"),
|
|
167
|
+
sessionId: Schema.String,
|
|
168
|
+
totalCostUSD: Schema.Finite,
|
|
169
|
+
modelUsage: Schema.Record(Schema.String, Schema.Unknown),
|
|
170
|
+
hasUnknownModelCost: Schema.optionalKey(Schema.Boolean),
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
/** Session files keep growing while a session runs; one unchanged since it was last read is not read again. */
|
|
174
|
+
const sessionCostCache = new Map<string, { readonly modifiedAt: number; readonly cost: SessionCost }>();
|
|
175
|
+
|
|
176
|
+
/** The daemon runs for weeks; files Claude Code deleted, or that left the period, leave the cache too. */
|
|
177
|
+
function forgetOtherSessionFiles(projects: string, current: ReadonlySet<string>): void {
|
|
178
|
+
for (const path of sessionCostCache.keys()) {
|
|
179
|
+
if (path.startsWith(projects + sep) && !current.has(path)) sessionCostCache.delete(path);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* The cost a session file last saved, and when the session was last active before that save: the time of the
|
|
185
|
+
* nearest earlier line that has one, since the cost line itself carries no time.
|
|
186
|
+
*/
|
|
187
|
+
export function latestSessionCost(file: { readonly path: string; readonly modifiedAt: number }): SessionCost {
|
|
188
|
+
const cached = sessionCostCache.get(file.path);
|
|
189
|
+
if (cached !== undefined && cached.modifiedAt === file.modifiedAt) return cached.cost;
|
|
190
|
+
let found: Extract<SessionCost, { kind: "cost" }> | undefined;
|
|
191
|
+
let cost: SessionCost = { kind: "none" };
|
|
192
|
+
for (const line of linesFromEnd(file.path, CLAUDE_TAIL_BYTES)) {
|
|
193
|
+
if (found === undefined) {
|
|
194
|
+
// Cheap test first, as for Codex: only the cost line is worth parsing until it is found.
|
|
195
|
+
if (!line.includes("\"cost-state\"")) continue;
|
|
196
|
+
const entry = parseJson(line);
|
|
197
|
+
if (typeof entry !== "object" || entry === null || !("type" in entry) || entry.type !== "cost-state") continue;
|
|
198
|
+
const decoded = Schema.decodeUnknownResult(CostState)(entry);
|
|
199
|
+
if (Result.isFailure(decoded)) {
|
|
200
|
+
cost = { kind: "changed", issue: decoded.failure.issue };
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
const state = decoded.success;
|
|
204
|
+
found = {
|
|
205
|
+
kind: "cost",
|
|
206
|
+
sessionId: state.sessionId,
|
|
207
|
+
costUsd: state.totalCostUSD,
|
|
208
|
+
lastActiveAt: file.modifiedAt,
|
|
209
|
+
partial: state.hasUnknownModelCost === true,
|
|
210
|
+
models: Object.keys(state.modelUsage),
|
|
211
|
+
};
|
|
212
|
+
cost = found;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (!line.includes("\"timestamp\"")) continue;
|
|
216
|
+
const entry = parseJson(line);
|
|
217
|
+
const at = typeof entry === "object" && entry !== null && "timestamp" in entry && typeof entry.timestamp === "string"
|
|
218
|
+
? Date.parse(entry.timestamp)
|
|
219
|
+
: NaN;
|
|
220
|
+
if (Number.isFinite(at)) {
|
|
221
|
+
cost = { ...found, lastActiveAt: at };
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
sessionCostCache.set(file.path, { modifiedAt: file.modifiedAt, cost });
|
|
226
|
+
return cost;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const parseJson = (line: string): unknown => {
|
|
230
|
+
try {
|
|
231
|
+
return JSON.parse(line);
|
|
232
|
+
} catch {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* The sum over sessions last active within the period. A session's saved cost covers the whole session, so
|
|
239
|
+
* a resumed one counts once, at its latest save, and a session forked from another carries the cost it
|
|
240
|
+
* started with, so the sum can count that part twice.
|
|
241
|
+
*/
|
|
242
|
+
export function estimateSpend(input: { readonly sessions: ReadonlyArray<SessionCost>; readonly bedrockSetting: boolean; readonly now: number }): Reading {
|
|
243
|
+
const changed = input.sessions.find((session) => session.kind === "changed");
|
|
244
|
+
if (changed !== undefined) return unknown("Claude Code's session cost record", changed.issue);
|
|
245
|
+
const since = input.now - CLAUDE_PERIOD_DAYS * DAY_MS;
|
|
246
|
+
const bySession = new Map<string, Extract<SessionCost, { kind: "cost" }>>();
|
|
247
|
+
for (const session of input.sessions) {
|
|
248
|
+
if (session.kind !== "cost" || session.lastActiveAt < since) continue;
|
|
249
|
+
const seen = bySession.get(session.sessionId);
|
|
250
|
+
if (seen === undefined || session.costUsd > seen.costUsd) bySession.set(session.sessionId, session);
|
|
251
|
+
}
|
|
252
|
+
const counted = [...bySession.values()];
|
|
253
|
+
if (counted.length === 0) return { state: "none" };
|
|
254
|
+
const usd = counted.reduce((sum, session) => sum + session.costUsd, 0);
|
|
255
|
+
return {
|
|
256
|
+
state: "estimate",
|
|
257
|
+
asOf: Math.max(...counted.map((session) => session.lastActiveAt)),
|
|
258
|
+
periodDays: CLAUDE_PERIOD_DAYS,
|
|
259
|
+
spent: { amountMinor: Math.round(usd * 100), currency: "USD", exponent: 2 },
|
|
260
|
+
sessions: counted.length,
|
|
261
|
+
partial: counted.some((session) => session.partial),
|
|
262
|
+
provider: input.bedrockSetting || counted.some((session) => session.models.some(isBedrockModelId)) ? "bedrock" : null,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const ClaudeWindow = Schema.Struct({ utilization: Schema.Finite, resets_at: Schema.NullOr(Schema.String) });
|
|
267
|
+
const ClaudeMoney = Schema.Struct({ amount_minor: Schema.Finite, currency: Schema.String, exponent: Schema.Int });
|
|
268
|
+
const ClaudeUsageCache = Schema.Struct({
|
|
269
|
+
fetchedAtMs: Schema.Finite,
|
|
270
|
+
utilization: Schema.Struct({
|
|
271
|
+
five_hour: Schema.optionalKey(Schema.NullOr(ClaudeWindow)),
|
|
272
|
+
seven_day: Schema.optionalKey(Schema.NullOr(ClaudeWindow)),
|
|
273
|
+
// Usage credits, the account's spend beyond its plan limits. `limit` has only been seen as null, so a
|
|
274
|
+
// limit in another shape is left out rather than failing the whole reading.
|
|
275
|
+
spend: Schema.optionalKey(Schema.NullOr(Schema.Struct({ enabled: Schema.Boolean, used: ClaudeMoney, limit: Schema.Unknown }))),
|
|
276
|
+
}),
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
/** Claude's documented window lengths: its status line calls them the 5-hour and 7-day limits. */
|
|
280
|
+
const CLAUDE_WINDOWS = [["five_hour", 300], ["seven_day", 7 * 24 * 60]] as const;
|
|
281
|
+
|
|
282
|
+
/** Reads the usage Claude Code cached in an account's `.claude.json`. */
|
|
283
|
+
export function parseClaudeState(text: string): Reading {
|
|
284
|
+
let state: unknown;
|
|
285
|
+
try {
|
|
286
|
+
state = JSON.parse(text);
|
|
287
|
+
} catch {
|
|
288
|
+
// Claude Code rewrites the file while it runs; a half-written one reads fine a moment later.
|
|
289
|
+
return { state: "unknown", reason: "the account's .claude.json is not valid JSON" };
|
|
290
|
+
}
|
|
291
|
+
if (typeof state !== "object" || state === null || !("cachedUsageUtilization" in state)) return { state: "none" };
|
|
292
|
+
const decoded = Schema.decodeUnknownResult(ClaudeUsageCache)(state.cachedUsageUtilization);
|
|
293
|
+
if (Result.isFailure(decoded)) return unknown("Claude Code's usage cache", decoded.failure.issue);
|
|
294
|
+
const cache = decoded.success;
|
|
295
|
+
|
|
296
|
+
const windows: UsageWindow[] = [];
|
|
297
|
+
for (const [key, minutes] of CLAUDE_WINDOWS) {
|
|
298
|
+
const window = cache.utilization[key];
|
|
299
|
+
if (window === undefined || window === null) continue;
|
|
300
|
+
const resetsAt = window.resets_at === null ? null : Date.parse(window.resets_at);
|
|
301
|
+
if (resetsAt !== null && !Number.isFinite(resetsAt)) {
|
|
302
|
+
return { state: "unknown", reason: `Claude Code's usage cache changed shape: ${key}.resets_at is not a time` };
|
|
303
|
+
}
|
|
304
|
+
windows.push({ minutes, usedPercent: window.utilization, resetsAt });
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const spend = cache.utilization.spend;
|
|
308
|
+
const limit = Schema.decodeUnknownOption(ClaudeMoney)(spend?.limit);
|
|
309
|
+
return {
|
|
310
|
+
state: "reading",
|
|
311
|
+
asOf: cache.fetchedAtMs,
|
|
312
|
+
windows,
|
|
313
|
+
...(spend?.enabled === true
|
|
314
|
+
? { spent: { used: money(spend.used), limit: limit._tag === "Some" ? money(limit.value) : null } }
|
|
315
|
+
: {}),
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const money = (value: Schema.Schema.Type<typeof ClaudeMoney>): Money =>
|
|
320
|
+
({ amountMinor: value.amount_minor, currency: value.currency, exponent: value.exponent });
|
|
321
|
+
|
|
322
|
+
// ── Codex ───────────────────────────────────────────────────────────────────────────────────────────
|
|
323
|
+
|
|
324
|
+
const CodexWindow = Schema.Struct({
|
|
325
|
+
used_percent: Schema.Finite,
|
|
326
|
+
window_minutes: Schema.NullOr(Schema.Finite),
|
|
327
|
+
resets_at: Schema.NullOr(Schema.Finite),
|
|
328
|
+
});
|
|
329
|
+
const CodexTokenCount = Schema.Struct({
|
|
330
|
+
timestamp: Schema.String,
|
|
331
|
+
payload: Schema.Struct({
|
|
332
|
+
type: Schema.Literal("token_count"),
|
|
333
|
+
rate_limits: Schema.NullOr(Schema.Struct({
|
|
334
|
+
limit_id: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
|
335
|
+
primary: Schema.NullOr(CodexWindow),
|
|
336
|
+
secondary: Schema.NullOr(CodexWindow),
|
|
337
|
+
})),
|
|
338
|
+
}),
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
/** Session files newest first; only this many are searched for a reading before giving up. */
|
|
342
|
+
const CODEX_FILES_SEARCHED = 5;
|
|
343
|
+
/** How far back from its end a session file is searched. Each turn writes one event, so the last is near the end. */
|
|
344
|
+
const CODEX_TAIL_BYTES = 16 * 1024 * 1024;
|
|
345
|
+
|
|
346
|
+
function readCodex(accountPath: string): Reading {
|
|
347
|
+
const files = sessionFiles(join(accountPath, "sessions"))
|
|
348
|
+
.map((path) => ({ path, modifiedAt: statSync(path).mtimeMs }))
|
|
349
|
+
.sort((a, b) => b.modifiedAt - a.modifiedAt)
|
|
350
|
+
.slice(0, CODEX_FILES_SEARCHED);
|
|
351
|
+
// The most recently written file holds the latest event; an older one only matters when the newer
|
|
352
|
+
// ones hold none, as for a session run with an API key, which has no plan limits to report.
|
|
353
|
+
for (const { path } of files) {
|
|
354
|
+
const reading = latestCodexReading(path);
|
|
355
|
+
if (reading.state !== "none") return reading;
|
|
356
|
+
}
|
|
357
|
+
return { state: "none" };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Every `rollout-*.jsonl` under `sessions/`, which Codex files by date: `YYYY/MM/DD/rollout-….jsonl`. */
|
|
361
|
+
function sessionFiles(dir: string): string[] {
|
|
362
|
+
if (!isDirectory(dir)) return [];
|
|
363
|
+
return readdirSync(dir, { recursive: true, encoding: "utf-8" })
|
|
364
|
+
.filter((path) => /(^|[\\/])rollout-[^\\/]*\.jsonl$/.test(path))
|
|
365
|
+
.map((path) => join(dir, path));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** The last rate-limit reading in one session file, searched from the end, since files reach hundreds of MB. */
|
|
369
|
+
export function latestCodexReading(path: string): Reading {
|
|
370
|
+
for (const line of linesFromEnd(path, CODEX_TAIL_BYTES)) {
|
|
371
|
+
const reading = parseCodexLine(line);
|
|
372
|
+
if (reading !== undefined) return reading;
|
|
373
|
+
}
|
|
374
|
+
return { state: "none" };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* The reading one session-file line carries, or undefined when it carries none: most lines are other
|
|
379
|
+
* events, and a `token_count` from a session without plan limits has `rate_limits: null`.
|
|
380
|
+
*/
|
|
381
|
+
export function parseCodexLine(line: string): Reading | undefined {
|
|
382
|
+
// Cheap test first: only these lines are worth parsing, and the others can be megabytes.
|
|
383
|
+
if (!line.includes("\"token_count\"")) return undefined;
|
|
384
|
+
let event: unknown;
|
|
385
|
+
try {
|
|
386
|
+
event = JSON.parse(line);
|
|
387
|
+
} catch {
|
|
388
|
+
return undefined; // The last line of a file Codex is still writing.
|
|
389
|
+
}
|
|
390
|
+
if (!isTokenCount(event)) return undefined;
|
|
391
|
+
const decoded = Schema.decodeUnknownResult(CodexTokenCount)(event);
|
|
392
|
+
if (Result.isFailure(decoded)) return unknown("Codex's rate-limit record", decoded.failure.issue);
|
|
393
|
+
const limits = decoded.success.payload.rate_limits;
|
|
394
|
+
// Another metered bucket than the main one; the main one is `codex`, or unnamed in older versions.
|
|
395
|
+
if (limits === null || (limits.limit_id !== undefined && limits.limit_id !== null && limits.limit_id !== "codex")) return undefined;
|
|
396
|
+
const asOf = Date.parse(decoded.success.timestamp);
|
|
397
|
+
if (!Number.isFinite(asOf)) return { state: "unknown", reason: "Codex's rate-limit record changed shape: timestamp is not a time" };
|
|
398
|
+
return {
|
|
399
|
+
state: "reading",
|
|
400
|
+
asOf,
|
|
401
|
+
windows: [limits.primary, limits.secondary].flatMap((window) => window === null ? [] : [{
|
|
402
|
+
minutes: window.window_minutes,
|
|
403
|
+
usedPercent: window.used_percent,
|
|
404
|
+
resetsAt: window.resets_at === null ? null : window.resets_at * 1000,
|
|
405
|
+
}]),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const isTokenCount = (event: unknown): boolean =>
|
|
410
|
+
typeof event === "object" && event !== null && "payload" in event
|
|
411
|
+
&& typeof event.payload === "object" && event.payload !== null
|
|
412
|
+
&& "type" in event.payload && event.payload.type === "token_count";
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* A file's whole lines, last first, reading at most `limit` bytes back from its end. Lines longer than
|
|
416
|
+
* `maxLine` bytes are skipped: holding a multi-megabyte line while reading backwards would copy it once
|
|
417
|
+
* per chunk read, and the lines wanted here are a few hundred bytes.
|
|
418
|
+
*/
|
|
419
|
+
export function* linesFromEnd(path: string, limit: number, maxLine = 1024 * 1024): Generator<string> {
|
|
420
|
+
const CHUNK = 64 * 1024;
|
|
421
|
+
const fd = openSync(path, "r");
|
|
422
|
+
try {
|
|
423
|
+
const size = statSync(path).size;
|
|
424
|
+
const stop = Math.max(0, size - limit);
|
|
425
|
+
let position = size;
|
|
426
|
+
// The start of a line whose line break has not been read yet, since reading goes backwards.
|
|
427
|
+
let carry = Buffer.alloc(0);
|
|
428
|
+
// The line being read is longer than `maxLine`; its bytes are dropped until its start is found.
|
|
429
|
+
let oversized = false;
|
|
430
|
+
while (position > stop) {
|
|
431
|
+
const length = Math.min(CHUNK, position - stop);
|
|
432
|
+
position -= length;
|
|
433
|
+
const chunk = Buffer.alloc(length);
|
|
434
|
+
readSync(fd, chunk, 0, length, position);
|
|
435
|
+
const buffer = Buffer.concat([chunk, carry]);
|
|
436
|
+
// Splitting on the newline byte is safe in UTF-8: it never occurs inside a multi-byte character.
|
|
437
|
+
let end = buffer.length;
|
|
438
|
+
for (let index = buffer.length - 1; index >= 0; index--) {
|
|
439
|
+
if (buffer[index] !== 0x0a) continue;
|
|
440
|
+
const line = buffer.subarray(index + 1, end).toString("utf-8").trim();
|
|
441
|
+
if (!oversized && line !== "") yield line;
|
|
442
|
+
oversized = false;
|
|
443
|
+
end = index;
|
|
444
|
+
}
|
|
445
|
+
carry = buffer.subarray(0, end);
|
|
446
|
+
if (carry.length > maxLine) {
|
|
447
|
+
carry = Buffer.alloc(0);
|
|
448
|
+
oversized = true;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
// The file's first line. When the search stopped short of the start, what is left is part of a line.
|
|
452
|
+
const first = carry.toString("utf-8").trim();
|
|
453
|
+
if (stop === 0 && !oversized && first !== "") yield first;
|
|
454
|
+
} finally {
|
|
455
|
+
closeSync(fd);
|
|
456
|
+
}
|
|
457
|
+
}
|