@capyclaw/capyclaw-workbench 0.0.0-stage → 0.1.1
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 +56 -2
- package/contract/capabilities.json +178 -0
- package/lib/descriptors.mjs +33 -0
- package/lib/host.mjs +106 -0
- package/lib/session-port.mjs +178 -0
- package/lib/session-watch.mjs +82 -0
- package/lib/tools.mjs +166 -0
- package/lib/workbench.mjs +133 -0
- package/lib/workspace-attach.mjs +147 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +570 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- 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/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
- package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
- package/package.json +68 -4
- package/plugin.mjs +17 -0
- package/ui/app.js +114 -0
- package/ui/index.html +64 -0
- package/ui/style.css +54 -0
package/lib/tools.mjs
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* capyclaw_* 工具面:子会话生命周期 + DSH 设置。
|
|
3
|
+
* 全部经 tool-host DSL 声明;handler 闭包 sessionPort/ledger,不依赖 DSH exec。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @param {{ toolHost:object, sessionPort:object, ledger:object, mountPath:string, guiUrl:string }} deps
|
|
8
|
+
*/
|
|
9
|
+
export function createCapyclawCapabilities({ toolHost, sessionPort, ledger, mountPath = '/capyclaw/capyclaw', guiUrl = '/' }) {
|
|
10
|
+
const { defineTool, defineCapability } = toolHost
|
|
11
|
+
|
|
12
|
+
const openSession = defineTool({
|
|
13
|
+
name: 'capyclaw_open_session',
|
|
14
|
+
description: '创建一个 DSH 子会话(同一宿主进程,非独立 dsh)。可选立即发一条启动消息。新会话会自动出现在 GUI 会话列表;返回 sessionId 供后续 send_message/transcript 使用。',
|
|
15
|
+
kind: 'control',
|
|
16
|
+
since: '0.1.0',
|
|
17
|
+
inputSchema: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
title: { type: 'string', description: '给子会话起的标题(仅本套件账本记录)' },
|
|
21
|
+
cwd: { type: 'string', description: '子会话工作目录(与 workspaceId 互斥)' },
|
|
22
|
+
workspaceId: { type: 'string', description: '工作区 id(与 cwd 互斥)' },
|
|
23
|
+
agentPreset: { type: 'string', description: 'agent 预设' },
|
|
24
|
+
prompt: { type: 'string', description: '创建后立即发送的启动消息(可选)' },
|
|
25
|
+
},
|
|
26
|
+
additionalProperties: false,
|
|
27
|
+
},
|
|
28
|
+
handler: async (args) => {
|
|
29
|
+
const { sessionId, agentPreset } = await sessionPort.createSession({
|
|
30
|
+
cwd: args.cwd, workspaceId: args.workspaceId, agentPreset: args.agentPreset,
|
|
31
|
+
})
|
|
32
|
+
const title = args.title || `子会话 ${sessionId.slice(0, 8)}`
|
|
33
|
+
ledger.record(sessionId, { title, cwd: args.cwd || null, agentPreset, parent: 'capyclaw' })
|
|
34
|
+
let accepted = null
|
|
35
|
+
if (args.prompt) {
|
|
36
|
+
const r = await sessionPort.prompt({ sessionId, text: args.prompt })
|
|
37
|
+
accepted = r.accepted
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
ok: true, sessionId, title, agentPreset, accepted,
|
|
41
|
+
consoleUrl: mountPath, guiUrl,
|
|
42
|
+
note: 'GUI 无会话深链:新会话已进 GUI 列表;用 capyclaw_send_message 驱动,或在套娃控制台查看转录。',
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
const sendMessage = defineTool({
|
|
48
|
+
name: 'capyclaw_send_message',
|
|
49
|
+
description: '向指定子会话发送一条用户消息,启动一轮 agent 工作。',
|
|
50
|
+
kind: 'write',
|
|
51
|
+
since: '0.1.0',
|
|
52
|
+
inputSchema: {
|
|
53
|
+
type: 'object',
|
|
54
|
+
properties: {
|
|
55
|
+
sessionId: { type: 'string', description: '目标子会话 id' },
|
|
56
|
+
text: { type: 'string', description: '消息文本' },
|
|
57
|
+
mode: { type: 'string', enum: ['queue', 'steer'], description: 'queue=排队新轮;steer=转向当前轮' },
|
|
58
|
+
},
|
|
59
|
+
required: ['sessionId', 'text'],
|
|
60
|
+
additionalProperties: false,
|
|
61
|
+
},
|
|
62
|
+
handler: async (args) => {
|
|
63
|
+
const r = await sessionPort.prompt({ sessionId: args.sessionId, text: args.text, mode: args.mode || 'queue' })
|
|
64
|
+
return { ok: true, ...r }
|
|
65
|
+
},
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
const listSessions = defineTool({
|
|
69
|
+
name: 'capyclaw_list_sessions',
|
|
70
|
+
description: '列出 DSH 会话(最新在前),并附上本套件账本里的标题/来源标记。',
|
|
71
|
+
kind: 'read',
|
|
72
|
+
since: '0.1.0',
|
|
73
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
74
|
+
handler: async () => {
|
|
75
|
+
const records = await sessionPort.listSessions()
|
|
76
|
+
const items = (Array.isArray(records) ? records : []).map((rec) => {
|
|
77
|
+
const id = rec.sessionId || rec.id
|
|
78
|
+
const meta = ledger.get(id) || {}
|
|
79
|
+
return { sessionId: id, title: meta.title || rec.title || null, cwd: meta.cwd ?? rec.cwd ?? null, fromCapyclaw: !!meta, closed: !!meta.closed, raw: rec }
|
|
80
|
+
})
|
|
81
|
+
return { ok: true, count: items.length, items }
|
|
82
|
+
},
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
const transcript = defineTool({
|
|
86
|
+
name: 'capyclaw_session_transcript',
|
|
87
|
+
description: '读取指定子会话的转录/事件(供编排器或用户查看进展)。',
|
|
88
|
+
kind: 'read',
|
|
89
|
+
since: '0.1.0',
|
|
90
|
+
inputSchema: {
|
|
91
|
+
type: 'object',
|
|
92
|
+
properties: { sessionId: { type: 'string', description: '目标子会话 id' } },
|
|
93
|
+
required: ['sessionId'],
|
|
94
|
+
additionalProperties: false,
|
|
95
|
+
},
|
|
96
|
+
handler: async (args) => {
|
|
97
|
+
const data = await sessionPort.readSession(args.sessionId)
|
|
98
|
+
return { ok: true, sessionId: args.sessionId, transcript: data }
|
|
99
|
+
},
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
const closeSession = defineTool({
|
|
103
|
+
name: 'capyclaw_close_session',
|
|
104
|
+
description: '关闭子会话:取消当前轮(best-effort)并在账本标记 closed。DSH 无显式销毁,会话记录仍保留。',
|
|
105
|
+
kind: 'control',
|
|
106
|
+
since: '0.1.0',
|
|
107
|
+
inputSchema: {
|
|
108
|
+
type: 'object',
|
|
109
|
+
properties: { sessionId: { type: 'string', description: '目标子会话 id' } },
|
|
110
|
+
required: ['sessionId'],
|
|
111
|
+
additionalProperties: false,
|
|
112
|
+
},
|
|
113
|
+
handler: async (args) => {
|
|
114
|
+
const r = await sessionPort.cancel(args.sessionId)
|
|
115
|
+
ledger.markClosed(args.sessionId)
|
|
116
|
+
return { ok: true, ...r, closed: true }
|
|
117
|
+
},
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
const settingsGet = defineTool({
|
|
121
|
+
name: 'capyclaw_settings_get',
|
|
122
|
+
description: '读取 DSH 设置快照(describe)。帮用户查看当前配置。',
|
|
123
|
+
kind: 'read',
|
|
124
|
+
since: '0.1.0',
|
|
125
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
126
|
+
handler: async () => ({ ok: true, settings: await sessionPort.describeSettings() }),
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
const settingsSet = defineTool({
|
|
130
|
+
name: 'capyclaw_settings_set',
|
|
131
|
+
description: '更新 DSH 设置(稀疏合并)。ns=profile 条目 id;高风险操作,需确认。revision 不符会抛 SETTINGS_CONFLICT。',
|
|
132
|
+
kind: 'write',
|
|
133
|
+
since: '0.1.0',
|
|
134
|
+
inputSchema: {
|
|
135
|
+
type: 'object',
|
|
136
|
+
properties: {
|
|
137
|
+
ns: { type: 'string', description: '设置命名空间(profile 条目 id)' },
|
|
138
|
+
patch: { type: 'object', description: '要合并的设置补丁', additionalProperties: true },
|
|
139
|
+
expectedRevision: { type: 'string', description: '乐观锁 revision(可选)' },
|
|
140
|
+
},
|
|
141
|
+
required: ['ns', 'patch'],
|
|
142
|
+
additionalProperties: false,
|
|
143
|
+
},
|
|
144
|
+
handler: async (args) => {
|
|
145
|
+
const value = await sessionPort.updateSettings({ ns: args.ns, patch: args.patch, expectedRevision: args.expectedRevision })
|
|
146
|
+
return { ok: true, ns: args.ns, value }
|
|
147
|
+
},
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
return [
|
|
151
|
+
defineCapability({
|
|
152
|
+
id: 'capyclaw.sessions',
|
|
153
|
+
title: '子会话生命周期',
|
|
154
|
+
description: '在同一宿主进程内创建/驱动/查询/关闭 DSH 子会话(俄罗斯套娃的控制面)。',
|
|
155
|
+
tags: ['session', 'subagent'],
|
|
156
|
+
tools: [openSession, sendMessage, listSessions, transcript, closeSession],
|
|
157
|
+
}),
|
|
158
|
+
defineCapability({
|
|
159
|
+
id: 'capyclaw.settings',
|
|
160
|
+
title: 'DSH 设置',
|
|
161
|
+
description: '读取/更新 DSH 设置,帮用户完成配置。',
|
|
162
|
+
tags: ['settings'],
|
|
163
|
+
tools: [settingsGet, settingsSet],
|
|
164
|
+
}),
|
|
165
|
+
]
|
|
166
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* capyclaw-workbench 可单测核心:会话控制台 + 套娃呈现 + MCP/HTTP 能力面。
|
|
3
|
+
* 不依赖 cordis ctx;服务(toolHost/serviceHost/sessionPort)全部注入。
|
|
4
|
+
* host.mjs 负责把它接进 DSH(listen + registerWithDsh + 描述符发布)。
|
|
5
|
+
*/
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
import { send, readBody } from '@capyclaw/plugin-kit/service/http'
|
|
9
|
+
import { attachSurface } from '@capyclaw/suite-kit/surface'
|
|
10
|
+
import { createCapyclawCapabilities } from './tools.mjs'
|
|
11
|
+
import { registerCapyclawDescriptors, CAPYCLAW_CONTRACT_VERSION } from './descriptors.mjs'
|
|
12
|
+
|
|
13
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
14
|
+
const DEFAULT_UI_DIR = path.join(HERE, '..', 'ui')
|
|
15
|
+
|
|
16
|
+
/** 子会话账本:标题/来源/closed 标记(DSH create 不收 title,这里补记)。 */
|
|
17
|
+
export function createLedger() {
|
|
18
|
+
const map = new Map()
|
|
19
|
+
return {
|
|
20
|
+
record(id, meta) { map.set(id, { ...map.get(id), ...meta, createdAt: map.get(id)?.createdAt || Date.now() }) },
|
|
21
|
+
get(id) { return map.get(id) || null },
|
|
22
|
+
markClosed(id) { if (map.has(id)) map.set(id, { ...map.get(id), closed: true }) },
|
|
23
|
+
all() { return [...map.entries()].map(([id, m]) => ({ sessionId: id, ...m })) },
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function statusFor(code) {
|
|
28
|
+
if (code === 'ARG_INVALID' || code === 'BAD_JSON') return 400
|
|
29
|
+
if (code === 'SESSION_SERVICE_UNAVAILABLE') return 503
|
|
30
|
+
return 500
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {{ toolHost:object, serviceHost:object, sessionPort:object,
|
|
35
|
+
* config?:{ mountPath?:string, guiUrl?:string, version?:string, uiDir?:string } }} deps
|
|
36
|
+
*/
|
|
37
|
+
export function createCapyclawWorkbench({ toolHost, serviceHost, sessionPort, config = {} }) {
|
|
38
|
+
const mountPath = config.mountPath || '/capyclaw/capyclaw'
|
|
39
|
+
const guiUrl = config.guiUrl || '/'
|
|
40
|
+
const version = config.version || '0.1.0'
|
|
41
|
+
const uiDir = config.uiDir || DEFAULT_UI_DIR
|
|
42
|
+
const ledger = createLedger()
|
|
43
|
+
|
|
44
|
+
const capabilities = createCapyclawCapabilities({ toolHost, sessionPort, ledger, mountPath, guiUrl })
|
|
45
|
+
const registry = toolHost.createRegistry(capabilities)
|
|
46
|
+
const mcpHandler = toolHost.createMcpHandler({
|
|
47
|
+
tools: registry.TOOLS,
|
|
48
|
+
// 结构化结果序列化为 JSON 文本:编排器(conductor)经 HTTP MCP tools/call
|
|
49
|
+
// 拿到的必须是可解析的 {ok,sessionId,...},而不是默认包装的 "ok"。
|
|
50
|
+
callTool: async (name, args, context) => {
|
|
51
|
+
const out = await registry.TOOL_IMPL[name](args, context)
|
|
52
|
+
const text = typeof out === 'string' ? out : JSON.stringify(out ?? null)
|
|
53
|
+
return { content: [{ type: 'text', text }] }
|
|
54
|
+
},
|
|
55
|
+
serverInfo: { name: 'capyclaw-workbench', version },
|
|
56
|
+
instructions: toolHost.buildInstructions({
|
|
57
|
+
title: 'CapyClaw 子会话工作台',
|
|
58
|
+
intro: '在同一宿主进程内创建/驱动 DSH 子会话(俄罗斯套娃),并可读写 DSH 设置。',
|
|
59
|
+
capabilities: registry.CAPABILITIES,
|
|
60
|
+
rules: ['GUI 无会话深链:新会话自动进 GUI 列表;用 sessionId 驱动与查转录。', 'settings_set 为高风险,需确认。'],
|
|
61
|
+
}),
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const app = serviceHost.createApp({
|
|
65
|
+
id: 'capyclaw-workbench',
|
|
66
|
+
title: 'CapyClaw 子会话工作台',
|
|
67
|
+
version,
|
|
68
|
+
contractVersion: CAPYCLAW_CONTRACT_VERSION,
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const guard = (handler) => async (req, res, u) => {
|
|
72
|
+
try { await handler(req, res, u) } catch (err) {
|
|
73
|
+
send(req, res, statusFor(err?.code), { ok: false, error: err?.message || String(err), code: err?.code || 'INTERNAL' })
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const mergeList = async () => {
|
|
77
|
+
let records = []
|
|
78
|
+
try { records = await sessionPort.listSessions() } catch { records = [] }
|
|
79
|
+
const byId = new Map()
|
|
80
|
+
for (const rec of Array.isArray(records) ? records : []) {
|
|
81
|
+
const id = rec.sessionId || rec.id
|
|
82
|
+
byId.set(id, { sessionId: id, ...rec, ...(ledger.get(id) || {}) })
|
|
83
|
+
}
|
|
84
|
+
for (const entry of ledger.all()) if (!byId.has(entry.sessionId)) byId.set(entry.sessionId, entry)
|
|
85
|
+
return [...byId.values()]
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
app.get('/api/sessions', guard(async (req, res) => send(req, res, 200, { ok: true, items: await mergeList() })))
|
|
89
|
+
app.post('/api/sessions', guard(async (req, res) => {
|
|
90
|
+
const body = await readBody(req)
|
|
91
|
+
const { sessionId, agentPreset } = await sessionPort.createSession({ cwd: body.cwd, workspaceId: body.workspaceId, agentPreset: body.agentPreset })
|
|
92
|
+
const title = body.title || `子会话 ${sessionId.slice(0, 8)}`
|
|
93
|
+
ledger.record(sessionId, { title, cwd: body.cwd || null, agentPreset, parent: 'capyclaw' })
|
|
94
|
+
let accepted = null
|
|
95
|
+
if (body.prompt) accepted = (await sessionPort.prompt({ sessionId, text: body.prompt })).accepted
|
|
96
|
+
send(req, res, 200, { ok: true, sessionId, title, accepted })
|
|
97
|
+
}))
|
|
98
|
+
app.post('/api/sessions/prompt', guard(async (req, res) => {
|
|
99
|
+
const body = await readBody(req)
|
|
100
|
+
send(req, res, 200, { ok: true, ...(await sessionPort.prompt({ sessionId: body.sessionId, text: body.text, mode: body.mode })) })
|
|
101
|
+
}))
|
|
102
|
+
app.get('/api/sessions/transcript', guard(async (req, res, u) => {
|
|
103
|
+
const sessionId = u.searchParams.get('sessionId')
|
|
104
|
+
send(req, res, 200, { ok: true, sessionId, transcript: await sessionPort.readSession(sessionId) })
|
|
105
|
+
}))
|
|
106
|
+
app.post('/api/sessions/close', guard(async (req, res) => {
|
|
107
|
+
const body = await readBody(req)
|
|
108
|
+
const r = await sessionPort.cancel(body.sessionId)
|
|
109
|
+
ledger.markClosed(body.sessionId)
|
|
110
|
+
send(req, res, 200, { ok: true, ...r, closed: true })
|
|
111
|
+
}))
|
|
112
|
+
app.get('/api/settings', guard(async (req, res) => send(req, res, 200, { ok: true, settings: await sessionPort.describeSettings() })))
|
|
113
|
+
app.post('/api/settings', guard(async (req, res) => {
|
|
114
|
+
const body = await readBody(req)
|
|
115
|
+
send(req, res, 200, { ok: true, value: await sessionPort.updateSettings({ ns: body.ns, patch: body.patch, expectedRevision: body.expectedRevision }) })
|
|
116
|
+
}))
|
|
117
|
+
app.get('/api/capabilities', guard(async (req, res) => send(req, res, 200, {
|
|
118
|
+
ok: true, contract: registry.ctx.contract.report(mountPath), available: sessionPort.services,
|
|
119
|
+
})))
|
|
120
|
+
app.get('/api/config', guard(async (req, res) => send(req, res, 200, { ok: true, mountPath, guiUrl, version, available: sessionPort.services })))
|
|
121
|
+
app.post('/mcp', guard(async (req, res) => { await mcpHandler(req, res) }))
|
|
122
|
+
// 呈现面接线(标准 §C.7):/embed.js 握手客户端 + /api/surface 自描述,单一真源在 suite-kit。
|
|
123
|
+
attachSurface(app, { suite: 'capyclaw', embedPath: mountPath })
|
|
124
|
+
app.static('/', uiDir)
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
app, registry, ledger, mountPath, guiUrl, sessionPort,
|
|
128
|
+
/** listen 后由 host 调:把描述符 + 调用地址登记进公共注册表。 */
|
|
129
|
+
publishDescriptors(baseUrl, { validate } = {}) {
|
|
130
|
+
return registerCapyclawDescriptors(toolHost, { baseUrl, validate })
|
|
131
|
+
},
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工作区登记:让「只传 cwd」创建的会话归属到对应的已存在工作区。
|
|
3
|
+
*
|
|
4
|
+
* 背景(2026-11-23):DSH 的 session.create 只有传 workspaceId 才登记工作区成员
|
|
5
|
+
* (dsh-api-session-controller commands.create);只传 cwd 创建不登记 ⇒ 会话落进
|
|
6
|
+
* 「未分组」桶,不出现在对应目录的工作区清单里。远程客户端(工作台 GUI)新建恰恰
|
|
7
|
+
* 只传 cwd,故 capyclaw 侧补登记:
|
|
8
|
+
* - attachSessionByCwd:createSession 成功后按 cwd 登记进匹配的已存在工作区(best-effort);
|
|
9
|
+
* - reconcileWorkspaceMembership:对「运行中、非子代理、未被任何工作区认领」的会话补登记;
|
|
10
|
+
* - createWorkspaceReconcile:周期补登记运行器(带 handled 集合:已处理过的会话不再重纳,
|
|
11
|
+
* 尊重用户手动移出;冷转 live 的会话会在变 live 后被捕捉)。
|
|
12
|
+
*
|
|
13
|
+
* 服务懒解析:workspaceRegistry 可传对象或零参解析函数(宿主装配可能早于服务注册,
|
|
14
|
+
* 用的时候现取,避免被一次性快照定格成缺席——2026-11-23 教训)。
|
|
15
|
+
*
|
|
16
|
+
* 设计口径:纯函数、服务全部注入、不 import DSH 包。只登记进【已存在】的工作区,
|
|
17
|
+
* 绝不擅自新建工作区;子代理(origin==='subagent')不参与;已被任何工作区认领的
|
|
18
|
+
* 会话不动(尊重用户手动摆放)。路径匹配用字符串规范化(分隔符/尾斜杠/Windows
|
|
19
|
+
* 不区分大小写);attachSession 自身还会按 realpath 校验 cwd,不匹配会拒绝写入,
|
|
20
|
+
* 因此不会误登记。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** 规范化路径用于比较:统一分隔符、去尾斜杠、Windows 不区分大小写。 */
|
|
24
|
+
function normPath(p, platform) {
|
|
25
|
+
if (typeof p !== 'string' || !p) return ''
|
|
26
|
+
let s = p.replace(/\\/g, '/').replace(/\/+$/, '')
|
|
27
|
+
if (s === '') s = '/'
|
|
28
|
+
if (platform === 'win32') s = s.toLowerCase()
|
|
29
|
+
return s
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 两个路径是否指向同一工作区目录(字符串规范化比较)。 */
|
|
33
|
+
export function sameWorkspacePath(a, b, platform = process.platform) {
|
|
34
|
+
const na = normPath(a, platform)
|
|
35
|
+
const nb = normPath(b, platform)
|
|
36
|
+
return na !== '' && na === nb
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 在已存在工作区里找 path 与 cwd 匹配的那一个;没有则 undefined(不新建)。 */
|
|
40
|
+
export function findWorkspaceByCwd(workspaces, cwd, platform = process.platform) {
|
|
41
|
+
if (!Array.isArray(workspaces) || typeof cwd !== 'string' || !cwd) return undefined
|
|
42
|
+
return workspaces.find((w) => w && sameWorkspacePath(w.path, cwd, platform))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 把会话登记进 cwd 匹配的已存在工作区。best-effort:无匹配/无服务/登记失败都返回
|
|
47
|
+
* false 而不抛错(调用方不应因登记失败而失败)。已是成员则幂等返回 true。
|
|
48
|
+
*/
|
|
49
|
+
export async function attachSessionByCwd(workspaceRegistry, sessionId, cwd, platform = process.platform) {
|
|
50
|
+
try {
|
|
51
|
+
if (!workspaceRegistry || typeof workspaceRegistry.list !== 'function') return false
|
|
52
|
+
if (typeof sessionId !== 'string' || !sessionId) return false
|
|
53
|
+
const ws = findWorkspaceByCwd(workspaceRegistry.list(), cwd, platform)
|
|
54
|
+
if (!ws || typeof ws.attachSession !== 'function') return false
|
|
55
|
+
if (Array.isArray(ws.sessionIds) && ws.sessionIds.includes(sessionId)) return true
|
|
56
|
+
await ws.attachSession(sessionId)
|
|
57
|
+
return true
|
|
58
|
+
} catch {
|
|
59
|
+
return false
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 补登记:遍历宿主会话,把「运行中(live)、非子代理、未被任何工作区认领、cwd 匹配某
|
|
65
|
+
* 已存在工作区」的会话登记进去。返回 { attached, ready };依赖缺失时 ready=false
|
|
66
|
+
* (调用方可稍后重试)。list() 抛错(如 registry 尚未初始化)向上传播,由运行器捕获重试。
|
|
67
|
+
*
|
|
68
|
+
* handled(可选 Set):已处理过的会话 id。已在集合里的跳过;本次「已成功登记」或
|
|
69
|
+
* 「已被某工作区认领」的会话记入集合——日后用户手动移出也不重纳(尊重摆放)。冷会话、
|
|
70
|
+
* 无匹配工作区、登记失败的不记入,留待后续拍捕捉(冷转 live / 稍后新建工作区)。
|
|
71
|
+
* workspaceRegistry 可为对象或零参解析函数。
|
|
72
|
+
*/
|
|
73
|
+
export async function reconcileWorkspaceMembership({ listSessions, workspaceRegistry, handled, platform = process.platform } = {}) {
|
|
74
|
+
const registry = typeof workspaceRegistry === 'function' ? workspaceRegistry() : workspaceRegistry
|
|
75
|
+
if (typeof listSessions !== 'function' || !registry || typeof registry.list !== 'function') {
|
|
76
|
+
return { attached: [], ready: false }
|
|
77
|
+
}
|
|
78
|
+
const workspaces = registry.list()
|
|
79
|
+
const accounted = new Set()
|
|
80
|
+
for (const w of workspaces) {
|
|
81
|
+
for (const id of (w?.sessionIds ?? [])) accounted.add(id)
|
|
82
|
+
}
|
|
83
|
+
const records = await listSessions()
|
|
84
|
+
const items = Array.isArray(records) ? records : []
|
|
85
|
+
const attached = []
|
|
86
|
+
for (const record of items) {
|
|
87
|
+
const header = record?.header ?? record
|
|
88
|
+
const id = header?.id ?? header?.sessionId
|
|
89
|
+
if (typeof id !== 'string' || !id) continue
|
|
90
|
+
if (handled && handled.has(id)) continue // 已处理过 ⇒ 尊重用户摆放,不重纳
|
|
91
|
+
if (record?.live === false) continue // 只补登记运行中的(冷转 live 后再捕捉)
|
|
92
|
+
if (header?.origin === 'subagent') continue // 子代理嵌套展示,不占工作区成员
|
|
93
|
+
if (accounted.has(id)) { // 已被某工作区认领 ⇒ 尊重现有摆放
|
|
94
|
+
if (handled) handled.add(id)
|
|
95
|
+
continue
|
|
96
|
+
}
|
|
97
|
+
const cwd = header?.cwd
|
|
98
|
+
if (typeof cwd !== 'string' || !cwd) continue
|
|
99
|
+
const ok = await attachSessionByCwd(registry, id, cwd, platform)
|
|
100
|
+
if (ok) { attached.push(id); accounted.add(id); if (handled) handled.add(id) }
|
|
101
|
+
}
|
|
102
|
+
return { attached, ready: true }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 补登记运行器的重试间隔(与 session-watch 同口径)。 */
|
|
106
|
+
export const WORKSPACE_RECONCILE_INTERVAL_MS = 5000
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 周期补登记运行器:每 intervalMs 跑一次 reconcileWorkspaceMembership,持续到 stop()。
|
|
110
|
+
* 带 handled 集合:已登记/已认领的会话不再重纳(尊重用户手动移出);冷转 live、稍后
|
|
111
|
+
* 新建工作区的会话会在后续拍被捕捉。服务未就绪(ready=false)或抛错时静默重试。
|
|
112
|
+
* workspaceRegistry 可为对象或零参解析函数(懒解析,装配早于服务注册也不丢)。
|
|
113
|
+
*/
|
|
114
|
+
export function createWorkspaceReconcile({ listSessions, workspaceRegistry, intervalMs = WORKSPACE_RECONCILE_INTERVAL_MS, platform } = {}) {
|
|
115
|
+
if (typeof listSessions !== 'function') throw new Error('createWorkspaceReconcile 需要 listSessions 函数')
|
|
116
|
+
if (workspaceRegistry == null) throw new Error('createWorkspaceReconcile 需要 workspaceRegistry(对象或解析函数)')
|
|
117
|
+
let timer = null
|
|
118
|
+
let stopped = false
|
|
119
|
+
let busy = false
|
|
120
|
+
const handled = new Set()
|
|
121
|
+
|
|
122
|
+
async function tick() {
|
|
123
|
+
if (stopped || busy) return null
|
|
124
|
+
busy = true
|
|
125
|
+
try {
|
|
126
|
+
return await reconcileWorkspaceMembership({ listSessions, workspaceRegistry, handled, platform })
|
|
127
|
+
} catch {
|
|
128
|
+
return null // 服务未就绪等 ⇒ 下一拍重试
|
|
129
|
+
} finally {
|
|
130
|
+
busy = false
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function start() {
|
|
135
|
+
if (timer || stopped) return
|
|
136
|
+
void tick()
|
|
137
|
+
timer = setInterval(tick, intervalMs)
|
|
138
|
+
timer.unref?.()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function stop() {
|
|
142
|
+
stopped = true
|
|
143
|
+
if (timer) { clearInterval(timer); timer = null }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return { start, stop, tick, get handledCount() { return handled.size } }
|
|
147
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# @capyclaw/foundation
|
|
2
|
+
|
|
3
|
+
dsh 插件基石层:接口 ABI、插件加载器与内核服务 `ctx.os`。
|
|
4
|
+
|
|
5
|
+
应用插件不再写 `inject` / `apply` / provider 装配,只声明「我实现了哪个接口」:
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
import { createPlugin, skillProvider } from '@capyclaw/foundation/abi'
|
|
9
|
+
|
|
10
|
+
export const { name, inject, apply } = createPlugin({
|
|
11
|
+
name: 'canvas',
|
|
12
|
+
requires: ['canvas.runtime@^1'],
|
|
13
|
+
implements: [skillProvider({ skill: './skills/canvas' })],
|
|
14
|
+
}, import.meta.url)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## 四个入口
|
|
18
|
+
|
|
19
|
+
| 入口 | 内容 | 谁用 |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| `.` | Cordis 插件,产出 `ctx.os` | dsh profile |
|
|
22
|
+
| `./abi` | 描述符构建器、加载器、错误码、版本工具 | 应用插件 |
|
|
23
|
+
| `./kit` | plugin-kit 兼容导出,包含 Node/dsh 耦合,非纯函数库 | 兼容调用方 |
|
|
24
|
+
| `./runtime` | `createKernel` 等宿主 API | dsh 之外的宿主(独立技能服务、测试夹具) |
|
|
25
|
+
|
|
26
|
+
## 状态
|
|
27
|
+
|
|
28
|
+
- 包清单当前为 `0.1.6`;0.1.6 修的是「关掉插件再启用撞 E_DUP_PLUGIN」(disposer 未登记 + 失败
|
|
29
|
+
记录占名),详见下面的「生命周期」。
|
|
30
|
+
- 分层:应用插件 → ABI → 内核 → Host 适配器 → 本地 Node.js agent 运行时。
|
|
31
|
+
dsh 服务访问位于 Host 适配层;memory 只是参考实现,不证明第二个真实 agent 兼容。
|
|
32
|
+
HTTP/资源/进程仍有本地 Node 协议约束,详见 `docs/HOST-ADAPTER.md`。
|
|
33
|
+
- ABI v1,六个标准接口 + `host-event@1` + `client-panel@1` + `service-provider@1` +
|
|
34
|
+
`own-server@1` + 可执行 `raw@1`;基建插件使用 `defineDriver` 驱动入口。
|
|
35
|
+
- 能力表按 `ctx` 实际服务探测(见 `lib/kernel.mjs` 的 `detectCapabilities`),不做空头承诺。
|
|
36
|
+
- 当前仓库:27 个插件走标准接口,`raw@1` 当前为空,6 个基建插件走
|
|
37
|
+
`defineDriver` 驱动层;`meta/foundation.allowlist.json` 的模糊豁免为 0。
|
|
38
|
+
详见 `docs/POLICY.md` 与 `docs/spec/plugin-abi.md`。
|
|
39
|
+
|
|
40
|
+
设计规范见 `docs/spec/plugin-abi.md`,强制规则见 `docs/POLICY.md`。
|
|
41
|
+
|
|
42
|
+
## 生命周期(0.1.6 起)
|
|
43
|
+
|
|
44
|
+
`createPlugin().apply` 会把 `os.mount()` 的 disposer 通过 `ctx.effect(() => () => dispose())`
|
|
45
|
+
登记到本次激活的 ctx 上——**不能只靠 apply 的返回值**:Cordis 只认 `ctx.effect` 回调返回的
|
|
46
|
+
disposer,返回值不可靠。漏登记时,关掉插件后内核里的记录不会摘除,再次启用就会撞
|
|
47
|
+
`E_DUP_PLUGIN: 插件 xxx 已挂载`。
|
|
48
|
+
|
|
49
|
+
加载器侧另有两条兜底:`mount()` 遇到 `disposed` / `failed` 的旧记录会先摘掉并尽力回收;
|
|
50
|
+
`start` 失败清理完成后立即让出插件名。两者共同保证「关掉 → 再启用」可重复无数次。
|
|
51
|
+
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 资产引用契约的单一真源(公共 ABI 常量)。
|
|
3
|
+
*
|
|
4
|
+
* 互操作标准里资产有两副面孔,前缀在这里定义一次,内核门面与资产服务都引用它,
|
|
5
|
+
* 避免「路由实现」与「URL 门面」各写一份 '/assets/' 而漂移:
|
|
6
|
+
* - 字节仓 HTTP 路由前缀 ASSET_URL_PREFIX = '/assets/' (asset-service 挂 GET/HEAD)
|
|
7
|
+
* - 结构化正文里的引用前缀 ASSET_REF_PREFIX = '@asset/' (work-store 信封/正文只存引用)
|
|
8
|
+
*
|
|
9
|
+
* 这是契约常量,不是宿主服务名——放 ABI 层,应用与驱动都可 import。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** 资产字节仓的 HTTP 路由前缀(asset-service 实现,内核 os.assets.url 复用)。 */
|
|
13
|
+
export const ASSET_URL_PREFIX = '/assets/'
|
|
14
|
+
|
|
15
|
+
/** 结构化正文/产物信封里的内容寻址引用前缀(@asset/<sha256>)。 */
|
|
16
|
+
export const ASSET_REF_PREFIX = '@asset/'
|
|
17
|
+
|
|
18
|
+
/** 由资产 id 生成可加载 URL:/assets/<id>(id 做 URI 编码)。 */
|
|
19
|
+
export function assetUrl(id) {
|
|
20
|
+
return `${ASSET_URL_PREFIX}${encodeURIComponent(String(id))}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 由资产 id 生成规范引用:@asset/<id>。 */
|
|
24
|
+
export function assetRef(id) {
|
|
25
|
+
return `${ASSET_REF_PREFIX}${String(id)}`
|
|
26
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 桥(editor bridge)与文档模型的标准声明。
|
|
3
|
+
*
|
|
4
|
+
* 这一层只放「协议常量 + 声明校验」,不放运行时:
|
|
5
|
+
* - 常量:协议版本、模型版本、能力名(suite 清单与 healthz 都用它)
|
|
6
|
+
* - declareBridge():把工作台的声明冻结成标准形状
|
|
7
|
+
* - assertBridgeRuntime():启动/巡检时把「声明」与「运行时实际上报」对齐
|
|
8
|
+
*
|
|
9
|
+
* 运行时(relay / 队列 / 租约)仍在 @capyclaw/document-workbench + service-host,
|
|
10
|
+
* 不进 ABI 层:foundation 是所有插件的地基,不该背 HTTP/store 依赖。
|
|
11
|
+
*
|
|
12
|
+
* 能力名(与 suite 清单的 requires/provides.capabilities 对应):
|
|
13
|
+
* editor.bridge —— 插件提供一个编辑器权威桥(/healthz + /status + /watch + /ack)
|
|
14
|
+
* doc.model —— 插件提供文档模型(稳定 ID / 清单 / 定位 / 编辑计划 / 校验)
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { AbiError, ERROR_CODES } from './errors.mjs'
|
|
18
|
+
|
|
19
|
+
/** 桥协议版本:端点集合与状态机语义的主版本。不兼容变更才升 major。 */
|
|
20
|
+
export const BRIDGE_PROTOCOL_VERSION = '1.0.0'
|
|
21
|
+
|
|
22
|
+
/** 文档模型版本:清单字段、定位器语义、编辑 op 的主版本。 */
|
|
23
|
+
export const DOC_MODEL_VERSION = '1.0.0'
|
|
24
|
+
|
|
25
|
+
export const BRIDGE_CAPABILITY = 'editor.bridge'
|
|
26
|
+
export const DOC_MODEL_CAPABILITY = 'doc.model'
|
|
27
|
+
|
|
28
|
+
/** healthz 里桥声明的字段名(避免与既有的 bridge: '<name>' 字符串冲突)。 */
|
|
29
|
+
export const BRIDGE_INFO_FIELD = 'bridgeInfo'
|
|
30
|
+
|
|
31
|
+
const ID_RE = /^[a-z0-9][a-z0-9-]*$/
|
|
32
|
+
const VERSION_RE = /^\d+\.\d+\.\d+$/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 校验并冻结一份桥声明。
|
|
36
|
+
* @param {{ id: string, protocol?: string, model?: string|null, editor?: 'required'|'optional' }} input
|
|
37
|
+
*/
|
|
38
|
+
export function declareBridge(input = {}) {
|
|
39
|
+
const { id, protocol = BRIDGE_PROTOCOL_VERSION, model = null, editor = 'required' } = input
|
|
40
|
+
const errors = []
|
|
41
|
+
if (typeof id !== 'string' || !ID_RE.test(id)) errors.push(`id 必须是 kebab-case:${id}`)
|
|
42
|
+
if (!VERSION_RE.test(protocol)) errors.push(`protocol 版本非法:${protocol}`)
|
|
43
|
+
if (model !== null && !VERSION_RE.test(model)) errors.push(`model 版本非法:${model}`)
|
|
44
|
+
if (editor !== 'required' && editor !== 'optional') errors.push(`editor 只能是 required/optional:${editor}`)
|
|
45
|
+
if (errors.length) throw new AbiError(ERROR_CODES.E_SCHEMA, `桥声明非法:${errors.join(';')}`, { errors })
|
|
46
|
+
return Object.freeze({ id, protocol, model, editor })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 桥声明 → suite 清单里的 provides.capabilities。 */
|
|
50
|
+
export function bridgeCapabilities(declaration) {
|
|
51
|
+
const decl = declaration && declaration.protocol ? declaration : declareBridge(declaration)
|
|
52
|
+
return Object.freeze({
|
|
53
|
+
[BRIDGE_CAPABILITY]: decl.protocol,
|
|
54
|
+
...(decl.model ? { [DOC_MODEL_CAPABILITY]: decl.model } : {}),
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 桥声明 → suite 清单里工具面对运行时的 requires.capabilities(skill 包用)。 */
|
|
59
|
+
export function bridgeConsumerRequirements(ns, { needsModel = false } = {}) {
|
|
60
|
+
const out = { [`${ns}.runtime`]: `^${BRIDGE_PROTOCOL_VERSION}` }
|
|
61
|
+
if (needsModel) out[DOC_MODEL_CAPABILITY] = `^${DOC_MODEL_VERSION}`
|
|
62
|
+
return Object.freeze(out)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 声明与运行时对账:启动或巡检时调用。
|
|
67
|
+
*
|
|
68
|
+
* @param {object} declaration declareBridge 的结果(来自插件代码/清单)
|
|
69
|
+
* @param {object} runtime healthz 里的 bridgeInfo(实际运行值)
|
|
70
|
+
* @returns {{ ok: boolean, issues: string[] }}
|
|
71
|
+
*/
|
|
72
|
+
export function assertBridgeRuntime(declaration, runtime) {
|
|
73
|
+
const issues = []
|
|
74
|
+
const decl = declaration && declaration.id ? declaration : declareBridge(declaration || {})
|
|
75
|
+
if (!runtime || typeof runtime !== 'object') {
|
|
76
|
+
return { ok: false, issues: [`运行时没有上报 ${BRIDGE_INFO_FIELD}`] }
|
|
77
|
+
}
|
|
78
|
+
if (runtime.id !== decl.id) issues.push(`id 不一致:声明 ${decl.id} / 运行 ${runtime.id}`)
|
|
79
|
+
if (runtime.protocol !== decl.protocol) {
|
|
80
|
+
issues.push(`协议版本不一致:声明 ${decl.protocol} / 运行 ${runtime.protocol}`)
|
|
81
|
+
}
|
|
82
|
+
const declaredModel = decl.model || null
|
|
83
|
+
const runtimeModel = runtime.model || null
|
|
84
|
+
if (declaredModel !== runtimeModel) {
|
|
85
|
+
issues.push(`模型版本不一致:声明 ${declaredModel || '无'} / 运行 ${runtimeModel || '无'}`)
|
|
86
|
+
}
|
|
87
|
+
return { ok: issues.length === 0, issues }
|
|
88
|
+
}
|