@coda-console/plugin-check 0.8.26 → 0.8.27

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.
@@ -98,7 +98,7 @@ export function implementsMissing(plugin, plugins, defined) {
98
98
  }
99
99
  // This Coda's API Level (docs/plugins.md「兼容」): what it offers plugins, counted. A manifest's `engines.coda` names the least
100
100
  // a plugin needs; one naming none needs 0, which any Coda has.
101
- export const API_LEVEL = 5;
101
+ export const API_LEVEL = 6;
102
102
  // The API Level a package's registry metadata asks for in its `engines`: a positive integer, or its digits as text (what
103
103
  // npm's registry may make of one); undefined when it asks for none, null when it is anything else. A manifest read from
104
104
  // its directory has the schema's shape (plugin-rules.mjs readPlugin).
@@ -186,9 +186,10 @@ export function subscribed(plugin, plugins, defined) {
186
186
  // a stream of its records (`{ stream }`), or reading its records (`'read'`; writing them is the implementer's alone) —
187
187
  // `definition` its protocol's (`protocolDefinition`), or null (docs/plugins.md「用到的权限」). The plugin that implements or
188
188
  // defines the kind may; any other, a built-in one too, only by a group of the kind's it uses that has the operation or the
189
- // stream, or reads its records. An operation or a stream in no group is open to no plugin.
190
- export function usesRefusal(plugin, kind, need, definition) {
191
- if (ownsProtocol(plugin, kind)) return null;
189
+ // stream, or reads its records. An operation or a stream in no group is open to no plugin. `owned` false: by its uses
190
+ // alone, implementing or defining the kind not counted.
191
+ export function usesRefusal(plugin, kind, need, definition, owned = true) {
192
+ if (owned && ownsProtocol(plugin, kind)) return null;
192
193
  const groups = Object.entries(definition?.permissions ?? {}), used = new Set(plugin.uses?.[kind] ?? []);
193
194
  const covers = ([, group]) => typeof need === 'string' ? group[need] === true
194
195
  : need.stream !== undefined ? (group.streams ?? []).includes(need.stream) : (group.operations ?? []).includes(need.operation);
@@ -20,15 +20,12 @@ import { iconFiles } from './plugin-icons.mjs';
20
20
  import { checkCatalog, extensionsFor, retiredContributes } from './plugin-extensions.mjs';
21
21
  import { contributionProblem, manifestProblem, TYPES } from '@coda-console/protocol/validate';
22
22
  import { ownedProtocolsProblem } from '@coda-console/protocol/protocol';
23
- import { claims, COMMIT, INTEGRITY, NPM_VERSION, npmPluginId, repoAddress, sourcePath } from './plugin-source-rules.mjs';
23
+ import { claims, npmPluginId, repoAddress, sourcePath } from './plugin-source-rules.mjs';
24
24
  import { CONTRIBUTION_POINTS } from './contribution-points.mjs';
25
25
 
26
26
  const ID = /^[a-z][a-z0-9-]{0,39}$/;
27
27
  // Plugins that ship with Coda, as VS Code's built-in extensions ship with it: updated with Coda itself.
28
28
  export const BUILTIN_DIR = fileURLToPath(new URL('../../resources/plugins/', import.meta.url));
29
- // The package the backend runs from (the runtime clone's, or the release's), whose npm dependencies may be built-in plugins
30
- // too (dependencyPlugins).
31
- const PACKAGE_ROOT = fileURLToPath(new URL('../../../', import.meta.url));
32
29
  // What the plugins' base reads of `contributes` itself, the general types schemas/plugin.json names; any other key is a
33
30
  // contribution point's (contribution-points.mjs), or for a point another plugin declares to take it (the resources
34
31
  // plugin's `panels`), refused when neither does.
@@ -212,18 +209,12 @@ export function mcpValues(plugin, settings, state, base) {
212
209
  return [{ name: server.name, command, args, env: Object.entries(env).map(([name, value]) => ({ name, value })) }];
213
210
  });
214
211
  }
215
- // The plugins Coda ships: those in `dir`, which come from nowhere else, and its npm dependencies that are plugins
216
- // (`dependencies`), each with where it comes from, which a version from that same place may stand in for (docs/plugins.md
217
- // 「内置插件的来源」).
218
- export function builtinPlugins(dir = BUILTIN_DIR, dependencies = dir === BUILTIN_DIR ? dependencyPlugins() : new Map()) {
212
+ // The plugins Coda ships: those in `dir`, which come from nowhere else.
213
+ export function builtinPlugins(dir = BUILTIN_DIR) {
219
214
  const plugins = new Map((existsSync(dir) ? readdirSync(dir, { withFileTypes: true }) : []).filter(d => d.isDirectory()).map(d => {
220
215
  const plugin = readPlugin(join(dir, d.name), { kind: 'builtin' });
221
216
  return [plugin.id, plugin];
222
217
  }));
223
- for (const [id, plugin] of dependencies) {
224
- check(!plugins.has(id), 'invalid_plugin', `插件 ${id} 同时存在于资源目录与 npm 依赖`);
225
- plugins.set(id, plugin);
226
- }
227
218
  // An agent, a group and Git's credentials for an address are one plugin's (components/plugins/plugin-source-rules.mjs claims).
228
219
  const owner = new Map();
229
220
  for (const plugin of plugins.values()) for (const claim of claims(plugin)) {
@@ -232,35 +223,6 @@ export function builtinPlugins(dir = BUILTIN_DIR, dependencies = dir === BUILTIN
232
223
  }
233
224
  return checkCatalog(plugins);
234
225
  }
235
- // A direct npm dependency declaring `contributes` is a bundled plugin (docs/plugins.md「npm 依赖中的插件」). npm installs its
236
- // files and dependencies; where it comes from is what the dependency pins: a version of a package from the registry, with
237
- // the integrity package-lock.json has of its tarball and the repository directory the package says it is published from,
238
- // or a commit of a Git repository. Installed from the start, unless `coda.optionalPlugins` of the backend's package.json
239
- // names it.
240
- export function dependencyPlugins(root = PACKAGE_ROOT) {
241
- const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')), plugins = new Map();
242
- const optional = new Set(manifest.coda?.optionalPlugins ?? []);
243
- let lock;
244
- for (const [name, spec] of Object.entries(manifest.dependencies ?? {})) {
245
- const dir = join(root, 'node_modules', name), pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
246
- if (!Object.hasOwn(pkg, 'contributes')) continue;
247
- let source;
248
- if (typeof spec === 'string' && NPM_VERSION.test(spec)) {
249
- lock ??= JSON.parse(readFileSync(join(root, 'package-lock.json'), 'utf8')).packages ?? {};
250
- const integrity = lock[`node_modules/${name}`]?.integrity;
251
- check(typeof integrity === 'string' && INTEGRITY.test(integrity), 'invalid_plugin', `package-lock.json 里没有插件依赖 ${name} 的 sha512 完整性摘要`);
252
- source = { kind: 'builtin', package: name, tag: 'latest', version: spec, integrity, ...publishedFrom(pkg.repository) };
253
- } else {
254
- const git = typeof spec === 'string' && /^git\+(.+)#([^#]+)$/.exec(spec);
255
- check(git && COMMIT.test(git[2]), 'invalid_plugin', `插件依赖 ${name} 须写一个版本号,或用 Git 仓库地址与完整提交号固定版本`);
256
- source = { kind: 'builtin', repo: repoAddress(git[1]), path: '', commit: git[2] };
257
- }
258
- const plugin = readPlugin(dir, source);
259
- check(!plugins.has(plugin.id), 'invalid_plugin', `多个 npm 依赖声明了插件 ${plugin.id}`);
260
- plugins.set(plugin.id, { ...plugin, defaultInstalled: !optional.has(name) });
261
- }
262
- return plugins;
263
- }
264
226
  // The repository directory a package says it is published from (`repository`: its address, and `directory` in it), as a
265
227
  // source names one; nothing where it says none Coda reads.
266
228
  export function publishedFrom(repository) {
@@ -72,8 +72,8 @@ export function repoIdentity(repo) {
72
72
  return github ? `github.com/${github[1].toLowerCase()}` : repo.replace(/\.git$/, '');
73
73
  }
74
74
  // Whether two sources name the same package, at whatever version, or the same directory of the same repository, at whatever
75
- // commit: a built-in plugin and a version of it from where it comes from. A built-in package's copy names both, the
76
- // directory being the one its package says it is published from (components/plugins/plugin-rules.mjs dependencyPlugins).
75
+ // commit: a package of the store and the plugin installed from it or from where it is published. A package read from npm
76
+ // names both, the directory being the one its package says it is published from (components/plugins/plugin-rules.mjs publishedFrom).
77
77
  export const sameSource = (a, b) => !!a?.package && a.package === b?.package
78
78
  || !!(a?.repo && b?.repo) && repoIdentity(a.repo) === repoIdentity(b.repo) && (a.path ?? '') === (b.path ?? '');
79
79
  // Installed again from the same directory, another commit keeps the one it replaces as `previous`, so that going back is
@@ -97,6 +97,11 @@ export const fromElsewhere = source => source?.kind === 'git' || source?.kind ==
97
97
  // the integrity of its tarball, which names that tarball and no other. The one it had before likewise (`previousKey`).
98
98
  export const versionKey = source => source.kind === 'npm' ? createHash('sha256').update(source.integrity).digest('hex').slice(0, 40) : source.commit;
99
99
  export const previousKey = source => !source.previous ? null : source.kind === 'npm' ? versionKey({ kind: 'npm', integrity: source.previous.integrity }) : source.previous;
100
+ // Whether `source` is going back from the one `installed`: its `previous`, from the same place (as nextSource keeps it) —
101
+ // the same package at that version and integrity, or the same repository and directory at that commit.
102
+ export const goesBack = (installed, source) => installed?.kind === source.kind && !!installed.previous && (source.kind === 'npm'
103
+ ? installed.package === source.package && installed.previous.version === source.version && installed.previous.integrity === source.integrity
104
+ : installed.repo === source.repo && installed.path === source.path && installed.previous === source.commit);
100
105
 
101
106
  // ---- npm ----
102
107
  // A package as npm names it (`name`, `@scope/name`) and the version of it wanted: one version, a dist-tag, or (empty) the
@@ -248,13 +253,10 @@ export function npmPackages(manifest, lock) {
248
253
  return { name, version: typeof version === 'string' ? version : String(range), ...(optional ? { optional: true } : {}) };
249
254
  });
250
255
  }
251
- // An installed built-in plugin (including an update from its own source) reserves its ID. Uninstalling frees the name;
252
- // an installed replacement from another source keeps it across refreshes and updates.
253
- export function builtinProblem(id, source, builtin, installed) {
254
- const copy = builtin.get(id), row = installed.get(id);
255
- if (!copy || !row || sameSource(copy.source, source)) return null;
256
- if (fromElsewhere(row.source) && !sameSource(copy.source, row.source)) return null;
257
- return `与内置插件 ${id} 同名${copy.source?.repo || copy.source?.package ? ',来源不同' : ''},请先卸载内置插件再安装`;
256
+ // A plugin from a repository or npm never takes the ID of one Coda ships (`builtin`), installed or not, nor Coda's own.
257
+ export function builtinProblem(id, builtin) {
258
+ if (id === 'coda') return 'coda 是 Coda 自己的 ID';
259
+ return builtin.has(id) ? `${id} 是 Coda 自带插件的 ID` : null;
258
260
  }
259
261
  // What only one plugin may declare, as said to the user: what a component's contribution point says (its `claim`: an
260
262
  // agent, which sessions name by its ID alone; a concurrency group, which any process takes by its name; Git's credentials
@@ -265,12 +267,12 @@ export const claims = plugin => [...[...CONTRIBUTION_POINTS.values()].flatMap(po
265
267
  ...(plugin.views ?? []).flatMap(v => (v.handles ?? []).map(kind => `打开 ${kind} 引用`)),
266
268
  ...Object.values(plugin.extensionPoints ?? {}).filter(p => p.contributes).map(p => `扩展点 contributes.${p.contributes}`)];
267
269
  // Why a plugin cannot sit beside those this machine has (`catalog`: built-in and installed, by ID; `builtin`: the plugins
268
- // Coda ships, by ID), or null: an installed built-in one's ID from another source (builtinProblem), what a component's
270
+ // Coda ships, by ID), or null: a built-in one's ID or Coda's own (builtinProblem), what a component's
269
271
  // contribution point lets only a built-in plugin bring (its `builtinOnly`, of the plugin read: why, none when it brings none
270
272
  // of it), or what only one plugin may declare (claims), a protocol or an event of one, another plugin declares. What it needs of the others — the plugins it depends on,
271
273
  // the points it plugs into or writes for (plugin-extensions.mjs offerProblem) — is checked once all of them are there.
272
- export function catalogProblem(plugin, catalog, builtin, installed) {
273
- const named = builtinProblem(plugin.id, plugin.source, builtin, installed);
274
+ export function catalogProblem(plugin, catalog, builtin) {
275
+ const named = builtinProblem(plugin.id, builtin);
274
276
  if (named) return named;
275
277
  if (plugin.source?.kind !== 'builtin') for (const point of CONTRIBUTION_POINTS.values()) {
276
278
  const only = point.builtinOnly?.(plugin);
@@ -385,13 +387,15 @@ export function candidate({ path, manifest, plugin, problem, fallback }, { catal
385
387
  const id = plugin?.id ?? (typeof manifestId(manifest) === 'string' ? manifestId(manifest) : fallback);
386
388
  const row = installed.get(id), along = plugin ? together(plugin, { catalog, installed, siblings, defined }) : [];
387
389
  const missing = along.filter(each => each.from === 'missing').map(each => each.id);
390
+ // One coming along from the source is installed as it is (components/plugins/plugins.mjs installFrom): judged by its ID the same.
391
+ const reserved = along.filter(each => each.from === 'source').map(each => [each.id, builtinProblem(each.id, builtin)]).find(([, why]) => why);
388
392
  // What this machine has once it is installed, those installed with it among them: the points it may write for.
389
393
  const after = plugin ? catalogAfter(plugin, { catalog, siblings }) : catalog;
390
394
  const incompatible = plugin ? installingIncompatibility(after, installed, id, { channel, level, defined }) : null;
391
395
  return { path, id, displayName: plugin?.displayName ?? (typeof manifest?.displayName === 'string' ? manifest.displayName : id),
392
396
  description: plugin?.description ?? (typeof manifest?.description === 'string' ? manifest.description : ''), version: plugin?.version ?? '',
393
- installed: row ? row.source ?? builtin.get(id)?.source ?? { kind: 'builtin' } : null,
394
- problem: problem ?? incompatible?.error ?? (plugin ? catalogProblem(plugin, catalog, builtin, installed) ?? offerProblem(plugin, after) : null)
397
+ installed: row ? row.source ?? { kind: 'builtin' } : null,
398
+ problem: problem ?? incompatible?.error ?? (plugin ? catalogProblem(plugin, catalog, builtin) ?? offerProblem(plugin, after) : null) ?? (reserved ? reserved.join(':') : null)
395
399
  ?? (missing.length ? `要一起装的 ${missing.join('、')} 不在这台机器上${plugin.source?.kind === 'npm' ? '' : ',也不在这个提交里'}` : null),
396
400
  ...(!problem && incompatible ? { incompatible } : {}), together: along.filter(each => each.from !== 'missing'),
397
401
  ...(plugin ? { contributes: contributions(plugin, after, defined) } : {}) };
@@ -1,10 +1,10 @@
1
1
  {
2
- "commit": "6152218e2afb04e9afba3fad4c312e5f155a1d56",
3
- "apiLevel": 5,
2
+ "commit": "54365d425202b30d8f400338a0ee2a3504b12522",
3
+ "apiLevel": 6,
4
4
  "packages": {
5
5
  "@0dep/piso": "5.2.0",
6
6
  "@agentclientprotocol/sdk": "2.6.0",
7
- "@coda-console/protocol": "6.15.0",
7
+ "@coda-console/protocol": "6.17.0",
8
8
  "ajv": "8.20.0",
9
9
  "yaml": "2.9.1"
10
10
  },
@@ -30,10 +30,10 @@
30
30
  "check/coda/components/plugins/contribution-points.mjs": "2dade9fe4f3fa2b4e89f49a1ac4378ab2621e5ac542eb175967091f04568b45c",
31
31
  "check/coda/components/plugins/git-contributions.mjs": "532917cd3ec45e12535e9e6c206ae14fa598bebc789ab0c8f15609d1699fa1cd",
32
32
  "check/coda/components/plugins/model-contributions.mjs": "018a7157954b2326887ba1a780b37d3beb33338e41a28936b313562c2939d563",
33
- "check/coda/components/plugins/plugin-extensions.mjs": "54b2fbc9db34ae0a18fe6193714287b82fff3f796069318c9a1e5f92d48475aa",
33
+ "check/coda/components/plugins/plugin-extensions.mjs": "49b6dc6203246f1fd4e9faf8dea33654c601a4d10145713bc3d84099df5f5f07",
34
34
  "check/coda/components/plugins/plugin-icons.mjs": "ec29cadce4948ecacabfe911a2ceb45414b96e28971358acbc4e952bedc78e1a",
35
- "check/coda/components/plugins/plugin-rules.mjs": "32cf0a3956a646e0c18cea62da4c0969af9f4c6f60ab1a4970937163a13a878a",
36
- "check/coda/components/plugins/plugin-source-rules.mjs": "d3bf278c4fb35e99f602ea81419dff0ad0c2753ee20e6e3b648d2fecf82da44f",
35
+ "check/coda/components/plugins/plugin-rules.mjs": "c1a8d7180b95585654a838cea8bf7fbc124c5e798ce1875f8a58d0f7fc3b21cd",
36
+ "check/coda/components/plugins/plugin-source-rules.mjs": "cbe26ff38c68f89958eb16e825d4b63de580f61b16e717404af195a5709f1f6d",
37
37
  "check/coda/components/plugins/process-contributions.mjs": "6d39a904f52956b87c04351398f79a4fc34981fa01453195bd7a3b9f2c5d237b",
38
38
  "check/coda/components/plugins/skill-document.mjs": "153ad3c096c7c9b7774bcf7dcc0ba603c962ee1ac8697c8a71e3f2c9ba9c92e6",
39
39
  "check/coda/components/prompt-recovery/prompt-recovery.mjs": "25477742af8a9134ae343af6ab702926692bdd8dd07844f3cba47e8b702c0e49",
@@ -60,7 +60,7 @@
60
60
  "check/coda/resources/plugins/resources/panels/panels.mjs": "37ffc6a4ede3e4612cd13cf1a973a90892f8ce7e8a0f055e7cfe86313aae5224",
61
61
  "check/coda/resources/plugins/resources/panels/rules.mjs": "a433d4e84138937297ec31a8912aab7bd48bba4b66da3a10978edb1367613c96",
62
62
  "check/coda/resources/plugins/resources/panels/sign-in.mjs": "6eb016ef9a7f8aa03e0f4b2fa35ce139b8b1ff0deb4ec6e6a34139aed4f2841a",
63
- "check/coda/builtin.json": "0eb63a693c912f7e339cda0b76b85110f881784b92c7788c8ea6d0a1c7468ade",
64
- "check/coda/api-surface.txt": "47fe85e101b2315d6e5783e1e74050f493c2045ca6ea4577ad841d6643d8b238"
63
+ "check/coda/builtin.json": "d42d66c67aa3a9dee8239146ef797617d6502b45f48e0557a7db899e12a5737c",
64
+ "check/coda/api-surface.txt": "babddd7c7fb1b897874d86deed1d42f07ded67b2fff60e75a9c0b8c4749581ea"
65
65
  }
66
66
  }
package/check/index.mjs CHANGED
@@ -7,6 +7,7 @@ import { checkLevel } from './level.mjs';
7
7
  import { checkManifest } from './manifest.mjs';
8
8
  import { checkModule } from './module.mjs';
9
9
  import { checkPanel } from './panel.mjs';
10
+ import { checkResources, RESOURCE } from './resources.mjs';
10
11
  import { checkWorkflows } from './workflows.mjs';
11
12
  import { Report } from './report.mjs';
12
13
 
@@ -19,12 +20,14 @@ export async function checkPlugin(dir, { agent: only = null, manifestOnly = fals
19
20
  checkLevel({ checked: plugin, say: report.scope('manifest'), note: report.scope('note') });
20
21
  const agents = only ? plugin.agents.filter(a => a.id === only) : plugin.agents;
21
22
  if (only && !agents.length) report.scope('manifest').fail('options.agent', `清单里没有能检查的 Agent ${only}`);
23
+ const resources = plugin.plugin.records?.some(one => one.kind === RESOURCE);
22
24
  if (manifestOnly) {
23
- if (agents.length || plugin.panels.length) report.scope('handshake').skip('options.manifest', '只查清单(--manifest):不启动 Agent、不读资源');
25
+ if (agents.length || plugin.panels.length || resources) report.scope('handshake').skip('options.manifest', '只查清单(--manifest):不启动 Agent、不读资源');
24
26
  return { report, plugin };
25
27
  }
26
28
  if (plugin.plugin.main) await checkModule({ checked: plugin, say: report.scope('module'), note: report.scope('note'), limit: limits?.activate });
27
29
  for (const agent of agents) await checkAgent({ agent, checked: plugin, live, prompt, limits, say: level => report.scope(level, `Agent ${agent.id}`) });
28
30
  if (!only) for (const panel of plugin.panels) await checkPanel({ panel, checked: plugin, say: report.scope('handshake', `${panel.format === 'resources' ? '资源类型' : '面板'} ${panel.id}`) });
31
+ if (!only && resources) await checkResources({ checked: plugin, say: report.scope('handshake', `资源记录 ${RESOURCE}`) });
29
32
  return { report, plugin };
30
33
  }
package/check/module.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // handshake, for a plugin with a `main`.
4
4
  import { join } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
- import { protocolHasRecords } from '@coda-console/protocol/protocol';
6
+ import { protocolHasRecords, RESOURCE_PROTOCOL } from '@coda-console/protocol/protocol';
7
7
  import { usesRefusal } from './coda/components/plugins/plugin-extensions.mjs';
8
8
  import { createTestHost } from './coda/adapters/plugin-test-host.mjs';
9
9
  import { closing, temporary } from './leftovers.mjs';
@@ -113,8 +113,9 @@ function unfinished({ plugin, definitions, definitionOf }, e, from, absent, used
113
113
  }
114
114
 
115
115
  // What the manifest says it implements against what the module registered, both ways: an operation not implemented by a command
116
- // is the module's to register (but for those only Coda answers); one registered that the definition lacks is no operation of the
117
- // protocol. (A protocol the manifest does not implement is refused by the test host as the module registers: it fails `activate`.)
116
+ // is the module's to register (but for those only Coda answers, and for `coda/resource@1`, whose operations a plugin offers one by
117
+ // one: the manifest writes only those it has); one registered that the definition lacks is no operation of the protocol.
118
+ // (A protocol the manifest does not implement is refused by the test host as the module registers: it fails `activate`.)
118
119
  function compare({ plugin, definitionOf }, { operations }, say) {
119
120
  const registered = new Set(operations.map(({ kind, operation }) => `${kind} ${operation}`));
120
121
  let problems = 0, incomplete = false;
@@ -123,7 +124,7 @@ function compare({ plugin, definitionOf }, { operations }, say) {
123
124
  if (!definition) { incomplete = true; say.warn('module.registered', `未完成核对:协议 ${kind} 的定义不在本地,查不了模块登记了它的哪些操作`); continue; }
124
125
  // `codaOnly`: Coda's own protocol's operation that Coda alone answers.
125
126
  for (const [operation, { codaOnly }] of Object.entries(definition.operations ?? {}))
126
- if (!codaOnly && !Object.hasOwn(commands, operation) && !registered.has(`${kind} ${operation}`)) { problems++; say.fail('module.unregistered', `清单写了实现 ${kind} 的操作 ${operation},模块没登记(coda.handle)`); }
127
+ if (!codaOnly && kind !== RESOURCE_PROTOCOL.name && !Object.hasOwn(commands, operation) && !registered.has(`${kind} ${operation}`)) { problems++; say.fail('module.unregistered', `清单写了实现 ${kind} 的操作 ${operation},模块没登记(coda.handle)`); }
127
128
  }
128
129
  for (const { kind, operation } of operations) {
129
130
  const definition = definitionOf(kind);
@@ -0,0 +1,99 @@
1
+ // A plugin's resource records (`coda/resource@1`, written by the command its `contributes.records` names for the kind) at the
2
+ // handshake level: the command run as Coda's host runs a record command (cwd the plugin's directory, its own environment,
3
+ // `{}` on standard input, `CODA_RECORD_KIND`, 30 seconds), and what it printed held to what the host holds it to before it
4
+ // writes the plugin's whole set of the kind (backend components/plugins/record-commands.mjs, components/protocols/providers.mjs):
5
+ // an array of `{ key, spec }`, each at most 64 KiB, each key once, the spec the protocol's schema, `spec.type` the key; and a
6
+ // button's `args` at most 4096 bytes, which no schema can say. Its operations (`act`, `sign-in`, `install`) are not run: a button
7
+ // may change things, and only a person presses it.
8
+ //
9
+ // For the tests of a plugin's resources: `resourceRecords(dir, { env })` runs the command and gives the records it printed, and
10
+ // throws what is wrong; `resourceRecordsProblem(output)` judges what is already at hand.
11
+ import { spawn } from 'node:child_process';
12
+ import { readFileSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import { RESOURCE_PROTOCOL } from '@coda-console/protocol/protocol';
15
+ import { pointProblem } from '@coda-console/protocol/validate';
16
+ import { fileCommand, runPluginCommand, settle } from './coda/adapters/plugin-command.mjs';
17
+ import { checkLabels, checkReplace, checkWrite } from './coda/components/protocols/record-rules.mjs';
18
+ import { cleared } from './coda/components/plugins/plugin-rules.mjs';
19
+ import { group, temporary } from './leftovers.mjs';
20
+
21
+ export const RESOURCE = RESOURCE_PROTOCOL.name;
22
+ // A record as the host takes it (at most, as JSON), and a button's `args` (as JSON, in bytes).
23
+ export const ENTRY = 64 * 1024, ARGS = 4096;
24
+ // How long the host gives a record command.
25
+ const TIMEOUT = 30_000;
26
+ const bytes = value => Buffer.byteLength(JSON.stringify(value));
27
+
28
+ // What is wrong with what a resource record command printed (`output`, parsed), as the host takes it, or null: the first thing
29
+ // found, naming the record by its place in the array.
30
+ export function resourceRecordsProblem(output) {
31
+ if (!Array.isArray(output)) return '命令的输出不是数组';
32
+ const big = output.findIndex(one => bytes(one) > ENTRY);
33
+ if (big >= 0) return `第 ${big + 1} 条记录超过 ${ENTRY / 1024} KiB`;
34
+ try { checkReplace(output); } catch (error) { return error.message; }
35
+ for (const [i, { key, ...value }] of output.entries()) {
36
+ const at = `第 ${i + 1} 条记录(${key})`;
37
+ try { checkWrite(value); checkLabels(value.labels ?? null); } catch (error) { return `${at}:${error.message}`; }
38
+ const problem = pointProblem(RESOURCE_PROTOCOL.spec, value.spec, `${at} spec`)
39
+ ?? (Object.hasOwn(value, 'status') ? pointProblem(RESOURCE_PROTOCOL.status, value.status, `${at} status`) : null);
40
+ if (problem) return problem;
41
+ if (value.spec.type !== key) return `${at}:spec.type(${value.spec.type})须与 key 相同`;
42
+ for (const [r, resource] of value.spec.resources.entries()) for (const [b, { args }] of resource.buttons.entries())
43
+ if (args !== undefined && bytes(args) > ARGS) return `${at}:spec.resources[${r}].buttons[${b}].args 序列化后 ${bytes(args)} 字节,超过 ${ARGS} 字节`;
44
+ }
45
+ return null;
46
+ }
47
+
48
+ // What starts a command: a child of the checker's, in a group of its own, which goes however the checker ends.
49
+ const ends = new Map();
50
+ const start = {
51
+ spawn: (owner, _entry, file, args, options) => {
52
+ const child = spawn(file, args, { ...options, detached: true });
53
+ ends.set(owner, group(child.pid));
54
+ return child;
55
+ },
56
+ remove: owner => { ends.get(owner)?.(); ends.delete(owner); },
57
+ };
58
+
59
+ // The plugin's resource record command `command` (a file in `dir`) run, as `{ result }`, the array it printed, or `{ error }`,
60
+ // the message of why it gave none. `env`: the environment of the plugin's processes, as the host gives it.
61
+ export async function runResourceCommand(dir, command, env) {
62
+ const ran = await runPluginCommand(fileCommand(command), { start, cwd: dir, env: { ...env, CODA_RECORD_KIND: RESOURCE }, input: '{}', timeoutMs: TIMEOUT });
63
+ const { result, error } = settle(ran, { what: '记录命令' });
64
+ return error ? { error: error.message } : { result };
65
+ }
66
+
67
+ // The records the plugin in `dir` gives of `coda/resource@1`: its manifest's command for the kind run (`env`: the environment of
68
+ // its processes, for a test that puts its own in place of the machine's, as the host gives it; by default this process's, with
69
+ // `CODA_PLUGIN_PATH` the plugin's directory and this Node first on the PATH), and what it printed, `[{ key, spec }]`, held to the
70
+ // host's limits. Throws what is wrong: the command's failure, or the first problem of its output (`resourceRecordsProblem`).
71
+ export async function resourceRecords(dir, { env = { ...process.env, CODA_PLUGIN_PATH: dir, PATH: [dirname(process.execPath), process.env.PATH].filter(Boolean).join(':') } } = {}) {
72
+ const { contributes } = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')), found = contributes?.records?.find(one => one.kind === RESOURCE);
73
+ if (!found) throw new Error(`清单的 contributes.records 里没有 ${RESOURCE}`);
74
+ const { error, result } = await runResourceCommand(dir, found.command, env);
75
+ if (error) throw new Error(error);
76
+ const problem = resourceRecordsProblem(result);
77
+ if (problem) throw new Error(problem);
78
+ return result;
79
+ }
80
+
81
+ // The check of the plugin `checked` (the manifest level's reading, manifest.mjs checkManifest) that writes `coda/resource@1`
82
+ // records: its command run once in the environment Coda gives its processes, what it printed judged as the tests judge it.
83
+ export async function checkResources({ checked, say }) {
84
+ const { plugin } = checked, { command } = plugin.records.find(one => one.kind === RESOURCE);
85
+ // The plugin's state directory, which Coda keeps for it; here a temporary one, gone however the checker ends.
86
+ const state = temporary('coda-plugin-check-state-');
87
+ try {
88
+ const env = { ...cleared(process.env), ...checked.env(state.dir) };
89
+ delete env.CODA_THREAD_ID;
90
+ env.PATH = [dirname(process.execPath), env.PATH].filter(Boolean).join(':');
91
+ env.CODA_GROUPS_STATE = JSON.stringify({ now: Date.now(), groups: [] });
92
+ const started = Date.now(), { error, result } = await runResourceCommand(plugin.dir, command, env), took = ((Date.now() - started) / 1000).toFixed(1);
93
+ if (error) return say.fail('resource.read', `读取没成功:${error}`);
94
+ const problem = resourceRecordsProblem(result);
95
+ if (problem) return say.fail('resource.output', `输出不合 ${RESOURCE}:${problem}`);
96
+ const resources = result.flatMap(record => record.spec.resources), count = key => resources.reduce((n, resource) => n + resource[key].length, 0);
97
+ say.pass('resource.read', `读取 ${took} 秒,输出合 ${RESOURCE}:${result.length} 条记录,${resources.length} 个资源,读数 ${count('values')} 个,按钮 ${count('buttons')} 个`);
98
+ } finally { state.remove(); }
99
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coda-console/plugin-check",
3
- "version": "0.8.26",
3
+ "version": "0.8.27",
4
4
  "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源类型(与旧的面板)。",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "dependencies": {
30
30
  "@0dep/piso": "5.2.0",
31
31
  "@agentclientprotocol/sdk": "2.6.0",
32
- "@coda-console/protocol": "6.15.0",
32
+ "@coda-console/protocol": "6.17.0",
33
33
  "ajv": "8.20.0",
34
34
  "yaml": "2.9.1"
35
35
  },