@noldova/terminal 0.0.2 → 0.0.3

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,12 +1,12 @@
1
1
  {
2
2
  "id": "terminal",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
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.1 <0.1.0",
9
+ "noldovaDesktop": ">=0.0.6 <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",
@@ -21,7 +21,7 @@
21
21
  ],
22
22
  "commands": ["terminal.new", "terminal.newWithShell", "terminal.toggle", "terminal.restartShell"],
23
23
  "menus": ["terminal.tabRow", "terminal.shellMenu"],
24
- "settings": ["terminal.defaultShell", "terminal.outputLimit", "terminal.fontSize", "terminal.suggestions", "terminal.commandColors", "terminal.completionList"],
24
+ "settings": ["terminal.defaultShell", "terminal.outputLimit", "terminal.fontSize", "terminal.suggestions", "terminal.commandColors", "terminal.completionList", "terminal.linkClick"],
25
25
  "views": ["terminal.panel", "terminal.session"],
26
26
  "tools": ["terminal_list", "terminal_read", "terminal_open", "terminal_run", "terminal_write", "terminal_interrupt", "terminal_close"]
27
27
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noldova/terminal",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
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",
@@ -36,17 +36,17 @@
36
36
  "registry": "https://registry.npmjs.org/"
37
37
  },
38
38
  "dependencies": {
39
- "@noldova/terminal.protocol": "0.0.2",
40
- "@noldova/terminal.window": "0.0.2",
39
+ "@noldova/terminal.protocol": "0.0.3",
40
+ "@noldova/terminal.window": "0.0.3",
41
41
  "@xterm/addon-serialize": "0.14.0",
42
42
  "@xterm/headless": "6.0.0",
43
43
  "node-pty": "1.2.0-beta.15"
44
44
  },
45
45
  "peerDependencies": {
46
- "@noldova/desktop.protocol": ">=0.0.1 <0.1.0",
47
- "@noldova/desktop.runtime": ">=0.0.1 <0.1.0",
46
+ "@noldova/desktop.protocol": ">=0.0.6 <0.1.0",
47
+ "@noldova/desktop.runtime": ">=0.0.6 <0.1.0",
48
48
  "@noldova/context.exceptions": ">=0.0.7 <0.1.0",
49
49
  "@noldova/context.json": ">=0.0.7 <0.1.0"
50
50
  },
51
- "gitHead": "316039e0b0bb4b5b351742560f9053dd72d7c1eb"
51
+ "gitHead": "4e9c842efd7a190f6e6e9174addca3606d2bb424"
52
52
  }
package/settings.json CHANGED
@@ -78,6 +78,23 @@
78
78
  "scopes": [],
79
79
  "page": "Terminal",
80
80
  "group": "Terminal"
81
+ },
82
+ {
83
+ "name": "terminal.linkClick",
84
+ "title": "Open clicked links",
85
+ "description": "Where a link you Ctrl+click in a terminal opens, Cmd+click on macOS. Sign-in links that tools print need your own browser, where you're signed in.",
86
+ "type": {
87
+ "kind": "Choice",
88
+ "options": [
89
+ { "value": "System", "title": "In your browser" },
90
+ { "value": "InApp", "title": "In the app's browser" }
91
+ ]
92
+ },
93
+ "default": "System",
94
+ "locality": "Shared",
95
+ "scopes": [],
96
+ "page": "Terminal",
97
+ "group": "Terminal"
81
98
  }
82
99
  ]
83
100
  }
