@cotal-ai/cli 0.172.0 → 0.172.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +68 -47
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts +2 -2
  5. package/dist/commands/agents.d.ts.map +1 -1
  6. package/dist/commands/agents.js +19 -12
  7. package/dist/commands/agents.js.map +1 -1
  8. package/dist/commands/channel-members.d.ts.map +1 -1
  9. package/dist/commands/channel-members.js +2 -1
  10. package/dist/commands/channel-members.js.map +1 -1
  11. package/dist/commands/channels.d.ts.map +1 -1
  12. package/dist/commands/channels.js +20 -9
  13. package/dist/commands/channels.js.map +1 -1
  14. package/dist/commands/clean.d.ts.map +1 -1
  15. package/dist/commands/clean.js +35 -9
  16. package/dist/commands/clean.js.map +1 -1
  17. package/dist/commands/completion.d.ts.map +1 -1
  18. package/dist/commands/completion.js +3 -2
  19. package/dist/commands/completion.js.map +1 -1
  20. package/dist/commands/config.d.ts.map +1 -1
  21. package/dist/commands/config.js +24 -7
  22. package/dist/commands/config.js.map +1 -1
  23. package/dist/commands/describe.js +2 -2
  24. package/dist/commands/describe.js.map +1 -1
  25. package/dist/commands/doctor.d.ts.map +1 -1
  26. package/dist/commands/doctor.js +25 -7
  27. package/dist/commands/doctor.js.map +1 -1
  28. package/dist/commands/down.d.ts.map +1 -1
  29. package/dist/commands/down.js +43 -12
  30. package/dist/commands/down.js.map +1 -1
  31. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  32. package/dist/commands/endpoint-authoring.js +16 -4
  33. package/dist/commands/endpoint-authoring.js.map +1 -1
  34. package/dist/commands/endpoint.d.ts.map +1 -1
  35. package/dist/commands/endpoint.js +8 -3
  36. package/dist/commands/endpoint.js.map +1 -1
  37. package/dist/commands/ext.d.ts.map +1 -1
  38. package/dist/commands/ext.js +9 -8
  39. package/dist/commands/ext.js.map +1 -1
  40. package/dist/commands/history-clear.d.ts.map +1 -1
  41. package/dist/commands/history-clear.js +10 -3
  42. package/dist/commands/history-clear.js.map +1 -1
  43. package/dist/commands/history-limit.js +2 -2
  44. package/dist/commands/history-limit.js.map +1 -1
  45. package/dist/commands/history.d.ts +1 -1
  46. package/dist/commands/history.d.ts.map +1 -1
  47. package/dist/commands/history.js +101 -41
  48. package/dist/commands/history.js.map +1 -1
  49. package/dist/commands/join.d.ts.map +1 -1
  50. package/dist/commands/join.js +54 -23
  51. package/dist/commands/join.js.map +1 -1
  52. package/dist/commands/manager-service.d.ts.map +1 -1
  53. package/dist/commands/manager-service.js +5 -1
  54. package/dist/commands/manager-service.js.map +1 -1
  55. package/dist/commands/meshes-add.d.ts +4 -0
  56. package/dist/commands/meshes-add.d.ts.map +1 -1
  57. package/dist/commands/meshes-add.js +35 -1
  58. package/dist/commands/meshes-add.js.map +1 -1
  59. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  60. package/dist/commands/meshes-wizard.js +5 -5
  61. package/dist/commands/meshes-wizard.js.map +1 -1
  62. package/dist/commands/meshes.d.ts.map +1 -1
  63. package/dist/commands/meshes.js +4 -3
  64. package/dist/commands/meshes.js.map +1 -1
  65. package/dist/commands/mint.d.ts.map +1 -1
  66. package/dist/commands/mint.js +11 -4
  67. package/dist/commands/mint.js.map +1 -1
  68. package/dist/commands/persona-remote.js +2 -2
  69. package/dist/commands/persona-remote.js.map +1 -1
  70. package/dist/commands/persona.d.ts.map +1 -1
  71. package/dist/commands/persona.js +28 -9
  72. package/dist/commands/persona.js.map +1 -1
  73. package/dist/commands/personas.d.ts.map +1 -1
  74. package/dist/commands/personas.js +17 -15
  75. package/dist/commands/personas.js.map +1 -1
  76. package/dist/commands/reset-space-apply.js +4 -4
  77. package/dist/commands/reset-space-apply.js.map +1 -1
  78. package/dist/commands/reset-store-apply.d.ts +2 -8
  79. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  80. package/dist/commands/reset-store-apply.js +12 -28
  81. package/dist/commands/reset-store-apply.js.map +1 -1
  82. package/dist/commands/reset.js +2 -2
  83. package/dist/commands/reset.js.map +1 -1
  84. package/dist/commands/send.d.ts.map +1 -1
  85. package/dist/commands/send.js +21 -9
  86. package/dist/commands/send.js.map +1 -1
  87. package/dist/commands/service-actions.d.ts.map +1 -1
  88. package/dist/commands/service-actions.js +15 -4
  89. package/dist/commands/service-actions.js.map +1 -1
  90. package/dist/commands/service-registry.d.ts.map +1 -1
  91. package/dist/commands/service-registry.js +16 -5
  92. package/dist/commands/service-registry.js.map +1 -1
  93. package/dist/commands/setup.d.ts.map +1 -1
  94. package/dist/commands/setup.js +18 -10
  95. package/dist/commands/setup.js.map +1 -1
  96. package/dist/commands/space-delete.d.ts.map +1 -1
  97. package/dist/commands/space-delete.js +72 -33
  98. package/dist/commands/space-delete.js.map +1 -1
  99. package/dist/commands/space-export.js +1 -1
  100. package/dist/commands/space-export.js.map +1 -1
  101. package/dist/commands/space-registration.d.ts +4 -3
  102. package/dist/commands/space-registration.d.ts.map +1 -1
  103. package/dist/commands/space-registration.js +63 -41
  104. package/dist/commands/space-registration.js.map +1 -1
  105. package/dist/commands/space.d.ts.map +1 -1
  106. package/dist/commands/space.js +24 -8
  107. package/dist/commands/space.js.map +1 -1
  108. package/dist/commands/spawn-enrollment.d.ts +93 -0
  109. package/dist/commands/spawn-enrollment.d.ts.map +1 -0
  110. package/dist/commands/spawn-enrollment.js +195 -0
  111. package/dist/commands/spawn-enrollment.js.map +1 -0
  112. package/dist/commands/spawn-flags.d.ts +205 -0
  113. package/dist/commands/spawn-flags.d.ts.map +1 -0
  114. package/dist/commands/spawn-flags.js +34 -0
  115. package/dist/commands/spawn-flags.js.map +1 -0
  116. package/dist/commands/spawn-foreground.d.ts +74 -0
  117. package/dist/commands/spawn-foreground.d.ts.map +1 -0
  118. package/dist/commands/spawn-foreground.js +355 -0
  119. package/dist/commands/spawn-foreground.js.map +1 -0
  120. package/dist/commands/spawn-managed-launch.d.ts +43 -0
  121. package/dist/commands/spawn-managed-launch.d.ts.map +1 -0
  122. package/dist/commands/spawn-managed-launch.js +631 -0
  123. package/dist/commands/spawn-managed-launch.js.map +1 -0
  124. package/dist/commands/spawn-preview.d.ts.map +1 -1
  125. package/dist/commands/spawn-preview.js +7 -4
  126. package/dist/commands/spawn-preview.js.map +1 -1
  127. package/dist/commands/spawn.d.ts +8 -266
  128. package/dist/commands/spawn.d.ts.map +1 -1
  129. package/dist/commands/spawn.js +21 -1198
  130. package/dist/commands/spawn.js.map +1 -1
  131. package/dist/commands/stack-down.d.ts +3 -2
  132. package/dist/commands/stack-down.d.ts.map +1 -1
  133. package/dist/commands/stack-down.js +72 -31
  134. package/dist/commands/stack-down.js.map +1 -1
  135. package/dist/commands/stack-up.d.ts +2 -0
  136. package/dist/commands/stack-up.d.ts.map +1 -1
  137. package/dist/commands/stack-up.js +16 -7
  138. package/dist/commands/stack-up.js.map +1 -1
  139. package/dist/commands/status-stop-impact.d.ts +3 -0
  140. package/dist/commands/status-stop-impact.d.ts.map +1 -0
  141. package/dist/commands/status-stop-impact.js +34 -0
  142. package/dist/commands/status-stop-impact.js.map +1 -0
  143. package/dist/commands/status.d.ts.map +1 -1
  144. package/dist/commands/status.js +96 -80
  145. package/dist/commands/status.js.map +1 -1
  146. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  147. package/dist/commands/team-boot-controller.js +21 -4
  148. package/dist/commands/team-boot-controller.js.map +1 -1
  149. package/dist/commands/team.d.ts.map +1 -1
  150. package/dist/commands/team.js +25 -23
  151. package/dist/commands/team.js.map +1 -1
  152. package/dist/commands/telemetry.d.ts +1 -1
  153. package/dist/commands/telemetry.d.ts.map +1 -1
  154. package/dist/commands/telemetry.js +17 -7
  155. package/dist/commands/telemetry.js.map +1 -1
  156. package/dist/commands/up-target.d.ts +7 -0
  157. package/dist/commands/up-target.d.ts.map +1 -0
  158. package/dist/commands/up-target.js +42 -0
  159. package/dist/commands/up-target.js.map +1 -0
  160. package/dist/commands/up.d.ts +4 -11
  161. package/dist/commands/up.d.ts.map +1 -1
  162. package/dist/commands/up.js +212 -207
  163. package/dist/commands/up.js.map +1 -1
  164. package/dist/commands/update-caches.d.ts +4 -0
  165. package/dist/commands/update-caches.d.ts.map +1 -0
  166. package/dist/commands/update-caches.js +82 -0
  167. package/dist/commands/update-caches.js.map +1 -0
  168. package/dist/commands/update.d.ts.map +1 -1
  169. package/dist/commands/update.js +29 -115
  170. package/dist/commands/update.js.map +1 -1
  171. package/dist/commands/use.d.ts.map +1 -1
  172. package/dist/commands/use.js +43 -22
  173. package/dist/commands/use.js.map +1 -1
  174. package/dist/commands/who.d.ts.map +1 -1
  175. package/dist/commands/who.js +2 -3
  176. package/dist/commands/who.js.map +1 -1
  177. package/dist/console/commands.d.ts.map +1 -1
  178. package/dist/console/commands.js +3 -2
  179. package/dist/console/commands.js.map +1 -1
  180. package/dist/help.d.ts.map +1 -1
  181. package/dist/help.js +2 -1
  182. package/dist/help.js.map +1 -1
  183. package/dist/index.d.ts.map +1 -1
  184. package/dist/index.js +5 -2
  185. package/dist/index.js.map +1 -1
  186. package/dist/lib/broker-log.d.ts +8 -0
  187. package/dist/lib/broker-log.d.ts.map +1 -0
  188. package/dist/lib/broker-log.js +27 -0
  189. package/dist/lib/broker-log.js.map +1 -0
  190. package/dist/lib/completion-install.d.ts.map +1 -1
  191. package/dist/lib/completion-install.js +17 -10
  192. package/dist/lib/completion-install.js.map +1 -1
  193. package/dist/lib/credential-authority.d.ts +7 -3
  194. package/dist/lib/credential-authority.d.ts.map +1 -1
  195. package/dist/lib/credential-authority.js +44 -11
  196. package/dist/lib/credential-authority.js.map +1 -1
  197. package/dist/lib/manifest/ledger.d.ts.map +1 -1
  198. package/dist/lib/manifest/ledger.js +7 -3
  199. package/dist/lib/manifest/ledger.js.map +1 -1
  200. package/dist/lib/paths.d.ts.map +1 -1
  201. package/dist/lib/paths.js +3 -3
  202. package/dist/lib/paths.js.map +1 -1
  203. package/dist/lib/restore.d.ts +32 -3
  204. package/dist/lib/restore.d.ts.map +1 -1
  205. package/dist/lib/restore.js +65 -54
  206. package/dist/lib/restore.js.map +1 -1
  207. package/dist/lib/service-preset-target.d.ts +2 -2
  208. package/dist/lib/service-preset-target.d.ts.map +1 -1
  209. package/dist/lib/service-preset-target.js +30 -15
  210. package/dist/lib/service-preset-target.js.map +1 -1
  211. package/dist/lib/service-presets.d.ts +2 -0
  212. package/dist/lib/service-presets.d.ts.map +1 -1
  213. package/dist/lib/service-presets.js +19 -2
  214. package/dist/lib/service-presets.js.map +1 -1
  215. package/dist/lib/spawn-defaults.d.ts +5 -0
  216. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  217. package/dist/lib/spawn-defaults.js +5 -0
  218. package/dist/lib/spawn-defaults.js.map +1 -1
  219. package/dist/lib/stack-journal.d.ts +7 -4
  220. package/dist/lib/stack-journal.d.ts.map +1 -1
  221. package/dist/lib/stack-journal.js +31 -15
  222. package/dist/lib/stack-journal.js.map +1 -1
  223. package/dist/lib/transient.d.ts +3 -3
  224. package/dist/lib/transient.d.ts.map +1 -1
  225. package/dist/lib/transient.js +6 -5
  226. package/dist/lib/transient.js.map +1 -1
  227. package/dist/lib/up-broker-address.d.ts +7 -0
  228. package/dist/lib/up-broker-address.d.ts.map +1 -0
  229. package/dist/lib/up-broker-address.js +76 -0
  230. package/dist/lib/up-broker-address.js.map +1 -0
  231. package/dist/lib/up-report.d.ts +2 -0
  232. package/dist/lib/up-report.d.ts.map +1 -1
  233. package/dist/lib/up-report.js +8 -1
  234. package/dist/lib/up-report.js.map +1 -1
  235. package/dist/lib/update-connector-config.d.ts +6 -0
  236. package/dist/lib/update-connector-config.d.ts.map +1 -0
  237. package/dist/lib/update-connector-config.js +44 -0
  238. package/dist/lib/update-connector-config.js.map +1 -0
  239. package/dist/seed/reconcile.d.ts +1 -1
  240. package/dist/seed/reconcile.d.ts.map +1 -1
  241. package/dist/seed/reconcile.js +113 -35
  242. package/dist/seed/reconcile.js.map +1 -1
  243. package/package.json +4 -4
