@celljs/ta-exec 4.6.1 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.en.md +43 -0
  2. package/README.md +5 -1
  3. package/esm/node/exec-client.d.ts +28 -11
  4. package/esm/node/exec-client.js +89 -33
  5. package/esm/node/exec-client.js.map +1 -1
  6. package/esm/node/exec-peer.d.ts +40 -0
  7. package/esm/node/exec-peer.js +167 -0
  8. package/esm/node/exec-peer.js.map +1 -0
  9. package/esm/node/exec-protocol.d.ts +19 -1
  10. package/esm/node/exec-remote-source.d.ts +5 -0
  11. package/esm/node/exec-remote-source.js +9 -0
  12. package/esm/node/exec-remote-source.js.map +1 -0
  13. package/esm/node/exec-rpc.d.ts +21 -3
  14. package/esm/node/exec-rpc.js +14 -3
  15. package/esm/node/exec-rpc.js.map +1 -1
  16. package/esm/node/exec-server.d.ts +2 -26
  17. package/esm/node/exec-server.js +3 -132
  18. package/esm/node/exec-server.js.map +1 -1
  19. package/esm/node/exec-stdio.d.ts +27 -0
  20. package/esm/node/exec-stdio.js +60 -0
  21. package/esm/node/exec-stdio.js.map +1 -0
  22. package/esm/node/index.d.ts +8 -0
  23. package/esm/node/index.js +8 -0
  24. package/esm/node/index.js.map +1 -1
  25. package/esm/node/local-exec-environment.d.ts +2 -2
  26. package/esm/node/local-exec-environment.js +11 -11
  27. package/esm/node/local-exec-environment.js.map +1 -1
  28. package/esm/node/remote-exec-environment.d.ts +3 -2
  29. package/esm/node/remote-exec-environment.js +41 -2
  30. package/esm/node/remote-exec-environment.js.map +1 -1
  31. package/esm/node/ssh/node-dist.d.ts +20 -0
  32. package/esm/node/ssh/node-dist.js +77 -0
  33. package/esm/node/ssh/node-dist.js.map +1 -0
  34. package/esm/node/ssh/ssh-askpass.d.ts +24 -0
  35. package/esm/node/ssh/ssh-askpass.js +112 -0
  36. package/esm/node/ssh/ssh-askpass.js.map +1 -0
  37. package/esm/node/ssh/ssh-config.d.ts +20 -0
  38. package/esm/node/ssh/ssh-config.js +127 -0
  39. package/esm/node/ssh/ssh-config.js.map +1 -0
  40. package/esm/node/ssh/ssh-host.d.ts +73 -0
  41. package/esm/node/ssh/ssh-host.js +258 -0
  42. package/esm/node/ssh/ssh-host.js.map +1 -0
  43. package/esm/node/ssh/ssh-util.d.ts +45 -0
  44. package/esm/node/ssh/ssh-util.js +110 -0
  45. package/esm/node/ssh/ssh-util.js.map +1 -0
  46. package/lib/node/exec-client.d.ts +28 -11
  47. package/lib/node/exec-client.d.ts.map +1 -1
  48. package/lib/node/exec-client.js +89 -33
  49. package/lib/node/exec-client.js.map +1 -1
  50. package/lib/node/exec-peer.d.ts +41 -0
  51. package/lib/node/exec-peer.d.ts.map +1 -0
  52. package/lib/node/exec-peer.js +171 -0
  53. package/lib/node/exec-peer.js.map +1 -0
  54. package/lib/node/exec-protocol.d.ts +19 -1
  55. package/lib/node/exec-protocol.d.ts.map +1 -1
  56. package/lib/node/exec-remote-source.d.ts +6 -0
  57. package/lib/node/exec-remote-source.d.ts.map +1 -0
  58. package/lib/node/exec-remote-source.js +10 -0
  59. package/lib/node/exec-remote-source.js.map +1 -0
  60. package/lib/node/exec-rpc.d.ts +21 -3
  61. package/lib/node/exec-rpc.d.ts.map +1 -1
  62. package/lib/node/exec-rpc.js +14 -3
  63. package/lib/node/exec-rpc.js.map +1 -1
  64. package/lib/node/exec-server.d.ts +2 -26
  65. package/lib/node/exec-server.d.ts.map +1 -1
  66. package/lib/node/exec-server.js +4 -134
  67. package/lib/node/exec-server.js.map +1 -1
  68. package/lib/node/exec-server.spec.js +4 -1
  69. package/lib/node/exec-server.spec.js.map +1 -1
  70. package/lib/node/exec-stdio.d.ts +28 -0
  71. package/lib/node/exec-stdio.d.ts.map +1 -0
  72. package/lib/node/exec-stdio.js +64 -0
  73. package/lib/node/exec-stdio.js.map +1 -0
  74. package/lib/node/exec-stdio.spec.d.ts +2 -0
  75. package/lib/node/exec-stdio.spec.d.ts.map +1 -0
  76. package/lib/node/exec-stdio.spec.js +106 -0
  77. package/lib/node/exec-stdio.spec.js.map +1 -0
  78. package/lib/node/index.d.ts +8 -0
  79. package/lib/node/index.d.ts.map +1 -1
  80. package/lib/node/index.js +8 -0
  81. package/lib/node/index.js.map +1 -1
  82. package/lib/node/local-exec-environment.d.ts +2 -2
  83. package/lib/node/local-exec-environment.d.ts.map +1 -1
  84. package/lib/node/local-exec-environment.js +10 -10
  85. package/lib/node/local-exec-environment.js.map +1 -1
  86. package/lib/node/local-exec-environment.spec.js +2 -0
  87. package/lib/node/local-exec-environment.spec.js.map +1 -1
  88. package/lib/node/remote-exec-environment.d.ts +3 -2
  89. package/lib/node/remote-exec-environment.d.ts.map +1 -1
  90. package/lib/node/remote-exec-environment.js +41 -2
  91. package/lib/node/remote-exec-environment.js.map +1 -1
  92. package/lib/node/ssh/node-dist.d.ts +21 -0
  93. package/lib/node/ssh/node-dist.d.ts.map +1 -0
  94. package/lib/node/ssh/node-dist.js +80 -0
  95. package/lib/node/ssh/node-dist.js.map +1 -0
  96. package/lib/node/ssh/ssh-askpass.d.ts +25 -0
  97. package/lib/node/ssh/ssh-askpass.d.ts.map +1 -0
  98. package/lib/node/ssh/ssh-askpass.js +114 -0
  99. package/lib/node/ssh/ssh-askpass.js.map +1 -0
  100. package/lib/node/ssh/ssh-config.d.ts +21 -0
  101. package/lib/node/ssh/ssh-config.d.ts.map +1 -0
  102. package/lib/node/ssh/ssh-config.js +130 -0
  103. package/lib/node/ssh/ssh-config.js.map +1 -0
  104. package/lib/node/ssh/ssh-host.d.ts +74 -0
  105. package/lib/node/ssh/ssh-host.d.ts.map +1 -0
  106. package/lib/node/ssh/ssh-host.js +262 -0
  107. package/lib/node/ssh/ssh-host.js.map +1 -0
  108. package/lib/node/ssh/ssh-host.spec.d.ts +2 -0
  109. package/lib/node/ssh/ssh-host.spec.d.ts.map +1 -0
  110. package/lib/node/ssh/ssh-host.spec.js +182 -0
  111. package/lib/node/ssh/ssh-host.spec.js.map +1 -0
  112. package/lib/node/ssh/ssh-util.d.ts +46 -0
  113. package/lib/node/ssh/ssh-util.d.ts.map +1 -0
  114. package/lib/node/ssh/ssh-util.js +113 -0
  115. package/lib/node/ssh/ssh-util.js.map +1 -0
  116. package/lib/node/ssh/ssh-util.spec.d.ts +2 -0
  117. package/lib/node/ssh/ssh-util.spec.d.ts.map +1 -0
  118. package/lib/node/ssh/ssh-util.spec.js +87 -0
  119. package/lib/node/ssh/ssh-util.spec.js.map +1 -0
  120. package/package.json +3 -3
  121. package/src/node/exec-client.ts +108 -39
  122. package/src/node/exec-peer.ts +186 -0
  123. package/src/node/exec-protocol.ts +21 -1
  124. package/src/node/exec-remote-source.ts +7 -0
  125. package/src/node/exec-rpc.ts +23 -3
  126. package/src/node/exec-server.spec.ts +4 -1
  127. package/src/node/exec-server.ts +4 -140
  128. package/src/node/exec-stdio.spec.ts +108 -0
  129. package/src/node/exec-stdio.ts +75 -0
  130. package/src/node/index.ts +8 -0
  131. package/src/node/local-exec-environment.spec.ts +2 -0
  132. package/src/node/local-exec-environment.ts +11 -10
  133. package/src/node/remote-exec-environment.ts +41 -3
  134. package/src/node/ssh/node-dist.ts +83 -0
  135. package/src/node/ssh/ssh-askpass.ts +117 -0
  136. package/src/node/ssh/ssh-config.ts +128 -0
  137. package/src/node/ssh/ssh-host.spec.ts +189 -0
  138. package/src/node/ssh/ssh-host.ts +300 -0
  139. package/src/node/ssh/ssh-util.spec.ts +97 -0
  140. package/src/node/ssh/ssh-util.ts +127 -0
