@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
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
export class ContractError extends Error {
|
|
2
|
-
|
|
2
|
+
// `effects`, when said: how much of what was asked was done — `none`, `some` or `unknown`; `retryAfterMs`, when said: how
|
|
3
|
+
// long the caller had better wait before asking again (docs/plugins.md「调用」).
|
|
4
|
+
constructor(code, message, { effects, retryAfterMs } = {}) {
|
|
3
5
|
super(message);
|
|
4
6
|
this.name = 'ContractError';
|
|
5
7
|
this.code = code;
|
|
8
|
+
if (effects) this.effects = effects;
|
|
9
|
+
if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;
|
|
6
10
|
}
|
|
7
11
|
}
|
|
8
12
|
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
// What a session is told when it goes on after a failed turn, and by which rule: pure, shared by the places that resume one.
|
|
4
|
+
// A turn's own retries (components/prompt-recovery/recovery.mjs) say only `continuationPrompt`; the rule
|
|
5
|
+
// (`resumeChoice`) and when a delegation goes on (`resumePlan`) are a workflow step's agent's (components/workflows), a
|
|
6
|
+
// session's call of another's (components/prompt-recovery/call-resumes.mjs) and a root session's resumes after a quota stop
|
|
7
|
+
// or a process exit.
|
|
8
|
+
export const continuationPrompt = '继续完成当前任务,沿用已有上下文和已完成的工作,从尚未完成的部分接着执行。';
|
|
9
|
+
// What a session is told when a turn of it was cut off and what came of it is not known (a lost connection, a restart of the
|
|
10
|
+
// backend or of the host): check what was done before going on, from what is not done, with the task for reference.
|
|
11
|
+
export const verifyPrompt = task => `上一轮执行中断,结果未知(例如断网、宿主掉线或后端重启)。请先核对已有上下文、工作区与正在进行的任务,确认中断前的操作结果,避免重复执行已完成或结果不明的操作;沿用原任务和已完成的工作,从尚未完成的部分继续。\n\n原任务参考(用于核对进度,不要从头重做):\n${task}`;
|
|
12
|
+
// What a session is told when it goes on after a failed turn, by one rule wherever that is done (a delegation, resumePlan
|
|
13
|
+
// below; a root session's quota or process-exit resume, components/workflows/quota-resumes.mjs):
|
|
14
|
+
// `continue`, to go on, for a turn after the one its input began (`turnId` is not the input's turn), or once the agent took
|
|
15
|
+
// the input (`failure.input` `accepted`; or the input `delivered`, but not for a quota: a turn ended by one is settled so
|
|
16
|
+
// whatever happened, so only the agent's word counts); `original`, the input again, when the agent said it never took it
|
|
17
|
+
// (`not_accepted`; `again` where something else says it was kept as it was); `verify`, the input with a check first, when
|
|
18
|
+
// nothing says. `input`: the input the turn began from as its operation keeps it, `{ turnId, inputState }`; none for a turn
|
|
19
|
+
// no input began.
|
|
20
|
+
export const resumeChoice = (failure, turnId, input, { quota = false, again = 'original' } = {}) =>
|
|
21
|
+
failure?.input === 'accepted' || (input?.inputState === 'delivered' && !quota) || turnId !== input?.turnId ? 'continue'
|
|
22
|
+
: failure?.input === 'not_accepted' ? again : 'verify';
|
|
23
|
+
// The request a workflow's `send-session` message is submitted as (application/coda-actions.mjs): one per session and key,
|
|
24
|
+
// so that a resume it sent is known again by the key it was sent under (components/workflows/quota-resumes.mjs).
|
|
25
|
+
export const sendRequestId = (threadId, key) => `send:${threadId}:${createHash('sha256').update(key).digest('hex').slice(0, 32)}`;
|
|
26
|
+
// The words of a choice: `task`, the input's, for the two that carry it; `go` the caller's own for going on.
|
|
27
|
+
export const resumeText = (choice, task, go) => ({ original: task, continue: go, verify: verifyPrompt(task) })[choice];
|
|
28
|
+
// Whether and when a delegation goes on after one of its attempts failed, by one rule wherever that is done: a workflow
|
|
29
|
+
// step's agent (docs/workflows.md「Agent 步骤」, components/workflows/workflow-jobs.mjs) and a session's call of another
|
|
30
|
+
// (docs/subagent-design.md「失败后续跑」, components/prompt-recovery/call-resumes.mjs). An attempt fails as it fails, and the
|
|
31
|
+
// delegation goes on in the same session after one that failed in a way worth going on from — the service unavailable or
|
|
32
|
+
// the outcome unknown (`service`), the quota spent (`quota`), a login to be done again (`auth`, of which the user is
|
|
33
|
+
// alerted) —, at the time this gives; it hands the failure back only once that gives up. `known`: what the delegation keeps
|
|
34
|
+
// of its attempts, `resume` how it went on so far; `standing`: how the session stands for the attempt that failed, judged by
|
|
35
|
+
// the turn that ended it (`endTurn`, with what its agent said of its failure), not whatever turn came after, and the
|
|
36
|
+
// operation of the input it began from (`operation`: its stage and error, `turnId` and `inputState`, as
|
|
37
|
+
// kernel.sessions standing gives them). Null for a failure not worth going on from (one the agent named no
|
|
38
|
+
// category for, a stop, a cancel, an input that could not be prepared); `exhausted` once the waiting allowed is spent.
|
|
39
|
+
// `prompt`: what the next call says, by the one rule every resume shares (domain/resume-prompt resumeChoice): `continue`,
|
|
40
|
+
// `original` or `verify`; also `verify` for an outcome unknown the agent said nothing of.
|
|
41
|
+
export const MINUTE = 60_000, HOUR = 60 * MINUTE;
|
|
42
|
+
export const RESUME = { service: { delays: [MINUTE, 5 * MINUTE, 15 * MINUTE, 30 * MINUTE], budget: 6 * HOUR },
|
|
43
|
+
quota: { delay: HOUR, budget: 24 * HOUR, after: 2 * MINUTE }, auth: { delay: 10 * MINUTE, budget: 24 * HOUR } };
|
|
44
|
+
// How long a call that went on from an `auth` wait must have gone without failing again for the login to count as done:
|
|
45
|
+
// the user's alert is then taken back.
|
|
46
|
+
export const AUTH_PROBE = 5 * MINUTE;
|
|
47
|
+
// `agent`: the name of the session's agent, for what the user is told of a login to do.
|
|
48
|
+
const KINDS = { quota_exhausted: 'quota', service_unavailable: 'service', auth_required: 'auth' };
|
|
49
|
+
export function resumePlan(known, { endTurn: turn, operation }, now, agent = '') {
|
|
50
|
+
const failure = turn?.failure, error = (turn?.error ?? operation?.error ?? '').replace(/^额度不足\s*/, '').replace(/\s+/g, ' ').trim().slice(0, 300);
|
|
51
|
+
let kind, prompt, reason;
|
|
52
|
+
const taken = operation?.inputState === 'delivered', again = known.resume?.prompt ?? 'original';
|
|
53
|
+
// Stuck (an outcome unknown), unless the turn that ended the call said why it failed and was not stopped: a turn ahead of
|
|
54
|
+
// its input in the session was stuck and stopped, and its own then ran into a quota, say. Stuck before its input began
|
|
55
|
+
// a turn, nothing of it was handed over.
|
|
56
|
+
if (known.stalled && !(KINDS[failure?.kind] && turn.stopRequestedAt == null)) [kind, prompt, reason] = ['service', !taken && !operation?.turnId ? again : 'verify', known.stalled];
|
|
57
|
+
else if (known.outcome === 'cancelled' || !turn || turn.stopRequestedAt != null || ['failed', 'cancelled'].includes(operation?.stage)) return null;
|
|
58
|
+
else if (KINDS[failure?.kind]) {
|
|
59
|
+
kind = KINDS[failure.kind];
|
|
60
|
+
prompt = resumeChoice(failure, turn.id, operation, { quota: kind === 'quota', again });
|
|
61
|
+
reason = { quota: '额度不足', service: '服务暂不可用', auth: `要重新登录${agent ? ` ${agent}` : ''}${failure.login ? `(${failure.login})` : ''}` }[kind];
|
|
62
|
+
}
|
|
63
|
+
// The agent's session ended under the turn (`session_ended`) is an outcome unknown as well, told by the rule.
|
|
64
|
+
else if (turn.state === 'unknown' && (!failure || failure.kind === 'session_ended'))
|
|
65
|
+
[kind, prompt, reason] = ['service', failure ? resumeChoice(failure, turn.id, operation, { again }) : 'verify', '结果未知'];
|
|
66
|
+
else return null;
|
|
67
|
+
const before = known.resume?.kind === kind ? known.resume : null, k = before ? before.k + 1 : 0, waited = before?.waited ?? 0;
|
|
68
|
+
// A quota given a reset time still to come is waited for however long it is; a little after it, as the reset is the upstream's
|
|
69
|
+
// estimate. One that is past or unreadable is no time at all: the quota then waits as one given none.
|
|
70
|
+
const reset = kind === 'quota' ? Date.parse(failure.resetAt) : NaN;
|
|
71
|
+
if (reset > now) return { kind, prompt, reason, error, k, waited, at: reset + RESUME.quota.after };
|
|
72
|
+
const { delays, delay: each, budget } = RESUME[kind];
|
|
73
|
+
const delay = each ?? Math.max(delays[Math.min(k, delays.length - 1)], failure?.retryAfterMs ?? 0);
|
|
74
|
+
if (waited + delay > budget) return { exhausted: true, reason, error, budget };
|
|
75
|
+
// What the user is alerted of a login to do names it by the agent's account, else the agent, from when it first stood in the way.
|
|
76
|
+
const alert = kind === 'auth' ? { who: failure.login ?? agent, since: before?.alert?.since ?? now } : null;
|
|
77
|
+
return { kind, prompt, reason, error, k, waited: waited + delay, at: now + delay, alert };
|
|
78
|
+
}
|
|
79
|
+
// A span of time as the lines below say it.
|
|
80
|
+
export const span = ms => ms >= HOUR ? `${ms / HOUR} 小时` : `${ms / MINUTE} 分钟`;
|
|
81
|
+
// Why a delegation is handed back failed after it went on (`resume`, as kept, `n` the times it went on): it waited all it was
|
|
82
|
+
// allowed (`plan` exhausted), or the failure now is not one to go on from (`plan` null). Null for one that never went on and
|
|
83
|
+
// fails as it failed.
|
|
84
|
+
export const gaveUpLine = (plan, resume) => plan
|
|
85
|
+
? `受阻(${plan.reason}),${resume ? `续跑 ${resume.n} 次后` : ''}等满 ${span(plan.budget)} 仍未恢复,不再续跑;最后一次:${plan.error || plan.reason}`
|
|
86
|
+
: resume ? `此前续跑 ${resume.n} 次;这次的失败不能自动续跑` : null;
|
|
87
|
+
const clockTime = time => { const d = new Date(time), p = n => String(n).padStart(2, '0'); return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; };
|
|
88
|
+
// What a delegation held up until it goes on says of itself (`resume`, as kept): in a step's log and as the step line of its
|
|
89
|
+
// node, and as the line of a session's wait to go on. The clients write no `<t:…>` mark in these lines, so the time is the
|
|
90
|
+
// backend's clock's.
|
|
91
|
+
export const blockedLine = ({ reason, at, n }) => `受阻:${reason},${clockTime(at)} 续(第 ${n} 次)`;
|
|
92
|
+
// What the conversation shows of a resume, by the choice; what the agent is told is the input itself (ProductService.inputPrompt).
|
|
93
|
+
export const RESUME_SAID = { original: '续跑:重发上一条消息', verify: '续跑:先核对再接着做', continue: '继续' };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Every command a session's agent runs inherits which session it belongs to, so that a tool such as `coda
|
|
1
|
+
// Every command a session's agent runs inherits which session it belongs to, so that a tool such as `coda run` knows who
|
|
2
2
|
// is asking without being told (docs/workflows.md「从命令行调用」); a process Coda runs for no session is started without it.
|
|
3
3
|
export const THREAD_ENV = 'CODA_THREAD_ID';
|
|
4
4
|
// With it, the token the backend issued to the process doing the session's or the step's work (kernel/records/tokens.mjs):
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// The resource types installed plugins bring to this machine's resources page (docs/plugins.md「资源」), read and acted on
|
|
2
2
|
// here, in the resources plugin's module: what each plugin declares comes from Coda's collection of the installed plugins
|
|
3
3
|
// (`coda.watch("plugins")`), and each command runs with that plugin's own environment (`coda.environment(null, { plugin })`),
|
|
4
|
-
// as Coda gives every process of the plugin's
|
|
4
|
+
// as Coda gives every process of the plugin's, with no token of its (docs/plugins.md「令牌」: a module never holds another
|
|
5
|
+
// plugin's; the host is to run them, coda#2749 H9). A plugin declaring `resources` has those; one still declaring the panels
|
|
5
6
|
// before them has its panels, read as they were (`format`), for the page to take as resources (docs/plugins.md「旧的面板」).
|
|
6
7
|
// A type is read when a page asks (opening it, refreshing, an action), or, for a kind declaring `report`, on its period
|
|
7
8
|
// while this machine shows it; nothing else is read in the background, and no reading is kept on disk.
|
|
@@ -9,20 +10,24 @@
|
|
|
9
10
|
// reading shown again within the type's `maxAge` and listed with it, and on failure the last good one kept and marked as
|
|
10
11
|
// such. The machine keeps which it shows and which not, in this plugin's state; their order is their plugins'
|
|
11
12
|
// (docs/resources-page.md「顺序」). Inside, a type is still called a panel, as the page's view and its messages are.
|
|
12
|
-
import { spawnSync } from 'node:child_process';
|
|
13
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
13
14
|
import { readFileSync, writeFileSync, renameSync } from 'node:fs';
|
|
14
15
|
import { tmpdir } from 'node:os';
|
|
15
16
|
import { join } from 'node:path';
|
|
16
|
-
import {
|
|
17
|
+
import { runPluginCommand, settle } from '../../../../adapters/plugin-command.mjs';
|
|
17
18
|
import { PanelError, panelDeclarations, panelItems, resourceItems, actionArgs, shownItems, displayOptions, keepMissingMetrics } from './rules.mjs';
|
|
18
19
|
import { SignIn, authorizationLink, deviceCode } from './sign-in.mjs';
|
|
19
20
|
|
|
20
21
|
const fail = (code, message) => { throw new PanelError(code, message); };
|
|
22
|
+
// How a command starts here, in the plugin host's tree, whose root is registered: in a process group of its own, as the
|
|
23
|
+
// backend's registry door starts one (adapters/process-start.mjs), registering nothing.
|
|
24
|
+
const start = { spawn: (_owner, _entry, file, args, options) => spawn(file, args, { ...options, detached: true }), remove: () => {} };
|
|
21
25
|
|
|
22
26
|
export class Panels {
|
|
23
27
|
// `onChange(key)`: a panel moved (its reading, its login, whether it is hidden); none for the list as a whole.
|
|
24
|
-
// `run`: how a command runs (
|
|
25
|
-
|
|
28
|
+
// `run`: how a command runs (adapters/plugin-command.mjs runPluginCommand, from its plugin's directory with its environment,
|
|
29
|
+
// started here); `now()`: the time, as readings are dated by it.
|
|
30
|
+
constructor(coda, { run = runPluginCommand, now = Date.now, readTimeoutMs = 30_000, actionTimeoutMs = 10 * 60_000, timer = true } = {}) {
|
|
26
31
|
this.coda = coda; this.run = run; this.now = now; this.readTimeoutMs = readTimeoutMs; this.actionTimeoutMs = actionTimeoutMs; this.timerOn = timer;
|
|
27
32
|
// `last`: each panel's last good items, for a failed reading to show again; `shown`: what its last reading answered.
|
|
28
33
|
this.plugins = new Map(); this.last = new Map(); this.shown = new Map(); this.reading = new Map(); this.acting = new Map(); this.failures = new Map();
|
|
@@ -143,16 +148,18 @@ export class Panels {
|
|
|
143
148
|
if (panel.reportMs) this.reportedAt.set(key, this.now());
|
|
144
149
|
let failure;
|
|
145
150
|
try {
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
151
|
+
const env = await this.env(plugin.id);
|
|
152
|
+
const ran = await this.run(panel.command, { start, cwd: env.CODA_PLUGIN_PATH, env, input: '{}', timeoutMs: this.readTimeoutMs, signal: this.closing.signal });
|
|
153
|
+
const { error } = settle(ran, { what: '读取' });
|
|
154
|
+
if (!error) {
|
|
155
|
+
const content = this.content(entry, ran.stdout), at = this.now();
|
|
149
156
|
this.last.set(key, { content, at }); this.failures.delete(key);
|
|
150
157
|
this.shown.set(key, { ...content, readAt: at });
|
|
151
158
|
// A kind's reading is what this machine reports of it: a failed one reports nothing, so the last good objects stay.
|
|
152
159
|
if (entry.panel.kind) await this.report(entry, content.resources, at);
|
|
153
160
|
return this.present(entry, { ...content, readAt: at });
|
|
154
161
|
}
|
|
155
|
-
failure =
|
|
162
|
+
failure = error.message;
|
|
156
163
|
} catch (e) {
|
|
157
164
|
if (!(e instanceof PanelError)) { this.failures.set(key, e.message); throw e; }
|
|
158
165
|
failure = `输出无效:${e.message}`;
|
|
@@ -231,9 +238,11 @@ export class Panels {
|
|
|
231
238
|
const action = panel.actions?.[name] ?? fail('not_found', `面板 ${panel.title} 没有动作 ${name}`);
|
|
232
239
|
const given = actionArgs(args);
|
|
233
240
|
this.acting.set(key, { button }); this.changed(key);
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
241
|
+
const env = await this.env(plugin.id, { CODA_PANEL_ARGS: JSON.stringify(given) });
|
|
242
|
+
const ran = await this.run(action.command, { start, cwd: env.CODA_PLUGIN_PATH, env, input: JSON.stringify(given), timeoutMs: this.actionTimeoutMs, signal: this.closing.signal });
|
|
243
|
+
// What an action prints is what it says, not a result: ending with 0 is all of it.
|
|
244
|
+
const { error } = settle(ran, { answers: false, what: '操作' });
|
|
245
|
+
if (error) fail(error.code, error.message);
|
|
237
246
|
this.acting.delete(key);
|
|
238
247
|
} catch (e) {
|
|
239
248
|
this.acting.set(key, { button, error: e.message }); this.changed(key);
|
|
@@ -258,8 +267,8 @@ export class Panels {
|
|
|
258
267
|
return change;
|
|
259
268
|
}
|
|
260
269
|
// A panel's login from Coda (docs/plugins.md「面板的登录」), one per panel at a time. Signed in, the panel is read anew;
|
|
261
|
-
// its CLI installed, the plugin's setup is run again (docs/plugins.md
|
|
262
|
-
// agents again: what they offer may be readable now.
|
|
270
|
+
// its CLI installed, the plugin's setup is run again (docs/plugins.md「准备运行环境」; `coda.pluginSetup`, asked as this
|
|
271
|
+
// plugin), which done well has Coda read its agents again: what they offer may be readable now.
|
|
263
272
|
login(entry) {
|
|
264
273
|
const { plugin, panel, key } = entry, known = this.logins.get(key);
|
|
265
274
|
const declared = panel.signIn ?? fail('not_found', `${panel.title} 不能从 Coda 登录`);
|
|
@@ -273,14 +282,14 @@ export class Panels {
|
|
|
273
282
|
if (!declared.installed) return true;
|
|
274
283
|
const given = this.envs.get(plugin.id);
|
|
275
284
|
if (!given) return false;
|
|
276
|
-
if (fresh || Date.now() - checkedAt > 2000) { there = spawnSync('/bin/sh', ['-c', declared.installed], { cwd:
|
|
285
|
+
if (fresh || Date.now() - checkedAt > 2000) { there = spawnSync('/bin/sh', ['-c', declared.installed], { cwd: given.CODA_PLUGIN_PATH, env: given, stdio: 'ignore', timeout: 2000 }).status === 0; checkedAt = Date.now(); }
|
|
277
286
|
return there;
|
|
278
287
|
};
|
|
279
288
|
const login = new SignIn({ provider: key, name: panel.title, command: declared.command, installed, install: declared.install ?? null,
|
|
280
289
|
readCode: declared.input ? authorizationLink : deviceCode, input: !!declared.input, note: declared.note ?? null },
|
|
281
|
-
{ env, onChange: () => this.changed(key),
|
|
290
|
+
{ start, env, onChange: () => this.changed(key),
|
|
282
291
|
onSignedIn: () => { this.read(key, { force: true }).catch(() => {}); },
|
|
283
|
-
onInstalled: () => { checkedAt = 0; this.coda.
|
|
292
|
+
onInstalled: () => { checkedAt = 0; this.coda.pluginSetup.retry(plugin.id).catch(() => {}); } });
|
|
284
293
|
login.declared = JSON.stringify(declared);
|
|
285
294
|
login.recheck = () => { checkedAt = 0; };
|
|
286
295
|
this.logins.set(key, login);
|
|
@@ -22,8 +22,6 @@ function durationMs(text) {
|
|
|
22
22
|
export const ITEM_TYPES = ['card', 'meter', 'stat', 'markdown', 'button', 'error'];
|
|
23
23
|
// How many resources a reading lists, and how many values and buttons one has.
|
|
24
24
|
const RESOURCES = 50, VALUES = 8, ACTIONS = 8;
|
|
25
|
-
// What a panel's command may print: past these, the reading fails rather than being cut short.
|
|
26
|
-
export const OUTPUT_LIMIT = 64 * 1024;
|
|
27
25
|
export const ARGS_LIMIT = 4 * 1024;
|
|
28
26
|
const ITEMS = 50, CARD_ITEMS = 20, LABEL = 80, IDENTITY = 200, MARKDOWN = 4000, ERROR = 500, CONFIRM = 200, LINK = 2000;
|
|
29
27
|
const fail = (code, message) => check(false, code, message);
|
|
@@ -132,7 +130,6 @@ function button(raw, where, scope, keys = BUTTON_KEYS) {
|
|
|
132
130
|
// of its plugin's views, which a button may open.
|
|
133
131
|
export function panelItems(output, panel, views = []) {
|
|
134
132
|
const code = 'invalid_panel';
|
|
135
|
-
check(Buffer.byteLength(output) <= OUTPUT_LIMIT, code, `输出超过 ${OUTPUT_LIMIT / 1024} KiB`);
|
|
136
133
|
let value;
|
|
137
134
|
try { value = JSON.parse(output); } catch { return fail(code, '输出不是 JSON'); }
|
|
138
135
|
object(value, '输出', code);
|
|
@@ -149,7 +146,6 @@ export function panelItems(output, panel, views = []) {
|
|
|
149
146
|
// explains: a value is a name and what it reads (docs/plugins.md「资源」). Anything else fails the reading, with where.
|
|
150
147
|
export function resourceItems(output, type, views = []) {
|
|
151
148
|
const code = 'invalid_panel';
|
|
152
|
-
check(Buffer.byteLength(output) <= OUTPUT_LIMIT, code, `输出超过 ${OUTPUT_LIMIT / 1024} KiB`);
|
|
153
149
|
let value;
|
|
154
150
|
try { value = JSON.parse(output); } catch { return fail(code, '输出不是 JSON'); }
|
|
155
151
|
object(value, '输出', code);
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
|
-
import { tmpdir } from 'node:os';
|
|
3
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { lastLine, settle, startPluginCommand } from '../../../../adapters/plugin-command.mjs';
|
|
4
3
|
import { PanelError } from './rules.mjs';
|
|
5
4
|
|
|
6
5
|
const check = (condition, code, message) => { if (!condition) throw new PanelError(code, message); };
|
|
@@ -24,12 +23,6 @@ export function authorizationLink(text) {
|
|
|
24
23
|
const url = text.slice(0, text.lastIndexOf('\n') + 1).replace(ansi, '').match(/https:\/\/\S+/)?.[0];
|
|
25
24
|
try { return url ? { url: new URL(url).href, input: 'authorizationCode' } : null; } catch { return null; }
|
|
26
25
|
}
|
|
27
|
-
const lastLine = output => output.replace(ansi, '').split('\n').map(line => line.trim()).filter(Boolean).at(-1)?.slice(0, 200);
|
|
28
|
-
// A command runs through a shell in its own process group (an installer pipes a download into a shell): ending it ends the
|
|
29
|
-
// whole group, asked (TERM) or, as the module goes and nothing is left to ask again, made to (KILL).
|
|
30
|
-
function end(child, signal = 'SIGTERM') {
|
|
31
|
-
try { process.kill(-child.pid, signal); } catch { child.kill(signal); }
|
|
32
|
-
}
|
|
33
26
|
|
|
34
27
|
// Signing in from Coda through a plugin's panel (docs/plugins.md「面板的登录」, panels.mjs): `login` is the
|
|
35
28
|
// panel's own — its login command, whether what it signs in to is there (`installed()`), the command that installs it, and
|
|
@@ -38,9 +31,12 @@ function end(child, signal = 'SIGTERM') {
|
|
|
38
31
|
// and renews the credentials, which Coda never reads.
|
|
39
32
|
// One login or install of each at a time: any page starting it again sees the one under way, and every page is told as it
|
|
40
33
|
// moves (`onChange`). Neither outlives the module that started it (`close` ends it), so neither is kept for after a restart.
|
|
34
|
+
// Both run as every plugin command does (adapters/plugin-command.mjs, docs/plugins.md「命令的约定」), through `start`, from
|
|
35
|
+
// the plugin's directory: in a process group of their own, cancelled with TERM and made to end past the grace. Neither
|
|
36
|
+
// answers: what they print is read for the link and code, or for why they failed, and ending with 0 is all of it.
|
|
41
37
|
export class SignIn {
|
|
42
|
-
constructor(login, { env = () => process.env, onChange = () => {}, onSignedIn = () => {}, onInstalled = () => {}, timeoutMs = 15 * 60 * 1000, startTimeoutMs = 20000, installTimeoutMs = 10 * 60 * 1000 }) {
|
|
43
|
-
this.login = login; this.env = env; this.onChange = onChange; this.onSignedIn = onSignedIn; this.onInstalled = onInstalled;
|
|
38
|
+
constructor(login, { start, env = () => process.env, onChange = () => {}, onSignedIn = () => {}, onInstalled = () => {}, timeoutMs = 15 * 60 * 1000, startTimeoutMs = 20000, installTimeoutMs = 10 * 60 * 1000 }) {
|
|
39
|
+
this.login = login; this.processStart = start; this.env = env; this.onChange = onChange; this.onSignedIn = onSignedIn; this.onInstalled = onInstalled;
|
|
44
40
|
this.timeoutMs = timeoutMs; this.startTimeoutMs = startTimeoutMs; this.installTimeoutMs = installTimeoutMs;
|
|
45
41
|
this._state = { state: 'idle' }; this.child = null;
|
|
46
42
|
}
|
|
@@ -50,28 +46,25 @@ export class SignIn {
|
|
|
50
46
|
view() { return { provider: this.login.provider, name: this.login.name, installed: this.available,
|
|
51
47
|
...(this.login.note ? { note: this.login.note } : {}), ...this.state }; }
|
|
52
48
|
get busy() { return ['starting', 'waiting', 'installing'].includes(this.state.state); }
|
|
53
|
-
spawn(command,
|
|
54
|
-
|
|
49
|
+
spawn(command, { open = false, tail = false, timeoutMs, onOutput }) {
|
|
50
|
+
const env = this.env();
|
|
51
|
+
return startPluginCommand(command, { start: this.processStart, cwd: env.CODA_PLUGIN_PATH, env, open, tail, timeoutMs, onOutput });
|
|
55
52
|
}
|
|
56
53
|
// Starts the installer and answers at once: clients follow a download as they follow a waiting login.
|
|
57
54
|
install() {
|
|
58
55
|
if (this.busy) return this.view();
|
|
59
56
|
if (this.available) { this.state = { state: 'idle' }; return this.view(); }
|
|
60
57
|
if (!this.login.install) { this.state = { state: 'failed', error: `这台机器没有安装 ${this.login.name},Coda 不能代为安装` }; return this.view(); }
|
|
61
|
-
|
|
58
|
+
// An installer may say much on its way: the last of it is kept, and it is never stopped for that.
|
|
59
|
+
const child = this.spawn(this.login.install, { tail: true, timeoutMs: this.installTimeoutMs });
|
|
62
60
|
this.child = child;
|
|
63
|
-
let output = '';
|
|
64
61
|
this.state = { state: 'installing' };
|
|
65
|
-
|
|
66
|
-
const read = chunk => { output = (output + chunk).slice(-8000); };
|
|
67
|
-
child.stdout.on('data', read); child.stderr.on('data', read);
|
|
68
|
-
child.on('error', error => { output += `\n${error.message}`; });
|
|
69
|
-
child.on('close', code => {
|
|
70
|
-
clearTimeout(due);
|
|
62
|
+
child.done.then(ran => {
|
|
71
63
|
if (this.child === child) {
|
|
72
64
|
this.child = null;
|
|
65
|
+
const { error } = settle(ran, { answers: false, what: '安装' });
|
|
73
66
|
// Asked anew: what was there a moment ago is not what the installer left.
|
|
74
|
-
this.state =
|
|
67
|
+
this.state = !error && this.login.installed(true) ? { state: 'idle' } : { state: 'failed', error: error?.message ?? '安装没有完成' };
|
|
75
68
|
if (this.state.state === 'idle') this.onInstalled();
|
|
76
69
|
}
|
|
77
70
|
});
|
|
@@ -81,31 +74,29 @@ export class SignIn {
|
|
|
81
74
|
start() {
|
|
82
75
|
if (this.busy) return this.ready ?? Promise.resolve(this.view());
|
|
83
76
|
if (!this.available) { this.state = { state: 'failed', error: `这台机器没有安装 ${this.login.name}` }; return Promise.resolve(this.view()); }
|
|
84
|
-
const child = this.spawn(this.login.command, this.login.input);
|
|
85
|
-
child.stdin?.on('error', () => {});
|
|
86
77
|
const attemptId = randomUUID();
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const
|
|
90
|
-
const done = () => { settle(this.view()); if (this.ready === ready) this.ready = null; };
|
|
91
|
-
this.ready = ready;
|
|
92
|
-
this.state = { state: 'starting' };
|
|
93
|
-
const startTimer = setTimeout(() => { if (this.child === child && this.state.state === 'starting') end(child); }, this.startTimeoutMs);
|
|
94
|
-
const due = setTimeout(() => { if (this.child === child) { expired = true; end(child); } }, this.timeoutMs);
|
|
78
|
+
let output = '', silent = false, settleReady;
|
|
79
|
+
const ready = new Promise(resolve => { settleReady = resolve; });
|
|
80
|
+
const done = () => { settleReady(this.view()); if (this.ready === ready) this.ready = null; };
|
|
95
81
|
const read = chunk => {
|
|
96
82
|
output = (output + chunk).slice(-8000);
|
|
97
83
|
const found = this.state.state === 'starting' && this.child === child && this.login.readCode(output);
|
|
98
84
|
if (found) { this.state = { state: 'waiting', ...found, ...(this.login.input ? { attemptId } : {}) }; done(); }
|
|
99
85
|
};
|
|
100
|
-
child.
|
|
101
|
-
child
|
|
102
|
-
|
|
103
|
-
|
|
86
|
+
const child = this.spawn(this.login.command, { open: this.login.input, timeoutMs: this.timeoutMs, onOutput: read });
|
|
87
|
+
this.child = child;
|
|
88
|
+
this.ready = ready;
|
|
89
|
+
this.state = { state: 'starting' };
|
|
90
|
+
const startTimer = setTimeout(() => { if (this.child === child && this.state.state === 'starting') { silent = true; child.stop(); } }, this.startTimeoutMs);
|
|
91
|
+
child.done.then(ran => {
|
|
92
|
+
clearTimeout(startTimer);
|
|
104
93
|
if (this.child !== child) return done(); // Cancelled: the state is already idle.
|
|
105
94
|
this.child = null;
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
else if (
|
|
95
|
+
const { error } = settle(ran, { answers: false, what: '登录' });
|
|
96
|
+
if (!error) { this.state = { state: 'idle' }; this.onSignedIn(); }
|
|
97
|
+
else if (ran.timedOut) this.state = { state: 'expired' };
|
|
98
|
+
// Stopped for printing no link in time, it failed as it says, not as one cancelled.
|
|
99
|
+
else if (this.state.state !== 'idle') this.state = { state: 'failed', error: silent ? lastLine(output) || '登录没有完成' : error.message };
|
|
109
100
|
done();
|
|
110
101
|
});
|
|
111
102
|
return ready;
|
|
@@ -115,17 +106,17 @@ export class SignIn {
|
|
|
115
106
|
'invalid_input', '此登录已结束,请重新登录');
|
|
116
107
|
check(typeof code === 'string' && code.length <= 4096, 'invalid_input', '请粘贴完整的授权码');
|
|
117
108
|
if (!this.state.submitted) {
|
|
118
|
-
this.child.
|
|
109
|
+
this.child.write(`${code.trim()}\n`);
|
|
119
110
|
this.state = { ...this.state, submitted: true };
|
|
120
111
|
}
|
|
121
112
|
return this.view();
|
|
122
113
|
}
|
|
123
114
|
cancel() {
|
|
124
115
|
const child = this.child; this.child = null;
|
|
125
|
-
|
|
116
|
+
child?.stop();
|
|
126
117
|
this.state = { state: 'idle' };
|
|
127
118
|
return this.view();
|
|
128
119
|
}
|
|
129
120
|
// `signal`: KILL as the module goes (the plugin host stopping), when nothing would end one that does not stop when asked.
|
|
130
|
-
close(signal = 'SIGTERM') { if (this.child)
|
|
121
|
+
close(signal = 'SIGTERM') { if (signal === 'SIGKILL') this.child?.kill(); else this.child?.stop(); this.child = null; }
|
|
131
122
|
}
|
package/check/manifest.mjs
CHANGED
|
@@ -88,7 +88,6 @@ export function checkManifest(dir, say) {
|
|
|
88
88
|
const settingCount = Object.keys(plugin.properties).length, names = list => list.map(x => x.name).join('、');
|
|
89
89
|
if (settingCount) say.pass('manifest.settings', `设置 ${settingCount} 项`);
|
|
90
90
|
if (plugin.workflows.length || plugin.capabilities.length) say.pass('manifest.capabilities', `流程 ${plugin.workflows.join('、') || '无'},能力 ${plugin.capabilities.join('、') || '无'}`);
|
|
91
|
-
if (plugin.groups.length) say.pass('manifest.groups', `并发组 ${names(plugin.groups)}`);
|
|
92
91
|
if (plugin.events?.length) say.pass('manifest.events', `发布的事件 ${names(plugin.events)}`);
|
|
93
92
|
if (plugin.commands.length) say.pass('manifest.commands', `会话 PATH 上的命令 ${names(plugin.commands)}`);
|
|
94
93
|
if (plugin.services.length) say.pass('manifest.services', `开启随包服务 ${plugin.services.join('、')}:没有已安装插件开启的服务不运行`);
|
package/check/panel.mjs
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
// Its actions are not run: a button may change things (switch an account, spend a reset), and only a person presses it.
|
|
6
6
|
import { dirname } from 'node:path';
|
|
7
7
|
import { cleared } from './coda/components/plugins/plugin-rules.mjs';
|
|
8
|
-
import {
|
|
8
|
+
import { ENVELOPE } from './coda/adapters/call-limit.mjs';
|
|
9
|
+
import { runPluginCommand } from './coda/adapters/plugin-command.mjs';
|
|
9
10
|
import { Panels } from './coda/resources/plugins/resources/panels/panels.mjs';
|
|
10
|
-
import {
|
|
11
|
+
import { panelItems, resourceItems } from './coda/resources/plugins/resources/panels/rules.mjs';
|
|
11
12
|
import { closing, temporary } from './leftovers.mjs';
|
|
12
13
|
|
|
13
14
|
// The session a process would belong to: the host's belong to none.
|
|
@@ -46,15 +47,15 @@ export async function checkPanel({ panel, checked, say, limit }) {
|
|
|
46
47
|
watch: async (name, told) => { told({ type: 'ADDED', id: offered.id, object: offered }); return { dispose() {} }; } };
|
|
47
48
|
// The command's own result, beside what the page shows of it: whether it ended well and what it printed was not a panel's.
|
|
48
49
|
let result = null;
|
|
49
|
-
const panels = new Panels(coda, { run: async (command, options) => (result = await
|
|
50
|
+
const panels = new Panels(coda, { run: async (command, options) => (result = await runPluginCommand(command, options)), ...(limit ? { readTimeoutMs: limit } : {}) });
|
|
50
51
|
const done = closing(() => panels.close());
|
|
51
52
|
try {
|
|
52
53
|
await panels.start();
|
|
53
54
|
const started = Date.now(), reading = await panels.read(`${plugin.id}/${panel.id}`), took = ((Date.now() - started) / 1000).toFixed(1);
|
|
54
55
|
const kind = panel.format === 'resources' ? '资源' : '面板';
|
|
55
|
-
if (reading.error && result &&
|
|
56
|
+
if (reading.error && result && result.code === 0 && !result.timedOut && !result.overflow) return say.fail('panel.output', `输出不合${kind}格式:资源页显示「${reading.error}」`);
|
|
56
57
|
if (reading.error) {
|
|
57
|
-
const why = !result ? '没有运行' : result.timedOut ? `${panels.readTimeoutMs / 1000} 秒没读完,Coda 停下这次读取` : result.overflow ? `标准输出超过 ${
|
|
58
|
+
const why = !result ? '没有运行' : result.timedOut ? `${panels.readTimeoutMs / 1000} 秒没读完,Coda 停下这次读取` : result.overflow ? `标准输出超过 ${ENVELOPE / 1024 / 1024} MiB,Coda 停下这次读取`
|
|
58
59
|
: result.error ? '命令起不来' : `退出码 ${result.code}`;
|
|
59
60
|
return say.fail('panel.read', `读取没成功(${why}):资源页显示「${reading.error}」`);
|
|
60
61
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coda-console/plugin-check",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.22",
|
|
4
4
|
"description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源类型(与旧的面板)。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@0dep/piso": "5.2.0",
|
|
26
26
|
"@agentclientprotocol/sdk": "2.6.0",
|
|
27
|
-
"@coda-console/protocol": "6.
|
|
27
|
+
"@coda-console/protocol": "6.13.0",
|
|
28
28
|
"ajv": "8.20.0",
|
|
29
29
|
"yaml": "2.9.1"
|
|
30
30
|
},
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { admissionFeatures } from '../domain/resource-admission.mjs';
|
|
2
|
-
|
|
3
|
-
// The module's local ledger API, exported unchanged to plugin-check.
|
|
4
|
-
export function admissionAPI(call, handlers = new Map()) {
|
|
5
|
-
return {
|
|
6
|
-
handle(operation, fn) {
|
|
7
|
-
if (!['lend', 'return'].includes(operation) || typeof fn !== 'function') throw new TypeError('resources.handle(lend|return, fn)');
|
|
8
|
-
if (handlers.has(operation)) throw new TypeError(`资源钩子已登记:${operation}`);
|
|
9
|
-
handlers.set(operation, fn);
|
|
10
|
-
return { dispose: () => handlers.delete(operation) };
|
|
11
|
-
},
|
|
12
|
-
declareEntities: entities => call('declareEntities', [entities]),
|
|
13
|
-
declareLinks: links => call('declareLinks', [links]),
|
|
14
|
-
links: entity => call('links', [entity]),
|
|
15
|
-
features: admissionFeatures,
|
|
16
|
-
declareGroups: groups => call('declareGroups', [groups]),
|
|
17
|
-
groupOwner: name => call('groupOwner', [name]),
|
|
18
|
-
acquire: request => call('acquire', [request]),
|
|
19
|
-
release: lease => call('release', [lease]),
|
|
20
|
-
list: () => call('list', []),
|
|
21
|
-
};
|
|
22
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
// Holder-owned envelope fields. Sequence orders originals across kinds on one holder; time is only for display.
|
|
2
|
-
import { requireCondition as check } from '../../domain/errors.mjs';
|
|
3
|
-
|
|
4
|
-
export const creationProperties = {
|
|
5
|
-
provider: { type: 'string' },
|
|
6
|
-
createdAt: { type: 'string' },
|
|
7
|
-
creationSequence: { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
|
|
8
|
-
};
|
|
9
|
-
|
|
10
|
-
export function creationOf(object) {
|
|
11
|
-
const { createdAt, creationSequence } = object;
|
|
12
|
-
check(typeof createdAt === 'string' && Number.isFinite(Date.parse(createdAt))
|
|
13
|
-
&& Number.isSafeInteger(creationSequence) && creationSequence > 0, 'invalid_input', '协议对象缺少有效的创建信息');
|
|
14
|
-
return { createdAt, creationSequence };
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function checkCreationReadOnly(object) {
|
|
18
|
-
check(Object.keys(creationProperties).every(key => !Object.hasOwn(object, key)), 'invalid_input', '创建信息由持有方写入,只读');
|
|
19
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { requireCondition as check } from './errors.mjs';
|
|
2
|
-
|
|
3
|
-
export const admissionFeatures = Object.freeze({ multiResource: false, multiUnit: false, exclusive: true });
|
|
4
|
-
|
|
5
|
-
export function admissionRequest(request) {
|
|
6
|
-
check(request && typeof request === 'object' && !Array.isArray(request) &&
|
|
7
|
-
Object.keys(request).every(key => ['requestId', 'group', 'resources', 'exclusive'].includes(key)), 'invalid_input', '无效的资源申请');
|
|
8
|
-
const { requestId, group, resources, exclusive = false } = request;
|
|
9
|
-
check(typeof requestId === 'string' && requestId.length > 0 && requestId.length <= 500, 'invalid_input', 'requestId 须为 1–500 字的稳定申请标识');
|
|
10
|
-
check(typeof group === 'string' && group.length > 0 && group.length <= 100, 'invalid_input', 'group 须为本机组名');
|
|
11
|
-
check(resources && Object.keys(resources).length === 1 && resources.slots === 1 && !Array.isArray(resources),
|
|
12
|
-
'invalid_input', '只支持 resources: { slots: 1 },不支持多资源或多单位');
|
|
13
|
-
check(typeof exclusive === 'boolean', 'invalid_input', 'exclusive 须为 boolean');
|
|
14
|
-
return { requestId, group, exclusive };
|
|
15
|
-
}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
// A panel's command run once to its end (a reading, an action): `sh -c` in its own process group, its standard output kept
|
|
2
|
-
// apart from what it says on standard error, both bounded. Past its deadline the group is asked to stop, and made to two
|
|
3
|
-
// seconds later; once `signal` aborts (the module closing) it is made to at once.
|
|
4
|
-
import { spawn } from 'node:child_process';
|
|
5
|
-
import { tmpdir } from 'node:os';
|
|
6
|
-
|
|
7
|
-
const ansi = /\x1b\[[0-9;]*[A-Za-z]/g;
|
|
8
|
-
// The last thing a failed command said, for the one line the user sees.
|
|
9
|
-
export const lastLine = text => text.replace(ansi, '').split('\n').map(line => line.trim()).filter(Boolean).at(-1)?.slice(0, 200) ?? '';
|
|
10
|
-
|
|
11
|
-
export function runCommand(command, { env, timeoutMs, signal: aborted, maxBytes = 64 * 1024 }) {
|
|
12
|
-
return new Promise(resolve => {
|
|
13
|
-
const child = spawn('/bin/sh', ['-c', command], { cwd: tmpdir(), env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
14
|
-
const out = [], err = [];
|
|
15
|
-
let sizes = [0, 0], overflow = false, timedOut = false, finished = false, hard = null;
|
|
16
|
-
const signal = name => { try { process.kill(-child.pid, name); } catch {} };
|
|
17
|
-
const stop = () => { signal('SIGTERM'); hard = setTimeout(() => signal('SIGKILL'), 2000); };
|
|
18
|
-
const due = setTimeout(() => { timedOut = true; stop(); }, timeoutMs);
|
|
19
|
-
const abort = () => { if (!finished) signal('SIGKILL'); };
|
|
20
|
-
aborted?.addEventListener('abort', abort, { once: true });
|
|
21
|
-
const keep = (chunks, i) => chunk => {
|
|
22
|
-
if (sizes[i] + chunk.length > maxBytes) { if (i === 0 && !overflow) { overflow = true; stop(); } return; }
|
|
23
|
-
sizes[i] += chunk.length; chunks.push(chunk);
|
|
24
|
-
};
|
|
25
|
-
child.stdout.on('data', keep(out, 0));
|
|
26
|
-
child.stderr.on('data', keep(err, 1));
|
|
27
|
-
const finish = (code, error) => {
|
|
28
|
-
if (finished) return;
|
|
29
|
-
finished = true; clearTimeout(due); clearTimeout(hard); aborted?.removeEventListener('abort', abort);
|
|
30
|
-
// Whatever it left behind in its group goes with it.
|
|
31
|
-
if (child.pid) signal('SIGKILL');
|
|
32
|
-
resolve({ code, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8'), timedOut, overflow, ...(error ? { error } : {}) });
|
|
33
|
-
};
|
|
34
|
-
child.on('error', error => finish(null, error.message));
|
|
35
|
-
child.on('close', code => finish(code));
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
// A command ended well: by itself, with 0. One stopped for its deadline or its output may still say 0 on the way out.
|
|
39
|
-
export const ended = result => result.code === 0 && !result.timedOut && !result.overflow;
|
|
40
|
-
// Why a command did not end well, in one line.
|
|
41
|
-
export function outcome(result, what) {
|
|
42
|
-
if (result.timedOut) return `${what}超时`;
|
|
43
|
-
if (result.overflow) return '输出过长';
|
|
44
|
-
if (result.error) return `${what}没有开始:${result.error}`;
|
|
45
|
-
return lastLine(result.stderr) || lastLine(result.stdout) || `${what}没有完成(退出码 ${result.code ?? '无'})`;
|
|
46
|
-
}
|
package/check/command.mjs
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
// A panel's command run once to its end, as Coda's panels module ran it before it took `runPluginCommand`
|
|
2
|
-
// (check/coda/resources/plugins/resources/panels/command.mjs, which a sync drops): `sh -c` in its own process group, its
|
|
3
|
-
// standard output kept apart from what it says on standard error, both bounded. Kept here so the checker runs with the
|
|
4
|
-
// panels module of either version: `start`, `cwd` and `input`, which the newer one passes, are ignored, and the command's
|
|
5
|
-
// standard input stays closed.
|
|
6
|
-
import { spawn } from 'node:child_process';
|
|
7
|
-
import { tmpdir } from 'node:os';
|
|
8
|
-
|
|
9
|
-
const ansi = /\x1b\[[0-9;]*[A-Za-z]/g;
|
|
10
|
-
// The last thing a failed command said, for the one line the user sees.
|
|
11
|
-
export const lastLine = text => text.replace(ansi, '').split('\n').map(line => line.trim()).filter(Boolean).at(-1)?.slice(0, 200) ?? '';
|
|
12
|
-
|
|
13
|
-
export function runCommand(command, { env, timeoutMs, signal: aborted, maxBytes = 64 * 1024 }) {
|
|
14
|
-
return new Promise(resolve => {
|
|
15
|
-
const child = spawn('/bin/sh', ['-c', command], { cwd: tmpdir(), env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
16
|
-
const out = [], err = [];
|
|
17
|
-
let sizes = [0, 0], overflow = false, timedOut = false, finished = false, hard = null;
|
|
18
|
-
const signal = name => { try { process.kill(-child.pid, name); } catch {} };
|
|
19
|
-
const stop = () => { signal('SIGTERM'); hard = setTimeout(() => signal('SIGKILL'), 2000); };
|
|
20
|
-
const due = setTimeout(() => { timedOut = true; stop(); }, timeoutMs);
|
|
21
|
-
const abort = () => { if (!finished) signal('SIGKILL'); };
|
|
22
|
-
aborted?.addEventListener('abort', abort, { once: true });
|
|
23
|
-
const keep = (chunks, i) => chunk => {
|
|
24
|
-
if (sizes[i] + chunk.length > maxBytes) { if (i === 0 && !overflow) { overflow = true; stop(); } return; }
|
|
25
|
-
sizes[i] += chunk.length; chunks.push(chunk);
|
|
26
|
-
};
|
|
27
|
-
child.stdout.on('data', keep(out, 0));
|
|
28
|
-
child.stderr.on('data', keep(err, 1));
|
|
29
|
-
const finish = (code, error) => {
|
|
30
|
-
if (finished) return;
|
|
31
|
-
finished = true; clearTimeout(due); clearTimeout(hard); aborted?.removeEventListener('abort', abort);
|
|
32
|
-
// Whatever it left behind in its group goes with it.
|
|
33
|
-
if (child.pid) signal('SIGKILL');
|
|
34
|
-
resolve({ code, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8'), timedOut, overflow, ...(error ? { error } : {}) });
|
|
35
|
-
};
|
|
36
|
-
child.on('error', error => finish(null, error.message));
|
|
37
|
-
child.on('close', code => finish(code));
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
// A command ended well: by itself, with 0. One stopped for its deadline or its output may still say 0 on the way out.
|
|
41
|
-
export const ended = result => result.code === 0 && !result.timedOut && !result.overflow;
|
|
42
|
-
// Why a command did not end well, in one line.
|
|
43
|
-
export function outcome(result, what) {
|
|
44
|
-
if (result.timedOut) return `${what}超时`;
|
|
45
|
-
if (result.overflow) return '输出过长';
|
|
46
|
-
if (result.error) return `${what}没有开始:${result.error}`;
|
|
47
|
-
return lastLine(result.stderr) || lastLine(result.stdout) || `${what}没有完成(退出码 ${result.code ?? '无'})`;
|
|
48
|
-
}
|