@cotal-ai/cli 0.172.1 → 0.173.0

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 (237) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +34 -20
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +8 -6
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/backup.d.ts.map +1 -1
  8. package/dist/commands/backup.js +15 -10
  9. package/dist/commands/backup.js.map +1 -1
  10. package/dist/commands/channel-members.d.ts.map +1 -1
  11. package/dist/commands/channel-members.js +2 -1
  12. package/dist/commands/channel-members.js.map +1 -1
  13. package/dist/commands/channels.d.ts.map +1 -1
  14. package/dist/commands/channels.js +19 -9
  15. package/dist/commands/channels.js.map +1 -1
  16. package/dist/commands/clean.d.ts.map +1 -1
  17. package/dist/commands/clean.js +2 -3
  18. package/dist/commands/clean.js.map +1 -1
  19. package/dist/commands/doctor.js +5 -2
  20. package/dist/commands/doctor.js.map +1 -1
  21. package/dist/commands/down-preserve.d.ts +74 -0
  22. package/dist/commands/down-preserve.d.ts.map +1 -0
  23. package/dist/commands/down-preserve.js +626 -0
  24. package/dist/commands/down-preserve.js.map +1 -0
  25. package/dist/commands/down.d.ts +2 -61
  26. package/dist/commands/down.d.ts.map +1 -1
  27. package/dist/commands/down.js +26 -617
  28. package/dist/commands/down.js.map +1 -1
  29. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  30. package/dist/commands/endpoint-authoring.js +16 -4
  31. package/dist/commands/endpoint-authoring.js.map +1 -1
  32. package/dist/commands/history-clear.d.ts.map +1 -1
  33. package/dist/commands/history-clear.js +10 -3
  34. package/dist/commands/history-clear.js.map +1 -1
  35. package/dist/commands/history-limit.js +2 -2
  36. package/dist/commands/history-limit.js.map +1 -1
  37. package/dist/commands/history.d.ts.map +1 -1
  38. package/dist/commands/history.js +49 -19
  39. package/dist/commands/history.js.map +1 -1
  40. package/dist/commands/join.d.ts.map +1 -1
  41. package/dist/commands/join.js +30 -7
  42. package/dist/commands/join.js.map +1 -1
  43. package/dist/commands/manager-service.d.ts.map +1 -1
  44. package/dist/commands/manager-service.js +5 -1
  45. package/dist/commands/manager-service.js.map +1 -1
  46. package/dist/commands/meshes-add.d.ts +4 -1
  47. package/dist/commands/meshes-add.d.ts.map +1 -1
  48. package/dist/commands/meshes-add.js +19 -1
  49. package/dist/commands/meshes-add.js.map +1 -1
  50. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  51. package/dist/commands/meshes-wizard.js +5 -5
  52. package/dist/commands/meshes-wizard.js.map +1 -1
  53. package/dist/commands/meshes.d.ts.map +1 -1
  54. package/dist/commands/meshes.js +4 -3
  55. package/dist/commands/meshes.js.map +1 -1
  56. package/dist/commands/persona-remote.js +2 -2
  57. package/dist/commands/persona-remote.js.map +1 -1
  58. package/dist/commands/persona.d.ts.map +1 -1
  59. package/dist/commands/persona.js +13 -5
  60. package/dist/commands/persona.js.map +1 -1
  61. package/dist/commands/personas.d.ts.map +1 -1
  62. package/dist/commands/personas.js +4 -1
  63. package/dist/commands/personas.js.map +1 -1
  64. package/dist/commands/reset-space-apply.js +2 -2
  65. package/dist/commands/reset-space-apply.js.map +1 -1
  66. package/dist/commands/reset-store-apply.d.ts +2 -2
  67. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  68. package/dist/commands/reset-store-apply.js +10 -7
  69. package/dist/commands/reset-store-apply.js.map +1 -1
  70. package/dist/commands/reset.js +2 -2
  71. package/dist/commands/reset.js.map +1 -1
  72. package/dist/commands/send.d.ts.map +1 -1
  73. package/dist/commands/send.js +21 -9
  74. package/dist/commands/send.js.map +1 -1
  75. package/dist/commands/service-actions.d.ts.map +1 -1
  76. package/dist/commands/service-actions.js +15 -4
  77. package/dist/commands/service-actions.js.map +1 -1
  78. package/dist/commands/service-registry.d.ts.map +1 -1
  79. package/dist/commands/service-registry.js +16 -5
  80. package/dist/commands/service-registry.js.map +1 -1
  81. package/dist/commands/space-delete.d.ts.map +1 -1
  82. package/dist/commands/space-delete.js +46 -31
  83. package/dist/commands/space-delete.js.map +1 -1
  84. package/dist/commands/space-registration.d.ts +4 -3
  85. package/dist/commands/space-registration.d.ts.map +1 -1
  86. package/dist/commands/space-registration.js +65 -45
  87. package/dist/commands/space-registration.js.map +1 -1
  88. package/dist/commands/space.d.ts.map +1 -1
  89. package/dist/commands/space.js +18 -6
  90. package/dist/commands/space.js.map +1 -1
  91. package/dist/commands/spawn-flags.d.ts +205 -0
  92. package/dist/commands/spawn-flags.d.ts.map +1 -0
  93. package/dist/commands/spawn-flags.js +34 -0
  94. package/dist/commands/spawn-flags.js.map +1 -0
  95. package/dist/commands/spawn-foreground.d.ts +74 -0
  96. package/dist/commands/spawn-foreground.d.ts.map +1 -0
  97. package/dist/commands/spawn-foreground.js +355 -0
  98. package/dist/commands/spawn-foreground.js.map +1 -0
  99. package/dist/commands/spawn-managed-launch.d.ts +43 -0
  100. package/dist/commands/spawn-managed-launch.d.ts.map +1 -0
  101. package/dist/commands/spawn-managed-launch.js +631 -0
  102. package/dist/commands/spawn-managed-launch.js.map +1 -0
  103. package/dist/commands/spawn-preview.d.ts.map +1 -1
  104. package/dist/commands/spawn-preview.js +10 -7
  105. package/dist/commands/spawn-preview.js.map +1 -1
  106. package/dist/commands/spawn.d.ts +6 -220
  107. package/dist/commands/spawn.d.ts.map +1 -1
  108. package/dist/commands/spawn.js +21 -1009
  109. package/dist/commands/spawn.js.map +1 -1
  110. package/dist/commands/stack-down.d.ts.map +1 -1
  111. package/dist/commands/stack-down.js +7 -4
  112. package/dist/commands/stack-down.js.map +1 -1
  113. package/dist/commands/stack-up.d.ts +5 -1
  114. package/dist/commands/stack-up.d.ts.map +1 -1
  115. package/dist/commands/stack-up.js +46 -15
  116. package/dist/commands/stack-up.js.map +1 -1
  117. package/dist/commands/status-delivery.d.ts +9 -0
  118. package/dist/commands/status-delivery.d.ts.map +1 -0
  119. package/dist/commands/status-delivery.js +19 -0
  120. package/dist/commands/status-delivery.js.map +1 -0
  121. package/dist/commands/status-legacy.d.ts +7 -0
  122. package/dist/commands/status-legacy.d.ts.map +1 -0
  123. package/dist/commands/status-legacy.js +35 -0
  124. package/dist/commands/status-legacy.js.map +1 -0
  125. package/dist/commands/status-stop-impact.d.ts +3 -0
  126. package/dist/commands/status-stop-impact.d.ts.map +1 -0
  127. package/dist/commands/status-stop-impact.js +34 -0
  128. package/dist/commands/status-stop-impact.js.map +1 -0
  129. package/dist/commands/status.d.ts.map +1 -1
  130. package/dist/commands/status.js +48 -105
  131. package/dist/commands/status.js.map +1 -1
  132. package/dist/commands/team-agent-apply.js +11 -11
  133. package/dist/commands/team-agent-apply.js.map +1 -1
  134. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  135. package/dist/commands/team-boot-controller.js +21 -4
  136. package/dist/commands/team-boot-controller.js.map +1 -1
  137. package/dist/commands/team-deploy-apply.js +2 -2
  138. package/dist/commands/team-deploy-apply.js.map +1 -1
  139. package/dist/commands/team.d.ts.map +1 -1
  140. package/dist/commands/team.js +37 -42
  141. package/dist/commands/team.js.map +1 -1
  142. package/dist/commands/telemetry.d.ts +1 -1
  143. package/dist/commands/telemetry.d.ts.map +1 -1
  144. package/dist/commands/telemetry.js +17 -7
  145. package/dist/commands/telemetry.js.map +1 -1
  146. package/dist/commands/up-target.d.ts +7 -0
  147. package/dist/commands/up-target.d.ts.map +1 -0
  148. package/dist/commands/up-target.js +42 -0
  149. package/dist/commands/up-target.js.map +1 -0
  150. package/dist/commands/up.d.ts +5 -10
  151. package/dist/commands/up.d.ts.map +1 -1
  152. package/dist/commands/up.js +55 -156
  153. package/dist/commands/up.js.map +1 -1
  154. package/dist/commands/update-caches.d.ts +4 -0
  155. package/dist/commands/update-caches.d.ts.map +1 -0
  156. package/dist/commands/update-caches.js +82 -0
  157. package/dist/commands/update-caches.js.map +1 -0
  158. package/dist/commands/update.d.ts.map +1 -1
  159. package/dist/commands/update.js +35 -121
  160. package/dist/commands/update.js.map +1 -1
  161. package/dist/commands/watch.d.ts.map +1 -1
  162. package/dist/commands/watch.js +5 -2
  163. package/dist/commands/watch.js.map +1 -1
  164. package/dist/commands/whoami.d.ts.map +1 -1
  165. package/dist/commands/whoami.js +3 -2
  166. package/dist/commands/whoami.js.map +1 -1
  167. package/dist/help.d.ts +1 -1
  168. package/dist/help.d.ts.map +1 -1
  169. package/dist/help.js +5 -2
  170. package/dist/help.js.map +1 -1
  171. package/dist/index.d.ts.map +1 -1
  172. package/dist/index.js +4 -2
  173. package/dist/index.js.map +1 -1
  174. package/dist/lib/broker-log.d.ts +8 -0
  175. package/dist/lib/broker-log.d.ts.map +1 -0
  176. package/dist/lib/broker-log.js +27 -0
  177. package/dist/lib/broker-log.js.map +1 -0
  178. package/dist/lib/choose-target.d.ts.map +1 -1
  179. package/dist/lib/choose-target.js +12 -9
  180. package/dist/lib/choose-target.js.map +1 -1
  181. package/dist/lib/credential-authority.d.ts.map +1 -1
  182. package/dist/lib/credential-authority.js +22 -5
  183. package/dist/lib/credential-authority.js.map +1 -1
  184. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  185. package/dist/lib/endpoint-errors.js +9 -2
  186. package/dist/lib/endpoint-errors.js.map +1 -1
  187. package/dist/lib/persona-files.d.ts.map +1 -1
  188. package/dist/lib/persona-files.js +2 -3
  189. package/dist/lib/persona-files.js.map +1 -1
  190. package/dist/lib/restore.d.ts +2 -1
  191. package/dist/lib/restore.d.ts.map +1 -1
  192. package/dist/lib/restore.js +4 -3
  193. package/dist/lib/restore.js.map +1 -1
  194. package/dist/lib/service-preset-target.d.ts.map +1 -1
  195. package/dist/lib/service-preset-target.js +6 -2
  196. package/dist/lib/service-preset-target.js.map +1 -1
  197. package/dist/lib/service-presets.d.ts +2 -0
  198. package/dist/lib/service-presets.d.ts.map +1 -1
  199. package/dist/lib/service-presets.js +19 -2
  200. package/dist/lib/service-presets.js.map +1 -1
  201. package/dist/lib/spawn-defaults.d.ts +7 -0
  202. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  203. package/dist/lib/spawn-defaults.js +16 -0
  204. package/dist/lib/spawn-defaults.js.map +1 -1
  205. package/dist/lib/stack-journal.d.ts +4 -4
  206. package/dist/lib/stack-journal.d.ts.map +1 -1
  207. package/dist/lib/stack-journal.js +16 -6
  208. package/dist/lib/stack-journal.js.map +1 -1
  209. package/dist/lib/store-dir.d.ts +3 -1
  210. package/dist/lib/store-dir.d.ts.map +1 -1
  211. package/dist/lib/store-dir.js +20 -4
  212. package/dist/lib/store-dir.js.map +1 -1
  213. package/dist/lib/team-deploy-inspection.d.ts +2 -1
  214. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  215. package/dist/lib/team-deploy-inspection.js +6 -1
  216. package/dist/lib/team-deploy-inspection.js.map +1 -1
  217. package/dist/lib/up-broker-address.d.ts +7 -0
  218. package/dist/lib/up-broker-address.d.ts.map +1 -0
  219. package/dist/lib/up-broker-address.js +76 -0
  220. package/dist/lib/up-broker-address.js.map +1 -0
  221. package/dist/lib/up-report.d.ts +2 -0
  222. package/dist/lib/up-report.d.ts.map +1 -1
  223. package/dist/lib/up-report.js +8 -1
  224. package/dist/lib/up-report.js.map +1 -1
  225. package/dist/lib/update-connector-config.d.ts +6 -0
  226. package/dist/lib/update-connector-config.d.ts.map +1 -0
  227. package/dist/lib/update-connector-config.js +44 -0
  228. package/dist/lib/update-connector-config.js.map +1 -0
  229. package/dist/seed/launch.d.ts +1 -1
  230. package/dist/seed/launch.d.ts.map +1 -1
  231. package/dist/seed/launch.js +3 -3
  232. package/dist/seed/launch.js.map +1 -1
  233. package/dist/seed/reconcile.d.ts +1 -1
  234. package/dist/seed/reconcile.d.ts.map +1 -1
  235. package/dist/seed/reconcile.js +28 -11
  236. package/dist/seed/reconcile.js.map +1 -1
  237. package/package.json +4 -4
