@coda-console/plugin-check 0.8.28 → 0.8.30
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.
- package/README.md +13 -23
- package/check/coda/adapters/plugin-events.mjs +3 -10
- package/check/coda/adapters/plugin-modules.mjs +19 -23
- package/check/coda/adapters/plugin-setup-api.mjs +5 -0
- package/check/coda/adapters/plugin-test-host.d.mts +0 -13
- package/check/coda/adapters/plugin-test-host.mjs +6 -25
- package/check/coda/api-surface.txt +3 -6
- package/check/coda/application/contributions.mjs +1 -0
- package/check/coda/builtin.json +15 -49
- package/check/coda/components/plugins/contribution-points.mjs +1 -2
- package/check/coda/components/plugins/git-contributions.mjs +10 -6
- package/check/coda/components/plugins/plugin-extensions.mjs +9 -72
- package/check/coda/components/plugins/plugin-rules.mjs +16 -20
- package/check/coda/components/plugins/plugin-source-rules.mjs +13 -29
- package/check/coda/components/plugins/self-contributions.mjs +13 -0
- package/check/coda/components/protocols/record-rules.mjs +8 -0
- package/check/coda/contract.json +18 -26
- package/check/manifest.mjs +10 -8
- package/package.json +2 -2
- package/templates/module/main.mjs +6 -13
- package/templates/module/package.json +7 -7
- package/templates/module/test/main.test.mjs +7 -23
- package/check/coda/application/host-protocols.mjs +0 -19
- package/check/coda/components/workflows/workflow-protocol-definitions.mjs +0 -362
- package/check/coda/domain/accord.mjs +0 -144
- package/check/coda/domain/jcs.mjs +0 -58
- package/check/coda/domain/usage.mjs +0 -56
- package/check/coda/kernel/accord-protocol.mjs +0 -168
- package/check/coda/kernel/plugin-protocol.mjs +0 -56
- package/check/coda/kernel/project-protocol.mjs +0 -52
- package/check/coda/kernel/thread-protocol.mjs +0 -167
- package/check/coda/kernel/usage-protocol.mjs +0 -97
|
@@ -1,58 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,56 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,168 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
// Coda's own protocol of the plugins installed here, `coda/plugin@1`: what each is and how it stands on this machine, as a
|
|
2
|
-
// record. A record is an installed plugin, its ID the plugin's; it has no operation. Its records are read through from the
|
|
3
|
-
// `plugins` table (Protocols.serve) by what the plugins component says of them (components/plugins/plugins.mjs `installedView`):
|
|
4
|
-
// nothing is kept of them besides, and they are no section and not in the record directory.
|
|
5
|
-
import { createHash } from 'node:crypto';
|
|
6
|
-
import { canonical } from '../domain/values.mjs';
|
|
7
|
-
|
|
8
|
-
export const PLUGIN = 'coda/plugin@1';
|
|
9
|
-
|
|
10
|
-
const text = { type: 'string' };
|
|
11
|
-
|
|
12
|
-
export const PLUGIN_PROTOCOL = {
|
|
13
|
-
kind: PLUGIN,
|
|
14
|
-
title: '插件',
|
|
15
|
-
// Its name and version, and where it comes from: an npm package, a Git repository (at a branch and a commit), or Coda's own copy.
|
|
16
|
-
spec: {
|
|
17
|
-
type: 'object',
|
|
18
|
-
properties: {
|
|
19
|
-
name: text,
|
|
20
|
-
version: text,
|
|
21
|
-
source: {
|
|
22
|
-
type: 'object',
|
|
23
|
-
properties: { kind: { enum: ['builtin', 'npm', 'git'] }, package: text, version: text, repo: text, path: text, ref: text, commit: text },
|
|
24
|
-
required: ['kind'],
|
|
25
|
-
additionalProperties: false,
|
|
26
|
-
},
|
|
27
|
-
},
|
|
28
|
-
required: ['name', 'version', 'source'],
|
|
29
|
-
additionalProperties: false,
|
|
30
|
-
},
|
|
31
|
-
// How it is on this machine: ready, being taken (`fetching`), not running here (`incompatible`) or failed, and why (`error`).
|
|
32
|
-
status: {
|
|
33
|
-
type: 'object',
|
|
34
|
-
properties: { state: { enum: ['ready', 'fetching', 'incompatible', 'failed'] }, error: text },
|
|
35
|
-
required: ['state'],
|
|
36
|
-
additionalProperties: false,
|
|
37
|
-
},
|
|
38
|
-
operations: {},
|
|
39
|
-
// What a plugin may ask for in its `uses` (docs/plugins.md「用到的权限」), on trial while the protocol is not stable.
|
|
40
|
-
permissions: {
|
|
41
|
-
read: { title: '查看这台机器装了哪些插件', trial: true, read: true },
|
|
42
|
-
},
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
const SOURCE_KEYS = ['package', 'version', 'repo', 'path', 'ref', 'commit'];
|
|
46
|
-
// The record of one installed plugin, as `installedView` says it; its revision is what its spec and status say.
|
|
47
|
-
const record = ({ id, installedAt, sequence, name, version, source, local }) => {
|
|
48
|
-
const spec = { name, version, source: { kind: source.kind ?? 'builtin', ...Object.fromEntries(SOURCE_KEYS.filter(key => typeof source[key] === 'string').map(key => [key, source[key]])) } };
|
|
49
|
-
const status = { state: local.state, ...(local.error ? { error: local.error } : {}) };
|
|
50
|
-
return { kind: PLUGIN, id, provider: 'coda', instance: id, createdAt: new Date(installedAt).toISOString(), creationSequence: sequence, spec, status,
|
|
51
|
-
revision: `${id}:${createHash('sha256').update(canonical([spec, status])).digest('hex').slice(0, 16)}` };
|
|
52
|
-
};
|
|
53
|
-
export const pluginRecords = plugins => ({
|
|
54
|
-
get: id => { const view = plugins.installedView().find(each => each.id === id); return view ? record(view) : null; },
|
|
55
|
-
list: () => plugins.installedView().map(record),
|
|
56
|
-
});
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
// Coda's own protocol of the directories registered here, `coda/project@1`: a directory as a record, its ID the project's,
|
|
2
|
-
// what is asked of a directory and not of a session or a workflow in it (#2749 3.5) its queries — its branches. Its records
|
|
3
|
-
// are read through from the `projects` table (Protocols.serve), as `coda/thread@1`'s are from `threads`: one for each
|
|
4
|
-
// directory not deleted, by its name, never its path; nothing is kept of them besides, they are no section and not in the
|
|
5
|
-
// record directory (one of another machine is not read).
|
|
6
|
-
import { createHash } from 'node:crypto';
|
|
7
|
-
import { canonical } from '../domain/values.mjs';
|
|
8
|
-
|
|
9
|
-
export const PROJECT = 'coda/project@1';
|
|
10
|
-
|
|
11
|
-
export const PROJECT_PROTOCOL = {
|
|
12
|
-
kind: PROJECT,
|
|
13
|
-
title: '目录',
|
|
14
|
-
spec: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], additionalProperties: false },
|
|
15
|
-
status: { type: 'object', additionalProperties: false },
|
|
16
|
-
operations: {
|
|
17
|
-
// Its branches, the default first and the rest by latest commit, as a new session reads them (for a `branch` input):
|
|
18
|
-
// `pending` while they are first read, `error` why they could not be.
|
|
19
|
-
branches: { safe: true, input: { type: 'object', additionalProperties: false }, result: {
|
|
20
|
-
type: 'object',
|
|
21
|
-
properties: { branches: { type: 'array', items: { type: 'string', minLength: 1 } }, default: { type: 'string' }, pending: { type: 'boolean' },
|
|
22
|
-
error: { type: 'string', minLength: 1 } },
|
|
23
|
-
required: ['branches', 'default'],
|
|
24
|
-
additionalProperties: false,
|
|
25
|
-
} },
|
|
26
|
-
},
|
|
27
|
-
// What a plugin may ask for in its `uses` (docs/plugins.md「用到的权限」), on trial while the protocol is not stable.
|
|
28
|
-
permissions: {
|
|
29
|
-
read: { title: '查看目录名与分支', trial: true, read: true, operations: ['branches'] },
|
|
30
|
-
},
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
const ROW = 'SELECT id, name, created_at, rowid AS sequence FROM projects WHERE deleted = 0';
|
|
34
|
-
const record = row => {
|
|
35
|
-
if (!row) return null;
|
|
36
|
-
const spec = { name: row.name }, status = {};
|
|
37
|
-
return { kind: PROJECT, id: row.id, provider: 'coda', createdAt: new Date(row.createdAt).toISOString(), creationSequence: row.sequence, spec, status,
|
|
38
|
-
revision: `${row.id}:${createHash('sha256').update(canonical([spec, status])).digest('hex').slice(0, 16)}` };
|
|
39
|
-
};
|
|
40
|
-
export const projectRecords = store => ({
|
|
41
|
-
get: id => record(store.one(`${ROW} AND id = ?`, id)),
|
|
42
|
-
list: () => store.all(`${ROW} ORDER BY created_at, rowid`).map(record),
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
// Its query through the unified call (components/protocols/calls.mjs `handle`): `branches`, read as the clients read them
|
|
46
|
-
// (`branches(projectId)`, SessionConfigService.branches, the same `GET /v1/projects/<id>/branches` answers with).
|
|
47
|
-
export function projectQueries(calls, { branches }) {
|
|
48
|
-
calls.handle(PROJECT, 'branches', async ({ held }) => {
|
|
49
|
-
const read = await branches(held.id);
|
|
50
|
-
return { branches: read.branches, default: read.defaultRef ?? '', ...(read.pending ? { pending: true } : {}), ...(read.error ? { error: String(read.error.message ?? read.error) } : {}) };
|
|
51
|
-
});
|
|
52
|
-
}
|
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
// Coda's own protocol of its sessions, `coda/thread@1`: what a session is like, as a record. A session is called, sent to and
|
|
2
|
-
// archived through the orchestration on the call kernel (kernel/party.mjs, docs/product-architecture.md「经调用内核的调用」);
|
|
3
|
-
// a plugin asks of it where it works and what it changed there (`workspace`, `changes`, queries `threadQueries` answers), and
|
|
4
|
-
// adds to its composer's draft (`append-draft`, a doing operation the orchestration does, its `side`). Its directory's
|
|
5
|
-
// workflows (`workflows`) are a query the workflows define and answer, with a group of its own, added as the protocol is
|
|
6
|
-
// registered (application/assembly.mjs). Its records are the
|
|
7
|
-
// sessions here, read through from the `threads` table (Protocols.serve): nothing is kept of them besides, and they are no section.
|
|
8
|
-
import { createHash } from 'node:crypto';
|
|
9
|
-
import { existsSync } from 'node:fs';
|
|
10
|
-
import { canonical } from '../domain/values.mjs';
|
|
11
|
-
|
|
12
|
-
export const THREAD = 'coda/thread@1';
|
|
13
|
-
|
|
14
|
-
const reference = {
|
|
15
|
-
type: 'object',
|
|
16
|
-
properties: { kind: { type: 'string' }, id: { type: 'string' } },
|
|
17
|
-
required: ['kind', 'id'],
|
|
18
|
-
additionalProperties: false,
|
|
19
|
-
};
|
|
20
|
-
// The payloads of its events (docs/session-contracts.md「事件」), as the kernel tells them (kernel/session-events.mjs,
|
|
21
|
-
// application/service.mjs sessionFacts, exited, settled) and the resumes say them (components/workflows/quota-resumes.mjs).
|
|
22
|
-
const string = { type: 'string' }, boolean = { type: 'boolean' }, nullable = type => ({ type: [type, 'null'] });
|
|
23
|
-
const object = (properties, required = Object.keys(properties)) => ({ type: 'object', required, properties });
|
|
24
|
-
// Opened: its project, its parent here, whether it works in a worktree, its agent.
|
|
25
|
-
const opened = object({ projectId: string, parentThreadId: nullable('string'), worktree: boolean, agent: string });
|
|
26
|
-
// What only Coda observes of it; `observing`, `quietSince`'s clock and the ledger's items as sessionFacts gives them.
|
|
27
|
-
const facts = object({
|
|
28
|
-
input: boolean, busy: boolean, background: boolean, observing: boolean, waiting: boolean, scheduled: boolean, looping: boolean,
|
|
29
|
-
live: boolean, archived: boolean, worktree: boolean, onDisk: boolean,
|
|
30
|
-
waits: { type: 'array', items: object({ kind: string, key: string, actor: { enum: ['user', 'system'] }, since: { type: 'integer' },
|
|
31
|
-
dueAt: nullable('integer'), input: string, holder: string, awaited: { const: false }, overdue: { const: true } }, ['kind', 'key', 'actor', 'since', 'dueAt']) },
|
|
32
|
-
waitsForSystem: boolean, unread: { type: 'integer', minimum: 0 }, overdue: boolean, quietSince: nullable('integer'), pinned: boolean,
|
|
33
|
-
usage: nullable('object'),
|
|
34
|
-
});
|
|
35
|
-
// A turn that failed so: its project, the turn and what it failed with — the input's quota spent (`failure` as the agent
|
|
36
|
-
// said it, `resetAt` kept), or its agent's process gone under it (the turn's, none when the agent said nothing).
|
|
37
|
-
const quotaSpent = object({ projectId: string, turnId: string, failure: { type: 'object' } });
|
|
38
|
-
const exited = object({ projectId: string, turnId: string, failure: nullable('object') });
|
|
39
|
-
// The resume of such a turn, under `key`: the failed turn's, its session, what the session is to go on with (`text`, and the
|
|
40
|
-
// input and how when it is sent again: domain/resume-prompt.mjs) and when (an ISO time) — always for a process gone, only when it
|
|
41
|
-
// resumes by itself for a quota spent — and, for a process gone, which resume in a row it is.
|
|
42
|
-
const resume = (key, turn, more, required) => object({ [key]: object({ ...turn.properties, threadId: string, text: string, input: string,
|
|
43
|
-
how: { enum: ['original', 'verify'] }, resumeAt: string, ...more },
|
|
44
|
-
[...turn.required, 'threadId', 'text', ...required]) });
|
|
45
|
-
|
|
46
|
-
export const THREAD_PROTOCOL = {
|
|
47
|
-
kind: THREAD,
|
|
48
|
-
title: '会话',
|
|
49
|
-
// A session's directory, and its parent here when it has one (a step's session reports to a run; S4c's `reported_to`).
|
|
50
|
-
spec: {
|
|
51
|
-
type: 'object',
|
|
52
|
-
properties: { project: { type: 'string' }, parent: reference },
|
|
53
|
-
additionalProperties: false,
|
|
54
|
-
},
|
|
55
|
-
// Its title, whether it is archived itself and whether its family's root is, its agent, and the turn of it that ended last
|
|
56
|
-
// (null before any has): another one ending moves it, however soon after the next begins.
|
|
57
|
-
status: {
|
|
58
|
-
type: 'object',
|
|
59
|
-
properties: {
|
|
60
|
-
title: { type: 'string' },
|
|
61
|
-
archived: { type: 'boolean' },
|
|
62
|
-
familyArchived: { type: 'boolean' },
|
|
63
|
-
agent: { type: 'string' },
|
|
64
|
-
lastTurn: { type: ['string', 'null'] },
|
|
65
|
-
},
|
|
66
|
-
additionalProperties: false,
|
|
67
|
-
},
|
|
68
|
-
operations: {
|
|
69
|
-
// Where the session works and in which project: its checkout's state, `gone` for one ready whose directory is no more,
|
|
70
|
-
// and its path only while it is ready.
|
|
71
|
-
workspace: { safe: true, input: { type: 'object', additionalProperties: false }, result: {
|
|
72
|
-
type: 'object',
|
|
73
|
-
properties: {
|
|
74
|
-
path: { type: ['string', 'null'] },
|
|
75
|
-
project: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: ['id', 'name'], additionalProperties: false },
|
|
76
|
-
state: { enum: ['preparing', 'ready', 'failed', 'gone'] },
|
|
77
|
-
},
|
|
78
|
-
required: ['path', 'project', 'state'],
|
|
79
|
-
additionalProperties: false,
|
|
80
|
-
} },
|
|
81
|
-
// What it changed in its worktree (docs/session-contracts.md「变更」): where it works (`kind`), and in a worktree of its
|
|
82
|
-
// own every file since its base commit (`base`, its ref and commit), with its lines, none cut (adapters/worktree-changes.mjs);
|
|
83
|
-
// a file's diff is the stream `diff`'s.
|
|
84
|
-
changes: { safe: true, input: { type: 'object', additionalProperties: false }, result: {
|
|
85
|
-
type: 'object',
|
|
86
|
-
properties: {
|
|
87
|
-
available: { type: 'boolean' }, kind: { type: 'string' },
|
|
88
|
-
base: { type: 'object', properties: { ref: { type: ['string', 'null'] }, commit: { type: 'string' } }, required: ['ref', 'commit'], additionalProperties: false },
|
|
89
|
-
files: { type: 'array' }, count: { type: 'integer' }, additions: { type: 'integer' }, deletions: { type: 'integer' },
|
|
90
|
-
},
|
|
91
|
-
required: ['available', 'kind'],
|
|
92
|
-
additionalProperties: false,
|
|
93
|
-
} },
|
|
94
|
-
// Text added at the end of its composer's draft: after a space, or on a line of its own (`line`), when the draft has text.
|
|
95
|
-
'append-draft': { input: {
|
|
96
|
-
type: 'object',
|
|
97
|
-
properties: { text: { type: 'string', minLength: 1 }, line: { type: 'boolean' } },
|
|
98
|
-
required: ['text'],
|
|
99
|
-
additionalProperties: false,
|
|
100
|
-
}, result: { type: 'object', additionalProperties: false } },
|
|
101
|
-
},
|
|
102
|
-
// Its worktree's diff from the base as Git writes it, not cut (`text/x-diff`; ProductService.diff), or with `path` that
|
|
103
|
-
// of a file `changes` lists, by its whole path (transport/record-streams.mjs).
|
|
104
|
-
streams: {
|
|
105
|
-
diff: { input: { type: 'object', properties: { path: { type: 'string', minLength: 1 } }, additionalProperties: false } },
|
|
106
|
-
},
|
|
107
|
-
// What Coda tells of its sessions (docs/session-contracts.md「事件」), each about the session (`thread:<id>`) but for the two
|
|
108
|
-
// resumes, which are of the turn they go on from (components/workflows/quota-resumes.mjs). In no permission group: open to no
|
|
109
|
-
// plugin's module; a workflow takes one by its name.
|
|
110
|
-
events: {
|
|
111
|
-
'session.opened': { payload: opened },
|
|
112
|
-
'session.facts': { payload: facts },
|
|
113
|
-
'session.quota_exhausted': { payload: quotaSpent },
|
|
114
|
-
'session.agent_exited': { payload: exited },
|
|
115
|
-
'session.quota_resume': { payload: resume('quota', quotaSpent, {}, []) },
|
|
116
|
-
'session.exit_resume': { payload: resume('exit', exited, { attempt: { type: 'integer', minimum: 1 } }, ['attempt', 'resumeAt']) },
|
|
117
|
-
},
|
|
118
|
-
// What a plugin may ask for in its `uses` (docs/plugins.md「用到的权限」), on trial while the protocol is not stable.
|
|
119
|
-
permissions: {
|
|
120
|
-
read: { title: '查看你的会话:标题、所在目录、用的 Agent 与是否归档', trial: true, read: true },
|
|
121
|
-
workspace: { title: '查看会话的工作目录与所在项目', trial: true, operations: ['workspace'] },
|
|
122
|
-
changes: { title: '查看会话里改了哪些文件和完整改动内容', trial: true, operations: ['changes'], streams: ['diff'] },
|
|
123
|
-
'append-draft': { title: '往会话的输入框末尾追加文字', trial: true, operations: ['append-draft'] },
|
|
124
|
-
},
|
|
125
|
-
// Its doing operations are the orchestration's, on the backend that holds the session (kernel/party.mjs).
|
|
126
|
-
side: 'orchestration',
|
|
127
|
-
};
|
|
128
|
-
|
|
129
|
-
// The record of each session here: one per row of `threads`, its envelope from the row, and what it is like — its directory
|
|
130
|
-
// and parent, its title, whether it or its family's root is archived, its agent, the turn of it that ended last. Its revision is what those say.
|
|
131
|
-
const ROW = `SELECT t.id, t.project_id, t.parent_thread_id, t.title, t.archived, t.created_at, t.rowid AS sequence, p.agent,
|
|
132
|
-
(SELECT id FROM turns WHERE thread_id = t.id AND ended_at IS NOT NULL ORDER BY ended_at DESC, rowid DESC LIMIT 1) AS last_turn
|
|
133
|
-
FROM threads t JOIN participants p ON p.id = t.participant_id`;
|
|
134
|
-
const record = (store, row) => {
|
|
135
|
-
if (!row) return null;
|
|
136
|
-
const spec = { project: row.projectId, ...(row.parentThreadId ? { parent: { kind: THREAD, id: row.parentThreadId } } : {}) };
|
|
137
|
-
const status = { title: row.title, archived: !!row.archived, familyArchived: !!store.familyRoot(row.id).archived, agent: row.agent, lastTurn: row.lastTurn ?? null };
|
|
138
|
-
return { kind: THREAD, id: row.id, provider: 'coda', createdAt: new Date(row.createdAt).toISOString(),
|
|
139
|
-
creationSequence: row.sequence, spec, status,
|
|
140
|
-
revision: `${row.id}:${createHash('sha256').update(canonical([spec, status])).digest('hex').slice(0, 16)}` };
|
|
141
|
-
};
|
|
142
|
-
// All of them are read a page at a time by ID, as the table is never read whole.
|
|
143
|
-
export const threadRecords = store => ({
|
|
144
|
-
get: id => record(store, store.one(`${ROW} WHERE t.id = ?`, id)),
|
|
145
|
-
list: () => {
|
|
146
|
-
const records = [];
|
|
147
|
-
for (let after = ''; ;) {
|
|
148
|
-
const page = store.all(`${ROW} WHERE t.id > ? ORDER BY t.id LIMIT 64`, after);
|
|
149
|
-
if (!page.length) return records;
|
|
150
|
-
records.push(...page.map(row => record(store, row))); after = page.at(-1).id;
|
|
151
|
-
}
|
|
152
|
-
},
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
// The queries of Coda's sessions here, through the unified call (components/protocols/calls.mjs `handle`): `workspace`,
|
|
156
|
-
// read from the session's checkout and project; `changes`, as the session's changes are read (`changes(threadId)`,
|
|
157
|
-
// ProductService.changes); and its stream `diff` (`calls.stream`), the same changes as the worktree's whole diff in the
|
|
158
|
-
// bytes Git writes it (`diff(threadId, { path }, signal)`, ProductService.diff).
|
|
159
|
-
export function threadQueries(calls, { store, changes, diff }) {
|
|
160
|
-
calls.handle(THREAD, 'workspace', ({ held }) => {
|
|
161
|
-
const thread = store.thread(held.id), checkout = store.checkout(thread.checkoutId), project = store.project(thread.projectId);
|
|
162
|
-
const state = checkout.state === 'ready' && !existsSync(checkout.path) ? 'gone' : checkout.state;
|
|
163
|
-
return { path: state === 'ready' ? checkout.path : null, project: { id: project.id, name: project.name }, state };
|
|
164
|
-
});
|
|
165
|
-
calls.handle(THREAD, 'changes', ({ held }) => changes(held.id));
|
|
166
|
-
calls.stream(THREAD, 'diff', ({ record, input, signal }) => diff(record.id, input, signal));
|
|
167
|
-
}
|