@cotal-ai/workspace 0.136.8 → 0.138.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/build/Release/darwin-arm64/build.json +1 -1
  2. package/build/Release/darwin-x64/build.json +1 -1
  3. package/build/Release/win32-arm64/build.json +1 -1
  4. package/build/Release/win32-x64/build.json +1 -1
  5. package/dist/attach/attach-client.d.ts +120 -0
  6. package/dist/attach/attach-client.d.ts.map +1 -0
  7. package/dist/attach/attach-client.js +525 -0
  8. package/dist/attach/attach-client.js.map +1 -0
  9. package/dist/attach/attach-seat.d.ts +174 -0
  10. package/dist/attach/attach-seat.d.ts.map +1 -0
  11. package/dist/attach/attach-seat.js +732 -0
  12. package/dist/attach/attach-seat.js.map +1 -0
  13. package/dist/attach/index.d.ts +3 -0
  14. package/dist/attach/index.d.ts.map +1 -0
  15. package/dist/attach/index.js +3 -0
  16. package/dist/attach/index.js.map +1 -0
  17. package/dist/chat/admission.d.ts +34 -0
  18. package/dist/chat/admission.d.ts.map +1 -0
  19. package/dist/chat/admission.js +18 -0
  20. package/dist/chat/admission.js.map +1 -0
  21. package/dist/chat/engine.d.ts +111 -0
  22. package/dist/chat/engine.d.ts.map +1 -0
  23. package/dist/chat/engine.js +225 -0
  24. package/dist/chat/engine.js.map +1 -0
  25. package/dist/chat/index.d.ts +8 -0
  26. package/dist/chat/index.d.ts.map +1 -0
  27. package/dist/chat/index.js +8 -0
  28. package/dist/chat/index.js.map +1 -0
  29. package/dist/chat/native-session.d.ts +120 -0
  30. package/dist/chat/native-session.d.ts.map +1 -0
  31. package/dist/chat/native-session.js +487 -0
  32. package/dist/chat/native-session.js.map +1 -0
  33. package/dist/chat/open-session.d.ts +9 -0
  34. package/dist/chat/open-session.d.ts.map +1 -0
  35. package/dist/chat/open-session.js +120 -0
  36. package/dist/chat/open-session.js.map +1 -0
  37. package/dist/chat/session.d.ts +230 -0
  38. package/dist/chat/session.d.ts.map +1 -0
  39. package/dist/chat/session.js +2 -0
  40. package/dist/chat/session.js.map +1 -0
  41. package/dist/chat/static-session.d.ts +63 -0
  42. package/dist/chat/static-session.d.ts.map +1 -0
  43. package/dist/chat/static-session.js +237 -0
  44. package/dist/chat/static-session.js.map +1 -0
  45. package/dist/chat/user-session.d.ts +22 -0
  46. package/dist/chat/user-session.d.ts.map +1 -0
  47. package/dist/chat/user-session.js +182 -0
  48. package/dist/chat/user-session.js.map +1 -0
  49. package/package.json +12 -4
