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