@cotal-ai/cli 0.132.4 → 0.132.6

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.
@@ -47,8 +47,17 @@ export declare function isPathSpec(spec: string, absolute?: (p: string) => boole
47
47
  export declare function ext(args: ParsedArgs): Promise<void>;
48
48
  /** `cotal ext add <spec>`: install one extension into the operator prefix and record what it provides.
49
49
  * `announce` takes the closing `✓ added` line; `cotal setup` sends it to stderr when stdout carries
50
- * a result. */
50
+ * a result. A signal during the add rolls it back and throws {@link ExtensionAddInterrupted}. */
51
51
  export declare function addExtension(spec: string, expectedPkg?: string, borrowMutation?: boolean, announce?: (line: string) => void): Promise<void>;
52
+ /** An `ext add` stopped by SIGINT or SIGTERM. `addExtension` throws it once the prefix and manifest
53
+ * are back as they were and its lock is released. */
54
+ export declare class ExtensionAddInterrupted extends Error {
55
+ readonly pkg: string;
56
+ readonly name = "ExtensionAddInterrupted";
57
+ constructor(pkg: string);
58
+ }
59
+ /** Ends a command whose add was interrupted with exit 130, and rethrows any other error. */
60
+ export declare function exitOnInterruptedAdd(e: unknown): void;
52
61
  /** One installed extension as the listing reports it. */
53
62
  export interface ExtensionRow {
54
63
  readonly pkg: string;
@@ -1 +1 @@
1
- {"version":3,"file":"ext.d.ts","sourceRoot":"","sources":["../../src/commands/ext.ts"],"names":[],"mappings":"AAGA,OAAO,EAA0E,KAAK,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAazH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;EAMmB,CAAC;AAIzC,+FAA+F;AAC/F,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;AAE/D;;;;qGAIqG;AACrG,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAE,CAAC,CAAC,EAAE,MAAM,KAAK,OAAoB,GAAG,OAAO,CAE/F;AASD;;;;;;;;;;;;;;GAcG;AAEH,wBAAsB,GAAG,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CA6BzD;AAmED;;gBAEgB;AAChB,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,cAAc,UAAQ,EAAE,QAAQ,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAuP5J;AAoID,yDAAyD;AACzD,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,6CAA6C;IAC7C,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,gCAAgC;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,qDAAqD;IACrD,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,kDAAkD;IAClD,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC"}
1
+ {"version":3,"file":"ext.d.ts","sourceRoot":"","sources":["../../src/commands/ext.ts"],"names":[],"mappings":"AAGA,OAAO,EAA0E,KAAK,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAazH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;EAMmB,CAAC;AAIzC,+FAA+F;AAC/F,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;AAE/D;;;;qGAIqG;AACrG,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAE,CAAC,CAAC,EAAE,MAAM,KAAK,OAAoB,GAAG,OAAO,CAE/F;AASD;;;;;;;;;;;;;;GAcG;AAEH,wBAAsB,GAAG,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CA6BzD;AAmED;;kGAEkG;AAClG,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,cAAc,UAAQ,EAAE,QAAQ,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAmC5J;AAED;sDACsD;AACtD,qBAAa,uBAAwB,SAAQ,KAAK;IAEpC,QAAQ,CAAC,GAAG,EAAE,MAAM;IADhC,SAAkB,IAAI,6BAA6B;gBAC9B,GAAG,EAAE,MAAM;CAGjC;AAED,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,OAAO,GAAG,IAAI,CAIrD;AA4VD,yDAAyD;AACzD,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,6CAA6C;IAC7C,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,gCAAgC;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,qDAAqD;IACrD,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,kDAAkD;IAClD,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC"}
@@ -64,13 +64,13 @@ export async function ext(args) {
64
64
  if (v.json || v.plain)
65
65
  throw usage(sub === "root" ? "ext root prints its path raw and has no --json or --plain" : `ext ${sub}: --json and --plain are taken by the listing only`);
66
66
  if (sub === "add" && rest[0])
67
- return addExtension(atThisVersion(rest[0]));
67
+ return addExtension(atThisVersion(rest[0])).catch(exitOnInterruptedAdd);
68
68
  if (sub === "__update-add" && rest[0] && rest[1]) {
69
69
  if (Number(process.env[EXT_UPDATE_PARENT_ENV]) !== process.ppid)
70
70
  throw new Error("internal update extension replay must be launched by its recorded parent");
71
71
  if (!extensionUpdatePassOwnedBy(process.ppid))
72
72
  throw new Error("internal update extension replay requires its parent to own the extension update pass");
73
- return addExtension(rest[1], rest[0], true);
73
+ return addExtension(rest[1], rest[0], true).catch(exitOnInterruptedAdd);
74
74
  }
75
75
  if (sub === "remove" && rest[0])
76
76
  return remove(rest[0]);
@@ -150,9 +150,9 @@ function linkExtensionPeers(recorded, operationPkg, note, candidate = false) {
150
150
  }
151
151
  /** `cotal ext add <spec>`: install one extension into the operator prefix and record what it provides.
152
152
  * `announce` takes the closing `✓ added` line; `cotal setup` sends it to stderr when stdout carries
153
- * a result. */
153
+ * a result. A signal during the add rolls it back and throws {@link ExtensionAddInterrupted}. */
154
154
  export async function addExtension(spec, expectedPkg, borrowMutation = false, announce = console.log) {
155
- let dir = extensionsDir();
155
+ const dir = extensionsDir();
156
156
  // A file:/path spec is resolved to an absolute path so the prefix install works from any cwd.
157
157
  const isPath = isPathSpec(spec);
158
158
  const resolved = isPath ? resolve(spec) : spec;
@@ -182,226 +182,247 @@ export async function addExtension(spec, expectedPkg, borrowMutation = false, an
182
182
  writeFileSync(join(dir, "package.json"), `${JSON.stringify({ name: "cotal-extensions", private: true }, null, 2)}\n`, { flag: "wx", mode: 0o644 });
183
183
  provenance.wrote("extensions prefix", join(dir, "package.json"));
184
184
  }
185
- await addTransaction();
185
+ await addTransaction(pkg, resolved, expectedPkg, seeding, announce);
186
186
  }
187
187
  finally {
188
188
  if (seeding)
189
189
  clearChildMarker();
190
190
  releaseMutation();
191
191
  }
192
- async function addTransaction() {
193
- // Validate/read workstation state before npm can mutate the prefix; this snapshot also drives the
194
- // final replacement entry so the manifest and installed tree commit as one logical transaction.
195
- const manifest = loadExtensionsManifest();
196
- // npm installs in-place and may replace the package plus shared dependency/lock state before we
197
- // can validate it. A failed update must restore the previously working prefix byte-for-byte.
198
- const updating = manifest.extensions.some((entry) => entry.pkg === pkg) || existsSync(extensionPackageDir(pkg));
199
- const staging = !seeding && expectedPkg === undefined && !updating && !existsSync(extensionPackageDir(pkg));
200
- const rollbackRoot = updating ? mkdtempSync(join(dirname(dir), ".extensions.rollback-")) : undefined;
201
- const stageRoot = staging ? mkdtempSync(join(dirname(dir), ".extensions.stage-")) : undefined;
202
- const rollbackDir = rollbackRoot ? join(rollbackRoot, "extensions") : undefined;
203
- const stageDir = stageRoot ? join(stageRoot, "cotal", "extensions") : undefined;
192
+ }
193
+ /** An `ext add` stopped by SIGINT or SIGTERM. `addExtension` throws it once the prefix and manifest
194
+ * are back as they were and its lock is released. */
195
+ export class ExtensionAddInterrupted extends Error {
196
+ pkg;
197
+ name = "ExtensionAddInterrupted";
198
+ constructor(pkg) {
199
+ super(`adding ${pkg} was interrupted, so the extensions are as they were before it`);
200
+ this.pkg = pkg;
201
+ }
202
+ }
203
+ /** Ends a command whose add was interrupted with exit 130, and rethrows any other error. */
204
+ export function exitOnInterruptedAdd(e) {
205
+ if (!(e instanceof ExtensionAddInterrupted))
206
+ throw e;
207
+ console.error(c.yellow(`! ${e.message}`));
208
+ process.exitCode = 130;
209
+ }
210
+ /** One add as a transaction over the prefix and its manifest: a failed or interrupted add leaves both
211
+ * as they were, and the add is announced only once it has committed. */
212
+ async function addTransaction(pkg, resolved, expectedPkg, seeding, announce) {
213
+ const liveDir = extensionsDir();
214
+ // Validate/read workstation state before npm can mutate the prefix; this snapshot also drives the
215
+ // final replacement entry so the manifest and installed tree commit as one logical transaction.
216
+ const manifest = loadExtensionsManifest();
217
+ // npm installs in-place and may replace the package plus shared dependency/lock state before we
218
+ // can validate it. A failed update must restore the previously working prefix byte-for-byte.
219
+ const updating = manifest.extensions.some((entry) => entry.pkg === pkg) || existsSync(extensionPackageDir(pkg));
220
+ const staging = !seeding && expectedPkg === undefined && !updating && !existsSync(extensionPackageDir(pkg));
221
+ const rollbackRoot = updating ? mkdtempSync(join(dirname(liveDir), ".extensions.rollback-")) : undefined;
222
+ const stageRoot = staging ? mkdtempSync(join(dirname(liveDir), ".extensions.stage-")) : undefined;
223
+ const rollbackDir = rollbackRoot ? join(rollbackRoot, "extensions") : undefined;
224
+ const stageDir = stageRoot ? join(stageRoot, "cotal", "extensions") : undefined;
225
+ if (stageDir) {
226
+ mkdirSync(stageDir, { recursive: true });
227
+ writeFileSync(join(stageDir, "package.json"), `${JSON.stringify({ name: "cotal-extensions", private: true }, null, 2)}\n`);
228
+ }
229
+ if (rollbackDir) {
230
+ // Snapshot beside the prefix (same filesystem), preserving npm's relative symlinks verbatim.
231
+ // npm mutates the live tree; rollback removes it and atomically renames this snapshot back.
232
+ cpSync(liveDir, rollbackDir, { recursive: true, verbatimSymlinks: true });
233
+ // npm otherwise treats a same-spec/same-version re-add as already current, even when the
234
+ // installed files are stale or damaged. Remove only the disposable copy's package so install
235
+ // must materialize it again; the untouched snapshot remains the rollback source.
236
+ rmSync(extensionPackageDir(pkg), { recursive: true, force: true });
237
+ }
238
+ const configHome = process.env.XDG_CONFIG_HOME;
239
+ let interrupted = false;
240
+ const interrupt = () => {
241
+ interrupted = true;
242
+ };
243
+ process.once("SIGINT", interrupt);
244
+ process.once("SIGTERM", interrupt);
245
+ let added;
246
+ try {
247
+ // The existing writer lock remains held while workspace helpers resolve into the stage.
248
+ if (stageRoot)
249
+ process.env.XDG_CONFIG_HOME = stageRoot;
250
+ try {
251
+ added = await installCandidate(pkg, resolved, stageDir ?? liveDir, manifest.extensions, seeding, stageDir !== undefined, announce);
252
+ }
253
+ finally {
254
+ if (configHome === undefined)
255
+ delete process.env.XDG_CONFIG_HOME;
256
+ else
257
+ process.env.XDG_CONFIG_HOME = configHome;
258
+ }
259
+ if (interrupted)
260
+ throw new ExtensionAddInterrupted(pkg);
204
261
  if (stageDir) {
205
- mkdirSync(stageDir, { recursive: true });
206
- writeFileSync(join(stageDir, "package.json"), `${JSON.stringify({ name: "cotal-extensions", private: true }, null, 2)}\n`);
207
- dir = stageDir;
262
+ const metadata = (file, base = stageDir) => JSON.parse(readFileSync(file, "utf8"), (_key, value) => typeof value === "string" && value.startsWith("file:") ? "file:" + resolve(base, value.slice(5)) : value);
263
+ const livePackage = metadata(join(liveDir, "package.json"), liveDir);
264
+ const stagedPackage = metadata(join(stageDir, "package.json"));
265
+ const dependencies = { ...livePackage.dependencies, ...stagedPackage.dependencies };
266
+ const lockPath = join(liveDir, "package-lock.json");
267
+ const liveLock = existsSync(lockPath) ? metadata(lockPath, liveDir) : {};
268
+ const stagedLock = metadata(join(stageDir, "package-lock.json"));
269
+ cpSync(join(stageDir, "node_modules"), join(liveDir, "node_modules"), { recursive: true, verbatimSymlinks: true });
270
+ writeFileSync(join(liveDir, "package.json"), JSON.stringify({ ...livePackage, dependencies }, null, 2) + "\n");
271
+ writeFileSync(lockPath, JSON.stringify({ ...liveLock, ...stagedLock,
272
+ packages: { ...liveLock.packages, ...stagedLock.packages, "": { ...stagedLock.packages?.[""], dependencies } },
273
+ }, null, 2) + "\n");
274
+ copyFileSync(join(stageDir, "extensions.json"), extensionsManifestPath());
275
+ rmSync(stageRoot, { recursive: true, force: true });
208
276
  }
277
+ }
278
+ catch (e) {
279
+ // Nothing has committed: put the prefix back the way the add found it.
209
280
  if (rollbackDir) {
210
- // Snapshot beside the prefix (same filesystem), preserving npm's relative symlinks verbatim.
211
- // npm mutates the live tree; rollback removes it and atomically renames this snapshot back.
212
- cpSync(dir, rollbackDir, { recursive: true, verbatimSymlinks: true });
213
- // npm otherwise treats a same-spec/same-version re-add as already current, even when the
214
- // installed files are stale or damaged. Remove only the disposable copy's package so install
215
- // must materialize it again; the untouched snapshot remains the rollback source.
216
- rmSync(extensionPackageDir(pkg), { recursive: true, force: true });
217
- }
218
- const liveDir = extensionsDir();
219
- const configHome = process.env.XDG_CONFIG_HOME;
220
- let committed = false;
221
- let restored = false;
222
- const restore = async () => {
223
- if (restored || committed)
224
- return;
225
- restored = true;
226
- if (rollbackDir) {
227
- rmSync(extensionsDir(), { recursive: true, force: true });
228
- renameSync(rollbackDir, extensionsDir());
229
- rmSync(rollbackRoot, { recursive: true, force: true });
230
- }
231
- else if (stageRoot) {
232
- rmSync(stageRoot, { recursive: true, force: true });
233
- }
234
- else {
235
- await npm(["remove", "--no-audit", "--no-fund", "--install-links", pkg], dir);
236
- linkExtensionPeers(manifest.extensions, pkg, announce);
237
- }
238
- };
239
- let wasInterrupted = false;
240
- const interrupted = () => {
241
- wasInterrupted = true;
242
- };
243
- process.once("SIGINT", interrupted);
244
- process.once("SIGTERM", interrupted);
245
- try {
246
- // The existing writer lock remains held while workspace helpers resolve into the stage.
247
- if (stageRoot)
248
- process.env.XDG_CONFIG_HOME = stageRoot;
249
- try {
250
- await installCandidate();
251
- }
252
- finally {
253
- if (configHome === undefined)
254
- delete process.env.XDG_CONFIG_HOME;
255
- else
256
- process.env.XDG_CONFIG_HOME = configHome;
257
- }
258
- if (wasInterrupted)
259
- throw new Error("extension install interrupted");
260
- if (stageDir) {
261
- const metadata = (file, base = stageDir) => JSON.parse(readFileSync(file, "utf8"), (_key, value) => typeof value === "string" && value.startsWith("file:") ? "file:" + resolve(base, value.slice(5)) : value);
262
- const livePackage = metadata(join(liveDir, "package.json"), liveDir);
263
- const stagedPackage = metadata(join(stageDir, "package.json"));
264
- const dependencies = { ...livePackage.dependencies, ...stagedPackage.dependencies };
265
- const lockPath = join(liveDir, "package-lock.json");
266
- const liveLock = existsSync(lockPath) ? metadata(lockPath, liveDir) : {};
267
- const stagedLock = metadata(join(stageDir, "package-lock.json"));
268
- cpSync(join(stageDir, "node_modules"), join(liveDir, "node_modules"), { recursive: true, verbatimSymlinks: true });
269
- writeFileSync(join(liveDir, "package.json"), JSON.stringify({ ...livePackage, dependencies }, null, 2) + "\n");
270
- writeFileSync(lockPath, JSON.stringify({ ...liveLock, ...stagedLock,
271
- packages: { ...liveLock.packages, ...stagedLock.packages, "": { ...stagedLock.packages?.[""], dependencies } },
272
- }, null, 2) + "\n");
273
- copyFileSync(join(stageDir, "extensions.json"), extensionsManifestPath());
274
- rmSync(stageRoot, { recursive: true, force: true });
275
- }
276
- committed = true;
277
- if (rollbackRoot)
278
- rmSync(rollbackRoot, { recursive: true, force: true });
281
+ rmSync(liveDir, { recursive: true, force: true });
282
+ renameSync(rollbackDir, liveDir);
283
+ rmSync(rollbackRoot, { recursive: true, force: true });
279
284
  }
280
- catch (e) {
281
- await restore();
282
- if (wasInterrupted) {
283
- if (seeding)
284
- clearChildMarker();
285
- releaseMutation();
286
- process.exit(130);
287
- }
288
- throw e;
285
+ else if (stageRoot) {
286
+ rmSync(stageRoot, { recursive: true, force: true });
289
287
  }
290
- finally {
291
- process.removeListener("SIGINT", interrupted);
292
- process.removeListener("SIGTERM", interrupted);
288
+ else {
289
+ await npm(["remove", "--no-audit", "--no-fund", "--install-links", pkg], liveDir);
290
+ linkExtensionPeers(manifest.extensions, pkg, announce);
293
291
  }
294
- async function installCandidate() {
295
- console.error(c.dim(`installing ${resolved} into ${dir} …`));
296
- // --legacy-peer-deps: never auto-install the peer'd core from the registry — the add ALWAYS
297
- // links the running binary's copy below (one core instance is the whole point).
298
- // --install-links: a file:/path spec is COPIED into the prefix, not symlinked — a symlink's
299
- // realpath would escape the prefix and Node could no longer resolve the linked core from it.
300
- const r = await npm(["install", "--save", "--no-audit", "--no-fund", "--legacy-peer-deps", "--install-links", resolved], dir);
301
- if (r.status !== 0) {
302
- fail(pkg, `npm install failed:\n${r.output.split("\n").slice(-8).join("\n")}`);
303
- }
304
- // The spec's package must now be a prefix dependency — anything else is a failed install.
305
- let deps;
306
- try {
307
- deps = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).dependencies ?? {};
308
- }
309
- catch (e) {
310
- fail(pkg, `left unreadable prefix metadata: ${e.message}`);
311
- }
312
- if (!deps[pkg]) {
313
- fail(pkg, `npm install succeeded but it is not among the prefix dependencies - remove and retry`);
314
- }
315
- const pkgDir = join(dir, "node_modules", ...pkg.split("/"));
316
- let pkgMeta;
317
- try {
318
- pkgMeta = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"));
319
- }
320
- catch (e) {
321
- fail(pkg, `has unreadable package metadata: ${e.message}`);
322
- }
323
- if (typeof pkgMeta.version !== "string" || !pkgMeta.version) {
324
- fail(pkg, `declares no "version" - the manifest pins an extension's version and every load checks the installed package against it`);
325
- }
326
- // Shared @cotal-ai/* packages must be PEER dependencies — a regular dependency vendors a second
327
- // copy: core's would swallow the extension's registrations into its own registry singleton, and
328
- // any other shared package would silently drift from the binary's. Fail with the exact reason.
329
- const vendored = Object.keys(pkgMeta.dependencies ?? {}).filter((d) => d.startsWith("@cotal-ai/"));
330
- if (vendored.length) {
331
- fail(pkg, `declares ${vendored.join(", ")} as a regular dependency - shared @cotal-ai/* packages must be peerDependencies, or the extension runs its own copy (core's would swallow its command registrations; any other's drifts from this CLI's)`);
332
- }
333
- if (!pkgMeta.peerDependencies?.["@cotal-ai/core"]) {
334
- fail(pkg, `does not declare @cotal-ai/core as a peerDependency - a cotal CLI extension must (its extension objects register into core's registry)`);
335
- }
336
- // npm mutates the shared prefix, so restore every package's private shared-peer links, not only
337
- // the candidate's. All extensions resolve the exact same host package instances.
338
- try {
339
- linkExtensionPeers(stageDir ? [] : manifest.extensions.filter((entry) => entry.pkg !== pkg), pkg, announce, true);
340
- }
341
- catch (e) {
342
- fail(pkg, e.message);
343
- }
344
- // Import once; every registration must LAND IN OUR REGISTRY. Runtime-only and other provider
345
- // packages are first-class extensions too; commands are only the display/dispatch subset.
346
- const before = new Set(registry.all().map((ext) => `${ext.kind}:${ext.name}`));
347
- const version = pkgMeta.version;
348
- await importExtensionEntry(pkg, version, "the add was rolled back; replace this build");
349
- const contributed = registry.all().filter((ext) => !before.has(`${ext.kind}:${ext.name}`));
350
- if (!contributed.length) {
351
- fail(pkg, `imported cleanly but registered no extensions in THIS CLI's registry - if it bundles its own @cotal-ai/core, make core a peerDependency`);
352
- }
353
- // `cotal` is reserved (the binary's own name — there is no runtime alias anymore); a connector must
354
- // never claim it, or `--agent cotal` would be ambiguous with the CLI.
355
- const reserved = contributed.find((ext) => ext.kind === "connector" && RESERVED_CONNECTOR_NAMES.includes(ext.name));
356
- if (reserved)
357
- fail(pkg, `contributes connector "${reserved.name}", which is a reserved name - a connector cannot be named ${RESERVED_CONNECTOR_NAMES.join(", ")}`);
358
- // Builtin collisions can't happen here (registry.register throws on a duplicate name or alias,
359
- // surfacing as failed-to-import above, naming the extension). OTHER installed extensions are
360
- // invisible to the registry during this add (they aren't imported), so their CACHED names and
361
- // aliases are checked explicitly — a duplicate fails the add under the same contract, naming both sides.
362
- for (const provided of contributed) {
363
- for (const word of providedWords(cacheExtension(provided))) {
364
- const other = manifest.extensions.find((e) => e.pkg !== pkg && extensionProvides(e).some((ref) => ref.kind === provided.kind && providedWords(ref).includes(word)));
365
- if (other) {
366
- fail(pkg, `contributes ${provided.kind} "${word}", already provided by installed extension ${other.pkg}@${other.version} - two extensions cannot claim one registry name or alias; \`cotal ext remove ${other.pkg}\` first if you want this one`);
367
- }
368
- }
369
- }
370
- const commands = contributed.filter((ext) => ext.kind === "command");
371
- // The dispatcher resolves a seeded package's commands before its first seed, from the declared list.
372
- const mismatch = seeding ? seededCommandsMismatch(pkg, commands) : undefined;
373
- if (mismatch)
374
- fail(pkg, mismatch);
375
- const connectors = contributed.filter((ext) => ext.kind === "connector");
376
- const localProcesses = contributed.filter((ext) => ext.kind === "local-process");
377
- const servicePresets = contributed.filter((ext) => ext.kind === "service-preset").map(cacheServicePreset);
378
- const entry = {
379
- pkg,
380
- version,
381
- spec: resolved,
382
- ...(seeding ? { source: "seeded" } : {}),
383
- provides: contributed.map(cacheExtension),
384
- commands: commands.map(cacheCommand),
385
- connectors: connectors.map(cacheConnector),
386
- localProcesses: localProcesses.map(cacheLocalProcess),
387
- servicePresets,
388
- serviceMetadata: cacheExtensionServiceMetadata(pkg, version, localProcesses, servicePresets),
389
- };
390
- try {
391
- saveExtensionsManifest({ extensions: [...manifest.extensions.filter((e) => e.pkg !== pkg), entry] });
392
- }
393
- catch (e) {
394
- fail(pkg, `could not update the extensions manifest: ${e.message}`);
292
+ throw interrupted ? new ExtensionAddInterrupted(pkg) : e;
293
+ }
294
+ finally {
295
+ process.removeListener("SIGINT", interrupt);
296
+ process.removeListener("SIGTERM", interrupt);
297
+ }
298
+ for (const line of added)
299
+ announce(line);
300
+ if (!rollbackRoot)
301
+ return;
302
+ // The add has committed, so a snapshot that cannot be removed is left over, not a failed add.
303
+ try {
304
+ rmSync(rollbackRoot, { recursive: true, force: true });
305
+ }
306
+ catch (e) {
307
+ console.error(c.yellow(`! could not remove the previous copy of the extensions at ${rollbackRoot} (${e.message}); remove it by hand`));
308
+ }
309
+ }
310
+ /** Installs `resolved` into the prefix at `dir`, checks what it registers against the `recorded`
311
+ * extensions and records it in that prefix's manifest. `staged`: `dir` is a fresh stage, which holds
312
+ * no other extension. `note` takes warnings as they happen; the returned lines announce the add, for
313
+ * the caller to print once it has committed. */
314
+ async function installCandidate(pkg, resolved, dir, recorded, seeding, staged, note) {
315
+ console.error(c.dim(`installing ${resolved} into ${dir} …`));
316
+ // --legacy-peer-deps: never auto-install the peer'd core from the registry — the add ALWAYS
317
+ // links the running binary's copy below (one core instance is the whole point).
318
+ // --install-links: a file:/path spec is COPIED into the prefix, not symlinked — a symlink's
319
+ // realpath would escape the prefix and Node could no longer resolve the linked core from it.
320
+ const r = await npm(["install", "--save", "--no-audit", "--no-fund", "--legacy-peer-deps", "--install-links", resolved], dir);
321
+ if (r.status !== 0) {
322
+ fail(pkg, `npm install failed:\n${r.output.split("\n").slice(-8).join("\n")}`);
323
+ }
324
+ // The spec's package must now be a prefix dependency — anything else is a failed install.
325
+ let deps;
326
+ try {
327
+ deps = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).dependencies ?? {};
328
+ }
329
+ catch (e) {
330
+ fail(pkg, `left unreadable prefix metadata: ${e.message}`);
331
+ }
332
+ if (!deps[pkg]) {
333
+ fail(pkg, `npm install succeeded but it is not among the prefix dependencies - remove and retry`);
334
+ }
335
+ const pkgDir = join(dir, "node_modules", ...pkg.split("/"));
336
+ let pkgMeta;
337
+ try {
338
+ pkgMeta = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"));
339
+ }
340
+ catch (e) {
341
+ fail(pkg, `has unreadable package metadata: ${e.message}`);
342
+ }
343
+ if (typeof pkgMeta.version !== "string" || !pkgMeta.version) {
344
+ fail(pkg, `declares no "version" - the manifest pins an extension's version and every load checks the installed package against it`);
345
+ }
346
+ // Shared @cotal-ai/* packages must be PEER dependencies — a regular dependency vendors a second
347
+ // copy: core's would swallow the extension's registrations into its own registry singleton, and
348
+ // any other shared package would silently drift from the binary's. Fail with the exact reason.
349
+ const vendored = Object.keys(pkgMeta.dependencies ?? {}).filter((d) => d.startsWith("@cotal-ai/"));
350
+ if (vendored.length) {
351
+ fail(pkg, `declares ${vendored.join(", ")} as a regular dependency - shared @cotal-ai/* packages must be peerDependencies, or the extension runs its own copy (core's would swallow its command registrations; any other's drifts from this CLI's)`);
352
+ }
353
+ if (!pkgMeta.peerDependencies?.["@cotal-ai/core"]) {
354
+ fail(pkg, `does not declare @cotal-ai/core as a peerDependency - a cotal CLI extension must (its extension objects register into core's registry)`);
355
+ }
356
+ // npm mutates the shared prefix, so restore every package's private shared-peer links, not only
357
+ // the candidate's. All extensions resolve the exact same host package instances.
358
+ try {
359
+ linkExtensionPeers(staged ? [] : recorded.filter((entry) => entry.pkg !== pkg), pkg, note, true);
360
+ }
361
+ catch (e) {
362
+ fail(pkg, e.message);
363
+ }
364
+ // Import once; every registration must LAND IN OUR REGISTRY. Runtime-only and other provider
365
+ // packages are first-class extensions too; commands are only the display/dispatch subset.
366
+ const before = new Set(registry.all().map((ext) => `${ext.kind}:${ext.name}`));
367
+ const version = pkgMeta.version;
368
+ await importExtensionEntry(pkg, version, "the add was rolled back; replace this build");
369
+ const contributed = registry.all().filter((ext) => !before.has(`${ext.kind}:${ext.name}`));
370
+ if (!contributed.length) {
371
+ fail(pkg, `imported cleanly but registered no extensions in THIS CLI's registry - if it bundles its own @cotal-ai/core, make core a peerDependency`);
372
+ }
373
+ // `cotal` is reserved (the binary's own name — there is no runtime alias anymore); a connector must
374
+ // never claim it, or `--agent cotal` would be ambiguous with the CLI.
375
+ const reserved = contributed.find((ext) => ext.kind === "connector" && RESERVED_CONNECTOR_NAMES.includes(ext.name));
376
+ if (reserved)
377
+ fail(pkg, `contributes connector "${reserved.name}", which is a reserved name - a connector cannot be named ${RESERVED_CONNECTOR_NAMES.join(", ")}`);
378
+ // Builtin collisions can't happen here (registry.register throws on a duplicate name or alias,
379
+ // surfacing as failed-to-import above, naming the extension). OTHER installed extensions are
380
+ // invisible to the registry during this add (they aren't imported), so their CACHED names and
381
+ // aliases are checked explicitly — a duplicate fails the add under the same contract, naming both sides.
382
+ for (const provided of contributed) {
383
+ for (const word of providedWords(cacheExtension(provided))) {
384
+ const other = recorded.find((e) => e.pkg !== pkg && extensionProvides(e).some((ref) => ref.kind === provided.kind && providedWords(ref).includes(word)));
385
+ if (other) {
386
+ fail(pkg, `contributes ${provided.kind} "${word}", already provided by installed extension ${other.pkg}@${other.version} - two extensions cannot claim one registry name or alias; \`cotal ext remove ${other.pkg}\` first if you want this one`);
395
387
  }
396
- provenance.wrote(`extensions manifest (+${pkg}@${version})`, extensionsManifestPath());
397
- announce(c.green(`✓ added ${pkg}@${version}`) + c.dim(` - provides: ${contributed.map((ext) => `${ext.kind}:${ext.name}`).join(", ")}`));
398
- if (!entry.serviceMetadata && (servicePresets.length || localProcesses.some((component) => component.service !== undefined)))
399
- announce(c.dim(` its services cannot run on this platform: protected workstation file access is not available in this release`));
400
- }
401
- function fail(p, why) {
402
- throw new Error(`${p} ${why}`);
403
388
  }
404
389
  }
390
+ const commands = contributed.filter((ext) => ext.kind === "command");
391
+ // The dispatcher resolves a seeded package's commands before its first seed, from the declared list.
392
+ const mismatch = seeding ? seededCommandsMismatch(pkg, commands) : undefined;
393
+ if (mismatch)
394
+ fail(pkg, mismatch);
395
+ const connectors = contributed.filter((ext) => ext.kind === "connector");
396
+ const localProcesses = contributed.filter((ext) => ext.kind === "local-process");
397
+ const servicePresets = contributed.filter((ext) => ext.kind === "service-preset").map(cacheServicePreset);
398
+ const entry = {
399
+ pkg,
400
+ version,
401
+ spec: resolved,
402
+ ...(seeding ? { source: "seeded" } : {}),
403
+ provides: contributed.map(cacheExtension),
404
+ commands: commands.map(cacheCommand),
405
+ connectors: connectors.map(cacheConnector),
406
+ localProcesses: localProcesses.map(cacheLocalProcess),
407
+ servicePresets,
408
+ serviceMetadata: cacheExtensionServiceMetadata(pkg, version, localProcesses, servicePresets),
409
+ };
410
+ try {
411
+ saveExtensionsManifest({ extensions: [...recorded.filter((e) => e.pkg !== pkg), entry] });
412
+ }
413
+ catch (e) {
414
+ fail(pkg, `could not update the extensions manifest: ${e.message}`);
415
+ }
416
+ provenance.wrote(`extensions manifest (+${pkg}@${version})`, extensionsManifestPath());
417
+ return [
418
+ c.green(`✓ added ${pkg}@${version}`) + c.dim(` - provides: ${contributed.map((ext) => `${ext.kind}:${ext.name}`).join(", ")}`),
419
+ ...(!entry.serviceMetadata && (servicePresets.length || localProcesses.some((component) => component.service !== undefined))
420
+ ? [c.dim(` its services cannot run on this platform: protected workstation file access is not available in this release`)]
421
+ : []),
422
+ ];
423
+ }
424
+ function fail(p, why) {
425
+ throw new Error(`${p} ${why}`);
405
426
  }
406
427
  /** The package NAME a spec installs, known BEFORE npm runs: a path spec reads its package.json;
407
428
  * a registry spec carries the name (`name`, `name@range`, `@scope/name@range`). Exotic forms