@coda-console/plugin-check 0.8.21 → 0.8.23

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,167 @@
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
+ }
@@ -9,9 +9,10 @@ import { existsSync, readFileSync, realpathSync } from 'node:fs';
9
9
  import { dirname, join } from 'node:path';
10
10
  import { inflateSync } from 'node:zlib';
11
11
  import './coda/application/contributions.mjs';
12
+ import { HOST_PROTOCOLS } from './coda/application/host-protocols.mjs';
12
13
  import shipped from './coda/builtin.json' with { type: 'json' };
13
14
  import { manifestProblem } from '@coda-console/protocol/validate';
14
- import { offerProblem } from './coda/components/plugins/plugin-extensions.mjs';
15
+ import { offerProblem, protocolDefinition, usesMissing } from './coda/components/plugins/plugin-extensions.mjs';
15
16
  import { choosesModelProviders, pluginEnv, readPlugin, resolveSettings } from './coda/components/plugins/plugin-rules.mjs';
16
17
  import { panelDeclarations } from './coda/resources/plugins/resources/panels/rules.mjs';
17
18
 
@@ -88,7 +89,6 @@ export function checkManifest(dir, say) {
88
89
  const settingCount = Object.keys(plugin.properties).length, names = list => list.map(x => x.name).join('、');
89
90
  if (settingCount) say.pass('manifest.settings', `设置 ${settingCount} 项`);
90
91
  if (plugin.workflows.length || plugin.capabilities.length) say.pass('manifest.capabilities', `流程 ${plugin.workflows.join('、') || '无'},能力 ${plugin.capabilities.join('、') || '无'}`);
91
- if (plugin.events?.length) say.pass('manifest.events', `发布的事件 ${names(plugin.events)}`);
92
92
  if (plugin.commands.length) say.pass('manifest.commands', `会话 PATH 上的命令 ${names(plugin.commands)}`);
93
93
  if (plugin.services.length) say.pass('manifest.services', `开启随包服务 ${plugin.services.join('、')}:没有已安装插件开启的服务不运行`);
94
94
  if (plugin.setup) say.pass('manifest.setup', '设置动作(contributes.setup):一行命令;检查不运行它(可能装软件)');
@@ -108,6 +108,28 @@ export function checkManifest(dir, say) {
108
108
  const found = besideAll(dir, plugin.dependencies);
109
109
  const offered = offerProblem(plugin, new Map([...builtin, ...found]));
110
110
  if (offered) say.fail('manifest.offers', offered);
111
+ // The events its own protocols define (protocol definitions' `events`), and the permission groups of protocols it uses (`uses`; a
112
+ // group with `events` is subscribing to all of them), as far as the protocols are here: its own, Coda's core, or a plugin's beside it.
113
+ for (const definition of plugin.protocols ?? [])
114
+ for (const [name, event] of Object.entries(definition.events ?? {})) say.pass('manifest.events', `协议 ${definition.name} 定义的事件 ${name}:starts ${event.starts ?? true},ends ${event.ends ?? false}`);
115
+ const protocols = new Map([...builtin, ...found, [plugin.id, plugin]]);
116
+ // Coda's own protocols, as Coda judges a plugin's `uses` against them (application/host-protocols.mjs).
117
+ const hosted = kind => HOST_PROTOCOLS.find(one => one.kind === kind);
118
+ for (const [kind, groups] of Object.entries(plugin.uses ?? {})) {
119
+ const definition = protocolDefinition(kind, protocols, hosted);
120
+ // A group the definition lacks is Coda's to refuse (usesMissing, as Coda does at install); a definition not here is only said.
121
+ const missing = definition && usesMissing({ ...plugin, uses: { [kind]: groups } }, protocols, hosted);
122
+ if (missing) say.fail('manifest.uses', `插件 ${plugin.id} 用到的协议 ${kind} 没有权限组 ${missing.group}`);
123
+ else for (const group of groups) {
124
+ const events = definition?.permissions[group].events;
125
+ if (!definition) say.info('manifest.events', `用到 ${kind} 的权限组 ${group}:协议定义不在本地,列不出事件`);
126
+ else if (events) {
127
+ say.pass('manifest.events', `用到 ${kind} 的事件组 ${group}:${events.join('、')}`);
128
+ if (!plugin.main) say.warn('manifest.events-main', `订了事件组 ${kind} ${group},但没有 main,收不到事件`);
129
+ }
130
+ else say.pass('manifest.events', `用到 ${kind} 的权限组 ${group}:不含事件`);
131
+ }
132
+ }
111
133
  // Its resource types, or the panels before them, as the resources plugin reads what is written for its point once that is
112
134
  // of the point's schema: one declaring types has those alone.
113
135
  const format = plugin.offers?.resources ? 'resources' : 'panels', what = format === 'resources' ? '资源类型' : '面板';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coda-console/plugin-check",
3
- "version": "0.8.21",
3
+ "version": "0.8.23",
4
4
  "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源类型(与旧的面板)。",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@0dep/piso": "5.2.0",
26
26
  "@agentclientprotocol/sdk": "2.6.0",
27
- "@coda-console/protocol": "6.12.0",
27
+ "@coda-console/protocol": "6.14.0",
28
28
  "ajv": "8.20.0",
29
29
  "yaml": "2.9.1"
30
30
  },