@jive-sh/skill-sync 0.10.3 → 0.10.4-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 (152) hide show
  1. package/multi-call-binary +4 -0
  2. package/package.json +11 -45
  3. package/README.md +0 -214
  4. package/bin/package.json +0 -1
  5. package/bin/skill-sync +0 -34
  6. package/bin/skill-sync-daemon +0 -34
  7. package/dist/daemons/skill-sync-daemon.js +0 -642
  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 -102
  14. package/dist/internal/agents/agent-tool.js.map +0 -1
  15. package/dist/internal/agents/claude.js +0 -424
  16. package/dist/internal/agents/claude.js.map +0 -1
  17. package/dist/internal/agents/codex.js +0 -270
  18. package/dist/internal/agents/codex.js.map +0 -1
  19. package/dist/internal/agents/command.js +0 -219
  20. package/dist/internal/agents/command.js.map +0 -1
  21. package/dist/internal/agents/grok.js +0 -170
  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 -185
  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 -68
  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 -80
  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/skill-refinement/evals/cases.js +0 -143
  46. package/dist/internal/skill-refinement/evals/cases.js.map +0 -1
  47. package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
  48. package/dist/internal/skill-refinement/evals/opus-judge-original.json +0 -165
  49. package/dist/internal/skill-refinement/feedback/import-legacy.js +0 -13
  50. package/dist/internal/skill-refinement/feedback/import-legacy.js.map +0 -1
  51. package/dist/internal/skill-refinement/feedback/intake.js +0 -52
  52. package/dist/internal/skill-refinement/feedback/intake.js.map +0 -1
  53. package/dist/internal/skill-refinement/feedback/managed-intake.js +0 -19
  54. package/dist/internal/skill-refinement/feedback/managed-intake.js.map +0 -1
  55. package/dist/internal/skill-refinement/feedback/outbox.js +0 -44
  56. package/dist/internal/skill-refinement/feedback/outbox.js.map +0 -1
  57. package/dist/internal/skill-refinement/jev/impl.js +0 -63
  58. package/dist/internal/skill-refinement/jev/impl.js.map +0 -1
  59. package/dist/internal/skill-refinement/jev/interface.js +0 -6
  60. package/dist/internal/skill-refinement/jev/interface.js.map +0 -1
  61. package/dist/internal/skill-refinement/managed-daemon.js +0 -30
  62. package/dist/internal/skill-refinement/managed-daemon.js.map +0 -1
  63. package/dist/internal/skill-refinement/managed-worker-credentials.js +0 -60
  64. package/dist/internal/skill-refinement/managed-worker-credentials.js.map +0 -1
  65. package/dist/internal/skill-refinement/managed-worker-files.js +0 -25
  66. package/dist/internal/skill-refinement/managed-worker-files.js.map +0 -1
  67. package/dist/internal/skill-refinement/managed-worker-loop.js +0 -36
  68. package/dist/internal/skill-refinement/managed-worker-loop.js.map +0 -1
  69. package/dist/internal/skill-refinement/organization-site.js +0 -13
  70. package/dist/internal/skill-refinement/organization-site.js.map +0 -1
  71. package/dist/internal/skill-refinement/paths.js +0 -62
  72. package/dist/internal/skill-refinement/paths.js.map +0 -1
  73. package/dist/internal/skill-refinement/platform.js +0 -67
  74. package/dist/internal/skill-refinement/platform.js.map +0 -1
  75. package/dist/internal/skill-refinement/service.js +0 -356
  76. package/dist/internal/skill-refinement/service.js.map +0 -1
  77. package/dist/internal/skill-refinement/skills/skill-text.js +0 -217
  78. package/dist/internal/skill-refinement/skills/skill-text.js.map +0 -1
  79. package/dist/internal/skill-refinement/workflow/retry.js +0 -44
  80. package/dist/internal/skill-refinement/workflow/retry.js.map +0 -1
  81. package/dist/internal/skill-refinement/workflow/skill-refinement.js +0 -668
  82. package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +0 -1
  83. package/dist/internal/skill-refinement/writer/impl.js +0 -2
  84. package/dist/internal/skill-refinement/writer/impl.js.map +0 -1
  85. package/dist/internal/skill-refinement/writer/interface.js +0 -2
  86. package/dist/internal/skill-refinement/writer/interface.js.map +0 -1
  87. package/dist/internal/sync.js +0 -182
  88. package/dist/internal/sync.js.map +0 -1
  89. package/dist/internal/wire.js +0 -31
  90. package/dist/internal/wire.js.map +0 -1
  91. package/dist/internal/writer/claude.js +0 -84
  92. package/dist/internal/writer/claude.js.map +0 -1
  93. package/dist/internal/writer/codex.js +0 -102
  94. package/dist/internal/writer/codex.js.map +0 -1
  95. package/dist/internal/writer/interface.js +0 -6
  96. package/dist/internal/writer/interface.js.map +0 -1
  97. package/dist/internal/writer/live.js +0 -13
  98. package/dist/internal/writer/live.js.map +0 -1
  99. package/dist/internal/writer/reset.js +0 -38
  100. package/dist/internal/writer/reset.js.map +0 -1
  101. package/dist/internal/writer/selection.js +0 -79
  102. package/dist/internal/writer/selection.js.map +0 -1
  103. package/postinstall.cjs +0 -663
  104. package/src/daemons/skill-sync-daemon.ts +0 -647
  105. package/src/entrypoints/skill-sync.ts +0 -12
  106. package/src/index.ts +0 -15
  107. package/src/internal/agents/agent-tool.ts +0 -149
  108. package/src/internal/agents/claude.ts +0 -442
  109. package/src/internal/agents/codex.ts +0 -288
  110. package/src/internal/agents/command.ts +0 -257
  111. package/src/internal/agents/grok.ts +0 -174
  112. package/src/internal/agents/index.ts +0 -74
  113. package/src/internal/cli.ts +0 -217
  114. package/src/internal/config.ts +0 -172
  115. package/src/internal/control.ts +0 -157
  116. package/src/internal/daemon-control/impl.ts +0 -80
  117. package/src/internal/daemon-control/interface.ts +0 -40
  118. package/src/internal/folders.ts +0 -50
  119. package/src/internal/local-skills.ts +0 -58
  120. package/src/internal/path.ts +0 -32
  121. package/src/internal/server.ts +0 -76
  122. package/src/internal/skill-check.ts +0 -97
  123. package/src/internal/skill-refinement/evals/cases.ts +0 -167
  124. package/src/internal/skill-refinement/evals/opus-action-judge-original.json +0 -350
  125. package/src/internal/skill-refinement/evals/opus-judge-original.json +0 -165
  126. package/src/internal/skill-refinement/feedback/import-legacy.ts +0 -16
  127. package/src/internal/skill-refinement/feedback/intake.ts +0 -66
  128. package/src/internal/skill-refinement/feedback/managed-intake.ts +0 -19
  129. package/src/internal/skill-refinement/feedback/outbox.ts +0 -50
  130. package/src/internal/skill-refinement/jev/impl.ts +0 -76
  131. package/src/internal/skill-refinement/jev/interface.ts +0 -56
  132. package/src/internal/skill-refinement/managed-daemon.ts +0 -38
  133. package/src/internal/skill-refinement/managed-worker-credentials.ts +0 -59
  134. package/src/internal/skill-refinement/managed-worker-files.ts +0 -24
  135. package/src/internal/skill-refinement/managed-worker-loop.ts +0 -46
  136. package/src/internal/skill-refinement/organization-site.ts +0 -15
  137. package/src/internal/skill-refinement/paths.ts +0 -87
  138. package/src/internal/skill-refinement/platform.ts +0 -71
  139. package/src/internal/skill-refinement/service.ts +0 -413
  140. package/src/internal/skill-refinement/skills/skill-text.ts +0 -290
  141. package/src/internal/skill-refinement/workflow/retry.ts +0 -61
  142. package/src/internal/skill-refinement/workflow/skill-refinement.ts +0 -756
  143. package/src/internal/skill-refinement/writer/impl.ts +0 -1
  144. package/src/internal/skill-refinement/writer/interface.ts +0 -1
  145. package/src/internal/sync.ts +0 -216
  146. package/src/internal/wire.ts +0 -439
  147. package/src/internal/writer/claude.ts +0 -98
  148. package/src/internal/writer/codex.ts +0 -93
  149. package/src/internal/writer/interface.ts +0 -48
  150. package/src/internal/writer/live.ts +0 -19
  151. package/src/internal/writer/reset.ts +0 -34
  152. package/src/internal/writer/selection.ts +0 -84
