@coda-console/plugin-check 0.8.25 → 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.
@@ -0,0 +1,168 @@
1
+ // Coda's own protocol of the friends of this machine and the signed records they keep, `coda/accord@1`: one record, this
2
+ // machine's (`local`), saying the key its records are signed with and the channels of its friends (components/network/friends.mjs),
3
+ // and its query `records`, the records of a kind signed by a key (AIP-01, domain/accord.mjs), this machine's and its
4
+ // friends'. What it does — publish a record, take a friend's invitation, exchange bindings, remove a friend — are doing
5
+ // operations, done by the friends' side of the call kernel (components/network/accord-operations.mjs). Nothing of a private
6
+ // key or of an invitation's `authKey` is ever said. The record is read through (Protocols.serve), nothing is kept of it, it
7
+ // is no section and not in the record directory: another machine's is not read. Its revision moves with the friends' count of
8
+ // changes too, as the records a query reads are not in the record.
9
+ // Only what a plugin's contract may carry is imported here (scripts/plugin-contract.mjs): the doing side is kept apart.
10
+ import { createHash } from 'node:crypto';
11
+ import { requireCondition as check } from '../domain/errors.mjs';
12
+ import { isAccordKind } from '../domain/accord.mjs';
13
+ import { canonical } from '../domain/values.mjs';
14
+
15
+ export const ACCORD = 'coda/accord@1';
16
+ export const ACCORD_LOCAL_ID = 'local';
17
+ export const ACCORD_SIDE = 'friends';
18
+ // What a record published says at most, as UTF-8 JSON (the signed record is bounded as a whole: domain/accord.mjs).
19
+ export const MAX_ACCORD_BODY_BYTES = 64 * 1024;
20
+ export const MAX_ACCORD_RECORDS_LIMIT = 200;
21
+ // What a read gives at most, as UTF-8 JSON: the envelope of a call is 1 MiB.
22
+ export const MAX_ACCORD_RESPONSE_BYTES = 768 * 1024;
23
+
24
+ const KEY = /^ed25519:[0-9a-f]{64}$/;
25
+ /** A key a record is signed with, `ed25519:<64 hex>`. */
26
+ export const isAccordAuthor = author => typeof author === 'string' && KEY.test(author);
27
+
28
+ const text = (schema = {}) => ({ type: 'string', minLength: 1, ...schema });
29
+ const time = { type: 'integer', minimum: 0 };
30
+
31
+ export const ACCORD_PROTOCOL = {
32
+ kind: ACCORD,
33
+ title: '好友与 Accord',
34
+ side: ACCORD_SIDE,
35
+ spec: { type: 'object', properties: { author: text() }, required: ['author'], additionalProperties: false },
36
+ status: {
37
+ type: 'object',
38
+ properties: {
39
+ friends: {
40
+ type: 'array',
41
+ items: {
42
+ type: 'object',
43
+ properties: {
44
+ node: text(), mode: text(), linkId: text(), scope: text(), peerNode: text(), author: { type: ['string', 'null'] },
45
+ bound: { type: 'boolean' }, conflict: { type: 'boolean' }, createdAt: time, updatedAt: time,
46
+ },
47
+ required: ['node', 'mode', 'scope', 'author', 'bound', 'createdAt', 'updatedAt'],
48
+ additionalProperties: false,
49
+ },
50
+ },
51
+ },
52
+ required: ['friends'],
53
+ additionalProperties: false,
54
+ },
55
+ operations: {
56
+ // The records of a kind, newest version first, of a key if given; `truncated` when more than `limit` (or than a call may
57
+ // carry) are.
58
+ records: { safe: true,
59
+ input: {
60
+ type: 'object',
61
+ properties: { kind: text({ maxLength: 129 }), author: text({ maxLength: 80 }), limit: { type: 'integer', minimum: 1, maximum: MAX_ACCORD_RECORDS_LIMIT } },
62
+ required: ['kind'],
63
+ additionalProperties: false,
64
+ },
65
+ result: {
66
+ type: 'object',
67
+ properties: {
68
+ records: {
69
+ type: 'array',
70
+ items: {
71
+ type: 'object',
72
+ properties: { author: text(), kind: text(), id: text(), version: time, body: { type: 'object' }, local: { type: 'boolean' } },
73
+ required: ['author', 'kind', 'id', 'version', 'body', 'local'],
74
+ additionalProperties: false,
75
+ },
76
+ },
77
+ truncated: { type: 'boolean' },
78
+ },
79
+ required: ['records', 'truncated'],
80
+ additionalProperties: false,
81
+ } },
82
+ // A record of this machine's key written and signed, for the keys in `audience` (or `'public'`).
83
+ publish: {
84
+ input: {
85
+ type: 'object',
86
+ properties: {
87
+ kind: text({ maxLength: 129 }), id: text({ maxLength: 200 }), body: { type: 'object' },
88
+ audience: { type: 'array', maxItems: 500, items: text({ maxLength: 80 }) },
89
+ },
90
+ required: ['kind', 'id', 'body', 'audience'],
91
+ additionalProperties: false,
92
+ },
93
+ result: {
94
+ type: 'object',
95
+ properties: { author: text(), kind: text(), id: text(), version: time, audience: { type: 'array', items: text() } },
96
+ required: ['author', 'kind', 'id', 'version', 'audience'],
97
+ additionalProperties: false,
98
+ } },
99
+ // A friend's invitation to its tailnet taken up (`Friends.joinLink`); its `authKey` is not said again.
100
+ accept: {
101
+ input: {
102
+ type: 'object',
103
+ properties: {
104
+ linkId: text({ maxLength: 100 }), scope: text({ maxLength: 200 }), control: text({ maxLength: 500 }), authKey: text({ maxLength: 500 }),
105
+ hostname: text({ maxLength: 100 }), peerNode: text({ maxLength: 100 }),
106
+ },
107
+ required: ['linkId', 'control', 'authKey'],
108
+ additionalProperties: false,
109
+ },
110
+ result: { type: 'object', properties: { node: text() }, required: ['node'], additionalProperties: false } },
111
+ // Both bindings exchanged with a friend (`Friends.handshake`).
112
+ handshake: {
113
+ input: { type: 'object', properties: { node: text({ maxLength: 120 }), peerNode: text({ maxLength: 100 }) }, required: ['node'], additionalProperties: false },
114
+ result: {
115
+ type: 'object',
116
+ properties: { node: text(), author: text(), peerNode: text() },
117
+ required: ['node', 'author'],
118
+ additionalProperties: false,
119
+ } },
120
+ // A friend no longer followed or kept (`Friends.remove`).
121
+ remove: {
122
+ input: { type: 'object', properties: { node: text({ maxLength: 120 }) }, required: ['node'], additionalProperties: false },
123
+ result: { type: 'object', properties: { ok: { const: true } }, required: ['ok'], additionalProperties: false } },
124
+ },
125
+ // What a plugin may ask for in its `uses` (docs/plugins.md「用到的权限」), on trial while the protocol is not stable.
126
+ permissions: {
127
+ read: { title: '查看本机的 Accord 身份、好友列表与好友发来的记录', trial: true, read: true, operations: ['records'] },
128
+ publish: { title: '向好友发布 Accord 签名记录', trial: true, operations: ['publish'] },
129
+ manage: { title: '接受好友邀请、完成互认或移除好友', trial: true, operations: ['accept', 'handshake', 'remove'] },
130
+ },
131
+ };
132
+
133
+ const record = friends => {
134
+ const spec = { author: friends.author() }, status = { friends: friends.list() };
135
+ return { kind: ACCORD, id: ACCORD_LOCAL_ID, provider: 'coda', createdAt: new Date(0).toISOString(), creationSequence: 0, spec, status,
136
+ revision: `local:${createHash('sha256').update(canonical([spec, status, friends.changeSeq])).digest('hex').slice(0, 16)}` };
137
+ };
138
+ export const accordRecords = friends => ({
139
+ get: id => id === ACCORD_LOCAL_ID ? record(friends) : null,
140
+ list: () => [record(friends)],
141
+ });
142
+
143
+ // Newest version first, then by key and ID, so that what is cut off is always the oldest.
144
+ const newest = (a, b) => b.version - a.version || (a.author < b.author ? -1 : a.author > b.author ? 1 : 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
145
+
146
+ // Its query through the unified call (components/protocols/calls.mjs `handle`): `records`, read from the friends, for this
147
+ // machine's callers alone: the record's ID is the same on every machine, so a call another backend sends is refused.
148
+ export function accordQueries(calls, { friends }) {
149
+ calls.handle(ACCORD, 'records', ({ input }) => {
150
+ check(isAccordKind(input.kind) && input.kind !== 'binding', 'invalid_input', '记录种类不合法');
151
+ check(input.author === undefined || isAccordAuthor(input.author), 'invalid_input', 'author 须为 ed25519:<64 位十六进制>');
152
+ const limit = input.limit ?? MAX_ACCORD_RECORDS_LIMIT;
153
+ const all = friends.read(input.kind, input.author ? { author: input.author } : {})
154
+ .map(({ record: one, local }) => ({ author: one.author, kind: one.kind, id: one.id, version: one.version, body: one.body ?? {}, local }))
155
+ .sort(newest);
156
+ // Whole the answer is at most `MAX_ACCORD_RESPONSE_BYTES` as JSON: its frame, each record and the comma before it; one
157
+ // record is always given.
158
+ const records = [];
159
+ let size = Buffer.byteLength('{"records":[],"truncated":false}', 'utf8');
160
+ for (const one of all.slice(0, limit)) {
161
+ const next = size + (records.length > 0 ? 1 : 0) + Buffer.byteLength(JSON.stringify(one), 'utf8');
162
+ if (records.length > 0 && next > MAX_ACCORD_RESPONSE_BYTES) break;
163
+ records.push(one);
164
+ size = next;
165
+ }
166
+ return { records, truncated: records.length < all.length };
167
+ }, { admit: ({ caller }) => check(caller === calls.self(), 'forbidden', '好友与 Accord 记录只在本机读取') });
168
+ }
@@ -0,0 +1,97 @@
1
+ // Coda's own protocol of the tokens the turns hosted here used, `coda/usage@1`: one record, this machine's (`local`), and its
2
+ // query `buckets`, the counts kept per UTC ten minutes, agent and model (domain/usage.mjs, usage_buckets). Nothing but the counts
3
+ // is said: no session, directory, text or cost. The record is read through (Protocols.serve), nothing is kept of it, it is
4
+ // no section and not in the record directory: another machine's is not read.
5
+ import { createHash } from 'node:crypto';
6
+ import { requireCondition as check } from '../domain/errors.mjs';
7
+ import { USAGE_BUCKET_MS } from '../domain/usage.mjs';
8
+ import { canonical } from '../domain/values.mjs';
9
+
10
+ export const USAGE = 'coda/usage@1';
11
+ export const USAGE_LOCAL_ID = 'local';
12
+ export const MAX_USAGE_SPAN_MS = 90 * 24 * 60 * 60 * 1000;
13
+ // About a fortnight of active buckets at a read, and the envelope of a call is far under 1 MiB even with 200-character
14
+ // four-byte model names.
15
+ export const MAX_USAGE_LIMIT = 500;
16
+
17
+ const time = { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER };
18
+
19
+ export const USAGE_PROTOCOL = {
20
+ kind: USAGE,
21
+ title: '用量',
22
+ spec: { type: 'object', properties: { bucketMs: { type: 'integer', minimum: 1 } }, required: ['bucketMs'], additionalProperties: false },
23
+ status: { type: 'object', additionalProperties: false },
24
+ operations: {
25
+ // The buckets starting in `[from, to)`, newest first, of an agent and a model if given; `truncated` when more than `limit` are.
26
+ buckets: { safe: true,
27
+ input: {
28
+ type: 'object',
29
+ properties: {
30
+ from: time,
31
+ to: time,
32
+ agent: { type: 'string', minLength: 1, maxLength: 100 },
33
+ model: { type: 'string', minLength: 1, maxLength: 200 },
34
+ limit: { type: 'integer', minimum: 1, maximum: MAX_USAGE_LIMIT },
35
+ },
36
+ required: ['from', 'to'],
37
+ additionalProperties: false,
38
+ },
39
+ result: {
40
+ type: 'object',
41
+ properties: {
42
+ buckets: {
43
+ type: 'array',
44
+ items: {
45
+ type: 'object',
46
+ properties: {
47
+ start: time,
48
+ agent: { type: 'string', minLength: 1 },
49
+ model: { type: 'string', minLength: 1 },
50
+ input: time,
51
+ output: time,
52
+ cacheRead: time,
53
+ cacheWrite: time,
54
+ turns: time,
55
+ reportedTurns: time,
56
+ },
57
+ required: ['start', 'agent', 'model', 'input', 'output', 'cacheRead', 'cacheWrite', 'turns', 'reportedTurns'],
58
+ additionalProperties: false,
59
+ },
60
+ },
61
+ truncated: { type: 'boolean' },
62
+ },
63
+ required: ['buckets', 'truncated'],
64
+ additionalProperties: false,
65
+ } },
66
+ },
67
+ // What a plugin may ask for in its `uses` (docs/plugins.md「用到的权限」), on trial while the protocol is not stable.
68
+ permissions: {
69
+ read: { title: '查看本机的 Token 用量统计', trial: true, read: true, operations: ['buckets'] },
70
+ },
71
+ };
72
+
73
+ const record = () => {
74
+ const spec = { bucketMs: USAGE_BUCKET_MS }, status = {};
75
+ return { kind: USAGE, id: USAGE_LOCAL_ID, provider: 'coda', createdAt: new Date(0).toISOString(), creationSequence: 0, spec, status,
76
+ revision: `local:${createHash('sha256').update(canonical([spec, status])).digest('hex').slice(0, 16)}` };
77
+ };
78
+ export const usageRecords = () => ({
79
+ get: id => id === USAGE_LOCAL_ID ? record() : null,
80
+ list: () => [record()],
81
+ });
82
+
83
+ // Its query through the unified call (components/protocols/calls.mjs `handle`): `buckets`, read from the store as it keeps them,
84
+ // for this machine's callers alone: the record's ID is the same on every machine, so a call another backend sends is refused.
85
+ export function usageQueries(calls, { store }) {
86
+ calls.handle(USAGE, 'buckets', ({ input }) => {
87
+ check(input.from <= input.to, 'invalid_input', 'from 不能大于 to');
88
+ check(input.to - input.from <= MAX_USAGE_SPAN_MS, 'invalid_input', '单次查询时间跨度不能超过 90 天');
89
+ for (const [name, value] of [['agent', input.agent], ['model', input.model]])
90
+ check(value === undefined || (!value.includes('\0') && value.trim().length > 0), 'invalid_input', `${name} 不能为空或含 NUL`);
91
+ const limit = input.limit ?? MAX_USAGE_LIMIT;
92
+ if (input.from === input.to) return { buckets: [], truncated: false };
93
+ const rows = store.usageBuckets({ from: input.from, to: input.to, agent: input.agent, model: input.model, limit: limit + 1 });
94
+ return { buckets: rows.slice(0, limit).map(row => ({ start: row.bucketStart, agent: row.agent, model: row.model, input: row.input, output: row.output,
95
+ cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, turns: row.turns, reportedTurns: row.reportedTurns })), truncated: rows.length > limit };
96
+ }, { admit: ({ caller }) => check(caller === calls.self(), 'forbidden', '用量统计只在本机读取') });
97
+ }
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.25",
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
  },