@coda-console/plugin-check 0.5.32 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,7 +16,7 @@ import { settings as agentSettings } from '../session-config/commands.mjs';
16
16
  import { requireCondition as check, ContractError } from '../../domain/errors.mjs';
17
17
  import { isDuration } from '../../domain/duration.mjs';
18
18
  import { AGENT_ID } from '../../domain/values.mjs';
19
- import { agentDeclarations } from './agent-plugins.mjs';
19
+ import { agentDeclarations, iconFiles } from './agent-plugins.mjs';
20
20
  import { checkCatalog, extensionsFor } from './plugin-extensions.mjs';
21
21
  import { manifestProblem, TYPES } from '@coda-console/protocol/validate';
22
22
  import { claims, COMMIT, INTEGRITY, NPM_VERSION, npmPluginId, repoAddress, sourcePath } from './plugin-source-rules.mjs';
@@ -95,6 +95,18 @@ function parametersOf(value, where) {
95
95
  }));
96
96
  return { properties, ...(value.required?.length ? { required: [...value.required] } : {}) };
97
97
  }
98
+ // Its icon (docs/plugins.md「插件页」): a symbol on a system colour as written, or its PDFs read as an agent's are; one that
99
+ // draws none and brings one agent is drawn as that agent. Nothing else: the clients draw its category's.
100
+ export function pluginIcon(declared, agents, dir) {
101
+ if (declared?.symbol) return { symbol: declared.symbol, color: declared.color };
102
+ if (declared) return iconFiles(dir, declared);
103
+ return agents.length === 1 ? agents[0].icon : null;
104
+ }
105
+ // The README a plugin's page shows (docs/plugins.md「插件页」), as npm and GitHub find it in its directory; null without one.
106
+ const README = /^readme(\.md|\.markdown)?$/i;
107
+ export function readmeFile(dir) {
108
+ try { const name = readdirSync(dir).filter(name => README.test(name)).sort()[0]; return name ? join(dir, name) : null; } catch { return null; }
109
+ }
98
110
  // The category it is listed under (docs/plugins.md「商店」): the first of its manifest's `categories`, as VS Code's are
99
111
  // written; empty when it names none.
100
112
  export const manifestCategory = manifest => Array.isArray(manifest?.categories) && typeof manifest.categories[0] === 'string' ? manifest.categories[0].trim().slice(0, 32) : '';
@@ -122,8 +134,10 @@ export function readPlugin(dir, source) {
122
134
  const displayName = typeof manifest.displayName === 'string' ? manifest.displayName : id;
123
135
  // What it writes under keys of `contributes` that are none of Coda's: for the points other plugins declare (checkCatalog).
124
136
  const offers = Object.fromEntries(Object.entries(contributes).filter(([key]) => !TYPES.includes(key)));
137
+ const agents = agentDeclarations(contributes.agents, dir), icon = pluginIcon(manifest.icon, agents, dir);
125
138
  return { id, displayName, description: typeof manifest.description === 'string' ? manifest.description : '', version: String(manifest.version ?? ''),
126
- category: manifestCategory(manifest), source, dir, title: typeof configuration.title === 'string' ? configuration.title : displayName, properties,
139
+ category: manifestCategory(manifest), ...(icon ? { icon } : {}), ...(readmeFile(dir) ? { readme: true } : {}),
140
+ source, dir, title: typeof configuration.title === 'string' ? configuration.title : displayName, properties,
127
141
  ...(manifest.coda !== undefined ? { coda: manifest.coda } : {}),
128
142
  ...(manifest.main ? { main: posix.normalize(manifest.main) } : {}), ...(activation.includes('onStartupFinished') ? { startup: true } : {}),
129
143
  ...(required.length ? { required: [...required] } : {}), workflows: files('.coda/workflows'),
@@ -139,7 +153,7 @@ export function readPlugin(dir, source) {
139
153
  ...(v.checkout ? { checkout: v.checkout } : {}), ...(v.frame ? { frame: v.frame } : {}) })),
140
154
  ...(contributes.composerModes?.length ? { composerModes: composerModes(contributes.composerModes) } : {}),
141
155
  ...(Object.keys(offers).length ? { offers } : {}),
142
- agents: agentDeclarations(contributes.agents, dir),
156
+ agents,
143
157
  dependencies: [...dependencies], extensionPoints: extensionPoints(contributes.extensionPoints, dir),
144
158
  extensions: Object.entries(contributes.extensions ?? {}).map(([key, value]) => { const [plugin, point] = key.split('/'); return { plugin, point, command: value.command }; }),
145
159
  ...(contributes.instructions ? { instructions: contributes.instructions.trim() } : {}), ...(contributes.setup ? { setup: { command: contributes.setup.command } } : {}),
@@ -1,4 +1,5 @@
1
- // Read-only Skill documents from the same plugin copy the catalog gives agents (docs/plugins.md「Skills」).
1
+ // Read-only documents of the same plugin copy the catalog gives agents: its Skills (docs/plugins.md「Skills」) and its README
2
+ // (docs/plugins.md「插件页」).
2
3
  import { readFileSync, realpathSync, statSync } from 'node:fs';
3
4
  import { isAbsolute, join, relative } from 'node:path';
4
5
  import { parse } from 'yaml';
@@ -33,3 +34,21 @@ export function readSkillDocument(plugin, name) {
33
34
  throw error;
34
35
  }
35
36
  }