@@ -0,0 +1,732 @@
1
+ import { dialerFor, mintCreds, newIdentity, oneLine, openSessionRail, standaloneConnectOpts } from "@cotal-ai/core";
2
+ import { divergentCwdAnchor } from "../auth-paths.js";
3
+ import { ConnectRefusal, userSessionAuth } from "../connect.js";
4
+ import { resolveControlTarget, resolveSeatControlTarget } from "../control-target.js";
5
+ import { askManager, managerFailure } from "../control/manager.js";
6
+ import { locateSeat, seatMissRefusal, seatNotFoundMessage } from "../control/seat.js";
7
+ import { isWorkspaceTargetError } from "../mesh-target.js";
8
+ import { CommandFailure, recordOperationSpace } from "../output.js";
9
+ import { renderReport } from "../present.js";
10
+ import { renderWorkspaceError } from "../render.js";
11
+ import { attachClient, detachKey, holdTerminal, isDetachPress, isTransportEnd, meshSessionTransport, writeNotice } from "./attach-client.js";
12
+ /** Re-establishment backoff, in order; the last value is the cap and repeats forever. A seat that
13
+ * exists is worth waiting for — the operator asked to be attached to it, and the alternative is
14
+ * the terminal they walked away from being gone when they come back. */
15
+ const RECONNECT_BACKOFF_MS = [1_000, 2_000, 5_000, 10_000, 30_000];
16
+ /** How long any single wait on a LINK may take before the loop stops waiting on it. Neither
17
+ * `flush()` nor `drain()` carries a deadline of its own, and `connect`'s `timeout` covers only the
18
+ * dial: a link that half-opens AFTER connect (the exact slow death this command exists for) would
19
+ * otherwise pin the loop, and the detach key with it, until the connection's own heartbeat gave up
20
+ * around two minutes later. */
21
+ const LINK_DEADLINE_MS = 5_000;
22
+ /** Race a link round trip against a deadline, and answer `no` if the deadline wins. The timer is
23
+ * deliberately NOT unref'd: it is the only thing keeping the process alive while we wait on a
24
+ * socket that will never answer, and an unref'd one lets node empty its loop and abort the whole
25
+ * command on a pending await instead of finishing the wait and printing why. It is cleared as soon
26
+ * as either side settles, so a healthy link is never held open for the remainder of the deadline. */
27
+ export const withDeadline = async (work, ms) => {
28
+ let timer;
29
+ const deadline = new Promise((r) => { timer = setTimeout(() => r(false), ms); });
30
+ try {
31
+ return await Promise.race([work, deadline]);
32
+ }
33
+ finally {
34
+ clearTimeout(timer);
35
+ }
36
+ };
37
+ /** Did a flush RETURN inside the deadline? That, and not the publish, is what says a frame left:
38
+ * publishing is a local buffer write. A rejection and a timeout are the same answer here, `no`. */
39
+ const flushed = (nc) => withDeadline(nc.flush().then(() => true, () => false), LINK_DEADLINE_MS);
40
+ /** Give a connection back, bounded. Draining is another flush, so a link that has already missed
41
+ * its deadline is closed outright instead of being asked to drain through the same dead socket.
42
+ * A drain that REJECTS has closed nothing either: it gives up inside that same flush, before the
43
+ * close it would have done, so a rejection means close it here or leak the socket. */
44
+ const closeLink = async (nc) => {
45
+ const drained = await withDeadline(nc.drain().then(() => true, () => false), LINK_DEADLINE_MS);
46
+ // The close gets the same deadline as everything else on this path. Tearing a socket down is
47
+ // local work and should not be able to wait at all, but "should not" is what the drain above was
48
+ // supposed to be too, and a bound that covers every wait but one is a bound with a footnote.
49
+ if (!drained)
50
+ await withDeadline(nc.close().then(() => true, () => true), LINK_DEADLINE_MS);
51
+ };
52
+ /** A session that ran at least this long counts as one that WORKED, whether or not the seat spoke.
53
+ * Below it, a link that comes up for the control round trip and dies again is a flap, and resetting
54
+ * the backoff on those re-mints a grant, a credential and a hand-back connection every second. */
55
+ const SESSION_WORKED_MS = 5_000;
56
+ /** `inspect` found durable nonterminal state after the live seat disappeared. The manager owns the
57
+ * detail shape; the CLI keys only on its namespaced discriminator so the manager's rich diagnostic
58
+ * remains intact for operator commands while reconnect can act on the one fact it needs. */
59
+ const STATIC_SLOT_OBSERVATION_DETAIL = "ai.cotal.manager.static-slot-observation";
60
+ /** The manager's marker for an attach refused because the seat's runtime opens no terminal stream.
61
+ * Same arrangement as the detail above: the manager owns the shape and its guidance wording, and
62
+ * the CLI keys only on the namespaced discriminator. */
63
+ const RUNTIME_NO_TERMINAL_DETAIL = "ai.cotal.manager.runtime-no-terminal";
64
+ /**
65
+ * Classify a refusal on the manager's structured error, never on its wording. The wording is
66
+ * operator copy and changes; the code and namespaced detail are the contract. Getting this wrong in
67
+ * either direction is a real failure: reading `permission-denied` as transient turns a refusal into
68
+ * an infinite retry loop against a manager that has already said no, and reading `not-found` or an
69
+ * `inspect` static-slot observation as transient does the same to a seat that no longer exists.
70
+ * Other `failed-precondition` refusals remain transient, including the session ceiling.
71
+ */
72
+ export function attachRefusal(code, details) {
73
+ if (code === "permission-denied")
74
+ return "denied";
75
+ if (code === "not-found")
76
+ return "gone";
77
+ // `unimplemented` is the manager saying this runtime does not do attach at all - a seat on an
78
+ // external terminal multiplexer or IDE, or a control instance that spawns nothing. Asking again
79
+ // cannot change it, so a reconnecting attach must stop rather than retry it forever.
80
+ if (code === "unimplemented")
81
+ return "denied";
82
+ if (code === "failed-precondition" && details?.some((detail) => detail.kind === STATIC_SLOT_OBSERVATION_DETAIL))
83
+ return "gone";
84
+ return "transient";
85
+ }
86
+ /**
87
+ * A re-establishment that threw, classified. A connect refusal that asking again cannot fix (a
88
+ * missing seed, refused credentials, a user-auth mesh offered static creds) is `fatal`, so the loop
89
+ * exits with the refusal's own sentence and hint instead of retrying it in silence. The control
90
+ * resolver's mode peek rethrows a broken mesh record as a raw target error before the connect
91
+ * helper can wrap it, and it only rethrows the codes that are not "no mesh found", so that is fatal
92
+ * too. Anything else, including a broker that is not reachable yet, is transient.
93
+ */
94
+ class SeatAttachCallerUnavailable extends Error {
95
+ constructor() { super("the launching seat could not re-establish its own caller; no operator identity was substituted"); }
96
+ }
97
+ function thrownEstablishment(e) {
98
+ if (e instanceof SeatAttachCallerUnavailable)
99
+ return { ok: false, kind: "fatal", message: e.message };
100
+ if (e instanceof ConnectRefusal && e.kind === "permanent")
101
+ return { ok: false, kind: "fatal", message: [e.rendered.replace(/^✗ /, ""), e.hint].filter(Boolean).join("\n") };
102
+ if (isWorkspaceTargetError(e))
103
+ return { ok: false, kind: "fatal", message: renderWorkspaceError({ kind: "target", error: e }).replace(/^✗ /, "") };
104
+ return { ok: false, kind: "transient", message: e.message };
105
+ }
106
+ /**
107
+ * What a re-establishment TELLS the operator while it keeps trying, and what it keeps to itself.
108
+ * Returns the line to print, or undefined for silence.
109
+ *
110
+ * Only the MANAGER's own refusal is relayed, and only when it changes. An operator watching
111
+ * `reconnecting` for ten minutes cannot otherwise tell a sleeping laptop from a manager that is at
112
+ * its session ceiling, and the ceiling is the one a person can act on. Repeating a steady refusal
113
+ * on every attempt would bury it.
114
+ *
115
+ * A LOCAL failure to reach anything is deliberately silent: it is already what `connection lost,
116
+ * reconnecting` says, and the copy on this path is written for someone who just typed a command
117
+ * ("no mesh running at X - run `cotal up`"), which is the wrong thing to tell someone whose wifi
118
+ * dropped.
119
+ */
120
+ export function reconnectNotice(est, alreadySaid) {
121
+ if (!est.fromManager || est.message === alreadySaid)
122
+ return undefined;
123
+ return `[cotal: ${est.message}]`;
124
+ }
125
+ /**
126
+ * The line an exit owes an operator about sessions this attach could not hand back, or nothing.
127
+ *
128
+ * Suppressed on `gone`, and that is not tidiness. That verdict exists only when the manager proves
129
+ * the live seat is absent: either `not-found`, or the namespaced durable static-slot observation
130
+ * after its process is gone. Freeing a seat ends every session bound to it (`freeSlot` into
131
+ * `endForTarget`, on despawn, self-stop, reap and natural exit alike). The sessions this would name
132
+ * have already been collected, so naming them would be inventing work for someone who is about to
133
+ * close their terminal.
134
+ */
135
+ export function heldSessionNotice(pending, verdict) {
136
+ if (pending < 1 || verdict === "gone")
137
+ return undefined;
138
+ const what = pending === 1 ? "a session" : `${pending} sessions`;
139
+ return `[cotal: the manager still holds ${what} from the lost link; each frees when the seat or the manager ends it]`;
140
+ }
141
+ /**
142
+ * Ask the manager for a session and open it: a FRESH grant, a FRESH per-session caller credential,
143
+ * a FRESH connection, every time. Nothing is carried over from a previous attempt, so a reconnect
144
+ * re-runs the manager's whole authorization path (`serveGated` → `authorizeNamed` → a one-use
145
+ * holder-bound grant with its own TTL) exactly as the first attach did. A revoked or expired grant
146
+ * cannot be kept alive by reconnecting, because no grant is ever presented twice. `v` carries the
147
+ * caller's {@link AttachCaller} choices beside the seat.
148
+ */
149
+ async function establishAttachSession(v, on, reconnect, firstAttempt) {
150
+ // A reconnect must never cross a path that can END THE PROCESS. The mesh resolve and its
151
+ // preflight are written to do exactly that ("no mesh running at X - run `cotal up`"), which is
152
+ // the right answer for a person who just typed a command and the wrong one for a link that is
153
+ // coming back. So a RE-ESTABLISHMENT asks for the throwing form, and the loop retries a refusal
154
+ // whose kind is transient and stops on a permanent one.
155
+ //
156
+ // Keyed off `first`, NOT off the reconnect flag, and the difference is user-visible. A refusal
157
+ // that escapes as an exception is rendered by the dispatcher's generic handler, which prints
158
+ // `✗ ${message}` over a sentence that already opens with `✗` and drops the refusal's hint line.
159
+ // The reconnect flag is on by DEFAULT, so keying on it sent the very first attach down that path
160
+ // and turned today's "no mesh running at X - run `cotal up`" into a double mark with no remedy.
161
+ // The first attempt is not a re-establishment and has nothing to survive for.
162
+ //
163
+ // Seat locality is deliberately not crossed here: it is resolved ONCE, before the loop, and the
164
+ // pin is carried in. On the command path it is the other step that exits.
165
+ // Same reach routing as stop: static mesh → any-mode on the `control-caller-admin` instrument;
166
+ // user mesh → the operator's own bearer with owner reach, the manager deciding (own owner-domain
167
+ // passes with "spawn", cross-owner needs ledger "admin").
168
+ // The console asks for the throwing form on the FIRST attempt as well (`onRefusal` on the
169
+ // target): inside a TUI a printed sentence and a `process.exit` would blank the operator's screen
170
+ // mid-session, and the refusal becomes a status-line notice instead. So "first" here means the
171
+ // first attempt of a command that wants the exit.
172
+ const first = firstAttempt && v.onRefusal === "exit";
173
+ const seat = v.asSeat ? await resolveSeatControlTarget(v, on) : undefined;
174
+ if (v.asSeat && !seat)
175
+ throw new SeatAttachCallerUnavailable();
176
+ const t = seat ?? await resolveControlTarget(v, "control-caller-admin", on, first ? {} : { onRefusal: "throw" });
177
+ recordOperationSpace(t.space);
178
+ const reach = t.auth.bearer ? "owner" : "any";
179
+ // A refusal's report names the mesh in its heading, so this block names it once, in a field.
180
+ if (first)
181
+ console.error(renderReport({ sections: [{ title: "Attach", blocks: [{ kind: "fields", rows: [["Space", t.space], ["Agent", v.name], ["Manager", on ?? t.auth.managerInstanceId ?? "native selection"]] }] }] }, "rich", process.stderr));
182
+ const reply = await askManager(v.control, t.space, t.server, "attach", { name: v.name }, t.auth, reach, undefined, { instanceId: on, expectedTarget: v.expectedTarget });
183
+ if (!reply.ok) {
184
+ // The one refusal no attach can work around: this seat's runtime streams no terminal. It is
185
+ // said once, with the runtime's own guidance for watching the agent where it really runs, and
186
+ // the Next names what does reach the seat - never "inspect and reattach", which cannot succeed
187
+ // here and is the advice this refusal exists to replace.
188
+ const noTerminal = reply.details?.some((detail) => detail.kind === RUNTIME_NO_TERMINAL_DETAIL) === true;
189
+ if (first && noTerminal)
190
+ throw new CommandFailure("refused", "UNSUPPORTED", reply.error ? oneLine(reply.error) : "the seat's runtime streams no terminal, so there is none to attach", {
191
+ target: { space: t.space, agent: v.name, managerInstanceId: reply.managerInstanceId ?? on ?? null },
192
+ native: { code: reply.code, outcome: reply.nativeOutcome },
193
+ ...(v.noTerminalRemedy ? { remedy: v.noTerminalRemedy({ space: t.space, name: v.name }) } : {}),
194
+ });
195
+ if (first && (reply.preSubmitRefusal || reply.nativeOutcome === "not-executed"))
196
+ throw managerFailure(reply, "terminal attach", { space: t.space, agent: v.name, managerInstanceId: reply.managerInstanceId ?? on ?? null });
197
+ return { ok: false, kind: attachRefusal(reply.code, reply.details), message: reply.error ?? "error", fromManager: true, code: reply.code, ...(noTerminal ? { noTerminal: true } : {}) };
198
+ }
199
+ // P2 item 6: the reply is the holder-bound §13.6 session GRANT (no ws:// URL). Redeem it over the
200
+ // mesh. A static-auth mesh mints a per-session, rails-only caller cred from the resolved root's
201
+ // seed. A registered open mesh has no seed: the same bare connection `askManagerEp` already used
202
+ // for the control round trip opens the caller rail. USER mesh (bearer, no local seed): refuse LOUD
203
+ // — the 2-step user-mode redemption callout is the #29 follow-up, deliberately not wired here.
204
+ const { grant, resumedFrom } = reply.data;
205
+ // The trust material the TARGET resolved, not a second answer walked up from the cwd. This used
206
+ // to be `loadSpaceAuth(authDir(findCotalRoot()), t.space)`, which is the defect behind issue #722:
207
+ // resolution had already picked a root from the registry and connected with it, and then this line
208
+ // asked the current directory the same question and got a different answer. On any machine that is
209
+ // not a hypothetical: `~/.cotal` exists because the registry lives there, `findCotalRoot` accepts
210
+ // any directory merely NAMED `.cotal`, so every cwd under $HOME outside a project resolves here to
211
+ // the home directory - whose trust chain for the same space differs from the resolved root's in
212
+ // account, signing, sys and operator material. The result was a credential minted from a mesh the
213
+ // broker never trusted, surfacing as a bare `Authorization Violation` that named nothing.
214
+ // `control.ts` already stated the rule this restores: trust is carried forward rather than
215
+ // re-loaded, because a second load is a second answer to "which space's seed" for one command.
216
+ // A cwd anchor holding a DIFFERENT chain for this space is reported, never obeyed. It cannot
217
+ // change what this command does any more - the seed above comes from the resolution, not the walk
218
+ // - but staying silent is how issue #722 stayed a mystery: the operator had no way to learn that
219
+ // the directory they were standing in carried another mesh's trust. Reported on the way past, so
220
+ // it is said whether or not the attach then succeeds.
221
+ const shadow = t.root === undefined ? undefined : divergentCwdAnchor(t.root, t.space);
222
+ if (shadow)
223
+ (v.notice ?? writeNotice)({
224
+ tone: "warning",
225
+ text: `! this directory resolves to ${shadow.cwdRoot}, whose .cotal/auth holds a DIFFERENT trust chain for space "${t.space}".\n` +
226
+ ` attach used ${t.root}, the root this mesh resolved to. The other one is not being used, and is worth a look.`,
227
+ });
228
+ const tls = t.auth.tls === true;
229
+ const id = newIdentity();
230
+ // WHICH CONTRACT redeems this grant is decided ONCE, by the recorded mesh mode, and the answer is
231
+ // a value this function then carries. It is never re-derived from the absence of a seed: that
232
+ // inference is issue #1205 itself, where an open mesh (which holds no seed BY DESIGN) was read as
233
+ // a static mesh whose seed had gone missing, and every open attach was refused.
234
+ const material = attachSessionMaterial(t);
235
+ if (material.kind === "fatal")
236
+ return { ok: false, kind: "fatal", message: material.message };
237
+ let link;
238
+ if (material.kind === "redeem") {
239
+ // #2312, USER mesh: present this login's identity together with the grant to the identity
240
+ // plane, which decides whether this principal holds the session and answers with a bearer the
241
+ // callout turns into the SAME session-caller rows and grant expiry the static arm mints. No seed
242
+ // is read or written, and nothing on this side decides who may hold the session.
243
+ let auth;
244
+ try {
245
+ auth = await userSessionAuth(t, grant);
246
+ }
247
+ catch (e) {
248
+ return { ok: false, kind: "fatal", message: e instanceof Error ? e.message : String(e) };
249
+ }
250
+ link = { mode: "session-bearer", tls, ...auth };
251
+ }
252
+ else
253
+ link =
254
+ material.kind === "bare"
255
+ // An open mesh has no credential system: the same bare connection the control round trip
256
+ // already used opens the caller rail. Nothing is minted and nothing is invented.
257
+ ? { mode: "bare", tls }
258
+ : {
259
+ mode: "session-caller",
260
+ tls,
261
+ creds: await mintCreds(material.auth, id, "session-caller", {
262
+ sessionCaller: { endpoint: grant.endpoint, sessionId: grant.sessionId, epoch: grant.serving.epoch },
263
+ expiresAt: Math.floor(grant.exp / 1000), // grant.exp is ms (now+ttlMs); the JWT exp is seconds
264
+ }),
265
+ };
266
+ // maxReconnectAttempts is the whole difference between the two modes, and it is deliberate.
267
+ // ONE-SHOT keeps the old -1: the NATS layer redials forever under a single session.
268
+ // RECONNECTING uses 0, because that redial is what breaks the attach rather than saving it — the
269
+ // session is already dead by the time the link comes back (the serving rail either kept
270
+ // advancing `seq` into a subject nobody was subscribed to, so the restored subscription faults
271
+ // with `gap`, or it stalled out and closed while this side was away, so nothing ever arrives
272
+ // again). Owning re-establishment here means the link coming back produces a real session with a
273
+ // real repaint, instead of a restored socket over a session that ended without us.
274
+ const nc = await dialerFor(t.server)({
275
+ servers: t.server,
276
+ inboxPrefix: `_INBOX_${id.id}`,
277
+ // After the default: a bearer link's callout scopes the inbox on its own connect nonce.
278
+ ...redeemConnectOpts(link),
279
+ maxReconnectAttempts: reconnect ? 0 : -1,
280
+ // Detection latency is part of the defect, not a detail of it. A laptop waking from sleep does
281
+ // not always get a socket error: the connection can sit half-open, and on the stock two-minute
282
+ // ping with two misses the client would not learn its link was dead for about four minutes,
283
+ // with the terminal frozen the whole time. Ten seconds puts that in tens of seconds. Only on
284
+ // the reconnecting path, so `--no-reconnect` keeps today's timing along with today's exit.
285
+ //
286
+ // NOT MEASURED by this change's suite, and said so rather than implied: the smoke severs the
287
+ // link by destroying sockets, so every number it prints is close detection. A fault model that
288
+ // half-opens a link is what would grade this line, and it does not exist here yet.
289
+ ...(reconnect ? { pingInterval: 10_000 } : {}),
290
+ });
291
+ return { ok: true, nc, grant, link, inbox: id.id, server: t.server, ...(resumedFrom ? { resumedFrom } : {}) };
292
+ }
293
+ /** The ONE place a {@link RedeemLink} becomes NATS connect options. Both connections on the redeem
294
+ * path (the session link and the abandoned-session hand-back) go through here, so neither can
295
+ * invent a credential for an open mesh or drop one on a sealed mesh, and a third caller gets the
296
+ * same two arms for free. */
297
+ export function redeemConnectOpts(link) {
298
+ if (link.mode === "session-bearer")
299
+ return standaloneConnectOpts({ bearer: link.bearer, sentinelCreds: link.sentinelCreds, tls: link.tls });
300
+ return link.mode === "bare"
301
+ ? standaloneConnectOpts({ tls: link.tls })
302
+ : standaloneConnectOpts({ creds: link.creds, tls: link.tls });
303
+ }
304
+ /**
305
+ * Which redeem contract this target gets: a bare open-mesh connection, a seed-backed mint, or a
306
+ * loud refusal. Graded by `smoke:attach-open-mode`, whose mutations flip each arm in turn.
307
+ *
308
+ * EXHAUSTIVE over the three recorded modes on purpose, with `user` named rather than reached by
309
+ * fallthrough. A `user` entry holds no local seed by design and its two-step redemption is not
310
+ * wired, so it must refuse even on the day a user-mode root happens to carry static material on
311
+ * disk; letting it fall through to the seed test would silently mint on the wrong identity plane.
312
+ * An UNRECORDED mode (a raw off-registry connection) is the conservative arm: it is not known to be
313
+ * open, so it takes the sealed test and refuses without a seed.
314
+ */
315
+ export function attachSessionMaterial(t) {
316
+ switch (t.mode) {
317
+ // An OPEN mesh: no credential system at all, so there is no seed to be missing and nothing to
318
+ // mint. This is the arm issue #1205 did not have.
319
+ case "open":
320
+ return { kind: "bare" };
321
+ // A USER mesh: the identity plane redeems the grant for the bearer (#2312), EVEN IF a seed is
322
+ // present, because the bearer plane is the control surface there and static material would be
323
+ // the wrong identity. `spaceAuth` is never consulted on this arm.
324
+ case "user":
325
+ return { kind: "redeem" };
326
+ // SEALED (`auth`) and unrecorded: the seed is required, and its absence is a refusal. A sealed
327
+ // mesh must never be rescued by the open arm — that is the failure a fix for #1205 is most
328
+ // likely to introduce, and `smoke:attach-open-mode` asserts the refusal by name against a live
329
+ // sealed broker.
330
+ default:
331
+ return t.spaceAuth ? { kind: "mint", auth: t.spaceAuth } : { kind: "fatal", message: attachNoSeedMessage(t) };
332
+ }
333
+ }
334
+ /** Why attach cannot redeem a session grant, said in terms of what the command actually resolved.
335
+ *
336
+ * Three distinct states, kept distinct because the remedy differs and a single sentence covering
337
+ * all three is the defect issue #722 opened on (its old text named an internal work item and no
338
+ * root at all). A USER-AUTH mesh holds no local seed by design. A REGISTERED static mesh has a
339
+ * root and it is named, so an operator can see which directory the command used rather than
340
+ * guessing at their cwd.
341
+ *
342
+ * The third arm is an INVARIANT, not advice, and is written that way on purpose. A connection with
343
+ * no resolved root is what the type allows, and no supported route reaches redemption in that
344
+ * state: both off-registry routes are refused earlier, which `smoke:attach-auth-root` measures
345
+ * rather than assumes. So that arm says what its own existence would mean instead of offering a
346
+ * remedy for a situation that cannot currently arise. */
347
+ function attachNoSeedMessage(t) {
348
+ const shadow = t.root === undefined ? undefined : divergentCwdAnchor(t.root, t.space);
349
+ const shadowLine = shadow
350
+ ? `\n NOTE this directory resolves to ${shadow.cwdRoot}, which holds a DIFFERENT trust chain for "${t.space}"; it was NOT used.`
351
+ : "";
352
+ const head = `mesh attach needs this space's local seed to redeem the session grant, and the mesh resolved for "${t.space}" does not provide one.`;
353
+ if (t.root === undefined)
354
+ return `${head}\n broker ${t.server}\n This connection resolved NO checkout root, and no supported route reaches redemption in that state: an off-registry \`--server\` on an unregistered space is refused for missing credentials, and \`--creds\` is refused at the control surface, both before a session grant is asked for. Reaching this sentence means a route now exists that skips both refusals.${shadowLine}`;
355
+ return `${head}\n broker ${t.server}\n resolved root ${t.root}\n This is a static-auth mesh. Attach still needs this space's seed under ${t.root}/.cotal/auth. Restore the seed at that checkout. This mesh is not open, so attach will not connect without the seed.${shadowLine}`;
356
+ }
357
+ /**
358
+ * Tell the manager a session is over, so it gets its slot back.
359
+ *
360
+ * NOTHING on the serving side reaps a session whose caller went away while the seat is quiet: the
361
+ * rail's stall watchdog only arms once the send window FILLS (`endpoint-session-rail.ts`), an idle
362
+ * seat never fills it, and the bridge has no expiry timer of its own. Measured against a manager
363
+ * with an idle seat: 45s of dead link left the live-session count at 1, and the reconnect took it
364
+ * to 2 — one slot per outage, held until the seat or the manager ends it, against a ceiling of 64.
365
+ *
366
+ * The mechanism is the advisory close frame the rail already defines; the manager's bridge ends on
367
+ * it. On a static-auth mesh it has to be published with THIS session's caller credential, the only
368
+ * one scoped to this session's subjects, so a re-establishment cannot send it on the abandoned
369
+ * session's behalf. On a registered open mesh there is no session-caller seed: the same bare
370
+ * connection the session used hands the slot back. Hence a short-lived connection minted from the
371
+ * abandoned session's own material, never an invented seed.
372
+ */
373
+ async function releaseAbandonedSession(s) {
374
+ const nc = await dialerFor(s.server)({
375
+ servers: s.server,
376
+ inboxPrefix: `_INBOX_${s.inbox}`,
377
+ ...redeemConnectOpts(s.link),
378
+ maxReconnectAttempts: 0,
379
+ timeout: LINK_DEADLINE_MS,
380
+ // The same short ping the reconnecting session uses. This connection exists BECAUSE a link died,
381
+ // so it is the last one that should be left waiting on the stock two-minute heartbeat to find
382
+ // out that the replacement died too.
383
+ pingInterval: 10_000,
384
+ });
385
+ try {
386
+ // The rail is opened only because `close()` is the public way to speak the framing; no timers,
387
+ // and it tears itself down on the same call.
388
+ openSessionRail({ nc, grant: s.grant, role: "caller", onData: () => { }, idleCreditMs: 0, stallTimeoutMs: 0 }).close();
389
+ // Throwing is what keeps the record: the caller holds the session until a flush RETURNS.
390
+ if (!(await flushed(nc)))
391
+ throw new Error(`the close frame for session ${s.grant.sessionId} never left`);
392
+ }
393
+ finally {
394
+ await closeLink(nc);
395
+ }
396
+ }
397
+ /** Watch stdin for the detach key while there is NO session reading it. Without this the key is
398
+ * dead for as long as a reconnect takes, which is exactly when an operator is most likely to give
399
+ * up and press it. Non-detach keystrokes are dropped: there is no seat to send them to, and
400
+ * buffering them would replay a burst into the agent on reconnect. */
401
+ function watchDetachKey(byte) {
402
+ const stdin = process.stdin;
403
+ let fire;
404
+ let pressedYet = false;
405
+ const pressed = new Promise((r) => { fire = r; });
406
+ const hit = () => { pressedYet = true; fire(); };
407
+ // The whole chunk must be exactly one press of the detach key: the legacy control byte, or the
408
+ // kitty keyboard protocol / xterm modifyOtherKeys encoding of the same press (see
409
+ // `isDetachPress`, #598). A chunk carrying it alongside anything else is NOT a keypress:
410
+ // measured on a pty, a real keypress arrives in a read of its own even at 3ms spacing, and the
411
+ // only two ways the byte arrives with company are a paste and a reader that was not reading.
412
+ // Treating a paste that happens to contain the byte (or the encoded sequence) as a detach would
413
+ // turn data into a control action on input nobody typed; the reader that was not reading is the
414
+ // defect this watcher's new lifetime fixes, not a matching problem.
415
+ // Under the console, Ink has called `stdin.setEncoding("utf8")`, and an encoding persists on the
416
+ // stream after Ink releases raw mode, so data arrives as a STRING there (the standalone command
417
+ // gets Buffers). Normalize first: a one-character string is not the number 0x1d, and the compare
418
+ // below would otherwise never match, making the key dead for as long as a reconnect takes.
419
+ const onData = (d) => { if (isDetachPress(d, byte))
420
+ hit(); };
421
+ const onChunk = (data) => onData(Buffer.isBuffer(data) ? data : Buffer.from(data, "utf8"));
422
+ stdin.on("data", onChunk);
423
+ stdin.resume();
424
+ // `pause: false` hands the stream to a session's own reader, which resumes it synchronously right
425
+ // after; pausing there and resuming a line later would be a window where a byte has no owner,
426
+ // which is the whole defect.
427
+ // `hit` as well as `pressed`, because the press has TWO consumers and one of them cannot await:
428
+ // the handoff to a session's reader is synchronous, and it has to know whether the byte it is
429
+ // taking the stream over from has already arrived.
430
+ return { pressed, hit: () => pressedYet, stop: ({ pause = true } = {}) => { stdin.off("data", onChunk); if (pause)
431
+ stdin.pause(); } };
432
+ }
433
+ /**
434
+ * The attach loop. One session at a time; when the LINK breaks and the operator did not detach, it
435
+ * re-establishes with backoff and keeps going, because the seat is still there and the terminal the
436
+ * operator walked away from should still be theirs when they come back.
437
+ */
438
+ async function runAttachLoop(vv, pin, reconnect, key, hold) {
439
+ const notice = vv.notice ?? writeNotice;
440
+ let first = true;
441
+ let attempt = 0; // consecutive re-establishment attempts since the last live session
442
+ // Sessions the manager still counts, waiting to be told. A LIST rather than one slot: a second
443
+ // link death before the first hand-back lands would overwrite the first and leak it with nothing
444
+ // said. It cannot grow without bound, because every entry needed a successful establishment, and
445
+ // successful establishments are exactly what the manager's own session ceiling counts.
446
+ const abandoned = [];
447
+ let saidWhy = ""; // the last transient refusal printed, so a steady reason prints once, not per attempt
448
+ // ONE reader owns stdin for the whole time there is no session: the backoff wait, the round trip
449
+ // that hands the old session back and opens the new one, and the gap in between. It used to exist
450
+ // only for the waits, which left the establishment unread: `stdin` was paused, the stream
451
+ // buffered, and `attachClient`'s `stdin.resume()` flushed whatever had been typed at a terminal
452
+ // with no session straight into the seat's pty. Measured on the code before this change, with the
453
+ // bytes graded at the SEAT rather than on screen: typed during a wait, dropped; during an attempt
454
+ // that failed, dropped; during an attempt that SUCCEEDED, delivered, and a 0x03 typed there
455
+ // arrived as SIGINT at the agent and killed it (the seat recorded the signal and its pid was
456
+ // gone). With the reader installed for the whole period those bytes are read and dropped, which
457
+ // is what the loop always claimed to do, and the detach key works during an attempt as well as
458
+ // during a wait.
459
+ let idle;
460
+ // A TERMINAL only, and the gate lives HERE rather than at the call sites, because there are three
461
+ // of them and a gate written at one is a promise the other two break silently. `printf 'ls\n' |
462
+ // cotal attach` writes into a PIPE, and those bytes are a script's input rather than an operator
463
+ // giving up on a frozen screen: a reader would eat them with no fault anywhere in sight. That is
464
+ // true in EVERY window, not only before the first session, so a pipe keeps the old contract
465
+ // throughout, paused between sessions and flushed into the next one. Measured with the gate at the
466
+ // first call site alone: a piped attach buffered correctly until its first reconnect and then had
467
+ // the reader installed on it by the backoff, so `tail -f log | cotal attach` lost its feed across a
468
+ // link blip. Cells J and I are the first-session halves, cell L is the reconnect one.
469
+ const ownStdin = () => (process.stdin.isTTY ? (idle ??= watchDetachKey(key.byte)) : undefined);
470
+ // Returns whether the detach key had ALREADY been pressed, which is the one thing the session's
471
+ // own reader cannot find out for itself once this reader is gone.
472
+ const releaseStdin = (opts) => {
473
+ const pressed = idle?.hit() ?? false;
474
+ idle?.stop(opts);
475
+ idle = undefined;
476
+ return pressed;
477
+ };
478
+ // Give the manager its slots back. Oldest first, and one failure ends the round rather than
479
+ // skipping ahead, because the reason is the link and the link is the same for all of them.
480
+ const releaseAbandoned = async () => {
481
+ while (abandoned.length > 0) {
482
+ try {
483
+ await releaseAbandonedSession(abandoned[0]);
484
+ abandoned.shift();
485
+ }
486
+ catch {
487
+ break;
488
+ }
489
+ }
490
+ };
491
+ // Every exit runs through here, so the one thing an operator cannot see for themselves is never
492
+ // swallowed. It TRIES first: an operator who detaches during the backoff may well be doing it
493
+ // because the link came back, and returning straight out would leave a slot held that one dial
494
+ // would have freed. The attempt is bounded exactly like every other, and what it could not
495
+ // deliver is what gets said. What to say, and when to say nothing, is `heldSessionNotice`.
496
+ const done = async (v) => {
497
+ // Give the stream back on the way out, on EVERY exit, because this reader resumed it: a resumed
498
+ // stdin is a ref'd handle, and one left behind holds the command open after it has said it
499
+ // detached. That is the same shape as the abandoned backoff timer, and it is why this lives
500
+ // here rather than at the call sites.
501
+ releaseStdin();
502
+ // And drop the process's own claim on the stream, which a PIPE keeps even after a pause. This is
503
+ // the exit path by definition, so nothing here reads stdin again. MEASURED, on a piped attach
504
+ // with the reader correctly not installed: the detach was honoured, the manager freed the slot,
505
+ // `detached from` printed, and the process then sat past 30s with its three stdio pipes as the
506
+ // only resources keeping the loop alive. A pause was not enough on its own.
507
+ //
508
+ // ONLY THE SOCKET KINDS HAVE `unref`, and this is a test of the stream rather than a fallback.
509
+ // Measured: at a terminal stdin is a `tty.ReadStream` and at a pipe a `net.Socket`, both of which
510
+ // have it; given a FILE (`cotal attach < seed.txt`) or a parent that spawns with stdio "ignore",
511
+ // stdin is an `fs.ReadStream` and has no `unref` at all. Calling it there is a TypeError, which
512
+ // is how `smoke:cli-on-instance` caught this: it spawns attach with stdin ignored, and the
513
+ // unguarded call turned a pinned-rail deadline into `process.stdin.unref is not a function`. The
514
+ // same measurement says the other branch needs nothing: a file-backed stdin ends at EOF instead
515
+ // of staying open like a socket, and a process that takes one and releases it exits at once with
516
+ // an empty resource list, where the pipe leaves a PipeWrap behind. So the release exists exactly
517
+ // where there is something to release. Cell N of `smoke:attach-stdin` is the file-backed route.
518
+ if (typeof process.stdin.unref === "function")
519
+ process.stdin.unref();
520
+ if (v.kind !== "gone")
521
+ await releaseAbandoned();
522
+ const held = heldSessionNotice(abandoned.length, v.kind);
523
+ if (held)
524
+ notice({ tone: "status", text: held });
525
+ return v;
526
+ };
527
+ // The FIRST establishment is an attach with no session too, and it is the path every attach takes.
528
+ // Own the keyboard from here rather than from the first reconnect, so a key struck while the
529
+ // command is still resolving the mesh is read and dropped instead of buffered and flushed into the
530
+ // seat when the session opens. Measured before this line existed: a nonce typed at that prompt
531
+ // arrived at the agent.
532
+ //
533
+ // `ownStdin` is a no-op at a pipe; both halves are cells (I and J), so neither is an assumption.
534
+ if (reconnect)
535
+ ownStdin();
536
+ for (;;) {
537
+ if (!first) {
538
+ // Back off BEFORE the attempt, and stay interruptible: the detach key must work while we
539
+ // wait, not only while a session is up. The timer is CLEARED rather than left to the race,
540
+ // because losing a `Promise.race` does not stop a `setTimeout`: the detach is honoured at
541
+ // once, the terminal comes back and `detached from` prints, and then node holds the process
542
+ // open until the abandoned timer fires. On the 30s rung that is half a minute of a shell that
543
+ // has already said it detached and will not give the prompt back. Measured before this line
544
+ // existed: press to first output 0.1s, press to EXIT 27.0s with the next attempt 26.9s away,
545
+ // and 8.3s with it 8.1s away, tracking the rung rather than the work.
546
+ const ms = RECONNECT_BACKOFF_MS[Math.min(attempt, RECONNECT_BACKOFF_MS.length - 1)];
547
+ const watch = ownStdin(); // and it STAYS installed through the attempt this wait precedes
548
+ let timer;
549
+ const waited = new Promise((r) => { timer = setTimeout(() => r(false), ms); });
550
+ // No watcher at a pipe, and nothing to replace it with: a detach byte a script writes here
551
+ // buffers and reaches the next session's own reader, which is exactly what it did before this
552
+ // change. Racing a promise that can never settle would be the same thing written longer.
553
+ const detached = watch ? await Promise.race([waited, watch.pressed.then(() => true)]) : await waited;
554
+ clearTimeout(timer);
555
+ if (detached)
556
+ return await done({ kind: "ended", reason: "detached" });
557
+ attempt++;
558
+ }
559
+ // Give the manager its slots back BEFORE claiming another one. The order is load-bearing at the
560
+ // ceiling: a client that claims first is refused by the very sessions it abandoned. A failure
561
+ // is retried on the next attempt and accounted for by `done` if it never lands.
562
+ await releaseAbandoned();
563
+ let est;
564
+ const attempting = establishAttachSession(vv, pin, reconnect, first);
565
+ // A press DURING the round trip ends the attach now, rather than when the round trip returns.
566
+ // The in-flight establishment is still awaited: it is bounded like every other one, and a
567
+ // session that lands after we have stopped looking is a slot the manager still counts, so it
568
+ // goes on the abandoned list and `done` hands it back over the link that is by then up.
569
+ //
570
+ // `idle` is also set on the FIRST establishment at a terminal, where what it buys is the same
571
+ // thing it buys everywhere else: what gets typed at a prompt that has not come up yet is read
572
+ // and dropped rather than delivered later, which is what cell I grades. It is not a second way
573
+ // to abort. Raw mode is entered in `attachClient`'s `onReady`, so before the
574
+ // first session this process has not touched the terminal's mode at all, and Ctrl-C at a cooked
575
+ // tty is how an operator leaves a command that has not attached.
576
+ if (idle) {
577
+ const raced = await Promise.race([
578
+ attempting.then((e) => ({ est: e }), () => ({ est: undefined })),
579
+ idle.pressed.then(() => ({ detached: true })),
580
+ ]);
581
+ if ("detached" in raced) {
582
+ releaseStdin();
583
+ const late = await attempting.catch(() => undefined);
584
+ if (late?.ok) {
585
+ abandoned.push({ grant: late.grant, link: late.link, inbox: late.inbox, server: late.server });
586
+ // And CLOSE the link that session came up on. Nothing here will ever read it, and an open
587
+ // NATS connection is a ref'd handle: measured, the attach printed `detached from` and then
588
+ // sat there forever, because the hand-back mints its own short-lived connection from the
589
+ // abandoned session's own credential and never touches this one. Same shape as the
590
+ // abandoned backoff timer, one layer down.
591
+ await closeLink(late.nc);
592
+ }
593
+ return await done({ kind: "ended", reason: "detached" });
594
+ }
595
+ }
596
+ try {
597
+ est = await attempting;
598
+ }
599
+ catch (e) {
600
+ // The FIRST attempt throws exactly as it always has — the CLI's top-level handler renders
601
+ // it. Only a reconnect turns a thrown establishment into another attempt. Give the stream
602
+ // back on the way out: this is the one exit from this loop that does not run through `done`,
603
+ // and a resumed stdin is a ref'd handle that would hold the command open after it has already
604
+ // printed why it is giving up.
605
+ if (first) {
606
+ releaseStdin();
607
+ throw e;
608
+ }
609
+ est = thrownEstablishment(e);
610
+ }
611
+ if (!est.ok) {
612
+ // Nothing changes for the first attach: any refusal is the same loud exit as before.
613
+ if (first || est.kind === "fatal" || est.kind === "denied")
614
+ return await done({ kind: "failed", message: est.message, ...(est.fromManager ? { refusal: { code: est.code, noTerminal: est.noTerminal === true } } : {}) });
615
+ if (est.kind === "gone")
616
+ return await done({ kind: "gone" });
617
+ const why = reconnectNotice(est, saidWhy);
618
+ if (why) {
619
+ saidWhy = est.message;
620
+ notice({ tone: "status", text: why });
621
+ }
622
+ continue; // transient: the manager or the link is unreachable right now
623
+ }
624
+ saidWhy = "";
625
+ const from = est.resumedFrom ? ` (resumed from ${est.resumedFrom.host}:${est.resumedFrom.source})` : "";
626
+ notice({ tone: "status", text: first ? `attached to ${vv.name}${from} - ${key.label} to detach` : "[cotal: reconnected]" });
627
+ first = false;
628
+ let outcome;
629
+ const startedAt = Date.now();
630
+ const transport = meshSessionTransport(est.nc, est.grant);
631
+ try {
632
+ // The manager replays its byte-exact backlog snapshot on every open (the `ready` handshake
633
+ // in session/bridge.ts), so the reconnected screen repaints through the path that already
634
+ // exists; there is no second backlog here.
635
+ outcome = await attachClient(transport, hold, () => releaseStdin({ pause: false }), notice);
636
+ }
637
+ finally {
638
+ // Take the stream back FIRST, ahead of the hand-back's own round trips. A session that ends
639
+ // while its SOCKET is still alive is the case this whole change is about, and everything
640
+ // below it here is a publish, a flush and a close, each bounded by LINK_DEADLINE_MS: placed
641
+ // after them, this line would leave the keyboard unowned for as long as a dying link takes
642
+ // to answer, which is precisely when an operator reaches for the detach key. attachClient's
643
+ // cleanup has already removed its own reader and paused the stream, so the ownerless gap is
644
+ // the width of this statement rather than of two deadlines. `done` releases it again on
645
+ // whichever exit follows, and the backoff wait re-installs the same reader.
646
+ if (reconnect)
647
+ ownStdin();
648
+ // Hand the session back. With the link still up that is one advisory frame over the
649
+ // connection already open (a rail that broke while the socket lived — a stall, a gap — is
650
+ // exactly this case, and it is idempotent after a detach has already closed it). The FLUSH is
651
+ // what decides whether it left, not the publish: a link can die between the closed-check and
652
+ // the frame, which is the same slow death this whole change is about. Only a flush that
653
+ // returned counts as handed back; anything else keeps the credential for the next attempt,
654
+ // and see releaseAbandonedSession for why no other credential can carry it.
655
+ let handedBack = false;
656
+ if (!est.nc.isClosed()) {
657
+ transport.close();
658
+ handedBack = await flushed(est.nc);
659
+ }
660
+ if (!handedBack && reconnect) {
661
+ abandoned.push({ grant: est.grant, link: est.link, inbox: est.inbox, server: est.server });
662
+ }
663
+ await closeLink(est.nc);
664
+ }
665
+ // The backoff resets on a session that WORKED, not on one that merely opened. `carried` is not
666
+ // enough on its own: a seat that has produced nothing has an empty backlog snapshot, so a
667
+ // perfectly healthy attach to a QUIET agent would never reset and would climb to the 30s cap
668
+ // over a few blips, which is the seat this whole change cares most about. A session that simply
669
+ // lasted is the other half of the same question.
670
+ if (outcome.carried || Date.now() - startedAt >= SESSION_WORKED_MS)
671
+ attempt = 0;
672
+ if (!reconnect) {
673
+ // One-shot: a faulted session still throws, so `--no-reconnect` exits the way it does today.
674
+ if (outcome.error)
675
+ throw outcome.error;
676
+ return await done({ kind: "ended", reason: outcome.reason });
677
+ }
678
+ if (!isTransportEnd(outcome.reason)) {
679
+ // A faulted end this classification does not recognise is NOT a detach. Printing
680
+ // `detached from` over it would be the silent swallow this whole change exists to remove,
681
+ // so it exits non-zero carrying the fault. Every `fireEnd` site passes a reason today, so
682
+ // this is a guard against a future one that forgets, not a live path.
683
+ if (outcome.error)
684
+ return await done({ kind: "failed", message: outcome.error.message });
685
+ return await done({ kind: "ended", reason: outcome.reason });
686
+ }
687
+ notice({ tone: "status", text: "[cotal: connection lost, reconnecting]" });
688
+ // Raw from here on, whether or not the session that just ended reached ready. A first session
689
+ // whose link died inside its opening flush never ran `onReady`, so the terminal is still cooked:
690
+ // the line discipline would echo the detach key as `^]` and hold it until Enter, and the reader
691
+ // below would never see it (#1471). The attach has already said it is attached, so Ctrl-C at a
692
+ // cooked tty is no longer the way out; the detach key is.
693
+ hold.enterRaw();
694
+ }
695
+ }
696
+ /**
697
+ * The whole attach, as one call: seat locality, the establish-redeem-drive loop with its reconnect,
698
+ * end-reason classification and abandoned-session hand-back, and the terminal given back before
699
+ * the verdict is returned. `cotal attach` and the console's `a` / `:attach` both run THIS, so the
700
+ * console can never drift into a lesser attach. The pin `on`, when the caller already knows it, is
701
+ * honoured. Otherwise a `throw` caller has the seat located the way `stop` locates it, and an `exit`
702
+ * caller has already located it in its own words, since that step prints and exits.
703
+ */
704
+ export async function attachSeat(v, opts) {
705
+ const { reconnect, on: pinned, ...caller } = opts;
706
+ let on = pinned;
707
+ if (on === undefined && caller.onRefusal === "throw") {
708
+ const loc = await locateSeat(caller.control, v, v.name, { onRefusal: "throw" });
709
+ if (loc.kind === "absent")
710
+ return { kind: "failed", message: seatNotFoundMessage(loc, v.name) };
711
+ if (loc.kind === "several")
712
+ return { kind: "failed", message: seatMissRefusal(v.name, caller.verb, loc) };
713
+ if (loc.kind === "pin")
714
+ on = loc.instanceId;
715
+ }
716
+ const detach = detachKey();
717
+ const hold = holdTerminal();
718
+ try {
719
+ return await runAttachLoop({ ...v, ...caller }, on, reconnect, detach, hold);
720
+ }
721
+ catch (e) {
722
+ if (caller.onRefusal === "exit")
723
+ throw e;
724
+ return { kind: "failed", message: e.message };
725
+ }
726
+ finally {
727
+ // The terminal comes back before anything else happens, whatever ended the attach — including
728
+ // a throw out of the one-shot path, which is how `--no-reconnect` keeps its old exit.
729
+ hold.restore();
730
+ }
731
+ }
732
+ //# sourceMappingURL=attach-seat.js.map