@seavideo/cli 0.0.0-stage → 0.3.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/LICENSE +12 -0
- package/README.md +153 -2
- package/README.publish.md +154 -0
- package/dist/bin/seavideo.js +11 -0
- package/dist/src/atomic-write.js +14 -0
- package/dist/src/canvas/api.js +172 -0
- package/dist/src/canvas/browser.js +40 -0
- package/dist/src/canvas/chrome-binary.js +109 -0
- package/dist/src/canvas/daemon.js +264 -0
- package/dist/src/canvas/engine-install.js +46 -0
- package/dist/src/canvas/engine-log.js +9 -0
- package/dist/src/canvas/engine.js +99 -0
- package/dist/src/canvas/entry.js +16 -0
- package/dist/src/canvas/env-lock.js +164 -0
- package/dist/src/canvas/launch.js +97 -0
- package/dist/src/canvas/lifecycle.js +65 -0
- package/dist/src/canvas/names.js +61 -0
- package/dist/src/canvas/params.js +38 -0
- package/dist/src/canvas/puppeteer.js +153 -0
- package/dist/src/canvas/screenshot.js +23 -0
- package/dist/src/canvas/session-record.js +77 -0
- package/dist/src/canvas/team.js +97 -0
- package/dist/src/canvas/tool-args.js +47 -0
- package/dist/src/canvas/tool-session.js +165 -0
- package/dist/src/canvas/tool-specs.js +54 -0
- package/dist/src/canvas/url.js +38 -0
- package/dist/src/cli/args.js +16 -0
- package/dist/src/cli/commands/auth.js +51 -0
- package/dist/src/cli/commands/canvas/common.js +31 -0
- package/dist/src/cli/commands/canvas/engine-choice.js +41 -0
- package/dist/src/cli/commands/canvas/index.js +5 -0
- package/dist/src/cli/commands/canvas/item.js +233 -0
- package/dist/src/cli/commands/canvas/list.js +168 -0
- package/dist/src/cli/commands/canvas/register.js +106 -0
- package/dist/src/cli/commands/canvas/render.js +229 -0
- package/dist/src/cli/commands/canvas/screenshot.js +52 -0
- package/dist/src/cli/commands/canvas/session.js +249 -0
- package/dist/src/cli/commands/canvas/teams.js +142 -0
- package/dist/src/cli/commands/config.js +74 -0
- package/dist/src/cli/commands/doctor.js +261 -0
- package/dist/src/cli/commands/engine.js +96 -0
- package/dist/src/cli/commands/env/create.js +160 -0
- package/dist/src/cli/commands/env/fields.js +26 -0
- package/dist/src/cli/commands/env/index.js +4 -0
- package/dist/src/cli/commands/env/list.js +44 -0
- package/dist/src/cli/commands/env/mutate.js +118 -0
- package/dist/src/cli/commands/login/flow-token.js +41 -0
- package/dist/src/cli/commands/login/index.js +12 -0
- package/dist/src/cli/commands/login/oauth.js +69 -0
- package/dist/src/cli/commands/login/save.js +26 -0
- package/dist/src/cli/commands/logout.js +92 -0
- package/dist/src/cli/commands/skill.js +185 -0
- package/dist/src/cli/commands/tool.js +279 -0
- package/dist/src/cli/commands/update.js +117 -0
- package/dist/src/cli/commands/wallet.js +69 -0
- package/dist/src/cli/commands/whoami.js +147 -0
- package/dist/src/cli/context.js +41 -0
- package/dist/src/cli/credential.js +93 -0
- package/dist/src/cli/elapsed.js +25 -0
- package/dist/src/cli/failure-screenshot.js +24 -0
- package/dist/src/cli/flags.js +1 -0
- package/dist/src/cli/hints.js +7 -0
- package/dist/src/cli/main.js +44 -0
- package/dist/src/cli/output-error.js +23 -0
- package/dist/src/cli/output.js +47 -0
- package/dist/src/cli/program.js +261 -0
- package/dist/src/cli/run.js +11 -0
- package/dist/src/cli/session.js +63 -0
- package/dist/src/config/base-url.js +26 -0
- package/dist/src/config/credential-vault.js +115 -0
- package/dist/src/config/dotenv.js +59 -0
- package/dist/src/config/envname.js +41 -0
- package/dist/src/config/paths.js +22 -0
- package/dist/src/config/preset-schema.js +67 -0
- package/dist/src/config/presets.js +132 -0
- package/dist/src/config/resolve.js +41 -0
- package/dist/src/config/secret-key.js +63 -0
- package/dist/src/config/store-schema.js +143 -0
- package/dist/src/config/store.js +273 -0
- package/dist/src/config/vault-crypto.js +44 -0
- package/dist/src/deps.js +191 -0
- package/dist/src/deps.types.js +1 -0
- package/dist/src/errors.js +24 -0
- package/dist/src/fs-retry.js +34 -0
- package/dist/src/i18n.js +1214 -0
- package/dist/src/loopback.js +134 -0
- package/dist/src/sdk/auth.js +20 -0
- package/dist/src/sdk/credential-expiry.js +67 -0
- package/dist/src/sdk/discovery.js +90 -0
- package/dist/src/sdk/http.js +98 -0
- package/dist/src/sdk/identity.js +17 -0
- package/dist/src/sdk/jwks.js +119 -0
- package/dist/src/sdk/oauth-protocol.js +226 -0
- package/dist/src/sdk/oauth.js +179 -0
- package/dist/src/sdk/provider/cn.js +34 -0
- package/dist/src/sdk/provider/index.js +16 -0
- package/dist/src/sdk/provider/oversea.js +41 -0
- package/dist/src/sdk/provider/types.js +1 -0
- package/dist/src/sdk/refresh.js +66 -0
- package/dist/src/semver.js +89 -0
- package/dist/src/skill/api.js +176 -0
- package/dist/src/text.js +3 -0
- package/dist/src/types.js +1 -0
- package/dist/src/update/check-cache.js +56 -0
- package/dist/src/update/install-layout.js +79 -0
- package/dist/src/update/notify.js +15 -0
- package/dist/src/update/npm-install.js +64 -0
- package/dist/src/update/passive.js +53 -0
- package/dist/src/update/registry.js +59 -0
- package/dist/src/wallet/api.js +107 -0
- package/package.json +59 -4
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { CliError } from "../errors.js";
|
|
3
|
+
import { withRetry } from "../fs-retry.js";
|
|
4
|
+
import { t } from "../i18n.js";
|
|
5
|
+
import { launchArgsOf } from "./browser.js";
|
|
6
|
+
import { terminateCommand } from "../deps.js";
|
|
7
|
+
export const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60_000;
|
|
8
|
+
export const WATCH_INTERVAL_MS = 60_000;
|
|
9
|
+
export const DEVTOOLS_PORT_FILE = 'DevToolsActivePort';
|
|
10
|
+
export const KEEPER_BOOT_PREFIX = 'keeper-boot-';
|
|
11
|
+
export function keeperBootName() {
|
|
12
|
+
return `${KEEPER_BOOT_PREFIX}${Math.random().toString(36).slice(2, 10)}.json`;
|
|
13
|
+
}
|
|
14
|
+
export const PORT_WAIT_MS = 15_000;
|
|
15
|
+
export const PORT_POLL_MS = 100;
|
|
16
|
+
export const SESSION_BOOT_MS = 240_000;
|
|
17
|
+
export function isIdleExpired(record, now, idleMs = DEFAULT_IDLE_TIMEOUT_MS) {
|
|
18
|
+
return now.getTime() - Date.parse(record.usedAt) > idleMs;
|
|
19
|
+
}
|
|
20
|
+
export async function spawnCanvasBrowser(executablePath, profileDir, sessionFile, nodePath, deps, options = {}) {
|
|
21
|
+
const headful = options.headful === true;
|
|
22
|
+
const bootName = keeperBootName();
|
|
23
|
+
const bootFile = join(profileDir, bootName);
|
|
24
|
+
try {
|
|
25
|
+
await withRetry(deps, () => deps.fs.rm(profileDir, { recursive: true, force: true }));
|
|
26
|
+
await deps.fs.mkdir(profileDir, { recursive: true, mode: 0o700 });
|
|
27
|
+
const args = [
|
|
28
|
+
...(headful ? [] : ['--headless=shell']),
|
|
29
|
+
...launchArgsOf(deps.env, headful),
|
|
30
|
+
'--remote-debugging-port=0',
|
|
31
|
+
`--user-data-dir=${profileDir}`,
|
|
32
|
+
'about:blank',
|
|
33
|
+
];
|
|
34
|
+
startWatcher({
|
|
35
|
+
executablePath,
|
|
36
|
+
args,
|
|
37
|
+
profileDir,
|
|
38
|
+
sessionFile,
|
|
39
|
+
bootName,
|
|
40
|
+
idleMs: DEFAULT_IDLE_TIMEOUT_MS,
|
|
41
|
+
nodePath,
|
|
42
|
+
platform: deps.platform,
|
|
43
|
+
deps,
|
|
44
|
+
});
|
|
45
|
+
return await waitForBoot(bootFile, args, deps);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
if (err instanceof CliError)
|
|
49
|
+
throw err;
|
|
50
|
+
throw new CliError('config', t('canvas.engineStartFailed', {}, deps.env), {
|
|
51
|
+
detail: err.code ?? (err instanceof Error ? err.name : String(err)),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async function waitForBoot(bootFile, args, deps) {
|
|
56
|
+
const waited = Math.ceil(PORT_WAIT_MS / PORT_POLL_MS);
|
|
57
|
+
for (let i = 0; i < waited; i += 1) {
|
|
58
|
+
const boot = await readBootFile(bootFile, deps);
|
|
59
|
+
if (boot !== null && 'error' in boot) {
|
|
60
|
+
throw new CliError('config', t('canvas.engineStartFailed', {}, deps.env), {
|
|
61
|
+
detail: boot.error,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (boot !== null)
|
|
65
|
+
return { pid: boot.pid, port: boot.port, args };
|
|
66
|
+
await deps.sleep(PORT_POLL_MS);
|
|
67
|
+
}
|
|
68
|
+
throw new CliError('config', t('canvas.engineStartFailed', {}, deps.env), {
|
|
69
|
+
detail: t('canvas.daemonNoPort', { ms: PORT_WAIT_MS }, deps.env),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async function readBootFile(bootFile, deps) {
|
|
73
|
+
let result;
|
|
74
|
+
try {
|
|
75
|
+
const raw = JSON.parse(await deps.fs.readFile(bootFile, 'utf8'));
|
|
76
|
+
const pid = raw['pid'];
|
|
77
|
+
const port = raw['port'];
|
|
78
|
+
const error = raw['error'];
|
|
79
|
+
if (typeof error === 'string' && error !== '') {
|
|
80
|
+
result = { error };
|
|
81
|
+
}
|
|
82
|
+
else if (typeof pid === 'number' &&
|
|
83
|
+
Number.isInteger(pid) &&
|
|
84
|
+
pid > 0 &&
|
|
85
|
+
typeof port === 'number' &&
|
|
86
|
+
Number.isInteger(port) &&
|
|
87
|
+
port > 0) {
|
|
88
|
+
result = { pid, port };
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
result = null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
result = null;
|
|
96
|
+
}
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
export async function sessionAlive(record, deps) {
|
|
100
|
+
let result;
|
|
101
|
+
if (!deps.processAlive(record.pid)) {
|
|
102
|
+
result = false;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
try {
|
|
106
|
+
const resp = await deps.fetch(`http://127.0.0.1:${record.port}/json/version`);
|
|
107
|
+
result = resp.ok;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
result = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
export const WATCHER_SCRIPT = `
|
|
116
|
+
const fs = require('node:fs');
|
|
117
|
+
const path = require('node:path');
|
|
118
|
+
const { spawn } = require('node:child_process');
|
|
119
|
+
const cfg = JSON.parse(process.argv[1]);
|
|
120
|
+
const bootFile = path.join(cfg.profileDir, cfg.bootFile);
|
|
121
|
+
const portFile = path.join(cfg.profileDir, cfg.portFile);
|
|
122
|
+
|
|
123
|
+
// 非 detached:Windows 上 detached 会让 windowsHide 失效,每个 console 子进程
|
|
124
|
+
// 都新开一个可见窗口(实测 3 个)。父进程是看门狗,够浏览器活过 CLI 退出。
|
|
125
|
+
const child = spawn(cfg.exe, cfg.args, { windowsHide: true, stdio: 'ignore' });
|
|
126
|
+
child.unref();
|
|
127
|
+
|
|
128
|
+
// spawn 的可执行文件不存在 / 不可执行时,Node 不在同步阶段抛,而是异步 emit
|
|
129
|
+
// 'error';没有监听器会把看门狗整个打崩(stdio 是 ignore,看起来就是无声无息)。
|
|
130
|
+
// 那种情况下 CLI 会白等 PORT_WAIT_MS 才报含糊的「没等到端口」。这里把原因写进
|
|
131
|
+
// 引导文件,CLI 读到 error 字段就立刻报真因。
|
|
132
|
+
child.on('error', function (err) {
|
|
133
|
+
try { fs.writeFileSync(bootFile, JSON.stringify({ error: String(err && err.code || err) })); } catch {}
|
|
134
|
+
process.exit(1);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// 回收浏览器。看门狗现在是闲置超时 / 记录被删 / pid 被接管三条路的**主要**回收者,
|
|
138
|
+
// 所以必须连子树一起收:Windows 上 process.kill 只杀主进程,gpu / renderer 子进程
|
|
139
|
+
// 可能残留(这正是 deps.terminate 用 taskkill /T 的理由)。
|
|
140
|
+
//
|
|
141
|
+
// 平台分支不在脚本里写:内联脚本不能读 process.platform(PF001 要求平台差异只在
|
|
142
|
+
// deps.ts 判定),所以 CLi 侧用 terminateCommand() 算出「怎么杀」,经 cfg.kill 传进来。
|
|
143
|
+
function die(code) {
|
|
144
|
+
try {
|
|
145
|
+
if (cfg.kill.kind === 'command') {
|
|
146
|
+
// argsTemplate 形如 ['/PID', '{pid}', '/T', '/F']
|
|
147
|
+
const args = cfg.kill.argsTemplate.map((a) => (a === '{pid}' ? String(child.pid) : a));
|
|
148
|
+
require('node:child_process').execFileSync(cfg.kill.command, args, { stdio: 'ignore' });
|
|
149
|
+
} else {
|
|
150
|
+
process.kill(child.pid, cfg.kill.signal);
|
|
151
|
+
}
|
|
152
|
+
} catch {}
|
|
153
|
+
process.exit(code);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// 等浏览器的 DevTools 端口,就绪后把 pid/port 写给 CLI。
|
|
157
|
+
// 超时就杀掉浏览器退出:CLI 那边等不到引导文件也会报错,别留半死进程。
|
|
158
|
+
const deadline = Date.now() + cfg.portWaitMs;
|
|
159
|
+
(function poll() {
|
|
160
|
+
let port = 0;
|
|
161
|
+
try {
|
|
162
|
+
port = Number(String(fs.readFileSync(portFile, 'utf8')).split('\\n')[0].trim());
|
|
163
|
+
} catch {}
|
|
164
|
+
if (Number.isInteger(port) && port > 0) {
|
|
165
|
+
try {
|
|
166
|
+
fs.writeFileSync(bootFile, JSON.stringify({ pid: child.pid, port }));
|
|
167
|
+
} catch {}
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (Date.now() > deadline) die(1);
|
|
171
|
+
else setTimeout(poll, cfg.portPollMs);
|
|
172
|
+
})();
|
|
173
|
+
|
|
174
|
+
// 浏览器自己没了(崩溃 / 被外部杀掉):看门狗跟着退,避免留下一个永远
|
|
175
|
+
// 盯着不存在的进程的僵尸。
|
|
176
|
+
//
|
|
177
|
+
// 连续失败两次才算数:spawn 之后的那一小段时间里,子进程可能还没来得及
|
|
178
|
+
// 被系统登记好,「探一次不在」会误判成崩溃,把看门狗提前打死——实测这样
|
|
179
|
+
// 引导文件永远写不出来。所以要求连续两次探不到才退出。
|
|
180
|
+
//
|
|
181
|
+
// 探活间隔比记录轮询短得多:记录轮询 60 秒是给「闲置判断」用的精度,
|
|
182
|
+
// 而「子进程已经没了」应当尽快发现——否则一次失败的 canvas use 会留下
|
|
183
|
+
// 一个空转的 node 进程。下面的 Math.min 让它最多两秒一探(连续两次才退出,
|
|
184
|
+
// 所以最坏约四秒),而不是跟着 60 秒的记录轮询一起等。
|
|
185
|
+
let missingTicks = 0;
|
|
186
|
+
const aliveTimer = setInterval(function () {
|
|
187
|
+
try {
|
|
188
|
+
process.kill(child.pid, 0);
|
|
189
|
+
missingTicks = 0;
|
|
190
|
+
} catch {
|
|
191
|
+
missingTicks += 1;
|
|
192
|
+
if (missingTicks >= 2) process.exit(0);
|
|
193
|
+
}
|
|
194
|
+
}, Math.min(cfg.intervalMs, 2000));
|
|
195
|
+
|
|
196
|
+
// 记录从「还没写」等到「等太久了」的门槛:CLI 打开页面有一个默认超时
|
|
197
|
+
// (90s),超过它还没写记录说明这条会话不会成立了,看门狗不该无限期占着浏览器。
|
|
198
|
+
let seenRecord = false;
|
|
199
|
+
const bootDeadline = Date.now() + cfg.sessionBootMs;
|
|
200
|
+
|
|
201
|
+
setInterval(function () {
|
|
202
|
+
let text;
|
|
203
|
+
try { text = fs.readFileSync(cfg.sessionFile, 'utf8'); }
|
|
204
|
+
catch {
|
|
205
|
+
// 记录还没出现是**启动中**的正常状态:看门狗先起浏览器,CLI 打开页面
|
|
206
|
+
// 成功后才写记录。只有「曾经见过记录、现在没了」才等于被显式收掉。
|
|
207
|
+
// 旧版没有这层区分,因为它是在记录写完之后才起的;现在它必须先起。
|
|
208
|
+
if (seenRecord) { clearInterval(aliveTimer); die(0); }
|
|
209
|
+
else if (Date.now() > bootDeadline) { clearInterval(aliveTimer); die(0); }
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
let rec;
|
|
213
|
+
try {
|
|
214
|
+
rec = JSON.parse(text);
|
|
215
|
+
if (typeof rec.usedAt !== 'string' || Number.isNaN(Date.parse(rec.usedAt))) throw new Error('bad');
|
|
216
|
+
} catch {
|
|
217
|
+
// 记录存在却解析不了:原子写(tmp + rename)让它本该不会发生,
|
|
218
|
+
// 但它没有别的出口——直接 return 就是「看门狗永远跑、浏览器永远不回收」。
|
|
219
|
+
// 曾经成功读过(seenRecord)说明会话已成立,现在读不出就等于记录没了;
|
|
220
|
+
// 从未读过则说明这条会话还没成立,按启动超时处理。
|
|
221
|
+
if (seenRecord || Date.now() > bootDeadline) { clearInterval(aliveTimer); die(0); }
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
seenRecord = true;
|
|
225
|
+
// 记录里的 pid 不是自己起的那个 → 新会话已接管,这个浏览器已经过时。
|
|
226
|
+
//
|
|
227
|
+
// 必须用 die() 主动杀掉子进程,不能只 process.exit(0):Windows 上父进程退出
|
|
228
|
+
// 会带走同控制台组的子进程(实测如此),但这一点**不能依赖**——从没有控制台
|
|
229
|
+
// 的环境(服务、CI)启动时并不成立,POSIX 上更是根本不会发生。只 exit 的话,
|
|
230
|
+
// 这个非 detached 的浏览器就成了永久孤儿,而下一次 canvas use 只 terminate
|
|
231
|
+
// 「当时的」记录 pid,永远不会回收它。
|
|
232
|
+
if (rec.pid !== child.pid) { clearInterval(aliveTimer); die(0); }
|
|
233
|
+
if (Date.now() - Date.parse(rec.usedAt) > cfg.idleMs) {
|
|
234
|
+
try { fs.unlinkSync(cfg.sessionFile); } catch {}
|
|
235
|
+
clearInterval(aliveTimer);
|
|
236
|
+
die(0);
|
|
237
|
+
}
|
|
238
|
+
}, cfg.intervalMs);
|
|
239
|
+
`;
|
|
240
|
+
export function startWatcher(options) {
|
|
241
|
+
const spec = terminateCommand(options.platform, 0);
|
|
242
|
+
const kill = spec.kind === 'command'
|
|
243
|
+
? {
|
|
244
|
+
kind: 'command',
|
|
245
|
+
command: spec.command,
|
|
246
|
+
argsTemplate: spec.args.map((a) => (a === '0' ? '{pid}' : a)),
|
|
247
|
+
}
|
|
248
|
+
: { kind: 'signal', signal: spec.signal };
|
|
249
|
+
const config = JSON.stringify({
|
|
250
|
+
exe: options.executablePath,
|
|
251
|
+
args: options.args,
|
|
252
|
+
profileDir: options.profileDir,
|
|
253
|
+
sessionFile: options.sessionFile,
|
|
254
|
+
bootFile: options.bootName,
|
|
255
|
+
portFile: DEVTOOLS_PORT_FILE,
|
|
256
|
+
idleMs: options.idleMs,
|
|
257
|
+
intervalMs: WATCH_INTERVAL_MS,
|
|
258
|
+
portWaitMs: PORT_WAIT_MS,
|
|
259
|
+
portPollMs: PORT_POLL_MS,
|
|
260
|
+
sessionBootMs: SESSION_BOOT_MS,
|
|
261
|
+
kill,
|
|
262
|
+
});
|
|
263
|
+
options.deps.spawnDetached(options.nodePath, ['-e', WATCHER_SCRIPT, config]);
|
|
264
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { BrowserPlatform } from '@puppeteer/browsers';
|
|
2
|
+
import { t } from "../i18n.js";
|
|
3
|
+
import { ENGINE_BROWSER, engineCacheDir } from "./engine.js";
|
|
4
|
+
export const MIRROR_BASE_URL = 'https://registry.npmmirror.com/-/binary/chrome-for-testing';
|
|
5
|
+
export const ENGINE_BUILD_ID = '156.0.8078.80';
|
|
6
|
+
export function browserPlatformOf(platform, arch) {
|
|
7
|
+
const arm = arch === 'arm64';
|
|
8
|
+
let result;
|
|
9
|
+
switch (platform) {
|
|
10
|
+
case 'darwin':
|
|
11
|
+
result = arm ? BrowserPlatform.MAC_ARM : BrowserPlatform.MAC;
|
|
12
|
+
break;
|
|
13
|
+
case 'win32':
|
|
14
|
+
result = BrowserPlatform.WIN64;
|
|
15
|
+
break;
|
|
16
|
+
default:
|
|
17
|
+
result = arm ? BrowserPlatform.LINUX_ARM : BrowserPlatform.LINUX;
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
export async function downloadCanvasEngine(deps, options = {}) {
|
|
22
|
+
const downloadOptions = {
|
|
23
|
+
browser: ENGINE_BROWSER,
|
|
24
|
+
buildId: ENGINE_BUILD_ID,
|
|
25
|
+
platform: browserPlatformOf(deps.platform, deps.arch),
|
|
26
|
+
cacheDir: engineCacheDir(deps),
|
|
27
|
+
baseUrl: options.baseUrl ?? MIRROR_BASE_URL,
|
|
28
|
+
};
|
|
29
|
+
deps.stderr(`${t('engine.downloading', { baseUrl: downloadOptions.baseUrl }, deps.env)}\n`);
|
|
30
|
+
let result;
|
|
31
|
+
try {
|
|
32
|
+
const path = await deps.download(downloadOptions);
|
|
33
|
+
result = { ok: true, path, version: ENGINE_BUILD_ID };
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
result = { ok: false, message: error instanceof Error ? error.message : String(error) };
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
export function makeEngineDownloader() {
|
|
41
|
+
return async (options) => {
|
|
42
|
+
const { install } = await import('@puppeteer/browsers');
|
|
43
|
+
const installed = await install(options);
|
|
44
|
+
return installed.executablePath;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { dirname, join } from 'node:path';
|
|
2
|
+
import { Browser } from '@puppeteer/browsers';
|
|
3
|
+
export const ENGINE_PATH_ENV = 'PUPPETEER_EXECUTABLE_PATH';
|
|
4
|
+
export const ENGINE_BROWSER = Browser.CHROMEHEADLESSSHELL;
|
|
5
|
+
export function engineCacheDir(deps) {
|
|
6
|
+
const override = deps.env?.['PUPPETEER_CACHE_DIR'];
|
|
7
|
+
let result;
|
|
8
|
+
if (override !== undefined && override !== '') {
|
|
9
|
+
result = override;
|
|
10
|
+
}
|
|
11
|
+
else {
|
|
12
|
+
result = join(deps.homeDir(), '.cache', 'puppeteer');
|
|
13
|
+
}
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
function engineBinaryName(platform) {
|
|
17
|
+
return platform === 'win32' ? `${ENGINE_BROWSER}.exe` : ENGINE_BROWSER;
|
|
18
|
+
}
|
|
19
|
+
export function engineInstallDir(binaryPath) {
|
|
20
|
+
return dirname(dirname(binaryPath));
|
|
21
|
+
}
|
|
22
|
+
const VERSION_DIR = /^[a-z0-9_]+-(\d+\.\d+\.\d+\.\d+)$/;
|
|
23
|
+
async function exists(deps, path) {
|
|
24
|
+
let result;
|
|
25
|
+
try {
|
|
26
|
+
await deps.fs.stat(path);
|
|
27
|
+
result = true;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
result = false;
|
|
31
|
+
}
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
function compareVersion(a, b) {
|
|
35
|
+
const pa = a.split('.').map(Number);
|
|
36
|
+
const pb = b.split('.').map(Number);
|
|
37
|
+
let result = 0;
|
|
38
|
+
for (let i = 0; i < 4; i += 1) {
|
|
39
|
+
const d = pa[i] - pb[i];
|
|
40
|
+
result = result === 0 ? d : result;
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
export async function detectCanvasEngine(deps) {
|
|
45
|
+
const override = deps.env[ENGINE_PATH_ENV];
|
|
46
|
+
let result;
|
|
47
|
+
if (override !== undefined && override !== '') {
|
|
48
|
+
if (await exists(deps, override)) {
|
|
49
|
+
result = { found: true, version: null, path: override };
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
result = { found: false, searched: override };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
result = await searchCache(deps);
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
async function searchCache(deps) {
|
|
61
|
+
const root = join(engineCacheDir(deps), ENGINE_BROWSER);
|
|
62
|
+
let entries;
|
|
63
|
+
try {
|
|
64
|
+
entries = await deps.fs.readdir(root);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
entries = [];
|
|
68
|
+
}
|
|
69
|
+
const versions = entries
|
|
70
|
+
.map((name) => ({ name, version: VERSION_DIR.exec(name)?.[1] }))
|
|
71
|
+
.filter((e) => e.version !== undefined)
|
|
72
|
+
.sort((a, b) => compareVersion(b.version, a.version));
|
|
73
|
+
const binary = engineBinaryName(deps.platform);
|
|
74
|
+
let result = { found: false, searched: root };
|
|
75
|
+
for (const { name, version } of versions) {
|
|
76
|
+
if (result.found)
|
|
77
|
+
break;
|
|
78
|
+
const dir = join(root, name);
|
|
79
|
+
let inner;
|
|
80
|
+
try {
|
|
81
|
+
inner = await deps.fs.readdir(dir);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
inner = [];
|
|
85
|
+
}
|
|
86
|
+
const binDir = inner.find((n) => n.startsWith(ENGINE_BROWSER));
|
|
87
|
+
if (binDir !== undefined) {
|
|
88
|
+
const bin = join(dir, binDir, binary);
|
|
89
|
+
if (await exists(deps, bin)) {
|
|
90
|
+
result = { found: true, version, path: bin };
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { CliError } from "../errors.js";
|
|
2
|
+
import { t } from "../i18n.js";
|
|
3
|
+
const CAPABILITIES = {
|
|
4
|
+
seavideo: new Set(['personal', 'team']),
|
|
5
|
+
seaflow: new Set(['personal']),
|
|
6
|
+
};
|
|
7
|
+
export function supportsSpace(entry, space) {
|
|
8
|
+
return CAPABILITIES[entry].has(space);
|
|
9
|
+
}
|
|
10
|
+
export function requireSpace(entry, space, envMap = process.env) {
|
|
11
|
+
if (supportsSpace(entry, space))
|
|
12
|
+
return;
|
|
13
|
+
throw new CliError('unsupported', t('canvas.spaceUnsupported', { entry, space }, envMap), {
|
|
14
|
+
detail: t('canvas.spaceUnsupportedDetail', { space }, envMap),
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { CliError } from "../errors.js";
|
|
3
|
+
import { t } from "../i18n.js";
|
|
4
|
+
const LOCK_ATTEMPTS = 3;
|
|
5
|
+
const ENOENT_ATTEMPTS = 2;
|
|
6
|
+
const heldLocks = new AsyncLocalStorage();
|
|
7
|
+
function errnoOf(err) {
|
|
8
|
+
const code = err?.code;
|
|
9
|
+
return typeof code === 'string' ? code : undefined;
|
|
10
|
+
}
|
|
11
|
+
export function parseLockHolder(text) {
|
|
12
|
+
let result = null;
|
|
13
|
+
try {
|
|
14
|
+
const raw = JSON.parse(text);
|
|
15
|
+
if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {
|
|
16
|
+
const pid = raw['pid'];
|
|
17
|
+
result = typeof pid === 'number' && Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
result = null;
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
async function reclaimStale(file, expected, attempt, deps) {
|
|
28
|
+
const moved = `${file}.stale.${process.pid}.${attempt}`;
|
|
29
|
+
try {
|
|
30
|
+
await deps.fs.rename(file, moved);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
let content = null;
|
|
36
|
+
try {
|
|
37
|
+
content = await deps.fs.readFile(moved, 'utf8');
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
content = null;
|
|
41
|
+
}
|
|
42
|
+
if (content === expected) {
|
|
43
|
+
try {
|
|
44
|
+
await deps.fs.unlink(moved);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
try {
|
|
51
|
+
await deps.fs.rename(moved, file);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
try {
|
|
55
|
+
await deps.fs.unlink(moved);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
throw busy(file, deps);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export class CanvasLockBusyError extends CliError {
|
|
64
|
+
constructor(message, options) {
|
|
65
|
+
super('config', message, options);
|
|
66
|
+
this.name = 'CanvasLockBusyError';
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export function isCanvasLockBusy(err) {
|
|
70
|
+
return err instanceof CanvasLockBusyError;
|
|
71
|
+
}
|
|
72
|
+
function busy(file, deps) {
|
|
73
|
+
return new CanvasLockBusyError(t('canvas.lockBusy', {}, deps.env), {
|
|
74
|
+
detail: t('canvas.lockBusyDetail', { path: file }, deps.env),
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
async function acquireLock(file, dir, deps) {
|
|
78
|
+
let attempt = 0;
|
|
79
|
+
let vanished = 0;
|
|
80
|
+
for (;;) {
|
|
81
|
+
try {
|
|
82
|
+
await deps.fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
83
|
+
await deps.fs.writeFile(file, `${JSON.stringify({ pid: process.pid })}\n`, {
|
|
84
|
+
mode: 0o600,
|
|
85
|
+
flag: 'wx',
|
|
86
|
+
});
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
const code = errnoOf(err);
|
|
91
|
+
if (code !== 'EEXIST' && code !== 'ENOENT') {
|
|
92
|
+
throw new CliError('config', t('canvas.lockWriteFailed', {}, deps.env), {
|
|
93
|
+
detail: code ?? String(err),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
if (code === 'EEXIST') {
|
|
97
|
+
attempt += 1;
|
|
98
|
+
const stale = await staleContent(file, deps);
|
|
99
|
+
if (stale === null || attempt >= LOCK_ATTEMPTS) {
|
|
100
|
+
throw busy(file, deps);
|
|
101
|
+
}
|
|
102
|
+
await reclaimStale(file, stale, attempt, deps);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
vanished += 1;
|
|
106
|
+
if (vanished >= ENOENT_ATTEMPTS) {
|
|
107
|
+
throw new CliError('config', t('canvas.lockWriteFailed', {}, deps.env), {
|
|
108
|
+
detail: 'ENOENT',
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function staleContent(file, deps) {
|
|
116
|
+
let text = null;
|
|
117
|
+
try {
|
|
118
|
+
text = await deps.fs.readFile(file, 'utf8');
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
text = null;
|
|
122
|
+
}
|
|
123
|
+
let result = null;
|
|
124
|
+
if (text === null) {
|
|
125
|
+
result = null;
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
const holder = parseLockHolder(text);
|
|
129
|
+
if (holder === null || !deps.processAlive(holder)) {
|
|
130
|
+
result = text;
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
result = null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
async function releaseLock(file, deps) {
|
|
139
|
+
try {
|
|
140
|
+
await deps.fs.unlink(file);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
export async function withCanvasLock(scope, env, fn) {
|
|
146
|
+
const file = scope.paths.canvasLockFile(env);
|
|
147
|
+
const held = heldLocks.getStore();
|
|
148
|
+
let result;
|
|
149
|
+
if (held?.has(file) === true) {
|
|
150
|
+
result = await fn();
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
await acquireLock(file, scope.paths.envDir(env), scope.deps);
|
|
154
|
+
try {
|
|
155
|
+
const next = new Set(held ?? []);
|
|
156
|
+
next.add(file);
|
|
157
|
+
result = await heldLocks.run(next, fn);
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
await releaseLock(file, scope.deps);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { CliError } from "../errors.js";
|
|
2
|
+
import { t } from "../i18n.js";
|
|
3
|
+
export const AGENT_LAUNCH_TIMEOUT_MS = 20_000;
|
|
4
|
+
const CANVAS_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
5
|
+
export async function requestCanvasLaunch(deps, config, canvasId, token) {
|
|
6
|
+
const envMap = deps.env;
|
|
7
|
+
const craft = new URL(config.seavideoBaseUrl);
|
|
8
|
+
const flow = new URL(config.flowWebBaseUrl);
|
|
9
|
+
if (craft.protocol !== 'https:' || flow.protocol !== 'https:') {
|
|
10
|
+
throw new CliError('config', t('launch.insecureOrigin', {}, envMap), {
|
|
11
|
+
detail: t('launch.insecureOriginDetail', {}, envMap),
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
assertCanvasId(canvasId, envMap);
|
|
15
|
+
const endpoint = new URL('/api/craft/v1/flow/agent-launch', craft.origin).href;
|
|
16
|
+
let response;
|
|
17
|
+
try {
|
|
18
|
+
response = await deps.fetch(endpoint, {
|
|
19
|
+
method: 'POST',
|
|
20
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
21
|
+
body: JSON.stringify({ canvas_id: canvasId }),
|
|
22
|
+
redirect: 'error',
|
|
23
|
+
signal: AbortSignal.timeout(AGENT_LAUNCH_TIMEOUT_MS),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
throw new CliError('network', t('launch.requestFailed', {}, envMap), {
|
|
28
|
+
detail: err instanceof Error ? err.message : String(err),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (!response.ok) {
|
|
32
|
+
throw new CliError('server', t('launch.httpError', { status: response.status }, envMap), {
|
|
33
|
+
detail: t('launch.httpErrorDetail', {}, envMap),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
let payload;
|
|
37
|
+
try {
|
|
38
|
+
payload = await response.json();
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
throw new CliError('server', t('launch.badJson', {}, envMap), {
|
|
42
|
+
detail: err instanceof Error ? err.message : String(err),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
return assertLaunchPayload(payload, flow, canvasId, token, envMap);
|
|
46
|
+
}
|
|
47
|
+
function assertCanvasId(canvasId, envMap) {
|
|
48
|
+
if (!CANVAS_ID_PATTERN.test(canvasId)) {
|
|
49
|
+
throw new CliError('usage', t('launch.badCanvasId', { id: canvasId }, envMap), {
|
|
50
|
+
detail: t('launch.badCanvasIdDetail', {}, envMap),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function assertLaunchPayload(payload, flow, canvasId, token, envMap) {
|
|
55
|
+
const expectedUrl = new URL(`/workflow/${canvasId}`, flow.origin).href;
|
|
56
|
+
const failure = () => new CliError('server', t('launch.mismatch', {}, envMap), {
|
|
57
|
+
detail: t('launch.mismatchDetail', {}, envMap),
|
|
58
|
+
});
|
|
59
|
+
if (typeof payload !== 'object' || payload === null)
|
|
60
|
+
throw failure();
|
|
61
|
+
const root = payload;
|
|
62
|
+
if (root['code'] !== 10_000)
|
|
63
|
+
throw failure();
|
|
64
|
+
const data = root['data'];
|
|
65
|
+
if (typeof data !== 'object' || data === null)
|
|
66
|
+
throw failure();
|
|
67
|
+
const d = data;
|
|
68
|
+
if (d['canvas_id'] !== canvasId)
|
|
69
|
+
throw failure();
|
|
70
|
+
if (d['open_url'] !== expectedUrl)
|
|
71
|
+
throw failure();
|
|
72
|
+
const rawCookie = d['cookie'];
|
|
73
|
+
if (typeof rawCookie !== 'object' || rawCookie === null)
|
|
74
|
+
throw failure();
|
|
75
|
+
const c = rawCookie;
|
|
76
|
+
const sameSite = c['sameSite'];
|
|
77
|
+
if (c['name'] !== 'T' ||
|
|
78
|
+
c['url'] !== `${flow.origin}/` ||
|
|
79
|
+
c['path'] !== '/' ||
|
|
80
|
+
c['secure'] !== true ||
|
|
81
|
+
c['httpOnly'] !== false ||
|
|
82
|
+
sameSite !== 'Lax') {
|
|
83
|
+
throw failure();
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
url: expectedUrl,
|
|
87
|
+
cookie: {
|
|
88
|
+
name: 'T',
|
|
89
|
+
value: token,
|
|
90
|
+
url: `${flow.origin}/`,
|
|
91
|
+
path: '/',
|
|
92
|
+
secure: true,
|
|
93
|
+
httpOnly: false,
|
|
94
|
+
sameSite,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|