37
+
38
+ // A plugin's README as its page shows it, from its own directory (never through a link out of it): empty without one.
39
+ export function readPluginReadme(plugin, file) {
40
+ const said = { plugin: plugin.id, displayName: plugin.displayName, version: plugin.version };
41
+ if (!file) return { ...said, markdown: '' };
42
+ try {
43
+ const path = realpathSync(file), within = relative(realpathSync(plugin.dir), path);
44
+ check(within && within !== '..' && !within.startsWith('../') && !isAbsolute(within), 'not_found', 'README 不在插件目录里');
45
+ const found = statSync(path);
46
+ check(found.isFile() && found.size <= README_LIMIT, 'invalid_plugin', 'README 须为不超过 1 MiB 的文本');
47
+ return { ...said, markdown: readFileSync(path, 'utf8') };
48
+ } catch (error) {
49
+ if (['ENOENT', 'ENOTDIR'].includes(error.code)) return { ...said, markdown: '' };
50
+ check(!['EACCES', 'EPERM'].includes(error.code), 'invalid_plugin', '无法读取这个插件的 README。');
51
+ throw error;
52
+ }
53
+ }
54
+ export const README_LIMIT = 1024 * 1024;
@@ -1,9 +1,9 @@
1
1
  {
2
- "commit": "b133b738adb57f44665c89f5a8ed8b1ebc84920c",
2
+ "commit": "d75bc18652da406a03a9d5665fa1f05034837206",
3
3
  "packages": {
4
4
  "@0dep/piso": "5.2.0",
5
5
  "@agentclientprotocol/sdk": "1.4.0",
6
- "@coda-console/protocol": "2.4.0",
6
+ "@coda-console/protocol": "2.5.0",
7
7
  "ajv": "8.20.0",
8
8
  "yaml": "2.9.1"
9
9
  },
@@ -14,11 +14,11 @@
14
14
  "check/coda/adapters/provider-api.mjs": "8a2b5d7b4a3766f9e28270bd355f4b4081d3069b4cedad120671995bea160253",
15
15
  "check/coda/adapters/admission-api.mjs": "461b5a8a1ad73d7afed5db308813d02324e29c643b8e773ad127d4bdb00fb524",
16
16
  "check/coda/components/composers/schemas.mjs": "282052bb58bdbf612a55b275456c6fea04d979136cf8a3700a4641380e501b3f",
17
- "check/coda/components/plugins/agent-plugins.mjs": "d117702f83c988aa89c2e5ae26aafd6ae3e8ba0829adaeedf9e8640f5f8282be",
17
+ "check/coda/components/plugins/agent-plugins.mjs": "7ca5c0303c6fedffa7b0bcd90546273356ebc410b101f203f2ee8e7503063403",
18
18
  "check/coda/components/plugins/plugin-extensions.mjs": "4d7963185195ba6d21a4e49a66987613d5892210b1eb1dc02cffb7b816407776",
19
- "check/coda/components/plugins/plugin-rules.mjs": "e0fd9c1dade361667337a4c680e399f02ddd557af79e476bcecd91daebcf81d5",
19
+ "check/coda/components/plugins/plugin-rules.mjs": "6a0e534aefb2256c4e88486a4727dc7ad88cb29bec755a854d5bf2f4bf773a24",
20
20
  "check/coda/components/plugins/plugin-source-rules.mjs": "d894d55a3272df5ef3b108b68820c64aefdf6b69346404b58954f2a3503cb4a5",
21
- "check/coda/components/plugins/skill-document.mjs": "c5b5e815c42cd836572f7b60e22a46af6ac607fd9df0170fa36f955825636ce6",
21
+ "check/coda/components/plugins/skill-document.mjs": "153ad3c096c7c9b7774bcf7dcc0ba603c962ee1ac8697c8a71e3f2c9ba9c92e6",
22
22
  "check/coda/components/prompt-recovery/prompt-recovery.mjs": "f43f21d24c19a58113d3304f9248225b12080ab00ed15eab74bf7b94642732de",
23
23
  "check/coda/components/session-config/commands.mjs": "2e4c80b0280db32fe220fa360f18a8e66f12e6a16e3e7bce545c762c9c6340e1",
24
24
  "check/coda/components/workflows/executor-labels.mjs": "dceca6ae60c0a4f3c3cc72a6c84f1489831790774c93caab96e4ddb493bc89e1",
@@ -30,9 +30,9 @@
30
30
  "check/coda/domain/values.mjs": "01cc72b8d9c09e3fe16c93ec332ca01148bba859b1c672586d9d07444d7816c4",
31
31
  "check/coda/kernel/agent-failures.mjs": "cbc215e2403d86f0acc765c2077197e0b529fc01e213db465c388361238ea8ce",
32
32
  "check/coda/resources/plugins/resources/panels/command.mjs": "606f28bf87f87dded9df2db892bc7624c770d795ffab88f2409998346920ae42",
33
- "check/coda/resources/plugins/resources/panels/panels.mjs": "9e25cfbc16ed9f68101fc7bfc34b8056c13a29d2368c5561e65e333233eb921e",
34
- "check/coda/resources/plugins/resources/panels/rules.mjs": "8418ed83b796f18047c154d8dea8dca7d98244af8ddfe3ddf188520c59324ee8",
33
+ "check/coda/resources/plugins/resources/panels/panels.mjs": "4862dccd91c29db76caf1033ffeab743c7943befaca7406a56467c470b90a1b8",
34
+ "check/coda/resources/plugins/resources/panels/rules.mjs": "8de0c45df3b252d49a5a012696db95c9c46f29262213b2f846928cd512dd7213",
35
35
  "check/coda/resources/plugins/resources/panels/sign-in.mjs": "1271a24e33b1b882a1fb9bee03b8e240db8b9bee1b5208f0e1c84499cfb1be7e",
36
- "check/coda/builtin.json": "837c8cc80b5313f41c0e452da6355183b7e9070eb44e00a21e30cf59eff38e9e"
36
+ "check/coda/builtin.json": "5a597073d8188733dda85977c4ba7ed83fe011b9968146e4b567b3b7219435ad"
37
37
  }
