@jive-sh/skill-sync 0.6.2-latest-darwin-x64 → 0.6.2

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/README.md +146 -0
  2. package/bin/package.json +1 -0
  3. package/bin/skill-sync +614 -0
  4. package/bin/skill-sync-daemon +614 -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 +7 -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 +266 -0
  16. package/dist/internal/agents/codex.js.map +1 -0
  17. package/dist/internal/agents/command.js +219 -0
  18. package/dist/internal/agents/command.js.map +1 -0
  19. package/dist/internal/agents/grok.js +172 -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/cli.js +161 -0
  24. package/dist/internal/cli.js.map +1 -0
  25. package/dist/internal/config.js +131 -0
  26. package/dist/internal/config.js.map +1 -0
  27. package/dist/internal/control.js +113 -0
  28. package/dist/internal/control.js.map +1 -0
  29. package/dist/internal/daemon-control/impl.js +62 -0
  30. package/dist/internal/daemon-control/impl.js.map +1 -0
  31. package/dist/internal/daemon-control/interface.js +4 -0
  32. package/dist/internal/daemon-control/interface.js.map +1 -0
  33. package/dist/internal/folders.js +47 -0
  34. package/dist/internal/folders.js.map +1 -0
  35. package/dist/internal/local-skills.js +43 -0
  36. package/dist/internal/local-skills.js.map +1 -0
  37. package/dist/internal/path.js +36 -0
  38. package/dist/internal/path.js.map +1 -0
  39. package/dist/internal/server.js +32 -0
  40. package/dist/internal/server.js.map +1 -0
  41. package/dist/internal/skill-check.js +83 -0
  42. package/dist/internal/skill-check.js.map +1 -0
  43. package/dist/internal/sync.js +183 -0
  44. package/dist/internal/sync.js.map +1 -0
  45. package/dist/internal/wire.js +24 -0
  46. package/dist/internal/wire.js.map +1 -0
  47. package/install.cjs +614 -0
  48. package/package.json +36 -11
  49. package/src/daemons/skill-sync-daemon.ts +491 -0
  50. package/src/entrypoints/skill-sync.ts +12 -0
  51. package/src/index.ts +15 -0
  52. package/src/internal/agents/agent-tool.ts +136 -0
  53. package/src/internal/agents/claude.ts +440 -0
  54. package/src/internal/agents/codex.ts +283 -0
  55. package/src/internal/agents/command.ts +257 -0
  56. package/src/internal/agents/grok.ts +176 -0
  57. package/src/internal/agents/index.ts +74 -0
  58. package/src/internal/cli.ts +194 -0
  59. package/src/internal/config.ts +172 -0
  60. package/src/internal/control.ts +153 -0
  61. package/src/internal/daemon-control/impl.ts +74 -0
  62. package/src/internal/daemon-control/interface.ts +38 -0
  63. package/src/internal/folders.ts +50 -0
  64. package/src/internal/local-skills.ts +58 -0
  65. package/src/internal/path.ts +32 -0
  66. package/src/internal/server.ts +34 -0
  67. package/src/internal/skill-check.ts +97 -0
  68. package/src/internal/sync.ts +217 -0
  69. package/src/internal/wire.ts +315 -0
  70. package/multi-call-binary +0 -4