@@ -1,35 +1,34 @@
1
1
  import { spawn as spawnProcess } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { readFileSync, realpathSync, rmSync, statSync } from "node:fs";
4
- import { constants as osConstants, hostname } from "node:os";
2
+ import { realpathSync, rmSync, statSync } from "node:fs";
3
+ import { constants as osConstants } from "node:os";
5
4
  import { resolve as resolvePath } from "node:path";
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
- import { readManagedLaunch, requestManagedLaunch } from "@cotal-ai/workspace/launch";
5
+ import { assertValidChannel, assertValidRole, connectorServers, spawnEnvAllow, deprovisionAgent, discardLaunchArtifacts, reclaimWithChild, loadCotalConfig, modelPolicyRefusal, mintCreds, newIdentity, DEV_OWNER, parseShareSelection, assertLifecycleToken, mintLifecycleUid, MANAGED_HANDOFF_FILE_ENV, parseManagedLifecycleHandoff, provisionAgent, lowerPersonaEndpoints, copyPersonaEndpoints, registry, resolveAuthProvider, resolveReadAcl, peerLabel, attemptCleanup, describeCleanupFailures, rejectionText, } from "@cotal-ai/core";
6
+ import { parseCommaList, CommandFailure, loadLaunchPersonaFile, personaFileReference, PersonaSourceError, inputDisabledByFlag, presentationOf, renderReport, agentLifecycleSecretFilePaths, agentSecretKeyForFile, cachedPreferences, findMesh, materializeSecretToFile, mergeLaunchOptions, parseLaunchOptions, preflightOrThrow, provenance, resolveAgentType, resolveOnPath, resolveTargetOrThrow, spaceKey, workspaceSecretStore, refreshRegistrationPolicy, oneLine, codeSpan, activateTerminalSeat, issueTerminalSeat, retireTerminalSeat, seatExpiryAt, } from "@cotal-ai/workspace";
9
7
  import { c, stderrLine } from "../ui.js";
10
- import { liveMeshNames } from "../lib/live-names.js";
11
8
  import { withProvisioner } from "../lib/provisioner.js";
12
9
  import { displayCmd } from "../lib/self-exec.js";
13
- import { entryScript } from "../seed/paths.js";
14
10
  import { completedFlagValue, completingFlagValue, hasCompletedFlagValue, positionalsForCompletion } from "../lib/completion.js";
15
11
  import { preflightOrExit, resolveTargetOrExit } from "../lib/connect.js";
16
- import { runningStackManagerPid, stackManagerAbsent, stackManagerStarting } from "../lib/stack-journal.js";
17
- import { cliControl, failIfNotOk, onInstance, onRerun } from "../lib/control.js";
18
- import { askManagerFolder, askSpawnPlace, managerPin, managerSelection, managersWithPersona, rerunOn, rerunWithCwd } from "../lib/manager-choice.js";
12
+ import { onInstance } from "../lib/control.js";
13
+ import { askSpawnPlace } from "../lib/manager-choice.js";
19
14
  import { canPrompt } from "./meshes-wizard.js";
20
15
  import { listDeclaredChannels, listDeclaredRoles, listPersonaNames } from "../lib/personas.js";
21
16
  import { personaCatalog } from "../lib/persona-files.js";
22
- import { callerHarness, missingConnector, missingPersona, spawnPersona, spawnUsesManager } from "../lib/spawn-defaults.js";
17
+ import { callerHarness, checkSpawnExpiryTarget, directPersonaPath, missingConnector, missingPersona, spawnPersona, spawnUsesManager } from "../lib/spawn-defaults.js";
23
18
  import { writeDefaultPersonaForLaunch } from "../lib/default-persona.js";
24
19
  import { spawnLaunchPreview } from "./spawn-preview.js";
25
20
  import { protectedCredentialReference, readLocalRecordSource } from "../lib/protected-records.js";
26
- import { attachSeat, joinedAgentRows, psSeatLabel } from "./agents.js";
27
- import { AgentAlreadyRunning, heldAnswer, settleHeldName } from "../lib/held-name.js";
21
+ import { AgentAlreadyRunning } from "../lib/held-name.js";
28
22
  import { shellWord } from "../lib/endpoint-errors.js";
29
- import { extensionNames, materializeExtension, preflightRuntime } from "../ext-loader.js";
23
+ import { extensionNames, materializeExtension } from "../ext-loader.js";
30
24
  import { claimManagedHandoff, holdsManagedHandoff, managedHandoffRefusal } from "../managed-handoff.js";
31
- import { askManager, describeUnanswered, liveManagerIds, managerRailGone, refuseUnregisteredManager, refuseWithoutLiveManager, START_TIMEOUT_MS, startStackManagerRemedy, withControlConnection } from "@cotal-ai/workspace/control";
32
- import { ENROLLMENT_URL_ENV, ENROLLMENT_FILE_ENV, stripTrailingNewline, enrollmentInput, scrubEnrollmentEnv, applyHandoffManagerInstance, checkEnrollmentBundle, HANDOFF_REFUSALS, handoffEnrollmentBundle, registerEnrollmentMesh, checkRemoteAgentMaterial, shredAgentMaterial, noExchangeEndpoint, } from "./spawn-enrollment.js";
25
+ import { ENROLLMENT_URL_ENV, ENROLLMENT_FILE_ENV, stripTrailingNewline, enrollmentInput, scrubEnrollmentEnv, applyHandoffManagerInstance, checkEnrollmentBundle, HANDOFF_REFUSALS, handoffEnrollmentBundle, registerEnrollmentMesh, noExchangeEndpoint, } from "./spawn-enrollment.js";
26
+ import { spawnFlags, spawnRerun } from "./spawn-flags.js";
27
+ import { connectorListed, refuseUnmintableName, launchManagedPersona, reportAlreadyRunning } from "./spawn-managed-launch.js";
28
+ import { uniqueMeshName, provisionFreshForeground, provisionRemoteUserForeground, provisionUserForeground } from "./spawn-foreground.js";
29
+ export { runBearerPreflight } from "./spawn-foreground.js";
30
+ export { launchServedHere, managedLaunchView, launchManagedPersona } from "./spawn-managed-launch.js";
31
+ export { spawnFlags } from "./spawn-flags.js";
33
32
  export { enrollmentInput, scrubEnrollmentEnv, applyHandoffManagerInstance, checkEnrollmentBundle, handoffEnrollmentBundle } from "./spawn-enrollment.js";