@@ -1,11 +1,21 @@
1
1
  import { ExecRpc } from './exec-rpc';
2
2
 
3
+ /** One connection to `ta exec-server`, whatever carries it: a WebSocket, or ssh (SshHost). */
4
+ export interface ExecConnection {
5
+ send(text: string): void;
6
+ close(): void;
7
+ onMessage(listener: (text: string) => void): void;
8
+ /** Once, with what went wrong when it was not closed on purpose. */
9
+ onClose(listener: (reason?: string) => void): void;
10
+ }
11
+
3
12
  export interface ExecClientOptions {
4
- /** The WebSocket URL of `ta exec-server`. */
5
- url: string;
6
- token: string;
13
+ /** Opens a connection; rejects with an ExecError when it cannot. See {@link ExecClient.webSocket}. */
14
+ connect(): Promise<ExecConnection>;
7
15
  /** Larger than the epoch of any host that ran these sessions before; see {@link ExecRpc.InitializeParams}. */
8
16
  epoch: number;
17
+ /** Pings this often (milliseconds) while connected, for a server that ends without them (over stdio). */
18
+ pingMs?: number;
9
19
  }
10
20
 
11
21
  /** A failed call to `ta exec-server`. */
@@ -32,20 +42,49 @@ interface PendingCall {
32
42
  * host with a newer epoch it refuses every call: this host must stop running sessions there.
33
43
  */
34
44
  export class ExecClient {
35
- protected socket?: Promise<WebSocket>;
36
- protected current?: WebSocket;
45
+ protected connection?: Promise<ExecConnection>;
46
+ protected current?: ExecConnection;
37
47
  protected nextCall = 0;
38
48
  protected nextProcess = 0;
39
49
  protected fenced = false;
50
+ protected pinger?: ReturnType<typeof setInterval>;
40
51
  protected initialized?: ExecRpc.InitializeResult;
41
52
  protected readonly pending = new Map<number, PendingCall>();
42
53
  protected readonly listeners = new Map<number, NotificationListener>();
54
+ protected readonly stateListeners = new Set<(connected: boolean, error?: string) => void>();
43
55
 
44
56
  constructor(protected readonly options: ExecClientOptions) {}
45
57
 
58
+ /** Connects to a `ta exec-server` listening on a WebSocket. */
59
+ static webSocket(url: string, token: string): () => Promise<ExecConnection> {
60
+ return async () => {
61
+ const address = new URL(url);
62
+ address.searchParams.set('token', token);
63
+ const socket = new WebSocket(address);
64
+ await new Promise<void>((resolve, reject) => {
65
+ socket.onopen = () => resolve();
66
+ socket.onerror = () => reject(new ExecError(`Cannot connect to ${url}.`, ExecRpc.ErrorCode.CONNECTION_LOST));
67
+ });
68
+ return {
69
+ send: text => socket.send(text),
70
+ close: () => socket.close(),
71
+ onMessage: listener => {
72
+ socket.onmessage = message => listener(String(message.data));
73
+ },
74
+ onClose: listener => {
75
+ socket.onclose = () => listener();
76
+ },
77
+ };
78
+ };
79
+ }
80
+
81
+ get connected(): boolean {
82
+ return this.current !== undefined;
83
+ }
84
+
46
85
  async call<T>(method: string, params: object): Promise<T> {
47
- const socket = await this.connect();
48
- return this.send<T>(socket, method, params);
86
+ const connection = await this.connect();
87
+ return this.send<T>(connection, method, params);
49
88
  }
50
89
 
51
90
  /** What the server said when this client connected. */
@@ -54,7 +93,7 @@ export class ExecClient {
54
93
  return this.initialized as ExecRpc.InitializeResult;
55
94
  }
56
95
 
57
- /** An id for a process, which its notifications carry. */
96
+ /** An id for a process or a TCP connection, which its notifications carry. */
58
97
  processId(): number {
59
98
  return ++this.nextProcess;
60
99
  }
@@ -64,59 +103,82 @@ export class ExecClient {
64
103
  return () => this.listeners.delete(id);
65
104
  }
66
105
 
106
+ /** Runs when a connection opens (true), is lost or closed (false), or cannot be opened (false, with why). */
107
+ onState(listener: (connected: boolean, error?: string) => void): () => void {
108
+ this.stateListeners.add(listener);
109
+ return () => this.stateListeners.delete(listener);
110
+ }
111
+
67
112
  close(): void {
68
- this.current?.close();
69
- this.current = undefined;
70
- this.socket = undefined;
113
+ const current = this.current;
114
+ this.connection = undefined;
115
+ current?.close();
116
+ if (current) {
117
+ this.lost(current);
118
+ }
71
119
  }
72
120
 
73
- protected connect(): Promise<WebSocket> {
121
+ protected connect(): Promise<ExecConnection> {
74
122
  if (this.fenced) {
75
123
  return Promise.reject(new ExecError('A host with a newer epoch took over the execution environment.', ExecRpc.ErrorCode.STALE_EPOCH));
76
124
  }
77
- this.socket ??= this.open().catch(error => {
78
- this.socket = undefined;
125
+ this.connection ??= this.open().catch(error => {
126
+ this.connection = undefined;
127
+ for (const listener of this.stateListeners) {
128
+ listener(false, error instanceof Error ? error.message : String(error));
129
+ }
79
130
  throw error;
80
131
  });
81
- return this.socket;
132
+ return this.connection;
82
133
  }
83
134
 
84
- protected async open(): Promise<WebSocket> {
85
- const url = new URL(this.options.url);
86
- url.searchParams.set('token', this.options.token);
87
- const socket = new WebSocket(url);
88
- await new Promise<void>((resolve, reject) => {
89
- socket.onopen = () => resolve();
90
- socket.onerror = () => reject(new ExecError(`Cannot connect to ${this.options.url}.`, ExecRpc.ErrorCode.CONNECTION_LOST));
91
- });
92
- socket.onmessage = message => this.receive(String(message.data));
93
- this.current = socket;
94
- socket.onclose = () => this.lost(socket);
135
+ protected async open(): Promise<ExecConnection> {
136
+ const connection = await this.options.connect();
137
+ connection.onMessage(text => this.receive(text));
138
+ connection.onClose(reason => this.lost(connection, reason));
139
+ this.current = connection;
95
140
  try {
96
- this.initialized = await this.send(socket, ExecRpc.Method.INITIALIZE, { epoch: this.options.epoch } satisfies ExecRpc.InitializeParams);
141
+ this.initialized = await this.send(connection, ExecRpc.Method.INITIALIZE, { epoch: this.options.epoch } satisfies ExecRpc.InitializeParams);
97
142
  } catch (error) {
98
143
  if ((error as ExecError).code === ExecRpc.ErrorCode.STALE_EPOCH) {
99
144
  this.fenced = true;
100
145
  }
101
- socket.close();
146
+ connection.close();
102
147
  throw error;
103
148
  }
104
- return socket;
149
+ if (this.options.pingMs) {
150
+ clearInterval(this.pinger);
151
+ this.pinger = setInterval(() => connection.send(JSON.stringify({ jsonrpc: '2.0', method: ExecRpc.PING })), this.options.pingMs);
152
+ this.pinger.unref?.();
153
+ }
154
+ for (const listener of this.stateListeners) {
155
+ listener(true);
156
+ }
157
+ return connection;
105
158
  }
106
159
 
107
- protected send<T>(socket: WebSocket, method: string, params: object): Promise<T> {
108
- if (socket.readyState !== WebSocket.OPEN) {
160
+ protected send<T>(connection: ExecConnection, method: string, params: object): Promise<T> {
161
+ if (this.current !== connection) {
109
162
  return Promise.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
110
163
  }
111
164
  const id = ++this.nextCall;
112
165
  return new Promise<T>((resolve, reject) => {
113
166
  this.pending.set(id, { resolve: resolve as (result: unknown) => void, reject });
114
- socket.send(JSON.stringify({ jsonrpc: '2.0', id, method, params } satisfies ExecRpc.Message));
167
+ connection.send(JSON.stringify({ jsonrpc: '2.0', id, method, params } satisfies ExecRpc.Message));
115
168
  });
116
169
  }
117
170
 
171
+ /** Anything but JSON-RPC is left alone: a shell of the other machine may have printed it first. */
118
172
  protected receive(text: string): void {
119
- const message = JSON.parse(text) as ExecRpc.Message;
173
+ let message: ExecRpc.Message;
174
+ try {
175
+ message = JSON.parse(text);
176
+ } catch {
177
+ return;
178
+ }
179
+ if (message?.jsonrpc !== '2.0') {
180
+ return;
181
+ }
120
182
  if (message.method) {
121
183
  this.listeners.get(message.params?.id)?.(message.method, message.params);
122
184
  return;
@@ -134,19 +196,26 @@ export class ExecClient {
134
196
  }
135
197
  }
136
198
 
137
- /** Calls fail, and processes are gone: the server ended them with the connection. */
138
- protected lost(socket: WebSocket): void {
139
- if (this.current === socket) {
140
- this.current = undefined;
141
- this.socket = undefined;
199
+ /** Calls fail, and processes are gone: the server ended them with the connection. `reason`: it was not closed on purpose. */
200
+ protected lost(connection: ExecConnection, reason?: string): void {
201
+ if (this.current !== connection) {
202
+ return;
142
203
  }
204
+ this.current = undefined;
205
+ this.connection = undefined;
206
+ clearInterval(this.pinger);
207
+ this.pinger = undefined;
208
+ const message = reason ?? 'The connection to the execution environment was lost.';
143
209
  for (const call of this.pending.values()) {
144
- call.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
210
+ call.reject(new ExecError(message, ExecRpc.ErrorCode.CONNECTION_LOST));
145
211
  }
146
212
  this.pending.clear();
147
213
  for (const listener of [...this.listeners.values()]) {
148
214
  listener(ExecRpc.Notification.EXIT, { exitCode: null });
149
215
  }
150
216
  this.listeners.clear();
217
+ for (const listener of this.stateListeners) {
218
+ listener(false, reason);
219
+ }
151
220
  }
152
221
  }
@@ -0,0 +1,186 @@
1
+ import { connect, type Socket } from 'node:net';
2
+ import type { ExecProcess } from './exec-protocol';
3
+ import { ExecRpc } from './exec-rpc';
4
+ import { LocalExecEnvironment } from './local-exec-environment';
5
+
6
+ type Method = (typeof ExecRpc.Method)[keyof typeof ExecRpc.Method];
7
+
8
+ /** What a peer needs of its server: the default directory, and which host may run things now. */
9
+ export interface ExecPeerServer {
10
+ readonly cwd: string;
11
+ /** False when a newer host has taken over. */
12
+ admit(peer: ExecPeer, epoch: number): boolean;
13
+ isCurrent(epoch: number | undefined): boolean;
14
+ }
15
+
16
+ /** How a peer answers its host: a WebSocket, or the standard output. */
17
+ export interface ExecPeerChannel {
18
+ send(text: string): void;
19
+ close(code: number, reason: string): void;
20
+ }
21
+
22
+ /** One host connection: its calls, and the processes and TCP connections it started. */
23
+ export class ExecPeer {
24
+ epoch?: number;
25
+ protected readonly running = new Map<number, AbortController>();
26
+ protected readonly spawned = new Map<number, ExecProcess>();
27
+ protected readonly sockets = new Map<number, Socket>();
28
+
29
+ constructor(
30
+ protected readonly server: ExecPeerServer,
31
+ protected readonly channel: ExecPeerChannel,
32
+ ) {}
33
+
34
+ close(code: number, reason: string): void {
35
+ this.dispose();
36
+ this.channel.close(code, reason);
37
+ }
38
+
39
+ /** Ends what this host started. */
40
+ dispose(): void {
41
+ for (const controller of this.running.values()) {
42
+ controller.abort();
43
+ }
44
+ for (const child of this.spawned.values()) {
45
+ child.kill();
46
+ }
47
+ for (const socket of this.sockets.values()) {
48
+ socket.destroy();
49
+ }
50
+ this.running.clear();
51
+ this.spawned.clear();
52
+ this.sockets.clear();
53
+ }
54
+
55
+ async receive(text: string): Promise<void> {
56
+ let message: ExecRpc.Message;
57
+ try {
58
+ message = JSON.parse(text);
59
+ } catch {
60
+ this.close(1007, 'Not JSON.');
61
+ return;
62
+ }
63
+ const { id, method, params } = message;
64
+ if (method === ExecRpc.PING) {
65
+ return;
66
+ }
67
+ let reply: ExecRpc.Message;
68
+ if (method === ExecRpc.Method.INITIALIZE) {
69
+ reply = this.initialize(id, params);
70
+ } else if (this.epoch === undefined) {
71
+ reply = ExecRpc.error(id, ExecRpc.ErrorCode.NOT_INITIALIZED, 'Call initialize first.');
72
+ } else if (!this.server.isCurrent(this.epoch)) {
73
+ reply = ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch took over.');
74
+ } else {
75
+ try {
76
+ reply = { jsonrpc: '2.0', id, result: (await this.call(method as Method, params)) ?? null };
77
+ } catch (error) {
78
+ reply = ExecRpc.error(id, ExecRpc.ErrorCode.FAILED, error instanceof Error ? error.message : String(error));
79
+ }
80
+ }
81
+ if (id !== undefined) {
82
+ this.send(reply);
83
+ }
84
+ }
85
+
86
+ protected initialize(id: number | undefined, params: ExecRpc.InitializeParams): ExecRpc.Message {
87
+ if (typeof params?.epoch !== 'number' || !this.server.admit(this, params.epoch)) {
88
+ return ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch is connected.');
89
+ }
90
+ this.epoch = params.epoch;
91
+ const result: ExecRpc.InitializeResult = { platform: process.platform, cwd: this.server.cwd };
92
+ return { jsonrpc: '2.0', id, result };
93
+ }
94
+
95
+ protected async call(method: Method, params: any): Promise<unknown> {
96
+ const environment = new LocalExecEnvironment(params.root ?? this.server.cwd);
97
+ switch (method) {
98
+ case ExecRpc.Method.EXEC:
99
+ return this.exec(environment, params);
100
+ case ExecRpc.Method.SPAWN:
101
+ return this.spawn(environment, params);
102
+ case ExecRpc.Method.WRITE:
103
+ this.spawned.get(params.id)?.write(ExecRpc.fromBase64(params.data));
104
+ return;
105
+ case ExecRpc.Method.KILL:
106
+ this.running.get(params.id)?.abort();
107
+ this.spawned.get(params.id)?.kill();
108
+ return;
109
+ case ExecRpc.Method.READ_FILE:
110
+ return ExecRpc.toBase64(await environment.readFile(params.path));
111
+ case ExecRpc.Method.WRITE_FILE:
112
+ return environment.writeFile(params.path, ExecRpc.fromBase64(params.data), { append: params.append === true });
113
+ case ExecRpc.Method.STAT:
114
+ return environment.stat(params.path);
115
+ case ExecRpc.Method.READDIR:
116
+ return environment.readdir(params.path);
117
+ case ExecRpc.Method.MKDIR:
118
+ return environment.mkdir(params.path);
119
+ case ExecRpc.Method.REMOVE:
120
+ return environment.remove(params.path, { recursive: params.recursive });
121
+ case ExecRpc.Method.NET_CONNECT:
122
+ return this.connect(params);
123
+ case ExecRpc.Method.NET_WRITE:
124
+ this.sockets.get(params.id)?.write(ExecRpc.fromBase64(params.data));
125
+ return;
126
+ case ExecRpc.Method.NET_CLOSE:
127
+ this.sockets.get(params.id)?.end();
128
+ return;
129
+ default:
130
+ throw new Error(`No method ${method}.`);
131
+ }
132
+ }
133
+
134
+ protected async exec(environment: LocalExecEnvironment, params: ExecRpc.ExecParams): Promise<unknown> {
135
+ const controller = new AbortController();
136
+ this.running.set(params.id, controller);
137
+ try {
138
+ return await environment.exec(params.command, {
139
+ cwd: params.cwd,
140
+ env: { ...process.env, ...params.env },
141
+ timeout: params.timeout,
142
+ signal: controller.signal,
143
+ onData: data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }),
144
+ });
145
+ } finally {
146
+ this.running.delete(params.id);
147
+ }
148
+ }
149
+
150
+ protected spawn(environment: LocalExecEnvironment, params: ExecRpc.SpawnParams): void {
151
+ const child = environment.spawn(params.command, params.args, { cwd: params.cwd, env: { ...process.env, ...params.env } });
152
+ this.spawned.set(params.id, child);
153
+ child.onStdout(data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }));
154
+ child.onStderr(data => this.notify(ExecRpc.Notification.STDERR, { id: params.id, data: ExecRpc.toBase64(data) }));
155
+ child.onExit(exitCode => {
156
+ this.spawned.delete(params.id);
157
+ this.notify(ExecRpc.Notification.EXIT, { id: params.id, exitCode });
158
+ });
159
+ }
160
+
161
+ /** Resolves once connected; the data comes as notifications, the end as NET_CLOSED. */
162
+ protected connect(params: ExecRpc.ConnectParams): Promise<void> {
163
+ return new Promise((resolve, reject) => {
164
+ const socket = connect({ port: params.port, host: params.host ?? '127.0.0.1' });
165
+ socket.once('connect', () => {
166
+ this.sockets.set(params.id, socket);
167
+ resolve();
168
+ });
169
+ socket.on('data', data => this.notify(ExecRpc.Notification.NET_DATA, { id: params.id, data: ExecRpc.toBase64(data) }));
170
+ socket.once('error', reject);
171
+ socket.once('close', () => {
172
+ if (this.sockets.delete(params.id)) {
173
+ this.notify(ExecRpc.Notification.NET_CLOSED, { id: params.id });
174
+ }
175
+ });
176
+ });
177
+ }
178
+
179
+ protected notify(method: string, params: unknown): void {
180
+ this.send({ jsonrpc: '2.0', method, params });
181
+ }
182
+
183
+ protected send(message: ExecRpc.Message): void {
184
+ this.channel.send(JSON.stringify(message));
185
+ }
186
+ }
@@ -30,6 +30,20 @@ export interface ExecProcess {
30
30
  kill(): void;
31
31
  }
32
32
 
33
+ /** A TCP connection made from inside an environment. */
34
+ export interface ExecSocket {
35
+ write(data: Uint8Array): void;
36
+ /** Ends the connection; `onClose` follows. */
37
+ end(): void;
38
+ onData(listener: (data: Uint8Array) => void): void;
39
+ /** Once, when either side ended it or the environment was lost. */
40
+ onClose(listener: () => void): void;
41
+ }
42
+
43
+ export interface WriteFileOptions {
44
+ append?: boolean;
45
+ }
46
+
33
47
  export interface FileStat {
34
48
  isDirectory: boolean;
35
49
  size: number;
@@ -53,12 +67,18 @@ export interface ExecEnvironment {
53
67
  exec(command: string, options?: ExecOptions): Promise<ExecResult>;
54
68
  spawn(command: string, args: string[], options?: SpawnOptions): ExecProcess;
55
69
  readFile(path: string): Promise<Uint8Array>;
56
- writeFile(path: string, data: Uint8Array | string): Promise<void>;
70
+ /** With `append`, the data goes after what the file holds (made when missing), as for a file sent in parts. */
71
+ writeFile(path: string, data: Uint8Array | string, options?: WriteFileOptions): Promise<void>;
57
72
  /** undefined when nothing is there. */
58
73
  stat(path: string): Promise<FileStat | undefined>;
59
74
  readdir(path: string): Promise<DirEntry[]>;
60
75
  mkdir(path: string): Promise<void>;
61
76
  remove(path: string, options?: { recursive?: boolean }): Promise<void>;
77
+ /**
78
+ * A TCP connection to a port of the environment's machine (default host 127.0.0.1), for one only
79
+ * reachable there; only environments on another machine have it. Rejects when nothing listens.
80
+ */
81
+ connect?(port: number, host?: string): Promise<ExecSocket>;
62
82
  }
63
83
 
64
84
  /** Bind another implementation with `rebind: true` to run sessions elsewhere. */
@@ -0,0 +1,7 @@
1
+ // Generated by scripts/remote-server.ts from scripts/remote-main.ts: do not edit.
2
+
3
+ /** `ta exec-server` on stdio in one script for Node.js 18, and the hash that names its version. */
4
+ export const EXEC_REMOTE_SOURCE = {
5
+ hash: "9c733cfd94c14c82",
6
+ script: "var b=require(\"node:net\");var H;((Y)=>{Y.PATH=\"/exec\",Y.Method={INITIALIZE:\"initialize\",EXEC:\"process/exec\",SPAWN:\"process/spawn\",WRITE:\"process/write\",KILL:\"process/kill\",READ_FILE:\"fs/readFile\",WRITE_FILE:\"fs/writeFile\",STAT:\"fs/stat\",READDIR:\"fs/readdir\",MKDIR:\"fs/mkdir\",REMOVE:\"fs/remove\",NET_CONNECT:\"net/connect\",NET_WRITE:\"net/write\",NET_CLOSE:\"net/close\"},Y.PING=\"ping\",Y.Notification={OUTPUT:\"process/output\",STDERR:\"process/stderr\",EXIT:\"process/exit\",NET_DATA:\"net/data\",NET_CLOSED:\"net/closed\"},Y.ErrorCode={STALE_EPOCH:\"CELL_TA_EXEC_STALE_EPOCH\",NOT_INITIALIZED:\"CELL_TA_EXEC_NOT_INITIALIZED\",FAILED:\"CELL_TA_EXEC_FAILED\",CONNECTION_LOST:\"CELL_TA_EXEC_CONNECTION_LOST\"},Y.ERROR=-32060;function Q(U,q,B){return{jsonrpc:\"2.0\",id:U,error:{code:-32060,message:B,data:{code:q}}}}Y.error=Q;function $(U){return Buffer.from(U).toString(\"base64\")}Y.toBase64=$;function Z(U){return Buffer.from(U,\"base64\")}Y.fromBase64=Z})(H||={});var O=require(\"node:child_process\"),V=require(\"node:fs/promises\"),I=require(\"node:path\");class P{cwd;local=!0;constructor(A){this.cwd=A}exec(A,z={}){let[G,...J]=process.platform===\"win32\"?[\"cmd.exe\",\"/d\",\"/s\",\"/c\"]:[\"/bin/sh\",\"-c\"],K=O.spawn(G,[...J,A],{cwd:I.resolve(this.cwd,z.cwd??\".\"),env:z.env??process.env,stdio:[\"ignore\",\"pipe\",\"pipe\"],detached:process.platform!==\"win32\"});return new Promise((X)=>{let Q=()=>this.killGroup(K),$=z.timeout?setTimeout(Q,z.timeout):void 0;if(z.signal?.addEventListener(\"abort\",Q,{once:!0}),z.signal?.aborted)Q();K.stdout?.on(\"data\",(U)=>z.onData?.(U)),K.stderr?.on(\"data\",(U)=>z.onData?.(U));let Z=(U)=>{clearTimeout($),z.signal?.removeEventListener(\"abort\",Q),X({exitCode:U})};K.once(\"error\",()=>Z(null)),K.once(\"close\",Z)})}spawn(A,z,G={}){let J=O.spawn(A,z,{cwd:I.resolve(this.cwd,G.cwd??\".\"),env:G.env??process.env,stdio:[\"pipe\",\"pipe\",\"pipe\"]});return J.stdin.on(\"error\",()=>{return}),{write:(K)=>J.stdin.write(K),onStdout:(K)=>J.stdout.on(\"data\",K),onStderr:(K)=>J.stderr.on(\"data\",K),onExit:(K)=>{J.once(\"error\",()=>K(null)),J.once(\"close\",K)},kill:()=>J.kill()}}readFile(A){return V.readFile(this.resolve(A))}writeFile(A,z,G={}){return G.append?V.appendFile(this.resolve(A),z):V.writeFile(this.resolve(A),z)}async stat(A){try{let z=await V.stat(this.resolve(A));return{isDirectory:z.isDirectory(),size:z.size,mtimeMs:z.mtimeMs}}catch(z){if(z.code===\"ENOENT\")return;throw z}}async readdir(A){return(await V.readdir(this.resolve(A),{withFileTypes:!0})).map((G)=>({name:G.name,isDirectory:G.isDirectory()}))}async mkdir(A){await V.mkdir(this.resolve(A),{recursive:!0})}remove(A,z={}){return V.rm(this.resolve(A),{recursive:z.recursive,force:!0})}resolve(A){return I.resolve(this.cwd,A)}killGroup(A){if(A.pid===void 0)return;if(process.platform!==\"win32\")try{process.kill(-A.pid,\"SIGKILL\");return}catch{}A.kill(\"SIGKILL\")}}class W{server;channel;epoch;running=new Map;spawned=new Map;sockets=new Map;constructor(A,z){this.server=A;this.channel=z}close(A,z){this.dispose(),this.channel.close(A,z)}dispose(){for(let A of this.running.values())A.abort();for(let A of this.spawned.values())A.kill();for(let A of this.sockets.values())A.destroy();this.running.clear(),this.spawned.clear(),this.sockets.clear()}async receive(A){let z;try{z=JSON.parse(A)}catch{this.close(1007,\"Not JSON.\");return}let{id:G,method:J,params:K}=z;if(J===H.PING)return;let X;if(J===H.Method.INITIALIZE)X=this.initialize(G,K);else if(this.epoch===void 0)X=H.error(G,H.ErrorCode.NOT_INITIALIZED,\"Call initialize first.\");else if(!this.server.isCurrent(this.epoch))X=H.error(G,H.ErrorCode.STALE_EPOCH,\"A host with a newer epoch took over.\");else try{X={jsonrpc:\"2.0\",id:G,result:await this.call(J,K)??null}}catch(Q){X=H.error(G,H.ErrorCode.FAILED,Q instanceof Error?Q.message:String(Q))}if(G!==void 0)this.send(X)}initialize(A,z){if(typeof z?.epoch!==\"number\"||!this.server.admit(this,z.epoch))return H.error(A,H.ErrorCode.STALE_EPOCH,\"A host with a newer epoch is connected.\");this.epoch=z.epoch;let G={platform:process.platform,cwd:this.server.cwd};return{jsonrpc:\"2.0\",id:A,result:G}}async call(A,z){let G=new P(z.root??this.server.cwd);switch(A){case H.Method.EXEC:return this.exec(G,z);case H.Method.SPAWN:return this.spawn(G,z);case H.Method.WRITE:this.spawned.get(z.id)?.write(H.fromBase64(z.data));return;case H.Method.KILL:this.running.get(z.id)?.abort(),this.spawned.get(z.id)?.kill();return;case H.Method.READ_FILE:return H.toBase64(await G.readFile(z.path));case H.Method.WRITE_FILE:return G.writeFile(z.path,H.fromBase64(z.data),{append:z.append===!0});case H.Method.STAT:return G.stat(z.path);case H.Method.READDIR:return G.readdir(z.path);case H.Method.MKDIR:return G.mkdir(z.path);case H.Method.REMOVE:return G.remove(z.path,{recursive:z.recursive});case H.Method.NET_CONNECT:return this.connect(z);case H.Method.NET_WRITE:this.sockets.get(z.id)?.write(H.fromBase64(z.data));return;case H.Method.NET_CLOSE:this.sockets.get(z.id)?.end();return;default:throw Error(`No method ${A}.`)}}async exec(A,z){let G=new AbortController;this.running.set(z.id,G);try{return await A.exec(z.command,{cwd:z.cwd,env:{...process.env,...z.env},timeout:z.timeout,signal:G.signal,onData:(J)=>this.notify(H.Notification.OUTPUT,{id:z.id,data:H.toBase64(J)})})}finally{this.running.delete(z.id)}}spawn(A,z){let G=A.spawn(z.command,z.args,{cwd:z.cwd,env:{...process.env,...z.env}});this.spawned.set(z.id,G),G.onStdout((J)=>this.notify(H.Notification.OUTPUT,{id:z.id,data:H.toBase64(J)})),G.onStderr((J)=>this.notify(H.Notification.STDERR,{id:z.id,data:H.toBase64(J)})),G.onExit((J)=>{this.spawned.delete(z.id),this.notify(H.Notification.EXIT,{id:z.id,exitCode:J})})}connect(A){return new Promise((z,G)=>{let J=b.connect({port:A.port,host:A.host??\"127.0.0.1\"});J.once(\"connect\",()=>{this.sockets.set(A.id,J),z()}),J.on(\"data\",(K)=>this.notify(H.Notification.NET_DATA,{id:A.id,data:H.toBase64(K)})),J.once(\"error\",G),J.once(\"close\",()=>{if(this.sockets.delete(A.id))this.notify(H.Notification.NET_CLOSED,{id:A.id})})})}notify(A,z){this.send({jsonrpc:\"2.0\",method:A,params:z})}send(A){this.channel.send(JSON.stringify(A))}}class N{options;cwd;epoch;constructor(A){this.options=A;this.cwd=A.cwd??process.cwd()}serve(){let{input:A,output:z,idleMs:G}=this.options;return new Promise((J)=>{let K,X=\"\",Q=()=>{clearTimeout(K),A.removeListener(\"data\",U),$.dispose(),J()},$=new W(this,{send:(q)=>z.write(`${q}\n`),close:Q}),Z=()=>{if(G)clearTimeout(K),K=setTimeout(Q,G)},U=(q)=>{Z();let B=(X+q.toString()).split(`\n`);X=B.pop()??\"\";for(let T of B)if(T.trim())$.receive(T)};A.on(\"data\",U),A.once(\"end\",Q),A.once(\"error\",Q),Z()})}admit(A,z){if(this.epoch!==void 0&&z<this.epoch)return!1;return this.epoch=z,!0}isCurrent(A){return A===this.epoch}}var j=60000;new N({input:process.stdin,output:process.stdout,idleMs:j}).serve().then(()=>process.exit(0));\n",
7
+ };
@@ -1,7 +1,8 @@
1
1
  /**
2
- * The protocol of `ta exec-server`: JSON-RPC 2.0 over a WebSocket, one text message each, as Codex's
3
- * exec-server does it. The host calls methods; the server sends the output of processes as
4
- * notifications. Bytes travel as base64.
2
+ * The protocol of `ta exec-server`: JSON-RPC 2.0, as Codex's exec-server does it, over a WebSocket (one
3
+ * text message each) or over the standard input and output of the server (one line each), which is how
4
+ * it runs at the other end of ssh. The host calls methods; the server sends the output of processes
5
+ * and the data of connections as notifications. Bytes travel as base64.
5
6
  */
6
7
  export namespace ExecRpc {
7
8
  /** Path of the WebSocket endpoint. */
@@ -19,14 +20,25 @@ export namespace ExecRpc {
19
20
  READDIR: 'fs/readdir',
20
21
  MKDIR: 'fs/mkdir',
21
22
  REMOVE: 'fs/remove',
23
+ /** A TCP connection from the server's machine, for a port only reachable there. */
24
+ NET_CONNECT: 'net/connect',
25
+ NET_WRITE: 'net/write',
26
+ NET_CLOSE: 'net/close',
22
27
  } as const;
23
28
 
29
+ /** Sent by the host, without an id, to say it is still there; over stdio the server ends without it. */
30
+ export const PING = 'ping';
31
+
24
32
  export const Notification = {
25
33
  /** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
26
34
  OUTPUT: 'process/output',
27
35
  STDERR: 'process/stderr',
28
36
  /** A spawned process ended. */
29
37
  EXIT: 'process/exit',
38
+ /** Data a connection of `net/connect` received. */
39
+ NET_DATA: 'net/data',
40
+ /** A connection of `net/connect` ended. */
41
+ NET_CLOSED: 'net/closed',
30
42
  } as const;
31
43
 
32
44
  /** `error.data.code` of failed calls. */
@@ -74,6 +86,14 @@ export namespace ExecRpc {
74
86
  args: string[];
75
87
  }
76
88
 
89
+ export interface ConnectParams {
90
+ /** Chosen by the host, unique per connection, as the id of a process: the notifications carry it. */
91
+ id: number;
92
+ port: number;
93
+ /** Default 127.0.0.1. */
94
+ host?: string;
95
+ }
96
+
77
97
  export interface PathParams {
78
98
  root: string;
79
99
  path: string;
@@ -24,7 +24,7 @@ describe('ta exec-server', () => {
24
24
  let url: string;
25
25
 
26
26
  const environment = (epoch = 1, token = TOKEN) => {
27
- const client = new ExecClient({ url, token, epoch });
27
+ const client = new ExecClient({ connect: ExecClient.webSocket(url, token), epoch });
28
28
  clients.push(client);
29
29
  return new RemoteExecEnvironment(client, root);
30
30
  };
@@ -70,6 +70,9 @@ describe('ta exec-server', () => {
70
70
  await env.mkdir('dir/sub');
71
71
  await env.writeFile('dir/sub/a.txt', 'hello');
72
72
  expect(readFileSync(join(root, 'dir/sub/a.txt'), 'utf8')).toBe('hello');
73
+ await env.writeFile('dir/sub/a.txt', ' world', { append: true });
74
+ expect(readFileSync(join(root, 'dir/sub/a.txt'), 'utf8')).toBe('hello world');
75
+ await env.writeFile('dir/sub/a.txt', 'hello');
73
76
  expect(Buffer.from(await env.readFile('dir/sub/a.txt')).toString()).toBe('hello');
74
77
  expect(await env.stat('dir')).toMatchObject({ isDirectory: true });
75
78
  expect(await env.stat('nothing')).toBeUndefined();