@jive-sh/skill-sync 0.5.1-latest-darwin-arm64 → 0.5.1

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