34
33
  /** Completion for `cotal spawn` — `--space <TAB>` lists the running meshes, and the first positional
35
34
  * is a persona from the mesh this spawn would target. Resolved OFFLINE (registry + `current`, no
@@ -94,77 +93,6 @@ function declaredFrom(argv, list) {
94
93
  return list(root);
95
94
  }
96
95
  export { spawnPersona } from "../lib/spawn-defaults.js";
97
- /**
98
- * Auto-number `requested` past any peer already present on the mesh (foo → foo_2 → foo_3) — the same
99
- * series the manager's spawn funnel uses (firstFreeName). Foreground `cotal spawn` doesn't go through
100
- * the manager, so it has no name reservation: this is a best-effort, advisory check. It connects a
101
- * transient presence-watching endpoint, lets the roster settle, and snapshots the live names; two
102
- * simultaneous `cotal spawn`s can still race onto the same number. If the mesh is unreachable the
103
- * agent couldn't join it anyway, so dedup is skipped and the requested name stands.
104
- */
105
- async function uniqueMeshName(requested, target) {
106
- const taken = await liveMeshNames(target);
107
- return taken ? firstFreeName(requested, (n) => taken.has(n)) : requested;
108
- }
109
- /** Only an occupied actor is retryable; authorization and provisioning failures stay failures.
110
- * Thrown only where the collision is found before anything is launched, issued or redeemed, so
111
- * it is a refusal. */
112
- class ForegroundActorCollision extends CommandFailure {
113
- constructor(message) {
114
- super("refused", "CONFLICT", message);
115
- }
116
- }
117
- async function provisionFreshForeground(requested, autoName, userMode, provision) {
118
- const occupied = new Set();
119
- for (;;) {
120
- let name;
121
- try {
122
- // The cap belongs to user mode alone, where the numbered name is the actor. Static and open
123
- // mode key the actor on the minted nkey, so a numbered name there has no length to fit.
124
- name = firstFreeName(requested, (candidate) => occupied.has(candidate), userMode ? { actorBound: true } : undefined);
125
- }
126
- catch (e) {
127
- // The series stops at the actor bound, so a base whose every fitting candidate is taken is a
128
- // refusal, not a crash: nothing has been launched, issued or redeemed yet.
129
- throw new CommandFailure("refused", "CONFLICT", e instanceof Error ? e.message : String(e));
130
- }
131
- try {
132
- return { name, provisioned: await provision(name) };
133
- }
134
- catch (e) {
135
- if (!autoName || !(e instanceof ForegroundActorCollision || e instanceof AgentGrantConflictError || e instanceof AgentAlreadyRunning))
136
- throw e;
137
- occupied.add(name);
138
- }
139
- }
140
- }
141
- /** `cotal spawn`'s grammar: the application in this terminal by default, a manager's launch only
142
- * with `--detach` or `--on`, and one positional persona or explicit persona file. Declared `as const` so the values cast
143
- * below is compile-checked against exactly these specs. Foreground and detached parse the SAME
144
- * flags — the old `spawn` vs `start` ability drift is structurally gone. */
145
- export const spawnFlags = [
146
- spaceFlag,
147
- serverFlag,
148
- { ...credsFlag, description: "control-caller creds for an off-registry manager (with --detach or --on)" },
149
- ...launchFlags,
150
- { name: "harness", short: "H", type: "string", value: "<connector>", description: "application connector; an explicit flag wins over persona and saved defaults" },
151
- { name: "foreground", type: "boolean", description: "run the application in this terminal, as a spawn without --detach or --on does; terminal exit may end it" },
152
- { name: "restarts", type: "string", value: "<n>", description: "with --detach or --on: maximum manager-supervised restarts in the selected restart window" },
153
- { name: "restart-window", type: "string", value: "<ms>", description: "time window for --restarts; both flags are required together" },
154
- jsonFlag, plainFlag,
155
- { name: "detach", type: "boolean", short: "d", description: "launch through a manager, await readiness and return without attaching" },
156
- { name: "live-only", type: "boolean", description: "foreground only: skip the durable backstop (no read-ACL row; messages missed while disconnected are not replayed)" },
157
- { name: "expires-in", type: "string", value: "<seconds>", description: "foreground only, static mesh: end this seat's credential after this many seconds; omitted, it has no expiry and ends when the seat leaves cleanly" },
158
- { name: "expires-at", type: "string", value: "<unix-seconds>", description: "foreground only, static mesh: end this seat's credential at this time; never with --expires-in" },
159
- { name: "file", type: "string", short: "f", value: "<persona-file>", description: "persona file on the execution host; never a manifest deploy or implicit upload" },
160
- { name: "dry-run", type: "boolean", description: "preview the launch without allocation, provisioning or starting an application" },
161
- { name: "enrollment-file", type: "string", value: "<private-file>", description: "foreground only: protected file holding this one seat's enrollment URL; never print or forward it" },
162
- { name: "allow-stale", type: "string", value: "<a,b>", description: "refused: a manifest deployment option; use `cotal team deploy <file>`" },
163
- { name: "runtime", type: "string", value: "<name>", description: "terminal runtime for this one managed seat; omitted, the serving manager uses its own" },
164
- { name: "on", type: "string", value: "<instance>", description: "launch through this manager instance, by the id `ps` prints, and attach; with --detach, return once it joins" },
165
- { name: "expect-owner", type: "string", value: "<u_…>", description: `with ${MANAGED_HANDOFF_FILE_ENV}: the owner the managed handoff must carry` },
166
- { name: "expect-lifecycle-uid", type: "string", value: "<uid>", description: `with ${MANAGED_HANDOFF_FILE_ENV}: the lifecycle UID the managed handoff must carry` },
167
- ];
168
96
  /** The expiry a seat started in this terminal asked for, in unix seconds, or `undefined` for none.
169
97
  * A managed seat's credential is renewed by its manager, so the flags belong to this terminal. */
