clearai-dsh 0.5.7 → 0.5.9
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/CHANGELOG.md +32 -0
- package/README.md +35 -19
- package/README.zh-CN.md +33 -17
- package/lib/client.js +506 -130
- package/lib/fold.js +60 -15
- package/lib/host.js +13 -0
- package/lib/research-events.d.ts +45 -0
- package/lib/research-events.js +138 -0
- package/package.json +7 -4
- package/presets/clearai/agent.cordis.yml +0 -3
- package/presets/clearai/clearai.patch.yml +0 -3
- package/presets/clearai/plugins/audit-evidence.js +31 -0
- package/presets/clearai/plugins/audit-material.js +32 -16
- package/presets/clearai/plugins/clearai-kernel.js +137 -128
- package/presets/clearai/plugins/integrity.js +70 -0
- package/presets/clearai/plugins/prompts.js +4 -2
- package/presets/clearai/plugins/rerun-copy.js +41 -0
- package/presets/clearai/plugins/tool-argument-stream.js +32 -0
- package/presets/clearai/plugins/workspace-path.js +23 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import { contentDigest } from './audit-material.js'
|
|
6
|
+
import { workspacePath } from './workspace-path.js'
|
|
7
|
+
|
|
8
|
+
export const protectedMaterial = path => /^clear\/(?:evidence|goals|knowledge\/(?:facts|lessons|negatives))\//.test(path) && !path.endsWith('/INDEX.md')
|
|
9
|
+
|
|
10
|
+
// Host-side receipts detect changes at trust boundaries. This is deliberately
|
|
11
|
+
// not a sandbox: a process with access to DSH_HOME can alter this store too.
|
|
12
|
+
export function integrityStore(cwd, home = process.env.DSH_HOME || join(homedir(), '.dsh')) {
|
|
13
|
+
const root = realpathSync(cwd)
|
|
14
|
+
const directory = join(home, 'storages', 'clearai-integrity', contentDigest(root))
|
|
15
|
+
const receiptFile = join(directory, 'receipts.json')
|
|
16
|
+
const read = () => {
|
|
17
|
+
if (!existsSync(receiptFile)) return { version: 1, workspace: root, files: {} }
|
|
18
|
+
const data = JSON.parse(readFileSync(receiptFile, 'utf8'))
|
|
19
|
+
if (data.version !== 1 || data.workspace !== root || !data.files) throw new Error('integrity-store-invalid')
|
|
20
|
+
return data
|
|
21
|
+
}
|
|
22
|
+
const inspect = (path, receipt) => {
|
|
23
|
+
const file = resolve(root, path)
|
|
24
|
+
try {
|
|
25
|
+
const checked = workspacePath(root, path, { mustExist: true })
|
|
26
|
+
if (lstatSync(file).isSymbolicLink() || checked.relative !== path) return 'link-replaced'
|
|
27
|
+
if (!receipt) return 'unregistered'
|
|
28
|
+
return contentDigest(readFileSync(file)) === receipt.digest ? null : 'modified'
|
|
29
|
+
} catch { return existsSync(file) ? 'unreadable-or-outside' : receipt ? 'removed' : 'unregistered' }
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
check() {
|
|
33
|
+
const receipts = read().files, paths = new Set(Object.keys(receipts))
|
|
34
|
+
const walk = directory => {
|
|
35
|
+
if (!existsSync(directory)) return
|
|
36
|
+
if (lstatSync(directory).isSymbolicLink()) { paths.add(relative(root, directory).replaceAll('\\', '/') + '/'); return }
|
|
37
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
38
|
+
const file = join(directory, entry.name)
|
|
39
|
+
if (entry.isDirectory()) walk(file)
|
|
40
|
+
else paths.add(relative(root, file).replaceAll('\\', '/'))
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
for (const dir of ['evidence', 'goals', 'knowledge/facts', 'knowledge/lessons', 'knowledge/negatives']) walk(join(root, 'clear', dir))
|
|
44
|
+
return [...paths].filter(protectedMaterial).sort().flatMap(path => { const code = inspect(path, receipts[path]); return code ? [{ path, code, expected: receipts[path]?.digest ?? null }] : [] })
|
|
45
|
+
},
|
|
46
|
+
write(path, content, origin) {
|
|
47
|
+
if (!origin?.session || !origin?.event) throw new Error('integrity-origin-required')
|
|
48
|
+
const target = workspacePath(root, path)
|
|
49
|
+
if (!protectedMaterial(target.relative)) throw new Error('integrity-path-not-protected')
|
|
50
|
+
mkdirSync(directory, { recursive: true })
|
|
51
|
+
const lock = join(directory, 'write.lock')
|
|
52
|
+
try { mkdirSync(lock) } catch { throw new Error('integrity-write-busy') }
|
|
53
|
+
try {
|
|
54
|
+
const data = read(), previous = data.files[target.relative]
|
|
55
|
+
const issue = inspect(target.relative, previous)
|
|
56
|
+
if (issue && (previous || existsSync(target.absolute))) throw new Error(`integrity-${issue}: ${target.relative}`)
|
|
57
|
+
const receipt = { digest: contentDigest(content), ...origin, revision: (previous?.revision ?? 0) + 1 }
|
|
58
|
+
mkdirSync(dirname(target.absolute), { recursive: true })
|
|
59
|
+
const temporary = target.absolute + '.' + randomUUID() + '.tmp'
|
|
60
|
+
writeFileSync(temporary, content)
|
|
61
|
+
renameSync(temporary, target.absolute)
|
|
62
|
+
data.files[target.relative] = receipt
|
|
63
|
+
const staging = join(directory, randomUUID() + '.json')
|
|
64
|
+
writeFileSync(staging, JSON.stringify(data), { mode: 0o600 })
|
|
65
|
+
renameSync(staging, receiptFile)
|
|
66
|
+
return { path: target.relative, ...receipt }
|
|
67
|
+
} finally { rmSync(lock, { recursive: true, force: true }) }
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -77,13 +77,15 @@ Meet a problem → retrieve existing knowledge and check that it applies → pro
|
|
|
77
77
|
|
|
78
78
|
- 用人正在用的语言和人的词,不用机制名;代码、路径、报错原文照录。
|
|
79
79
|
- 汇报按这个顺序:结论 / 依据 / 尚未确定的事项 / 待您决策;写明排除了哪些可能、结论在什么范围内成立,能信到什么程度就说到什么程度。
|
|
80
|
-
-
|
|
80
|
+
- 在已有回复中简短说明会影响研究方向的发现、当前未验证的部分和下一步;有合理默认路径时说明后继续。只展示公开计划、证据与结果,不展示内部思维过程。提到文件写完整相对路径,如 \`@reports/summary.md\`。
|
|
81
|
+
- 用户补充要求时区分已收到、等待处理与已生效;只有实际提交修订后才说已生效。目标变化沿用现有目标修订流程,不能静默替换目标。最终回复收束为成果、依据、不确定性和研究/本体面板入口,避免重述整段历史。
|
|
81
82
|
- 需要人决定时用 \`ask_user_question\`:一次一题,带上猜想、依据和推荐;能自己查到的不问人。`,
|
|
82
83
|
en: `# Talking to people
|
|
83
84
|
|
|
84
85
|
- Use the person's language and words, not mechanism names; quote code, paths and error text verbatim.
|
|
85
86
|
- Report in this order: conclusion / basis / open points / decisions for the person; say which possibilities were ruled out and where the conclusion holds, and say exactly as much as can be trusted.
|
|
86
|
-
-
|
|
87
|
+
- In existing replies, briefly explain findings that change the research direction, what remains unverified, and the next step. State a reasonable default and continue. Show public plans, evidence and results, without exposing internal reasoning. Give files their full relative path, like \`@reports/summary.md\`.
|
|
88
|
+
- Distinguish receipt, pending handling and effective changes when the person adds a request; call it effective only after the revision commits. Use the existing goal revision process for goal changes. Close with outcomes, evidence, uncertainty and Research/Ontology panel entry points without repeating the full history.
|
|
87
89
|
- When a person needs to decide, use \`ask_user_question\`: one question at a time, with your guess, its basis and your recommendation; do not ask about what you can look up yourself.`,
|
|
88
90
|
},
|
|
89
91
|
},
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { cp, lstat, mkdir, realpath, readdir, rm } from 'node:fs/promises'
|
|
2
|
+
import { join, relative } from 'node:path'
|
|
3
|
+
import { workspacePath } from './workspace-path.js'
|
|
4
|
+
|
|
5
|
+
export const RERUN_EXCLUDED = new Set(['.clearai-reruns', '.git', 'node_modules', '.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', '.cache'])
|
|
6
|
+
const excluded = path => path.split(/[\\/]/).some(part => RERUN_EXCLUDED.has(part))
|
|
7
|
+
|
|
8
|
+
export async function createRerunCopy(cwd, target, { required = [], signal } = {}) {
|
|
9
|
+
const started = performance.now(), metrics = { files: 0, bytes: 0, elapsedMs: 0, status: 'copying' }
|
|
10
|
+
let created = false
|
|
11
|
+
try {
|
|
12
|
+
for (const path of required) {
|
|
13
|
+
const checked = workspacePath(cwd, path, { mustExist: true })
|
|
14
|
+
if (excluded(checked.relative)) throw new Error(`rerun-required-input-excluded: ${path}`)
|
|
15
|
+
}
|
|
16
|
+
signal?.throwIfAborted()
|
|
17
|
+
await mkdir(target, { recursive: false }); created = true
|
|
18
|
+
const root = await realpath(cwd)
|
|
19
|
+
const filter = async source => {
|
|
20
|
+
signal?.throwIfAborted()
|
|
21
|
+
const path = relative(root, source).replaceAll('\\', '/')
|
|
22
|
+
if (excluded(path)) return false
|
|
23
|
+
const stat = await lstat(source)
|
|
24
|
+
if (stat.isSymbolicLink()) throw new Error(`rerun-symlink-not-supported: ${path}`)
|
|
25
|
+
if (stat.isFile()) { metrics.files++; metrics.bytes += stat.size }
|
|
26
|
+
return true
|
|
27
|
+
}
|
|
28
|
+
for (const entry of await readdir(root)) {
|
|
29
|
+
if (excluded(entry)) continue
|
|
30
|
+
await cp(join(root, entry), join(target, entry), { recursive: true, dereference: true, filter })
|
|
31
|
+
}
|
|
32
|
+
metrics.status = 'ready'
|
|
33
|
+
return { directory: target, ...metrics, elapsedMs: performance.now() - started }
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (created) {
|
|
36
|
+
try { await rm(target, { recursive: true, force: true }); metrics.cleanup = 'removed' }
|
|
37
|
+
catch (cleanupError) { metrics.cleanup = String(cleanupError.message) }
|
|
38
|
+
}
|
|
39
|
+
return { directory: null, ...metrics, elapsedMs: performance.now() - started, status: signal?.aborted ? 'cancelled' : 'unavailable', error: String(error.message) }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Preserve malformed ClearAI calls for explicit rejection by the tool gate. */
|
|
2
|
+
export async function* recoverToolArguments(stream, names, signal) {
|
|
3
|
+
const pending = new Map()
|
|
4
|
+
const canRecover = error => !signal?.aborted && error?.code === 'MALFORMED_RESPONSE' && pending.size > 0 && [...pending.values()].every(call => {
|
|
5
|
+
if (!call.id || !names.has(call.name)) return false
|
|
6
|
+
try { JSON.parse(call.arguments); return false } catch { return true }
|
|
7
|
+
})
|
|
8
|
+
function* rejectedCalls() {
|
|
9
|
+
for (const [index, call] of pending) yield { type: 'block-end', index, block: { type: 'tool-call', ...call } }
|
|
10
|
+
yield { type: 'finish', reason: { kind: 'tool-calls' } }
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
for await (const chunk of stream) {
|
|
14
|
+
if (chunk.type === 'finish' && chunk.reason?.kind === 'error' && canRecover(chunk.reason.failure)) {
|
|
15
|
+
yield* rejectedCalls()
|
|
16
|
+
return
|
|
17
|
+
}
|
|
18
|
+
if (chunk.type === 'tool-call-delta') {
|
|
19
|
+
const call = pending.get(chunk.index) ?? { id: '', name: '', arguments: '' }
|
|
20
|
+
if (chunk.id) call.id = chunk.id
|
|
21
|
+
if (chunk.name) call.name = chunk.name
|
|
22
|
+
call.arguments += chunk.argumentsDelta ?? ''
|
|
23
|
+
pending.set(chunk.index, call)
|
|
24
|
+
}
|
|
25
|
+
if (chunk.type === 'block-end') pending.delete(chunk.index)
|
|
26
|
+
yield chunk
|
|
27
|
+
}
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (!canRecover(error)) throw error
|
|
30
|
+
yield* rejectedCalls()
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from 'node:fs'
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export class MaterialError extends Error {
|
|
5
|
+
constructor(code, path) { super(`${code}: ${String(path)}`); this.code = code; this.path = path }
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const outside = (base, file) => { const rel = relative(base, file); return rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) }
|
|
9
|
+
|
|
10
|
+
// Check both the lexical path and the nearest existing ancestor. The latter also
|
|
11
|
+
// protects planned outputs which do not exist yet under a symlinked directory.
|
|
12
|
+
export function workspacePath(cwd, value, { mustExist = false } = {}) {
|
|
13
|
+
if (!cwd || typeof value !== 'string' || !value.trim() || value.includes('\0')) throw new MaterialError('invalid-material-path', value)
|
|
14
|
+
const root = realpathSync(cwd)
|
|
15
|
+
const file = resolve(cwd, value)
|
|
16
|
+
if (outside(resolve(cwd), file)) throw new MaterialError('outside-workspace', value)
|
|
17
|
+
let ancestor = file
|
|
18
|
+
while (!existsSync(ancestor) && dirname(ancestor) !== ancestor) ancestor = dirname(ancestor)
|
|
19
|
+
if (outside(root, realpathSync(ancestor))) throw new MaterialError('outside-workspace', value)
|
|
20
|
+
if (mustExist && !existsSync(file)) throw new MaterialError('missing-or-unreadable', value)
|
|
21
|
+
const canonical = existsSync(file) ? realpathSync(file) : resolve(realpathSync(ancestor), relative(ancestor, file))
|
|
22
|
+
return { absolute: canonical, relative: relative(root, canonical).split(sep).join('/') }
|
|
23
|
+
}
|