@cotal-ai/cli 0.171.1 → 0.171.3

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 (168) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +140 -85
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +12 -8
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/app-identity.d.ts +6 -0
  8. package/dist/commands/app-identity.d.ts.map +1 -1
  9. package/dist/commands/app-identity.js +4 -4
  10. package/dist/commands/app-identity.js.map +1 -1
  11. package/dist/commands/backup-maintenance.js +1 -1
  12. package/dist/commands/backup-maintenance.js.map +1 -1
  13. package/dist/commands/backup.d.ts.map +1 -1
  14. package/dist/commands/backup.js +12 -5
  15. package/dist/commands/backup.js.map +1 -1
  16. package/dist/commands/down.d.ts.map +1 -1
  17. package/dist/commands/down.js +11 -7
  18. package/dist/commands/down.js.map +1 -1
  19. package/dist/commands/ext.js +1 -1
  20. package/dist/commands/ext.js.map +1 -1
  21. package/dist/commands/help.d.ts.map +1 -1
  22. package/dist/commands/help.js +2 -13
  23. package/dist/commands/help.js.map +1 -1
  24. package/dist/commands/history-clear.d.ts.map +1 -1
  25. package/dist/commands/history-clear.js +18 -2
  26. package/dist/commands/history-clear.js.map +1 -1
  27. package/dist/commands/join.js +7 -2
  28. package/dist/commands/join.js.map +1 -1
  29. package/dist/commands/manager-service.d.ts +1 -1
  30. package/dist/commands/manager-service.d.ts.map +1 -1
  31. package/dist/commands/manager-service.js +9 -4
  32. package/dist/commands/manager-service.js.map +1 -1
  33. package/dist/commands/reset-space-apply.d.ts.map +1 -1
  34. package/dist/commands/reset-space-apply.js +2 -1
  35. package/dist/commands/reset-space-apply.js.map +1 -1
  36. package/dist/commands/reset-store-apply.d.ts +6 -0
  37. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  38. package/dist/commands/reset-store-apply.js +22 -2
  39. package/dist/commands/reset-store-apply.js.map +1 -1
  40. package/dist/commands/service-registry.d.ts.map +1 -1
  41. package/dist/commands/service-registry.js +2 -0
  42. package/dist/commands/service-registry.js.map +1 -1
  43. package/dist/commands/setup.d.ts.map +1 -1
  44. package/dist/commands/setup.js +14 -2
  45. package/dist/commands/setup.js.map +1 -1
  46. package/dist/commands/space-registration.d.ts +3 -1
  47. package/dist/commands/space-registration.d.ts.map +1 -1
  48. package/dist/commands/space-registration.js +20 -14
  49. package/dist/commands/space-registration.js.map +1 -1
  50. package/dist/commands/space.d.ts +1 -0
  51. package/dist/commands/space.d.ts.map +1 -1
  52. package/dist/commands/space.js +5 -1
  53. package/dist/commands/space.js.map +1 -1
  54. package/dist/commands/spawn-preview.d.ts +1 -1
  55. package/dist/commands/spawn-preview.d.ts.map +1 -1
  56. package/dist/commands/spawn-preview.js +36 -6
  57. package/dist/commands/spawn-preview.js.map +1 -1
  58. package/dist/commands/spawn.d.ts +7 -2
  59. package/dist/commands/spawn.d.ts.map +1 -1
  60. package/dist/commands/spawn.js +158 -75
  61. package/dist/commands/spawn.js.map +1 -1
  62. package/dist/commands/stack-down.js +9 -4
  63. package/dist/commands/stack-down.js.map +1 -1
  64. package/dist/commands/stack-gone.d.ts +8 -5
  65. package/dist/commands/stack-gone.d.ts.map +1 -1
  66. package/dist/commands/stack-gone.js +8 -6
  67. package/dist/commands/stack-gone.js.map +1 -1
  68. package/dist/commands/stack-up.d.ts +2 -1
  69. package/dist/commands/stack-up.d.ts.map +1 -1
  70. package/dist/commands/stack-up.js +9 -5
  71. package/dist/commands/stack-up.js.map +1 -1
  72. package/dist/commands/status.d.ts +6 -1
  73. package/dist/commands/status.d.ts.map +1 -1
  74. package/dist/commands/status.js +71 -27
  75. package/dist/commands/status.js.map +1 -1
  76. package/dist/commands/up.d.ts +2 -1
  77. package/dist/commands/up.d.ts.map +1 -1
  78. package/dist/commands/up.js +72 -43
  79. package/dist/commands/up.js.map +1 -1
  80. package/dist/commands/update.d.ts +9 -3
  81. package/dist/commands/update.d.ts.map +1 -1
  82. package/dist/commands/update.js +230 -40
  83. package/dist/commands/update.js.map +1 -1
  84. package/dist/ext-loader.d.ts +1 -1
  85. package/dist/ext-loader.d.ts.map +1 -1
  86. package/dist/ext-loader.js +3 -3
  87. package/dist/ext-loader.js.map +1 -1
  88. package/dist/index.d.ts.map +1 -1
  89. package/dist/index.js +4 -2
  90. package/dist/index.js.map +1 -1
  91. package/dist/lib/backup-artifact.d.ts.map +1 -1
  92. package/dist/lib/backup-artifact.js +11 -3
  93. package/dist/lib/backup-artifact.js.map +1 -1
  94. package/dist/lib/credential-authority.d.ts.map +1 -1
  95. package/dist/lib/credential-authority.js +3 -1
  96. package/dist/lib/credential-authority.js.map +1 -1
  97. package/dist/lib/delivery-proc.d.ts +2 -1
  98. package/dist/lib/delivery-proc.d.ts.map +1 -1
  99. package/dist/lib/delivery-proc.js.map +1 -1
  100. package/dist/lib/local-process-stop.d.ts +2 -0
  101. package/dist/lib/local-process-stop.d.ts.map +1 -1
  102. package/dist/lib/local-process-stop.js +1 -0
  103. package/dist/lib/local-process-stop.js.map +1 -1
  104. package/dist/lib/manager-proc.d.ts +4 -2
  105. package/dist/lib/manager-proc.d.ts.map +1 -1
  106. package/dist/lib/manager-proc.js +10 -3
  107. package/dist/lib/manager-proc.js.map +1 -1
  108. package/dist/lib/manifest/render.d.ts.map +1 -1
  109. package/dist/lib/manifest/render.js +4 -0
  110. package/dist/lib/manifest/render.js.map +1 -1
  111. package/dist/lib/nats-bin.d.ts +1 -0
  112. package/dist/lib/nats-bin.d.ts.map +1 -1
  113. package/dist/lib/nats-bin.js +1 -0
  114. package/dist/lib/nats-bin.js.map +1 -1
  115. package/dist/lib/persona-files.d.ts +1 -1
  116. package/dist/lib/persona-files.d.ts.map +1 -1
  117. package/dist/lib/persona-files.js +10 -2
  118. package/dist/lib/persona-files.js.map +1 -1
  119. package/dist/lib/registry-errors.d.ts +4 -0
  120. package/dist/lib/registry-errors.d.ts.map +1 -1
  121. package/dist/lib/registry-errors.js +3 -2
  122. package/dist/lib/registry-errors.js.map +1 -1
  123. package/dist/lib/restore.d.ts +4 -3
  124. package/dist/lib/restore.d.ts.map +1 -1
  125. package/dist/lib/restore.js +12 -10
  126. package/dist/lib/restore.js.map +1 -1
  127. package/dist/lib/self-exec.d.ts.map +1 -1
  128. package/dist/lib/self-exec.js +24 -3
  129. package/dist/lib/self-exec.js.map +1 -1
  130. package/dist/lib/service-adapters.d.ts +1 -1
  131. package/dist/lib/service-adapters.d.ts.map +1 -1
  132. package/dist/lib/service-adapters.js +2 -2
  133. package/dist/lib/service-adapters.js.map +1 -1
  134. package/dist/lib/service-census.d.ts +5 -5
  135. package/dist/lib/service-install-intent.d.ts +2 -2
  136. package/dist/lib/service-instances.d.ts +2 -2
  137. package/dist/lib/service-preset-target.d.ts.map +1 -1
  138. package/dist/lib/service-preset-target.js +6 -1
  139. package/dist/lib/service-preset-target.js.map +1 -1
  140. package/dist/lib/service-presets.d.ts +1 -1
  141. package/dist/lib/service-presets.d.ts.map +1 -1
  142. package/dist/lib/service-presets.js +7 -5
  143. package/dist/lib/service-presets.js.map +1 -1
  144. package/dist/lib/service-process.d.ts +2 -0
  145. package/dist/lib/service-process.d.ts.map +1 -1
  146. package/dist/lib/service-process.js +3 -3
  147. package/dist/lib/service-process.js.map +1 -1
  148. package/dist/lib/service-supervision.d.ts +1 -1
  149. package/dist/lib/service-systemd-attempt-read.d.ts +3 -3
  150. package/dist/lib/service-uninstall-intent.d.ts +2 -2
  151. package/dist/lib/stack-journal.d.ts +5 -2
  152. package/dist/lib/stack-journal.d.ts.map +1 -1
  153. package/dist/lib/stack-journal.js +5 -2
  154. package/dist/lib/stack-journal.js.map +1 -1
  155. package/dist/lib/team-agent-removal.d.ts +1 -1
  156. package/dist/lib/update-pending.d.ts.map +1 -1
  157. package/dist/lib/update-pending.js +4 -2
  158. package/dist/lib/update-pending.js.map +1 -1
  159. package/dist/lib/update-snapshot.js +3 -3
  160. package/dist/lib/update-snapshot.js.map +1 -1
  161. package/dist/lib/version.d.ts +2 -0
  162. package/dist/lib/version.d.ts.map +1 -1
  163. package/dist/lib/version.js +15 -1
  164. package/dist/lib/version.js.map +1 -1
  165. package/dist/seed/reconcile.d.ts.map +1 -1
  166. package/dist/seed/reconcile.js +5 -2
  167. package/dist/seed/reconcile.js.map +1 -1
  168. package/package.json +12 -4