170
98
  function seatExpiry(values, direct) {
@@ -172,9 +100,6 @@ function seatExpiry(values, direct) {
172
100
  throw new CommandFailure("refused", "USAGE_INVALID", "--expires-in and --expires-at set the expiry of a seat this terminal starts; a manager renews its own seats' credentials", { remedy: "drop the flag, or drop -d and --on to run the seat here" });
173
101
  return seatExpiryAt(values);
174
102
  }
175
- /** The spawn an `--on` refusal tells the caller to rerun: the persona and `-d` as given, with the
176
- * `--space` or `--server` given (#7644). */
177
- const spawnRerun = (values, positionals) => onRerun("cotal spawn", values, [...positionals, ...(values.detach === true ? ["-d"] : [])]);
178
103
  /** Check the public mode and spelling before catalog preparation or identity allocation.
179
104
  * Return the parsed channel overrides for the foreground policy. */
180
105
  export function validateSpawnArguments(args) {
@@ -313,617 +238,6 @@ export function validateSpawnArguments(args) {
313
238
  export function spawnRequiredExtensions(_args) {
314
239
  return [];
315
240
  }
316
- /** Whether the installed manifest lists a connector named `name`. An unreadable manifest answers
317
- * true, so the import's own refusal reports it. */
318
- function connectorListed(name) {
319
- try {
320
- return manifestExtensionNames("connector").includes(name);
321
- }
322
- catch {
323
- return true;
324
- }
325
- }
326
- /** #867: the name a spawn sends must already be a mintable identity, and the check must not wait
327
- * for the manager's round trip. `spawnNameError` is the SAME predicate the manager applies at its
328
- * door (manager.ts `start`), so the operator sees core's own refusal — offending character,
329
- * reservation reason, and the `_` remedy — before any request leaves. A courtesy only: the
330
- * manager door stays the enforcement point; this is why the CLI passes the target mesh's auth
331
- * mode rather than restating the grammar (static mode keys the actor on the nkey, not the name). */
332
- function refuseUnmintableName(name, userMode) {
333
- const refusal = spawnNameError(name, { userMode });
334
- if (refusal)
335
- throw new CommandFailure("refused", "USAGE_INVALID", refusal, { selfContained: true });
336
- }
337
- /** Whether a managed launch can reach only this root's own manager: the instance it names, or else
338
- * the only one the registry lists, is the one recorded under the target's root. An unread registry
339
- * or an unreadable record proves nothing, and the launch then goes to whichever manager serves it. */
340
- export function launchServedHere(t, serving, live) {
341
- if (t.root === undefined)
342
- return false;
343
- let here;
344
- try {
345
- here = loadManagerInstanceIdentity(t.root, t.space)?.instanceId;
346
- }
347
- catch {
348
- return false;
349
- }
350
- if (here === undefined)
351
- return false;
352
- return serving !== undefined ? serving === here : live?.length === 1 && live[0] === here;
353
- }
354
- /** A runtime this root's own manager cannot launch on is refused before the launch is sent, through
355
- * the installed-extension lookup `up --runtime` uses. A manager on another host reads that host's
356
- * extensions, so a launch that may reach one sends the name and that manager decides. */
357
- async function refuseRuntimeHere(runtime, t, serving, live) {
358
- if (!launchServedHere(t, serving, live))
359
- return;
360
- try {
361
- await preflightRuntime(runtime);
362
- }
363
- catch (error) {
364
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight on this machine, where the selected manager runs; nothing was launched", { target: { space: t.space, managerInstanceId: serving ?? live?.[0] ?? null, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
365
- }
366
- }
367
- const channelList = (channels) => channels.length ? channels.join(", ") : "none";
368
- export function managedLaunchView(r) {
369
- const concrete = [r.name, r.space, r.managerInstanceId].every((value) => /^[A-Za-z0-9_-]+$/.test(value));
370
- const target = concrete ? `${r.name} --space ${r.space} --on ${r.managerInstanceId}` : "<name> --space <space> --on <manager-instance>";
371
- const noStream = r.streamsTerminal === false;
372
- return { sections: [
373
- { title: "Agent joined", blocks: [
374
- { kind: "fields", rows: [["Agent", psSeatLabel({ name: r.name, id: r.id })], ["Identity", r.id], ["Lifecycle", r.lifecycleUid], ["Space", r.space], ["Manager receipt", r.managerInstanceId], ["Original request", r.intent?.requestId ?? r.request?.requestId ?? "not recorded"], ["Accepted goal", r.request?.goalId ?? "not reported"], ["Application", r.harness], ["Runtime", noStream ? `${r.runtime} · no terminal stream` : r.runtime], ["Role", r.role ?? "not recorded"], ...(r.acl ? [["Granted", `read ${channelList(r.acl.effective.allowSubscribe)} · post ${channelList(r.acl.effective.allowPublish)}; asked for read ${channelList(r.acl.requested.allowSubscribe)} · post ${channelList(r.acl.requested.allowPublish)}`]] : []), ["Model request", r.requestedModel ?? "persona/manager precedence; not inspected"], ["View", noStream ? `not attached; the seat runs in the manager's ${r.runtime} session` : r.detached ? "not attached" : "attaching to the allocated incarnation"]] },
375
- { kind: "lines", lines: [{ text: "The manager confirmed presence readiness. This is not proof that the kickoff task completed.", tone: "hint" }] },
376
- ] },
377
- ...(noStream ? [{ title: "Next", blocks: [
378
- { kind: "commands", items: [
379
- { command: `${displayCmd()} watch --space ${r.space}`, description: "Follow this mesh, this agent's messages included" },
380
- { command: `${displayCmd()} send -t ${r.name} "<message>"`, description: "Give the agent work over the mesh" },
381
- { command: `${displayCmd()} status ${target}`, description: "Read the agent's reported state" },
382
- ] },
383
- { kind: "lines", lines: [{ text: `${displayCmd()} attach is not available here: the ${r.runtime} runtime streams no terminal.`, tone: "hint" }] },
384
- ] }] : r.detached ? [{ title: "Next", blocks: [{ kind: "commands", items: [
385
- { command: `${displayCmd()} attach ${target}`, description: concrete ? "Return to this allocated incarnation's manager" : "Use the full identities recorded above" },
386
- { command: `${displayCmd()} status ${target}`, description: "Read the agent's reported state" },
387
- ] }] }] : []),
388
- ] };
389
- }
390
- /** The auth mode of the mesh `flags` name, or undefined when they name no registered mesh, which
391
- * the launch's own resolve then reports. */
392
- function meshMode(flags) {
393
- try {
394
- return resolveMeshTarget(process.cwd(), { space: flags.space, server: flags.server }).mode;
395
- }
396
- catch {
397
- return undefined;
398
- }
399
- }
400
- /** Shared managed launch. The manager resolves its persona and returns real readiness before
401
- * any view opens. Detach changes terminal attachment, not the launch or caller authority. */
402
- export async function launchManagedPersona(values, positionals, events, launchOptions, observer) {
403
- // WHICH file the manager loads — the exact foreground precedence (`--config` > positional >
404
- // `COTAL_DEFAULT_PERSONA` > `default`). Identity is separate:
405
- // when `--name` is given it OVERRIDES the file's `name:` (foreground's `requested`), threaded
406
- // as the op's `identity` so it is never silently dropped in detached mode.
407
- let on = await managerPin(values, spawnRerun(values, positionals));
408
- // From a managed seat's own shell the launch is the SEAT's, as its `cotal_spawn` tool is: the
409
- // manager records the seat as the spawner, so the seat can stop the child it asked for (#718).
410
- // `--on` keeps the pin on that path too.
411
- const flags = { space: values.space, server: values.server, creds: values.creds };
412
- const seatIntent = Boolean(process.env.COTAL_NAME || process.env.COTAL_ID || process.env.COTAL_LIFECYCLE_UID || process.env.COTAL_ACCEPTED_TOKEN);
413
- if (seatIntent && values.creds !== undefined)
414
- throw new CommandFailure("refused", "USAGE_INVALID", "a managed seat's child launch uses that seat's own caller, not a --creds override");
415
- let cwd = values.cwd;
416
- // On a terminal, a pinned manager that is not known to run on this host is asked which of its
417
- // folders the agent works in, unless -C names one. One resolve, dropped again here, answers
418
- // everything that question needs: that the mesh runs and the pin names a manager that is running,
419
- // which manager an unpinned launch on a user-auth mesh goes to (the exchange picks your only live
420
- // one, and the launch is pinned to it so the question asks about the manager that runs the
421
- // agent), and the host that manager reports. So an unknown --on or a stopped mesh is refused
422
- // before anything is asked, and the question still holds no manager credential: a typed folder is
423
- // checked under a view of that manager acquired after it is answered, and the launch acquires its
424
- // own below. A manager that has stopped by the time the launch is sent is refused there and goes
425
- // to no other manager.
426
- if (cwd === undefined && !seatIntent && canPrompt() && (on !== undefined || (values.creds === undefined && meshMode(flags) === "user"))) {
427
- const probe = await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
428
- const pin = on ?? probe.auth.managerInstanceId;
429
- if (pin !== undefined) {
430
- if (!probe.auth.bearer)
431
- await refuseUnregisteredManager(probe.space, probe.server, probe.auth, pin);
432
- on = pin;
433
- const selection = await managerSelection(values, pin, probe);
434
- if (selection.manager.host !== hostname()) {
435
- const folder = await askManagerFolder(selection, process.argv.slice(2), (path) => checkFolder(flags, pin, path));
436
- if (folder === null)
437
- process.exit(0);
438
- cwd = folder;
439
- }
440
- }
441
- }
442
- let seat;
443
- if (seatIntent) {
444
- try {
445
- seat = await resolveSeatControlTarget({ ...flags, space: flags.space ?? process.env.COTAL_SPACE }, on);
446
- }
447
- catch {
448
- throw new CommandFailure("refused", "AUTH_REQUIRED", "the launching seat's own credential could not be verified; no operator identity was substituted");
449
- }
450
- if (!seat)
451
- throw new CommandFailure("refused", "UNSUPPORTED", "the managed seat cannot act as itself through this CLI; missing/mismatched caller context and user-auth self impersonation do not fall back to the operator");
452
- }
453
- const t = seat ?? await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
454
- recordOperationSpace(t.space);
455
- let policy;
456
- try {
457
- policy = await refreshRegistrationPolicy(t);
458
- }
459
- catch {
460
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected registration policy could not be observed; no manager launch was submitted");
461
- }
462
- // #867: refuse an unmintable identity BEFORE the round trip. On this path the persona is
463
- // resolved manager-side, so the effective identity is `--name` alone — when it is absent the
464
- // manager applies the same spawnNameError to the file's `name:` at its own door.
465
- if (values.name !== undefined)
466
- refuseUnmintableName(values.name, t.mode === "user");
467
- const eventsRequired = policy?.events === "required";
468
- if (eventsRequired && events === false) {
469
- throw new CommandFailure("refused", "PERMISSION_DENIED", `space "${t.space}" requires the event plane by registration policy; no launch was submitted`);
470
- }
471
- const live = on === undefined && !t.auth.bearer ? await refuseWithoutLiveManager(t.space, t.server, t.auth, { space: t.space, managerInstanceId: null, managerEpoch: null }, "launch an agent") : undefined;
472
- // A pin the registry does not list is refused at once; only a registered manager is waited on.
473
- if (on !== undefined && !t.auth.bearer)
474
- await refuseUnregisteredManager(t.space, t.server, t.auth, on);
475
- if (values.runtime !== undefined)
476
- await refuseRuntimeHere(values.runtime.trim(), t, on ?? t.auth.managerInstanceId, live);
477
- const { ref, from: personaFrom } = spawnPersona(values.config, positionals, { space: t.space, preferences: cachedPreferences() });
478
- const managerConfigRef = values.config ?? (personaFrom !== undefined ? ref : undefined);
479
- const defaultAgent = callerHarness(t.space);
480
- let resumeClaim;
481
- if (values.resume !== undefined) {
482
- // Without a flag the harness is the persona pin or a default, which only the target manager
483
- // can read: ask it, so the carry looks with the connector the launch runs (#2899).
484
- const agent = values.agent ?? await launchAgentOrExit(t, on, { name: ref, config: managerConfigRef, defaultAgent });
485
- // The carry and its transfer-writer view stay on the mesh selected for this launch.
486
- const claim = await carryTranscript({ ...flags, space: t.space, server: t.server }, on, values.resume, agent);
487
- if (claim !== undefined)
488
- resumeClaim = { claim, agent };
489
- }
490
- // The report that answers names the mesh in its heading, so this block names it once, in a field.
491
- const toStdout = !observer && presentationOf(values) !== "json";
492
- (toStdout ? console.log : console.error)(renderReport({ sections: [{ title: "Managed launch", blocks: [{ kind: "fields", rows: [["Space", t.space], ["Manager selector", on ?? t.auth.managerInstanceId ?? "native class selection"], ["Persona", ref], ["File source", managerConfigRef ? `${managerConfigRef} · manager execution host` : "selected manager's persona catalog"], ["File transfer", "none"]] }, { kind: "lines", lines: [{ text: "The accepting manager validates its own visible file before allocation. No local file is uploaded, and a pin never selects a replacement manager.", tone: "hint" }] }] }] }, presentationOf(values) === "plain" ? "plain" : "rich", toStdout ? process.stdout : process.stderr));
493
- for (const line of wrapWords("waiting for the manager: it answers when it refuses the launch, or when the agent joins or exits (at most about 30s) …", terminalWidth(process.stderr)))
494
- console.error(c.dim(line));
495
- const start = () => requestManagedLaunch({
496
- persona: ref,
497
- identity: values.name,
498
- role: values.role,
499
- // #869: keep an explicit `--agent` and the invoking operator's default (COTAL_DEFAULT_AGENT or a
500
- // saved harness preference) in separate fields. Collapsing them made the default
501
- // indistinguishable from a flag, so it beat the persona pin; dropping it instead changed detached
502
- // semantics whenever the manager's own environment differed. The manager applies flag > file >
503
- // caller default > manager default.
504
- agent: values.agent,
505
- defaultAgent,
506
- config: managerConfigRef,
507
- model: values.model,
508
- variant: values.variant,
509
- ...(values.restarts !== undefined ? { supervise: { restarts: Number(values.restarts), windowMs: Number(values["restart-window"]) } } : {}),
510
- launchOptions,
511
- cwd,
512
- resume: values.resume,
513
- resumeClaim,
514
- prompt: values.prompt,
515
- shareTools: parseShareSelection(values["share-tools"]),
516
- subscribe: parseCommaList(values.subscribe),
517
- allowSubscribe: parseCommaList(values["allow-subscribe"]),
518
- allowPublish: parseCommaList(values["allow-publish"]),
519
- // #373: send the bit only when the operator chose it. On an events-required space the
520
- // policy still forces the plane on (the manager refuses a non-admin caller on such a space
521
- // anyway, so the operator must hold the admin tier for the spawn to succeed at all).
522
- events: eventsRequired ? true : events,
523
- ...(values["no-event-payloads"] || policy?.eventPayloads === "withheld" ? { eventPayloads: false } : {}),
524
- ...(values.runtime !== undefined ? { runtime: values.runtime.trim() } : {}),
525
- // #159 B1: the manager replies only on a REAL outcome (presence join / process exit / ~30s
526
- // readiness backstop) — the start request must outlive that window, not the 5s op default.
527
- // `--on <instance>` pins the spawn to that exact manager instance (P2 item 3 multi-manager).
528
- }, (args) => askManager(cliControl, t.space, t.server, "start", args, t.auth, "owner", START_TIMEOUT_MS, { instanceId: on }));
529
- // A refusal before execution launched nothing, so the launch is sent again once a name held by a
530
- // lifecycle that is not running is released. A name that runs is not launched a second time.
531
- let reply;
532
- try {
533
- let mesh;
534
- try {
535
- mesh = resolveMeshTarget(process.cwd(), { space: flags.space, server: flags.server });
536
- }
537
- catch { /* no registered mesh: nothing to release */ }
538
- reply = await settleHeldName(flags, start, (o) => "value" in o && !o.value.ok && o.value.nativeOutcome === "not-executed"
539
- ? heldAnswer({ code: o.value.code, details: o.value.details, message: o.value.error ?? "" }, values.name) : undefined, meshRelease(mesh));
540
- }
541
- catch (e) {
542
- if (!(e instanceof AgentAlreadyRunning))
543
- throw e;
544
- if (observer)
545
- throw new CommandFailure("refused", "CONFLICT", `${e.message}; nothing new was launched`, { target: { space: t.space, agent: e.agent, managerInstanceId: e.manager?.instanceId ?? null } });
546
- return reportAlreadyRunning(e, values, t.space, t.server);
547
- }
548
- const target = { space: t.space, managerInstanceId: reply.managerInstanceId ?? on ?? null, managerEpoch: reply.managerEpoch ?? null, ...(reply.intent ? { requestId: reply.intent.requestId, requestedGoalId: reply.intent.requestedGoalId ?? null } : {}), ...(reply.request ? { acceptedGoalId: reply.request.goalId ?? null } : {}) };
549
- // A launch whose process the manager reports running is starting: one that waits for the operator at
550
- // a screen its harness names was ready once it ran, and one that did not join in time may still be
551
- // coming up or sitting at a prompt. Either way the operator is sent to its terminal.
552
- const started = reply.ok ? reply.data : undefined;
553
- const running = !reply.ok && reply.code === "uncertain" && reply.details?.some((d) => d.kind === GOAL_ENTITY_RUNNING_DETAIL_KIND) === true;
554
- const startedName = typeof started?.name === "string" ? started.name : reply.request?.allocation?.name;
555
- if (!observer && reply.managerInstanceId && startedName && (typeof started?.waitingFor === "string" || running)) {
556
- const expected = typeof started?.id === "string" && typeof started.lifecycleUid === "string" ? { id: started.id, lifecycleUid: started.lifecycleUid } : undefined;
557
- return reportStarting({ name: startedName, managerInstanceId: reply.managerInstanceId, ...(typeof started?.waitingFor === "string" ? { waitingFor: started.waitingFor } : {}), ...(expected ? { expected } : {}) }, values, t.space, t.server, target);
558
- }
559
- if (!reply.ok) {
560
- const refusal = { "permission-denied": "PERMISSION_DENIED", "unauthenticated": "AUTH_REQUIRED", "not-found": "TARGET_NOT_FOUND", "unavailable": "TARGET_UNAVAILABLE", "bad-request": "SCHEMA_INVALID", "failed-precondition": "LIFECYCLE_BLOCKED", "already-exists": "CONFLICT", "conflict": "CONFLICT", "unimplemented": "UNSUPPORTED" };
561
- const code = reply.code === undefined ? undefined : refusal[reply.code];
562
- const native = { code: reply.code, outcome: reply.nativeOutcome, ...(reply.request || reply.intent ? { detail: { request: reply.request ?? null, intent: reply.intent ?? null, observation: reply.observationCause ?? null } } : {}) };
563
- // The broker attested that no manager received an unpinned launch: none takes the class queue.
564
- if (on === undefined && !t.auth.bearer && reply.unanswered && reply.nativeOutcome === "not-executed")
565
- throw await unservedClassLaunch(seat ? undefined : flags, t, values.agent ?? defaultAgent, { target, native });
566
- // A pinned describe that drew no answer means the launch was never sent, as ps and stop --on say.
567
- if (on !== undefined && describeUnanswered(reply))
568
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `manager instance ${on} did not answer, so the launch was not sent and nothing was launched`, { target, native: { code: reply.code, ...(reply.error ? { detail: oneLine(reply.error) } : {}) }, remedy: "cotal ps shows which managers answer; rerun the spawn on one of them with --on <instance>" });
569
- // So does an unpinned one: no manager answered, and the launch was never published.
570
- if (on === undefined && describeUnanswered(reply))
571
- throw unansweredClassLaunch(t, { target, native: { code: reply.code, ...(reply.error ? { detail: oneLine(reply.error) } : {}) } });
572
- // The owner's seat cap. Keyed on the marker, not the code: the numbers are what a script acts
573
- // on, and the remedy is the operator's knob, neither of which a code alone can carry. It is a
574
- // CONFLICT with the seats this owner already holds, the same shape as a pinned-name collision:
575
- // nothing here is unreachable or unauthorized, and freeing one seat admits the launch.
576
- const cap = seatCapFrom(reply);
577
- if (cap !== undefined)
578
- throw new CommandFailure("refused", "CONFLICT", reply.error ? oneLine(reply.error) : "the manager refused the launch: this owner is at its seat cap", {
579
- target, native: { code: reply.code, outcome: reply.nativeOutcome, detail: { owner: cap.owner, seats: cap.seats, cap: cap.cap } },
580
- remedy: `nothing was launched; stop one of this owner's seats with \`cotal stop --name <name>\`, or ask the operator who runs that manager to restart it with a higher --seat-cap (it admits ${cap.cap} per owner)`,
581
- });
582
- // A manager without the connector: it is added where that manager runs, not on this machine.
583
- const absent = reply.nativeOutcome === "not-executed" && reply.error !== undefined ? hintedConnector(reply.error) : undefined;
584
- if (absent !== undefined) {
585
- const answered = reply.managerInstanceId ?? on;
586
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `no connector "${absent}" is installed on ${answered ? await managerNamed(seat ? undefined : flags, t, answered) : "the manager"}; nothing was launched`, { target, native,
587
- remedy: `add it where that manager runs, such as ${extAddFor(absent)}, then restart that manager; it reads its agent applications when it starts` });
588
- }
589
- if (reply.nativeOutcome === "not-executed" && code) {
590
- // A manager without the persona: it is created on that manager's host, or the spawn goes to
591
- // another live manager whose catalog has it.
592
- const missing = managerConfigRef === undefined && reply.error?.startsWith(`no persona "${ref}"`) === true;
593
- const elsewhere = missing ? await managersWithPersona(flags, reply.managerInstanceId ?? on, ref).catch(() => []) : [];
594
- throw new CommandFailure("refused", code, reply.error ? oneLine(reply.error) : "the manager refused the launch before execution", { target, native, remedy: elsewhere.length
595
- ? `nothing was launched; ${elsewhere.length === 1 ? "this manager of yours has" : "these managers of yours have"} ${ref === "default" ? "a default persona" : `persona "${ref}"`}: ${elsewhere.map((selector) => rerunOn(process.argv.slice(2), selector)).join(" or ")}`
596
- : missing ? "nothing was launched; create that file on the manager's host, then run the spawn again"
597
- // This CLI refused before sending, so the manager reported nothing; the refusal names the side to update.
598
- : reply.details?.some((d) => d.kind === EP_UNDECLARED_ARG) ? "nothing was launched; update the side the refusal names, then run the spawn again"
599
- : "nothing was launched; fix what the manager reported, then run the spawn again" });
600
- }
601
- // A committed `failed` terminal is the manager's answer: the launch ran and failed, as an agent
602
- // that exits at once does, and the manager says why.
603
- if (reply.code === "failed")
604
- throw new CommandFailure("failed", "OPERATION_FAILED", reply.error ? oneLine(reply.error) : "the manager reported that the launch failed", { target, native, remedy: "fix what the manager reported, then run the spawn again" });
605
- const unknown = reply.nativeOutcome !== "executed" || reply.unanswered;
606
- throw new CommandFailure(unknown ? "unknown" : "failed", unknown ? "OPERATION_UNKNOWN" : "OPERATION_FAILED", reply.error ? oneLine(reply.error) : "the manager did not confirm launch readiness", { target, native, remedy: "inspect `cotal ps` and the selected manager before retrying; this launch was not submitted again" });
607
- }
608
- const { result, eventsNotice, startupNotice } = readManagedLaunch(reply, { space: t.space, requestedModel: values.model ?? null, detached: values.detach === true }, target);
609
- const { streamsTerminal } = result;
610
- const presentation = presentationOf(values);
611
- const warnings = [
612
- ...(eventsNotice ? [{ code: "EVENT_PLANE_NOTICE", target, message: eventsNotice }] : []),
613
- ...(startupNotice ? [{ code: "STARTUP_NOTICE", target, message: `${result.name} joined, but ${startupNotice}` }] : []),
614
- ];
615
- if (observer) {
616
- try {
617
- observer.ready(result, warnings);
618
- }
619
- catch {
620
- throw new CommandFailure("partial", "OPERATION_PARTIAL", "the agent joined, but the composite command could not record its native readiness; no replacement was launched", { target, changed: [result], remedy: "inspect the original agent and manager before another launch" });
621
- }
622
- }
623
- else
624
- writeResult(presentation, { command: "spawn", target, result, warnings }, managedLaunchView);
625
- if (values.detach)
626
- return;
627
- // A runtime that streams no terminal has none to attach, so this launch does not ask for one: the
628
- // seat is up, the receipt above says where it runs and what reaches it, and the command is done.
629
- // Asking anyway is the whole of this failure mode - the manager's refusal is correct and cannot
630
- // be retried, and turning a launch that did everything the runtime allows into a partial told the
631
- // operator to reattach, which that runtime cannot do either.
632
- if (streamsTerminal === false)
633
- return;
634
- // A partial names the step that works on this seat, on the manager that runs it: ps, then attach
635
- // where the runtime streams a terminal, or its own session where it streams none.
636
- const where = `--space ${shellWord(t.space)} --on ${shellWord(result.managerInstanceId)}`;
637
- const ps = `${displayCmd()} ps ${where}`;
638
- const next = async () => (streamsTerminal ?? await registeredStreamsTerminal(result.runtime, t.space)) === false
639
- ? `nothing was relaunched; check the agent with ${codeSpan(ps)} and watch it in the manager's ${result.runtime} session, which has no terminal to attach`
640
- : `nothing was relaunched; check the agent with ${codeSpan(ps)}, then attach to it with ${codeSpan(`${displayCmd()} attach ${shellWord(result.name)} ${where}`)}`;
641
- let verdict;
642
- try {
643
- verdict = await attachSeat({ space: t.space, server: t.server, creds: values.creds, name: result.name, expectedTarget: { id: result.id, lifecycleUid: result.lifecycleUid }, asSeat: seat !== undefined }, { on: result.managerInstanceId, reconnect: true, onRefusal: "throw" });
644
- }
645
- catch (e) {
646
- throw new CommandFailure("partial", "OPERATION_PARTIAL", "the agent joined, but its terminal could not be attached; it was not relaunched", { target, changed: [result], native: { detail: oneLine(e.message) }, remedy: await next() });
647
- }
648
- // A manager too old to report the terminal says so by refusing the attach, and that refusal ends
649
- // the launch as a reported one does. Since #4845 it carries a marker. Before it, the manager refused
650
- // with the runtime's own text and the code an agent that is not running also gets, so that refusal
651
- // counts only for a runtime this CLI's own registry declares streams no terminal.
652
- if (verdict.kind === "failed" && streamsTerminal === null && (verdict.refusal?.noTerminal || (verdict.refusal?.code === "failed-precondition" && await registeredStreamsTerminal(result.runtime, t.space) === false))) {
653
- stderrLine("", `the ${result.runtime} runtime has no terminal to attach, so none was opened; the agent runs in the manager's ${result.runtime} session`, c.dim);
654
- return;
655
- }
656
- if (verdict.kind === "failed")
657
- throw new CommandFailure("partial", "OPERATION_PARTIAL", "the agent joined, but attachment did not complete; no replacement was launched", { target, changed: [result], native: { detail: oneLine(verdict.message) }, remedy: await next() });
658
- if (verdict.kind === "gone" && observer)
659
- throw new CommandFailure("partial", "OPERATION_PARTIAL", "the agent joined, but its exact native terminal was unavailable before setup could open the view; no replacement was launched", { target, changed: [result], remedy: `check the original lifecycle with ${codeSpan(ps)} before another startup` });
660
- console.error(renderReport({ sections: [{ title: verdict.kind === "gone" ? "Attach target unavailable" : verdict.reason === "detached" ? "Detached" : "Attach session ended", blocks: [{ kind: "fields", rows: joinedAgentRows(result) }, { kind: "lines", lines: [{ text: "Leaving the view sent no stop request. The original lifecycle was not replaced.", tone: "hint" }] }] }] }, "rich", process.stderr));
661
- }
662
- /** Whether `runtime` streams a terminal, as a provider registered in this CLI or installed as its
663
- * extension declares it. Null when this CLI has no such provider, or it does not say. */
664
- async function registeredStreamsTerminal(runtime, space) {
665
- try {
666
- const declared = (await materializeExtension({ kind: "runtime", name: runtime })).create({ session: `cotal-${space}` }).streamsTerminal;
667
- return typeof declared === "boolean" ? declared : null;
668
- }
669
- catch {
670
- return null;
671
- }
672
- }
673
- /** The mesh's release of one agent lifecycle, when `mesh` is a remote user-auth mesh that advertises
674
- * an agent-provisioning endpoint and the auth provider can call it there. */
675
- function meshRelease(mesh) {
676
- const ua = mesh?.mode === "user" && mesh.userAuth?.remote ? mesh.userAuth : undefined;
677
- const url = ua?.endpoints?.agentProvisioningUrl;
678
- if (!ua || !url)
679
- return undefined;
680
- const provider = resolveAuthProvider();
681
- if (!provider.releaseAgentLifecycle)
682
- return undefined;
683
- return (lifecycleUid, agent) => provider.releaseAgentLifecycle({ url, idpUrl: ua.idp.url, lifecycleUid, actor: agent });
684
- }
685
- /** A managed launch whose process runs but has not joined the mesh: say where it runs and, when its
686
- * harness waits for the operator, at which screen. A terminal attaches to an operator screen at once,
687
- * even with -d, and to a starting agent only when the spawn was not detached; otherwise the attach
688
- * command is printed. */
689
- async function reportStarting(start, values, space, server, target) {
690
- const selection = await managerSelection(values, start.managerInstanceId).catch(() => undefined);
691
- const selector = selection?.selector ?? start.managerInstanceId, host = selection?.manager.host ?? null;
692
- const attach = `${displayCmd()} attach ${shellWord(start.name)} --on ${shellWord(selector)}`;
693
- const presentation = presentationOf(values);
694
- const now = presentation !== "json" && canPrompt() && (start.waitingFor !== undefined || !values.detach);
695
- const place = `on ${selector}${host && host !== selector ? ` (${host})` : ""}`;
696
- writeResult(presentation, {
697
- command: "spawn",
698
- target,
699
- result: { kind: "managed-launch-running", name: start.name, managerInstanceId: start.managerInstanceId, host, waitingFor: start.waitingFor ?? null, attach },
700
- }, (r) => ({ sections: [{ title: r.waitingFor ? "Waiting for you" : "Agent starting", blocks: [{ kind: "lines", lines: [
701
- r.waitingFor ? `${r.name} is running ${place} and waiting for you at ${r.waitingFor}.` : `${r.name} is running ${place} and has not joined the mesh yet; it may still be starting or waiting at a prompt.`,
702
- { text: now ? "Attaching to it now." : `Attach to it: ${codeSpan(r.attach)}`, tone: "hint" },
703
- ] }] }] }));
704
- if (!now)
705
- return;
706
- const verdict = await attachSeat({ space, server, creds: values.creds, name: start.name, ...(start.expected ? { expectedTarget: start.expected } : {}) }, { on: start.managerInstanceId, reconnect: true, onRefusal: "throw" });
707
- if (verdict.kind === "failed")
708
- stderrLine("! ", `${start.name} could not be attached: ${verdict.message}; attach to it with ${codeSpan(attach)}`, c.yellow);
709
- }
710
- /** The agent a spawn asked for already runs, so nothing new is launched: say where it runs, then
711
- * attach to it in this terminal unless the spawn was detached or cannot attach, or print the
712
- * command that does. */
713
- async function reportAlreadyRunning(running, values, space, server) {
714
- const where = running.manager;
715
- const attach = where ? `${displayCmd()} attach ${shellWord(running.agent)} --on ${shellWord(where.selector)}` : null;
716
- const presentation = presentationOf(values);
717
- const now = where !== null && !values.detach && presentation !== "json" && canPrompt();
718
- const place = where ? `on ${where.selector}${where.host && where.host !== where.selector ? ` (${where.host})` : ""}` : "on the mesh, not on a manager of yours";
719
- writeResult(presentation, {
720
- command: "spawn",
721
- target: { space, agent: running.agent, managerInstanceId: where?.instanceId ?? null },
722
- result: { kind: "already-running", name: running.agent, managerInstanceId: where?.instanceId ?? null, host: where?.host ?? null, attach },
723
- noOp: true,
724
- }, (r) => ({ sections: [{ title: "Already running", blocks: [{ kind: "lines", lines: [
725
- `${r.name} is already running ${place}; nothing new was launched.`,
726
- { text: now ? "Attaching to it now." : r.attach ? `Attach to it: ${codeSpan(r.attach)}` : "To start a second agent, pick another name with --name <other>.", tone: "hint" },
727
- ] }] }] }));
728
- if (!now)
729
- return;
730
- const verdict = await attachSeat({ space, server, creds: values.creds, name: running.agent }, { on: where.instanceId, reconnect: true, onRefusal: "throw" });
731
- if (verdict.kind === "failed")
732
- stderrLine("! ", `${running.agent} could not be attached: ${verdict.message}; attach to it with ${codeSpan(attach)}`, c.yellow);
733
- }
734
- /** Whether the manager `on` pins can launch an agent in `path`, answered by its `resolve-cwd` over
735
- * a view of that manager acquired for this check alone. A path it cannot use is its refusal, which
736
- * the question shows and asks again. A check it does not answer refuses the launch: the reason
737
- * rides the structured cause rather than the sentence, because a responder's own words there are
738
- * an internal subject and a spec reference, and the way past it is `-C <dir>`, which sends the
739
- * folder with the launch and asks nothing. */
740
- async function checkFolder(flags, on, path) {
741
- const t = await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
742
- const reply = await askManager(cliControl, t.space, t.server, "resolveCwd", { cwd: path }, t.auth, "owner", undefined, { instanceId: on });
743
- const cwd = reply.ok ? reply.data?.cwd : undefined;
744
- if (typeof cwd === "string")
745
- return { cwd };
746
- if (!reply.ok && reply.code === "failed-precondition" && reply.error)
747
- return { refusal: oneLine(reply.error) };
748
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `the folder ${JSON.stringify(path)} could not be checked with manager instance ${on}, so nothing was launched`, {
749
- target: { space: t.space, managerInstanceId: on },
750
- ...(reply.error ? { native: { ...(reply.code ? { code: reply.code } : {}), detail: { reason: oneLine(reply.error) } } } : {}),
751
- remedy: `send the folder with the launch instead of answering the question: ${codeSpan(rerunWithCwd(process.argv.slice(2), path, on))}`,
752
- });
753
- }
754
- /** Why no manager received an unpinned launch. A manager whose boot inventory found no agent
755
- * application available leaves the class queue. When every live one that answered reports that on
756
- * its instance rail, distinguish an empty connector inventory from installed but unavailable ones.
757
- * A manager the broker affirms gone is skipped and named in a warning, so its registration costs
758
- * no deadline and hides no reason. A seat
759
- * (`flags` undefined) does not read the census as the operator. `agent` is the harness this caller
760
- * would choose, for the install hint. */
761
- async function unservedClassLaunch(flags, t, agent, at) {
762
- const census = flags ? await classLaunchCensus(flags, t).catch(() => undefined) : undefined;
763
- for (const instanceId of census?.gone ?? [])
764
- 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)` });
765
- if (census?.noApplication && census.unavailable.length) {
766
- 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,
767
- 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)}` : ""}.` });
768
- }
769
- if (census?.noApplication) {
770
- 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,
771
- remedy: `add one where ${census.managers.length > 1 ? "one of them" : "that manager"} runs, such as ${extAddFor(agent ?? DEFAULT_CONNECTOR)}, then restart that manager; it reads its agent applications when it starts` });
772
- }
773
- return new CommandFailure("refused", "TARGET_UNAVAILABLE", "no manager of yours received this unpinned launch; nothing was launched", { ...at, remedy: "run the spawn again, or pin one manager with --on <instance> from `cotal ps`" });
774
- }
775
- /** Why no manager answered an unpinned launch's describe, so the launch was never sent. This root's
776
- * own stack says why when it records one, in the words `ps` uses for the same silence. */
777
- function unansweredClassLaunch(t, at) {
778
- const refused = (message, remedy) => new CommandFailure("refused", "TARGET_UNAVAILABLE", `${message}, so the launch was not sent and nothing was launched`, { ...at, remedy });
779
- if (t.root !== undefined && stackManagerStarting(t.root, t.space))
780
- return refused("the stack's manager is starting", "run the spawn again once `cotal up` reports the manager started");
781
- if (t.root !== undefined && stackManagerAbsent(t.root, t.space))
782
- return refused("no manager is running for this space", startStackManagerRemedy(t.space, t.server));
783
- const pid = t.root === undefined ? undefined : runningStackManagerPid(t.root, t.space);
784
- if (pid !== undefined)
785
- return refused(`this space's stack manager (pid ${pid}) is running but did not answer`, `if it stays unresponsive, end that process with kill -KILL ${pid}; then bare \`cotal up\` starts the manager again`);
786
- return refused("no manager answered", "cotal ps shows which managers answer; run the spawn again once one does");
787
- }
788
- /** What the registered managers say about unpinned launches. `noApplication` holds when one answered
789
- * and each one that answered says it runs agents but takes no unpinned launch; `gone` lists the
790
- * managers skipped because the broker affirms nothing subscribed on their rail. Status has no
791
- * scatter route, so each is read pinned to its instance, racing the rail probe: whichever settles
792
- * first stops the other, so neither a live manager nor a gone one is waited out. */
793
- async function classLaunchCensus(flags, t) {
794
- const gone = [];
795
- const managers = [];
796
- const unavailable = [];
797
- const empty = [];
798
- for (const instanceId of await liveManagerIds(t.space, t.server, t.auth)) {
799
- const pinned = await resolveControlTarget(flags, "control-caller-privileged", instanceId, { onRefusal: "throw" });
800
- const settled = new AbortController();
801
- const status = await Promise.race([
802
- managerRailGone(pinned.space, pinned.server, pinned.auth, instanceId, settled.signal).then((isGone) => isGone ? undefined : new Promise(() => { })),
803
- askManager(cliControl, pinned.space, pinned.server, "managerStatus", undefined, pinned.auth, "owner", 5_000, { instanceId, signal: settled.signal }),
804
- ]).finally(() => settled.abort());
805
- if (status === undefined) {
806
- gone.push(instanceId);
807
- continue;
808
- }
809
- const data = status.data;
810
- if (!status.ok || data?.classSpawn !== false || data.execution === "none")
811
- return { noApplication: false, gone, managers, unavailable, empty };
812
- const manager = managerAt(instanceId, data.host);
813
- managers.push(manager);
814
- if (data.connectors?.length) {
815
- for (const connector of data.connectors.filter(row => row.state === "unavailable"))
816
- unavailable.push(`${manager}: ${connector.agent}: ${oneLine(connector.reason ?? "unavailable at manager startup")}`);
817
- }
818
- else
819
- empty.push(manager);
820
- }
821
- return { noApplication: managers.length > 0, gone, managers, unavailable, empty };
822
- }
823
- /** A manager as a refusal names it: its instance id, and the host its own status reports. */
824
- const managerAt = (instanceId, host) => typeof host === "string" && host ? `manager ${instanceId} on host ${host}` : `manager ${instanceId}`;
825
- /** {@link managerAt} for one manager, read pinned to it. A seat (`flags` undefined) reads with its
826
- * own caller, and a status that cannot be read leaves the host out. */
827
- async function managerNamed(flags, t, instanceId) {
828
- try {
829
- const pinned = flags ? await resolveControlTarget(flags, "control-caller-privileged", instanceId, { onRefusal: "throw" }) : t;
830
- const status = await askManager(cliControl, pinned.space, pinned.server, "managerStatus", undefined, pinned.auth, "owner", 5_000, { instanceId });
831
- return managerAt(instanceId, status.ok ? status.data?.host : undefined);
832
- }
833
- catch {
834
- return managerAt(instanceId, undefined);
835
- }
836
- }
837
- /** The `cotal ext add` that installs connector `name`, quoted for a refusal. */
838
- const extAddFor = (name) => OFFICIAL_CONNECTORS[name] ? `\`cotal ext add ${OFFICIAL_CONNECTORS[name]}\`` : `\`cotal ext add <npm-package>\` for "${name}"`;
839
- /** The harness the manager's `spawn` resolves for this persona, read with the same fields `start` sends. */
840
- async function launchAgentOrExit(t, on, fields) {
841
- const reply = await askManager(cliControl, t.space, t.server, "resolveAgent", fields, t.auth, "owner", undefined, { instanceId: on });
842
- failIfNotOk(reply);
843
- return reply.data.agent;
844
- }
845
- /**
846
- * Carry a session this host holds to the manager instance a detached resume launches on, and return
847
- * the claim its `spawn` names (#1499, docs/design/resume-transfer.md section 2). Undefined when this
848
- * host holds no session `id`: the id then resolves on the manager's host as it always has. Only the
849
- * connector can tell a local session from one that lives on the manager's host, so a connector this
850
- * CLI cannot load is refused.
851
- */
852
- async function carryTranscript(flags, on, id, agent) {
853
- let connector;
854
- try {
855
- connector = await materializeExtension({ kind: "connector", name: agent });
856
- }
857
- catch (error) {
858
- if (isCommandFailure(error))
859
- throw error;
860
- if (!connectorListed(agent))
861
- throw missingConnector(agent, { space: flags.space });
862
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `resume: ${oneLine(error.message)}`);
863
- }
864
- let found;
865
- try {
866
- found = connector.resumeTranscript?.find(id, process.env);
867
- }
868
- catch (error) {
869
- if (isCommandFailure(error))
870
- throw error;
871
- throw new CommandFailure("refused", "USAGE_INVALID", `resume: ${error.message}`, { selfContained: true });
872
- }
873
- if (found === undefined)
874
- return undefined;
875
- if (on === undefined) {
876
- throw new CommandFailure("refused", "USAGE_INVALID", `resume: session ${id} is held on this host, and carrying it needs one manager instance`, {
877
- remedy: "pass --on <instance>", selfContained: true,
878
- });
879
- }
880
- const bytes = readFileSync(found.path);
881
- const sha256 = createHash("sha256").update(bytes).digest("hex");
882
- const t = await resolveControlTarget(flags, "control-caller-admin", on);
883
- recordOperationSpace(t.space);
884
- const bucket = transferBucket(t.space, on);
885
- const writer = await transferWriterOrExit(flags, t, on, sha256);
886
- let sent = 0;
887
- let chunks = 0;
888
- for (;;) {
889
- const reply = await askManager(cliControl, t.space, t.server, "transcriptReceive", {
890
- sha256, size: bytes.length, source: id, sourceHost: hostname(), ...(found.title ? { title: found.title } : {}),
891
- }, t.auth, "owner", undefined, { instanceId: on });
892
- failIfNotOk(reply);
893
- const answer = reply.data;
894
- if (answer.state === "staged") {
895
- console.log(c.dim(`carried session ${id} to ${on}: sha256:${sha256}, ${sent} of ${bytes.length} bytes sent in ${chunks} chunks`));
896
- return answer.claim;
897
- }
898
- const pass = await withControlConnection(t.server, writer, (nc) => writeTransfer(nc, bucket, bytes));
899
- sent += pass.sent;
900
- chunks += pass.chunks;
901
- }
902
- }
903
- /** The transfer writer instrument for one object in one instance's bucket (design section 6), once
904
- * the transcript is hashed: minted from this host's copy of the mesh's signing seed, or on a
905
- * user-auth mesh exchanged from the operator's login as a `transfer-writer` view. An open mesh
906
- * enforces no grants, so a bare connection writes there. */
907
- async function transferWriterOrExit(flags, t, instanceId, hex) {
908
- if (t.mode === "open")
909
- return { tls: t.auth.tls };
910
- if (t.mode === "user") {
911
- const conn = await connectUserControlOrExit(flags);
912
- try {
913
- const view = await userViewAuth(conn, "transfer-writer", { transferWriter: { instanceId, hex } });
914
- return { bearer: view.bearer, sentinelCreds: view.sentinelCreds, tls: conn.tls };
915
- }
916
- catch (e) {
917
- stderrLine("✗ ", `resume: ${e.message}`, c.red);
918
- process.exit(1);
919
- }
920
- }
921
- if (t.mode !== "auth" || !t.spaceAuth) {
922
- stderrLine("✗ ", "resume: carrying a session mints a transfer writer from this mesh's signing seed, and this host holds none for it (an off-registry connection)", c.red);
923
- process.exit(1);
924
- }
925
- return { creds: await mintCreds(t.spaceAuth, newIdentity(), "transfer-writer", { transferWriter: { instanceId, hex } }), tls: t.auth.tls };
926
- }
927
241
  /**
928
242
  * `cotal spawn [<persona>] [--file <persona-file>]` runs the native application in this terminal.
929
243
  * `--detach` launches it through a manager and returns after readiness, and `--on <instance>`
@@ -935,7 +249,7 @@ async function transferWriterOrExit(flags, t, instanceId, hex) {
935
249
  * here vs. a supervised runtime in the manager. The connector is resolved from
936
250
  * the registry by agent type, composed at the root.
937
251
  *
938
- * The mesh it joins — creds and personas together — is resolved by {@link resolveMeshTarget}, so a
252
+ * The mesh it joins — creds and personas together — is resolved by `resolveMeshTarget` (in @cotal-ai/workspace), so a
939
253
  * bare `cotal spawn <persona>` from any directory finds the running mesh (one up, or the `current`
940
254
  * default) instead of mistaking `~/.cotal` for a space.
941
255
  */
