@jive-sh/skill-sync 0.4.13 → 0.4.14-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 (40) hide show
  1. package/multi-call-binary +4 -0
  2. package/package.json +11 -39
  3. package/README.md +0 -103
  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 -463
  8. package/dist/daemons/skill-sync-daemon.js.map +0 -1
  9. package/dist/entrypoints/skill-sync.js +0 -140
  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/config.js +0 -155
  14. package/dist/internal/config.js.map +0 -1
  15. package/dist/internal/control.js +0 -101
  16. package/dist/internal/control.js.map +0 -1
  17. package/dist/internal/folders.js +0 -46
  18. package/dist/internal/folders.js.map +0 -1
  19. package/dist/internal/path.js +0 -36
  20. package/dist/internal/path.js.map +0 -1
  21. package/dist/internal/server.js +0 -32
  22. package/dist/internal/server.js.map +0 -1
  23. package/dist/internal/sync.js +0 -162
  24. package/dist/internal/sync.js.map +0 -1
  25. package/dist/internal/usage.js +0 -419
  26. package/dist/internal/usage.js.map +0 -1
  27. package/dist/internal/wire.js +0 -18
  28. package/dist/internal/wire.js.map +0 -1
  29. package/install.cjs +0 -576
  30. package/src/daemons/skill-sync-daemon.ts +0 -457
  31. package/src/entrypoints/skill-sync.ts +0 -143
  32. package/src/index.ts +0 -15
  33. package/src/internal/config.ts +0 -198
  34. package/src/internal/control.ts +0 -127
  35. package/src/internal/folders.ts +0 -49
  36. package/src/internal/path.ts +0 -32
  37. package/src/internal/server.ts +0 -34
  38. package/src/internal/sync.ts +0 -197
  39. package/src/internal/usage.ts +0 -457
  40. package/src/internal/wire.ts +0 -229