@@ -1,10 +1,10 @@
1
1
  import { spawn as spawnProcess } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { readFileSync, rmSync, statSync } from "node:fs";
3
+ import { readFileSync, realpathSync, rmSync, statSync } from "node:fs";
4
4
  import { constants as osConstants, hostname } from "node:os";
5
5
  import { resolve as resolvePath } from "node:path";
6
- import { assertValidRole, agentFilePath, AgentGrantConflictError, connectorServers, spawnEnvAllow, deprovisionAgent, discardLaunchArtifacts, firstFreeName, reclaimWithChild, loadCotalConfig, modelPolicyRefusal, mintCreds, newIdentity, DEV_OWNER, parseShareSelection, principalKey, assertLifecycleToken, mintLifecycleUid, MANAGED_HANDOFF_FILE_ENV, parseManagedLifecycleHandoff, spawnNameError, provisionAgent, provisionAgentDurables, lowerPersonaEndpoints, copyPersonaEndpoints, registry, resolveAuthProvider, resolveReadAcl, runAgentBearer, GOAL_ENTITY_RUNNING_DETAIL_KIND, EP_UNDECLARED_ARG, seatCapFrom, acquireLock, inspectLock, localConsumerClaimPath, transferBucket, writeTransfer, peerLabel, attemptCleanup, describeCleanupFailures, rejectionText, } from "@cotal-ai/core";
7
- import { parseCommaList, CommandFailure, loadLaunchPersonaFile, personaFileReference, PersonaSourceError, inputDisabledByFlag, jsonFlag, plainFlag, presentationOf, recordOperationWarning, renderReport, terminalWidth, wrapWords, writeResult, agentActorTokenKey, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, agentSentinelCredsKey, authDir, cachedPreferences, credsFlag, launchFlags, findMesh, getSpaceAuth, loadManagerInstanceIdentity, materializeSecretToFile, mergeLaunchOptions, parseLaunchOptions, preflightOrThrow, provenance, resolveAgentType, resolveOnPath, resolveTargetOrThrow, serverFlag, spaceAccountPath, spaceFlag, spaceKey, userAuthStateDir, workspaceSecretStore, refreshRegistrationPolicy, resolveSeatControlTarget, connectUserControlOrExit, userViewAuth, oneLine, codeSpan, DEFAULT_CONNECTOR, hintedConnector, manifestExtensionNames, OFFICIAL_CONNECTORS, recordOperationSpace, resolveMeshTarget, activateTerminalSeat, issueTerminalSeat, retireTerminalSeat, seatExpiryAt, resolveControlTarget, } from "@cotal-ai/workspace";
6
+ import { assertValidChannel, assertValidRole, agentFilePath, AgentGrantConflictError, connectorServers, spawnEnvAllow, deprovisionAgent, discardLaunchArtifacts, firstFreeName, reclaimWithChild, loadCotalConfig, modelPolicyRefusal, mintCreds, newIdentity, DEV_OWNER, parseShareSelection, principalKey, assertLifecycleToken, mintLifecycleUid, MANAGED_HANDOFF_FILE_ENV, parseManagedLifecycleHandoff, spawnNameError, provisionAgent, provisionAgentDurables, lowerPersonaEndpoints, copyPersonaEndpoints, registry, resolveAuthProvider, resolveReadAcl, runAgentBearer, GOAL_ENTITY_RUNNING_DETAIL_KIND, EP_UNDECLARED_ARG, seatCapFrom, acquireLock, inspectLock, localConsumerClaimPath, transferBucket, writeTransfer, peerLabel, attemptCleanup, describeCleanupFailures, rejectionText, } from "@cotal-ai/core";
7
+ import { parseCommaList, CommandFailure, isCommandFailure, loadLaunchPersonaFile, personaFileReference, PersonaSourceError, inputDisabledByFlag, jsonFlag, plainFlag, presentationOf, recordOperationWarning, renderReport, terminalWidth, wrapWords, writeResult, agentActorTokenKey, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, agentSentinelCredsKey, authDir, cachedPreferences, credsFlag, launchFlags, findMesh, getSpaceAuth, loadManagerInstanceIdentity, materializeSecretToFile, mergeLaunchOptions, parseLaunchOptions, preflightOrThrow, provenance, resolveAgentType, resolveOnPath, resolveTargetOrThrow, serverFlag, spaceAccountPath, spaceFlag, spaceKey, userAuthStateDir, workspaceSecretStore, refreshRegistrationPolicy, resolveSeatControlTarget, connectUserControlOrExit, userViewAuth, oneLine, codeSpan, DEFAULT_CONNECTOR, hintedConnector, manifestExtensionNames, OFFICIAL_CONNECTORS, recordOperationSpace, resolveMeshTarget, activateTerminalSeat, issueTerminalSeat, retireTerminalSeat, seatExpiryAt, resolveControlTarget, } from "@cotal-ai/workspace";
8
8
  import { readManagedLaunch, requestManagedLaunch } from "@cotal-ai/workspace/launch";
