@coda-console/protocol 6.22.0 → 6.23.0

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/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  版本规矩见 README 的[「版本」一节](README.md#版本)。协议自己的大版本写在协议名里(如 `coda/run@1`),与 npm 包版本、插件清单的 v2 独立;更早的版本见 git 历史。
4
4
 
5
+ ## 6.23.0 — 2026-11-23
6
+
7
+ - 这是在 6.22.0 之上的次版本。依据 README「版本」一节:新增导出是内部面,升次版本;`stable/` 不动,清单与协议的 schema 没改。这一版把 `@coda-console/plugin-check` 里不依赖 Coda 宿主运行时的两样迁进本包,供 Coda 与各插件仓库直接依赖。
8
+ - 新增导出 `./types`(`plugin.d.mts`):插件模块的公开 TypeScript 类型(`Json`、`Ref`、`KeyRef`、`Context`、`Handler`、`Coda`、`ViewInstance` 等),与此前 `plugin-check` 的 `./types` 同源,只去掉了测试宿主专用的声明(`TestHost`、`TestPlugin`、`TestCallOptions`、`ProtocolImplementation`、`createTestHost`、`TEST_OWNER`)。TypeScript 与 `@ts-check` 的 JSDoc 都能解析。
9
+ - `./validate` 新增 `resourceRecordsProblem(output)`:一个插件为 `coda/resource@1` 写的记录(命令输出,已解析)按 Coda 收的标准查,合乎返回 `null`,否则是第一处问题的说明,按记录在数组里的位置说。查的是:顶层为数组;每条序列化后至多 64 KiB(不能序列化的,如循环引用、BigInt,说出原因,不抛);每条是不带 `id` 的对象,`key` 为 1–256 个字符、不含 NUL 且不重复;除 `key` 外只有 `spec`、`status`、`labels`,`labels` 写了须为 `null` 或值为文本的对象;`spec`、`status`(写了才查)合 `RESOURCE_PROTOCOL` 的 schema;`spec.type` 与 `key` 相同;按钮的 `args` 序列化后至多 4096 字节。纯函数,不读文件、不跑命令。`validate.mjs` 与 `protocol.mjs` 共用同一份 `RESOURCE_PROTOCOL`(新增内部文件 `resource-protocol.mjs`,随包发布,不是导出);`./protocol` 的导出不变。
10
+ - `./types` 引用了 `node:http`、`node:stream` 的类型,类型检查时使用方须自己装 `@types/node`;本包不依赖它。
11
+
5
12
  ## 6.22.0 — 2026-11-22
6
13
 
7
14
  - 这是在 6.21.0 之上的次版本。依据 README「版本」一节:新增可选的清单键升次版本;`optionalUses` 暂不进稳定面,`stable/` 不动,旧清单不受影响。
package/README.md CHANGED
@@ -68,6 +68,15 @@ invocationRequestProblem({ record: { kind: 'coda/session@1', id: 'chat-1' }, ope
68
68
  invocationResponseProblem({ run: { kind: 'coda/run@1', id: 'run-1' } });
69
69
  ```
70
70
 
71
+ ```js
72
+ import { resourceRecordsProblem } from '@coda-console/protocol/validate';
73
+
74
+ // 插件写 coda/resource@1 记录时,命令输出(已解析的 JSON)按 Coda 收的标准查:合乎返回 null,否则是第一处问题,按记录在数组里的位置说。
75
+ // 数组里每条 { key, spec, status?, labels? }:序列化后至多 64 KiB,key 为 1–256 个字符、不含 NUL 且不重复,不写 id,spec、status 合协议的 schema,
76
+ // spec.type 与 key 相同,按钮的 args 序列化后至多 4096 字节。纯函数,不读文件、不跑命令。
77
+ const problem = resourceRecordsProblem(JSON.parse(output));
78
+ ```
79
+
71
80
  ```js
72
81
  import { readFrames, writeFrames } from '@coda-console/protocol/frames';
73
82
 
@@ -102,6 +111,18 @@ optionsProblem([{ id: 'release', name: '发布正式版', default: false, inputs
102
111
 
103
112
  `TYPES` 是清单 schema 自己校验的通用键(4.0.0 起不含 `agents` 等 Coda 业务键),`SCHEMAS` 是 `schemas/plugin/` 里的全部 schema(按文件名),包括业务键的。协议定义的 schema 在 `schemas/protocol/v1/`,由 `@coda-console/protocol/protocol` 导出。
104
113
 
114
+ ## 插件的类型
115
+
116
+ `@coda-console/protocol/types`(`plugin.d.mts`)是插件模块的公开 TypeScript 类型:调用与处理(`Context`、`Handler`、`Caller`)、记录(`Ref`、`KeyRef`、`RecordValue`、`RecordFilter`、`RecordChange`)、页面(`ViewInstance`)和模块里的 `coda` 对象(`Coda`)等。它们属于内部面,随 Coda 的版本可能变。TypeScript 与 `// @ts-check` 的 JSDoc 都能解析(`moduleResolution` 为 `node16`、`nodenext` 或 `bundler`):
117
+
118
+ ```js
119
+ // @ts-check
120
+ /** @param {import('@coda-console/protocol/types').Context} ctx */
121
+ export async function handle(ctx) {}
122
+ ```
123
+
124
+ `./types` 引用了 `node:http` 与 `node:stream` 的类型,用 TypeScript 或 `@ts-check` 做类型检查时,使用方须自己安装 `@types/node`;本包不把它列入 `dependencies`。
125
+
105
126
  ## 插件的后端通道
106
127
 
107
128
  插件清单可以声明 `"coda": { "channels": ["preview"] }`,限定只在预览版后端安装和更新。允许的通道是 `stable`(正式版)和 `preview`(预览版);数组非空、不重复。不写 `channels` 的插件不限制通道。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coda-console/protocol",
3
- "version": "6.22.0",
3
+ "version": "6.23.0",
4
4
  "description": "Coda 的协议:插件清单的类型(JSON Schema)、通用校验器、协议定义与调用信封、流程方言与 Agent 接入协议",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -19,8 +19,10 @@
19
19
  "workflow.mjs",
20
20
  "docs",
21
21
  "protocol.mjs",
22
+ "resource-protocol.mjs",
22
23
  "frames.mjs",
23
24
  "blob.mjs",
25
+ "plugin.d.mts",
24
26
  "CHANGELOG.md",
25
27
  "stable"
26
28
  ],
@@ -35,6 +37,7 @@
35
37
  "./protocol": "./protocol.mjs",
36
38
  "./frames": "./frames.mjs",
37
39
  "./blob": "./blob.mjs",
40
+ "./types": "./plugin.d.mts",
38
41
  "./stable/*": "./stable/*"
39
42
  },
40
43
  "engines": {
package/plugin.d.mts ADDED
@@ -0,0 +1,396 @@
1
+ // Types of what a plugin's module queries and answers by (docs/plugins.md「调用」, coda#2749 3.1 and 第 7 节), and of the
2
+ // records (coda#2749 3.7), as `@coda-console/protocol/types`. All on the trial surface: they may change from one version of
3
+ // Coda to the next. Only these members of `coda` are typed here; the others are not yet.
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { Readable, Writable } from 'node:stream';
6
+
7
+ export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
8
+ /** A record: its protocol and its ID, the space's one. */
9
+ export type Ref = { kind: string; id: string };
10
+ /**
11
+ * A record this plugin writes, as it names it: its protocol and the plugin's own key (1–256 characters: a device's udid,
12
+ * `account:group`, a source's name). Its ID is derived by the host from this backend, the plugin, the kind and the key,
13
+ * the same every time; the plugin makes no ID, nor keeps a table from its keys to IDs.
14
+ */
15
+ export type KeyRef = { kind: string; key: string };
16
+ /** A record a call is of, as its handler is given it: with its `key` when it is this plugin's own on this machine. */
17
+ export type HandledRef = Ref & { key?: string };
18
+ /** How much a call that failed did: nothing, some of it, or none can say. */
19
+ export type Effects = 'none' | 'some' | 'unknown';
20
+
21
+ /**
22
+ * A blob pointer, as `coda.pointer` makes it: which machine has the content (`owner`, its ID) and where there (`path`), with
23
+ * what its writer says of it. A reader takes it to Coda as it is; a pointer is not the content.
24
+ */
25
+ export interface BlobPointer {
26
+ owner: string;
27
+ path: string;
28
+ name?: string;
29
+ size?: number;
30
+ mime?: string;
31
+ /** Of the whole content, lowercase hex. */
32
+ sha256?: string;
33
+ }
34
+
35
+ /** A failed call, as its caller sees it and as `coda.error` makes it. */
36
+ export interface CallError extends Error {
37
+ code: string;
38
+ effects?: Effects;
39
+ retryAfterMs?: number;
40
+ }
41
+
42
+ export interface QueryOptions {
43
+ /** Going off, the call is given up: it fails as an `AbortError`. */
44
+ signal?: AbortSignal;
45
+ /** Milliseconds; at most the operation's own `timeout`, or 30 seconds. */
46
+ timeout?: number;
47
+ }
48
+
49
+ export interface CallOptions {
50
+ /**
51
+ * The call's idempotency key, by default a new one: made again with the same key and the same content, it is the same call,
52
+ * not done again, its outcome the first one's; with other content it is refused (`idempotency_conflict`, `none`).
53
+ */
54
+ id?: string;
55
+ /** Going off, the call is cancelled and not waited on: it fails as an `AbortError`. */
56
+ signal?: AbortSignal;
57
+ /** Milliseconds it is waited on; past them it is given up (its callee asked to cancel) and fails as a `TimeoutError`. */
58
+ timeout?: number;
59
+ /** How the call goes, as its handler says it (`ctx.progress`): a hint; only the latest is kept, and it may be lost. */
60
+ onProgress?(value: Json): void;
61
+ }
62
+
63
+ /**
64
+ * Who is before the page that made a doing call: Coda's own client on this machine, or a device, with its name if known.
65
+ * A call forwarded to the backend that holds the record has no `local` but the `machine` it was made from (that one's ID),
66
+ * a device kept as it is: so `{ machine }` or `{ machine, device, name? }`.
67
+ */
68
+ export type Caller = { local: true } | { device: string; name?: string } | { machine: string; device?: string; name?: string };
69
+
70
+ /** What a handler of a call is given beside its input. A handler of a query, and `resume`, have no `progress` nor `ask`. */
71
+ export interface Context {
72
+ /** This call's ID, the host's, unique: the same for the same caller's same request. */
73
+ id: string;
74
+ /** The record the call is of; with its `key` when it is this plugin's own. */
75
+ record: HandledRef;
76
+ /**
77
+ * Goes off when the caller gives up or cancels (`AbortError`) or the deadline passes (a query's `timeout`, a doing
78
+ * call's `TimeoutError`). A doing call's handler still ends it: thrown its reason, it is cancelled or timed out.
79
+ */
80
+ signal: AbortSignal;
81
+ /** When the call's time is up, in milliseconds since the epoch; a doing call may have none. */
82
+ deadline: number | null;
83
+ /** `coda.query` under this call: given up on with it, and given at most the time it has left. Only queries. */
84
+ query: Coda['query'];
85
+ /**
86
+ * `coda.spawn` under this call: ended as `signal` goes off, and, still running, once the call has ended (its handler
87
+ * returned or threw, or the host ended it). One `name`d outlives it.
88
+ */
89
+ spawn: Coda['spawn'];
90
+ /** A doing call's: how it goes, a hint; only the latest is kept, and it may be lost. */
91
+ progress?(value: Json): void;
92
+ /** A doing call's: a question to whoever answers it, its answer once given; one at a time. */
93
+ ask?(question: Json): Promise<Json>;
94
+ /**
95
+ * A doing call's handler's, and its `resume`'s: `coda.call` made by this call, so that it is cancelled as this call is;
96
+ * given up on with it, and given at most the time it has left. Made again by the same `id` in `resume`, it is the call
97
+ * made before the process ended, its outcome waited on again.
98
+ */
99
+ call?: Coda['call'];
100
+ /**
101
+ * A doing call's, made from a plugin's page: who is before that page, as Coda knows it, never as the page says. None
102
+ * for a call a module (`coda.call`), a command (`coda call`) or a flow makes.
103
+ */
104
+ caller?: Caller;
105
+ }
106
+
107
+ /** Its return value is the result; what it throws, the failure (`coda.error`, or anything else as `handler_error`). */
108
+ export type Handler = (input: Json, ctx: Context) => Json | Promise<Json>;
109
+ /**
110
+ * Who asks a service or a stream: this machine's own client or tools, a device, another backend of the space (the last hop,
111
+ * of one sent on), or a plugin (by its token, or from its page; a stream's only).
112
+ */
113
+ export type StreamCaller = { local: true } | { device: string; role: 'client' | 'backend'; name?: string } | { plugin: string };
114
+ /** What a handler of a service (`coda.serve`) is given beside its request. */
115
+ export interface ServeContext {
116
+ caller: StreamCaller;
117
+ /** Goes off when the caller leaves before the answer is done; `request.signal` goes off with it. */
118
+ signal: AbortSignal;
119
+ }
120
+ /** What a handler of a record's stream (`coda.stream`) is given beside its request. */
121
+ export interface StreamContext extends ServeContext {
122
+ /** The record the stream is of; with its `key` when it is this plugin's own. */
123
+ record: HandledRef;
124
+ /** Its parameters, from the query string, as the definition's `input` has them; none (`{}`) of an `http` stream. */
125
+ input: Record<string, string>;
126
+ }
127
+ /**
128
+ * Web standard, both ways: `request.url` has the path below the service or the stream and the query string as asked,
129
+ * `request.headers` those of content and negotiation, `request.body` (of any method but `GET` and `HEAD`) the bytes as they
130
+ * come, read no further ahead than the handler reads them. The `Response`'s status, headers of content and body are what the
131
+ * caller is answered, the body as it comes, its head with its first byte. Thrown before that, by the handler or the body it
132
+ * gave, a failure is the answer (`{ error: { code, message, effects } }`, as `coda.error` says it, or `handler_error`); after
133
+ * it, the connection is broken off.
134
+ */
135
+ export type ServeHandler = (request: Request, ctx: ServeContext) => Response | Promise<Response>;
136
+ export type StreamHandler = (request: Request, ctx: StreamContext) => Response | Promise<Response>;
137
+
138
+ /** A doing call handed to a process of the plugin's that ended before its handler did. */
139
+ export interface Interrupted {
140
+ /** The call's ID, as its handler was given it (`ctx.id`). */
141
+ id: string;
142
+ record: HandledRef;
143
+ op: string;
144
+ input: Json;
145
+ /** The last progress its handler gave, only a hint: no evidence of what was done. */
146
+ progress: Json | null;
147
+ /** Whether it was asked to be cancelled. */
148
+ canceled: boolean;
149
+ }
150
+ /**
151
+ * Says how such a call ended, as a handler does, once a later process of the plugin's has the module activated: its
152
+ * return value the result, what it throws the failure. Given 30 seconds; its `ctx` is a query's handler's (no `progress`
153
+ * nor `ask`). Asked to be cancelled, or past its deadline, before it is called, its `ctx.signal` has gone off already
154
+ * (`AbortError`, `TimeoutError`). It may be called more than once, its process ending meanwhile: it only says, and does
155
+ * nothing.
156
+ */
157
+ export type Resume = (call: Interrupted, ctx: Context) => Json | Promise<Json>;
158
+
159
+ export interface Disposable { dispose(): void }
160
+
161
+ export interface SpawnOptions {
162
+ /** Its working directory; by default the plugin's directory. */
163
+ cwd?: string;
164
+ /** Added over the environment of the plugin's processes. */
165
+ env?: Record<string, string>;
166
+ /**
167
+ * One of the names the manifest's `contributes.processes` declares: the process outlives the call or the module that
168
+ * started it, until it exits or the plugin is uninstalled. One at a time: while one of the name runs, another fails
169
+ * (`conflict`). It has no input, and its output goes to `<plugin's state directory>/processes/<name>.log`, written anew
170
+ * each time it starts and never rotated: its handle's streams are `null`.
171
+ */
172
+ name?: string;
173
+ }
174
+
175
+ /** A process the host started for the module, as Node's ChildProcess has the most of it. */
176
+ export interface Process {
177
+ pid: number;
178
+ /** `null` for a named one, as for a ChildProcess whose stdio is not piped. */
179
+ stdin: Writable | null;
180
+ /**
181
+ * Read it, or `resume()` it to drop it: what is not read holds the process once a window of it waits. `null` for a
182
+ * named one: its output is in its log.
183
+ */
184
+ stdout: Readable | null;
185
+ stderr: Readable | null;
186
+ /**
187
+ * Once the process has exited and all of `stdout` and `stderr` is in them, ended. Fails (`interrupted`) if the
188
+ * plugin's host stops first: the host ends the process.
189
+ */
190
+ exited: Promise<{ code: number | null; signal: string | null }>;
191
+ /** Sends it `signal` (SIGTERM by default), the process alone, as `ChildProcess.kill` does. */
192
+ kill(signal?: string): void;
193
+ }
194
+
195
+ export interface Settings {
196
+ /** This plugin's own settings as they are now (secrets are not among them); asked each time. */
197
+ get(): Promise<Json>;
198
+ /** Told the new settings after they are written; `dispose()` stops it, as does the module stopping. */
199
+ onChange(fn: (settings: Json) => void): Disposable;
200
+ }
201
+
202
+ /**
203
+ * A record as it is read (`get`, `list`, `watch`): its holder's backend (`owner`) and the machine it is on (`location`),
204
+ * its own ID, the plugin that holds it (`plugin`; `coda` for Coda's own), the key this plugin named it by (only of its own
205
+ * on this machine; no other plugin, nor any other machine, is told it), whether it is this machine's (`local`: the holder's original; another's is a copy, which only its holder
206
+ * writes), its spec and status as written, the records they refer to by their IDs (`get` reads them wherever they are
207
+ * held), its labels, and a version that changes as it does. In a space every machine's records are read on every other but
208
+ * Coda's composers and submissions, only on the machine that wrote them, and its runs and cards, which the catalog does not take.
209
+ */
210
+ export interface Entry {
211
+ owner: string;
212
+ location: string;
213
+ id: string;
214
+ plugin: string;
215
+ key?: string;
216
+ local: boolean;
217
+ spec: { [key: string]: Json };
218
+ status: { [key: string]: Json };
219
+ labels?: Record<string, string>;
220
+ version: string;
221
+ }
222
+ /**
223
+ * A record as `put` writes it, and `replace` each: its spec and its labels (none: none) whole; its status as given, or, not
224
+ * given, as the record has it (a new one's empty), as a status is the one's that keeps it so.
225
+ */
226
+ export interface RecordValue {
227
+ spec: { [key: string]: Json };
228
+ status?: { [key: string]: Json };
229
+ labels?: Record<string, string>;
230
+ }
231
+ /** `local`: this machine's records only; `available` (by default): every machine's in the space. `id`: of that ID only. */
232
+ export interface RecordFilter { scope?: 'local' | 'available'; id?: string }
233
+ /** A record read anew, made or gone: by its ID, as it is now, or as it was last. */
234
+ export interface RecordChange { type: 'ADDED' | 'MODIFIED' | 'DELETED'; id: string; entry: Entry }
235
+
236
+ /** An event, as a module's handler of it is given it (`coda.on`). */
237
+ export interface Event {
238
+ /** Its name, the full dotted one (`pull_request.closed`), one on this machine. */
239
+ name: string;
240
+ /** The protocol it is of, with its major version (`github/pull-request@1`): the event's version. */
241
+ kind: string;
242
+ /** What it is about, `<kind>:<id>`. */
243
+ subject: string;
244
+ /** The ID of the project of this machine it was published in. */
245
+ project: string;
246
+ /** What it says, as its protocol's payload schema has it. */
247
+ data: { [key: string]: Json };
248
+ /** The ID of the plugin that published it; `coda` for Coda's own. */
249
+ publisher: string;
250
+ }
251
+
252
+ export interface Coda {
253
+ /** Handles an operation of a protocol the plugin implements: a query (`safe`) or a doing call (any other, `idempotent` among them). */
254
+ handle(kind: string, operation: string, handler: Handler | { run: Handler; resume?: Resume }): Disposable;
255
+ /** `self` is no protocol: `handle('self', …)` throws `invalid_input`. */
256
+ self: {
257
+ /**
258
+ * Handles a query only the plugin's own processes make (`coda self <name> [input]`), listed in no manifest: its
259
+ * `ctx.record` is `{ kind: 'self', id: <plugin's ID> }`; given 30 seconds; one not registered fails as `not_found`.
260
+ */
261
+ handle(name: string, handler: Handler): Disposable;
262
+ };
263
+ /** Queries a record: only a `safe` operation. Fails with a `CallError`, its `effects` always `none`. */
264
+ query(record: Ref, operation: string, input?: Json, options?: QueryOptions): Promise<Json>;
265
+ /**
266
+ * Does an operation of a record that is not `safe` (an `idempotent` one too), as this plugin, through Coda's call kernel: its
267
+ * result. Fails with a `CallError`, its `code` and `effects` as the callee said them; cancelled, as an `AbortError`; past
268
+ * `timeout`, as a `TimeoutError`.
269
+ */
270
+ call(record: Ref, operation: string, input?: Json, options?: CallOptions): Promise<Json>;
271
+ error(code: string, message: string, more?: { effects?: Effects; retryAfterMs?: number }): CallError;
272
+ /**
273
+ * Starts a process for the module: until it stops (the plugin host's process ends, the plugin is uninstalled), or, with
274
+ * `name`, beyond it. What it leaves in its group as it exits is ended with it. Fails as `spawn_failed`: of `none`
275
+ * effect if it never started, of `unknown` if it started and could not be registered (killed with its group at once).
276
+ */
277
+ spawn(command: string, args?: string[], options?: SpawnOptions): Promise<Process>;
278
+ /**
279
+ * Serves the plugin's own bytes at `/v1/plugins/<plugin>/services/<id>/…`, any method a standard
280
+ * `Request` takes: all but `CONNECT`, `TRACE` and `TRACK`. Done once Coda has it; the handle's
281
+ * `dispose()` withdraws it and breaks off its exchanges. Throws for an ID a service of the plugin has already
282
+ * (`services.register`'s among them).
283
+ */
284
+ serve(id: string, handler: ServeHandler): Promise<{ dispose(): Promise<void> }>;
285
+ /**
286
+ * Implements a stream of the records this plugin holds of a protocol it implements, the stream one the protocol's definition
287
+ * has; otherwise it throws at once. Done once Coda has it; `dispose()` as `serve`'s.
288
+ */
289
+ stream(kind: string, name: string, handler: StreamHandler): Promise<{ dispose(): Promise<void> }>;
290
+ /** Frame streams: ndjson, one JSON object a line, a blank line a heartbeat. As `@coda-console/protocol/frames` has them. */
291
+ frames: Readonly<{
292
+ /** The frames of a body, heartbeats skipped; fails with `code` `truncated`, `too_large` (a line over `maxBytes`, by default 1 MiB) or `invalid`. */
293
+ read(stream: ReadableStream<Uint8Array>, options?: { maxBytes?: number }): AsyncIterableIterator<{ [key: string]: Json }>;
294
+ /** A body of the iterable's objects; with `heartbeatMs`, a blank line whenever nothing has been written for that long. */
295
+ write(iterable: Iterable<{ [key: string]: Json }> | AsyncIterable<{ [key: string]: Json }>, options?: { heartbeatMs?: number }): ReadableStream<Uint8Array>;
296
+ }>;
297
+ /**
298
+ * A pointer to content of one of the plugin's own services, on this machine: `path`, what is below the service, as it is
299
+ * (not encoded, segments between `/`); `extra`, what it says of the content. Throws a `TypeError` for no pointer: a service
300
+ * ID that is none, a path with an empty, `.` or `..` segment or a `\`, too long, an `extra` with anything else. Whether the
301
+ * service is registered is not asked.
302
+ */
303
+ pointer(service: string, path: string, extra?: { name?: string; size?: number; mime?: string; sha256?: string }): BlobPointer;
304
+ /** This plugin's own settings. */
305
+ settings: Settings;
306
+ /**
307
+ * One record of a kind, of its ID (a record's ID is the space's one): this machine's, else the one another machine
308
+ * holds; `null` for none. Read after what the module wrote before.
309
+ */
310
+ get(record: Ref): Promise<Entry | null>;
311
+ /** The records of a kind, this machine's first; read after what the module wrote before. */
312
+ list(kind: string, filter?: RecordFilter): Promise<Entry[]>;
313
+ /**
314
+ * Watches a kind's records: each there is given as `ADDED` first, then each change. Gone over again whole if the host
315
+ * restarts (the module is activated anew). Done once the first are given.
316
+ */
317
+ watch(kind: string, fn: (change: RecordChange) => void, filter?: RecordFilter): Promise<Disposable>;
318
+ /**
319
+ * Makes or replaces a record this plugin holds (`RecordValue`), or makes one of a kind it implements, by its key; another's
320
+ * it may not write (`forbidden`). What people read of it is in its spec. Done once it is read so, with its entry (its
321
+ * `id`, the host's, and its `key`); refused (`invalid_input` for a key not 1–256 characters, an `id` given, or a value
322
+ * its kind's schemas, or the space's 64 KiB a record, refuse; `conflict` for a group named as another here), nothing was
323
+ * written. The module's writes are done one after another, as it made them.
324
+ */
325
+ put(record: KeyRef, value: RecordValue): Promise<Entry>;
326
+ /** Deletes a record this plugin holds, by its key; one not there is no failure. */
327
+ delete(record: KeyRef): Promise<void>;
328
+ /**
329
+ * Every record this plugin holds of a kind, given whole by their keys: each written as `put` writes it, and those it
330
+ * holds and no longer gives deleted; another plugin's of the kind are left. All of it is done, or nothing; done, with
331
+ * the entries given, in their order.
332
+ */
333
+ replace(kind: string, entries: (RecordValue & { key: string })[]): Promise<Entry[]>;
334
+ /**
335
+ * Handles an event the plugin subscribes to: one of an event group in its `uses`, any other throwing at once (`forbidden`).
336
+ * Given each one published in a project the plugin applies in, at most once, while the module is activated; not sorted by
337
+ * subject. What it throws is logged; the event is not given again.
338
+ */
339
+ on(name: string, fn: (event: Event) => void): Disposable;
340
+ /** Trial. The plugin itself: its ID, its directory, and its state directory on this backend (`null` when the backend has no state root). */
341
+ plugin: Readonly<{ id: string; path: string; state: string | null }>;
342
+ /**
343
+ * Trial. To be withdrawn: use `serve`. Local streaming services: `register` serves `id` on this machine (an HTTP handler, given the caller as Coda
344
+ * names it), done once Coda has it; the handle's `dispose()` withdraws it and closes its connections.
345
+ */
346
+ services: Readonly<{
347
+ register(id: string, handler: (request: IncomingMessage, response: ServerResponse, caller: Readonly<{ [key: string]: Json }>) => void | Promise<void>): Promise<{ dispose(): Promise<void> }>;
348
+ }>;
349
+ /** Trial. The plugin's own pages: `register` the provider of a view the manifest declares (`contributes.views`); its `open` is called each time one is opened. */
350
+ views: Readonly<{ register(id: string, provider: { open(view: ViewInstance): void | Promise<void> }): { dispose(): void } }>;
351
+ /** Trial. Protocol contributions: a contributor to another protocol's records, and an upload of this machine's. */
352
+ protocols: Readonly<{
353
+ register(kind: string, key: string, handler: (object: ProtocolObject, key: string) => Contribution | null | Promise<Contribution | null>): Disposable;
354
+ upload(id: string): Promise<{ id: string; name: string; size: number; path: string; mime?: string; duration?: number; [key: string]: Json | undefined }>;
355
+ }>;
356
+ /** Trial. Tells a session's agent something, told with its next turn and waking nothing; `told` is `false` for a session archived. */
357
+ tell(session: string, text: string): Promise<{ told: boolean }>;
358
+ /** Trial. Runs an installed plugin's environment setup again, asked as this plugin. */
359
+ pluginSetup: Readonly<{ retry(plugin: string): Promise<Json> }>;
360
+ }
361
+
362
+ /** The record or draft a protocol hands a contributor, without who created it: its `spec` and `status` are objects the protocol's schemas describe. */
363
+ export interface ProtocolObject {
364
+ kind: string;
365
+ id: string;
366
+ spec: { [key: string]: Json };
367
+ status: { [key: string]: Json };
368
+ }
369
+
370
+ /** What a contributor adds: only the fields the protocol declares as contributions, each of the value the protocol says (an object, not a list or a scalar); `null` adds nothing. */
371
+ export type Contribution = { [field: string]: Json };
372
+
373
+ /** A page of the plugin's, opened, as its view provider's `open` is given it. */
374
+ export interface ViewInstance {
375
+ /** This opening's ID. */
376
+ id: string;
377
+ /** The view's ID. */
378
+ view: string;
379
+ /** What the page was opened beside: the session's ID, and the `args` of the button or card that opened it; `null` for none. */
380
+ context: { session: string | null; args: Json | null };
381
+ /** Who opened it: this machine's client (`{ local: true }`) or a device. */
382
+ caller: { local?: boolean; device?: string; name?: string };
383
+ /** Sends the page a message; `false` once the page is gone. */
384
+ postMessage(message: Json): boolean;
385
+ /** A collection handed to the page: `set` and `delete` give whether the page was told anything. */
386
+ collection(name: string): {
387
+ set(id: string, object: { [key: string]: Json }): boolean;
388
+ delete(id: string): boolean;
389
+ get(id: string): { [key: string]: Json } | undefined;
390
+ keys(): string[];
391
+ };
392
+ /** Each returns a handle that stops it. */
393
+ onMessage(fn: (message: Json) => void): Disposable;
394
+ onContext(fn: (context: ViewInstance['context']) => void): Disposable;
395
+ onClose(fn: () => void): Disposable;
396
+ }
package/protocol.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // record format (spec/status JSON Schemas) and operations (input plus an immediate result schema or a run reference).
3
3
  // Nothing here reads a live Coda store or decides who may call what.
4
4
  import { readFileSync } from 'node:fs';
5
+ import { RESOURCE_PROTOCOL } from './resource-protocol.mjs';
5
6
  import { explain, newAjv } from './validate.mjs';
6
7
 
7
8
  const base = new URL('./schemas/protocol/v1/', import.meta.url);
@@ -15,7 +16,7 @@ export const AGENT_PROTOCOL = read('agent.json');
15
16
  export const SESSION_PROTOCOL = read('session.json');
16
17
  export const ENVIRONMENT_PROTOCOL = read('environment.json');
17
18
  export const CARD_PROTOCOL = read('card.json');
18
- export const RESOURCE_PROTOCOL = read('resource.json');
19
+ export { RESOURCE_PROTOCOL };
19
20
  export const CORE_PROTOCOLS = Object.freeze(Object.fromEntries(
20
21
  [RUN_PROTOCOL, AGENT_PROTOCOL, SESSION_PROTOCOL, ENVIRONMENT_PROTOCOL, CARD_PROTOCOL, RESOURCE_PROTOCOL].map(protocol => [protocol.name, protocol])));
21
22
 
@@ -0,0 +1,5 @@
1
+ // The definition of `coda/resource@1`, read once for protocol.mjs (which exports it) and validate.mjs (which judges a plugin's
2
+ // records by it, and which protocol.mjs imports, so it cannot import protocol.mjs back).
3
+ import { readFileSync } from 'node:fs';
4
+
5
+ export const RESOURCE_PROTOCOL = JSON.parse(readFileSync(new URL('./schemas/protocol/v1/resource.json', import.meta.url), 'utf8'));
package/validate.mjs CHANGED
@@ -27,6 +27,7 @@ import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } fr
27
27
  import { isAbsolute, join, normalize, sep } from 'node:path';
28
28
  import { fileURLToPath } from 'node:url';
29
29
  import Ajv2020 from 'ajv/dist/2020.js';
30
+ import { RESOURCE_PROTOCOL } from './resource-protocol.mjs';
30
31
 
31
32
  export const SCHEMA_DIR = fileURLToPath(new URL('./schemas/plugin/', import.meta.url));
32
33
  const BASE = 'https://coda.pub/schemas/plugin/v2/';
@@ -334,3 +335,59 @@ export function contributionProblem(schema, manifest, key, dir = null) {
334
335
  return point.validate.call({ dir }, manifest.contributes[key], { instancePath: `/contributes/${escape(key)}`, parentData: manifest.contributes,
335
336
  parentDataProperty: key, rootData: manifest, dynamicAnchors: {} }) ? null : explain(point.validate.errors, '', [point.schema]);
336
337
  }
338
+
339
+ // The serialized size of a value in UTF-8 bytes, `{ ok: true, bytes }`, or why it has none, `{ ok: false, error }`: what
340
+ // `JSON.stringify` refuses (a circular structure, a BigInt) or a `toJSON` throws, which may be any value.
341
+ function sized(value) {
342
+ try { const text = JSON.stringify(value); return { ok: true, bytes: text === undefined ? 0 : Buffer.byteLength(text) }; }
343
+ catch (thrown) { return { ok: false, error: thrown instanceof Error ? thrown.message || thrown.name || 'Error' : typeof thrown === 'string' && thrown ? thrown : `抛出了 ${typeof thrown === 'object' && thrown !== null ? Object.prototype.toString.call(thrown) : String(thrown)}` }; }
344
+ }
345
+ // A value as an error message names it, which never throws.
346
+ function shown(value) {
347
+ try { return JSON.stringify(value) ?? String(value); } catch { return Object.prototype.toString.call(value); }
348
+ }
349
+ // What Coda holds the records a plugin's command prints to, beyond the schema: a record at most 64 KiB serialized, a button's
350
+ // `args` at most 4096 bytes.
351
+ const RECORD_BYTES = 64 * 1024, ARGS_BYTES = 4096;
352
+ // What is wrong with the records a plugin writes of `coda/resource@1` (`output`, an array of `{ key, spec, status?, labels? }`, as
353
+ // parsed), judged as Coda takes them before it replaces the plugin's whole set of the kind: null, or the first thing found,
354
+ // naming the record by its place in the array. Nothing is read or run; the same value always has the same answer.
355
+ export function resourceRecordsProblem(output) {
356
+ if (!Array.isArray(output)) return '记录须为数组';
357
+ for (const [i, record] of output.entries()) {
358
+ const size = sized(record);
359
+ if (!size.ok) return `第 ${i + 1} 条记录无法序列化为 JSON:${size.error}`;
360
+ if (size.bytes > RECORD_BYTES) return `第 ${i + 1} 条记录超过 ${RECORD_BYTES / 1024} KiB`;
361
+ }
362
+ const keys = new Set();
363
+ for (const [i, record] of output.entries()) {
364
+ if (record === null || typeof record !== 'object' || Array.isArray(record)) return `第 ${i + 1} 条记录须为 { key, spec, status?, labels? }`;
365
+ if (Object.hasOwn(record, 'id')) return `第 ${i + 1} 条记录不能写 id:插件只给 key,id 由宿主派生`;
366
+ const { key } = record;
367
+ if (typeof key !== 'string' || key.length === 0 || key.length > 256 || key.includes('\0'))
368
+ return `第 ${i + 1} 条记录的 key 须为 1–256 个字符、不含 NUL 的文本,不是 ${shown(key)}`;
369
+ if (keys.has(key)) return `第 ${i + 1} 条记录的 key 重复:${key}`;
370
+ keys.add(key);
371
+ }
372
+ for (const [i, { key, ...value }] of output.entries()) {
373
+ const at = `第 ${i + 1} 条记录(${key})`;
374
+ const extra = Object.keys(value).find(name => !['spec', 'status', 'labels'].includes(name));
375
+ if (extra !== undefined) return `${at} 里有不认识的键:${extra}(记录只写 key、spec、status、labels)`;
376
+ if (Object.hasOwn(value, 'labels')) {
377
+ const { labels } = value;
378
+ if (labels !== null && (typeof labels !== 'object' || Array.isArray(labels) || !Object.values(labels).every(each => typeof each === 'string')))
379
+ return `${at}:labels 须为 null 或值为文本的对象`;
380
+ }
381
+ const problem = pointProblem(RESOURCE_PROTOCOL.spec, value.spec, `${at} spec`)
382
+ ?? (Object.hasOwn(value, 'status') ? pointProblem(RESOURCE_PROTOCOL.status, value.status, `${at} status`) : null);
383
+ if (problem) return problem;
384
+ if (value.spec.type !== key) return `${at}:spec.type(${value.spec.type})须与 key 相同`;
385
+ for (const [r, resource] of value.spec.resources.entries()) for (const [b, { args }] of resource.buttons.entries()) {
386
+ if (args === undefined) continue;
387
+ const size = sized(args), where = `${at}:spec.resources[${r}].buttons[${b}].args`;
388
+ if (!size.ok) return `${where} 无法序列化为 JSON:${size.error}`;
389
+ if (size.bytes > ARGS_BYTES) return `${where} 序列化后 ${size.bytes} 字节,超过 ${ARGS_BYTES} 字节`;
390
+ }
391
+ }
392
+ return null;
393
+ }