@cotal-ai/cli 0.172.1 → 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 (186) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +19 -13
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +8 -6
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/channel-members.d.ts.map +1 -1
  8. package/dist/commands/channel-members.js +2 -1
  9. package/dist/commands/channel-members.js.map +1 -1
  10. package/dist/commands/channels.d.ts.map +1 -1
  11. package/dist/commands/channels.js +11 -7
  12. package/dist/commands/channels.js.map +1 -1
  13. package/dist/commands/clean.js +1 -1
  14. package/dist/commands/clean.js.map +1 -1
  15. package/dist/commands/down.d.ts.map +1 -1
  16. package/dist/commands/down.js +27 -7
  17. package/dist/commands/down.js.map +1 -1
  18. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  19. package/dist/commands/endpoint-authoring.js +16 -4
  20. package/dist/commands/endpoint-authoring.js.map +1 -1
  21. package/dist/commands/history-clear.d.ts.map +1 -1
  22. package/dist/commands/history-clear.js +10 -3
  23. package/dist/commands/history-clear.js.map +1 -1
  24. package/dist/commands/history-limit.js +2 -2
  25. package/dist/commands/history-limit.js.map +1 -1
  26. package/dist/commands/history.d.ts.map +1 -1
  27. package/dist/commands/history.js +49 -19
  28. package/dist/commands/history.js.map +1 -1
  29. package/dist/commands/join.d.ts.map +1 -1
  30. package/dist/commands/join.js +30 -7
  31. package/dist/commands/join.js.map +1 -1
  32. package/dist/commands/manager-service.d.ts.map +1 -1
  33. package/dist/commands/manager-service.js +5 -1
  34. package/dist/commands/manager-service.js.map +1 -1
  35. package/dist/commands/meshes-add.d.ts +4 -0
  36. package/dist/commands/meshes-add.d.ts.map +1 -1
  37. package/dist/commands/meshes-add.js +35 -1
  38. package/dist/commands/meshes-add.js.map +1 -1
  39. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  40. package/dist/commands/meshes-wizard.js +5 -5
  41. package/dist/commands/meshes-wizard.js.map +1 -1
  42. package/dist/commands/meshes.d.ts.map +1 -1
  43. package/dist/commands/meshes.js +4 -3
  44. package/dist/commands/meshes.js.map +1 -1
  45. package/dist/commands/persona-remote.js +2 -2
  46. package/dist/commands/persona-remote.js.map +1 -1
  47. package/dist/commands/persona.d.ts.map +1 -1
  48. package/dist/commands/persona.js +13 -5
  49. package/dist/commands/persona.js.map +1 -1
  50. package/dist/commands/personas.d.ts.map +1 -1
  51. package/dist/commands/personas.js +4 -1
  52. package/dist/commands/personas.js.map +1 -1
  53. package/dist/commands/reset-space-apply.js +2 -2
  54. package/dist/commands/reset-space-apply.js.map +1 -1
  55. package/dist/commands/reset-store-apply.d.ts +2 -2
  56. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  57. package/dist/commands/reset-store-apply.js +10 -7
  58. package/dist/commands/reset-store-apply.js.map +1 -1
  59. package/dist/commands/reset.js +2 -2
  60. package/dist/commands/reset.js.map +1 -1
  61. package/dist/commands/send.d.ts.map +1 -1
  62. package/dist/commands/send.js +21 -9
  63. package/dist/commands/send.js.map +1 -1
  64. package/dist/commands/service-actions.d.ts.map +1 -1
  65. package/dist/commands/service-actions.js +15 -4
  66. package/dist/commands/service-actions.js.map +1 -1
  67. package/dist/commands/service-registry.d.ts.map +1 -1
  68. package/dist/commands/service-registry.js +16 -5
  69. package/dist/commands/service-registry.js.map +1 -1
  70. package/dist/commands/space-delete.d.ts.map +1 -1
  71. package/dist/commands/space-delete.js +46 -31
  72. package/dist/commands/space-delete.js.map +1 -1
  73. package/dist/commands/space-registration.d.ts +4 -3
  74. package/dist/commands/space-registration.d.ts.map +1 -1
  75. package/dist/commands/space-registration.js +57 -37
  76. package/dist/commands/space-registration.js.map +1 -1
  77. package/dist/commands/space.d.ts.map +1 -1
  78. package/dist/commands/space.js +3 -1
  79. package/dist/commands/space.js.map +1 -1
  80. package/dist/commands/spawn-flags.d.ts +205 -0
  81. package/dist/commands/spawn-flags.d.ts.map +1 -0
  82. package/dist/commands/spawn-flags.js +34 -0
  83. package/dist/commands/spawn-flags.js.map +1 -0
  84. package/dist/commands/spawn-foreground.d.ts +74 -0
  85. package/dist/commands/spawn-foreground.d.ts.map +1 -0
  86. package/dist/commands/spawn-foreground.js +355 -0
  87. package/dist/commands/spawn-foreground.js.map +1 -0
  88. package/dist/commands/spawn-managed-launch.d.ts +43 -0
  89. package/dist/commands/spawn-managed-launch.d.ts.map +1 -0
  90. package/dist/commands/spawn-managed-launch.js +631 -0
  91. package/dist/commands/spawn-managed-launch.js.map +1 -0
  92. package/dist/commands/spawn-preview.d.ts.map +1 -1
  93. package/dist/commands/spawn-preview.js +7 -4
  94. package/dist/commands/spawn-preview.js.map +1 -1
  95. package/dist/commands/spawn.d.ts +6 -220
  96. package/dist/commands/spawn.d.ts.map +1 -1
  97. package/dist/commands/spawn.js +20 -1008
  98. package/dist/commands/spawn.js.map +1 -1
  99. package/dist/commands/stack-down.d.ts.map +1 -1
  100. package/dist/commands/stack-down.js +7 -4
  101. package/dist/commands/stack-down.js.map +1 -1
  102. package/dist/commands/stack-up.d.ts +2 -0
  103. package/dist/commands/stack-up.d.ts.map +1 -1
  104. package/dist/commands/stack-up.js +9 -5
  105. package/dist/commands/stack-up.js.map +1 -1
  106. package/dist/commands/status-stop-impact.d.ts +3 -0
  107. package/dist/commands/status-stop-impact.d.ts.map +1 -0
  108. package/dist/commands/status-stop-impact.js +34 -0
  109. package/dist/commands/status-stop-impact.js.map +1 -0
  110. package/dist/commands/status.d.ts.map +1 -1
  111. package/dist/commands/status.js +20 -41
  112. package/dist/commands/status.js.map +1 -1
  113. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  114. package/dist/commands/team-boot-controller.js +21 -4
  115. package/dist/commands/team-boot-controller.js.map +1 -1
  116. package/dist/commands/team.d.ts.map +1 -1
  117. package/dist/commands/team.js +25 -23
  118. package/dist/commands/team.js.map +1 -1
  119. package/dist/commands/telemetry.d.ts +1 -1
  120. package/dist/commands/telemetry.d.ts.map +1 -1
  121. package/dist/commands/telemetry.js +17 -7
  122. package/dist/commands/telemetry.js.map +1 -1
  123. package/dist/commands/up-target.d.ts +7 -0
  124. package/dist/commands/up-target.d.ts.map +1 -0
  125. package/dist/commands/up-target.js +42 -0
  126. package/dist/commands/up-target.js.map +1 -0
  127. package/dist/commands/up.d.ts +3 -10
  128. package/dist/commands/up.d.ts.map +1 -1
  129. package/dist/commands/up.js +44 -126
  130. package/dist/commands/up.js.map +1 -1
  131. package/dist/commands/update-caches.d.ts +4 -0
  132. package/dist/commands/update-caches.d.ts.map +1 -0
  133. package/dist/commands/update-caches.js +82 -0
  134. package/dist/commands/update-caches.js.map +1 -0
  135. package/dist/commands/update.d.ts.map +1 -1
  136. package/dist/commands/update.js +29 -115
  137. package/dist/commands/update.js.map +1 -1
  138. package/dist/help.d.ts.map +1 -1
  139. package/dist/help.js +2 -1
  140. package/dist/help.js.map +1 -1
  141. package/dist/index.d.ts.map +1 -1
  142. package/dist/index.js +1 -0
  143. package/dist/index.js.map +1 -1
  144. package/dist/lib/broker-log.d.ts +8 -0
  145. package/dist/lib/broker-log.d.ts.map +1 -0
  146. package/dist/lib/broker-log.js +27 -0
  147. package/dist/lib/broker-log.js.map +1 -0
  148. package/dist/lib/credential-authority.d.ts.map +1 -1
  149. package/dist/lib/credential-authority.js +22 -5
  150. package/dist/lib/credential-authority.js.map +1 -1
  151. package/dist/lib/restore.d.ts +2 -1
  152. package/dist/lib/restore.d.ts.map +1 -1
  153. package/dist/lib/restore.js +4 -3
  154. package/dist/lib/restore.js.map +1 -1
  155. package/dist/lib/service-preset-target.d.ts.map +1 -1
  156. package/dist/lib/service-preset-target.js +6 -2
  157. package/dist/lib/service-preset-target.js.map +1 -1
  158. package/dist/lib/service-presets.d.ts +2 -0
  159. package/dist/lib/service-presets.d.ts.map +1 -1
  160. package/dist/lib/service-presets.js +19 -2
  161. package/dist/lib/service-presets.js.map +1 -1
  162. package/dist/lib/spawn-defaults.d.ts +5 -0
  163. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  164. package/dist/lib/spawn-defaults.js +5 -0
  165. package/dist/lib/spawn-defaults.js.map +1 -1
  166. package/dist/lib/stack-journal.d.ts +4 -4
  167. package/dist/lib/stack-journal.d.ts.map +1 -1
  168. package/dist/lib/stack-journal.js +6 -5
  169. package/dist/lib/stack-journal.js.map +1 -1
  170. package/dist/lib/up-broker-address.d.ts +7 -0
  171. package/dist/lib/up-broker-address.d.ts.map +1 -0
  172. package/dist/lib/up-broker-address.js +76 -0
  173. package/dist/lib/up-broker-address.js.map +1 -0
  174. package/dist/lib/up-report.d.ts +2 -0
  175. package/dist/lib/up-report.d.ts.map +1 -1
  176. package/dist/lib/up-report.js +8 -1
  177. package/dist/lib/up-report.js.map +1 -1
  178. package/dist/lib/update-connector-config.d.ts +6 -0
  179. package/dist/lib/update-connector-config.d.ts.map +1 -0
  180. package/dist/lib/update-connector-config.js +44 -0
  181. package/dist/lib/update-connector-config.js.map +1 -0
  182. package/dist/seed/reconcile.d.ts +1 -1
  183. package/dist/seed/reconcile.d.ts.map +1 -1
  184. package/dist/seed/reconcile.js +28 -11
  185. package/dist/seed/reconcile.js.map +1 -1
  186. package/package.json +4 -4
