@yitom/acp-client 0.1.6 → 0.1.8

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 CHANGED
@@ -29,6 +29,8 @@
29
29
  自动处理 `resume` → `load` → `new` 会话恢复流程,处理模型方言(models 数组/对象)、无 MCP 自动降级与网络抖动重试。
30
30
  - **解耦的事件钩子与审批**:
31
31
  工具调用审批、权限请求、会话流式更新采用标准的回调与事件驱动,宿主自由决定如何确认(命令行交互 / 桌面弹窗 / Web 消息)。
32
+ - **应用资源目录(单目录接口)**:
33
+ 宿主只传 `resources: { directory }`(`AGENTS.md` + `skills/<name>/SKILL.md`),SDK 负责读取、摘要、配置合并、资格/版本门、会话级记录与温复用标签;详见 `docs/api-reference.md §5` 与 `examples/app-resources-demo.ts`。
32
34
 
33
35
  ---
34
36
 
@@ -135,3 +137,15 @@ bun run build:acp
135
137
  ```bash
136
138
  bun run packages/acp/examples/standalone-acp-demo.ts
137
139
  ```
140
+
141
+ 资源接口当前为未发布试点:规则准备与会话应用分开记录;已有磁盘配置保守回退;skillsFound 仅 SDK 文件扫描,尚无原生技能挂载或通用兼容提示词注入。详见 docs/api-reference.md 第 5 节。
142
+
143
+ 应用资源跨运行时验收:OpenCode 1.18.35 已通过真实 ACP + 本地 mock 模型 + 技能 MCP 两轮链路,复跑脚本为 `scripts/smoke-opencode-resources.mjs`;2.0.6 完整链路仍待验,详见 `docs/api-reference.md` 支持矩阵。
144
+
145
+ 原生资源策略见 `src/resources/runtime-bindings.ts` / `docs/api-reference.md §5`:OpenCode 1.18.35 已验证原生 system 规则、native skill 和 MCP;Claude 0.91.0 已接官方原生会话扩展(仅源码契约+mock 验收);其余运行时明确兼容,不自动迁移认证 HOME。
146
+
147
+ 会话专属配置环境:`resources: { directory, configurationScope: 'session' }`。仅替换子进程原生配置根,生成规则/纯文档技能、断开清理;不复制用户认证。支持范围、Cursor 规则边界及 agy/DeepSeek 的明确拒绝见 `docs/api-reference.md`。实现与测试:`src/resources/session-config.ts` / `session-config.test.ts`。
148
+
149
+ ### Antigravity session resources
150
+
151
+ With `@yitom/agy-acp-map` 0.1.24, `resources.directory` is delivered through the bridge session extension `_meta.appResources.directory`. Rules, native Skills and session MCP live in a private temporary additional workspace; cwd, global configuration and authentication remain unchanged. Close/delete/orderly shutdown remove the temporary workspace. Unknown bridge versions keep compatibility guidance and the app-skills MCP fallback. This extension is bridge-specific, not a standard ACP configuration-home API. `configurationScope: "session"` also supports agy; its configuration report remains conservative until the bridge accepts the session extension.
@@ -0,0 +1,291 @@
1
+ // src/mcp/app-skills-mcp-serve.ts
2
+ var import_node_readline = require("node:readline");
3
+
4
+ // src/mcp/app-skills-mcp.ts
5
+ var import_node_path2 = require("node:path");
6
+ var import_node_path3 = require("node:path");
7
+ var import_node_fs2 = require("node:fs");
8
+
9
+ // src/resources/app-resources.ts
10
+ var import_node_crypto = require("node:crypto");
11
+ var import_node_fs = require("node:fs");
12
+ var import_node_path = require("node:path");
13
+ var APP_RULES_FILE = "AGENTS.md";
14
+ var APP_SKILLS_DIR = "skills";
15
+ var APP_SKILL_FILE = "SKILL.md";
16
+ function parseSkillFrontmatter(text) {
17
+ const lines = text.split(`
18
+ `);
19
+ if (lines[0]?.trim() !== "---")
20
+ return {};
21
+ const out = {};
22
+ for (let i = 1;i < lines.length; i += 1) {
23
+ const line = lines[i] ?? "";
24
+ if (line.trim() === "---")
25
+ break;
26
+ const cut = line.indexOf(":");
27
+ if (cut <= 0)
28
+ continue;
29
+ const key = line.slice(0, cut).trim().toLowerCase();
30
+ if (key !== "name" && key !== "description")
31
+ continue;
32
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
33
+ if (value)
34
+ out[key] = value;
35
+ }
36
+ return out;
37
+ }
38
+ function sha256Hex(text) {
39
+ return import_node_crypto.createHash("sha256").update(text, "utf8").digest("hex");
40
+ }
41
+ function readTextFile(path) {
42
+ try {
43
+ if (!import_node_fs.statSync(path).isFile())
44
+ return null;
45
+ const text = import_node_fs.readFileSync(path, "utf8");
46
+ return text.trim() ? text : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ function readAppResourcesDir(directory) {
52
+ const warnings = [];
53
+ if (!import_node_path.isAbsolute(directory))
54
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
55
+ let directoryReadable = false;
56
+ try {
57
+ directoryReadable = import_node_fs.statSync(directory).isDirectory();
58
+ } catch {
59
+ directoryReadable = false;
60
+ }
61
+ if (!directoryReadable) {
62
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
63
+ }
64
+ let rules = null;
65
+ const rulesText = readTextFile(import_node_path.join(directory, APP_RULES_FILE));
66
+ if (rulesText === null) {
67
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
68
+ } else {
69
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
70
+ ${rulesText}`) };
71
+ }
72
+ const skills = [];
73
+ const skillsRoot = import_node_path.join(directory, APP_SKILLS_DIR);
74
+ let skillNames = [];
75
+ try {
76
+ if (import_node_fs.statSync(skillsRoot).isDirectory()) {
77
+ skillNames = import_node_fs.readdirSync(skillsRoot).filter((name) => {
78
+ try {
79
+ return import_node_fs.statSync(import_node_path.join(skillsRoot, name)).isDirectory();
80
+ } catch {
81
+ return false;
82
+ }
83
+ });
84
+ }
85
+ } catch {
86
+ skillNames = [];
87
+ }
88
+ for (const name of skillNames.sort()) {
89
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
90
+ const text = readTextFile(import_node_path.join(directory, rel));
91
+ if (text === null) {
92
+ warnings.push(`技能缺正文已跳过: ${rel}`);
93
+ continue;
94
+ }
95
+ const front = parseSkillFrontmatter(text);
96
+ const skillName = front.name || name;
97
+ if (skills.some((s) => s.name === skillName)) {
98
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
99
+ continue;
100
+ }
101
+ const description = front.description || "";
102
+ skills.push({
103
+ name: skillName,
104
+ description,
105
+ path: rel,
106
+ chars: text.length,
107
+ digest: sha256Hex(`app-skill-v1
108
+ ${skillName}
109
+ ${description}
110
+ ${text}`)
111
+ });
112
+ }
113
+ return { directoryReadable: true, rules, skills, warnings };
114
+ }
115
+
116
+ // src/mcp/app-skills-mcp.ts
117
+ var APP_SKILLS_TOOLS = [
118
+ {
119
+ name: "app_list_skills",
120
+ description: "List host skill catalog (names and one-line descriptions). " + "Call this first to discover available skills; then read a body with app_read_skill before claiming its content. " + "Skill bodies are never inlined here—always read on demand.",
121
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
122
+ },
123
+ {
124
+ name: "app_read_skill",
125
+ description: "Read one registered skill body by exact name from app_list_skills. " + "Optional ref reads another Markdown file in the same skill directory " + "(same-directory relative .md only; anything else is rejected).",
126
+ inputSchema: {
127
+ type: "object",
128
+ properties: {
129
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
130
+ ref: {
131
+ type: "string",
132
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
133
+ }
134
+ },
135
+ required: ["name"],
136
+ additionalProperties: false
137
+ }
138
+ }
139
+ ];
140
+ function skillDirOf(directory, skillName) {
141
+ const load = readAppResourcesDir(directory);
142
+ const found = load.skills.find((s) => s.name === skillName);
143
+ if (!found)
144
+ return null;
145
+ return import_node_path3.join(directory, APP_SKILLS_DIR, found.path.split("/")[1]);
146
+ }
147
+ function readSkillFile(skillDir, ref) {
148
+ let rel = APP_SKILL_FILE;
149
+ if (ref !== undefined) {
150
+ if (typeof ref !== "string" || !ref.trim())
151
+ return { error: "invalid-ref: ref 必须是非空相对路径" };
152
+ const normalized = import_node_path2.normalize(ref.trim());
153
+ if (normalized.startsWith("..") || normalized.startsWith(import_node_path2.sep) || /^[A-Za-z]:/.test(normalized)) {
154
+ return { error: "invalid-ref: 只允许技能目录内的相对路径" };
155
+ }
156
+ if (!normalized.toLowerCase().endsWith(".md")) {
157
+ return { error: "invalid-ref: 只允许同目录 .md 文件" };
158
+ }
159
+ const resolved = import_node_path2.resolve(skillDir, normalized);
160
+ const root = import_node_path2.resolve(skillDir) + import_node_path2.sep;
161
+ if (resolved !== import_node_path2.resolve(skillDir) && !resolved.startsWith(root)) {
162
+ return { error: "invalid-ref: 越界引用被拒绝" };
163
+ }
164
+ rel = normalized;
165
+ }
166
+ const full = import_node_path3.join(skillDir, rel);
167
+ try {
168
+ if (!import_node_fs2.statSync(full).isFile())
169
+ return { error: "unreadable-skill-file" };
170
+ const text = import_node_fs2.readFileSync(full, "utf8");
171
+ if (!text.trim())
172
+ return { error: "unreadable-skill-file" };
173
+ return { text };
174
+ } catch {
175
+ return { error: "unreadable-skill-file" };
176
+ }
177
+ }
178
+ async function callAppSkillsTool(directory, name, args) {
179
+ const text = (value) => ({ content: [{ type: "text", text: value }] });
180
+ const fail = (message) => ({
181
+ content: [{ type: "text", text: message }],
182
+ isError: true
183
+ });
184
+ if (name === "app_list_skills") {
185
+ const load = readAppResourcesDir(directory);
186
+ if (!load.directoryReadable)
187
+ return fail("resource-directory-unreadable");
188
+ const items = load.skills.map((s) => ({ name: s.name, description: s.description, version: s.digest.slice(0, 16) }));
189
+ return text(JSON.stringify({ skills: items }, null, 2));
190
+ }
191
+ if (name === "app_read_skill") {
192
+ const skillName = args?.["name"];
193
+ if (typeof skillName !== "string" || !skillName)
194
+ return fail("unknown-skill: 需要 exact name");
195
+ const skillDir = skillDirOf(directory, skillName);
196
+ if (!skillDir)
197
+ return fail(`unknown-skill: ${skillName}`);
198
+ const load = readAppResourcesDir(directory);
199
+ const record = load.skills.find((s) => s.name === skillName);
200
+ const got = readSkillFile(skillDir, args?.["ref"]);
201
+ if ("error" in got)
202
+ return fail(got.error);
203
+ const body = {
204
+ name: skillName,
205
+ description: record?.description ?? parseSkillFrontmatter(got.text).description ?? "",
206
+ version: record ? record.digest.slice(0, 16) : null,
207
+ text: got.text
208
+ };
209
+ return text(JSON.stringify(body, null, 2));
210
+ }
211
+ return fail(`unknown-tool: ${name}`);
212
+ }
213
+
214
+ // src/mcp/app-skills-mcp-serve.ts
215
+ var FALLBACK_PROTOCOL_VERSION = "2025-06-18";
216
+ function send(value) {
217
+ process.stdout.write(`${JSON.stringify(value)}
218
+ `);
219
+ }
220
+ function logRead(skill, version) {
221
+ process.stderr.write(`${JSON.stringify({ "app-skills-read": { skill, version } })}
222
+ `);
223
+ }
224
+ async function main() {
225
+ const directory = process.argv[2];
226
+ if (!directory) {
227
+ process.stderr.write(`用法: app-skills-mcp.cjs <directory>
228
+ `);
229
+ process.exitCode = 2;
230
+ return;
231
+ }
232
+ const rl = import_node_readline.createInterface({ input: process.stdin });
233
+ rl.on("line", (line) => {
234
+ handleLine(line).catch((error) => {
235
+ process.stderr.write(`handler failed: ${error instanceof Error ? error.message : String(error)}
236
+ `);
237
+ });
238
+ });
239
+ async function handleLine(line) {
240
+ let msg;
241
+ try {
242
+ msg = JSON.parse(line);
243
+ } catch {
244
+ return;
245
+ }
246
+ if (msg.id === undefined || msg.id === null)
247
+ return;
248
+ const { id, method, params } = msg;
249
+ if (method === "initialize") {
250
+ const requested = params?.["protocolVersion"];
251
+ send({
252
+ jsonrpc: "2.0",
253
+ id,
254
+ result: {
255
+ protocolVersion: typeof requested === "string" ? requested : FALLBACK_PROTOCOL_VERSION,
256
+ capabilities: { tools: { listChanged: false } },
257
+ serverInfo: { name: "app-skills", version: "1" }
258
+ }
259
+ });
260
+ return;
261
+ }
262
+ if (method === "ping") {
263
+ send({ jsonrpc: "2.0", id, result: {} });
264
+ return;
265
+ }
266
+ if (method === "tools/list") {
267
+ send({ jsonrpc: "2.0", id, result: { tools: APP_SKILLS_TOOLS } });
268
+ return;
269
+ }
270
+ if (method === "tools/call") {
271
+ const name = params?.["name"];
272
+ if (typeof name !== "string") {
273
+ send({ jsonrpc: "2.0", id, error: { code: -32602, message: "tools/call 需要 name" } });
274
+ return;
275
+ }
276
+ const rawArgs = params?.["arguments"];
277
+ const args = rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs) ? rawArgs : undefined;
278
+ const result = await callAppSkillsTool(directory, name, args);
279
+ if (name === "app_read_skill" && !result.isError && typeof args?.["name"] === "string") {
280
+ try {
281
+ const parsed = JSON.parse(result.content[0]?.text ?? "{}");
282
+ logRead(args["name"], typeof parsed.version === "string" ? parsed.version : null);
283
+ } catch {}
284
+ }
285
+ send({ jsonrpc: "2.0", id, result });
286
+ return;
287
+ }
288
+ send({ jsonrpc: "2.0", id, error: { code: -32601, message: `未实现的方法: ${method}` } });
289
+ }
290
+ }
291
+ main();
@@ -3,6 +3,7 @@ import type { AcpAgentQuota } from '../contracts';
3
3
  import { type InitializeResponse } from '@agentclientprotocol/sdk';
4
4
  import type { AcpConnectionStatus, AcpPermissionOutcome, AcpProxySettings, AcpRuntimeInfo, AcpSessionRestoreMethod, AppError, InkdownVirtualResource } from "../contracts";
5
5
  import { type Result } from "../contracts";
6
+ import type { AppResourceReport } from '../resources/app-resources';
6
7
  export interface AcpClientCallbacks {
7
8
  /** 权限审批回调:当 Agent 尝试执行工具调用或敏感操作时触发 */
8
9
  onPermissionRequest?: (payload: {
@@ -41,6 +42,20 @@ export interface AcpClientOptions {
41
42
  proxy?: Partial<AcpProxySettings>;
42
43
  /** 附加环境变量 */
43
44
  env?: NodeJS.ProcessEnv;
45
+ /**
46
+ * 应用资源目录(单目录接口):`{ directory: 绝对路径 }`,
47
+ * 含 AGENTS.md 与 skills/ 下 SKILL.md。提供即走原生资源准备
48
+ * (读取/合并/注入/报告),缺席则保持旧行为一字不动。
49
+ * `attachSkillsMcp` 缺省 true:建会话时自动挂载技能 MCP(调用方
50
+ * 同名服务优先保留);显式 false 关闭自动挂载。
51
+ * configurationScope=session:子进程独占临时原生配置根,断开清理;
52
+ * 不复制认证。缺省 overlay 保持现有用户登录环境。
53
+ */
54
+ resources?: {
55
+ directory: string;
56
+ attachSkillsMcp?: boolean;
57
+ configurationScope?: 'overlay' | 'session';
58
+ };
44
59
  /** 事件与审批回调 */
45
60
  callbacks?: AcpClientCallbacks;
46
61
  }
@@ -49,7 +64,11 @@ export declare class AcpSessionHandle {
49
64
  private readonly client;
50
65
  readonly restoreMethod: AcpSessionRestoreMethod;
51
66
  readonly configOptions?: unknown;
52
- constructor(sessionId: string, client: AcpClient, restoreMethod: AcpSessionRestoreMethod, configOptions?: unknown);
67
+ /** 建会话时刻的应用资源加载报告快照(规则/技能分开记录) */
68
+ readonly resourceReport?: AppResourceReport | null | undefined;
69
+ constructor(sessionId: string, client: AcpClient, restoreMethod: AcpSessionRestoreMethod, configOptions?: unknown,
70
+ /** 建会话时刻的应用资源加载报告快照(规则/技能分开记录) */
71
+ resourceReport?: AppResourceReport | null | undefined);
53
72
  /** 向当前会话发送 Prompt / 消息交互 */
54
73
  prompt(promptText: string, options?: {
55
74
  timeoutMs?: number;
@@ -84,6 +103,10 @@ export declare class AcpClient {
84
103
  private readonly clientInfo;
85
104
  private readonly dataDir;
86
105
  private readonly extraEnv;
106
+ private readonly configurationScope;
107
+ private sessionConfig;
108
+ private readonly resourcesDir;
109
+ private readonly processScopeKey;
87
110
  private readonly callbacks;
88
111
  private readonly terminals;
89
112
  private processHandle;
@@ -91,6 +114,26 @@ export declare class AcpClient {
91
114
  private sdkConnection;
92
115
  private streamHandle;
93
116
  private initResponse;
117
+ /** 在途 prompt 会话集合(忙时不打断温进程的判定依据) */
118
+ private readonly inflightPrompts;
119
+ /** 本次连接周期的应用资源准备结果(无 resources 入口时为 null) */
120
+ private resourcePrep;
121
+ /** 连接代次(connect 推进;兼容记账与重连后重附带的诊断依据) */
122
+ private connectionGen;
123
+ /** 是否自动挂载技能 MCP(resources.attachSkillsMcp,缺省 true) */
124
+ private readonly attachSkillsMcp;
125
+ /**
126
+ * 会话兼容记账:sessionId → { 建会话时的恢复方式/代次/技能暴露 }。
127
+ * 兼容引导按“会话 + 代次 + 资源摘要”键只发一次;取消/失败不重置;
128
+ * 断开即清空(会话随进程消亡)。
129
+ */
130
+ private readonly sessionLedger;
131
+ /** 已发送兼容引导的交付键(见 compatDeliveryKey,有界不累积) */
132
+ private readonly compatSentKeys;
133
+ /** 已发送兼容引导的快照(同一次交付的正文与摘要配对,不混版本) */
134
+ private readonly compatSnapshots;
135
+ /** 当前连接的应用资源加载报告(规则/技能分开记录;无则为 null) */
136
+ get resourceReport(): AppResourceReport | null;
94
137
  constructor(options: AcpClientOptions);
95
138
  get currentStatus(): AcpConnectionStatus;
96
139
  get isConnected(): boolean;
@@ -128,6 +171,14 @@ export declare class AcpClient {
128
171
  data: string;
129
172
  }>;
130
173
  }): Promise<Result<unknown, AppError>>;
174
+ /**
175
+ * 兼容引导前置文本(首轮一次制):
176
+ * - 无 resources / 未知会话 / 原生已交付 → null(原文不动);
177
+ * - 已按“会话+代次+摘要”发送过 → null(取消/失败重试不重复);
178
+ * - 否则单次原子读取(正文与摘要配对快照)构建并记账。
179
+ * 恢复会话因送达状态未知,按新代次重新附带一次(有界、可诊断,不声称 exactly-once)。
180
+ */
181
+ private buildCompatPrepend;
131
182
  /** 动态更新会话配置项(如模型 ID) */
132
183
  setSessionConfigOption(sessionId: string, configId: string, value: string | boolean): Promise<Result<unknown, AppError>>;
133
184
  /** 断开连接并清理资源 */
@@ -9,6 +9,8 @@ export interface RestoreOrCreateSessionInput {
9
9
  loadSupported: boolean;
10
10
  /** 客户端自带的 MCP server(Inkdown 工具);Agent 不支持 HTTP 传输时传空数组 */
11
11
  mcpServers?: unknown[];
12
+ /** Runtime-specific native options; not a standard ACP system prompt field. */
13
+ sessionMeta?: Record<string, unknown>;
12
14
  /** session/load 回放期间回调(主进程用来压制 UI 更新) */
13
15
  onSuppressUpdates?: (suppress: boolean) => void;
14
16
  /** 测试可设为 0 */
@@ -16,6 +18,9 @@ export interface RestoreOrCreateSessionInput {
16
18
  log?: (level: 'info' | 'warn', message: string, data?: Record<string, unknown>) => void;
17
19
  }
18
20
  export interface RestoreOrCreateSessionResult {
21
+ /** Agent accepted the supplied MCP descriptors; not proof of tool execution. */
22
+ mcpServersAccepted: boolean;
23
+ nativeSessionAccepted: boolean;
19
24
  sessionId: string;
20
25
  configOptions: unknown;
21
26
  restoreMethod: AcpSessionRestoreMethod;
@@ -10,6 +10,8 @@
10
10
  export interface AcpQuotaLimitWindow {
11
11
  /** 限制窗口标识或名称,如 '5h limit', 'Weekly limit', 'Monthly limit' */
12
12
  label: string;
13
+ /** 分组标识,如 'Gemini Models', 'Claude and GPT models' */
14
+ group?: string;
13
15
  /** 剩余百分比 (0 - 100) */
14
16
  percentLeft: number;
15
17
  /** 已用百分比 (0 - 100) */