@jive-sh/skill-sync 0.8.0 → 0.8.1-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.
- package/multi-call-binary +4 -0
- package/package.json +11 -45
- package/README.md +0 -202
- package/bin/package.json +0 -1
- package/bin/skill-sync +0 -34
- package/bin/skill-sync-daemon +0 -34
- package/dist/daemons/skill-sync-daemon.js +0 -640
- package/dist/daemons/skill-sync-daemon.js.map +0 -1
- package/dist/entrypoints/skill-sync.js +0 -7
- package/dist/entrypoints/skill-sync.js.map +0 -1
- package/dist/index.js +0 -10
- package/dist/index.js.map +0 -1
- package/dist/internal/agents/agent-tool.js +0 -102
- package/dist/internal/agents/agent-tool.js.map +0 -1
- package/dist/internal/agents/claude.js +0 -424
- package/dist/internal/agents/claude.js.map +0 -1
- package/dist/internal/agents/codex.js +0 -270
- package/dist/internal/agents/codex.js.map +0 -1
- package/dist/internal/agents/command.js +0 -219
- package/dist/internal/agents/command.js.map +0 -1
- package/dist/internal/agents/grok.js +0 -170
- package/dist/internal/agents/grok.js.map +0 -1
- package/dist/internal/agents/index.js +0 -70
- package/dist/internal/agents/index.js.map +0 -1
- package/dist/internal/cli.js +0 -185
- package/dist/internal/cli.js.map +0 -1
- package/dist/internal/config.js +0 -131
- package/dist/internal/config.js.map +0 -1
- package/dist/internal/control.js +0 -113
- package/dist/internal/control.js.map +0 -1
- package/dist/internal/daemon-control/impl.js +0 -68
- package/dist/internal/daemon-control/impl.js.map +0 -1
- package/dist/internal/daemon-control/interface.js +0 -4
- package/dist/internal/daemon-control/interface.js.map +0 -1
- package/dist/internal/folders.js +0 -47
- package/dist/internal/folders.js.map +0 -1
- package/dist/internal/local-skills.js +0 -43
- package/dist/internal/local-skills.js.map +0 -1
- package/dist/internal/path.js +0 -36
- package/dist/internal/path.js.map +0 -1
- package/dist/internal/server.js +0 -80
- package/dist/internal/server.js.map +0 -1
- package/dist/internal/skill-check.js +0 -83
- package/dist/internal/skill-check.js.map +0 -1
- package/dist/internal/skill-refinement/evals/cases.js +0 -143
- package/dist/internal/skill-refinement/evals/cases.js.map +0 -1
- package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
- package/dist/internal/skill-refinement/evals/opus-judge-original.json +0 -165
- package/dist/internal/skill-refinement/feedback/intake.js +0 -52
- package/dist/internal/skill-refinement/feedback/intake.js.map +0 -1
- package/dist/internal/skill-refinement/jev/impl.js +0 -51
- package/dist/internal/skill-refinement/jev/impl.js.map +0 -1
- package/dist/internal/skill-refinement/jev/interface.js +0 -14
- package/dist/internal/skill-refinement/jev/interface.js.map +0 -1
- package/dist/internal/skill-refinement/paths.js +0 -62
- package/dist/internal/skill-refinement/paths.js.map +0 -1
- package/dist/internal/skill-refinement/platform.js +0 -67
- package/dist/internal/skill-refinement/platform.js.map +0 -1
- package/dist/internal/skill-refinement/service.js +0 -255
- package/dist/internal/skill-refinement/service.js.map +0 -1
- package/dist/internal/skill-refinement/skills/skill-text.js +0 -217
- package/dist/internal/skill-refinement/skills/skill-text.js.map +0 -1
- package/dist/internal/skill-refinement/workflow/retry.js +0 -69
- package/dist/internal/skill-refinement/workflow/retry.js.map +0 -1
- package/dist/internal/skill-refinement/workflow/skill-refinement.js +0 -595
- package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +0 -1
- package/dist/internal/skill-refinement/writer/impl.js +0 -69
- package/dist/internal/skill-refinement/writer/impl.js.map +0 -1
- package/dist/internal/skill-refinement/writer/interface.js +0 -10
- package/dist/internal/skill-refinement/writer/interface.js.map +0 -1
- package/dist/internal/sync.js +0 -182
- package/dist/internal/sync.js.map +0 -1
- package/dist/internal/wire.js +0 -31
- package/dist/internal/wire.js.map +0 -1
- package/postinstall.cjs +0 -663
- package/src/daemons/skill-sync-daemon.ts +0 -645
- package/src/entrypoints/skill-sync.ts +0 -12
- package/src/index.ts +0 -15
- package/src/internal/agents/agent-tool.ts +0 -149
- package/src/internal/agents/claude.ts +0 -442
- package/src/internal/agents/codex.ts +0 -288
- package/src/internal/agents/command.ts +0 -257
- package/src/internal/agents/grok.ts +0 -174
- package/src/internal/agents/index.ts +0 -74
- package/src/internal/cli.ts +0 -217
- package/src/internal/config.ts +0 -172
- package/src/internal/control.ts +0 -157
- package/src/internal/daemon-control/impl.ts +0 -80
- package/src/internal/daemon-control/interface.ts +0 -40
- package/src/internal/folders.ts +0 -50
- package/src/internal/local-skills.ts +0 -58
- package/src/internal/path.ts +0 -32
- package/src/internal/server.ts +0 -76
- package/src/internal/skill-check.ts +0 -97
- package/src/internal/skill-refinement/evals/cases.ts +0 -167
- package/src/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
- package/src/internal/skill-refinement/evals/opus-judge-original.json +0 -165
- package/src/internal/skill-refinement/feedback/intake.ts +0 -66
- package/src/internal/skill-refinement/jev/impl.ts +0 -63
- package/src/internal/skill-refinement/jev/interface.ts +0 -51
- package/src/internal/skill-refinement/paths.ts +0 -87
- package/src/internal/skill-refinement/platform.ts +0 -71
- package/src/internal/skill-refinement/service.ts +0 -301
- package/src/internal/skill-refinement/skills/skill-text.ts +0 -290
- package/src/internal/skill-refinement/workflow/retry.ts +0 -76
- package/src/internal/skill-refinement/workflow/skill-refinement.ts +0 -667
- package/src/internal/skill-refinement/writer/impl.ts +0 -79
- package/src/internal/skill-refinement/writer/interface.ts +0 -29
- package/src/internal/sync.ts +0 -216
- package/src/internal/wire.ts +0 -439
|
@@ -1,149 +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 { AccountIdentity, AccountLimits, AccountUsage, LocalUse, SessionUse } 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
|
-
/**
|
|
24
|
-
* Who the account is and its plan limits, asked of the tool's own CLI, which makes the authenticated
|
|
25
|
-
* call to its service; from the tool's saved record of its last fetch when the CLI cannot be run. Each
|
|
26
|
-
* call runs the CLI, so callers cache the result (`readUsage`).
|
|
27
|
-
*/
|
|
28
|
-
readAccount(account: string, context: AccountContext): Promise<AccountReading>;
|
|
29
|
-
/** What this machine's sessions of the account used, from the files the tool writes for itself. */
|
|
30
|
-
readLocalUse(account: string, home: string, now: number): LocalUse;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** What reading an account needs: the home it is in, the time, and where a CLI is (`findCommand` outside tests). */
|
|
34
|
-
export interface AccountContext {
|
|
35
|
-
readonly home: string;
|
|
36
|
-
readonly now: number;
|
|
37
|
-
/** The path of a command, or undefined when it is not installed; `also` lists paths to try after the usual ones. */
|
|
38
|
-
readonly findCommand: (input: { readonly name: string; readonly also?: ReadonlyArray<string> }) => string | undefined;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** What a tool's CLI says about one account. */
|
|
42
|
-
export interface AccountReading {
|
|
43
|
-
readonly identity: AccountIdentity | null;
|
|
44
|
-
readonly limits: AccountLimits;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Sessions are counted over this many days: Claude Code deletes session files older than 30 days by default. */
|
|
48
|
-
export const PERIOD_DAYS = 30;
|
|
49
|
-
export const DAY_MS = 24 * 60 * 60 * 1000;
|
|
50
|
-
/**
|
|
51
|
-
* Each session's cost goes out in millionths of a dollar: rounded to cents one by one, a few hundred sessions
|
|
52
|
-
* would add up to a total off by dollars.
|
|
53
|
-
*/
|
|
54
|
-
export const USD_MICROS = { currency: "USD", exponent: 6 } as const;
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Sessions in one order whatever order their files were listed in: the daemon sends usage again only when its text
|
|
58
|
-
* changes, so an order that varies between readings would resend unchanged figures.
|
|
59
|
-
*/
|
|
60
|
-
export const inSessionOrder = (sessions: ReadonlyArray<SessionUse>): ReadonlyArray<SessionUse> =>
|
|
61
|
-
[...sessions].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
62
|
-
|
|
63
|
-
/** A CLI asked for an account's limits gets this long to answer. */
|
|
64
|
-
export const CLI_TIMEOUT_MS = 30_000;
|
|
65
|
-
|
|
66
|
-
const formatIssue = SchemaIssue.makeFormatterDefault();
|
|
67
|
-
|
|
68
|
-
/** A record that failed to decode: what failed, on one line, so the dashboard can say why it shows nothing. */
|
|
69
|
-
export const unknownShape = (what: string, issue: SchemaIssue.Issue): { readonly state: "unknown"; readonly reason: string } =>
|
|
70
|
-
({ state: "unknown", reason: `${what} changed shape: ${formatIssue(issue).replace(/\s+/g, " ").slice(0, 160)}` });
|
|
71
|
-
|
|
72
|
-
/** A limit's name from its length, the same for every tool: `5-hour`, `weekly`. */
|
|
73
|
-
export const windowName = (minutes: number | null): string =>
|
|
74
|
-
minutes === null ? "limit"
|
|
75
|
-
: minutes === 7 * 24 * 60 ? "weekly"
|
|
76
|
-
: minutes === 24 * 60 ? "daily"
|
|
77
|
-
: minutes % (24 * 60) === 0 ? `${minutes / (24 * 60)}-day`
|
|
78
|
-
: minutes % 60 === 0 ? `${minutes / 60}-hour`
|
|
79
|
-
: `${minutes}-minute`;
|
|
80
|
-
|
|
81
|
-
export function isDirectory(path: string): boolean {
|
|
82
|
-
try {
|
|
83
|
-
return statSync(path).isDirectory();
|
|
84
|
-
} catch {
|
|
85
|
-
return false;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export const parseJson = (line: string): unknown => {
|
|
90
|
-
try {
|
|
91
|
-
return JSON.parse(line);
|
|
92
|
-
} catch {
|
|
93
|
-
return undefined;
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* A file's whole lines, last first, reading at most `limit` bytes back from its end. Lines longer than
|
|
99
|
-
* `maxLine` bytes are skipped: holding a multi-megabyte line while reading backwards would copy it once
|
|
100
|
-
* per chunk read, and the lines wanted here are a few hundred bytes.
|
|
101
|
-
*/
|
|
102
|
-
export function* linesFromEnd(path: string, limit: number, maxLine = 1024 * 1024): Generator<string> {
|
|
103
|
-
const CHUNK = 64 * 1024;
|
|
104
|
-
const fd = openSync(path, "r");
|
|
105
|
-
try {
|
|
106
|
-
const size = statSync(path).size;
|
|
107
|
-
const stop = Math.max(0, size - limit);
|
|
108
|
-
let position = size;
|
|
109
|
-
// The start of a line whose line break has not been read yet, since reading goes backwards.
|
|
110
|
-
let carry = Buffer.alloc(0);
|
|
111
|
-
// The line being read is longer than `maxLine`; its bytes are dropped until its start is found.
|
|
112
|
-
let oversized = false;
|
|
113
|
-
while (position > stop) {
|
|
114
|
-
const length = Math.min(CHUNK, position - stop);
|
|
115
|
-
position -= length;
|
|
116
|
-
const chunk = Buffer.alloc(length);
|
|
117
|
-
readSync(fd, chunk, 0, length, position);
|
|
118
|
-
const buffer = Buffer.concat([chunk, carry]);
|
|
119
|
-
// Splitting on the newline byte is safe in UTF-8: it never occurs inside a multi-byte character.
|
|
120
|
-
let end = buffer.length;
|
|
121
|
-
for (let index = buffer.length - 1; index >= 0; index--) {
|
|
122
|
-
if (buffer[index] !== 0x0a) continue;
|
|
123
|
-
const line = buffer.subarray(index + 1, end).toString("utf-8").trim();
|
|
124
|
-
if (!oversized && line !== "") yield line;
|
|
125
|
-
oversized = false;
|
|
126
|
-
end = index;
|
|
127
|
-
}
|
|
128
|
-
carry = buffer.subarray(0, end);
|
|
129
|
-
if (carry.length > maxLine) {
|
|
130
|
-
carry = Buffer.alloc(0);
|
|
131
|
-
oversized = true;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
// The file's first line. When the search stopped short of the start, what is left is part of a line.
|
|
135
|
-
const first = carry.toString("utf-8").trim();
|
|
136
|
-
if (stop === 0 && !oversized && first !== "") yield first;
|
|
137
|
-
} finally {
|
|
138
|
-
closeSync(fd);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/** The directories in `home` named `.<name>` or `.<name>-<suffix>`, never a lock: one tool's account folders. */
|
|
143
|
-
export function homesNamed(home: string, name: string): string[] {
|
|
144
|
-
return readdirSync(home)
|
|
145
|
-
.filter((entry) => (entry === `.${name}` || entry.startsWith(`.${name}-`)) && !isLock(entry))
|
|
146
|
-
.map((entry) => join(home, entry))
|
|
147
|
-
.filter(isDirectory)
|
|
148
|
-
.sort();
|
|
149
|
-
}
|
|
@@ -1,442 +0,0 @@
|
|
|
1
|
-
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
-
import { tmpdir } from "node:os";
|
|
3
|
-
import { join, sep } from "node:path";
|
|
4
|
-
import { Result, Schema, SchemaIssue } from "effect";
|
|
5
|
-
import type { AccountIdentity, AccountLimits, LocalUse, Money, UsageWindow } from "../wire";
|
|
6
|
-
import {
|
|
7
|
-
CLI_TIMEOUT_MS, DAY_MS, PERIOD_DAYS, USD_MICROS, homesNamed, inSessionOrder, isDirectory, linesFromEnd, parseJson, unknownShape, windowName,
|
|
8
|
-
type AccountContext, type AccountReading, type AgentTool,
|
|
9
|
-
} from "./agent-tool";
|
|
10
|
-
import { runCommand } from "./command";
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Claude Code. Each account is a `CLAUDE_CONFIG_DIR` (`~/.claude`, `~/.claude-<name>`), and reads its
|
|
14
|
-
* user skills from the `skills` folder inside it.
|
|
15
|
-
*
|
|
16
|
-
* - Account: `claude auth status` says who is signed in (email, organization, plan), and `claude -p /usage`
|
|
17
|
-
* prints the plan limits Claude Code fetches from Anthropic for the account, which count every
|
|
18
|
-
* machine's use. Neither starts a model turn. When `claude` cannot be found or fails, the limits come
|
|
19
|
-
* from the plan usage Claude Code last fetched and keeps in the account's `.claude.json`
|
|
20
|
-
* (`cachedUsageUtilization`, refreshed about every five minutes while a session runs), and who is
|
|
21
|
-
* signed in from the same file's `oauthAccount`.
|
|
22
|
-
* - This machine: Claude Code computes each session's cost locally from token counts at list price, the
|
|
23
|
-
* figure `/usage` shows as a session's total cost (https://code.claude.com/docs/en/costs), and saves it
|
|
24
|
-
* as a `cost-state` line in the session's file under `projects/`. The sum over recent sessions is the
|
|
25
|
-
* machine's use of the account, whatever the plan.
|
|
26
|
-
*
|
|
27
|
-
* No credential file is read: the CLI makes the authenticated calls. `/usage`'s text and both files are
|
|
28
|
-
* not published formats, so a shape this code does not recognise is reported as `unknown`.
|
|
29
|
-
*/
|
|
30
|
-
export const claude: AgentTool = {
|
|
31
|
-
tool: "claude",
|
|
32
|
-
skillsFolders: (home) => homesNamed(home, "claude").map((account) => join(account, "skills")),
|
|
33
|
-
accounts: (home) => homesNamed(home, "claude"),
|
|
34
|
-
readAccount: (account, context) => readClaudeAccount(account, context),
|
|
35
|
-
readLocalUse: (account, home, now) => readClaudeLocalUse(account, home, now),
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* The default account keeps its state in `~/.claude.json`, beside its folder rather than in it; an
|
|
40
|
-
* account given its own `CLAUDE_CONFIG_DIR` keeps it inside that folder.
|
|
41
|
-
*/
|
|
42
|
-
export function claudeStatePath(accountPath: string, home: string): string {
|
|
43
|
-
return accountPath === join(home, ".claude") ? join(home, ".claude.json") : join(accountPath, ".claude.json");
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
const accountUsesBedrock = (accountPath: string): boolean => {
|
|
47
|
-
const settingsPath = join(accountPath, "settings.json");
|
|
48
|
-
return existsSync(settingsPath) && settingsUseBedrock(readFileSync(settingsPath, "utf-8"));
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
// ── The account ─────────────────────────────────────────────────────────────────────────────────────
|
|
52
|
-
|
|
53
|
-
async function readClaudeAccount(accountPath: string, { home, now, findCommand }: AccountContext): Promise<AccountReading> {
|
|
54
|
-
if (accountUsesBedrock(accountPath)) {
|
|
55
|
-
return { identity: null, limits: { state: "none", reason: "Amazon Bedrock has no plan limits" } };
|
|
56
|
-
}
|
|
57
|
-
const command = findCommand({ name: "claude", also: [join(home, ".claude", "local", "claude")] });
|
|
58
|
-
if (command === undefined) return savedAccount(accountPath, home, "`claude` was not found");
|
|
59
|
-
// The default account is the one Claude Code uses with no CLAUDE_CONFIG_DIR: setting it to `~/.claude`
|
|
60
|
-
// would move its state from `~/.claude.json` into the folder.
|
|
61
|
-
const { CLAUDE_CONFIG_DIR: _inherited, ...env } = process.env;
|
|
62
|
-
const run = (args: ReadonlyArray<string>) => runCommand({
|
|
63
|
-
command,
|
|
64
|
-
args,
|
|
65
|
-
env: { ...env, ...(accountPath === join(home, ".claude") ? {} : { CLAUDE_CONFIG_DIR: accountPath }), DISABLE_AUTOUPDATER: "1" },
|
|
66
|
-
// Away from any project, so no project's settings or hooks apply.
|
|
67
|
-
cwd: tmpdir(),
|
|
68
|
-
timeoutMs: CLI_TIMEOUT_MS,
|
|
69
|
-
});
|
|
70
|
-
const [auth, usage] = await Promise.all([
|
|
71
|
-
run(["auth", "status"]),
|
|
72
|
-
// Not saved as a session, so it adds nothing to the account's session files or to this machine's use.
|
|
73
|
-
run(["-p", "/usage", "--no-session-persistence"]),
|
|
74
|
-
]);
|
|
75
|
-
// Signed out, it still prints its JSON, and exits 1.
|
|
76
|
-
const status = auth.failure === undefined ? parseAuthStatus(auth.stdout) : undefined;
|
|
77
|
-
if (status === undefined || (status.kind === "changed" && auth.status !== 0)) {
|
|
78
|
-
return savedAccount(accountPath, home, `\`claude auth status\` failed: ${auth.failure ?? (auth.stderr.trim().slice(0, 160) || `exit ${auth.status}`)}`);
|
|
79
|
-
}
|
|
80
|
-
if (status.kind === "changed") return { identity: null, limits: status.limits };
|
|
81
|
-
if (status.kind === "signedOut") return { identity: null, limits: { state: "none", reason: "signed out" } };
|
|
82
|
-
if (status.kind === "noPlan") return { identity: status.identity, limits: { state: "none", reason: status.reason } };
|
|
83
|
-
if (usage.failure !== undefined || usage.status !== 0) {
|
|
84
|
-
const saved = savedAccount(accountPath, home, `\`claude -p /usage\` failed: ${usage.failure ?? (usage.stderr.trim().slice(0, 160) || `exit ${usage.status}`)}`);
|
|
85
|
-
return { identity: status.identity, limits: saved.limits };
|
|
86
|
-
}
|
|
87
|
-
return { identity: status.identity, limits: parseUsageOutput(usage.stdout, now) };
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const AuthStatus = Schema.Struct({
|
|
91
|
-
loggedIn: Schema.Boolean,
|
|
92
|
-
authMethod: Schema.optionalKey(Schema.String),
|
|
93
|
-
apiProvider: Schema.optionalKey(Schema.String),
|
|
94
|
-
email: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
|
95
|
-
orgId: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
|
96
|
-
subscriptionType: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
export type AuthStatus =
|
|
100
|
-
| { readonly kind: "subscription"; readonly identity: AccountIdentity }
|
|
101
|
-
/** Signed in another way (an API key, a cloud provider): no plan limits to read. */
|
|
102
|
-
| { readonly kind: "noPlan"; readonly identity: AccountIdentity | null; readonly reason: string }
|
|
103
|
-
| { readonly kind: "signedOut" }
|
|
104
|
-
| { readonly kind: "changed"; readonly limits: AccountLimits };
|
|
105
|
-
|
|
106
|
-
/** What `claude auth status` prints: JSON naming the sign-in method, and for claude.ai the account. */
|
|
107
|
-
export function parseAuthStatus(stdout: string): AuthStatus {
|
|
108
|
-
const decoded = Schema.decodeUnknownResult(AuthStatus)(parseJson(stdout.trim()));
|
|
109
|
-
if (Result.isFailure(decoded)) return { kind: "changed", limits: unknownShape("`claude auth status` output", decoded.failure.issue) };
|
|
110
|
-
const status = decoded.success;
|
|
111
|
-
if (!status.loggedIn) return { kind: "signedOut" };
|
|
112
|
-
const identity: AccountIdentity | null = typeof status.orgId === "string" && typeof status.email === "string"
|
|
113
|
-
? { id: status.orgId, email: status.email, plan: status.subscriptionType ?? null }
|
|
114
|
-
: null;
|
|
115
|
-
if (status.authMethod !== "claude.ai" || identity === null) {
|
|
116
|
-
return { kind: "noPlan", identity, reason: `signed in with ${status.authMethod ?? status.apiProvider ?? "an API key"}: no plan limits` };
|
|
117
|
-
}
|
|
118
|
-
return { kind: "subscription", identity };
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* One limit line of `/usage`, as Claude Code 2.1.316 prints it:
|
|
123
|
-
* `Current week (all models): 21% used · resets Nov 3 at 4pm (America/Los_Angeles)`, and 2.1.326:
|
|
124
|
-
* `Current week (Fable): 0% used · resets Nov 18, 12am (UTC)`. The zone is the machine's IANA zone. The
|
|
125
|
-
* reset part is absent while no window is running.
|
|
126
|
-
*/
|
|
127
|
-
const USAGE_LINE = /^Current (session|day|week|month)(?: \(([^)]+)\))?: (\d+(?:\.\d+)?)% used(?: · resets (.+) \(([^()]+)\))?$/;
|
|
128
|
-
|
|
129
|
-
/** The plan limits `claude -p /usage` prints, each line one limit. */
|
|
130
|
-
export function parseUsageOutput(stdout: string, now: number): AccountLimits {
|
|
131
|
-
const windows: UsageWindow[] = [];
|
|
132
|
-
for (const raw of stdout.split("\n")) {
|
|
133
|
-
const match = USAGE_LINE.exec(raw.trim());
|
|
134
|
-
if (match === null) continue;
|
|
135
|
-
const [, period, scope, used, resets, timeZone] = match;
|
|
136
|
-
// A session is Claude's 5-hour limit.
|
|
137
|
-
const minutes = period === "session" ? 300 : period === "day" ? 24 * 60 : period === "week" ? 7 * 24 * 60 : null;
|
|
138
|
-
let resetsAt: number | null = null;
|
|
139
|
-
if (resets !== undefined && timeZone !== undefined) {
|
|
140
|
-
const parsed = parseResetTime({ text: resets, timeZone, now });
|
|
141
|
-
if (parsed === undefined) return { state: "unknown", reason: `\`claude /usage\` changed shape: reset time "${resets} (${timeZone})"` };
|
|
142
|
-
resetsAt = parsed;
|
|
143
|
-
}
|
|
144
|
-
const base = period === "month" ? "monthly" : windowName(minutes);
|
|
145
|
-
windows.push({ name: scope === undefined || scope === "all models" ? base : `${base} ${scope}`, minutes, usedPercent: Number(used), resetsAt });
|
|
146
|
-
}
|
|
147
|
-
if (windows.length === 0) {
|
|
148
|
-
return { state: "unknown", reason: `\`claude /usage\` changed shape: no "Current …: N% used" line in "${stdout.trim().slice(0, 120)}"` };
|
|
149
|
-
}
|
|
150
|
-
return { state: "reading", asOf: now, source: "account", windows };
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
154
|
-
/**
|
|
155
|
-
* `Nov 3 at 4pm`, `Nov 1 at 3:40am`, `Nov 3, 2027 at 4pm` (2.1.316), `Nov 18, 6am`, `Nov 17, 1:09pm`
|
|
156
|
-
* (2.1.326), or a time alone for later today.
|
|
157
|
-
*/
|
|
158
|
-
const RESET_TIME = /^(?:([A-Z][a-z]{2}) (\d{1,2})(?:, (\d{4}))?(?: at |, ))?(\d{1,2})(?::(\d{2}))?(am|pm)$/;
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* A reset time as `/usage` prints it, a wall-clock time in a named time zone, in milliseconds since the
|
|
162
|
-
* epoch. Without a year, the year that puts it nearest to now; without a date, the next such time.
|
|
163
|
-
* Undefined when it is not in that form or the zone is unknown.
|
|
164
|
-
*/
|
|
165
|
-
export function parseResetTime(input: { readonly text: string; readonly timeZone: string; readonly now: number }): number | undefined {
|
|
166
|
-
const match = RESET_TIME.exec(input.text.trim());
|
|
167
|
-
if (match === null) return undefined;
|
|
168
|
-
const [, monthName, day, year, hour12, minute, meridiem] = match;
|
|
169
|
-
const hour = (Number(hour12) % 12) + (meridiem === "pm" ? 12 : 0);
|
|
170
|
-
let today: { year: number; month: number; day: number };
|
|
171
|
-
try {
|
|
172
|
-
today = wallClock(input.now, input.timeZone);
|
|
173
|
-
} catch {
|
|
174
|
-
return undefined;
|
|
175
|
-
}
|
|
176
|
-
const at = (y: number, m: number, d: number) => zonedTime({ year: y, month: m, day: d, hour, minute: Number(minute ?? 0), timeZone: input.timeZone });
|
|
177
|
-
if (monthName === undefined) {
|
|
178
|
-
const sameDay = at(today.year, today.month, today.day);
|
|
179
|
-
return sameDay >= input.now - 60_000 ? sameDay : at(today.year, today.month, today.day + 1);
|
|
180
|
-
}
|
|
181
|
-
const month = MONTHS.indexOf(monthName);
|
|
182
|
-
if (month === -1) return undefined;
|
|
183
|
-
if (year !== undefined) return at(Number(year), month, Number(day));
|
|
184
|
-
return [today.year - 1, today.year, today.year + 1]
|
|
185
|
-
.map((y) => at(y, month, Number(day)))
|
|
186
|
-
.reduce((best, candidate) => Math.abs(candidate - input.now) < Math.abs(best - input.now) ? candidate : best);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** The date and time in a time zone at an instant; month counted from 0, as `Date.UTC` takes it. Throws for an unknown zone. */
|
|
190
|
-
function wallClock(at: number, timeZone: string): { year: number; month: number; day: number; hour: number; minute: number; second: number } {
|
|
191
|
-
const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", {
|
|
192
|
-
timeZone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric",
|
|
193
|
-
}).formatToParts(new Date(at)).map((part) => [part.type, Number(part.value)]));
|
|
194
|
-
return { year: parts["year"]!, month: parts["month"]! - 1, day: parts["day"]!, hour: parts["hour"]!, minute: parts["minute"]!, second: parts["second"]! };
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** The instant a wall-clock time in a time zone names: its UTC reading, moved by the zone's offset at that instant. */
|
|
198
|
-
function zonedTime(input: { year: number; month: number; day: number; hour: number; minute: number; timeZone: string }): number {
|
|
199
|
-
const asUtc = Date.UTC(input.year, input.month, input.day, input.hour, input.minute);
|
|
200
|
-
const offsetAt = (instant: number) => {
|
|
201
|
-
const clock = wallClock(instant, input.timeZone);
|
|
202
|
-
return Date.UTC(clock.year, clock.month, clock.day, clock.hour, clock.minute, clock.second) - Math.floor(instant / 1000) * 1000;
|
|
203
|
-
};
|
|
204
|
-
const guess = asUtc - offsetAt(asUtc);
|
|
205
|
-
// Across a daylight-saving change the offset at the guess can differ from the one first assumed.
|
|
206
|
-
return asUtc - offsetAt(guess);
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** The account as the account's `.claude.json` last recorded it, for when the CLI cannot be asked. */
|
|
210
|
-
function savedAccount(accountPath: string, home: string, why: string): AccountReading {
|
|
211
|
-
const statePath = claudeStatePath(accountPath, home);
|
|
212
|
-
if (!existsSync(statePath)) return { identity: null, limits: { state: "unknown", reason: why } };
|
|
213
|
-
const saved = parseClaudeState(readFileSync(statePath, "utf-8"));
|
|
214
|
-
const limits: AccountLimits = saved.limits.state === "reading" ? { ...saved.limits, cliFailure: why }
|
|
215
|
-
: saved.limits.state === "none" ? { state: "unknown", reason: why }
|
|
216
|
-
: saved.limits;
|
|
217
|
-
return { identity: saved.identity, limits };
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// ── This machine's use ──────────────────────────────────────────────────────────────────────────────
|
|
221
|
-
|
|
222
|
-
function readClaudeLocalUse(accountPath: string, _home: string, now: number): LocalUse {
|
|
223
|
-
const projects = join(accountPath, "projects");
|
|
224
|
-
const files = [...sessionFilesSince(projects, now - PERIOD_DAYS * DAY_MS)];
|
|
225
|
-
forgetOtherSessionFiles(projects, new Set(files.map((file) => file.path)));
|
|
226
|
-
return estimateSpend({ sessions: files.map(latestSessionCost), bedrockSetting: accountUsesBedrock(accountPath), now });
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/** How far back from its end a session file is searched for its cost. Claude Code writes it last, on leaving the session. */
|
|
230
|
-
const CLAUDE_TAIL_BYTES = 16 * 1024 * 1024;
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* True when the account's `settings.json` turns on Bedrock: the `/setup-bedrock` wizard writes
|
|
234
|
-
* `CLAUDE_CODE_USE_BEDROCK` to its `env` block (https://code.claude.com/docs/en/amazon-bedrock), and
|
|
235
|
-
* `CLAUDE_CODE_USE_MANTLE` selects Bedrock's Mantle endpoint. Set only in a shell, it is invisible here;
|
|
236
|
-
* the model IDs in the account's sessions then say Bedrock instead.
|
|
237
|
-
*/
|
|
238
|
-
export function settingsUseBedrock(text: string): boolean {
|
|
239
|
-
let settings: unknown;
|
|
240
|
-
try {
|
|
241
|
-
settings = JSON.parse(text);
|
|
242
|
-
} catch {
|
|
243
|
-
return false;
|
|
244
|
-
}
|
|
245
|
-
const env = Schema.decodeUnknownOption(Schema.Struct({ env: Schema.Record(Schema.String, Schema.Unknown) }))(settings);
|
|
246
|
-
if (env._tag === "None") return false;
|
|
247
|
-
return [env.value.env["CLAUDE_CODE_USE_BEDROCK"], env.value.env["CLAUDE_CODE_USE_MANTLE"]]
|
|
248
|
-
.some((value) => value === true || (typeof value === "string" && /^(1|true)$/i.test(value.trim())));
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* Bedrock's model IDs: a cross-region inference profile (`us.anthropic.claude-opus-4-8`, with `us-gov.`, `eu.`,
|
|
253
|
-
* `apac.`, `jp.`, `au.` or `global.`), a Mantle or foundation model ID (`anthropic.claude-haiku-4-5`), or an
|
|
254
|
-
* application inference profile ARN (`arn:aws:bedrock:…`), per https://code.claude.com/docs/en/amazon-bedrock.
|
|
255
|
-
* An Anthropic API model ID (`claude-opus-5-5`) has no `anthropic.` prefix.
|
|
256
|
-
*/
|
|
257
|
-
export const isBedrockModelId = (model: string): boolean =>
|
|
258
|
-
/^(?:(?:us|us-gov|eu|apac|jp|au|global)\.)?anthropic\./.test(model) || /^arn:aws[a-z-]*:bedrock:/.test(model);
|
|
259
|
-
|
|
260
|
-
/** What one session file says the session cost, as of its last save. */
|
|
261
|
-
export type SessionCost =
|
|
262
|
-
| { readonly kind: "cost"; readonly sessionId: string; readonly costUsd: number; readonly lastActiveAt: number; readonly partial: boolean; readonly models: ReadonlyArray<string> }
|
|
263
|
-
| { readonly kind: "none" }
|
|
264
|
-
| { readonly kind: "changed"; readonly issue: SchemaIssue.Issue };
|
|
265
|
-
|
|
266
|
-
/** Session files written to since `since`: `projects/<project>/<session id>.jsonl`. Subagents' files are a level deeper and hold no cost. */
|
|
267
|
-
function* sessionFilesSince(projects: string, since: number): Generator<{ readonly path: string; readonly modifiedAt: number }> {
|
|
268
|
-
if (!isDirectory(projects)) return;
|
|
269
|
-
for (const project of readdirSync(projects)) {
|
|
270
|
-
const dir = join(projects, project);
|
|
271
|
-
if (!isDirectory(dir)) continue;
|
|
272
|
-
for (const entry of readdirSync(dir)) {
|
|
273
|
-
if (!entry.endsWith(".jsonl")) continue;
|
|
274
|
-
const path = join(dir, entry);
|
|
275
|
-
const modifiedAt = statSync(path).mtimeMs;
|
|
276
|
-
if (modifiedAt >= since) yield { path, modifiedAt };
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
const CostState = Schema.Struct({
|
|
282
|
-
type: Schema.Literal("cost-state"),
|
|
283
|
-
sessionId: Schema.String,
|
|
284
|
-
totalCostUSD: Schema.Finite,
|
|
285
|
-
modelUsage: Schema.Record(Schema.String, Schema.Unknown),
|
|
286
|
-
hasUnknownModelCost: Schema.optionalKey(Schema.Boolean),
|
|
287
|
-
});
|
|
288
|
-
|
|
289
|
-
/** Session files keep growing while a session runs; one unchanged since it was last read is not read again. */
|
|
290
|
-
const sessionCostCache = new Map<string, { readonly modifiedAt: number; readonly cost: SessionCost }>();
|
|
291
|
-
|
|
292
|
-
/** The daemon runs for weeks; files Claude Code deleted, or that left the period, leave the cache too. */
|
|
293
|
-
function forgetOtherSessionFiles(projects: string, current: ReadonlySet<string>): void {
|
|
294
|
-
for (const path of sessionCostCache.keys()) {
|
|
295
|
-
if (path.startsWith(projects + sep) && !current.has(path)) sessionCostCache.delete(path);
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
/**
|
|
300
|
-
* The cost a session file last saved, and when the session was last active before that save: the time of the
|
|
301
|
-
* nearest earlier line that has one, since the cost line itself carries no time.
|
|
302
|
-
*/
|
|
303
|
-
export function latestSessionCost(file: { readonly path: string; readonly modifiedAt: number }): SessionCost {
|
|
304
|
-
const cached = sessionCostCache.get(file.path);
|
|
305
|
-
if (cached !== undefined && cached.modifiedAt === file.modifiedAt) return cached.cost;
|
|
306
|
-
let found: Extract<SessionCost, { kind: "cost" }> | undefined;
|
|
307
|
-
let cost: SessionCost = { kind: "none" };
|
|
308
|
-
for (const line of linesFromEnd(file.path, CLAUDE_TAIL_BYTES)) {
|
|
309
|
-
if (found === undefined) {
|
|
310
|
-
// Cheap test first: only the cost line is worth parsing until it is found.
|
|
311
|
-
if (!line.includes("\"cost-state\"")) continue;
|
|
312
|
-
const entry = parseJson(line);
|
|
313
|
-
if (typeof entry !== "object" || entry === null || !("type" in entry) || entry.type !== "cost-state") continue;
|
|
314
|
-
const decoded = Schema.decodeUnknownResult(CostState)(entry);
|
|
315
|
-
if (Result.isFailure(decoded)) {
|
|
316
|
-
cost = { kind: "changed", issue: decoded.failure.issue };
|
|
317
|
-
break;
|
|
318
|
-
}
|
|
319
|
-
const state = decoded.success;
|
|
320
|
-
found = {
|
|
321
|
-
kind: "cost",
|
|
322
|
-
sessionId: state.sessionId,
|
|
323
|
-
costUsd: state.totalCostUSD,
|
|
324
|
-
lastActiveAt: file.modifiedAt,
|
|
325
|
-
partial: state.hasUnknownModelCost === true,
|
|
326
|
-
models: Object.keys(state.modelUsage),
|
|
327
|
-
};
|
|
328
|
-
cost = found;
|
|
329
|
-
continue;
|
|
330
|
-
}
|
|
331
|
-
if (!line.includes("\"timestamp\"")) continue;
|
|
332
|
-
const entry = parseJson(line);
|
|
333
|
-
const at = typeof entry === "object" && entry !== null && "timestamp" in entry && typeof entry.timestamp === "string"
|
|
334
|
-
? Date.parse(entry.timestamp)
|
|
335
|
-
: NaN;
|
|
336
|
-
if (Number.isFinite(at)) {
|
|
337
|
-
cost = { ...found, lastActiveAt: at };
|
|
338
|
-
break;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
sessionCostCache.set(file.path, { modifiedAt: file.modifiedAt, cost });
|
|
342
|
-
return cost;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
/**
|
|
347
|
-
* Each session last active within the period, once. A session's saved cost covers the whole session, so
|
|
348
|
-
* a resumed one counts once, at its latest save, and a session forked from another carries the cost it
|
|
349
|
-
* started with, so the sum can count that part twice.
|
|
350
|
-
*/
|
|
351
|
-
export function estimateSpend(input: { readonly sessions: ReadonlyArray<SessionCost>; readonly bedrockSetting: boolean; readonly now: number }): LocalUse {
|
|
352
|
-
const changed = input.sessions.find((session) => session.kind === "changed");
|
|
353
|
-
if (changed !== undefined) return unknownShape("Claude Code's session cost record", changed.issue);
|
|
354
|
-
const since = input.now - PERIOD_DAYS * DAY_MS;
|
|
355
|
-
const bySession = new Map<string, Extract<SessionCost, { kind: "cost" }>>();
|
|
356
|
-
for (const session of input.sessions) {
|
|
357
|
-
if (session.kind !== "cost" || session.lastActiveAt < since) continue;
|
|
358
|
-
const seen = bySession.get(session.sessionId);
|
|
359
|
-
if (seen === undefined || session.costUsd > seen.costUsd) bySession.set(session.sessionId, session);
|
|
360
|
-
}
|
|
361
|
-
const counted = [...bySession.values()];
|
|
362
|
-
if (counted.length === 0) return { state: "none" };
|
|
363
|
-
return {
|
|
364
|
-
state: "spend",
|
|
365
|
-
periodDays: PERIOD_DAYS,
|
|
366
|
-
...USD_MICROS,
|
|
367
|
-
sessions: inSessionOrder(counted.map((session) => ({ id: session.sessionId, amount: Math.round(session.costUsd * 10 ** USD_MICROS.exponent), lastActiveAt: session.lastActiveAt }))),
|
|
368
|
-
partial: counted.some((session) => session.partial),
|
|
369
|
-
provider: input.bedrockSetting || counted.some((session) => session.models.some(isBedrockModelId)) ? "bedrock" : null,
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
// ── The saved record, when the CLI cannot be asked ──────────────────────────────────────────────────
|
|
374
|
-
|
|
375
|
-
const ClaudeWindow = Schema.Struct({ utilization: Schema.Finite, resets_at: Schema.NullOr(Schema.String) });
|
|
376
|
-
const ClaudeMoney = Schema.Struct({ amount_minor: Schema.Finite, currency: Schema.String, exponent: Schema.Int });
|
|
377
|
-
const ClaudeUsageCache = Schema.Struct({
|
|
378
|
-
fetchedAtMs: Schema.Finite,
|
|
379
|
-
utilization: Schema.Struct({
|
|
380
|
-
five_hour: Schema.optionalKey(Schema.NullOr(ClaudeWindow)),
|
|
381
|
-
seven_day: Schema.optionalKey(Schema.NullOr(ClaudeWindow)),
|
|
382
|
-
// Usage credits, the account's spend beyond its plan limits. `limit` has only been seen as null, so a
|
|
383
|
-
// limit in another shape is left out rather than failing the whole reading.
|
|
384
|
-
spend: Schema.optionalKey(Schema.NullOr(Schema.Struct({ enabled: Schema.Boolean, used: ClaudeMoney, limit: Schema.Unknown }))),
|
|
385
|
-
}),
|
|
386
|
-
});
|
|
387
|
-
const OAuthAccount = Schema.Struct({ emailAddress: Schema.String, organizationUuid: Schema.String });
|
|
388
|
-
|
|
389
|
-
/** Claude's documented window lengths: its status line calls them the 5-hour and 7-day limits. */
|
|
390
|
-
const CLAUDE_WINDOWS = [["five_hour", 300], ["seven_day", 7 * 24 * 60]] as const;
|
|
391
|
-
|
|
392
|
-
/**
|
|
393
|
-
* The account and its plan usage as Claude Code last recorded them in the account's `.claude.json`: who
|
|
394
|
-
* signed in under `oauthAccount`, the usage it last fetched under `cachedUsageUtilization`.
|
|
395
|
-
*/
|
|
396
|
-
export function parseClaudeState(text: string): AccountReading {
|
|
397
|
-
let state: unknown;
|
|
398
|
-
try {
|
|
399
|
-
state = JSON.parse(text);
|
|
400
|
-
} catch {
|
|
401
|
-
// Claude Code rewrites the file while it runs; a half-written one reads fine a moment later.
|
|
402
|
-
return { identity: null, limits: { state: "unknown", reason: "the account's .claude.json is not valid JSON" } };
|
|
403
|
-
}
|
|
404
|
-
if (typeof state !== "object" || state === null) return { identity: null, limits: { state: "none", reason: "no usage recorded" } };
|
|
405
|
-
const account = Schema.decodeUnknownOption(OAuthAccount)("oauthAccount" in state ? state.oauthAccount : undefined);
|
|
406
|
-
const identity: AccountIdentity | null = account._tag === "Some"
|
|
407
|
-
? { id: account.value.organizationUuid, email: account.value.emailAddress, plan: null }
|
|
408
|
-
: null;
|
|
409
|
-
if (!("cachedUsageUtilization" in state)) return { identity, limits: { state: "none", reason: "no usage recorded" } };
|
|
410
|
-
const decoded = Schema.decodeUnknownResult(ClaudeUsageCache)(state.cachedUsageUtilization);
|
|
411
|
-
if (Result.isFailure(decoded)) return { identity, limits: unknownShape("Claude Code's usage cache", decoded.failure.issue) };
|
|
412
|
-
const cache = decoded.success;
|
|
413
|
-
|
|
414
|
-
const windows: UsageWindow[] = [];
|
|
415
|
-
for (const [key, minutes] of CLAUDE_WINDOWS) {
|
|
416
|
-
const window = cache.utilization[key];
|
|
417
|
-
if (window === undefined || window === null) continue;
|
|
418
|
-
const resetsAt = window.resets_at === null ? null : Date.parse(window.resets_at);
|
|
419
|
-
if (resetsAt !== null && !Number.isFinite(resetsAt)) {
|
|
420
|
-
return { identity, limits: { state: "unknown", reason: `Claude Code's usage cache changed shape: ${key}.resets_at is not a time` } };
|
|
421
|
-
}
|
|
422
|
-
windows.push({ name: windowName(minutes), minutes, usedPercent: window.utilization, resetsAt });
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
const spend = cache.utilization.spend;
|
|
426
|
-
const limit = Schema.decodeUnknownOption(ClaudeMoney)(spend?.limit);
|
|
427
|
-
return {
|
|
428
|
-
identity,
|
|
429
|
-
limits: {
|
|
430
|
-
state: "reading",
|
|
431
|
-
asOf: cache.fetchedAtMs,
|
|
432
|
-
source: "saved",
|
|
433
|
-
windows,
|
|
434
|
-
...(spend?.enabled === true
|
|
435
|
-
? { spent: { used: money(spend.used), limit: limit._tag === "Some" ? money(limit.value) : null } }
|
|
436
|
-
: {}),
|
|
437
|
-
},
|
|
438
|
-
};
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
const money = (value: Schema.Schema.Type<typeof ClaudeMoney>): Money =>
|
|
442
|
-
({ amountMinor: value.amount_minor, currency: value.currency, exponent: value.exponent });
|