@twinsearth/ai-prison-dsh-plugin 0.0.0-stage → 1.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.
@@ -0,0 +1,30 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300" fill="none">
2
+ <rect x="24" y="24" width="592" height="252" rx="16" fill="#f8fafc"/>
3
+ <rect x="24" y="24" width="592" height="252" rx="16" stroke="#e2e8f0" stroke-width="2"/>
4
+ <path d="M132 58 214 91v58c0 44-82 86-82 86S50 193 50 149V91z" stroke="#334155" stroke-width="6" stroke-linejoin="round"/>
5
+ <path d="M104 116v64M132 108v80M160 116v64" stroke="#334155" stroke-width="6" stroke-linecap="round"/>
6
+ <circle cx="132" cy="228" r="10" fill="#334155"/>
7
+ <rect x="268" y="62" width="52" height="22" rx="11" fill="#334155"/>
8
+ <rect x="336" y="62" width="196" height="22" rx="11" fill="#cbd5e1"/>
9
+ <rect x="268" y="100" width="52" height="22" rx="11" fill="#475569"/>
10
+ <rect x="336" y="100" width="164" height="22" rx="11" fill="#cbd5e1"/>
11
+ <rect x="268" y="138" width="52" height="22" rx="11" fill="#64748b"/>
12
+ <rect x="336" y="138" width="132" height="22" rx="11" fill="#cbd5e1"/>
13
+ <rect x="268" y="176" width="52" height="22" rx="11" fill="#94a3b8"/>
14
+ <rect x="336" y="176" width="100" height="22" rx="11" fill="#cbd5e1"/>
15
+ <rect x="268" y="214" width="52" height="22" rx="11" fill="#2563eb"/>
16
+ <rect x="336" y="214" width="68" height="22" rx="11" fill="#bfdbfe"/>
17
+ <g stroke="#2563eb" stroke-width="3" fill="none">
18
+ <rect x="464" y="88" width="44" height="26" rx="13"/>
19
+ <rect x="520" y="88" width="44" height="26" rx="13"/>
20
+ <rect x="464" y="150" width="44" height="26" rx="13"/>
21
+ <rect x="520" y="150" width="44" height="26" rx="13"/>
22
+ <rect x="464" y="212" width="44" height="26" rx="13"/>
23
+ <rect x="520" y="212" width="44" height="26" rx="13"/>
24
+ </g>
25
+ <path d="M508 101h12M508 163h12M508 225h12" stroke="#2563eb" stroke-width="3"/>
26
+ <path d="M452 101h8M452 163h8M452 225h8" stroke="#94a3b8" stroke-width="3"/>
27
+ <circle cx="576" cy="101" r="7" fill="#16a34a"/>
28
+ <circle cx="576" cy="163" r="7" fill="#16a34a"/>
29
+ <circle cx="576" cy="225" r="7" fill="#16a34a"/>
30
+ </svg>
package/icon.svg ADDED
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
2
+ <path d="M18 4.4 29.4 9v9.1c0 6.7-11.4 13.2-11.4 13.2S6.6 24.7 6.6 18.1V9z" stroke="#334155" stroke-width="2.2" stroke-linejoin="round"/>
3
+ <path d="M14 12.6v11.2M18 11.4v13.4M22 12.6v11.2" stroke="#334155" stroke-width="2.2" stroke-linecap="round"/>
4
+ <circle cx="18" cy="27.4" r="2.1" fill="#334155"/>
5
+ </svg>
package/index.js ADDED
@@ -0,0 +1,30 @@
1
+ import { registerApi } from './lib/api.js'
2
+ import { installTools } from './lib/tools.js'
3
+
4
+ function loggerOf(ctx) {
5
+ const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined
6
+ return {
7
+ info: (...args) => (typeof logger?.info === 'function' ? logger.info(...args) : console.log('[ai-prison]', ...args)),
8
+ warn: (...args) => (typeof logger?.warn === 'function' ? logger.warn(...args) : console.warn('[ai-prison]', ...args)),
9
+ }
10
+ }
11
+
12
+ /**
13
+ * Host half of the bundle. It registers the aiprison_* tools and the read-only
14
+ * status API; the Client half (client.js) owns the sidebar panel. Both halves
15
+ * are optional services: a profile without `connection` keeps the tools, and a
16
+ * harness whose tools module cannot be resolved keeps the panel.
17
+ */
18
+ export function apply(ctx, config = {}) {
19
+ const logger = loggerOf(ctx)
20
+ const pluginConfig = config && typeof config === 'object' ? config : {}
21
+
22
+ const apiInstalled = registerApi({ ctx, config: pluginConfig, logger })
23
+ if (!apiInstalled) logger.info('ctx.inject 不可用:状态 API 未注册')
24
+
25
+ installTools({ ctx, config: pluginConfig, logger }).catch((error) => {
26
+ logger.warn(`aiprison_* 工具注册失败:${String((error && error.message) || error)}`)
27
+ })
28
+
29
+ ctx.effect(() => () => logger.info('AI Prison 插件已卸载'), 'ai-prison: lifecycle')
30
+ }
package/lib/api.js ADDED
@@ -0,0 +1,120 @@
1
+ import { resolveCli, resolveDataDir, runCli } from './cli.js'
2
+ import { buildStatus, summarizeRun } from './status.js'
3
+
4
+ /**
5
+ * Resolve the directory panel actions should default to. The route has no Agent
6
+ * of its own, so it borrows the most recent live Session's effective directory;
7
+ * without one it falls back to the Host process directory.
8
+ */
9
+ export function resolveSessionCwd(ctx) {
10
+ try {
11
+ const sessions = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : undefined
12
+ const workingDirectory = ctx && typeof ctx.get === 'function' ? ctx.get('workingDirectory') : undefined
13
+ const list = sessions && typeof sessions.list === 'function' ? sessions.list() : []
14
+ for (let index = list.length - 1; index >= 0; index -= 1) {
15
+ const session = list[index]
16
+ if (workingDirectory && typeof workingDirectory.get === 'function') {
17
+ try {
18
+ const dir = workingDirectory.get(session)
19
+ if (typeof dir === 'string' && dir) return dir
20
+ } catch {
21
+ // A session whose directory is unavailable falls through to its header.
22
+ }
23
+ }
24
+ const headerCwd = session && session.header ? session.header.cwd : undefined
25
+ if (typeof headerCwd === 'string' && headerCwd) return headerCwd
26
+ }
27
+ } catch {
28
+ // A profile without sessions keeps the process directory.
29
+ }
30
+ return undefined
31
+ }
32
+
33
+ function jsonResponse(payload, status = 200) {
34
+ return Response.json(payload, { status, headers: { 'cache-control': 'no-store' } })
35
+ }
36
+
37
+ /**
38
+ * Panel API: read-only status plus the two explicit ledger actions the panel
39
+ * offers. Actions run the bundled CLI and therefore write the ledger only when
40
+ * the user presses the corresponding button.
41
+ */
42
+ export function registerApi({ ctx, config = {}, logger } = {}) {
43
+ if (!ctx || typeof ctx.inject !== 'function') return false
44
+ ctx.inject(['connection'], (child) => {
45
+ const registerRoute = (route, label) => {
46
+ try {
47
+ child.effect(() => child.connection.fetch.register(route), label)
48
+ } catch (error) {
49
+ logger?.warn?.(`注册 ${route.path} 失败:${String(error && error.message)}`)
50
+ }
51
+ }
52
+
53
+ registerRoute(
54
+ {
55
+ path: '/api/ai-prison/status',
56
+ methods: ['GET'],
57
+ requestBody: 'buffered',
58
+ fetch: async (request) => {
59
+ try {
60
+ const url = new URL(request.url)
61
+ const requested = url.searchParams.get('data_dir')
62
+ const statusConfig = requested ? { ...config, dataDir: requested } : config
63
+ const cwd = resolveSessionCwd(ctx)
64
+ const status = await buildStatus({ config: statusConfig, cwd })
65
+ return jsonResponse(status)
66
+ } catch (error) {
67
+ return jsonResponse({ ok: false, error: String((error && error.message) || error) }, 500)
68
+ }
69
+ },
70
+ },
71
+ 'ai-prison: status api',
72
+ )
73
+
74
+ registerRoute(
75
+ {
76
+ path: '/api/ai-prison/run',
77
+ methods: ['POST'],
78
+ requestBody: 'buffered',
79
+ fetch: async (request) => {
80
+ let body
81
+ try {
82
+ body = await request.json()
83
+ } catch {
84
+ body = {}
85
+ }
86
+ const action = String(body?.action ?? '')
87
+ if (action !== 'demo' && action !== 'drill') {
88
+ return jsonResponse({ ok: false, error: 'action must be "demo" or "drill"' }, 400)
89
+ }
90
+ const resolved = resolveCli({ config })
91
+ if (!resolved.path) {
92
+ return jsonResponse({ ok: false, error: resolved.missing, reason: 'cli-missing' }, 409)
93
+ }
94
+ const cwd = resolveSessionCwd(ctx) || process.cwd()
95
+ const requested = typeof body?.data_dir === 'string' && body.data_dir ? body.data_dir : undefined
96
+ const dataDir = requested ? requested : resolveDataDir({ config, cwd })
97
+ const timeoutMs = Number(config.timeoutMs) > 0 ? Number(config.timeoutMs) : 120_000
98
+ const result = await runCli(['--data-dir', dataDir, action], {
99
+ bin: resolved.path,
100
+ cwd,
101
+ timeoutMs: Math.max(timeoutMs, 180_000),
102
+ })
103
+ return jsonResponse({
104
+ ok: result.ok,
105
+ action,
106
+ dataDir,
107
+ cwd,
108
+ exitCode: result.exitCode,
109
+ timedOut: result.timedOut === true,
110
+ summary: summarizeRun(action, result),
111
+ stdout: result.stdout,
112
+ stderr: result.stderr,
113
+ })
114
+ },
115
+ },
116
+ 'ai-prison: run api',
117
+ )
118
+ })
119
+ return true
120
+ }
package/lib/cli.js ADDED
@@ -0,0 +1,187 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ /** Package root: the bundle directory that owns bin/, lib/ and index.js. */
7
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
8
+
9
+ export const PLATFORM_KEYS = { win32: 'windows', darwin: 'macos', linux: 'linux' }
10
+ export const ARCH_KEYS = { x64: 'amd64', arm64: 'arm64' }
11
+
12
+ /** Platforms the release bundles; keep in sync with scripts/build-binaries.mjs. */
13
+ export const BUNDLED_TARGETS = [
14
+ 'windows-amd64',
15
+ 'windows-arm64',
16
+ 'macos-amd64',
17
+ 'macos-arm64',
18
+ 'linux-amd64',
19
+ 'linux-arm64',
20
+ ]
21
+
22
+ const MAX_CAPTURE = 512 * 1024
23
+
24
+ function trimEnv(value) {
25
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
26
+ }
27
+
28
+ function expandHome(value) {
29
+ if (typeof value !== 'string') return undefined
30
+ const text = value.trim()
31
+ if (text === '') return undefined
32
+ if (text === '~') return path.join(process.env.HOME || process.env.USERPROFILE || '')
33
+ if (text.startsWith('~/') || text.startsWith('~\\')) {
34
+ return path.join(process.env.HOME || process.env.USERPROFILE || '', text.slice(2))
35
+ }
36
+ return text
37
+ }
38
+
39
+ /** Path of the bundled CLI for one platform, when that build ships. */
40
+ export function bundledCliPath({ platform = process.platform, arch = process.arch, root = PACKAGE_ROOT } = {}) {
41
+ const dir = `${PLATFORM_KEYS[platform] || platform}-${ARCH_KEYS[arch] || arch}`
42
+ const file = path.join(root, 'bin', dir, platform === 'win32' ? 'aiprison.exe' : 'aiprison')
43
+ return existsSync(file) ? file : undefined
44
+ }
45
+
46
+ /** Search PATH entries for a native aiprison executable (`aiprison`, not a shim). */
47
+ export function pathCliPath({ env = process.env, platform = process.platform } = {}) {
48
+ const name = platform === 'win32' ? 'aiprison.exe' : 'aiprison'
49
+ const entries = String(env.PATH || env.Path || '')
50
+ .split(platform === 'win32' ? ';' : ':')
51
+ .map((entry) => entry.trim())
52
+ .filter(Boolean)
53
+ for (const entry of entries) {
54
+ const candidate = path.join(entry, name)
55
+ if (existsSync(candidate)) return candidate
56
+ }
57
+ return undefined
58
+ }
59
+
60
+ /**
61
+ * Resolve the CLI the plugin should run, in priority order: explicit config,
62
+ * AIPRISON_BIN, the bundled build, then PATH. Returns the path plus the source
63
+ * label used by tool results and the panel.
64
+ */
65
+ export function resolveCli({ config = {}, env = process.env, platform = process.platform, arch = process.arch, root = PACKAGE_ROOT } = {}) {
66
+ const fromConfig = expandHome(config.cliPath)
67
+ if (fromConfig) {
68
+ if (existsSync(fromConfig)) return { path: fromConfig, source: 'config' }
69
+ return { missing: `配置的 cliPath 不存在:${fromConfig}`, source: 'config' }
70
+ }
71
+ const fromEnv = expandHome(trimEnv(env.AIPRISON_BIN))
72
+ if (fromEnv) {
73
+ if (existsSync(fromEnv)) return { path: fromEnv, source: 'AIPRISON_BIN' }
74
+ return { missing: `AIPRISON_BIN 指向的文件不存在:${fromEnv}`, source: 'env' }
75
+ }
76
+ const bundled = bundledCliPath({ platform, arch, root })
77
+ if (bundled) return { path: bundled, source: 'bundled' }
78
+ const fromPath = pathCliPath({ env, platform })
79
+ if (fromPath) return { path: fromPath, source: 'PATH' }
80
+ return {
81
+ missing:
82
+ `没有找到 aiprison 可执行文件(本平台 ${platform}-${arch} 没有内置构建)。` +
83
+ '可设置 AIPRISON_BIN、在插件配置里填 cliPath,或把 aiprison 放进 PATH。',
84
+ source: 'none',
85
+ }
86
+ }
87
+
88
+ function truncate(text) {
89
+ if (text.length <= MAX_CAPTURE) return text
90
+ return `${text.slice(0, MAX_CAPTURE / 2)}\n…[输出被截断]…\n${text.slice(-MAX_CAPTURE / 2)}`
91
+ }
92
+
93
+ /**
94
+ * Run the CLI and never reject: a non-zero exit, a spawn failure and a timeout
95
+ * all come back as data so a tool can report them without ending the turn.
96
+ */
97
+ export function runCli(args, { bin, cwd, timeoutMs = 120_000, env = process.env, signal } = {}) {
98
+ return new Promise((resolve) => {
99
+ if (typeof bin !== 'string' || bin === '') {
100
+ resolve({ ok: false, exitCode: null, stdout: '', stderr: '', error: 'no binary', timedOut: false })
101
+ return
102
+ }
103
+ const options = { cwd: cwd || process.cwd(), env, windowsHide: true }
104
+ let child
105
+ try {
106
+ child = spawn(bin, args, options)
107
+ } catch (error) {
108
+ resolve({ ok: false, exitCode: null, stdout: '', stderr: '', error: String(error && error.message), timedOut: false })
109
+ return
110
+ }
111
+ let stdout = ''
112
+ let stderr = ''
113
+ let timedOut = false
114
+ let spawnError
115
+ const timer = setTimeout(() => {
116
+ timedOut = true
117
+ try {
118
+ child.kill('SIGKILL')
119
+ } catch {
120
+ // The exit handler below still settles the promise.
121
+ }
122
+ }, Math.max(1_000, Number(timeoutMs) || 120_000))
123
+ const onAbort = () => {
124
+ try {
125
+ child.kill('SIGKILL')
126
+ } catch {
127
+ // ignore
128
+ }
129
+ }
130
+ if (signal && typeof signal.addEventListener === 'function') {
131
+ if (signal.aborted) onAbort()
132
+ else signal.addEventListener('abort', onAbort, { once: true })
133
+ }
134
+ child.stdout?.on('data', (chunk) => {
135
+ stdout = truncate(stdout + chunk.toString())
136
+ })
137
+ child.stderr?.on('data', (chunk) => {
138
+ stderr = truncate(stderr + chunk.toString())
139
+ })
140
+ child.on('error', (error) => {
141
+ spawnError = String((error && error.message) || error)
142
+ })
143
+ child.on('close', (code, sig) => {
144
+ clearTimeout(timer)
145
+ if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
146
+ resolve({
147
+ ok: code === 0 && !timedOut && !spawnError,
148
+ exitCode: code,
149
+ signal: sig || undefined,
150
+ stdout: stdout.trimEnd(),
151
+ stderr: stderr.trimEnd(),
152
+ error: spawnError,
153
+ timedOut,
154
+ bin,
155
+ })
156
+ })
157
+ })
158
+ }
159
+
160
+ /** Resolve the CLI and read `aiprison version -v`; used by tools and the panel. */
161
+ export async function describeCli(options = {}) {
162
+ const resolved = resolveCli(options)
163
+ if (!resolved.path) return { found: false, source: resolved.source, error: resolved.missing, path: null, version: null, commit: null }
164
+ const probe = await runCli(['version', '-v'], { bin: resolved.path, cwd: options.cwd, timeoutMs: options.timeoutMs })
165
+ const text = `${probe.stdout}\n${probe.stderr}`
166
+ const versionMatch = text.match(/aiprison\s+([0-9][^\s]*)/)
167
+ const commitMatch = text.match(/commit:\s*([^\s]+)/)
168
+ return {
169
+ found: probe.ok,
170
+ source: resolved.source,
171
+ path: resolved.path,
172
+ version: versionMatch ? versionMatch[1] : null,
173
+ commit: commitMatch ? commitMatch[1] : null,
174
+ error: probe.ok ? null : `${probe.stderr || probe.stdout || 'version probe failed'}`,
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Default durable ledger directory: the plugin config when set, else
180
+ * `<working directory>/.ai-prison` so the ledger lives beside the project it
181
+ * audits instead of in a shared home directory.
182
+ */
183
+ export function resolveDataDir({ config = {}, cwd } = {}) {
184
+ const configured = expandHome(config.dataDir)
185
+ if (configured) return configured
186
+ return path.join(cwd || process.cwd(), '.ai-prison')
187
+ }
package/lib/harness.js ADDED
@@ -0,0 +1,51 @@
1
+ import path from 'node:path'
2
+ import { createRequire } from 'node:module'
3
+ import { pathToFileURL } from 'node:url'
4
+
5
+ /**
6
+ * Candidate anchors for the running harness installation. The Desktop app ships
7
+ * one asar archive, while CLI layouts use a plain package directory; every
8
+ * candidate is tried with createRequire because module resolution inside an asar
9
+ * only works in the Electron-as-Node runtime that launched DSH.
10
+ */
11
+ export function installationAnchors({ execPath = process.execPath, env = process.env } = {}) {
12
+ const dir = path.dirname(execPath)
13
+ return [
14
+ env.DSH_APP_ANCHOR,
15
+ path.join(dir, 'resources', 'app.asar', 'dsh', 'package.json'),
16
+ path.join(dir, 'resources', 'app', 'dsh', 'package.json'),
17
+ path.join(dir, '..', 'Resources', 'app.asar', 'dsh', 'package.json'),
18
+ path.join(dir, '..', 'Resources', 'app', 'dsh', 'package.json'),
19
+ ].filter(Boolean)
20
+ }
21
+
22
+ /**
23
+ * Import the harness' own copy of a core package. A plugin must register tools
24
+ * through the exact module instance the harness validated, so resolve it from
25
+ * the installation rather than bundling a second copy.
26
+ */
27
+ export async function loadHarnessModule(specifier, { anchors = installationAnchors() } = {}) {
28
+ for (const anchor of anchors) {
29
+ let file
30
+ try {
31
+ const require_ = createRequire(pathToFileURL(anchor))
32
+ file = require_.resolve(specifier)
33
+ } catch {
34
+ continue
35
+ }
36
+ try {
37
+ const module = await import(pathToFileURL(file).href)
38
+ return { module, file, anchor }
39
+ } catch {
40
+ // Keep trying other anchors.
41
+ }
42
+ }
43
+ return undefined
44
+ }
45
+
46
+ /** The `defineTool` builder from @deepseek-ai/dsh-tools, when resolvable. */
47
+ export async function loadDefineTool(options = {}) {
48
+ const found = await loadHarnessModule('@deepseek-ai/dsh-tools', options)
49
+ const defineTool = found && found.module && found.module.defineTool
50
+ return typeof defineTool === 'function' ? { defineTool, file: found.file } : undefined
51
+ }
package/lib/levels.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The CLI prints the matrix as human text; this turns it back into data:
3
+ *
4
+ * L0 Warning [immediate] immediate, appealable
5
+ * - reputation deduction
6
+ * - record flag
7
+ */
8
+ const HEADER = /^([A-Z][0-9])\s+([^\s[][^[]*?)\s+\[([^\]]+)\]\s*(.*)$/
9
+ const ITEM = /^\s+[-*]\s+(.*)$/
10
+
11
+ export function parseLevels(text) {
12
+ const levels = []
13
+ let current
14
+ for (const raw of String(text || '').split(/\r?\n/)) {
15
+ const line = raw.replace(/\s+$/, '')
16
+ if (line === '') continue
17
+ const header = line.match(HEADER)
18
+ if (header) {
19
+ current = {
20
+ code: header[1],
21
+ name: header[2].trim(),
22
+ durationClass: header[3].trim(),
23
+ durationHint: header[4].trim(),
24
+ deprivations: [],
25
+ }
26
+ levels.push(current)
27
+ continue
28
+ }
29
+ const item = line.match(ITEM)
30
+ if (item && current) current.deprivations.push(item[1].trim())
31
+ }
32
+ return levels
33
+ }
34
+
35
+ /** One line per level, for tool results and compact logs. */
36
+ export function summarizeLevels(levels) {
37
+ return (levels || []).map((level) => `${level.code} ${level.name} [${level.durationClass}] ${level.deprivations.length} 项剥夺`)
38
+ }
package/lib/status.js ADDED
@@ -0,0 +1,95 @@
1
+ import { existsSync, readdirSync, statSync } from 'node:fs'
2
+ import { describeCli, resolveCli, resolveDataDir, runCli } from './cli.js'
3
+ import { parseLevels } from './levels.js'
4
+
5
+ const MAX_DETAIL = 600
6
+
7
+ function firstLines(text, count = 3) {
8
+ return String(text || '')
9
+ .split(/\r?\n/)
10
+ .map((line) => line.trim())
11
+ .filter(Boolean)
12
+ .slice(0, count)
13
+ .join(' · ')
14
+ .slice(0, MAX_DETAIL)
15
+ }
16
+
17
+ /** Read the durable ledger's integrity through `aiprison verify`. */
18
+ export async function inspectLedger({ bin, dataDir, timeoutMs } = {}) {
19
+ if (!dataDir || !existsSync(dataDir)) {
20
+ return { dir: dataDir || null, exists: false, integrity: 'none', records: null, detail: '', files: 0 }
21
+ }
22
+ let files = 0
23
+ try {
24
+ files = readdirSync(dataDir).length
25
+ } catch {
26
+ files = 0
27
+ }
28
+ const result = await runCli(['--data-dir', dataDir, 'verify'], { bin, timeoutMs })
29
+ const text = result.ok ? result.stdout : `${result.stdout}\n${result.stderr}`
30
+ if (result.ok) {
31
+ const records = text.match(/(\d+)\s+records?/i)
32
+ return {
33
+ dir: dataDir,
34
+ exists: true,
35
+ integrity: 'ok',
36
+ records: records ? Number(records[1]) : null,
37
+ detail: firstLines(text, 1),
38
+ files,
39
+ }
40
+ }
41
+ return {
42
+ dir: dataDir,
43
+ exists: true,
44
+ integrity: 'failed',
45
+ records: null,
46
+ detail: firstLines(text, 3) || (result.timedOut ? 'verify timed out' : 'verify failed'),
47
+ files,
48
+ }
49
+ }
50
+
51
+ /** Everything the panel and the status tool show, in one read-only snapshot. */
52
+ export async function buildStatus({ config = {}, cwd, timeoutMs = 120_000, root } = {}) {
53
+ const resolved = resolveCli({ config, root })
54
+ const cli = await describeCli({ config, cwd, timeoutMs, root })
55
+ let levels = []
56
+ if (resolved.path) {
57
+ const levelsRun = await runCli(['levels'], { bin: resolved.path, cwd, timeoutMs })
58
+ if (levelsRun.ok) levels = parseLevels(levelsRun.stdout)
59
+ }
60
+ const dataDir = resolveDataDir({ config, cwd })
61
+ const ledger = await inspectLedger({ bin: resolved.path, dataDir, timeoutMs })
62
+ return {
63
+ ok: resolved.path !== undefined,
64
+ generatedAt: new Date().toISOString(),
65
+ cwd: cwd || null,
66
+ platform: `${process.platform}-${process.arch}`,
67
+ cli,
68
+ levels,
69
+ ledger,
70
+ }
71
+ }
72
+
73
+ /** Bounded human summary used by tool results. */
74
+ export function statusSummary(status) {
75
+ const cliLine = status.cli.found
76
+ ? `aiprison ${status.cli.version || '?'}(${status.cli.source}: ${status.cli.path})`
77
+ : `CLI 不可用:${status.cli.error || 'unknown'}`
78
+ const ledgerLine = status.ledger.exists
79
+ ? `账本 ${status.ledger.dir}:${status.ledger.integrity === 'ok' ? `INTEGRITY OK(${status.ledger.records ?? '?'} 条记录)` : `校验失败(${status.ledger.detail})`}`
80
+ : `账本 ${status.ledger.dir}:尚未初始化`
81
+ return [cliLine, ledgerLine, `分级矩阵:${status.levels.length} 级`].join('\n')
82
+ }
83
+
84
+ /** One-line outcome for a panel action (`demo` or `drill`). */
85
+ export function summarizeRun(action, result) {
86
+ if (result && result.timedOut) return `超时:${action} 超过时间上限`
87
+ const lines = `${(result && result.stdout) || ''}\n${(result && result.stderr) || ''}`
88
+ .split(/\r?\n/)
89
+ .map((line) => line.trim())
90
+ .filter(Boolean)
91
+ const picked = lines.filter((line) => /OVERALL|已落盘|INTEGRITY|记录数|段数|最终运行状态|恢复令/.test(line)).slice(-4)
92
+ const detail = (picked.length > 0 ? picked : lines.slice(-2)).join(' · ').slice(0, 500)
93
+ if (result && result.ok) return detail || `${action} 完成`
94
+ return `失败(exit ${result ? result.exitCode : '?'}):${detail || 'no output'}`
95
+ }