clearai-dsh 0.5.6 → 0.5.8
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 +34 -0
- package/README.md +33 -19
- package/README.zh-CN.md +31 -17
- package/lib/client.js +529 -163
- package/lib/fold.js +60 -15
- package/package.json +4 -3
- 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/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
|
+
}
|
|
@@ -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
|
+
}
|