@@ -1,457 +0,0 @@
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
- }
@@ -1,229 +0,0 @@
1
- /**
2
- * The shapes the daemon and the service exchange.
3
- *
4
- * Declared in the library and imported by the service so there is one definition rather than two that
5
- * drift. The service depends on the library; nothing goes the other way.
6
- */
7
-
8
- export interface RemoteFile {
9
- readonly path: string;
10
- /** Null when the file is deleted; the row stays, so the deletion reaches every machine. */
11
- readonly hash: string | null;
12
- /** When this version was edited, in milliseconds since the epoch. The latest edit wins. */
13
- readonly editedAt: number;
14
- readonly updatedBy: string;
15
- }
16
-
17
- export interface ListFilesResponse {
18
- /** Highest sequence number in this page; the caller sends it back as `since`. */
19
- readonly cursor: number;
20
- readonly files: ReadonlyArray<RemoteFile>;
21
- }
22
-
23
- /** Taken only when `editedAt` is later than the edit the server holds; refused with 409 otherwise. */
24
- export interface PutFileRequest {
25
- readonly path: string;
26
- /** When the file was edited: its modification time, or for a deletion, when it was noticed. */
27
- readonly editedAt: number;
28
- /** Null to delete. */
29
- readonly hash: string | null;
30
- /** Base64, absent for a delete. */
31
- readonly content: string | null;
32
- readonly machine: string;
33
- }
34
-
35
- /** Where a folder's sync stands, as the dashboard shows it. `attention` means a cycle failed; `detail` says why. */
36
- export type FolderState = "idle" | "attention";
37
-
38
- /**
39
- * A skill is a top-level entry of a skills folder — usually a directory like `jive/` holding `SKILL.md`
40
- * and its files — and it is the unit of opting in: all of its files sync, or none do, so a skill never
41
- * arrives half-present on another machine.
42
- */
43
- export const skillOf = (path: string): string => path.split("/")[0]!;
44
-
45
- /** A file and the SHA-256 of its content — the same hash the server stores, so copies can be compared. */
46
- export interface FileHash {
47
- readonly path: string;
48
- readonly hash: string;
49
- }
50
-
51
- /** One skill as a folder holds it. */
52
- export interface LocalSkill {
53
- readonly name: string;
54
- readonly files: ReadonlyArray<FileHash>;
55
- }
56
-
57
- /**
58
- * `POST /folders`: every folder this machine found, with the skills in each, for the dashboard. Answered
59
- * with the enabled folders, each with the synced list: the daemon pushes and pulls exactly those skills,
60
- * and never touches any other.
61
- */
62
- export interface FoldersRequest {
63
- readonly folders: ReadonlyArray<{ readonly path: string; readonly skills: ReadonlyArray<LocalSkill> }>;
64
- }
65
- export interface FolderPrefs {
66
- readonly path: string;
67
- readonly skills: ReadonlyArray<string>;
68
- }
69
- export interface FoldersResponse {
70
- readonly folders: ReadonlyArray<FolderPrefs>;
71
- }
72
-
73
- /** `GET /skills`: the synced list, as `skill-sync list` shows it. Deleted skills are not on it. */
74
- export interface ListSkillsResponse {
75
- readonly skills: ReadonlyArray<ListedSkill>;
76
- }
77
- export interface ListedSkill {
78
- readonly name: string;
79
- /** Live files on the server; zero for a skill ticked before any machine has pushed it. */
80
- readonly files: number;
81
- /** The latest edit of any of its files, and the display name of the machine it came from; null with no files. */
82
- readonly editedAt: number | null;
83
- readonly editedBy: string | null;
84
- }
85
-
86
- /**
87
- * The header a daemon names its own version in when it opens its WebSocket to the hub, so the dashboard
88
- * can show which version each machine runs. Daemons before 0.4.6 do not send it.
89
- */
90
- export const DAEMON_VERSION_HEADER = "x-skill-sync-version";
91
-
92
- /** One usage limit of an account: how much of it is used and when it starts over. */
93
- export interface UsageWindow {
94
- /** How long the window is, in minutes (300 for five hours, 10080 for a week); null when the tool does not say. */
95
- readonly minutes: number | null;
96
- /** Percent of the limit used, from 0 to 100, as the tool last recorded it. */
97
- readonly usedPercent: number;
98
- /** When the window starts over, in milliseconds since the epoch; null when no window is running. */
99
- readonly resetsAt: number | null;
100
- }
101
-
102
- /** Money as the tool records it: an amount in the currency's smallest unit, so 1234 with exponent 2 is 12.34. */
103
- export interface Money {
104
- readonly amountMinor: number;
105
- readonly currency: string;
106
- readonly exponent: number;
107
- }
108
-
109
- /**
110
- * What a daemon knows about one Claude or Codex account on its machine, read from files the tool itself
111
- * writes. Never a credential: only these numbers leave the machine.
112
- *
113
- * `reading`: the tool's latest record, with the time it was taken (`asOf`); every number is as of then.
114
- * `estimate`: a Claude account with no plan limits, such as one on Amazon Bedrock or an API key: what
115
- * Claude Code estimated its recent sessions cost at list price. `none`: the tool has not recorded usage for
116
- * this account yet. `unknown`: the record exists but is in a shape this version cannot read, as when a new
117
- * release of the tool changes it.
118
- */
119
- export type AccountUsage = {
120
- readonly tool: "claude" | "codex";
121
- /** The account's folder in the home directory, such as `.claude-work` or `.codex`. */
122
- readonly home: string;
123
- } & (
124
- | {
125
- readonly state: "reading";
126
- readonly asOf: number;
127
- readonly windows: ReadonlyArray<UsageWindow>;
128
- /** Spent beyond the plan, when the account pays for usage past its limits; absent when it does not. */
129
- readonly spent?: { readonly used: Money; readonly limit: Money | null };
130
- }
131
- | {
132
- readonly state: "estimate";
133
- /** When the newest session counted was last active; nothing later is in the sum. */
134
- readonly asOf: number;
135
- /** Sessions last active within this many days before the reading are counted. */
136
- readonly periodDays: number;
137
- /**
138
- * The sum of Claude Code's own estimate for each session, at list price. Claude Code saves a session's
139
- * estimate when the session ends, is cleared, resumed or forked, so a session still running is not in it.
140
- */
141
- readonly spent: Money;
142
- readonly sessions: number;
143
- /** Claude Code could not price a model in at least one session, so the true cost is higher. */
144
- readonly partial: boolean;
145
- /** `bedrock` when the account's settings or the model IDs its sessions used say so; null when nothing says. */
146
- readonly provider: "bedrock" | null;
147
- }
148
- | { readonly state: "none" }
149
- | { readonly state: "unknown"; readonly reason: string }
150
- );
151
-
152
- /** Daemon → hub, over the daemon's WebSocket. */
153
- export type DaemonMessage =
154
- | {
155
- readonly type: "status";
156
- readonly folder: string;
157
- readonly state: FolderState;
158
- readonly detail?: string;
159
- /** A one-line summary of what the last cycle changed, when it changed anything. */
160
- readonly activity?: string;
161
- }
162
- /** Every account on the machine, sent on connecting and whenever a number changes. Daemons before 0.4.9 never send it. */
163
- | { readonly type: "usage"; readonly accounts: ReadonlyArray<AccountUsage> };
164
-
165
- /** Hub → daemon. `prefs` replaces what syncs; `changed` means another write landed on the server. */
166
- export type HubToDaemon =
167
- | { readonly type: "prefs"; readonly folders: ReadonlyArray<FolderPrefs> }
168
- | { readonly type: "changed" };
169
-
170
- export interface SkillView {
171
- readonly name: string;
172
- /** On the list of synced skills, which every enabled folder sends and receives. */
173
- readonly synced: boolean;
174
- /** The folder has a copy on disk. */
175
- readonly local: boolean;
176
- readonly files: ReadonlyArray<FileHash>;
177
- }
178
-
179
- export interface FolderView {
180
- readonly path: string;
181
- readonly enabled: boolean;
182
- readonly state: FolderState;
183
- readonly detail: string | null;
184
- readonly lastActivityAt: number | null;
185
- readonly lastActivity: string | null;
186
- readonly skills: ReadonlyArray<SkillView>;
187
- }
188
-
189
- export interface MachineView {
190
- /** The name the machine's daemon uses; it identifies the machine and never changes. */
191
- readonly machine: string;
192
- /** What the dashboard calls it: renamed there, or the machine name until then. */
193
- readonly name: string;
194
- /** True while this machine's daemon holds a connection to the hub. */
195
- readonly online: boolean;
196
- /** The version its connected daemon runs; null while offline, or when the daemon is too old to say. */
197
- readonly daemonVersion: string | null;
198
- /** Each account's usage as its connected daemon last sent it; empty while offline, or from a daemon before 0.4.9. */
199
- readonly accounts: ReadonlyArray<AccountUsage>;
200
- readonly lastSeen: number | null;
201
- readonly folders: ReadonlyArray<FolderView>;
202
- }
203
-
204
- /** A skill on the synced list, as the server holds it: the version every enabled folder converges on. */
205
- export interface SyncedSkill {
206
- readonly name: string;
207
- readonly files: ReadonlyArray<FileHash & { readonly updatedBy: string; readonly editedAt: number }>;
208
- }
209
-
210
- /** Hub → dashboard: the whole picture, resent on every change. It is small, and a diff protocol is not. */
211
- export interface Snapshot {
212
- readonly type: "snapshot";
213
- /** The deployed service version. A dashboard built by another version reloads itself. */
214
- readonly version: string;
215
- /** The `latest` version of this package on npm, which every daemon upgrades to; null if npm could not be reached. */
216
- readonly publishedVersion: string | null;
217
- /** Display name for every machine name that appears anywhere in the snapshot, including old log entries. */
218
- readonly names: Readonly<Record<string, string>>;
219
- readonly skills: ReadonlyArray<SyncedSkill>;
220
- readonly machines: ReadonlyArray<MachineView>;
221
- }
222
-
223
- /** Dashboard → hub. */
224
- export type DashboardMessage =
225
- | { readonly type: "setFolder"; readonly machine: string; readonly path: string; readonly enabled: boolean }
226
- /** Adds a skill to the synced list, or removes it: one list for every machine and folder. */
227
- | { readonly type: "setSkill"; readonly skill: string; readonly synced: boolean }
228
- /** An empty name restores the machine name. */
229
- | { readonly type: "renameMachine"; readonly machine: string; readonly name: string };