@coda-console/plugin-check 0.8.25 → 0.8.26

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.
@@ -332,4 +332,18 @@
332
332
  3 module ctx.record
333
333
  3 module ctx.signal
334
334
  3 module ctx.spawn
335
- level 3
335
+ 4 coda/usage@1
336
+ 4 coda/usage@1 read
337
+ 4 coda/usage@1 read operation buckets
338
+ 4 coda/usage@1 read records
339
+ 5 coda/accord@1
340
+ 5 coda/accord@1 manage
341
+ 5 coda/accord@1 manage operation accept
342
+ 5 coda/accord@1 manage operation handshake
343
+ 5 coda/accord@1 manage operation remove
344
+ 5 coda/accord@1 publish
345
+ 5 coda/accord@1 publish operation publish
346
+ 5 coda/accord@1 read
347
+ 5 coda/accord@1 read operation records
348
+ 5 coda/accord@1 read records
349
+ level 5
@@ -7,6 +7,8 @@
7
7
  // (CORE_PROTOCOLS).
8
8
  import { PLUGIN_PROTOCOL } from '../kernel/plugin-protocol.mjs';
9
9
  import { PROJECT_PROTOCOL } from '../kernel/project-protocol.mjs';
10
+ import { USAGE_PROTOCOL } from '../kernel/usage-protocol.mjs';
11
+ import { ACCORD_PROTOCOL } from '../kernel/accord-protocol.mjs';
10
12
  import { THREAD_PROTOCOL } from '../kernel/thread-protocol.mjs';
11
13
  import { composerType, submissionType } from '../components/composers/schemas.mjs';
12
14
  import { groupType } from '../components/concurrency-groups/schemas.mjs';
@@ -14,4 +16,4 @@ import { WORKFLOW_PROTOCOL, WORKFLOW_RUN_PROTOCOL, withWorkflows } from '../comp
14
16
 
15
17
  // A session's, with the workflows' query and the group that has it (workflow-protocol-definitions.mjs `withWorkflows`).
16
18
  export const THREAD_DEFINITION = withWorkflows(THREAD_PROTOCOL);
17
- export const HOST_PROTOCOLS = [THREAD_DEFINITION, PROJECT_PROTOCOL, PLUGIN_PROTOCOL, WORKFLOW_PROTOCOL, WORKFLOW_RUN_PROTOCOL, composerType, submissionType, groupType];
19
+ export const HOST_PROTOCOLS = [THREAD_DEFINITION, PROJECT_PROTOCOL, PLUGIN_PROTOCOL, USAGE_PROTOCOL, ACCORD_PROTOCOL, WORKFLOW_PROTOCOL, WORKFLOW_RUN_PROTOCOL, composerType, submissionType, groupType];
@@ -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 = 3;
101
+ export const API_LEVEL = 5;
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).
@@ -6,13 +6,13 @@ import { derivedUUID } from '../../domain/values.mjs';
6
6
 
7
7
  // Where a kind's records are, said once for every kind (Protocols `register` reads it). The kinds only this machine keeps:
8
8
  // Coda's composers and what is submitted through them, the runs of its posts to sessions, and the kinds it serves whole
9
- // from its own tables: `coda/thread@1`, `coda/project@1`, `coda/card@1`, `coda/plugin@1` and the workflows' `coda/workflow@1`
9
+ // from its own tables: `coda/thread@1`, `coda/project@1`, `coda/card@1`, `coda/plugin@1`, `coda/usage@1`, `coda/accord@1` (this machine's friends and its key, each machine its own) and the workflows' `coda/workflow@1`
10
10
  // and `coda/workflow-run@1` (one of another backend is found by asking the space: mirror.mjs `place`). `coda/session@1` is shared (Coda's sessions are served beside
11
11
  // it, a plugin's external sessions are written in the record directory). They are never in the record directory, and no
12
12
  // plugin writes one. Every other kind, every one a plugin defines among them, is shared: its records are this machine's rows of
13
13
  // the record directory, which the other backends of a space copy.
