@coda-console/plugin-check 0.8.20 → 0.8.22
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 +3 -3
- package/check/agent.mjs +2 -1
- package/check/coda/adapters/call-limit.mjs +56 -0
- package/check/coda/adapters/clock.mjs +48 -0
- package/check/coda/adapters/plugin-command.mjs +171 -0
- package/check/coda/adapters/plugin-modules.mjs +505 -0
- package/check/coda/adapters/plugin-stream-services.mjs +53 -0
- package/check/coda/adapters/plugin-test-host.d.mts +316 -0
- package/check/coda/adapters/plugin-test-host.mjs +404 -0
- package/check/coda/adapters/process-relay.mjs +74 -0
- package/check/coda/adapters/provider-api.mjs +147 -40
- package/check/coda/application/contributions.mjs +1 -0
- package/check/coda/builtin.json +66 -67
- package/check/coda/components/composers/schemas.mjs +4 -2
- package/check/coda/components/concurrency-groups/schemas.mjs +102 -0
- package/check/coda/components/plugins/plugin-extensions.mjs +104 -10
- package/check/coda/components/plugins/plugin-rules.mjs +19 -1
- package/check/coda/components/plugins/plugin-source-rules.mjs +34 -14
- package/check/coda/components/plugins/process-contributions.mjs +9 -0
- package/check/coda/components/prompt-recovery/prompt-recovery.mjs +2 -49
- package/check/coda/components/protocols/record-rules.mjs +70 -0
- package/check/coda/components/protocols/types.mjs +22 -4
- package/check/coda/components/workflows/contributions.mjs +2 -6
- package/check/coda/contract.json +29 -21
- package/check/coda/domain/errors.mjs +5 -1
- package/check/coda/domain/resume-prompt.mjs +93 -0
- package/check/coda/domain/session-env.mjs +1 -1
- package/check/coda/resources/plugins/resources/panels/panels.mjs +26 -17
- package/check/coda/resources/plugins/resources/panels/rules.mjs +0 -4
- package/check/coda/resources/plugins/resources/panels/sign-in.mjs +32 -41
- package/check/manifest.mjs +0 -1
- package/check/panel.mjs +6 -5
- package/package.json +2 -2
- package/check/coda/adapters/admission-api.mjs +0 -22
- package/check/coda/components/protocols/creation.mjs +0 -19
- package/check/coda/domain/resource-admission.mjs +0 -15
- package/check/coda/resources/plugins/resources/panels/command.mjs +0 -46
- package/check/command.mjs +0 -48
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ plugins/codex-accounts/ Codex 多账号:管理登录、自动续期与账号
|
|
|
18
18
|
plugins/cursor/ Cursor:直接启动运行机的 cursor-agent acp
|
|
19
19
|
plugins/antigravity/ Antigravity:转发运行机的 agy acp,不把附加目录交给它,加「全部放行」模式,资源页登录
|
|
20
20
|
plugins/git/ Git 源与快照:本机仓库 provider、运行关联的工作树/提交快照、临时 ref 回收与只读 smart HTTP v2
|
|
21
|
-
plugins/host/
|
|
21
|
+
plugins/host/ 宿主资源:Xcode 构建、Apple 模拟器与项目要求排队的命令共用这台机器的一组名额(组 host、持锁执行 run-held、host-sim),资源「构建名额」
|
|
22
22
|
plugins/magpie/ Magpie:把本机的 Magpie 网关作为模型服务提供给 Pi 等插件,安装时装好 Magpie 并让网关常驻
|
|
23
23
|
plugins/network-log/ 网络记录:默认关闭,按需开启建连等待与定时探测采集;关闭后仍可查看历史
|
|
24
24
|
plugins/review/ PR 生命流程:会话开的 PR 先跑项目的检查、再交叉评审,你批准后合并、部署与发布,别人的 PR 只评审;也是写 PR 流程的样例
|
|
@@ -438,7 +438,7 @@ Coda 根上的同一条 overrides 由 `sync-coda` 一起改(npm 只认根的
|
|
|
438
438
|
- `name` 是包名;另写 `id` 时以它为 Coda 插件 ID,否则以 `name` 为 ID。ID 只能用小写字母、数字和 `-`,以字母开头,至多 40 个字符。
|
|
439
439
|
本仓库的包名是 `@coda-console/<id>`,设置名与 Agent ID 仍使用原来的插件 ID。可以与 Coda 内置插件同名;从其他来源替换时,须先在目标机器卸载内置插件。契约检查照刚装好的 Coda 读:与它默认装着的内置插件同名、又不是那个插件的同一来源的,判不通过。
|
|
440
440
|
- `displayName`、`description`、`version` 显示在安装确认与插件页。
|
|
441
|
-
- `contributes` 只能有 Coda 认识的贡献:`agents`、`resources`(旧的 `panels` 仍认)、`configuration`、`capabilities`、`instructions`、`extensionPoints`、`extensions`、`
|
|
441
|
+
- `contributes` 只能有 Coda 认识的贡献:`agents`、`resources`(旧的 `panels` 仍认)、`configuration`、`capabilities`、`instructions`、`extensionPoints`、`extensions`、`commands`、`services`、`setup`;读不懂的键一律报错,不会被悄悄忽略。
|
|
442
442
|
- `setup` 是插件的设置动作:`{ "command": "…" }`,一行、不超过 4000 字(与资源命令同样的规则),没有别的键。
|
|
443
443
|
|
|
444
444
|
**从仓库安装的限制**:带 npm 依赖(`dependencies`、`optionalDependencies`)就要把 `package-lock.json` 一起提交,Coda 在插件的版本目录里
|
|
@@ -489,7 +489,7 @@ Agent 进程的环境是会话的环境再加插件进程的那组变量(资
|
|
|
489
489
|
| `actions` | 至多 8 个按钮,每个 `label` 和 `action`(须是这个类型声明的动作)、`view`(插件的视图)或 `url`(`https://` 网页)之一,可选 `args`、`disabled`、`confirm` |
|
|
490
490
|
|
|
491
491
|
`name` 与 `values` 至少有一个。没有副标题、说明行或整段文字:资源页上只有类型名、名字、读数与按钮,要说明的写进插件自己的文档或视图。
|
|
492
|
-
只在打开资源页或点「刷新」时读,30 秒没结束或输出超过
|
|
492
|
+
只在打开资源页或点「刷新」时读,30 秒没结束或输出超过 1 MiB 就停下;读不懂的键算这次读取失败。`resources` 为空的类型不显示。
|
|
493
493
|
命令的环境是后端的环境(不带会话 ID)加上插件进程的那组变量(同上),`PATH` 最前面是 Coda 后端的 `node`;`CODA_GROUPS_STATE` 是这一刻这个后端各并发组的占用与排队
|
|
494
494
|
(`{now, groups}`);动作另有 `CODA_PANEL_ARGS`(按钮的 `args`)。
|
|
495
495
|
动作至多跑 10 分钟,成功后 Coda 立即重读这个类型。之前的写法 `contributes.panels`(`{ "items": [...] }`,卡片与说明行)Coda 仍读,当作资源显示、说明文字丢掉;新插件写 `resources`。
|
package/check/agent.mjs
CHANGED
|
@@ -8,7 +8,8 @@ import { setTimeout as delay } from 'node:timers/promises';
|
|
|
8
8
|
import { mkdirSync } from 'node:fs';
|
|
9
9
|
import { join } from 'node:path';
|
|
10
10
|
import { cleared } from './coda/components/plugins/plugin-rules.mjs';
|
|
11
|
-
import { RETRY_DELAYS,
|
|
11
|
+
import { RETRY_DELAYS, serviceFailure } from './coda/components/prompt-recovery/prompt-recovery.mjs';
|
|
12
|
+
import { continuationPrompt } from './coda/domain/resume-prompt.mjs';
|
|
12
13
|
import { NOT_STEERED, OPEN_LIMIT, REMOTE_CODE, SIGNED_OUT, STEERED, STEERING, STOP_LIMIT, TERM_GRACE, clientCapabilities, currentModel, steeringParams, supportsSteering, systemPrompt, instructionsBlock,
|
|
13
14
|
takesInstructions } from './coda/domain/agent-protocol.mjs';
|
|
14
15
|
import { agentErrorMessage } from './coda/kernel/agent-failures.mjs';
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// What a call goes by (docs/plugins.md「调用」), the same for the backend's unified call (components/protocols/calls.mjs)
|
|
2
|
+
// and a plugin's test host (adapters/plugin-test-host.mjs): the operation's own `timeout`, or 30 seconds, from now on
|
|
3
|
+
// `clock` (adapters/clock.mjs), or the caller's `deadline` when that is earlier; its input and result as the operation's
|
|
4
|
+
// definition has them (`found`, as components/protocols/types.mjs compiles it); its envelope at most 1 MiB encoded.
|
|
5
|
+
import { ContractError, requireCondition as check } from '../domain/errors.mjs';
|
|
6
|
+
|
|
7
|
+
export const TIMEOUT = 30_000, ENVELOPE = 1024 * 1024;
|
|
8
|
+
const encoded = value => Buffer.byteLength(JSON.stringify(value));
|
|
9
|
+
// A request's envelope, refused past 1 MiB.
|
|
10
|
+
export const checkRequest = request => check(encoded(request) <= ENVELOPE, 'invalid_input', '调用信封超过 1 MiB');
|
|
11
|
+
// `name`: the record's protocol and the operation, as said in a refusal.
|
|
12
|
+
export const checkInput = (found, name, input) => check(found.input(input), 'invalid_input', `${name} 的输入无效`);
|
|
13
|
+
// An operation that opens a run (`run: true`) has no result of its own to check.
|
|
14
|
+
export function checkResult(found, name, result) {
|
|
15
|
+
check(!found.result || found.result(result), 'internal_error', `${name} 的结果无效`);
|
|
16
|
+
check(encoded({ result }) <= ENVELOPE, 'handler_error', `${name} 的回答超过 1 MiB`);
|
|
17
|
+
}
|
|
18
|
+
// How much a call that failed did (docs/plugins.md「调用」): nothing, some of it, or none can say.
|
|
19
|
+
export const EFFECTS = ['none', 'some', 'unknown'];
|
|
20
|
+
// A failure is an envelope too, `{ error: said }`, `said` its `code`, `message`, `effects` and `retryAfterMs` as they go out,
|
|
21
|
+
// all strings and numbers. One that says what it may not (`effects` of none of these, a `retryAfterMs` that is no whole
|
|
22
|
+
// number of milliseconds) is `handler_error`, `unknown`; one whose envelope encoded then passes 1 MiB is so with a message that
|
|
23
|
+
// says so: wherever the failure takes shape (the plugin host's channel, the unified call).
|
|
24
|
+
export const FAILURE_TOO_BIG = { code: 'handler_error', message: '调用失败,原错误的信息超过 1 MiB,已丢弃', effects: 'unknown' };
|
|
25
|
+
export function bounded(said) {
|
|
26
|
+
const { effects, retryAfterMs } = said;
|
|
27
|
+
const fine = (effects === undefined || EFFECTS.includes(effects)) && (retryAfterMs === undefined || (Number.isSafeInteger(retryAfterMs) && retryAfterMs >= 0));
|
|
28
|
+
const out = fine ? said : { code: 'handler_error', message: said.message, effects: 'unknown' };
|
|
29
|
+
return encoded({ error: out }) <= ENVELOPE ? out : { ...FAILURE_TOO_BIG };
|
|
30
|
+
}
|
|
31
|
+
// A call its caller gave up on.
|
|
32
|
+
export const abortError = effects => Object.assign(new Error('调用方已放弃这次调用'), { name: 'AbortError', ...(effects ? { effects } : {}) });
|
|
33
|
+
// A doing call past its deadline (coda#2749 3.3), as its handler's `ctx.signal` goes off with it: thrown, a `timeout` that
|
|
34
|
+
// may have been done.
|
|
35
|
+
export const timeoutError = () => Object.assign(new ContractError('timeout', '调用超过了期限', { effects: 'unknown' }), { name: 'TimeoutError' });
|
|
36
|
+
// The call's `signal` goes off at its `deadline`, as a `timeout`, or when the caller's own does, as an `AbortError`.
|
|
37
|
+
// `end()` once settled.
|
|
38
|
+
export function limit(clock, found, { signal, deadline } = {}) {
|
|
39
|
+
const at = Math.min(clock.now() + (found.timeout ?? TIMEOUT), deadline ?? Infinity);
|
|
40
|
+
const controller = new AbortController();
|
|
41
|
+
const given = () => controller.abort(abortError());
|
|
42
|
+
const passed = () => controller.abort(new ContractError('timeout', '调用超过了期限,没有等到回答'));
|
|
43
|
+
if (signal?.aborted) given(); else signal?.addEventListener('abort', given, { once: true });
|
|
44
|
+
let unarm = () => {};
|
|
45
|
+
if (at <= clock.now()) passed(); else unarm = clock.at(at, passed);
|
|
46
|
+
return { signal: controller.signal, deadline: at, end: () => { unarm(); signal?.removeEventListener('abort', given); } };
|
|
47
|
+
}
|
|
48
|
+
// Goes off with the signal's reason, for what a call waits on to race; never unhandled once what it races has settled.
|
|
49
|
+
export const stopped = signal => {
|
|
50
|
+
const promise = new Promise((_, reject) => {
|
|
51
|
+
if (signal.aborted) reject(signal.reason);
|
|
52
|
+
else signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
|
53
|
+
});
|
|
54
|
+
promise.catch(() => {});
|
|
55
|
+
return promise;
|
|
56
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// The one clock deadlines go off by (issue #720「可靠计时」): whatever is due at a time asks it, and it keeps a single
|
|
2
|
+
// timer, for the earliest. `now` is the backend's clock (tests move it), read again whenever the timer goes off; what is
|
|
3
|
+
// due by then is called, the rest waits on.
|
|
4
|
+
export class Clock {
|
|
5
|
+
constructor(now = Date.now) { this.now = now; this.due = new Set(); this.timer = null; this.armed = null; }
|
|
6
|
+
// Calls `fn` once `now()` has reached `time`; returns what cancels it.
|
|
7
|
+
at(time, fn) {
|
|
8
|
+
const entry = { time, fn };
|
|
9
|
+
this.due.add(entry); this.arm();
|
|
10
|
+
return () => { if (this.due.delete(entry)) this.arm(); };
|
|
11
|
+
}
|
|
12
|
+
// Calls `fn` once `ms` have passed on this clock; Infinity never comes. Returns what cancels it.
|
|
13
|
+
after(ms, fn) { return Number.isFinite(ms) ? this.at(this.now() + ms, fn) : () => {}; }
|
|
14
|
+
arm() {
|
|
15
|
+
let next = null;
|
|
16
|
+
for (const { time } of this.due) if (next === null || time < next) next = time;
|
|
17
|
+
if (next === this.armed) return;
|
|
18
|
+
clearTimeout(this.timer); this.armed = next;
|
|
19
|
+
if (next === null) return;
|
|
20
|
+
// A timer waits at most about 24 days; one due later is looked at again then.
|
|
21
|
+
this.timer = setTimeout(() => this.fire(), Math.min(Math.max(0, next - this.now()) + 1, 2 ** 31 - 1));
|
|
22
|
+
this.timer.unref?.();
|
|
23
|
+
}
|
|
24
|
+
// What is due by now goes off; then the next is asked of the timer. Also when the clock was moved (tests set `now`).
|
|
25
|
+
fire() {
|
|
26
|
+
this.armed = null;
|
|
27
|
+
const now = this.now();
|
|
28
|
+
for (const entry of [...this.due]) {
|
|
29
|
+
if (entry.time > now || !this.due.delete(entry)) continue;
|
|
30
|
+
try { entry.fn(); } catch (e) { console.error('到期处理失败', e); }
|
|
31
|
+
}
|
|
32
|
+
this.arm();
|
|
33
|
+
}
|
|
34
|
+
close() { clearTimeout(this.timer); this.due.clear(); this.armed = null; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// A limit of `ms` from `started` that does not count while paused (the job's, while its script waits on an agent): `due()`
|
|
38
|
+
// is when it comes, null while paused; what was spent paused moves it on.
|
|
39
|
+
export class Limit {
|
|
40
|
+
constructor(started, ms) { this.started = started; this.ms = ms; this.pausedAt = null; this.spent = 0; }
|
|
41
|
+
// Told at `now` whether the time is paused; returns whether that changed anything.
|
|
42
|
+
pause(paused, now) {
|
|
43
|
+
if (paused === (this.pausedAt !== null)) return false;
|
|
44
|
+
if (paused) this.pausedAt = now; else { this.spent += now - this.pausedAt; this.pausedAt = null; }
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
due() { return this.pausedAt === null ? this.started + this.ms + this.spent : null; }
|
|
48
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// The one runner of a plugin's commands (docs/plugins.md「命令的约定」): its endpoints, the operations its commands implement
|
|
2
|
+
// (components/plugins/plugin-host.mjs `startCommand`), its resources' readings and actions,
|
|
3
|
+
// their logins and installers, its setup; and, bounded the same way, the programs Coda runs for a plugin itself (Git taking a
|
|
4
|
+
// plugin from its repository, components/plugins/plugin-sources.mjs; a repository's listing; what a plugin tells agents).
|
|
5
|
+
// A command runs in a process group of its own, and only that group is touched: once it is cancelled (`cancel`, `stop()`) or
|
|
6
|
+
// past its deadline on `clock` (the backend's one clock, adapters/clock.mjs; a clock of its own in a plugin's module) the
|
|
7
|
+
// group is asked to end (TERM), and made to (KILL) once `graceMs` has passed; once `signal` aborts (its owner closing, the
|
|
8
|
+
// clock with it, nothing left to wait out the grace) it is made to at once. Whatever it left in its group goes as its process
|
|
9
|
+
// exits of itself, not once its pipes close: what it left may hold them (`sleep 300 & …`); asked to end, what it left has
|
|
10
|
+
// the rest of the grace to, even once the run has settled (its pipes closed, what it left writing elsewhere). One that left
|
|
11
|
+
// its group still holding them (a daemon it started, `adb start-server`'s) is waited for no longer than DRAIN once its
|
|
12
|
+
// process has exited and nothing is left of the grace: its pipes are closed, and it ended as its exit code and what it
|
|
13
|
+
// said by then say.
|
|
14
|
+
// What it reads is `input`, written to its standard input and closed (`open`: kept open, for what a login is given later).
|
|
15
|
+
// Its standard output is its answer, at most `maxBytes` (an envelope's, 1 MiB), past which it is stopped; `tail` keeps the last
|
|
16
|
+
// of it instead, for one that may say much on its way (a setup installing what it needs). Its standard error is its log, the
|
|
17
|
+
// last LOG bytes of it kept, never a reason to stop it. `onOutput` is told every piece of either as it comes.
|
|
18
|
+
// It starts its process through `start` (the backend's registry door, adapters/process-start.mjs; a plugin's module, the
|
|
19
|
+
// resources plugin's, gives one that registers nothing): a command a backend starts is registered for as long as it runs,
|
|
20
|
+
// under `label` (docs/process-registry.md). A plugin's command is handed a token of its plugin's in CODA_TOKEN (`token`,
|
|
21
|
+
// docs/plugins.md「令牌」): `issue(run)` issues it for this run, as it starts, and `revoke(run)` revokes it as it ends.
|
|
22
|
+
// `settle` says what it came to, by the convention.
|
|
23
|
+
import { randomUUID } from 'node:crypto';
|
|
24
|
+
import { tmpdir } from 'node:os';
|
|
25
|
+
import { posix } from 'node:path';
|
|
26
|
+
import { ENVELOPE, stopped } from './call-limit.mjs';
|
|
27
|
+
import { Clock } from './clock.mjs';
|
|
28
|
+
import { failureOf } from './provider-api.mjs';
|
|
29
|
+
import { ContractError } from '../domain/errors.mjs';
|
|
30
|
+
import { TOKEN_ENV } from '../domain/session-env.mjs';
|
|
31
|
+
import { derivedUUID } from '../domain/values.mjs';
|
|
32
|
+
|
|
33
|
+
export const GRACE = 10_000, LOG = 64 * 1024;
|
|
34
|
+
// How long what a command wrote just before it exited is waited for once it has: its pipes drain at once unless a process
|
|
35
|
+
// outside its group holds them, which may hold them for ever. Ample for the last of its output, short beside any call.
|
|
36
|
+
export const DRAIN = 2_000;
|
|
37
|
+
const ansi = /\x1b\[[0-9;]*[A-Za-z]/g;
|
|
38
|
+
// The last thing a failed command said, for the one line the user sees.
|
|
39
|
+
export const lastLine = text => text.replace(ansi, '').split('\n').map(line => line.trim()).filter(Boolean).at(-1)?.slice(0, 200) ?? '';
|
|
40
|
+
// A module's own: it has no backend clock to share.
|
|
41
|
+
const SYSTEM = new Clock();
|
|
42
|
+
// Whether a process group lives.
|
|
43
|
+
export function groupAlive(pgid) {
|
|
44
|
+
if (!Number.isSafeInteger(pgid) || pgid <= 1) return false;
|
|
45
|
+
try { process.kill(-pgid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// A command line from a plugin's manifest, `sh -c` from `cwd`: the plugin's directory for those of the convention
|
|
49
|
+
// (docs/plugins.md「命令的约定」), a temporary one for the rest.
|
|
50
|
+
export const runPluginCommand = (command, options) => runBounded('/bin/sh', ['-c', command], { cwd: tmpdir(), ...options });
|
|
51
|
+
export const startPluginCommand = (command, options) => startBounded('/bin/sh', ['-c', command], { cwd: tmpdir(), ...options });
|
|
52
|
+
export const runBounded = (program, args, options) => startBounded(program, args, options).done;
|
|
53
|
+
// The command line that runs a plugin's file implementing an operation (docs/plugins.md「用命令实现操作」), from its directory.
|
|
54
|
+
export const fileCommand = file => `./'${posix.normalize(file).replaceAll("'", "'\\''")}'`;
|
|
55
|
+
// What a command implementing an operation is told of its call in its environment, as a module's handler is in its `ctx`
|
|
56
|
+
// (docs/plugins.md「用命令实现操作」): its record (`ctx.record`, its key only of one its plugin holds here), its ID (`ctx.id`)
|
|
57
|
+
// and, when it has one, its deadline (`ctx.deadline`, milliseconds).
|
|
58
|
+
export const callEnv = ({ id, record, deadline }) => ({ CODA_RECORD_KIND: record.kind, CODA_RECORD_ID: record.id,
|
|
59
|
+
...(record.key === undefined ? {} : { CODA_RECORD_KEY: record.key }), CODA_CALL_ID: id,
|
|
60
|
+
...(deadline === null || deadline === undefined ? {} : { CODA_DEADLINE: String(deadline) }) });
|
|
61
|
+
// A query's ID, as its handler is given it (`ctx.id`, adapters/plugin-modules.mjs): of its caller and its request's.
|
|
62
|
+
export const queryId = request => derivedUUID('query', request.parent, request.requestId);
|
|
63
|
+
|
|
64
|
+
// `label`: what the registry says of it, the plugin and the command by name (never the command's text or what it is given: those may carry credentials).
|
|
65
|
+
// `{ done, ended, write, stop, kill }`: how it ended (`{ code, stdout, stderr, timedOut, canceled, overflow, error?, started? }`);
|
|
66
|
+
// once its group has, nothing of it left (made to end, so the grace passed at most): `done` may come before, what it left
|
|
67
|
+
// still in its grace; what writes to its standard input, when kept `open`; what cancels it (TERM, then KILL past the grace);
|
|
68
|
+
// what ends it at once.
|
|
69
|
+
export function startBounded(program, args, { start, label, cwd, env, clock = SYSTEM, timeoutMs, graceMs = GRACE, signal: closing, cancel,
|
|
70
|
+
maxBytes = ENVELOPE, tail = false, input = null, open = false, onOutput = () => {}, token = null }) {
|
|
71
|
+
// One owner for each run: two of the same command at once are two entries, with a token each.
|
|
72
|
+
const owner = { party: 'host', kind: 'plugin-command', object: randomUUID() };
|
|
73
|
+
let resolve, reaped;
|
|
74
|
+
const done = new Promise(r => { resolve = r; }), ended = new Promise(r => { reaped = r; });
|
|
75
|
+
const handle = { done, ended, write: () => {}, stop: () => {}, kill: () => {} };
|
|
76
|
+
let child;
|
|
77
|
+
const handed = token ? { ...env, [TOKEN_ENV]: token.issue(owner.object) } : env;
|
|
78
|
+
try { child = start.spawn(owner, { tier: 'full', claim: null, label, outlives: false }, program, args, { cwd, env: handed, stdio: [input === null && !open ? 'ignore' : 'pipe', 'pipe', 'pipe'] }); }
|
|
79
|
+
// The registry could not take it, and has ended its group: as good as one that did not start, but for having run a moment.
|
|
80
|
+
catch (error) {
|
|
81
|
+
token?.revoke(owner.object);
|
|
82
|
+
reaped();
|
|
83
|
+
resolve({ code: null, stdout: '', stderr: '', timedOut: false, canceled: false, overflow: false, error: error.message, started: !!error.started });
|
|
84
|
+
return handle;
|
|
85
|
+
}
|
|
86
|
+
// A command that ends without reading all of it is no error of the writing.
|
|
87
|
+
if (input !== null || open) child.stdin.on('error', () => {});
|
|
88
|
+
if (input !== null) child.stdin.end(input);
|
|
89
|
+
const out = [], err = [];
|
|
90
|
+
let sizes = [0, 0], overflow = false, timedOut = false, canceled = false, finished = false, hard = null, drain = null;
|
|
91
|
+
// `graced`: asked to end (TERM), the grace not yet run out; `exited`: its process has, with `exitCode`.
|
|
92
|
+
let graced = false, exited = false, exitCode = null;
|
|
93
|
+
const signal = name => { try { process.kill(-child.pid, name); } catch {} };
|
|
94
|
+
// What still holds its pipes past DRAIN is no longer waited for.
|
|
95
|
+
const drained = () => { drain = clock.at(clock.now() + DRAIN, () => { child.stdout.destroy(); child.stderr.destroy(); finish(exitCode); }); };
|
|
96
|
+
// Its group made to end and its entry gone, nothing left to wait for it.
|
|
97
|
+
const reap = () => { hard?.(); closing?.removeEventListener('abort', kill); if (child.pid) { signal('SIGKILL'); start.remove(owner); } reaped(); };
|
|
98
|
+
const stop = () => {
|
|
99
|
+
if (finished || hard) return;
|
|
100
|
+
signal('SIGTERM'); graced = true;
|
|
101
|
+
hard = clock.at(clock.now() + graceMs, () => { graced = false; if (finished) return reap(); signal('SIGKILL'); if (exited) drained(); });
|
|
102
|
+
};
|
|
103
|
+
// Its process made to end at once; settled already, in its grace, what it left in its group is.
|
|
104
|
+
const kill = () => { const pending = graced; graced = false; if (!finished) signal('SIGKILL'); else if (pending) reap(); };
|
|
105
|
+
const due = clock.at(clock.now() + timeoutMs, () => { timedOut = true; stop(); });
|
|
106
|
+
const cancelled = () => { canceled = true; stop(); };
|
|
107
|
+
closing?.addEventListener('abort', kill, { once: true });
|
|
108
|
+
cancel?.addEventListener('abort', cancelled, { once: true });
|
|
109
|
+
const keep = (chunks, i, most, last) => chunk => {
|
|
110
|
+
onOutput(chunk.toString('utf8'));
|
|
111
|
+
if (last) { sizes[i] += chunk.length; chunks.push(chunk); while (sizes[i] > most && chunks.length > 1) sizes[i] -= chunks.shift().length; return; }
|
|
112
|
+
if (sizes[i] + chunk.length > most) { if (!overflow) { overflow = true; stop(); } return; }
|
|
113
|
+
sizes[i] += chunk.length; chunks.push(chunk);
|
|
114
|
+
};
|
|
115
|
+
child.stdout.on('data', keep(out, 0, maxBytes, tail));
|
|
116
|
+
child.stderr.on('data', keep(err, 1, LOG, true));
|
|
117
|
+
const finish = (code, error) => {
|
|
118
|
+
if (finished) return;
|
|
119
|
+
finished = true; due(); drain?.(); cancel?.removeEventListener('abort', cancelled);
|
|
120
|
+
// Whatever it left behind in its group goes with it; asked to end, once the grace has passed, if anything is left.
|
|
121
|
+
if (!graced || !groupAlive(child.pid)) reap();
|
|
122
|
+
token?.revoke(owner.object);
|
|
123
|
+
resolve({ code, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8'), timedOut, canceled, overflow, ...(error ? { error } : {}) });
|
|
124
|
+
};
|
|
125
|
+
child.on('error', error => finish(null, error.message));
|
|
126
|
+
// Exited of itself, what it left in its group goes now; asked to end, what it left has the rest of the grace to.
|
|
127
|
+
child.on('exit', code => {
|
|
128
|
+
exited = true; exitCode = code;
|
|
129
|
+
if (graced) return;
|
|
130
|
+
signal('SIGKILL'); drained();
|
|
131
|
+
});
|
|
132
|
+
child.on('close', code => finish(code));
|
|
133
|
+
return Object.assign(handle, { write: text => child.stdin?.write(text), stop: cancelled, kill });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const failure = (code, message, effects = 'unknown') => ({ error: { code, message, effects } });
|
|
137
|
+
// What a command that ended as `ran` came to (docs/plugins.md「命令的约定」): `{ result }`, or `{ error: { code, message,
|
|
138
|
+
// effects } }`. The exit code first: 0 is done, its standard output whole the result, a JSON value; anything else failed, as
|
|
139
|
+
// the `{ "error": … }` it printed says (checked as a module's, adapters/provider-api.mjs failureOf), or else `command_failed`.
|
|
140
|
+
// Stopped, by its deadline or for saying more than 1 MiB, or cancelled, it may have done anything: `unknown`. `answers`:
|
|
141
|
+
// false for a command whose standard output is no result but what it says on its way (a setup, a login, an action), which
|
|
142
|
+
// ending with 0 is all of. `what`: the command, as a failure names it.
|
|
143
|
+
export function settle(ran, { answers = true, what = '命令' } = {}) {
|
|
144
|
+
if (ran.error) return failure('command_failed', `${what}没有开始:${ran.error}`, ran.started ? 'unknown' : 'none');
|
|
145
|
+
if (ran.overflow) return failure('handler_error', `${what}的输出超过 1 MiB`);
|
|
146
|
+
if (ran.timedOut) return failure('timeout', `${what}超时`);
|
|
147
|
+
if (ran.canceled) return failure('canceled', `${what}已取消`);
|
|
148
|
+
if (ran.code !== 0) return { error: said(ran.stdout) ?? { code: 'command_failed', effects: 'unknown',
|
|
149
|
+
message: lastLine(ran.stderr) || lastLine(ran.stdout) || `${what}没有完成(退出码 ${ran.code ?? '无'})` } };
|
|
150
|
+
if (!answers) return { result: null };
|
|
151
|
+
let result;
|
|
152
|
+
try { result = JSON.parse(ran.stdout); } catch { return failure('command_failed', `${what}的输出不是 JSON`); }
|
|
153
|
+
return Buffer.byteLength(JSON.stringify({ result })) <= ENVELOPE ? { result } : failure('handler_error', `${what}的输出超过 1 MiB`);
|
|
154
|
+
}
|
|
155
|
+
// A query a command answers (components/plugins/plugin-host.mjs `queryCommand`, the plugin test host's), given up on as `signal`
|
|
156
|
+
// goes off: its result, or the failure it ended with (`settle`). Given up on already, its command is not started (`start`)
|
|
157
|
+
// and it fails with the reason, nothing done; given up on while it runs, it fails at once with the reason, and its command,
|
|
158
|
+
// started with `signal` as its `cancel`, is stopped.
|
|
159
|
+
export async function queryCommand(start, signal) {
|
|
160
|
+
if (signal.aborted) throw Object.assign(signal.reason, { effects: 'none' });
|
|
161
|
+
const { result, error } = settle(await Promise.race([start().done, stopped(signal)]));
|
|
162
|
+
if (error) throw new ContractError(error.code, error.message, error);
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
// The failure a command printed as it failed, `{ "error": { code, message, effects } }`, or null for anything else.
|
|
166
|
+
function said(stdout) {
|
|
167
|
+
let value;
|
|
168
|
+
try { value = JSON.parse(stdout); } catch { return null; }
|
|
169
|
+
const error = value?.error;
|
|
170
|
+
return error && typeof error === 'object' && typeof error.message === 'string' ? failureOf(error) : null;
|
|
171
|
+
}
|