@capyclaw/ppt-suite 2.5.70 → 2.5.71
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/composition.lock.json +27 -27
- package/contract/ppt-contract.json +1 -1
- package/dsh-suite.json +27 -17
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/asset-service/package.json +1 -1
- package/node_modules/@capyclaw/asset-service/src/index.mjs +4 -3
- package/node_modules/@capyclaw/document-workbench/package.json +6 -3
- package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +56 -3
- package/node_modules/@capyclaw/document-workbench/src/client/visibility.mjs +112 -0
- package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +6 -4
- package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +7 -2
- package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +8 -0
- package/node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs +17 -10
- package/node_modules/@capyclaw/document-workbench/src/store/projection.mjs +39 -0
- package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +14 -11
- package/node_modules/@capyclaw/editor-host/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/editor-host/package.json +1 -1
- package/node_modules/@capyclaw/editor-host/src/index.mjs +12 -21
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
- package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
- package/node_modules/@capyclaw/foundation/package.json +1 -1
- package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
- package/node_modules/@capyclaw/portal/package.json +1 -1
- package/node_modules/@capyclaw/ppt-editor/app.js +458 -10
- package/node_modules/@capyclaw/ppt-editor/contract/ppt-contract.json +1 -1
- package/node_modules/@capyclaw/ppt-editor/heartbeat-worker.js +5 -2
- package/node_modules/@capyclaw/ppt-editor/index.html +4 -0
- package/node_modules/@capyclaw/ppt-editor/package.json +2 -2
- package/node_modules/@capyclaw/ppt-skill-api/contract/ppt-contract.json +1 -1
- package/node_modules/@capyclaw/ppt-skill-api/package.json +1 -1
- package/node_modules/@capyclaw/ppt-skill-api/skills/pptist-api/references/tool-contract.md +1 -1
- package/node_modules/@capyclaw/ppt-skill-proposal/contract/ppt-contract.json +1 -1
- package/node_modules/@capyclaw/ppt-skill-proposal/package.json +1 -1
- package/node_modules/@capyclaw/ppt-workbench/contract/ppt-contract.json +1 -1
- package/node_modules/@capyclaw/ppt-workbench/core/deck-layout.js +3 -1
- package/node_modules/@capyclaw/ppt-workbench/core/ops/slide.js +9 -3
- package/node_modules/@capyclaw/ppt-workbench/core/text.js +14 -2
- package/node_modules/@capyclaw/ppt-workbench/package.json +10 -8
- package/node_modules/@capyclaw/ppt-workbench/plugin.mjs +13 -1
- package/node_modules/@capyclaw/ppt-workbench/server/contract.mjs +1 -1
- package/node_modules/@capyclaw/ppt-workbench/server/embedded-host.mjs +200 -29
- package/node_modules/@capyclaw/ppt-workbench/server/relay.mjs +10 -7
- package/node_modules/@capyclaw/ppt-workbench/server/shared/SHARED_MANIFEST.json +4 -4
- package/node_modules/@capyclaw/ppt-workbench/server/store/backends/file-backend.mjs +3 -0
- package/node_modules/@capyclaw/ppt-workbench/server/store/checkpoints.mjs +4 -1
- package/node_modules/@capyclaw/ppt-workbench/server/store/index.mjs +4 -0
- package/node_modules/@capyclaw/ppt-workbench/server/store/sessions.mjs +139 -4
- package/node_modules/@capyclaw/ppt-workbench/server/store/shape.mjs +37 -0
- package/node_modules/@capyclaw/service-broker/README.md +1 -1
- package/node_modules/@capyclaw/service-broker/lib/host.mjs +11 -6
- package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +13 -5
- package/node_modules/@capyclaw/service-broker/package.json +1 -1
- package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/service-host/package.json +1 -1
- package/node_modules/@capyclaw/service-host/src/index.mjs +13 -22
- package/node_modules/@capyclaw/skills-service/README.md +42 -10
- package/node_modules/@capyclaw/skills-service/package.json +6 -3
- package/node_modules/@capyclaw/skills-service/server.mjs +129 -51
- package/node_modules/@capyclaw/suite-kit/README.md +289 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
- package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
- package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
- package/node_modules/@capyclaw/suite-kit/package.json +58 -0
- package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
- package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
- package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
- package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
- package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
- package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
- package/node_modules/@capyclaw/suite-kit/src/host.mjs +230 -0
- package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
- package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
- package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
- package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
- package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
- package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +15 -4
- package/node_modules/@capyclaw/tool-host/package.json +1 -1
- package/node_modules/@capyclaw/tool-host/src/index.mjs +19 -5
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +71 -3
- package/node_modules/@capyclaw/work-store/README.md +83 -0
- package/node_modules/@capyclaw/work-store/STANDARD.md +263 -0
- package/node_modules/@capyclaw/work-store/cordis.patch.yml +3 -0
- package/node_modules/@capyclaw/work-store/dsh-suite.json +33 -0
- package/node_modules/@capyclaw/work-store/icon.svg +7 -0
- package/node_modules/@capyclaw/work-store/lib/host.mjs +21 -0
- package/node_modules/@capyclaw/work-store/package.json +68 -0
- package/node_modules/@capyclaw/work-store/src/backend.mjs +90 -0
- package/node_modules/@capyclaw/work-store/src/db.mjs +199 -0
- package/node_modules/@capyclaw/work-store/src/envelope.mjs +132 -0
- package/node_modules/@capyclaw/work-store/src/index.mjs +571 -0
- package/node_modules/@capyclaw/work-store/src/interop.mjs +70 -0
- package/node_modules/@capyclaw/work-store/src/refs.mjs +99 -0
- package/node_modules/@capyclaw/work-store/src/routes.mjs +135 -0
- package/package.json +16 -14
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/work-store —— 通用作品持久化底座。
|
|
3
|
+
*
|
|
4
|
+
* 提供 ctx.workStore:作品目录(分类清晰)+ 当前状态 + 不可变版本 + journal +
|
|
5
|
+
* checkpoint + 前端查询面。结构化正文进 SQLite;非结构化字节委托内容寻址 blob 仓
|
|
6
|
+
* (ctx.assets),正文只存 @asset/<sha> 引用(见 refs.mjs)。
|
|
7
|
+
*
|
|
8
|
+
* 标准见 STANDARD.md(v2 增量:tx 单事务 / purgeWork 硬删 / work_meta KV /
|
|
9
|
+
* findJournal 台账查询 / 通用 checkpoint 清单 / schema 迁移执行器)。
|
|
10
|
+
* 第一个适配者是 PPT(backendFor 返回 FileStateBackend 同接口)。
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto'
|
|
13
|
+
import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
|
|
14
|
+
import { openWorkDb } from './db.mjs'
|
|
15
|
+
import { createSqliteBackend } from './backend.mjs'
|
|
16
|
+
import { createWorkRoutes } from './routes.mjs'
|
|
17
|
+
import { collectRefs, resolveRefs } from './refs.mjs'
|
|
18
|
+
import {
|
|
19
|
+
makeArtifactId, normalizeEnvelopeInput, shapeArtifact, assetIdOf,
|
|
20
|
+
} from './envelope.mjs'
|
|
21
|
+
|
|
22
|
+
export const WORK_STORE_API = createServiceApi('workStore', '1.2.0', [
|
|
23
|
+
'workStore.store', 'workStore.catalog', 'workStore.versions', 'workStore.query',
|
|
24
|
+
'workStore.artifacts',
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
const CHECKPOINT_NAME = /^[a-zA-Z0-9._-]{1,64}$/
|
|
28
|
+
const sha256Of = (text) => createHash('sha256').update(text, 'utf8').digest('hex')
|
|
29
|
+
const now = () => Date.now()
|
|
30
|
+
|
|
31
|
+
function parseJson(text, fallback) {
|
|
32
|
+
try { return JSON.parse(text) } catch { return fallback }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 把一行 works 记录整理成对外形状(tags/meta 解析成对象)。 */
|
|
36
|
+
function shapeWork(row) {
|
|
37
|
+
if (!row) return null
|
|
38
|
+
return {
|
|
39
|
+
id: row.id,
|
|
40
|
+
suite: row.suite,
|
|
41
|
+
kind: row.kind,
|
|
42
|
+
sessionId: row.session_id || '',
|
|
43
|
+
title: row.title || '',
|
|
44
|
+
brief: row.brief || '',
|
|
45
|
+
tags: parseJson(row.tags, []),
|
|
46
|
+
status: row.status,
|
|
47
|
+
coverAsset: row.cover_asset || '',
|
|
48
|
+
currentVersion: row.current_version,
|
|
49
|
+
meta: parseJson(row.meta, {}),
|
|
50
|
+
createdAt: row.created_at,
|
|
51
|
+
updatedAt: row.updated_at,
|
|
52
|
+
deletedAt: row.deleted_at ?? null,
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 创建作品库服务。
|
|
58
|
+
* @param {{ dir?: string, file?: string, env?: object, db?: object }} config
|
|
59
|
+
*/
|
|
60
|
+
export function createWorkStore(config = {}) {
|
|
61
|
+
const handle = config.db ? { db: config.db, dir: config.dir || '', file: config.file || '', close() {} } : openWorkDb(config)
|
|
62
|
+
const { db } = handle
|
|
63
|
+
|
|
64
|
+
const stmt = {
|
|
65
|
+
insertWork: db.prepare(`INSERT INTO works(id, suite, kind, session_id, title, brief, tags, status, cover_asset, current_version, meta, created_at, updated_at)
|
|
66
|
+
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),
|
|
67
|
+
getWork: db.prepare('SELECT * FROM works WHERE id = ?'),
|
|
68
|
+
updateWork: db.prepare(`UPDATE works SET title=?, brief=?, tags=?, status=?, cover_asset=?, meta=?, updated_at=? WHERE id=?`),
|
|
69
|
+
touchWork: db.prepare('UPDATE works SET title=?, updated_at=? WHERE id=?'),
|
|
70
|
+
setVersionPointer: db.prepare('UPDATE works SET current_version=?, updated_at=? WHERE id=?'),
|
|
71
|
+
softDelete: db.prepare('UPDATE works SET deleted_at=?, updated_at=? WHERE id=?'),
|
|
72
|
+
upsertState: db.prepare(`INSERT INTO work_state(work_id, payload, seq, updated_at) VALUES(?, ?, ?, ?)
|
|
73
|
+
ON CONFLICT(work_id) DO UPDATE SET payload=excluded.payload, seq=excluded.seq, updated_at=excluded.updated_at`),
|
|
74
|
+
getState: db.prepare('SELECT * FROM work_state WHERE work_id = ?'),
|
|
75
|
+
maxVersion: db.prepare('SELECT COALESCE(MAX(version), 0) AS v FROM work_versions WHERE work_id = ?'),
|
|
76
|
+
insertVersion: db.prepare('INSERT INTO work_versions(work_id, version, payload, payload_sha256, note, created_at) VALUES(?, ?, ?, ?, ?, ?)'),
|
|
77
|
+
getVersion: db.prepare('SELECT * FROM work_versions WHERE work_id = ? AND version = ?'),
|
|
78
|
+
listVersions: db.prepare('SELECT version, payload_sha256, note, created_at FROM work_versions WHERE work_id = ? ORDER BY version DESC'),
|
|
79
|
+
insertJournal: db.prepare('INSERT INTO work_journal(work_id, seq, type, data, ts) VALUES(?, ?, ?, ?, ?)'),
|
|
80
|
+
journalTail: db.prepare('SELECT * FROM work_journal WHERE work_id = ? ORDER BY id DESC LIMIT ?'),
|
|
81
|
+
upsertCheckpoint: db.prepare(`INSERT INTO work_checkpoints(work_id, name, payload, created_at) VALUES(?, ?, ?, ?)
|
|
82
|
+
ON CONFLICT(work_id, name) DO UPDATE SET payload=excluded.payload, created_at=excluded.created_at`),
|
|
83
|
+
getCheckpoint: db.prepare('SELECT * FROM work_checkpoints WHERE work_id = ? AND name = ?'),
|
|
84
|
+
listCheckpoints: db.prepare('SELECT * FROM work_checkpoints WHERE work_id = ? ORDER BY created_at DESC'),
|
|
85
|
+
deleteAssets: db.prepare('DELETE FROM work_assets WHERE work_id = ?'),
|
|
86
|
+
insertAsset: db.prepare('INSERT INTO work_assets(work_id, asset_id, role) VALUES(?, ?, ?) ON CONFLICT DO NOTHING'),
|
|
87
|
+
listAssets: db.prepare('SELECT asset_id, role FROM work_assets WHERE work_id = ?'),
|
|
88
|
+
insertArtifact: db.prepare(`INSERT INTO artifacts(id, work_id, session_id, type, mime, asset_ref, title, producer, producer_suite, version, lineage, meta, created_at, updated_at)
|
|
89
|
+
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),
|
|
90
|
+
getArtifact: db.prepare('SELECT * FROM artifacts WHERE id = ?'),
|
|
91
|
+
softDeleteArtifact: db.prepare('UPDATE artifacts SET deleted_at=?, updated_at=? WHERE id=?'),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/* ---- 事务(STANDARD v2 V2-2) ---- */
|
|
95
|
+
|
|
96
|
+
let txDepth = 0
|
|
97
|
+
/**
|
|
98
|
+
* 单事务执行组合写(目录+状态+版本必须原子)。不支持嵌套:
|
|
99
|
+
* 事务内直接调用存储方法即可,它们会自动加入当前事务。
|
|
100
|
+
*/
|
|
101
|
+
function tx(fn) {
|
|
102
|
+
if (txDepth > 0) throw new Error('tx 不支持嵌套:请在外层事务内直接调用存储方法')
|
|
103
|
+
if (typeof fn !== 'function') throw new Error('tx 需要一个函数')
|
|
104
|
+
db.exec('BEGIN IMMEDIATE')
|
|
105
|
+
txDepth = 1
|
|
106
|
+
try {
|
|
107
|
+
const result = fn(api)
|
|
108
|
+
db.exec('COMMIT')
|
|
109
|
+
return result
|
|
110
|
+
} catch (error) {
|
|
111
|
+
try { db.exec('ROLLBACK') } catch { /* 已回滚 */ }
|
|
112
|
+
throw error
|
|
113
|
+
} finally {
|
|
114
|
+
txDepth = 0
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 内部原子化:已在事务内则直接执行,否则自成单事务(saveVersion/rollback/purge 用)。 */
|
|
119
|
+
function atomic(fn) {
|
|
120
|
+
return txDepth > 0 ? fn() : tx(fn)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 自然键:同一 suite+kind+session 幂等映射到同一个作品。 */
|
|
124
|
+
function naturalId({ suite, kind, sessionId }) {
|
|
125
|
+
return `${suite}:${kind}:${sessionId || '_'}`
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function ensureWork(input = {}) {
|
|
129
|
+
const suite = String(input.suite || '').trim()
|
|
130
|
+
const kind = String(input.kind || '').trim()
|
|
131
|
+
if (!suite || !kind) throw new Error('ensureWork 需要 suite 与 kind')
|
|
132
|
+
const sessionId = String(input.sessionId || '')
|
|
133
|
+
const id = String(input.id || naturalId({ suite, kind, sessionId }))
|
|
134
|
+
const existing = stmt.getWork.get(id)
|
|
135
|
+
if (existing) return shapeWork(existing)
|
|
136
|
+
const ts = now()
|
|
137
|
+
const tags = JSON.stringify(Array.isArray(input.tags) ? input.tags : [])
|
|
138
|
+
const meta = JSON.stringify(input.meta && typeof input.meta === 'object' ? input.meta : {})
|
|
139
|
+
stmt.insertWork.run(id, suite, kind, sessionId, String(input.title || ''), String(input.brief || ''),
|
|
140
|
+
tags, Number.isInteger(input.status) ? input.status : 1, String(input.coverAsset || ''), 0, meta, ts, ts)
|
|
141
|
+
return shapeWork(stmt.getWork.get(id))
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function getWork(id) {
|
|
145
|
+
return shapeWork(stmt.getWork.get(String(id)))
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function requireWork(id) {
|
|
149
|
+
const row = stmt.getWork.get(String(id))
|
|
150
|
+
if (!row) throw new Error(`作品不存在: ${id}`)
|
|
151
|
+
return row
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 原地更新当前活状态(= 文件后端 writeState)。同时刷新目录的 title/updated_at。 */
|
|
155
|
+
function writeState(id, doc) {
|
|
156
|
+
requireWork(id)
|
|
157
|
+
const payload = JSON.stringify(doc ?? {})
|
|
158
|
+
const seq = Number(doc?.seq) | 0
|
|
159
|
+
const ts = now()
|
|
160
|
+
stmt.upsertState.run(String(id), payload, seq, ts)
|
|
161
|
+
stmt.touchWork.run(String(doc?.title || ''), ts, String(id))
|
|
162
|
+
indexRefs(id, doc)
|
|
163
|
+
return { seq, updatedAt: ts }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function readState(id) {
|
|
167
|
+
const row = stmt.getState.get(String(id))
|
|
168
|
+
if (!row) return null
|
|
169
|
+
return parseJson(row.payload, null)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 把正文里引用的 blob 记进 work_assets(供 GC 与前端)。 */
|
|
173
|
+
function indexRefs(id, doc) {
|
|
174
|
+
try {
|
|
175
|
+
const refs = collectRefs(doc)
|
|
176
|
+
stmt.deleteAssets.run(String(id))
|
|
177
|
+
for (const ref of refs) stmt.insertAsset.run(String(id), ref, '')
|
|
178
|
+
} catch { /* 索引失败不阻塞主状态 */ }
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 取当前文档(documentKey 下的领域产物,缺省整份状态)。 */
|
|
182
|
+
function getDocument(id, documentKey) {
|
|
183
|
+
const state = readState(id)
|
|
184
|
+
if (state == null) return null
|
|
185
|
+
return documentKey ? (state[documentKey] ?? null) : state
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 存一个不可变版本快照,并把 current_version 指过去(单事务,V2-2)。 */
|
|
189
|
+
function saveVersion(id, payload, options = {}) {
|
|
190
|
+
return atomic(() => {
|
|
191
|
+
requireWork(id)
|
|
192
|
+
const version = stmt.maxVersion.get(String(id)).v + 1
|
|
193
|
+
const text = payload == null ? null : JSON.stringify(payload)
|
|
194
|
+
const sha = text == null ? '' : sha256Of(text)
|
|
195
|
+
const ts = now()
|
|
196
|
+
stmt.insertVersion.run(String(id), version, text, sha, String(options.note || ''), ts)
|
|
197
|
+
stmt.setVersionPointer.run(version, ts, String(id))
|
|
198
|
+
if (payload != null) indexRefs(id, payload)
|
|
199
|
+
return { version, sha256: sha, createdAt: ts }
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function listVersions(id) {
|
|
204
|
+
return stmt.listVersions.all(String(id)).map((r) => ({
|
|
205
|
+
version: r.version, sha256: r.payload_sha256, note: r.note, createdAt: r.created_at,
|
|
206
|
+
}))
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function getVersion(id, version) {
|
|
210
|
+
const row = stmt.getVersion.get(String(id), Number(version))
|
|
211
|
+
if (!row) return null
|
|
212
|
+
return { version: row.version, payload: parseJson(row.payload, null), sha256: row.payload_sha256, note: row.note, createdAt: row.created_at }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 回滚 = 挪指针 + 把当前状态恢复成该版本(历史不可变,不生成新版本;单事务,V2-2)。 */
|
|
216
|
+
function rollback(id, version) {
|
|
217
|
+
return atomic(() => {
|
|
218
|
+
requireWork(id)
|
|
219
|
+
const v = getVersion(id, version)
|
|
220
|
+
if (!v) throw new Error(`版本不存在: ${id} v${version}`)
|
|
221
|
+
const ts = now()
|
|
222
|
+
stmt.setVersionPointer.run(v.version, ts, String(id))
|
|
223
|
+
if (v.payload != null) {
|
|
224
|
+
stmt.upsertState.run(String(id), JSON.stringify(v.payload), Number(v.payload.seq) | 0, ts)
|
|
225
|
+
indexRefs(id, v.payload)
|
|
226
|
+
}
|
|
227
|
+
return getWork(id)
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function updateWork(id, patch = {}) {
|
|
232
|
+
const row = requireWork(id)
|
|
233
|
+
const title = patch.title != null ? String(patch.title) : row.title
|
|
234
|
+
const brief = patch.brief != null ? String(patch.brief) : row.brief
|
|
235
|
+
const tags = patch.tags != null ? JSON.stringify(Array.isArray(patch.tags) ? patch.tags : []) : row.tags
|
|
236
|
+
const status = Number.isInteger(patch.status) ? patch.status : row.status
|
|
237
|
+
const cover = patch.coverAsset != null ? String(patch.coverAsset) : row.cover_asset
|
|
238
|
+
const meta = patch.meta != null ? JSON.stringify(patch.meta && typeof patch.meta === 'object' ? patch.meta : {}) : row.meta
|
|
239
|
+
stmt.updateWork.run(title, brief, tags, status, cover, meta, now(), String(id))
|
|
240
|
+
return getWork(id)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function deleteWork(id) {
|
|
244
|
+
requireWork(id)
|
|
245
|
+
const ts = now()
|
|
246
|
+
stmt.softDelete.run(ts, ts, String(id))
|
|
247
|
+
return { id: String(id), deletedAt: ts }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* 硬删除(V2-5):目录+状态+版本+checkpoint+资产引用级联清除(FK CASCADE),
|
|
252
|
+
* journal 无 FK 得以保留,并追加 {type:'purge'} tombstone 事件供审计。单事务。
|
|
253
|
+
*/
|
|
254
|
+
function purgeWork(id) {
|
|
255
|
+
return atomic(() => {
|
|
256
|
+
requireWork(id)
|
|
257
|
+
const ts = now()
|
|
258
|
+
db.prepare('DELETE FROM works WHERE id = ?').run(String(id))
|
|
259
|
+
stmt.insertJournal.run(String(id), null, 'purge', JSON.stringify({ type: 'purge', id: String(id), ts }), ts / 1000)
|
|
260
|
+
return { id: String(id), purgedAt: ts }
|
|
261
|
+
})
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/* ---- 产物信封(artifacts,schema 3 / API 1.2.0,能力 workStore.artifacts) ----
|
|
265
|
+
* 套件间引用交接:只存 @asset/<sha> 引用 + 类型/来源/谱系,字节在 ctx.assets。
|
|
266
|
+
* 规范见 docs/suite-interop-standard.md §B。work_id 软引用,产物可独立于作品存续。 */
|
|
267
|
+
|
|
268
|
+
/** 注册一个产物信封(单事务)。lineage.parent 存在时版本自动 +1 并继承 root。 */
|
|
269
|
+
function registerArtifact(input = {}) {
|
|
270
|
+
return atomic(() => {
|
|
271
|
+
const norm = normalizeEnvelopeInput(input)
|
|
272
|
+
if (norm.workId) requireWork(norm.workId)
|
|
273
|
+
const id = String(input.id || makeArtifactId())
|
|
274
|
+
let version = Number.isInteger(input.version) ? input.version : 1
|
|
275
|
+
if (norm.lineage.parent) {
|
|
276
|
+
const parent = stmt.getArtifact.get(norm.lineage.parent)
|
|
277
|
+
if (parent) {
|
|
278
|
+
version = parent.version + 1
|
|
279
|
+
if (!norm.lineage.root) norm.lineage.root = parseJson(parent.lineage, {}).root || parent.id
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (!norm.lineage.root) norm.lineage.root = id
|
|
283
|
+
const ts = now()
|
|
284
|
+
stmt.insertArtifact.run(id, norm.workId, norm.sessionId, norm.type, norm.mime, norm.assetRef,
|
|
285
|
+
norm.title, norm.producer, norm.producerSuite, version,
|
|
286
|
+
JSON.stringify(norm.lineage), JSON.stringify(norm.meta), ts, ts)
|
|
287
|
+
if (norm.workId) stmt.insertAsset.run(norm.workId, assetIdOf(norm.assetRef), 'artifact')
|
|
288
|
+
return shapeArtifact(stmt.getArtifact.get(id))
|
|
289
|
+
})
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function getArtifact(id) {
|
|
293
|
+
return shapeArtifact(stmt.getArtifact.get(String(id)))
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** 产物查询面:work/session/type/producer 筛选 + 标题全文 + 排序 + 分页 + total。 */
|
|
297
|
+
function listArtifacts(query = {}) {
|
|
298
|
+
const where = []
|
|
299
|
+
const params = []
|
|
300
|
+
if (!query.includeDeleted) where.push('deleted_at IS NULL')
|
|
301
|
+
if (query.workId) { where.push('work_id = ?'); params.push(String(query.workId)) }
|
|
302
|
+
if (query.sessionId != null && query.sessionId !== '') { where.push('session_id = ?'); params.push(String(query.sessionId)) }
|
|
303
|
+
if (query.type) { where.push('type = ?'); params.push(String(query.type)) }
|
|
304
|
+
if (query.producer) { where.push('producer = ?'); params.push(String(query.producer)) }
|
|
305
|
+
if (query.producerSuite) { where.push('producer_suite = ?'); params.push(String(query.producerSuite)) }
|
|
306
|
+
if (query.query) { where.push('title LIKE ?'); params.push(`%${String(query.query)}%`) }
|
|
307
|
+
const clause = where.length ? `WHERE ${where.join(' AND ')}` : ''
|
|
308
|
+
const sort = query.sort === 'created' ? 'created_at DESC' : query.sort === 'title' ? 'title ASC' : 'updated_at DESC'
|
|
309
|
+
const limit = Math.max(1, Math.min(500, Number(query.limit) || 50))
|
|
310
|
+
const offset = Math.max(0, Number(query.offset) || 0)
|
|
311
|
+
const total = db.prepare(`SELECT COUNT(*) AS n FROM artifacts ${clause}`).get(...params).n
|
|
312
|
+
const rows = db.prepare(`SELECT * FROM artifacts ${clause} ORDER BY ${sort} LIMIT ? OFFSET ?`).all(...params, limit, offset)
|
|
313
|
+
return { items: rows.map(shapeArtifact), total, limit, offset }
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function deleteArtifact(id) {
|
|
317
|
+
const row = stmt.getArtifact.get(String(id))
|
|
318
|
+
if (!row) throw new Error(`产物不存在: ${id}`)
|
|
319
|
+
const ts = now()
|
|
320
|
+
stmt.softDeleteArtifact.run(ts, ts, String(id))
|
|
321
|
+
return { artifactId: String(id), deletedAt: ts }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** 读取展开:把信封 assetRef 展开成可加载 URL(urlBase 如 /capyclaw/ppt/)。返回新副本。 */
|
|
325
|
+
function resolveArtifact(id, urlBase) {
|
|
326
|
+
const env = getArtifact(id)
|
|
327
|
+
if (!env) return null
|
|
328
|
+
return { ...env, url: resolveRefs({ ref: env.assetRef }, urlBase).ref }
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** 沿 lineage.parent 回溯谱系链(根 → … → 当前),上限 64 防环。 */
|
|
332
|
+
function artifactChain(id) {
|
|
333
|
+
const chain = []
|
|
334
|
+
const seen = new Set()
|
|
335
|
+
let cur = getArtifact(id)
|
|
336
|
+
while (cur && !seen.has(cur.artifactId) && chain.length < 64) {
|
|
337
|
+
seen.add(cur.artifactId)
|
|
338
|
+
chain.unshift(cur)
|
|
339
|
+
cur = cur.lineage?.parent ? getArtifact(cur.lineage.parent) : null
|
|
340
|
+
}
|
|
341
|
+
return chain
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/* ---- work_meta 通用 KV(迁移标志 / highWater / idmap 等套件级状态,V2-5) ---- */
|
|
345
|
+
|
|
346
|
+
function getMeta(key, fallback = null) {
|
|
347
|
+
const row = db.prepare('SELECT value FROM work_meta WHERE key = ?').get(String(key))
|
|
348
|
+
return row ? parseJson(row.value, fallback) : fallback
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function setMeta(key, value) {
|
|
352
|
+
db.prepare('INSERT INTO work_meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value')
|
|
353
|
+
.run(String(key), JSON.stringify(value ?? null))
|
|
354
|
+
return value
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/* ---- 会话模式锁(F:一个会话只有一次认领工作台种类的机会,认领后终生固化) ----
|
|
358
|
+
* 单一真源:所有 bridge 共用 works.db 的这条会话级记录。认领走 tx(BEGIN IMMEDIATE)
|
|
359
|
+
* 保证跨 bridge 原子——两个工作台同时首写同一会话时,只有一个能认领成功。
|
|
360
|
+
* 无会话身份(standalone default)不启用:返回 skipped,调用方照常工作。 */
|
|
361
|
+
|
|
362
|
+
const sessionModeKey = (sessionId) => `session-mode:${String(sessionId)}`
|
|
363
|
+
|
|
364
|
+
/** 读会话已固化的模式:{kind, claimedAt, claimedBy, explicit?} 或 null(未认领)。
|
|
365
|
+
* explicit=true 表示这次认领是用户显式选择(展示墙点选),而非工具首写懒认领——
|
|
366
|
+
* 主区舞台据此对该种类豁免「有没有内容」闸(选了就要摆出来,哪怕还没内容)。 */
|
|
367
|
+
function getSessionMode(sessionId) {
|
|
368
|
+
const sid = String(sessionId || '')
|
|
369
|
+
if (!sid) return null
|
|
370
|
+
return getMeta(sessionModeKey(sid), null)
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* 认领/校验会话模式。opts.explicit=true 标记「用户显式选择」(展示墙点选):
|
|
375
|
+
* 首认领落 explicit:true;同种类再认领只升不降(懒认领可被显式选择升级)。
|
|
376
|
+
* 返回:
|
|
377
|
+
* {ok:true, kind, fresh, explicit} 未认领→认领成功;或已固化为本种类→放行
|
|
378
|
+
* {ok:false, kind, lockedTo} 已固化为别的种类→硬拒(调用方据此报错「请新开会话」)
|
|
379
|
+
* {ok:true, kind, skipped:true} 无会话身份→不启用
|
|
380
|
+
*/
|
|
381
|
+
function claimSessionMode(sessionId, kind, claimedBy = '', opts = {}) {
|
|
382
|
+
const sid = String(sessionId || '')
|
|
383
|
+
const k = String(kind || '')
|
|
384
|
+
if (!sid) return { ok: true, kind: k, skipped: true }
|
|
385
|
+
if (!k) throw new Error('claimSessionMode 需要 kind')
|
|
386
|
+
const explicit = !!(opts && opts.explicit)
|
|
387
|
+
return atomic(() => {
|
|
388
|
+
const cur = getMeta(sessionModeKey(sid), null)
|
|
389
|
+
if (cur && cur.kind && cur.kind !== k) {
|
|
390
|
+
return { ok: false, kind: k, lockedTo: cur.kind, claimedAt: cur.claimedAt }
|
|
391
|
+
}
|
|
392
|
+
if (!cur) {
|
|
393
|
+
const rec = { kind: k, claimedAt: now(), claimedBy: String(claimedBy || '') }
|
|
394
|
+
if (explicit) rec.explicit = true
|
|
395
|
+
setMeta(sessionModeKey(sid), rec)
|
|
396
|
+
return { ok: true, kind: k, fresh: true, explicit }
|
|
397
|
+
}
|
|
398
|
+
/* 同种类再认领:explicit 只升不降,不改 claimedAt/claimedBy(首次认领者留痕)。 */
|
|
399
|
+
if (explicit && !cur.explicit) setMeta(sessionModeKey(sid), { ...cur, explicit: true })
|
|
400
|
+
return { ok: true, kind: k, fresh: false, explicit: !!(cur.explicit || explicit) }
|
|
401
|
+
})
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* 按事件类型 + 字面子串查 journal(摄入幂等台账等,V2-6)。
|
|
406
|
+
* needle 用 instr 字面匹配(无 LIKE 通配符歧义);调用方拼 JSON 字面量,
|
|
407
|
+
* 如 `"ingest_key":${JSON.stringify(key)}`,转义由 JSON.stringify 保证。
|
|
408
|
+
*/
|
|
409
|
+
function findJournal(type, needle, limit = 50) {
|
|
410
|
+
const rows = db.prepare('SELECT work_id, data, ts FROM work_journal WHERE type = ? AND instr(data, ?) > 0 ORDER BY id DESC LIMIT ?')
|
|
411
|
+
.all(String(type), String(needle), Math.max(1, Number(limit) || 50))
|
|
412
|
+
return rows.map((r) => ({ workId: r.work_id, ...parseJson(r.data, {}), ts: r.ts }))
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* 前端查询面:分类筛选 + 全文 + 排序 + 分页。
|
|
417
|
+
* @returns {{ items: object[], total: number, limit: number, offset: number }}
|
|
418
|
+
*/
|
|
419
|
+
function listWorks(query = {}) {
|
|
420
|
+
const where = []
|
|
421
|
+
const params = []
|
|
422
|
+
if (!query.includeDeleted) where.push('deleted_at IS NULL')
|
|
423
|
+
if (query.suite) { where.push('suite = ?'); params.push(String(query.suite)) }
|
|
424
|
+
if (query.kind) { where.push('kind = ?'); params.push(String(query.kind)) }
|
|
425
|
+
if (query.sessionId != null && query.sessionId !== '') { where.push('session_id = ?'); params.push(String(query.sessionId)) }
|
|
426
|
+
if (Number.isInteger(query.status)) { where.push('status = ?'); params.push(query.status) }
|
|
427
|
+
if (query.tag) { where.push('tags LIKE ?'); params.push(`%"${String(query.tag)}"%`) }
|
|
428
|
+
if (query.query) { where.push('(title LIKE ? OR brief LIKE ?)'); const like = `%${String(query.query)}%`; params.push(like, like) }
|
|
429
|
+
const clause = where.length ? `WHERE ${where.join(' AND ')}` : ''
|
|
430
|
+
const sort = query.sort === 'created' ? 'created_at DESC'
|
|
431
|
+
: query.sort === 'title' ? 'title ASC'
|
|
432
|
+
: 'updated_at DESC'
|
|
433
|
+
const limit = Math.max(1, Math.min(500, Number(query.limit) || 50))
|
|
434
|
+
const offset = Math.max(0, Number(query.offset) || 0)
|
|
435
|
+
const total = db.prepare(`SELECT COUNT(*) AS n FROM works ${clause}`).get(...params).n
|
|
436
|
+
const rows = db.prepare(`SELECT * FROM works ${clause} ORDER BY ${sort} LIMIT ? OFFSET ?`).all(...params, limit, offset)
|
|
437
|
+
return { items: rows.map(shapeWork), total, limit, offset }
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** 分类统计(前端仪表盘):按 suite/kind 计数。 */
|
|
441
|
+
function stats() {
|
|
442
|
+
const bySuite = db.prepare("SELECT suite, COUNT(*) AS n FROM works WHERE deleted_at IS NULL GROUP BY suite ORDER BY n DESC").all()
|
|
443
|
+
const byKind = db.prepare("SELECT suite, kind, COUNT(*) AS n FROM works WHERE deleted_at IS NULL GROUP BY suite, kind ORDER BY n DESC").all()
|
|
444
|
+
const total = db.prepare('SELECT COUNT(*) AS n FROM works WHERE deleted_at IS NULL').get().n
|
|
445
|
+
return { total, bySuite, byKind }
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/* ---- journal / checkpoint(与 FileStateBackend 同语义) ---- */
|
|
449
|
+
|
|
450
|
+
function appendJournal(id, event = {}) {
|
|
451
|
+
const ts = now() / 1000
|
|
452
|
+
stmt.insertJournal.run(String(id), event.seq ?? null, String(event.type || ''), JSON.stringify(event), ts)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function journalTail(id, limit = 8) {
|
|
456
|
+
const rows = stmt.journalTail.all(String(id), Math.max(1, Number(limit) || 8))
|
|
457
|
+
return rows.reverse().map((r) => ({ ...parseJson(r.data, {}), ts: r.ts }))
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function writeCheckpoint(id, name, payload) {
|
|
461
|
+
const safe = String(name || '')
|
|
462
|
+
if (!CHECKPOINT_NAME.test(safe)) throw new Error('checkpoint 名称必须是 1-64 位字母/数字/._-')
|
|
463
|
+
stmt.upsertCheckpoint.run(String(id), safe, JSON.stringify(payload ?? {}), now())
|
|
464
|
+
return { name: safe }
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function readCheckpoint(id, name) {
|
|
468
|
+
const row = stmt.getCheckpoint.get(String(id), String(name))
|
|
469
|
+
return row ? parseJson(row.payload, null) : null
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* 通用 checkpoint 清单(V2-5):{name, ts, createdAt, size, meta}——
|
|
474
|
+
* 内核不解析 payload 内部任何业务形状(PPT 的 slides/title、会话的 seq 等)。
|
|
475
|
+
* 扩展字段由套件适配层经 options.project(payload, base) 显式声明并叠加;
|
|
476
|
+
* 旧 checkpoint 的 payload 原样保留(readCheckpoint 返回全量),套件投影兼容读旧形状。
|
|
477
|
+
* 合并约定与 document-workbench/store/projection 的 projectCheckpoint 一致
|
|
478
|
+
* (底座刻意不 import document-workbench,故内联同约定)。
|
|
479
|
+
*/
|
|
480
|
+
function listCheckpoints(id, options = {}) {
|
|
481
|
+
const project = typeof options.project === 'function' ? options.project : null
|
|
482
|
+
return stmt.listCheckpoints.all(String(id)).map((r) => {
|
|
483
|
+
const parsed = parseJson(r.payload, {})
|
|
484
|
+
const p = parsed && typeof parsed === 'object' ? parsed : {}
|
|
485
|
+
const base = {
|
|
486
|
+
name: r.name,
|
|
487
|
+
ts: r.created_at,
|
|
488
|
+
createdAt: r.created_at,
|
|
489
|
+
size: Buffer.byteLength(r.payload, 'utf8'),
|
|
490
|
+
meta: p.meta && typeof p.meta === 'object' ? p.meta : {},
|
|
491
|
+
}
|
|
492
|
+
if (!project) return base
|
|
493
|
+
const extra = project(p, base)
|
|
494
|
+
return extra && typeof extra === 'object' ? { ...base, ...extra } : base
|
|
495
|
+
})
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function listAssets(id) {
|
|
499
|
+
return stmt.listAssets.all(String(id)).map((r) => ({ assetId: r.asset_id, role: r.role }))
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* 给 DocumentSession 用的后端:实现 FileStateBackend 同接口,上层零改。
|
|
504
|
+
* 先 ensureWork(幂等),再返回绑定该作品的 SqliteStateBackend。
|
|
505
|
+
* input.project:checkpoint 列表的套件投影(形状声明),透传给 backend。
|
|
506
|
+
*/
|
|
507
|
+
function backendFor(input = {}) {
|
|
508
|
+
const work = ensureWork(input)
|
|
509
|
+
return createSqliteBackend({
|
|
510
|
+
store: api,
|
|
511
|
+
workId: work.id,
|
|
512
|
+
initialDoc: input.initialDoc || {},
|
|
513
|
+
transform: typeof input.transform === 'function' ? input.transform : null,
|
|
514
|
+
project: typeof input.project === 'function' ? input.project : null,
|
|
515
|
+
})
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const api = {
|
|
519
|
+
api: WORK_STORE_API,
|
|
520
|
+
dir: handle.dir,
|
|
521
|
+
file: handle.file,
|
|
522
|
+
naturalId,
|
|
523
|
+
tx,
|
|
524
|
+
ensureWork,
|
|
525
|
+
getWork,
|
|
526
|
+
writeState,
|
|
527
|
+
readState,
|
|
528
|
+
getDocument,
|
|
529
|
+
saveVersion,
|
|
530
|
+
listVersions,
|
|
531
|
+
getVersion,
|
|
532
|
+
rollback,
|
|
533
|
+
updateWork,
|
|
534
|
+
deleteWork,
|
|
535
|
+
purgeWork,
|
|
536
|
+
getMeta,
|
|
537
|
+
setMeta,
|
|
538
|
+
getSessionMode,
|
|
539
|
+
claimSessionMode,
|
|
540
|
+
findJournal,
|
|
541
|
+
listWorks,
|
|
542
|
+
stats,
|
|
543
|
+
appendJournal,
|
|
544
|
+
journalTail,
|
|
545
|
+
writeCheckpoint,
|
|
546
|
+
readCheckpoint,
|
|
547
|
+
listCheckpoints,
|
|
548
|
+
listAssets,
|
|
549
|
+
registerArtifact,
|
|
550
|
+
getArtifact,
|
|
551
|
+
listArtifacts,
|
|
552
|
+
deleteArtifact,
|
|
553
|
+
resolveArtifact,
|
|
554
|
+
artifactChain,
|
|
555
|
+
backendFor,
|
|
556
|
+
flush() { try { db.exec('PRAGMA wal_checkpoint(PASSIVE)') } catch { /* 尽力收 WAL */ } },
|
|
557
|
+
routes(options = {}) { return createWorkRoutes({ store: api, ...options }) },
|
|
558
|
+
close() { handle.close() },
|
|
559
|
+
}
|
|
560
|
+
return api
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export { createSqliteBackend } from './backend.mjs'
|
|
564
|
+
export { createWorkRoutes } from './routes.mjs'
|
|
565
|
+
export { extractDataUris, resolveRefs, collectRefs } from './refs.mjs'
|
|
566
|
+
export { openWorkDb, defaultWorkDir, SCHEMA_VERSION } from './db.mjs'
|
|
567
|
+
export {
|
|
568
|
+
ARTIFACT_TYPES, ARTIFACT_EXT, makeArtifactId, normalizeAssetRef, assetIdOf,
|
|
569
|
+
normalizeEnvelopeInput, normalizeLineage, shapeArtifact, isAssetRef, mimeFor,
|
|
570
|
+
} from './envelope.mjs'
|
|
571
|
+
export { registerBytesArtifact, registerFileArtifact, materializeArtifact } from './interop.mjs'
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 引用交接助手 —— 最小闭环的边缘物化原语(docs/suite-interop-standard.md §B/§E)。
|
|
3
|
+
*
|
|
4
|
+
* 套件之间只传 artifactId / assetRef;字节只在两端物化:
|
|
5
|
+
* 生产端:registerBytesArtifact / registerFileArtifact (字节 → ctx.assets.put → 信封)
|
|
6
|
+
* 消费端:materializeArtifact (信封 → ctx.assets.get → 本机临时文件)
|
|
7
|
+
*
|
|
8
|
+
* 解耦:putAsset / getAsset 以**注入**方式传入(通常接 ctx.assets.put / ctx.assets.get),
|
|
9
|
+
* 本模块不 import asset-service,也不 import 任何具体套件。store 是 ctx.workStore 句柄。
|
|
10
|
+
* 这样 browser 上传边缘只需 materializeArtifact 拿到本机路径,再交给 browser_upload,
|
|
11
|
+
* browser 套件本身完全不知道 work-store / 信封的存在。
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import os from 'node:os'
|
|
16
|
+
import { ARTIFACT_EXT, assetIdOf, mimeFor } from './envelope.mjs'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 字节 → 产物信封。putAsset(buffer, mime) → { id }(内容寻址 blob 仓)。
|
|
20
|
+
* @param {object} store ctx.workStore
|
|
21
|
+
* @param {(buf: Buffer, mime: string) => Promise<{id: string}>} putAsset
|
|
22
|
+
* @param {Buffer|Uint8Array|string} bytes
|
|
23
|
+
* @param {object} input 信封输入(type 必填;title/producer/workId/sessionId/lineage/meta…)
|
|
24
|
+
*/
|
|
25
|
+
export async function registerBytesArtifact(store, putAsset, bytes, input = {}) {
|
|
26
|
+
if (!store || typeof store.registerArtifact !== 'function') throw new Error('registerBytesArtifact 需要 ctx.workStore 句柄')
|
|
27
|
+
if (typeof putAsset !== 'function') throw new Error('registerBytesArtifact 需要注入 putAsset(如 ctx.assets.put)')
|
|
28
|
+
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
|
|
29
|
+
const mime = input.mime || mimeFor(input.type)
|
|
30
|
+
const asset = await putAsset(buf, mime)
|
|
31
|
+
const id = String(asset?.id ?? '').toLowerCase()
|
|
32
|
+
if (!/^[a-f0-9]{64}$/.test(id)) throw new Error(`putAsset 未返回合法 sha256 id:${asset?.id}`)
|
|
33
|
+
return store.registerArtifact({ ...input, assetRef: `@asset/${id}`, mime })
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 本机文件 → 产物信封(ppt_export_pptx 产出 path 后走这里)。
|
|
38
|
+
* 缺省 title 取文件名。读文件字节 → putAsset → registerArtifact。
|
|
39
|
+
*/
|
|
40
|
+
export async function registerFileArtifact(store, putAsset, filePath, input = {}) {
|
|
41
|
+
const bytes = await fs.promises.readFile(filePath)
|
|
42
|
+
return registerBytesArtifact(store, putAsset, bytes, {
|
|
43
|
+
title: input.title || path.basename(String(filePath)),
|
|
44
|
+
...input,
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 产物信封 → 本机临时文件(browser 上传边缘走这里)。
|
|
50
|
+
* getAsset(sha) → { data, contentType }(或直接返回 Buffer)。
|
|
51
|
+
* 返回 { path, envelope };path 是写好的本机文件,可直接交给 browser_upload。
|
|
52
|
+
* options.dir 缺省新建临时目录;options.name/ext 可覆盖文件名。
|
|
53
|
+
*/
|
|
54
|
+
export async function materializeArtifact(store, getAsset, artifactId, options = {}) {
|
|
55
|
+
if (!store || typeof store.getArtifact !== 'function') throw new Error('materializeArtifact 需要 ctx.workStore 句柄')
|
|
56
|
+
if (typeof getAsset !== 'function') throw new Error('materializeArtifact 需要注入 getAsset(如 ctx.assets.get)')
|
|
57
|
+
const envelope = store.getArtifact(artifactId)
|
|
58
|
+
if (!envelope) throw new Error(`产物不存在: ${artifactId}`)
|
|
59
|
+
const sha = assetIdOf(envelope.assetRef)
|
|
60
|
+
const got = await getAsset(sha)
|
|
61
|
+
const data = got?.data ?? got
|
|
62
|
+
if (!data) throw new Error(`blob 仓缺少字节: ${sha}`)
|
|
63
|
+
const dir = options.dir || fs.mkdtempSync(path.join(os.tmpdir(), 'capyclaw-artifact-'))
|
|
64
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
65
|
+
const ext = options.ext ?? ARTIFACT_EXT[envelope.type] ?? ''
|
|
66
|
+
const name = options.name || `${envelope.artifactId}${ext}`
|
|
67
|
+
const file = path.join(dir, name)
|
|
68
|
+
await fs.promises.writeFile(file, data)
|
|
69
|
+
return { path: file, envelope }
|
|
70
|
+
}
|