14
14
  export const LOCAL_KINDS = new Set(['coda/composer@1', 'coda/submission@1', 'coda/run@1', 'coda/thread@1', 'coda/project@1', 'coda/card@1',
15
- 'coda/plugin@1', 'coda/workflow@1', 'coda/workflow-run@1']);
15
+ 'coda/plugin@1', 'coda/usage@1', 'coda/accord@1', 'coda/workflow@1', 'coda/workflow-run@1']);
16
16
  // `list(kind, { scope?, id?, labels? })`: this machine's records (`local`) or this machine's and the others' (`available`,
17
17
  // unsaid), all of them, those of an ID, or those whose labels have each of these values (`labels`, as Kubernetes' equality
18
18
  // selector: nothing but equality).
@@ -1,6 +1,6 @@
1
1
  {
2
- "commit": "46a06458a98d290d4cc69dfdfcf1880889d0bfcf",
3
- "apiLevel": 3,
2
+ "commit": "6152218e2afb04e9afba3fad4c312e5f155a1d56",
3
+ "apiLevel": 5,
4
4
  "packages": {
5
5
  "@0dep/piso": "5.2.0",
6
6
  "@agentclientprotocol/sdk": "2.6.0",
@@ -10,9 +10,9 @@
10
10
  },
11
11
  "files": {
12
12
  "check/coda/application/contributions.mjs": "861c363d06cdabfc4ce15435126fbc7ad7dafd3c93ca2ad9e9534a6f5a237942",
13
- "check/coda/application/host-protocols.mjs": "5ffe956f9ff5b38efac34a7d36a799f4249391b01a92b7c07b5f2c3c233b6f99",
13
+ "check/coda/application/host-protocols.mjs": "1153b5e35f59ab04bef50dc4cecbca4fb2326096eb556978dd7d51736611e970",
14
14
  "check/coda/components/protocols/protocol-events.mjs": "076f335287d0398c602ad6db286ab0001dc00ac42d32a23918a66ee37c3e9a2f",
15
- "check/coda/components/protocols/record-rules.mjs": "116bd103102afb94589d1df69786a780d2745165f46b878ddd48ac6d630694b1",
15
+ "check/coda/components/protocols/record-rules.mjs": "c6bbafdaa869543ea4759be526ca8cf1ff5a03dad999f6ad724a602703c92a44",
16
16
  "check/coda/components/protocols/types.mjs": "283cd0f4516f10637d6fe257fe645ead87912219d471c06408d56617f244e1d1",
17
17
  "check/coda/adapters/provider-api.mjs": "70441ea2a417ede13e04113ec254496883be3186f291ef5ee65834f35009eb9e",
18
18
  "check/coda/adapters/call-limit.mjs": "7e86d95ff7b0a88955015904ec91ae55e78fad816d06f710d6e62af53ccbdeab",
@@ -30,7 +30,7 @@
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": "4b0f5379de25c464b044dbfc293e421f4f0c36b16bd4742d90ed82f5bd7d7162",
33
+ "check/coda/components/plugins/plugin-extensions.mjs": "54b2fbc9db34ae0a18fe6193714287b82fff3f796069318c9a1e5f92d48475aa",
34
34
  "check/coda/components/plugins/plugin-icons.mjs": "ec29cadce4948ecacabfe911a2ceb45414b96e28971358acbc4e952bedc78e1a",
35
35
  "check/coda/components/plugins/plugin-rules.mjs": "32cf0a3956a646e0c18cea62da4c0969af9f4c6f60ab1a4970937163a13a878a",
36
36
  "check/coda/components/plugins/plugin-source-rules.mjs": "d3bf278c4fb35e99f602ea81419dff0ad0c2753ee20e6e3b648d2fecf82da44f",
@@ -41,21 +41,26 @@
41
41
  "check/coda/components/session-config/contributions.mjs": "74d52d65dc7b6f13ef301a211bdf50cc91ae468c462cbe201f5dc34f7437b97b",
42
42
  "check/coda/components/workflows/contributions.mjs": "f16e36e5e591d7ab6c6e63f252e780717ba17bb4642aedd2797c5ff017df9d95",
43
43
  "check/coda/components/workflows/workflow-protocol-definitions.mjs": "094ab1b2676f05fa88eb7ccd558b4eb4dce609fdf412f7663f84906ac2732186",
44
+ "check/coda/domain/accord.mjs": "35cb6c2f918433b72aa44996efe2212d9b9c4ea807858d80947c8aa089b85fa2",
44
45
  "check/coda/domain/agent-protocol.mjs": "f1d7c939c240664b773c04d9a1c1e9457cc8396fd8f99f1d5b6b6964150843c0",
45
46
  "check/coda/domain/duration.mjs": "3f07411812362adcacfc288b1513f10e7d0ea1addcdc1b47ae553561f1d3430b",
46
47
  "check/coda/domain/errors.mjs": "15ad3348ea0e173a1a8602ec72766592cb41c0221420d9e5884bd68090ecc84b",
48
+ "check/coda/domain/jcs.mjs": "2f1074ac2dd23d397567c01c7a7107ad3607bad6995a8a5c9115a6705a015afe",
47
49
  "check/coda/domain/resume-prompt.mjs": "9895ccf235808b9bf3f4836999c65ddd6d764fcaa6e8a9a9647612faf0c9629a",
48
50
  "check/coda/domain/plugin-services.mjs": "940a72a14da980188a32c790c7f341d3ec0062a6e87ef1ebc9ef051798ea0a75",
49
51
  "check/coda/domain/session-env.mjs": "283bbc2e8ae9ea22b53747865a651a4dac9c6cfc242f27612e0c82e6e9cc151a",
52
+ "check/coda/domain/usage.mjs": "9077cfb738016fed72e4fb43f415aab258bdfa213e466740f2c0535dbba45ed3",
50
53
  "check/coda/domain/values.mjs": "afb8bf30e374bed27fe41ee4b6d8c3c0b4dbe1dcfb6b62dad9d3d53b966706a1",
54
+ "check/coda/kernel/accord-protocol.mjs": "f9a5c59f9b278f0ceebb9c1c5f6c2b49be0300ce3bde04e46dcf1c10acf2f0ac",
51
55
  "check/coda/kernel/agent-failures.mjs": "cbc215e2403d86f0acc765c2077197e0b529fc01e213db465c388361238ea8ce",
52
56
  "check/coda/kernel/plugin-protocol.mjs": "c514f9b6237404f8877dea568e4d425f1e380c19f3cb87764edf56f6c92ebd69",
53
57
  "check/coda/kernel/project-protocol.mjs": "69874b2b226f111b156724454c968e829018f1caac0a02883f13e1f980482739",
54
58
  "check/coda/kernel/thread-protocol.mjs": "58bbd66c0058552f26c1b4ed08231e9afd142f2b7a9f50ed6bd66cbfe8f579e1",
59
+ "check/coda/kernel/usage-protocol.mjs": "4bd07a4d4c63c75e5328ef7e907bfa4e83af430f7f04a08cf8eb883a23ddc51f",
55
60
  "check/coda/resources/plugins/resources/panels/panels.mjs": "37ffc6a4ede3e4612cd13cf1a973a90892f8ce7e8a0f055e7cfe86313aae5224",
56
61
  "check/coda/resources/plugins/resources/panels/rules.mjs": "a433d4e84138937297ec31a8912aab7bd48bba4b66da3a10978edb1367613c96",
57
62
  "check/coda/resources/plugins/resources/panels/sign-in.mjs": "6eb016ef9a7f8aa03e0f4b2fa35ce139b8b1ff0deb4ec6e6a34139aed4f2841a",
58
63
  "check/coda/builtin.json": "0eb63a693c912f7e339cda0b76b85110f881784b92c7788c8ea6d0a1c7468ade",
59
- "check/coda/api-surface.txt": "7ce7dca260719ef0f756b0f73eceec447eacec6d966d9671b312e15c7ec4034a"
64
+ "check/coda/api-surface.txt": "47fe85e101b2315d6e5783e1e74050f493c2045ca6ea4577ad841d6643d8b238"
60
65
  }
61
66
  }
