@noldova/terminal 0.0.10 → 0.0.11

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/module.json CHANGED
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "id": "terminal",
3
- "version": "0.0.10",
3
+ "version": "0.0.11",
4
4
  "displayName": "Terminal",
5
5
  "description": "Runs shells in terminal panes, and lets AI agents run commands in them through permission requests.",
6
6
  "parts": ["runtime", "window"],
7
7
  "pseudoTerminals": true,
8
8
  "dependencies": {},
9
- "noldovaDesktop": ">=0.0.21 <0.1.0",
9
+ "noldovaDesktop": ">=0.0.24 <0.1.0",
10
10
  "contributes": {
11
11
  "methods": [
12
12
  "terminal.shells", "terminal.open", "terminal.close", "terminal.restart", "terminal.sessions", "terminal.attach", "terminal.input", "terminal.resize",
13
13
  "terminal.ack", "terminal.visibility", "terminal.detach", "terminal.lines", "terminal.restore", "terminal.closeOwner", "terminal.launch",
14
14
  "terminal.run", "terminal.runOutput", "terminal.windowStarted", "terminal.showOwner", "terminal.rename",
15
- "terminal.complete", "terminal.findCommands", "terminal.write"
15
+ "terminal.complete", "terminal.findCommands", "terminal.write", "terminal.changeFolder"
16
16
  ],
17
17
  "events": [
18
18
  "terminal.output", "terminal.exited", "terminal.restarted", "terminal.titleChanged", "terminal.cwdChanged", "terminal.detached",
19
19
  "terminal.closed", "terminal.opened", "terminal.launchCommandEnded", "terminal.runOpened", "terminal.runEnded",
20
- "terminal.renamed", "terminal.commandAdded", "terminal.commandStarted", "terminal.outputStarted",
20
+ "terminal.renamed", "terminal.commandAdded", "terminal.commandStarted", "terminal.outputStarted", "terminal.outputPrinted",
21
21
  "terminal.commandEnded", "terminal.promptStarted", "terminal.screenChanged"
22
22
  ],
23
23
  "commands": ["terminal.new", "terminal.newWithShell", "terminal.toggle", "terminal.restartShell"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noldova/terminal",
3
- "version": "0.0.10",
3
+ "version": "0.0.11",
4
4
  "description": "The terminal module for apps on Noldova Desktop: terminal panes over real shells, and agent tools that run commands through permission requests.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,18 +37,18 @@
37
37
  "registry": "https://registry.npmjs.org/"
38
38
  },
39
39
  "dependencies": {
40
- "@noldova/terminal.protocol": "0.0.10",
41
- "@noldova/terminal.window": "0.0.10",
40
+ "@noldova/terminal.protocol": "0.0.11",
41
+ "@noldova/terminal.window": "0.0.11",
42
42
  "@xterm/addon-serialize": "0.14.0",
43
43
  "@xterm/headless": "6.0.0",
44
44
  "node-pty": "1.2.0-beta.15"
45
45
  },
46
46
  "peerDependencies": {
47
- "@noldova/desktop.protocol": ">=0.0.21 <0.1.0",
48
- "@noldova/desktop.runtime": ">=0.0.21 <0.1.0",
47
+ "@noldova/desktop.protocol": ">=0.0.24 <0.1.0",
48
+ "@noldova/desktop.runtime": ">=0.0.24 <0.1.0",
49
49
  "@noldova/context.core": ">=0.0.18 <0.1.0",
50
50
  "@noldova/context.exceptions": ">=0.0.18 <0.1.0",
51
51
  "@noldova/context.json": ">=0.0.18 <0.1.0"
52
52
  },
53
- "gitHead": "2c149af6c1a395e79ed2e344947040781730ae2a"
53
+ "gitHead": "f4cfef7c6d5c0e3594311e1f220adb65d1404beb"
54
54
  }
@@ -147,7 +147,8 @@ export { RunShellKindsMissingException } from "@noldova/terminal.window";
147
147
  export { RunLinesRefusedException } from "@noldova/terminal.window";
148
148
 
149
149
  /**
150
- * Thrown when a run picked, opened or was given a terminal but its commands weren't typed, saying why, from `@noldova/terminal.window`.
150
+ * Thrown when a run picked, opened or was given a terminal but its commands weren't typed, or a folder move found the terminal not free,
151
+ * saying why, from `@noldova/terminal.window`.
151
152
  *
152
153
  * @example
153
154
  * ```ts
@@ -319,6 +320,18 @@ export { TerminalLauncher } from "@noldova/terminal.window";
319
320
  */
320
321
  export { TerminalLaunch } from "@noldova/terminal.window";
321
322
 
323
+ /**
324
+ * The tab of a launched terminal, from `@noldova/terminal.window`.
325
+ *
326
+ * @example
327
+ * ```ts
328
+ * import { LaunchedTab } from "@noldova/terminal/window";
329
+ *
330
+ * console.log(LaunchedTab.none.isShown());
331
+ * ```
332
+ */
333
+ export { LaunchedTab } from "@noldova/terminal.window";
334
+
322
335
  /**
323
336
  * A terminal the launcher opened, with the promise of its end, from `@noldova/terminal.window`.
324
337
  *
@@ -344,6 +357,31 @@ export { LaunchedTerminal } from "@noldova/terminal.window";
344
357
  */
345
358
  export type { ITerminalWriteOptions } from "@noldova/terminal.window";
346
359
 
360
+ /**
361
+ * How a launched terminal's `showAsync` shows its tab, from `@noldova/terminal.window`.
362
+ *
363
+ * @example
364
+ * ```ts
365
+ * import type { ITerminalShowOptions } from "@noldova/terminal/window";
366
+ *
367
+ * const options: ITerminalShowOptions = { focus: true };
368
+ * console.log(options.focus);
369
+ * ```
370
+ */
371
+ export type { ITerminalShowOptions } from "@noldova/terminal.window";
372
+
373
+ /**
374
+ * Thrown when a launched terminal's tab can't be shown because it was launched without one, from `@noldova/terminal.window`.
375
+ *
376
+ * @example
377
+ * ```ts
378
+ * import { TerminalWithoutTabException } from "@noldova/terminal/window";
379
+ *
380
+ * console.log(new TerminalWithoutTabException("session-1").sessionId);
381
+ * ```
382
+ */
383
+ export { TerminalWithoutTabException } from "@noldova/terminal.window";
384
+
347
385
  /**
348
386
  * Thrown when a launched terminal's text can't be written because it ended, from `@noldova/terminal.window`.
349
387
  *
@@ -356,6 +394,31 @@ export type { ITerminalWriteOptions } from "@noldova/terminal.window";
356
394
  */
357
395
  export { TerminalEndedException } from "@noldova/terminal.window";
358
396
 
