@noldova/terminal 0.0.10 → 0.0.12

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.
@@ -8,7 +8,7 @@
8
8
  import "@noldova/context.core";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { ArgumentException } from "@noldova/context.exceptions";
11
- import { EndedBy, Resources as ProtocolResources, TerminalAckParams, TerminalCommandAdded, TerminalCommandEnded, TerminalCompleteParams, TerminalCompletion, TerminalExit, TerminalExited, TerminalFindCommandsParams, TerminalInputParams, TerminalLaunched, TerminalLaunchParams, TerminalLinesParams, TerminalName, TerminalNames, TerminalOpenParams, TerminalOwnerReference, TerminalPaneReference, TerminalReference, TerminalResizeParams, TerminalRestartParams, TerminalRestoreParams, TerminalRunBusy, TerminalRunEnded, TerminalRunEndedBy, TerminalRunOutcome, TerminalRunOutputParams, TerminalRunParams, TerminalRunResult, TerminalSessions, TerminalShellKind, TerminalShells, TerminalShowOwnerParams, TerminalSize, TerminalVisibilityParams, TerminalWriteParams, WindowsPty } from "@noldova/terminal.protocol";
11
+ import { EndedBy, Resources as ProtocolResources, TerminalAckParams, TerminalChangeFolderParams, TerminalCommandAdded, TerminalCommandEnded, TerminalCompleteParams, TerminalCompletion, TerminalDescribeParams, TerminalExit, TerminalExited, TerminalFindCommandsParams, TerminalFolderChanged, TerminalInputParams, TerminalLaunched, TerminalLaunchParams, TerminalLinesParams, TerminalName, TerminalNames, TerminalOpenParams, TerminalOwnerReference, TerminalPaneReference, TerminalReference, TerminalResizeParams, TerminalRestartParams, TerminalRestoreParams, TerminalRunBusy, TerminalRunEnded, TerminalRunEndedBy, TerminalRunOutcome, TerminalRunOutputParams, TerminalRunParams, TerminalRunResult, TerminalSessions, TerminalShellKind, TerminalShells, TerminalShowOwnerParams, TerminalSize, TerminalVisibilityParams, TerminalWriteParams, WindowsPty } from "@noldova/terminal.protocol";
12
12
  import { AgentTerminalRestartException } from "../exceptions/agent-terminal-restart.exception.js";
13
13
  import { SystemRequirement } from "../enums/system-requirement.js";
14
14
  import { ConnectionClosingException } from "../exceptions/connection-closing.exception.js";
@@ -31,6 +31,7 @@ import { Resources } from "../resources.js";
31
31
  import { CommandHistory } from "./command-history.js";
32
32
  import { DeferredPtyProcess } from "./deferred-pty-process.js";
33
33
  import { FailureText } from "./failure-text.js";
34
+ import { FolderChangeLine } from "./folder-change-line.js";
34
35
  import { SystemRequirements } from "./system-requirements.js";
35
36
  import { TerminalAudience } from "./terminal-audience.js";
36
37
  import { TerminalSession } from "./terminal-session.js";
