@celljs/ta-exec 4.8.0 → 4.9.1

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 (86) hide show
  1. package/package.json +4 -3
  2. package/esm/node/exec-client.js.map +0 -1
  3. package/esm/node/exec-peer.js.map +0 -1
  4. package/esm/node/exec-protocol.js.map +0 -1
  5. package/esm/node/exec-remote-source.js.map +0 -1
  6. package/esm/node/exec-rpc.js.map +0 -1
  7. package/esm/node/exec-server.js.map +0 -1
  8. package/esm/node/exec-stdio.js.map +0 -1
  9. package/esm/node/index.js.map +0 -1
  10. package/esm/node/local-exec-environment.js.map +0 -1
  11. package/esm/node/remote-exec-environment.js.map +0 -1
  12. package/esm/node/ssh/node-dist.js.map +0 -1
  13. package/esm/node/ssh/ssh-askpass.js.map +0 -1
  14. package/esm/node/ssh/ssh-config.js.map +0 -1
  15. package/esm/node/ssh/ssh-host.js.map +0 -1
  16. package/esm/node/ssh/ssh-util.js.map +0 -1
  17. package/lib/node/exec-client.d.ts.map +0 -1
  18. package/lib/node/exec-client.js.map +0 -1
  19. package/lib/node/exec-peer.d.ts.map +0 -1
  20. package/lib/node/exec-peer.js.map +0 -1
  21. package/lib/node/exec-protocol.d.ts.map +0 -1
  22. package/lib/node/exec-protocol.js.map +0 -1
  23. package/lib/node/exec-remote-source.d.ts.map +0 -1
  24. package/lib/node/exec-remote-source.js.map +0 -1
  25. package/lib/node/exec-rpc.d.ts.map +0 -1
  26. package/lib/node/exec-rpc.js.map +0 -1
  27. package/lib/node/exec-server.d.ts.map +0 -1
  28. package/lib/node/exec-server.js.map +0 -1
  29. package/lib/node/exec-server.spec.d.ts +0 -2
  30. package/lib/node/exec-server.spec.d.ts.map +0 -1
  31. package/lib/node/exec-server.spec.js +0 -104
  32. package/lib/node/exec-server.spec.js.map +0 -1
  33. package/lib/node/exec-stdio.d.ts.map +0 -1
  34. package/lib/node/exec-stdio.js.map +0 -1
  35. package/lib/node/exec-stdio.spec.d.ts +0 -2
  36. package/lib/node/exec-stdio.spec.d.ts.map +0 -1
  37. package/lib/node/exec-stdio.spec.js +0 -106
  38. package/lib/node/exec-stdio.spec.js.map +0 -1
  39. package/lib/node/index.d.ts.map +0 -1
  40. package/lib/node/index.js.map +0 -1
  41. package/lib/node/local-exec-environment.d.ts.map +0 -1
  42. package/lib/node/local-exec-environment.js.map +0 -1
  43. package/lib/node/local-exec-environment.spec.d.ts +0 -2
  44. package/lib/node/local-exec-environment.spec.d.ts.map +0 -1
  45. package/lib/node/local-exec-environment.spec.js +0 -57
  46. package/lib/node/local-exec-environment.spec.js.map +0 -1
  47. package/lib/node/remote-exec-environment.d.ts.map +0 -1
  48. package/lib/node/remote-exec-environment.js.map +0 -1
  49. package/lib/node/ssh/node-dist.d.ts.map +0 -1
  50. package/lib/node/ssh/node-dist.js.map +0 -1
  51. package/lib/node/ssh/ssh-askpass.d.ts.map +0 -1
  52. package/lib/node/ssh/ssh-askpass.js.map +0 -1
  53. package/lib/node/ssh/ssh-config.d.ts.map +0 -1
  54. package/lib/node/ssh/ssh-config.js.map +0 -1
  55. package/lib/node/ssh/ssh-host.d.ts.map +0 -1
  56. package/lib/node/ssh/ssh-host.js.map +0 -1
  57. package/lib/node/ssh/ssh-host.spec.d.ts +0 -2
  58. package/lib/node/ssh/ssh-host.spec.d.ts.map +0 -1
  59. package/lib/node/ssh/ssh-host.spec.js +0 -182
  60. package/lib/node/ssh/ssh-host.spec.js.map +0 -1
  61. package/lib/node/ssh/ssh-util.d.ts.map +0 -1
  62. package/lib/node/ssh/ssh-util.js.map +0 -1
  63. package/lib/node/ssh/ssh-util.spec.d.ts +0 -2
  64. package/lib/node/ssh/ssh-util.spec.d.ts.map +0 -1
  65. package/lib/node/ssh/ssh-util.spec.js +0 -87
  66. package/lib/node/ssh/ssh-util.spec.js.map +0 -1
  67. package/src/node/exec-client.ts +0 -221
  68. package/src/node/exec-peer.ts +0 -186
  69. package/src/node/exec-protocol.ts +0 -89
  70. package/src/node/exec-remote-source.ts +0 -7
  71. package/src/node/exec-rpc.ts +0 -124
  72. package/src/node/exec-server.spec.ts +0 -113
  73. package/src/node/exec-server.ts +0 -107
  74. package/src/node/exec-stdio.spec.ts +0 -108
  75. package/src/node/exec-stdio.ts +0 -75
  76. package/src/node/index.ts +0 -14
  77. package/src/node/local-exec-environment.spec.ts +0 -60
  78. package/src/node/local-exec-environment.ts +0 -112
  79. package/src/node/remote-exec-environment.ts +0 -162
  80. package/src/node/ssh/node-dist.ts +0 -83
  81. package/src/node/ssh/ssh-askpass.ts +0 -117
  82. package/src/node/ssh/ssh-config.ts +0 -128
  83. package/src/node/ssh/ssh-host.spec.ts +0 -189
  84. package/src/node/ssh/ssh-host.ts +0 -300
  85. package/src/node/ssh/ssh-util.spec.ts +0 -97
  86. package/src/node/ssh/ssh-util.ts +0 -127