@@ -1166,6 +480,7 @@ export async function spawn(args) {
1166
480
  stderrLine("✗ ", "the managed handoff's space is registered here as a local mesh, so it cannot host a managed handoff", c.red);
1167
481
  process.exit(1);
1168
482
  }
483
+ checkSpawnExpiryTarget(values, target);
1169
484
  let policy;
1170
485
  try {
1171
486
  policy = await refreshRegistrationPolicy(target);
@@ -1182,18 +497,15 @@ export async function spawn(args) {
1182
497
  process.exit(1);
1183
498
  }
1184
499
  const { space, server, auth } = target;
1185
- // Only a static mesh's seat carries an issuance whose expiry the person sets here.
1186
- if ((values["expires-in"] !== undefined || values["expires-at"] !== undefined) && (target.mode === "user" || !auth))
1187
- throw new CommandFailure("refused", "USAGE_INVALID", `--expires-in and --expires-at set the expiry of a seat's issued credential on a static mesh, and mesh "${space}" is ${target.mode === "user" ? "a user-auth mesh, where the seat's bearer comes from your login" : "open and mints no credential"}`, { remedy: "drop the flag" });
1188
500
  // Where the config lives: --config, else the positional <persona>, else the persona preference
1189
501
  // (.cotal/agents/<name>.md under the TARGET mesh's root). With none, fall back to its `default`
1190
502
  // persona — `cotal spawn` with no args launches `<root>/.cotal/agents/default.md`.
1191
503
  const { ref, from: personaFrom } = spawnPersona(values.config, positionals, { space, preferences: cachedPreferences() });
1192
504
  const personaProject = resolvePath(target.personaRoot, "..", "..");
1193
- const path = values.file !== undefined || (redeemedEnrollment && values.config) ? resolvePath(ref) : agentFilePath(personaProject, ref);
505
+ const path = values.file !== undefined || (redeemedEnrollment && values.config) ? resolvePath(ref) : directPersonaPath(personaProject, ref, values.config === undefined && positionals.length > 0);
1194
506
  // The product default of a catalog nothing prepared, as a Cloud space's is until a spawn, is
1195
- // written from the shipped template here and launched. A named or preferred persona is the
1196
- // user's own choice, so one that is missing is still refused.
507
+ // written from the shipped template here and launched. This also applies to positional `default`.
508
+ // A missing file, preference or other catalog name is still refused.
1197
509
  const implicitDefault = ref === "default" && personaFrom === undefined && values.config === undefined && handoffText === undefined && redeemedEnrollment === undefined;
1198
510
  let def;
1199
511
  try {
@@ -1781,304 +1093,4 @@ export async function spawn(args) {
1781
1093
  process.off(sig, onTerminate);
1782
1094
  }
1783
1095
  }
1784
- /** Foreground REMOTE-USER onboarding — the participant path for a mesh registered with
1785
- * `meshes add --from` that advertises an agent-provisioning endpoint (U6 §2).
1786
- *
1787
- * The local twin below ({@link provisionUserForeground}) cannot run here and must not try: it
1788
- * needs the space's owner secret and account signer to grant a row and pre-create durables, and
1789
- * those never leave the machine the mesh runs on. Instead the mesh's own endpoint does that work
1790
- * inside the owner's delegation envelope and hands back ready material; this function's job is to
1791
- * present the login bearer, validate what comes back, land it 0600, and prove the bearer chain
1792
- * before launch — the same preflight discipline, with the grant performed remotely.
1793
- *
1794
- * Deliberately NOT reusing the local path's cleanup: nothing here created broker state locally, so
1795
- * teardown is the mesh's business (its lifecycle owns the row and the durables). The spawned
1796
- * agent's material is shredded on exit; the row is not revoked from here, because this machine
1797
- * holds no authority to revoke it. For a managed handoff, `refusals` replaces the sentences of the
1798
- * local-state, material and bearer steps, which quote the space, the actor or the exchange URL. */
1799
- async function provisionRemoteUserForeground(target, name, source, refusals) {
1800
- const { space } = target;
1801
- const store = workspaceSecretStore(target.root);
1802
- const composition = { injected: false, root: target.root };
1803
- const fail = (msg) => {
1804
- stderrLine("✗ ", `${msg}`, c.red);
1805
- process.exit(1);
1806
- };
1807
- // Resolved first, as by every consumer of the space's local state: each resolution migrates a
1808
- // pre-hex or root-scoped layout, or refuses an ambiguous one, before any request or material.
1809
- let paths;
1810
- try {
1811
- userAuthStateDir(target.root, space);
1812
- paths = agentSecretFilePaths(target.root, space, name);
1813
- }
1814
- catch (e) {
1815
- return fail(refusals?.registration ?? e.message);
1816
- }
1817
- let provider;
1818
- try {
1819
- provider = resolveAuthProvider();
1820
- }
1821
- catch (e) {
1822
- return fail(e.message);
1823
- }
1824
- // Checked before the grant is requested, because `fail` exits without running the shred in the
1825
- // catch below and would leave the granted material on disk.
1826
- const exchangeUrl = "body" in source ? source.exchangeUrl : target.userAuth?.endpoints?.url;
1827
- if (!exchangeUrl)
1828
- return fail(noExchangeEndpoint(space));
1829
- let body;
1830
- const held = `foreground actor material for "${name}" is already held; preserve its session and choose a distinct actor for a new launch`;
1831
- const materialClaim = acquireLock(`${paths.actorToken}.launch.lock`, {
1832
- waitMs: 0,
1833
- // A supplied body comes from an enrollment that was already redeemed, so its collision is not
1834
- // a refusal: the one-time enrollment is spent.
1835
- onTimeout: () => "body" in source ? new Error(held) : new ForegroundActorCollision(held),
1836
- });
1837
- if ("body" in source) {
1838
- body = source.body;
1839
- }
1840
- else {
1841
- const idpUrl = target.userAuth?.idp.url;
1842
- if (!idpUrl)
1843
- return fail(`mesh "${space}" records no IdP to sign in against - re-register it with \`cotal meshes add ${space} --from <url> --mode user\``);
1844
- // The login proof rides the provisioning request, so the POST is the PROVIDER's (this package
1845
- // never touches the session cache); its thrown sentences are already operator-exact — the
1846
- // no-login gate names the `cotal login --idp …` line, a refusal carries the mesh's own reason.
1847
- if (!provider.postAgentProvisioning)
1848
- return fail(`the registered auth provider "${provider.name}" cannot provision agents on a remote mesh - run the agent where the mesh runs`);
1849
- // A name held by a lifecycle that is not running is released and asked for again.
1850
- try {
1851
- body = await settleHeldName({ space }, () => provider.postAgentProvisioning({ url: source.provisioningUrl, idpUrl, actor: name }), (o) => "error" in o
1852
- ? heldAnswer({ code: o.error?.code, details: o.error?.details, message: rejectionText(o.error) }, name) : undefined, meshRelease(target));
1853
- }
1854
- catch (e) {
1855
- materialClaim.release();
1856
- // No sign-in refuses before any request. Any failure after the request, an endpoint refusal
1857
- // included, may have provisioned the actor.
1858
- if (e.code === "signed-out")
1859
- throw new CommandFailure("refused", "AUTH_REQUIRED", e.message);
1860
- throw e;
1861
- }
1862
- }
1863
- const checked = checkRemoteAgentMaterial(body, name);
1864
- if (!checked.ok) {
1865
- materialClaim.release();
1866
- if (checked.exists && "provisioningUrl" in source)
1867
- throw new ForegroundActorCollision(checked.message);
1868
- return fail(refusals?.bundle ?? checked.message);
1869
- }
1870
- const material = checked.material;
1871
- const { actorToken: tokenPath, sentinelCreds: sentinelPath, health: healthPath } = paths;
1872
- if (inspectLock(localConsumerClaimPath(target.server, space, material.owner, name, material.lifecycleUid)).state === "active") {
1873
- materialClaim.release();
1874
- return fail(`local inbox already has a consuming session for ${material.owner}.${name}; no local material was replaced`);
1875
- }
1876
- try {
1877
- // Land both secrets 0600 through the store, exactly as the local path does — the bearer
1878
- // re-exec and the launch handoff read FILES.
1879
- await store.put(agentActorTokenKey(space, name, composition), material.actorToken);
1880
- await store.put(agentSentinelCredsKey(space, name, composition), material.sentinelCreds);
1881
- await materializeSecretToFile(store, agentActorTokenKey(space, name, composition), tokenPath);
1882
- await materializeSecretToFile(store, agentSentinelCredsKey(space, name, composition), sentinelPath);
1883
- rmSync(healthPath, { force: true });
1884
- provenance.wrote(`remote actor material ${material.owner}.${name} (user mode)`, tokenPath);
1885
- // The bearer preflight — the same one-shot proof the local path runs, pointed at the pinned
1886
- // exchange instead of a local service. A dead auth chain stops the spawn here. The agent runs
1887
- // this command for every renewal, so it names the resolved entry: an install can replace the
1888
- // bin link meanwhile (get.cotal.ai writes a shell launcher over `~/.local/bin/cotal`).
1889
- const bearerCmd = [
1890
- process.execPath,
1891
- ...process.execArgv,
1892
- entryScript(),
1893
- provider.agentBearerCommand,
1894
- "--exchange-url", exchangeUrl,
1895
- "--space", space,
1896
- "--owner", material.owner,
1897
- "--actor", name,
1898
- "--token-file", tokenPath,
1899
- "--health-file", healthPath,
1900
- ];
1901
- await runBearerPreflight(bearerCmd);
1902
- return {
1903
- userAuth: { owner: material.owner, actor: name, sentinelCredsPath: sentinelPath, bearerCmd },
1904
- material,
1905
- // Local shred only. The remote row and its durables belong to the mesh's lifecycle; this
1906
- // machine has no authority to retire them and must not pretend otherwise.
1907
- cleanup: async () => {
1908
- const failed = [];
1909
- if (await store.get(agentActorTokenKey(space, name, composition)) === material.actorToken)
1910
- await shredAgentMaterial(failed, store, space, name, composition, paths);
1911
- materialClaim.release();
1912
- if (failed.length)
1913
- throw new Error(describeCleanupFailures(failed));
1914
- },
1915
- };
1916
- }
1917
- catch (e) {
1918
- // What the shred left behind joins the refusal after its cause. A handoff refusal keeps its
1919
- // fixed sentence and names only the failed steps, because their errors quote paths named for
1920
- // the handoff's actor.
1921
- const failed = [];
1922
- if (await store.get(agentActorTokenKey(space, name, composition)) === material.actorToken)
1923
- await shredAgentMaterial(failed, store, space, name, composition, paths);
1924
- materialClaim.release();
1925
- const steps = refusals ? failed.map((f) => f.step).join("; ") : describeCleanupFailures(failed);
1926
- const leftover = failed.length ? `; cleanup failed: ${steps}` : "";
1927
- return fail(`${refusals?.bearer ?? `agent auth preflight failed for "${name}": ${rejectionText(e)}`}${leftover}`);
1928
- }
1929
- }
1930
- /** Foreground USER-MODE onboarding — the CLI-side twin of the manager's user spawn provisioning:
1931
- * owner = the logged-in operator (offline, from the login cache + local user-auth material);
1932
- * principal-keyed durables on an ephemeral provisioner (LIVE-ONLY, like static foreground);
1933
- * fresh ledger grant that refuses an occupied actor; 0600 secret/sentinel files; and a
1934
- * one-shot bearer preflight whose operator-exact sentence is the refusal. Exits on any failure —
1935
- * the agent process is never launched into a broken auth chain. */
1936
- async function provisionUserForeground(target, name, ref, opts) {
1937
- const { space, server } = target;
1938
- const dir = userAuthStateDir(target.root, space);
1939
- const store = workspaceSecretStore(target.root);
1940
- const composition = { injected: false, root: target.root };
1941
- const fail = (msg) => {
1942
- stderrLine("✗ ", `${msg}`, c.red);
1943
- process.exit(1);
1944
- };
1945
- let provider;
1946
- let owner;
1947
- try {
1948
- provider = resolveAuthProvider();
1949
- owner = await provider.ownerForLogin({ store, dir, space });
1950
- }
1951
- catch (e) {
1952
- return fail(e.message);
1953
- }
1954
- // The provisioner cred is INFRA (pre-flip static coexistence, like the manager's own creds) —
1955
- // loaded explicitly here for durable pre-creation only, never for the agent's identity.
1956
- // The event grant, derived HERE because this is the first point at which the owner exists: in
1957
- // user mode the principal is (resolved owner, actor name), and neither half is known to the
1958
- // caller before `ownerForLogin` answers.
1959
- const eventGrant = opts.eventChannel?.({ owner, actor: name });
1960
- const publish = eventGrant ? [...(opts.allowPublish ?? []), eventGrant] : (opts.allowPublish ?? []);
1961
- const infra = await getSpaceAuth(store, space); // cross-check the bundle names the space we resolved this root for
1962
- if (!infra)
1963
- return fail(`space "${space}" has user-auth state but no trust record under ${authDir(target.root)} (expected ${spaceAccountPath(authDir(target.root), space)} or the legacy auth.json) - re-run \`cotal up --user-auth\` here`);
1964
- const paths = agentSecretFilePaths(target.root, space, name);
1965
- const { actorToken: tokenPath, sentinelCreds: sentinelPath, health: healthPath } = paths;
1966
- const materialClaim = acquireLock(`${tokenPath}.launch.lock`, {
1967
- waitMs: 0,
1968
- onTimeout: () => new ForegroundActorCollision(`foreground actor material for "${name}" is already held; preserve its session and choose a distinct actor for a new launch`),
1969
- });
1970
- // An existing row is not this new launch's property. In particular, a dead launcher may
1971
- // leave its consuming child alive. Never overwrite the row to discover occupancy later.
1972
- if (await provider.actorScope({ dir, owner, actor: name }) !== undefined) {
1973
- materialClaim.release();
1974
- throw new ForegroundActorCollision(`actor "${name}" already has a grant; preserve its session and choose a distinct actor for a new launch`);
1975
- }
1976
- let ownedToken;
1977
- // Revoke the row, shred the secret material, and retire the broker footprint the durable
1978
- // provisioning below creates (DM/DLV durables + ACL row). Every step is attempted, so a failed
1979
- // removal cannot strand the durables on the broker, and the failures go back to the caller.
1980
- const teardown = async () => {
1981
- const failed = [];
1982
- if (ownedToken === undefined)
1983
- return failed;
1984
- let revoked = false;
1985
- await attemptCleanup(failed, "revoke agent grant", async () => {
1986
- revoked = await provider.revokeAgent({ dir, owner, actor: name, lifecycleUid: opts.lifecycleUid, actorToken: ownedToken });
1987
- });
1988
- if (await store.get(agentActorTokenKey(space, name, composition)) === ownedToken)
1989
- await shredAgentMaterial(failed, store, space, name, composition, paths);
1990
- if (!revoked)
1991
- return failed;
1992
- const targetId = principalKey(owner, name).key;
1993
- await attemptCleanup(failed, "deprovision", () => mintCreds(infra, newIdentity(), "deprovisioner", { deprovisionTarget: { principal: targetId, lifecycleUid: opts.lifecycleUid } })
1994
- .then((creds) => deprovisionAgent({ servers: server, space, targetId, lifecycleUid: opts.lifecycleUid, creds })));
1995
- return failed;
1996
- };
1997
- try {
1998
- // The GRANT first — it is the envelope-rule enforcement point (a delegation must sit within
1999
- // the spawner's own grant), so a refused delegation exits here with zero broker footprint —
2000
- // the same ordering as Manager.provisionUserAgent, for the same reason.
2001
- const grant = await provider.grantAgent({
2002
- store,
2003
- dir,
2004
- space,
2005
- owner,
2006
- actor: name,
2007
- scope: (opts.capabilities ?? []).filter((s) => s === "spawn" || s === "run" || s === "admin" || /^role:[A-Za-z0-9_-]+$/.test(s)),
2008
- allowSubscribe: opts.allowSubscribe,
2009
- allowPublish: publish,
2010
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
2011
- role: opts.role,
2012
- parent: `${owner}.cli`,
2013
- label: ref,
2014
- lifecycleUid: opts.lifecycleUid,
2015
- fresh: true,
2016
- // A foreground launch has no manager; its row says so.
2017
- custody: { kind: "foreground" },
2018
- });
2019
- ownedToken = grant.actorToken;
2020
- await withProvisioner({ space, servers: server, auth: infra }, "spawn-provisioner", (prov) =>
2021
- // Full durable footprint, same as the static foreground path: the ACL row is what lets the
2022
- // delivery daemon authorize this agent's durable joins. `--live-only` opts out.
2023
- provisionAgentDurables(prov, { owner, actor: name, lifecycleUid: opts.lifecycleUid }, {
2024
- subscribe: opts.subscribe,
2025
- allowSubscribe: opts.allowSubscribe,
2026
- role: opts.role,
2027
- ...(opts.liveOnly ? { durableMembership: false } : {}),
2028
- }));
2029
- // The store holds the source of truth; the bearer re-exec (`--token-file`) and the launch's
2030
- // sentinel handoff read FILES — materialize both at the canonical paths (byte-identical
2031
- // rewrites under this, the local FS, composition).
2032
- await store.put(agentActorTokenKey(space, name, composition), grant.actorToken);
2033
- await store.put(agentSentinelCredsKey(space, name, composition), grant.sentinelCreds);
2034
- await materializeSecretToFile(store, agentActorTokenKey(space, name, composition), tokenPath);
2035
- await materializeSecretToFile(store, agentSentinelCredsKey(space, name, composition), sentinelPath);
2036
- rmSync(healthPath, { force: true });
2037
- provenance.wrote(`actor grant ${owner}.${name} (user mode)`, tokenPath);
2038
- // The resolved entry, for the same reason as the remote arm above.
2039
- const bearerCmd = [
2040
- process.execPath,
2041
- ...process.execArgv,
2042
- entryScript(),
2043
- provider.agentBearerCommand,
2044
- "--dir", dir,
2045
- "--space", space,
2046
- "--owner", owner,
2047
- "--actor", name,
2048
- "--token-file", tokenPath,
2049
- "--health-file", healthPath,
2050
- ];
2051
- await runBearerPreflight(bearerCmd);
2052
- return {
2053
- userAuth: { owner, actor: name, sentinelCredsPath: sentinelPath, bearerCmd },
2054
- ...(eventGrant ? { eventChannel: eventGrant } : {}),
2055
- // The foreground departure's half of the runtime-grant invariant: the caller runs this when
2056
- // the agent process exits, the same teardown the rollback below runs on a failed preflight.
2057
- cleanup: async () => {
2058
- const failed = await teardown();
2059
- if (failed.length)
2060
- throw new Error(describeCleanupFailures(failed));
2061
- materialClaim.release();
2062
- },
2063
- };
2064
- }
2065
- catch (e) {
2066
- // Roll back EVERYTHING this attempt materialized: a refused spawn leaves no row, no secret, no
2067
- // orphaned durables. What the teardown could not remove joins the refusal after its cause.
2068
- const failed = await teardown();
2069
- materialClaim.release();
2070
- if (e instanceof AgentGrantConflictError && ownedToken === undefined && failed.length === 0)
2071
- throw e;
2072
- const leftover = failed.length ? `; cleanup failed: ${describeCleanupFailures(failed)}` : "";
2073
- return fail(`agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}`);
2074
- }
2075
- }
2076
- /** Run the one-shot bearer proof with an explicit credential-scrubbed environment. The enrollment
2077
- * path removes the variables from the parent before any child, and this boundary independently
2078
- * refuses to inherit them if another caller reaches it with ambient enrollment input. */
2079
- export async function runBearerPreflight(bearerCmd, env = process.env) {
2080
- const childEnv = { ...env };
2081
- scrubEnrollmentEnv(childEnv);
2082
- await runAgentBearer(bearerCmd, { env: childEnv });
2083
- }
2084
1096
  //# sourceMappingURL=spawn.js.map