@coda-console/plugin-check 0.8.23 → 0.8.25

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 = 1;
101
+ export const API_LEVEL = 3;
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).
@@ -108,12 +108,17 @@ export function wantedLevel(engines) {
108
108
  if (Number.isInteger(value) && value >= 1) return value;
109
109
  return typeof value === 'string' && /^[1-9][0-9]{0,8}$/.test(value) ? Number(value) : null;
110
110
  }
111
+ // The keys of `contributes` Coda once read and no longer does: a manifest still writing one was made for what Coda took away.
112
+ const RETIRED_CONTRIBUTES = ['endpoints', 'groups', 'events'];
113
+ // Those of them `contributes` writes, a manifest's or a version's registry metadata: what either is read with as its `retired`.
114
+ export const retiredContributes = contributes => RETIRED_CONTRIBUTES.filter(key => Object.hasOwn(contributes ?? {}, key));
111
115
  // Whether a plugin runs on this machine (docs/plugins.md「兼容」): the one judgment reading a source, installing, the store and
112
116
  // the catalog take. Null when it does; else what it needs (`need`), what is missing (`missing`) and why, as the user is
113
117
  // told (`error`). `host`: this machine — its API Level (`level`), its backend's channel, the catalog beside the plugin and
114
118
  // Coda's own protocols (`defined`, as usesMissing takes them). A Level above this Coda's is Coda's to catch up with
