@coda-console/plugin-check 0.8.23 → 0.8.25
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 +16 -3
- package/bin/check.mjs +18 -2
- package/check/coda/adapters/plugin-command.mjs +5 -4
- package/check/coda/adapters/plugin-events.mjs +2 -0
- package/check/coda/adapters/plugin-modules.mjs +18 -8
- package/check/coda/adapters/plugin-test-host.d.mts +81 -3
- package/check/coda/adapters/plugin-test-host.mjs +19 -12
- package/check/coda/api-surface.txt +335 -0
- package/check/coda/builtin.json +178 -30
- package/check/coda/components/plugins/plugin-extensions.mjs +12 -4
- package/check/coda/components/plugins/plugin-rules.mjs +41 -4
- package/check/coda/components/plugins/plugin-source-rules.mjs +6 -2
- package/check/coda/contract.json +13 -11
- package/check/index.mjs +6 -2
- package/check/init.mjs +33 -0
- package/check/level.mjs +70 -0
- package/check/manifest.mjs +5 -2
- package/check/module.mjs +133 -0
- package/check/report.mjs +2 -2
- package/package.json +8 -3
- package/templates/agent/agent/entry.mjs +128 -0
- package/templates/agent/icons/README.md +14 -0
- package/templates/agent/icons/echo.pdf +0 -0
- package/templates/agent/icons/echo.svg +8 -0
- package/templates/agent/package.json +20 -0
- package/templates/module/main.mjs +37 -0
- package/templates/module/package-lock.json +306 -0
- package/templates/module/package.json +80 -0
- package/templates/module/test/main.test.mjs +65 -0
- package/templates/resource/package.json +22 -0
- package/templates/resource/scripts/mark.mjs +6 -0
- package/templates/resource/scripts/resources.mjs +35 -0
package/README.md
CHANGED
|
@@ -27,6 +27,7 @@ plugins/testbed/ 测试机:长插在 Mac 上的 iPhone、iPad 只经 u
|
|
|
27
27
|
plugins/composer/ 输入框模式与开发流程:监督开发(一个需求一条需求分支,主 Agent 把一块块改动合进需求分支,用户批准一次)与需求交付;Ultra 名单引用 composer.templates
|
|
28
28
|
templates/agent/ 最小的 Agent 插件:手写 ACP 的回声 Agent,演示会话指令、插话、Agent 活动与自主轮次
|
|
29
29
|
templates/resource/ 最小的资源插件:一个资源、两个读数、一个按钮
|
|
30
|
+
templates/module/ 带模块的插件:自己的协议(一个查询、一个做事的操作、一个事件),模块登记操作、写记录、发布并订阅事件,附测试
|
|
30
31
|
bin/、check/ 契约检查(仓库根的 package.json 就是它,@coda-console/plugin-check);check/coda/ 是 Coda 同步来的规则副本,不要手改
|
|
31
32
|
test/ 检查包的测试;test/plugins/ 是各插件的测试(插件目录里只放运行要用的文件)
|
|
32
33
|
.coda/workflows/ 本仓库自己的流程:sync-coda 等新版本发到 npm,再给 Coda 开升级依赖的 PR
|
|
@@ -421,7 +422,7 @@ Coda 根上的同一条 overrides 由 `sync-coda` 一起改(npm 只认根的
|
|
|
421
422
|
「设置 › 插件 › 从仓库添加…」:
|
|
422
423
|
|
|
423
424
|
1. **仓库**填 `coda-console/coda-plugins`(或 `https://github.com/coda-console/coda-plugins`);**版本**留空是默认分支,也可以填分支、标签或完整的提交号。
|
|
424
|
-
2. **读取**:Coda 拉取那个提交,把仓库根与两层以内 `package.json` 带 `contributes` 的目录各列成一个插件——这个仓库里是 `plugins/`
|
|
425
|
+
2. **读取**:Coda 拉取那个提交,把仓库根与两层以内 `package.json` 带 `contributes` 的目录各列成一个插件——这个仓库里是 `plugins/` 下的七个与三个模板。Coda 内置的那几个只能从 npm 上自己的包单独更新;在 Coda 里先卸载它,才能从这里装同名的。
|
|
425
426
|
3. 选一个,确认里逐条列出它会运行的命令(Agent 的 `command`、资源的命令与动作),确认就是批准:这些命令以你的账户在空间里每台机器上运行,Coda 不做隔离,只装你信任的来源。
|
|
426
427
|
|
|
427
428
|
**Coda 只认提交**:安装时钉在读取到的那个提交上,每台机器各自取同一个提交。「检查更新」用记下的仓库与版本再读一次,提交变了才有更新;
|
|
@@ -431,7 +432,16 @@ Coda 根上的同一条 overrides 由 `sync-coda` 一起改(npm 只认根的
|
|
|
431
432
|
|
|
432
433
|
## 写一个插件
|
|
433
434
|
|
|
434
|
-
|
|
435
|
+
从模板开始:
|
|
436
|
+
|
|
437
|
+
```sh
|
|
438
|
+
npx @coda-console/plugin-check init my-plugin # 默认 module:带模块与测试
|
|
439
|
+
npx @coda-console/plugin-check init my-plugin --template agent # 或 resource
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
目录要不存在或为空;目录名就是插件 ID(小写字母开头,小写字母、数字和 `-`,至多 40 个字符),`name` 与模块模板里协议名的前缀都换成它。
|
|
443
|
+
生成后 `npx @coda-console/plugin-check my-plugin` 检查;模块模板的测试在装好依赖后用 `npm test` 跑(`devDependencies` 只有检查包,钉确切版本,模板带 `package-lock.json`)。
|
|
444
|
+
Agent 模板里 Agent 的 `id` 不随目录名变,按需自己改。
|
|
435
445
|
|
|
436
446
|
**清单**(`package.json`)
|
|
437
447
|
|
|
@@ -535,9 +545,12 @@ node bin/check.mjs <插件目录> [--agent <id>] [--manifest] [--live] [--prompt
|
|
|
535
545
|
npx github:coda-console/coda-plugins#<提交> <插件目录>
|
|
536
546
|
```
|
|
537
547
|
|
|
548
|
+
插件自己的测试用检查包的出口:`@coda-console/plugin-check/test-host`(`createTestHost`,Coda 自己的 `coda`、`ctx` 构造)与 `@coda-console/plugin-check/types`(类型),不必直接依赖协议包。
|
|
549
|
+
|
|
538
550
|
| 级 | 要不要登录 | 查什么 |
|
|
539
551
|
| --- | --- | --- |
|
|
540
|
-
| 清单(总是) | 不要 | `package.json` 的通用键对协议 schema 校验(`manifestProblem`),再照 Coda 读成插件(`readPlugin`:登记的贡献点各按自己的 schema 查、读,ID、设置名在 ID 之下);其余写给别的插件扩展点的键,要有 Coda 自带的或旁边依赖的插件声明这个类型。资源类型与旧的面板按资源插件给扩展点 `resources`、`panels` 带的 schema 查。`.coda/workflows/` 里的每个流程(含能力)按协议的流程方言读(`workflowProblem`):不是 BPMN、认不出的 `coda:` 属性或元素、没有的动作或动作不接受的参数都算失败。另有只提醒的:分类、版本、图标页面太小、旧的 Agent ID `claude` |
|
|
552
|
+
| 清单(总是) | 不要 | `package.json` 的通用键对协议 schema 校验(`manifestProblem`),再照 Coda 读成插件(`readPlugin`:登记的贡献点各按自己的 schema 查、读,ID、设置名在 ID 之下);其余写给别的插件扩展点的键,要有 Coda 自带的或旁边依赖的插件声明这个类型。资源类型与旧的面板按资源插件给扩展点 `resources`、`panels` 带的 schema 查。`.coda/workflows/` 里的每个流程(含能力)按协议的流程方言读(`workflowProblem`):不是 BPMN、认不出的 `coda:` 属性或元素、没有的动作或动作不接受的参数都算失败。另有只提醒的:分类、版本、图标页面太小、旧的 Agent ID `claude`。还算 `engines.coda` 该写几(读 `check/coda/api-surface.txt`):清单的键、`contributes.<键>`、`uses` 的协议与权限组、自己协议定义里的键,以及插件目录里 `.mjs`/`.js`(不含 `node_modules`)的 `coda.<成员>`、`ctx.<成员>` 与页面里的 `window.coda.<成员>`;要的 Level 取最大的,清单写的 `engines.coda` 比清单、`uses`、定义的项小算失败,比文本扫出的项小只提醒,没写只提醒并给出该写的值。用到的试行面(`trial` 的权限组、模块接口)列在「说明」里,一行一项 |
|
|
553
|
+
| 模块(有 `main`;`--manifest` 不跑) | 不要 | 清单之后、握手之前:用 `createTestHost({ plugin, settings })` 起 Coda 自己的 `coda`(状态目录是临时的),`import(main)` 后调 `activate(host.coda)`,10 秒没完成或抛错算失败(带堆栈第一行);`host.registered()` 与清单两个方向对:清单的 `protocolImplementations` 写了、定义里有、又不由 `commands` 实现的操作,模块没 `coda.handle` 算失败,模块登记了定义里没有的操作也算失败(Coda 自己的协议里 `codaOnly` 的操作只由 Coda 回答,不要求登记);`coda.on` 订了不在自己事件组里的名字,测试宿主当场抛 `forbidden`:按被拒的事件名在已知的协议定义(Coda 自己的、自己的、依赖的)里查它归谁,查到了(它的组不在 `uses` 里)算失败,另有无关的依赖缺定义也一样;查不到,而 `uses` 里有协议的定义不在本地(依赖没放在旁边),归属可能取决于缺的定义,报「未完成核对」,不判插件错;`coda.get`/`coda.list` 遇到测试宿主没有的记录类型,先按已知定义判断:协议有定义却没有记录(只含事件)、或 `uses` 没给读记录的权限(`usesRefusal`,如只申请了事件组)算失败;有记录又已获授权的,测试宿主登记不了别的插件的记录类型(登记进自己的协议会让模块也能发它的事件),报「未完成核对」,之后的调用没有核对;协议在 `uses` 里而定义不在本地的同样报「未完成核对」。`activate` 成功之后才调模块导出的 `deactivate`(抛错、或与 `activate` 一样 10 秒没完成都算失败);`activate` 失败、超时或「未完成核对」时不调,只靠 `host.close()` 收掉模块起的进程(`deactivate` 之后同样收)。`activate` 最终抛出的错,检查包用包了一层的 `coda` 认出它是哪个成员出的:成员是测试宿主没有后端的几个之一(`coda.watch`、`coda.services.register`、`coda.tell`、`coda.api`、`coda.environment`、`coda.protocols.resolve`、`coda.protocols.upload`、`coda.pluginSetup.retry`),错误又正是测试宿主为这个成员答的那一条(错误码与固定说法都对上)时不算失败:「说明」里写明模块一级只验到这里,登记不与清单比对,模块一级报「未完成核对」(清单写的协议没有定义时同样);别的都算激活失败:同一成员的别的错(回调、筛选条件不合法等),别的成员的错,包括回 `unsupported` 的(比如 `coda.query` 调非只读操作) |
|
|
541
554
|
| 握手(默认) | 不要 | `sh -c` 启动 `command`(环境是 Coda 的 `pluginEnv` 给的:`CODA_NODE`、`CODA_PLUGIN_PATH`、临时的 `CODA_PLUGIN_STATE`、设置默认值的 `CODA_PLUGIN_SETTINGS`;依赖的插件在旁边(同一个父目录里同名的目录)时 `CODA_PLUGIN_DEPENDENCIES` 给它的目录,Coda 自带的不在这里、不给),发与 Coda 相同的 `initialize`,要求 `protocolVersion` 为 1;能力声明的 `_meta.coda` 与顶层插话声明交协议 schema 校验;检查会话指令能力(`sessionCapabilities.systemPrompt`,没声明也通过,由 Coda 在第一轮送入);声明了的 `session/new` 带会话指令,给出会话与当前模型,配置选项的 `_meta.coda.default` 交协议校验;错误里声明的执行失败也查协议 schema,回 -32000 记为未登录、跳过后面的检查(不算失败);像 Coda 一样对进程组发 SIGTERM,5 秒内要退出(超过 0.8 秒提醒);另起一个进程,关掉标准输入后 5 秒内不退出只提醒;声明了配置探测(`_meta.coda.probe`)的,再另起进程发带探测标记的 `session/new`(要给非空的 `sessionId`;标记不是 `true` 的要回 -32602):逐个模型用 `category: model` 的配置项切换(只有 `models` 的用 `session/set_model`),每次要返回该模型完整的配置、思考档位在它自己的选项里并能设回(标了 `_meta.coda.default` 的设回那一项),不存在的模型与配置项要报错,`session/prompt` 要回 -32602,声明了 `session/close` 的另开一个虚拟会话关掉,要回 `{}`、之后它的请求回 -32002,探测期间不干活;断线后新进程的 `session/load`、`session/resume` 要回 -32002,`session/list`(带探测的 `cwd`,沿 `nextCursor` 翻完;每页、每个会话条目合 ACP schema,`sessionId` 非空,`nextCursor` 只能是字符串或 null;重复的游标或超过 100 页算失败)不列出这个虚拟会话,没声明的跳过。资源类型(或旧的面板)由 Coda 资源插件的 `Panels` 读一次(30 秒),输出合格式 |
|
|
542
555
|
| 一轮(`--live`) | 要 | 声明了会话指令的经 `systemPrompt` 送入,没声明的在第一轮前加契约的 `instructionsBlock`;第一轮问会话指令里的检查词(一个随机词),回复里要有它;再发一轮提示词(默认「只回复 ok」)收到 `stopReason`;每条 `session/update` 先过 ACP SDK 的 schema,工具审核、用量与默认选项标记再过协议 schema;`_coda/wait` 用协议的 `agentMessageProblem` 校验形状,另查会话归属、登记与终态(子 Agent 不带 `childSessionId`、定时不带 `at` 只提醒);扩展形状问题按现有规则报告协议返回的「位置:说明」;远端绑定码请求先查协议参数再查本会话归属;执行失败的形状交协议校验,重试预算照 Coda 策略;审批与提问一律回拒绝,在一轮之外发来的算失败;再发一轮并 `session/cancel`,30 秒内要结束,读到取消后还在做事或拖过 5 秒才答复却不回 `cancelled` 算失败(见下);有自主轮次的也取消一次;声明插话的,答复用协议的 `agentResultProblem` 校验,一轮结束后插话要回 `promptRequired` 且不自己另开一轮,一轮进行中插话要回 `injected` 或 `promptRequired`(`injected` 的那一轮照常回 `stopReason`);声明 `loadSession` 的,新开进程 `session/load`(声明了的同样带会话指令)要成功,随后在新进程里再跑一轮也要收到 `stopReason` |
|
|
543
556
|
|
package/bin/check.mjs
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// coda-plugin-check <插件目录> [--agent <id>] [--manifest] [--live] [--prompt "…"]
|
|
3
|
+
// coda-plugin-check init <目录> [--template module|agent|resource]
|
|
3
4
|
import { resolve } from 'node:path';
|
|
4
5
|
import { parseArgs } from 'node:util';
|
|
5
6
|
import pkg from '../package.json' with { type: 'json' };
|
|
6
7
|
import { ACP_PROTOCOL_VERSION } from '../check/agent.mjs';
|
|
7
8
|
import contract from '../check/coda/contract.json' with { type: 'json' };
|
|
8
9
|
import { checkPlugin } from '../check/index.mjs';
|
|
10
|
+
import { init } from '../check/init.mjs';
|
|
9
11
|
import { format } from '../check/report.mjs';
|
|
10
12
|
|
|
11
13
|
const USAGE = `用法:coda-plugin-check <插件目录> [--agent <id>] [--manifest] [--live] [--prompt "…"]
|
|
14
|
+
coda-plugin-check init <目录> [--template module|agent|resource]
|
|
12
15
|
|
|
13
|
-
清单(总是查) package.json 能不能被 Coda 读懂,从仓库安装的限制(带 npm 依赖要有 package-lock.json
|
|
16
|
+
清单(总是查) package.json 能不能被 Coda 读懂,从仓库安装的限制(带 npm 依赖要有 package-lock.json);engines.coda 够不够用到的各项(算出该写几);列出用到的试行面
|
|
17
|
+
模块(有 main) 用 Coda 自己的 coda(测试宿主)加载 main、调 activate(10 秒内要完成);模块登记的操作与清单的 protocolImplementations 两个方向对一遍;coda.on 只能订自己事件组里的事件
|
|
14
18
|
握手(默认查) 照 Coda 的样子启动每个 Agent,发 initialize、session/new(声明了的带 systemPrompt,没声明的在第一轮送入指令);SIGTERM 后 5 秒内要退出(关标准输入后不退出只提醒);读每个面板一次
|
|
15
19
|
一轮(--live) 每个 Agent 先问会话指令里的检查词,再发一轮提示词(默认「只回复 ok」)、再发一轮并取消(读到取消后要回 cancelled)、核对 _coda/wait;
|
|
16
20
|
声明插话的,一轮结束后与一轮进行中各插话一次;声明 loadSession 的再开进程 session/load,并在新进程里再跑一轮
|
|
@@ -18,7 +22,19 @@ const USAGE = `用法:coda-plugin-check <插件目录> [--agent <id>] [--manif
|
|
|
18
22
|
--agent <id> 只查这一个 Agent(面板不读)
|
|
19
23
|
--manifest 只查清单,什么也不运行
|
|
20
24
|
--live 查一轮:会真的发提示词,可能要登录、花额度
|
|
21
|
-
--prompt "…"
|
|
25
|
+
--prompt "…" 一轮用的提示词
|
|
26
|
+
|
|
27
|
+
init 把模板(默认 module)复制到一个新目录(须不存在或为空),插件名与协议名前缀换成目录名`;
|
|
28
|
+
|
|
29
|
+
if (process.argv[2] === 'init') {
|
|
30
|
+
try {
|
|
31
|
+
const { values: { template = 'module' }, positionals } = parseArgs({ args: process.argv.slice(3), allowPositionals: true, options: { template: { type: 'string' } } });
|
|
32
|
+
if (positionals.length !== 1) throw new Error(`init 要一个目录\n\n${USAGE}`);
|
|
33
|
+
const id = init(positionals[0], template);
|
|
34
|
+
console.log(`已从模板 ${template} 生成插件 ${id}:${positionals[0]}\n检查:coda-plugin-check ${positionals[0]}`);
|
|
35
|
+
process.exit(0);
|
|
36
|
+
} catch (e) { console.error(e.message); process.exit(2); }
|
|
37
|
+
}
|
|
22
38
|
|
|
23
39
|
let options;
|
|
24
40
|
try {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The one runner of a plugin's commands (docs/plugins.md「命令的约定」):
|
|
1
|
+
// The one runner of a plugin's commands (docs/plugins.md「命令的约定」): the operations its commands implement
|
|
2
2
|
// (components/plugins/plugin-host.mjs `startCommand`), its resources' readings and actions,
|
|
3
3
|
// their logins and installers, its setup; and, bounded the same way, the programs Coda runs for a plugin itself (Git taking a
|
|
4
4
|
// plugin from its repository, components/plugins/plugin-sources.mjs; a repository's listing; what a plugin tells agents).
|
|
@@ -54,10 +54,11 @@ export const runBounded = (program, args, options) => startBounded(program, args
|
|
|
54
54
|
export const fileCommand = file => `./'${posix.normalize(file).replaceAll("'", "'\\''")}'`;
|
|
55
55
|
// What a command implementing an operation is told of its call in its environment, as a module's handler is in its `ctx`
|
|
56
56
|
// (docs/plugins.md「用命令实现操作」): its record (`ctx.record`, its key only of one its plugin holds here), its ID (`ctx.id`)
|
|
57
|
-
// and, when it has one, its deadline (`ctx.deadline`, milliseconds).
|
|
58
|
-
export const callEnv = ({ id, record, deadline }) => ({ CODA_RECORD_KIND: record.kind, CODA_RECORD_ID: record.id,
|
|
57
|
+
// and, when it has one, its deadline (`ctx.deadline`, milliseconds); made from a page, who is before it (`ctx.caller`, JSON).
|
|
58
|
+
export const callEnv = ({ id, record, deadline, caller }) => ({ CODA_RECORD_KIND: record.kind, CODA_RECORD_ID: record.id,
|
|
59
59
|
...(record.key === undefined ? {} : { CODA_RECORD_KEY: record.key }), CODA_CALL_ID: id,
|
|
60
|
-
...(deadline === null || deadline === undefined ? {} : { CODA_DEADLINE: String(deadline) })
|
|
60
|
+
...(deadline === null || deadline === undefined ? {} : { CODA_DEADLINE: String(deadline) }),
|
|
61
|
+
...(caller ? { CODA_CALLER: JSON.stringify(caller) } : {}) });
|
|
61
62
|
// A query's ID, as its handler is given it (`ctx.id`, adapters/plugin-modules.mjs): of its caller and its request's.
|
|
62
63
|
export const queryId = request => derivedUUID('query', request.parent, request.requestId);
|
|
63
64
|
|
|
@@ -32,6 +32,8 @@ export function pluginEvents(plugin, asks, fire) {
|
|
|
32
32
|
deliver(event) {
|
|
33
33
|
for (const entry of [...handlers.get(event?.name) ?? []]) if (!entry.disposed) fire([entry.fn], event);
|
|
34
34
|
},
|
|
35
|
+
// The names of the events it has handlers of now.
|
|
36
|
+
names() { return [...handlers].filter(([, entries]) => entries.size).map(([name]) => name); },
|
|
35
37
|
// The module stopped: its handlers go.
|
|
36
38
|
clear() { handlers.clear(); },
|
|
37
39
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The plugin host's modules (docs/plugins.md「插件宿主」): each plugin's that has a `main`, loaded the first time anything
|
|
2
2
|
// of it is needed, or when the backend says to, and given a `coda` of its own. What the runner (adapters/plugin-host-runner.mjs)
|
|
3
3
|
// runs over Node's IPC channel with the backend, and the test host (adapters/plugin-test-host.mjs) over a channel of its own:
|
|
4
|
-
// `send(message)` to the backend, `receive(message)` from it. `adopt(plugin, token)`: a plugin's `coda` made with no module
|
|
4
|
+
// `send(message)` to the backend, `receive(message)` from it. `adopt(plugin, token, parts?)`: a plugin's `coda` made with no module
|
|
5
5
|
// loaded, for whoever holds it to activate a module with; `stop()`: each module loaded ends what it started (`deactivate`).
|
|
6
6
|
//
|
|
7
7
|
// From the backend: `start { api: { url }, parts }`, `activate { plugin, token }` (before anything else of the plugin's),
|
|
@@ -42,10 +42,11 @@ export function pluginModules({ send }) {
|
|
|
42
42
|
// What a handler of a call is given beside its input (coda#2749 3.1): the call's ID, its record, its `signal`, which goes
|
|
43
43
|
// off as the backend calls it off, its `deadline` (milliseconds on the backend's clock, or none), `query`, queries made
|
|
44
44
|
// under it, and `spawn`, processes started for it, the backend's request `under` which the call came; a doing call's
|
|
45
|
-
// handler (`run`, `resume`), `call` too, doing calls it makes (`doingOf`).
|
|
45
|
+
// handler (`run`, `resume`), `call` too, doing calls it makes, and, made from a page, `caller`, who is before it (`doingOf`).
|
|
46
46
|
const contextOf = ({ id, record, deadline }, signal, { querying, spawnFor }, under) =>
|
|
47
47
|
({ id, record, signal, deadline, query: querying.within(signal, deadline), spawn: spawnFor(under, signal) });
|
|
48
|
-
const doingOf = (call, signal, made, under) => ({ ...contextOf(call, signal, made, under), call: made.calling.within(signal, call.deadline, under)
|
|
48
|
+
const doingOf = (call, signal, made, under) => ({ ...contextOf(call, signal, made, under), call: made.calling.within(signal, call.deadline, under),
|
|
49
|
+
...(call.caller ? { caller: call.caller } : {}) });
|
|
49
50
|
// The processes the modules started through the backend (`spawn`), by the key this host gave each, until they have
|
|
50
51
|
// exited or the host stops.
|
|
51
52
|
const processes = new Map();
|
|
@@ -398,7 +399,7 @@ export function pluginModules({ send }) {
|
|
|
398
399
|
} finally { cancels.delete(id); }
|
|
399
400
|
},
|
|
400
401
|
// A doing call of a protocol the plugin implements (docs/plugins.md「做事的操作」), as the backend hosts it
|
|
401
|
-
// (components/plugins/hosted-calls.mjs): `call` is `{ id, ref, record, operation, input, deadline }`, `ref` the call's on the call
|
|
402
|
+
// (components/plugins/hosted-calls.mjs): `call` is `{ id, ref, record, operation, input, deadline, caller? }`, `ref` the call's on the call
|
|
402
403
|
// kernel (`{ from, id }`), which the doing calls its handler makes are made by. Its handler is given
|
|
403
404
|
// besides `progress`, said to the backend as it comes, and `ask`, answered as the backend passes the answer on (one at
|
|
404
405
|
// a time, as the backend has it: components/plugins/hosted-calls.mjs `question`). It ends with the call's outcome (`ending`). Not handled, nothing was done.
|
|
@@ -421,7 +422,7 @@ export function pluginModules({ send }) {
|
|
|
421
422
|
});
|
|
422
423
|
},
|
|
423
424
|
// A doing call left by a host process that ended before its handler did (coda#2749 3.6), handed to its operation's
|
|
424
|
-
// `resume` in this one: `call` is `{ id, ref, record, operation, input, deadline, progress, canceled, halted }`, `halted`
|
|
425
|
+
// `resume` in this one: `call` is `{ id, ref, record, operation, input, deadline, caller?, progress, canceled, halted }`, `halted`
|
|
425
426
|
// why its `ctx.signal` has gone off already (asked to be cancelled, or past its deadline, as `cancel`'s reason
|
|
426
427
|
// crosses), or none. `resume` is given the call as `Interrupted` and a `ctx` as a query's handler is with `call`, and ends it as
|
|
427
428
|
// `run` does; with none, null, for the backend to end it as it does then. Its `ctx.call` makes calls as the call's, as `run`'s
|
|
@@ -507,10 +508,19 @@ export function pluginModules({ send }) {
|
|
|
507
508
|
await services.close(false);
|
|
508
509
|
if (typeof module?.deactivate === 'function') await module.deactivate();
|
|
509
510
|
})));
|
|
510
|
-
|
|
511
|
-
|
|
511
|
+
const adopted = new Map();
|
|
512
|
+
function adopt(plugin, token, provided = []) {
|
|
513
|
+
const made = codaFor(plugin, provided, token);
|
|
514
|
+
adopted.set(plugin.id, made);
|
|
512
515
|
loading.set(plugin.id, Promise.resolve(made));
|
|
513
516
|
return made.coda;
|
|
514
517
|
}
|
|
515
|
-
|
|
518
|
+
// What an adopted plugin's module has registered: its operations (`handle`), its own queries (`self.handle`: kept under
|
|
519
|
+
// `self`) and the events it handles (`on`).
|
|
520
|
+
function registered(plugin) {
|
|
521
|
+
const { operations, events } = adopted.get(plugin.id), kept = [...operations.keys()].map(id => JSON.parse(id));
|
|
522
|
+
return { operations: kept.filter(([kind]) => kind !== 'self').map(([kind, operation]) => ({ kind, operation })),
|
|
523
|
+
self: kept.filter(([kind]) => kind === 'self').map(([, name]) => name), events: events.names() };
|
|
524
|
+
}
|
|
525
|
+
return { receive, stop, adopt, registered };
|
|
516
526
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Types of what a plugin's module queries and answers by (docs/plugins.md「调用」, coda#2749 3.1 and 第 7 节), and of the test
|
|
2
2
|
// host (plugin-test-host.mjs), and of the records (coda#2749 3.7). All on the trial surface: they may change from one
|
|
3
3
|
// version of 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';
|
|
4
5
|
import type { Readable, Writable } from 'node:stream';
|
|
5
6
|
|
|
6
7
|
export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
|
@@ -45,6 +46,13 @@ export interface CallOptions {
|
|
|
45
46
|
onProgress?(value: Json): void;
|
|
46
47
|
}
|
|
47
48
|
|
|
49
|
+
/**
|
|
50
|
+
* 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.
|
|
51
|
+
* A call forwarded to the backend that holds the record has no `local` but the `machine` it was made from (that one's ID),
|
|
52
|
+
* a device kept as it is: so `{ machine }` or `{ machine, device, name? }`.
|
|
53
|
+
*/
|
|
54
|
+
export type Caller = { local: true } | { device: string; name?: string } | { machine: string; device?: string; name?: string };
|
|
55
|
+
|
|
48
56
|
/** What a handler of a call is given beside its input. A handler of a query, and `resume`, have no `progress` nor `ask`. */
|
|
49
57
|
export interface Context {
|
|
50
58
|
/** This call's ID, the host's, unique: the same for the same caller's same request. */
|
|
@@ -75,6 +83,11 @@ export interface Context {
|
|
|
75
83
|
* made before the process ended, its outcome waited on again.
|
|
76
84
|
*/
|
|
77
85
|
call?: Coda['call'];
|
|
86
|
+
/**
|
|
87
|
+
* 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
|
|
88
|
+
* for a call a module (`coda.call`), a command (`coda call`) or a flow makes.
|
|
89
|
+
*/
|
|
90
|
+
caller?: Caller;
|
|
78
91
|
}
|
|
79
92
|
|
|
80
93
|
/** Its return value is the result; what it throws, the failure (`coda.error`, or anything else as `handler_error`). */
|
|
@@ -263,6 +276,67 @@ export interface Coda {
|
|
|
263
276
|
* subject. What it throws is logged; the event is not given again.
|
|
264
277
|
*/
|
|
265
278
|
on(name: string, fn: (event: Event) => void): Disposable;
|
|
279
|
+
/** Trial. The plugin itself: its ID, its directory, and its state directory on this backend (`null` when the backend has no state root). */
|
|
280
|
+
plugin: Readonly<{ id: string; path: string; state: string | null }>;
|
|
281
|
+
/**
|
|
282
|
+
* Trial. Local streaming services: `register` serves `id` on this machine (an HTTP handler, given the caller as Coda
|
|
283
|
+
* names it), done once Coda has it; the handle's `dispose()` withdraws it and closes its connections.
|
|
284
|
+
*/
|
|
285
|
+
services: Readonly<{
|
|
286
|
+
register(id: string, handler: (request: IncomingMessage, response: ServerResponse, caller: Readonly<{ [key: string]: Json }>) => void | Promise<void>): Promise<{ dispose(): Promise<void> }>;
|
|
287
|
+
}>;
|
|
288
|
+
/** 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. */
|
|
289
|
+
views: Readonly<{ register(id: string, provider: { open(view: ViewInstance): void | Promise<void> }): { dispose(): void } }>;
|
|
290
|
+
/** Trial. Protocol contributions and the records' services: a contributor to another protocol's records, a record's service as this machine reaches it, and an upload of this machine's. */
|
|
291
|
+
protocols: Readonly<{
|
|
292
|
+
register(kind: string, key: string, handler: (object: ProtocolObject, key: string) => Contribution | null | Promise<Contribution | null>): Disposable;
|
|
293
|
+
resolve(record: Ref, service: string): Promise<{ resource: Ref; url: string; headers: Record<string, string> }>;
|
|
294
|
+
upload(id: string): Promise<{ id: string; name: string; size: number; path: string; mime?: string; duration?: number; [key: string]: Json | undefined }>;
|
|
295
|
+
}>;
|
|
296
|
+
/** Trial. Tells a session's agent something, told with its next turn and waking nothing; `told` is `false` for a session archived. */
|
|
297
|
+
tell(session: string, text: string): Promise<{ told: boolean }>;
|
|
298
|
+
/** Trial. This machine's Coda API as its clients reach it (the path after `/v1/`): GET without a body, POST with one; the answer is JSON. */
|
|
299
|
+
api(path: string, body?: Json): Promise<Json>;
|
|
300
|
+
/** Trial. What Coda gives every process of the plugin's, for one the module starts itself; `plugin` is another installed plugin's, for a command of its the module runs. */
|
|
301
|
+
environment(project?: string | null, options?: { plugin?: string }): Promise<Record<string, string>>;
|
|
302
|
+
/** Trial. Runs an installed plugin's environment setup again, asked as this plugin; the test host's fails (`unsupported`). */
|
|
303
|
+
pluginSetup: Readonly<{ retry(plugin: string): Promise<Json> }>;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The record or draft a protocol hands a contributor, without who created it: its `spec` and `status` are objects the protocol's schemas describe. */
|
|
307
|
+
export interface ProtocolObject {
|
|
308
|
+
kind: string;
|
|
309
|
+
id: string;
|
|
310
|
+
spec: { [key: string]: Json };
|
|
311
|
+
status: { [key: string]: Json };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** 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. */
|
|
315
|
+
export type Contribution = { [field: string]: Json };
|
|
316
|
+
|
|
317
|
+
/** A page of the plugin's, opened, as its view provider's `open` is given it. */
|
|
318
|
+
export interface ViewInstance {
|
|
319
|
+
/** This opening's ID. */
|
|
320
|
+
id: string;
|
|
321
|
+
/** The view's ID. */
|
|
322
|
+
view: string;
|
|
323
|
+
/** What the page was opened beside: the session's ID, and the `args` of the button or card that opened it; `null` for none. */
|
|
324
|
+
context: { session: string | null; args: Json | null };
|
|
325
|
+
/** Who opened it: this machine's client (`{ local: true }`) or a device. */
|
|
326
|
+
caller: { local?: boolean; device?: string; name?: string };
|
|
327
|
+
/** Sends the page a message; `false` once the page is gone. */
|
|
328
|
+
postMessage(message: Json): boolean;
|
|
329
|
+
/** A collection handed to the page: `set` and `delete` give whether the page was told anything. */
|
|
330
|
+
collection(name: string): {
|
|
331
|
+
set(id: string, object: { [key: string]: Json }): boolean;
|
|
332
|
+
delete(id: string): boolean;
|
|
333
|
+
get(id: string): { [key: string]: Json } | undefined;
|
|
334
|
+
keys(): string[];
|
|
335
|
+
};
|
|
336
|
+
/** Each returns a handle that stops it. */
|
|
337
|
+
onMessage(fn: (message: Json) => void): Disposable;
|
|
338
|
+
onContext(fn: (context: ViewInstance['context']) => void): Disposable;
|
|
339
|
+
onClose(fn: () => void): Disposable;
|
|
266
340
|
}
|
|
267
341
|
|
|
268
342
|
/** A protocol a plugin implements, some of its operations by commands: operation name to the file that implements it. */
|
|
@@ -283,7 +357,7 @@ export interface TestPlugin {
|
|
|
283
357
|
* or `{ kind, commands }`, the operations in `commands` each implemented by a file of the plugin's (its path from `path`),
|
|
284
358
|
* the rest its module's. Such a command is run as Coda runs it, its call in its environment as its `ctx` has it
|
|
285
359
|
* (`CODA_RECORD_KIND`, `CODA_RECORD_ID`, `CODA_RECORD_KEY` of a record the plugin holds, `CODA_CALL_ID`, `CODA_DEADLINE`
|
|
286
|
-
* when it has one), but with no token: `coda progress`, `coda ask`, `coda query` and `coda self` in it are not answered
|
|
360
|
+
* when it has one, `CODA_CALLER`, the `caller` as JSON, when it has one), but with no token: `coda progress`, `coda ask`, `coda query` and `coda self` in it are not answered
|
|
287
361
|
* by the test host.
|
|
288
362
|
*/
|
|
289
363
|
protocolImplementations?: (string | ProtocolImplementation)[];
|
|
@@ -298,11 +372,13 @@ export interface TestCallOptions extends QueryOptions {
|
|
|
298
372
|
onProgress?(value: Json): void;
|
|
299
373
|
/** Answers a doing call's question (`ctx.ask`); without it, the question fails. */
|
|
300
374
|
answer?(question: Json): Json | Promise<Json>;
|
|
375
|
+
/** A doing call's: made from a page this caller is before (`ctx.caller`, `CODA_CALLER`); without it, as a module's call. */
|
|
376
|
+
caller?: Caller;
|
|
301
377
|
}
|
|
302
378
|
|
|
303
379
|
export interface TestHost {
|
|
304
380
|
/** The plugin's `coda`, for its module's `activate`. */
|
|
305
|
-
coda: Coda
|
|
381
|
+
coda: Coda;
|
|
306
382
|
/**
|
|
307
383
|
* Calls the plugin's module as a caller would: a query, or a doing call, which ends as its handler ends it. An operation
|
|
308
384
|
* one of its commands implements is run as Coda runs it: its input on standard input, its exit code first, its output
|
|
@@ -320,7 +396,7 @@ export interface TestHost {
|
|
|
320
396
|
* `ctx.deadline`) or none: `canceled`, or the deadline past by the host's clock, its `ctx.signal` has gone off already
|
|
321
397
|
* (`AbortError`, `TimeoutError`); its result, or its failure; with no `resume`, an `interrupted` failure of unknown effect.
|
|
322
398
|
*/
|
|
323
|
-
resume(record: Ref, operation: string, call?: { id?: string; input?: Json; progress?: Json | null; canceled?: boolean; deadline?: number | null }): Promise<Json>;
|
|
399
|
+
resume(record: Ref, operation: string, call?: { id?: string; input?: Json; progress?: Json | null; canceled?: boolean; deadline?: number | null; caller?: Caller }): Promise<Json>;
|
|
324
400
|
/** Writes the plugin's settings again, as the backend does: `coda.settings.get` gives them, and `onChange` is told. */
|
|
325
401
|
setSettings(settings: Json): Promise<void>;
|
|
326
402
|
/** Delivers an event to the module as Coda does: to its handlers of the name (`coda.on`) now. */
|
|
@@ -330,6 +406,8 @@ export interface TestHost {
|
|
|
330
406
|
* protocol the plugin defines or implements, not one of Coda's own, as its payload schema has it.
|
|
331
407
|
*/
|
|
332
408
|
emitted: Omit<Event, 'publisher'>[];
|
|
409
|
+
/** What the module has registered so far: its operations (`coda.handle`), its own queries' names (`coda.self.handle`) and the events it handles (`coda.on`). */
|
|
410
|
+
registered(): { operations: { kind: string; operation: string }[]; self: string[]; events: string[] };
|
|
333
411
|
close(): Promise<unknown>;
|
|
334
412
|
}
|
|
335
413
|
|
|
@@ -89,7 +89,9 @@ export function createTestHost({ plugin = {}, call = null, clock = new Clock(),
|
|
|
89
89
|
const ending = new AbortController();
|
|
90
90
|
// What the module sends the backend, taken after the turn it is sent in, as over a process's channel.
|
|
91
91
|
const modules = pluginModules({ send: message => queueMicrotask(() => taken(message)) });
|
|
92
|
-
|
|
92
|
+
// `coda.pluginSetup`, a part the backend provides, is there as the module has it, but fails: the test host has no backend to ask.
|
|
93
|
+
const setup = () => ({ retry: async () => { throw refused('unsupported', '测试宿主不提供 coda.pluginSetup'); } });
|
|
94
|
+
const coda = modules.adopt(described, randomUUID(), [['pluginSetup', setup]]);
|
|
93
95
|
// The records, by kind, each an entry (`{ owner, location, id, plugin, local, spec, status, labels?, version }`) by its holder and
|
|
94
96
|
// ID, and the keys of those of each kind the plugin holds, by their IDs (record-rules.mjs `recordId`); and the module's
|
|
95
97
|
// watches of them, by the watch's key, each with what it was last told.
|
|
@@ -316,8 +318,8 @@ export function createTestHost({ plugin = {}, call = null, clock = new Clock(),
|
|
|
316
318
|
}
|
|
317
319
|
|
|
318
320
|
// A run of the plugin's command `file` implementing an operation, as the backend runs one (components/plugins/plugin-host.mjs
|
|
319
|
-
// `startCommand`): `sh -c` from the plugin's directory, the call's input as JSON on its standard input, its record, ID
|
|
320
|
-
// deadline in its environment (`callEnv`); cancelled (`cancel`), its group asked to end, and made to once the grace has
|
|
321
|
+
// `startCommand`): `sh -c` from the plugin's directory, the call's input as JSON on its standard input, its record, ID,
|
|
322
|
+
// deadline and caller in its environment (`callEnv`); cancelled (`cancel`), its group asked to end, and made to once the grace has
|
|
321
323
|
// passed on the host's clock; the host closing kills it at once.
|
|
322
324
|
const commanded = (file, call, cancel) => startPluginCommand(fileCommand(file), { cwd: described.path, env: { ...process.env, ...callEnv(call) },
|
|
323
325
|
clock, timeoutMs: Infinity, signal: ending.signal, cancel, input: JSON.stringify(call.input), start: unregistered, label: `${described.id} · ${file}` });
|
|
@@ -342,10 +344,11 @@ export function createTestHost({ plugin = {}, call = null, clock = new Clock(),
|
|
|
342
344
|
// input checked as the operation has it, its deadline its `timeout` from now or the operation's own, or none; called
|
|
343
345
|
// off with `signal`, or past its deadline, its handler's `ctx.signal` goes off (`AbortError`, `TimeoutError`) and its
|
|
344
346
|
// handler ends it still. Its result as the module's outcome says (`outcomeOf`); failed, thrown with its code; cancelled,
|
|
345
|
-
// thrown as `canceled`. Each progress is given to `onProgress`, each question to `answer`, which answers it.
|
|
346
|
-
|
|
347
|
+
// thrown as `canceled`. Each progress is given to `onProgress`, each question to `answer`, which answers it. `caller`, who
|
|
348
|
+
// is before the page that made it (`ctx.caller`, `CODA_CALLER`), or none, as for a call not made from a page.
|
|
349
|
+
async function run(record, operation, input, found, { signal, timeout, onProgress, answer, caller }) {
|
|
347
350
|
const name = `${record.kind}/${operation}`, at = timeout ?? found.timeout;
|
|
348
|
-
const call = { id: randomUUID(), record: recordFor(record), operation, input, deadline: at ? clock.now() + at : null };
|
|
351
|
+
const call = { id: randomUUID(), record: recordFor(record), operation, input, deadline: at ? clock.now() + at : null, ...(caller ? { caller } : {}) };
|
|
349
352
|
try { checkInput(found, name, input); checkRequest(call); } catch (error) { throw Object.assign(error, { effects: 'none' }); }
|
|
350
353
|
const command = commandOf(manifest, record.kind, operation);
|
|
351
354
|
if (command) return ended(found, name, await commandRun(command, call, signal));
|
|
@@ -374,10 +377,11 @@ export function createTestHost({ plugin = {}, call = null, clock = new Clock(),
|
|
|
374
377
|
coda,
|
|
375
378
|
// Calls the plugin's module (or, for another's record, `call`) as a caller would: its result, or a failure with its
|
|
376
379
|
// `code`, `effects` and `retryAfterMs`. A query given up on with `signal` fails as an `AbortError`, past `timeout` as a
|
|
377
|
-
// `timeout`; a doing call of a protocol the plugin implements ends as its handler ends it (`run`)
|
|
378
|
-
|
|
380
|
+
// `timeout`; a doing call of a protocol the plugin implements ends as its handler ends it (`run`), made from a page
|
|
381
|
+
// when it has a `caller`.
|
|
382
|
+
call(record, operation, input = {}, { signal = null, timeout = null, onProgress = null, answer = null, caller = null } = {}) {
|
|
379
383
|
const found = operationOf(record?.kind, operation);
|
|
380
|
-
if (found && !found.safe && implemented.includes(record.kind)) return run(record, operation, input, found, { signal, timeout, onProgress, answer });
|
|
384
|
+
if (found && !found.safe && implemented.includes(record.kind)) return run(record, operation, input, found, { signal, timeout, onProgress, answer, caller });
|
|
381
385
|
return query(record, operation, input, { signal, deadline: timeout ? clock.now() + timeout : null });
|
|
382
386
|
},
|
|
383
387
|
// A query of the module's own (`coda self <名字>`, docs/plugins.md「只给自己用的查询」), handed to what it registered with
|
|
@@ -397,15 +401,15 @@ export function createTestHost({ plugin = {}, call = null, clock = new Clock(),
|
|
|
397
401
|
},
|
|
398
402
|
// A doing call of a protocol the plugin implements, left by a process of the plugin's that ended before its handler did,
|
|
399
403
|
// handed to its operation's `resume` as the backend hands it (coda#2749 3.6), with the call's `deadline` (`ctx.deadline`),
|
|
400
|
-
// or none: asked to be cancelled (`canceled`), or past its deadline, its `ctx.signal` gone off already as an
|
|
404
|
+
// or none, and its `caller` (`ctx.caller`), or none: asked to be cancelled (`canceled`), or past its deadline, its `ctx.signal` gone off already as an
|
|
401
405
|
// `AbortError` or a `TimeoutError`; its result, or its failure, as `call`'s; with no `resume`, interrupted, of unknown
|
|
402
406
|
// effect, as the backend ends it then.
|
|
403
|
-
async resume(record, operation, { id = randomUUID(), input = {}, progress = null, canceled = false, deadline = null } = {}) {
|
|
407
|
+
async resume(record, operation, { id = randomUUID(), input = {}, progress = null, canceled = false, deadline = null, caller = null } = {}) {
|
|
404
408
|
const found = operationOf(record?.kind, operation), name = `${record?.kind}/${operation}`;
|
|
405
409
|
if (!found || found.safe || !implemented.includes(record.kind)) throw refused('not_found', `插件没有实现做事的操作 ${name}`);
|
|
406
410
|
const halted = canceled ? { name: 'AbortError' } : deadline !== null && deadline <= clock.now() ? { name: 'TimeoutError' } : null;
|
|
407
411
|
const call = { id, record: recordFor(record), operation, input, deadline, progress, canceled,
|
|
408
|
-
...(halted ? { halted } : {}) }, at = ++next;
|
|
412
|
+
...(caller ? { caller } : {}), ...(halted ? { halted } : {}) }, at = ++next;
|
|
409
413
|
const said = await new Promise((resolve, reject) => {
|
|
410
414
|
waiting.set(at, { resolve, reject });
|
|
411
415
|
modules.receive({ id: at, method: 'resume', params: { plugin: described, call } });
|
|
@@ -418,6 +422,9 @@ export function createTestHost({ plugin = {}, call = null, clock = new Clock(),
|
|
|
418
422
|
emit: event => modules.receive({ method: 'event', params: { plugin: described.id, event: structuredClone(event) } }),
|
|
419
423
|
// The events the module published (`coda.emit`), in order: `{ name, kind, subject, project, data }` each.
|
|
420
424
|
emitted,
|
|
425
|
+
// What the module has registered so far: `{ operations: [{ kind, operation }], self: [name], events: [name] }`, by
|
|
426
|
+
// `coda.handle`, `coda.self.handle` and `coda.on`.
|
|
427
|
+
registered: () => modules.registered(described),
|
|
421
428
|
// The plugin's settings written again, as `Plugins.setSettings` leaves them: what the module's `settings.get` gives from now
|
|
422
429
|
// on, and what its `settings.onChange` listeners are told, which have been by the time this is done.
|
|
423
430
|
setSettings: async next => {
|