dsh-learn-mode 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/client.js +452 -0
- package/cordis.patch.yml +111 -0
- package/index.js +19 -0
- package/package.json +42 -6
- package/skills/dsh-learn-mode/SKILL.md +190 -0
- package/skills/learn-synthesizer/SKILL.md +278 -0
- package/skills/learn-synthesizer/analysis/workspace-file-convention.md +402 -0
- package/skills/learn-synthesizer/evals/evals.json +72 -0
- package/skills/learn-synthesizer/references/axis-types.md +20 -0
- package/skills/learn-synthesizer/references/example-structures.md +291 -0
- package/skills/learn-synthesizer/references/feedback-types.md +296 -0
- package/skills/learn-synthesizer/references/gotchas.md +322 -0
- package/skills/learn-synthesizer/references/sub-agent-prompt.md +222 -0
- package/skills/learn-synthesizer/rules/core-principles.md +173 -0
- package/skills/learn-synthesizer/rules/output-format.md +355 -0
- package/skills/learn-synthesizer/rules/quality-gates.md +209 -0
- package/skills/learn-synthesizer/scripts/pdf_to_md.py +124 -0
- package/skills/learn-synthesizer/templates/MISSION.md +38 -0
- package/skills/learn-synthesizer/templates/deep-dive.md +73 -0
- package/skills/learn-synthesizer/templates/map-evolution.md +38 -0
- package/skills/learn-synthesizer/templates/understanding-map.md +42 -0
- package/skills/learn-synthesizer/workflows/stage0.5-mission.md +141 -0
- package/skills/learn-synthesizer/workflows/stage1-collect.md +214 -0
- package/skills/learn-synthesizer/workflows/stage2-extract.md +254 -0
- package/skills/learn-synthesizer/workflows/stage2.5-importance.md +197 -0
- package/skills/learn-synthesizer/workflows/stage3-merge.md +492 -0
- package/skills/learn-synthesizer/workflows/stage3.5-gap.md +317 -0
- package/skills/learn-synthesizer/workflows/stage4-chapter-agent.md +342 -0
- package/skills/learn-synthesizer/workflows/stage4-ref-extract.md +111 -0
- package/skills/learn-synthesizer/workflows/stage4-write.md +355 -0
- package/skills/learn-synthesizer/workflows/stage4.5-verify.md +327 -0
- package/skills/learn-synthesizer/workflows/stage5-review.md +196 -0
- package/skills/learn-synthesizer/workflows/stage5.5-iterate.md +297 -0
- package/skills/learn-synthesizer/workflows/stage6-finalize.md +310 -0
- package/skills/learn-synthesizer/workflows/stage6-progressive.md +173 -0
- package/skills-provider.mjs +99 -0
- package/workbench-host.mjs +425 -0
- package/README.md +0 -3
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 学习工作台 Host 侧:只读资源路由 + present 信号读取。
|
|
3
|
+
*
|
|
4
|
+
* 设计约束(见 changes/0012-study-workbench.md 与 decisions/0008-host-security.md):
|
|
5
|
+
* - 一切文件读取走宿主 workspaceFiles 服务,继承平台的会话作用域与围栏;
|
|
6
|
+
* - 本插件另加扩展名白名单、拒绝绝对路径/`..`/NUL、单文件 ≤ 2MB;
|
|
7
|
+
* - 只用 node 内置模块,零第三方依赖。
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from 'node:crypto'
|
|
10
|
+
import { realpath } from 'node:fs/promises'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
|
|
13
|
+
const ALLOWED_EXT = new Set([
|
|
14
|
+
'.md', '.markdown', '.txt',
|
|
15
|
+
'.html', '.htm',
|
|
16
|
+
'.png', '.jpg', '.jpeg', '.svg', '.webp',
|
|
17
|
+
])
|
|
18
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024
|
|
19
|
+
const MIME = {
|
|
20
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
21
|
+
'.markdown': 'text/markdown; charset=utf-8',
|
|
22
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
23
|
+
'.html': 'text/html; charset=utf-8',
|
|
24
|
+
'.htm': 'text/html; charset=utf-8',
|
|
25
|
+
'.png': 'image/png',
|
|
26
|
+
'.jpg': 'image/jpeg',
|
|
27
|
+
'.jpeg': 'image/jpeg',
|
|
28
|
+
'.svg': 'image/svg+xml',
|
|
29
|
+
'.webp': 'image/webp',
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 归一化 HTML 白名单:只有「相对路径 + 内容哈希」同时匹配才授权交互档。
|
|
34
|
+
* @param {unknown} raw
|
|
35
|
+
* @returns {Array<{ path: string, hash: string }>}
|
|
36
|
+
*/
|
|
37
|
+
export function normalizeHtmlWhitelist(raw) {
|
|
38
|
+
if (!Array.isArray(raw)) return []
|
|
39
|
+
const out = []
|
|
40
|
+
for (const entry of raw) {
|
|
41
|
+
if (entry === null || typeof entry !== 'object') continue
|
|
42
|
+
const rel = typeof entry.path === 'string' ? entry.path.replace(/\\/gu, '/').replace(/^\.\//u, '') : ''
|
|
43
|
+
const hash = typeof entry.hash === 'string' ? entry.hash.trim().toLowerCase() : ''
|
|
44
|
+
if (rel === '' || !/^sha256:[0-9a-f]{64}$/u.test(hash)) continue
|
|
45
|
+
out.push({ path: rel, hash })
|
|
46
|
+
}
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 读取白名单:只信任插件 config,不读取 agent 可写目录。
|
|
52
|
+
* @param {object} config
|
|
53
|
+
* @returns {Array<{ path: string, hash: string }>}
|
|
54
|
+
*/
|
|
55
|
+
function loadHtmlWhitelist(config) {
|
|
56
|
+
return normalizeHtmlWhitelist(config?.htmlWhitelist)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const BASE_CSP = "default-src 'none'; img-src data: blob:; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'"
|
|
60
|
+
|
|
61
|
+
/** HTML/SVG 响应头 CSP:静态档额外 sandbox;交互档只放 allow-scripts。 */
|
|
62
|
+
function documentCsp(mode) {
|
|
63
|
+
return mode === 'interactive'
|
|
64
|
+
? BASE_CSP + "; script-src 'unsafe-inline'; sandbox allow-scripts"
|
|
65
|
+
: BASE_CSP + '; sandbox'
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 决定 HTML 的渲染档位:白名单命中且哈希一致才 interactive,否则一律 static。
|
|
70
|
+
* @param {Array<{ path: string, hash: string }>} whitelist
|
|
71
|
+
* @param {string[]} candidates 相对路径候选(rel 与 full)
|
|
72
|
+
* @param {string} actualHash
|
|
73
|
+
* @returns {'static'|'interactive'}
|
|
74
|
+
*/
|
|
75
|
+
export function resolveHtmlMode(whitelist, candidates, actualHash) {
|
|
76
|
+
const wanted = String(actualHash).toLowerCase()
|
|
77
|
+
for (const entry of whitelist) {
|
|
78
|
+
if (!candidates.includes(entry.path)) continue
|
|
79
|
+
if (entry.hash === wanted) return 'interactive'
|
|
80
|
+
}
|
|
81
|
+
return 'static'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 校验学科名:不允许路径分隔符、`..`、NUL 或超长。
|
|
86
|
+
* @param {string} subject
|
|
87
|
+
* @returns {string}
|
|
88
|
+
*/
|
|
89
|
+
export function validateSubjectName(subject) {
|
|
90
|
+
if (typeof subject !== 'string' || subject.length === 0 || subject.length > 120) {
|
|
91
|
+
throw new WorkbenchError('workbench/bad-subject', 'subject must be a non-empty string of at most 120 chars')
|
|
92
|
+
}
|
|
93
|
+
if (subject.includes('\0') || subject.includes('/') || subject.includes('\\') || subject.split(/[\\/]+/u).includes('..')) {
|
|
94
|
+
throw new WorkbenchError('workbench/bad-subject', 'invalid subject name')
|
|
95
|
+
}
|
|
96
|
+
return subject
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
class WorkbenchError extends Error {
|
|
100
|
+
constructor(code, message, status = 400) {
|
|
101
|
+
super(message)
|
|
102
|
+
this.code = code
|
|
103
|
+
this.status = status
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 校验并归一化工作台内的相对路径。
|
|
109
|
+
* @param {string} rel
|
|
110
|
+
* @returns {string} 以 `/` 分隔、去掉前导 `./` 的相对路径
|
|
111
|
+
*/
|
|
112
|
+
export function validateRelativePath(rel) {
|
|
113
|
+
if (typeof rel !== 'string' || rel.length === 0 || rel.length > 400) {
|
|
114
|
+
throw new WorkbenchError('workbench/bad-path', 'path must be a non-empty string of at most 400 chars')
|
|
115
|
+
}
|
|
116
|
+
if (rel.includes('\0')) throw new WorkbenchError('workbench/bad-path', 'path contains NUL')
|
|
117
|
+
if (/^[a-zA-Z]:/.test(rel) || rel.startsWith('/') || rel.startsWith('\\')) {
|
|
118
|
+
throw new WorkbenchError('workbench/bad-path', 'absolute paths are rejected')
|
|
119
|
+
}
|
|
120
|
+
const segments = rel.split(/[\\/]+/u)
|
|
121
|
+
if (segments.some((s) => s === '..')) throw new WorkbenchError('workbench/bad-path', 'path traversal is rejected')
|
|
122
|
+
const ext = path.extname(rel).toLowerCase()
|
|
123
|
+
if (!ALLOWED_EXT.has(ext)) {
|
|
124
|
+
throw new WorkbenchError('workbench/type-not-allowed', `extension not allowed: ${ext || '(none)'}`, 415)
|
|
125
|
+
}
|
|
126
|
+
return rel.replace(/\\/gu, '/').replace(/^\.\//u, '')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function sessionRoot(ctx, sessionId) {
|
|
130
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
131
|
+
throw new WorkbenchError('workbench/bad-session', 'session is required')
|
|
132
|
+
}
|
|
133
|
+
const header = ctx.sessions?.get?.(sessionId)?.header
|
|
134
|
+
if (header === undefined || header === null) {
|
|
135
|
+
throw new WorkbenchError('workbench/unknown-session', `unknown session: ${sessionId}`, 404)
|
|
136
|
+
}
|
|
137
|
+
if (typeof header.cwd !== 'string' || header.cwd.length === 0) {
|
|
138
|
+
throw new WorkbenchError('workbench/no-workspace', `session ${sessionId} has no workspace`, 409)
|
|
139
|
+
}
|
|
140
|
+
return header.cwd
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function scopeOf(sessionId, root) {
|
|
144
|
+
return { sessionId, workspaceRoot: root }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 符号链接解析后仍须位于会话根内,否则视为不可读。 */
|
|
148
|
+
async function insideRoot(root, absolute) {
|
|
149
|
+
const rootReal = await realpath(root)
|
|
150
|
+
let fileReal
|
|
151
|
+
try {
|
|
152
|
+
fileReal = await realpath(absolute)
|
|
153
|
+
} catch {
|
|
154
|
+
// 目标不存在时交给读取层报 not-found;只有解析成功却指向根外才视为逃逸。
|
|
155
|
+
return true
|
|
156
|
+
}
|
|
157
|
+
return fileReal === rootReal || fileReal.startsWith(rootReal + path.sep)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function readRoadmap(ctx, scope, root, subject) {
|
|
161
|
+
const candidates = []
|
|
162
|
+
if (typeof subject === 'string' && subject.length > 0) {
|
|
163
|
+
validateSubjectName(subject)
|
|
164
|
+
candidates.push(`subjects/${subject}/roadmap.json`)
|
|
165
|
+
}
|
|
166
|
+
candidates.push('roadmap.json')
|
|
167
|
+
for (const candidate of candidates) {
|
|
168
|
+
const absolute = path.resolve(root, candidate)
|
|
169
|
+
if (!(await insideRoot(root, absolute))) {
|
|
170
|
+
throw new WorkbenchError('workbench/bad-roadmap', 'roadmap path escapes the workspace', 403)
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const page = await ctx.workspaceFiles.read(scope, absolute, { limit: 5000 })
|
|
174
|
+
return { roadmap: JSON.parse(page.text), roadmapPath: root }
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (candidate === candidates[candidates.length - 1]) {
|
|
177
|
+
throw new WorkbenchError('workbench/missing-roadmap', `roadmap.json not found (${error?.code ?? error?.message ?? error})`, 404)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
throw new WorkbenchError('workbench/missing-roadmap', 'roadmap.json not found', 404)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function contentBase(roadmapPath, subject) {
|
|
185
|
+
return roadmapPath === null ? '' : ''
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function buildManifest(ctx, scope, root, roadmap, subject, nodeId) {
|
|
189
|
+
const nodes = Array.isArray(roadmap.nodes) ? roadmap.nodes : []
|
|
190
|
+
const baseDir = typeof subject === 'string' && subject.length > 0 ? `subjects/${subject}` : ''
|
|
191
|
+
const items = []
|
|
192
|
+
const wantsNode = nodeId !== undefined && nodeId !== null && nodeId !== ''
|
|
193
|
+
const selected = wantsNode
|
|
194
|
+
? nodes.find((node) => node?.id === nodeId)
|
|
195
|
+
: nodes.find((node) => Array.isArray(node?.content) && node.content.length > 0) || nodes[0]
|
|
196
|
+
const contentOf = (node) => {
|
|
197
|
+
const raw = node?.content
|
|
198
|
+
if (raw === undefined) return []
|
|
199
|
+
if (!Array.isArray(raw)) throw new WorkbenchError('workbench/bad-roadmap', `node ${node?.id} content must be an array`)
|
|
200
|
+
return raw
|
|
201
|
+
}
|
|
202
|
+
const target = contentOf(selected)
|
|
203
|
+
for (const entry of target) {
|
|
204
|
+
const rel = validateRelativePath(entry)
|
|
205
|
+
const full = baseDir === '' ? rel : `${baseDir}/${rel}`
|
|
206
|
+
let stat
|
|
207
|
+
try {
|
|
208
|
+
stat = await ctx.workspaceFiles.stat(scope, path.resolve(root, full))
|
|
209
|
+
} catch {
|
|
210
|
+
items.push({ path: rel, full, exists: false, size: 0 })
|
|
211
|
+
continue
|
|
212
|
+
}
|
|
213
|
+
items.push({ path: rel, full, exists: true, size: stat.bytes ?? 0, type: 'file' })
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
subject: roadmap.subject ?? subject ?? null,
|
|
217
|
+
subjectDir: typeof subject === 'string' && subject.length > 0 ? subject : null,
|
|
218
|
+
node: selected === undefined ? null : { id: selected.id, title: selected.title, type: selected.type, status: selected.status },
|
|
219
|
+
items,
|
|
220
|
+
nodes: nodes.map((node) => ({
|
|
221
|
+
id: node?.id,
|
|
222
|
+
title: node?.title,
|
|
223
|
+
type: node?.type,
|
|
224
|
+
status: node?.status,
|
|
225
|
+
hasContent: Array.isArray(node?.content) && node.content.length > 0,
|
|
226
|
+
})),
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function sendJson(res, status, payload) {
|
|
231
|
+
const body = JSON.stringify(payload)
|
|
232
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
233
|
+
res.end(body)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function readJsonBody(req) {
|
|
237
|
+
const chunks = []
|
|
238
|
+
let total = 0
|
|
239
|
+
for await (const chunk of req) {
|
|
240
|
+
total += chunk.length
|
|
241
|
+
if (total > 64 * 1024) throw new WorkbenchError('workbench/body-too-large', 'body too large', 413)
|
|
242
|
+
chunks.push(chunk)
|
|
243
|
+
}
|
|
244
|
+
if (total === 0) return {}
|
|
245
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function handleManifest(ctx, req, res, url) {
|
|
249
|
+
const sessionId = url.searchParams.get('session') ?? undefined
|
|
250
|
+
const subject = url.searchParams.get('subject') ?? undefined
|
|
251
|
+
const nodeId = url.searchParams.get('node') ?? undefined
|
|
252
|
+
const root = sessionRoot(ctx, sessionId)
|
|
253
|
+
const scope = scopeOf(sessionId, root)
|
|
254
|
+
const { roadmap } = await readRoadmap(ctx, scope, root, subject)
|
|
255
|
+
const manifest = await buildManifest(ctx, scope, root, roadmap, subject, nodeId)
|
|
256
|
+
sendJson(res, 200, manifest)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function handleFile(ctx, req, res, url, config = {}) {
|
|
260
|
+
const sessionId = url.searchParams.get('session') ?? undefined
|
|
261
|
+
const subject = url.searchParams.get('subject') ?? undefined
|
|
262
|
+
const rel = validateRelativePath(url.searchParams.get('path') ?? '')
|
|
263
|
+
const root = sessionRoot(ctx, sessionId)
|
|
264
|
+
const scope = scopeOf(sessionId, root)
|
|
265
|
+
const baseDir = typeof subject === 'string' && subject.length > 0 ? `subjects/${validateSubjectName(subject)}` : ''
|
|
266
|
+
const full = baseDir === '' || rel.startsWith(baseDir + '/') ? rel : `${baseDir}/${rel}`
|
|
267
|
+
// 客户端可能传相对路径,也可能传带学科前缀的 full;白名单按学科内相对路径登记,因此三种形态都作为候选。
|
|
268
|
+
const relFromSubject = baseDir !== '' && full.startsWith(baseDir + '/') ? full.slice(baseDir.length + 1) : full
|
|
269
|
+
let stat
|
|
270
|
+
try {
|
|
271
|
+
stat = await ctx.workspaceFiles.stat(scope, path.resolve(root, full))
|
|
272
|
+
} catch (cause) {
|
|
273
|
+
const code = cause && typeof cause === 'object' ? cause.code : undefined
|
|
274
|
+
if (code === 'workspace-file/not-found' || code === 'ENOENT') throw new WorkbenchError('workbench/not-found', `no entry at ${rel}`, 404)
|
|
275
|
+
throw new WorkbenchError('workbench/read-failed', `cannot stat ${rel}`, 500)
|
|
276
|
+
}
|
|
277
|
+
if (typeof stat.bytes !== 'number') throw new WorkbenchError('workbench/not-file', `not a regular file: ${rel}`, 415)
|
|
278
|
+
if (stat.bytes > MAX_FILE_BYTES) throw new WorkbenchError('workbench/too-large', `file exceeds ${MAX_FILE_BYTES} bytes`, 413)
|
|
279
|
+
// 真实路径围栏:符号链接解析后必须仍在会话工作区内
|
|
280
|
+
const rootReal = await realpath(root)
|
|
281
|
+
const fileReal = await realpath(path.resolve(root, full))
|
|
282
|
+
if (fileReal !== rootReal && !fileReal.startsWith(rootReal + path.sep)) {
|
|
283
|
+
throw new WorkbenchError('workbench/outside-workspace', 'resolved path escapes the workspace', 403)
|
|
284
|
+
}
|
|
285
|
+
let bytes
|
|
286
|
+
try {
|
|
287
|
+
bytes = await ctx.workspaceFiles.readBytes(scope, path.resolve(root, full), {})
|
|
288
|
+
} catch (cause) {
|
|
289
|
+
const code = cause && typeof cause === 'object' ? cause.code : undefined
|
|
290
|
+
if (code === 'workspace-file/not-found') throw new WorkbenchError('workbench/not-found', `no entry at ${rel}`, 404)
|
|
291
|
+
if (code === 'workspace-file/too-large') throw new WorkbenchError('workbench/too-large', `file exceeds ${MAX_FILE_BYTES} bytes`, 413)
|
|
292
|
+
if (code === 'workspace-file/not-text') throw new WorkbenchError('workbench/type-not-allowed', `not a text file: ${rel}`, 415)
|
|
293
|
+
throw cause
|
|
294
|
+
}
|
|
295
|
+
const data = bytes.data
|
|
296
|
+
const hash = `sha256:${createHash('sha256').update(data).digest('hex')}`
|
|
297
|
+
const mime = MIME[path.extname(rel).toLowerCase()] ?? 'application/octet-stream'
|
|
298
|
+
const headers = {
|
|
299
|
+
'content-type': mime,
|
|
300
|
+
'cache-control': 'no-store',
|
|
301
|
+
'x-content-type-options': 'nosniff',
|
|
302
|
+
'referrer-policy': 'no-referrer',
|
|
303
|
+
'x-study-hash': hash,
|
|
304
|
+
'content-length': data.length,
|
|
305
|
+
}
|
|
306
|
+
if (mime.indexOf('text/html') === 0 || mime === 'image/svg+xml') {
|
|
307
|
+
const whitelist = loadHtmlWhitelist(config)
|
|
308
|
+
const mode = mime.indexOf('text/html') === 0 ? resolveHtmlMode(whitelist, [rel, full, relFromSubject], hash) : 'static'
|
|
309
|
+
headers['x-study-html-mode'] = mode
|
|
310
|
+
headers['content-security-policy'] = documentCsp(mode)
|
|
311
|
+
}
|
|
312
|
+
res.writeHead(200, headers)
|
|
313
|
+
res.end(data)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function handlePresent(ctx, req, res, url) {
|
|
317
|
+
if (req.method === 'POST') {
|
|
318
|
+
const body = await readJsonBody(req)
|
|
319
|
+
const sessionId = body.session
|
|
320
|
+
if (typeof sessionId !== 'string') throw new WorkbenchError('workbench/bad-session', 'session is required')
|
|
321
|
+
if (ctx.sessions?.get?.(sessionId) === undefined) throw new WorkbenchError('workbench/unknown-session', `unknown session: ${sessionId}`, 404)
|
|
322
|
+
present.set(sessionId, { subject: body.subject ?? null, node: body.node ?? null, at: body.at ?? new Date().toISOString() })
|
|
323
|
+
while (present.size > 200) present.delete(present.keys().next().value)
|
|
324
|
+
lastPresent = present.get(sessionId)
|
|
325
|
+
sendJson(res, 200, { ok: true })
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
const sessionId = url.searchParams.get('session') ?? undefined
|
|
329
|
+
if (typeof sessionId !== 'string') {
|
|
330
|
+
const scanned = await scanPresentFiles(ctx)
|
|
331
|
+
if (lastPresent !== null && (scanned === null || String(lastPresent.at ?? '') >= String(scanned.at ?? ''))) {
|
|
332
|
+
sendJson(res, 200, lastPresent)
|
|
333
|
+
return
|
|
334
|
+
}
|
|
335
|
+
sendJson(res, 200, scanned)
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
const memory = present.get(sessionId)
|
|
339
|
+
if (memory !== undefined) {
|
|
340
|
+
sendJson(res, 200, memory)
|
|
341
|
+
return
|
|
342
|
+
}
|
|
343
|
+
const fromFile = await readPresentFile(ctx, sessionId)
|
|
344
|
+
sendJson(res, 200, fromFile)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* 扫描所有活动会话的学习根 present 文件,返回 `at` 最新的一条。
|
|
349
|
+
* 客户端在页签尚未打开、拿不到 sessionId 时依赖本函数自动展开。
|
|
350
|
+
* @returns {Promise<object|null>}
|
|
351
|
+
*/
|
|
352
|
+
async function scanPresentFiles(ctx) {
|
|
353
|
+
let sessions = []
|
|
354
|
+
try {
|
|
355
|
+
sessions = typeof ctx.sessions?.list === 'function' ? ctx.sessions.list() : []
|
|
356
|
+
} catch {
|
|
357
|
+
return null
|
|
358
|
+
}
|
|
359
|
+
let best = null
|
|
360
|
+
for (const session of sessions) {
|
|
361
|
+
const id = typeof session?.id === 'string' ? session.id : undefined
|
|
362
|
+
if (id === undefined) continue
|
|
363
|
+
const candidate = await readPresentFile(ctx, id)
|
|
364
|
+
if (candidate === null) continue
|
|
365
|
+
if (best === null || String(candidate.at ?? '') > String(best.at ?? '')) best = candidate
|
|
366
|
+
}
|
|
367
|
+
return best
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* 读取学习根下的 `_internal/workbench/present.json`。
|
|
372
|
+
* skill 侧只写文件、不调 HTTP,Host 在内存信号缺失时回落到该文件。
|
|
373
|
+
* @returns {Promise<{subject: string|null, node: string|null, at: string|null, source: 'file'}|null>}
|
|
374
|
+
*/
|
|
375
|
+
async function readPresentFile(ctx, sessionId) {
|
|
376
|
+
let root
|
|
377
|
+
try {
|
|
378
|
+
root = sessionRoot(ctx, sessionId)
|
|
379
|
+
} catch {
|
|
380
|
+
return null
|
|
381
|
+
}
|
|
382
|
+
try {
|
|
383
|
+
const absolute = path.resolve(root, '_internal/workbench/present.json')
|
|
384
|
+
if (!(await insideRoot(root, absolute))) return null
|
|
385
|
+
const page = await ctx.workspaceFiles.read(scopeOf(sessionId, root), absolute, { offset: 1 })
|
|
386
|
+
const parsed = JSON.parse(page.text)
|
|
387
|
+
if (parsed === null || typeof parsed !== 'object') return null
|
|
388
|
+
return {
|
|
389
|
+
subject: typeof parsed.subject === 'string' ? parsed.subject : null,
|
|
390
|
+
node: typeof parsed.node === 'string' ? parsed.node : null,
|
|
391
|
+
at: typeof parsed.at === 'string' ? parsed.at : null,
|
|
392
|
+
source: 'file',
|
|
393
|
+
}
|
|
394
|
+
} catch (error) {
|
|
395
|
+
if (process.env.STUDY_WORKBENCH_DEBUG === '1') {
|
|
396
|
+
console.error('[study-workbench] present.json read failed:', error?.code ?? '', error?.message ?? error)
|
|
397
|
+
}
|
|
398
|
+
return null
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const present = new Map()
|
|
403
|
+
let lastPresent = null
|
|
404
|
+
|
|
405
|
+
/** 注册工作台 Host 路由;由 index.mjs 在 webServer/workspaceFiles/sessions 就绪后调用。 */
|
|
406
|
+
export function registerWorkbench(ctx, config = {}) {
|
|
407
|
+
const wrap = (handler) => async (req, res) => {
|
|
408
|
+
try {
|
|
409
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
410
|
+
await handler(ctx, req, res, url, config)
|
|
411
|
+
} catch (error) {
|
|
412
|
+
const status = error instanceof WorkbenchError ? error.status : 500
|
|
413
|
+
if (status >= 500) console.error('[study-workbench]', error)
|
|
414
|
+
if (!res.headersSent) {
|
|
415
|
+
sendJson(res, status, error instanceof WorkbenchError
|
|
416
|
+
? { error: error.code, message: error.message }
|
|
417
|
+
: { error: 'workbench/internal', message: 'internal error' })
|
|
418
|
+
} else res.end()
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
ctx.webServer.register({ kind: 'exact', path: '/study-workbench/manifest', handler: wrap(handleManifest) })
|
|
422
|
+
ctx.webServer.register({ kind: 'exact', path: '/study-workbench/file', handler: wrap(handleFile) })
|
|
423
|
+
ctx.webServer.register({ kind: 'exact', path: '/study-workbench/present', handler: wrap(handlePresent) })
|
|
424
|
+
ctx.webServer.register({ kind: 'exact', path: '/study-workbench/present/latest', handler: wrap(handlePresent) })
|
|
425
|
+
}
|
package/README.md
DELETED