@coda-console/antigravity 1.2.2 → 1.3.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/README.md +5 -3
- package/agent/catalog.mjs +240 -0
- package/agent/entry.mjs +33 -5
- package/agent/probe.mjs +76 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
把 [Google Antigravity](https://antigravity.google/cli) 的 Agent 接进 Coda。清单经一个薄转发入口(`agent/entry.mjs`)启动运行机上的 `agy acp`(Antigravity CLI 的 ACP 服务),
|
|
4
4
|
先找 `~/.local/bin/agy`,没有再用 PATH。每个会话一个进程,不登记等待项。
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
入口改三处,其余消息原样双向转发。第一处:把 `initialize` 答复里的 `additionalDirectories` 能力去掉,Coda 就不再给它传附加目录;
|
|
7
7
|
`session/new`、`session/load`、`session/resume` 里若仍带 `additionalDirectories` 也删掉。原因:agy 1.5.9 收到附加目录后,
|
|
8
8
|
没给 Cwd 的命令默认跑在**字典序最前的附加根**,而不是会话的工作副本(实测规律,不是上游的保证;数组顺序、`session/load` 都不改变它);
|
|
9
9
|
不传附加目录时命令就在工作副本里跑。
|
|
10
10
|
|
|
11
|
-
第二处是虚拟模式 `full
|
|
11
|
+
第二处是虚拟模式 `full`(「全部放行」),见下面「全部放行」一节。第三处是配置探测:入口在 `initialize` 声明 `_meta.coda.probe`,
|
|
12
|
+
带探测标记的 `session/new` 由入口用本机的目录缓存应答,不转给 agy,见「已知限制」的「配置探测」。
|
|
12
13
|
|
|
13
14
|
需要带会话指令兜底的 Coda(2026-11-13 部署版,coda#2500)或更新版本;旧版 Coda 不会给 Antigravity 送入会话指令。
|
|
14
15
|
|
|
@@ -78,13 +79,14 @@
|
|
|
78
79
|
| 额度的口径 | 报告按模型组给额度:同组模型共享每周与 5 小时限额,不是每个模型各算一份;报告里没有套餐名。第一次在某个目录运行 `/usage` 时,CLI 会在 `implicit/` 下留一个小文件;插件固定在系统临时目录运行,之后复用,不新增会话与项目记录 |
|
|
79
80
|
| 等待项登记 `_coda/wait` | 不登记,会话底部不列它在等什么 |
|
|
80
81
|
| Plan 模式 | 产出计划文件并要求审阅,审阅前不动手;plan 下只读的 shell 命令也按权限规则请求审批,这是 agy 的设计 |
|
|
81
|
-
| 删除会话 | 不支持:agy 1.5.9 的 ACP 没有 `session/delete`(回 -32601),`session/close`
|
|
82
|
+
| 删除会话 | 不支持:agy 1.5.9 的 ACP 没有 `session/delete`(回 -32601),`session/close` 也不删除。在 agy 历史里留下零步空会话的只有两种:不支持配置探测的旧版 Coda 每次普通探测建的会话,和插件缓存采集目录时自己建的那条,见「配置探测」。插件不自己删文件:那会绕过 agy 的取消、摘要缓存和搜索索引,agy 运行中删也不安全;等上游提供删除接口再接 |
|
|
82
83
|
| 附加目录 | 不交给 Antigravity:读工作副本外的附件、会话临时目录、skill 真实文件可能要审批;`.agents/skills` 的链接照旧 |
|
|
83
84
|
| Coda 的 MCP 工具在 auto 下也要审批 | 无人值守的子会话、流程步骤调用它们会停下;「全部放行」下不会。要在 auto 下放行,写法是在运行机的 `~/.gemini/antigravity-cli/settings.json` 里加 `{"permissions": {"allow": ["mcp(coda/*)"]}}`,出处是官方[权限文档](https://antigravity.google/docs/permissions/);插件不替你改这个文件 |
|
|
84
85
|
| 压缩上下文不上报 Coda | Antigravity 会压缩上下文:`/compact` 在 `agy acp` 1.5.9 上实测会跑一次摘要,对话库里留下摘要步骤;二进制里也有按 token 阈值触发的压缩配置,自动压缩没有实测触发。但 ACP 流和 `acp-server` 日志都不报压缩(没有 `compaction_update`,也没有专门的通知或工具调用),唯一的痕迹在它私有的对话库里,入口不读它,也不从文本或用量反推。所以依赖压缩的功能(如 Ultra 压缩后重发说明)在它上面压缩后不生效 |
|
|
85
86
|
| 额度耗尽 | 没有真实样本,不做失败分类,Coda 只看到 Antigravity 给的错误文字 |
|
|
86
87
|
| 没有桌面会话的 Linux 登录 | 未实测:Linux 用 Secret Service(D-Bus),二进制里有「keyring 失败就落文件」的回退,但文件路径与触发条件没查清。资源页在 Linux 上用 `secret-tool lookup service gemini username antigravity` 查条目(属性名按 go-keyring 的写法,未在真机上试过),没有 `secret-tool`、查不到条目,或登录落在文件里时,资源页当作未登录(只是仍在「添加资源」里出现,会话不受影响)。装了 `secret-tool` 却联系不上 Secret Service(典型是没有会话 D-Bus 的无桌面机器,它带错误信息退出)时,资源页读数失败、保留上次的显示,首次读取就没有可保留的,也就无法从资源页添加:这样的机器在终端里运行 `agy acp --login` 登录 |
|
|
87
88
|
| 第三方模型 | 账号里的 Claude、GPT-OSS 未实测 |
|
|
89
|
+
| 配置探测 | Coda 读模型、思考档位与模式的目录时,入口用插件状态目录里的缓存(`$CODA_PLUGIN_STATE/catalog-v1.json`)答一个只在当前连接有效的虚拟会话(`coda-probe:` 开头,不接受 prompt、不能恢复、断线即释放):**缓存命中时不建 Antigravity 会话**。缓存维护大约每天一次,以及 agy 的路径或版本、`~/.gemini/antigravity-cli/settings.json` 变化、真实会话报的配置与缓存对不上时,用一个独立的 `agy acp` 建一条空会话逐个模型读一遍(agy 1.5.9 删不了会话,这条会留在 `~/.gemini/antigravity-cli/conversations/`,会话 ID 记在 `catalog-v1.log`)。读失败时这次探测报错、不改用普通会话,同样的 agy 与设置 5 分钟内不再重读(未登录除外)。要支持配置探测的新版 Coda 才生效;旧版 Coda 每次探测仍各建一条空会话 |
|
|
88
90
|
| 并发进程 | 不加 `--process-per-session`:Coda 交给 Agent 的 MCP 服务器都是 stdio,官方只对 HTTP MCP 要求这个参数 |
|
|
89
91
|
|
|
90
92
|
## 验收
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// The catalog of Antigravity's models, modes and options that answers Coda's configuration probes (the protocol's
|
|
2
|
+
// 「配置探测」) without a native session: agy 1.5.9 cannot delete one, and each probe used to leave an empty conversation.
|
|
3
|
+
// It is kept in the plugin's state directory, `catalog-v1.json`, and collected when there is none or it is out of date:
|
|
4
|
+
// one `agy acp` of its own, initialize, session/new in a neutral directory of the state's, then each base model through
|
|
5
|
+
// set_config_option, and the process closed. No prompt, no delete, nothing global set. That collection does leave one
|
|
6
|
+
// empty conversation; its ID goes to the log, `catalog-v1.log`.
|
|
7
|
+
//
|
|
8
|
+
// Out of date: a day old, another format, another agy (path or version), another stat of ~/.gemini/antigravity-cli/settings.json,
|
|
9
|
+
// or marked by a real session whose options did not match. Entries collect one at a time (a lock in the state directory,
|
|
10
|
+
// waited on for a while, the catalog and the last failure read again once it is held); a collection that fails, or answers
|
|
11
|
+
// options that do not hold together, is not tried again for five minutes for the same agy and settings, and leaves the
|
|
12
|
+
// catalog there was.
|
|
13
|
+
//
|
|
14
|
+
// The lock is a line of generations, `catalog-v1.lock.<n>`, each made at once with its holder in it (a hard link); the
|
|
15
|
+
// highest is the lock. It is free once its holder marks it `.free`, is gone, or is past a collection's time, and is then
|
|
16
|
+
// taken by making the next generation, which only one entry can. No entry removes a lock above its own, so taking over a
|
|
17
|
+
// lock left behind cannot remove another's; the holder of a generation clears those below it.
|
|
18
|
+
import { execFile, spawn as spawnProcess } from 'node:child_process';
|
|
19
|
+
import { randomUUID } from 'node:crypto';
|
|
20
|
+
import { writeFileSync } from 'node:fs';
|
|
21
|
+
import * as fsPromises from 'node:fs/promises';
|
|
22
|
+
import { homedir } from 'node:os';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
25
|
+
import { versionOf } from '../scripts/agy.mjs';
|
|
26
|
+
|
|
27
|
+
export const FORMAT = 1;
|
|
28
|
+
// `collect` stays inside the 60 seconds Coda gives a probe; `wait` is how long an entry waits for another's collection.
|
|
29
|
+
export const LIMITS = { ttl: 24 * 3600_000, collect: 40_000, wait: 45_000, cooldown: 5 * 60_000, poll: 200, version: 10_000 };
|
|
30
|
+
const SIGNED_OUT = -32000;
|
|
31
|
+
|
|
32
|
+
export class CatalogError extends Error {
|
|
33
|
+
constructor(message, code = -32603) { super(message); this.code = code; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// The values of a select option, its groups flattened.
|
|
37
|
+
export const values = option => (Array.isArray(option?.options) ? option.options : [])
|
|
38
|
+
.flatMap(choice => Array.isArray(choice?.options) ? choice.options : [choice]).map(choice => choice?.value);
|
|
39
|
+
// What a list of options offers, without what is chosen: compared with the catalog's for the same model.
|
|
40
|
+
const shape = configOptions => JSON.stringify(configOptions.map(option => [option?.id, option?.category, option?.type, values(option)]));
|
|
41
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
42
|
+
// What is wrong with a list of options agy gave, or null: each select's current value is one of its own values.
|
|
43
|
+
function optionsProblem(configOptions) {
|
|
44
|
+
if (!Array.isArray(configOptions) || !configOptions.length) return '没有配置项';
|
|
45
|
+
for (const option of configOptions) {
|
|
46
|
+
if (typeof option?.id !== 'string') return '配置项没有 id';
|
|
47
|
+
if (option.type === 'select' && !values(option).includes(option.currentValue)) return `配置项 ${option.id} 的当前值 ${option.currentValue} 不在它的选项里`;
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const LOCK = /^catalog-v1\.lock\.(\d+)(\.free)?$/;
|
|
52
|
+
const generation = name => Number(LOCK.exec(name)?.[1] ?? 0);
|
|
53
|
+
|
|
54
|
+
async function askVersion(binary, timeout) {
|
|
55
|
+
return new Promise(resolve => execFile(binary, ['--version'], { encoding: 'utf8', timeout, env: { ...process.env, AGY_CLI_DISABLE_AUTO_UPDATE: 'true' } },
|
|
56
|
+
(error, stdout, stderr) => resolve(error ? null : versionOf({ stdout, stderr }))));
|
|
57
|
+
}
|
|
58
|
+
const alive = pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
|
|
59
|
+
|
|
60
|
+
// `state`: the plugin's state directory; `binary`: agy's path. The clock, the file system (node:fs/promises), the process
|
|
61
|
+
// (node:child_process spawn) and how agy's version is asked are given for the tests.
|
|
62
|
+
export function createCatalog({ state, binary, home = homedir(), now = Date.now, fs = fsPromises, spawn = spawnProcess, version = askVersion,
|
|
63
|
+
limits: given = {} } = {}) {
|
|
64
|
+
const limits = { ...LIMITS, ...given };
|
|
65
|
+
const file = name => join(state, name);
|
|
66
|
+
const paths = state && { catalog: file('catalog-v1.json'), failure: file('catalog-v1.failure.json'),
|
|
67
|
+
stale: file('catalog-v1.stale.json'), log: file('catalog-v1.log'), cwd: file('catalog-cwd') };
|
|
68
|
+
const lockFile = n => file(`catalog-v1.lock.${n}`);
|
|
69
|
+
let child = null, holding = 0, aborted = false;
|
|
70
|
+
|
|
71
|
+
const readJson = async path => { try { return JSON.parse(await fs.readFile(path, 'utf8')); } catch { return null; } };
|
|
72
|
+
const log = async event => {
|
|
73
|
+
const line = JSON.stringify({ at: new Date(now()).toISOString(), ...event });
|
|
74
|
+
process.stderr.write(`antigravity catalog: ${line}\n`);
|
|
75
|
+
try { await fs.appendFile(paths.log, `${line}\n`); } catch {}
|
|
76
|
+
};
|
|
77
|
+
// What a catalog is valid for: this agy and these settings.
|
|
78
|
+
async function fingerprint() {
|
|
79
|
+
const settings = await fs.stat(join(home, '.gemini/antigravity-cli/settings.json')).then(
|
|
80
|
+
s => ({ exists: true, size: s.size, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs, ino: s.ino }), () => ({ exists: false }));
|
|
81
|
+
return { format: FORMAT, agy: { path: binary, version: await version(binary, limits.version) }, settings };
|
|
82
|
+
}
|
|
83
|
+
async function usable(catalog, print) {
|
|
84
|
+
if (!catalog || catalog.format !== print.format || !same(catalog.agy, print.agy) || !same(catalog.settings, print.settings)) return false;
|
|
85
|
+
const age = now() - catalog.collectedAt;
|
|
86
|
+
if (!(age >= 0 && age < limits.ttl)) return false;
|
|
87
|
+
return (await readJson(paths.stale))?.collectedAt !== catalog.collectedAt;
|
|
88
|
+
}
|
|
89
|
+
// The lock, or false while another live entry holds it (or took it first).
|
|
90
|
+
async function lock() {
|
|
91
|
+
const names = await fs.readdir(state).catch(error => { throw new CatalogError(`插件状态目录读不了(${error.code ?? error.message}):${state}`); });
|
|
92
|
+
const top = Math.max(0, ...names.filter(name => !name.endsWith('.free')).map(generation));
|
|
93
|
+
if (top) {
|
|
94
|
+
const holder = await readJson(lockFile(top));
|
|
95
|
+
if (!names.includes(`catalog-v1.lock.${top}.free`) && holder && alive(holder.pid) && now() - holder.at <= limits.collect + 10_000) return false;
|
|
96
|
+
}
|
|
97
|
+
const mine = top + 1, temporary = `${lockFile(mine)}.${randomUUID()}.tmp`;
|
|
98
|
+
try { await fs.writeFile(temporary, JSON.stringify({ pid: process.pid, at: now() })); await fs.link(temporary, lockFile(mine)); }
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error.code === 'EEXIST') return false;
|
|
101
|
+
throw new CatalogError(`插件状态目录写不进去(${error.code ?? error.message}):${state}`);
|
|
102
|
+
} finally { await fs.rm(temporary, { force: true }); }
|
|
103
|
+
// One that read an older line than there is now may have made a generation that was cleared: a higher one wins.
|
|
104
|
+
const current = await fs.readdir(state);
|
|
105
|
+
if (current.some(name => generation(name) > mine)) return false;
|
|
106
|
+
holding = mine;
|
|
107
|
+
for (const name of current) if (generation(name) && generation(name) < mine) await fs.rm(file(name), { force: true });
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
const unlock = async () => { if (holding) { const n = holding; holding = 0; await fs.writeFile(`${lockFile(n)}.free`, ''); } };
|
|
111
|
+
|
|
112
|
+
// One collection, through an agy of its own: the catalog, or a CatalogError.
|
|
113
|
+
async function collect(print) {
|
|
114
|
+
await fs.mkdir(paths.cwd, { recursive: true });
|
|
115
|
+
const proc = child = spawn(binary, ['acp'], { cwd: paths.cwd, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
116
|
+
const pending = new Map();
|
|
117
|
+
let next = 0, rest = '', said = '', timer;
|
|
118
|
+
const send = message => { if (proc.stdin.writable) proc.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`); };
|
|
119
|
+
const ended = new Promise((_, reject) => {
|
|
120
|
+
proc.on('error', error => reject(new CatalogError(`无法运行 Antigravity CLI:${error.code ?? error.message}`)));
|
|
121
|
+
proc.on('close', code => reject(new CatalogError(`agy acp 提前退出了(${code ?? '信号'})${said.trim() ? `:${said.trim().split('\n').at(-1)}` : ''}`)));
|
|
122
|
+
timer = setTimeout(() => reject(new CatalogError(`读取模型目录超过 ${limits.collect / 1000} 秒`)), limits.collect);
|
|
123
|
+
});
|
|
124
|
+
ended.catch(() => {});
|
|
125
|
+
proc.stdin.on('error', () => {});
|
|
126
|
+
proc.stderr.setEncoding('utf8').on('data', text => { said = (said + text).slice(-2000); });
|
|
127
|
+
proc.stdout.setEncoding('utf8').on('data', text => {
|
|
128
|
+
const lines = (rest + text).split('\n'); rest = lines.pop();
|
|
129
|
+
for (const line of lines) {
|
|
130
|
+
let m; try { m = JSON.parse(line); } catch { continue; }
|
|
131
|
+
if (!m || typeof m !== 'object') continue;
|
|
132
|
+
if ('id' in m && !m.method) { pending.get(m.id)?.(m); pending.delete(m.id); }
|
|
133
|
+
else if ('id' in m) send({ id: m.id, error: { code: -32601, message: 'Method not found' } });
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
const call = (method, params) => Promise.race([ended, new Promise((resolve, reject) => {
|
|
137
|
+
const id = ++next;
|
|
138
|
+
pending.set(id, m => m.error ? reject(new CatalogError(`${method}:${m.error.message}`, m.error.code === SIGNED_OUT ? SIGNED_OUT : undefined)) : resolve(m.result));
|
|
139
|
+
send({ id, method, params });
|
|
140
|
+
})]);
|
|
141
|
+
try {
|
|
142
|
+
await call('initialize', { protocolVersion: 1, clientCapabilities: {} });
|
|
143
|
+
const opened = await call('session/new', { cwd: paths.cwd, mcpServers: [] });
|
|
144
|
+
await log({ event: 'collect.session', sessionId: opened?.sessionId });
|
|
145
|
+
const { sessionId, models, modes, configOptions } = opened ?? {};
|
|
146
|
+
const model = Array.isArray(configOptions) ? configOptions.find(option => option?.category === 'model' && option.type === 'select') : null;
|
|
147
|
+
if (!model) throw new CatalogError('agy 的 session/new 没给 category 为 model 的配置项');
|
|
148
|
+
const problem = optionsProblem(configOptions);
|
|
149
|
+
if (problem) throw new CatalogError(`agy 的 session/new 给的配置不对:${problem}`);
|
|
150
|
+
if (modes && !modes.availableModes?.some?.(mode => mode?.id === modes.currentModeId)) throw new CatalogError(`agy 的当前模式 ${modes.currentModeId} 不在它的模式里`);
|
|
151
|
+
const byModel = {};
|
|
152
|
+
for (const value of values(model)) {
|
|
153
|
+
const answer = await call('session/set_config_option', { sessionId, configId: model.id, value });
|
|
154
|
+
const chosen = Array.isArray(answer?.configOptions) ? answer.configOptions.find(option => option?.id === model.id) : null;
|
|
155
|
+
if (chosen?.currentValue !== value) throw new CatalogError(`切到模型 ${value} 后 agy 给的配置不是这个模型的`);
|
|
156
|
+
const wrong = optionsProblem(answer.configOptions) ?? (same(values(chosen), values(model)) ? null : '模型列表与 session/new 的不同');
|
|
157
|
+
if (wrong) throw new CatalogError(`切到模型 ${value} 后 agy 给的配置不对:${wrong}`);
|
|
158
|
+
byModel[value] = answer.configOptions;
|
|
159
|
+
}
|
|
160
|
+
if (!Object.keys(byModel).length) throw new CatalogError('agy 没给任何模型');
|
|
161
|
+
return { format: FORMAT, collectedAt: now(), agy: print.agy, settings: print.settings, initial: { models, modes, configOptions }, byModel };
|
|
162
|
+
} finally {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
child = null;
|
|
165
|
+
proc.stdin.end(); proc.kill();
|
|
166
|
+
setTimeout(() => proc.kill('SIGKILL'), 800).unref();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
// Collects and writes the catalog, all of it or nothing; a failure is remembered.
|
|
170
|
+
async function refresh(print) {
|
|
171
|
+
const started = now();
|
|
172
|
+
try {
|
|
173
|
+
const catalog = await collect(print);
|
|
174
|
+
const temporary = `${paths.catalog}.${process.pid}.${randomUUID()}.tmp`;
|
|
175
|
+
try { await fs.writeFile(temporary, JSON.stringify(catalog)); await fs.rename(temporary, paths.catalog); }
|
|
176
|
+
catch (error) { await fs.rm(temporary, { force: true }).catch(() => {}); throw new CatalogError(`写不了模型目录(${error.code ?? error.message}):${state}`); }
|
|
177
|
+
await fs.rm(paths.failure, { force: true });
|
|
178
|
+
await log({ event: 'collect.done', models: Object.keys(catalog.byModel).length, ms: now() - started });
|
|
179
|
+
return catalog;
|
|
180
|
+
} catch (error) {
|
|
181
|
+
const reason = error.message;
|
|
182
|
+
await log({ event: 'collect.failed', reason, ms: now() - started });
|
|
183
|
+
// Signed out is not remembered: signing in changes nothing a catalog is checked against; nor is a collection the
|
|
184
|
+
// entry stopped as it went.
|
|
185
|
+
if (error.code !== SIGNED_OUT && !aborted) await fs.writeFile(paths.failure, JSON.stringify({ at: now(), reason, fingerprint: print })).catch(() => {});
|
|
186
|
+
throw error instanceof CatalogError ? error : new CatalogError(reason);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
// The catalog, up to date: read, or collected. A CatalogError says why there is none.
|
|
192
|
+
async get() {
|
|
193
|
+
if (!state) throw new CatalogError('没有插件状态目录(CODA_PLUGIN_STATE),存不了模型目录');
|
|
194
|
+
const print = await fingerprint(), deadline = now() + limits.wait;
|
|
195
|
+
// The catalog if it is up to date, null if it is to be collected; a failure still cooling down is thrown.
|
|
196
|
+
const settled = async () => {
|
|
197
|
+
const cached = await readJson(paths.catalog);
|
|
198
|
+
if (await usable(cached, print)) return cached;
|
|
199
|
+
const failure = await readJson(paths.failure);
|
|
200
|
+
if (failure && same(failure.fingerprint, print) && now() - failure.at < limits.cooldown)
|
|
201
|
+
throw new CatalogError(`读取 Antigravity 的模型目录失败,${Math.ceil((failure.at + limits.cooldown - now()) / 1000)} 秒后再试:${failure.reason}`);
|
|
202
|
+
return null;
|
|
203
|
+
};
|
|
204
|
+
for (;;) {
|
|
205
|
+
const cached = await settled();
|
|
206
|
+
if (cached) return cached;
|
|
207
|
+
if (await lock()) {
|
|
208
|
+
// Another entry may have collected, or failed to, between the reading and the lock.
|
|
209
|
+
try { return await settled() ?? await refresh(print); } finally { await unlock(); }
|
|
210
|
+
}
|
|
211
|
+
if (now() >= deadline) throw new CatalogError(`等另一个进程读取模型目录超过 ${limits.wait / 1000} 秒`);
|
|
212
|
+
await delay(limits.poll);
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
// What a real session offers (its configOptions, and modes when it says them), held to the catalog's for its current model:
|
|
216
|
+
// one that differs marks the catalog to be collected again. Nothing else is learnt from it.
|
|
217
|
+
observe({ configOptions, modes } = {}) {
|
|
218
|
+
if (!state || !Array.isArray(configOptions)) return;
|
|
219
|
+
const model = configOptions.find(option => option?.category === 'model'), seen = shape(configOptions);
|
|
220
|
+
const modeIds = Array.isArray(modes?.availableModes) ? modes.availableModes.map(mode => mode?.id) : null;
|
|
221
|
+
if (!model) return;
|
|
222
|
+
void (async () => {
|
|
223
|
+
const catalog = await readJson(paths.catalog);
|
|
224
|
+
if (!catalog?.byModel) return;
|
|
225
|
+
const known = catalog.byModel[model.currentValue];
|
|
226
|
+
const reason = !known ? `目录里没有模型 ${model.currentValue}` : shape(known) !== seen ? `模型 ${model.currentValue} 的配置项与目录不同`
|
|
227
|
+
: modeIds && !same(modeIds, catalog.initial?.modes?.availableModes?.map(mode => mode?.id)) ? '模式与目录不同' : null;
|
|
228
|
+
if (!reason || (await readJson(paths.stale))?.collectedAt === catalog.collectedAt) return;
|
|
229
|
+
await fs.writeFile(paths.stale, JSON.stringify({ collectedAt: catalog.collectedAt, at: now(), reason }));
|
|
230
|
+
await log({ event: 'stale', reason });
|
|
231
|
+
})().catch(() => {});
|
|
232
|
+
},
|
|
233
|
+
// The entry is going: its collection, if any, and its lock go with it.
|
|
234
|
+
abort() {
|
|
235
|
+
aborted = true;
|
|
236
|
+
child?.kill('SIGKILL');
|
|
237
|
+
if (holding) { writeFileSync(`${lockFile(holding)}.free`, ''); holding = 0; }
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
package/agent/entry.mjs
CHANGED
|
@@ -6,16 +6,26 @@
|
|
|
6
6
|
// 2. A virtual mode `full` ("allow everything"). agy has no such mode and cannot change its permission policy once it
|
|
7
7
|
// runs, so a session in `full` runs in agy's `default` and the entry answers each of its permission requests itself
|
|
8
8
|
// with the allow_once option. Switching in and out is rewritten on the way: Coda sees `full` as an ordinary mode.
|
|
9
|
+
// 3. Configuration probes (catalog.mjs, probe.mjs): `initialize` declares `_meta.coda.probe`, and `session/new` marked
|
|
10
|
+
// `_meta.coda.probe: true` opens a session of this connection alone, answered from the catalog and never sent to agy; so
|
|
11
|
+
// does every request about a session of the `coda-probe:` namespace. What real sessions say of their options is held to
|
|
12
|
+
// the catalog, which one that differs marks to be collected again.
|
|
9
13
|
import { spawn } from 'node:child_process';
|
|
10
14
|
import { agyBinary } from '../scripts/agy.mjs';
|
|
15
|
+
import { createCatalog } from './catalog.mjs';
|
|
16
|
+
import { PREFIX, Probes, probeMark } from './probe.mjs';
|
|
11
17
|
|
|
12
|
-
const
|
|
18
|
+
const binary = agyBinary() ?? 'agy';
|
|
19
|
+
const agy = spawn(binary, ['acp'], { stdio: ['pipe', 'pipe', 'inherit'] });
|
|
13
20
|
const initializing = new Set();
|
|
14
21
|
const sessionRequests = new Set();
|
|
15
22
|
const configRequests = new Map(); // request id -> { sessionId, was }: a set_config_option, whose answer lists the options; `was` for a mode switch, undone if agy refuses it
|
|
16
23
|
const full = new Set(); // sessions in `full`
|
|
17
24
|
const FULL_NAME = '全部放行';
|
|
18
25
|
const FULL_DESCRIPTION = 'Approve everything without asking.';
|
|
26
|
+
const catalog = createCatalog({ state: process.env.CODA_PLUGIN_STATE, binary });
|
|
27
|
+
const probes = new Probes({ extraMode: { id: 'full', name: FULL_NAME, description: FULL_DESCRIPTION } });
|
|
28
|
+
const answer = (id, reply) => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id, ...reply })}\n`);
|
|
19
29
|
let stopping = false;
|
|
20
30
|
|
|
21
31
|
// Only LF separates JSON messages; readline would also split literal Unicode line separators inside JSON strings.
|
|
@@ -49,8 +59,23 @@ function switchMode(message, to) {
|
|
|
49
59
|
if (to === 'full') full.add(sessionId); else full.delete(sessionId);
|
|
50
60
|
}
|
|
51
61
|
|
|
62
|
+
// A probe's `session/new`: a session from the catalog, or the reason there is none. A wrong mark is refused.
|
|
63
|
+
function probe(id) {
|
|
64
|
+
catalog.get().then(got => answer(id, { result: probes.open(got) }),
|
|
65
|
+
error => answer(id, { error: { code: error.code ?? -32603, message: error.message } }));
|
|
66
|
+
}
|
|
67
|
+
|
|
52
68
|
relay(process.stdin, agy.stdin, message => {
|
|
53
69
|
const { method, params, id } = message;
|
|
70
|
+
if (method === 'session/new' && probeMark(params) !== undefined) {
|
|
71
|
+
if (!('id' in message)) return false;
|
|
72
|
+
if (probeMark(params)) probe(id); else answer(id, { error: { code: -32602, message: '_meta.coda.probe 只能为 true' } });
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
if (typeof params?.sessionId === 'string' && params.sessionId.startsWith(PREFIX)) {
|
|
76
|
+
if ('id' in message) answer(id, probes.handle(method, params));
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
54
79
|
if (method === 'initialize' && 'id' in message) initializing.add(id);
|
|
55
80
|
if (['session/new', 'session/load', 'session/resume'].includes(method)) { delete params?.additionalDirectories; sessionRequests.add(id); }
|
|
56
81
|
if (method === 'session/set_mode' && typeof params?.sessionId === 'string') {
|
|
@@ -68,10 +93,13 @@ relay(process.stdin, agy.stdin, message => {
|
|
|
68
93
|
relay(agy.stdout, process.stdout, message => {
|
|
69
94
|
const { method, params, id } = message;
|
|
70
95
|
if (!method) {
|
|
71
|
-
if (initializing.delete(id)) {
|
|
72
|
-
|
|
96
|
+
if (initializing.delete(id) && message.result?.agentCapabilities) {
|
|
97
|
+
const capabilities = message.result.agentCapabilities;
|
|
98
|
+
for (const key of ['sessionCapabilities', 'session_capabilities']) delete capabilities[key]?.additionalDirectories;
|
|
99
|
+
capabilities._meta = { ...capabilities._meta, coda: { ...capabilities._meta?.coda, probe: {} } };
|
|
73
100
|
}
|
|
74
101
|
if (sessionRequests.delete(id) && message.result) {
|
|
102
|
+
catalog.observe(message.result);
|
|
75
103
|
const { modes } = message.result;
|
|
76
104
|
if (Array.isArray(modes?.availableModes)) modes.availableModes.push({ id: 'full', name: FULL_NAME, description: FULL_DESCRIPTION });
|
|
77
105
|
fixConfigOptions(message.result.sessionId, message.result.configOptions);
|
|
@@ -79,7 +107,7 @@ relay(agy.stdout, process.stdout, message => {
|
|
|
79
107
|
const config = configRequests.get(id);
|
|
80
108
|
if (config) {
|
|
81
109
|
configRequests.delete(id);
|
|
82
|
-
if (!message.error) fixConfigOptions(config.sessionId, message.result?.configOptions);
|
|
110
|
+
if (!message.error) { catalog.observe(message.result ?? {}); fixConfigOptions(config.sessionId, message.result?.configOptions); }
|
|
83
111
|
else if (config.was) full.add(config.sessionId);
|
|
84
112
|
else if (config.was === false) full.delete(config.sessionId);
|
|
85
113
|
}
|
|
@@ -100,7 +128,7 @@ relay(agy.stdout, process.stdout, message => {
|
|
|
100
128
|
});
|
|
101
129
|
const stop = () => {
|
|
102
130
|
if (stopping) return;
|
|
103
|
-
stopping = true; agy.stdin.end(); agy.kill();
|
|
131
|
+
stopping = true; probes.clear(); catalog.abort(); agy.stdin.end(); agy.kill();
|
|
104
132
|
setTimeout(() => agy.kill('SIGKILL'), 800).unref();
|
|
105
133
|
};
|
|
106
134
|
agy.stdin.on('error', () => {});
|
package/agent/probe.mjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// The sessions of Coda's configuration probes (the protocol's「配置探测」): `session/new` marked `_meta.coda.probe: true`
|
|
2
|
+
// opens one in this connection alone, answered from the catalog (catalog.mjs) and never sent to agy. Each has its own copy
|
|
3
|
+
// of the catalog's options; switching the model takes that model's whole list. It takes no prompt, cannot be loaded or
|
|
4
|
+
// resumed, and goes with the connection.
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { values } from './catalog.mjs';
|
|
7
|
+
|
|
8
|
+
export const PREFIX = 'coda-probe:';
|
|
9
|
+
const INVALID = -32602, UNKNOWN = -32002;
|
|
10
|
+
const refuse = (code, message) => ({ error: { code, message } });
|
|
11
|
+
|
|
12
|
+
// Whether `session/new` params ask for a probe: undefined for an ordinary session, else whether the mark is right (`true`).
|
|
13
|
+
export function probeMark(params) {
|
|
14
|
+
const coda = params?._meta?.coda;
|
|
15
|
+
return coda && typeof coda === 'object' && 'probe' in coda ? coda.probe === true : undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// `extraMode`: a mode of the entry's own ({ id, name, description }), offered beside agy's.
|
|
19
|
+
export class Probes {
|
|
20
|
+
constructor({ extraMode } = {}) { this.extraMode = extraMode; this.sessions = new Map(); }
|
|
21
|
+
|
|
22
|
+
// Adds the entry's mode to the mode option and sets it to the session's mode.
|
|
23
|
+
withMode(configOptions, modeId) {
|
|
24
|
+
const mode = configOptions.find(option => option?.category === 'mode' || option?.id === 'mode');
|
|
25
|
+
if (!mode) return configOptions;
|
|
26
|
+
if (this.extraMode && Array.isArray(mode.options)) mode.options.push({ value: this.extraMode.id, name: this.extraMode.name, description: this.extraMode.description });
|
|
27
|
+
if (modeId) mode.currentValue = modeId;
|
|
28
|
+
return configOptions;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// A new session from the catalog: what `session/new` answers.
|
|
32
|
+
open(catalog) {
|
|
33
|
+
const sessionId = `${PREFIX}${randomUUID()}`, { models, modes, configOptions } = structuredClone(catalog.initial);
|
|
34
|
+
if (this.extraMode && Array.isArray(modes?.availableModes)) modes.availableModes.push({ ...this.extraMode });
|
|
35
|
+
const session = { catalog, models, modes, configOptions: this.withMode(configOptions) };
|
|
36
|
+
this.sessions.set(sessionId, session);
|
|
37
|
+
return structuredClone({ sessionId, ...(models && { models }), ...(modes && { modes }), configOptions: session.configOptions });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The answer to a request about a session of this namespace, `{ result }` or `{ error }`; nothing goes to agy.
|
|
41
|
+
handle(method, params) {
|
|
42
|
+
const { sessionId } = params;
|
|
43
|
+
const session = this.sessions.get(sessionId);
|
|
44
|
+
if (!session) return refuse(UNKNOWN, `配置探测会话 ${sessionId} 不存在或已失效`);
|
|
45
|
+
if (method === 'session/load' || method === 'session/resume') return refuse(INVALID, '配置探测会话不能恢复');
|
|
46
|
+
if (method === 'session/prompt') return refuse(INVALID, '配置探测会话不接受 prompt');
|
|
47
|
+
if (method === 'session/close') { this.sessions.delete(sessionId); return { result: {} }; }
|
|
48
|
+
if (method === 'session/set_config_option') return this.configure(session, params);
|
|
49
|
+
if (method === 'session/set_mode') {
|
|
50
|
+
if (!session.modes?.availableModes?.some(mode => mode?.id === params.modeId)) return refuse(INVALID, `没有模式 ${params.modeId}`);
|
|
51
|
+
this.setMode(session, params.modeId);
|
|
52
|
+
return { result: {} };
|
|
53
|
+
}
|
|
54
|
+
return refuse(INVALID, `配置探测会话不支持 ${method}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
setMode(session, modeId) {
|
|
58
|
+
if (session.modes) session.modes.currentModeId = modeId;
|
|
59
|
+
for (const option of session.configOptions) if (option?.category === 'mode' || option?.id === 'mode') option.currentValue = modeId;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
configure(session, { configId, value }) {
|
|
63
|
+
const option = session.configOptions.find(o => o?.id === configId);
|
|
64
|
+
if (!option) return refuse(INVALID, `当前模型没有配置项 ${configId}`);
|
|
65
|
+
if (!values(option).includes(value)) return refuse(INVALID, `配置项 ${configId} 没有值 ${value}`);
|
|
66
|
+
if (option.category === 'model') {
|
|
67
|
+
const options = session.catalog.byModel[value];
|
|
68
|
+
if (!options) return refuse(-32603, `模型目录里没有模型 ${value} 的配置`);
|
|
69
|
+
session.configOptions = this.withMode(structuredClone(options), session.modes?.currentModeId);
|
|
70
|
+
} else if (option.category === 'mode' || option.id === 'mode') this.setMode(session, value);
|
|
71
|
+
else option.currentValue = value;
|
|
72
|
+
return { result: { configOptions: structuredClone(session.configOptions) } };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
clear() { this.sessions.clear(); }
|
|
76
|
+
}
|