38
38
  }
@@ -1,17 +1,19 @@
1
- // The panels installed plugins bring to this machine's resources page (docs/plugins.md「面板」), read and acted on here, in
2
- // the resources plugin's module: what each plugin declares comes from Coda's collection of the installed plugins
1
+ // The resource types installed plugins bring to this machine's resources page (docs/plugins.md「资源」), read and acted on
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. A panel is read only when a page asks (opening it, refreshing), never in
5
- // the background, and no reading is kept on disk. What every panel gets from here and not from its plugin: one reading
6
- // at a time (a second ask joins it), the last good reading shown again within the panel's `maxAge` and listed with the
7
- // panel, and on failure the last good one kept and marked as such. The machine keeps the panels it hides, in this
8
- // plugin's state; their order is their plugins' (docs/resources-page.md「顺序」).
4
+ // as Coda gives every process of the plugin's. A plugin declaring `resources` has those; one still declaring the panels
5
+ // before them has its panels, read as they were (`format`), for the page to take as resources (docs/plugins.md「旧的面板」).
6
+ // A type is read only when a page asks (opening it, refreshing), never in the background, and no reading is kept on disk.
7
+ // What every type gets from here and not from its plugin: one reading at a time (a second ask joins it), the last good
8
+ // reading shown again within the type's `maxAge` and listed with it, and on failure the last good one kept and marked as
9
+ // such. The machine keeps which it shows and which not, in this plugin's state; their order is their plugins'
10
+ // (docs/resources-page.md「顺序」). Inside, a type is still called a panel, as the page's view and its messages are.
9
11
  import { spawnSync } from 'node:child_process';
10
12
  import { readFileSync, writeFileSync, renameSync } from 'node:fs';
11
13
  import { tmpdir } from 'node:os';
12
14
  import { join } from 'node:path';
13
15
  import { runCommand, ended, outcome } from './command.mjs';
14
- import { PanelError, panelDeclarations, panelItems, actionArgs, shownItems, displayOptions, keepMissingMetrics } from './rules.mjs';
16
+ import { PanelError, panelDeclarations, panelItems, resourceItems, actionArgs, shownItems, displayOptions, keepMissingMetrics } from './rules.mjs';
15
17
  import { SignIn, authorizationLink, deviceCode } from './sign-in.mjs';
16
18
 
17
19
  const fail = (code, message) => { throw new PanelError(code, message); };