115
- // (`coda`); short of that, a channel it is not for, or a protocol or permission group it uses or a protocol it implements
116
- // that is not here, is the plugin's to update (`update`): Coda no longer offers what it was made for.
119
+ // (`coda`); short of that, a channel it is not for, a key of `contributes` Coda retired, or a protocol or permission group
120
+ // it uses or a protocol it implements that is not here, is the plugin's to update (`update`): Coda no longer offers what it
121
+ // was made for.
117
122
  export function compatibility(plugin, { catalog = new Map(), defined = () => null, ...here }) {
118
123
  const own = ownIncompatibility(plugin, here);
119
124
  if (own) return own;
@@ -124,10 +129,13 @@ export function compatibility(plugin, { catalog = new Map(), defined = () => nul
124
129
  : coda ? `本机的 Coda 已不提供协议 ${protocol},插件需要更新` : `${used ? '用到' : '实现'}的协议 ${protocol} 不在这台机器上,也不随它一起装`;
125
130
  return { need: 'update', missing, error };
126
131
  }
127
- // What of that a plugin answers by itself, whatever else is here: the API Level it needs, the channels it is for.
132
+ // What of that a plugin answers by itself, whatever else is here: the API Level it needs, the channels it is for, the keys of
133
+ // `contributes` Coda retired it still writes (`retired`).
128
134
  export function ownIncompatibility(plugin, { level = API_LEVEL, channel = null }) {
129
135
  const wanted = plugin.engines?.coda ?? 0;
130
136
  if (wanted > level) return { need: 'coda', missing: { level: wanted }, error: `这个版本要 Coda API Level ≥ ${wanted}(本机 ${level}),请先升级 Coda` };
137
+ const retired = plugin.retired?.[0];
138
+ if (retired) return { need: 'update', missing: { contribution: retired }, error: `本机的 Coda 已不提供 contributes.${retired},插件需要更新` };
131
139
  const channelProblem = pluginChannelProblem(plugin, channel);
132
140
  return channelProblem ? { need: 'update', missing: { channel }, error: channelProblem } : null;
133
141
  }
@@ -9,15 +9,15 @@
9
9
  // gives), and that its settings are named under it.
10
10
  // A secret (`writeOnly`) is a text written and never read back, kept in a file beside the database and given to the
11
11
  // plugin's processes as that file's path (`CODA_PLUGIN_SECRETS`).
12
- import { readFileSync, readdirSync, existsSync } from 'node:fs';
12
+ import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';
13
13
  import { join, normalize, posix } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { requireCondition as check, ContractError } from '../../domain/errors.mjs';
16
- import { isDuration } from '../../domain/duration.mjs';
16
+ import { durationMs, isDuration } from '../../domain/duration.mjs';
17
17
  import { AGENT_ID } from '../../domain/values.mjs';
18
18
  import { THREAD_ENV, TOKEN_ENV } from '../../domain/session-env.mjs';
19
19
  import { iconFiles } from './plugin-icons.mjs';
20
- import { checkCatalog, extensionsFor } from './plugin-extensions.mjs';
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
23
  import { claims, COMMIT, INTEGRITY, NPM_VERSION, npmPluginId, repoAddress, sourcePath } from './plugin-source-rules.mjs';
@@ -33,6 +33,8 @@ const PACKAGE_ROOT = fileURLToPath(new URL('../../../', import.meta.url));
33
33
  // contribution point's (contribution-points.mjs), or for a point another plugin declares to take it (the resources
34
34
  // plugin's `panels`), refused when neither does.
35
35
  export const CONTRIBUTES = TYPES;
36
+ // The shortest a kind's records are given again by its command on their own (`contributes.records`' `every`).
37
+ const EVERY_LEAST = 60_000;
36
38
  export const MODEL_PROVIDER = /^[a-z][a-z0-9-]{0,39}\/[a-z][a-z0-9-]{0,39}$/;
37
39
  // How many model services a setting of several may name.
38
40
  const MODEL_PROVIDERS_AT_MOST = 20;
@@ -114,6 +116,7 @@ export function readPlugin(dir, source, points = CONTRIBUTION_POINTS) {
114
116
  const contributes = manifest.contributes ?? {}, configuration = contributes.configuration ?? {};
115
117
  const protocolsProblem = ownedProtocolsProblem({ id, contributes: { protocols: contributes.protocols } });
116
118
  check(!protocolsProblem, 'invalid_plugin', protocolsProblem);
119
+ const records = recordCommands(contributes, dir), self = selfCommands(contributes, dir), retired = retiredContributes(contributes);
117
120
  const properties = Object.fromEntries(Object.entries(configuration.properties ?? {}).map(([key, value]) => {
118
121
  check(key.split('.')[0] === id, 'invalid_plugin', `设置名须以「${id}.」开头:${key}`);
119
122
  return [key, setting(value, key)];
@@ -131,6 +134,7 @@ export function readPlugin(dir, source, points = CONTRIBUTION_POINTS) {
131
134
  ...(manifest.coda !== undefined ? { coda: manifest.coda } : {}),
132
135
  // The API Level it needs (plugin-extensions.mjs compatibility).
133
136
  ...(manifest.engines?.coda !== undefined ? { engines: { coda: manifest.engines.coda } } : {}),
137
+ ...(retired.length ? { retired } : {}),
134
138
  // The permission groups of others' protocols it uses (docs/plugins.md「用到的权限」), by protocol: checked against the
135
139
  // catalog it is installed into, and whenever the catalog is read (plugin-extensions.mjs compatibility).
136
140
  ...(manifest.uses && Object.keys(manifest.uses).length ? { uses: structuredClone(manifest.uses) } : {}),
@@ -138,13 +142,14 @@ export function readPlugin(dir, source, points = CONTRIBUTION_POINTS) {
138
142
  ...(required.length ? { required: [...required] } : {}), workflows: files('.coda/workflows'),
139
143
  services: [...(contributes.services ?? [])],
140
144
  ...read,
141
- endpoints: (contributes.endpoints ?? []).map(e => ({ id: e.id, command: e.command })),
142
145
  // The entry as one path in its directory (`./view/a.html`, `view//a.html` are `view/a.html`): the clients load it by that.
143
146
  views: (contributes.views ?? []).map(v => ({ id: v.id, title: v.title, entry: posix.normalize(v.entry), ...(v.in?.length ? { in: [...v.in] } : {}),
144
147
  ...(v.icon ? { icon: v.icon } : {}), ...(v.handles?.length ? { handles: [...v.handles] } : {}), ...(v.readout ? { readout: v.readout } : {}),
145
148
  ...(v.checkout ? { checkout: v.checkout } : {}), ...(v.frame ? { frame: v.frame } : {}), ...(v.provides?.length ? { provides: [...v.provides] } : {}) })),
146
149
  ...(contributes.protocols?.length ? { protocols: structuredClone(contributes.protocols) } : {}),
147
150
  ...(contributes.protocolImplementations?.length ? { protocolImplementations: implementations(contributes.protocolImplementations) } : {}),
151
+ ...(records.length ? { records } : {}),
152
+ ...(Object.keys(self).length ? { self } : {}),
148
153
  ...(Object.keys(offers).length ? { offers } : {}),
149
154
  dependencies: [...dependencies], extensionPoints: extensionPoints(contributes.extensionPoints, dir),
150
155
  extensions: Object.entries(contributes.extensions ?? {}).map(([key, value]) => { const [plugin, point] = key.split('/'); return { plugin, point, command: value.command }; }),
@@ -290,6 +295,38 @@ export function pluginEnv({ catalog, installed, id, stateDir = () => null, setti
290
295
  // (docs/plugins.md「用命令实现操作」). The test host (adapters/plugin-test-host.mjs) reads a manifest's with it too.
291
296
  export const implementations = entries => entries
292
297
  .map(entry => typeof entry === 'string' ? { kind: entry, commands: {} } : { kind: entry.kind, commands: { ...entry.commands } });
298
+ // A manifest's `contributes.records` as Coda keeps it (docs/plugins.md「命令写记录」), each `{ kind, command, every? }`, `every`
299
+ // in milliseconds: the kinds its commands give the records of, each one it implements (`protocolImplementations`, as only
300
+ // a plugin implementing a kind holds its records), given again no oftener than EVERY_LEAST. The file is one it runs itself (`runnable`).
301
+ function recordCommands(contributes, dir) {
302
+ const implemented = new Set(implementations(contributes.protocolImplementations ?? []).map(entry => entry.kind));
303
+ return (contributes.records ?? []).map(({ kind, command, every }, i) => {
304
+ const where = `contributes.records 第 ${i + 1} 项(${kind})`;
305
+ check(implemented.has(kind), 'invalid_plugin', `contributes.records 第 ${i + 1} 项的种类 ${kind} 不在这个插件的 protocolImplementations 里`);
306
+ let ms = null;
307
+ if (every !== undefined) {
308
+ try { ms = durationMs(every); } catch { ms = NaN; }
309
+ check(Number.isSafeInteger(ms), 'invalid_plugin', `${where}的 every ${every} 不是能用的时长`);
310
+ }
311
+ runnable(dir, command, where);
312
+ check(ms === null || ms >= EVERY_LEAST, 'invalid_plugin', `${where}的 every ${every} 短于 PT1M`);
313
+ return { kind, command, ...(ms === null ? {} : { every: ms }) };
314
+ });
315
+ }
316
+ // A manifest's `contributes.self` as Coda keeps it (docs/plugins.md「只给自己用的查询」): by name, the file in its directory
317
+ // that answers its own query of that name, before its module (plugin-host.mjs `querySelf`); each one it runs itself (`runnable`).
318
+ function selfCommands(contributes, dir) {
319
+ const self = { ...contributes.self };
320
+ for (const [name, command] of Object.entries(self)) runnable(dir, command, `contributes.self「${name}」`);
321
+ return self;
322
+ }
323
+ // A file of a plugin's that Coda runs itself (adapters/plugin-command.mjs fileCommand), there in its directory as the schema
324
+ // checks: executable, starting with `#!`; refused naming `where` it is written.
325
+ function runnable(dir, command, where) {
326
+ const path = join(dir, command);
327
+ check(statSync(path).mode & 0o111, 'invalid_plugin', `${where}的 ${command} 不可执行`);
328
+ check(readFileSync(path).subarray(0, 2).toString('latin1') === '#!', 'invalid_plugin', `${where}的 ${command} 不以 #! 开头`);
329
+ }
293
330
  // The file in its directory that implements an operation of a protocol the plugin implements (`protocolImplementations`'
294
331
  // `commands`), or null: its module's, or not the plugin's at all.
295
332
  export function commandOf(plugin, kind, operation) {
@@ -319,7 +319,8 @@ export function catalogAfter(plugin, { catalog, siblings }) {
319
319
  // What installing it brings, as the confirmation lists it: every command it runs, word for word (those it plugs into
320
320
  // another plugin's points too, which that plugin runs — those it writes for a point under a key of `contributes`, where
321
321
  // the point says, the catalog beside it (`catalog`) declaring it —, those it puts on every session's PATH, those
322
- // answering clients' requests, those implementing operations of its protocols (by kind, operation and file), and the one that makes each
322
+ // answering clients' requests, those implementing operations of its protocols (by kind, operation and file), those giving
323
+ // the records of its kinds and answering its own queries, and the one that makes each
323
324
  // machine ready for it, run as it is installed or updated), what a component's contribution point confirms (its
324
325
  // `confirm`: its agents and the commands it puts on sessions' PATH, the Agent Skills it lays into projects, the MCP
325
326
  // servers their agents start and what it tells every agent; the groups it brings, what it calls its capabilities; the
@@ -335,9 +336,12 @@ export function contributions(plugin, catalog = new Map(), defined = () => null)
335
336
  // directories it puts on their PATH.
336
337
  ...(plugin.environment?.length ? { environment: plugin.environment.map(({ name, value }) => ({ name, value })) } : {}),
337
338
  ...(plugin.path?.length ? { path: plugin.path } : {}),
338
- ...(plugin.endpoints?.length ? { endpoints: plugin.endpoints.map(e => ({ id: e.id, command: e.command })) } : {}),
339
339
  // The files in its directory the backend runs as Coda calls an operation of a protocol it implements (docs/plugins.md「用命令实现操作」).
340
340
  ...(operationCommands(plugin).length ? { operations: operationCommands(plugin) } : {}),
341
+ // The files it runs to give the records of a kind it implements (docs/plugins.md「命令写记录」), by kind, and those
342
+ // answering its own queries (docs/plugins.md「只给自己用的查询」), by name.
343
+ ...(plugin.records?.length ? { records: plugin.records.map(({ kind, command }) => ({ kind, command })) } : {}),
344
+ ...(plugin.self ? { self: Object.entries(plugin.self).map(([name, command]) => ({ name, command })) } : {}),
341
345
  // Its module the plugin host runs (docs/plugins.md「插件宿主」): code of its own in Coda's Node on this machine.
342
346
  ...(plugin.main ? { main: plugin.main } : {}),
343
347
  // The pages it opens in the clients, by name, with where they stay and their icon there: they run in the client's
@@ -1,9 +1,10 @@
1
1
  {
2
- "commit": "603281c3a2cdf7904055adf62964f9482b2682d4",
2
+ "commit": "46a06458a98d290d4cc69dfdfcf1880889d0bfcf",
3
+ "apiLevel": 3,
3
4
  "packages": {
4
5
  "@0dep/piso": "5.2.0",
5
6
  "@agentclientprotocol/sdk": "2.6.0",
6
- "@coda-console/protocol": "6.14.0",
7
+ "@coda-console/protocol": "6.15.0",
7
8
  "ajv": "8.20.0",
8
9
  "yaml": "2.9.1"
9
10
  },
@@ -16,12 +17,12 @@
16
17
  "check/coda/adapters/provider-api.mjs": "70441ea2a417ede13e04113ec254496883be3186f291ef5ee65834f35009eb9e",
17
18
  "check/coda/adapters/call-limit.mjs": "7e86d95ff7b0a88955015904ec91ae55e78fad816d06f710d6e62af53ccbdeab",
18
19
  "check/coda/adapters/clock.mjs": "79733b9ac3807b3da147fe8b782318a1cb42d1d51b9c8b81a507c13c7a8025fd",
19
- "check/coda/adapters/plugin-command.mjs": "526b4f57a549d9f74bac508f5803a592210cbf24ab67148260262f02d2bc75b5",
20
- "check/coda/adapters/plugin-events.mjs": "8d63b55e333d3943d8c189d10439d5804372fbd831958491c93943f98cd078be",
21
- "check/coda/adapters/plugin-modules.mjs": "bea6dac783a1c5fcee618e36821a4a23a1e3df155658f2f37cf8288c19009a09",
20
+ "check/coda/adapters/plugin-command.mjs": "47bd580f7142780933315f64d4562d23a61f996b3f411cfb583333261b590ee8",
21
+ "check/coda/adapters/plugin-events.mjs": "5b6b98063a2a2f3d112908ad9fdc08119ec1bd577ca765811799ef6d1030dfe4",
22
+ "check/coda/adapters/plugin-modules.mjs": "dd916da2c3411087fc09ed20e2c1c5f10ce450ed096b9054db7d9c47000a2857",
22
23
  "check/coda/adapters/plugin-stream-services.mjs": "1e92eb3dd9d844d4f2773a60bc2941aae3c9cda10d9e96e31de9f09f51e672e5",
23
- "check/coda/adapters/plugin-test-host.d.mts": "bb1b05afccbf59626ff4e004a9cec743c7381a92992640e00b243b8a01795355",
24
- "check/coda/adapters/plugin-test-host.mjs": "a48b6fb7df7b8ad1a4775bf18a1eb414d74ab83f7798ddaa1e2e6032ff4607a7",
24
+ "check/coda/adapters/plugin-test-host.d.mts": "d0592b00e898da7abae8d48b0ee6f72cd807ac9b7a7e8d185148904082850575",
25
+ "check/coda/adapters/plugin-test-host.mjs": "7c8e5ee46792181bfd3b2f4d67d1ac6844c64c2af678655308cfdeb5ecf84c42",
25
26
  "check/coda/adapters/process-relay.mjs": "5d379bd7ad07138d69c7accbe769d71294843399539bdf1fab8b6a1ddf13b9d8",
26
27
  "check/coda/components/composers/contributions.mjs": "43d3e15fb1f63b7b5c20716030d9537613809ed5cc2fb466a3678bfa308f9f92",
27
28
  "check/coda/components/concurrency-groups/schemas.mjs": "3c422044c637dee10565fb1b8bdc75b9c6a31e3b600ed223b7e5e345e1baf092",
@@ -29,10 +30,10 @@
29
30
  "check/coda/components/plugins/contribution-points.mjs": "2dade9fe4f3fa2b4e89f49a1ac4378ab2621e5ac542eb175967091f04568b45c",
30
31
  "check/coda/components/plugins/git-contributions.mjs": "532917cd3ec45e12535e9e6c206ae14fa598bebc789ab0c8f15609d1699fa1cd",
31
32
  "check/coda/components/plugins/model-contributions.mjs": "018a7157954b2326887ba1a780b37d3beb33338e41a28936b313562c2939d563",
32
- "check/coda/components/plugins/plugin-extensions.mjs": "f7c277f5e885127ee9ed12c1894eb8e4415d7cd7f51f712cbf3316304d6e7215",
33
+ "check/coda/components/plugins/plugin-extensions.mjs": "4b0f5379de25c464b044dbfc293e421f4f0c36b16bd4742d90ed82f5bd7d7162",
33
34
  "check/coda/components/plugins/plugin-icons.mjs": "ec29cadce4948ecacabfe911a2ceb45414b96e28971358acbc4e952bedc78e1a",
34
- "check/coda/components/plugins/plugin-rules.mjs": "1f1ec7504d41b0ac0b6f05d02ca5a5e964c1b90cd9cc5af1b9c4f9edb25ff040",
35
- "check/coda/components/plugins/plugin-source-rules.mjs": "6e69d7ecdb3180bbf28a6f3ae11c5bb067dea33b2904324989b9a13d7162f937",
35
+ "check/coda/components/plugins/plugin-rules.mjs": "32cf0a3956a646e0c18cea62da4c0969af9f4c6f60ab1a4970937163a13a878a",
36
+ "check/coda/components/plugins/plugin-source-rules.mjs": "d3bf278c4fb35e99f602ea81419dff0ad0c2753ee20e6e3b648d2fecf82da44f",
36
37
  "check/coda/components/plugins/process-contributions.mjs": "6d39a904f52956b87c04351398f79a4fc34981fa01453195bd7a3b9f2c5d237b",
37
38
  "check/coda/components/plugins/skill-document.mjs": "153ad3c096c7c9b7774bcf7dcc0ba603c962ee1ac8697c8a71e3f2c9ba9c92e6",
38
39
  "check/coda/components/prompt-recovery/prompt-recovery.mjs": "25477742af8a9134ae343af6ab702926692bdd8dd07844f3cba47e8b702c0e49",
@@ -54,6 +55,7 @@
54
55
  "check/coda/resources/plugins/resources/panels/panels.mjs": "37ffc6a4ede3e4612cd13cf1a973a90892f8ce7e8a0f055e7cfe86313aae5224",
55
56
  "check/coda/resources/plugins/resources/panels/rules.mjs": "a433d4e84138937297ec31a8912aab7bd48bba4b66da3a10978edb1367613c96",
56
57
  "check/coda/resources/plugins/resources/panels/sign-in.mjs": "6eb016ef9a7f8aa03e0f4b2fa35ce139b8b1ff0deb4ec6e6a34139aed4f2841a",
57
- "check/coda/builtin.json": "cee3567d4926e63cc15f82642befbdb93259e7e0198c9e70cd32e9d2cfae321b"
58
+ "check/coda/builtin.json": "0eb63a693c912f7e339cda0b76b85110f881784b92c7788c8ea6d0a1c7468ade",
59
+ "check/coda/api-surface.txt": "7ce7dca260719ef0f756b0f73eceec447eacec6d966d9671b312e15c7ec4034a"
58
60
  }
59
61
  }
package/check/index.mjs CHANGED
@@ -1,25 +1,29 @@
1
- // The contract check of one plugin directory: the manifest and its workflows, then each agent's handshake (and with `live`, a
1
+ // The contract check of one plugin directory: the manifest and its workflows, its module if it has one, then each agent's handshake (and with `live`, a
2
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';
6
+ import { checkLevel } from './level.mjs';
6
7
  import { checkManifest } from './manifest.mjs';
8
+ import { checkModule } from './module.mjs';
7
9
  import { checkPanel } from './panel.mjs';
8
10
  import { checkWorkflows } from './workflows.mjs';
9
11
  import { Report } from './report.mjs';
10
12
 
11
- // `agent`: only this agent of the plugin; `manifestOnly`: nothing is run; `live`: one turn each with `prompt`.
13
+ // `agent`: only this agent of the plugin; `manifestOnly`: nothing is run (not its module either); `live`: one turn each with `prompt`.
12
14
  export async function checkPlugin(dir, { agent: only = null, manifestOnly = false, live = false, prompt, limits } = {}) {
13
15
  const pluginDir = resolve(dir), report = new Report();
14
16
  const plugin = checkManifest(pluginDir, report.scope('manifest'));
15
17
  if (!plugin) return { report, plugin };
16
18
  await checkWorkflows(plugin, report.scope('manifest'));
19
+ checkLevel({ checked: plugin, say: report.scope('manifest'), note: report.scope('note') });
17
20
  const agents = only ? plugin.agents.filter(a => a.id === only) : plugin.agents;
18
21
  if (only && !agents.length) report.scope('manifest').fail('options.agent', `清单里没有能检查的 Agent ${only}`);
19
22
  if (manifestOnly) {
20
23
  if (agents.length || plugin.panels.length) report.scope('handshake').skip('options.manifest', '只查清单(--manifest):不启动 Agent、不读资源');
21
24
  return { report, plugin };
22
25
  }
26
+ if (plugin.plugin.main) await checkModule({ checked: plugin, say: report.scope('module'), note: report.scope('note'), limit: limits?.activate });
23
27
  for (const agent of agents) await checkAgent({ agent, checked: plugin, live, prompt, limits, say: level => report.scope(level, `Agent ${agent.id}`) });
24
28
  if (!only) for (const panel of plugin.panels) await checkPanel({ panel, checked: plugin, say: report.scope('handshake', `${panel.format === 'resources' ? '资源类型' : '面板'} ${panel.id}`) });
25
29
  return { report, plugin };
package/check/init.mjs ADDED
@@ -0,0 +1,33 @@
1
+ // `coda-plugin-check init <目录> [--template module|agent|resource]`: a template copied into a new directory, named after it.
2
+ import { cpSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const TEMPLATES = ['module', 'agent', 'resource'];
7
+ const ROOT = fileURLToPath(new URL('../templates', import.meta.url));
8
+ // A plugin ID: the directory's name is the plugin's.
9
+ const ID = /^[a-z][a-z0-9-]{0,39}$/;
10
+
11
+ // Copies `template` into `target` (absent or empty), and says the plugin's `name`, the protocol prefix of the module template's
12
+ // `<name>/note@1` and the domain of its event `note_<name>.added` (event names are one machine's: `_` for `-`), the directory's.
13
+ // Returns the plugin ID.
14
+ export function init(target, template) {
15
+ if (!TEMPLATES.includes(template)) throw new Error(`没有模板「${template}」,可选 ${TEMPLATES.join('、')}`);
16
+ const dir = resolve(target), id = basename(dir);
17
+ if (!ID.test(id)) throw new Error(`目录名「${id}」要作插件 ID:小写字母开头,只用小写字母、数字和 -,至多 40 个字符`);
18
+ if (existsSync(dir) && (!statSync(dir).isDirectory() || readdirSync(dir).length)) throw new Error(`${target} 不是空目录,不往里复制`);
19
+ const source = join(ROOT, template);
20
+ const was = JSON.parse(readFileSync(join(source, 'package.json'), 'utf8')).name;
21
+ cpSync(source, dir, { recursive: true, filter: path => basename(path) !== 'node_modules' });
22
+ for (const file of ['package.json', 'package-lock.json', 'main.mjs', 'test/main.test.mjs']) {
23
+ const path = join(dir, file);
24
+ if (!existsSync(path)) continue;
25
+ const text = readFileSync(path, 'utf8').replaceAll(`${was}/note@1`, `${id}/note@1`).replaceAll(`note_${was}.added`, `note_${id.replaceAll('-', '_')}.added`);
26
+ if (!file.endsWith('.json')) { writeFileSync(path, text); continue; }
27
+ const json = JSON.parse(text);
28
+ json.name = id;
29
+ if (json.packages?.['']) json.packages[''].name = id;
30
+ writeFileSync(path, `${JSON.stringify(json, null, 2)}\n`);
31
+ }
32
+ return id;
33
+ }
@@ -0,0 +1,70 @@
1
+ // The API Level a plugin needs, reckoned from what it uses (check/coda/api-surface.txt: every item Coda offers plugins, with the
2
+ // Level it came in) against its `engines.coda`. What the manifest and its protocols name is certain; what is read from the text of
3
+ // its files (`coda.<member>`, `ctx.<member>`, `window.coda.<member>`) may be a misreading, and is only remarked on.
4
+ // Also lists the trial surface it uses: the permission groups and module interfaces that may change from one Coda to the next.
5
+ import { readdirSync, readFileSync } from 'node:fs';
6
+ import { extname, join } from 'node:path';
7
+ import { wantedLevel } from './coda/components/plugins/plugin-extensions.mjs';
8
+
9
+ // The lines of a surface (check/coda/api-surface.txt) as item → Level.
10
+ export const parseSurface = text => new Map(text.split('\n').flatMap(line => { const match = /^(\d+) (.+)$/.exec(line); return match ? [[match[2], Number(match[1])]] : []; }));
11
+ const SURFACE = parseSurface(readFileSync(new URL('./coda/api-surface.txt', import.meta.url), 'utf8'));
12
+
13
+ // The source files of a directory by their paths in it, but what npm installed and Git keeps.
14
+ function files(dir, prefix = '') {
15
+ return readdirSync(join(dir, prefix), { withFileTypes: true }).flatMap(entry => {
16
+ const path = join(prefix, entry.name);
17
+ if (entry.isDirectory()) return entry.name === 'node_modules' || entry.name === '.git' ? [] : files(dir, path);
18
+ return entry.isFile() ? [path] : [];
19
+ });
20
+ }
21
+ function scan(dir, views, surface) {
22
+ const items = new Set();
23
+ for (const path of files(dir)) {
24
+ const script = ['.mjs', '.js'].includes(extname(path));
25
+ if (!script && !views.has(path)) continue;
26
+ const text = readFileSync(join(dir, path), 'utf8');
27
+ for (const [, name] of text.matchAll(/\bwindow\.coda\.(\w+)/g)) if (surface.has(`bridge window.coda.${name}`)) items.add(`bridge window.coda.${name}`);
28
+ if (!script) continue;
29
+ // The deepest member of `coda` the surface has: `coda.settings.get`, else `coda.settings`.
30
+ for (const [, name, sub] of text.matchAll(/(?<!window\.)\bcoda\.(\w+)(?:\.(\w+))?/g))
31
+ for (const item of [`module coda.${name}.${sub}`, `module coda.${name}`]) if (surface.has(item)) { items.add(item); break; }
32
+ for (const [, name] of text.matchAll(/\bctx\.(\w+)/g)) if (surface.has(`module ctx.${name}`)) items.add(`module ctx.${name}`);
33
+ }
34
+ return items;
35
+ }
36
+ // What the manifest names: its keys, their keys under them, and what a protocol's `uses` and its own definitions are made of.
37
+ function named({ manifest, plugin }, surface) {
38
+ const items = new Set();
39
+ for (const [key, value] of Object.entries(manifest)) {
40
+ items.add(`manifest ${key}`);
41
+ if (value && typeof value === 'object' && !Array.isArray(value)) for (const sub of Object.keys(value)) items.add(`manifest ${key}.${sub}`);
42
+ }
43
+ for (const [kind, groups] of Object.entries(plugin.uses ?? {})) { items.add(kind); for (const group of groups) items.add(`${kind} ${group}`); }
44
+ for (const definition of plugin.protocols ?? []) {
45
+ for (const key of Object.keys(definition)) items.add(`definition ${key}`);
46
+ for (const section of ['permissions', 'operations', 'events', 'streams'])
47
+ for (const entry of Object.values(definition[section] ?? {})) for (const key of Object.keys(entry)) items.add(`definition ${section}.${key}`);
48
+ }
49
+ return [...items].filter(item => surface.has(item));
50
+ }
51
+
52
+ // `checked`: the plugin as the manifest level read it. `say`: the manifest level's; `note`: the notes'. `surface`: the items and
53
+ // their Levels, as this Coda has them unless given.
54
+ export function checkLevel({ checked, say, note, surface = SURFACE }) {
55
+ const { plugin } = checked;
56
+ const certain = named(checked, surface), read = [...scan(plugin.dir, new Set(plugin.views.map(view => view.entry)), surface)];
57
+ const highest = items => items.reduce((top, item) => !top || surface.get(item) > surface.get(top) ? item : top, null);
58
+ const written = wantedLevel(plugin.engines) ?? undefined, top = highest([...certain, ...read]);
59
+ const need = top ? surface.get(top) : 0;
60
+ if (written === undefined) say.warn('manifest.level', `没写 engines.coda:用到的项最高 Level ${need}${top ? `(${top})` : ''},该写 "engines": { "coda": ${need} }`);
61
+ else {
62
+ const short = highest(certain.filter(item => surface.get(item) > written));
63
+ if (short) say.fail('manifest.level', `用到 ${short}(Level ${surface.get(short)}),engines.coda 至少写 ${surface.get(short)}(现写 ${written})`);
64
+ for (const item of read.filter(item => surface.get(item) > written)) say.warn('manifest.level-text', `文件里出现 ${item}(Level ${surface.get(item)}),engines.coda 写 ${written}:扫描文本得来,可能认错;没错的话至少写 ${surface.get(item)}`);
65
+ if (!short && !read.some(item => surface.get(item) > written)) say.pass('manifest.level', `engines.coda ${written},用到的项最高 Level ${need}`);
66
+ }
67
+ for (const [kind, groups] of Object.entries(plugin.uses ?? {}))
68
+ for (const group of groups) if (checked.definitionOf(kind)?.permissions?.[group]?.trial) note.info('note.trial', `用到试行面:${kind} 的权限组 ${group},随 Coda 版本可能变`);
69
+ for (const item of [...certain, ...read].filter(item => item.startsWith('module '))) note.info('note.trial', `用到试行面:模块接口 ${item.slice('module '.length)},随 Coda 版本可能变`);
70
+ }
@@ -11,6 +11,7 @@ import { inflateSync } from 'node:zlib';
11
11
  import './coda/application/contributions.mjs';
12
12
  import { HOST_PROTOCOLS } from './coda/application/host-protocols.mjs';
13
13
  import shipped from './coda/builtin.json' with { type: 'json' };
14
+ import { CORE_PROTOCOLS } from '@coda-console/protocol/protocol';
14
15
  import { manifestProblem } from '@coda-console/protocol/validate';
15
16
  import { offerProblem, protocolDefinition, usesMissing } from './coda/components/plugins/plugin-extensions.mjs';
16
17
  import { choosesModelProviders, pluginEnv, readPlugin, resolveSettings } from './coda/components/plugins/plugin-rules.mjs';
@@ -63,7 +64,8 @@ function pageSize(data) {
63
64
 
64
65
  // Checks the manifest in `dir` and reports under `say` (report.mjs). Returns what the later levels need — the plugin as Coda
65
66
  // reads it, its agents and the panels the resources plugin can read, its settings for every project, the directories of the
66
- // plugins it depends on that are here, and `env(stateDir)`, what Coda gives each of its processes —; null when it is no
67
+ // plugins it depends on that are here, `definitionOf(kind)`, a protocol's definition as far as it is here (its own, Coda's
68
+ // or a plugin's beside it; undefined if not), `definitions`, all of those that are here, and `env(stateDir)`, what Coda gives each of its processes —; null when it is no
67
69
  // plugin, or not of the types it names.
68
70
  export function checkManifest(dir, say) {
69
71
  let manifest;
@@ -150,5 +152,6 @@ export function checkManifest(dir, say) {
150
152
  // The model services of a machine with none, for one that chooses them; the PATH has no directories of Coda's own here.
151
153
  const env = stateDir => pluginEnv({ catalog: given, installed, id: plugin.id, stateDir: id => id === plugin.id ? stateDir : null, settings,
152
154
  providers: choosesModelProviders(plugin) ? {} : null, userPath: process.env.PATH ?? '' });
153
- return { id: plugin.id, manifest, plugin, agents: plugin.agents, panels, settings, dependencies, env };
155
+ return { id: plugin.id, manifest, plugin, agents: plugin.agents, panels, settings, dependencies, env, definitionOf: kind => protocolDefinition(kind, protocols, hosted),
156
+ definitions: [...Object.values(CORE_PROTOCOLS), ...HOST_PROTOCOLS, ...[...protocols.values()].flatMap(each => each.protocols ?? [])] };
154
157
  }
@@ -0,0 +1,133 @@
1
+ // The module level: the plugin's `main` loaded by Coda's own `coda` (the test host, check/coda/adapters/plugin-test-host.mjs),
2
+ // activated, and what it registered set against what the manifest says it implements. Runs between the manifest and the Agent
3
+ // handshake, for a plugin with a `main`.
4
+ import { join } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { protocolHasRecords } from '@coda-console/protocol/protocol';
7
+ import { usesRefusal } from './coda/components/plugins/plugin-extensions.mjs';
8
+ import { createTestHost } from './coda/adapters/plugin-test-host.mjs';
9
+ import { closing, temporary } from './leftovers.mjs';
10
+
11
+ // How long `activate` may take before the check gives up on it.
12
+ export const ACTIVATE_LIMIT = 10_000;
13
+
14
+ const firstLine = e => String(e?.stack ?? e).split('\n')[0];
15
+
16
+ // The members of `coda` the test host has no backend for, each with the failure the test host answers it with (the code, and the
17
+ // text): the same member failing otherwise is the module's own (an argument it gave, a handler it wrote).
18
+ export const NOT_PROVIDED = {
19
+ watch: { message: '测试宿主没有后端,不答 watch' },
20
+ 'services.register': { message: '测试宿主没有后端,不答 serviceRegister' },
21
+ tell: { message: '测试宿主没有后端,不答 tell' },
22
+ api: { message: 'Coda 还在启动,稍后再试' },
23
+ environment: { message: '测试宿主没有后端,不答 environment' },
24
+ 'protocols.resolve': { message: '测试宿主没有后端,不答 provider' },
25
+ 'protocols.upload': { message: '测试宿主没有后端,不答 provider' },
26
+ 'pluginSetup.retry': { code: 'unsupported', message: '测试宿主不提供 coda.pluginSetup' },
27
+ };
28
+
29
+ // `coda` as the module is given it, each function noting which member each error it ends with came out of (the first, when it is
30
+ // passed on): the member that ended the module's `activate` tells a refusal of `coda.on` and a missing backend from the
31
+ // module's own failure.
32
+ function traced(coda, thrown) {
33
+ const wrap = (object, path) => Object.fromEntries(Object.entries(object).map(([key, value]) => {
34
+ const member = path ? `${path}.${key}` : key;
35
+ if (typeof value === 'function') return [key, (...args) => {
36
+ const fail = error => { if (!thrown.has(error)) thrown.set(error, member); throw error; };
37
+ try { const result = value.apply(object, args); return result instanceof Promise ? result.catch(fail) : result; } catch (error) { return fail(error); }
38
+ }];
39
+ return [key, value && typeof value === 'object' ? wrap(value, member) : value];
40
+ }));
41
+ return wrap(coda, '');
42
+ }
43
+
44
+ // Gives `work` `limit` milliseconds, then fails with it.
45
+ function within(work, limit) {
46
+ let timer;
47
+ return Promise.race([work, new Promise((_, reject) => { timer = setTimeout(reject, limit, new Error(`${limit / 1000} 秒没完成`)); })]).finally(() => clearTimeout(timer));
48
+ }
49
+
50
+ // `checked`: the plugin as the manifest level read it (manifest.mjs checkManifest). `limit`: how long `activate` and `deactivate`
51
+ // may each take.
52
+ export async function checkModule({ checked, say, note, limit = ACTIVATE_LIMIT }) {
53
+ const { plugin } = checked, main = plugin.main;
54
+ const state = temporary('coda-plugin-check-state-');
55
+ // Others' definitions of the protocols it uses, for the event groups its `coda.on` may name. The test host takes them for
56
+ // those alone: its record types are Coda's, the plugin's own and its kinds that stay on this machine, so it cannot hand out a
57
+ // dependency's records (registering the definitions among the plugin's own protocols would let it publish their events too).
58
+ const used = Object.keys(plugin.uses ?? {}).filter(kind => !plugin.protocols?.some(one => one.name === kind));
59
+ const protocols = used.map(checked.definitionOf).filter(Boolean);
60
+ const absent = used.filter(kind => !checked.definitionOf(kind));
61
+ const host = createTestHost({ plugin: { id: plugin.id, path: plugin.dir, state: state.dir, protocols: plugin.protocols,
62
+ protocolImplementations: plugin.protocolImplementations, processes: plugin.processes, uses: plugin.uses }, settings: checked.settings, protocols });
63
+ const done = closing(() => host.close());
64
+ const thrown = new Map();
65
+ try {
66
+ let module;
67
+ try { module = await import(pathToFileURL(join(plugin.dir, main)).href); }
68
+ catch (e) { return say.fail('module.load', `main ${main} 加载不了:${firstLine(e)}`); }
69
+ if (typeof module.activate !== 'function') return say.fail('module.activate', `main ${main} 没有导出 activate(coda)`);
70
+ let activated = false;
71
+ try {
72
+ await within(module.activate(traced(host.coda, thrown)), limit);
73
+ activated = true;
74
+ } catch (e) {
75
+ const from = thrown.get(e), lacking = NOT_PROVIDED[from];
76
+ const unsettled = from === 'on' || from === 'get' || from === 'list' ? unfinished(checked, e, from, absent, used) : null;
77
+ if (unsettled?.fail) say.fail(...unsettled.fail);
78
+ else if (unsettled) say.warn('module.registered', `未完成核对:${unsettled.warn}`);
79
+ else if (lacking && e.code === lacking.code && e.message === lacking.message) {
80
+ note.info('note.host', `模块用到测试宿主不提供的能力 coda.${from},模块一级只验到这里`);
81
+ say.warn('module.registered', `未完成核对:模块用到测试宿主不提供的能力 coda.${from},登记的操作没有拿去与清单比对`);
82
+ } else say.fail('module.activate', `activate 失败:${firstLine(e)}`);
83
+ }
84
+ if (activated) {
85
+ say.pass('module.activate', `activate 完成:${main}`);
86
+ compare(checked, host.registered(), say);
87
+ }
88
+ // As Coda's host ends a module before it goes, once it has been activated: what it started ends with it. One that did not
89
+ // finish activating is not called; closing the test host ends what it started.
90
+ if (activated) try { await within(module.deactivate?.(), limit); } catch (e) { say.fail('module.deactivate', `deactivate 失败:${firstLine(e)}`); }
91
+ } finally { done(); await host.close(); state.remove(); }
92
+ }
93
+
94
+ // A `coda.on` the test host refused, or a `coda.get`/`coda.list` of a kind it does not have, judged by the definitions that are
95
+ // here: a failure when they settle it (`{ fail: [rule, message] }`), what the check could not tell when it depends on one that
96
+ // is not (`{ warn }`), null when it is neither (the module's own failure). `absent`: the protocols it uses whose definition is
97
+ // not here; `used`: those it uses that are not its own.
98
+ function unfinished({ plugin, definitions, definitionOf }, e, from, absent, used) {
99
+ if (from === 'on') {
100
+ if (e.code !== 'forbidden') return null;
101
+ const name = /没有订事件 (\S+):/.exec(e.message)?.[1];
102
+ // An event is one protocol's, as far as the definitions here say: its group is not among those used, whoever else is missing.
103
+ if (definitions.some(one => one.events && Object.hasOwn(one.events, name)) || !absent.length) return { fail: ['module.events', `coda.on 订了不在自己事件组里的事件:${e.message}`] };
104
+ return { warn: `协议 ${absent.join('、')} 的定义不在本地,coda.on 被拒可能只是不认识它的事件组` };
105
+ }
106
+ const kind = /^没有协议:(.+)$/.exec(e.message)?.[1];
107
+ if (e.code !== 'not_found' || kind === undefined) return null;
108
+ const definition = definitionOf(kind);
109
+ if (!definition) return used.includes(kind) ? { warn: `协议 ${kind} 的定义不在本地,查不了 coda.${from} 读它的记录是不是已获授权` } : null;
110
+ if (!protocolHasRecords(definition)) return null;
111
+ const refusal = usesRefusal(plugin, kind, 'read', definition);
112
+ return refusal ? { fail: ['module.activate', `activate 失败:${refusal}`] } : { warn: `测试宿主登记不了已获授权的记录类型 ${kind},coda.${from} 之后没有核对` };
113
+ }
114
+
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`.)
118
+ function compare({ plugin, definitionOf }, { operations }, say) {
119
+ const registered = new Set(operations.map(({ kind, operation }) => `${kind} ${operation}`));
120
+ let problems = 0, incomplete = false;
121
+ for (const { kind, commands } of plugin.protocolImplementations ?? []) {
122
+ const definition = definitionOf(kind);
123
+ if (!definition) { incomplete = true; say.warn('module.registered', `未完成核对:协议 ${kind} 的定义不在本地,查不了模块登记了它的哪些操作`); continue; }
124
+ // `codaOnly`: Coda's own protocol's operation that Coda alone answers.
125
+ 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
+ }
128
+ for (const { kind, operation } of operations) {
129
+ const definition = definitionOf(kind);
130
+ if (definition && !Object.hasOwn(definition.operations ?? {}, operation)) { problems++; say.fail('module.unlisted', `模块登记了 ${kind} 的操作 ${operation},协议定义里没有这个操作`); }
131
+ }
132
+ if (!problems && !incomplete) say.pass('module.registered', `模块登记了 ${operations.length} 个操作,与清单一致`);
133
+ }
package/check/report.mjs CHANGED
@@ -1,6 +1,6 @@
1
- // What a check found, in the order found: each line a level (清单, 握手, 一轮), what it is about (the plugin, an agent, a panel),
1
+ // What a check found, in the order found: each line a level (清单, 模块, 握手, 一轮, 说明), what it is about (the plugin, an agent, a panel),
2
2
  // whether it passed, failed, was skipped or is worth a look (warn, info), a rule ID the tests name, and a line of Chinese.
3
- export const LEVELS = { manifest: '清单', handshake: '握手', live: '一轮' };
3
+ export const LEVELS = { manifest: '清单', module: '模块', handshake: '握手', live: '一轮', note: '说明' };
4
4
  const MARKS = { pass: '✓', fail: '✗', warn: '!', skip: '-', info: '·' };
5
5
 
6
6
  export class Report {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coda-console/plugin-check",
3
- "version": "0.8.23",
3
+ "version": "0.8.25",
4
4
  "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源类型(与旧的面板)。",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -11,12 +11,17 @@
11
11
  "engines": {
12
12
  "node": ">=24"
13
13
  },
14
+ "exports": {
15
+ "./types": "./check/coda/adapters/plugin-test-host.d.mts",
16
+ "./test-host": "./check/coda/adapters/plugin-test-host.mjs"
17
+ },
14
18
  "bin": {
15
19
  "coda-plugin-check": "bin/check.mjs"
16
20
  },
17
21
  "files": [
18
22
  "bin",
19
- "check"
23
+ "check",
24
+ "templates"
20
25
  ],
21
26
  "scripts": {
22
27
  "test": "node --test 'test/**/*.test.mjs'"
@@ -24,7 +29,7 @@
24
29
  "dependencies": {
25
30
  "@0dep/piso": "5.2.0",
26
31
  "@agentclientprotocol/sdk": "2.6.0",
27
- "@coda-console/protocol": "6.14.0",
32
+ "@coda-console/protocol": "6.15.0",
28
33
  "ajv": "8.20.0",
29
34
  "yaml": "2.9.1"
30
35
  },