Skip to content

Commit 4df60e0

Browse files
author
hzq
committed
Index current skill exports for bounded reads
Commit the active export index together with the bundle alias. Seek the selected manifest or bytes without reading the bundle payload, and repair existing indexes during startup without a schema-version bump.
1 parent 1488c27 commit 4df60e0

9 files changed

Lines changed: 372 additions & 79 deletions

File tree

‎docs/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,8 @@ Skills remain metadata-only in discovery. To make a bundle skill readable, add `
291291

292292
`GET /v1/catalog/skill?agent=AGENT&skill=NAME` and MCP `oaa_inspect_skill` resolve the current publication and return file paths, sizes, and SHA-256 digests. Use the returned MCP resource links or `GET /v1/catalog/skill/content?agent=AGENT&skill=NAME&agent_version=DIGEST&file=SKILL.md`. Both operations require the agent grant and `read` and `files` scopes (or admin). Content reads require an exact version. Once a different version is published, old resource links return 404; they never load the new version. The bridge does not load or execute skills, and a digest match does not confer trust or permissions. This is an OAA MCP tool and resource contract, not an advertisement of the SEP-2640 Skills extension.
293293

294+
The gateway keeps a SQLite read index of current, explicitly exported files only. The publication and its index change in one transaction. Reads do not open the full bundle; file reads verify the selected bytes against their stored digest. Startup indexes previously published bundles when necessary, without changing the bundle format or database schema version.
295+
294296
Summary discovery seeds a lightweight publication-only notification cursor. It does not scan all runtimes to create that cursor; runtime observation starts when watched or refreshed through full discovery. Publication changes between listing and watching are still detected. The publication `revision`, immutable `agent_version` and ephemeral `catalog_cursor` are separate tokens with separate purposes; none grants access.
295297

296298
### Read-only route inspection

‎docs/zh-CN/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,8 @@ MCP 的 `oaa_list_agents` 使用有界摘要端点;`oaa_inspect_agent` 暴露
301301

302302
`GET /v1/catalog/skill?agent=AGENT&skill=NAME` 和 MCP `oaa_inspect_skill` 可解析当前发布,返回文件路径、大小和 SHA-256 摘要。通过 MCP 返回的资源链接或 `GET /v1/catalog/skill/content?agent=AGENT&skill=NAME&agent_version=DIGEST&file=SKILL.md` 读取。两者均要求智能体授权及 `read`、`files` scope(或 admin)。正文必须指定精确版本。发布不同版本后旧链接返回 404,不会返回新版内容。桥接不会加载或执行技能,摘要匹配也不等于信任或授权。这是 OAA 的 MCP 工具与资源接口,不声明支持 SEP-2640 Skills 扩展。
303303

304+
网关在 SQLite 中只为当前发布且明确导出的文件建立读取索引。发布与索引在同一事务中更新;读取不加载完整能力包,并校验目标文件的摘要。启动时按需为已发布的能力包补建索引,不改变能力包格式或数据库 schema 版本。
305+
304306
摘要式发现会播下一个只含发布信息的轻量通知游标。它不会为了创建这个游标而扫描所有运行时;运行时观察要等到被监视或经完整发现刷新时才开始。列出与监视之间发生的发布变化仍然会被发现。发布 `revision`、不可变的 `agent_version` 与临时的 `catalog_cursor` 是三种分开的令牌,各有各的用途;都不授予访问权限。
305307

306308
<a id="read-only-route-inspection"></a>

‎src/core/skill-files.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,15 @@ export const skillDeclarationSchema = (name: z.ZodString) =>
2727
.optional(),
2828
})
2929
.strict();
30+
31+
export function skillExportPaths(skill: {
32+
path: string;
33+
exportFiles?: readonly string[] | undefined;
34+
}): Map<string, string> {
35+
const files = new Map<string, string>();
36+
if (skill.exportFiles === undefined) return files;
37+
const prefix = skill.path.slice(0, skill.path.lastIndexOf('/') + 1);
38+
files.set(SKILL_ENTRY_FILE, skill.path);
39+
for (const file of skill.exportFiles) files.set(file, `${prefix}${file}`);
40+
return files;
41+
}

‎src/gateway/skill-routes.ts‎

Lines changed: 8 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,16 @@
11
import type { FastifyInstance } from 'fastify';
22
import type { z } from 'zod';
3-
import { exportedSkillPath, MAX_SKILL_EXPORT_FILE_BYTES } from '../core/skill-files.js';
3+
import { exportedSkillPath } from '../core/skill-files.js';
44
import type { Principal } from '../core/contracts.js';
5-
import { Fault, noAgent, sha } from '../core/util.js';
6-
import { skillExportPaths } from '../lang/skill-exports.js';
75
import { authorize } from '../kernel/submission.js';
86
import type { Store } from '../store/store.js';
7+
import { readSkillFile, readSkillManifest } from '../store/skill-exports.js';
98
import type { Auth } from './auth.js';
109
import { definitionQuery, skillExportQuery } from './discovery.js';
1110

1211
type SkillExportQuery = z.infer<typeof skillExportQuery>;
1312

14-
export type SkillExportManifest = {
15-
agent: string;
16-
agent_version: string;
17-
skill: string;
18-
files: { path: string; bytes: number; sha256: string }[];
19-
};
13+
export type SkillExportManifest = ReturnType<typeof readSkillManifest>;
2014

2115
const skillContentQuery = skillExportQuery
2216
.extend({
@@ -25,54 +19,23 @@ const skillContentQuery = skillExportQuery
2519
})
2620
.strict();
2721

28-
const missingExport = () =>
29-
new Fault('skill_export_not_found', 'The skill file is not exported by this publication.', 404);
30-
3122
export function registerSkillRoutes(app: FastifyInstance, auth: Auth, store: Store): void {
32-
function resolve(p: Principal, query: SkillExportQuery) {
23+
function requireRead(p: Principal, query: SkillExportQuery) {
3324
authorize(p, query.agent, 'read');
3425
auth.require(p, 'files');
35-
const owner = p.owner;
36-
// The current publication is the grant. Historical bundle rows cannot extend it.
37-
const [current] = store.agentIndex(owner, [query.agent]);
38-
if (!current || (query.agent_version !== undefined && current.digest !== query.agent_version))
39-
throw noAgent();
40-
const bundle = store.bundle(owner, query.agent, current.digest);
41-
const skill = bundle.agent.skills.find(
42-
(s) => s.name === query.skill && s.exportFiles !== undefined,
43-
);
44-
if (!skill) throw missingExport();
45-
return { bundle, paths: skillExportPaths(skill) };
4626
}
4727

4828
app.get('/v1/catalog/skill', async (req, reply) => {
4929
const query = skillExportQuery.parse(req.query);
50-
const { bundle, paths } = resolve(req.principal, query);
51-
const index = new Map(bundle.files.map((file) => [file.path, file]));
52-
const result: SkillExportManifest = {
53-
agent: bundle.agent.id,
54-
agent_version: bundle.digest,
55-
skill: query.skill,
56-
files: [...paths].map(([path, bundlePath]) => {
57-
const file = index.get(bundlePath);
58-
if (!file) throw missingExport();
59-
return { path, bytes: Buffer.byteLength(file.content, 'base64'), sha256: file.sha256 };
60-
}),
61-
};
30+
requireRead(req.principal, query);
31+
const result = readSkillManifest(store, { ...query, owner: req.principal.owner });
6232
return reply.header('Cache-Control', 'private, no-store').send(result);
6333
});
6434

6535
app.get('/v1/catalog/skill/content', async (req, reply) => {
6636
const query = skillContentQuery.parse(req.query);
67-
const { bundle, paths } = resolve(req.principal, query);
68-
const path = paths.get(query.file);
69-
const file = path && bundle.files.find((file) => file.path === path);
70-
if (!file) throw missingExport();
71-
if (Buffer.byteLength(file.content, 'base64') > MAX_SKILL_EXPORT_FILE_BYTES)
72-
throw new Error('Stored skill export exceeds its size limit.');
73-
const bytes = Buffer.from(file.content, 'base64');
74-
if (sha(bytes) !== file.sha256)
75-
throw new Error('Stored skill export failed its integrity check.');
37+
requireRead(req.principal, query);
38+
const bytes = readSkillFile(store, { ...query, owner: req.principal.owner });
7639
return reply
7740
.header('Cache-Control', 'private, no-store')
7841
.header('Content-Disposition', 'attachment')

‎src/lang/skill-exports.ts‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,13 @@
11
import { parse as parseYaml } from 'yaml';
2-
import type { AgentBundle, AgentDefinition } from '../core/contracts.js';
2+
import type { AgentBundle } from '../core/contracts.js';
33
import {
44
exportedSkillName,
55
MAX_SKILL_EXPORT_FILE_BYTES,
66
SKILL_ENTRY_FILE,
7+
skillExportPaths,
78
} from '../core/skill-files.js';
89
import { Fault } from '../core/util.js';
910

10-
type SkillDeclaration = AgentDefinition['skills'][number];
11-
12-
export function skillExportPaths(skill: SkillDeclaration): Map<string, string> {
13-
const files = new Map<string, string>();
14-
if (skill.exportFiles === undefined) return files;
15-
const prefix = skill.path.slice(0, skill.path.lastIndexOf('/') + 1);
16-
files.set(SKILL_ENTRY_FILE, skill.path);
17-
for (const file of skill.exportFiles) files.set(file, `${prefix}${file}`);
18-
return files;
19-
}
20-
2111
export function validateSkillExports(
2212
bundle: AgentBundle,
2313
checkMetadata: (value: unknown) => void,

‎src/store/bundle-publication.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import type { DatabaseSync, StatementSync } from 'node:sqlite';
2+
import type { AgentBundle } from '../core/contracts.js';
3+
import { Fault } from '../core/util.js';
4+
import { replaceSkillExports } from './skill-exports.js';
5+
6+
export function commitBundlePublication(
7+
store: { db: DatabaseSync; prepare(sql: string): StatementSync },
8+
owner: string,
9+
bundle: AgentBundle,
10+
serialized: string,
11+
persistMetadata?: () => void,
12+
): void {
13+
const { db } = store;
14+
db.exec('BEGIN IMMEDIATE');
15+
try {
16+
const existing = store.prepare('SELECT owner FROM bundles WHERE digest=?').get(bundle.digest);
17+
if (existing && existing.owner !== owner)
18+
throw new Fault('bundle_owner_conflict', 'The bundle digest belongs to another owner.', 409);
19+
store
20+
.prepare('INSERT OR IGNORE INTO bundles VALUES(?,?,?,?,?)')
21+
.run(bundle.digest, owner, bundle.agent.id, serialized, Date.now());
22+
const changed = store
23+
.prepare(
24+
`
25+
INSERT INTO agents VALUES(?,?,?)
26+
ON CONFLICT(owner,id) DO UPDATE SET digest=excluded.digest WHERE digest<>excluded.digest`,
27+
)
28+
.run(owner, bundle.agent.id, bundle.digest);
29+
if (changed.changes) replaceSkillExports(store, owner, bundle);
30+
persistMetadata?.();
31+
db.exec('COMMIT');
32+
} catch (error) {
33+
if (db.isTransaction) db.exec('ROLLBACK');
34+
throw error;
35+
}
36+
}

‎src/store/skill-exports.ts‎

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import type { DatabaseSync, StatementSync } from 'node:sqlite';
2+
import { bundleSchema, type AgentBundle } from '../core/contracts.js';
3+
import { MAX_SKILL_EXPORT_FILE_BYTES, skillExportPaths } from '../core/skill-files.js';
4+
import { Fault, canonical, noAgent, sha } from '../core/util.js';
5+
6+
type Statements = { prepare(sql: string): StatementSync };
7+
8+
/** Rebuild only changed aliases, including publications made by older gateways after rollback. */
9+
export function installSkillExports(db: DatabaseSync): void {
10+
db.exec(`
11+
CREATE TABLE IF NOT EXISTS agent_skill_index(
12+
owner TEXT NOT NULL, agent_id TEXT NOT NULL, digest TEXT NOT NULL,
13+
PRIMARY KEY(owner,agent_id),
14+
FOREIGN KEY(owner,agent_id) REFERENCES agents(owner,id) ON DELETE CASCADE
15+
);
16+
CREATE TABLE IF NOT EXISTS agent_skill_bytes(
17+
owner TEXT NOT NULL, agent_id TEXT NOT NULL, digest TEXT NOT NULL, sha256 TEXT NOT NULL,
18+
content BLOB NOT NULL CHECK(length(content)<=${MAX_SKILL_EXPORT_FILE_BYTES}),
19+
PRIMARY KEY(owner,agent_id,digest,sha256),
20+
FOREIGN KEY(owner,agent_id) REFERENCES agents(owner,id) ON DELETE CASCADE
21+
);
22+
CREATE TABLE IF NOT EXISTS agent_skill_files(
23+
owner TEXT NOT NULL, agent_id TEXT NOT NULL, digest TEXT NOT NULL, skill TEXT NOT NULL, path TEXT NOT NULL,
24+
ordinal INTEGER NOT NULL, bytes INTEGER NOT NULL, sha256 TEXT NOT NULL,
25+
PRIMARY KEY(owner,agent_id,skill,path),
26+
FOREIGN KEY(owner,agent_id,digest,sha256) REFERENCES agent_skill_bytes(owner,agent_id,digest,sha256) ON DELETE CASCADE
27+
);`);
28+
const changed = db
29+
.prepare(
30+
`
31+
SELECT a.owner,a.id,a.digest FROM agents a
32+
LEFT JOIN agent_skill_index i ON i.owner=a.owner AND i.agent_id=a.id AND i.digest=a.digest
33+
WHERE i.digest IS NULL`,
34+
)
35+
.all();
36+
if (!changed.length) return;
37+
const payload = db.prepare(`
38+
SELECT payload FROM bundles WHERE owner=? AND agent_id=? AND digest=?
39+
AND CASE WHEN json_valid(payload) THEN EXISTS(
40+
SELECT 1 FROM json_each(payload,'$.agent.skills') s
41+
WHERE CASE WHEN s.type='object' THEN json_type(s.value,'$.exportFiles')='array' ELSE 0 END
42+
) ELSE 0 END`);
43+
for (const row of changed) {
44+
const owner = String(row.owner),
45+
id = String(row.id),
46+
digest = String(row.digest);
47+
const source = payload.get(owner, id, digest);
48+
const bundle = source && bundleSchema.parse(JSON.parse(String(source.payload)));
49+
if (bundle) {
50+
const { digest: storedDigest, ...data } = bundle;
51+
if (storedDigest !== digest || data.agent.id !== id || sha(canonical(data)) !== digest)
52+
throw new Fault(
53+
'bundle_integrity',
54+
'Skill export backfill did not match the published bundle.',
55+
);
56+
}
57+
writeProjection(db, owner, id, digest, bundle);
58+
}
59+
}
60+
61+
/** The alias and its read projection must commit or roll back together. */
62+
export function replaceSkillExports(store: Statements, owner: string, bundle: AgentBundle): void {
63+
writeProjection(store, owner, bundle.agent.id, bundle.digest, bundle);
64+
}
65+
66+
function writeProjection(
67+
store: Statements,
68+
owner: string,
69+
agentId: string,
70+
digest: string,
71+
bundle?: AgentBundle,
72+
): void {
73+
store.prepare('DELETE FROM agent_skill_files WHERE owner=? AND agent_id=?').run(owner, agentId);
74+
store.prepare('DELETE FROM agent_skill_bytes WHERE owner=? AND agent_id=?').run(owner, agentId);
75+
store
76+
.prepare(
77+
`
78+
INSERT INTO agent_skill_index VALUES(?,?,?) ON CONFLICT(owner,agent_id) DO UPDATE SET digest=excluded.digest`,
79+
)
80+
.run(owner, agentId, digest);
81+
if (!bundle?.agent.skills.some((skill) => skill.exportFiles !== undefined)) return;
82+
const insertBytes = store.prepare('INSERT INTO agent_skill_bytes VALUES(?,?,?,?,?)');
83+
const insertFile = store.prepare('INSERT INTO agent_skill_files VALUES(?,?,?,?,?,?,?,?)');
84+
const files = new Map(bundle.files.map((file) => [file.path, file]));
85+
const saved = new Set<string>();
86+
for (const skill of bundle.agent.skills) {
87+
let ordinal = 0;
88+
for (const [path, bundlePath] of skillExportPaths(skill)) {
89+
const file = files.get(bundlePath);
90+
if (!file) throw new Fault('missing_skill', 'A declared skill export file is missing.');
91+
if (!saved.has(file.sha256)) {
92+
insertBytes.run(owner, agentId, digest, file.sha256, Buffer.from(file.content, 'base64'));
93+
saved.add(file.sha256);
94+
}
95+
insertFile.run(
96+
owner,
97+
agentId,
98+
digest,
99+
skill.name,
100+
path,
101+
ordinal++,
102+
Buffer.byteLength(file.content, 'base64'),
103+
file.sha256,
104+
);
105+
}
106+
}
107+
}
108+
109+
type SkillRead = { owner: string; agent: string; skill: string; agent_version?: string };
110+
const filesForAlias = `
111+
FROM agents a LEFT JOIN agent_skill_files s
112+
ON s.owner=a.owner AND s.agent_id=a.id AND s.digest=a.digest AND s.skill=?`;
113+
const activeAlias = 'WHERE a.owner=? AND a.id=? AND a.digest=coalesce(?,a.digest)';
114+
const missingExport = () =>
115+
new Fault('skill_export_not_found', 'The skill file is not exported by this publication.', 404);
116+
117+
export function readSkillManifest(store: Statements, query: SkillRead) {
118+
const rows = store
119+
.prepare(
120+
`
121+
SELECT a.digest,s.path,s.bytes,s.sha256
122+
${filesForAlias} ${activeAlias} ORDER BY s.ordinal`,
123+
)
124+
.all(query.skill, query.owner, query.agent, query.agent_version ?? null);
125+
if (!rows.length) throw noAgent();
126+
if (rows[0]!.path === null) throw missingExport();
127+
return {
128+
agent: query.agent,
129+
agent_version: String(rows[0]!.digest),
130+
skill: query.skill,
131+
files: rows.map((row) => ({
132+
path: String(row.path),
133+
bytes: Number(row.bytes),
134+
sha256: String(row.sha256),
135+
})),
136+
};
137+
}
138+
139+
export function readSkillFile(
140+
store: Statements,
141+
query: SkillRead & { agent_version: string; file: string },
142+
): Buffer {
143+
const row = store
144+
.prepare(
145+
`
146+
SELECT s.path,s.bytes,s.sha256,b.content
147+
${filesForAlias} AND s.path=?
148+
LEFT JOIN agent_skill_bytes b
149+
ON b.owner=s.owner AND b.agent_id=s.agent_id AND b.digest=s.digest AND b.sha256=s.sha256
150+
${activeAlias}`,
151+
)
152+
.get(query.skill, query.file, query.owner, query.agent, query.agent_version);
153+
if (!row) throw noAgent();
154+
if (row.path === null) throw missingExport();
155+
const content = row.content;
156+
if (
157+
!(content instanceof Uint8Array) ||
158+
content.byteLength > MAX_SKILL_EXPORT_FILE_BYTES ||
159+
content.byteLength !== row.bytes
160+
)
161+
throw new Error('Stored skill export failed its integrity check.');
162+
const bytes = Buffer.from(content.buffer, content.byteOffset, content.byteLength);
163+
if (sha(bytes) !== row.sha256) throw new Error('Stored skill export failed its integrity check.');
164+
return bytes;
165+
}

‎src/store/store.ts‎

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,8 @@ import { ProvisionalInputs } from './provisional-inputs.js';
9595
import { writeFileRecord } from './file-write.js';
9696
import { installUploadBudget, type UploadPolicy } from './upload-budget.js';
9797
import { installInputJournal } from './input-journal.js';
98+
import { installSkillExports } from './skill-exports.js';
99+
import { commitBundlePublication } from './bundle-publication.js';
98100
import {
99101
commitNewRun,
100102
idemKey,
@@ -259,6 +261,7 @@ export class Store {
259261
}
260262
}
261263
installRunOutcomes(this.db);
264+
installSkillExports(this.db);
262265
if (version < SCHEMA_VERSION) this.db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
263266
this.db.exec('COMMIT');
264267
this.lease.acquired();
@@ -388,29 +391,8 @@ export class Store {
388391
}
389392
}
390393
publish(owner: string, bundle: AgentBundle, persistMetadata?: () => void): void {
391-
const existing = this.prepare('SELECT owner FROM bundles WHERE digest=?').get(bundle.digest) as
392-
Row | undefined;
393-
if (existing && existing.owner !== owner)
394-
throw new Fault('bundle_owner_conflict', 'The bundle digest belongs to another owner.', 409);
395394
const serialized = JSON.stringify(bundle);
396-
this.db.exec('BEGIN IMMEDIATE');
397-
try {
398-
this.prepare('INSERT OR IGNORE INTO bundles VALUES(?,?,?,?,?)').run(
399-
bundle.digest,
400-
owner,
401-
bundle.agent.id,
402-
serialized,
403-
Date.now(),
404-
);
405-
this.prepare(
406-
'INSERT INTO agents VALUES(?,?,?) ON CONFLICT(owner,id) DO UPDATE SET digest=excluded.digest',
407-
).run(owner, bundle.agent.id, bundle.digest);
408-
persistMetadata?.();
409-
this.db.exec('COMMIT');
410-
} catch (e) {
411-
if (this.db.isTransaction) this.db.exec('ROLLBACK');
412-
throw e;
413-
}
395+
commitBundlePublication(this, owner, bundle, serialized, persistMetadata);
414396
this.aliasDigestCache.set(`${owner}:${bundle.agent.id}`, bundle.digest);
415397
if (serialized.length <= 262_144) this.rememberBundle(owner, bundle);
416398
this.notices.single('catalog', { agent: bundle.agent.id, digest: bundle.digest, owner });

0 commit comments

Comments
 (0)