@jive-sh/skill-sync 0.5.1 → 0.6.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 (58) hide show
  1. package/multi-call-binary +4 -0
  2. package/package.json +11 -39
  3. package/README.md +0 -138
  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 -499
  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 -92
  14. package/dist/internal/agents/agent-tool.js.map +0 -1
  15. package/dist/internal/agents/claude.js +0 -422
  16. package/dist/internal/agents/claude.js.map +0 -1
  17. package/dist/internal/agents/codex.js +0 -294
  18. package/dist/internal/agents/codex.js.map +0 -1
  19. package/dist/internal/agents/command.js +0 -79
  20. package/dist/internal/agents/command.js.map +0 -1
  21. package/dist/internal/agents/grok.js +0 -115
  22. package/dist/internal/agents/grok.js.map +0 -1
  23. package/dist/internal/agents/index.js +0 -70
  24. package/dist/internal/agents/index.js.map +0 -1
  25. package/dist/internal/config.js +0 -131
  26. package/dist/internal/config.js.map +0 -1
  27. package/dist/internal/control.js +0 -101
  28. package/dist/internal/control.js.map +0 -1
  29. package/dist/internal/folders.js +0 -47
  30. package/dist/internal/folders.js.map +0 -1
  31. package/dist/internal/path.js +0 -36
  32. package/dist/internal/path.js.map +0 -1
  33. package/dist/internal/server.js +0 -32
  34. package/dist/internal/server.js.map +0 -1
  35. package/dist/internal/skill-check.js +0 -83
  36. package/dist/internal/skill-check.js.map +0 -1
  37. package/dist/internal/sync.js +0 -183
  38. package/dist/internal/sync.js.map +0 -1
  39. package/dist/internal/wire.js +0 -24
  40. package/dist/internal/wire.js.map +0 -1
  41. package/install.cjs +0 -576
  42. package/src/daemons/skill-sync-daemon.ts +0 -491
  43. package/src/entrypoints/skill-sync.ts +0 -156
  44. package/src/index.ts +0 -15
  45. package/src/internal/agents/agent-tool.ts +0 -136
  46. package/src/internal/agents/claude.ts +0 -440
  47. package/src/internal/agents/codex.ts +0 -314
  48. package/src/internal/agents/command.ts +0 -97
  49. package/src/internal/agents/grok.ts +0 -117
  50. package/src/internal/agents/index.ts +0 -74
  51. package/src/internal/config.ts +0 -172
  52. package/src/internal/control.ts +0 -140
  53. package/src/internal/folders.ts +0 -50
  54. package/src/internal/path.ts +0 -32
  55. package/src/internal/server.ts +0 -34
  56. package/src/internal/skill-check.ts +0 -97
  57. package/src/internal/sync.ts +0 -217
  58. package/src/internal/wire.ts +0 -279
