@jive-sh/skill-sync 0.4.18 → 0.5.0-latest-darwin-arm64

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 (55) hide show
  1. package/multi-call-binary +4 -0
  2. package/package.json +11 -39
  3. package/README.md +0 -127
  4. package/bin/package.json +0 -1
  5. package/bin/skill-sync +0 -576
  6. package/bin/skill-sync-daemon +0 -576
  7. package/dist/daemons/skill-sync-daemon.js +0 -491
  8. package/dist/daemons/skill-sync-daemon.js.map +0 -1
  9. package/dist/entrypoints/skill-sync.js +0 -153
  10. package/dist/entrypoints/skill-sync.js.map +0 -1
  11. package/dist/index.js +0 -10
  12. package/dist/index.js.map +0 -1
  13. package/dist/internal/agents/agent-tool.js +0 -83
  14. package/dist/internal/agents/agent-tool.js.map +0 -1
  15. package/dist/internal/agents/claude.js +0 -249
  16. package/dist/internal/agents/claude.js.map +0 -1
  17. package/dist/internal/agents/codex.js +0 -150
  18. package/dist/internal/agents/codex.js.map +0 -1
  19. package/dist/internal/agents/grok.js +0 -111
  20. package/dist/internal/agents/grok.js.map +0 -1
  21. package/dist/internal/agents/index.js +0 -31
  22. package/dist/internal/agents/index.js.map +0 -1
  23. package/dist/internal/config.js +0 -131
  24. package/dist/internal/config.js.map +0 -1
  25. package/dist/internal/control.js +0 -101
  26. package/dist/internal/control.js.map +0 -1
  27. package/dist/internal/folders.js +0 -47
  28. package/dist/internal/folders.js.map +0 -1
  29. package/dist/internal/path.js +0 -36
  30. package/dist/internal/path.js.map +0 -1
  31. package/dist/internal/server.js +0 -32
  32. package/dist/internal/server.js.map +0 -1
  33. package/dist/internal/skill-check.js +0 -83
  34. package/dist/internal/skill-check.js.map +0 -1
  35. package/dist/internal/sync.js +0 -183
  36. package/dist/internal/sync.js.map +0 -1
  37. package/dist/internal/wire.js +0 -24
  38. package/dist/internal/wire.js.map +0 -1
  39. package/install.cjs +0 -576
  40. package/src/daemons/skill-sync-daemon.ts +0 -483
  41. package/src/entrypoints/skill-sync.ts +0 -156
  42. package/src/index.ts +0 -15
  43. package/src/internal/agents/agent-tool.ts +0 -109
  44. package/src/internal/agents/claude.ts +0 -259
  45. package/src/internal/agents/codex.ts +0 -163
  46. package/src/internal/agents/grok.ts +0 -112
  47. package/src/internal/agents/index.ts +0 -34
  48. package/src/internal/config.ts +0 -172
  49. package/src/internal/control.ts +0 -140
  50. package/src/internal/folders.ts +0 -50
  51. package/src/internal/path.ts +0 -32
  52. package/src/internal/server.ts +0 -34
  53. package/src/internal/skill-check.ts +0 -97
  54. package/src/internal/sync.ts +0 -217
  55. package/src/internal/wire.ts +0 -252
