@x-otto/workspace 0.1.0-alpha.43 → 0.3.0-beta.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.
- package/dist/build-revision.json +4 -0
- package/dist/index.d.ts +71 -196
- package/dist/index.js +287 -16
- package/package.json +10 -12
- package/runner/app-runner.mjs +74 -0
- package/README.md +0 -98
package/dist/index.d.ts
CHANGED
|
@@ -1,206 +1,81 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
* docs/rfc/RFC-034-workspace-mechanism-persistence-dimension.md §4.1。
|
|
8
|
-
*
|
|
9
|
-
* 历史注(RFC-067 M115-04,2026-08-14 执行):早期设计有 `backend`(local/remote) × `root`
|
|
10
|
-
* 两正交轴推导出的 L/R/V 三形态 + `RemoteRef`/信任门。经核实 R/V 生产不可达(无代码写带
|
|
11
|
-
* remote 的 marker、`confirmTrust` 从不注入、`backend` 恒 'local' 且无真实分支),且实际上线
|
|
12
|
-
* 的 workspace 记忆远端同步(RFC-164)走的是独立的 `sessionUrl + memorySyncEnabled opt-in`
|
|
13
|
-
* 轴(见 coding/storage-wiring.ts),与 `backend` 无关——证伪了原抽象方向。故塌成 L。将来若
|
|
14
|
-
* 真需远端 workspace 后端,应以可替换 provider seam 重新长出,而非复活死枚举。
|
|
15
|
-
*/
|
|
16
|
-
/**
|
|
17
|
-
* 运行时引用:身份永远是 `ws_<id>`,本地文件根为 `root`(唯一 L 形态)。
|
|
18
|
-
*/
|
|
19
|
-
interface WorkspaceRef {
|
|
20
|
-
/** = `ws_` + id,持久化第一维。 */
|
|
21
|
-
readonly key: string;
|
|
22
|
-
readonly id: string;
|
|
23
|
-
/** 本地文件根(工具 root)。 */
|
|
24
|
-
readonly root: string;
|
|
25
|
-
/**
|
|
26
|
-
* workspace 记忆远端同步 opt-in(RFC-164 M164-2 D2),透传自 `WorkspaceMarker`。
|
|
27
|
-
* 缺省/`false` = 记忆走本地文件(M58-02 现状);`true` = auto-memory/lessons 走远端。
|
|
28
|
-
*/
|
|
29
|
-
readonly memorySyncEnabled?: boolean;
|
|
1
|
+
import { SandboxPort } from "@x-otto/kernel";
|
|
2
|
+
|
|
3
|
+
//#region src/sandbox-launch.d.ts
|
|
4
|
+
interface ProcessSandbox {
|
|
5
|
+
port: SandboxPort;
|
|
6
|
+
cwd: string;
|
|
30
7
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/executor.d.ts
|
|
10
|
+
declare const APP_ENV_ALLOWLIST: readonly string[];
|
|
11
|
+
declare function appChildEnv(read: (key: string) => string | undefined, extra?: Readonly<Record<string, string>>): NodeJS.ProcessEnv;
|
|
12
|
+
interface AppExecutorOptions {
|
|
13
|
+
appEntry: string;
|
|
14
|
+
input: unknown;
|
|
15
|
+
config?: Readonly<Record<string, unknown>>;
|
|
16
|
+
timeoutMs?: number;
|
|
17
|
+
sandbox?: ProcessSandbox;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
readEnv?(key: string): string | undefined;
|
|
20
|
+
callAtom(atom: string, input: unknown): Promise<unknown>;
|
|
44
21
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
*/
|
|
49
|
-
interface WorkspaceIO {
|
|
50
|
-
/** 读文件 utf-8;不存在返回 null(不抛)。 */
|
|
51
|
-
readFile(path: string): Promise<string | null>;
|
|
52
|
-
/** 写文件 utf-8(父目录由实现保证存在)。 */
|
|
53
|
-
writeFile(path: string, content: string): Promise<void>;
|
|
54
|
-
/**
|
|
55
|
-
* RFC-303 D7(M2 T303-05):独占创建写——O_EXCL 语义,目标文件已存在则失败
|
|
56
|
-
* (返回 `false`,不覆盖、不抛异常),成功创建返回 `true`。用于并发首启创建互斥
|
|
57
|
-
* (两进程同时对空目录 createLocal 时,只有一个能真正创建 marker,另一个应改为
|
|
58
|
-
* 读取刚创建的 marker 复用其 id,而非各自生成不同 id 互相覆盖)。
|
|
59
|
-
*/
|
|
60
|
-
writeFileExclusive(path: string, content: string): Promise<boolean>;
|
|
61
|
-
/** 生成不可变 workspace id(默认实现见 id.ts)。 */
|
|
62
|
-
genId(): string;
|
|
63
|
-
/** 当前时间 ISO 串;注入式(纯层不直接取系统时钟,便于测试)。 */
|
|
64
|
-
now(): string;
|
|
22
|
+
interface AppExecutorResult {
|
|
23
|
+
value: unknown;
|
|
24
|
+
logs: readonly string[];
|
|
65
25
|
}
|
|
26
|
+
declare function runApp(options: AppExecutorOptions): Promise<AppExecutorResult>;
|
|
66
27
|
//#endregion
|
|
67
|
-
//#region src/
|
|
68
|
-
|
|
69
|
-
declare const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
/** id 是否合法(charset `[A-Za-z0-9_-]`,长度 1..64)。 */
|
|
77
|
-
declare function isValidWorkspaceId(id: string): boolean;
|
|
78
|
-
/** 校验 id,不合法即抛(fail-closed;读 marker / bind 入口用)。 */
|
|
79
|
-
declare function assertValidWorkspaceId(id: string): void;
|
|
80
|
-
/**
|
|
81
|
-
* 持久化第一维 key。id 不可变 ⇒ key 稳定。
|
|
82
|
-
* 校验后拼接,杜绝非法 id 进入 storage/URL。
|
|
83
|
-
*/
|
|
84
|
-
declare function workspaceKey(id: string): string;
|
|
85
|
-
/**
|
|
86
|
-
* 默认 id 生成器:客户端生成、全局唯一、不可变(RFC 规则 1)。
|
|
87
|
-
* 用 uuid(去横线 → 32 hex),落在合法字符集内;远端 bind 时直接接受(不重分配)。
|
|
88
|
-
* resolver 接受注入覆盖以便测试。
|
|
89
|
-
*/
|
|
90
|
-
declare function genWorkspaceId(): string;
|
|
91
|
-
//#endregion
|
|
92
|
-
//#region src/marker.d.ts
|
|
93
|
-
/** workspace 本地足迹目录名。 */
|
|
94
|
-
declare const MARKER_DIR = ".otto";
|
|
95
|
-
/** 关联 marker 文件名。 */
|
|
96
|
-
declare const MARKER_FILE = "workspace.json";
|
|
97
|
-
/** 生成的 gitignore 文件名。 */
|
|
98
|
-
declare const GITIGNORE_FILE = ".gitignore";
|
|
99
|
-
/**
|
|
100
|
-
* `.otto/.gitignore` 模板(RFC-034 规则 3 / 决策 D4):
|
|
101
|
-
* 身份(`workspace.json`)默认私有 + 易变忽略;项目知识(AGENTS.md/MEMORY.md/memory/)默认提交。
|
|
102
|
-
* 团队共享 workspace 实体需显式 `git add -f .otto/workspace.json`。
|
|
103
|
-
*/
|
|
104
|
-
declare const OTTO_GITIGNORE = "# otto workspace \u672C\u5730\u8DB3\u8FF9 \u2014 RFC-034 \u89C4\u5219 3\n# \u8EAB\u4EFD\u79C1\u6709 + \u6613\u53D8\u5FFD\u7565;\u9879\u76EE\u77E5\u8BC6(AGENTS.md / MEMORY.md / memory/)\u9ED8\u8BA4\u63D0\u4EA4\u3002\n# \u56E2\u961F\u5171\u4EAB workspace \u5B9E\u4F53:\u663E\u5F0F `git add -f .otto/workspace.json`\u3002\nworkspace.json\ncache/\nlogs/\n*.tmp\n# Machine-specific memory (RFC-164 M164-1 D3) \u2014 local/ is never synced across devices, never committed.\nlocal/\n";
|
|
105
|
-
/**
|
|
106
|
-
* 按 `memorySyncEnabled` 状态生成 gitignore 内容——opt-in 生效时追加 D4 单一权威切换规则。
|
|
107
|
-
* `writeMarker` 用此替代裸 `OTTO_GITIGNORE` 常量,使 marker 与 gitignore 内容随 opt-in 状态同步。
|
|
108
|
-
*
|
|
109
|
-
* 注意:`writeMarker` 会同时写入 gitignore 以保证 marker 的 `memorySyncEnabled` 字段与
|
|
110
|
-
* gitignore 规则一致——用户自定义 gitignore 规则应写在 `.otto/.gitignore` 文件末尾。
|
|
111
|
-
*/
|
|
112
|
-
declare function buildGitignoreContent(memorySyncEnabled: boolean): string;
|
|
113
|
-
/** `<dir>/.otto/workspace.json` 绝对路径。 */
|
|
114
|
-
declare function markerPath(dir: string): string;
|
|
115
|
-
/** `<dir>/.otto/.gitignore` 绝对路径。 */
|
|
116
|
-
declare function gitignorePath(dir: string): string;
|
|
117
|
-
/** 读取某目录的 marker;不存在返回 null,内容非法则抛(fail-closed)。 */
|
|
118
|
-
declare function readMarker(dir: string, io: WorkspaceIO): Promise<WorkspaceMarker | null>;
|
|
119
|
-
/** 命中结果:marker 所在目录 + 解析内容。 */
|
|
120
|
-
interface MarkerHit {
|
|
121
|
-
readonly dir: string;
|
|
122
|
-
readonly marker: WorkspaceMarker;
|
|
28
|
+
//#region src/rpc.d.ts
|
|
29
|
+
declare const RPC_MAX_FRAME_BYTES: number;
|
|
30
|
+
declare const APP_ATOMS: readonly ["http.request"];
|
|
31
|
+
type AppAtom = (typeof APP_ATOMS)[number];
|
|
32
|
+
type RpcErrorCode = 'FRAME_TOO_LARGE' | 'INVALID_FRAME' | 'ATOM_NOT_ALLOWED' | 'ATOM_FAILED';
|
|
33
|
+
interface RpcRequest {
|
|
34
|
+
id: string;
|
|
35
|
+
method: 'atom.call';
|
|
36
|
+
params?: Record<string, unknown>;
|
|
123
37
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
declare function writeMarker(dir: string, marker: WorkspaceMarker, io: WorkspaceIO, options?: {
|
|
138
|
-
exclusive?: boolean;
|
|
139
|
-
}): Promise<boolean>;
|
|
140
|
-
//#endregion
|
|
141
|
-
//#region src/resolver.d.ts
|
|
142
|
-
/**
|
|
143
|
-
* `resolveLocal` 在 `autoCreate:false` 模式下,向上递归在**父级目录**命中 marker 时的返回值。
|
|
144
|
-
* 调用方(交互态 CLI)应提示用户选择"使用上级 workspace"还是"在当前目录创建新 workspace",
|
|
145
|
-
* 而非静默采用父级身份(防止子目录 workspace 被意外吞入父 workspace)。
|
|
146
|
-
*/
|
|
147
|
-
interface ParentWorkspaceExisted {
|
|
148
|
-
readonly kind: 'parentWorkspaceExisted';
|
|
149
|
-
/** marker 所在目录(父级 workspace 根)。 */
|
|
150
|
-
readonly parentRoot: string;
|
|
151
|
-
/** 用户当前工作目录(pwd)。 */
|
|
152
|
-
readonly currentRoot: string;
|
|
153
|
-
/** 父级 marker 内容。 */
|
|
154
|
-
readonly marker: WorkspaceMarker;
|
|
38
|
+
interface RpcSuccess {
|
|
39
|
+
id: string;
|
|
40
|
+
result: {
|
|
41
|
+
ok: true;
|
|
42
|
+
value?: unknown;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
interface RpcFailure {
|
|
46
|
+
id: string;
|
|
47
|
+
error: {
|
|
48
|
+
code: RpcErrorCode;
|
|
49
|
+
message: string;
|
|
50
|
+
};
|
|
155
51
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
52
|
+
type RpcResponse = RpcSuccess | RpcFailure;
|
|
53
|
+
declare class RpcError extends Error {
|
|
54
|
+
readonly code: RpcErrorCode;
|
|
55
|
+
constructor(code: RpcErrorCode, message: string);
|
|
56
|
+
}
|
|
57
|
+
declare function encodeFrame(value: RpcResponse): string;
|
|
58
|
+
declare function decodeFrame(line: string): RpcRequest;
|
|
59
|
+
interface RpcHostOptions {
|
|
60
|
+
callAtom(atom: AppAtom, input: unknown): Promise<unknown>;
|
|
61
|
+
}
|
|
62
|
+
declare function createRpcHost(options: RpcHostOptions): (line: string) => Promise<RpcResponse>;
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/engine.d.ts
|
|
65
|
+
interface WorkspaceEngineRunInput {
|
|
66
|
+
directory: string;
|
|
67
|
+
entry: string;
|
|
68
|
+
input: unknown;
|
|
69
|
+
config?: Readonly<Record<string, unknown>>;
|
|
70
|
+
timeoutMs?: number;
|
|
171
71
|
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
* 才建立 workspace 身份,防止 `.otto/workspace.json` 缺失时静默生成新随机 id 致旧会话孤儿化)。
|
|
176
|
-
*/
|
|
177
|
-
interface UninitializedWorkspace {
|
|
178
|
-
readonly kind: 'uninitialized';
|
|
179
|
-
readonly root: string;
|
|
72
|
+
interface WorkspaceEngineOptions {
|
|
73
|
+
sandbox?: () => ProcessSandbox | undefined;
|
|
74
|
+
callAtom(atom: AppAtom, input: unknown): Promise<unknown>;
|
|
180
75
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* 本地 resolve-or-create:
|
|
185
|
-
* - `opts.id` 在场 → 显式绑定该 id(写/刷新 marker),忽略 autoCreate(DevPod/`--id` 模式无歧义)。
|
|
186
|
-
* - 否则向上 walk 找 marker:
|
|
187
|
-
* - 命中且 `hit.dir === cwd` → 当前目录已有 workspace 身份 → L 形态。
|
|
188
|
-
* - 命中且 `hit.dir !== cwd` + `autoCreate:false` → 返回 `ParentWorkspaceExisted`,
|
|
189
|
-
* 调用层应提示用户选择"使用上级 workspace"还是"在当前目录创建新 workspace",
|
|
190
|
-
* 防止子目录 workspace 被静默吞入父 workspace。
|
|
191
|
-
* - 命中且 `hit.dir !== cwd` + `autoCreate` 未传/`true`(headless)→ 静默采用父级。
|
|
192
|
-
* - 未命中:`opts.autoCreate !== false`(缺省/headless 等旧行为)→ 在 cwd 生成 id + 写 marker → L;
|
|
193
|
-
* `opts.autoCreate === false`(交互态新流程)→ 返回 `UninitializedWorkspace`,不写文件,
|
|
194
|
-
* 调用方需在用户确认(信任门)后调 `createLocal()` 才真正建立身份。
|
|
195
|
-
*/
|
|
196
|
-
resolveLocal(cwd: string, opts?: ResolveLocalOptions): Promise<WorkspaceRef | UninitializedWorkspace | ParentWorkspaceExisted>;
|
|
197
|
-
/**
|
|
198
|
-
* 显式创建 L 形态 workspace(写 marker)——`resolveLocal({autoCreate:false})` 返回
|
|
199
|
-
* `uninitialized` 后,调用方(信任确认后)调此方法完成创建。与 resolveLocal 内部的
|
|
200
|
-
* 自动创建分支同一实现,只是从"自动触发"变为"显式调用"。
|
|
201
|
-
*/
|
|
202
|
-
createLocal(root: string, opts?: ResolveLocalOptions): Promise<WorkspaceRef>;
|
|
76
|
+
interface WorkspaceEnginePort {
|
|
77
|
+
run(input: WorkspaceEngineRunInput, signal?: AbortSignal): Promise<AppExecutorResult>;
|
|
203
78
|
}
|
|
204
|
-
declare function
|
|
79
|
+
declare function createWorkspaceEngine(options: WorkspaceEngineOptions): WorkspaceEnginePort;
|
|
205
80
|
//#endregion
|
|
206
|
-
export {
|
|
81
|
+
export { APP_ATOMS, APP_ENV_ALLOWLIST, type AppAtom, type AppExecutorOptions, type AppExecutorResult, type ProcessSandbox, RPC_MAX_FRAME_BYTES, RpcError, type RpcErrorCode, type RpcFailure, type RpcRequest, type RpcResponse, type RpcSuccess, type WorkspaceEngineOptions, type WorkspaceEnginePort, type WorkspaceEngineRunInput, appChildEnv, createRpcHost, createWorkspaceEngine, decodeFrame, encodeFrame, runApp };
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,287 @@
|
|
|
1
|
-
import{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { extname, resolve, sep } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
|
|
7
|
+
//#region src/rpc.ts
|
|
8
|
+
const RPC_MAX_FRAME_BYTES = 1024 * 1024;
|
|
9
|
+
const APP_ATOMS = ["http.request"];
|
|
10
|
+
var RpcError = class extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function isAppAtom(value) {
|
|
18
|
+
return APP_ATOMS.some((atom) => atom === value);
|
|
19
|
+
}
|
|
20
|
+
function encodeFrame(value) {
|
|
21
|
+
const body = `${JSON.stringify(value)}\n`;
|
|
22
|
+
if (Buffer.byteLength(body, "utf8") <= 1048576) return body;
|
|
23
|
+
const failure = {
|
|
24
|
+
id: value.id,
|
|
25
|
+
error: {
|
|
26
|
+
code: "FRAME_TOO_LARGE",
|
|
27
|
+
message: "rpc frame exceeds max size"
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
return `${JSON.stringify(failure)}\n`;
|
|
31
|
+
}
|
|
32
|
+
function decodeFrame(line) {
|
|
33
|
+
if (Buffer.byteLength(line, "utf8") > 1048576) throw new RpcError("FRAME_TOO_LARGE", "rpc frame exceeds max size");
|
|
34
|
+
const value = JSON.parse(line);
|
|
35
|
+
if (typeof value.id !== "string" || value.method !== "atom.call") throw new RpcError("INVALID_FRAME", "rpc frame requires id and method atom.call");
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
function idOfRawFrame(line) {
|
|
39
|
+
try {
|
|
40
|
+
const value = JSON.parse(line);
|
|
41
|
+
return typeof value.id === "string" ? value.id : "0";
|
|
42
|
+
} catch {
|
|
43
|
+
return "0";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function createRpcHost(options) {
|
|
47
|
+
return async (line) => {
|
|
48
|
+
let request;
|
|
49
|
+
try {
|
|
50
|
+
request = decodeFrame(line);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
const rpcError = error instanceof RpcError ? error : new RpcError("INVALID_FRAME", String(error));
|
|
53
|
+
return {
|
|
54
|
+
id: idOfRawFrame(line),
|
|
55
|
+
error: {
|
|
56
|
+
code: rpcError.code,
|
|
57
|
+
message: rpcError.message
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const atom = request.params?.["atom"];
|
|
62
|
+
if (!isAppAtom(atom)) return {
|
|
63
|
+
id: request.id,
|
|
64
|
+
error: {
|
|
65
|
+
code: "ATOM_NOT_ALLOWED",
|
|
66
|
+
message: `atom not allowed: ${String(atom)}`
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
try {
|
|
70
|
+
const value = await options.callAtom(atom, request.params?.["input"]);
|
|
71
|
+
return {
|
|
72
|
+
id: request.id,
|
|
73
|
+
result: {
|
|
74
|
+
ok: true,
|
|
75
|
+
value
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return {
|
|
80
|
+
id: request.id,
|
|
81
|
+
error: {
|
|
82
|
+
code: "ATOM_FAILED",
|
|
83
|
+
message: error instanceof Error ? error.message : String(error)
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/sandbox-launch.ts
|
|
92
|
+
function definedEnv(env) {
|
|
93
|
+
const defined = {};
|
|
94
|
+
for (const [name, value] of Object.entries(env)) if (value !== void 0) defined[name] = value;
|
|
95
|
+
return defined;
|
|
96
|
+
}
|
|
97
|
+
function prepareProcessLaunch(command, argumentList, env, sandbox) {
|
|
98
|
+
if (sandbox === void 0) return {
|
|
99
|
+
command,
|
|
100
|
+
argumentList,
|
|
101
|
+
env,
|
|
102
|
+
release: () => void 0
|
|
103
|
+
};
|
|
104
|
+
const snapshot = sandbox.port.snapshot({ cwd: sandbox.cwd });
|
|
105
|
+
const input = {
|
|
106
|
+
command,
|
|
107
|
+
argumentList,
|
|
108
|
+
cwd: sandbox.cwd,
|
|
109
|
+
env: definedEnv(env)
|
|
110
|
+
};
|
|
111
|
+
const prepared = sandbox.port.prepare(snapshot, input);
|
|
112
|
+
let isReleased = false;
|
|
113
|
+
return {
|
|
114
|
+
command: prepared.command,
|
|
115
|
+
argumentList: [...prepared.argumentList],
|
|
116
|
+
env: prepared.env === void 0 ? env : { ...prepared.env },
|
|
117
|
+
cwd: sandbox.cwd,
|
|
118
|
+
release: () => {
|
|
119
|
+
if (isReleased) return;
|
|
120
|
+
isReleased = true;
|
|
121
|
+
prepared.release();
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//#endregion
|
|
127
|
+
//#region src/executor.ts
|
|
128
|
+
const RUNNER_PATH = fileURLToPath(new URL("../runner/app-runner.mjs", import.meta.url));
|
|
129
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
130
|
+
const KILL_GRACE_MS = 2e3;
|
|
131
|
+
const APP_ENV_ALLOWLIST = [
|
|
132
|
+
"PATH",
|
|
133
|
+
"HOME",
|
|
134
|
+
"TMPDIR",
|
|
135
|
+
"TMP",
|
|
136
|
+
"TEMP",
|
|
137
|
+
"LANG",
|
|
138
|
+
"LC_ALL",
|
|
139
|
+
"LC_CTYPE",
|
|
140
|
+
"TERM",
|
|
141
|
+
"SHELL",
|
|
142
|
+
"USER",
|
|
143
|
+
"LOGNAME",
|
|
144
|
+
"SYSTEMROOT",
|
|
145
|
+
"COMSPEC",
|
|
146
|
+
"PATHEXT",
|
|
147
|
+
"WINDIR"
|
|
148
|
+
];
|
|
149
|
+
function appChildEnv(read, extra) {
|
|
150
|
+
const env = {};
|
|
151
|
+
for (const name of APP_ENV_ALLOWLIST) {
|
|
152
|
+
const value = read(name);
|
|
153
|
+
if (value !== void 0) env[name] = value;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
...env,
|
|
157
|
+
...extra
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function loaderFor(entry) {
|
|
161
|
+
const extension = extname(entry);
|
|
162
|
+
if (extension !== ".ts" && extension !== ".tsx") return [];
|
|
163
|
+
return ["--import", createRequire(import.meta.url).resolve("tsx")];
|
|
164
|
+
}
|
|
165
|
+
function processEnvReader(key) {
|
|
166
|
+
return process.env[key];
|
|
167
|
+
}
|
|
168
|
+
function crashMessageOf(code, stderr) {
|
|
169
|
+
const tail = stderr.trim();
|
|
170
|
+
const head = `APP_EXECUTOR_CRASHED:${code ?? "unknown"}`;
|
|
171
|
+
return tail === "" ? head : `${head} (${tail.slice(-2e3)})`;
|
|
172
|
+
}
|
|
173
|
+
function runApp(options) {
|
|
174
|
+
const childEnv = {
|
|
175
|
+
...appChildEnv(options.readEnv ?? processEnvReader),
|
|
176
|
+
APP_ENTRY: options.appEntry,
|
|
177
|
+
APP_INPUT: JSON.stringify(options.input ?? {}),
|
|
178
|
+
APP_CONFIG: JSON.stringify(options.config ?? {})
|
|
179
|
+
};
|
|
180
|
+
const launcher = `import(${JSON.stringify(pathToFileURL(RUNNER_PATH).href)}).then((runner) => runner.runAppProcess())`;
|
|
181
|
+
const argumentList = [
|
|
182
|
+
...loaderFor(options.appEntry),
|
|
183
|
+
"--input-type=module",
|
|
184
|
+
"--eval",
|
|
185
|
+
launcher
|
|
186
|
+
];
|
|
187
|
+
const launch = prepareProcessLaunch(process.execPath, argumentList, childEnv, options.sandbox);
|
|
188
|
+
const child = spawn(launch.command, launch.argumentList, {
|
|
189
|
+
...launch.cwd === void 0 ? {} : { cwd: launch.cwd },
|
|
190
|
+
env: launch.env,
|
|
191
|
+
stdio: [
|
|
192
|
+
"pipe",
|
|
193
|
+
"pipe",
|
|
194
|
+
"pipe"
|
|
195
|
+
]
|
|
196
|
+
});
|
|
197
|
+
child.once("exit", launch.release);
|
|
198
|
+
child.once("error", launch.release);
|
|
199
|
+
const host = createRpcHost({ callAtom: options.callAtom });
|
|
200
|
+
const logs = [];
|
|
201
|
+
let stderr = "";
|
|
202
|
+
return new Promise((resolve, reject) => {
|
|
203
|
+
let settled = false;
|
|
204
|
+
const finish = (action) => {
|
|
205
|
+
if (settled) return;
|
|
206
|
+
settled = true;
|
|
207
|
+
clearTimeout(timer);
|
|
208
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
209
|
+
if (child.exitCode === null) {
|
|
210
|
+
child.kill("SIGTERM");
|
|
211
|
+
setTimeout(() => child.exitCode === null && child.kill("SIGKILL"), KILL_GRACE_MS).unref();
|
|
212
|
+
}
|
|
213
|
+
action();
|
|
214
|
+
};
|
|
215
|
+
const onAbort = () => {
|
|
216
|
+
finish(() => reject(/* @__PURE__ */ new Error("APP_EXECUTOR_CANCELLED")));
|
|
217
|
+
};
|
|
218
|
+
const timer = setTimeout(() => {
|
|
219
|
+
finish(() => reject(/* @__PURE__ */ new Error("APP_EXECUTOR_TIMEOUT")));
|
|
220
|
+
}, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
221
|
+
if (options.signal?.aborted === true) {
|
|
222
|
+
onAbort();
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
226
|
+
createInterface({ input: child.stdout }).on("line", (line) => {
|
|
227
|
+
if (line === "") return;
|
|
228
|
+
let frame;
|
|
229
|
+
try {
|
|
230
|
+
frame = JSON.parse(line);
|
|
231
|
+
} catch {
|
|
232
|
+
logs.push(`${line}\n`);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (frame.id === "done") {
|
|
236
|
+
const failure = frame.error;
|
|
237
|
+
const value = frame.result?.value;
|
|
238
|
+
finish(() => failure === void 0 ? resolve({
|
|
239
|
+
value,
|
|
240
|
+
logs
|
|
241
|
+
}) : reject(new Error(failure.message ?? "APP_EXECUTOR_FAILED")));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
host(line).then((response) => {
|
|
245
|
+
if (!settled) child.stdin.write(encodeFrame(response));
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
child.stderr.on("data", (chunk) => {
|
|
249
|
+
const text = chunk.toString("utf8");
|
|
250
|
+
stderr += text;
|
|
251
|
+
logs.push(text);
|
|
252
|
+
});
|
|
253
|
+
child.on("error", (error) => {
|
|
254
|
+
finish(() => reject(error));
|
|
255
|
+
});
|
|
256
|
+
child.on("exit", (code) => {
|
|
257
|
+
finish(() => reject(new Error(crashMessageOf(code, stderr))));
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
//#endregion
|
|
263
|
+
//#region src/engine.ts
|
|
264
|
+
function entryWithin(directory, entry) {
|
|
265
|
+
const root = resolve(directory);
|
|
266
|
+
const target = resolve(root, entry);
|
|
267
|
+
if (!target.startsWith(`${root}${sep}`)) throw new Error(`APP_REVISION_PATH_ESCAPE:${entry}`);
|
|
268
|
+
return target;
|
|
269
|
+
}
|
|
270
|
+
function createWorkspaceEngine(options) {
|
|
271
|
+
return { async run(input, signal) {
|
|
272
|
+
const appEntry = entryWithin(input.directory, input.entry);
|
|
273
|
+
const sandbox = options.sandbox?.();
|
|
274
|
+
return runApp({
|
|
275
|
+
appEntry,
|
|
276
|
+
input: input.input,
|
|
277
|
+
callAtom: options.callAtom,
|
|
278
|
+
...input.config === void 0 ? {} : { config: input.config },
|
|
279
|
+
...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
|
|
280
|
+
...sandbox === void 0 ? {} : { sandbox },
|
|
281
|
+
...signal === void 0 ? {} : { signal }
|
|
282
|
+
});
|
|
283
|
+
} };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
//#endregion
|
|
287
|
+
export { APP_ATOMS, APP_ENV_ALLOWLIST, RPC_MAX_FRAME_BYTES, RpcError, appChildEnv, createRpcHost, createWorkspaceEngine, decodeFrame, encodeFrame, runApp };
|
package/package.json
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-otto/workspace",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-beta.0",
|
|
4
|
+
"description": "Workspace app engine:在沙箱子进程里跑一个固定 revision 的 app(只开放 http.request 原子)",
|
|
4
5
|
"files": [
|
|
5
|
-
"dist"
|
|
6
|
+
"dist",
|
|
7
|
+
"runner"
|
|
6
8
|
],
|
|
7
9
|
"type": "module",
|
|
8
10
|
"main": "./dist/index.js",
|
|
@@ -13,16 +15,12 @@
|
|
|
13
15
|
"import": "./dist/index.js"
|
|
14
16
|
}
|
|
15
17
|
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@x-otto/kernel": "^0.3.0-beta.0",
|
|
20
|
+
"tsx": "4.23.12"
|
|
21
|
+
},
|
|
16
22
|
"publishConfig": {
|
|
17
23
|
"access": "public",
|
|
18
|
-
"
|
|
19
|
-
"tag": "alpha"
|
|
20
|
-
},
|
|
21
|
-
"private": false,
|
|
22
|
-
"scripts": {
|
|
23
|
-
"build": "tsdown",
|
|
24
|
-
"typecheck:project": "tsc -p tsconfig.json --noEmit",
|
|
25
|
-
"typecheck": "tsc --noEmit",
|
|
26
|
-
"clean": "rm -rf dist"
|
|
24
|
+
"tag": "beta"
|
|
27
25
|
}
|
|
28
|
-
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { pathToFileURL } from 'node:url'
|
|
2
|
+
import { createInterface } from 'node:readline'
|
|
3
|
+
|
|
4
|
+
const writeProtocol = process.stdout.write.bind(process.stdout)
|
|
5
|
+
|
|
6
|
+
function protocolFrame(value) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
writeProtocol(`${JSON.stringify(value)}\n`, (error) => (error === undefined || error === null ? resolve() : reject(error)))
|
|
9
|
+
})
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function runAppProcess() {
|
|
13
|
+
const pending = new Map()
|
|
14
|
+
let sequence = 0
|
|
15
|
+
|
|
16
|
+
process.stdout.write = (chunk, encoding, callback) => process.stderr.write(chunk, encoding, callback)
|
|
17
|
+
|
|
18
|
+
const call = (atom, input) => {
|
|
19
|
+
sequence += 1
|
|
20
|
+
const id = String(sequence)
|
|
21
|
+
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
pending.set(id, { resolve, reject })
|
|
24
|
+
void protocolFrame({ id, method: 'atom.call', params: { atom, input } }).catch(reject)
|
|
25
|
+
})
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const reader = createInterface({ input: process.stdin })
|
|
29
|
+
reader.on('line', (line) => {
|
|
30
|
+
if (line === '') {
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let frame
|
|
35
|
+
try {
|
|
36
|
+
frame = JSON.parse(line)
|
|
37
|
+
} catch {
|
|
38
|
+
return
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const waiter = pending.get(frame.id)
|
|
42
|
+
if (waiter === undefined) {
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
pending.delete(frame.id)
|
|
47
|
+
if (frame.error !== undefined) {
|
|
48
|
+
waiter.reject(new Error(frame.error.message))
|
|
49
|
+
} else {
|
|
50
|
+
waiter.resolve(frame.result?.value)
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
const entry = process.env.APP_ENTRY
|
|
55
|
+
const input = JSON.parse(process.env.APP_INPUT ?? '{}')
|
|
56
|
+
const config = JSON.parse(process.env.APP_CONFIG ?? '{}')
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const module = await import(pathToFileURL(entry).href)
|
|
60
|
+
const ctx = {
|
|
61
|
+
input,
|
|
62
|
+
config,
|
|
63
|
+
atoms: { http: { request: (value) => call('http.request', value) } },
|
|
64
|
+
log: (message) => process.stderr.write(`${String(message)}\n`),
|
|
65
|
+
}
|
|
66
|
+
const value = await module.run(ctx)
|
|
67
|
+
await protocolFrame({ id: 'done', result: { ok: true, value } })
|
|
68
|
+
} catch (error) {
|
|
69
|
+
await protocolFrame({ id: 'done', error: { message: error instanceof Error ? error.message : String(error) } })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
reader.close()
|
|
73
|
+
process.stdin.destroy()
|
|
74
|
+
}
|
package/README.md
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
# @x-otto/workspace
|
|
2
|
-
|
|
3
|
-
> Workspace identity primitives: unique IDs, local marker read/write, and upward search (single Local form).
|
|
4
|
-
|
|
5
|
-
`@x-otto/workspace` defines how otto identifies and associates a workspace with a directory. A workspace is a first-class logical entity with an immutable `id`, persisted via a local marker file (`.otto/workspace.json`). The package handles id generation and validation, upward directory search for existing markers, and resolution of the single Local workspace form. Zero internal dependencies — only Node.js built-ins.
|
|
6
|
-
|
|
7
|
-
## Installation
|
|
8
|
-
|
|
9
|
-
```bash
|
|
10
|
-
pnpm add @x-otto/workspace
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
## Usage
|
|
14
|
-
|
|
15
|
-
```typescript
|
|
16
|
-
import {
|
|
17
|
-
createWorkspaceResolver,
|
|
18
|
-
genWorkspaceId,
|
|
19
|
-
isValidWorkspaceId,
|
|
20
|
-
workspaceKey,
|
|
21
|
-
readMarker,
|
|
22
|
-
findMarker,
|
|
23
|
-
DEFAULT_WORKSPACE_KEY,
|
|
24
|
-
} from '@x-otto/workspace'
|
|
25
|
-
|
|
26
|
-
// Create a resolver with injected I/O
|
|
27
|
-
const io: WorkspaceIO = {
|
|
28
|
-
readFile: async (path) => { /* read from real fs or mock */ return null },
|
|
29
|
-
writeFile: async (path, content) => { /* write to real fs or mock */ },
|
|
30
|
-
genId: () => genWorkspaceId(),
|
|
31
|
-
now: () => new Date().toISOString(),
|
|
32
|
-
}
|
|
33
|
-
const resolver = createWorkspaceResolver(io)
|
|
34
|
-
|
|
35
|
-
// Resolve workspace identity for a directory
|
|
36
|
-
// Finds existing marker via upward search, or creates one
|
|
37
|
-
const ref = await resolver.resolveLocal('/path/to/project')
|
|
38
|
-
// ref.key === 'ws_<id>'
|
|
39
|
-
// ref.root === '/path/to/project'
|
|
40
|
-
|
|
41
|
-
// Explicit workspace id override (--id mode)
|
|
42
|
-
const devpodRef = await resolver.resolveLocal('/path/to/project', {
|
|
43
|
-
id: 'my-custom-id',
|
|
44
|
-
})
|
|
45
|
-
|
|
46
|
-
// Interactive mode: don't auto-create, let the user decide
|
|
47
|
-
const result = await resolver.resolveLocal('/safe/path', { autoCreate: false })
|
|
48
|
-
if (result.kind === 'uninitialized') {
|
|
49
|
-
// Show trust prompt → user confirms → create explicitly
|
|
50
|
-
const ref = await resolver.createLocal('/safe/path')
|
|
51
|
-
} else if (result.kind === 'parentWorkspaceExisted') {
|
|
52
|
-
// A marker was found in parent directory — choose how to proceed
|
|
53
|
-
}
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
### Id Utilities
|
|
57
|
-
|
|
58
|
-
```typescript
|
|
59
|
-
import { genWorkspaceId, isValidWorkspaceId, workspaceKey } from '@x-otto/workspace'
|
|
60
|
-
|
|
61
|
-
const id = genWorkspaceId()
|
|
62
|
-
// → 'a1b2c3d4e5f6789012345678abcdef01'
|
|
63
|
-
|
|
64
|
-
isValidWorkspaceId(id) // → true
|
|
65
|
-
workspaceKey(id) // → 'ws_a1b2c3d4e5f6789012345678abcdef01'
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
## Key Exports
|
|
69
|
-
|
|
70
|
-
### Types
|
|
71
|
-
- `WorkspaceRef` — Runtime reference: key, id, root, memorySyncEnabled
|
|
72
|
-
- `WorkspaceMarker` — `.otto/workspace.json` shape: id, name, createdAt, memorySyncEnabled
|
|
73
|
-
- `WorkspaceIO` — Injected I/O interface: readFile, writeFile, writeFileExclusive, genId, now
|
|
74
|
-
- `WorkspaceResolver` — `resolveLocal()` + `createLocal()` interface
|
|
75
|
-
|
|
76
|
-
### Functions
|
|
77
|
-
- `createWorkspaceResolver()` — Create resolver with given IO adapter
|
|
78
|
-
- `genWorkspaceId()` — Generate uuid-based id (32 hex chars)
|
|
79
|
-
- `isValidWorkspaceId()` / `assertValidWorkspaceId()` — Validate charset + length
|
|
80
|
-
- `workspaceKey()` — Build storage key (`ws_<id>`)
|
|
81
|
-
- `readMarker()` / `writeMarker()` — Read/write `.otto/workspace.json`
|
|
82
|
-
- `findMarker()` — Upward directory search for existing marker
|
|
83
|
-
|
|
84
|
-
### Constants
|
|
85
|
-
- `MARKER_DIR` — `.otto`
|
|
86
|
-
- `MARKER_FILE` — `workspace.json`
|
|
87
|
-
- `OTTO_GITIGNORE` — Default gitignore template for `.otto/`
|
|
88
|
-
- `DEFAULT_WORKSPACE_KEY` — `'default'` fallback for unbound sessions
|
|
89
|
-
- `WS_KEY_PREFIX` — `ws_`
|
|
90
|
-
|
|
91
|
-
## Dependencies
|
|
92
|
-
|
|
93
|
-
- **Internal**: None
|
|
94
|
-
- **External**: Node.js built-ins only (`node:crypto`, `node:path`)
|
|
95
|
-
|
|
96
|
-
## Related
|
|
97
|
-
|
|
98
|
-
- [Architecture](./ARCHITECTURE.md)
|