@@ -31,10 +33,10 @@ export class Panels {
31
33
  // Nothing is told before the plugins' environments are there (`ready`): what a login says of whether its program is
32
34
  // installed is checked with its plugin's own.
33
35
  changed(key = null) { if (this.ready) for (const fn of this.listeners) try { fn(key); } catch {} }
34
- // Once: the installed plugins watched, what this machine hides, and the environment of each plugin whose panels sign in.
36
+ // Once: the installed plugins watched, what this machine shows and hides, and the environment of each plugin whose panels sign in.
35
37
  start() {
36
38
  this.started ??= (async () => {
37
- this.hidden = this.readHidden();
39
+ this.choices = this.readHidden();
38
40
  const watched = await this.coda.watch('plugins', ({ type, id, object }) => {
39
41
  if (type === 'DELETED') this.plugins.delete(id); else this.plugins.set(id, object);
40
42
  // Another version (another directory, another environment): what was checked with the last is checked again.
@@ -51,20 +53,29 @@ export class Panels {
51
53
  })();
52
54
  return this.started;
53
55
  }
54
- // What the machine hides, as it was kept: none when nothing is, or what is cannot be read.
56
+ // What the machine was told to hide or show, by panel: none when nothing is, or what is cannot be read. Kept before as
57
+ // the list of those hidden.
55
58
  readHidden() {
56
- try { return new Set(JSON.parse(readFileSync(this.file, 'utf8'))); } catch { return new Set(); }
59
+ try {
60
+ const kept = JSON.parse(readFileSync(this.file, 'utf8'));
61
+ return Array.isArray(kept) ? Object.fromEntries(kept.map(key => [key, true])) : kept && typeof kept === 'object' ? kept : {};
62
+ } catch { return {}; }
57
63
  }
58
- keepHidden(hidden) {
64
+ keepHidden(choices) {
59
65
  const next = `${this.file}.next`;
60
- writeFileSync(next, JSON.stringify([...hidden].sort()));
66
+ writeFileSync(next, JSON.stringify(Object.fromEntries(Object.entries(choices).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
61
67
  renameSync(next, this.file);
62
68
  }
63
- // The installed plugins' panels, by plugin id, each plugin's in the order it declares them. A project disabling a plugin
64
- // does not take its panels away: the page is the machine's, not a project's.
69
+ // Whether the machine hides it: as it was told, else as its type says (`hidden`, shown only once chosen).
70
+ hiddenOf({ key, panel }) { return this.choices[key] ?? !!panel.hidden; }
71
+ // The installed plugins' types, by plugin id, each plugin's in the order it declares them: its resource types, or the
72
+ // panels of one that declares none. A project disabling a plugin does not take them away: the page is the machine's,
73
+ // not a project's.
65
74
  installed() {
66
- return [...this.plugins.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).flatMap(plugin =>
67
- panelDeclarations(plugin.contributes?.panels).map(panel => ({ plugin, panel, key: `${plugin.id}/${panel.id}` })));
75
+ return [...this.plugins.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).flatMap(plugin => {
76
+ const format = plugin.contributes?.resources ? 'resources' : 'panels';
77
+ return panelDeclarations(plugin.contributes?.[format]).map(panel => ({ plugin, panel, key: `${plugin.id}/${panel.id}`, format }));
78
+ });
68
79
  }
69
80
  find(key) {
70
81
  return this.installed().find(e => e.key === key) ?? fail('not_found', `没有面板 ${key}`);
@@ -76,14 +87,15 @@ export class Panels {
76
87
  }
77
88
  // What a page shows of a panel: what it is, whether the machine hides it, what was last read and how that stands now.
78
89
  view(entry, index) {
79
- const { plugin, panel, key } = entry, shown = this.shown.get(key);
80
- return { plugin: plugin.id, pluginName: plugin.name, panel: panel.id, title: panel.title, version: plugin.version ?? '', source: plugin.source ?? { kind: 'builtin' },
90
+ const { plugin, panel, key, format } = entry, shown = this.shown.get(key), acting = this.acting.get(key);
91
+ return { plugin: plugin.id, pluginName: plugin.name, panel: panel.id, title: panel.title, format, version: plugin.version ?? '', source: plugin.source ?? { kind: 'builtin' },
81
92
  actions: Object.fromEntries(Object.entries(panel.actions ?? {}).map(([name, a]) => [name, a.confirm ? { confirm: a.confirm } : {}])),
82
- configurable: !!panel.displaySetting, signsIn: !!panel.signIn, hidden: this.hidden.has(key), index,
93
+ configurable: !!panel.displaySetting, signsIn: !!panel.signIn, hidden: this.hiddenOf(entry), index,
83
94
  signIn: panel.signIn ? this.login(entry).view() : null,
84
95
  reading: shown ? this.present(entry, shown) : null,
85
96
  busy: this.reading.has(key), failure: this.failures.get(key) ?? null,
86
- acting: this.acting.get(key)?.button ?? null, actionError: this.acting.get(key)?.error ?? null };
97
+ // The action under way, by its button; or why the last one did not go through, with the button it was.
98
+ acting: acting && !acting.error ? acting.button : null, actionError: acting?.error ?? null, failedButton: acting?.error ? acting.button : null };
87
99
  }
88
100
  list() { return this.installed().map((entry, index) => [entry.key, this.view(entry, index)]); }
89
101
  // One panel's, as `list` has it; none for one no longer installed.
@@ -106,13 +118,14 @@ export class Panels {
106
118
  const values = this.settingsOf(plugin.id)[panel.displaySetting] ?? {};
107
119
  return { ...reading, items: shownItems(reading.items, values), display: { setting: panel.displaySetting, options: displayOptions(reading.items, values) } };
108
120
  }
109
- // `{ items, readAt }`, or with `error` when this reading failed: then the last good items with `stale`, or none.
121
+ // `{ resources, readAt }` (a panel's `{ items, readAt }`), or with `error` when this reading failed: then the last good
122
+ // one with `stale`, or none.
110
123
  read(key, { force = false } = {}) {
111
124
  const entry = this.find(key);
112
125
  const pending = this.reading.get(key);
113
126
  if (pending) return pending;
114
127
  const last = this.last.get(key);
115
- if (!force && last && entry.panel.maxAgeMs && this.now() - last.at < entry.panel.maxAgeMs && !this.shown.get(key)?.error) return Promise.resolve(this.present(entry, { items: last.items, readAt: last.at }));
128
+ if (!force && last && entry.panel.maxAgeMs && this.now() - last.at < entry.panel.maxAgeMs && !this.shown.get(key)?.error) return Promise.resolve(this.present(entry, { ...last.content, readAt: last.at }));
116
129
  const reading = this.fetch(entry).finally(() => { this.reading.delete(key); this.changed(key); });
117
130
  this.reading.set(key, reading);
118
131
  this.changed(key);
@@ -124,11 +137,10 @@ export class Panels {
124
137
  try {
125
138
  const result = await this.run(panel.command, { env: await this.env(plugin.id), timeoutMs: this.readTimeoutMs, signal: this.closing.signal });
126
139
  if (ended(result)) {
127
- const parsed = panelItems(result.stdout, panel, plugin.views ?? []), at = this.now();
128
- const items = panel.displaySetting ? keepMissingMetrics(parsed, this.last.get(key)?.items ?? []) : parsed;
129
- this.last.set(key, { items, at }); this.failures.delete(key);
130
- this.shown.set(key, { items, readAt: at });
131
- return this.present(entry, { items, readAt: at });
140
+ const content = this.content(entry, result.stdout), at = this.now();
141
+ this.last.set(key, { content, at }); this.failures.delete(key);
142
+ this.shown.set(key, { ...content, readAt: at });
143
+ return this.present(entry, { ...content, readAt: at });
132
144
  }
133
145
  failure = outcome(result, '读取');
134
146
  } catch (e) {
@@ -136,15 +148,21 @@ export class Panels {
136
148
  failure = `输出无效:${e.message}`;
137
149
  }
138
150
  const last = this.last.get(key);
139
- const reading = last ? { items: last.items, readAt: last.at, stale: true, error: failure } : { items: [], error: failure };
151
+ const reading = last ? { ...last.content, readAt: last.at, stale: true, error: failure } : { [entry.format === 'resources' ? 'resources' : 'items']: [], error: failure };
140
152
  this.shown.set(key, reading);
141
153
  return this.present(entry, reading);
142
154
  }
155
+ // What a command printed, as its format has it: resources, or a panel's items (those it chooses among keeping their places).
156
+ content({ plugin, panel, key, format }, output) {
157
+ if (format === 'resources') return { resources: resourceItems(output, panel, plugin.views ?? []) };
158
+ const items = panelItems(output, panel, plugin.views ?? []);
159
+ return { items: panel.displaySetting ? keepMissingMetrics(items, this.last.get(key)?.content.items ?? []) : items };
160
+ }
143
161
  // Runs one of a panel's actions with what its button sent, then reads the panel again. One action of a panel at a time;
144
162
  // one under way goes on to its end even when whoever asked has gone.
145
163
  async act(key, name, args, button = name) {
146
- const entry = this.find(key), { plugin, panel } = entry;
147
- if (this.acting.get(key)?.button) fail('panel_busy', `${panel.title} 正在进行另一项操作`);
164
+ const entry = this.find(key), { plugin, panel } = entry, now = this.acting.get(key);
165
+ if (now && !now.error) fail('panel_busy', `${panel.title} 正在进行另一项操作`);
148
166
  // What went wrong is said under the panel, whatever it was.
149
167
  try {
150
168
  const action = panel.actions?.[name] ?? fail('not_found', `面板 ${panel.title} 没有动作 ${name}`);
@@ -155,20 +173,19 @@ export class Panels {
155
173
  if (!ended(result)) fail('action_failed', outcome(result, '操作'));
156
174
  this.acting.delete(key);
157
175
  } catch (e) {
158
- this.acting.set(key, { error: e.message }); this.changed(key);
176
+ this.acting.set(key, { button, error: e.message }); this.changed(key);
159
177
  throw e;
160
178
  }
161
179
  // A reading that began before the action ended may not show what it did.
162
180
  await this.reading.get(key);
163
181
  return this.read(key, { force: true });
164
182
  }
165
- // One panel hidden or shown again on this machine, the others as they were: one change at a time.
183
+ // One type hidden or shown on this machine, the others as they were: one change at a time.
166
184
  hide(key, hidden) {
167
185
  const change = this.hides.then(() => {
168
- const next = new Set(this.hidden);
169
- if (hidden) next.add(key); else next.delete(key);
186
+ const next = { ...this.choices, [key]: !!hidden };
170
187
  this.keepHidden(next);
171
- this.hidden = next;
188
+ this.choices = next;
172
189
  this.changed(key);
173
190
  });
174
191
  this.hides = change.catch(() => {});
@@ -1,7 +1,8 @@
1
- // What a panel is (docs/plugins.md「面板」): how a plugin declares one (`contributes.panels`, of the schema the resources
2
- // plugin declares for its point, schema.json, checked where the plugin is installed) and what its command may print,
3
- // checked here, where the panels are read, the way a task's card is drawn from its fields. Nothing here knows what a panel
4
- // is about: CPU, an account's quota and a disk are all meters and figures.
1
+ // What a resource type is (docs/plugins.md「资源」): how a plugin declares one (`contributes.resources`, of the schema the
2
+ // resources plugin declares for its point, resources.schema.json, checked where the plugin is installed) and what its
3
+ // command may print, checked here, where the types are read. Nothing here knows what a resource is about: CPU, an account's
4
+ // quota and a disk are all names and values. A plugin still declaring the panels before them (`contributes.panels`,
5
+ // schema.json) has them read as they were, for the page to take as resources (docs/plugins.md「旧的面板」).
5
6
 
6
7
  // What is not as it must be: the panel says so where it would show.
7
8
  export class PanelError extends Error {
@@ -19,6 +20,8 @@ function durationMs(text) {
19
20
  }
20
21
 
21
22
  export const ITEM_TYPES = ['card', 'meter', 'stat', 'markdown', 'button', 'error'];
23
+ // How many resources a reading lists, and how many values and buttons one has.
24
+ const RESOURCES = 50, VALUES = 8, ACTIONS = 8;
22
25
  // What a panel's command may print: past these, the reading fails rather than being cut short.
23
26
  export const OUTPUT_LIMIT = 64 * 1024;
24
27
  export const ARGS_LIMIT = 4 * 1024;
@@ -36,8 +39,8 @@ const text = (value, max, where, code, { need = true, line = true } = {}) => {
36
39
  };
37
40
  const object = (value, where, code) => check(value && typeof value === 'object' && !Array.isArray(value), code, `${where} 须为对象`);
38
41
 
39
- // ---- Declarations (`contributes.panels`) ----
40
- // A plugin's panels as it declares them, in its order, each with the actions its buttons may take (none when it declares
42
+ // ---- Declarations (`contributes.resources`, or the panels before them) ----
43
+ // A plugin's types as it declares them, in its order, each with the actions its buttons may take (none when it declares
41
44
  // none) and, with a `maxAge`, how long a reading may be shown again without asking.
42
45
  export function panelDeclarations(raw = []) {
43
46
  return raw.map(panel => ({ ...panel, actions: panel.actions ?? {}, ...(panel.maxAge ? { maxAgeMs: durationMs(panel.maxAge) } : {}) }));
@@ -98,24 +101,28 @@ function plainItem(raw, where, scope, inCard) {
98
101
  case 'error':
99
102
  keys(raw, ['type', 'text'], where, code);
100
103
  return { type: 'error', text: text(raw.text, ERROR, `${where} 的 text`, code, { line: false }) };
101
- case 'button': {
102
- keys(raw, ['type', 'label', 'action', 'view', 'args', 'disabled', 'confirm'], where, code);
103
- // What it does: run one of the panel's actions here, or open one of its plugin's views in the client.
104
- const opens = raw.view !== undefined;
105
- check(opens !== (raw.action !== undefined), code, `${where} 须有 action 或 view 之一`);
106
- if (opens) check(typeof raw.view === 'string' && scope.views.includes(raw.view), code, `${where} 的 view 须是插件声明的视图:${raw.view}`);
107
- else check(typeof raw.action === 'string' && Object.hasOwn(scope.actions, raw.action), code, `${where} 的 action 须是面板声明的动作:${raw.action}`);
108
- check(raw.args === undefined || (raw.args && typeof raw.args === 'object' && !Array.isArray(raw.args) && JSON.stringify(raw.args).length <= ARGS_LIMIT), code,
109
- `${where} 的 args 须为不超过 ${ARGS_LIMIT} 字节的对象`);
110
- check(raw.disabled === undefined || typeof raw.disabled === 'boolean', code, `${where} 的 disabled 须为开或关`);
111
- // Its own question, for what this one button does (which account, which credit), in place of its action's.
112
- return { type: 'button', label: text(raw.label, LABEL, `${where} 的 label`, code), ...(opens ? { view: raw.view } : { action: raw.action }),
113
- ...(raw.args ? { args: raw.args } : {}), ...(raw.disabled ? { disabled: true } : {}),
114
- ...(raw.confirm !== undefined ? { confirm: text(raw.confirm, CONFIRM, `${where} 的 confirm`, code, { line: false }) } : {}) };
115
- }
104
+ case 'button':
105
+ keys(raw, ['type', ...BUTTON_KEYS], where, code);
106
+ return { type: 'button', ...button(raw, where, scope) };
116
107
  }
117
108
  return fail(code, `${where} 的 type 不受支持`);
118
109
  }
110
+ const BUTTON_KEYS = ['label', 'action', 'view', 'args', 'disabled', 'confirm'];
111
+ // What a button does: run one of the type's actions here, or open one of its plugin's views in the client.
112
+ function button(raw, where, scope) {
113
+ const code = 'invalid_panel';
114
+ const opens = raw.view !== undefined;
115
+ check(opens !== (raw.action !== undefined), code, `${where} 须有 action 或 view 之一`);
116
+ if (opens) check(typeof raw.view === 'string' && scope.views.includes(raw.view), code, `${where} 的 view 须是插件声明的视图:${raw.view}`);
117
+ else check(typeof raw.action === 'string' && Object.hasOwn(scope.actions, raw.action), code, `${where} 的 action 须是声明的动作:${raw.action}`);
118
+ check(raw.args === undefined || (raw.args && typeof raw.args === 'object' && !Array.isArray(raw.args) && JSON.stringify(raw.args).length <= ARGS_LIMIT), code,
119
+ `${where} 的 args 须为不超过 ${ARGS_LIMIT} 字节的对象`);
120
+ check(raw.disabled === undefined || typeof raw.disabled === 'boolean', code, `${where} 的 disabled 须为开或关`);
121
+ // Its own question, for what this one button does (which account, which credit), in place of its action's.
122
+ return { label: text(raw.label, LABEL, `${where} 的 label`, code), ...(opens ? { view: raw.view } : { action: raw.action }),
123
+ ...(raw.args ? { args: raw.args } : {}), ...(raw.disabled ? { disabled: true } : {}),
124
+ ...(raw.confirm !== undefined ? { confirm: text(raw.confirm, CONFIRM, `${where} 的 confirm`, code, { line: false }) } : {}) };
125
+ }
119
126
  // A panel's reading from what its command printed. Anything it cannot be fails the reading, with where. `views`: the ids
120
127
  // of its plugin's views, which a button may open.
121
128
  export function panelItems(output, panel, views = []) {
@@ -132,6 +139,55 @@ export function panelItems(output, panel, views = []) {
132
139
  check(new Set(ids).size === ids.length, code, 'display.id 不能重复');
133
140
  return items;
134
141
  }
142
+ // A type's reading from what its command printed: `{ resources: [...] }`, each a name, the outside identity it is (an
143
+ // account, compared and nothing else), its values, one line of what is wrong with it, and its buttons. Nothing that
144
+ // explains: a value is a name and what it reads (docs/plugins.md「资源」). Anything else fails the reading, with where.
145
+ export function resourceItems(output, type, views = []) {
146
+ const code = 'invalid_panel';
147
+ check(Buffer.byteLength(output) <= OUTPUT_LIMIT, code, `输出超过 ${OUTPUT_LIMIT / 1024} KiB`);
148
+ let value;
149
+ try { value = JSON.parse(output); } catch { return fail(code, '输出不是 JSON'); }
150
+ object(value, '输出', code);
151
+ keys(value, ['resources'], '输出', code);
152
+ check(Array.isArray(value.resources) && value.resources.length <= RESOURCES, code, `输出的 resources 须为不超过 ${RESOURCES} 项的数组`);
153
+ return value.resources.map((r, i) => resource(r, `resources[${i}]`, { actions: type.actions, views }));
154
+ }
155
+ function resource(raw, where, scope) {
156
+ const code = 'invalid_panel';
157
+ object(raw, where, code);
158
+ keys(raw, ['name', 'identity', 'values', 'error', 'actions'], where, code);
159
+ const list = (value, max, name) => {
160
+ check(value === undefined || (Array.isArray(value) && value.length <= max), code, `${where} 的 ${name} 须为不超过 ${max} 项的数组`);
161
+ return value ?? [];
162
+ };
163
+ const name = text(raw.name, LABEL, `${where} 的 name`, code, { need: false });
164
+ const values = list(raw.values, VALUES, 'values').map((v, i) => reading(v, `${where}.values[${i}]`));
165
+ const actions = list(raw.actions, ACTIONS, 'actions').map((b, i) => {
166
+ const at = `${where}.actions[${i}]`;
167
+ object(b, at, code);
168
+ keys(b, BUTTON_KEYS, at, code);
169
+ return button(b, at, scope);
170
+ });
171
+ check(name !== undefined || values.length, code, `${where} 须有 name 或 values`);
172
+ return { ...(name !== undefined ? { name } : {}),
173
+ ...(raw.identity !== undefined ? { identity: text(raw.identity, IDENTITY, `${where} 的 identity`, code) } : {}),
174
+ values, ...(raw.error !== undefined ? { error: text(raw.error, LABEL, `${where} 的 error`, code) } : {}), actions };
175
+ }
176
+ // One value: what it is called (left out where its resource has only it), what it reads, how much of it is left (0–1,
177
+ // left out when not known: never drawn as empty), and a time it comes with (when a quota is back).
178
+ function reading(raw, where) {
179
+ const code = 'invalid_panel';
180
+ object(raw, where, code);
181
+ keys(raw, ['label', 'value', 'fraction', 'time'], where, code);
182
+ check(raw.fraction === undefined || raw.fraction === null || (typeof raw.fraction === 'number' && raw.fraction >= 0 && raw.fraction <= 1), code,
183
+ `${where} 的 fraction 须在 0–1 之间,不知道时不写`);
184
+ check(raw.time === undefined || (typeof raw.time === 'string' && Number.isFinite(Date.parse(raw.time))), code, `${where} 的 time 须为 ISO 8601 时间`);
185
+ check(raw.value !== undefined || typeof raw.fraction === 'number', code, `${where} 须有 value 或 fraction`);
186
+ return { ...(raw.label !== undefined ? { label: text(raw.label, LABEL, `${where} 的 label`, code) } : {}),
187
+ ...(raw.value !== undefined ? { value: text(raw.value, LABEL, `${where} 的 value`, code) } : {}),
188
+ ...(typeof raw.fraction === 'number' ? { fraction: raw.fraction } : {}),
189
+ ...(raw.time !== undefined ? { time: new Date(raw.time).toISOString() } : {}) };
190
+ }
135
191
  // What a button sends: an object the action's command reads as JSON.
136
192
  export function actionArgs(value) {
137
193
  if (value === undefined || value === null) return {};
package/check/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // The contract check of one plugin directory: the manifest and its workflows, then each agent's handshake (and with `live`, a
2
- // turn) and each panel's reading. The manifest is checked against Coda's schemas of its types and its workflows against Coda's
2
+ // turn) and each resource type's (or panel's) reading. The manifest is checked against Coda's schemas of its types and its workflows against Coda's
3
3
  // dialect of BPMN (both the protocol's), the rest by Coda's own code (check/coda/), run where a plugin is written.
4
4
  import { resolve } from 'node:path';
5
5
  import { checkAgent } from './agent.mjs';
@@ -17,10 +17,10 @@ export async function checkPlugin(dir, { agent: only = null, manifestOnly = fals
17
17
  const agents = only ? plugin.agents.filter(a => a.id === only) : plugin.agents;
18
18
  if (only && !agents.length) report.scope('manifest').fail('options.agent', `清单里没有能检查的 Agent ${only}`);
19
19
  if (manifestOnly) {
20
- if (agents.length || plugin.panels.length) report.scope('handshake').skip('options.manifest', '只查清单(--manifest):不启动 Agent、不读面板');
20
+ if (agents.length || plugin.panels.length) report.scope('handshake').skip('options.manifest', '只查清单(--manifest):不启动 Agent、不读资源');
21
21
  return { report, plugin };
22
22
  }
23
23
  for (const agent of agents) await checkAgent({ agent, checked: plugin, live, prompt, limits, say: level => report.scope(level, `Agent ${agent.id}`) });
24
- if (!only) for (const panel of plugin.panels) await checkPanel({ panel, checked: plugin, say: report.scope('handshake', `面板 ${panel.id}`) });
24
+ if (!only) for (const panel of plugin.panels) await checkPanel({ panel, checked: plugin, say: report.scope('handshake', `${panel.format === 'resources' ? '资源类型' : '面板'} ${panel.id}`) });
25
25
  return { report, plugin };
26
26
  }
@@ -107,9 +107,11 @@ export function checkManifest(dir, say) {
107
107
  const found = besideAll(dir, plugin.dependencies);
108
108
  const offered = offerProblem(plugin, new Map([...builtin, ...found]));
109
109
  if (offered) say.fail('manifest.offers', offered);
110
- // Its panels, as the resources plugin reads what is written for its point once that is of the point's schema.
111
- const panels = offered ? [] : panelDeclarations(plugin.offers?.panels);
112
- for (const panel of panels) say.pass('manifest.panels', `面板 ${panel.id}「${panel.title}」:动作 ${Object.keys(panel.actions).join('、') || '无'}${panel.signIn ? ',可从 Coda 登录' : ''}`);
110
+ // Its resource types, or the panels before them, as the resources plugin reads what is written for its point once that is
111
+ // of the point's schema: one declaring types has those alone.
112
+ const format = plugin.offers?.resources ? 'resources' : 'panels', what = format === 'resources' ? '资源类型' : '面板';
113
+ const panels = offered ? [] : panelDeclarations(plugin.offers?.[format]).map(panel => ({ ...panel, format }));
114
+ for (const panel of panels) say.pass('manifest.panels', `${what} ${panel.id}「${panel.title}」:动作 ${Object.keys(panel.actions).join('、') || '无'}${panel.signIn ? ',可从 Coda 登录' : ''}`);
113
115
 
114
116
  // What its processes are given (pluginEnv): the plugins it depends on, those beside it here; one Coda ships has its
115
117
  // directory in Coda, not here, even with one of its ID beside it (Coda picks its own), and one found nowhere is not named.
package/check/panel.mjs CHANGED
@@ -1,12 +1,13 @@
1
- // A panel at the handshake level: read once by Coda's own resources module (check/coda/resources/plugins/resources/panels/,
2
- // Panels), given what Coda's plugin host gives it (components/plugins/plugin-host.mjs): the installed plugins as it watches
3
- // them, here the one checked, and each one's environment, as Coda gives every process of the plugin's.
1
+ // A resource type (or a panel before them) at the handshake level: read once by Coda's own resources module
2
+ // (check/coda/resources/plugins/resources/panels/, Panels), given what Coda's plugin host gives it
3
+ // (components/plugins/plugin-host.mjs): the installed plugins as it watches them, here the one checked, and each one's
4
+ // environment, as Coda gives every process of the plugin's.
4
5
  // Its actions are not run: a button may change things (switch an account, spend a reset), and only a person presses it.
5
6
  import { dirname } from 'node:path';
6
7
  import { cleared } from './coda/components/plugins/plugin-rules.mjs';
7
8
  import { ended, runCommand } from './coda/resources/plugins/resources/panels/command.mjs';
8
9
  import { Panels } from './coda/resources/plugins/resources/panels/panels.mjs';
9
- import { OUTPUT_LIMIT, panelItems } from './coda/resources/plugins/resources/panels/rules.mjs';
10
+ import { OUTPUT_LIMIT, panelItems, resourceItems } from './coda/resources/plugins/resources/panels/rules.mjs';
10
11
  import { closing, temporary } from './leftovers.mjs';
11
12
 
12
13
  // The session a process would belong to: the host's belong to none.
@@ -17,6 +18,12 @@ const typesOf = items => items.flatMap(item => item.type === 'card' ? ['card', .
17
18
  // What a panel's command printed as Coda takes it (panelItems), by type; throws PanelError with where it went wrong. For the
18
19
  // tests of a plugin's panel.
19
20
  export const panelTypes = (output, panel, views = []) => typesOf(panelItems(output, panel, views));
21
+ // What a resource type's command printed as Coda takes it (resourceItems): its resources, each with only the keys it has and
22
+ // its values and buttons; throws PanelError with where it went wrong. For the tests of a plugin's resources.
23
+ export const readResources = (output, type, views = []) => resourceItems(output, type, views);
24
+ // A reading of resources in a line: how many, and how many values and buttons they have.
25
+ const counted = resources => `${resources.length} 个资源,读数 ${resources.reduce((n, r) => n + r.values.length, 0)} 个,按钮 ${resources.reduce((n, r) => n + r.actions.length, 0)} 个${
26
+ resources.some(r => r.error) ? `,${resources.filter(r => r.error).length} 个写了错误` : ''}`;
20
27
 
21
28
  // `checked`: the plugin as the manifest level read it (manifest.mjs checkManifest). `limit`: how long a reading may take, as
22
29
  // Panels has it unless given.
@@ -44,16 +51,23 @@ export async function checkPanel({ panel, checked, say, limit }) {
44
51
  try {
45
52
  await panels.start();
46
53
  const started = Date.now(), reading = await panels.read(`${plugin.id}/${panel.id}`), took = ((Date.now() - started) / 1000).toFixed(1);
47
- if (reading.error && result && ended(result)) return say.fail('panel.output', `输出不合面板格式:资源页显示「${reading.error}」`);
54
+ const kind = panel.format === 'resources' ? '资源' : '面板';
55
+ if (reading.error && result && ended(result)) return say.fail('panel.output', `输出不合${kind}格式:资源页显示「${reading.error}」`);
48
56
  if (reading.error) {
49
57
  const why = !result ? '没有运行' : result.timedOut ? `${panels.readTimeoutMs / 1000} 秒没读完,Coda 停下这次读取` : result.overflow ? `标准输出超过 ${OUTPUT_LIMIT / 1024} KiB,Coda 停下这次读取`
50
58
  : result.error ? '命令起不来' : `退出码 ${result.code}`;
51
59
  return say.fail('panel.read', `读取没成功(${why}):资源页显示「${reading.error}」`);
52
60
  }
53
- const types = typesOf(reading.items);
54
- const counts = Object.entries(Object.groupBy(types, t => t)).map(([t, list]) => `${t} ×${list.length}`).join(',');
55
- if (!types.length) say.info('panel.read', `读出空的 items(${took} 秒):资源页不显示它${panel.signIn ? ',它出现在「添加资源」里' : ''}`);
56
- else say.pass('panel.read', `读取 ${took} 秒,输出合面板格式:${counts}`);
61
+ const empty = `资源页不显示它${panel.signIn ? ',它出现在「添加资源」里' : ''}`;
62
+ if (panel.format === 'resources') {
63
+ if (!reading.resources.length) say.info('panel.read', `读出空的 resources(${took} 秒):${empty}`);
64
+ else say.pass('panel.read', `读取 ${took} 秒,输出合资源格式:${counted(reading.resources)}`);
65
+ } else {
66
+ const types = typesOf(reading.items);
67
+ const counts = Object.entries(Object.groupBy(types, t => t)).map(([t, list]) => `${t} ×${list.length}`).join(',');
68
+ if (!types.length) say.info('panel.read', `读出空的 items(${took} 秒):${empty}`);
69
+ else say.pass('panel.read', `读取 ${took} 秒,输出合面板格式:${counts}`);
70
+ }
57
71
  if (Object.keys(panel.actions).length) say.skip('panel.actions', `动作 ${Object.keys(panel.actions).join('、')} 不运行:按钮可能改动东西,只由人点`);
58
72
  } finally {
59
73
  panels.close();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coda-console/plugin-check",
3
- "version": "0.5.32",
4
- "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读面板。",
3
+ "version": "0.6.0",
4
+ "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源类型(与旧的面板)。",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@0dep/piso": "5.2.0",
26
26
  "@agentclientprotocol/sdk": "1.4.0",
27
- "@coda-console/protocol": "2.4.0",
27
+ "@coda-console/protocol": "2.5.0",
28
28
  "ajv": "8.20.0",
29
29
  "yaml": "2.9.1"
30
30
  },