@@ -1,109 +0,0 @@
1
- import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { SchemaIssue } from "effect";
4
- import { isLock } from "../config";
5
- import type { AccountUsage } from "../wire";
6
-
7
- /**
8
- * One coding agent skill-sync works with (Claude Code, Codex, Grok): where it reads a user's skills, which
9
- * of its accounts are on this machine, and how much each has used.
10
- *
11
- * Everything skill-sync knows about one tool lives in that tool's implementation, so adding a tool is one
12
- * new file and one line in `AGENT_TOOLS`, and no other code tests a folder name to tell tools apart.
13
- */
14
- export interface AgentTool {
15
- readonly tool: AccountUsage["tool"];
16
- /**
17
- * The skills folders this tool reads a user's skills from on this machine, whether or not they exist
18
- * yet: a folder that is ticked on the dashboard and missing is created.
19
- */
20
- skillsFolders(home: string): string[];
21
- /** This tool's account folders in `home`, as absolute paths. */
22
- accounts(home: string): string[];
23
- /** How much one of those accounts has used, from files and commands the tool itself provides. */
24
- readUsage(account: string, home: string, now: number): Reading;
25
- }
26
-
27
- /** What a tool learns about one account; `readUsage` adds which account it is. */
28
- export type Reading = DistributiveOmit<AccountUsage, "tool" | "home">;
29
- type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
30
-
31
- /** Sessions are counted over this many days: Claude Code deletes session files older than 30 days by default. */
32
- export const PERIOD_DAYS = 30;
33
- export const DAY_MS = 24 * 60 * 60 * 1000;
34
-
35
- const formatIssue = SchemaIssue.makeFormatterDefault();
36
-
37
- /** A record that failed to decode: what failed, on one line, so the dashboard can say why it shows nothing. */
38
- export const unknownShape = (what: string, issue: SchemaIssue.Issue): Reading =>
39
- ({ state: "unknown", reason: `${what} changed shape: ${formatIssue(issue).replace(/\s+/g, " ").slice(0, 160)}` });
40
-
41
- export function isDirectory(path: string): boolean {
42
- try {
43
- return statSync(path).isDirectory();
44
- } catch {
45
- return false;
46
- }
47
- }
48
-
49
- export const parseJson = (line: string): unknown => {
50
- try {
51
- return JSON.parse(line);
52
- } catch {
53
- return undefined;
54
- }
55
- };
56
-
57
- /**
58
- * A file's whole lines, last first, reading at most `limit` bytes back from its end. Lines longer than
59
- * `maxLine` bytes are skipped: holding a multi-megabyte line while reading backwards would copy it once
60
- * per chunk read, and the lines wanted here are a few hundred bytes.
61
- */
62
- export function* linesFromEnd(path: string, limit: number, maxLine = 1024 * 1024): Generator<string> {
63
- const CHUNK = 64 * 1024;
64
- const fd = openSync(path, "r");
65
- try {
66
- const size = statSync(path).size;
67
- const stop = Math.max(0, size - limit);
68
- let position = size;
69
- // The start of a line whose line break has not been read yet, since reading goes backwards.
70
- let carry = Buffer.alloc(0);
71
- // The line being read is longer than `maxLine`; its bytes are dropped until its start is found.
72
- let oversized = false;
73
- while (position > stop) {
74
- const length = Math.min(CHUNK, position - stop);
75
- position -= length;
76
- const chunk = Buffer.alloc(length);
77
- readSync(fd, chunk, 0, length, position);
78
- const buffer = Buffer.concat([chunk, carry]);
79
- // Splitting on the newline byte is safe in UTF-8: it never occurs inside a multi-byte character.
80
- let end = buffer.length;
81
- for (let index = buffer.length - 1; index >= 0; index--) {
82
- if (buffer[index] !== 0x0a) continue;
83
- const line = buffer.subarray(index + 1, end).toString("utf-8").trim();
84
- if (!oversized && line !== "") yield line;
85
- oversized = false;
86
- end = index;
87
- }
88
- carry = buffer.subarray(0, end);
89
- if (carry.length > maxLine) {
90
- carry = Buffer.alloc(0);
91
- oversized = true;
92
- }
93
- }
94
- // The file's first line. When the search stopped short of the start, what is left is part of a line.
95
- const first = carry.toString("utf-8").trim();
96
- if (stop === 0 && !oversized && first !== "") yield first;
97
- } finally {
98
- closeSync(fd);
99
- }
100
- }
101
-
102
- /** The directories in `home` named `.<name>` or `.<name>-<suffix>`, never a lock: one tool's account folders. */
103
- export function homesNamed(home: string, name: string): string[] {
104
- return readdirSync(home)
105
- .filter((entry) => (entry === `.${name}` || entry.startsWith(`.${name}-`)) && !isLock(entry))
106
- .map((entry) => join(home, entry))
107
- .filter(isDirectory)
108
- .sort();
109
- }
@@ -1,259 +0,0 @@
1
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
- import { join, sep } from "node:path";
3
- import { Result, Schema, SchemaIssue } from "effect";
4
- import type { Money, UsageWindow } from "../wire";
5
- import {
6
- DAY_MS, PERIOD_DAYS, homesNamed, isDirectory, linesFromEnd, parseJson, unknownShape, type AgentTool, type Reading,
7
- } from "./agent-tool";
8
-
9
- /**
10
- * Claude Code. Each account is a `CLAUDE_CONFIG_DIR` (`~/.claude`, `~/.claude-<name>`), and reads its
11
- * user skills from the `skills` folder inside it.
12
- *
13
- * Usage is read only from files Claude Code writes for itself, never from its credentials. Neither file
14
- * format is a published contract, so a shape this code does not recognise is reported as `unknown`.
15
- *
16
- * - Plan limits: Claude Code keeps the last plan usage it fetched in the account's `.claude.json` under
17
- * `cachedUsageUtilization`, and refreshes it about every five minutes while a session runs on that
18
- * account. It is what `/usage` shows when the usage endpoint is rate limited.
19
- * - No plan limits (Amazon Bedrock, an API key): Claude Code computes each session's cost locally from
20
- * token counts at list price, the figure `/usage` shows as the Session block's total cost
21
- * (https://code.claude.com/docs/en/costs), and saves it as a `cost-state` line in the session's file
22
- * under `projects/`. An account with a plan cache keeps showing its limits, unless its settings turn
23
- * Bedrock on.
24
- */
25
- export const claude: AgentTool = {
26
- tool: "claude",
27
- skillsFolders: (home) => homesNamed(home, "claude").map((account) => join(account, "skills")),
28
- accounts: (home) => homesNamed(home, "claude"),
29
- readUsage: (account, home, now) => readClaude(account, home, now),
30
- };
31
-
32
- // ── Claude ──────────────────────────────────────────────────────────────────────────────────────────
33
-
34
- /**
35
- * The default account keeps its state in `~/.claude.json`, beside its folder rather than in it; an
36
- * account given its own `CLAUDE_CONFIG_DIR` keeps it inside that folder.
37
- */
38
- export function claudeStatePath(accountPath: string, home: string): string {
39
- return accountPath === join(home, ".claude") ? join(home, ".claude.json") : join(accountPath, ".claude.json");
40
- }
41
-
42
- /**
43
- * A subscription account's plan limits, else what its recent sessions cost. A Bedrock account can still
44
- * hold a plan cache from before it switched, so its settings saying Bedrock outrank the cache.
45
- */
46
- function readClaude(accountPath: string, home: string, now: number): Reading {
47
- const statePath = claudeStatePath(accountPath, home);
48
- const plan: Reading = existsSync(statePath) ? parseClaudeState(readFileSync(statePath, "utf-8")) : { state: "none" };
49
- const settingsPath = join(accountPath, "settings.json");
50
- const bedrockSetting = existsSync(settingsPath) && settingsUseBedrock(readFileSync(settingsPath, "utf-8"));
51
- if (plan.state !== "none" && !bedrockSetting) return plan;
52
- const projects = join(accountPath, "projects");
53
- const files = [...sessionFilesSince(projects, now - PERIOD_DAYS * DAY_MS)];
54
- forgetOtherSessionFiles(projects, new Set(files.map((file) => file.path)));
55
- return estimateSpend({ sessions: files.map(latestSessionCost), bedrockSetting, now });
56
- }
57
-
58
- // ── Claude without plan limits ──────────────────────────────────────────────────────────────────────
59
-
60
- /** How far back from its end a session file is searched for its cost. Claude Code writes it last, on leaving the session. */
61
- const CLAUDE_TAIL_BYTES = 16 * 1024 * 1024;
62
-
63
- /**
64
- * True when the account's `settings.json` turns on Bedrock: the `/setup-bedrock` wizard writes
65
- * `CLAUDE_CODE_USE_BEDROCK` to its `env` block (https://code.claude.com/docs/en/amazon-bedrock), and
66
- * `CLAUDE_CODE_USE_MANTLE` selects Bedrock's Mantle endpoint. Set only in a shell, it is invisible here;
67
- * the model IDs in the account's sessions then say Bedrock instead.
68
- */
69
- export function settingsUseBedrock(text: string): boolean {
70
- let settings: unknown;
71
- try {
72
- settings = JSON.parse(text);
73
- } catch {
74
- return false;
75
- }
76
- const env = Schema.decodeUnknownOption(Schema.Struct({ env: Schema.Record(Schema.String, Schema.Unknown) }))(settings);
77
- if (env._tag === "None") return false;
78
- return [env.value.env.CLAUDE_CODE_USE_BEDROCK, env.value.env.CLAUDE_CODE_USE_MANTLE]
79
- .some((value) => value === true || (typeof value === "string" && /^(1|true)$/i.test(value.trim())));
80
- }
81
-
82
- /**
83
- * Bedrock's model IDs: a cross-region inference profile (`us.anthropic.claude-opus-4-8`, with `us-gov.`, `eu.`,
84
- * `apac.`, `jp.`, `au.` or `global.`), a Mantle or foundation model ID (`anthropic.claude-haiku-4-5`), or an
85
- * application inference profile ARN (`arn:aws:bedrock:…`), per https://code.claude.com/docs/en/amazon-bedrock.
86
- * An Anthropic API model ID (`claude-opus-5-5`) has no `anthropic.` prefix.
87
- */
88
- export const isBedrockModelId = (model: string): boolean =>
89
- /^(?:(?:us|us-gov|eu|apac|jp|au|global)\.)?anthropic\./.test(model) || /^arn:aws[a-z-]*:bedrock:/.test(model);
90
-
91
- /** What one session file says the session cost, as of its last save. */
92
- export type SessionCost =
93
- | { readonly kind: "cost"; readonly sessionId: string; readonly costUsd: number; readonly lastActiveAt: number; readonly partial: boolean; readonly models: ReadonlyArray<string> }
94
- | { readonly kind: "none" }
95
- | { readonly kind: "changed"; readonly issue: SchemaIssue.Issue };
96
-
97
- /** Session files written to since `since`: `projects/<project>/<session id>.jsonl`. Subagents' files are a level deeper and hold no cost. */
98
- function* sessionFilesSince(projects: string, since: number): Generator<{ readonly path: string; readonly modifiedAt: number }> {
99
- if (!isDirectory(projects)) return;
100
- for (const project of readdirSync(projects)) {
101
- const dir = join(projects, project);
102
- if (!isDirectory(dir)) continue;
103
- for (const entry of readdirSync(dir)) {
104
- if (!entry.endsWith(".jsonl")) continue;
105
- const path = join(dir, entry);
106
- const modifiedAt = statSync(path).mtimeMs;
107
- if (modifiedAt >= since) yield { path, modifiedAt };
108
- }
109
- }
110
- }
111
-
112
- const CostState = Schema.Struct({
113
- type: Schema.Literal("cost-state"),
114
- sessionId: Schema.String,
115
- totalCostUSD: Schema.Finite,
116
- modelUsage: Schema.Record(Schema.String, Schema.Unknown),
117
- hasUnknownModelCost: Schema.optionalKey(Schema.Boolean),
118
- });
119
-
120
- /** Session files keep growing while a session runs; one unchanged since it was last read is not read again. */
121
- const sessionCostCache = new Map<string, { readonly modifiedAt: number; readonly cost: SessionCost }>();
122
-
123
- /** The daemon runs for weeks; files Claude Code deleted, or that left the period, leave the cache too. */
124
- function forgetOtherSessionFiles(projects: string, current: ReadonlySet<string>): void {
125
- for (const path of sessionCostCache.keys()) {
126
- if (path.startsWith(projects + sep) && !current.has(path)) sessionCostCache.delete(path);
127
- }
128
- }
129
-
130
- /**
131
- * The cost a session file last saved, and when the session was last active before that save: the time of the
132
- * nearest earlier line that has one, since the cost line itself carries no time.
133
- */
134
- export function latestSessionCost(file: { readonly path: string; readonly modifiedAt: number }): SessionCost {
135
- const cached = sessionCostCache.get(file.path);
136
- if (cached !== undefined && cached.modifiedAt === file.modifiedAt) return cached.cost;
137
- let found: Extract<SessionCost, { kind: "cost" }> | undefined;
138
- let cost: SessionCost = { kind: "none" };
139
- for (const line of linesFromEnd(file.path, CLAUDE_TAIL_BYTES)) {
140
- if (found === undefined) {
141
- // Cheap test first: only the cost line is worth parsing until it is found.
142
- if (!line.includes("\"cost-state\"")) continue;
143
- const entry = parseJson(line);
144
- if (typeof entry !== "object" || entry === null || !("type" in entry) || entry.type !== "cost-state") continue;
145
- const decoded = Schema.decodeUnknownResult(CostState)(entry);
146
- if (Result.isFailure(decoded)) {
147
- cost = { kind: "changed", issue: decoded.failure.issue };
148
- break;
149
- }
150
- const state = decoded.success;
151
- found = {
152
- kind: "cost",
153
- sessionId: state.sessionId,
154
- costUsd: state.totalCostUSD,
155
- lastActiveAt: file.modifiedAt,
156
- partial: state.hasUnknownModelCost === true,
157
- models: Object.keys(state.modelUsage),
158
- };
159
- cost = found;
160
- continue;
161
- }
162
- if (!line.includes("\"timestamp\"")) continue;
163
- const entry = parseJson(line);
164
- const at = typeof entry === "object" && entry !== null && "timestamp" in entry && typeof entry.timestamp === "string"
165
- ? Date.parse(entry.timestamp)
166
- : NaN;
167
- if (Number.isFinite(at)) {
168
- cost = { ...found, lastActiveAt: at };
169
- break;
170
- }
171
- }
172
- sessionCostCache.set(file.path, { modifiedAt: file.modifiedAt, cost });
173
- return cost;
174
- }
175
-
176
- /**
177
- * The sum over sessions last active within the period. A session's saved cost covers the whole session, so
178
- * a resumed one counts once, at its latest save, and a session forked from another carries the cost it
179
- * started with, so the sum can count that part twice.
180
- */
181
- export function estimateSpend(input: { readonly sessions: ReadonlyArray<SessionCost>; readonly bedrockSetting: boolean; readonly now: number }): Reading {
182
- const changed = input.sessions.find((session) => session.kind === "changed");
183
- if (changed !== undefined) return unknownShape("Claude Code's session cost record", changed.issue);
184
- const since = input.now - PERIOD_DAYS * DAY_MS;
185
- const bySession = new Map<string, Extract<SessionCost, { kind: "cost" }>>();
186
- for (const session of input.sessions) {
187
- if (session.kind !== "cost" || session.lastActiveAt < since) continue;
188
- const seen = bySession.get(session.sessionId);
189
- if (seen === undefined || session.costUsd > seen.costUsd) bySession.set(session.sessionId, session);
190
- }
191
- const counted = [...bySession.values()];
192
- if (counted.length === 0) return { state: "none" };
193
- const usd = counted.reduce((sum, session) => sum + session.costUsd, 0);
194
- return {
195
- state: "estimate",
196
- asOf: Math.max(...counted.map((session) => session.lastActiveAt)),
197
- periodDays: PERIOD_DAYS,
198
- spent: { amountMinor: Math.round(usd * 100), currency: "USD", exponent: 2 },
199
- sessions: counted.length,
200
- partial: counted.some((session) => session.partial),
201
- provider: input.bedrockSetting || counted.some((session) => session.models.some(isBedrockModelId)) ? "bedrock" : null,
202
- };
203
- }
204
-
205
- const ClaudeWindow = Schema.Struct({ utilization: Schema.Finite, resets_at: Schema.NullOr(Schema.String) });
206
- const ClaudeMoney = Schema.Struct({ amount_minor: Schema.Finite, currency: Schema.String, exponent: Schema.Int });
207
- const ClaudeUsageCache = Schema.Struct({
208
- fetchedAtMs: Schema.Finite,
209
- utilization: Schema.Struct({
210
- five_hour: Schema.optionalKey(Schema.NullOr(ClaudeWindow)),
211
- seven_day: Schema.optionalKey(Schema.NullOr(ClaudeWindow)),
212
- // Usage credits, the account's spend beyond its plan limits. `limit` has only been seen as null, so a
213
- // limit in another shape is left out rather than failing the whole reading.
214
- spend: Schema.optionalKey(Schema.NullOr(Schema.Struct({ enabled: Schema.Boolean, used: ClaudeMoney, limit: Schema.Unknown }))),
215
- }),
216
- });
217
-
218
- /** Claude's documented window lengths: its status line calls them the 5-hour and 7-day limits. */
219
- const CLAUDE_WINDOWS = [["five_hour", 300], ["seven_day", 7 * 24 * 60]] as const;
220
-
221
- /** Reads the usage Claude Code cached in an account's `.claude.json`. */
222
- export function parseClaudeState(text: string): Reading {
223
- let state: unknown;
224
- try {
225
- state = JSON.parse(text);
226
- } catch {
227
- // Claude Code rewrites the file while it runs; a half-written one reads fine a moment later.
228
- return { state: "unknown", reason: "the account's .claude.json is not valid JSON" };
229
- }
230
- if (typeof state !== "object" || state === null || !("cachedUsageUtilization" in state)) return { state: "none" };
231
- const decoded = Schema.decodeUnknownResult(ClaudeUsageCache)(state.cachedUsageUtilization);
232
- if (Result.isFailure(decoded)) return unknownShape("Claude Code's usage cache", decoded.failure.issue);
233
- const cache = decoded.success;
234
-
235
- const windows: UsageWindow[] = [];
236
- for (const [key, minutes] of CLAUDE_WINDOWS) {
237
- const window = cache.utilization[key];
238
- if (window === undefined || window === null) continue;
239
- const resetsAt = window.resets_at === null ? null : Date.parse(window.resets_at);
240
- if (resetsAt !== null && !Number.isFinite(resetsAt)) {
241
- return { state: "unknown", reason: `Claude Code's usage cache changed shape: ${key}.resets_at is not a time` };
242
- }
243
- windows.push({ minutes, usedPercent: window.utilization, resetsAt });
244
- }
245
-
246
- const spend = cache.utilization.spend;
247
- const limit = Schema.decodeUnknownOption(ClaudeMoney)(spend?.limit);
248
- return {
249
- state: "reading",
250
- asOf: cache.fetchedAtMs,
251
- windows,
252
- ...(spend?.enabled === true
253
- ? { spent: { used: money(spend.used), limit: limit._tag === "Some" ? money(limit.value) : null } }
254
- : {}),
255
- };
256
- }
257
-
258
- const money = (value: Schema.Schema.Type<typeof ClaudeMoney>): Money =>
259
- ({ amountMinor: value.amount_minor, currency: value.currency, exponent: value.exponent });
@@ -1,163 +0,0 @@
1
- import { readdirSync, statSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { Result, Schema } from "effect";
4
- import type { TokenSpend } from "../wire";
5
- import {
6
- DAY_MS, PERIOD_DAYS, homesNamed, isDirectory, linesFromEnd, parseJson, unknownShape, type AgentTool, type Reading,
7
- } from "./agent-tool";
8
-
9
- /**
10
- * Codex. Each account is a `CODEX_HOME` (`~/.codex`, `~/.codex-<name>`). Every account reads a user's
11
- * skills from `~/.agents/skills`, offered when any Codex account or `~/.agents` exists, because a
12
- * machine with Codex installed may have no `~/.agents` yet.
13
- *
14
- * Codex records what its backend reports with every turn, as a `token_count` event in that turn's session
15
- * file under `sessions/`: the rate limits (Codex's `RateLimitSnapshot`, codex-rs/protocol/src/protocol.rs)
16
- * and the session's running token total. The limits come from the newest event; the tokens are each
17
- * session's total, summed over sessions active in the last `PERIOD_DAYS` days.
18
- */
19
- export const codex: AgentTool = {
20
- tool: "codex",
21
- skillsFolders: (home) =>
22
- homesNamed(home, "codex").length > 0 || isDirectory(join(home, ".agents")) ? [join(home, ".agents", "skills")] : [],
23
- accounts: (home) => homesNamed(home, "codex"),
24
- readUsage: (account, _home, now) => readCodex(account, now),
25
- };
26
-
27
- const CodexWindow = Schema.Struct({
28
- used_percent: Schema.Finite,
29
- window_minutes: Schema.NullOr(Schema.Finite),
30
- resets_at: Schema.NullOr(Schema.Finite),
31
- });
32
- const CodexTokenCount = Schema.Struct({
33
- timestamp: Schema.String,
34
- payload: Schema.Struct({
35
- type: Schema.Literal("token_count"),
36
- info: Schema.optionalKey(Schema.NullOr(Schema.Struct({
37
- total_token_usage: Schema.Struct({ total_tokens: Schema.Finite }),
38
- }))),
39
- rate_limits: Schema.NullOr(Schema.Struct({
40
- limit_id: Schema.optionalKey(Schema.NullOr(Schema.String)),
41
- primary: Schema.NullOr(CodexWindow),
42
- secondary: Schema.NullOr(CodexWindow),
43
- })),
44
- }),
45
- });
46
-
47
- /** Session files newest first; only this many are searched for a rate-limit reading before giving up. */
48
- const CODEX_FILES_SEARCHED = 5;
49
- /** How far back from its end a session file is searched. Each turn writes one event, so the last is near the end. */
50
- const CODEX_TAIL_BYTES = 16 * 1024 * 1024;
51
-
52
- /** What one session file's latest `token_count` events say. */
53
- export interface SessionRecord {
54
- /** The newest rate-limit reading, or undefined when the file has none (a session run with an API key). */
55
- readonly limits: Reading | undefined;
56
- /** The session's token total so far, or undefined when no event carries one. */
57
- readonly tokens: number | undefined;
58
- }
59
-
60
- /** Session files keep growing while a session runs; one unchanged since it was last read is not read again. */
61
- const sessionCache = new Map<string, { readonly modifiedAt: number; readonly record: SessionRecord }>();
62
-
63
- function readCodex(account: string, now: number): Reading {
64
- const files = sessionFiles(join(account, "sessions"))
65
- .map((path) => ({ path, modifiedAt: statSync(path).mtimeMs }))
66
- .sort((a, b) => b.modifiedAt - a.modifiedAt);
67
- const since = now - PERIOD_DAYS * DAY_MS;
68
- const recent = files.filter((file) => file.modifiedAt >= since);
69
- for (const path of sessionCache.keys()) {
70
- if (path.startsWith(account) && !files.some((file) => file.path === path)) sessionCache.delete(path);
71
- }
72
-
73
- // The most recently written file holds the latest reading; an older one only matters when the newer
74
- // ones hold none.
75
- let limits: Reading = { state: "none" };
76
- for (const file of files.slice(0, CODEX_FILES_SEARCHED)) {
77
- const record = sessionRecord(file);
78
- if (record.limits !== undefined) {
79
- limits = record.limits;
80
- break;
81
- }
82
- }
83
- if (limits.state !== "reading") return limits;
84
-
85
- const totals = recent.map((file) => sessionRecord(file).tokens).filter((tokens) => tokens !== undefined);
86
- const tokens: TokenSpend = {
87
- count: totals.reduce((sum, count) => sum + count, 0),
88
- periodDays: PERIOD_DAYS,
89
- sessions: totals.length,
90
- };
91
- return { ...limits, tokens };
92
- }
93
-
94
- function sessionRecord(file: { readonly path: string; readonly modifiedAt: number }): SessionRecord {
95
- const cached = sessionCache.get(file.path);
96
- if (cached !== undefined && cached.modifiedAt === file.modifiedAt) return cached.record;
97
- const record = latestSessionRecord(file.path);
98
- sessionCache.set(file.path, { modifiedAt: file.modifiedAt, record });
99
- return record;
100
- }
101
-
102
- /** Every `rollout-*.jsonl` under `sessions/`, which Codex files by date: `YYYY/MM/DD/rollout-….jsonl`. */
103
- function sessionFiles(dir: string): string[] {
104
- if (!isDirectory(dir)) return [];
105
- return readdirSync(dir, { recursive: true, encoding: "utf-8" })
106
- .filter((path) => /(^|[\\/])rollout-[^\\/]*\.jsonl$/.test(path))
107
- .map((path) => join(dir, path));
108
- }
109
-
110
- /** The newest rate-limit reading and token total in one session file, searched from the end, since files reach hundreds of MB. */
111
- export function latestSessionRecord(path: string): SessionRecord {
112
- let limits: Reading | undefined;
113
- let tokens: number | undefined;
114
- for (const line of linesFromEnd(path, CODEX_TAIL_BYTES)) {
115
- const event = parseCodexLine(line);
116
- if (event === undefined) continue;
117
- if (limits === undefined) limits = event.limits;
118
- if (tokens === undefined) tokens = event.tokens;
119
- if (limits !== undefined && tokens !== undefined) break;
120
- }
121
- return { limits, tokens };
122
- }
123
-
124
- /**
125
- * What one session-file line carries, or undefined when it is not a `token_count` event: most lines are
126
- * other events. A `token_count` from a session without plan limits has `rate_limits: null`.
127
- */
128
- export function parseCodexLine(line: string): SessionRecord | undefined {
129
- // Cheap test first: only these lines are worth parsing, and the others can be megabytes.
130
- if (!line.includes("\"token_count\"")) return undefined;
131
- const event = parseJson(line); // Undefined for the last line of a file Codex is still writing.
132
- if (!isTokenCount(event)) return undefined;
133
- const decoded = Schema.decodeUnknownResult(CodexTokenCount)(event);
134
- if (Result.isFailure(decoded)) return { limits: unknownShape("Codex's rate-limit record", decoded.failure.issue), tokens: undefined };
135
- const { payload, timestamp } = decoded.success;
136
- const tokens = payload.info?.total_token_usage.total_tokens;
137
- const limits = payload.rate_limits;
138
- // Another metered bucket than the main one; the main one is `codex`, or unnamed in older versions.
139
- if (limits === null || (limits.limit_id !== undefined && limits.limit_id !== null && limits.limit_id !== "codex")) {
140
- return { limits: undefined, tokens };
141
- }
142
- const asOf = Date.parse(timestamp);
143
- if (!Number.isFinite(asOf)) {
144
- return { limits: { state: "unknown", reason: "Codex's rate-limit record changed shape: timestamp is not a time" }, tokens };
145
- }
146
- return {
147
- limits: {
148
- state: "reading",
149
- asOf,
150
- windows: [limits.primary, limits.secondary].flatMap((window) => window === null ? [] : [{
151
- minutes: window.window_minutes,
152
- usedPercent: window.used_percent,
153
- resetsAt: window.resets_at === null ? null : window.resets_at * 1000,
154
- }]),
155
- },
156
- tokens,
157
- };
158
- }
159
-
160
- const isTokenCount = (event: unknown): boolean =>
161
- typeof event === "object" && event !== null && "payload" in event
162
- && typeof event.payload === "object" && event.payload !== null
163
- && "type" in event.payload && event.payload.type === "token_count";
@@ -1,112 +0,0 @@
1
- import { existsSync, readdirSync, statSync } from "node:fs";
2
- import { spawnSync } from "node:child_process";
3
- import { join } from "node:path";
4
- import { Result, Schema } from "effect";
5
- import { DAY_MS, PERIOD_DAYS, homesNamed, isDirectory, parseJson, unknownShape, type AgentTool, type Reading } from "./agent-tool";
6
-
7
- /**
8
- * Grok. Each account is a `GROK_HOME` (`~/.grok`, `~/.grok-<name>`), and Grok's docs name its `skills`
9
- * folder as where it reads a user's skills. Grok also reads `~/.agents/skills`, undocumented; a skill in
10
- * both loads once, from the Grok home (checked with `grok inspect`, Grok 1.0.70).
11
- *
12
- * Usage is what `grok usage <session-id>` prints, the command Grok's docs say to use instead of reading
13
- * session files: each session's token and cost totals (`costUsdTicks`, 10^10 per US dollar). The line sums
14
- * sessions active in the last `PERIOD_DAYS` days. A session's totals include history it inherited by
15
- * resume or fork, so a fork counts that part twice. Grok's plan allowance is only in its interactive
16
- * `/usage`, so no limit is shown.
17
- */
18
- export const grok: AgentTool = {
19
- tool: "grok",
20
- skillsFolders: (home) => homesNamed(home, "grok").map((account) => join(account, "skills")),
21
- accounts: (home) => homesNamed(home, "grok"),
22
- readUsage: (account, _home, now) => readGrok(account, now),
23
- };
24
-
25
- const GrokUsage = Schema.Struct({
26
- sessionId: Schema.String,
27
- updatedAt: Schema.String,
28
- session: Schema.Struct({ costUsdTicks: Schema.Finite, totalTokens: Schema.Finite }),
29
- });
30
- const TICKS_PER_USD = 1e10;
31
- /** `grok usage` reads one session's file and exits; this bounds a hung one. */
32
- const COMMAND_TIMEOUT_MS = 10_000;
33
-
34
- export type SessionTotals =
35
- | { readonly kind: "totals"; readonly usd: number; readonly updatedAt: number }
36
- /** A session with no turn yet: `grok usage` exits 1 saying "No usage recorded". */
37
- | { readonly kind: "empty" }
38
- | { readonly kind: "failed"; readonly reason: string };
39
-
40
- /** A session's totals are fetched again only when its directory changed: each `grok usage` run takes most of a second. */
41
- const sessionCache = new Map<string, { readonly modifiedAt: number; readonly totals: SessionTotals }>();
42
-
43
- function readGrok(account: string, now: number): Reading {
44
- const command = join(account, "bin", "grok");
45
- const sessions = sessionDirs(join(account, "sessions"), now - PERIOD_DAYS * DAY_MS);
46
- if (sessions.length === 0) return { state: "none" };
47
- if (!existsSync(command)) return { state: "unknown", reason: `Grok's command is not at ${command}` };
48
-
49
- const totals: Extract<SessionTotals, { kind: "totals" }>[] = [];
50
- for (const session of sessions) {
51
- const cached = sessionCache.get(session.path);
52
- const result = cached !== undefined && cached.modifiedAt === session.modifiedAt
53
- ? cached.totals
54
- : runGrokUsage(command, account, session.id);
55
- // A failure is asked again next time rather than kept until the session changes.
56
- if (result.kind !== "failed") sessionCache.set(session.path, { modifiedAt: session.modifiedAt, totals: result });
57
- if (result.kind === "failed") return { state: "unknown", reason: result.reason };
58
- if (result.kind === "totals") totals.push(result);
59
- }
60
- if (totals.length === 0) return { state: "none" };
61
- const usd = totals.reduce((sum, session) => sum + session.usd, 0);
62
- return {
63
- state: "estimate",
64
- asOf: Math.max(...totals.map((session) => session.updatedAt)),
65
- periodDays: PERIOD_DAYS,
66
- spent: { amountMinor: Math.round(usd * 100), currency: "USD", exponent: 2 },
67
- sessions: totals.length,
68
- partial: false,
69
- provider: null,
70
- };
71
- }
72
-
73
- /**
74
- * Sessions active since `since`: `sessions/<encoded working directory>/<session id>/`, whose modification
75
- * time moves whenever Grok writes the session's files.
76
- */
77
- function sessionDirs(dir: string, since: number): { readonly id: string; readonly path: string; readonly modifiedAt: number }[] {
78
- if (!isDirectory(dir)) return [];
79
- return readdirSync(dir).flatMap((project) => {
80
- const projectDir = join(dir, project);
81
- if (!isDirectory(projectDir)) return [];
82
- return readdirSync(projectDir).flatMap((id) => {
83
- const path = join(projectDir, id);
84
- if (!/^[0-9a-f-]{36}$/i.test(id) || !isDirectory(path)) return [];
85
- const modifiedAt = statSync(path).mtimeMs;
86
- return modifiedAt >= since ? [{ id, path, modifiedAt }] : [];
87
- });
88
- });
89
- }
90
-
91
- export function runGrokUsage(command: string, account: string, sessionId: string): SessionTotals {
92
- const run = spawnSync(command, ["usage", sessionId], {
93
- env: { ...process.env, GROK_HOME: account },
94
- encoding: "utf-8",
95
- timeout: COMMAND_TIMEOUT_MS,
96
- });
97
- if (run.status === 0) return parseGrokUsage(run.stdout);
98
- const stderr = (run.stderr ?? "").trim();
99
- if (stderr.includes("No usage recorded")) return { kind: "empty" };
100
- return { kind: "failed", reason: `\`grok usage\` failed: ${run.error?.message ?? (stderr.slice(0, 160) || `exit ${run.status}`)}` };
101
- }
102
-
103
- export function parseGrokUsage(stdout: string): SessionTotals {
104
- const decoded = Schema.decodeUnknownResult(GrokUsage)(parseJson(stdout));
105
- if (Result.isFailure(decoded)) {
106
- const reading = unknownShape("`grok usage` output", decoded.failure.issue);
107
- return { kind: "failed", reason: reading.state === "unknown" ? reading.reason : "" };
108
- }
109
- const updatedAt = Date.parse(decoded.success.updatedAt);
110
- if (!Number.isFinite(updatedAt)) return { kind: "failed", reason: "`grok usage` output changed shape: updatedAt is not a time" };
111
- return { kind: "totals", usd: decoded.success.session.costUsdTicks / TICKS_PER_USD, updatedAt };
112
- }