@@ -1,221 +0,0 @@
1
- import { ExecRpc } from './exec-rpc';
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
-
12
- export interface ExecClientOptions {
13
- /** Opens a connection; rejects with an ExecError when it cannot. See {@link ExecClient.webSocket}. */
14
- connect(): Promise<ExecConnection>;
15
- /** Larger than the epoch of any host that ran these sessions before; see {@link ExecRpc.InitializeParams}. */
16
- epoch: number;
17
- /** Pings this often (milliseconds) while connected, for a server that ends without them (over stdio). */
18
- pingMs?: number;
19
- }
20
-
21
- /** A failed call to `ta exec-server`. */
22
- export class ExecError extends Error {
23
- constructor(
24
- message: string,
25
- readonly code: ExecRpc.ErrorCode,
26
- ) {
27
- super(message);
28
- this.name = 'ExecError';
29
- }
30
- }
31
-
32
- type NotificationListener = (method: string, params: { data?: string; exitCode?: number | null }) => void;
33
-
34
- interface PendingCall {
35
- resolve(result: unknown): void;
36
- reject(error: Error): void;
37
- }
38
-
39
- /**
40
- * One connection of a host to `ta exec-server`, shared by its environments. It connects on the first
41
- * call and again on the first call after a loss; processes do not survive a loss. Once fenced by a
42
- * host with a newer epoch it refuses every call: this host must stop running sessions there.
43
- */
44
- export class ExecClient {
45
- protected connection?: Promise<ExecConnection>;
46
- protected current?: ExecConnection;
47
- protected nextCall = 0;
48
- protected nextProcess = 0;
49
- protected fenced = false;
50
- protected pinger?: ReturnType<typeof setInterval>;
51
- protected initialized?: ExecRpc.InitializeResult;
52
- protected readonly pending = new Map<number, PendingCall>();
53
- protected readonly listeners = new Map<number, NotificationListener>();
54
- protected readonly stateListeners = new Set<(connected: boolean, error?: string) => void>();
55
-
56
- constructor(protected readonly options: ExecClientOptions) {}
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
-
85
- async call<T>(method: string, params: object): Promise<T> {
86
- const connection = await this.connect();
87
- return this.send<T>(connection, method, params);
88
- }
89
-
90
- /** What the server said when this client connected. */
91
- async info(): Promise<ExecRpc.InitializeResult> {
92
- await this.connect();
93
- return this.initialized as ExecRpc.InitializeResult;
94
- }
95
-
96
- /** An id for a process or a TCP connection, which its notifications carry. */
97
- processId(): number {
98
- return ++this.nextProcess;
99
- }
100
-
101
- listen(id: number, listener: NotificationListener): () => void {
102
- this.listeners.set(id, listener);
103
- return () => this.listeners.delete(id);
104
- }
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
-
112
- close(): void {
113
- const current = this.current;
114
- this.connection = undefined;
115
- current?.close();
116
- if (current) {
117
- this.lost(current);
118
- }
119
- }
120
-
121
- protected connect(): Promise<ExecConnection> {
122
- if (this.fenced) {
123
- return Promise.reject(new ExecError('A host with a newer epoch took over the execution environment.', ExecRpc.ErrorCode.STALE_EPOCH));
124
- }
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
- }
130
- throw error;
131
- });
132
- return this.connection;
133
- }
134
-
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;
140
- try {
141
- this.initialized = await this.send(connection, ExecRpc.Method.INITIALIZE, { epoch: this.options.epoch } satisfies ExecRpc.InitializeParams);
142
- } catch (error) {
143
- if ((error as ExecError).code === ExecRpc.ErrorCode.STALE_EPOCH) {
144
- this.fenced = true;
145
- }
146
- connection.close();
147
- throw error;
148
- }
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;
158
- }
159
-
160
- protected send<T>(connection: ExecConnection, method: string, params: object): Promise<T> {
161
- if (this.current !== connection) {
162
- return Promise.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
163
- }
164
- const id = ++this.nextCall;
165
- return new Promise<T>((resolve, reject) => {
166
- this.pending.set(id, { resolve: resolve as (result: unknown) => void, reject });
167
- connection.send(JSON.stringify({ jsonrpc: '2.0', id, method, params } satisfies ExecRpc.Message));
168
- });
169
- }
170
-
171
- /** Anything but JSON-RPC is left alone: a shell of the other machine may have printed it first. */
172
- protected receive(text: string): void {
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
- }
182
- if (message.method) {
183
- this.listeners.get(message.params?.id)?.(message.method, message.params);
184
- return;
185
- }
186
- const call = this.pending.get(message.id as number);
187
- this.pending.delete(message.id as number);
188
- if (message.error) {
189
- const code = message.error.data?.code ?? ExecRpc.ErrorCode.FAILED;
190
- if (code === ExecRpc.ErrorCode.STALE_EPOCH) {
191
- this.fenced = true;
192
- }
193
- call?.reject(new ExecError(message.error.message, code));
194
- } else {
195
- call?.resolve(message.result);
196
- }
197
- }
198
-
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;
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.';
209
- for (const call of this.pending.values()) {
210
- call.reject(new ExecError(message, ExecRpc.ErrorCode.CONNECTION_LOST));
211
- }
212
- this.pending.clear();
213
- for (const listener of [...this.listeners.values()]) {
214
- listener(ExecRpc.Notification.EXIT, { exitCode: null });
215
- }
216
- this.listeners.clear();
217
- for (const listener of this.stateListeners) {
218
- listener(false, reason);
219
- }
220
- }
221
- }
@@ -1,186 +0,0 @@
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
- }
@@ -1,89 +0,0 @@
1
- export const ExecEnvironmentFactory = Symbol('ExecEnvironmentFactory');
2
-
3
- export interface ExecOptions {
4
- /** Default: the `cwd` of the environment. */
5
- cwd?: string;
6
- env?: NodeJS.ProcessEnv;
7
- /** Milliseconds; the process is killed afterwards. */
8
- timeout?: number;
9
- signal?: AbortSignal;
10
- onData?: (data: Uint8Array) => void;
11
- }
12
-
13
- export interface ExecResult {
14
- /** null when the process was killed. */
15
- exitCode: number | null;
16
- }
17
-
18
- export interface SpawnOptions {
19
- cwd?: string;
20
- env?: NodeJS.ProcessEnv;
21
- }
22
-
23
- /** A running program, for long-lived ones that talk over stdin and stdout (MCP servers, language servers). */
24
- export interface ExecProcess {
25
- write(data: Uint8Array | string): void;
26
- onStdout(listener: (data: Uint8Array) => void): void;
27
- onStderr(listener: (data: Uint8Array) => void): void;
28
- /** Also called when the program could not start, with a null code. */
29
- onExit(listener: (exitCode: number | null) => void): void;
30
- kill(): void;
31
- }
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
-
47
- export interface FileStat {
48
- isDirectory: boolean;
49
- size: number;
50
- mtimeMs: number;
51
- }
52
-
53
- export interface DirEntry {
54
- name: string;
55
- isDirectory: boolean;
56
- }
57
-
58
- /**
59
- * Where an agent runs commands and touches files. Paths are paths inside this environment, which may
60
- * be another machine: never hand one to `node:fs`, and hand the model only these.
61
- */
62
- export interface ExecEnvironment {
63
- /** Working directory, inside the environment. */
64
- readonly cwd: string;
65
- /** This machine: pi's own implementations of its tools do the same work, so they stay in use. */
66
- readonly local: boolean;
67
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
68
- spawn(command: string, args: string[], options?: SpawnOptions): ExecProcess;
69
- readFile(path: string): Promise<Uint8Array>;
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>;
72
- /** undefined when nothing is there. */
73
- stat(path: string): Promise<FileStat | undefined>;
74
- readdir(path: string): Promise<DirEntry[]>;
75
- mkdir(path: string): Promise<void>;
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>;
82
- }
83
-
84
- /** Bind another implementation with `rebind: true` to run sessions elsewhere. */
85
- export interface ExecEnvironmentFactory {
86
- create(cwd: string): ExecEnvironment;
87
- /** Where sessions run when nobody names a directory: a path of the environment. */
88
- defaultCwd(): Promise<string>;
89
- }
@@ -1,7 +0,0 @@
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,124 +0,0 @@
1
- /**
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.
6
- */
7
- export namespace ExecRpc {
8
- /** Path of the WebSocket endpoint. */
9
- export const PATH = '/exec';
10
-
11
- export const Method = {
12
- INITIALIZE: 'initialize',
13
- EXEC: 'process/exec',
14
- SPAWN: 'process/spawn',
15
- WRITE: 'process/write',
16
- KILL: 'process/kill',
17
- READ_FILE: 'fs/readFile',
18
- WRITE_FILE: 'fs/writeFile',
19
- STAT: 'fs/stat',
20
- READDIR: 'fs/readdir',
21
- MKDIR: 'fs/mkdir',
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',
27
- } as const;
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
-
32
- export const Notification = {
33
- /** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
34
- OUTPUT: 'process/output',
35
- STDERR: 'process/stderr',
36
- /** A spawned process ended. */
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',
42
- } as const;
43
-
44
- /** `error.data.code` of failed calls. */
45
- export const ErrorCode = {
46
- /** A host with a newer epoch connected: this one may no longer run anything. */
47
- STALE_EPOCH: 'CELL_TA_EXEC_STALE_EPOCH',
48
- NOT_INITIALIZED: 'CELL_TA_EXEC_NOT_INITIALIZED',
49
- FAILED: 'CELL_TA_EXEC_FAILED',
50
- CONNECTION_LOST: 'CELL_TA_EXEC_CONNECTION_LOST',
51
- } as const;
52
- export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
53
-
54
- /**
55
- * The epoch fences hosts: when a session moves to another host instance (a restart, a failover), the
56
- * new one connects with a larger epoch, and the server stops taking calls from smaller ones and kills
57
- * their processes, so that two hosts never run the same session's tools.
58
- */
59
- export interface InitializeParams {
60
- epoch: number;
61
- }
62
-
63
- export interface InitializeResult {
64
- platform: string;
65
- /** The working directory of the server: where sessions run when nobody names another. */
66
- cwd: string;
67
- }
68
-
69
- /** Every call names the directory of its environment; a relative `cwd` or path resolves against it. */
70
- export interface ProcessParams {
71
- root: string;
72
- /** Chosen by the host, unique per connection: the notifications carry it. */
73
- id: number;
74
- cwd?: string;
75
- /** Only what the host sets on top of the server's own environment, never the host's environment. */
76
- env?: Record<string, string>;
77
- }
78
-
79
- export interface ExecParams extends ProcessParams {
80
- command: string;
81
- timeout?: number;
82
- }
83
-
84
- export interface SpawnParams extends ProcessParams {
85
- command: string;
86
- args: string[];
87
- }
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
-
97
- export interface PathParams {
98
- root: string;
99
- path: string;
100
- }
101
-
102
- export interface Message {
103
- jsonrpc: '2.0';
104
- id?: number;
105
- method?: string;
106
- params?: any;
107
- result?: unknown;
108
- error?: { code: number; message: string; data?: { code: ErrorCode } };
109
- }
110
-
111
- export const ERROR = -32060;
112
-
113
- export function error(id: number | undefined, code: ErrorCode, message: string): Message {
114
- return { jsonrpc: '2.0', id, error: { code: ERROR, message, data: { code } } };
115
- }
116
-
117
- export function toBase64(data: Uint8Array | string): string {
118
- return Buffer.from(data).toString('base64');
119
- }
120
-
121
- export function fromBase64(data: string): Uint8Array {
122
- return Buffer.from(data, 'base64');
123
- }
124
- }