@@ -0,0 +1,631 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { hostname } from "node:os";
4
+ import { mintCreds, newIdentity, parseShareSelection, spawnNameError, resolveAuthProvider, GOAL_ENTITY_RUNNING_DETAIL_KIND, EP_UNDECLARED_ARG, seatCapFrom, transferBucket, writeTransfer, } from "@cotal-ai/core";
5
+ import { parseCommaList, CommandFailure, isCommandFailure, presentationOf, recordOperationWarning, renderReport, terminalWidth, wrapWords, writeResult, cachedPreferences, loadManagerInstanceIdentity, refreshRegistrationPolicy, resolveSeatControlTarget, connectUserControlOrExit, userViewAuth, oneLine, codeSpan, DEFAULT_CONNECTOR, hintedConnector, manifestExtensionNames, OFFICIAL_CONNECTORS, recordOperationSpace, resolveMeshTarget, resolveControlTarget, } from "@cotal-ai/workspace";
6
+ import { readManagedLaunch, requestManagedLaunch } from "@cotal-ai/workspace/launch";
7
+ import { c, stderrLine } from "../ui.js";
8
+ import { displayCmd } from "../lib/self-exec.js";
9
+ import { runningStackManagerPid, stackManagerAbsent, stackManagerStarting } from "../lib/stack-journal.js";
10
+ import { cliControl, failIfNotOk } from "../lib/control.js";
11
+ import { askManagerFolder, managerPin, managerSelection, managersWithPersona, rerunOn, rerunWithCwd } from "../lib/manager-choice.js";
12
+ import { canPrompt } from "./meshes-wizard.js";
13
+ import { callerHarness, missingConnector, spawnPersona } from "../lib/spawn-defaults.js";
14
+ import { attachSeat, joinedAgentRows, psSeatLabel } from "./agents.js";
15
+ import { AgentAlreadyRunning, heldAnswer, settleHeldName } from "../lib/held-name.js";
16
+ import { shellWord } from "../lib/endpoint-errors.js";
17
+ import { materializeExtension, preflightRuntime } from "../ext-loader.js";
18
+ import { askManager, describeUnanswered, liveManagerIds, managerRailGone, refuseUnregisteredManager, refuseWithoutLiveManager, START_TIMEOUT_MS, startStackManagerRemedy, withControlConnection, } from "@cotal-ai/workspace/control";
19
+ import { spawnFlags, spawnRerun } from "./spawn-flags.js";
20
+ /** Whether the installed manifest lists a connector named `name`. An unreadable manifest answers
21
+ * true, so the import's own refusal reports it. */
22
+ export function connectorListed(name) {
23
+ try {
24
+ return manifestExtensionNames("connector").includes(name);
25
+ }
26
+ catch {
27
+ return true;
28
+ }
29
+ }
30
+ /** #867: the name a spawn sends must already be a mintable identity, and the check must not wait
31
+ * for the manager's round trip. `spawnNameError` is the SAME predicate the manager applies at its
32
+ * door (manager.ts `start`), so the operator sees core's own refusal — offending character,
33
+ * reservation reason, and the `_` remedy — before any request leaves. A courtesy only: the
34
+ * manager door stays the enforcement point; this is why the CLI passes the target mesh's auth
35
+ * mode rather than restating the grammar (static mode keys the actor on the nkey, not the name). */
36
+ export function refuseUnmintableName(name, userMode) {
37
+ const refusal = spawnNameError(name, { userMode });
38
+ if (refusal)
39
+ throw new CommandFailure("refused", "USAGE_INVALID", refusal, { selfContained: true });
40
+ }
41
+ /** Whether a managed launch can reach only this root's own manager: the instance it names, or else
42
+ * the only one the registry lists, is the one recorded under the target's root. An unread registry
43
+ * or an unreadable record proves nothing, and the launch then goes to whichever manager serves it. */
44
+ export function launchServedHere(t, serving, live) {
45
+ if (t.root === undefined)
46
+ return false;
47
+ let here;
48
+ try {
49
+ here = loadManagerInstanceIdentity(t.root, t.space)?.instanceId;
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ if (here === undefined)
55
+ return false;
56
+ return serving !== undefined ? serving === here : live?.length === 1 && live[0] === here;
57
+ }
58
+ /** A runtime this root's own manager cannot launch on is refused before the launch is sent, through
59
+ * the installed-extension lookup `up --runtime` uses. A manager on another host reads that host's
60
+ * extensions, so a launch that may reach one sends the name and that manager decides. */
61
+ async function refuseRuntimeHere(runtime, t, serving, live) {
62
+ if (!launchServedHere(t, serving, live))
63
+ return;
64
+ try {
65
+ await preflightRuntime(runtime);
66
+ }
67
+ catch (error) {
68
+ 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" });
69
+ }
70
+ }
71
+ const channelList = (channels) => channels.length ? channels.join(", ") : "none";
72
+ export function managedLaunchView(r) {
73
+ const concrete = [r.name, r.space, r.managerInstanceId].every((value) => /^[A-Za-z0-9_-]+$/.test(value));
74
+ const target = concrete ? `${r.name} --space ${r.space} --on ${r.managerInstanceId}` : "<name> --space <space> --on <manager-instance>";
75
+ const noStream = r.streamsTerminal === false;
76
+ return { sections: [
77
+ { title: "Agent joined", blocks: [
78
+ { 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"]] },
79
+ { kind: "lines", lines: [{ text: "The manager confirmed presence readiness. This is not proof that the kickoff task completed.", tone: "hint" }] },
80
+ ] },
81
+ ...(noStream ? [{ title: "Next", blocks: [
82
+ { kind: "commands", items: [
83
+ { command: `${displayCmd()} watch --space ${r.space}`, description: "Follow this mesh, this agent's messages included" },
84
+ { command: `${displayCmd()} send -t ${r.name} "<message>"`, description: "Give the agent work over the mesh" },
85
+ { command: `${displayCmd()} status ${target}`, description: "Read the agent's reported state" },
86
+ ] },
87
+ { kind: "lines", lines: [{ text: `${displayCmd()} attach is not available here: the ${r.runtime} runtime streams no terminal.`, tone: "hint" }] },
88
+ ] }] : r.detached ? [{ title: "Next", blocks: [{ kind: "commands", items: [
89
+ { command: `${displayCmd()} attach ${target}`, description: concrete ? "Return to this allocated incarnation's manager" : "Use the full identities recorded above" },
90
+ { command: `${displayCmd()} status ${target}`, description: "Read the agent's reported state" },
91
+ ] }] }] : []),
92
+ ] };
93
+ }
94
+ /** The auth mode of the mesh `flags` name, or undefined when they name no registered mesh, which
95
+ * the launch's own resolve then reports. */
96
+ function meshMode(flags) {
97
+ try {
98
+ return resolveMeshTarget(process.cwd(), { space: flags.space, server: flags.server }).mode;
99
+ }
100
+ catch {
101
+ return undefined;
102
+ }
103
+ }
104
+ /** Shared managed launch. The manager resolves its persona and returns real readiness before
105
+ * any view opens. Detach changes terminal attachment, not the launch or caller authority. */
106
+ export async function launchManagedPersona(values, positionals, events, launchOptions, observer) {
107
+ // WHICH file the manager loads — the exact foreground precedence (`--config` > positional >
108
+ // `COTAL_DEFAULT_PERSONA` > `default`). Identity is separate:
109
+ // when `--name` is given it OVERRIDES the file's `name:` (foreground's `requested`), threaded
110
+ // as the op's `identity` so it is never silently dropped in detached mode.
111
+ let on = await managerPin(values, spawnRerun(values, positionals));
112
+ // From a managed seat's own shell the launch is the SEAT's, as its `cotal_spawn` tool is: the
113
+ // manager records the seat as the spawner, so the seat can stop the child it asked for (#718).
114
+ // `--on` keeps the pin on that path too.
115
+ const flags = { space: values.space, server: values.server, creds: values.creds };
116
+ const seatIntent = Boolean(process.env.COTAL_NAME || process.env.COTAL_ID || process.env.COTAL_LIFECYCLE_UID || process.env.COTAL_ACCEPTED_TOKEN);
117
+ if (seatIntent && values.creds !== undefined)
118
+ throw new CommandFailure("refused", "USAGE_INVALID", "a managed seat's child launch uses that seat's own caller, not a --creds override");
119
+ let cwd = values.cwd;
120
+ // On a terminal, a pinned manager that is not known to run on this host is asked which of its
121
+ // folders the agent works in, unless -C names one. One resolve, dropped again here, answers
122
+ // everything that question needs: that the mesh runs and the pin names a manager that is running,
123
+ // which manager an unpinned launch on a user-auth mesh goes to (the exchange picks your only live
124
+ // one, and the launch is pinned to it so the question asks about the manager that runs the
125
+ // agent), and the host that manager reports. So an unknown --on or a stopped mesh is refused
126
+ // before anything is asked, and the question still holds no manager credential: a typed folder is
127
+ // checked under a view of that manager acquired after it is answered, and the launch acquires its
128
+ // own below. A manager that has stopped by the time the launch is sent is refused there and goes
129
+ // to no other manager.
130
+ if (cwd === undefined && !seatIntent && canPrompt() && (on !== undefined || (values.creds === undefined && meshMode(flags) === "user"))) {
131
+ const probe = await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
132
+ const pin = on ?? probe.auth.managerInstanceId;
133
+ if (pin !== undefined) {
134
+ if (!probe.auth.bearer)
135
+ await refuseUnregisteredManager(probe.space, probe.server, probe.auth, pin);
136
+ on = pin;
137
+ const selection = await managerSelection(values, pin, probe);
138
+ if (selection.manager.host !== hostname()) {
139
+ const folder = await askManagerFolder(selection, process.argv.slice(2), (path) => checkFolder(flags, pin, path));
140
+ if (folder === null)
141
+ process.exit(0);
142
+ cwd = folder;
143
+ }
144
+ }
145
+ }
146
+ let seat;
147
+ if (seatIntent) {
148
+ try {
149
+ seat = await resolveSeatControlTarget({ ...flags, space: flags.space ?? process.env.COTAL_SPACE }, on);
150
+ }
151
+ catch {
152
+ throw new CommandFailure("refused", "AUTH_REQUIRED", "the launching seat's own credential could not be verified; no operator identity was substituted");
153
+ }
154
+ if (!seat)
155
+ 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");
156
+ }
157
+ const t = seat ?? await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
158
+ recordOperationSpace(t.space);
159
+ let policy;
160
+ try {
161
+ policy = await refreshRegistrationPolicy(t);
162
+ }
163
+ catch {
164
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected registration policy could not be observed; no manager launch was submitted");
165
+ }
166
+ // #867: refuse an unmintable identity BEFORE the round trip. On this path the persona is
167
+ // resolved manager-side, so the effective identity is `--name` alone — when it is absent the
168
+ // manager applies the same spawnNameError to the file's `name:` at its own door.
169
+ if (values.name !== undefined)
170
+ refuseUnmintableName(values.name, t.mode === "user");
171
+ const eventsRequired = policy?.events === "required";
172
+ if (eventsRequired && events === false) {
173
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `space "${t.space}" requires the event plane by registration policy; no launch was submitted`);
174
+ }
175
+ 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;
176
+ // A pin the registry does not list is refused at once; only a registered manager is waited on.
177
+ if (on !== undefined && !t.auth.bearer)
178
+ await refuseUnregisteredManager(t.space, t.server, t.auth, on);
179
+ if (values.runtime !== undefined)
180
+ await refuseRuntimeHere(values.runtime.trim(), t, on ?? t.auth.managerInstanceId, live);
181
+ const { ref, from: personaFrom } = spawnPersona(values.config, positionals, { space: t.space, preferences: cachedPreferences() });
182
+ const managerConfigRef = values.config ?? (personaFrom !== undefined ? ref : undefined);
183
+ const defaultAgent = callerHarness(t.space);
184
+ let resumeClaim;
185
+ if (values.resume !== undefined) {
186
+ // Without a flag the harness is the persona pin or a default, which only the target manager
187
+ // can read: ask it, so the carry looks with the connector the launch runs (#2899).
188
+ const agent = values.agent ?? await launchAgentOrExit(t, on, { name: ref, config: managerConfigRef, defaultAgent });
189
+ // The carry and its transfer-writer view stay on the mesh selected for this launch.
190
+ const claim = await carryTranscript({ ...flags, space: t.space, server: t.server }, on, values.resume, agent);
191
+ if (claim !== undefined)
192
+ resumeClaim = { claim, agent };
193
+ }
194
+ // The report that answers names the mesh in its heading, so this block names it once, in a field.
195
+ const toStdout = !observer && presentationOf(values) !== "json";
196
+ (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));
197
+ 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)))
198
+ console.error(c.dim(line));
199
+ const start = () => requestManagedLaunch({
200
+ persona: ref,
201
+ identity: values.name,
202
+ role: values.role,
203
+ // #869: keep an explicit `--agent` and the invoking operator's default (COTAL_DEFAULT_AGENT or a
204
+ // saved harness preference) in separate fields. Collapsing them made the default
205
+ // indistinguishable from a flag, so it beat the persona pin; dropping it instead changed detached
206
+ // semantics whenever the manager's own environment differed. The manager applies flag > file >
207
+ // caller default > manager default.
208
+ agent: values.agent,
209
+ defaultAgent,
210
+ config: managerConfigRef,
211
+ model: values.model,
212
+ variant: values.variant,
213
+ ...(values.restarts !== undefined ? { supervise: { restarts: Number(values.restarts), windowMs: Number(values["restart-window"]) } } : {}),
214
+ launchOptions,
215
+ cwd,
216
+ resume: values.resume,
217
+ resumeClaim,
218
+ prompt: values.prompt,
219
+ shareTools: parseShareSelection(values["share-tools"]),
220
+ subscribe: parseCommaList(values.subscribe),
221
+ allowSubscribe: parseCommaList(values["allow-subscribe"]),
222
+ allowPublish: parseCommaList(values["allow-publish"]),
223
+ // #373: send the bit only when the operator chose it. On an events-required space the
224
+ // policy still forces the plane on (the manager refuses a non-admin caller on such a space
225
+ // anyway, so the operator must hold the admin tier for the spawn to succeed at all).
226
+ events: eventsRequired ? true : events,
227
+ ...(values["no-event-payloads"] || policy?.eventPayloads === "withheld" ? { eventPayloads: false } : {}),
228
+ ...(values.runtime !== undefined ? { runtime: values.runtime.trim() } : {}),
229
+ // #159 B1: the manager replies only on a REAL outcome (presence join / process exit / ~30s
230
+ // readiness backstop) — the start request must outlive that window, not the 5s op default.
231
+ // `--on <instance>` pins the spawn to that exact manager instance (P2 item 3 multi-manager).
232
+ }, (args) => askManager(cliControl, t.space, t.server, "start", args, t.auth, "owner", START_TIMEOUT_MS, { instanceId: on }));
233
+ // A refusal before execution launched nothing, so the launch is sent again once a name held by a
234
+ // lifecycle that is not running is released. A name that runs is not launched a second time.
235
+ let reply;
236
+ try {
237
+ let mesh;
238
+ try {
239
+ mesh = resolveMeshTarget(process.cwd(), { space: flags.space, server: flags.server });
240
+ }
241
+ catch { /* no registered mesh: nothing to release */ }
242
+ reply = await settleHeldName(flags, start, (o) => "value" in o && !o.value.ok && o.value.nativeOutcome === "not-executed"
243
+ ? heldAnswer({ code: o.value.code, details: o.value.details, message: o.value.error ?? "" }, values.name) : undefined, meshRelease(mesh));
244
+ }
245
+ catch (e) {
246
+ if (!(e instanceof AgentAlreadyRunning))
247
+ throw e;
248
+ if (observer)
249
+ throw new CommandFailure("refused", "CONFLICT", `${e.message}; nothing new was launched`, { target: { space: t.space, agent: e.agent, managerInstanceId: e.manager?.instanceId ?? null } });
250
+ return reportAlreadyRunning(e, values, t.space, t.server);
251
+ }
252
+ 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 } : {}) };
253
+ // A launch whose process the manager reports running is starting: one that waits for the operator at
254
+ // a screen its harness names was ready once it ran, and one that did not join in time may still be
255
+ // coming up or sitting at a prompt. Either way the operator is sent to its terminal.
256
+ const started = reply.ok ? reply.data : undefined;
257
+ const running = !reply.ok && reply.code === "uncertain" && reply.details?.some((d) => d.kind === GOAL_ENTITY_RUNNING_DETAIL_KIND) === true;
258
+ const startedName = typeof started?.name === "string" ? started.name : reply.request?.allocation?.name;
259
+ if (!observer && reply.managerInstanceId && startedName && (typeof started?.waitingFor === "string" || running)) {
260
+ const expected = typeof started?.id === "string" && typeof started.lifecycleUid === "string" ? { id: started.id, lifecycleUid: started.lifecycleUid } : undefined;
261
+ return reportStarting({ name: startedName, managerInstanceId: reply.managerInstanceId, ...(typeof started?.waitingFor === "string" ? { waitingFor: started.waitingFor } : {}), ...(expected ? { expected } : {}) }, values, t.space, t.server, target);
262
+ }
263
+ if (!reply.ok) {
264
+ 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" };
265
+ const code = reply.code === undefined ? undefined : refusal[reply.code];
266
+ 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 } } : {}) };
267
+ // The broker attested that no manager received an unpinned launch: none takes the class queue.
268
+ if (on === undefined && !t.auth.bearer && reply.unanswered && reply.nativeOutcome === "not-executed")
269
+ throw await unservedClassLaunch(seat ? undefined : flags, t, values.agent ?? defaultAgent, { target, native });
270
+ // A pinned describe that drew no answer means the launch was never sent, as ps and stop --on say.
271
+ if (on !== undefined && describeUnanswered(reply))
272
+ 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>" });
273
+ // So does an unpinned one: no manager answered, and the launch was never published.
274
+ if (on === undefined && describeUnanswered(reply))
275
+ throw unansweredClassLaunch(t, { target, native: { code: reply.code, ...(reply.error ? { detail: oneLine(reply.error) } : {}) } });
276
+ // The owner's seat cap. Keyed on the marker, not the code: the numbers are what a script acts
277
+ // on, and the remedy is the operator's knob, neither of which a code alone can carry. It is a
278
+ // CONFLICT with the seats this owner already holds, the same shape as a pinned-name collision:
279
+ // nothing here is unreachable or unauthorized, and freeing one seat admits the launch.
280
+ const cap = seatCapFrom(reply);
281
+ if (cap !== undefined)
282
+ throw new CommandFailure("refused", "CONFLICT", reply.error ? oneLine(reply.error) : "the manager refused the launch: this owner is at its seat cap", {
283
+ target, native: { code: reply.code, outcome: reply.nativeOutcome, detail: { owner: cap.owner, seats: cap.seats, cap: cap.cap } },
284
+ 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)`,
285
+ });
286
+ // A manager without the connector: it is added where that manager runs, not on this machine.
287
+ const absent = reply.nativeOutcome === "not-executed" && reply.error !== undefined ? hintedConnector(reply.error) : undefined;
288
+ if (absent !== undefined) {
289
+ const answered = reply.managerInstanceId ?? on;
290
+ 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,
291
+ remedy: `add it where that manager runs, such as ${extAddFor(absent)}, then restart that manager; it reads its agent applications when it starts` });
292
+ }
293
+ if (reply.nativeOutcome === "not-executed" && code) {
294
+ // A manager without the persona: it is created on that manager's host, or the spawn goes to
295
+ // another live manager whose catalog has it.
296
+ const missing = managerConfigRef === undefined && reply.error?.startsWith(`no persona "${ref}"`) === true;
297
+ const elsewhere = missing ? await managersWithPersona(flags, reply.managerInstanceId ?? on, ref).catch(() => []) : [];
298
+ throw new CommandFailure("refused", code, reply.error ? oneLine(reply.error) : "the manager refused the launch before execution", { target, native, remedy: elsewhere.length
299
+ ? `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 ")}`
300
+ : missing ? "nothing was launched; create that file on the manager's host, then run the spawn again"
301
+ // This CLI refused before sending, so the manager reported nothing; the refusal names the side to update.
302
+ : reply.details?.some((d) => d.kind === EP_UNDECLARED_ARG) ? "nothing was launched; update the side the refusal names, then run the spawn again"
303
+ : "nothing was launched; fix what the manager reported, then run the spawn again" });
304
+ }
305
+ // A committed `failed` terminal is the manager's answer: the launch ran and failed, as an agent
306
+ // that exits at once does, and the manager says why.
307
+ if (reply.code === "failed")
308
+ 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" });
309
+ const unknown = reply.nativeOutcome !== "executed" || reply.unanswered;
310
+ 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" });
311
+ }
312
+ const { result, eventsNotice, startupNotice } = readManagedLaunch(reply, { space: t.space, requestedModel: values.model ?? null, detached: values.detach === true }, target);
313
+ const { streamsTerminal } = result;
314
+ const presentation = presentationOf(values);
315
+ const warnings = [
316
+ ...(eventsNotice ? [{ code: "EVENT_PLANE_NOTICE", target, message: eventsNotice }] : []),
317
+ ...(startupNotice ? [{ code: "STARTUP_NOTICE", target, message: `${result.name} joined, but ${startupNotice}` }] : []),
318
+ ];
319
+ if (observer) {
320
+ try {
321
+ observer.ready(result, warnings);
322
+ }
323
+ catch {
324
+ 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" });
325
+ }
326
+ }
327
+ else
328
+ writeResult(presentation, { command: "spawn", target, result, warnings }, managedLaunchView);
329
+ if (values.detach)
330
+ return;
331
+ // A runtime that streams no terminal has none to attach, so this launch does not ask for one: the
332
+ // seat is up, the receipt above says where it runs and what reaches it, and the command is done.
333
+ // Asking anyway is the whole of this failure mode - the manager's refusal is correct and cannot
334
+ // be retried, and turning a launch that did everything the runtime allows into a partial told the
335
+ // operator to reattach, which that runtime cannot do either.
336
+ if (streamsTerminal === false)
337
+ return;
338
+ // A partial names the step that works on this seat, on the manager that runs it: ps, then attach
339
+ // where the runtime streams a terminal, or its own session where it streams none.
340
+ const where = `--space ${shellWord(t.space)} --on ${shellWord(result.managerInstanceId)}`;
341
+ const ps = `${displayCmd()} ps ${where}`;
342
+ const next = async () => (streamsTerminal ?? await registeredStreamsTerminal(result.runtime, t.space)) === false
343
+ ? `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`
344
+ : `nothing was relaunched; check the agent with ${codeSpan(ps)}, then attach to it with ${codeSpan(`${displayCmd()} attach ${shellWord(result.name)} ${where}`)}`;
345
+ let verdict;
346
+ try {
347
+ 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" });
348
+ }
349
+ catch (e) {
350
+ 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() });
351
+ }
352
+ // A manager too old to report the terminal says so by refusing the attach, and that refusal ends
353
+ // the launch as a reported one does. Since #4845 it carries a marker. Before it, the manager refused
354
+ // with the runtime's own text and the code an agent that is not running also gets, so that refusal
355
+ // counts only for a runtime this CLI's own registry declares streams no terminal.
356
+ if (verdict.kind === "failed" && streamsTerminal === null && (verdict.refusal?.noTerminal || (verdict.refusal?.code === "failed-precondition" && await registeredStreamsTerminal(result.runtime, t.space) === false))) {
357
+ 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);
358
+ return;
359
+ }
360
+ if (verdict.kind === "failed")
361
+ 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() });
362
+ if (verdict.kind === "gone" && observer)
363
+ 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` });
364
+ 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));
365
+ }
366
+ /** Whether `runtime` streams a terminal, as a provider registered in this CLI or installed as its
367
+ * extension declares it. Null when this CLI has no such provider, or it does not say. */
368
+ async function registeredStreamsTerminal(runtime, space) {
369
+ try {
370
+ const declared = (await materializeExtension({ kind: "runtime", name: runtime })).create({ session: `cotal-${space}` }).streamsTerminal;
371
+ return typeof declared === "boolean" ? declared : null;
372
+ }
373
+ catch {
374
+ return null;
375
+ }
376
+ }
377
+ /** The mesh's release of one agent lifecycle, when `mesh` is a remote user-auth mesh that advertises
378
+ * an agent-provisioning endpoint and the auth provider can call it there. */
379
+ export function meshRelease(mesh) {
380
+ const ua = mesh?.mode === "user" && mesh.userAuth?.remote ? mesh.userAuth : undefined;
381
+ const url = ua?.endpoints?.agentProvisioningUrl;
382
+ if (!ua || !url)
383
+ return undefined;
384
+ const provider = resolveAuthProvider();
385
+ if (!provider.releaseAgentLifecycle)
386
+ return undefined;
387
+ return (lifecycleUid, agent) => provider.releaseAgentLifecycle({ url, idpUrl: ua.idp.url, lifecycleUid, actor: agent });
388
+ }
389
+ /** A managed launch whose process runs but has not joined the mesh: say where it runs and, when its
390
+ * harness waits for the operator, at which screen. A terminal attaches to an operator screen at once,
391
+ * even with -d, and to a starting agent only when the spawn was not detached; otherwise the attach
392
+ * command is printed. */
393
+ async function reportStarting(start, values, space, server, target) {
394
+ const selection = await managerSelection(values, start.managerInstanceId).catch(() => undefined);
395
+ const selector = selection?.selector ?? start.managerInstanceId, host = selection?.manager.host ?? null;
396
+ const attach = `${displayCmd()} attach ${shellWord(start.name)} --on ${shellWord(selector)}`;
397
+ const presentation = presentationOf(values);
398
+ const now = presentation !== "json" && canPrompt() && (start.waitingFor !== undefined || !values.detach);
399
+ const place = `on ${selector}${host && host !== selector ? ` (${host})` : ""}`;
400
+ writeResult(presentation, {
401
+ command: "spawn",
402
+ target,
403
+ result: { kind: "managed-launch-running", name: start.name, managerInstanceId: start.managerInstanceId, host, waitingFor: start.waitingFor ?? null, attach },
404
+ }, (r) => ({ sections: [{ title: r.waitingFor ? "Waiting for you" : "Agent starting", blocks: [{ kind: "lines", lines: [
405
+ 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.`,
406
+ { text: now ? "Attaching to it now." : `Attach to it: ${codeSpan(r.attach)}`, tone: "hint" },
407
+ ] }] }] }));
408
+ if (!now)
409
+ return;
410
+ const verdict = await attachSeat({ space, server, creds: values.creds, name: start.name, ...(start.expected ? { expectedTarget: start.expected } : {}) }, { on: start.managerInstanceId, reconnect: true, onRefusal: "throw" });
411
+ if (verdict.kind === "failed")
412
+ stderrLine("! ", `${start.name} could not be attached: ${verdict.message}; attach to it with ${codeSpan(attach)}`, c.yellow);
413
+ }
414
+ /** The agent a spawn asked for already runs, so nothing new is launched: say where it runs, then
415
+ * attach to it in this terminal unless the spawn was detached or cannot attach, or print the
416
+ * command that does. */
417
+ export async function reportAlreadyRunning(running, values, space, server) {
418
+ const where = running.manager;
419
+ const attach = where ? `${displayCmd()} attach ${shellWord(running.agent)} --on ${shellWord(where.selector)}` : null;
420
+ const presentation = presentationOf(values);
421
+ const now = where !== null && !values.detach && presentation !== "json" && canPrompt();
422
+ const place = where ? `on ${where.selector}${where.host && where.host !== where.selector ? ` (${where.host})` : ""}` : "on the mesh, not on a manager of yours";
423
+ writeResult(presentation, {
424
+ command: "spawn",
425
+ target: { space, agent: running.agent, managerInstanceId: where?.instanceId ?? null },
426
+ result: { kind: "already-running", name: running.agent, managerInstanceId: where?.instanceId ?? null, host: where?.host ?? null, attach },
427
+ noOp: true,
428
+ }, (r) => ({ sections: [{ title: "Already running", blocks: [{ kind: "lines", lines: [
429
+ `${r.name} is already running ${place}; nothing new was launched.`,
430
+ { 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" },
431
+ ] }] }] }));
432
+ if (!now)
433
+ return;
434
+ const verdict = await attachSeat({ space, server, creds: values.creds, name: running.agent }, { on: where.instanceId, reconnect: true, onRefusal: "throw" });
435
+ if (verdict.kind === "failed")
436
+ stderrLine("! ", `${running.agent} could not be attached: ${verdict.message}; attach to it with ${codeSpan(attach)}`, c.yellow);
437
+ }
438
+ /** Whether the manager `on` pins can launch an agent in `path`, answered by its `resolve-cwd` over
439
+ * a view of that manager acquired for this check alone. A path it cannot use is its refusal, which
440
+ * the question shows and asks again. A check it does not answer refuses the launch: the reason
441
+ * rides the structured cause rather than the sentence, because a responder's own words there are
442
+ * an internal subject and a spec reference, and the way past it is `-C <dir>`, which sends the
443
+ * folder with the launch and asks nothing. */
444
+ async function checkFolder(flags, on, path) {
445
+ const t = await resolveControlTarget(flags, "control-caller-privileged", on, { onRefusal: "throw" });
446
+ const reply = await askManager(cliControl, t.space, t.server, "resolveCwd", { cwd: path }, t.auth, "owner", undefined, { instanceId: on });
447
+ const cwd = reply.ok ? reply.data?.cwd : undefined;
448
+ if (typeof cwd === "string")
449
+ return { cwd };
450
+ if (!reply.ok && reply.code === "failed-precondition" && reply.error)
451
+ return { refusal: oneLine(reply.error) };
452
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `the folder ${JSON.stringify(path)} could not be checked with manager instance ${on}, so nothing was launched`, {
453
+ target: { space: t.space, managerInstanceId: on },
454
+ ...(reply.error ? { native: { ...(reply.code ? { code: reply.code } : {}), detail: { reason: oneLine(reply.error) } } } : {}),
455
+ remedy: `send the folder with the launch instead of answering the question: ${codeSpan(rerunWithCwd(process.argv.slice(2), path, on))}`,
456
+ });
457
+ }
458
+ /** Why no manager received an unpinned launch. A manager whose boot inventory found no agent
459
+ * application available leaves the class queue. When every live one that answered reports that on
460
+ * its instance rail, distinguish an empty connector inventory from installed but unavailable ones.
461
+ * A manager the broker affirms gone is skipped and named in a warning, so its registration costs
462
+ * no deadline and hides no reason. A seat
463
+ * (`flags` undefined) does not read the census as the operator. `agent` is the harness this caller
464
+ * would choose, for the install hint. */
465
+ async function unservedClassLaunch(flags, t, agent, at) {
466
+ const census = flags ? await classLaunchCensus(flags, t).catch(() => undefined) : undefined;
467
+ for (const instanceId of census?.gone ?? [])
468
+ 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)` });
469
+ if (census?.noApplication && census.unavailable.length) {
470
+ 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,
471
+ 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)}` : ""}.` });
472
+ }
473
+ if (census?.noApplication) {
474
+ 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,
475
+ 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` });
476
+ }
477
+ 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`" });
478
+ }
479
+ /** Why no manager answered an unpinned launch's describe, so the launch was never sent. This root's
480
+ * own stack says why when it records one, in the words `ps` uses for the same silence. */
481
+ function unansweredClassLaunch(t, at) {
482
+ const refused = (message, remedy) => new CommandFailure("refused", "TARGET_UNAVAILABLE", `${message}, so the launch was not sent and nothing was launched`, { ...at, remedy });
483
+ if (t.root !== undefined && stackManagerStarting(t.root, t.space))
484
+ return refused("the stack's manager is starting", "run the spawn again once `cotal up` reports the manager started");
485
+ if (t.root !== undefined && stackManagerAbsent(t.root, t.space))
486
+ return refused("no manager is running for this space", startStackManagerRemedy(t.space, t.server));
487
+ const pid = t.root === undefined ? undefined : runningStackManagerPid(t.root, t.space);
488
+ if (pid !== undefined)
489
+ 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`);
490
+ return refused("no manager answered", "cotal ps shows which managers answer; run the spawn again once one does");
491
+ }
492
+ /** What the registered managers say about unpinned launches. `noApplication` holds when one answered
493
+ * and each one that answered says it runs agents but takes no unpinned launch; `gone` lists the
494
+ * managers skipped because the broker affirms nothing subscribed on their rail. Status has no
495
+ * scatter route, so each is read pinned to its instance, racing the rail probe: whichever settles
496
+ * first stops the other, so neither a live manager nor a gone one is waited out. */
497
+ async function classLaunchCensus(flags, t) {
498
+ const gone = [];
499
+ const managers = [];
500
+ const unavailable = [];
501
+ const empty = [];
502
+ for (const instanceId of await liveManagerIds(t.space, t.server, t.auth)) {
503
+ const pinned = await resolveControlTarget(flags, "control-caller-privileged", instanceId, { onRefusal: "throw" });
504
+ const settled = new AbortController();
505
+ const status = await Promise.race([
506
+ managerRailGone(pinned.space, pinned.server, pinned.auth, instanceId, settled.signal).then((isGone) => isGone ? undefined : new Promise(() => { })),
507
+ askManager(cliControl, pinned.space, pinned.server, "managerStatus", undefined, pinned.auth, "owner", 5_000, { instanceId, signal: settled.signal }),
508
+ ]).finally(() => settled.abort());
509
+ if (status === undefined) {
510
+ gone.push(instanceId);
511
+ continue;
512
+ }
513
+ const data = status.data;
514
+ if (!status.ok || data?.classSpawn !== false || data.execution === "none")
515
+ return { noApplication: false, gone, managers, unavailable, empty };
516
+ const manager = managerAt(instanceId, data.host);
517
+ managers.push(manager);
518
+ if (data.connectors?.length) {
519
+ for (const connector of data.connectors.filter(row => row.state === "unavailable"))
520
+ unavailable.push(`${manager}: ${connector.agent}: ${oneLine(connector.reason ?? "unavailable at manager startup")}`);
521
+ }
522
+ else
523
+ empty.push(manager);
524
+ }
525
+ return { noApplication: managers.length > 0, gone, managers, unavailable, empty };
526
+ }
527
+ /** A manager as a refusal names it: its instance id, and the host its own status reports. */
528
+ const managerAt = (instanceId, host) => typeof host === "string" && host ? `manager ${instanceId} on host ${host}` : `manager ${instanceId}`;
529
+ /** {@link managerAt} for one manager, read pinned to it. A seat (`flags` undefined) reads with its
530
+ * own caller, and a status that cannot be read leaves the host out. */
531
+ async function managerNamed(flags, t, instanceId) {
532
+ try {
533
+ const pinned = flags ? await resolveControlTarget(flags, "control-caller-privileged", instanceId, { onRefusal: "throw" }) : t;
534
+ const status = await askManager(cliControl, pinned.space, pinned.server, "managerStatus", undefined, pinned.auth, "owner", 5_000, { instanceId });
535
+ return managerAt(instanceId, status.ok ? status.data?.host : undefined);
536
+ }
537
+ catch {
538
+ return managerAt(instanceId, undefined);
539
+ }
540
+ }
541
+ /** The `cotal ext add` that installs connector `name`, quoted for a refusal. */
542
+ const extAddFor = (name) => OFFICIAL_CONNECTORS[name] ? `\`cotal ext add ${OFFICIAL_CONNECTORS[name]}\`` : `\`cotal ext add <npm-package>\` for "${name}"`;
543
+ /** The harness the manager's `spawn` resolves for this persona, read with the same fields `start` sends. */
544
+ async function launchAgentOrExit(t, on, fields) {
545
+ const reply = await askManager(cliControl, t.space, t.server, "resolveAgent", fields, t.auth, "owner", undefined, { instanceId: on });
546
+ failIfNotOk(reply);
547
+ return reply.data.agent;
548
+ }
549
+ /**
550
+ * Carry a session this host holds to the manager instance a detached resume launches on, and return
551
+ * the claim its `spawn` names (#1499, docs/design/resume-transfer.md section 2). Undefined when this
552
+ * host holds no session `id`: the id then resolves on the manager's host as it always has. Only the
553
+ * connector can tell a local session from one that lives on the manager's host, so a connector this
554
+ * CLI cannot load is refused.
555
+ */
556
+ async function carryTranscript(flags, on, id, agent) {
557
+ let connector;
558
+ try {
559
+ connector = await materializeExtension({ kind: "connector", name: agent });
560
+ }
561
+ catch (error) {
562
+ if (isCommandFailure(error))
563
+ throw error;
564
+ if (!connectorListed(agent))
565
+ throw missingConnector(agent, { space: flags.space });
566
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `resume: ${oneLine(error.message)}`);
567
+ }
568
+ let found;
569
+ try {
570
+ found = connector.resumeTranscript?.find(id, process.env);
571
+ }
572
+ catch (error) {
573
+ if (isCommandFailure(error))
574
+ throw error;
575
+ throw new CommandFailure("refused", "USAGE_INVALID", `resume: ${error.message}`, { selfContained: true });
576
+ }
577
+ if (found === undefined)
578
+ return undefined;
579
+ if (on === undefined) {
580
+ throw new CommandFailure("refused", "USAGE_INVALID", `resume: session ${id} is held on this host, and carrying it needs one manager instance`, {
581
+ remedy: "pass --on <instance>", selfContained: true,
582
+ });
583
+ }
584
+ const bytes = readFileSync(found.path);
585
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
586
+ const t = await resolveControlTarget(flags, "control-caller-admin", on);
587
+ recordOperationSpace(t.space);
588
+ const bucket = transferBucket(t.space, on);
589
+ const writer = await transferWriterOrExit(flags, t, on, sha256);
590
+ let sent = 0;
591
+ let chunks = 0;
592
+ for (;;) {
593
+ const reply = await askManager(cliControl, t.space, t.server, "transcriptReceive", {
594
+ sha256, size: bytes.length, source: id, sourceHost: hostname(), ...(found.title ? { title: found.title } : {}),
595
+ }, t.auth, "owner", undefined, { instanceId: on });
596
+ failIfNotOk(reply);
597
+ const answer = reply.data;
598
+ if (answer.state === "staged") {
599
+ console.log(c.dim(`carried session ${id} to ${on}: sha256:${sha256}, ${sent} of ${bytes.length} bytes sent in ${chunks} chunks`));
600
+ return answer.claim;
601
+ }
602
+ const pass = await withControlConnection(t.server, writer, (nc) => writeTransfer(nc, bucket, bytes));
603
+ sent += pass.sent;
604
+ chunks += pass.chunks;
605
+ }
606
+ }
607
+ /** The transfer writer instrument for one object in one instance's bucket (design section 6), once
608
+ * the transcript is hashed: minted from this host's copy of the mesh's signing seed, or on a
609
+ * user-auth mesh exchanged from the operator's login as a `transfer-writer` view. An open mesh
610
+ * enforces no grants, so a bare connection writes there. */
611
+ async function transferWriterOrExit(flags, t, instanceId, hex) {
612
+ if (t.mode === "open")
613
+ return { tls: t.auth.tls };
614
+ if (t.mode === "user") {
615
+ const conn = await connectUserControlOrExit(flags);
616
+ try {
617
+ const view = await userViewAuth(conn, "transfer-writer", { transferWriter: { instanceId, hex } });
618
+ return { bearer: view.bearer, sentinelCreds: view.sentinelCreds, tls: conn.tls };
619
+ }
620
+ catch (e) {
621
+ stderrLine("✗ ", `resume: ${e.message}`, c.red);
622
+ process.exit(1);
623
+ }
624
+ }
625
+ if (t.mode !== "auth" || !t.spaceAuth) {
626
+ 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);
627
+ process.exit(1);
628
+ }
629
+ return { creds: await mintCreds(t.spaceAuth, newIdentity(), "transfer-writer", { transferWriter: { instanceId, hex } }), tls: t.auth.tls };
630
+ }
631
+ //# sourceMappingURL=spawn-managed-launch.js.map