@@ -0,0 +1,15 @@
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
+ export class CommandRun {
9
+ answer;
10
+ ended;
11
+ constructor(answer, ended) {
12
+ this.answer = answer;
13
+ this.ended = ended;
14
+ }
15
+ }
package/src/resources.js CHANGED
@@ -21,6 +21,7 @@ export class Resources {
21
21
  static echoSettleMilliseconds = 1_000;
22
22
  static runInterruptWaitMilliseconds = 2_000;
23
23
  static foregroundPollMilliseconds = 50;
24
+ static cursorAnswerMilliseconds = 500;
24
25
  static maximumKeptRuns = 100;
25
26
  static scrollback = 1_000;
26
27
  static terminalHistoryFlags = "w+";
@@ -82,6 +83,7 @@ export class Resources {
82
83
  static agentColumns = 120;
83
84
  static agentRows = 30;
84
85
  static integrationWaitMilliseconds = 10_000;
86
+ static paneFitWaitMilliseconds = 10_000;
85
87
  static shellStartMilliseconds = 60_000;
86
88
  static maximumExitedSessions = 32;
87
89
  static restartReset = "\u001b[?1047l\u001b[!p\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?2004l\r";
@@ -96,6 +98,8 @@ export class Resources {
96
98
  static lineBreaks = /\r\n|\r|\n/u;
97
99
  static escapesOnly = /^(?:\u001b\[[0-9;?]*[A-Za-z])*(?:\u001b(?:\[[0-9;?]*)?)?$/u;
98
100
  static resizeStall = /^(?:\u001b\[[0-9;?]*[A-Za-z])*\u001b\[6n\u001b\[\d+;\d+H$/u;
101
+ static cursorRequest = "\u001b[6n";
102
+ static cursorAnswers = /\u001b\[\d+;\d+R/gu;
99
103
  static whiteSpace = /\s+/gu;
100
104
  static controlCharacters = /[\u0000-\u001f\u007f-\u009f]/gu;
101
105
  static controlReplacement = "?";
@@ -294,7 +298,10 @@ export class Resources {
294
298
  [TerminalShellKind.Zsh, "\u001b[24;7~"]
295
299
  ]);
296
300
  static optionsMilliseconds = 500;
301
+ static firstOptionsMilliseconds = 2_000;
297
302
  static powerShellLookupMilliseconds = 10_000;
303
+ static powerShellLookupEndMilliseconds = 60_000;
304
+ static powerShellLookupCacheMilliseconds = 15_000;
298
305
  static powerShellLookupPathReset = "the session's PATH was reset";
299
306
  static powerShellLookupModulePathReset = "the session's PSModulePath was reset";
300
307
  static powerShellLookupNamesTooLong = "the shell's last list of its names was too long to send";
@@ -533,6 +540,9 @@ for ($index = 0; $index -lt $names.Count; $index++) {
533
540
  $index
534
541
  }
535
542
  }
543
+ if (((Get-Date) - [Diagnostics.Process]::GetCurrentProcess().StartTime).TotalMilliseconds -ge ${Resources.powerShellLookupMilliseconds}) {
544
+ Start-Sleep -Milliseconds ${Resources.powerShellLookupCacheMilliseconds}
545
+ }
536
546
  exit 0
537
547
  `;
538
548
  }
@@ -69,7 +69,7 @@ export class AgentTerminal {
69
69
  const received = this.hosted.inputReceivedLength;
70
70
  if (received === null || !this.hosted.hasRecentInput)
71
71
  return false;
72
- return !this.hasShellIntegration || this.session.receivedLength <= received;
72
+ return !this.hasShellIntegration || this.hosted.hasUnreadInput;
73
73
  }
74
74
  get session() {
75
75
  return this.hosted.session;
@@ -11,6 +11,7 @@ import { CommandExitedException } from "../exceptions/command-exited.exception.j
11
11
  import { CommandNotStartedException } from "../exceptions/command-not-started.exception.js";
12
12
  import { CommandOutputTooLongException } from "../exceptions/command-output-too-long.exception.js";
13
13
  import { CommandTimedOutException } from "../exceptions/command-timed-out.exception.js";
14
+ import { CommandRun } from "../models/command-run.js";
14
15
  import { Resources } from "../resources.js";
15
16
  export class CommandRunner {
16
17
  context;
@@ -18,50 +19,58 @@ export class CommandRunner {
18
19
  this.context = context;
19
20
  }
20
21
  async runAsync(file, args, timeoutMilliseconds, environment = {}) {
22
+ return await this.start(file, args, timeoutMilliseconds, timeoutMilliseconds, environment).answer;
23
+ }
24
+ start(file, args, timeoutMilliseconds, endMilliseconds, environment = {}) {
21
25
  const name = path.basename(file);
22
26
  const stopping = new AbortController();
23
27
  const request = new ProcessRequest(file, [...args], path.dirname(file), environment, [], stopping.signal);
24
- let isTooLong = false;
25
- const timer = setTimeout(() => stopping.abort(), timeoutMilliseconds);
28
+ const answer = Promise.withResolvers();
29
+ const late = setTimeout(() => answer.reject(new CommandTimedOutException(name, timeoutMilliseconds)), timeoutMilliseconds);
30
+ const ending = setTimeout(() => stopping.abort(), Math.max(timeoutMilliseconds, endMilliseconds));
31
+ const stopTimers = () => {
32
+ clearTimeout(late);
33
+ clearTimeout(ending);
34
+ };
35
+ const ended = this.readAsync(name, request, stopping, timeoutMilliseconds, stopTimers).then(answer.resolve, answer.reject).finally(stopTimers);
36
+ return new CommandRun(answer.promise, ended);
37
+ }
38
+ async readAsync(name, request, stopping, timeoutMilliseconds, exited) {
39
+ let process;
26
40
  try {
27
- let process;
28
- try {
29
- process = await this.context.startProcessAsync(request);
30
- }
31
- catch (error) {
32
- if (stopping.signal.aborted && error === stopping.signal.reason)
33
- throw new CommandTimedOutException(name, timeoutMilliseconds);
34
- if (!(error instanceof ProcessStartException))
35
- throw error;
36
- throw new CommandNotStartedException(name, error);
37
- }
38
- let output = "";
39
- process.output.setEncoding(Resources.utf8Encoding);
40
- process.output.on(Resources.dataEvent, (text) => {
41
- output += text;
42
- if (output.length > Resources.maximumCommandOutputLength) {
43
- isTooLong = true;
44
- stopping.abort();
45
- }
46
- });
47
- let errors = "";
48
- process.errors.setEncoding(Resources.utf8Encoding);
49
- process.errors.on(Resources.dataEvent, (text) => {
50
- errors = (errors + text).slice(-Resources.maximumCommandErrorLength);
51
- });
52
- const closed = new Promise(resolve => process.output.once(Resources.closeEvent, () => resolve()));
53
- const errorsClosed = new Promise(resolve => process.errors.once(Resources.closeEvent, () => resolve()));
54
- const [exit] = await Promise.all([process.exited.finally(() => clearTimeout(timer)), closed, errorsClosed]);
55
- if (isTooLong)
56
- throw new CommandOutputTooLongException(name, Resources.maximumCommandOutputLength);
57
- if (stopping.signal.aborted)
58
- throw new CommandTimedOutException(name, timeoutMilliseconds);
59
- if (exit.code !== 0)
60
- throw new CommandExitedException(name, exit, errors);
61
- return output;
41
+ process = await this.context.startProcessAsync(request);
62
42
  }
63
- finally {
64
- clearTimeout(timer);
43
+ catch (error) {
44
+ if (stopping.signal.aborted && error === stopping.signal.reason)
45
+ throw new CommandTimedOutException(name, timeoutMilliseconds);
46
+ if (!(error instanceof ProcessStartException))
47
+ throw error;
48
+ throw new CommandNotStartedException(name, error);
65
49
  }
50
+ let isTooLong = false;
51
+ let output = "";
52
+ process.output.setEncoding(Resources.utf8Encoding);
53
+ process.output.on(Resources.dataEvent, (text) => {
54
+ output += text;
55
+ if (output.length > Resources.maximumCommandOutputLength) {
56
+ isTooLong = true;
57
+ stopping.abort();
58
+ }
59
+ });
60
+ let errors = "";
61
+ process.errors.setEncoding(Resources.utf8Encoding);
62
+ process.errors.on(Resources.dataEvent, (text) => {
63
+ errors = (errors + text).slice(-Resources.maximumCommandErrorLength);
64
+ });
65
+ const closed = new Promise(resolve => process.output.once(Resources.closeEvent, () => resolve()));
66
+ const errorsClosed = new Promise(resolve => process.errors.once(Resources.closeEvent, () => resolve()));
67
+ const [exit] = await Promise.all([process.exited.finally(exited), closed, errorsClosed]);
68
+ if (isTooLong)
69
+ throw new CommandOutputTooLongException(name, Resources.maximumCommandOutputLength);
70
+ if (stopping.signal.aborted)
71
+ throw new CommandTimedOutException(name, timeoutMilliseconds);
72
+ if (exit.code !== 0)
73
+ throw new CommandExitedException(name, exit, errors);
74
+ return output;
66
75
  }
67
76
  }
@@ -30,6 +30,7 @@ export class CompletionSource {
30
30
  looked = new WeakMap();
31
31
  skipped = new WeakMap();
32
32
  failing = new WeakSet();
33
+ lookups = new WeakMap();
33
34
  log;
34
35
  constructor(fileSystem, runner, platform, homeFolder, log) {
35
36
  this.runner = runner;
@@ -109,10 +110,13 @@ export class CompletionSource {
109
110
  const asked = [...new Set(names)].filter(t => !this.isPath(t) && Resources.powerShellLookupNamePattern.test(t)
110
111
  && !known.has(t.toLowerCase()) && !known.has(`${Resources.powerShellImplicitVerb}${t}`.toLowerCase()));
111
112
  const unasked = asked.filter(t => !answers.has(t));
112
- if (unasked.length > 0) {
113
+ if (unasked.length > 0 && !this.lookups.has(shell)) {
114
+ const run = this.runner.start(program, [...Resources.environmentReadArguments,
115
+ Buffer.from(Resources.formatPowerShellLookupScript(unasked), Resources.utf16Encoding).toString(Resources.base64Encoding)], Resources.powerShellLookupMilliseconds, Resources.powerShellLookupEndMilliseconds, variables);
116
+ this.lookups.set(shell, run);
117
+ void run.ended.then(() => this.lookups.delete(shell));
113
118
  try {
114
- const output = await this.runner.runAsync(program, [...Resources.environmentReadArguments,
115
- Buffer.from(Resources.formatPowerShellLookupScript(unasked), Resources.utf16Encoding).toString(Resources.base64Encoding)], Resources.powerShellLookupMilliseconds, variables);
119
+ const output = await run.answer;
116
120
  const missing = new Set(output.split(Resources.lineBreaks).map(t => t.trim()));
117
121
  for (const [index, name] of unasked.entries())
118
122
  answers.set(name, missing.has(String(index)));
@@ -5,17 +5,29 @@
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
+ import { Resources } from "../resources.js";
8
9
  export class PseudoTerminal {
9
10
  process;
10
11
  listener;
12
+ isConPty;
13
+ heldKeys = [];
11
14
  hasExited = false;
12
15
  isEnding = false;
13
- constructor(process, listener) {
16
+ openRequests = 0;
17
+ outputEnd = "";
18
+ answerLimit = undefined;
19
+ constructor(process, listener, isConPty = false) {
14
20
  this.process = process;
15
21
  this.listener = listener;
16
- this.process.onData(t => this.listener.onData(t));
22
+ this.isConPty = isConPty;
23
+ this.process.onData(t => {
24
+ if (this.isConPty)
25
+ this.watchCursorRequests(t);
26
+ this.listener.onData(t);
27
+ });
17
28
  this.process.onExit(t => {
18
29
  this.hasExited = true;
30
+ this.releaseKeys();
19
31
  if (!this.isEnding)
20
32
  void this.endAsync();
21
33
  this.listener.onExit(PseudoTerminal.toExitCode(t));
@@ -25,8 +37,22 @@ export class PseudoTerminal {
25
37
  return this.process.pid;
26
38
  }
27
39
  write(data) {
28
- if (!this.hasExited)
40
+ if (this.hasExited)
41
+ return;
42
+ if (this.openRequests === 0)
29
43
  this.process.write(data);
44
+ else
45
+ this.heldKeys.push(data);
46
+ }
47
+ answer(data) {
48
+ if (this.hasExited)
49
+ return;
50
+ this.process.write(data);
51
+ if (this.openRequests === 0)
52
+ return;
53
+ this.openRequests = Math.max(0, this.openRequests - (data.match(Resources.cursorAnswers) ?? []).length);
54
+ if (this.openRequests === 0)
55
+ this.releaseKeys();
30
56
  }
31
57
  resize(size) {
32
58
  if (!this.hasExited)
@@ -48,6 +74,23 @@ export class PseudoTerminal {
48
74
  this.resume();
49
75
  return this.process.endAsync();
50
76
  }
77
+ watchCursorRequests(data) {
78
+ const text = this.outputEnd + data;
79
+ const requests = text.split(Resources.cursorRequest).length - 1;
80
+ this.outputEnd = text.slice(1 - Resources.cursorRequest.length);
81
+ if (requests === 0)
82
+ return;
83
+ clearTimeout(this.answerLimit);
84
+ this.answerLimit = setTimeout(() => this.releaseKeys(), Resources.cursorAnswerMilliseconds);
85
+ this.openRequests += requests;
86
+ }
87
+ releaseKeys() {
88
+ clearTimeout(this.answerLimit);
89
+ this.answerLimit = undefined;
90
+ this.openRequests = 0;
91
+ for (const key of this.heldKeys.splice(0))
92
+ this.write(key);
93
+ }
51
94
  static toExitCode(event) {
52
95
  return event.signal === undefined || event.signal === 0 ? event.exitCode ?? null : null;
53
96
  }
@@ -368,8 +368,11 @@ export class TerminalHost {
368
368
  const signal = pending.signal;
369
369
  const inputCount = terminal.inputCount;
370
370
  const keyCount = terminal.keyCount;
371
- if (waitsForFit)
372
- await session.changes.waitUntilAsync(() => session.hasExited || terminal.isSized || terminal.deferredShell?.hasStarted !== false, null, signal);
371
+ if (waitsForFit) {
372
+ await session.changes.waitUntilAsync(() => session.hasExited || terminal.isSized || terminal.deferredShell?.hasStarted !== false, Resources.paneFitWaitMilliseconds, signal);
373
+ if (!signal.aborted && this.sessions.get(session.sessionId) === terminal)
374
+ this.startShell(terminal);
375
+ }
373
376
  const startedAt = Date.now();
374
377
  const isReady = () => session.hasIntegration ? session.commands.promptEndOffset !== null : session.receivedLength > 0;
375
378
  const isStarted = () => session.hasExited || isReady() || session.commands.isLoaded;
@@ -43,6 +43,7 @@ export class TerminalSession {
43
43
  typedLines = new Set();
44
44
  options = new ShellOptionsQueue();
45
45
  isPromptNew = false;
46
+ hasAnsweredOptions = false;
46
47
  disposal = new AbortController();
47
48
  sessionId;
48
49
  shellId;
@@ -68,7 +69,7 @@ export class TerminalSession {
68
69
  });
69
70
  this.history = new TerminalHistory(historyPaths, storedLimit, () => this.flow.acknowledgeStoring(this.history.backlog));
70
71
  this.mirror = new TerminalMirror(size, this.history, {
71
- onReply: t => this.terminal.write(t),
72
+ onReply: t => this.terminal.answer(t),
72
73
  onParsed: t => this.flow.acknowledgeMirror(t, this.history.backlog),
73
74
  onTitleChanged: t => this.listener.onTitleChanged(new TerminalTitle(this.sessionId, t))
74
75
  });
@@ -151,7 +152,8 @@ export class TerminalSession {
151
152
  if (!this.hasIntegration || !this.commands.hasOptionsBinding || !this.commands.isWaitingAtPrompt || this.commands.runningCommand !== null
152
153
  || this.exit !== null)
153
154
  return ShellOptionsReply.none;
154
- const reply = this.options.askAsync(Resources.optionsMilliseconds);
155
+ const reply = this.options.askAsync(this.hasAnsweredOptions ? Resources.optionsMilliseconds
156
+ : Resources.firstOptionsMilliseconds);
155
157
  this.wakeup?.beforeInput();
156
158
  this.terminal.write(keys);
157
159
  const answered = await reply;
@@ -218,6 +220,7 @@ export class TerminalSession {
218
220
  this.hasIntegration = nonce !== null;
219
221
  this.commands = this.trackCommands();
220
222
  this.options.reset();
223
+ this.hasAnsweredOptions = false;
221
224
  this.isPromptNew = false;
222
225
  this.replacePromptLine(null);
223
226
  this.typedLines.clear();
@@ -298,8 +301,10 @@ export class TerminalSession {
298
301
  this.changes.notify();
299
302
  }
300
303
  applyMark(mark) {
301
- if (mark.kind === MarkKind.Options)
304
+ if (mark.kind === MarkKind.Options) {
305
+ this.hasAnsweredOptions = true;
302
306
  this.options.answer(mark.values);
307
+ }
303
308
  else if (mark.kind === MarkKind.OutputStart || mark.kind === MarkKind.PromptStart && this.isPromptNew)
304
309
  this.options.reset();
305
310
  if (mark.kind === MarkKind.CommandEnd || mark.kind === MarkKind.Property)
@@ -342,7 +347,7 @@ export class TerminalSession {
342
347
  if (this.terminal === terminal)
343
348
  this.end(t);
344
349
  }
345
- });
350
+ }, this.windowsPty !== null);
346
351
  return terminal;
347
352
  }
348
353
  end(exitCode) {