@@ -1,186 +1,35 @@
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, agentFilePath, 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, 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 { checkDialPolicy, checkEnforcement, checkServer, checkBundleDocument, persistRemoteUserEntry, probeEnforcement, tlsIntent, userExchangeIssuer, verifyUserExchange, } from "./meshes-add.js";
32
- import { askManager, describeUnanswered, liveManagerIds, managerRailGone, refuseUnregisteredManager, refuseWithoutLiveManager, START_TIMEOUT_MS, startStackManagerRemedy, withControlConnection } from "@cotal-ai/workspace/control";
33
- const ENROLLMENT_URL_ENV = "COTAL_ENROLLMENT_URL";
34
- const ENROLLMENT_FILE_ENV = "COTAL_ENROLLMENT_FILE";
35
- /** Remove the one line terminator a text file ends with, and nothing else: the file holds the URL
36
- * and at most that terminator. Any other whitespace belongs to the credential the owner minted and
37
- * must reach the URL grammar, which refuses it rather than silently redeeming a repaired URL. The
38
- * environment value is taken byte for byte; nothing is stripped from it. */
39
- function stripTrailingNewline(value) {
40
- return value.replace(/\r?\n$/, "");
41
- }
42
- export function enrollmentInput(env = process.env) {
43
- const rawUrl = env[ENROLLMENT_URL_ENV];
44
- const file = env[ENROLLMENT_FILE_ENV]?.trim();
45
- if (rawUrl && file)
46
- throw new Error(`both ${ENROLLMENT_URL_ENV} and ${ENROLLMENT_FILE_ENV} are set - pass one enrollment source, not both`);
47
- if (rawUrl)
48
- return rawUrl;
49
- if (!file)
50
- return undefined;
51
- let st;
52
- try {
53
- st = statSync(file);
54
- }
55
- catch (e) {
56
- throw new Error(`cannot read the enrollment file (${e instanceof Error ? e.message : String(e)})`);
57
- }
58
- if (!st.isFile())
59
- throw new Error("the enrollment file path is not a regular file");
60
- if (process.platform !== "win32" && (st.mode & 0o777) !== 0o600)
61
- throw new Error("the enrollment file must have mode 0600");
62
- const value = stripTrailingNewline(readFileSync(file, "utf8"));
63
- if (!value)
64
- throw new Error("the enrollment file is empty");
65
- return value;
66
- }
67
- export function scrubEnrollmentEnv(env) {
68
- if (!env)
69
- return;
70
- for (const key of Object.keys(env)) {
71
- const normalized = key.toUpperCase();
72
- if (normalized === ENROLLMENT_URL_ENV || normalized === ENROLLMENT_FILE_ENV)
73
- delete env[key];
74
- }
75
- }
76
- /** Carry the launching manager's validated `COTAL_MANAGER_INSTANCE` onto a managed-handoff
77
- * child's connector launch spec (`spawnProcess` passes `env: spec.env` only, and `launchEnv`
78
- * does not forward `COTAL_MANAGER_INSTANCE` from `process.env`). */
79
- export function applyHandoffManagerInstance(spec, handoffManagerInstanceId) {
80
- if (handoffManagerInstanceId !== undefined) {
81
- spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: handoffManagerInstanceId };
82
- }
83
- }
84
- export function checkEnrollmentBundle(raw, actor) {
85
- const material = checkRemoteAgentMaterial(raw, actor);
86
- if (!material.ok)
87
- throw new Error(material.message.replaceAll("agent-provisioning endpoint", "enrollment endpoint"));
88
- const o = raw;
89
- if (typeof o.space !== "string" || !o.space)
90
- throw new Error("the enrollment bundle names no space");
91
- if (o.brokerAccess === null || typeof o.brokerAccess !== "object" || typeof o.brokerAccess.kind !== "string" || !o.brokerAccess.kind)
92
- throw new Error("the enrollment bundle carries no brokerAccess kind");
93
- if (typeof o.authServiceUrl !== "string" || !o.authServiceUrl)
94
- throw new Error("the enrollment bundle carries no authServiceUrl");
95
- const idp = o.idp;
96
- if (idp === null || typeof idp !== "object" || typeof idp.url !== "string" || !idp.url ||
97
- typeof idp.issuer !== "string" || !idp.issuer || typeof idp.audience !== "string" || !idp.audience)
98
- throw new Error("the enrollment bundle carries no complete idp { url, issuer, audience }");
99
- let stock;
100
- const hasStock = [o.server, o.tlsRequired, o.userAuth].some((v) => v !== undefined);
101
- const rawPolicy = o.policy;
102
- if (rawPolicy !== undefined && !hasStock)
103
- throw new Error("the enrollment bundle's policy requires its stock server, tlsRequired, and userAuth fields");
104
- if (hasStock) {
105
- if ([o.server, o.tlsRequired, o.userAuth].some((v) => v === undefined))
106
- throw new Error("the enrollment bundle's stock mesh fields must include server, tlsRequired, and userAuth together");
107
- const checked = checkBundleDocument({
108
- space: o.space,
109
- server: o.server,
110
- tlsRequired: o.tlsRequired,
111
- userAuth: o.userAuth,
112
- policy: o.policy,
113
- sentinelCreds: material.material.sentinelCreds,
114
- });
115
- if (!checked.ok)
116
- throw new Error(checked.message.replace(/^✗\s*/, ""));
117
- stock = checked.value;
118
- if (stock.userAuth.idp.url !== idp.url || stock.userAuth.idp.issuer !== idp.issuer || stock.userAuth.idp.audience !== idp.audience)
119
- throw new Error("the enrollment bundle's stock userAuth IdP pins do not match its top-level idp pins");
120
- if (stock.userAuth.endpoints.url !== o.authServiceUrl)
121
- throw new Error("the enrollment bundle's stock userAuth exchange URL does not match authServiceUrl");
122
- const access = o.brokerAccess;
123
- if (access.kind === "direct" && (typeof access.url !== "string" || !access.url))
124
- throw new Error("the enrollment bundle's direct brokerAccess carries no url");
125
- if (access.kind === "direct" && access.url !== stock.server)
126
- throw new Error("the enrollment bundle's direct brokerAccess url does not match its stock server");
127
- }
128
- return { bundle: { ...o, ...material.material, idp }, ...(stock ? { stock } : {}) };
129
- }
130
- /** What a managed handoff's bootstrap refuses with at each phase that runs a check shared with the
131
- * enrollment path. Those checks' diagnostics, and the filesystem errors under them, quote the
132
- * space, the server, the exchange URL, the actor or a path named for one of them, and a handoff
133
- * refusal never echoes the document, so each sentence names only the field and the phase. */
134
- const HANDOFF_REFUSALS = {
135
- space: "the managed handoff's space is malformed",
136
- bundle: "the managed handoff's mesh fields failed the user-auth bundle check",
137
- registration: "the managed handoff's space failed the local registration",
138
- target: "the managed handoff's space failed target resolution",
139
- server: "the managed handoff's server is not a broker URL this machine may dial",
140
- exchange: "the managed handoff's exchangeUrl failed the exchange check",
141
- enforcement: "the managed handoff's server failed the enforcement check",
142
- policy: "the managed handoff's exchangeUrl failed the policy refresh",
143
- preflight: "the managed handoff's server failed the broker preflight",
144
- bearer: "the managed handoff's actorToken failed the agent auth preflight",
145
- };
146
- /** Map a parsed handoff onto the redeem consumer's shapes. Pure. */
147
- export function handoffEnrollmentBundle(h) {
148
- const userAuth = { provider: h.authProvider, idp: h.idp, endpoints: { url: h.exchangeUrl }, remote: true };
149
- try {
150
- const { bundle, stock } = checkEnrollmentBundle({
151
- space: h.space, actor: h.actor, owner: h.owner, lifecycleUid: h.lifecycleUid, actorToken: h.actorToken, sentinelCreds: h.sentinelCreds,
152
- subscribe: h.subscribe, allowSubscribe: h.allowSubscribe, allowPublish: h.allowPublish,
153
- brokerAccess: { kind: "direct", url: h.server }, authServiceUrl: h.exchangeUrl, idp: h.idp,
154
- server: h.server, tlsRequired: h.tlsRequired, userAuth, ...(h.policy ? { policy: h.policy } : {}),
155
- }, h.actor);
156
- return { bundle, stock: stock };
157
- }
158
- catch {
159
- throw new Error(HANDOFF_REFUSALS.bundle);
160
- }
161
- }
162
- /** With `refusals`, a step that fails its check or throws refuses with its phase's sentence instead
163
- * of its diagnostic. */
164
- async function registerEnrollmentMesh(stock, root, refusals) {
165
- const step = async (phase, run) => {
166
- let check;
167
- try {
168
- check = await run();
169
- }
170
- catch (e) {
171
- throw refusals ? new Error(refusals[phase]) : e;
172
- }
173
- if (!check.ok)
174
- throw new Error(refusals?.[phase] ?? check.message.replace(/^✗\s*/, ""));
175
- return check.value;
176
- };
177
- await step("server", () => checkServer(stock.server, "the enrollment bundle's server"));
178
- const tlsRequired = stock.tlsRequired || tlsIntent(stock.server, false);
179
- const dial = await step("server", () => checkDialPolicy(stock.server, { tlsRequired, allowUnencryptedOverlay: false }));
180
- await step("exchange", () => verifyUserExchange(stock.userAuth.endpoints.url, userExchangeIssuer(stock.space)));
181
- await step("enforcement", async () => checkEnforcement("user", await probeEnforcement(stock.server), stock.server, stock.space, root));
182
- await step("registration", () => ({ ok: true, value: persistRemoteUserEntry(stock.space, stock.server, root, stock, tlsRequired, Boolean(dial.residual)) }));
183
- }
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";
32
+ export { enrollmentInput, scrubEnrollmentEnv, applyHandoffManagerInstance, checkEnrollmentBundle, handoffEnrollmentBundle } from "./spawn-enrollment.js";
184
33
  /** Completion for `cotal spawn` — `--space <TAB>` lists the running meshes, and the first positional
185
34
  * is a persona from the mesh this spawn would target. Resolved OFFLINE (registry + `current`, no
186
35
  * probe — a <TAB> must stay cheap and never open the network), so it lists the *target* mesh's
@@ -244,77 +93,6 @@ function declaredFrom(argv, list) {
244
93
  return list(root);
245
94
  }
246
95
  export { spawnPersona } from "../lib/spawn-defaults.js";
247
- /**
248
- * Auto-number `requested` past any peer already present on the mesh (foo → foo_2 → foo_3) — the same
249
- * series the manager's spawn funnel uses (firstFreeName). Foreground `cotal spawn` doesn't go through
250
- * the manager, so it has no name reservation: this is a best-effort, advisory check. It connects a
251
- * transient presence-watching endpoint, lets the roster settle, and snapshots the live names; two
252
- * simultaneous `cotal spawn`s can still race onto the same number. If the mesh is unreachable the
253
- * agent couldn't join it anyway, so dedup is skipped and the requested name stands.
254
- */
255
- async function uniqueMeshName(requested, target) {
256
- const taken = await liveMeshNames(target);
257
- return taken ? firstFreeName(requested, (n) => taken.has(n)) : requested;
258
- }
259
- /** Only an occupied actor is retryable; authorization and provisioning failures stay failures.
260
- * Thrown only where the collision is found before anything is launched, issued or redeemed, so
261
- * it is a refusal. */
262
- class ForegroundActorCollision extends CommandFailure {
263
- constructor(message) {
264
- super("refused", "CONFLICT", message);
265
- }
266
- }
267
- async function provisionFreshForeground(requested, autoName, userMode, provision) {
268
- const occupied = new Set();
269
- for (;;) {
270
- let name;
271
- try {
272
- // The cap belongs to user mode alone, where the numbered name is the actor. Static and open
273
- // mode key the actor on the minted nkey, so a numbered name there has no length to fit.
274
- name = firstFreeName(requested, (candidate) => occupied.has(candidate), userMode ? { actorBound: true } : undefined);
275
- }
276
- catch (e) {
277
- // The series stops at the actor bound, so a base whose every fitting candidate is taken is a
278
- // refusal, not a crash: nothing has been launched, issued or redeemed yet.
279
- throw new CommandFailure("refused", "CONFLICT", e instanceof Error ? e.message : String(e));
280
- }
281
- try {
282
- return { name, provisioned: await provision(name) };
283
- }
284
- catch (e) {
285
- if (!autoName || !(e instanceof ForegroundActorCollision || e instanceof AgentGrantConflictError || e instanceof AgentAlreadyRunning))
286
- throw e;
287
- occupied.add(name);
288
- }
289
- }
290
- }
291
- /** `cotal spawn`'s grammar: the application in this terminal by default, a manager's launch only
292
- * with `--detach` or `--on`, and one positional persona or explicit persona file. Declared `as const` so the values cast
293
- * below is compile-checked against exactly these specs. Foreground and detached parse the SAME
294
- * flags — the old `spawn` vs `start` ability drift is structurally gone. */
295
- export const spawnFlags = [
296
- spaceFlag,
297
- serverFlag,
298
- { ...credsFlag, description: "control-caller creds for an off-registry manager (with --detach or --on)" },
299
- ...launchFlags,
300
- { name: "harness", short: "H", type: "string", value: "<connector>", description: "application connector; an explicit flag wins over persona and saved defaults" },
301
- { name: "foreground", type: "boolean", description: "run the application in this terminal, as a spawn without --detach or --on does; terminal exit may end it" },
302
- { name: "restarts", type: "string", value: "<n>", description: "with --detach or --on: maximum manager-supervised restarts in the selected restart window" },
303
- { name: "restart-window", type: "string", value: "<ms>", description: "time window for --restarts; both flags are required together" },
304
- jsonFlag, plainFlag,
305
- { name: "detach", type: "boolean", short: "d", description: "launch through a manager, await readiness and return without attaching" },
306
- { name: "live-only", type: "boolean", description: "foreground only: skip the durable backstop (no read-ACL row; messages missed while disconnected are not replayed)" },
307
- { 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" },
308
- { 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" },
309
- { name: "file", type: "string", short: "f", value: "<persona-file>", description: "persona file on the execution host; never a manifest deploy or implicit upload" },
310
- { name: "dry-run", type: "boolean", description: "preview the launch without allocation, provisioning or starting an application" },
311
- { 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" },
312
- { name: "allow-stale", type: "string", value: "<a,b>", description: "refused: a manifest deployment option; use `cotal team deploy <file>`" },
313
- { name: "runtime", type: "string", value: "<name>", description: "terminal runtime for this one managed seat; omitted, the serving manager uses its own" },
314
- { 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" },
315
- { name: "expect-owner", type: "string", value: "<u_…>", description: `with ${MANAGED_HANDOFF_FILE_ENV}: the owner the managed handoff must carry` },
316
- { name: "expect-lifecycle-uid", type: "string", value: "<uid>", description: `with ${MANAGED_HANDOFF_FILE_ENV}: the lifecycle UID the managed handoff must carry` },
317
- ];
318
96
  /** The expiry a seat started in this terminal asked for, in unix seconds, or `undefined` for none.
319
97
  * A managed seat's credential is renewed by its manager, so the flags belong to this terminal. */
320
98
  function seatExpiry(values, direct) {
@@ -322,9 +100,6 @@ function seatExpiry(values, direct) {
322
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" });
323
101
  return seatExpiryAt(values);
324
102
  }
325
- /** The spawn an `--on` refusal tells the caller to rerun: the persona and `-d` as given, with the
326
- * `--space` or `--server` given (#7644). */
327
- const spawnRerun = (values, positionals) => onRerun("cotal spawn", values, [...positionals, ...(values.detach === true ? ["-d"] : [])]);
328
103
  /** Check the public mode and spelling before catalog preparation or identity allocation.
329
104
  * Return the parsed channel overrides for the foreground policy. */
330
105
  export function validateSpawnArguments(args) {
@@ -463,617 +238,6 @@ export function validateSpawnArguments(args) {
463
238
  export function spawnRequiredExtensions(_args) {
464
239
  return [];
465
240
  }
466
- /** Whether the installed manifest lists a connector named `name`. An unreadable manifest answers
467
- * true, so the import's own refusal reports it. */
468
- function connectorListed(name) {
469
- try {
470
- return manifestExtensionNames("connector").includes(name);
471
- }
472
- catch {
473
- return true;
474
- }
475
- }
476
- /** #867: the name a spawn sends must already be a mintable identity, and the check must not wait
477
- * for the manager's round trip. `spawnNameError` is the SAME predicate the manager applies at its
478
- * door (manager.ts `start`), so the operator sees core's own refusal — offending character,
479
- * reservation reason, and the `_` remedy — before any request leaves. A courtesy only: the
480
- * manager door stays the enforcement point; this is why the CLI passes the target mesh's auth
481
- * mode rather than restating the grammar (static mode keys the actor on the nkey, not the name). */
482
- function refuseUnmintableName(name, userMode) {
483
- const refusal = spawnNameError(name, { userMode });
484
- if (refusal)
485
- throw new CommandFailure("refused", "USAGE_INVALID", refusal, { selfContained: true });
486
- }
487
- /** Whether a managed launch can reach only this root's own manager: the instance it names, or else
488
- * the only one the registry lists, is the one recorded under the target's root. An unread registry
489
- * or an unreadable record proves nothing, and the launch then goes to whichever manager serves it. */
490
- export function launchServedHere(t, serving, live) {
491
- if (t.root === undefined)
492
- return false;
493
- let here;
494
- try {
495
- here = loadManagerInstanceIdentity(t.root, t.space)?.instanceId;
496
- }
497
- catch {
498
- return false;
499
- }
500
- if (here === undefined)
501
- return false;
502
- return serving !== undefined ? serving === here : live?.length === 1 && live[0] === here;
503
- }
504
- /** A runtime this root's own manager cannot launch on is refused before the launch is sent, through
505
- * the installed-extension lookup `up --runtime` uses. A manager on another host reads that host's
506
- * extensions, so a launch that may reach one sends the name and that manager decides. */
507
- async function refuseRuntimeHere(runtime, t, serving, live) {
508
- if (!launchServedHere(t, serving, live))
509
- return;
510
- try {
511
- await preflightRuntime(runtime);
512
- }
513
- catch (error) {
514
- 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" });
515
- }
516
- }
517
- const channelList = (channels) => channels.length ? channels.join(", ") : "none";
518
- export function managedLaunchView(r) {
519
- const concrete = [r.name, r.space, r.managerInstanceId].every((value) => /^[A-Za-z0-9_-]+$/.test(value));
520
- const target = concrete ? `${r.name} --space ${r.space} --on ${r.managerInstanceId}` : "<name> --space <space> --on <manager-instance>";
521
- const noStream = r.streamsTerminal === false;
522
- return { sections: [
523
- { title: "Agent joined", blocks: [
524
- { 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"]] },
525
- { kind: "lines", lines: [{ text: "The manager confirmed presence readiness. This is not proof that the kickoff task completed.", tone: "hint" }] },
526
- ] },
527
- ...(noStream ? [{ title: "Next", blocks: [
528
- { kind: "commands", items: [
529
- { command: `${displayCmd()} watch --space ${r.space}`, description: "Follow this mesh, this agent's messages included" },
530
- { command: `${displayCmd()} send -t ${r.name} "<message>"`, description: "Give the agent work over the mesh" },
531
- { command: `${displayCmd()} status ${target}`, description: "Read the agent's reported state" },
532
- ] },
533
- { kind: "lines", lines: [{ text: `${displayCmd()} attach is not available here: the ${r.runtime} runtime streams no terminal.`, tone: "hint" }] },
534
- ] }] : r.detached ? [{ title: "Next", blocks: [{ kind: "commands", items: [
535
- { command: `${displayCmd()} attach ${target}`, description: concrete ? "Return to this allocated incarnation's manager" : "Use the full identities recorded above" },
536
- { command: `${displayCmd()} status ${target}`, description: "Read the agent's reported state" },
537
- ] }] }] : []),
538
- ] };
539
- }
540
- /** The auth mode of the mesh `flags` name, or undefined when they name no registered mesh, which
541
- * the launch's own resolve then reports. */
542
- function meshMode(flags) {
543
- try {
544
- return resolveMeshTarget(process.cwd(), { space: flags.space, server: flags.server }).mode;
545
- }
546
- catch {
547
- return undefined;
548
- }
549
- }
550
- /** Shared managed launch. The manager resolves its persona and returns real readiness before
551
- * any view opens. Detach changes terminal attachment, not the launch or caller authority. */
552
- export async function launchManagedPersona(values, positionals, events, launchOptions, observer) {
553
- // WHICH file the manager loads — the exact foreground precedence (`--config` > positional >
554
- // `COTAL_DEFAULT_PERSONA` > `default`). Identity is separate:
555
- // when `--name` is given it OVERRIDES the file's `name:` (foreground's `requested`), threaded
556
- // as the op's `identity` so it is never silently dropped in detached mode.
557
- let on = await managerPin(values, spawnRerun(values, positionals));
558
- // From a managed seat's own shell the launch is the SEAT's, as its `cotal_spawn` tool is: the
559
- // manager records the seat as the spawner, so the seat can stop the child it asked for (#718).
560
- // `--on` keeps the pin on that path too.
561
- const flags = { space: values.space, server: values.server, creds: values.creds };
562
- const seatIntent = Boolean(process.env.COTAL_NAME || process.env.COTAL_ID || process.env.COTAL_LIFECYCLE_UID || process.env.COTAL_ACCEPTED_TOKEN);
563
- if (seatIntent && values.creds !== undefined)
564
- throw new CommandFailure("refused", "USAGE_INVALID", "a managed seat's child launch uses that seat's own caller, not a --creds override");
565
- let cwd = values.cwd;
566
- // On a terminal, a pinned manager that is not known to run on this host is asked which of its
567
- // folders the agent works in, unless -C names one. One resolve, dropped again here, answers
568
- // everything that question needs: that the mesh runs and the pin names a manager that is running,
569
- // which manager an unpinned launch on a user-auth mesh goes to (the exchange picks your only live
570
- // one, and the launch is pinned to it so the question asks about the manager that runs the
571
- // agent), and the host that manager reports. So an unknown --on or a stopped mesh is refused
572
- // before anything is asked, and the question still holds no manager credential: a typed folder is
573
- // checked under a view of that manager acquired after it is answered, and the launch acquires its
574
- // own below. A manager that has stopped by the time the launch is sent is refused there and goes
575
- // to no other manager.
576
- if (cwd === undefined && !seatIntent && canPrompt() && (on !== undefined || (values.creds === undefined && meshMode(flags) === "user"))) {
577
- const probe = await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
578
- const pin = on ?? probe.auth.managerInstanceId;
579
- if (pin !== undefined) {
580
- if (!probe.auth.bearer)
581
- await refuseUnregisteredManager(probe.space, probe.server, probe.auth, pin);
582
- on = pin;
583
- const selection = await managerSelection(values, pin, probe);
584
- if (selection.manager.host !== hostname()) {
585
- const folder = await askManagerFolder(selection, process.argv.slice(2), (path) => checkFolder(flags, pin, path));
586
- if (folder === null)
587
- process.exit(0);
588
- cwd = folder;
589
- }
590
- }
591
- }
592
- let seat;
593
- if (seatIntent) {
594
- try {
595
- seat = await resolveSeatControlTarget({ ...flags, space: flags.space ?? process.env.COTAL_SPACE }, on);
596
- }
597
- catch {
598
- throw new CommandFailure("refused", "AUTH_REQUIRED", "the launching seat's own credential could not be verified; no operator identity was substituted");
599
- }
600
- if (!seat)
601
- 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");
602
- }
603
- const t = seat ?? await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
604
- recordOperationSpace(t.space);
605
- let policy;
606
- try {
607
- policy = await refreshRegistrationPolicy(t);
608
- }
609
- catch {
610
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected registration policy could not be observed; no manager launch was submitted");
611
- }
612
- // #867: refuse an unmintable identity BEFORE the round trip. On this path the persona is
613
- // resolved manager-side, so the effective identity is `--name` alone — when it is absent the
614
- // manager applies the same spawnNameError to the file's `name:` at its own door.
615
- if (values.name !== undefined)
616
- refuseUnmintableName(values.name, t.mode === "user");
617
- const eventsRequired = policy?.events === "required";
618
- if (eventsRequired && events === false) {
619
- throw new CommandFailure("refused", "PERMISSION_DENIED", `space "${t.space}" requires the event plane by registration policy; no launch was submitted`);
620
- }
621
- 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;
622
- // A pin the registry does not list is refused at once; only a registered manager is waited on.
623
- if (on !== undefined && !t.auth.bearer)
624
- await refuseUnregisteredManager(t.space, t.server, t.auth, on);
625
- if (values.runtime !== undefined)
626
- await refuseRuntimeHere(values.runtime.trim(), t, on ?? t.auth.managerInstanceId, live);
627
- const { ref, from: personaFrom } = spawnPersona(values.config, positionals, { space: t.space, preferences: cachedPreferences() });
628
- const managerConfigRef = values.config ?? (personaFrom !== undefined ? ref : undefined);
629
- const defaultAgent = callerHarness(t.space);
630
- let resumeClaim;
631
- if (values.resume !== undefined) {
632
- // Without a flag the harness is the persona pin or a default, which only the target manager
633
- // can read: ask it, so the carry looks with the connector the launch runs (#2899).
634
- const agent = values.agent ?? await launchAgentOrExit(t, on, { name: ref, config: managerConfigRef, defaultAgent });
635
- // The carry and its transfer-writer view stay on the mesh selected for this launch.
636
- const claim = await carryTranscript({ ...flags, space: t.space, server: t.server }, on, values.resume, agent);
637
- if (claim !== undefined)
638
- resumeClaim = { claim, agent };
639
- }
640
- // The report that answers names the mesh in its heading, so this block names it once, in a field.
641
- const toStdout = !observer && presentationOf(values) !== "json";
642
- (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));
643
- 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)))
644
- console.error(c.dim(line));
645
- const start = () => requestManagedLaunch({
646
- persona: ref,
647
- identity: values.name,
648
- role: values.role,
649
- // #869: keep an explicit `--agent` and the invoking operator's default (COTAL_DEFAULT_AGENT or a
650
- // saved harness preference) in separate fields. Collapsing them made the default
651
- // indistinguishable from a flag, so it beat the persona pin; dropping it instead changed detached
652
- // semantics whenever the manager's own environment differed. The manager applies flag > file >
653
- // caller default > manager default.
654
- agent: values.agent,
655
- defaultAgent,
656
- config: managerConfigRef,
657
- model: values.model,
658
- variant: values.variant,
659
- ...(values.restarts !== undefined ? { supervise: { restarts: Number(values.restarts), windowMs: Number(values["restart-window"]) } } : {}),
660
- launchOptions,
661
- cwd,
662
- resume: values.resume,
663
- resumeClaim,
664
- prompt: values.prompt,
665
- shareTools: parseShareSelection(values["share-tools"]),
666
- subscribe: parseCommaList(values.subscribe),
667
- allowSubscribe: parseCommaList(values["allow-subscribe"]),
668
- allowPublish: parseCommaList(values["allow-publish"]),
669
- // #373: send the bit only when the operator chose it. On an events-required space the
670
- // policy still forces the plane on (the manager refuses a non-admin caller on such a space
671
- // anyway, so the operator must hold the admin tier for the spawn to succeed at all).
672
- events: eventsRequired ? true : events,
673
- ...(values["no-event-payloads"] || policy?.eventPayloads === "withheld" ? { eventPayloads: false } : {}),
674
- ...(values.runtime !== undefined ? { runtime: values.runtime.trim() } : {}),
675
- // #159 B1: the manager replies only on a REAL outcome (presence join / process exit / ~30s
676
- // readiness backstop) — the start request must outlive that window, not the 5s op default.
677
- // `--on <instance>` pins the spawn to that exact manager instance (P2 item 3 multi-manager).
678
- }, (args) => askManager(cliControl, t.space, t.server, "start", args, t.auth, "owner", START_TIMEOUT_MS, { instanceId: on }));
679
- // A refusal before execution launched nothing, so the launch is sent again once a name held by a
680
- // lifecycle that is not running is released. A name that runs is not launched a second time.
681
- let reply;
682
- try {
683
- let mesh;
684
- try {
685
- mesh = resolveMeshTarget(process.cwd(), { space: flags.space, server: flags.server });
686
- }
687
- catch { /* no registered mesh: nothing to release */ }
688
- reply = await settleHeldName(flags, start, (o) => "value" in o && !o.value.ok && o.value.nativeOutcome === "not-executed"
689
- ? heldAnswer({ code: o.value.code, details: o.value.details, message: o.value.error ?? "" }, values.name) : undefined, meshRelease(mesh));
690
- }
691
- catch (e) {
692
- if (!(e instanceof AgentAlreadyRunning))
693
- throw e;
694
- if (observer)
695
- throw new CommandFailure("refused", "CONFLICT", `${e.message}; nothing new was launched`, { target: { space: t.space, agent: e.agent, managerInstanceId: e.manager?.instanceId ?? null } });
696
- return reportAlreadyRunning(e, values, t.space, t.server);
697
- }
698
- 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 } : {}) };
699
- // A launch whose process the manager reports running is starting: one that waits for the operator at
700
- // a screen its harness names was ready once it ran, and one that did not join in time may still be
701
- // coming up or sitting at a prompt. Either way the operator is sent to its terminal.
702
- const started = reply.ok ? reply.data : undefined;
703
- const running = !reply.ok && reply.code === "uncertain" && reply.details?.some((d) => d.kind === GOAL_ENTITY_RUNNING_DETAIL_KIND) === true;
704
- const startedName = typeof started?.name === "string" ? started.name : reply.request?.allocation?.name;
705
- if (!observer && reply.managerInstanceId && startedName && (typeof started?.waitingFor === "string" || running)) {
706
- const expected = typeof started?.id === "string" && typeof started.lifecycleUid === "string" ? { id: started.id, lifecycleUid: started.lifecycleUid } : undefined;
707
- return reportStarting({ name: startedName, managerInstanceId: reply.managerInstanceId, ...(typeof started?.waitingFor === "string" ? { waitingFor: started.waitingFor } : {}), ...(expected ? { expected } : {}) }, values, t.space, t.server, target);
708
- }
709
- if (!reply.ok) {
710
- 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" };
711
- const code = reply.code === undefined ? undefined : refusal[reply.code];
712
- 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 } } : {}) };
713
- // The broker attested that no manager received an unpinned launch: none takes the class queue.
714
- if (on === undefined && !t.auth.bearer && reply.unanswered && reply.nativeOutcome === "not-executed")
715
- throw await unservedClassLaunch(seat ? undefined : flags, t, values.agent ?? defaultAgent, { target, native });
716
- // A pinned describe that drew no answer means the launch was never sent, as ps and stop --on say.
717
- if (on !== undefined && describeUnanswered(reply))
718
- 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>" });
719
- // So does an unpinned one: no manager answered, and the launch was never published.
720
- if (on === undefined && describeUnanswered(reply))
721
- throw unansweredClassLaunch(t, { target, native: { code: reply.code, ...(reply.error ? { detail: oneLine(reply.error) } : {}) } });
722
- // The owner's seat cap. Keyed on the marker, not the code: the numbers are what a script acts
723
- // on, and the remedy is the operator's knob, neither of which a code alone can carry. It is a
724
- // CONFLICT with the seats this owner already holds, the same shape as a pinned-name collision:
725
- // nothing here is unreachable or unauthorized, and freeing one seat admits the launch.
726
- const cap = seatCapFrom(reply);
727
- if (cap !== undefined)
728
- throw new CommandFailure("refused", "CONFLICT", reply.error ? oneLine(reply.error) : "the manager refused the launch: this owner is at its seat cap", {
729
- target, native: { code: reply.code, outcome: reply.nativeOutcome, detail: { owner: cap.owner, seats: cap.seats, cap: cap.cap } },
730
- 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)`,
731
- });
732
- // A manager without the connector: it is added where that manager runs, not on this machine.
733
- const absent = reply.nativeOutcome === "not-executed" && reply.error !== undefined ? hintedConnector(reply.error) : undefined;
734
- if (absent !== undefined) {
735
- const answered = reply.managerInstanceId ?? on;
736
- 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,
737
- remedy: `add it where that manager runs, such as ${extAddFor(absent)}, then restart that manager; it reads its agent applications when it starts` });
738
- }
739
- if (reply.nativeOutcome === "not-executed" && code) {
740
- // A manager without the persona: it is created on that manager's host, or the spawn goes to
741
- // another live manager whose catalog has it.
742
- const missing = managerConfigRef === undefined && reply.error?.startsWith(`no persona "${ref}"`) === true;
743
- const elsewhere = missing ? await managersWithPersona(flags, reply.managerInstanceId ?? on, ref).catch(() => []) : [];
744
- throw new CommandFailure("refused", code, reply.error ? oneLine(reply.error) : "the manager refused the launch before execution", { target, native, remedy: elsewhere.length
745
- ? `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 ")}`
746
- : missing ? "nothing was launched; create that file on the manager's host, then run the spawn again"
747
- // This CLI refused before sending, so the manager reported nothing; the refusal names the side to update.
748
- : reply.details?.some((d) => d.kind === EP_UNDECLARED_ARG) ? "nothing was launched; update the side the refusal names, then run the spawn again"
749
- : "nothing was launched; fix what the manager reported, then run the spawn again" });
750
- }
751
- // A committed `failed` terminal is the manager's answer: the launch ran and failed, as an agent
752
- // that exits at once does, and the manager says why.
753
- if (reply.code === "failed")
754
- 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" });
755
- const unknown = reply.nativeOutcome !== "executed" || reply.unanswered;
756
- 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" });
757
- }
758
- const { result, eventsNotice, startupNotice } = readManagedLaunch(reply, { space: t.space, requestedModel: values.model ?? null, detached: values.detach === true }, target);
759
- const { streamsTerminal } = result;
760
- const presentation = presentationOf(values);
761
- const warnings = [
762
- ...(eventsNotice ? [{ code: "EVENT_PLANE_NOTICE", target, message: eventsNotice }] : []),
763
- ...(startupNotice ? [{ code: "STARTUP_NOTICE", target, message: `${result.name} joined, but ${startupNotice}` }] : []),
764
- ];
765
- if (observer) {
766
- try {
767
- observer.ready(result, warnings);
768
- }
769
- catch {
770
- 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" });
771
- }
772
- }
773
- else
774
- writeResult(presentation, { command: "spawn", target, result, warnings }, managedLaunchView);
775
- if (values.detach)
776
- return;
777
- // A runtime that streams no terminal has none to attach, so this launch does not ask for one: the
778
- // seat is up, the receipt above says where it runs and what reaches it, and the command is done.
779
- // Asking anyway is the whole of this failure mode - the manager's refusal is correct and cannot
780
- // be retried, and turning a launch that did everything the runtime allows into a partial told the
781
- // operator to reattach, which that runtime cannot do either.
782
- if (streamsTerminal === false)
783
- return;
784
- // A partial names the step that works on this seat, on the manager that runs it: ps, then attach
785
- // where the runtime streams a terminal, or its own session where it streams none.
786
- const where = `--space ${shellWord(t.space)} --on ${shellWord(result.managerInstanceId)}`;
787
- const ps = `${displayCmd()} ps ${where}`;
788
- const next = async () => (streamsTerminal ?? await registeredStreamsTerminal(result.runtime, t.space)) === false
789
- ? `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`
790
- : `nothing was relaunched; check the agent with ${codeSpan(ps)}, then attach to it with ${codeSpan(`${displayCmd()} attach ${shellWord(result.name)} ${where}`)}`;
791
- let verdict;
792
- try {
793
- 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" });
794
- }
795
- catch (e) {
796
- 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() });
797
- }
798
- // A manager too old to report the terminal says so by refusing the attach, and that refusal ends
799
- // the launch as a reported one does. Since #4845 it carries a marker. Before it, the manager refused
800
- // with the runtime's own text and the code an agent that is not running also gets, so that refusal
801
- // counts only for a runtime this CLI's own registry declares streams no terminal.
802
- if (verdict.kind === "failed" && streamsTerminal === null && (verdict.refusal?.noTerminal || (verdict.refusal?.code === "failed-precondition" && await registeredStreamsTerminal(result.runtime, t.space) === false))) {
803
- 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);
804
- return;
805
- }
806
- if (verdict.kind === "failed")
807
- 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() });
808
- if (verdict.kind === "gone" && observer)
809
- 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` });
810
- 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));
811
- }
812
- /** Whether `runtime` streams a terminal, as a provider registered in this CLI or installed as its
813
- * extension declares it. Null when this CLI has no such provider, or it does not say. */
814
- async function registeredStreamsTerminal(runtime, space) {
815
- try {
816
- const declared = (await materializeExtension({ kind: "runtime", name: runtime })).create({ session: `cotal-${space}` }).streamsTerminal;
817
- return typeof declared === "boolean" ? declared : null;
818
- }
819
- catch {
820
- return null;
821
- }
822
- }
823
- /** The mesh's release of one agent lifecycle, when `mesh` is a remote user-auth mesh that advertises
824
- * an agent-provisioning endpoint and the auth provider can call it there. */
825
- function meshRelease(mesh) {
826
- const ua = mesh?.mode === "user" && mesh.userAuth?.remote ? mesh.userAuth : undefined;
827
- const url = ua?.endpoints?.agentProvisioningUrl;
828
- if (!ua || !url)
829
- return undefined;
830
- const provider = resolveAuthProvider();
831
- if (!provider.releaseAgentLifecycle)
832
- return undefined;
833
- return (lifecycleUid, agent) => provider.releaseAgentLifecycle({ url, idpUrl: ua.idp.url, lifecycleUid, actor: agent });
834
- }
835
- /** A managed launch whose process runs but has not joined the mesh: say where it runs and, when its
836
- * harness waits for the operator, at which screen. A terminal attaches to an operator screen at once,
837
- * even with -d, and to a starting agent only when the spawn was not detached; otherwise the attach
838
- * command is printed. */
839
- async function reportStarting(start, values, space, server, target) {
840
- const selection = await managerSelection(values, start.managerInstanceId).catch(() => undefined);
841
- const selector = selection?.selector ?? start.managerInstanceId, host = selection?.manager.host ?? null;
842
- const attach = `${displayCmd()} attach ${shellWord(start.name)} --on ${shellWord(selector)}`;
843
- const presentation = presentationOf(values);
844
- const now = presentation !== "json" && canPrompt() && (start.waitingFor !== undefined || !values.detach);
845
- const place = `on ${selector}${host && host !== selector ? ` (${host})` : ""}`;
846
- writeResult(presentation, {
847
- command: "spawn",
848
- target,
849
- result: { kind: "managed-launch-running", name: start.name, managerInstanceId: start.managerInstanceId, host, waitingFor: start.waitingFor ?? null, attach },
850
- }, (r) => ({ sections: [{ title: r.waitingFor ? "Waiting for you" : "Agent starting", blocks: [{ kind: "lines", lines: [
851
- 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.`,
852
- { text: now ? "Attaching to it now." : `Attach to it: ${codeSpan(r.attach)}`, tone: "hint" },
853
- ] }] }] }));
854
- if (!now)
855
- return;
856
- const verdict = await attachSeat({ space, server, creds: values.creds, name: start.name, ...(start.expected ? { expectedTarget: start.expected } : {}) }, { on: start.managerInstanceId, reconnect: true, onRefusal: "throw" });
857
- if (verdict.kind === "failed")
858
- stderrLine("! ", `${start.name} could not be attached: ${verdict.message}; attach to it with ${codeSpan(attach)}`, c.yellow);
859
- }
860
- /** The agent a spawn asked for already runs, so nothing new is launched: say where it runs, then
861
- * attach to it in this terminal unless the spawn was detached or cannot attach, or print the
862
- * command that does. */
863
- async function reportAlreadyRunning(running, values, space, server) {
864
- const where = running.manager;
865
- const attach = where ? `${displayCmd()} attach ${shellWord(running.agent)} --on ${shellWord(where.selector)}` : null;
866
- const presentation = presentationOf(values);
867
- const now = where !== null && !values.detach && presentation !== "json" && canPrompt();
868
- const place = where ? `on ${where.selector}${where.host && where.host !== where.selector ? ` (${where.host})` : ""}` : "on the mesh, not on a manager of yours";
869
- writeResult(presentation, {
870
- command: "spawn",
871
- target: { space, agent: running.agent, managerInstanceId: where?.instanceId ?? null },
872
- result: { kind: "already-running", name: running.agent, managerInstanceId: where?.instanceId ?? null, host: where?.host ?? null, attach },
873
- noOp: true,
874
- }, (r) => ({ sections: [{ title: "Already running", blocks: [{ kind: "lines", lines: [
875
- `${r.name} is already running ${place}; nothing new was launched.`,
876
- { 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" },
877
- ] }] }] }));
878
- if (!now)
879
- return;
880
- const verdict = await attachSeat({ space, server, creds: values.creds, name: running.agent }, { on: where.instanceId, reconnect: true, onRefusal: "throw" });
881
- if (verdict.kind === "failed")
882
- stderrLine("! ", `${running.agent} could not be attached: ${verdict.message}; attach to it with ${codeSpan(attach)}`, c.yellow);
883
- }
884
- /** Whether the manager `on` pins can launch an agent in `path`, answered by its `resolve-cwd` over
885
- * a view of that manager acquired for this check alone. A path it cannot use is its refusal, which
886
- * the question shows and asks again. A check it does not answer refuses the launch: the reason
887
- * rides the structured cause rather than the sentence, because a responder's own words there are
888
- * an internal subject and a spec reference, and the way past it is `-C <dir>`, which sends the
889
- * folder with the launch and asks nothing. */
890
- async function checkFolder(flags, on, path) {
891
- const t = await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
892
- const reply = await askManager(cliControl, t.space, t.server, "resolveCwd", { cwd: path }, t.auth, "owner", undefined, { instanceId: on });
893
- const cwd = reply.ok ? reply.data?.cwd : undefined;
894
- if (typeof cwd === "string")
895
- return { cwd };
896
- if (!reply.ok && reply.code === "failed-precondition" && reply.error)
897
- return { refusal: oneLine(reply.error) };
898
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `the folder ${JSON.stringify(path)} could not be checked with manager instance ${on}, so nothing was launched`, {
899
- target: { space: t.space, managerInstanceId: on },
900
- ...(reply.error ? { native: { ...(reply.code ? { code: reply.code } : {}), detail: { reason: oneLine(reply.error) } } } : {}),
901
- remedy: `send the folder with the launch instead of answering the question: ${codeSpan(rerunWithCwd(process.argv.slice(2), path, on))}`,
902
- });
903
- }
904
- /** Why no manager received an unpinned launch. A manager whose boot inventory found no agent
905
- * application available leaves the class queue. When every live one that answered reports that on
906
- * its instance rail, distinguish an empty connector inventory from installed but unavailable ones.
907
- * A manager the broker affirms gone is skipped and named in a warning, so its registration costs
908
- * no deadline and hides no reason. A seat
909
- * (`flags` undefined) does not read the census as the operator. `agent` is the harness this caller
910
- * would choose, for the install hint. */
911
- async function unservedClassLaunch(flags, t, agent, at) {
912
- const census = flags ? await classLaunchCensus(flags, t).catch(() => undefined) : undefined;
913
- for (const instanceId of census?.gone ?? [])
914
- recordOperationWarning({ code: "MANAGER_SILENT", target: { space: t.space, managerInstanceId: instanceId }, message: `manager ${instanceId} was skipped: its registration is stale (the broker reports nothing subscribed on its rail; its host is gone and never deregistered)` });
915
- if (census?.noApplication && census.unavailable.length) {
916
- return new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `no manager of yours takes unpinned launches: installed agent applications are unavailable (${census.unavailable.join("; ")}); nothing was launched`, { ...at,
917
- remedy: `install or repair the reported applications and dependencies on the named manager hosts. If the PATH used to start each manager needs to change, restart it under its own supervisor. For a saved manager service, use \`cotal service restart <name> --yes\`. For a foreground \`cotal up\` stack, stop it with \`cotal down --yes\` from its project folder or Ctrl-C in its terminal. This stops the broker and hosted workflow runs and can stop agents. Repeat the original foreground start with the updated PATH${census.empty.length ? `. No connectors are installed on ${census.empty.join(", ")}: add one there, such as ${extAddFor(agent ?? DEFAULT_CONNECTOR)}` : ""}.` });
918
- }
919
- if (census?.noApplication) {
920
- return new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `no manager of yours takes unpinned launches: none ${census.gone.length ? "that answered " : ""}has an agent application installed${census.managers.length ? ` (${census.managers.join(", ")})` : ""}; nothing was launched`, { ...at,
921
- 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` });
922
- }
923
- 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`" });
924
- }
925
- /** Why no manager answered an unpinned launch's describe, so the launch was never sent. This root's
926
- * own stack says why when it records one, in the words `ps` uses for the same silence. */
927
- function unansweredClassLaunch(t, at) {
928
- const refused = (message, remedy) => new CommandFailure("refused", "TARGET_UNAVAILABLE", `${message}, so the launch was not sent and nothing was launched`, { ...at, remedy });
929
- if (t.root !== undefined && stackManagerStarting(t.root, t.space))
930
- return refused("the stack's manager is starting", "run the spawn again once `cotal up` reports the manager started");
931
- if (t.root !== undefined && stackManagerAbsent(t.root, t.space))
932
- return refused("no manager is running for this space", startStackManagerRemedy(t.space, t.server));
933
- const pid = t.root === undefined ? undefined : runningStackManagerPid(t.root, t.space);
934
- if (pid !== undefined)
935
- 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`);
936
- return refused("no manager answered", "cotal ps shows which managers answer; run the spawn again once one does");
937
- }
938
- /** What the registered managers say about unpinned launches. `noApplication` holds when one answered
939
- * and each one that answered says it runs agents but takes no unpinned launch; `gone` lists the
940
- * managers skipped because the broker affirms nothing subscribed on their rail. Status has no
941
- * scatter route, so each is read pinned to its instance, racing the rail probe: whichever settles
942
- * first stops the other, so neither a live manager nor a gone one is waited out. */
943
- async function classLaunchCensus(flags, t) {
944
- const gone = [];
945
- const managers = [];
946
- const unavailable = [];
947
- const empty = [];
948
- for (const instanceId of await liveManagerIds(t.space, t.server, t.auth)) {
949
- const pinned = await resolveControlTarget(flags, "control-caller-privileged", instanceId, { onRefusal: "throw" });
950
- const settled = new AbortController();
951
- const status = await Promise.race([
952
- managerRailGone(pinned.space, pinned.server, pinned.auth, instanceId, settled.signal).then((isGone) => isGone ? undefined : new Promise(() => { })),
953
- askManager(cliControl, pinned.space, pinned.server, "managerStatus", undefined, pinned.auth, "owner", 5_000, { instanceId, signal: settled.signal }),
954
- ]).finally(() => settled.abort());
955
- if (status === undefined) {
956
- gone.push(instanceId);
957
- continue;
958
- }
959
- const data = status.data;
960
- if (!status.ok || data?.classSpawn !== false || data.execution === "none")
961
- return { noApplication: false, gone, managers, unavailable, empty };
962
- const manager = managerAt(instanceId, data.host);
963
- managers.push(manager);
964
- if (data.connectors?.length) {
965
- for (const connector of data.connectors.filter(row => row.state === "unavailable"))
966
- unavailable.push(`${manager}: ${connector.agent}: ${oneLine(connector.reason ?? "unavailable at manager startup")}`);
967
- }
968
- else
969
- empty.push(manager);
970
- }
971
- return { noApplication: managers.length > 0, gone, managers, unavailable, empty };
972
- }
973
- /** A manager as a refusal names it: its instance id, and the host its own status reports. */
974
- const managerAt = (instanceId, host) => typeof host === "string" && host ? `manager ${instanceId} on host ${host}` : `manager ${instanceId}`;
975
- /** {@link managerAt} for one manager, read pinned to it. A seat (`flags` undefined) reads with its
976
- * own caller, and a status that cannot be read leaves the host out. */
977
- async function managerNamed(flags, t, instanceId) {
978
- try {
979
- const pinned = flags ? await resolveControlTarget(flags, "control-caller-privileged", instanceId, { onRefusal: "throw" }) : t;
980
- const status = await askManager(cliControl, pinned.space, pinned.server, "managerStatus", undefined, pinned.auth, "owner", 5_000, { instanceId });
981
- return managerAt(instanceId, status.ok ? status.data?.host : undefined);
982
- }
983
- catch {
984
- return managerAt(instanceId, undefined);
985
- }
986
- }
987
- /** The `cotal ext add` that installs connector `name`, quoted for a refusal. */
988
- const extAddFor = (name) => OFFICIAL_CONNECTORS[name] ? `\`cotal ext add ${OFFICIAL_CONNECTORS[name]}\`` : `\`cotal ext add <npm-package>\` for "${name}"`;
989
- /** The harness the manager's `spawn` resolves for this persona, read with the same fields `start` sends. */
990
- async function launchAgentOrExit(t, on, fields) {
991
- const reply = await askManager(cliControl, t.space, t.server, "resolveAgent", fields, t.auth, "owner", undefined, { instanceId: on });
992
- failIfNotOk(reply);
993
- return reply.data.agent;
994
- }
995
- /**
996
- * Carry a session this host holds to the manager instance a detached resume launches on, and return
997
- * the claim its `spawn` names (#1499, docs/design/resume-transfer.md section 2). Undefined when this
998
- * host holds no session `id`: the id then resolves on the manager's host as it always has. Only the
999
- * connector can tell a local session from one that lives on the manager's host, so a connector this
1000
- * CLI cannot load is refused.
1001
- */
1002
- async function carryTranscript(flags, on, id, agent) {
1003
- let connector;
1004
- try {
1005
- connector = await materializeExtension({ kind: "connector", name: agent });
1006
- }
1007
- catch (error) {
1008
- if (isCommandFailure(error))
1009
- throw error;
1010
- if (!connectorListed(agent))
1011
- throw missingConnector(agent, { space: flags.space });
1012
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `resume: ${oneLine(error.message)}`);
1013
- }
1014
- let found;
1015
- try {
1016
- found = connector.resumeTranscript?.find(id, process.env);
1017
- }
1018
- catch (error) {
1019
- if (isCommandFailure(error))
1020
- throw error;
1021
- throw new CommandFailure("refused", "USAGE_INVALID", `resume: ${error.message}`, { selfContained: true });
1022
- }
1023
- if (found === undefined)
1024
- return undefined;
1025
- if (on === undefined) {
1026
- throw new CommandFailure("refused", "USAGE_INVALID", `resume: session ${id} is held on this host, and carrying it needs one manager instance`, {
1027
- remedy: "pass --on <instance>", selfContained: true,
1028
- });
1029
- }
1030
- const bytes = readFileSync(found.path);
1031
- const sha256 = createHash("sha256").update(bytes).digest("hex");
1032
- const t = await resolveControlTarget(flags, "control-caller-admin", on);
1033
- recordOperationSpace(t.space);
1034
- const bucket = transferBucket(t.space, on);
1035
- const writer = await transferWriterOrExit(flags, t, on, sha256);
1036
- let sent = 0;
1037
- let chunks = 0;
1038
- for (;;) {
1039
- const reply = await askManager(cliControl, t.space, t.server, "transcriptReceive", {
1040
- sha256, size: bytes.length, source: id, sourceHost: hostname(), ...(found.title ? { title: found.title } : {}),
1041
- }, t.auth, "owner", undefined, { instanceId: on });
1042
- failIfNotOk(reply);
1043
- const answer = reply.data;
1044
- if (answer.state === "staged") {
1045
- console.log(c.dim(`carried session ${id} to ${on}: sha256:${sha256}, ${sent} of ${bytes.length} bytes sent in ${chunks} chunks`));
1046
- return answer.claim;
1047
- }
1048
- const pass = await withControlConnection(t.server, writer, (nc) => writeTransfer(nc, bucket, bytes));
1049
- sent += pass.sent;
1050
- chunks += pass.chunks;
1051
- }
1052
- }
1053
- /** The transfer writer instrument for one object in one instance's bucket (design section 6), once
1054
- * the transcript is hashed: minted from this host's copy of the mesh's signing seed, or on a
1055
- * user-auth mesh exchanged from the operator's login as a `transfer-writer` view. An open mesh
1056
- * enforces no grants, so a bare connection writes there. */
1057
- async function transferWriterOrExit(flags, t, instanceId, hex) {
1058
- if (t.mode === "open")
1059
- return { tls: t.auth.tls };
1060
- if (t.mode === "user") {
1061
- const conn = await connectUserControlOrExit(flags);
1062
- try {
1063
- const view = await userViewAuth(conn, "transfer-writer", { transferWriter: { instanceId, hex } });
1064
- return { bearer: view.bearer, sentinelCreds: view.sentinelCreds, tls: conn.tls };
1065
- }
1066
- catch (e) {
1067
- stderrLine("✗ ", `resume: ${e.message}`, c.red);
1068
- process.exit(1);
1069
- }
1070
- }
1071
- if (t.mode !== "auth" || !t.spaceAuth) {
1072
- 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);
1073
- process.exit(1);
1074
- }
1075
- return { creds: await mintCreds(t.spaceAuth, newIdentity(), "transfer-writer", { transferWriter: { instanceId, hex } }), tls: t.auth.tls };
1076
- }
1077
241
  /**
1078
242
  * `cotal spawn [<persona>] [--file <persona-file>]` runs the native application in this terminal.
1079
243
  * `--detach` launches it through a manager and returns after readiness, and `--on <instance>`
@@ -1085,7 +249,7 @@ async function transferWriterOrExit(flags, t, instanceId, hex) {
1085
249
  * here vs. a supervised runtime in the manager. The connector is resolved from
1086
250
  * the registry by agent type, composed at the root.
1087
251
  *
1088
- * 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
1089
253
  * bare `cotal spawn <persona>` from any directory finds the running mesh (one up, or the `current`
1090
254
  * default) instead of mistaking `~/.cotal` for a space.
1091
255
  */
