@eum-agent/web-shell 0.0.0-stage → 1.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,793 @@
1
+ import { Changed, CloseParams, CreateParams, ListResult, OperationResult, OperationStatusParams, RenameParams, RestartParams, RootsResult, TerminalInput, TerminalOpen, TerminalOutput, TerminalReady, TerminalSummary, WorkspaceId } from "./schema.js";
2
+ import { existsSync } from "node:fs";
3
+ import { userInfo } from "node:os";
4
+ import { fileURLToPath } from "node:url";
5
+ import { z } from "zod";
6
+ import { randomUUID } from "node:crypto";
7
+ import nodePath from "node:path";
8
+ //#region src/output.ts
9
+ const WINDOW = 4194304;
10
+ const BLOCK = 8192;
11
+ const HIGH = 524288;
12
+ const LOW = 131072;
13
+ /** Retains bounded UTF-8 replay and controls each independent consumer's output pressure. */
14
+ function createTerminalOutput(handle, summary, attachments) {
15
+ const chunks = [];
16
+ const observers = /* @__PURE__ */ new Map();
17
+ let retained = 0;
18
+ let epoch = 0;
19
+ let paused = false;
20
+ let ended = false;
21
+ const first = () => chunks[0]?.cursor ?? summary.cursor + 1;
22
+ const send = (observer, value) => observer.context.send(value).catch(() => {
23
+ detach(observer);
24
+ observer.context.close();
25
+ });
26
+ const pressure = () => {
27
+ if (ended) return;
28
+ const blocked = [...observers.values()].some((value) => value.bytes >= HIGH || value.deadline !== void 0);
29
+ if (blocked && !paused) {
30
+ paused = true;
31
+ try {
32
+ handle.pauseOutput();
33
+ } catch {}
34
+ } else if (!blocked && paused) {
35
+ paused = false;
36
+ try {
37
+ handle.resumeOutput();
38
+ } catch {}
39
+ }
40
+ };
41
+ const writer = () => {
42
+ for (const observer of observers.values()) send(observer, {
43
+ kind: "writer",
44
+ inputOwner: summary.inputOwner,
45
+ leaseEpoch: epoch
46
+ });
47
+ };
48
+ const detach = (observer) => {
49
+ if (observer.detached) return;
50
+ observer.detached = true;
51
+ clearTimeout(observer.deadline);
52
+ observer.context.signal.removeEventListener("abort", observer.abort);
53
+ observers.delete(observer.id);
54
+ attachments.change(-1);
55
+ observer.sent.clear();
56
+ observer.bytes = 0;
57
+ if (summary.inputOwner === observer.id) {
58
+ summary.inputOwner = null;
59
+ epoch++;
60
+ writer();
61
+ }
62
+ pressure();
63
+ };
64
+ const pump = async (observer) => {
65
+ if (observer.pumping || observer.detached || ended) return;
66
+ observer.pumping = true;
67
+ try {
68
+ while (!observer.detached && !ended && observer.deadline === void 0 && observer.bytes < HIGH) {
69
+ const earliest = first();
70
+ if (observer.cursor < earliest - 1) {
71
+ const requested = observer.cursor;
72
+ observer.cursor = earliest - 1;
73
+ observer.acknowledged = Math.max(observer.acknowledged, observer.cursor);
74
+ await send(observer, {
75
+ kind: "gap",
76
+ firstCursor: earliest,
77
+ requestedCursor: requested
78
+ });
79
+ }
80
+ const chunk = chunks.find((value) => value.cursor > observer.cursor);
81
+ if (!chunk) break;
82
+ observer.cursor = chunk.cursor;
83
+ observer.sent.set(chunk.cursor, chunk.bytes);
84
+ observer.bytes += chunk.bytes;
85
+ if (observer.bytes >= HIGH && observer.deadline === void 0) {
86
+ observer.deadline = setTimeout(() => {
87
+ if (observer.detached) return;
88
+ detach(observer);
89
+ observer.context.send({
90
+ kind: "error",
91
+ error: {
92
+ code: "slow-observer",
93
+ message: "Terminal consumer did not drain output within one second"
94
+ }
95
+ }).catch(() => {}).finally(() => observer.context.close());
96
+ }, 1e3);
97
+ observer.deadline.unref?.();
98
+ pressure();
99
+ }
100
+ await send(observer, {
101
+ kind: "output",
102
+ cursor: chunk.cursor,
103
+ text: chunk.text
104
+ });
105
+ }
106
+ } finally {
107
+ observer.pumping = false;
108
+ }
109
+ };
110
+ const unwatch = handle.onOutput((output) => {
111
+ if (ended) return;
112
+ if (output.droppedBefore > 0) {
113
+ chunks.length = 0;
114
+ retained = 0;
115
+ summary.truncated = true;
116
+ }
117
+ const data = Buffer.from(output.data, "utf8");
118
+ for (let offset = 0; offset < data.length;) {
119
+ let end = Math.min(offset + BLOCK, data.length);
120
+ while (end < data.length && (data[end] & 192) === 128) end--;
121
+ const slice = data.subarray(offset, end);
122
+ const chunk = {
123
+ cursor: ++summary.cursor,
124
+ text: slice.toString("utf8"),
125
+ bytes: slice.length
126
+ };
127
+ chunks.push(chunk);
128
+ retained += chunk.bytes;
129
+ offset = end;
130
+ while (retained > WINDOW) {
131
+ retained -= chunks.shift().bytes;
132
+ summary.truncated = true;
133
+ }
134
+ }
135
+ for (const observer of observers.values()) pump(observer);
136
+ });
137
+ return {
138
+ /** Atomically snapshots replay and subscribes one observer, with explicit writer ownership. */
139
+ open(params, context) {
140
+ if (ended || summary.status === "ended") throw new TerminalError("terminal-ended");
141
+ if (summary.status !== "running") throw new TerminalError("terminal-not-running");
142
+ if (observers.size >= 4 || attachments.count() >= 32) throw new TerminalError("capacity");
143
+ const cursor = params.cursor ?? 0;
144
+ if (cursor > summary.cursor) throw new TerminalError("invalid-cursor", 400);
145
+ context.signal.throwIfAborted();
146
+ const id = randomUUID();
147
+ const observer = {
148
+ id,
149
+ context,
150
+ cursor,
151
+ acknowledged: cursor,
152
+ sent: /* @__PURE__ */ new Map(),
153
+ bytes: 0,
154
+ pumping: false,
155
+ detached: false,
156
+ abort: () => {
157
+ detach(observer);
158
+ }
159
+ };
160
+ observers.set(id, observer);
161
+ attachments.change(1);
162
+ context.signal.addEventListener("abort", observer.abort, { once: true });
163
+ if (params.desiredInput && summary.inputOwner === null) {
164
+ summary.inputOwner = id;
165
+ epoch++;
166
+ writer();
167
+ }
168
+ const ready = {
169
+ terminal: structuredClone(summary),
170
+ subscriptionId: id,
171
+ writer: summary.inputOwner === id,
172
+ leaseEpoch: epoch,
173
+ firstCursor: first(),
174
+ lastCursor: summary.cursor,
175
+ truncated: cursor < first() - 1 || Boolean(summary.truncated)
176
+ };
177
+ pump(observer);
178
+ return {
179
+ ready,
180
+ async input(input) {
181
+ if (observer.detached || ended) throw new TerminalError("attachment-closed");
182
+ if (input.kind === "ack") {
183
+ if (input.cursor < observer.acknowledged || input.cursor > observer.cursor) throw new TerminalError("invalid-ack", 400);
184
+ observer.acknowledged = input.cursor;
185
+ for (const [cursor, bytes] of observer.sent) if (cursor <= input.cursor) {
186
+ observer.sent.delete(cursor);
187
+ observer.bytes -= bytes;
188
+ }
189
+ if (observer.bytes < LOW && observer.deadline !== void 0) {
190
+ clearTimeout(observer.deadline);
191
+ observer.deadline = void 0;
192
+ }
193
+ pressure();
194
+ pump(observer);
195
+ return;
196
+ }
197
+ if (summary.status !== "running") throw new TerminalError("terminal-not-running");
198
+ if (input.kind === "takeover") {
199
+ summary.inputOwner = id;
200
+ epoch++;
201
+ writer();
202
+ return;
203
+ }
204
+ if (summary.inputOwner !== id || input.leaseEpoch !== epoch) throw new TerminalError("input-ownership");
205
+ if (input.kind === "write") handle.input(input.text);
206
+ else {
207
+ handle.resize(input.cols, input.rows);
208
+ summary.cols = input.cols;
209
+ summary.rows = input.rows;
210
+ for (const value of observers.values()) send(value, {
211
+ kind: "status",
212
+ terminal: structuredClone(summary)
213
+ });
214
+ }
215
+ },
216
+ /** Removes this observation only; the physical process remains owned by the directory. */
217
+ async close() {
218
+ detach(observer);
219
+ }
220
+ };
221
+ },
222
+ /** Publishes current status to attached consumers without adding replay history. */
223
+ status() {
224
+ for (const observer of observers.values()) send(observer, {
225
+ kind: "status",
226
+ terminal: structuredClone(summary)
227
+ });
228
+ },
229
+ /** Releases replay bytes and attachments after physical process-group cleanup is confirmed. */
230
+ end() {
231
+ ended = true;
232
+ unwatch();
233
+ summary.truncated ||= [...observers.values()].some((value) => value.cursor < summary.cursor || value.bytes > 0);
234
+ chunks.length = 0;
235
+ retained = 0;
236
+ for (const observer of [...observers.values()]) {
237
+ detach(observer);
238
+ observer.context.send({
239
+ kind: "status",
240
+ terminal: structuredClone(summary)
241
+ }).catch(() => {}).finally(() => observer.context.close());
242
+ }
243
+ }
244
+ };
245
+ }
246
+ //#endregion
247
+ //#region src/path-semantics.ts
248
+ /** Host path syntax only; resolved object identity remains the platform's responsibility. */
249
+ /** Requires an independent absolute root, excluding Windows drive-relative and root-relative forms. */
250
+ function isFullAbsolute(value, paths = nodePath) {
251
+ if (value.includes("\0") || !paths.isAbsolute(value)) return false;
252
+ if (paths.sep !== "\\") return true;
253
+ if (/^[A-Za-z]:[\\/]/.test(value)) return true;
254
+ const unc = /^[\\/]{2}([^\\/]+)[\\/]([^\\/]+)(?:[\\/]|$)/.exec(value);
255
+ const server = unc?.[1];
256
+ const share = unc?.[2];
257
+ return server !== void 0 && share !== void 0 && ![
258
+ ".",
259
+ "..",
260
+ "?"
261
+ ].includes(server) && ![".", ".."].includes(share);
262
+ }
263
+ /** Compares canonical ancestor segments exactly; drive-letter syntax alone is case-insensitive. */
264
+ function containsHostPath(root, value, paths = nodePath) {
265
+ if (!isFullAbsolute(root, paths) || !isFullAbsolute(value, paths)) return false;
266
+ const parts = (path) => {
267
+ const normalized = paths.normalize(path);
268
+ const { root } = paths.parse(normalized);
269
+ return {
270
+ root: paths.sep === "\\" && /^[A-Za-z]:\\$/.test(root) ? root.toUpperCase() : root,
271
+ segments: normalized.slice(root.length).split(paths.sep).filter(Boolean)
272
+ };
273
+ };
274
+ const parent = parts(root);
275
+ const child = parts(value);
276
+ return parent.root === child.root && parent.segments.length <= child.segments.length && parent.segments.every((segment, index) => segment === child.segments[index]);
277
+ }
278
+ //#endregion
279
+ //#region src/provider.ts
280
+ /** A bounded business failure without terminal output or raw environment details. */
281
+ var TerminalError = class extends Error {
282
+ /** Stable safe failure category exposed to the client. */
283
+ code;
284
+ /** Generic HTTP-like status used by the host client IO error mapping. */
285
+ status;
286
+ /** Defaults ordinary business conflicts to status 409. */
287
+ constructor(code, status = 409) {
288
+ super(code);
289
+ this.name = "TerminalError";
290
+ this.code = code;
291
+ this.status = status;
292
+ }
293
+ };
294
+ /** Constructs the owner-held terminal directory and bounded operation facts. */
295
+ function createWebShell(options) {
296
+ const identity = options.roots.availability();
297
+ if (!identity.available) throw new TerminalError("unavailable", 503);
298
+ const terminals = /* @__PURE__ */ new Map();
299
+ const operations = /* @__PURE__ */ new Map();
300
+ const titleNumbers = /* @__PURE__ */ new Map();
301
+ let stopped = false;
302
+ let pendingCreates = 0;
303
+ let pendingRecords = 0;
304
+ let attachmentCount = 0;
305
+ const pendingByWorkspace = /* @__PURE__ */ new Map();
306
+ const current = () => {
307
+ if (stopped || options.signal.aborted) throw new TerminalError("unavailable", 503);
308
+ };
309
+ const notify = (workspaceId) => {
310
+ try {
311
+ options.changed?.({
312
+ instanceId: identity.instanceId,
313
+ workspaceId
314
+ });
315
+ } catch {}
316
+ };
317
+ const sweep = () => {
318
+ const now = Date.now();
319
+ for (const [id, entry] of operations) if (entry.settledAt !== void 0 && now - entry.settledAt >= 6e5) operations.delete(id);
320
+ };
321
+ const operation = (id, key, work) => {
322
+ current();
323
+ sweep();
324
+ const prior = operations.get(id);
325
+ if (prior) {
326
+ if (prior.key !== key) throw new TerminalError("operation-conflict");
327
+ return prior.promise;
328
+ }
329
+ if (operations.size >= 1e3) {
330
+ const oldest = [...operations].filter(([, entry]) => entry.settledAt !== void 0).sort((a, b) => a[1].settledAt - b[1].settledAt)[0];
331
+ if (oldest) operations.delete(oldest[0]);
332
+ else throw new TerminalError("capacity");
333
+ }
334
+ const result = {
335
+ operationId: id,
336
+ instanceId: identity.instanceId,
337
+ status: "pending"
338
+ };
339
+ const entry = {
340
+ key,
341
+ result,
342
+ promise: Promise.resolve(result)
343
+ };
344
+ operations.set(id, entry);
345
+ entry.promise = Promise.resolve().then(work).then((terminal) => ({
346
+ ...result,
347
+ status: "succeeded",
348
+ terminal: structuredClone(terminal)
349
+ }), (error) => ({
350
+ ...result,
351
+ status: "failed",
352
+ error: {
353
+ code: error instanceof TerminalError ? error.code : "terminal-failed",
354
+ message: error instanceof TerminalError ? error.code : "Terminal operation failed"
355
+ }
356
+ })).then((value) => {
357
+ entry.result = value;
358
+ entry.settledAt = Date.now();
359
+ return value;
360
+ });
361
+ return entry.promise;
362
+ };
363
+ const reserve = (workspaceId, newRecord = false) => {
364
+ current();
365
+ const live = [...terminals.values()].filter((value) => value.summary.status !== "ended");
366
+ if (newRecord && terminals.size + pendingRecords >= 48 || live.length + pendingCreates >= 16 || live.filter((value) => value.summary.workspaceId === workspaceId).length + (pendingByWorkspace.get(workspaceId) ?? 0) >= 8) throw new TerminalError("capacity");
367
+ pendingCreates++;
368
+ if (newRecord) pendingRecords++;
369
+ pendingByWorkspace.set(workspaceId, (pendingByWorkspace.get(workspaceId) ?? 0) + 1);
370
+ };
371
+ const release = (workspaceId, newRecord = false) => {
372
+ pendingCreates--;
373
+ if (newRecord) pendingRecords--;
374
+ pendingByWorkspace.set(workspaceId, (pendingByWorkspace.get(workspaceId) ?? 1) - 1);
375
+ if (pendingByWorkspace.get(workspaceId) === 0) pendingByWorkspace.delete(workspaceId);
376
+ };
377
+ const spawn = async (params, track, expectedCwd) => {
378
+ const snapshot = await options.roots.read(params.workspaceId);
379
+ const root = snapshot.roots.find((value) => params.rootId === void 0 ? value.kind === "own" : value.id === params.rootId);
380
+ if (!root) throw new TerminalError("root-unavailable", 404);
381
+ const anchor = await options.files.anchor(root.path, {
382
+ sealedDirectories: snapshot.sealedDirectories,
383
+ signal: snapshot.signal
384
+ });
385
+ let directory = anchor;
386
+ let handle;
387
+ const errors = [];
388
+ try {
389
+ if (params.path) directory = await anchor.openDirectory(params.path.split("/"));
390
+ if (expectedCwd !== void 0 && directory.path !== expectedCwd) throw new TerminalError("cwd-unavailable", 400);
391
+ await snapshot.assertCurrent();
392
+ current();
393
+ handle = await options.pty.spawn({
394
+ file: options.shell,
395
+ args: options.shellArgs,
396
+ cwd: directory.path,
397
+ cols: params.cols,
398
+ rows: params.rows
399
+ });
400
+ track(handle);
401
+ const within = (parent, path) => containsHostPath(parent, path, options.paths ?? nodePath);
402
+ await snapshot.assertCurrent();
403
+ if (expectedCwd !== void 0 && handle.cwd !== expectedCwd || !within(root.path, handle.cwd) || snapshot.sealedDirectories.some((path) => within(path, handle.cwd))) throw new TerminalError("cwd-unavailable", 400);
404
+ } catch (error) {
405
+ errors.push(error);
406
+ } finally {
407
+ const results = await Promise.allSettled([directory !== anchor ? directory.close() : Promise.resolve(), anchor.close()]);
408
+ errors.push(...results.filter((value) => value.status === "rejected").map((value) => value.reason));
409
+ }
410
+ if (errors.length === 1) throw errors[0];
411
+ if (errors.length) throw new AggregateError(errors, "Initial directory creation/release failed");
412
+ if (!handle) throw new TerminalError("cwd-unavailable", 400);
413
+ current();
414
+ return {
415
+ handle,
416
+ initial: {
417
+ rootId: root.id,
418
+ path: params.path ?? ""
419
+ }
420
+ };
421
+ };
422
+ const rememberCleanup = (terminal, warnings) => {
423
+ terminal.cleanupWarnings = [.../* @__PURE__ */ new Set([...terminal.cleanupWarnings, ...warnings])].slice(-32);
424
+ terminal.summary.cleanupWarnings = [...terminal.cleanupWarnings];
425
+ };
426
+ const finish = (terminal) => {
427
+ if (terminal.summary.status === "ended") return Promise.resolve();
428
+ if (terminal.closing) return terminal.closing;
429
+ terminal.summary.status = "closing";
430
+ terminal.summary.inputOwner = null;
431
+ terminal.flow?.status();
432
+ terminal.closing = (async () => {
433
+ try {
434
+ const cleanup = await terminal.handle.closeTree();
435
+ terminal.summary.status = "ended";
436
+ rememberCleanup(terminal, cleanup.warnings);
437
+ terminal.flow?.end();
438
+ terminal.flow = void 0;
439
+ for (const stop of terminal.unwatch.splice(0)) stop();
440
+ terminal.handle = void 0;
441
+ sweep();
442
+ } catch (error) {
443
+ terminal.summary.status = "close-failed";
444
+ terminal.summary.cleanupWarnings = [...terminal.cleanupWarnings, "PTY/original process group cleanup failed; retry is required"].slice(-32);
445
+ terminal.flow?.status();
446
+ throw error;
447
+ }
448
+ })().finally(() => {
449
+ terminal.closing = void 0;
450
+ });
451
+ return terminal.closing;
452
+ };
453
+ const bind = (terminal, handle) => {
454
+ terminal.handle = handle;
455
+ terminal.flow = createTerminalOutput(handle, terminal.summary, {
456
+ count: () => attachmentCount,
457
+ change: (delta) => {
458
+ attachmentCount += delta;
459
+ }
460
+ });
461
+ terminal.unwatch.push(handle.onExit((exit) => {
462
+ if (terminal.handle !== handle) return;
463
+ terminal.summary.exitCode = exit.exitCode;
464
+ finish(terminal).catch(() => {});
465
+ }));
466
+ };
467
+ return {
468
+ /** Returns current independent workspace roots and physical availability. */
469
+ async roots(workspaceId) {
470
+ current();
471
+ const snapshot = await options.roots.read(workspaceId);
472
+ const capability = options.pty.availability();
473
+ const files = options.files.availability();
474
+ return {
475
+ gatewayId: identity.gatewayId,
476
+ instanceId: identity.instanceId,
477
+ roots: [...snapshot.roots],
478
+ available: capability.available && files.available,
479
+ ...!capability.available ? { reason: capability.reason } : !files.available ? { reason: files.reason } : {}
480
+ };
481
+ },
482
+ /** Returns bounded summaries without creating or attaching a terminal. */
483
+ list(workspaceId) {
484
+ current();
485
+ sweep();
486
+ return {
487
+ gatewayId: identity.gatewayId,
488
+ instanceId: identity.instanceId,
489
+ terminals: [...terminals.values()].filter((value) => value.summary.workspaceId === workspaceId).map((value) => structuredClone(value.summary))
490
+ };
491
+ },
492
+ /** Admits once per retained operation ID; connection cancellation does not cancel creation. */
493
+ create(input) {
494
+ const params = CreateParams.parse(input);
495
+ return operation(params.operationId, JSON.stringify(["create", params]), async () => {
496
+ reserve(params.workspaceId, true);
497
+ let handle;
498
+ try {
499
+ const created = await spawn(params, (value) => {
500
+ handle = value;
501
+ });
502
+ const defaultTitleNumber = (titleNumbers.get(params.workspaceId) ?? 0) + 1;
503
+ titleNumbers.set(params.workspaceId, defaultTitleNumber);
504
+ const terminal = {
505
+ summary: {
506
+ id: randomUUID(),
507
+ runId: randomUUID(),
508
+ creationOperationId: params.operationId,
509
+ title: `Terminal ${defaultTitleNumber}`,
510
+ defaultTitleNumber,
511
+ workspaceId: params.workspaceId,
512
+ instanceId: identity.instanceId,
513
+ cwd: created.handle.cwd,
514
+ status: "running",
515
+ hostAccount: options.hostAccount,
516
+ inputOwner: null,
517
+ cols: params.cols,
518
+ rows: params.rows,
519
+ cursor: 0,
520
+ cleanupScope: created.handle.cleanupScope
521
+ },
522
+ initial: created.initial,
523
+ cleanupWarnings: [],
524
+ handle: created.handle,
525
+ unwatch: []
526
+ };
527
+ terminals.set(terminal.summary.id, terminal);
528
+ bind(terminal, created.handle);
529
+ notify(params.workspaceId);
530
+ return terminal.summary;
531
+ } catch (error) {
532
+ if (handle) await handle.closeTree();
533
+ throw error;
534
+ } finally {
535
+ release(params.workspaceId, true);
536
+ }
537
+ });
538
+ },
539
+ /** Restarts once per operation ID after cleanup; preserves record/cursor and assigns a new runId. */
540
+ restart(input) {
541
+ const params = RestartParams.parse(input);
542
+ return operation(params.operationId, JSON.stringify(["restart", params]), async () => {
543
+ if (params.instanceId !== identity.instanceId) throw new TerminalError("context-mismatch");
544
+ const terminal = terminals.get(params.terminalId);
545
+ if (!terminal || terminal.summary.workspaceId !== params.workspaceId) throw new TerminalError("terminal-missing", 404);
546
+ if (terminal.restarting) throw new TerminalError("restart-in-progress");
547
+ if (terminal.summary.status !== "ended" || terminal.handle || terminal.closing) throw new TerminalError("terminal-not-ended");
548
+ reserve(params.workspaceId);
549
+ terminal.restarting = true;
550
+ const previous = {
551
+ cols: terminal.summary.cols,
552
+ rows: terminal.summary.rows,
553
+ exitCode: terminal.summary.exitCode,
554
+ runId: terminal.summary.runId
555
+ };
556
+ let handle;
557
+ try {
558
+ const cols = params.cols ?? terminal.summary.cols;
559
+ const rows = params.rows ?? terminal.summary.rows;
560
+ const started = await spawn({
561
+ workspaceId: params.workspaceId,
562
+ ...terminal.initial,
563
+ cols,
564
+ rows
565
+ }, (value) => {
566
+ handle = value;
567
+ }, terminal.summary.cwd);
568
+ terminal.summary = {
569
+ ...terminal.summary,
570
+ status: "running",
571
+ runId: randomUUID(),
572
+ inputOwner: null,
573
+ cols,
574
+ rows
575
+ };
576
+ delete terminal.summary.exitCode;
577
+ delete terminal.summary.truncated;
578
+ bind(terminal, started.handle);
579
+ notify(params.workspaceId);
580
+ return terminal.summary;
581
+ } catch (error) {
582
+ if (handle) {
583
+ terminal.summary.status = "closing";
584
+ terminal.summary.inputOwner = null;
585
+ terminal.flow?.status();
586
+ try {
587
+ const cleanup = await handle.closeTree();
588
+ rememberCleanup(terminal, cleanup.warnings);
589
+ } catch {
590
+ terminal.handle = handle;
591
+ terminal.summary.status = "close-failed";
592
+ terminal.summary.cleanupWarnings = [...terminal.cleanupWarnings, "Restart PTY cleanup failed; close the terminal before restarting again."].slice(-32);
593
+ notify(params.workspaceId);
594
+ throw new TerminalError("restart-cleanup-failed");
595
+ }
596
+ terminal.summary.status = "ended";
597
+ terminal.summary.runId = previous.runId;
598
+ terminal.summary.cols = previous.cols;
599
+ terminal.summary.rows = previous.rows;
600
+ if (previous.exitCode === void 0) delete terminal.summary.exitCode;
601
+ else terminal.summary.exitCode = previous.exitCode;
602
+ terminal.summary.cleanupWarnings = [...terminal.cleanupWarnings];
603
+ terminal.flow?.end();
604
+ terminal.flow = void 0;
605
+ for (const stop of terminal.unwatch.splice(0)) stop();
606
+ terminal.handle = void 0;
607
+ }
608
+ throw error;
609
+ } finally {
610
+ terminal.restarting = false;
611
+ release(params.workspaceId);
612
+ }
613
+ });
614
+ },
615
+ /** Trims one shared title without affecting its process, output or input ownership. */
616
+ rename(input) {
617
+ current();
618
+ const params = RenameParams.parse(input);
619
+ if (params.instanceId !== identity.instanceId) throw new TerminalError("context-mismatch");
620
+ const terminal = terminals.get(params.terminalId);
621
+ if (!terminal || terminal.summary.workspaceId !== params.workspaceId) throw new TerminalError("terminal-missing", 404);
622
+ terminal.summary.title = params.title;
623
+ delete terminal.summary.defaultTitleNumber;
624
+ terminal.flow?.status();
625
+ notify(params.workspaceId);
626
+ return structuredClone(terminal.summary);
627
+ },
628
+ /** Attaches one bounded observer; closing it leaves the terminal alive. */
629
+ open(input, context) {
630
+ current();
631
+ if (input.instanceId !== identity.instanceId) throw new TerminalError("context-mismatch");
632
+ const terminal = terminals.get(input.terminalId);
633
+ if (!terminal || terminal.summary.workspaceId !== input.workspaceId) throw new TerminalError("terminal-missing", 404);
634
+ if (!terminal.flow) throw new TerminalError("terminal-ended");
635
+ return terminal.flow.open(input, context);
636
+ },
637
+ /** Removes a terminal after confirmed PTY/group cleanup, retaining operation facts and failures. */
638
+ closeTerminal(raw) {
639
+ const input = CloseParams.parse(raw);
640
+ return operation(input.operationId, JSON.stringify(["close", input]), async () => {
641
+ if (input.instanceId !== identity.instanceId) throw new TerminalError("context-mismatch");
642
+ const terminal = terminals.get(input.terminalId);
643
+ if (!terminal || terminal.summary.workspaceId !== input.workspaceId) throw new TerminalError("terminal-missing", 404);
644
+ if (terminal.restarting) throw new TerminalError("restart-in-progress");
645
+ if (input.endedRunId !== void 0) {
646
+ if (terminal.summary.status !== "ended" || terminal.summary.runId !== input.endedRunId) throw new TerminalError("terminal-run-changed");
647
+ terminals.delete(terminal.summary.id);
648
+ notify(input.workspaceId);
649
+ return terminal.summary;
650
+ }
651
+ await finish(terminal);
652
+ terminals.delete(terminal.summary.id);
653
+ notify(input.workspaceId);
654
+ return terminal.summary;
655
+ });
656
+ },
657
+ /** Queries retained execution facts; unknown never replays an operation. */
658
+ operationStatus(input) {
659
+ current();
660
+ sweep();
661
+ return input.instanceId === identity.instanceId ? structuredClone(operations.get(input.operationId)?.result ?? {
662
+ operationId: input.operationId,
663
+ instanceId: identity.instanceId,
664
+ status: "unknown"
665
+ }) : {
666
+ operationId: input.operationId,
667
+ instanceId: identity.instanceId,
668
+ status: "unknown"
669
+ };
670
+ },
671
+ /** Stops admission and awaits all late creations and owned physical cleanup. */
672
+ async close() {
673
+ stopped = true;
674
+ await Promise.allSettled([...operations.values()].map((value) => value.promise));
675
+ const failed = (await Promise.allSettled([...terminals.values()].filter((value) => value.summary.status !== "ended").map(finish))).filter((value) => value.status === "rejected");
676
+ const adapters = await Promise.allSettled([options.pty.close(), options.files.close()]);
677
+ failed.push(...adapters.filter((value) => value.status === "rejected"));
678
+ if (failed.length) throw new AggregateError(failed.map((value) => value.reason), "Terminal cleanup failed");
679
+ }
680
+ };
681
+ }
682
+ //#endregion
683
+ //#region src/index.ts
684
+ /** Sessionless host-account terminals; registration exposes no Agent tools or approvals. */
685
+ /** Registers one activation's terminal directory and awaited shutdown drain. */
686
+ function registerWebShell(ctx) {
687
+ let account;
688
+ try {
689
+ account = userInfo().username;
690
+ } catch {
691
+ account = process.getuid ? `uid ${process.getuid()}` : "Gateway OS account";
692
+ }
693
+ const changed = ctx.client.registerFrame({
694
+ name: "changed",
695
+ delivery: "broadcast",
696
+ payload: Changed
697
+ });
698
+ const pty = ctx.services.get("pty");
699
+ const shell = pty.defaultShell();
700
+ const provider = createWebShell({
701
+ pty,
702
+ files: ctx.services.get("client-files"),
703
+ roots: ctx.services.get("workspace-roots"),
704
+ signal: ctx.signal,
705
+ shell: shell.file,
706
+ shellArgs: shell.args,
707
+ hostAccount: account,
708
+ changed: (value) => changed.emit(value)
709
+ });
710
+ let withdrawn = false;
711
+ let unbind = () => {};
712
+ const drain = async () => {
713
+ await provider.close();
714
+ if (withdrawn) {
715
+ unbind();
716
+ unbind = () => {};
717
+ }
718
+ };
719
+ const withdraw = () => {
720
+ drain().catch(() => {});
721
+ };
722
+ ctx.signal.addEventListener("abort", withdraw, { once: true });
723
+ unbind = ctx.services.get("work-lifecycle").register(drain);
724
+ ctx.onDispose(async () => {
725
+ withdrawn = true;
726
+ ctx.signal.removeEventListener("abort", withdraw);
727
+ await drain();
728
+ });
729
+ ctx.client.registerMethod({
730
+ name: "roots",
731
+ params: z.object({ workspaceId: WorkspaceId }).strict(),
732
+ result: RootsResult,
733
+ handle: (params) => provider.roots(params.workspaceId)
734
+ });
735
+ ctx.client.registerMethod({
736
+ name: "list",
737
+ params: z.object({ workspaceId: WorkspaceId }).strict(),
738
+ result: ListResult,
739
+ handle: (params) => provider.list(params.workspaceId)
740
+ });
741
+ ctx.client.registerMethod({
742
+ name: "create",
743
+ params: CreateParams,
744
+ result: OperationResult,
745
+ handle: (params) => provider.create(params)
746
+ });
747
+ ctx.client.registerMethod({
748
+ name: "restart",
749
+ params: RestartParams,
750
+ result: OperationResult,
751
+ handle: (params) => provider.restart(params)
752
+ });
753
+ ctx.client.registerMethod({
754
+ name: "rename",
755
+ params: RenameParams,
756
+ result: TerminalSummary,
757
+ handle: (params) => provider.rename(params)
758
+ });
759
+ ctx.client.registerMethod({
760
+ name: "close",
761
+ params: CloseParams,
762
+ result: OperationResult,
763
+ handle: (params) => provider.closeTerminal(params)
764
+ });
765
+ ctx.client.registerMethod({
766
+ name: "operationStatus",
767
+ params: OperationStatusParams,
768
+ result: OperationResult,
769
+ handle: (params) => provider.operationStatus(params)
770
+ });
771
+ ctx.client.registerStream({
772
+ name: "terminal",
773
+ openParams: TerminalOpen,
774
+ ready: TerminalReady,
775
+ input: TerminalInput,
776
+ output: TerminalOutput,
777
+ open: (params, pipe) => provider.open(params, pipe)
778
+ });
779
+ const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
780
+ if (existsSync(module)) ctx.client.registerUi({ module });
781
+ }
782
+ const plugin = {
783
+ name: "@eum-agent/web-shell",
784
+ requires: [
785
+ "pty",
786
+ "client-files",
787
+ "workspace-roots",
788
+ "work-lifecycle"
789
+ ],
790
+ apply: registerWebShell
791
+ };
792
+ //#endregion
793
+ export { plugin as default, registerWebShell };