9
9
  import { c, stderrLine } from "../ui.js";
10
10
  import { liveMeshNames } from "../lib/live-names.js";
@@ -325,7 +325,8 @@ function seatExpiry(values, direct) {
325
325
  /** The spawn an `--on` refusal tells the caller to rerun: the persona and `-d` as given, with the
326
326
  * `--space` or `--server` given (#7644). */
327
327
  const spawnRerun = (values, positionals) => onRerun("cotal spawn", values, [...positionals, ...(values.detach === true ? ["-d"] : [])]);
328
- /** Check the public mode and spelling before catalog preparation or identity allocation. */
328
+ /** Check the public mode and spelling before catalog preparation or identity allocation.
329
+ * Return the parsed channel overrides for the foreground policy. */
329
330
  export function validateSpawnArguments(args) {
330
331
  const values = args.values;
331
332
  const handoffRefusal = managedHandoffRefusal();
@@ -344,7 +345,9 @@ export function validateSpawnArguments(args) {
344
345
  if (values.file !== undefined && (args.positionals.length || values.config !== undefined))
345
346
  throw new CommandFailure("refused", "USAGE_INVALID", "choose one positional persona or --file/-f, not multiple explicit persona sources");
346
347
  if (!internal && values.config !== undefined)
347
- throw new CommandFailure("refused", "USAGE_INVALID", "--config is reserved for persisted internal launch callers; use `cotal spawn --file <persona-file>`");
348
+ throw new CommandFailure("refused", "USAGE_INVALID", "--config is reserved for persisted internal launch callers", {
349
+ remedy: "use `cotal spawn <persona>` for a catalog name or `cotal spawn --file <persona-file>` for a file",
350
+ });
348
351
  if (values.file !== undefined) {
349
352
  try {
350
353
  personaFileReference(values.file);
@@ -372,8 +375,12 @@ export function validateSpawnArguments(args) {
372
375
  throw new CommandFailure("refused", "USAGE_INVALID", "choose --harness/-H or the legacy --agent spelling, not both");
373
376
  if (values.detach && direct)
374
377
  throw new CommandFailure("refused", "USAGE_INVALID", "--detach and direct foreground execution are different launch modes");
375
- if (direct && ((!values["dry-run"] && (values.json || values.plain)) || values.creds !== undefined || values.on !== undefined))
376
- throw new CommandFailure("refused", "USAGE_INVALID", "a spawn in this terminal takes no structured receipt, manager credential or manager pin", { remedy: "add -d to launch it through a manager, which returns a receipt once the agent joins", selfContained: true });
378
+ if (direct && ((!values["dry-run"] && (values.json || values.plain)) || values.creds !== undefined || values.on !== undefined)) {
379
+ const without = [...(!values["dry-run"] && values.json ? ["--json"] : []), ...(!values["dry-run"] && values.plain ? ["--plain"] : []), ...(values.creds !== undefined ? ["--creds"] : []), ...(values.on !== undefined ? ["--on"] : [])];
380
+ const foreground = `omit ${without.join(", ")} to launch in this terminal`;
381
+ const managed = values.foreground ? "replace --foreground with -d" : "add -d";
382
+ throw new CommandFailure("refused", "USAGE_INVALID", "a spawn in this terminal takes no structured receipt, manager credential or manager pin", { remedy: internal ? foreground : `${foreground}, or ${managed} to launch through a manager and get a receipt once the agent joins`, selfContained: true });
383
+ }
377
384
  if ((values.restarts === undefined) !== (values["restart-window"] === undefined))
378
385
  throw new CommandFailure("refused", "USAGE_INVALID", "--restarts and --restart-window must be supplied together");
379
386
  if (values.restarts !== undefined) {
@@ -388,7 +395,7 @@ export function validateSpawnArguments(args) {
388
395
  seatExpiry(values, direct);
389
396
  if (!values["dry-run"] && !direct && !values.detach && (values.json || values.plain || inputDisabledByFlag() || !process.stdin.isTTY || !process.stdout.isTTY))
390
397
  throw new CommandFailure("refused", "USAGE_INVALID", "attaching to a manager's launch needs usable input and output terminals before an identity is allocated", { remedy: "add -d to wait for readiness without attaching, or drop --on to run it in this terminal", selfContained: true });
391
- for (const field of ["harness", "agent", "model", "variant", "name"])
398
+ for (const field of ["harness", "agent", "model", "variant", "name", "cwd"])
392
399
  if (values[field] !== undefined && !values[field].trim())
393
400
  throw new CommandFailure("refused", "USAGE_INVALID", `--${field} cannot be empty`);
394
401
  if (values.events && values["no-events"])
@@ -404,10 +411,39 @@ export function validateSpawnArguments(args) {
404
411
  catch {
405
412
  throw new CommandFailure("refused", "USAGE_INVALID", "invalid launch options, native role or tool-sharing selection; use declared keys and unique key=value option pairs");
406
413
  }
414
+ const channels = {
415
+ subscribe: parseCommaList(values.subscribe),
416
+ "allow-subscribe": parseCommaList(values["allow-subscribe"]),
417
+ "allow-publish": parseCommaList(values["allow-publish"]),
418
+ };
419
+ for (const [flag, list] of Object.entries(channels)) {
420
+ for (const channel of list ?? []) {
421
+ try {
422
+ assertValidChannel(channel);
423
+ }
424
+ catch (error) {
425
+ throw new CommandFailure("refused", "USAGE_INVALID", `--${flag}: ${oneLine(error.message)}`, {
426
+ selfContained: true,
427
+ ...(channel.startsWith("#") ? { remedy: `pass the channel without its #, as ${JSON.stringify(channel.slice(1))}` } : {}),
428
+ });
429
+ }
430
+ }
431
+ }
432
+ if (channels.subscribe !== undefined && channels["allow-subscribe"] !== undefined) {
433
+ try {
434
+ resolveReadAcl(channels.subscribe, channels["allow-subscribe"]);
435
+ }
436
+ catch (error) {
437
+ throw new CommandFailure("refused", "USAGE_INVALID", oneLine(error.message), {
438
+ remedy: "include every --subscribe channel in --allow-subscribe", selfContained: true,
439
+ });
440
+ }
441
+ }
407
442
  if (!internal && args.positionals.length > 1)
408
443
  throw new CommandFailure("refused", "USAGE_INVALID", "spawn takes one persona; pass the kickoff request with --prompt/-p");
409
444
  if (!internal && values.config !== undefined && args.positionals.length)
410
445
  throw new CommandFailure("refused", "USAGE_INVALID", "choose one persona input, not both a positional name and --config");
446
+ return channels;
411
447
  }
412
448
  /** Foreground `cotal spawn` resolves its `--agent` connector from the registry (spawn.ts below); on
413
449
  * the published binary nothing static-imports connectors, so the resolved one is materialized as a
@@ -443,12 +479,10 @@ function connectorListed(name) {
443
479
  * reservation reason, and the `_` remedy — before any request leaves. A courtesy only: the
444
480
  * manager door stays the enforcement point; this is why the CLI passes the target mesh's auth
445
481
  * mode rather than restating the grammar (static mode keys the actor on the nkey, not the name). */
446
- function refuseUnmintableNameOrExit(name, userMode) {
482
+ function refuseUnmintableName(name, userMode) {
447
483
  const refusal = spawnNameError(name, { userMode });
448
- if (refusal) {
449
- stderrLine("✗ ", `${refusal}`, c.red);
450
- process.exit(1);
451
- }
484
+ if (refusal)
485
+ throw new CommandFailure("refused", "USAGE_INVALID", refusal, { selfContained: true });
452
486
  }
453
487
  /** Whether a managed launch can reach only this root's own manager: the instance it names, or else
454
488
  * the only one the registry lists, is the one recorded under the target's root. An unread registry
@@ -579,7 +613,7 @@ export async function launchManagedPersona(values, positionals, events, launchOp
579
613
  // resolved manager-side, so the effective identity is `--name` alone — when it is absent the
580
614
  // manager applies the same spawnNameError to the file's `name:` at its own door.
581
615
  if (values.name !== undefined)
582
- refuseUnmintableNameOrExit(values.name, t.mode === "user");
616
+ refuseUnmintableName(values.name, t.mode === "user");
583
617
  const eventsRequired = policy?.events === "required";
584
618
  if (eventsRequired && events === false) {
585
619
  throw new CommandFailure("refused", "PERMISSION_DENIED", `space "${t.space}" requires the event plane by registration policy; no launch was submitted`);
@@ -599,7 +633,7 @@ export async function launchManagedPersona(values, positionals, events, launchOp
599
633
  // can read: ask it, so the carry looks with the connector the launch runs (#2899).
600
634
  const agent = values.agent ?? await launchAgentOrExit(t, on, { name: ref, config: managerConfigRef, defaultAgent });
601
635
  // The carry and its transfer-writer view stay on the mesh selected for this launch.
602
- const claim = await carryTranscriptOrExit({ ...flags, space: t.space, server: t.server }, on, values.resume, agent);
636
+ const claim = await carryTranscript({ ...flags, space: t.space, server: t.server }, on, values.resume, agent);
603
637
  if (claim !== undefined)
604
638
  resumeClaim = { claim, agent };
605
639
  }
@@ -880,7 +914,7 @@ async function unservedClassLaunch(flags, t, agent, at) {
880
914
  recordOperationWarning({ code: "MANAGER_SILENT", target: { space: t.space, managerInstanceId: instanceId }, message: `manager ${instanceId} was skipped: its registration is stale (the broker reports nothing subscribed on its rail; its host is gone and never deregistered)` });
881
915
  if (census?.noApplication && census.unavailable.length) {
882
916
  return new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `no manager of yours takes unpinned launches: installed agent applications are unavailable (${census.unavailable.join("; ")}); nothing was launched`, { ...at,
883
- remedy: `install or repair the reported applications and dependencies on the named manager hosts, with the required executables on the PATH used to start each manager, then restart those managers; for a stack started with \`cotal up\`, run \`cotal manager stop --yes\` then \`cotal up\` from its project folder${census.empty.length ? `; no connectors are installed on ${census.empty.join(", ")}: add one there, such as ${extAddFor(agent ?? DEFAULT_CONNECTOR)}` : ""}` });
917
+ remedy: `install or repair the reported applications and dependencies on the named manager hosts. If the PATH used to start each manager needs to change, restart it under its own supervisor. For a saved manager service, use \`cotal service restart <name> --yes\`. For a foreground \`cotal up\` stack, stop it with \`cotal down --yes\` from its project folder or Ctrl-C in its terminal. This stops the broker and hosted workflow runs and can stop agents. Repeat the original foreground start with the updated PATH${census.empty.length ? `. No connectors are installed on ${census.empty.join(", ")}: add one there, such as ${extAddFor(agent ?? DEFAULT_CONNECTOR)}` : ""}.` });
884
918
  }
885
919
  if (census?.noApplication) {
886
920
  return new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `no manager of yours takes unpinned launches: none ${census.gone.length ? "that answered " : ""}has an agent application installed${census.managers.length ? ` (${census.managers.join(", ")})` : ""}; nothing was launched`, { ...at,
@@ -965,21 +999,33 @@ async function launchAgentOrExit(t, on, fields) {
965
999
  * connector can tell a local session from one that lives on the manager's host, so a connector this
966
1000
  * CLI cannot load is refused.
967
1001
  */
968
- async function carryTranscriptOrExit(flags, on, id, agent) {
1002
+ async function carryTranscript(flags, on, id, agent) {
1003
+ let connector;
1004
+ try {
1005
+ connector = await materializeExtension({ kind: "connector", name: agent });
1006
+ }
1007
+ catch (error) {
1008
+ if (isCommandFailure(error))
1009
+ throw error;
1010
+ if (!connectorListed(agent))
1011
+ throw missingConnector(agent, { space: flags.space });
1012
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `resume: ${oneLine(error.message)}`);
1013
+ }
969
1014
  let found;
970
1015
  try {
971
- await materializeExtension({ kind: "connector", name: agent });
972
- found = registry.resolve("connector", agent).resumeTranscript?.find(id, process.env);
1016
+ found = connector.resumeTranscript?.find(id, process.env);
973
1017
  }
974
- catch (e) {
975
- stderrLine("✗ ", `resume: ${e.message}`, c.red);
976
- process.exit(1);
1018
+ catch (error) {
1019
+ if (isCommandFailure(error))
1020
+ throw error;
1021
+ throw new CommandFailure("refused", "USAGE_INVALID", `resume: ${error.message}`, { selfContained: true });
977
1022
  }
978
1023
  if (found === undefined)
979
1024
  return undefined;
980
1025
  if (on === undefined) {
981
- stderrLine("✗ ", `resume: session ${id} is held on this host, and carrying it needs one manager instance; pass --on <instance>`, c.red);
982
- process.exit(1);
1026
+ throw new CommandFailure("refused", "USAGE_INVALID", `resume: session ${id} is held on this host, and carrying it needs one manager instance`, {
1027
+ remedy: "pass --on <instance>", selfContained: true,
1028
+ });
983
1029
  }
984
1030
  const bytes = readFileSync(found.path);
985
1031
  const sha256 = createHash("sha256").update(bytes).digest("hex");
@@ -1045,7 +1091,7 @@ async function transferWriterOrExit(flags, t, instanceId, hex) {
1045
1091
  */
1046
1092
  export async function spawn(args) {
1047
1093
  const positionals = args.positionals;
1048
- validateSpawnArguments(args);
1094
+ const channels = validateSpawnArguments(args);
1049
1095
  const values = { ...args.values, ...(typeof args.values.harness === "string" ? { agent: args.values.harness } : {}), ...(typeof args.values.file === "string" ? { config: personaFileReference(args.values.file) } : {}) };
1050
1096
  if (values["dry-run"])
1051
1097
  return spawnLaunchPreview({ ...args, values });
@@ -1213,6 +1259,24 @@ export async function spawn(args) {
1213
1259
  stderrLine("✗ ", "--creds is only valid with --detach (it authenticates the manager control call)", c.red);
1214
1260
  process.exit(1);
1215
1261
  }
1262
+ let launchCwd;
1263
+ if (values.cwd !== undefined) {
1264
+ const requestedCwd = resolvePath(values.cwd);
1265
+ let reason;
1266
+ try {
1267
+ launchCwd = realpathSync(requestedCwd);
1268
+ if (!statSync(launchCwd).isDirectory())
1269
+ reason = "is not a directory";
1270
+ }
1271
+ catch (error) {
1272
+ const code = error.code;
1273
+ reason = code === "ENOENT" ? "does not exist" : code === "ENOTDIR" ? "is not a directory" : `cannot be used (${oneLine(error.message)})`;
1274
+ }
1275
+ if (reason !== undefined)
1276
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `--cwd ${JSON.stringify(requestedCwd)} ${reason}. Nothing was launched.`, {
1277
+ target: { path: requestedCwd }, remedy: "pass an existing directory to --cwd",
1278
+ });
1279
+ }
1216
1280
  // An enrollment may bootstrap the stock remote user-mesh record before normal target resolution.
1217
1281
  // Redeem only when the named space is not registered; an existing entry defers redemption until
1218
1282
  // after persona resolution so the response actor can be checked against the requested identity.
@@ -1276,7 +1340,7 @@ export async function spawn(args) {
1276
1340
  // persona — `cotal spawn` with no args launches `<root>/.cotal/agents/default.md`.
1277
1341
  const { ref, from: personaFrom } = spawnPersona(values.config, positionals, { space, preferences: cachedPreferences() });
1278
1342
  const personaProject = resolvePath(target.personaRoot, "..", "..");
1279
- const path = redeemedEnrollment && values.config ? resolvePath(values.config) : agentFilePath(personaProject, ref);
1343
+ const path = values.file !== undefined || (redeemedEnrollment && values.config) ? resolvePath(ref) : agentFilePath(personaProject, ref);
1280
1344
  // The product default of a catalog nothing prepared, as a Cloud space's is until a spawn, is
1281
1345
  // written from the shipped template here and launched. A named or preferred persona is the
1282
1346
  // user's own choice, so one that is missing is still refused.
@@ -1334,7 +1398,7 @@ export async function spawn(args) {
1334
1398
  }
1335
1399
  // #867: same door as the detached path — the effective identity (flag or file) must be mintable
1336
1400
  // before any provision work; core's own refusal names the offender and the `_` remedy.
1337
- refuseUnmintableNameOrExit(requested, target.mode === "user");
1401
+ refuseUnmintableName(requested, target.mode === "user");
1338
1402
  // #581: the same per-role model allowlist the manager enforces on a detached spawn, judged on the
1339
1403
  // effective role, model (flag over file) and launch options before anything is provisioned or launched.
1340
1404
  let cotalConfig;
@@ -1398,18 +1462,36 @@ export async function spawn(args) {
1398
1462
  }
1399
1463
  const binaryPins = { opencode: process.env.COTAL_OPENCODE_BIN, codex: process.env.COTAL_CODEX_BIN };
1400
1464
  const missing = (connector.requires ?? []).filter((bin) => !resolveOnPath(binaryPins[bin]?.trim() || bin));
1401
- if (missing.length)
1402
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `${agentType} needs ${missing.join(", ")} on PATH; nothing was launched`, {
1465
+ if (missing.length) {
1466
+ const binaries = missing.join(", ");
1467
+ const guide = ["claude", "codex", "opencode", "jcode", "hermes", "pi"].includes(agentType) ? `https://docs.cotal.ai/docs/connect-${agentType}/` : "https://docs.cotal.ai/docs/connectors/";
1468
+ const message = `${agentType} needs ${binaries} on PATH; nothing was launched`;
1469
+ const install = `Follow ${guide} to install ${binaries}`;
1470
+ if (agentType === "hermes") {
1471
+ if (process.env.COTAL_HERMES_ADOPT_HOME?.trim()) {
1472
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", message, {
1473
+ target: { space, path },
1474
+ remedy: `${install} and check the adopted Hermes profile's requirements before retrying.`,
1475
+ });
1476
+ }
1477
+ if (!model) {
1478
+ const example = codeSpan(`${displayCmd()} spawn --harness hermes --no-events --model <model>`);
1479
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `${message}. A managed Hermes profile needs a model. Set one with --model or the agent file's model: field.`, {
1480
+ target: { space, path },
1481
+ remedy: `${install}. For a basic launch: ${example}`,
1482
+ });
1483
+ }
1484
+ }
1485
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", message, {
1403
1486
  target: { space, path },
1404
- remedy: `Follow ${["claude", "codex", "opencode", "jcode", "hermes", "pi"].includes(agentType) ? `https://docs.cotal.ai/docs/connect-${agentType}/` : "https://docs.cotal.ai/docs/connectors/"} to install ${missing.join(", ")}, then retry: \`${displayCmd()} spawn ${args.raw.map(shellWord).join(" ")}\``,
1487
+ remedy: `${install}, then retry: \`${displayCmd()} spawn ${args.raw.map(shellWord).join(" ")}\``,
1405
1488
  });
1489
+ }
1406
1490
  if (variant && !connector.supportsModelVariant) {
1407
- stderrLine("✗ ", `${agentType} connector does not support model variants (variant)`, c.red);
1408
- process.exit(1);
1491
+ throw new CommandFailure("refused", "USAGE_INVALID", `${agentType} connector does not support model variants (variant)`, { target: { space, path } });
1409
1492
  }
1410
1493
  if (values.prompt !== undefined && !connector.supportsPrompt) {
1411
- stderrLine("✗ ", `${agentType} connector does not support an initial prompt (prompt)`, c.red);
1412
- process.exit(1);
1494
+ throw new CommandFailure("refused", "USAGE_INVALID", `${agentType} connector does not support an initial prompt (prompt)`, { target: { space, path } });
1413
1495
  }
1414
1496
  // Which of the operator's personal MCP servers to share with this agent: declared in the cotal
1415
1497
  // config (global ~/.config/cotal + the target mesh's .cotal), narrowed by an optional
@@ -1449,16 +1531,16 @@ export async function spawn(args) {
1449
1531
  // connector (COTAL_SUBSCRIBE / COTAL_ALLOW_*) so the session's runtime read/post set matches its
1450
1532
  // credentials. One source, so a `--subscribe` override can't land in the creds yet be lost at
1451
1533
  // runtime (the connector would otherwise read only the persona file and miss the override).
1452
- let subscribe = parseCommaList(values.subscribe) ?? def.subscribe;
1534
+ let subscribe = channels.subscribe ?? def.subscribe;
1453
1535
  let allowSubscribe;
1454
1536
  try {
1455
- allowSubscribe = resolveReadAcl(subscribe ?? [], parseCommaList(values["allow-subscribe"]) ?? def.allowSubscribe);
1537
+ allowSubscribe = resolveReadAcl(subscribe ?? [], channels["allow-subscribe"] ?? def.allowSubscribe);
1456
1538
  }
1457
1539
  catch (e) {
1458
1540
  stderrLine("✗ ", `${e.message}`, c.red);
1459
1541
  process.exit(1);
1460
1542
  }
1461
- let allowPublish = parseCommaList(values["allow-publish"]) ?? def.allowPublish;
1543
+ let allowPublish = channels["allow-publish"] ?? def.allowPublish;
1462
1544
  // The AG-UI event plane, refused HERE for the same reason the manager refuses it before
1463
1545
  // provisioning: a connector that cannot emit must stop the launch while there is still nothing to
1464
1546
  // roll back. The GRANT cannot be derived yet, because it is keyed on the principal and in user
@@ -1472,6 +1554,22 @@ export async function spawn(args) {
1472
1554
  : `✗ connector "${connector.name}" does not publish an AG-UI event plane; omit --events to launch it without one`));
1473
1555
  process.exit(1);
1474
1556
  }
1557
+ const launchOpts = {
1558
+ space, name, role, servers: server, configPath: path,
1559
+ model, variant, launchOptions, subscribe, allowSubscribe, allowPublish,
1560
+ endpoints: copyPersonaEndpoints(def.endpoints) ?? [], prompt: values.prompt,
1561
+ resume: values.resume, events: launchEvents, eventPayloads, eventsRequired,
1562
+ mcpServers, mcpServersExclusive: shareTools !== undefined, envAllow,
1563
+ // Keep the foreground directory on the child spawn. Connector cwd marks a supervised seat.
1564
+ workspaceRoot: target.root,
1565
+ };
1566
+ try {
1567
+ if (connector.supportsLaunchValidation)
1568
+ connector.buildLaunch({ ...launchOpts, validateOnly: true });
1569
+ }
1570
+ catch (error) {
1571
+ throw new CommandFailure("refused", "USAGE_INVALID", rejectionText(error), { target: { space, path } });
1572
+ }
1475
1573
  // A REMOTE user mesh (registered with `meshes add --from`) that advertises a provisioning
1476
1574
  // endpoint: the mesh grants the row and pre-creates the durables inside the owner's envelope,
1477
1575
  // because the material to do that locally — the space's owner secret and account signer — only
@@ -1493,8 +1591,8 @@ export async function spawn(args) {
1493
1591
  const endpointCapabilities = lowerPersonaEndpoints(def.endpoints);
1494
1592
  // Said once every check above has passed, so a refusal is never read as a launch that started.
1495
1593
  console.error(renderReport({ space, sections: [{ title: "Direct application", blocks: [{ kind: "lines", lines: ["This is native foreground execution, not a detachable Cotal view.", { text: "Native exit, Ctrl-C or terminal loss may end this process. No crash or reboot survival is promised.", tone: "hint" }] }] }] }, "rich", process.stderr));
1496
- // Auth mode provisions the identity + writes its creds to disk BEFORE the connector validates the
1497
- // launch (e.g. `buildLaunch` throws on a rejected `--opt`) and before the child execs. The SAME
1594
+ // Auth mode provisions the identity and writes its creds after launch-argument validation, but
1595
+ // launch materialization or child exec can still fail. The SAME
1498
1596
  // retirement serves a failed provisioning or launch (rollback) and the normal foreground
1499
1597
  // departure: each spawn mints a fresh identity, so an exited agent's footprint (creds file, DM/DLV
1500
1598
  // durables, ACL row) is dead weight no future spawn reuses — mirror the manager's `deprovision`
@@ -1698,41 +1796,26 @@ export async function spawn(args) {
1698
1796
  console.error(`"${requested}" is already on the mesh - spawning as ${name} instead`);
1699
1797
  if (target.source === "registry" || target.source === "current")
1700
1798
  console.error(c.dim(`→ joining mesh ${space} (${server}) as ${name}`));
1701
- spec = connector.buildLaunch({
1702
- space,
1703
- name,
1704
- role,
1705
- id,
1706
- creds: credsPath,
1707
- ...(acceptedToken !== undefined ? { acceptedToken } : {}),
1708
- userAuth,
1709
- lifecycleUid,
1710
- servers: server,
1711
- configPath: path,
1712
- model,
1713
- variant,
1714
- launchOptions,
1715
- subscribe,
1716
- allowSubscribe,
1717
- allowPublish,
1718
- // The endpoint commands this launch minted (on a static mesh) or names (on an open one), so the
1719
- // session reads them from the launch rather than from a persona file that may change.
1720
- endpoints: copyPersonaEndpoints(def.endpoints) ?? [],
1721
- prompt: values.prompt,
1722
- // Fork an existing session into the mesh. `prompt + resume` is a supported combo (claude accepts
1723
- // the positional prompt alongside `--resume … --fork-session`); an unsupported connector throws.
1724
- resume: values.resume,
1725
- events: launchEvents,
1726
- eventPayloads,
1727
- eventsRequired,
1728
- mcpServers,
1729
- mcpServersExclusive: shareTools !== undefined,
1730
- envAllow,
1731
- // Where a connector that keeps per-agent local state roots it. The manager passes its own
1732
- // workspace root here; the foreground path did not, so an armed session refused at launch
1733
- // construction because its write-ahead log had nowhere to live that a later start would look.
1734
- workspaceRoot: target.root,
1735
- });
1799
+ try {
1800
+ spec = connector.buildLaunch({
1801
+ ...launchOpts,
1802
+ name,
1803
+ id,
1804
+ creds: credsPath,
1805
+ ...(acceptedToken !== undefined ? { acceptedToken } : {}),
1806
+ userAuth,
1807
+ lifecycleUid,
1808
+ // Provisioning can replace the requested ACLs or add an event grant.
1809
+ subscribe,
1810
+ allowSubscribe,
1811
+ allowPublish,
1812
+ });
1813
+ }
1814
+ catch (error) {
1815
+ if (error instanceof CommandFailure)
1816
+ throw error;
1817
+ throw new CommandFailure("refused", "USAGE_INVALID", rejectionText(error), { target: { space, path } });
1818
+ }
1736
1819
  applyHandoffManagerInstance(spec, handoffManagerInstanceId);
1737
1820
  artifacts = spec.artifacts;
1738
1821
  scrubEnrollmentEnv(spec.env);
@@ -1760,7 +1843,7 @@ export async function spawn(args) {
1760
1843
  env: spec.env ?? {},
1761
1844
  // `--cwd` roots the agent at another folder/repo (launch-grammar parity with --detach); a
1762
1845
  // relative path resolves against the invoking shell's cwd. Omitted → inherit this cwd.
1763
- cwd: values.cwd ? resolvePath(values.cwd) : undefined,
1846
+ cwd: launchCwd,
1764
1847
  });
1765
1848
  }
1766
1849
  catch (e) {