@@ -0,0 +1,144 @@
1
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from 'node:crypto';
2
+ import { jcs } from './jcs.mjs';
3
+
4
+ // Accord records (AIP-01) and bindings (AIP-02): formats, signing and verification. Pure: keys are node:crypto KeyObjects.
5
+
6
+ export const MAX_RECORD_BYTES = 65536;
7
+ const KEY = /^ed25519:[0-9a-f]{64}$/;
8
+ const SIGNATURE = /^[0-9a-f]{128}$/;
9
+ const KIND = /^[a-z0-9-]{1,64}(\/[a-z0-9-]{1,64})?$/;
10
+ // RFC 8410: SubjectPublicKeyInfo of an Ed25519 key is this prefix followed by the 32 raw bytes.
11
+ const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
12
+ const RECORD_DOMAIN = 'accord:record:1\n';
13
+ const CERT_DOMAIN = 'accord:cert:1\n';
14
+ const CERT_FIELDS = ['key', 'from', 'until', 'sig'];
15
+
16
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
17
+ const isTime = value => Number.isSafeInteger(value) && value >= 0;
18
+ const bytes = text => Buffer.byteLength(text, 'utf8');
19
+
20
+ export const isAccordKind = kind => typeof kind === 'string' && KIND.test(kind);
21
+
22
+ export function generateIdentity() {
23
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
24
+ return { author: publicKeyToAuthor(publicKey), publicKey, privateKey };
25
+ }
26
+
27
+ export function publicKeyToAuthor(publicKey) {
28
+ const der = publicKey.export({ format: 'der', type: 'spki' });
29
+ if (der.length !== SPKI_PREFIX.length + 32 || !der.subarray(0, SPKI_PREFIX.length).equals(SPKI_PREFIX)) {
30
+ throw new TypeError('不是 Ed25519 公钥');
31
+ }
32
+ return `ed25519:${der.subarray(SPKI_PREFIX.length).toString('hex')}`;
33
+ }
34
+
35
+ export function authorToPublicKey(author) {
36
+ if (typeof author !== 'string' || !KEY.test(author)) throw new TypeError('钥匙格式不合法');
37
+ return createPublicKey({ key: Buffer.concat([SPKI_PREFIX, Buffer.from(author.slice(8), 'hex')]), format: 'der', type: 'spki' });
38
+ }
39
+
40
+ const isEd25519 = privateKey => privateKey?.type === 'private' && privateKey.asymmetricKeyType === 'ed25519';
41
+ const signed = (domain, value, privateKey) => {
42
+ if (!isEd25519(privateKey)) throw new TypeError('签名须用 Ed25519 私钥');
43
+ return sign(null, Buffer.from(domain + jcs(value), 'utf8'), privateKey).toString('hex');
44
+ };
45
+ const verified = (domain, value, signature, key) => verify(null, Buffer.from(domain + jcs(value), 'utf8'), authorToPublicKey(key), Buffer.from(signature, 'hex'));
46
+
47
+ function certBodyProblem({ key, from, until }) {
48
+ if (typeof key !== 'string' || !KEY.test(key)) return '证书钥匙格式不合法';
49
+ if (!isTime(from) || !isTime(until) || from > until) return '证书有效期不合法';
50
+ return null;
51
+ }
52
+
53
+ function certProblem(cert) {
54
+ if (!isObject(cert)) return '证书不是对象';
55
+ if (Object.keys(cert).length !== CERT_FIELDS.length || !CERT_FIELDS.every(name => Object.hasOwn(cert, name))) return '证书字段不符';
56
+ if (typeof cert.sig !== 'string' || !SIGNATURE.test(cert.sig)) return '证书签名格式不合法';
57
+ return certBodyProblem(cert);
58
+ }
59
+
60
+ /// A certificate: the author's signature over the key that may sign for them during [from, until].
61
+ export function signCert({ key, from, until }, authorPrivateKey) {
62
+ const body = { key, from, until };
63
+ const problem = certBodyProblem(body);
64
+ if (problem) throw new TypeError(problem);
65
+ return { ...body, sig: signed(CERT_DOMAIN, body, authorPrivateKey) };
66
+ }
67
+
68
+ export function verifyCert(cert, author) {
69
+ const problem = certProblem(cert);
70
+ if (problem) return { ok: false, reason: problem };
71
+ if (typeof author !== 'string' || !KEY.test(author)) return { ok: false, reason: '作者钥匙格式不合法' };
72
+ const { key, from, until, sig } = cert;
73
+ return verified(CERT_DOMAIN, { key, from, until }, sig, author) ? { ok: true } : { ok: false, reason: '证书签名不符' };
74
+ }
75
+
76
+ function recordProblem(record) {
77
+ if (!isObject(record)) return '记录不是对象';
78
+ if (Object.hasOwn(record, 'gone')) return '记录顶层不能有 gone';
79
+ if (typeof record.author !== 'string' || !KEY.test(record.author)) return '作者钥匙格式不合法';
80
+ if (typeof record.id !== 'string' || bytes(record.id) < 1 || bytes(record.id) > 256) return 'id 须为 1 到 256 字节';
81
+ if (!isAccordKind(record.kind)) return '种类不合法';
82
+ if (!isTime(record.version)) return 'version 须为安全非负整数';
83
+ if (Object.hasOwn(record, 'body') && !isObject(record.body)) return 'body 须为对象';
84
+ return null;
85
+ }
86
+
87
+ export function signRecord(record, signerPrivateKey) {
88
+ if (isObject(record) && Object.hasOwn(record, 'sig')) throw new TypeError('待签记录不能已有 sig');
89
+ const problem = recordProblem(record);
90
+ if (problem) throw new TypeError(problem);
91
+ const full = { ...record, sig: signed(RECORD_DOMAIN, record, signerPrivateKey) };
92
+ const checked = verifyRecord(full);
93
+ if (!checked.ok) throw new TypeError(checked.reason);
94
+ return full;
95
+ }
96
+
97
+ export function verifyRecord(record) {
98
+ const problem = recordProblem(record);
99
+ if (problem) return { ok: false, reason: problem };
100
+ if (typeof record.sig !== 'string' || !SIGNATURE.test(record.sig)) return { ok: false, reason: '签名格式不合法' };
101
+ const { sig, ...rest } = record;
102
+ let whole;
103
+ try { whole = jcs(record); } catch (error) { return { ok: false, reason: `记录不能规范化:${error.message}` }; }
104
+ if (bytes(whole) > MAX_RECORD_BYTES) return { ok: false, reason: '记录超过 64 KiB' };
105
+ let signer = record.author;
106
+ if (Object.hasOwn(record, 'cert')) {
107
+ const certified = verifyCert(record.cert, record.author);
108
+ if (!certified.ok) return certified;
109
+ if (record.version < record.cert.from || record.version > record.cert.until) return { ok: false, reason: 'version 不在证书有效期内' };
110
+ signer = record.cert.key;
111
+ }
112
+ return verified(RECORD_DOMAIN, rest, sig, signer) ? { ok: true } : { ok: false, reason: '签名不符' };
113
+ }
114
+
115
+ /// AIP-02: the record by which an author says that `endpoint` speaks for them in `scope`.
116
+ const bindingProblem = (scope, endpoint) => {
117
+ if (typeof scope !== 'string' || scope === '') return 'scope 须为非空字符串';
118
+ if (typeof endpoint !== 'string' || endpoint === '') return 'endpoint 须为非空字符串';
119
+ return null;
120
+ };
121
+
122
+ export function signBinding({ author, id, version, scope, endpoint, cert }, signerPrivateKey) {
123
+ const problem = bindingProblem(scope, endpoint);
124
+ if (problem) throw new TypeError(problem);
125
+ const record = { author, id, kind: 'binding', version, body: { scope, endpoint } };
126
+ if (cert !== undefined) record.cert = cert;
127
+ return signRecord(record, signerPrivateKey);
128
+ }
129
+
130
+ export function verifyBinding(record, { scope, endpoint, now = Date.now(), clockSkewMs = 5 * 60_000 }) {
131
+ const expected = bindingProblem(scope, endpoint);
132
+ if (expected) return { ok: false, reason: `期望的${expected}` };
133
+ const checked = verifyRecord(record);
134
+ if (!checked.ok) return checked;
135
+ if (record.kind !== 'binding') return { ok: false, reason: '不是绑定记录' };
136
+ const stated = bindingProblem(record.body?.scope, record.body?.endpoint);
137
+ if (stated) return { ok: false, reason: `记录的${stated}` };
138
+ if (record.body?.scope !== scope) return { ok: false, reason: 'scope 不符' };
139
+ if (record.body?.endpoint !== endpoint) return { ok: false, reason: 'endpoint 不符' };
140
+ if (record.cert && !(now >= record.cert.from - clockSkewMs && now <= record.cert.until + clockSkewMs)) {
141
+ return { ok: false, reason: '证书不在有效期内' };
142
+ }
143
+ return { ok: true, author: record.author };
144
+ }
@@ -0,0 +1,58 @@
1
+ // RFC 8785 (JCS): the one byte-exact serialization a signature covers. Input is JSON data only — anything that has no JSON
2
+ // form is refused rather than dropped, since a silently dropped field would sign something other than what was meant.
3
+
4
+ const plain = value => { const proto = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null; };
5
+
6
+ function text(value) {
7
+ if (!value.isWellFormed()) throw new TypeError('JCS 不接受孤立的 UTF-16 代理项');
8
+ return JSON.stringify(value);
9
+ }
10
+
11
+ function scalar(value) {
12
+ if (value === null) return 'null';
13
+ switch (typeof value) {
14
+ case 'boolean': return String(value);
15
+ case 'number':
16
+ if (!Number.isFinite(value)) throw new TypeError('JCS 不接受 NaN 与 Infinity');
17
+ return String(value); // ECMAScript Number::toString: shortest round-trip form; -0 is "0"
18
+ case 'string': return text(value);
19
+ default: throw new TypeError(`JCS 不接受 ${typeof value}`);
20
+ }
21
+ }
22
+
23
+ // Walks with an explicit stack, so nesting depth is bounded by memory and not by the call stack. Each work item is a
24
+ // value still to write, a piece of punctuation (`{ text }`) to write as it is, or the end of a container (`{ leave }`);
25
+ // items are pushed in reverse. `active` holds the containers being written, so a cycle is refused where a shared
26
+ // child, reached again after its first visit is done, is not.
27
+ export function jcs(root) {
28
+ const out = [], work = [{ value: root }], active = new Set();
29
+ while (work.length) {
30
+ const item = work.pop();
31
+ if (Object.hasOwn(item, 'text')) { out.push(item.text); continue; }
32
+ if (Object.hasOwn(item, 'leave')) { active.delete(item.leave); continue; }
33
+ const { value } = item;
34
+ if (value === null || typeof value !== 'object') { out.push(scalar(value)); continue; }
35
+ if (active.has(value)) throw new TypeError('JCS 不接受循环引用');
36
+ if (Array.isArray(value)) {
37
+ active.add(value);
38
+ out.push('[');
39
+ work.push({ leave: value }, { text: ']' });
40
+ for (let i = value.length - 1; i >= 0; i--) {
41
+ work.push({ value: value[i] });
42
+ if (i > 0) work.push({ text: ',' });
43
+ }
44
+ continue;
45
+ }
46
+ if (!plain(value)) throw new TypeError('JCS 只接受普通对象与数组');
47
+ // Default string comparison orders by UTF-16 code units, as RFC 8785 requires.
48
+ const keys = Object.keys(value).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
49
+ active.add(value);
50
+ out.push('{');
51
+ work.push({ leave: value }, { text: '}' });
52
+ for (let i = keys.length - 1; i >= 0; i--) {
53
+ work.push({ value: value[keys[i]] }, { text: `${text(keys[i])}:` });
54
+ if (i > 0) work.push({ text: ',' });
55
+ }
56
+ }
57
+ return out.join('');
58
+ }
@@ -0,0 +1,56 @@
1
+ // What a turn the agent reported using, as a Coda turn's `usage` (the agent's own count of this turn, not a running total),
2
+ // brought to the counts usage_buckets keeps. Only this standard shape is read: nothing here knows an agent's own fields.
3
+ export const USAGE_BUCKET_MS = 600_000;
4
+
5
+ export function bucketStart(timeMs) {
6
+ if (!Number.isSafeInteger(timeMs) || timeMs < 0) throw new TypeError('时间必须是非负整数毫秒');
7
+ return Math.floor(timeMs / USAGE_BUCKET_MS) * USAGE_BUCKET_MS;
8
+ }
9
+
10
+ // A model's name as a session keeps it (domain/values.mjs text), as it is: not blank, at most `max` long, no NUL; null for one that is not.
11
+ export const modelName = (value, max = 200) => typeof value === 'string' && value.trim().length > 0 && value.length <= max && !value.includes('\0') ? value : null;
12
+
13
+ const FIELDS = [['inputTokens', 'input'], ['outputTokens', 'output'], ['cachedReadTokens', 'cacheRead'], ['cachedWriteTokens', 'cacheWrite']];
14
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
15
+ && [Object.prototype, null].includes(Object.getPrototypeOf(value));
16
+
17
+ // The counts of one object, `{ ok, counts }` or `{ ok: false, reason }`: each given field (not undefined or null) a non-negative safe integer, at least one given.
18
+ function counts(raw, what) {
19
+ const result = {};
20
+ let given = 0;
21
+ for (const [field, name] of FIELDS) {
22
+ const value = raw[field];
23
+ if (value === undefined || value === null) { result[name] = 0; continue; }
24
+ if (!Number.isSafeInteger(value) || value < 0) return { ok: false, reason: `${what}的 ${field} 不是非负整数` };
25
+ result[name] = value; given++;
26
+ }
27
+ return given ? { ok: true, counts: result } : { ok: false, reason: `${what}没有任何 token 字段` };
28
+ }
29
+
30
+ // `{ ok: true, usage: null }` for none reported; otherwise `{ ok: true, usage: { input, output, cacheRead, cacheWrite } }`, or
31
+ // `{ usage: { breakdown: [{ model, ...counts }] } }` of a turn that used several models (the only source then, the top
32
+ // level not counted beside it); `{ ok: false, reason }` for anything else, never thrown.
33
+ export function normalizeTurnUsage(raw) {
34
+ if (raw === undefined || raw === null) return { ok: true, usage: null };
35
+ if (!isObject(raw)) return { ok: false, reason: 'usage 不是对象' };
36
+ if (!('breakdown' in raw)) {
37
+ const top = counts(raw, 'usage');
38
+ return top.ok ? { ok: true, usage: top.counts } : top;
39
+ }
40
+ const { breakdown } = raw;
41
+ if (!Array.isArray(breakdown) || !breakdown.length) return { ok: false, reason: 'breakdown 不是非空数组' };
42
+ const byModel = new Map();
43
+ for (const item of breakdown) {
44
+ if (!isObject(item)) return { ok: false, reason: 'breakdown 的项不是对象' };
45
+ const model = modelName(item.model);
46
+ if (!model) return { ok: false, reason: 'breakdown 的 model 不是 1–200 字、不含 NUL 的文本' };
47
+ const each = counts(item, `模型 ${model}`);
48
+ if (!each.ok) return each;
49
+ const sum = byModel.get(model) ?? { model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
50
+ for (const [, name] of FIELDS) sum[name] += each.counts[name];
51
+ if (!Number.isSafeInteger(sum.input) || !Number.isSafeInteger(sum.output) || !Number.isSafeInteger(sum.cacheRead) || !Number.isSafeInteger(sum.cacheWrite))
52
+ return { ok: false, reason: `模型 ${model} 的合计超出安全整数` };
53
+ byModel.set(model, sum);
54
+ }
55
+ return { ok: true, usage: { breakdown: [...byModel.values()] } };
56
+ }
@@ -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/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.26",
4
4
  "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源类型(与旧的面板)。",
5
5
  "license": "MIT",
6
6
  "repository": {