@celljs/ta-exec 4.5.1 → 4.6.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.
- package/README.md +24 -2
- package/esm/node/exec-client.d.ts +52 -0
- package/esm/node/exec-client.js +128 -0
- package/esm/node/exec-client.js.map +1 -0
- package/esm/node/exec-protocol.d.ts +2 -0
- package/esm/node/exec-rpc.d.ts +90 -0
- package/esm/node/exec-rpc.js +52 -0
- package/esm/node/exec-rpc.js.map +1 -0
- package/esm/node/exec-server.d.ts +61 -0
- package/esm/node/exec-server.js +217 -0
- package/esm/node/exec-server.js.map +1 -0
- package/esm/node/index.d.ts +4 -0
- package/esm/node/index.js +4 -0
- package/esm/node/index.js.map +1 -1
- package/esm/node/remote-exec-environment.d.ts +26 -0
- package/esm/node/remote-exec-environment.js +115 -0
- package/esm/node/remote-exec-environment.js.map +1 -0
- package/lib/node/exec-client.d.ts +53 -0
- package/lib/node/exec-client.d.ts.map +1 -0
- package/lib/node/exec-client.js +133 -0
- package/lib/node/exec-client.js.map +1 -0
- package/lib/node/exec-protocol.d.ts +2 -0
- package/lib/node/exec-protocol.d.ts.map +1 -1
- package/lib/node/exec-rpc.d.ts +91 -0
- package/lib/node/exec-rpc.d.ts.map +1 -0
- package/lib/node/exec-rpc.js +55 -0
- package/lib/node/exec-rpc.js.map +1 -0
- package/lib/node/exec-server.d.ts +62 -0
- package/lib/node/exec-server.d.ts.map +1 -0
- package/lib/node/exec-server.js +222 -0
- package/lib/node/exec-server.js.map +1 -0
- package/lib/node/exec-server.spec.d.ts +2 -0
- package/lib/node/exec-server.spec.d.ts.map +1 -0
- package/lib/node/exec-server.spec.js +101 -0
- package/lib/node/exec-server.spec.js.map +1 -0
- package/lib/node/index.d.ts +4 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +4 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/remote-exec-environment.d.ts +27 -0
- package/lib/node/remote-exec-environment.d.ts.map +1 -0
- package/lib/node/remote-exec-environment.js +119 -0
- package/lib/node/remote-exec-environment.js.map +1 -0
- package/package.json +5 -3
- package/src/node/exec-client.ts +152 -0
- package/src/node/exec-protocol.ts +2 -0
- package/src/node/exec-rpc.ts +104 -0
- package/src/node/exec-server.spec.ts +110 -0
- package/src/node/exec-server.ts +243 -0
- package/src/node/index.ts +4 -0
- package/src/node/remote-exec-environment.ts +124 -0
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Cell -
|
|
1
|
+
# Cell - Ta Exec
|
|
2
2
|
|
|
3
3
|
Agent 执行命令、读写文件的地方,作用相当于 Codex 的 exec-server:Agent 循环留在宿主,进程与文件操作交给执行环境。不依赖 pi。
|
|
4
4
|
|
|
@@ -14,4 +14,26 @@ interface ExecEnvironment {
|
|
|
14
14
|
|
|
15
15
|
路径一律是执行环境里的路径:不要交给 `node:fs`,交给模型的也只能是这些路径。
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
## 实现
|
|
18
|
+
|
|
19
|
+
| | |
|
|
20
|
+
| --- | --- |
|
|
21
|
+
| `LocalExecEnvironment` | 本机 |
|
|
22
|
+
| `RemoteExecEnvironment` + `ExecClient` | 另一台机器(容器、沙箱)上的 `ta exec-server` |
|
|
23
|
+
| `ExecServer` | `ta exec-server` 本身:一个不加载 Cell 的 HTTP 服务(空载约 60 MB) |
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
# 执行机(容器里)
|
|
27
|
+
TA_EXEC_TOKEN=... ta exec-server --host 0.0.0.0 --port 4200 --cwd /workspace
|
|
28
|
+
# 宿主
|
|
29
|
+
TA_EXEC_TOKEN=... ta serve --exec ws://exec-host:4200/exec
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
协议(`ExecRpc`)对标 Codex exec-server:WebSocket 上的 JSON-RPC 2.0,`process/exec`、`process/spawn`、`process/write`、`process/kill`、`fs/readFile`、`fs/writeFile`、`fs/stat`、`fs/readdir`、`fs/mkdir`、`fs/remove`;进程输出以 `process/output`、`process/stderr`、`process/exit` 通知推送,字节用 base64。
|
|
33
|
+
|
|
34
|
+
- **鉴权**:token(`Authorization: Bearer` 或 `?token=`)。安全边界是执行机本身(与 pi 一致:不在工具调用前审批,靠操作系统/容器隔离)。
|
|
35
|
+
- **环境变量**:工具传入的环境只发送它在宿主环境之上新增或改动的变量(`RemoteExecEnvironment.delta`),宿主的变量(API key 等)不会到执行机。
|
|
36
|
+
- **epoch 隔离**:宿主连接时带 epoch(默认是宿主启动时间)。更大的 epoch 连上后,执行机断开更小 epoch 的连接、杀掉它们启动的进程,之后它们的调用一律报 `CELL_TA_EXEC_STALE_EPOCH`:会话迁到新的宿主实例后,旧实例不能再执行工具。
|
|
37
|
+
- **进程归属连接**:连接断开即结束该连接启动的进程;`ExecClient` 在下一次调用时重连。
|
|
38
|
+
|
|
39
|
+
宿主侧的 pi 内置工具(read、bash、edit、write、ls、find、`!` 命令)与 stdio MCP 服务都经执行环境运行(见 @celljs/ta-harness 的 `ExecExtension`、`ExecMcpTransport`);ripgrep 版的 grep 只能在本机运行,远程时去掉,模型改用 bash 里的 `rg`。
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { ExecRpc } from './exec-rpc.js';
|
|
2
|
+
export interface ExecClientOptions {
|
|
3
|
+
/** The WebSocket URL of `ta exec-server`. */
|
|
4
|
+
url: string;
|
|
5
|
+
token: string;
|
|
6
|
+
/** Larger than the epoch of any host that ran these sessions before; see {@link ExecRpc.InitializeParams}. */
|
|
7
|
+
epoch: number;
|
|
8
|
+
}
|
|
9
|
+
/** A failed call to `ta exec-server`. */
|
|
10
|
+
export declare class ExecError extends Error {
|
|
11
|
+
readonly code: ExecRpc.ErrorCode;
|
|
12
|
+
constructor(message: string, code: ExecRpc.ErrorCode);
|
|
13
|
+
}
|
|
14
|
+
type NotificationListener = (method: string, params: {
|
|
15
|
+
data?: string;
|
|
16
|
+
exitCode?: number | null;
|
|
17
|
+
}) => void;
|
|
18
|
+
interface PendingCall {
|
|
19
|
+
resolve(result: unknown): void;
|
|
20
|
+
reject(error: Error): void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* One connection of a host to `ta exec-server`, shared by its environments. It connects on the first
|
|
24
|
+
* call and again on the first call after a loss; processes do not survive a loss. Once fenced by a
|
|
25
|
+
* host with a newer epoch it refuses every call: this host must stop running sessions there.
|
|
26
|
+
*/
|
|
27
|
+
export declare class ExecClient {
|
|
28
|
+
protected readonly options: ExecClientOptions;
|
|
29
|
+
protected socket?: Promise<WebSocket>;
|
|
30
|
+
protected current?: WebSocket;
|
|
31
|
+
protected nextCall: number;
|
|
32
|
+
protected nextProcess: number;
|
|
33
|
+
protected fenced: boolean;
|
|
34
|
+
protected initialized?: ExecRpc.InitializeResult;
|
|
35
|
+
protected readonly pending: Map<number, PendingCall>;
|
|
36
|
+
protected readonly listeners: Map<number, NotificationListener>;
|
|
37
|
+
constructor(options: ExecClientOptions);
|
|
38
|
+
call<T>(method: string, params: object): Promise<T>;
|
|
39
|
+
/** What the server said when this client connected. */
|
|
40
|
+
info(): Promise<ExecRpc.InitializeResult>;
|
|
41
|
+
/** An id for a process, which its notifications carry. */
|
|
42
|
+
processId(): number;
|
|
43
|
+
listen(id: number, listener: NotificationListener): () => void;
|
|
44
|
+
close(): void;
|
|
45
|
+
protected connect(): Promise<WebSocket>;
|
|
46
|
+
protected open(): Promise<WebSocket>;
|
|
47
|
+
protected send<T>(socket: WebSocket, method: string, params: object): Promise<T>;
|
|
48
|
+
protected receive(text: string): void;
|
|
49
|
+
/** Calls fail, and processes are gone: the server ended them with the connection. */
|
|
50
|
+
protected lost(socket: WebSocket): void;
|
|
51
|
+
}
|
|
52
|
+
export {};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { ExecRpc } from './exec-rpc.js';
|
|
2
|
+
/** A failed call to `ta exec-server`. */
|
|
3
|
+
export class ExecError extends Error {
|
|
4
|
+
constructor(message, code) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.name = 'ExecError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* One connection of a host to `ta exec-server`, shared by its environments. It connects on the first
|
|
12
|
+
* call and again on the first call after a loss; processes do not survive a loss. Once fenced by a
|
|
13
|
+
* host with a newer epoch it refuses every call: this host must stop running sessions there.
|
|
14
|
+
*/
|
|
15
|
+
export class ExecClient {
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.options = options;
|
|
18
|
+
this.nextCall = 0;
|
|
19
|
+
this.nextProcess = 0;
|
|
20
|
+
this.fenced = false;
|
|
21
|
+
this.pending = new Map();
|
|
22
|
+
this.listeners = new Map();
|
|
23
|
+
}
|
|
24
|
+
async call(method, params) {
|
|
25
|
+
const socket = await this.connect();
|
|
26
|
+
return this.send(socket, method, params);
|
|
27
|
+
}
|
|
28
|
+
/** What the server said when this client connected. */
|
|
29
|
+
async info() {
|
|
30
|
+
await this.connect();
|
|
31
|
+
return this.initialized;
|
|
32
|
+
}
|
|
33
|
+
/** An id for a process, which its notifications carry. */
|
|
34
|
+
processId() {
|
|
35
|
+
return ++this.nextProcess;
|
|
36
|
+
}
|
|
37
|
+
listen(id, listener) {
|
|
38
|
+
this.listeners.set(id, listener);
|
|
39
|
+
return () => this.listeners.delete(id);
|
|
40
|
+
}
|
|
41
|
+
close() {
|
|
42
|
+
var _a;
|
|
43
|
+
(_a = this.current) === null || _a === void 0 ? void 0 : _a.close();
|
|
44
|
+
this.current = undefined;
|
|
45
|
+
this.socket = undefined;
|
|
46
|
+
}
|
|
47
|
+
connect() {
|
|
48
|
+
var _a;
|
|
49
|
+
if (this.fenced) {
|
|
50
|
+
return Promise.reject(new ExecError('A host with a newer epoch took over the execution environment.', ExecRpc.ErrorCode.STALE_EPOCH));
|
|
51
|
+
}
|
|
52
|
+
(_a = this.socket) !== null && _a !== void 0 ? _a : (this.socket = this.open().catch(error => {
|
|
53
|
+
this.socket = undefined;
|
|
54
|
+
throw error;
|
|
55
|
+
}));
|
|
56
|
+
return this.socket;
|
|
57
|
+
}
|
|
58
|
+
async open() {
|
|
59
|
+
const url = new URL(this.options.url);
|
|
60
|
+
url.searchParams.set('token', this.options.token);
|
|
61
|
+
const socket = new WebSocket(url);
|
|
62
|
+
await new Promise((resolve, reject) => {
|
|
63
|
+
socket.onopen = () => resolve();
|
|
64
|
+
socket.onerror = () => reject(new ExecError(`Cannot connect to ${this.options.url}.`, ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
65
|
+
});
|
|
66
|
+
socket.onmessage = message => this.receive(String(message.data));
|
|
67
|
+
this.current = socket;
|
|
68
|
+
socket.onclose = () => this.lost(socket);
|
|
69
|
+
try {
|
|
70
|
+
this.initialized = await this.send(socket, ExecRpc.Method.INITIALIZE, { epoch: this.options.epoch });
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (error.code === ExecRpc.ErrorCode.STALE_EPOCH) {
|
|
74
|
+
this.fenced = true;
|
|
75
|
+
}
|
|
76
|
+
socket.close();
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
return socket;
|
|
80
|
+
}
|
|
81
|
+
send(socket, method, params) {
|
|
82
|
+
if (socket.readyState !== WebSocket.OPEN) {
|
|
83
|
+
return Promise.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
84
|
+
}
|
|
85
|
+
const id = ++this.nextCall;
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
this.pending.set(id, { resolve: resolve, reject });
|
|
88
|
+
socket.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }));
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
receive(text) {
|
|
92
|
+
var _a, _b, _c;
|
|
93
|
+
var _d;
|
|
94
|
+
const message = JSON.parse(text);
|
|
95
|
+
if (message.method) {
|
|
96
|
+
(_b = this.listeners.get((_a = message.params) === null || _a === void 0 ? void 0 : _a.id)) === null || _b === void 0 ? void 0 : _b(message.method, message.params);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const call = this.pending.get(message.id);
|
|
100
|
+
this.pending.delete(message.id);
|
|
101
|
+
if (message.error) {
|
|
102
|
+
const code = (_d = (_c = message.error.data) === null || _c === void 0 ? void 0 : _c.code) !== null && _d !== void 0 ? _d : ExecRpc.ErrorCode.FAILED;
|
|
103
|
+
if (code === ExecRpc.ErrorCode.STALE_EPOCH) {
|
|
104
|
+
this.fenced = true;
|
|
105
|
+
}
|
|
106
|
+
call === null || call === void 0 ? void 0 : call.reject(new ExecError(message.error.message, code));
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
call === null || call === void 0 ? void 0 : call.resolve(message.result);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** Calls fail, and processes are gone: the server ended them with the connection. */
|
|
113
|
+
lost(socket) {
|
|
114
|
+
if (this.current === socket) {
|
|
115
|
+
this.current = undefined;
|
|
116
|
+
this.socket = undefined;
|
|
117
|
+
}
|
|
118
|
+
for (const call of this.pending.values()) {
|
|
119
|
+
call.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
120
|
+
}
|
|
121
|
+
this.pending.clear();
|
|
122
|
+
for (const listener of [...this.listeners.values()]) {
|
|
123
|
+
listener(ExecRpc.Notification.EXIT, { exitCode: null });
|
|
124
|
+
}
|
|
125
|
+
this.listeners.clear();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=exec-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exec-client.js","sourceRoot":"","sources":["../../src/node/exec-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAUrC,yCAAyC;AACzC,MAAM,OAAO,SAAU,SAAQ,KAAK;IAChC,YACI,OAAe,EACN,IAAuB;QAEhC,KAAK,CAAC,OAAO,CAA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,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC;QAC3H,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,KAAK,MAAM,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;YAClD,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QAC5D,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IAC3B,CAAC;CACJ"}
|
|
@@ -58,4 +58,6 @@ export interface ExecEnvironment {
|
|
|
58
58
|
/** Bind another implementation with `rebind: true` to run sessions elsewhere. */
|
|
59
59
|
export interface ExecEnvironmentFactory {
|
|
60
60
|
create(cwd: string): ExecEnvironment;
|
|
61
|
+
/** Where sessions run when nobody names a directory: a path of the environment. */
|
|
62
|
+
defaultCwd(): Promise<string>;
|
|
61
63
|
}
|
|
@@ -0,0 +1,90 @@
|
|
|
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.
|
|
5
|
+
*/
|
|
6
|
+
export declare namespace ExecRpc {
|
|
7
|
+
/** Path of the WebSocket endpoint. */
|
|
8
|
+
const PATH = "/exec";
|
|
9
|
+
const Method: {
|
|
10
|
+
readonly INITIALIZE: 'initialize';
|
|
11
|
+
readonly EXEC: 'process/exec';
|
|
12
|
+
readonly SPAWN: 'process/spawn';
|
|
13
|
+
readonly WRITE: 'process/write';
|
|
14
|
+
readonly KILL: 'process/kill';
|
|
15
|
+
readonly READ_FILE: 'fs/readFile';
|
|
16
|
+
readonly WRITE_FILE: 'fs/writeFile';
|
|
17
|
+
readonly STAT: 'fs/stat';
|
|
18
|
+
readonly READDIR: 'fs/readdir';
|
|
19
|
+
readonly MKDIR: 'fs/mkdir';
|
|
20
|
+
readonly REMOVE: 'fs/remove';
|
|
21
|
+
};
|
|
22
|
+
const Notification: {
|
|
23
|
+
/** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
|
|
24
|
+
readonly OUTPUT: 'process/output';
|
|
25
|
+
readonly STDERR: 'process/stderr';
|
|
26
|
+
/** A spawned process ended. */
|
|
27
|
+
readonly EXIT: 'process/exit';
|
|
28
|
+
};
|
|
29
|
+
/** `error.data.code` of failed calls. */
|
|
30
|
+
const ErrorCode: {
|
|
31
|
+
/** A host with a newer epoch connected: this one may no longer run anything. */
|
|
32
|
+
readonly STALE_EPOCH: 'CELL_TA_EXEC_STALE_EPOCH';
|
|
33
|
+
readonly NOT_INITIALIZED: 'CELL_TA_EXEC_NOT_INITIALIZED';
|
|
34
|
+
readonly FAILED: 'CELL_TA_EXEC_FAILED';
|
|
35
|
+
readonly CONNECTION_LOST: 'CELL_TA_EXEC_CONNECTION_LOST';
|
|
36
|
+
};
|
|
37
|
+
type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
|
|
38
|
+
/**
|
|
39
|
+
* The epoch fences hosts: when a session moves to another host instance (a restart, a failover), the
|
|
40
|
+
* new one connects with a larger epoch, and the server stops taking calls from smaller ones and kills
|
|
41
|
+
* their processes, so that two hosts never run the same session's tools.
|
|
42
|
+
*/
|
|
43
|
+
interface InitializeParams {
|
|
44
|
+
epoch: number;
|
|
45
|
+
}
|
|
46
|
+
interface InitializeResult {
|
|
47
|
+
platform: string;
|
|
48
|
+
/** The working directory of the server: where sessions run when nobody names another. */
|
|
49
|
+
cwd: string;
|
|
50
|
+
}
|
|
51
|
+
/** Every call names the directory of its environment; a relative `cwd` or path resolves against it. */
|
|
52
|
+
interface ProcessParams {
|
|
53
|
+
root: string;
|
|
54
|
+
/** Chosen by the host, unique per connection: the notifications carry it. */
|
|
55
|
+
id: number;
|
|
56
|
+
cwd?: string;
|
|
57
|
+
/** Only what the host sets on top of the server's own environment, never the host's environment. */
|
|
58
|
+
env?: Record<string, string>;
|
|
59
|
+
}
|
|
60
|
+
interface ExecParams extends ProcessParams {
|
|
61
|
+
command: string;
|
|
62
|
+
timeout?: number;
|
|
63
|
+
}
|
|
64
|
+
interface SpawnParams extends ProcessParams {
|
|
65
|
+
command: string;
|
|
66
|
+
args: string[];
|
|
67
|
+
}
|
|
68
|
+
interface PathParams {
|
|
69
|
+
root: string;
|
|
70
|
+
path: string;
|
|
71
|
+
}
|
|
72
|
+
interface Message {
|
|
73
|
+
jsonrpc: '2.0';
|
|
74
|
+
id?: number;
|
|
75
|
+
method?: string;
|
|
76
|
+
params?: any;
|
|
77
|
+
result?: unknown;
|
|
78
|
+
error?: {
|
|
79
|
+
code: number;
|
|
80
|
+
message: string;
|
|
81
|
+
data?: {
|
|
82
|
+
code: ErrorCode;
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
const ERROR = -32060;
|
|
87
|
+
function error(id: number | undefined, code: ErrorCode, message: string): Message;
|
|
88
|
+
function toBase64(data: Uint8Array | string): string;
|
|
89
|
+
function fromBase64(data: string): Uint8Array;
|
|
90
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
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.
|
|
5
|
+
*/
|
|
6
|
+
export var ExecRpc;
|
|
7
|
+
(function (ExecRpc) {
|
|
8
|
+
/** Path of the WebSocket endpoint. */
|
|
9
|
+
ExecRpc.PATH = '/exec';
|
|
10
|
+
ExecRpc.Method = {
|
|
11
|
+
INITIALIZE: 'initialize',
|
|
12
|
+
EXEC: 'process/exec',
|
|
13
|
+
SPAWN: 'process/spawn',
|
|
14
|
+
WRITE: 'process/write',
|
|
15
|
+
KILL: 'process/kill',
|
|
16
|
+
READ_FILE: 'fs/readFile',
|
|
17
|
+
WRITE_FILE: 'fs/writeFile',
|
|
18
|
+
STAT: 'fs/stat',
|
|
19
|
+
READDIR: 'fs/readdir',
|
|
20
|
+
MKDIR: 'fs/mkdir',
|
|
21
|
+
REMOVE: 'fs/remove',
|
|
22
|
+
};
|
|
23
|
+
ExecRpc.Notification = {
|
|
24
|
+
/** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
|
|
25
|
+
OUTPUT: 'process/output',
|
|
26
|
+
STDERR: 'process/stderr',
|
|
27
|
+
/** A spawned process ended. */
|
|
28
|
+
EXIT: 'process/exit',
|
|
29
|
+
};
|
|
30
|
+
/** `error.data.code` of failed calls. */
|
|
31
|
+
ExecRpc.ErrorCode = {
|
|
32
|
+
/** A host with a newer epoch connected: this one may no longer run anything. */
|
|
33
|
+
STALE_EPOCH: 'CELL_TA_EXEC_STALE_EPOCH',
|
|
34
|
+
NOT_INITIALIZED: 'CELL_TA_EXEC_NOT_INITIALIZED',
|
|
35
|
+
FAILED: 'CELL_TA_EXEC_FAILED',
|
|
36
|
+
CONNECTION_LOST: 'CELL_TA_EXEC_CONNECTION_LOST',
|
|
37
|
+
};
|
|
38
|
+
ExecRpc.ERROR = -32060;
|
|
39
|
+
function error(id, code, message) {
|
|
40
|
+
return { jsonrpc: '2.0', id, error: { code: ExecRpc.ERROR, message, data: { code } } };
|
|
41
|
+
}
|
|
42
|
+
ExecRpc.error = error;
|
|
43
|
+
function toBase64(data) {
|
|
44
|
+
return Buffer.from(data).toString('base64');
|
|
45
|
+
}
|
|
46
|
+
ExecRpc.toBase64 = toBase64;
|
|
47
|
+
function fromBase64(data) {
|
|
48
|
+
return Buffer.from(data, 'base64');
|
|
49
|
+
}
|
|
50
|
+
ExecRpc.fromBase64 = fromBase64;
|
|
51
|
+
})(ExecRpc || (ExecRpc = {}));
|
|
52
|
+
//# sourceMappingURL=exec-rpc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file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AAA;IAED,SAAgB,UAAU,CAAC,IAAY;QACnC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACvC,CAAC;IAFe,QAAA,UAAU,aAEzB,CAAA;AACL,CAAC,EAlGgB,OAAO,KAAP,OAAO,QAkGvB"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type IncomingMessage, type Server } from 'node:http';
|
|
2
|
+
import type { Duplex } from 'node:stream';
|
|
3
|
+
import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
4
|
+
import type { ExecProcess } from './exec-protocol.js';
|
|
5
|
+
import { ExecRpc } from './exec-rpc.js';
|
|
6
|
+
import { LocalExecEnvironment } from './local-exec-environment.js';
|
|
7
|
+
export interface ExecServerOptions {
|
|
8
|
+
/** Default 127.0.0.1. */
|
|
9
|
+
host?: string;
|
|
10
|
+
/** Default: a free port. */
|
|
11
|
+
port?: number;
|
|
12
|
+
/** What hosts must present. */
|
|
13
|
+
token: string;
|
|
14
|
+
/** Default: the working directory of the process. */
|
|
15
|
+
cwd?: string;
|
|
16
|
+
/** Largest message in bytes, for files in one piece. Default 64 MiB. */
|
|
17
|
+
maxPayload?: number;
|
|
18
|
+
}
|
|
19
|
+
type Method = (typeof ExecRpc.Method)[keyof typeof ExecRpc.Method];
|
|
20
|
+
/**
|
|
21
|
+
* `ta exec-server`: runs the commands and file operations of a host's sessions on this machine, which
|
|
22
|
+
* may be a container or a sandbox: the security boundary is the machine, as pi's is. Processes belong
|
|
23
|
+
* to the connection that started them and end with it.
|
|
24
|
+
*/
|
|
25
|
+
export declare class ExecServer {
|
|
26
|
+
protected readonly options: ExecServerOptions;
|
|
27
|
+
protected server?: Server;
|
|
28
|
+
/** The largest epoch a host connected with. */
|
|
29
|
+
protected epoch: number;
|
|
30
|
+
protected readonly peers: Set<ExecPeer>;
|
|
31
|
+
constructor(options: ExecServerOptions);
|
|
32
|
+
get cwd(): string;
|
|
33
|
+
/** Resolves to the WebSocket URL. */
|
|
34
|
+
listen(): Promise<string>;
|
|
35
|
+
close(): Promise<void>;
|
|
36
|
+
/** False when a newer host has taken over; a newer one fences the older ones. */
|
|
37
|
+
admit(peer: ExecPeer, epoch: number): boolean;
|
|
38
|
+
isCurrent(epoch: number | undefined): boolean;
|
|
39
|
+
protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void;
|
|
40
|
+
protected matches(token: string): boolean;
|
|
41
|
+
}
|
|
42
|
+
/** One host connection: its calls, and the processes it started. */
|
|
43
|
+
export declare class ExecPeer {
|
|
44
|
+
protected readonly server: ExecServer;
|
|
45
|
+
protected readonly connection: WebSocketConnection;
|
|
46
|
+
epoch?: number;
|
|
47
|
+
protected readonly running: Map<number, AbortController>;
|
|
48
|
+
protected readonly spawned: Map<number, ExecProcess>;
|
|
49
|
+
constructor(server: ExecServer, connection: WebSocketConnection);
|
|
50
|
+
close(code: number, reason: string): void;
|
|
51
|
+
/** Ends what this host started. */
|
|
52
|
+
dispose(): void;
|
|
53
|
+
protected receive(text: string): Promise<void>;
|
|
54
|
+
protected initialize(id: number | undefined, params: ExecRpc.InitializeParams): ExecRpc.Message;
|
|
55
|
+
protected call(method: Method, params: any): Promise<unknown>;
|
|
56
|
+
protected exec(environment: LocalExecEnvironment, params: ExecRpc.ExecParams): Promise<unknown>;
|
|
57
|
+
protected spawn(environment: LocalExecEnvironment, params: ExecRpc.SpawnParams): void;
|
|
58
|
+
protected notify(method: string, params: unknown): void;
|
|
59
|
+
protected send(message: ExecRpc.Message): void;
|
|
60
|
+
}
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
4
|
+
import { ExecRpc } from './exec-rpc.js';
|
|
5
|
+
import { LocalExecEnvironment } from './local-exec-environment.js';
|
|
6
|
+
/**
|
|
7
|
+
* `ta exec-server`: runs the commands and file operations of a host's sessions on this machine, which
|
|
8
|
+
* may be a container or a sandbox: the security boundary is the machine, as pi's is. Processes belong
|
|
9
|
+
* to the connection that started them and end with it.
|
|
10
|
+
*/
|
|
11
|
+
export class ExecServer {
|
|
12
|
+
constructor(options) {
|
|
13
|
+
this.options = options;
|
|
14
|
+
/** The largest epoch a host connected with. */
|
|
15
|
+
this.epoch = 0;
|
|
16
|
+
this.peers = new Set();
|
|
17
|
+
}
|
|
18
|
+
get cwd() {
|
|
19
|
+
var _a;
|
|
20
|
+
return (_a = this.options.cwd) !== null && _a !== void 0 ? _a : process.cwd();
|
|
21
|
+
}
|
|
22
|
+
/** Resolves to the WebSocket URL. */
|
|
23
|
+
async listen() {
|
|
24
|
+
var _a;
|
|
25
|
+
const server = createServer((_request, response) => response.writeHead(404).end());
|
|
26
|
+
server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
|
|
27
|
+
this.server = server;
|
|
28
|
+
await new Promise(resolve => { var _a, _b; return server.listen((_a = this.options.port) !== null && _a !== void 0 ? _a : 0, (_b = this.options.host) !== null && _b !== void 0 ? _b : '127.0.0.1', resolve); });
|
|
29
|
+
const { port } = server.address();
|
|
30
|
+
return `ws://${(_a = this.options.host) !== null && _a !== void 0 ? _a : '127.0.0.1'}:${port}${ExecRpc.PATH}`;
|
|
31
|
+
}
|
|
32
|
+
async close() {
|
|
33
|
+
for (const peer of this.peers) {
|
|
34
|
+
peer.close(1001, 'The server stops.');
|
|
35
|
+
}
|
|
36
|
+
await new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
|
|
37
|
+
}
|
|
38
|
+
/** False when a newer host has taken over; a newer one fences the older ones. */
|
|
39
|
+
admit(peer, epoch) {
|
|
40
|
+
if (epoch < this.epoch) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (epoch > this.epoch) {
|
|
44
|
+
this.epoch = epoch;
|
|
45
|
+
for (const other of this.peers) {
|
|
46
|
+
if (other !== peer && other.epoch !== undefined && other.epoch < epoch) {
|
|
47
|
+
other.close(4001, 'A host with a newer epoch connected.');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
isCurrent(epoch) {
|
|
54
|
+
return epoch === this.epoch;
|
|
55
|
+
}
|
|
56
|
+
upgrade(request, socket, head) {
|
|
57
|
+
var _a, _b;
|
|
58
|
+
const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://localhost');
|
|
59
|
+
if (url.pathname !== ExecRpc.PATH) {
|
|
60
|
+
WebSocketConnection.refuse(socket, 404, 'Not found.');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const checked = WebSocketConnection.check(request);
|
|
64
|
+
if ('status' in checked) {
|
|
65
|
+
WebSocketConnection.refuse(socket, checked.status, checked.message);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const header = request.headers.authorization;
|
|
69
|
+
const token = (header === null || header === void 0 ? void 0 : header.startsWith('Bearer ')) ? header.slice('Bearer '.length) : url.searchParams.get('token');
|
|
70
|
+
if (!token || !this.matches(token)) {
|
|
71
|
+
WebSocketConnection.refuse(socket, 401, 'Not authorized.');
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: (_b = this.options.maxPayload) !== null && _b !== void 0 ? _b : 67108864, heartbeat: 30000 });
|
|
75
|
+
const peer = new ExecPeer(this, connection);
|
|
76
|
+
this.peers.add(peer);
|
|
77
|
+
connection.onClose(() => {
|
|
78
|
+
this.peers.delete(peer);
|
|
79
|
+
peer.dispose();
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
matches(token) {
|
|
83
|
+
const [left, right] = [Buffer.from(token), Buffer.from(this.options.token)];
|
|
84
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** One host connection: its calls, and the processes it started. */
|
|
88
|
+
export class ExecPeer {
|
|
89
|
+
constructor(server, connection) {
|
|
90
|
+
this.server = server;
|
|
91
|
+
this.connection = connection;
|
|
92
|
+
this.running = new Map();
|
|
93
|
+
this.spawned = new Map();
|
|
94
|
+
connection.onMessage(text => void this.receive(text));
|
|
95
|
+
}
|
|
96
|
+
close(code, reason) {
|
|
97
|
+
this.dispose();
|
|
98
|
+
this.connection.close(code, reason);
|
|
99
|
+
}
|
|
100
|
+
/** Ends what this host started. */
|
|
101
|
+
dispose() {
|
|
102
|
+
for (const controller of this.running.values()) {
|
|
103
|
+
controller.abort();
|
|
104
|
+
}
|
|
105
|
+
for (const child of this.spawned.values()) {
|
|
106
|
+
child.kill();
|
|
107
|
+
}
|
|
108
|
+
this.running.clear();
|
|
109
|
+
this.spawned.clear();
|
|
110
|
+
}
|
|
111
|
+
async receive(text) {
|
|
112
|
+
var _a;
|
|
113
|
+
let message;
|
|
114
|
+
try {
|
|
115
|
+
message = JSON.parse(text);
|
|
116
|
+
}
|
|
117
|
+
catch (_b) {
|
|
118
|
+
this.connection.close(1007, 'Not JSON.');
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const { id, method, params } = message;
|
|
122
|
+
let reply;
|
|
123
|
+
if (method === ExecRpc.Method.INITIALIZE) {
|
|
124
|
+
reply = this.initialize(id, params);
|
|
125
|
+
}
|
|
126
|
+
else if (this.epoch === undefined) {
|
|
127
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.NOT_INITIALIZED, 'Call initialize first.');
|
|
128
|
+
}
|
|
129
|
+
else if (!this.server.isCurrent(this.epoch)) {
|
|
130
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch took over.');
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
try {
|
|
134
|
+
reply = { jsonrpc: '2.0', id, result: (_a = (await this.call(method, params))) !== null && _a !== void 0 ? _a : null };
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.FAILED, error instanceof Error ? error.message : String(error));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (id !== undefined) {
|
|
141
|
+
this.send(reply);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
initialize(id, params) {
|
|
145
|
+
if (typeof (params === null || params === void 0 ? void 0 : params.epoch) !== 'number' || !this.server.admit(this, params.epoch)) {
|
|
146
|
+
return ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch is connected.');
|
|
147
|
+
}
|
|
148
|
+
this.epoch = params.epoch;
|
|
149
|
+
const result = { platform: process.platform, cwd: this.server.cwd };
|
|
150
|
+
return { jsonrpc: '2.0', id, result };
|
|
151
|
+
}
|
|
152
|
+
async call(method, params) {
|
|
153
|
+
var _a, _b, _c;
|
|
154
|
+
var _d;
|
|
155
|
+
const environment = new LocalExecEnvironment((_d = params.root) !== null && _d !== void 0 ? _d : this.server.cwd);
|
|
156
|
+
switch (method) {
|
|
157
|
+
case ExecRpc.Method.EXEC:
|
|
158
|
+
return this.exec(environment, params);
|
|
159
|
+
case ExecRpc.Method.SPAWN:
|
|
160
|
+
return this.spawn(environment, params);
|
|
161
|
+
case ExecRpc.Method.WRITE:
|
|
162
|
+
(_a = this.spawned.get(params.id)) === null || _a === void 0 ? void 0 : _a.write(ExecRpc.fromBase64(params.data));
|
|
163
|
+
return;
|
|
164
|
+
case ExecRpc.Method.KILL:
|
|
165
|
+
(_b = this.running.get(params.id)) === null || _b === void 0 ? void 0 : _b.abort();
|
|
166
|
+
(_c = this.spawned.get(params.id)) === null || _c === void 0 ? void 0 : _c.kill();
|
|
167
|
+
return;
|
|
168
|
+
case ExecRpc.Method.READ_FILE:
|
|
169
|
+
return ExecRpc.toBase64(await environment.readFile(params.path));
|
|
170
|
+
case ExecRpc.Method.WRITE_FILE:
|
|
171
|
+
return environment.writeFile(params.path, ExecRpc.fromBase64(params.data));
|
|
172
|
+
case ExecRpc.Method.STAT:
|
|
173
|
+
return environment.stat(params.path);
|
|
174
|
+
case ExecRpc.Method.READDIR:
|
|
175
|
+
return environment.readdir(params.path);
|
|
176
|
+
case ExecRpc.Method.MKDIR:
|
|
177
|
+
return environment.mkdir(params.path);
|
|
178
|
+
case ExecRpc.Method.REMOVE:
|
|
179
|
+
return environment.remove(params.path, { recursive: params.recursive });
|
|
180
|
+
default:
|
|
181
|
+
throw new Error(`No method ${method}.`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async exec(environment, params) {
|
|
185
|
+
const controller = new AbortController();
|
|
186
|
+
this.running.set(params.id, controller);
|
|
187
|
+
try {
|
|
188
|
+
return await environment.exec(params.command, {
|
|
189
|
+
cwd: params.cwd,
|
|
190
|
+
env: { ...process.env, ...params.env },
|
|
191
|
+
timeout: params.timeout,
|
|
192
|
+
signal: controller.signal,
|
|
193
|
+
onData: data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }),
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
this.running.delete(params.id);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
spawn(environment, params) {
|
|
201
|
+
const child = environment.spawn(params.command, params.args, { cwd: params.cwd, env: { ...process.env, ...params.env } });
|
|
202
|
+
this.spawned.set(params.id, child);
|
|
203
|
+
child.onStdout(data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
204
|
+
child.onStderr(data => this.notify(ExecRpc.Notification.STDERR, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
205
|
+
child.onExit(exitCode => {
|
|
206
|
+
this.spawned.delete(params.id);
|
|
207
|
+
this.notify(ExecRpc.Notification.EXIT, { id: params.id, exitCode });
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
notify(method, params) {
|
|
211
|
+
this.send({ jsonrpc: '2.0', method, params });
|
|
212
|
+
}
|
|
213
|
+
send(message) {
|
|
214
|
+
this.connection.send(JSON.stringify(message));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
//# sourceMappingURL=exec-server.js.map
|