@@ -0,0 +1,283 @@
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";
@@ -0,0 +1,257 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { readFileSync, readdirSync, readlinkSync, statSync, writeFileSync } from "node:fs";
3
+ import { userInfo } from "node:os";
4
+ import { basename, delimiter, join } from "node:path";
5
+ import { Schema } from "effect";
6
+ import { parseJson } from "./agent-tool";
7
+
8
+ /**
9
+ * Finding and running an agent tool's own CLI.
10
+ *
11
+ * The daemon is started by the service manager (launchd, systemd, the Windows task scheduler), whose
12
+ * PATH is the system's (`/usr/bin:/bin:/usr/sbin:/sbin` under launchd), not the user's shell's. So a CLI
13
+ * is looked for on PATH, then in the folders its installers put it in, then on the PATH the user's own
14
+ * login shell sets up, which covers any installer this list does not name. A CLI an app starts from its
15
+ * own private folder is on none of those; it is found while it runs, and its path is remembered.
16
+ */
17
+
18
+ /** Where package managers and installers put a user's commands, after PATH. */
19
+ function installFolders(home: string): string[] {
20
+ return [
21
+ join(home, ".local", "bin"), // Claude Code's native installer
22
+ join(home, ".bun", "bin"),
23
+ join(home, ".npm-global", "bin"),
24
+ join(home, ".volta", "bin"),
25
+ join(home, "Library", "pnpm"),
26
+ join(home, ".local", "share", "pnpm"),
27
+ ...nvmFolders(home),
28
+ "/opt/homebrew/bin",
29
+ "/usr/local/bin",
30
+ "/home/linuxbrew/.linuxbrew/bin",
31
+ ];
32
+ }
33
+
34
+ /** Every Node version nvm installed, newest name last; a global npm install lands in one of them. */
35
+ function nvmFolders(home: string): string[] {
36
+ const versions = join(home, ".nvm", "versions", "node");
37
+ try {
38
+ return readdirSync(versions).sort().reverse().map((version) => join(versions, version, "bin"));
39
+ } catch {
40
+ return [];
41
+ }
42
+ }
43
+
44
+ export const isFile = (path: string): boolean => {
45
+ try {
46
+ return statSync(path).isFile();
47
+ } catch {
48
+ return false;
49
+ }
50
+ };
51
+
52
+ /**
53
+ * The first `name` on PATH, then in the install folders, then at the paths in `also` (an app bundle that
54
+ * ships the CLI, an installer's own folder), then on the login shell's PATH. Undefined when none exists.
55
+ */
56
+ export function findCommand(input: { readonly name: string; readonly home: string; readonly also?: ReadonlyArray<string> }): string | undefined {
57
+ const file = process.platform === "win32" ? `${input.name}.exe` : input.name;
58
+ const onPath = (process.env.PATH ?? "").split(delimiter).filter((folder) => folder !== "");
59
+ const candidates = [...[...onPath, ...installFolders(input.home)].map((folder) => join(folder, file)), ...(input.also ?? [])];
60
+ return candidates.find(isFile)
61
+ ?? loginShellFolders().map((folder) => join(folder, file)).find(isFile)
62
+ ?? runningOrRemembered(input.name, input.home);
63
+ }
64
+
65
+ /** Where each CLI was last seen running: `~/.jive/skill-sync-commands.json`, `{ "codex": "/path/to/codex" }`. */
66
+ const rememberedPath = (home: string) => join(home, ".jive", "skill-sync-commands.json");
67
+
68
+ function readRemembered(home: string): Record<string, string> {
69
+ try {
70
+ const parsed: unknown = JSON.parse(readFileSync(rememberedPath(home), "utf-8"));
71
+ return typeof parsed === "object" && parsed !== null ? Object.fromEntries(Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === "string")) : {};
72
+ } catch {
73
+ return {};
74
+ }
75
+ }
76
+
77
+ /**
78
+ * A running process's executable named `name`, which is then remembered for when none runs; otherwise the
79
+ * remembered one, if it still exists.
80
+ */
81
+ function runningOrRemembered(name: string, home: string): string | undefined {
82
+ const remembered = readRemembered(home);
83
+ const running = runningExecutables(name).find(isFile);
84
+ if (running !== undefined) {
85
+ if (remembered[name] !== running) {
86
+ try {
87
+ writeFileSync(rememberedPath(home), JSON.stringify({ ...remembered, [name]: running }, null, 2) + "\n");
88
+ } catch {
89
+ // Not remembered: found again the next time it runs.
90
+ }
91
+ }
92
+ return running;
93
+ }
94
+ const last = remembered[name];
95
+ return last !== undefined && isFile(last) ? last : undefined;
96
+ }
97
+
98
+ /** The executables of running processes named `name`: from `ps` on macOS, `/proc/<pid>/exe` on Linux. */
99
+ export function runningExecutables(name: string): string[] {
100
+ if (process.platform === "darwin") {
101
+ const run = spawnSync("/bin/ps", ["-axo", "comm="], { encoding: "utf-8", timeout: 5_000 });
102
+ return (run.stdout ?? "").split("\n").map((line) => line.trim()).filter((line) => line.startsWith("/") && basename(line) === name);
103
+ }
104
+ if (process.platform === "linux") {
105
+ let pids: string[];
106
+ try {
107
+ pids = readdirSync("/proc").filter((entry) => /^\d+$/.test(entry));
108
+ } catch {
109
+ return [];
110
+ }
111
+ return pids.flatMap((pid) => {
112
+ try {
113
+ const exe = readlinkSync(join("/proc", pid, "exe"));
114
+ return basename(exe) === name ? [exe] : [];
115
+ } catch {
116
+ return [];
117
+ }
118
+ });
119
+ }
120
+ return [];
121
+ }
122
+
123
+ /** The login shell's PATH is read once per daemon process: starting the shell takes up to a second. */
124
+ let loginShellPathCache: ReadonlyArray<string> | undefined;
125
+
126
+ /**
127
+ * The folders on the PATH the user's login shell sets up (its profile and rc files), as their terminal
128
+ * sees it. Empty on Windows, whose service PATH is already the user's, and when the shell fails.
129
+ */
130
+ export function loginShellFolders(): ReadonlyArray<string> {
131
+ if (loginShellPathCache !== undefined) return loginShellPathCache;
132
+ loginShellPathCache = process.platform === "win32" ? [] : readLoginShellPath();
133
+ return loginShellPathCache;
134
+ }
135
+
136
+ function readLoginShellPath(): string[] {
137
+ const shell = process.env.SHELL ?? userInfo().shell ?? "/bin/sh";
138
+ // `env` prints PATH joined by ":" in every shell (fish keeps it as a list internally).
139
+ const run = spawnSync(shell, ["-l", "-i", "-c", "env"], { encoding: "utf-8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"] });
140
+ const line = (run.stdout ?? "").split("\n").find((entry) => entry.startsWith("PATH="));
141
+ return line === undefined ? [] : line.slice("PATH=".length).split(":").filter((folder) => folder !== "");
142
+ }
143
+
144
+ export interface CommandResult {
145
+ /** Null when the command was killed or could not start. */
146
+ readonly status: number | null;
147
+ readonly stdout: string;
148
+ readonly stderr: string;
149
+ /** Why it did not finish: it could not start, or ran past its timeout. */
150
+ readonly failure: string | undefined;
151
+ }
152
+
153
+ /** Runs a command to completion without blocking the daemon, killing it after `timeoutMs`. */
154
+ export function runCommand(input: {
155
+ readonly command: string;
156
+ readonly args: ReadonlyArray<string>;
157
+ readonly env: NodeJS.ProcessEnv;
158
+ readonly cwd: string;
159
+ readonly timeoutMs: number;
160
+ }): Promise<CommandResult> {
161
+ return new Promise((resolve) => {
162
+ const child = spawn(input.command, [...input.args], { env: input.env, cwd: input.cwd, stdio: ["ignore", "pipe", "pipe"] });
163
+ let stdout = "";
164
+ let stderr = "";
165
+ let failure: string | undefined;
166
+ child.stdout.setEncoding("utf-8").on("data", (chunk: string) => { stdout += chunk; });
167
+ child.stderr.setEncoding("utf-8").on("data", (chunk: string) => { stderr += chunk; });
168
+ const timer = setTimeout(() => {
169
+ failure = `did not finish within ${input.timeoutMs / 1000} s`;
170
+ child.kill("SIGKILL");
171
+ }, input.timeoutMs);
172
+ // A command that cannot start emits `error`, and may or may not emit `close` after it.
173
+ const finish = (status: number | null) => {
174
+ clearTimeout(timer);
175
+ resolve({ status, stdout, stderr, failure });
176
+ };
177
+ child.on("error", (error) => {
178
+ failure = error.message;
179
+ finish(null);
180
+ });
181
+ child.on("close", finish);
182
+ });
183
+ }
184
+
185
+ /** One JSON-RPC response: `result` on success, `error` otherwise. */
186
+ export const RpcResponse = Schema.Struct({
187
+ id: Schema.Finite,
188
+ result: Schema.optionalKey(Schema.Unknown),
189
+ error: Schema.optionalKey(Schema.Struct({ message: Schema.String })),
190
+ });
191
+ export type RpcResponse = Schema.Schema.Type<typeof RpcResponse>;
192
+
193
+ /** A message to send: a request when it has an `id`, a notification otherwise. */
194
+ export interface RpcMessage {
195
+ readonly id?: number;
196
+ readonly method: string;
197
+ readonly params?: unknown;
198
+ }
199
+
200
+ /**
201
+ * Starts a CLI that speaks JSON-RPC over stdio (`codex app-server`, `grok agent stdio`), sends `messages`, and
202
+ * stops it once every request has an answer. The first request is the handshake: an error answering it ends the
203
+ * conversation, since the server answers nothing after a refused handshake. `name` says which CLI in a failure.
204
+ */
205
+ export function askJsonRpc(input: {
206
+ readonly name: string;
207
+ readonly command: string;
208
+ readonly args: ReadonlyArray<string>;
209
+ readonly env: NodeJS.ProcessEnv;
210
+ readonly cwd: string;
211
+ readonly timeoutMs: number;
212
+ readonly messages: ReadonlyArray<RpcMessage>;
213
+ }): Promise<
214
+ | { readonly kind: "answered"; readonly answers: ReadonlyMap<number, RpcResponse> }
215
+ | { readonly kind: "failed"; readonly reason: string }
216
+ > {
217
+ const { name } = input;
218
+ const requestIds = input.messages.flatMap((message) => message.id === undefined ? [] : [message.id]);
219
+ const handshakeId = requestIds[0];
220
+ return new Promise((resolve) => {
221
+ const child = spawn(input.command, [...input.args], { env: input.env, cwd: input.cwd, stdio: ["pipe", "pipe", "pipe"] });
222
+ const answers = new Map<number, RpcResponse>();
223
+ let stderr = "";
224
+ let pending = "";
225
+ let settled = false;
226
+ const settle = (outcome: Parameters<typeof resolve>[0]) => {
227
+ if (settled) return;
228
+ settled = true;
229
+ clearTimeout(timer);
230
+ child.kill();
231
+ resolve(outcome);
232
+ };
233
+ const timer = setTimeout(() => settle({ kind: "failed", reason: `\`${name}\` did not answer within ${input.timeoutMs / 1000} s` }), input.timeoutMs);
234
+ child.on("error", (error) => settle({ kind: "failed", reason: `\`${name}\` could not start: ${error.message}` }));
235
+ child.on("close", (status) => settle({ kind: "failed", reason: `\`${name}\` exited (${status}) before answering: ${stderr.trim().slice(0, 160)}` }));
236
+ child.stderr.setEncoding("utf-8").on("data", (chunk: string) => { stderr = (stderr + chunk).slice(-4096); });
237
+ child.stdout.setEncoding("utf-8").on("data", (chunk: string) => {
238
+ pending += chunk;
239
+ const lines = pending.split("\n");
240
+ pending = lines.pop() ?? "";
241
+ for (const line of lines) {
242
+ // Notifications arrive between responses; only responses have an id.
243
+ const response = Schema.decodeUnknownOption(RpcResponse)(parseJson(line));
244
+ if (response._tag === "Some") answers.set(response.value.id, response.value);
245
+ }
246
+ const handshake = handshakeId === undefined ? undefined : answers.get(handshakeId);
247
+ if (handshake?.error !== undefined) {
248
+ settle({ kind: "failed", reason: `\`${name}\` refused to initialize: ${handshake.error.message.slice(0, 160)}` });
249
+ return;
250
+ }
251
+ if (requestIds.every((id) => answers.has(id))) settle({ kind: "answered", answers });
252
+ });
253
+ // A dead stdin raises EPIPE here; the `close` above reports why the server went.
254
+ child.stdin.on("error", () => {});
255
+ child.stdin.write(input.messages.map((message) => `${JSON.stringify(message)}\n`).join(""));
256
+ });
257
+ }