397
+ /**
398
+ * Thrown when a launched terminal's shell can't be moved to a folder because its kind doesn't report its folder, from
399
+ * `@noldova/terminal.window`.
400
+ *
401
+ * @example
402
+ * ```ts
403
+ * import { TerminalFolderNotFollowedException } from "@noldova/terminal/window";
404
+ *
405
+ * console.log(new TerminalFolderNotFollowedException("session-1", "CommandPrompt").shellKind);
406
+ * ```
407
+ */
408
+ export { TerminalFolderNotFollowedException } from "@noldova/terminal.window";
409
+
410
+ /**
411
+ * Thrown when a launched terminal's shell didn't move to a folder, from `@noldova/terminal.window`.
412
+ *
413
+ * @example
414
+ * ```ts
415
+ * import { TerminalFolderRefusedException } from "@noldova/terminal/window";
416
+ *
417
+ * console.log(new TerminalFolderRefusedException("session-1", "/gone").folder);
418
+ * ```
419
+ */
420
+ export { TerminalFolderRefusedException } from "@noldova/terminal.window";
421
+
359
422
  /**
360
423
  * Tells an app the events of a terminal session it reaches, from `@noldova/terminal.window`.
361
424
  *
package/src/api/window.js CHANGED
@@ -5,4 +5,4 @@
5
5
  * This source code is licensed under the license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
- export { EmbeddedRowsRefusedException, EmbeddedTerminal, LaunchArgumentRefusedException, LaunchedTerminal, LaunchFolderMissingException, LaunchPartInactiveException, LaunchRowsRefusedException, LaunchRowsWithoutTabException, LaunchTitleRefusedException, OwnersProvidedException, RunArgumentRefusedException, RunLinesRefusedException, RunPartInactiveException, RunShellKindsMissingException, StartFolderProvidedException, TerminalEnd, TerminalLaunch, TerminalLauncher, TerminalLaunchRefusedException, TerminalEndedException, TerminalNotActiveException, TerminalLine, TerminalListener, TerminalOwners, TerminalRun, TerminalRunBusy, TerminalRunEnd, TerminalRunNotFoundException, TerminalRunNotTypedException, TerminalRunOutcome, TerminalRunOutput, TerminalRunRefusedException, TerminalRunTarget, TerminalShellKind, TerminalStartFolder, TerminalTextRun, TerminalTextStyle, TerminalWindowException, windowPart } from "@noldova/terminal.window";
8
+ export { EmbeddedRowsRefusedException, EmbeddedTerminal, LaunchArgumentRefusedException, LaunchedTab, LaunchedTerminal, LaunchFolderMissingException, LaunchPartInactiveException, LaunchRowsRefusedException, LaunchRowsWithoutTabException, LaunchTitleRefusedException, OwnersProvidedException, RunArgumentRefusedException, RunLinesRefusedException, RunPartInactiveException, RunShellKindsMissingException, StartFolderProvidedException, TerminalEnd, TerminalLaunch, TerminalLauncher, TerminalLaunchRefusedException, TerminalEndedException, TerminalFolderNotFollowedException, TerminalFolderRefusedException, TerminalNotActiveException, TerminalLine, TerminalListener, TerminalOwners, TerminalRun, TerminalRunBusy, TerminalRunEnd, TerminalRunNotFoundException, TerminalRunNotTypedException, TerminalRunOutcome, TerminalRunOutput, TerminalRunRefusedException, TerminalRunTarget, TerminalShellKind, TerminalStartFolder, TerminalTextRun, TerminalTextStyle, TerminalWindowException, TerminalWithoutTabException, windowPart } from "@noldova/terminal.window";
@@ -0,0 +1 @@
1
+ export {};
@@ -12,12 +12,16 @@ export class EnvironmentTools {
12
12
  writer;
13
13
  access;
14
14
  temporaryFolder;
15
- constructor(starter, runner, reader, writer, access, temporaryFolder) {
15
+ signaller;
16
+ pid;
17
+ constructor(starter, runner, reader, writer, access, temporaryFolder, signaller, pid) {
16
18
  this.starter = starter;
17
19
  this.runner = runner;
18
20
  this.reader = reader;
19
21
  this.writer = writer;
20
22
  this.access = access;
21
23
  this.temporaryFolder = temporaryFolder;
24
+ this.signaller = signaller;
25
+ this.pid = pid;
22
26
  }
23
27
  }
@@ -21,10 +21,11 @@ export class TerminalEvents {
21
21
  commandAdded;
22
22
  commandStarted;
23
23
  outputStarted;
24
+ outputPrinted;
24
25
  commandEnded;
25
26
  promptStarted;
26
27
  screenChanged;
27
- constructor(output, exited, restarted, titleChanged, cwdChanged, detached, closed, opened, launchCommandEnded, runOpened, runEnded, renamed, commandAdded, commandStarted, outputStarted, commandEnded, promptStarted, screenChanged) {
28
+ constructor(output, exited, restarted, titleChanged, cwdChanged, detached, closed, opened, launchCommandEnded, runOpened, runEnded, renamed, commandAdded, commandStarted, outputStarted, outputPrinted, commandEnded, promptStarted, screenChanged) {
28
29
  this.output = output;
29
30
  this.exited = exited;
30
31
  this.restarted = restarted;
@@ -40,6 +41,7 @@ export class TerminalEvents {
40
41
  this.commandAdded = commandAdded;
41
42
  this.commandStarted = commandStarted;
42
43
  this.outputStarted = outputStarted;
44
+ this.outputPrinted = outputPrinted;
43
45
  this.commandEnded = commandEnded;
44
46
  this.promptStarted = promptStarted;
45
47
  this.screenChanged = screenChanged;
package/src/resources.js CHANGED
@@ -87,6 +87,7 @@ export class Resources {
87
87
  static integrationWaitMilliseconds = 10_000;
88
88
  static paneFitWaitMilliseconds = 10_000;
89
89
  static shellStartMilliseconds = 60_000;
90
+ static folderChangeWaitMilliseconds = 30_000;
90
91
  static maximumExitedSessions = 32;
91
92
  static restartReset = "\u001b[?1047l\u001b[!p\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?2004l\r";
92
93
  static lineFeed = "\n";
@@ -174,6 +175,10 @@ export class Resources {
174
175
  static posixEscape = "\\";
175
176
  static powerShellEscape = "`";
176
177
  static singleQuote = "'";
178
+ static posixChangeFolder = "cd -- ";
179
+ static posixQuotedSingleQuote = "'\\''";
180
+ static powerShellChangeFolder = "Set-Location -LiteralPath ";
181
+ static powerShellSingleQuotes = /['\u2018\u2019\u201a\u201b]/gu;
177
182
  static doubleQuote = "\"";
178
183
  static wordBreaks = " \t";
179
184
  static commandBreaks = "|;&";
@@ -300,10 +305,8 @@ export class Resources {
300
305
  static completionReadMilliseconds = 1_000;
301
306
  static runFolderReadMilliseconds = 1_000;
302
307
  static completionConcurrentReads = 2;
303
- static optionsKeys = new Map([
304
- [TerminalShellKind.PowerShell, "\u001b[24~o"],
305
- [TerminalShellKind.Zsh, "\u001b[24;7~"]
306
- ]);
308
+ static powerShellOptionsKeys = "\u001b[24~o";
309
+ static zshOptionsKeys = "\u001b[24;7~";
307
310
  static optionsMilliseconds = 500;
308
311
  static firstOptionsMilliseconds = 3_500;
309
312
  static powerShellLookupMilliseconds = 10_000;
@@ -322,7 +325,6 @@ export class Resources {
322
325
  "Select-String", "Set-Content", "Set-Location", "Sort-Object", "Split-Path", "Start-Process", "Stop-Process", "Test-Path", "Where-Object",
323
326
  "Write-Host", "Write-Output", "cat", "cd", "cls", "copy", "del", "dir", "echo", "exit", "ls", "md", "move", "pwd", "ren", "rm", "type"
324
327
  ];
325
- static completedShellKinds = [TerminalShellKind.Bash, TerminalShellKind.Zsh, TerminalShellKind.PowerShell];
326
328
  static programFilesVariable = "ProgramFiles";
327
329
  static programFilesX86Variable = "ProgramFiles(x86)";
328
330
  static localAppDataVariable = "LOCALAPPDATA";
@@ -581,6 +583,8 @@ exit 0
581
583
  static storedLinesFailed = "The terminal's stored lines could not be written.";
582
584
  static storedLinesDamaged = "The terminal's stored lines are damaged.";
583
585
  static carriageReturn = "\r";
586
+ static printedTextBreaks = /(\r|\n)/u;
587
+ static lineEndMarks = ["%", "#"];
584
588
  static decimalRadix = 10;
585
589
  static hexadecimalRadix = 16;
586
590
  static utf8Encoding = "utf8";
@@ -723,6 +727,9 @@ exit 0
723
727
  static formatTerminalHistoryFolder(pid) {
724
728
  return `${Resources.terminalHistoryFolderPrefix}${pid}-`;
725
729
  }
730
+ static formatEnvironmentFolder(pid) {
731
+ return `${Resources.environmentFolderPrefix}${pid}-`;
732
+ }
726
733
  static formatTerminalHistoryNotPrivate(message) {
727
734
  return `A terminal opens without stored lines, whose folder could not be made private: ${message}`;
728
735
  }
@@ -1703,7 +1710,8 @@ fi
1703
1710
  static shellWordsPosixQuotedSingleQuote = "'\\''";
1704
1711
  static systemRequirementsWindowsBuild = /^\d+\.\d+\.(\d+)$/u;
1705
1712
  static systemRequirementsGlibcVersion = /^(\d+)\.(\d+)/u;
1706
- static terminalHistoryFolderFolderSuffix = /^(\d{1,10})-.{6}$/u;
1713
+ static leftoverFolderSuffix = /^(\d{1,10})-.{6}$/u;
1714
+ static leftoverFolderSuffixWithoutPid = /^[0-9A-Za-z]{6}$/u;
1707
1715
  static terminalHostUuidSeparator = "-";
1708
1716
  static terminalMirrorLeadingWhiteSpace = /^\s/u;
1709
1717
  static terminalOwnerServiceAgentSessionIdField = "agentSessionId";
@@ -49,11 +49,12 @@ export class RuntimePart {
49
49
  const writer = new FileSystemWriter();
50
50
  const runner = new CommandRunner(context);
51
51
  const access = FolderAccess.create(process.platform, runner, process.env);
52
- const environment = ShellEnvironment.create(process.platform, process.env, new EnvironmentTools(new LineProcessStarter(context), runner, reader, writer, access, tmpdir()), context.log, Intl.DateTimeFormat().resolvedOptions().locale, MacEnvironment.hasSystemLocaleAsync);
52
+ const signaller = new ProcessSignaller();
53
+ const environment = ShellEnvironment.create(process.platform, process.env, new EnvironmentTools(new LineProcessStarter(context), runner, reader, writer, access, tmpdir(), signaller, process.pid), context.log, Intl.DateTimeFormat().resolvedOptions().locale, MacEnvironment.hasSystemLocaleAsync);
53
54
  environment.start();
54
55
  try {
55
- const events = new TerminalEvents(context.declareEvent(TerminalNames.outputEvent), context.declareEvent(TerminalNames.exitedEvent), context.declareEvent(TerminalNames.restartedEvent), context.declareEvent(TerminalNames.titleChangedEvent), context.declareEvent(TerminalNames.cwdChangedEvent), context.declareEvent(TerminalNames.detachedEvent), context.declareEvent(TerminalNames.closedEvent), context.declareEvent(TerminalNames.openedEvent), context.declareEvent(TerminalNames.launchCommandEndedEvent), context.declareEvent(TerminalNames.runOpenedEvent), context.declareEvent(TerminalNames.runEndedEvent), context.declareEvent(TerminalNames.renamedEvent), context.declareEvent(TerminalNames.commandAddedEvent), context.declareEvent(TerminalNames.commandStartedEvent), context.declareEvent(TerminalNames.outputStartedEvent), context.declareEvent(TerminalNames.commandEndedEvent), context.declareEvent(TerminalNames.promptStartedEvent), context.declareEvent(TerminalNames.screenChangedEvent));
56
- const host = new TerminalHost(new ContextPtySpawner(context), reader, new ShellIntegration(writer, tmpdir(), context.log, access, context.settings, process.platform), new TerminalHistoryFolder(writer, reader, new ProcessSignaller(), tmpdir(), process.pid, context.log, access), new ShellLocator(process.platform, process.arch, process.env, ShellLocator.readUserShell(), reader, runner, context.log), process.platform, release(), new LatestEnvironment(environment, process.env), homedir(), context.log, events, new SavedTerminals(context.database, context.log), new CompletionSource(reader, runner, process.platform, homedir(), context.log));
56
+ const events = new TerminalEvents(context.declareEvent(TerminalNames.outputEvent), context.declareEvent(TerminalNames.exitedEvent), context.declareEvent(TerminalNames.restartedEvent), context.declareEvent(TerminalNames.titleChangedEvent), context.declareEvent(TerminalNames.cwdChangedEvent), context.declareEvent(TerminalNames.detachedEvent), context.declareEvent(TerminalNames.closedEvent), context.declareEvent(TerminalNames.openedEvent), context.declareEvent(TerminalNames.launchCommandEndedEvent), context.declareEvent(TerminalNames.runOpenedEvent), context.declareEvent(TerminalNames.runEndedEvent), context.declareEvent(TerminalNames.renamedEvent), context.declareEvent(TerminalNames.commandAddedEvent), context.declareEvent(TerminalNames.commandStartedEvent), context.declareEvent(TerminalNames.outputStartedEvent), context.declareEvent(TerminalNames.outputPrintedEvent), context.declareEvent(TerminalNames.commandEndedEvent), context.declareEvent(TerminalNames.promptStartedEvent), context.declareEvent(TerminalNames.screenChangedEvent));
57
+ const host = new TerminalHost(new ContextPtySpawner(context), reader, new ShellIntegration(writer, tmpdir(), context.log, access, context.settings, process.platform), new TerminalHistoryFolder(writer, reader, signaller, tmpdir(), process.pid, context.log, access), new ShellLocator(process.platform, process.arch, process.env, ShellLocator.readUserShell(), reader, runner, context.log), process.platform, release(), new LatestEnvironment(environment, process.env), homedir(), context.log, events, new SavedTerminals(context.database, context.log), new CompletionSource(reader, runner, process.platform, homedir(), context.log));
57
58
  for (const name of TerminalNames.methods)
58
59
  context.registerMethod(name, { handleAsync: t => host.handleAsync(name, t.payload, RequestClient.fromContext(t)) });
59
60
  context.onClientClosed(t => host.closeConnectionAsync(t.connection, t.window));
@@ -16,15 +16,14 @@ import { ShellLine } from "../models/shell-line.js";
16
16
  import { Resources } from "../resources.js";
17
17
  import { BoundedReads } from "./bounded-reads.js";
18
18
  import { FailureText } from "./failure-text.js";
19
- import { PowerShellBinding } from "./powershell-binding.js";
20
19
  import { SharedReads } from "./shared-reads.js";
21
- import { ShellWords } from "./shell-words.js";
20
+ import { ShellAdapters } from "./shell-adapters.js";
22
21
  export class CompletionSource {
23
22
  runner;
24
23
  isWindows;
25
24
  paths;
26
25
  homeFolder;
27
- binding;
26
+ adapters;
28
27
  shared;
29
28
  stuck = [];
30
29
  listed = new WeakMap();
@@ -39,25 +38,29 @@ export class CompletionSource {
39
38
  this.isWindows = platform === Resources.windowsPlatform;
40
39
  this.paths = this.isWindows ? path.win32 : path.posix;
41
40
  this.homeFolder = homeFolder;
42
- this.binding = new PowerShellBinding(this.isWindows);
41
+ this.adapters = new ShellAdapters(this.isWindows);
43
42
  this.shared = new SharedReads(fileSystem);
44
43
  }
45
44
  async completeAsync(key, kind, line, cursor, folder, environment, shellNames, shellBuiltins) {
46
- if (!Resources.completedShellKinds.includes(kind) || this.stuck.includes(key))
45
+ const shell = this.adapters.of(kind);
46
+ if (Object.isNull(shell) || this.stuck.includes(key))
47
47
  return new TerminalCompletion(cursor, []);
48
- const builtins = kind === TerminalShellKind.PowerShell ? Resources.powerShellBuiltins
49
- : [...new Set([...shellBuiltins ?? [], ...shellNames ?? []])]
50
- .filter(t => !t.startsWith(Resources.helperNamePrefix) && t !== Resources.autocdName && !t.startsWith(Resources.suffixAliasNameStart));
51
- return this.readAsync(key, t => this.completeLineAsync(t, kind, builtins, line.slice(0, cursor), folder, environment));
48
+ const builtins = shell.listBuiltins(shellNames, shellBuiltins);
49
+ return this.readAsync(key, t => this.completeLineAsync(t, shell, builtins, line.slice(0, cursor), folder, environment));
50
+ }
51
+ adapterOf(kind) {
52
+ return this.adapters.of(kind);
52
53
  }
53
54
  toLocalFolder(folder, kind, environment) {
54
- return this.toLocalPath(folder, kind, this.readVariable(environment, Resources.temporaryFolderVariable) ?? null);
55
+ const shell = this.adapters.of(kind);
56
+ return Object.isNull(shell) ? folder : shell.toLocalPath(folder, this.readVariable(environment, Resources.temporaryFolderVariable) ?? null);
55
57
  }
56
58
  followsCommand(kind, line, cursor) {
57
- return ShellWords.read(line.slice(0, cursor), kind === TerminalShellKind.PowerShell).words.length > 0;
59
+ const shell = this.adapters.of(kind);
60
+ return !Object.isNull(shell) && shell.readWords(line.slice(0, cursor)).words.length > 0;
58
61
  }
59
62
  addOptions(completion, kind, line, cursor, options) {
60
- const ignoresCase = this.isWindows || kind === TerminalShellKind.PowerShell;
63
+ const ignoresCase = this.isWindows || this.adapters.of(kind)?.ignoresCase === true;
61
64
  const toKey = (text) => ignoresCase ? text.toLowerCase() : text;
62
65
  const prefix = toKey(line.slice(completion.replaceFrom, cursor));
63
66
  const labels = new Set(completion.items.map(t => t.label));
@@ -71,9 +74,10 @@ export class CompletionSource {
71
74
  return new TerminalCompletion(completion.replaceFrom, items.slice(0, ProtocolResources.maximumCompletionItems));
72
75
  }
73
76
  async findMissingAsync(key, shell, prompt, kind, folder, names, shellNames, environment) {
74
- if (kind === TerminalShellKind.PowerShell || !Resources.completedShellKinds.includes(kind) || Object.isNull(shellNames) || this.stuck.includes(key))
77
+ const adapter = this.adapters.of(kind);
78
+ if (Object.isNull(adapter) || adapter.looksUpMissing || Object.isNull(shellNames) || this.stuck.includes(key))
75
79
  return new TerminalMissingCommands([]);
76
- const takesBareNames = this.isWindows && kind === TerminalShellKind.Bash;
80
+ const takesBareNames = adapter.takesBareNames;
77
81
  const search = JSON.stringify([kind, this.readVariable(environment, Resources.pathVariable),
78
82
  this.readVariable(environment, Resources.pathExtensionsVariable)]);
79
83
  const last = this.listed.get(shell);
@@ -88,7 +92,7 @@ export class CompletionSource {
88
92
  const unknown = names.filter(t => !this.isPath(t) && !t.startsWith(Resources.helperNamePrefix)
89
93
  && !known.has(this.toCommandName(t)) && !this.hasSuffixAlias(t, shellNames));
90
94
  const missing = unknown.length > 0 && shellNames.has(Resources.autocdName)
91
- ? await this.dropFoldersAsync(reads, kind, folder, environment, unknown) : unknown;
95
+ ? await this.dropFoldersAsync(reads, adapter, folder, environment, unknown) : unknown;
92
96
  return new TerminalMissingCommands(reads.wasCutShort ? [] : missing);
93
97
  });
94
98
  }
@@ -141,8 +145,8 @@ export class CompletionSource {
141
145
  const start = name.lastIndexOf(Resources.suffixStart);
142
146
  return start > 0 && shellNames.has(`${Resources.suffixAliasNameStart}${name.slice(start + 1)}`);
143
147
  }
144
- async dropFoldersAsync(reads, kind, folder, environment, names) {
145
- const workFolder = this.toLocalFolder(folder, kind, environment);
148
+ async dropFoldersAsync(reads, shell, folder, environment, names) {
149
+ const workFolder = shell.toLocalPath(folder, this.readVariable(environment, Resources.temporaryFolderVariable) ?? null);
146
150
  if (Object.isNull(workFolder))
147
151
  return names;
148
152
  const folders = new Set((await reads.readEntriesAsync(workFolder)).filter(t => t.isFolder)
@@ -162,49 +166,47 @@ export class CompletionSource {
162
166
  }
163
167
  }
164
168
  }
165
- async completeLineAsync(reads, kind, builtins, line, folder, environment) {
166
- const isPowerShell = kind === TerminalShellKind.PowerShell;
167
- const typed = ShellWords.read(line, isPowerShell);
168
- const escapesWildcards = isPowerShell && this.binding.bindsWildcardPath(typed.words);
169
+ async completeLineAsync(reads, shell, builtins, line, folder, environment) {
170
+ const typed = shell.readWords(line);
171
+ const escapesWildcards = shell.escapesWildcards(typed.words);
169
172
  const shellLine = escapesWildcards
170
173
  ? new ShellLine(typed.words, typed.start, typed.value.replace(Resources.powerShellEscapedWildcards, Resources.completionSourceEscapedWildcardReplacement), typed.quote, typed.startsQuoted)
171
174
  : typed;
172
- const ignoresCase = this.isWindows || isPowerShell;
175
+ const ignoresCase = this.isWindows || shell.ignoresCase;
173
176
  const prefix = ignoresCase ? shellLine.value.toLowerCase() : shellLine.value;
174
- const expandsHome = isPowerShell || !shellLine.startsQuoted;
177
+ const expandsHome = shell.expandsHome(shellLine.startsQuoted);
175
178
  const keepsHome = expandsHome && this.isHome(shellLine.value);
176
- const candidates = (await this.listAsync(reads, kind, builtins, shellLine, folder, environment, expandsHome))
179
+ const candidates = (await this.listAsync(reads, shell, builtins, shellLine, folder, environment, expandsHome))
177
180
  .filter(t => (ignoresCase ? t.value.toLowerCase() : t.value).startsWith(prefix));
178
181
  const items = [...new Map(candidates.map(t => [t.value, t])).values()]
179
182
  .sort((a, b) => a.label.localeCompare(b.label, Resources.sortLocale))
180
183
  .flatMap(t => {
181
- const text = ShellWords.write(t.value, shellLine.quote, isPowerShell, t.closesQuote, escapesWildcards && (t.kind === TerminalCompletionKind.File || t.kind === TerminalCompletionKind.Folder), keepsHome);
184
+ const text = shell.writeWord(t.value, shellLine.quote, t.closesQuote, escapesWildcards && (t.kind === TerminalCompletionKind.File || t.kind === TerminalCompletionKind.Folder), keepsHome);
182
185
  return text.length <= ProtocolResources.maximumPathLength && !ProtocolResources.controlCharacters.test(text)
183
186
  ? [new TerminalCompletionItem(text, t.label, t.kind)]
184
187
  : [];
185
188
  });
186
189
  return new TerminalCompletion(shellLine.start, items.slice(0, ProtocolResources.maximumCompletionItems));
187
190
  }
188
- listAsync(reads, kind, builtins, shellLine, folder, environment, expandsHome) {
191
+ listAsync(reads, shell, builtins, shellLine, folder, environment, expandsHome) {
189
192
  const words = shellLine.words.map(t => this.toCommandName(t));
190
193
  if (words.length === 0 && !this.isPath(shellLine.value))
191
194
  return this.listCommandsAsync(reads, builtins, environment);
192
195
  const temporaryFolder = this.readVariable(environment, Resources.temporaryFolderVariable) ?? null;
193
- const workFolder = this.toLocalPath(folder, kind, temporaryFolder);
196
+ const workFolder = shell.toLocalPath(folder, temporaryFolder);
194
197
  if (!Object.isNull(workFolder) && words.length === Resources.subcommandWordCount && words[0] === Resources.gitCommand && Resources.gitBranchCommands.some(t => shellLine.words[1] === t))
195
198
  return this.listBranchesAsync(reads, workFolder, environment);
196
199
  if (!Object.isNull(workFolder) && words.length === Resources.subcommandWordCount && words[0] === Resources.npmCommand && Resources.npmRunCommands.some(t => shellLine.words[1] === t))
197
200
  return this.listScriptsAsync(reads, workFolder);
198
- return this.listPathsAsync(reads, kind, shellLine.value, workFolder, expandsHome, temporaryFolder);
201
+ return this.listPathsAsync(reads, shell, shellLine.value, workFolder, expandsHome, temporaryFolder);
199
202
  }
200
- async listPathsAsync(reads, kind, value, workFolder, expandsHome, temporaryFolder) {
203
+ async listPathsAsync(reads, shell, value, workFolder, expandsHome, temporaryFolder) {
201
204
  const end = Math.max(value.lastIndexOf(Resources.posixSeparator), this.isWindows ? value.lastIndexOf(Resources.windowsSeparator) : -1);
202
205
  const typedFolder = value.slice(0, end + 1);
203
- const folder = Object.isNull(workFolder) ? null : this.toFolder(kind, typedFolder, workFolder, expandsHome, temporaryFolder);
206
+ const folder = Object.isNull(workFolder) ? null : this.toFolder(shell, typedFolder, workFolder, expandsHome, temporaryFolder);
204
207
  if (Object.isNull(folder))
205
208
  return [];
206
- const separator = end >= 0 ? value.charAt(end)
207
- : this.isWindows && kind === TerminalShellKind.PowerShell ? Resources.windowsSeparator : Resources.posixSeparator;
209
+ const separator = end >= 0 ? value.charAt(end) : shell.separator;
208
210
  const showsHidden = value.slice(end + 1).startsWith(Resources.hiddenPrefix);
209
211
  return (await reads.readEntriesAsync(folder))
210
212
  .filter(t => showsHidden || !t.name.startsWith(Resources.hiddenPrefix))
@@ -299,21 +301,10 @@ export class CompletionSource {
299
301
  readVariable(environment, name) {
300
302
  return this.isWindows ? Object.entries(environment).find(([t]) => t.toUpperCase() === name)?.[1] : environment[name];
301
303
  }
302
- toFolder(kind, typedFolder, workFolder, expandsHome, temporaryFolder) {
303
- const folder = expandsHome && this.isHome(typedFolder) ? this.paths.join(this.homeFolder, typedFolder.slice(Resources.homePrefix.length)) : this.toLocalPath(typedFolder, kind, temporaryFolder);
304
+ toFolder(shell, typedFolder, workFolder, expandsHome, temporaryFolder) {
305
+ const folder = expandsHome && this.isHome(typedFolder) ? this.paths.join(this.homeFolder, typedFolder.slice(Resources.homePrefix.length)) : shell.toLocalPath(typedFolder, temporaryFolder);
304
306
  return Object.isNull(folder) ? null : this.paths.resolve(workFolder, folder);
305
307
  }
306
- toLocalPath(value, kind, temporaryFolder) {
307
- if (!this.isWindows || kind !== TerminalShellKind.Bash || !value.startsWith(Resources.posixSeparator))
308
- return value;
309
- const temporary = Resources.gitBashTemporaryFolder;
310
- if (!Object.isNull(temporaryFolder) && path.win32.isAbsolute(temporaryFolder)
311
- && (value === temporary || value.startsWith(`${temporary}${Resources.posixSeparator}`)))
312
- return path.win32.join(temporaryFolder, value.slice(temporary.length));
313
- if (!Resources.gitBashDrivePath.test(value))
314
- return null;
315
- return Resources.formatCompletionSourceWindowsDrivePath(value.charAt(1).toUpperCase(), value.slice(Resources.completionSourceGitBashDrivePrefixLength).replaceAll(Resources.posixSeparator, Resources.windowsSeparator));
316
- }
317
308
  toCommandName(word) {
318
309
  const name = this.paths.basename(word);
319
310
  return this.isWindows ? name.toLowerCase().replace(Resources.windowsProgramExtension, "") : name;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import "@noldova/context.core";
9
+ import { TerminalShellKind } from "@noldova/terminal.protocol";
10
+ import { Resources } from "../resources.js";
11
+ export class FolderChangeLine {
12
+ static format(kind, folder) {
13
+ switch (kind) {
14
+ case TerminalShellKind.PowerShell:
15
+ return `${Resources.powerShellChangeFolder}${Resources.singleQuote}${folder.replace(Resources.powerShellSingleQuotes, "$&$&")}${Resources.singleQuote}`;
16
+ case TerminalShellKind.Bash:
17
+ case TerminalShellKind.Zsh:
18
+ return `${Resources.posixChangeFolder}${Resources.singleQuote}${folder.replaceAll(Resources.singleQuote, Resources.posixQuotedSingleQuote)}${Resources.singleQuote}`;
19
+ default:
20
+ return null;
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import "@noldova/context.core";
9
+ import path from "node:path";
10
+ import { Resources } from "../resources.js";
11
+ export class LeftoverFolders {
12
+ reader;
13
+ signaller;
14
+ temporaryFolder;
15
+ pid;
16
+ constructor(reader, signaller, temporaryFolder, pid) {
17
+ this.reader = reader;
18
+ this.signaller = signaller;
19
+ this.temporaryFolder = temporaryFolder;
20
+ this.pid = pid;
21
+ }
22
+ async findAsync(prefix, isWithoutPidLeftover = false) {
23
+ const found = [];
24
+ for (const name of await this.reader.readFolderNamesAsync(this.temporaryFolder)) {
25
+ if (!name.startsWith(prefix))
26
+ continue;
27
+ const suffix = name.slice(prefix.length);
28
+ const pid = LeftoverFolders.toPid(suffix);
29
+ const isLeftover = Object.isNull(pid)
30
+ ? isWithoutPidLeftover && Resources.leftoverFolderSuffixWithoutPid.test(suffix)
31
+ : pid !== this.pid && !this.signaller.isRunning(pid);
32
+ if (isLeftover)
33
+ found.push(path.join(this.temporaryFolder, name));
34
+ }
35
+ return found;
36
+ }
37
+ static toPid(suffix) {
38
+ const match = Resources.leftoverFolderSuffix.exec(suffix);
39
+ const pid = Number(match?.[1]);
40
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
41
+ }
42
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import "@noldova/context.core";
9
+ import path from "node:path";
10
+ import { Resources } from "../resources.js";
11
+ import { ShellWords } from "./shell-words.js";
12
+ export class PosixShellAdapter {
13
+ ignoresCase;
14
+ separator = Resources.posixSeparator;
15
+ takesBareNames;
16
+ optionsKeys;
17
+ looksUpMissing = false;
18
+ isGitBash;
19
+ constructor(isWindows, optionsKeys, isBash) {
20
+ this.ignoresCase = isWindows;
21
+ this.optionsKeys = optionsKeys;
22
+ this.isGitBash = isWindows && isBash;
23
+ this.takesBareNames = this.isGitBash;
24
+ }
25
+ readWords(line) {
26
+ return ShellWords.read(line, false);
27
+ }
28
+ writeWord(value, quote, closesQuote, escapesWildcards, keepsHome) {
29
+ return ShellWords.write(value, quote, false, closesQuote, escapesWildcards, keepsHome);
30
+ }
31
+ escapesWildcards() {
32
+ return false;
33
+ }
34
+ expandsHome(startsQuoted) {
35
+ return !startsQuoted;
36
+ }
37
+ listBuiltins(shellNames, shellBuiltins) {
38
+ return [...new Set([...shellBuiltins ?? [], ...shellNames ?? []])]
39
+ .filter(t => !t.startsWith(Resources.helperNamePrefix) && t !== Resources.autocdName && !t.startsWith(Resources.suffixAliasNameStart));
40
+ }
41
+ toLocalPath(value, temporaryFolder) {
42
+ if (!this.isGitBash || !value.startsWith(Resources.posixSeparator))
43
+ return value;
44
+ const temporary = Resources.gitBashTemporaryFolder;
45
+ if (!Object.isNull(temporaryFolder) && path.win32.isAbsolute(temporaryFolder)
46
+ && (value === temporary || value.startsWith(`${temporary}${Resources.posixSeparator}`)))
47
+ return path.win32.join(temporaryFolder, value.slice(temporary.length));
48
+ if (!Resources.gitBashDrivePath.test(value))
49
+ return null;
50
+ return Resources.formatCompletionSourceWindowsDrivePath(value.charAt(1).toUpperCase(), value.slice(Resources.completionSourceGitBashDrivePrefixLength).replaceAll(Resources.posixSeparator, Resources.windowsSeparator));
51
+ }
52
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import "@noldova/context.core";
9
+ import { Resources } from "../resources.js";
10
+ import { PowerShellBinding } from "./powershell-binding.js";
11
+ import { ShellWords } from "./shell-words.js";
12
+ export class PowerShellShellAdapter {
13
+ ignoresCase = true;
14
+ separator;
15
+ takesBareNames = false;
16
+ optionsKeys = Resources.powerShellOptionsKeys;
17
+ looksUpMissing = true;
18
+ binding;
19
+ constructor(isWindows) {
20
+ this.separator = isWindows ? Resources.windowsSeparator : Resources.posixSeparator;
21
+ this.binding = new PowerShellBinding(isWindows);
22
+ }
23
+ readWords(line) {
24
+ return ShellWords.read(line, true);
25
+ }
26
+ writeWord(value, quote, closesQuote, escapesWildcards, keepsHome) {
27
+ return ShellWords.write(value, quote, true, closesQuote, escapesWildcards, keepsHome);
28
+ }
29
+ escapesWildcards(words) {
30
+ return this.binding.bindsWildcardPath(words);
31
+ }
32
+ expandsHome() {
33
+ return true;
34
+ }
35
+ listBuiltins() {
36
+ return Resources.powerShellBuiltins;
37
+ }
38
+ toLocalPath(value) {
39
+ return value;
40
+ }
41
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { Resources } from "../resources.js";
9
+ import { EscapeStripper } from "./escape-stripper.js";
10
+ export class PrintedText {
11
+ stripper = new EscapeStripper();
12
+ line = [];
13
+ column = 0;
14
+ isVisible(data) {
15
+ for (const part of data.split(Resources.printedTextBreaks)) {
16
+ if (part === Resources.carriageReturn) {
17
+ this.column = 0;
18
+ continue;
19
+ }
20
+ if (part === Resources.lineFeed) {
21
+ if (!PrintedText.isBlank(this.line))
22
+ return true;
23
+ this.line = [];
24
+ this.column = 0;
25
+ continue;
26
+ }
27
+ for (const character of this.stripper.strip(part)) {
28
+ this.line[this.column] = character;
29
+ this.column++;
30
+ }
31
+ }
32
+ return !PrintedText.isBlank(this.line) && !PrintedText.isLineEndMark(this.line);
33
+ }
34
+ static isBlank(line) {
35
+ return line.join("").trim().length === 0;
36
+ }
37
+ static isLineEndMark(line) {
38
+ return Resources.lineEndMarks.includes(line.join("").trimEnd());
39
+ }
40
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import "@noldova/context.core";
9
+ import { TerminalShellKind } from "@noldova/terminal.protocol";
10
+ import { Resources } from "../resources.js";
11
+ import { PosixShellAdapter } from "./posix-shell-adapter.js";
12
+ import { PowerShellShellAdapter } from "./powershell-shell-adapter.js";
13
+ export class ShellAdapters {
14
+ adapters;
15
+ constructor(isWindows) {
16
+ this.adapters = new Map([
17
+ [TerminalShellKind.PowerShell, new PowerShellShellAdapter(isWindows)],
18
+ [TerminalShellKind.Bash, new PosixShellAdapter(isWindows, null, true)],
19
+ [TerminalShellKind.Zsh, new PosixShellAdapter(isWindows, Resources.zshOptionsKeys, false)]
20
+ ]);
21
+ }
22
+ of(kind) {
23
+ return this.adapters.get(kind) ?? null;
24
+ }
25
+ }
@@ -10,10 +10,10 @@ import path from "node:path";
10
10
  import { TerminalHistoryPaths } from "../models/terminal-history-paths.js";
11
11
  import { Resources } from "../resources.js";
12
12
  import { FailureText } from "./failure-text.js";
13
+ import { LeftoverFolders } from "./leftover-folders.js";
13
14
  export class TerminalHistoryFolder {
14
15
  writer;
15
- reader;
16
- signaller;
16
+ leftovers;
17
17
  temporaryFolder;
18
18
  pid;
19
19
  log;
@@ -21,8 +21,7 @@ export class TerminalHistoryFolder {
21
21
  folder = null;
22
22
  constructor(writer, reader, signaller, temporaryFolder, pid, log, access = null) {
23
23
  this.writer = writer;
24
- this.reader = reader;
25
- this.signaller = signaller;
24
+ this.leftovers = new LeftoverFolders(reader, signaller, temporaryFolder, pid);
26
25
  this.temporaryFolder = temporaryFolder;
27
26
  this.pid = pid;
28
27
  this.log = log;
@@ -74,11 +73,8 @@ export class TerminalHistoryFolder {
74
73
  return folder;
75
74
  }
76
75
  async removeLeftoversAsync() {
77
- for (const name of await this.reader.readFolderNamesAsync(this.temporaryFolder)) {
78
- const pid = TerminalHistoryFolder.toPid(name);
79
- if (!Object.isNull(pid) && pid !== this.pid && !this.signaller.isRunning(pid))
80
- await this.removeFolderAsync(path.join(this.temporaryFolder, name));
81
- }
76
+ for (const folder of await this.leftovers.findAsync(Resources.terminalHistoryFolderPrefix))
77
+ await this.removeFolderAsync(folder);
82
78
  }
83
79
  async removeFolderAsync(folder) {
84
80
  try {
@@ -88,11 +84,4 @@ export class TerminalHistoryFolder {
88
84
  this.log.write(Resources.formatTerminalHistoryRemovalFailed(folder, FailureText.read(error)));
89
85
  }
90
86
  }
91
- static toPid(name) {
92
- if (!name.startsWith(Resources.terminalHistoryFolderPrefix))
93
- return null;
94
- const match = Resources.terminalHistoryFolderFolderSuffix.exec(name.slice(Resources.terminalHistoryFolderPrefix.length));
95
- const pid = Number(match?.[1]);
96
- return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
97
- }
98
87
  }
@@ -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, 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";
@@ -106,6 +107,8 @@ export class TerminalHost {
106
107
  case TerminalNames.writeMethod:
107
108
  await this.writeAsync(TerminalWriteParams.fromJson(payload), client);
108
109
  return null;
110
+ case TerminalNames.changeFolderMethod:
111
+ return (await this.changeFolderAsync(TerminalChangeFolderParams.fromJson(payload), client)).toJson();
109
112
  case TerminalNames.resizeMethod:
110
113
  this.resize(TerminalResizeParams.fromJson(payload), client);
111
114
  return null;
@@ -312,6 +315,7 @@ export class TerminalHost {
312
315
  this.addCommand(shell.id, t.command);
313
316
  },
314
317
  onOutputStarted: t => publish(this.events.outputStarted, t.toJson()),
318
+ onOutputPrinted: t => publish(this.events.outputPrinted, t.toJson()),
315
319
  onScreenChanged: t => publish(this.events.screenChanged, t.toJson()),
316
320
  onDetached: t => publish(this.events.detached, t.toJson()),
317
321
  onFailed: (id, message) => this.log.write(Resources.formatStartedCommandUnread(id, message)),
@@ -417,9 +421,9 @@ export class TerminalHost {
417
421
  if (t !== TerminalRunOutcome.Typed || !terminal.session.commands.hasMarks || Object.isNull(terminal.session.commands.promptEndOffset) || terminal.keyCount !== 0)
418
422
  this.endLaunchCommand(terminal, null);
419
423
  }).catch((error) => this.log.write(Resources.formatLaunchCommandFailed(terminal.session.sessionId, FailureText.read(error))));
420
- return new TerminalLaunched(terminal.session.sessionId, null);
424
+ return new TerminalLaunched(terminal.session.sessionId, null, terminal.shell.kind);
421
425
  }
422
- async typeCommandAsync(terminal, command, isPaste = false, waitsForFit = false) {
426
+ async typeCommandAsync(terminal, command, isPaste = false, waitsForFit = false, readRefusal = () => null) {
423
427
  const session = terminal.session;
424
428
  const typed = isPaste ? command.replace(Resources.leadingBlankLines, "") : command;
425
429
  const pending = new AbortController();
@@ -451,7 +455,7 @@ export class TerminalHost {
451
455
  const outcome = isEnded() ? TerminalRunOutcome.Ended
452
456
  : isPaste && ((waitsForFit ? terminal.keyCount !== keyCount : terminal.inputCount !== inputCount) || !Object.isNull(session.commands.promptEndOffset) && session.readPromptLine() !== "") ? TerminalRunOutcome.Input
453
457
  : isPaste && !isBracketed && typed.includes(Resources.tabKey) ? TerminalRunOutcome.Tab
454
- : TerminalRunOutcome.Typed;
458
+ : readRefusal() ?? TerminalRunOutcome.Typed;
455
459
  if (outcome === TerminalRunOutcome.Typed) {
456
460
  const text = isPaste ? TerminalHost.toPaste(typed, isBracketed) : `${command}${Resources.enterKey}`;
457
461
  terminal.typedEnds = isBracketed || !isPaste ? 1 : text.split(Resources.enterKey).length - 1;
@@ -858,7 +862,7 @@ export class TerminalHost {
858
862
  async completeAsync(params, client) {
859
863
  const terminal = this.findHosted(params.sessionId, client);
860
864
  const keys = params.asksShell && this.completions.followsCommand(terminal.shell.kind, params.line, params.cursor)
861
- ? Resources.optionsKeys.get(terminal.shell.kind) : undefined;
865
+ ? this.completions.adapterOf(terminal.shell.kind)?.optionsKeys ?? undefined : undefined;
862
866
  const [completion, reply] = await Promise.all([
863
867
  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
868
  Object.isUndefined(keys) ? Promise.resolve(ShellOptionsReply.none) : terminal.session.askOptionsAsync(keys)
@@ -873,7 +877,7 @@ export class TerminalHost {
873
877
  const shellNames = terminal.session.isShellPathReset || terminal.session.isShellModulePathReset ? null
874
878
  : terminal.session.shellNames;
875
879
  const environment = this.readCompletionEnvironment(terminal);
876
- return terminal.shell.kind === TerminalShellKind.PowerShell
880
+ return this.completions.adapterOf(terminal.shell.kind)?.looksUpMissing === true
877
881
  ? this.completions.findMissingPowerShellAsync(terminal.session.commands, terminal.shell.file, params.names, shellNames, environment)
878
882
  : this.completions.findMissingAsync(params.sessionId, terminal.session.commands, terminal.session.prompts, terminal.shell.kind, terminal.session.cwd ?? terminal.folder, params.names, shellNames, environment);
879
883
  }
@@ -994,6 +998,40 @@ export class TerminalHost {
994
998
  terminal.recordInput(false, written, true);
995
999
  session.write(written);
996
1000
  }
1001
+ async changeFolderAsync(params, client) {
1002
+ const terminal = this.findHosted(params.sessionId, client);
1003
+ const session = terminal.session;
1004
+ const line = FolderChangeLine.format(terminal.shell.kind, params.folder);
1005
+ if (Object.isNull(line) || !session.hasIntegration)
1006
+ return new TerminalFolderChanged(null, false);
1007
+ if (!this.isAbsolute(params.folder))
1008
+ throw new ArgumentException(ProtocolResources.formatNotAbsolutePath(ProtocolResources.valueSubject), Resources.folderParameter);
1009
+ if (!await this.fileSystem.isFolderAsync(params.folder))
1010
+ return new TerminalFolderChanged(null, true);
1011
+ if (!Object.isNull(terminal.pendingCommand) || !Object.isNull(session.commands.runningCommand))
1012
+ return new TerminalFolderChanged(null, true, TerminalRunOutcome.Busy);
1013
+ const outcome = await this.typeCommandAsync(terminal, line, false, false, () => TerminalHost.readMoveRefusal(terminal));
1014
+ if (outcome === TerminalRunOutcome.NoShell)
1015
+ return new TerminalFolderChanged(null, false);
1016
+ if (outcome === TerminalRunOutcome.Busy || outcome === TerminalRunOutcome.Input)
1017
+ return new TerminalFolderChanged(null, true, outcome);
1018
+ if (outcome !== TerminalRunOutcome.Typed)
1019
+ throw new SessionNotFoundException(params.sessionId);
1020
+ const typedAt = session.text.endOffset;
1021
+ const isMoved = () => (session.commands.promptEndOffset ?? typedAt) > typedAt;
1022
+ await session.changes.waitUntilAsync(() => session.hasExited || this.sessions.get(params.sessionId) !== terminal || isMoved(), Resources.folderChangeWaitMilliseconds, new AbortController().signal);
1023
+ if (session.hasExited || this.sessions.get(params.sessionId) !== terminal)
1024
+ throw new SessionNotFoundException(params.sessionId);
1025
+ return new TerminalFolderChanged(isMoved() && session.commands.lastCommand?.exitCode === 0 ? session.cwd : null, true);
1026
+ }
1027
+ static readMoveRefusal(terminal) {
1028
+ const commands = terminal.session.commands;
1029
+ if (!commands.hasMarks)
1030
+ return TerminalRunOutcome.NoShell;
1031
+ if (Object.isNull(commands.promptEndOffset))
1032
+ return TerminalRunOutcome.Busy;
1033
+ return terminal.hasUnreadInput || terminal.session.readPromptLine() !== "" ? TerminalRunOutcome.Input : null;
1034
+ }
997
1035
  resize(params, client) {
998
1036
  const terminal = this.findHosted(params.sessionId, client);
999
1037
  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;
@@ -238,6 +240,7 @@ export class TerminalSession {
238
240
  this.replacePromptLine(null);
239
241
  this.typedLines.clear();
240
242
  this.reportedCwd = null;
243
+ this.printing = null;
241
244
  this.exit = null;
242
245
  this.isClosing = false;
243
246
  this.size = size;
@@ -274,6 +277,7 @@ export class TerminalSession {
274
277
  for (const mark of marks) {
275
278
  const end = mark.offset - this.receivedOffset;
276
279
  this.text.append(data.slice(position, end));
280
+ this.watchPrinting(data.slice(position, end));
277
281
  position = end;
278
282
  const edge = this.readInputEdge(mark);
279
283
  if (mark.kind === MarkKind.PromptStart || !Object.isNull(edge)) {
@@ -296,11 +300,19 @@ export class TerminalSession {
296
300
  }
297
301
  this.mirror.write(data.slice(mirrored));
298
302
  this.text.append(data.slice(position));
303
+ this.watchPrinting(data.slice(position));
299
304
  this.wakeup?.receive(data);
300
305
  this.receivedOffset += data.length;
301
306
  this.changes.notify();
302
307
  }
308
+ watchPrinting(data) {
309
+ if (Object.isNull(this.printing) || !this.printing.isVisible(data))
310
+ return;
311
+ this.printing = null;
312
+ this.listener.onOutputPrinted(new TerminalReference(this.sessionId));
313
+ }
303
314
  startOutput(mark, offset) {
315
+ this.printing = new PrintedText();
304
316
  const enteredAt = Math.max(this.enteredAt ?? Date.now(), this.idleAt);
305
317
  this.enteredAt = null;
306
318
  this.listener.onOutputStarted(new TerminalCommandStart(this.sessionId, offset, enteredAt, TerminalSession.toCommand(mark.value)));
@@ -335,6 +347,8 @@ export class TerminalSession {
335
347
  this.isPromptNew = false;
336
348
  this.commands.apply(mark);
337
349
  this.settleTypedLines(mark);
350
+ if (mark.kind === MarkKind.CommandEnd || mark.kind === MarkKind.PromptStart)
351
+ this.printing = null;
338
352
  if (mark.kind === MarkKind.CommandEnd) {
339
353
  const exitCode = this.commands.lastCommand?.exitCode ?? null;
340
354
  this.listener.onCommandEnded(new TerminalCommandEnded(this.sessionId, !Object.isNull(exitCode) && exitCode >= ProtocolResources.minimumExitCode && exitCode <= ProtocolResources.maximumExitCode ? exitCode : null));
@@ -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];