@@ -1316,6 +480,7 @@ export async function spawn(args) {
1316
480
  stderrLine("✗ ", "the managed handoff's space is registered here as a local mesh, so it cannot host a managed handoff", c.red);
1317
481
  process.exit(1);
1318
482
  }
483
+ checkSpawnExpiryTarget(values, target);
1319
484
  let policy;
1320
485
  try {
1321
486
  policy = await refreshRegistrationPolicy(target);
@@ -1332,9 +497,6 @@ export async function spawn(args) {
1332
497
  process.exit(1);
1333
498
  }
1334
499
  const { space, server, auth } = target;
1335
- // Only a static mesh's seat carries an issuance whose expiry the person sets here.
1336
- if ((values["expires-in"] !== undefined || values["expires-at"] !== undefined) && (target.mode === "user" || !auth))
1337
- 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" });
1338
500
  // Where the config lives: --config, else the positional <persona>, else the persona preference
1339
501
  // (.cotal/agents/<name>.md under the TARGET mesh's root). With none, fall back to its `default`
1340
502
  // persona — `cotal spawn` with no args launches `<root>/.cotal/agents/default.md`.
@@ -1342,8 +504,8 @@ export async function spawn(args) {
1342
504
  const personaProject = resolvePath(target.personaRoot, "..", "..");
1343
505
  const path = values.file !== undefined || (redeemedEnrollment && values.config) ? resolvePath(ref) : agentFilePath(personaProject, ref);
1344
506
  // The product default of a catalog nothing prepared, as a Cloud space's is until a spawn, is
1345
- // written from the shipped template here and launched. A named or preferred persona is the
1346
- // 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.
1347
509
  const implicitDefault = ref === "default" && personaFrom === undefined && values.config === undefined && handoffText === undefined && redeemedEnrollment === undefined;
1348
510
  let def;
1349
511
  try {
@@ -1931,343 +1093,4 @@ export async function spawn(args) {
1931
1093
  process.off(sig, onTerminate);
1932
1094
  }
1933
1095
  }
1934
- /** Validate the provisioning response. Returns the material, or the refusal sentence. */
1935
- function checkRemoteAgentMaterial(v, actor) {
1936
- const o = v;
1937
- const bad = (m) => ({ ok: false, message: m });
1938
- if (o === null || typeof o !== "object")
1939
- return bad("the mesh's agent-provisioning endpoint did not answer with a JSON object");
1940
- // An occupied actor carries no material. Only an implicit new launch may try a different actor.
1941
- if (o.exists === true)
1942
- return { ok: false, exists: true, message: `agent "${actor}" already exists on this mesh and its credentials were not reissued - spawn it under a different name, or ask the mesh operator to reissue it` };
1943
- const str = (k) => (typeof o[k] === "string" && o[k] ? o[k] : undefined);
1944
- for (const k of ["actor", "owner", "lifecycleUid", "actorToken", "sentinelCreds"])
1945
- if (!str(k))
1946
- return bad(`the mesh's agent-provisioning endpoint returned no ${k} - it cannot provision agents for this mesh`);
1947
- const list = (k) => Array.isArray(o[k]) && o[k].every((s) => typeof s === "string") ? o[k] : undefined;
1948
- if (o.actor !== actor)
1949
- return bad(`the mesh provisioned actor "${String(o.actor)}" for a request naming "${actor}" - refusing material that does not match what was asked for`);
1950
- return {
1951
- ok: true,
1952
- material: {
1953
- actor: o.actor, owner: o.owner, lifecycleUid: o.lifecycleUid, actorToken: o.actorToken, sentinelCreds: o.sentinelCreds,
1954
- ...(list("subscribe") ? { subscribe: list("subscribe") } : {}),
1955
- ...(list("allowSubscribe") ? { allowSubscribe: list("allowSubscribe") } : {}),
1956
- ...(list("allowPublish") ? { allowPublish: list("allowPublish") } : {}),
1957
- },
1958
- };
1959
- }
1960
- /** Shred a user-mode agent's local material: both secrets from the store, then their files and the
1961
- * health file. Each step is attempted and a failed one is recorded in `failed`. */
1962
- async function shredAgentMaterial(failed, store, space, name, composition, paths) {
1963
- await attemptCleanup(failed, "actor token secret", () => store.delete(agentActorTokenKey(space, name, composition)));
1964
- await attemptCleanup(failed, "sentinel creds secret", () => store.delete(agentSentinelCredsKey(space, name, composition)));
1965
- await attemptCleanup(failed, "actor token file", () => rmSync(paths.actorToken, { force: true }));
1966
- await attemptCleanup(failed, "sentinel creds file", () => rmSync(paths.sentinelCreds, { force: true }));
1967
- await attemptCleanup(failed, "health file", () => rmSync(paths.health, { force: true }));
1968
- }
1969
- /** Both remote arms refuse a record that pins no exchange URL with this sentence, before any request. */
1970
- function noExchangeEndpoint(space) {
1971
- return `mesh "${space}" records no exchange endpoint - re-register it with \`cotal meshes add ${space} --from <url> --mode user\``;
1972
- }
1973
- /** Foreground REMOTE-USER onboarding — the participant path for a mesh registered with
1974
- * `meshes add --from` that advertises an agent-provisioning endpoint (U6 §2).
1975
- *
1976
- * The local twin below ({@link provisionUserForeground}) cannot run here and must not try: it
1977
- * needs the space's owner secret and account signer to grant a row and pre-create durables, and
1978
- * those never leave the machine the mesh runs on. Instead the mesh's own endpoint does that work
1979
- * inside the owner's delegation envelope and hands back ready material; this function's job is to
1980
- * present the login bearer, validate what comes back, land it 0600, and prove the bearer chain
1981
- * before launch — the same preflight discipline, with the grant performed remotely.
1982
- *
1983
- * Deliberately NOT reusing the local path's cleanup: nothing here created broker state locally, so
1984
- * teardown is the mesh's business (its lifecycle owns the row and the durables). The spawned
1985
- * agent's material is shredded on exit; the row is not revoked from here, because this machine
1986
- * holds no authority to revoke it. For a managed handoff, `refusals` replaces the sentences of the
1987
- * local-state, material and bearer steps, which quote the space, the actor or the exchange URL. */
1988
- async function provisionRemoteUserForeground(target, name, source, refusals) {
1989
- const { space } = target;
1990
- const store = workspaceSecretStore(target.root);
1991
- const composition = { injected: false, root: target.root };
1992
- const fail = (msg) => {
1993
- stderrLine("✗ ", `${msg}`, c.red);
1994
- process.exit(1);
1995
- };
1996
- // Resolved first, as by every consumer of the space's local state: each resolution migrates a
1997
- // pre-hex or root-scoped layout, or refuses an ambiguous one, before any request or material.
1998
- let paths;
1999
- try {
2000
- userAuthStateDir(target.root, space);
2001
- paths = agentSecretFilePaths(target.root, space, name);
2002
- }
2003
- catch (e) {
2004
- return fail(refusals?.registration ?? e.message);
2005
- }
2006
- let provider;
2007
- try {
2008
- provider = resolveAuthProvider();
2009
- }
2010
- catch (e) {
2011
- return fail(e.message);
2012
- }
2013
- // Checked before the grant is requested, because `fail` exits without running the shred in the
2014
- // catch below and would leave the granted material on disk.
2015
- const exchangeUrl = "body" in source ? source.exchangeUrl : target.userAuth?.endpoints?.url;
2016
- if (!exchangeUrl)
2017
- return fail(noExchangeEndpoint(space));
2018
- let body;
2019
- const held = `foreground actor material for "${name}" is already held; preserve its session and choose a distinct actor for a new launch`;
2020
- const materialClaim = acquireLock(`${paths.actorToken}.launch.lock`, {
2021
- waitMs: 0,
2022
- // A supplied body comes from an enrollment that was already redeemed, so its collision is not
2023
- // a refusal: the one-time enrollment is spent.
2024
- onTimeout: () => "body" in source ? new Error(held) : new ForegroundActorCollision(held),
2025
- });
2026
- if ("body" in source) {
2027
- body = source.body;
2028
- }
2029
- else {
2030
- const idpUrl = target.userAuth?.idp.url;
2031
- if (!idpUrl)
2032
- return fail(`mesh "${space}" records no IdP to sign in against - re-register it with \`cotal meshes add ${space} --from <url> --mode user\``);
2033
- // The login proof rides the provisioning request, so the POST is the PROVIDER's (this package
2034
- // never touches the session cache); its thrown sentences are already operator-exact — the
2035
- // no-login gate names the `cotal login --idp …` line, a refusal carries the mesh's own reason.
2036
- if (!provider.postAgentProvisioning)
2037
- return fail(`the registered auth provider "${provider.name}" cannot provision agents on a remote mesh - run the agent where the mesh runs`);
2038
- // A name held by a lifecycle that is not running is released and asked for again.
2039
- try {
2040
- body = await settleHeldName({ space }, () => provider.postAgentProvisioning({ url: source.provisioningUrl, idpUrl, actor: name }), (o) => "error" in o
2041
- ? heldAnswer({ code: o.error?.code, details: o.error?.details, message: rejectionText(o.error) }, name) : undefined, meshRelease(target));
2042
- }
2043
- catch (e) {
2044
- materialClaim.release();
2045
- // No sign-in refuses before any request. Any failure after the request, an endpoint refusal
2046
- // included, may have provisioned the actor.
2047
- if (e.code === "signed-out")
2048
- throw new CommandFailure("refused", "AUTH_REQUIRED", e.message);
2049
- throw e;
2050
- }
2051
- }
2052
- const checked = checkRemoteAgentMaterial(body, name);
2053
- if (!checked.ok) {
2054
- materialClaim.release();
2055
- if (checked.exists && "provisioningUrl" in source)
2056
- throw new ForegroundActorCollision(checked.message);
2057
- return fail(refusals?.bundle ?? checked.message);
2058
- }
2059
- const material = checked.material;
2060
- const { actorToken: tokenPath, sentinelCreds: sentinelPath, health: healthPath } = paths;
2061
- if (inspectLock(localConsumerClaimPath(target.server, space, material.owner, name, material.lifecycleUid)).state === "active") {
2062
- materialClaim.release();
2063
- return fail(`local inbox already has a consuming session for ${material.owner}.${name}; no local material was replaced`);
2064
- }
2065
- try {
2066
- // Land both secrets 0600 through the store, exactly as the local path does — the bearer
2067
- // re-exec and the launch handoff read FILES.
2068
- await store.put(agentActorTokenKey(space, name, composition), material.actorToken);
2069
- await store.put(agentSentinelCredsKey(space, name, composition), material.sentinelCreds);
2070
- await materializeSecretToFile(store, agentActorTokenKey(space, name, composition), tokenPath);
2071
- await materializeSecretToFile(store, agentSentinelCredsKey(space, name, composition), sentinelPath);
2072
- rmSync(healthPath, { force: true });
2073
- provenance.wrote(`remote actor material ${material.owner}.${name} (user mode)`, tokenPath);
2074
- // The bearer preflight — the same one-shot proof the local path runs, pointed at the pinned
2075
- // exchange instead of a local service. A dead auth chain stops the spawn here. The agent runs
2076
- // this command for every renewal, so it names the resolved entry: an install can replace the
2077
- // bin link meanwhile (get.cotal.ai writes a shell launcher over `~/.local/bin/cotal`).
2078
- const bearerCmd = [
2079
- process.execPath,
2080
- ...process.execArgv,
2081
- entryScript(),
2082
- provider.agentBearerCommand,
2083
- "--exchange-url", exchangeUrl,
2084
- "--space", space,
2085
- "--owner", material.owner,
2086
- "--actor", name,
2087
- "--token-file", tokenPath,
2088
- "--health-file", healthPath,
2089
- ];
2090
- await runBearerPreflight(bearerCmd);
2091
- return {
2092
- userAuth: { owner: material.owner, actor: name, sentinelCredsPath: sentinelPath, bearerCmd },
2093
- material,
2094
- // Local shred only. The remote row and its durables belong to the mesh's lifecycle; this
2095
- // machine has no authority to retire them and must not pretend otherwise.
2096
- cleanup: async () => {
2097
- const failed = [];
2098
- if (await store.get(agentActorTokenKey(space, name, composition)) === material.actorToken)
2099
- await shredAgentMaterial(failed, store, space, name, composition, paths);
2100
- materialClaim.release();
2101
- if (failed.length)
2102
- throw new Error(describeCleanupFailures(failed));
2103
- },
2104
- };
2105
- }
2106
- catch (e) {
2107
- // What the shred left behind joins the refusal after its cause. A handoff refusal keeps its
2108
- // fixed sentence and names only the failed steps, because their errors quote paths named for
2109
- // the handoff's actor.
2110
- const failed = [];
2111
- if (await store.get(agentActorTokenKey(space, name, composition)) === material.actorToken)
2112
- await shredAgentMaterial(failed, store, space, name, composition, paths);
2113
- materialClaim.release();
2114
- const steps = refusals ? failed.map((f) => f.step).join("; ") : describeCleanupFailures(failed);
2115
- const leftover = failed.length ? `; cleanup failed: ${steps}` : "";
2116
- return fail(`${refusals?.bearer ?? `agent auth preflight failed for "${name}": ${rejectionText(e)}`}${leftover}`);
2117
- }
2118
- }
2119
- /** Foreground USER-MODE onboarding — the CLI-side twin of the manager's user spawn provisioning:
2120
- * owner = the logged-in operator (offline, from the login cache + local user-auth material);
2121
- * principal-keyed durables on an ephemeral provisioner (LIVE-ONLY, like static foreground);
2122
- * fresh ledger grant that refuses an occupied actor; 0600 secret/sentinel files; and a
2123
- * one-shot bearer preflight whose operator-exact sentence is the refusal. Exits on any failure —
2124
- * the agent process is never launched into a broken auth chain. */
2125
- async function provisionUserForeground(target, name, ref, opts) {
2126
- const { space, server } = target;
2127
- const dir = userAuthStateDir(target.root, space);
2128
- const store = workspaceSecretStore(target.root);
2129
- const composition = { injected: false, root: target.root };
2130
- const fail = (msg) => {
2131
- stderrLine("✗ ", `${msg}`, c.red);
2132
- process.exit(1);
2133
- };
2134
- let provider;
2135
- let owner;
2136
- try {
2137
- provider = resolveAuthProvider();
2138
- owner = await provider.ownerForLogin({ store, dir, space });
2139
- }
2140
- catch (e) {
2141
- return fail(e.message);
2142
- }
2143
- // The provisioner cred is INFRA (pre-flip static coexistence, like the manager's own creds) —
2144
- // loaded explicitly here for durable pre-creation only, never for the agent's identity.
2145
- // The event grant, derived HERE because this is the first point at which the owner exists: in
2146
- // user mode the principal is (resolved owner, actor name), and neither half is known to the
2147
- // caller before `ownerForLogin` answers.
2148
- const eventGrant = opts.eventChannel?.({ owner, actor: name });
2149
- const publish = eventGrant ? [...(opts.allowPublish ?? []), eventGrant] : (opts.allowPublish ?? []);
2150
- const infra = await getSpaceAuth(store, space); // cross-check the bundle names the space we resolved this root for
2151
- if (!infra)
2152
- 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`);
2153
- const paths = agentSecretFilePaths(target.root, space, name);
2154
- const { actorToken: tokenPath, sentinelCreds: sentinelPath, health: healthPath } = paths;
2155
- const materialClaim = acquireLock(`${tokenPath}.launch.lock`, {
2156
- waitMs: 0,
2157
- onTimeout: () => new ForegroundActorCollision(`foreground actor material for "${name}" is already held; preserve its session and choose a distinct actor for a new launch`),
2158
- });
2159
- // An existing row is not this new launch's property. In particular, a dead launcher may
2160
- // leave its consuming child alive. Never overwrite the row to discover occupancy later.
2161
- if (await provider.actorScope({ dir, owner, actor: name }) !== undefined) {
2162
- materialClaim.release();
2163
- throw new ForegroundActorCollision(`actor "${name}" already has a grant; preserve its session and choose a distinct actor for a new launch`);
2164
- }
2165
- let ownedToken;
2166
- // Revoke the row, shred the secret material, and retire the broker footprint the durable
2167
- // provisioning below creates (DM/DLV durables + ACL row). Every step is attempted, so a failed
2168
- // removal cannot strand the durables on the broker, and the failures go back to the caller.
2169
- const teardown = async () => {
2170
- const failed = [];
2171
- if (ownedToken === undefined)
2172
- return failed;
2173
- let revoked = false;
2174
- await attemptCleanup(failed, "revoke agent grant", async () => {
2175
- revoked = await provider.revokeAgent({ dir, owner, actor: name, lifecycleUid: opts.lifecycleUid, actorToken: ownedToken });
2176
- });
2177
- if (await store.get(agentActorTokenKey(space, name, composition)) === ownedToken)
2178
- await shredAgentMaterial(failed, store, space, name, composition, paths);
2179
- if (!revoked)
2180
- return failed;
2181
- const targetId = principalKey(owner, name).key;
2182
- await attemptCleanup(failed, "deprovision", () => mintCreds(infra, newIdentity(), "deprovisioner", { deprovisionTarget: { principal: targetId, lifecycleUid: opts.lifecycleUid } })
2183
- .then((creds) => deprovisionAgent({ servers: server, space, targetId, lifecycleUid: opts.lifecycleUid, creds })));
2184
- return failed;
2185
- };
2186
- try {
2187
- // The GRANT first — it is the envelope-rule enforcement point (a delegation must sit within
2188
- // the spawner's own grant), so a refused delegation exits here with zero broker footprint —
2189
- // the same ordering as Manager.provisionUserAgent, for the same reason.
2190
- const grant = await provider.grantAgent({
2191
- store,
2192
- dir,
2193
- space,
2194
- owner,
2195
- actor: name,
2196
- scope: (opts.capabilities ?? []).filter((s) => s === "spawn" || s === "run" || s === "admin" || /^role:[A-Za-z0-9_-]+$/.test(s)),
2197
- allowSubscribe: opts.allowSubscribe,
2198
- allowPublish: publish,
2199
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
2200
- role: opts.role,
2201
- parent: `${owner}.cli`,
2202
- label: ref,
2203
- lifecycleUid: opts.lifecycleUid,
2204
- fresh: true,
2205
- // A foreground launch has no manager; its row says so.
2206
- custody: { kind: "foreground" },
2207
- });
2208
- ownedToken = grant.actorToken;
2209
- await withProvisioner({ space, servers: server, auth: infra }, "spawn-provisioner", (prov) =>
2210
- // Full durable footprint, same as the static foreground path: the ACL row is what lets the
2211
- // delivery daemon authorize this agent's durable joins. `--live-only` opts out.
2212
- provisionAgentDurables(prov, { owner, actor: name, lifecycleUid: opts.lifecycleUid }, {
2213
- subscribe: opts.subscribe,
2214
- allowSubscribe: opts.allowSubscribe,
2215
- role: opts.role,
2216
- ...(opts.liveOnly ? { durableMembership: false } : {}),
2217
- }));
2218
- // The store holds the source of truth; the bearer re-exec (`--token-file`) and the launch's
2219
- // sentinel handoff read FILES — materialize both at the canonical paths (byte-identical
2220
- // rewrites under this, the local FS, composition).
2221
- await store.put(agentActorTokenKey(space, name, composition), grant.actorToken);
2222
- await store.put(agentSentinelCredsKey(space, name, composition), grant.sentinelCreds);
2223
- await materializeSecretToFile(store, agentActorTokenKey(space, name, composition), tokenPath);
2224
- await materializeSecretToFile(store, agentSentinelCredsKey(space, name, composition), sentinelPath);
2225
- rmSync(healthPath, { force: true });
2226
- provenance.wrote(`actor grant ${owner}.${name} (user mode)`, tokenPath);
2227
- // The resolved entry, for the same reason as the remote arm above.
2228
- const bearerCmd = [
2229
- process.execPath,
2230
- ...process.execArgv,
2231
- entryScript(),
2232
- provider.agentBearerCommand,
2233
- "--dir", dir,
2234
- "--space", space,
2235
- "--owner", owner,
2236
- "--actor", name,
2237
- "--token-file", tokenPath,
2238
- "--health-file", healthPath,
2239
- ];
2240
- await runBearerPreflight(bearerCmd);
2241
- return {
2242
- userAuth: { owner, actor: name, sentinelCredsPath: sentinelPath, bearerCmd },
2243
- ...(eventGrant ? { eventChannel: eventGrant } : {}),
2244
- // The foreground departure's half of the runtime-grant invariant: the caller runs this when
2245
- // the agent process exits, the same teardown the rollback below runs on a failed preflight.
2246
- cleanup: async () => {
2247
- const failed = await teardown();
2248
- if (failed.length)
2249
- throw new Error(describeCleanupFailures(failed));
2250
- materialClaim.release();
2251
- },
2252
- };
2253
- }
2254
- catch (e) {
2255
- // Roll back EVERYTHING this attempt materialized: a refused spawn leaves no row, no secret, no
2256
- // orphaned durables. What the teardown could not remove joins the refusal after its cause.
2257
- const failed = await teardown();
2258
- materialClaim.release();
2259
- if (e instanceof AgentGrantConflictError && ownedToken === undefined && failed.length === 0)
2260
- throw e;
2261
- const leftover = failed.length ? `; cleanup failed: ${describeCleanupFailures(failed)}` : "";
2262
- return fail(`agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}`);
2263
- }
2264
- }
2265
- /** Run the one-shot bearer proof with an explicit credential-scrubbed environment. The enrollment
2266
- * path removes the variables from the parent before any child, and this boundary independently
2267
- * refuses to inherit them if another caller reaches it with ambient enrollment input. */
2268
- export async function runBearerPreflight(bearerCmd, env = process.env) {
2269
- const childEnv = { ...env };
2270
- scrubEnrollmentEnv(childEnv);
2271
- await runAgentBearer(bearerCmd, { env: childEnv });
2272
- }
2273
1096
  //# sourceMappingURL=spawn.js.map