@@ -47,6 +48,7 @@ export class TerminalHost {
47
48
  events;
48
49
  saved;
49
50
  completions;
51
+ describer;
50
52
  folderKeys = new WeakMap();
51
53
  realFolderReads = new Map();
52
54
  sessions = new Map();
@@ -62,7 +64,7 @@ export class TerminalHost {
62
64
  appCloses = new Set();
63
65
  closings = new Map();
64
66
  closingConnections = new Set();
65
- constructor(spawner, fileSystem, integration, historyFolder, locator, platform, osRelease, environment, homeFolder, log, events, saved, completions) {
67
+ constructor(spawner, fileSystem, integration, historyFolder, locator, platform, osRelease, environment, homeFolder, log, events, saved, completions, describer) {
66
68
  this.spawner = spawner;
67
69
  this.fileSystem = fileSystem;
68
70
  this.integration = integration;
@@ -81,6 +83,7 @@ export class TerminalHost {
81
83
  this.events = events;
82
84
  this.saved = saved;
83
85
  this.completions = completions;
86
+ this.describer = describer;
84
87
  }
85
88
  async handleAsync(method, payload, client) {
86
89
  this.audience.see(client);
@@ -106,6 +109,8 @@ export class TerminalHost {
106
109
  case TerminalNames.writeMethod:
107
110
  await this.writeAsync(TerminalWriteParams.fromJson(payload), client);
108
111
  return null;
112
+ case TerminalNames.changeFolderMethod:
113
+ return (await this.changeFolderAsync(TerminalChangeFolderParams.fromJson(payload), client)).toJson();
109
114
  case TerminalNames.resizeMethod:
110
115
  this.resize(TerminalResizeParams.fromJson(payload), client);
111
116
  return null;
@@ -141,6 +146,8 @@ export class TerminalHost {
141
146
  return (await this.completeAsync(TerminalCompleteParams.fromJson(payload), client)).toJson();
142
147
  case TerminalNames.findCommandsMethod:
143
148
  return (await this.findCommandsAsync(TerminalFindCommandsParams.fromJson(payload), client)).toJson();
149
+ case TerminalNames.describeMethod:
150
+ return (await this.describeAsync(TerminalDescribeParams.fromJson(payload), client)).toJson();
144
151
  case TerminalNames.windowStartedMethod:
145
152
  if (!Object.isNull(client.window)) {
146
153
  this.detachLeftPanes(t => t.connection === client.connection && t.window === client.window && t.page !== client.page);
@@ -312,6 +319,7 @@ export class TerminalHost {
312
319
  this.addCommand(shell.id, t.command);
313
320
  },
314
321
  onOutputStarted: t => publish(this.events.outputStarted, t.toJson()),
322
+ onOutputPrinted: t => publish(this.events.outputPrinted, t.toJson()),
315
323
  onScreenChanged: t => publish(this.events.screenChanged, t.toJson()),
316
324
  onDetached: t => publish(this.events.detached, t.toJson()),
317
325
  onFailed: (id, message) => this.log.write(Resources.formatStartedCommandUnread(id, message)),
@@ -417,9 +425,9 @@ export class TerminalHost {
417
425
  if (t !== TerminalRunOutcome.Typed || !terminal.session.commands.hasMarks || Object.isNull(terminal.session.commands.promptEndOffset) || terminal.keyCount !== 0)
418
426
  this.endLaunchCommand(terminal, null);
419
427
  }).catch((error) => this.log.write(Resources.formatLaunchCommandFailed(terminal.session.sessionId, FailureText.read(error))));
420
- return new TerminalLaunched(terminal.session.sessionId, null);
428
+ return new TerminalLaunched(terminal.session.sessionId, null, terminal.shell.kind, terminal.session.hasIntegration);
421
429
  }
422
- async typeCommandAsync(terminal, command, isPaste = false, waitsForFit = false) {
430
+ async typeCommandAsync(terminal, command, isPaste = false, waitsForFit = false, readRefusal = () => null, folderKeys = null) {
423
431
  const session = terminal.session;
424
432
  const typed = isPaste ? command.replace(Resources.leadingBlankLines, "") : command;
425
433
  const pending = new AbortController();
@@ -451,8 +459,10 @@ export class TerminalHost {
451
459
  const outcome = isEnded() ? TerminalRunOutcome.Ended
452
460
  : isPaste && ((waitsForFit ? terminal.keyCount !== keyCount : terminal.inputCount !== inputCount) || !Object.isNull(session.commands.promptEndOffset) && session.readPromptLine() !== "") ? TerminalRunOutcome.Input
453
461
  : isPaste && !isBracketed && typed.includes(Resources.tabKey) ? TerminalRunOutcome.Tab
454
- : TerminalRunOutcome.Typed;
455
- if (outcome === TerminalRunOutcome.Typed) {
462
+ : readRefusal() ?? TerminalRunOutcome.Typed;
463
+ if (outcome === TerminalRunOutcome.Typed && !Object.isNull(folderKeys))
464
+ session.sendFolder(folderKeys, command);
465
+ else if (outcome === TerminalRunOutcome.Typed) {
456
466
  const text = isPaste ? TerminalHost.toPaste(typed, isBracketed) : `${command}${Resources.enterKey}`;
457
467
  terminal.typedEnds = isBracketed || !isPaste ? 1 : text.split(Resources.enterKey).length - 1;
458
468
  terminal.paste = isBracketed ? typed.replace(Resources.whitespace, "") : "";
@@ -858,7 +868,7 @@ export class TerminalHost {
858
868
  async completeAsync(params, client) {
859
869
  const terminal = this.findHosted(params.sessionId, client);
860
870
  const keys = params.asksShell && this.completions.followsCommand(terminal.shell.kind, params.line, params.cursor)
861
- ? Resources.optionsKeys.get(terminal.shell.kind) : undefined;
871
+ ? this.completions.adapterOf(terminal.shell.kind)?.optionsKeys ?? undefined : undefined;
862
872
  const [completion, reply] = await Promise.all([
863
873
  this.completions.completeAsync(params.sessionId, terminal.shell.kind, params.line, params.cursor, terminal.session.cwd ?? terminal.folder, this.readCompletionEnvironment(terminal), terminal.session.shellNames, terminal.session.shellBuiltins),
864
874
  Object.isUndefined(keys) ? Promise.resolve(ShellOptionsReply.none) : terminal.session.askOptionsAsync(keys)
@@ -873,10 +883,14 @@ export class TerminalHost {
873
883
  const shellNames = terminal.session.isShellPathReset || terminal.session.isShellModulePathReset ? null
874
884
  : terminal.session.shellNames;
875
885
  const environment = this.readCompletionEnvironment(terminal);
876
- return terminal.shell.kind === TerminalShellKind.PowerShell
886
+ return this.completions.adapterOf(terminal.shell.kind)?.looksUpMissing === true
877
887
  ? this.completions.findMissingPowerShellAsync(terminal.session.commands, terminal.shell.file, params.names, shellNames, environment)
878
888
  : this.completions.findMissingAsync(params.sessionId, terminal.session.commands, terminal.session.prompts, terminal.shell.kind, terminal.session.cwd ?? terminal.folder, params.names, shellNames, environment);
879
889
  }
890
+ async describeAsync(params, client) {
891
+ const terminal = this.findHosted(params.sessionId, client);
892
+ return await this.describer.describeAsync(terminal.shell.kind, terminal.shell.file, params.names, this.readCompletionEnvironment(terminal));
893
+ }
880
894
  readCompletionEnvironment(terminal) {
881
895
  const replaced = {};
882
896
  if (!Object.isNull(terminal.session.shellPath))
@@ -994,6 +1008,45 @@ export class TerminalHost {
994
1008
  terminal.recordInput(false, written, true);
995
1009
  session.write(written);
996
1010
  }
1011
+ async changeFolderAsync(params, client) {
1012
+ const terminal = this.findHosted(params.sessionId, client);
1013
+ const session = terminal.session;
1014
+ const line = FolderChangeLine.format(terminal.shell.kind, params.folder);
1015
+ if (Object.isNull(line) || !session.hasIntegration)
1016
+ return new TerminalFolderChanged(null, false);
1017
+ if (!this.isAbsolute(params.folder))
1018
+ throw new ArgumentException(ProtocolResources.formatNotAbsolutePath(ProtocolResources.valueSubject), Resources.folderParameter);
1019
+ if (!await this.fileSystem.isFolderAsync(params.folder))
1020
+ return new TerminalFolderChanged(null, true);
1021
+ if (!Object.isNull(terminal.pendingCommand) || !Object.isNull(session.commands.runningCommand))
1022
+ return new TerminalFolderChanged(null, true, TerminalRunOutcome.Busy);
1023
+ const folderKeys = session.commands.hasFolderBinding ? this.completions.adapterOf(terminal.shell.kind)?.folderKeys ?? null : null;
1024
+ const before = session.cwd;
1025
+ const outcome = await this.typeCommandAsync(terminal, Object.isNull(folderKeys) ? line : params.folder, false, false, () => TerminalHost.readMoveRefusal(terminal), folderKeys);
1026
+ if (outcome === TerminalRunOutcome.NoShell)
1027
+ return new TerminalFolderChanged(null, false);
1028
+ if (outcome === TerminalRunOutcome.Busy || outcome === TerminalRunOutcome.Input)
1029
+ return new TerminalFolderChanged(null, true, outcome);
1030
+ if (outcome !== TerminalRunOutcome.Typed)
1031
+ throw new SessionNotFoundException(params.sessionId);
1032
+ const typedAt = session.text.endOffset;
1033
+ const prompts = session.prompts;
1034
+ const isMoved = () => Object.isNull(folderKeys) ? (session.commands.promptEndOffset ?? typedAt) > typedAt
1035
+ : session.prompts > prompts && !Object.isNull(session.commands.promptEndOffset);
1036
+ await session.changes.waitUntilAsync(() => session.hasExited || this.sessions.get(params.sessionId) !== terminal || isMoved(), Resources.folderChangeWaitMilliseconds, new AbortController().signal);
1037
+ if (session.hasExited || this.sessions.get(params.sessionId) !== terminal)
1038
+ throw new SessionNotFoundException(params.sessionId);
1039
+ const isChanged = Object.isNull(folderKeys) ? session.commands.lastCommand?.exitCode === 0 : session.cwd !== before || session.cwd === params.folder;
1040
+ return new TerminalFolderChanged(isMoved() && isChanged ? session.cwd : null, true);
1041
+ }
1042
+ static readMoveRefusal(terminal) {
1043
+ const commands = terminal.session.commands;
1044
+ if (!commands.hasMarks)
1045
+ return TerminalRunOutcome.NoShell;
1046
+ if (Object.isNull(commands.promptEndOffset))
1047
+ return TerminalRunOutcome.Busy;
1048
+ return terminal.hasUnreadInput || terminal.session.readPromptLine() !== "" ? TerminalRunOutcome.Input : null;
1049
+ }
997
1050
  resize(params, client) {
998
1051
  const terminal = this.findHosted(params.sessionId, client);
999
1052
  terminal.session.resize(params.size);
@@ -19,6 +19,7 @@ import { FlowController } from "./flow-controller.js";
19
19
  import { MarkScanner } from "./mark-scanner.js";
20
20
  import { OutputBatcher } from "./output-batcher.js";
21
21
  import { OutputLog } from "./output-log.js";
22
+ import { PrintedText } from "./printed-text.js";
22
23
  import { PseudoTerminal } from "./pseudo-terminal.js";
23
24
  import { ResizeWakeup } from "./resize-wakeup.js";
24
25
  import { ShellOptionsQueue } from "./shell-options-queue.js";
@@ -47,6 +48,7 @@ export class TerminalSession {
47
48
  isPromptNew = false;
48
49
  enteredAt = null;
49
50
  idleAt = 0;
51
+ printing = null;
50
52
  hasAnsweredOptions = false;
51
53
  disposal = new AbortController();
52
54
  sessionId;
@@ -55,6 +57,7 @@ export class TerminalSession {
55
57
  text;
56
58
  changes = new ChangeSignal();
57
59
  hasIntegration;
60
+ hasPrompted = false;
58
61
  promptLine = null;
59
62
  constructor(sessionId, shellId, size, process, nonce, windowsPty, historyPaths, storedLimit, listener, textLimit, shellKind, marksInput) {
60
63
  this.sessionId = sessionId;
@@ -147,6 +150,11 @@ export class TerminalSession {
147
150
  }
148
151
  this.terminal.write(data);
149
152
  }
153
+ sendFolder(keys, folder) {
154
+ this.options.cancel();
155
+ this.beforeInput();
156
+ this.terminal.write(`${keys}${Buffer.from(folder).toString(Resources.folderEncoding)}${Resources.enterKey}`);
157
+ }
150
158
  typeLine(text) {
151
159
  const line = new TypedLine(this.text.endOffset, text);
152
160
  this.typedLines.add(line);
@@ -231,6 +239,7 @@ export class TerminalSession {
231
239
  this.terminal.pause();
232
240
  this.scanner = Object.isNull(nonce) ? null : new MarkScanner(nonce);
233
241
  this.hasIntegration = !Object.isNull(nonce);
242
+ this.hasPrompted = false;
234
243
  this.commands = this.trackCommands();
235
244
  this.options.reset();
236
245
  this.hasAnsweredOptions = false;
@@ -238,6 +247,7 @@ export class TerminalSession {
238
247
  this.replacePromptLine(null);
239
248
  this.typedLines.clear();
240
249
  this.reportedCwd = null;
250
+ this.printing = null;
241
251
  this.exit = null;
242
252
  this.isClosing = false;
243
253
  this.size = size;
@@ -248,7 +258,7 @@ export class TerminalSession {
248
258
  this.insert(TerminalSession.toNote(text));
249
259
  }
250
260
  toSummary(folder, isAgentTerminal, isPanelTerminal, owner, opensTab, name, shellName) {
251
- return new TerminalSummary(this.sessionId, this.shellId, folder, this.mirror.title, this.exit, isAgentTerminal, isPanelTerminal, owner, opensTab, name, shellName, this.shellKind);
261
+ return new TerminalSummary(this.sessionId, this.shellId, folder, this.mirror.title, this.exit, isAgentTerminal, isPanelTerminal, owner, opensTab, name, shellName, this.shellKind, this.hasIntegration, this.hasPrompted);
252
262
  }
253
263
  disposeAsync() {
254
264
  this.disposal.abort();
@@ -274,6 +284,7 @@ export class TerminalSession {
274
284
  for (const mark of marks) {
275
285
  const end = mark.offset - this.receivedOffset;
276
286
  this.text.append(data.slice(position, end));
287
+ this.watchPrinting(data.slice(position, end));
277
288
  position = end;
278
289
  const edge = this.readInputEdge(mark);
279
290
  if (mark.kind === MarkKind.PromptStart || !Object.isNull(edge)) {
@@ -296,11 +307,19 @@ export class TerminalSession {
296
307
  }
297
308
  this.mirror.write(data.slice(mirrored));
298
309
  this.text.append(data.slice(position));
310
+ this.watchPrinting(data.slice(position));
299
311
  this.wakeup?.receive(data);
300
312
  this.receivedOffset += data.length;
301
313
  this.changes.notify();
302
314
  }
315
+ watchPrinting(data) {
316
+ if (Object.isNull(this.printing) || !this.printing.isVisible(data))
317
+ return;
318
+ this.printing = null;
319
+ this.listener.onOutputPrinted(new TerminalReference(this.sessionId));
320
+ }
303
321
  startOutput(mark, offset) {
322
+ this.printing = new PrintedText();
304
323
  const enteredAt = Math.max(this.enteredAt ?? Date.now(), this.idleAt);
305
324
  this.enteredAt = null;
306
325
  this.listener.onOutputStarted(new TerminalCommandStart(this.sessionId, offset, enteredAt, TerminalSession.toCommand(mark.value)));
@@ -335,12 +354,16 @@ export class TerminalSession {
335
354
  this.isPromptNew = false;
336
355
  this.commands.apply(mark);
337
356
  this.settleTypedLines(mark);
357
+ if (mark.kind === MarkKind.CommandEnd || mark.kind === MarkKind.PromptStart)
358
+ this.printing = null;
338
359
  if (mark.kind === MarkKind.CommandEnd) {
339
360
  const exitCode = this.commands.lastCommand?.exitCode ?? null;
340
361
  this.listener.onCommandEnded(new TerminalCommandEnded(this.sessionId, !Object.isNull(exitCode) && exitCode >= ProtocolResources.minimumExitCode && exitCode <= ProtocolResources.maximumExitCode ? exitCode : null));
341
362
  }
342
- else if (mark.kind === MarkKind.PromptStart)
363
+ else if (mark.kind === MarkKind.PromptStart) {
364
+ this.hasPrompted = true;
343
365
  this.listener.onPromptStarted(new TerminalReference(this.sessionId));
366
+ }
344
367
  const cwd = this.commands.cwd;
345
368
  if (Object.isNull(cwd) || cwd === this.reportedCwd || cwd.trim().length === 0 || cwd.length > ProtocolResources.maximumPathLength)
346
369
  return;
@@ -374,7 +397,7 @@ export class TerminalSession {
374
397
  if (this.terminal === terminal)
375
398
  this.wakeup?.beforeInput();
376
399
  }
377
- }, !Object.isNull(this.windowsPty));
400
+ }, !Object.isNull(this.windowsPty), !Resources.resizeQuietShellIds.includes(this.shellId));
378
401
  return terminal;
379
402
  }
380
403
  end(exitCode) {
@@ -14,6 +14,7 @@ import { SystemRootMissingException } from "../exceptions/system-root-missing.ex
14
14
  import { EnvironmentVariable } from "../models/environment-variable.js";
15
15
  import { Resources } from "../resources.js";
16
16
  import { FailureText } from "./failure-text.js";
17
+ import { LeftoverFolders } from "./leftover-folders.js";
17
18
  import { RegistryExport } from "./registry-export.js";
18
19
  export class WindowsEnvironment {
19
20
  environment;
@@ -100,7 +101,8 @@ export class WindowsEnvironment {
100
101
  }
101
102
  }
102
103
  async createFolderAsync() {
103
- const folder = await this.tools.writer.createPrivateFolderAsync(path.join(this.tools.temporaryFolder, Resources.environmentFolderPrefix));
104
+ await this.removeLeftoversAsync();
105
+ const folder = await this.tools.writer.createPrivateFolderAsync(path.join(this.tools.temporaryFolder, Resources.formatEnvironmentFolder(this.tools.pid)));
104
106
  try {
105
107
  await this.tools.access?.restrictAsync(folder);
106
108
  }
@@ -110,6 +112,11 @@ export class WindowsEnvironment {
110
112
  }
111
113
  return folder;
112
114
  }
115
+ async removeLeftoversAsync() {
116
+ const leftovers = new LeftoverFolders(this.tools.reader, this.tools.signaller, this.tools.temporaryFolder, this.tools.pid);
117
+ for (const folder of await leftovers.findAsync(Resources.environmentFolderPrefix, true))
118
+ await this.tools.writer.removeFolderAsync(folder).catch((error) => this.logCleanupFailure(error));
119
+ }
113
120
  async readScopeAsync(reg, key, folder, name) {
114
121
  let file = path.win32.join(folder, `${name}${Resources.windowsEnvironmentExportExtension}`);
115
122
  const files = [file];