package/postinstall.cjs DELETED
@@ -1,663 +0,0 @@
1
- "use strict";
2
- // Its literals deliberately repeat the library's constants (src/internal/common/constants.ts and
3
- // src/internal/public/cli/parse.ts), so this shipped file stays plain, readable JS with nothing generated into it. The
4
- // test "the library's daemon listing finds the daemon postinstall.cjs registered, with its log where the library
5
- // expects" (postinstall.test.ts) catches any disagreement.
6
- /**
7
- * The install step of every package built with jive-abstract-library that has commands or daemons. The builder copies
8
- * this file unchanged to the root of each such package; the package's postinstall script runs it, and each command's
9
- * launcher in bin/ requires it to do the same on its first run, because Bun skips postinstall for a package it does not
10
- * trust.
11
- *
12
- * Nothing in it is filled in per package. It reads its own package's package.json at run time: "name", the commands in
13
- * "bin", the platform packages in "optionalDependencies", and "jive", which the builder adds for what package.json has
14
- * no field for (the daemons, and the commands that set up Tab completion).
15
- *
16
- * CommonJS, not an ES module: Node 14 and 16 refuse to load an extensionless ES module in a "type": "module" package
17
- * (ERR_UNKNOWN_FILE_EXTENSION; Node 18.20 accepts it), and the launchers are extensionless. bin/package.json marks that
18
- * directory "commonjs" and this file ends in .cjs, so both load the same way on every Node and on Bun.
19
- */
20
- const { spawnSync } = require("child_process");
21
- const {
22
- chmodSync,
23
- copyFileSync,
24
- existsSync,
25
- linkSync,
26
- mkdirSync,
27
- readdirSync,
28
- readFileSync,
29
- realpathSync,
30
- renameSync,
31
- rmSync,
32
- writeFileSync,
33
- } = require("fs");
34
- const { createHash } = require("crypto");
35
- const { homedir, userInfo } = require("os");
36
- const { basename, delimiter, dirname, join } = require("path");
37
-
38
- /** Where a built package keeps its commands: the launchers, and on macOS and Linux the hard links that replace them. */
39
- const BIN_DIR = "bin";
40
- /** The real program in each platform package, holding every command and daemon; it runs the one its own name says. */
41
- const MULTI_CALL_BINARY = "multi-call-binary";
42
- const WINDOWS_EXECUTABLE_SUFFIX = ".exe";
43
- /** On Windows, beside the commands: the platform package version they were copied from. */
44
- const INSTALLED_JSON = "installed.json";
45
-
46
- /**
47
- * Prefix every daemon registration carries, on every platform: the record file name, the launchd label, the systemd unit
48
- * and the scheduled task are all this same one string.
49
- *
50
- * It exists so Jive's own registrations are identifiable without the registry, which is the recovery path for exactly
51
- * the orphaned-unit problem the registry is there to prevent, and so a command that lists daemons and their statuses
52
- * has one thing to look for rather than three per-platform conventions.
53
- */
54
- const DAEMON_ID_PREFIX = "jive-daemon";
55
- /** Directory under the user's home where every Jive daemon's registration record and log live. */
56
- const DAEMON_HOME_DIR = ".jive";
57
- const DAEMON_REGISTRY_SUBDIR = "daemons";
58
- const DAEMON_LOG_SUBDIR = "logs";
59
-
60
- /**
61
- * Tells this script to link the commands and stop, leaving daemons unregistered.
62
- *
63
- * An argument rather than an environment variable: this is one caller telling one callee about one invocation, and an
64
- * ambient variable would be inherited by everything either of them spawns.
65
- */
66
- const REPAIR_ONLY_FLAG = "--repair-only";
67
-
68
- /*
69
- * Hidden flags of a command built with the library's Cli, never offered by Tab or listed by --help: what shells,
70
- * launchers and builds call a command with. Together they are the completion protocol (COMPLETION_PROTOCOL in
71
- * public/cli/parse.ts). A launcher leaves Tab completion alone when the first argument is one of them.
72
- */
73
- /** What a shell's Tab completion calls the command with, followed by the words typed so far. */
74
- const COMPGEN_FLAG = "--compgen";
75
- /** Followed by a shell's name: prints the script that registers Tab completion, which the startup line evaluates. */
76
- const COMPLETION_SCRIPT_FLAG = "--completion";
77
- /** Prints the completion protocol's version: how a build, or another copy of the command, learns this one speaks it. */
78
- const COMPLETION_PROTOCOL_FLAG = "--completion-protocol";
79
- const SET_UP_COMPLETION_FLAG = "--setup-completion";
80
- const REMOVE_COMPLETION_FLAG = "--remove-completion";
81
- /** What this script runs each completion command with after an install or upgrade: set up Tab completion if the user's shell lacks it. */
82
- const SET_UP_MISSING_COMPLETION_FLAG = "--setup-completion-if-missing";
83
- const COMPLETION_FLAGS = [
84
- COMPGEN_FLAG,
85
- COMPLETION_SCRIPT_FLAG,
86
- COMPLETION_PROTOCOL_FLAG,
87
- SET_UP_COMPLETION_FLAG,
88
- REMOVE_COMPLETION_FLAG,
89
- SET_UP_MISSING_COMPLETION_FLAG,
90
- ];
91
-
92
- function fail(message) {
93
- console.error(message);
94
- process.exit(1);
95
- }
96
-
97
- /**
98
- * The package at `packageDir`, from its package.json: its name, its commands in "bin" order, its platform packages, and
99
- * the daemons and completion commands the builder put in its "jive" field.
100
- */
101
- function readPackage(packageDir) {
102
- const manifestPath = join(packageDir, "package.json");
103
- let manifest;
104
- try {
105
- manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
106
- } catch (error) {
107
- fail(`Cannot read ${manifestPath}: ${error.message}`);
108
- }
109
- const jive = manifest.jive || {};
110
- return {
111
- packageDir,
112
- name: manifest.name,
113
- commands: Object.keys(manifest.bin || {}),
114
- platformPackages: Object.keys(manifest.optionalDependencies || {}),
115
- daemons: jive.daemons || [],
116
- completionCommands: jive.completionCommands || [],
117
- };
118
- }
119
-
120
- function installedPlatformPackage(pkg, platformPackage) {
121
- try {
122
- const manifestPath = require.resolve(`${platformPackage}/package.json`, { paths: [pkg.packageDir] });
123
- const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
124
- if (!Array.isArray(manifest.os) || !Array.isArray(manifest.cpu)) return undefined;
125
- const binaryFile = manifest.os.includes("win32") ? `${MULTI_CALL_BINARY}${WINDOWS_EXECUTABLE_SUFFIX}` : MULTI_CALL_BINARY;
126
- return {
127
- name: platformPackage,
128
- os: manifest.os,
129
- cpu: manifest.cpu,
130
- binaryPath: join(dirname(manifestPath), binaryFile),
131
- version: manifest.version,
132
- };
133
- } catch {
134
- return undefined;
135
- }
136
- }
137
-
138
- /**
139
- * The base package has one optional dependency per platform, each holding that platform's build of every command. The
140
- * package manager installs the one whose "os" and "cpu" match the machine, so this uses whichever is installed rather
141
- * than deciding the platform again. Asking again can disagree with the package manager: on an Apple Silicon Mac, bun
142
- * (native) installs darwin-arm64, while an Intel build of Node running under Rosetta reports process.arch "x64".
143
- * @returns the path to the platform binary and the exact version of the platform package.
144
- */
145
- function currentPlatformPackage(pkg) {
146
- const installed = pkg.platformPackages.map((name) => installedPlatformPackage(pkg, name)).filter(Boolean);
147
- if (installed.length === 1) return installed[0];
148
-
149
- // More than one is installed only when the package manager was told to (npm's --cpu and --os flags).
150
- const matching = installed.find((platformPackage) =>
151
- platformPackage.os.includes(process.platform) && platformPackage.cpu.includes(process.arch));
152
- if (matching) return matching;
153
-
154
- fail(installed.length === 0
155
- ? `None of ${pkg.name}'s platform packages is installed (${pkg.platformPackages.join(", ")}). Reinstall ${pkg.name}.`
156
- : `Several of ${pkg.name}'s platform packages are installed (${installed.map((p) => p.name).join(", ")}) and none matches ${process.platform}-${process.arch}. Reinstall ${pkg.name}.`);
157
- }
158
-
159
- /** The real program a command runs: on macOS and Linux its own file in bin/, once linked; on Windows the .exe beside it. */
160
- function commandTarget(input) {
161
- const suffix = process.platform === "win32" ? WINDOWS_EXECUTABLE_SUFFIX : "";
162
- return join(input.packageDir, BIN_DIR, `${input.command}${suffix}`);
163
- }
164
-
165
- function installedJsonPath(packageDir) {
166
- return join(packageDir, BIN_DIR, INSTALLED_JSON);
167
- }
168
-
169
- /**
170
- * Whether the Windows commands are copies of the installed platform package's version. A launcher on Windows runs every
171
- * time, since Windows runs a command through its .cmd shim rather than the file in bin/, so it sets up again only when
172
- * this says the commands are stale: after an install or upgrade the package manager skipped this script for.
173
- */
174
- function commandsAreCurrent(input) {
175
- if (process.platform !== "win32") return false;
176
- const pkg = readPackage(input.packageDir);
177
- const platformPackage = currentPlatformPackage(pkg);
178
- if (!pkg.commands.every((command) => existsSync(commandTarget({ packageDir: pkg.packageDir, command })))) return false;
179
-
180
- try {
181
- const installed = JSON.parse(readFileSync(installedJsonPath(pkg.packageDir), "utf-8"));
182
- return installed.version === platformPackage.version;
183
- } catch {
184
- return false;
185
- }
186
- }
187
-
188
- function temporaryPath(targetPath) {
189
- return `${targetPath}.${process.pid}.${Date.now()}.tmp${process.platform === "win32" ? WINDOWS_EXECUTABLE_SUFFIX : ""}`;
190
- }
191
-
192
- function linkOrCopyFirstExecutable(sourcePath, targetPath) {
193
- mkdirSync(dirname(targetPath), { recursive: true });
194
- const tempPath = temporaryPath(targetPath);
195
- rmSync(tempPath, { force: true });
196
-
197
- try {
198
- try {
199
- linkSync(sourcePath, tempPath);
200
- } catch {
201
- copyFileSync(sourcePath, tempPath);
202
- }
203
-
204
- chmodSync(tempPath, 0o755);
205
- rmSync(targetPath, { force: true });
206
- renameSync(tempPath, targetPath);
207
- } finally {
208
- rmSync(tempPath, { force: true });
209
- }
210
- }
211
-
212
- function hardLinkCommandTarget(sourcePath, targetPath) {
213
- if (sourcePath === targetPath) return;
214
-
215
- const tempPath = temporaryPath(targetPath);
216
- rmSync(tempPath, { force: true });
217
-
218
- try {
219
- linkSync(sourcePath, tempPath);
220
- chmodSync(tempPath, 0o755);
221
- rmSync(targetPath, { force: true });
222
- renameSync(tempPath, targetPath);
223
- } finally {
224
- rmSync(tempPath, { force: true });
225
- }
226
- }
227
-
228
- /**
229
- * Points every command at the installed platform package's program: on macOS and Linux each launcher in bin/ is
230
- * replaced by a hard link to it, so later runs start the program directly; on Windows a .exe beside each launcher, with
231
- * installed.json recording the version, unless the commands are already that version's.
232
- */
233
- function linkCommands(pkg) {
234
- const platformPackage = currentPlatformPackage(pkg);
235
- if (commandsAreCurrent({ packageDir: pkg.packageDir })) return;
236
-
237
- const firstTargetPath = commandTarget({ packageDir: pkg.packageDir, command: pkg.commands[0] });
238
- linkOrCopyFirstExecutable(platformPackage.binaryPath, firstTargetPath);
239
-
240
- for (const command of pkg.commands.slice(1)) {
241
- hardLinkCommandTarget(firstTargetPath, commandTarget({ packageDir: pkg.packageDir, command }));
242
- }
243
-
244
- if (process.platform === "win32") {
245
- writeFileSync(installedJsonPath(pkg.packageDir), `${JSON.stringify({ version: platformPackage.version }, null, 2)}\n`);
246
- }
247
- }
248
-
249
- /* ------------------------------------------------------------------ Tab completion ---------- */
250
-
251
- /**
252
- * Asks each command built with Cli to set up Tab completion if the user's shell lacks it. The command decides everything
253
- * (which shell, which file, whether this copy is the one the user's PATH runs, whether it was turned off) and says on
254
- * stderr what it set up; its stdout is dropped, since the caller of the command the user typed may be reading this
255
- * process's stdout.
256
- */
257
- function setUpMissingCompletion(pkg) {
258
- for (const command of pkg.completionCommands) {
259
- const result = spawnSync(commandTarget({ packageDir: pkg.packageDir, command }), [SET_UP_MISSING_COMPLETION_FLAG], { stdio: ["ignore", "ignore", "inherit"] });
260
- if (result.error) console.error(`Could not check Tab completion for ${command}: ${result.error.message}`);
261
- }
262
- }
263
-
264
- /* ------------------------------------------------------------------ daemon registration ---------- */
265
-
266
- /**
267
- * Registering a package's daemons with the operating system so they start at login.
268
- *
269
- * As the user, not system-wide: a daemon here acts for one user, with access to that user's keychain, SSH agent and home
270
- * directory, and a system-wide service would have none of those. On macOS and Windows it starts at login; on Linux at
271
- * boot, because the user is made to linger (registerSystemd). On Windows that is a scheduled task rather than a service
272
- * for the same reason: a service runs in session 0, isolated from the desktop the user is actually logged into.
273
- *
274
- * This runs here, in plain JavaScript, because it has to run on a machine that has only just received the package. The
275
- * daemon binary cannot register itself: nothing has started it yet.
276
- */
277
-
278
- function jiveHome() {
279
- return join(homedir(), DAEMON_HOME_DIR);
280
- }
281
-
282
- function registryDir() {
283
- return join(jiveHome(), DAEMON_REGISTRY_SUBDIR);
284
- }
285
-
286
- function logDir() {
287
- return join(jiveHome(), DAEMON_LOG_SUBDIR);
288
- }
289
-
290
- function recordPath(id) {
291
- return join(registryDir(), `${id}.json`);
292
- }
293
-
294
- /**
295
- * The tree this copy of the package was installed into, which is where its daemons should work.
296
- *
297
- * Derived from the path rather than from INIT_CWD, which npm sets and Bun does not, and which answers the wrong question
298
- * anyway: where the install was *typed*, not what it installed into. Walking out of the enclosing node_modules answers
299
- * it for a project install and a global one alike, and a package with no node_modules above it (one built and installed
300
- * in place) is its own root.
301
- */
302
- function installRoot(pkg) {
303
- let dir = pkg.packageDir;
304
- while (true) {
305
- if (basename(dir) === "node_modules") return dirname(dir);
306
- const parent = dirname(dir);
307
- if (parent === dir) return pkg.packageDir;
308
- dir = parent;
309
- }
310
- }
311
-
312
- /** One id segment: dots separate segments, so a dot inside a name cannot be left as one. */
313
- function idSegment(value) {
314
- return value.replace(/[^A-Za-z0-9-]+/g, "-");
315
- }
316
-
317
- /**
318
- * Scope and name get a segment each, and an unscoped package gets "_" where its scope would be.
319
- *
320
- * Joining them with a dash instead would not be reversible: `@ozyman42/ozy-cli` and a package actually named
321
- * `ozyman42-ozy-cli` would produce the same text. "_" is safe as the marker because npm forbids a scope or name from
322
- * starting with it, so no real scope can collide with it.
323
- */
324
- function packageSegments(packageName) {
325
- if (!packageName.startsWith("@")) return ["_", idSegment(packageName)];
326
- const separator = packageName.indexOf("/");
327
- return [
328
- idSegment(packageName.slice(1, separator)),
329
- idSegment(packageName.slice(separator + 1)),
330
- ];
331
- }
332
-
333
- /**
334
- * The id a registration is replaced at: the package's name, the daemon's name, and a digest of the directory this copy
335
- * of the package was installed into.
336
- *
337
- * **Where the package is installed is what decides how many of its daemons exist.** Reinstalling or upgrading the same
338
- * copy keeps the id, so the registration is replaced; a second copy installed somewhere else gets its own id, so each
339
- * project that installs its own copy gets its own daemon and a globally installed copy gets exactly one.
340
- *
341
- * An earlier version had each daemon declare `local` or `global` in the manifest instead. That was a second source of
342
- * truth that contradicted the real one: a `global` daemon installed into two projects registered once, pointing at
343
- * whichever installed last, so uninstalling the second took the first project's daemon away, the very failure `local`
344
- * existed to prevent.
345
- */
346
- function daemonId(pkg, name) {
347
- const [scope, packageName] = packageSegments(pkg.name);
348
- const installDigest = createHash("sha256").update(pkg.packageDir).digest("hex").slice(0, 10);
349
- return `${DAEMON_ID_PREFIX}.${scope}.${packageName}.${idSegment(name)}.${installDigest}`;
350
- }
351
-
352
- function run(argv, allowFailure) {
353
- const result = spawnSync(argv[0], argv.slice(1), { stdio: ["ignore", "ignore", "pipe"] });
354
- if (result.error || result.status !== 0) {
355
- if (!allowFailure) {
356
- const detail = result.error ? result.error.message : String(result.stderr || "").trim();
357
- console.error(` ${argv.join(" ")} failed: ${detail}`);
358
- }
359
- return false;
360
- }
361
- return true;
362
- }
363
-
364
- function xmlEscape(value) {
365
- return String(value)
366
- .split("&").join("&")
367
- .split("<").join("&lt;")
368
- .split(">").join("&gt;");
369
- }
370
-
371
- /**
372
- * launchd. KeepAlive on SuccessfulExit=false restarts a daemon that crashes but respects one that exits zero, which is
373
- * how a daemon that has removed its own registration stays stopped.
374
- */
375
- function registerLaunchd(input) {
376
- const { id, executable, workingDirectory, logPath } = input;
377
- // The id verbatim, rather than a reverse-DNS label: one string names this daemon on every platform.
378
- const label = id;
379
- const agentsDir = join(homedir(), "Library", "LaunchAgents");
380
- const plistPath = join(agentsDir, `${label}.plist`);
381
- const domain = `gui/${process.getuid()}`;
382
- const unregister = ["launchctl", "bootout", `${domain}/${label}`];
383
-
384
- mkdirSync(agentsDir, { recursive: true });
385
- writeFileSync(plistPath, [
386
- '<?xml version="1.0" encoding="UTF-8"?>',
387
- '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
388
- '<plist version="1.0">',
389
- "<dict>",
390
- ` <key>Label</key><string>${xmlEscape(label)}</string>`,
391
- ` <key>ProgramArguments</key><array><string>${xmlEscape(executable)}</string></array>`,
392
- ` <key>WorkingDirectory</key><string>${xmlEscape(workingDirectory)}</string>`,
393
- " <key>RunAtLoad</key><true/>",
394
- " <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>",
395
- ` <key>StandardOutPath</key><string>${xmlEscape(logPath)}</string>`,
396
- ` <key>StandardErrorPath</key><string>${xmlEscape(logPath)}</string>`,
397
- " <key>ProcessType</key><string>Background</string>",
398
- "</dict>",
399
- "</plist>",
400
- "",
401
- ].join("\n"));
402
-
403
- const start = () => {
404
- // Booting out first: bootstrap refuses a label that is already loaded, and a reinstall is the common case. bootout
405
- // returns before launchd has finished stopping a daemon that is running, and bootstrap is refused until it has
406
- // ("Bootstrap failed: 5"), so a reinstall over a live daemon left it stopped until the next login. Retry for a few
407
- // seconds; only the last failure is reported.
408
- run(unregister, true);
409
- const attempts = 20;
410
- let started = false;
411
- for (let attempt = 1; attempt <= attempts && !started; attempt++) {
412
- if (attempt > 1) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250);
413
- started = run(["launchctl", "bootstrap", domain, plistPath], attempt < attempts);
414
- }
415
- return started;
416
- };
417
- return { kind: "launchd", unit: label, files: [plistPath], unregister, start };
418
- }
419
-
420
- /**
421
- * systemd user units. `--user` rather than system units, for the same reason launchd gets a LaunchAgent.
422
- *
423
- * A user's systemd manager, and every unit in it, stops when their last session ends and starts again at their next
424
- * login, unless the user lingers. On a server nobody stays logged in to, the daemons would be down most of the time, so
425
- * the user is made to linger, which starts their manager at boot. systemd lets every user set their own (polkit's
426
- * org.freedesktop.login1.set-self-linger), with no password. Removing a registration leaves lingering on: something
427
- * else of the user's may rely on it, and it costs only their manager running.
428
- */
429
- function registerSystemd(input) {
430
- const { id, name, packageName, executable, workingDirectory, logPath } = input;
431
- const unit = `${id}.service`;
432
- const unitDir = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "systemd", "user");
433
- const unitPath = join(unitDir, unit);
434
- const unregister = ["systemctl", "--user", "disable", "--now", unit];
435
-
436
- mkdirSync(unitDir, { recursive: true });
437
- writeFileSync(unitPath, [
438
- "[Unit]",
439
- `Description=Jive daemon ${name} for ${packageName}`,
440
- "",
441
- "[Service]",
442
- "Type=simple",
443
- `ExecStart=${executable}`,
444
- `WorkingDirectory=${workingDirectory}`,
445
- "Restart=on-failure",
446
- "RestartSec=5",
447
- `StandardOutput=append:${logPath}`,
448
- `StandardError=append:${logPath}`,
449
- "",
450
- "[Install]",
451
- "WantedBy=default.target",
452
- "",
453
- ].join("\n"));
454
-
455
- const start = () => {
456
- if (!run(["loginctl", "enable-linger", "--no-ask-password"], false)) {
457
- console.error(` ${unit} stops whenever you have no session open; \`sudo loginctl enable-linger ${userInfo().username}\` keeps it running`);
458
- }
459
- run(["systemctl", "--user", "daemon-reload"], true);
460
- // Restart rather than `enable --now`, which leaves a running daemon on the executable it started from: after an
461
- // upgrade that is the old version, held open after its file was replaced.
462
- return run(["systemctl", "--user", "enable", unit], false)
463
- && run(["systemctl", "--user", "restart", unit], false);
464
- };
465
- return { kind: "systemd", unit, files: [unitPath], unregister, start };
466
- }
467
-
468
- /**
469
- * Windows Task Scheduler, through a .cmd shim.
470
- *
471
- * The shim exists because schtasks can set neither a working directory nor environment variables, and it also supplies
472
- * the restart-on-crash behaviour the other two platforms get from their service manager: an ONLOGON task starts its
473
- * program once and does not watch it. The loop mirrors launchd's KeepAlive, so a daemon that exits zero after removing
474
- * itself is not restarted.
475
- */
476
- function registerScheduledTask(input) {
477
- const { id, executable, workingDirectory, logPath } = input;
478
- const taskName = id;
479
- const shimPath = join(registryDir(), `${id}.cmd`);
480
- const unregister = ["schtasks", "/Delete", "/F", "/TN", taskName];
481
-
482
- writeFileSync(shimPath, [
483
- "@echo off",
484
- `cd /d "${workingDirectory}"`,
485
- ":jive_loop",
486
- `"${executable}" >> "${logPath}" 2>&1`,
487
- "if %ERRORLEVEL% EQU 0 goto :eof",
488
- "timeout /t 5 /nobreak > nul",
489
- "goto jive_loop",
490
- "",
491
- ].join("\r\n"));
492
-
493
- // An ONLOGON task waits for the next login, so it is also run now, as launchd and systemd start theirs.
494
- const start = () => run([
495
- "schtasks", "/Create", "/F",
496
- "/SC", "ONLOGON",
497
- "/TN", taskName,
498
- "/TR", `"${shimPath}"`,
499
- "/RL", "LIMITED",
500
- ], false) && run(["schtasks", "/Run", "/TN", taskName], false);
501
- return { kind: "scheduled-task", unit: taskName, files: [shimPath], unregister, start };
502
- }
503
-
504
- const DAEMON_REGISTRARS = {
505
- darwin: registerLaunchd,
506
- linux: registerSystemd,
507
- win32: registerScheduledTask,
508
- };
509
-
510
- function readRecord(path) {
511
- try {
512
- return JSON.parse(readFileSync(path, "utf-8"));
513
- } catch {
514
- return undefined;
515
- }
516
- }
517
-
518
- function removeRegistration(record, reason) {
519
- console.log(`Removing daemon ${record.id} (${reason})`);
520
- if (Array.isArray(record.unregister) && record.unregister.length > 0) {
521
- run(record.unregister, true);
522
- }
523
- for (const file of record.files || []) {
524
- rmSync(file, { force: true });
525
- }
526
- }
527
-
528
- /**
529
- * Drops this package's registrations that should no longer exist.
530
- *
531
- * Three cases, all of which would otherwise leave the operating system starting a missing or unwanted executable at
532
- * every login: a daemon this version of the package no longer has, a copy of the package whose directory is gone, and a
533
- * registration of this very copy under an id we no longer use, which is what makes a change to the id scheme replace
534
- * its registrations instead of doubling them.
535
- *
536
- * Only this package's own registrations are considered, by name, so another package's daemon is never touched; and only
537
- * this copy's, except where the copy itself has been deleted.
538
- */
539
- function pruneRemovedDaemons(pkg, currentIds) {
540
- let entries;
541
- try {
542
- entries = readdirSync(registryDir());
543
- } catch {
544
- return;
545
- }
546
-
547
- for (const entry of entries) {
548
- if (!entry.endsWith(".json")) continue;
549
- const path = join(registryDir(), entry);
550
- const record = readRecord(path);
551
- if (!record || record.packageName !== pkg.name) continue;
552
-
553
- const reason =
554
- !pkg.daemons.includes(record.name) ? `no longer part of ${pkg.name}`
555
- : !existsSync(record.packageDir) ? `${record.packageDir} is gone`
556
- : record.packageDir === pkg.packageDir && !currentIds.includes(record.id) ? "superseded by a new id"
557
- : undefined;
558
- if (reason === undefined) continue;
559
-
560
- removeRegistration(record, reason);
561
- rmSync(path, { force: true });
562
- }
563
- }
564
-
565
- function registerDaemons(pkg, repairOnly) {
566
- // Two reasons not to register. The caller asked for repair alone: the local deploy does, because its install exists so
567
- // the launcher can resolve a platform package, not because anyone chose to install that copy. Or this is a build
568
- // agent, which installs a package to run one command and is then discarded: registering something to start at a login
569
- // that will never happen is pure noise, and in a container it fails outright.
570
- const skip = repairOnly ? `${REPAIR_ONLY_FLAG} was passed`
571
- : process.env.CI ? "CI is set"
572
- : undefined;
573
- const names = skip === undefined ? pkg.daemons : [];
574
-
575
- // Pruning first, and with no current ids when skipping: declining to run daemons here has to also take away any this
576
- // copy registered earlier, or one such install would leave them starting at every login forever. Before the early
577
- // return below, too: a version that drops its last daemon still has to take the previous version's registration away,
578
- // and the record carries everything undoing it needs.
579
- pruneRemovedDaemons(pkg, names.map((name) => daemonId(pkg, name)));
580
- if (skip !== undefined) {
581
- if (pkg.daemons.length > 0) console.log(`${skip}: not registering ${pkg.daemons.join(", ")}`);
582
- return;
583
- }
584
- if (names.length === 0) return;
585
-
586
- const registrar = DAEMON_REGISTRARS[process.platform];
587
- if (!registrar) {
588
- console.log(`No daemon support for ${process.platform}: ${names.join(", ")} will not start automatically`);
589
- return;
590
- }
591
-
592
- mkdirSync(registryDir(), { recursive: true });
593
- mkdirSync(logDir(), { recursive: true });
594
-
595
- for (const name of names) {
596
- const id = daemonId(pkg, name);
597
- const path = recordPath(id);
598
- const previous = readRecord(path);
599
- const workingDirectory = installRoot(pkg);
600
- const executable = commandTarget({ packageDir: pkg.packageDir, command: name });
601
- const logPath = join(logDir(), `${id}.log`);
602
-
603
- console.log(
604
- `${previous ? "Replacing existing" : "Creating"} daemon ${id}`
605
- + ` (${name} from ${pkg.name}) in ${workingDirectory}`,
606
- );
607
-
608
- // The registrar writes its unit file and says how it will be loaded; the record goes down, whole, before the unit is
609
- // loaded, because loading it starts the daemon, and the first thing the daemon does is read this file to find out
610
- // how it was registered. Whole, so an install stopped at any point leaves either the previous record or this one,
611
- // never one missing the kind and unit a listing command asks the platform about.
612
- const registration = registrar({ id, name, packageName: pkg.name, executable, workingDirectory, logPath });
613
- writeFileSync(path, `${JSON.stringify({
614
- id,
615
- name,
616
- packageName: pkg.name,
617
- packageDir: pkg.packageDir,
618
- workingDirectory,
619
- executable,
620
- registeredAt: new Date().toISOString(),
621
- searchPath: [...new Set((process.env.PATH || "").split(delimiter).filter(Boolean))].join(delimiter),
622
- kind: registration.kind,
623
- unit: registration.unit,
624
- logPath,
625
- files: [...registration.files, path],
626
- unregister: registration.unregister,
627
- }, null, 2)}\n`);
628
-
629
- if (!registration.start()) {
630
- console.error(` ${id} is registered but could not be started; it will start at your next login`);
631
- }
632
- }
633
- }
634
-
635
- /**
636
- * Sets up the package at `packageDir`: links its commands to the installed platform package's program, registers its
637
- * daemons (or, with `repairOnly`, removes this copy's registrations), and with `setUpCompletion` asks its completion
638
- * commands to set up Tab completion.
639
- *
640
- * Every step replaces what an earlier run did rather than assuming it is the first: package.json's postinstall names
641
- * this file, and a package manager may run it again at any later install (bun reruns a trusted folder dependency's on
642
- * later global installs).
643
- */
644
- function setUp(input) {
645
- const pkg = readPackage(input.packageDir);
646
- linkCommands(pkg);
647
- registerDaemons(pkg, input.repairOnly);
648
- if (input.setUpCompletion) setUpMissingCompletion(pkg);
649
- }
650
-
651
- // What a command's launcher in bin/ uses.
652
- module.exports = {
653
- COMPLETION_FLAGS,
654
- commandTarget,
655
- commandsAreCurrent,
656
- setUp,
657
- };
658
-
659
- // Run as package.json's postinstall (`node ./postinstall.cjs`); a launcher only uses the exports above.
660
- if (require.main === module) {
661
- const repairOnly = process.argv.includes(REPAIR_ONLY_FLAG);
662
- setUp({ packageDir: realpathSync(__dirname), repairOnly, setUpCompletion: !repairOnly });
663
- }