@@ -1,314 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { readdirSync, statSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { Result, Schema } from "effect";
6
- import type { AccountLimits, LocalUse, UsageWindow } from "../wire";
7
- import {
8
- CLI_TIMEOUT_MS, DAY_MS, PERIOD_DAYS, homesNamed, isDirectory, linesFromEnd, parseJson, unknownShape, windowName,
9
- type AccountContext, type AccountReading, type AgentTool,
10
- } from "./agent-tool";
11
-
12
- /**
13
- * Codex. Each account is a `CODEX_HOME` (`~/.codex`, `~/.codex-<name>`). Every account reads a user's
14
- * skills from `~/.agents/skills`, offered when any Codex account or `~/.agents` exists, because a
15
- * machine with Codex installed may have no `~/.agents` yet.
16
- *
17
- * - Account: `codex app-server` speaks JSON-RPC over stdio, the protocol Codex's own editors and desktop
18
- * app use (openai/codex, codex-rs/app-server-protocol). `account/read` says who is signed in and
19
- * `account/rateLimits/read` fetches the account's limits from OpenAI. The `codex` binary is looked for
20
- * on PATH, in the folders npm, bun and Homebrew install to, and inside the ChatGPT and Codex desktop
21
- * apps, which ship one. Without one, the limits are the ones Codex recorded with its latest turn, as a
22
- * `token_count` event in that turn's session file under `sessions/` (Codex's `RateLimitSnapshot`,
23
- * codex-rs/protocol/src/protocol.rs).
24
- * - This machine: each session's running token total, from the same events, summed over sessions active
25
- * in the last `PERIOD_DAYS` days.
26
- */
27
- export const codex: AgentTool = {
28
- tool: "codex",
29
- skillsFolders: (home) =>
30
- homesNamed(home, "codex").length > 0 || isDirectory(join(home, ".agents")) ? [join(home, ".agents", "skills")] : [],
31
- accounts: (home) => homesNamed(home, "codex"),
32
- readAccount: (account, context) => readCodexAccount(account, context),
33
- readLocalUse: (account, _home, now) => localTokens(account, now),
34
- };
35
-
36
- // ── The account ─────────────────────────────────────────────────────────────────────────────────────
37
-
38
- /** The desktop apps that ship a `codex` binary, on macOS. */
39
- const appBundles = (home: string): string[] => ["/Applications", join(home, "Applications")]
40
- .flatMap((folder) => ["ChatGPT.app", "Codex.app"].map((app) => join(folder, app, "Contents", "Resources", "codex")));
41
-
42
- async function readCodexAccount(account: string, { home, now, findCommand }: AccountContext): Promise<AccountReading> {
43
- const command = findCommand({ name: "codex", also: appBundles(home) });
44
- if (command === undefined) return { identity: null, limits: savedLimits(account, "`codex` was not found") };
45
- const answers = await askAppServer({ command, account });
46
- if (answers.kind === "failed") return { identity: null, limits: savedLimits(account, answers.reason) };
47
- return parseAppServerAnswers({ account: answers.account, rateLimits: answers.rateLimits, now });
48
- }
49
-
50
- /** One JSON-RPC response: `result` on success, `error` otherwise. */
51
- const RpcResponse = Schema.Struct({
52
- id: Schema.Finite,
53
- result: Schema.optionalKey(Schema.Unknown),
54
- error: Schema.optionalKey(Schema.Struct({ message: Schema.String })),
55
- });
56
- type RpcResponse = Schema.Schema.Type<typeof RpcResponse>;
57
-
58
- const REQUEST_ACCOUNT = 2;
59
- const REQUEST_RATE_LIMITS = 3;
60
-
61
- /**
62
- * Starts `codex app-server` for the account, initializes the connection as the protocol requires, asks
63
- * for the account and its rate limits, and stops it once both answers are in. `account/rateLimits/read`
64
- * is sent without params: older versions refuse any (`invalid type: map, expected unit`).
65
- */
66
- function askAppServer(input: { readonly command: string; readonly account: string }): Promise<
67
- | { readonly kind: "answered"; readonly account: RpcResponse; readonly rateLimits: RpcResponse }
68
- | { readonly kind: "failed"; readonly reason: string }
69
- > {
70
- return new Promise((resolve) => {
71
- const child = spawn(input.command, ["app-server"], {
72
- env: { ...process.env, CODEX_HOME: input.account },
73
- cwd: tmpdir(),
74
- stdio: ["pipe", "pipe", "pipe"],
75
- });
76
- const answers = new Map<number, RpcResponse>();
77
- let stderr = "";
78
- let pending = "";
79
- let settled = false;
80
- const settle = (outcome: Parameters<typeof resolve>[0]) => {
81
- if (settled) return;
82
- settled = true;
83
- clearTimeout(timer);
84
- child.kill();
85
- resolve(outcome);
86
- };
87
- const timer = setTimeout(() => settle({ kind: "failed", reason: `\`codex app-server\` did not answer within ${CLI_TIMEOUT_MS / 1000} s` }), CLI_TIMEOUT_MS);
88
- child.on("error", (error) => settle({ kind: "failed", reason: `\`codex app-server\` could not start: ${error.message}` }));
89
- child.on("close", (status) => settle({
90
- kind: "failed",
91
- reason: `\`codex app-server\` exited (${status}) before answering: ${stderr.trim().slice(0, 160)}`,
92
- }));
93
- child.stderr.setEncoding("utf-8").on("data", (chunk: string) => { stderr = (stderr + chunk).slice(-4096); });
94
- child.stdout.setEncoding("utf-8").on("data", (chunk: string) => {
95
- pending += chunk;
96
- const lines = pending.split("\n");
97
- pending = lines.pop() ?? "";
98
- for (const line of lines) {
99
- // Notifications (`account/updated`, `remoteControl/status/changed`) arrive between responses; only responses have an id.
100
- const response = Schema.decodeUnknownOption(RpcResponse)(parseJson(line));
101
- if (response._tag === "Some") answers.set(response.value.id, response.value);
102
- }
103
- const initialized = answers.get(1);
104
- if (initialized?.error !== undefined) {
105
- settle({ kind: "failed", reason: `\`codex app-server\` refused to initialize: ${initialized.error.message.slice(0, 160)}` });
106
- return;
107
- }
108
- const account = answers.get(REQUEST_ACCOUNT);
109
- const rateLimits = answers.get(REQUEST_RATE_LIMITS);
110
- if (account !== undefined && rateLimits !== undefined) settle({ kind: "answered", account, rateLimits });
111
- });
112
- // A dead stdin raises EPIPE here; the `close` above reports why the server went.
113
- child.stdin.on("error", () => {});
114
- child.stdin.write([
115
- { id: 1, method: "initialize", params: { clientInfo: { name: "skill-sync", title: null, version: "1" }, capabilities: null } },
116
- { method: "initialized" },
117
- { id: REQUEST_ACCOUNT, method: "account/read", params: {} },
118
- { id: REQUEST_RATE_LIMITS, method: "account/rateLimits/read" },
119
- ].map((message) => JSON.stringify(message) + "\n").join(""));
120
- });
121
- }
122
-
123
- /** `account/read`'s answer (codex-rs/app-server-protocol/schema/typescript/v2/GetAccountResponse.ts). */
124
- const AccountResponse = Schema.Struct({
125
- account: Schema.NullOr(Schema.Struct({
126
- type: Schema.String,
127
- email: Schema.optionalKey(Schema.NullOr(Schema.String)),
128
- planType: Schema.optionalKey(Schema.NullOr(Schema.String)),
129
- })),
130
- });
131
- const AppServerWindow = Schema.Struct({
132
- usedPercent: Schema.Finite,
133
- windowDurationMins: Schema.NullOr(Schema.Finite),
134
- resetsAt: Schema.NullOr(Schema.Finite),
135
- });
136
- const AppServerSnapshot = Schema.Struct({ primary: Schema.NullOr(AppServerWindow), secondary: Schema.NullOr(AppServerWindow) });
137
- /** `account/rateLimits/read`'s answer (GetAccountRateLimitsResponse.ts): the main bucket is `codex`. */
138
- const RateLimitsResponse = Schema.Struct({
139
- rateLimits: AppServerSnapshot,
140
- rateLimitsByLimitId: Schema.optionalKey(Schema.NullOr(Schema.Record(Schema.String, AppServerSnapshot))),
141
- });
142
-
143
- /** The account and its limits from the two answers `codex app-server` gave. */
144
- export function parseAppServerAnswers(input: { readonly account: RpcResponse; readonly rateLimits: RpcResponse; readonly now: number }): AccountReading {
145
- if (input.account.error !== undefined) {
146
- return { identity: null, limits: { state: "unknown", reason: `\`account/read\` failed: ${input.account.error.message.slice(0, 160)}` } };
147
- }
148
- const decodedAccount = Schema.decodeUnknownResult(AccountResponse)(input.account.result);
149
- if (Result.isFailure(decodedAccount)) return { identity: null, limits: unknownShape("Codex's `account/read` answer", decodedAccount.failure.issue) };
150
- const signedIn = decodedAccount.success.account;
151
- if (signedIn === null) return { identity: null, limits: { state: "none", reason: "signed out" } };
152
- if (signedIn.type !== "chatgpt" || typeof signedIn.email !== "string") {
153
- return { identity: null, limits: { state: "none", reason: `signed in with ${signedIn.type}: no plan limits` } };
154
- }
155
- const plan = signedIn.planType;
156
- const identity = { id: signedIn.email, email: signedIn.email, plan: typeof plan === "string" && plan !== "unknown" ? plan : null };
157
-
158
- if (input.rateLimits.error !== undefined) {
159
- return { identity, limits: { state: "unknown", reason: `\`account/rateLimits/read\` failed: ${input.rateLimits.error.message.slice(0, 160)}` } };
160
- }
161
- const decodedLimits = Schema.decodeUnknownResult(RateLimitsResponse)(input.rateLimits.result);
162
- if (Result.isFailure(decodedLimits)) return { identity, limits: unknownShape("Codex's `account/rateLimits/read` answer", decodedLimits.failure.issue) };
163
- const snapshot = decodedLimits.success.rateLimitsByLimitId?.codex ?? decodedLimits.success.rateLimits;
164
- return {
165
- identity,
166
- limits: {
167
- state: "reading",
168
- asOf: input.now,
169
- source: "account",
170
- windows: [snapshot.primary, snapshot.secondary].flatMap((window) => window === null ? [] : [{
171
- name: windowName(window.windowDurationMins),
172
- minutes: window.windowDurationMins,
173
- usedPercent: window.usedPercent,
174
- resetsAt: window.resetsAt === null ? null : window.resetsAt * 1000,
175
- }]),
176
- },
177
- };
178
- }
179
-
180
- // ── Session files ───────────────────────────────────────────────────────────────────────────────────
181
-
182
- const CodexWindow = Schema.Struct({
183
- used_percent: Schema.Finite,
184
- window_minutes: Schema.NullOr(Schema.Finite),
185
- resets_at: Schema.NullOr(Schema.Finite),
186
- });
187
- const CodexTokenCount = Schema.Struct({
188
- timestamp: Schema.String,
189
- payload: Schema.Struct({
190
- type: Schema.Literal("token_count"),
191
- info: Schema.optionalKey(Schema.NullOr(Schema.Struct({
192
- total_token_usage: Schema.Struct({ total_tokens: Schema.Finite }),
193
- }))),
194
- rate_limits: Schema.NullOr(Schema.Struct({
195
- limit_id: Schema.optionalKey(Schema.NullOr(Schema.String)),
196
- primary: Schema.NullOr(CodexWindow),
197
- secondary: Schema.NullOr(CodexWindow),
198
- })),
199
- }),
200
- });
201
-
202
- /** Session files newest first; only this many are searched for a rate-limit reading before giving up. */
203
- const CODEX_FILES_SEARCHED = 5;
204
- /** How far back from its end a session file is searched. Each turn writes one event, so the last is near the end. */
205
- const CODEX_TAIL_BYTES = 16 * 1024 * 1024;
206
-
207
- /** What one session file's latest `token_count` events say. */
208
- export interface SessionRecord {
209
- /** The newest rate-limit reading, or undefined when the file has none (a session run with an API key). */
210
- readonly limits: AccountLimits | undefined;
211
- /** The session's token total so far, or undefined when no event carries one. */
212
- readonly tokens: number | undefined;
213
- }
214
-
215
- /** Session files keep growing while a session runs; one unchanged since it was last read is not read again. */
216
- const sessionCache = new Map<string, { readonly modifiedAt: number; readonly record: SessionRecord }>();
217
-
218
- /** The account's session files, newest first; files Codex deleted leave the cache. */
219
- function sessionFilesNewestFirst(account: string): { readonly path: string; readonly modifiedAt: number }[] {
220
- const files = sessionFiles(join(account, "sessions"))
221
- .map((path) => ({ path, modifiedAt: statSync(path).mtimeMs }))
222
- .sort((a, b) => b.modifiedAt - a.modifiedAt);
223
- const current = new Set(files.map((file) => file.path));
224
- for (const path of sessionCache.keys()) {
225
- if (path.startsWith(account) && !current.has(path)) sessionCache.delete(path);
226
- }
227
- return files;
228
- }
229
-
230
- /** The limits Codex recorded with its latest turn, for when `codex app-server` cannot be asked; `why` says why it could not. */
231
- function savedLimits(account: string, why: string): AccountLimits {
232
- // The most recently written file holds the latest reading; an older one only matters when the newer
233
- // ones hold none.
234
- for (const file of sessionFilesNewestFirst(account).slice(0, CODEX_FILES_SEARCHED)) {
235
- const record = sessionRecord(file);
236
- if (record.limits !== undefined) return record.limits.state === "reading" ? { ...record.limits, cliFailure: why } : record.limits;
237
- }
238
- return { state: "unknown", reason: why };
239
- }
240
-
241
- function localTokens(account: string, now: number): LocalUse {
242
- const since = now - PERIOD_DAYS * DAY_MS;
243
- const totals = sessionFilesNewestFirst(account)
244
- .filter((file) => file.modifiedAt >= since)
245
- .map((file) => sessionRecord(file).tokens)
246
- .filter((tokens) => tokens !== undefined);
247
- return { state: "tokens", periodDays: PERIOD_DAYS, count: totals.reduce((sum, count) => sum + count, 0), sessions: totals.length };
248
- }
249
-
250
- function sessionRecord(file: { readonly path: string; readonly modifiedAt: number }): SessionRecord {
251
- const cached = sessionCache.get(file.path);
252
- if (cached !== undefined && cached.modifiedAt === file.modifiedAt) return cached.record;
253
- const record = latestSessionRecord(file.path);
254
- sessionCache.set(file.path, { modifiedAt: file.modifiedAt, record });
255
- return record;
256
- }
257
-
258
- /** Every `rollout-*.jsonl` under `sessions/`, which Codex files by date: `YYYY/MM/DD/rollout-….jsonl`. */
259
- function sessionFiles(dir: string): string[] {
260
- if (!isDirectory(dir)) return [];
261
- return readdirSync(dir, { recursive: true, encoding: "utf-8" })
262
- .filter((path) => /(^|[\\/])rollout-[^\\/]*\.jsonl$/.test(path))
263
- .map((path) => join(dir, path));
264
- }
265
-
266
- /** The newest rate-limit reading and token total in one session file, searched from the end, since files reach hundreds of MB. */
267
- export function latestSessionRecord(path: string): SessionRecord {
268
- let limits: AccountLimits | undefined;
269
- let tokens: number | undefined;
270
- for (const line of linesFromEnd(path, CODEX_TAIL_BYTES)) {
271
- const event = parseCodexLine(line);
272
- if (event === undefined) continue;
273
- if (limits === undefined) limits = event.limits;
274
- if (tokens === undefined) tokens = event.tokens;
275
- if (limits !== undefined && tokens !== undefined) break;
276
- }
277
- return { limits, tokens };
278
- }
279
-
280
- /**
281
- * What one session-file line carries, or undefined when it is not a `token_count` event: most lines are
282
- * other events. A `token_count` from a session without plan limits has `rate_limits: null`.
283
- */
284
- export function parseCodexLine(line: string): SessionRecord | undefined {
285
- // Cheap test first: only these lines are worth parsing, and the others can be megabytes.
286
- if (!line.includes("\"token_count\"")) return undefined;
287
- const event = parseJson(line); // Undefined for the last line of a file Codex is still writing.
288
- if (!isTokenCount(event)) return undefined;
289
- const decoded = Schema.decodeUnknownResult(CodexTokenCount)(event);
290
- if (Result.isFailure(decoded)) return { limits: unknownShape("Codex's rate-limit record", decoded.failure.issue), tokens: undefined };
291
- const { payload, timestamp } = decoded.success;
292
- const tokens = payload.info?.total_token_usage.total_tokens;
293
- const limits = payload.rate_limits;
294
- // Another metered bucket than the main one; the main one is `codex`, or unnamed in older versions.
295
- if (limits === null || (limits.limit_id !== undefined && limits.limit_id !== null && limits.limit_id !== "codex")) {
296
- return { limits: undefined, tokens };
297
- }
298
- const asOf = Date.parse(timestamp);
299
- if (!Number.isFinite(asOf)) {
300
- return { limits: { state: "unknown", reason: "Codex's rate-limit record changed shape: timestamp is not a time" }, tokens };
301
- }
302
- const windows: UsageWindow[] = [limits.primary, limits.secondary].flatMap((window) => window === null ? [] : [{
303
- name: windowName(window.window_minutes),
304
- minutes: window.window_minutes,
305
- usedPercent: window.used_percent,
306
- resetsAt: window.resets_at === null ? null : window.resets_at * 1000,
307
- }]);
308
- return { limits: { state: "reading", asOf, source: "saved", windows }, tokens };
309
- }
310
-
311
- const isTokenCount = (event: unknown): boolean =>
312
- typeof event === "object" && event !== null && "payload" in event
313
- && typeof event.payload === "object" && event.payload !== null
314
- && "type" in event.payload && event.payload.type === "token_count";
@@ -1,97 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { readdirSync, statSync } from "node:fs";
3
- import { delimiter, join } from "node:path";
4
-
5
- /**
6
- * Finding and running an agent tool's own CLI.
7
- *
8
- * The daemon is started by the service manager (launchd, systemd, the Windows task scheduler), whose
9
- * PATH is the system's (`/usr/bin:/bin:/usr/sbin:/sbin` under launchd), not the user's shell's. So a CLI
10
- * is looked for on PATH and then in the folders its installers put it in.
11
- */
12
-
13
- /** Where package managers and installers put a user's commands, after PATH. */
14
- function installFolders(home: string): string[] {
15
- return [
16
- join(home, ".local", "bin"), // Claude Code's native installer
17
- join(home, ".bun", "bin"),
18
- join(home, ".npm-global", "bin"),
19
- join(home, ".volta", "bin"),
20
- join(home, "Library", "pnpm"),
21
- join(home, ".local", "share", "pnpm"),
22
- ...nvmFolders(home),
23
- "/opt/homebrew/bin",
24
- "/usr/local/bin",
25
- "/home/linuxbrew/.linuxbrew/bin",
26
- ];
27
- }
28
-
29
- /** Every Node version nvm installed, newest name last; a global npm install lands in one of them. */
30
- function nvmFolders(home: string): string[] {
31
- const versions = join(home, ".nvm", "versions", "node");
32
- try {
33
- return readdirSync(versions).sort().reverse().map((version) => join(versions, version, "bin"));
34
- } catch {
35
- return [];
36
- }
37
- }
38
-
39
- const isFile = (path: string): boolean => {
40
- try {
41
- return statSync(path).isFile();
42
- } catch {
43
- return false;
44
- }
45
- };
46
-
47
- /**
48
- * The first `name` on PATH, then in the install folders, then at the paths in `also` (an app bundle that
49
- * ships the CLI, an installer's own folder). Undefined when none exists.
50
- */
51
- export function findCommand(input: { readonly name: string; readonly home: string; readonly also?: ReadonlyArray<string> }): string | undefined {
52
- const file = process.platform === "win32" ? `${input.name}.exe` : input.name;
53
- const onPath = (process.env.PATH ?? "").split(delimiter).filter((folder) => folder !== "");
54
- const candidates = [...[...onPath, ...installFolders(input.home)].map((folder) => join(folder, file)), ...(input.also ?? [])];
55
- return candidates.find(isFile);
56
- }
57
-
58
- export interface CommandResult {
59
- /** Null when the command was killed or could not start. */
60
- readonly status: number | null;
61
- readonly stdout: string;
62
- readonly stderr: string;
63
- /** Why it did not finish: it could not start, or ran past its timeout. */
64
- readonly failure: string | undefined;
65
- }
66
-
67
- /** Runs a command to completion without blocking the daemon, killing it after `timeoutMs`. */
68
- export function runCommand(input: {
69
- readonly command: string;
70
- readonly args: ReadonlyArray<string>;
71
- readonly env: NodeJS.ProcessEnv;
72
- readonly cwd: string;
73
- readonly timeoutMs: number;
74
- }): Promise<CommandResult> {
75
- return new Promise((resolve) => {
76
- const child = spawn(input.command, [...input.args], { env: input.env, cwd: input.cwd, stdio: ["ignore", "pipe", "pipe"] });
77
- let stdout = "";
78
- let stderr = "";
79
- let failure: string | undefined;
80
- child.stdout.setEncoding("utf-8").on("data", (chunk: string) => { stdout += chunk; });
81
- child.stderr.setEncoding("utf-8").on("data", (chunk: string) => { stderr += chunk; });
82
- const timer = setTimeout(() => {
83
- failure = `did not finish within ${input.timeoutMs / 1000} s`;
84
- child.kill("SIGKILL");
85
- }, input.timeoutMs);
86
- // A command that cannot start emits `error`, and may or may not emit `close` after it.
87
- const finish = (status: number | null) => {
88
- clearTimeout(timer);
89
- resolve({ status, stdout, stderr, failure });
90
- };
91
- child.on("error", (error) => {
92
- failure = error.message;
93
- finish(null);
94
- });
95
- child.on("close", finish);
96
- });
97
- }
@@ -1,117 +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 type { LocalUse } from "../wire";
6
- import { DAY_MS, PERIOD_DAYS, homesNamed, isDirectory, parseJson, unknownShape, type AgentTool } from "./agent-tool";
7
-
8
- /**
9
- * Grok. Each account is a `GROK_HOME` (`~/.grok`, `~/.grok-<name>`), and Grok's docs name its `skills`
10
- * folder as where it reads a user's skills. Grok also reads `~/.agents/skills`, undocumented; a skill in
11
- * both loads once, from the Grok home (checked with `grok inspect`, Grok 1.0.70).
12
- *
13
- * Usage is what `grok usage <session-id>` prints, the command Grok's docs say to use instead of reading
14
- * session files: each session's token and cost totals (`costUsdTicks`, 10^10 per US dollar). The line sums
15
- * sessions active in the last `PERIOD_DAYS` days. A session's totals include history it inherited by
16
- * resume or fork, so a fork counts that part twice. Grok's plan allowance is only in its interactive
17
- * `/usage`, and `grok` has no command that says who is signed in, so no limit or account is shown.
18
- */
19
- export const grok: AgentTool = {
20
- tool: "grok",
21
- skillsFolders: (home) => homesNamed(home, "grok").map((account) => join(account, "skills")),
22
- accounts: (home) => homesNamed(home, "grok"),
23
- readAccount: async () => ({
24
- identity: null,
25
- limits: { state: "none", reason: "only in Grok's interactive /usage" },
26
- }),
27
- readLocalUse: (account, _home, now) => readGrok(account, now),
28
- };
29
-
30
- const GrokUsage = Schema.Struct({
31
- sessionId: Schema.String,
32
- updatedAt: Schema.String,
33
- session: Schema.Struct({ costUsdTicks: Schema.Finite, totalTokens: Schema.Finite }),
34
- });
35
- const TICKS_PER_USD = 1e10;
36
- /** `grok usage` reads one session's file and exits; this bounds a hung one. */
37
- const COMMAND_TIMEOUT_MS = 10_000;
38
-
39
- export type SessionTotals =
40
- | { readonly kind: "totals"; readonly usd: number; readonly updatedAt: number }
41
- /** A session with no turn yet: `grok usage` exits 1 saying "No usage recorded". */
42
- | { readonly kind: "empty" }
43
- | { readonly kind: "failed"; readonly reason: string };
44
-
45
- /** A session's totals are fetched again only when its directory changed: each `grok usage` run takes most of a second. */
46
- const sessionCache = new Map<string, { readonly modifiedAt: number; readonly totals: SessionTotals }>();
47
-
48
- function readGrok(account: string, now: number): LocalUse {
49
- const command = join(account, "bin", "grok");
50
- const sessions = sessionDirs(join(account, "sessions"), now - PERIOD_DAYS * DAY_MS);
51
- if (sessions.length === 0) return { state: "none" };
52
- if (!existsSync(command)) return { state: "unknown", reason: `Grok's command is not at ${command}` };
53
-
54
- const totals: Extract<SessionTotals, { kind: "totals" }>[] = [];
55
- for (const session of sessions) {
56
- const cached = sessionCache.get(session.path);
57
- const result = cached !== undefined && cached.modifiedAt === session.modifiedAt
58
- ? cached.totals
59
- : runGrokUsage(command, account, session.id);
60
- // A failure is asked again next time rather than kept until the session changes.
61
- if (result.kind !== "failed") sessionCache.set(session.path, { modifiedAt: session.modifiedAt, totals: result });
62
- if (result.kind === "failed") return { state: "unknown", reason: result.reason };
63
- if (result.kind === "totals") totals.push(result);
64
- }
65
- if (totals.length === 0) return { state: "none" };
66
- const usd = totals.reduce((sum, session) => sum + session.usd, 0);
67
- return {
68
- state: "spend",
69
- asOf: Math.max(...totals.map((session) => session.updatedAt)),
70
- periodDays: PERIOD_DAYS,
71
- spent: { amountMinor: Math.round(usd * 100), currency: "USD", exponent: 2 },
72
- sessions: totals.length,
73
- partial: false,
74
- provider: null,
75
- };
76
- }
77
-
78
- /**
79
- * Sessions active since `since`: `sessions/<encoded working directory>/<session id>/`, whose modification
80
- * time moves whenever Grok writes the session's files.
81
- */
82
- function sessionDirs(dir: string, since: number): { readonly id: string; readonly path: string; readonly modifiedAt: number }[] {
83
- if (!isDirectory(dir)) return [];
84
- return readdirSync(dir).flatMap((project) => {
85
- const projectDir = join(dir, project);
86
- if (!isDirectory(projectDir)) return [];
87
- return readdirSync(projectDir).flatMap((id) => {
88
- const path = join(projectDir, id);
89
- if (!/^[0-9a-f-]{36}$/i.test(id) || !isDirectory(path)) return [];
90
- const modifiedAt = statSync(path).mtimeMs;
91
- return modifiedAt >= since ? [{ id, path, modifiedAt }] : [];
92
- });
93
- });
94
- }
95
-
96
- export function runGrokUsage(command: string, account: string, sessionId: string): SessionTotals {
97
- const run = spawnSync(command, ["usage", sessionId], {
98
- env: { ...process.env, GROK_HOME: account },
99
- encoding: "utf-8",
100
- timeout: COMMAND_TIMEOUT_MS,
101
- });
102
- if (run.status === 0) return parseGrokUsage(run.stdout);
103
- const stderr = (run.stderr ?? "").trim();
104
- if (stderr.includes("No usage recorded")) return { kind: "empty" };
105
- return { kind: "failed", reason: `\`grok usage\` failed: ${run.error?.message ?? (stderr.slice(0, 160) || `exit ${run.status}`)}` };
106
- }
107
-
108
- export function parseGrokUsage(stdout: string): SessionTotals {
109
- const decoded = Schema.decodeUnknownResult(GrokUsage)(parseJson(stdout));
110
- if (Result.isFailure(decoded)) {
111
- const reading = unknownShape("`grok usage` output", decoded.failure.issue);
112
- return { kind: "failed", reason: reading.state === "unknown" ? reading.reason : "" };
113
- }
114
- const updatedAt = Date.parse(decoded.success.updatedAt);
115
- if (!Number.isFinite(updatedAt)) return { kind: "failed", reason: "`grok usage` output changed shape: updatedAt is not a time" };
116
- return { kind: "totals", usd: decoded.success.session.costUsdTicks / TICKS_PER_USD, updatedAt };
117
- }
@@ -1,74 +0,0 @@
1
- import { homedir } from "node:os";
2
- import type { AccountUsage, LocalUse } from "../wire";
3
- import type { AccountContext, AccountReading, AgentTool } from "./agent-tool";
4
- import { findCommand } from "./command";
5
- import { claude } from "./claude";
6
- import { codex } from "./codex";
7
- import { grok } from "./grok";
8
-
9
- /** Every coding agent skill-sync syncs skills for and reads usage of. */
10
- export const AGENT_TOOLS: ReadonlyArray<AgentTool> = [claude, codex, grok];
11
-
12
- /**
13
- * Every skills folder any agent tool reads on this machine. Every one is a candidate, whether or not it
14
- * exists yet, so an account added later joins without anyone listing it. Which of them actually sync is
15
- * the user's choice on the dashboard; a folder that is synced and missing is created.
16
- */
17
- export function detectFolders(home: string = homedir()): string[] {
18
- return [...new Set(AGENT_TOOLS.flatMap((tool) => tool.skillsFolders(home)))].sort();
19
- }
20
-
21
- /**
22
- * How long an account reading is kept before its CLI is asked again. Each ask starts the tool's CLI
23
- * (about two seconds of CPU for `claude`) and calls its service, so it happens at most this often per
24
- * account, while this machine's use, read from local files, is read on every call.
25
- */
26
- export const ACCOUNT_READ_MS = 5 * 60_000;
27
-
28
- const accountCache = new Map<string, { readonly readAt: number; readonly reading: AccountReading }>();
29
-
30
- /**
31
- * Every account of every agent tool on this machine: who it is and its plan limits (from the tool's CLI,
32
- * at most every `ACCOUNT_READ_MS`), and this machine's use of it. One account's failure never hides another's.
33
- */
34
- export async function readUsage(input: Partial<AccountContext> = {}): Promise<AccountUsage[]> {
35
- const home = input.home ?? homedir();
36
- const context: AccountContext = {
37
- home,
38
- now: input.now ?? Date.now(),
39
- findCommand: input.findCommand ?? ((command) => findCommand({ ...command, home })),
40
- };
41
- const now = context.now;
42
- const accounts = AGENT_TOOLS
43
- .flatMap((tool) => tool.accounts(home).map((account) => ({ tool, account })))
44
- .sort((a, b) => a.account.localeCompare(b.account));
45
- for (const account of accountCache.keys()) {
46
- if (!accounts.some((entry) => entry.account === account)) accountCache.delete(account);
47
- }
48
- return Promise.all(accounts.map(async ({ tool, account }): Promise<AccountUsage> => {
49
- const reading = await cachedAccount(tool, account, context);
50
- let local: LocalUse;
51
- try {
52
- local = tool.readLocalUse(account, home, now);
53
- } catch (cause) {
54
- local = { state: "unknown", reason: `could not read: ${describe(cause)}` };
55
- }
56
- return { tool: tool.tool, home: account.slice(home.length).replace(/^[\\/]/, ""), ...reading, local };
57
- }));
58
- }
59
-
60
- async function cachedAccount(tool: AgentTool, account: string, context: AccountContext): Promise<AccountReading> {
61
- const now = context.now;
62
- const cached = accountCache.get(account);
63
- if (cached !== undefined && now - cached.readAt < ACCOUNT_READ_MS) return cached.reading;
64
- let reading: AccountReading;
65
- try {
66
- reading = await tool.readAccount(account, context);
67
- } catch (cause) {
68
- reading = { identity: null, limits: { state: "unknown", reason: `could not read: ${describe(cause)}` } };
69
- }
70
- accountCache.set(account, { readAt: now, reading });
71
- return reading;
72
- }
73
-
74
- const describe = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause);