@kioku-memory/cli 0.0.0 → 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.
@@ -0,0 +1,152 @@
1
+ // 起 npm 装的那类外部命令(openclaw、hermes,以及 kioku run 要跑的命令)。
2
+ // Windows 上这类命令是 .cmd 文件,不经 cmd.exe 起不来(直接起会报找不到,或者被 Node 拒绝),
3
+ // 而经 cmd.exe 时参数要按它的规则转义,否则参数里的 & | % 这类字符会被当成命令。
4
+ // 别的系统上什么都不做,原样交给系统:找命令、判断能不能执行都是系统的事。
5
+ // 转义的规则照 cross-spawn 的做法写(MIT,来源登记在 NOTICE)
6
+
7
+ import { execFile, spawn } from 'node:child_process'
8
+ import { accessSync, constants, statSync } from 'node:fs'
9
+ import { join, win32 } from 'node:path'
10
+
11
+ import { KiokuFailure } from './http.mjs'
12
+
13
+ const isFile = (file) => {
14
+ try {
15
+ return statSync(file).isFile()
16
+ } catch {
17
+ return false
18
+ }
19
+ }
20
+
21
+ // Windows 的环境变量名不分大小写。同一个名字写了几种大小写时(Path 与 PATH),
22
+ // 取排序后的第一个:Node 把环境交给子进程时也是这样取的,两边看到的要是同一个
23
+ export function envValue(env, name) {
24
+ const key = Object.keys(env)
25
+ .filter((item) => item.toLowerCase() === name.toLowerCase())
26
+ .sort()[0]
27
+ return key === undefined ? undefined : env[key]
28
+ }
29
+
30
+ // Windows 上一个命令的完整路径;找不到为 null。名字里带目录时只看这个位置,否则在 PATH 里逐个目录找。
31
+ // 名字没写扩展名时只按 PATHEXT 补上扩展名找,不找原样的名字:npm 在 .cmd 旁边还放着一个同名、
32
+ // 没有扩展名的脚本(给 sh 用的),Windows 起不了它
33
+ export function findCommand(name, env, { exists = isFile } = {}) {
34
+ if (typeof name !== 'string' || !name) return null
35
+ const extensions = (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
36
+ const suffixes = win32.extname(name) ? ['', ...extensions] : extensions
37
+ const dirs = /[\\/]/.test(name)
38
+ ? ['']
39
+ : (envValue(env, 'PATH') ?? '')
40
+ .split(win32.delimiter)
41
+ // 带空格的目录有人会加上引号
42
+ .map((dir) => dir.replace(/^"(.*)"$/, '$1'))
43
+ .filter(Boolean)
44
+ for (const dir of dirs) {
45
+ for (const suffix of suffixes) {
46
+ const file = (dir ? win32.join(dir, name) : name) + suffix
47
+ if (exists(file)) return file
48
+ }
49
+ }
50
+ return null
51
+ }
52
+
53
+ // PATH 里有没有这个命令(向导的面板用来看平台装没装)。Windows 上照 findCommand 的规则找;
54
+ // 别的系统上找能执行的普通文件
55
+ export function hasCommand(name, env, { platform = process.platform } = {}) {
56
+ if (platform === 'win32') return findCommand(name, env) !== null
57
+ if (typeof name !== 'string' || !name) return false
58
+ const dirs = /\//.test(name) ? [''] : (envValue(env, 'PATH') ?? '').split(':').filter(Boolean)
59
+ return dirs.some((dir) => {
60
+ const file = dir ? join(dir, name) : name
61
+ try {
62
+ accessSync(file, constants.X_OK)
63
+ return statSync(file).isFile()
64
+ } catch {
65
+ return false
66
+ }
67
+ })
68
+ }
69
+
70
+ // cmd.exe 认作有特殊含义的字符
71
+ const META = /([()\][%!^"`<>&|;, *?])/g
72
+
73
+ // 一个参数在 cmd.exe 的命令行里的写法:先按 Windows 程序解析参数的规则加引号、处理反斜杠与引号,
74
+ // 再给 cmd.exe 自己的特殊字符加 ^。经 node_modules/.bin 里的 .cmd 转一道的要转义两遍(它里面又解析一次)
75
+ function escapeArgument(value, twice) {
76
+ let arg = String(value)
77
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
78
+ arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1')
79
+ arg = `"${arg}"`.replace(META, '^$1')
80
+ return twice ? arg.replace(META, '^$1') : arg
81
+ }
82
+
83
+ // 怎么起这个命令:{ file, args, options, shell },交给 spawn、execFile;Windows 上找不到这个命令时为 null。
84
+ // shell 为真表示中间隔着一层 cmd.exe,结束它要用 killTree。别的系统上原样返回,找不到由系统报 ENOENT
85
+ export function launch(name, args, env, { platform = process.platform, exists } = {}) {
86
+ if (platform !== 'win32') return { file: name, args, options: {}, shell: false }
87
+ const file = findCommand(name, env, { exists })
88
+ if (!file) return null
89
+ if (!/\.(cmd|bat)$/i.test(file)) return { file, args, options: {}, shell: false }
90
+ // cmd.exe 把换行当成一行命令的结尾,后面的参数会悄悄丢掉:不起
91
+ if ([file, ...args].some((item) => /[\r\n]/.test(String(item)))) {
92
+ throw new KiokuFailure('参数里有换行,经 cmd.exe 起的命令收不到完整的参数')
93
+ }
94
+ const twice = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(file)
95
+ const line = [file.replace(META, '^$1'), ...args.map((arg) => escapeArgument(arg, twice))]
96
+ return {
97
+ file: envValue(env, 'ComSpec') || 'cmd.exe',
98
+ // /d 不跑注册表里的自动命令,/s 加外层引号让整行原样交给 /c
99
+ args: ['/d', '/s', '/c', `"${line.join(' ')}"`],
100
+ // 这一行已经按 cmd.exe 的规则写好了,不让 Node 再加一层引号
101
+ options: { windowsVerbatimArguments: true },
102
+ shell: true,
103
+ }
104
+ }
105
+
106
+ // 结束一个起好的命令。隔着 cmd.exe 时只结束它的话,真正的命令还活着、还占着输出的管道,
107
+ // 所以连它下面的进程一起结束(Windows 上没有信号可转,只能强行结束)
108
+ export function killTree(child, signal, { shell, platform = process.platform } = {}) {
109
+ if (platform !== 'win32' || !shell || child.pid === undefined) return child.kill(signal)
110
+ try {
111
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on(
112
+ 'error',
113
+ () => child.kill(),
114
+ )
115
+ return true
116
+ } catch {
117
+ return child.kill()
118
+ }
119
+ }
120
+
121
+ // 跑一个命令到结束,收下它的输出:{ found: false }(没有这个命令),
122
+ // 或者 { found: true, ok, stdout, output }(output 是两路输出合在一起,只用来认是哪种失败)。
123
+ // 超过时限就结束它(连同它下面的进程),算失败。不抛错
124
+ export function capture(name, args, env, { timeout, maxBuffer = 8 * 1024 * 1024 } = {}) {
125
+ let run
126
+ try {
127
+ run = launch(name, args, env)
128
+ } catch {
129
+ return Promise.resolve({ found: true, ok: false, stdout: '', output: '' })
130
+ }
131
+ if (!run) return Promise.resolve({ found: false })
132
+ return new Promise((resolve) => {
133
+ let timer
134
+ const child = execFile(
135
+ run.file,
136
+ run.args,
137
+ { env, maxBuffer, ...run.options },
138
+ (err, stdout, stderr) => {
139
+ clearTimeout(timer)
140
+ if (err?.code === 'ENOENT') resolve({ found: false })
141
+ else {
142
+ const out = String(stdout ?? '')
143
+ resolve({ found: true, ok: !err, stdout: out, output: `${out}\n${stderr ?? ''}` })
144
+ }
145
+ },
146
+ )
147
+ if (timeout) {
148
+ timer = setTimeout(() => killTree(child, 'SIGTERM', { shell: run.shell }), timeout)
149
+ timer.unref?.()
150
+ }
151
+ })
152
+ }
package/lib/config.mjs CHANGED
@@ -7,6 +7,9 @@ import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
7
7
  const NOT_CONFIGURED =
8
8
  '缺少 Kioku 的地址或访问密钥:在 Claude Code 里启用 kioku 插件、填好配置后新开会话,或者设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY'
9
9
 
10
+ // 地址或访问密钥根本没有配(区别于配了但不对)
11
+ export class NotConfigured extends KiokuFailure {}
12
+
10
13
  // 地址与访问密钥。访问密钥先读插件在会话开始时配好的 KIOKU_API_KEY_FILE,读不到再用 KIOKU_API_KEY;
11
14
  // 两样都没有才报错,报错只写文件的位置与错误类别
12
15
  export async function loadConfig(env) {
@@ -25,12 +28,11 @@ export async function loadConfig(env) {
25
28
  if (key) await utimes(file, new Date(), new Date()).catch(() => {})
26
29
  }
27
30
  if (!key) key = (env.KIOKU_API_KEY ?? '').trim()
28
- if (!url) throw new KiokuFailure(NOT_CONFIGURED)
31
+ if (!url) throw new NotConfigured(NOT_CONFIGURED)
29
32
  if (!key) {
33
+ if (!fileProblem) throw new NotConfigured(NOT_CONFIGURED)
30
34
  throw new KiokuFailure(
31
- fileProblem
32
- ? `无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`
33
- : NOT_CONFIGURED,
35
+ `无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`,
34
36
  )
35
37
  }
36
38
  let protocol
@@ -0,0 +1,152 @@
1
+ // 把几个平台接到 Kioku:拿到访问密钥之后交给各平台的 kioku setup 写下(核对、写文件都照它的规矩)。
2
+ // 向导走浏览器授权,几个平台一起申请、只确认一次;服务端不认这种写法时逐个平台申请。
3
+ // kioku install 的访问密钥从环境变量来,直接写下。插件不替用户装,只列出要运行的命令
4
+
5
+ import { KiokuFailure } from './http.mjs'
6
+ import { deviceLogin, deviceLoginMany, LegacyServer, MAX_PLATFORMS } from './login.mjs'
7
+ import { PLATFORMS } from './platforms.mjs'
8
+ import { plain } from './text.mjs'
9
+
10
+ // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着。kioku login 也用它
11
+ export function orphanHint(app) {
12
+ const name = app?.name ? `(应用 ${plain(app.name)})` : ''
13
+ return `访问密钥已经签发、但没有写下:到管理界面的应用页吊销它${name},解决上面的问题后重新运行`
14
+ }
15
+
16
+ // 用给定的地址与访问密钥配好一个平台。setup 的输出写到 out;hints 为假时不打印「接下来装上」,
17
+ // 由调用方统一列出(向导与 kioku install),kioku login 只配一个平台,照旧打印
18
+ export function configure(id, { url, key }, { env, out, cwd }, { hints = false } = {}) {
19
+ return PLATFORMS[id].setup(
20
+ { serverUrl: url, dryRun: false, undo: false, check: true },
21
+ { env, out, cwd, readKey: async () => key, plain, login: null, hints },
22
+ )
23
+ }
24
+
25
+ // 签发好的访问密钥写下;写不下时提醒去吊销
26
+ async function settle(id, key, app, io) {
27
+ io.out.write(`\n${PLATFORMS[id].name}\n`)
28
+ try {
29
+ await configure(id, { url: io.url, key }, io)
30
+ return { id, status: 'connected', app }
31
+ } catch (err) {
32
+ // 别的错误照旧抛出(由入口报内部错误),不当成一个平台的失败吞掉
33
+ if (!(err instanceof KiokuFailure)) throw err
34
+ return { id, status: 'failed', reason: `${err.message}。${orphanHint(app)}` }
35
+ }
36
+ }
37
+
38
+ // 用浏览器授权把这几个平台接到 url。返回每个平台的结果(按 ids 的顺序):
39
+ // { id, status: 'connected' | 'skipped' | 'denied' | 'failed', reason?, app? }
40
+ export async function connectPlatforms(
41
+ { url, ids },
42
+ { env, out, cwd, open, browser = true, clientName, sleep, now },
43
+ ) {
44
+ const io = { env, out, cwd, url }
45
+ const login = { out, open, browser, sleep, now, ...(clientName ? { clientName } : {}) }
46
+ const results = new Map()
47
+ // 申请之前先看各平台的配置写不写得进去:访问密钥只在签发时给一次
48
+ const ready = []
49
+ for (const id of ids) {
50
+ try {
51
+ await PLATFORMS[id].preflight?.({ env, cwd })
52
+ ready.push(id)
53
+ } catch (err) {
54
+ if (!(err instanceof KiokuFailure)) throw err
55
+ results.set(id, { id, status: 'failed', reason: err.message })
56
+ }
57
+ }
58
+ // 一次最多 MAX_PLATFORMS 个:多了分批,每批确认一次,前一批签发的先写下再申请下一批
59
+ const batches = []
60
+ for (let i = 0; i < ready.length; i += MAX_PLATFORMS) {
61
+ batches.push(ready.slice(i, i + MAX_PLATFORMS))
62
+ }
63
+ if (batches.length > 1) {
64
+ out.write(`一次最多申请 ${MAX_PLATFORMS} 个平台:分 ${batches.length} 批,每批确认一次\n`)
65
+ }
66
+ let legacy = false
67
+ for (const batch of batches) {
68
+ out.write(
69
+ `这次申请 ${batch.length} 个平台:${batch.map((id) => PLATFORMS[id].name).join('、')}\n`,
70
+ )
71
+ let answers
72
+ try {
73
+ answers = await deviceLoginMany(
74
+ { url, runtimeFamilies: batch.map((id) => PLATFORMS[id].runtimeFamily) },
75
+ login,
76
+ )
77
+ } catch (err) {
78
+ if (err instanceof LegacyServer) {
79
+ legacy = true
80
+ out.write(`${err.message}\n`)
81
+ break
82
+ }
83
+ if (!(err instanceof KiokuFailure)) throw err
84
+ for (const id of batch) results.set(id, { id, status: 'failed', reason: err.message })
85
+ continue
86
+ }
87
+ for (const id of batch) {
88
+ const answer = answers.find((item) => item.runtimeFamily === PLATFORMS[id].runtimeFamily)
89
+ if (answer?.status === 'issued') results.set(id, await settle(id, answer.key, answer.app, io))
90
+ else if (answer?.status === 'denied') {
91
+ results.set(id, { id, status: 'denied', reason: answer.reason || '没有签发' })
92
+ } else results.set(id, { id, status: 'skipped', reason: '确认页上没有勾选' })
93
+ }
94
+ }
95
+ if (legacy) {
96
+ // 旧的服务端:还没有结果的平台逐个申请,每个确认一次;一个不成不影响下一个
97
+ for (const id of ready.filter((item) => !results.has(item))) {
98
+ out.write(`\n${PLATFORMS[id].name}:浏览器授权\n`)
99
+ let key
100
+ try {
101
+ key = await deviceLogin({ url, runtimeFamily: PLATFORMS[id].runtimeFamily }, login)
102
+ } catch (err) {
103
+ if (!(err instanceof KiokuFailure)) throw err
104
+ results.set(id, { id, status: 'failed', reason: err.message })
105
+ continue
106
+ }
107
+ results.set(id, await settle(id, key, null, io))
108
+ }
109
+ }
110
+ return ids.map((id) => results.get(id))
111
+ }
112
+
113
+ const STATUS_NAMES = {
114
+ connected: '已接入',
115
+ manual: '待完成',
116
+ skipped: '跳过',
117
+ denied: '被拒绝',
118
+ failed: '失败',
119
+ }
120
+
121
+ // 结果的文字:按状态分组,一组一行,原因跟在平台名后面
122
+ export function resultsText(results) {
123
+ const lines = []
124
+ for (const status of Object.keys(STATUS_NAMES)) {
125
+ const group = results.filter((item) => item.status === status)
126
+ if (!group.length) continue
127
+ const names = group.map((item) => {
128
+ const detail = item.reason ?? (item.app?.name ? `应用 ${plain(item.app.name)}` : '')
129
+ return detail ? `${PLATFORMS[item.id].name}(${detail})` : PLATFORMS[item.id].name
130
+ })
131
+ lines.push(`${STATUS_NAMES[status]}:${names.join('、')}`)
132
+ }
133
+ return lines.join('\n')
134
+ }
135
+
136
+ // 这几个平台里还要自己装插件的(查得到装好了的不列),每个平台一段:在哪里运行、可以直接复制的命令、之后要做的事。
137
+ // 访问密钥在插件配置里填的平台(Claude Code),给了 url 时写明要填的服务地址
138
+ export async function pluginSteps(ids, { env, cwd, url }) {
139
+ const blocks = []
140
+ for (const id of ids) {
141
+ const platform = PLATFORMS[id]
142
+ const status = await platform.status({ env, cwd }).catch(() => ({ plugin: null }))
143
+ if (status.plugin === true) continue
144
+ const { where = '在终端里', commands, after } = platform.install
145
+ const lines = [`${platform.name}(${where}运行)`, ...commands.map((line) => ` ${line}`)]
146
+ if (!platform.setup && url) lines.push(` 服务地址填:${url}`)
147
+ lines.push(` 然后:${after}`)
148
+ blocks.push(lines.join('\n'))
149
+ }
150
+ if (!blocks.length) return ''
151
+ return `接下来自己装插件,装好之后再运行 kioku 看状态:\n\n${blocks.join('\n\n')}`
152
+ }
package/lib/doctor.mjs CHANGED
@@ -1,10 +1,12 @@
1
1
  // kioku doctor:检查地址与访问密钥能不能用、访问密钥的权限,以及平台这一边配好没有。
2
2
  // 每项一行:✓ 正常,! 要留意,✗ 有问题;有 ✗ 时退出码为 1
3
3
 
4
- import { loadConfig } from './config.mjs'
5
- import { failureText, fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
4
+ import { loadConfig, NotConfigured } from './config.mjs'
5
+ import { whoami } from './api.mjs'
6
+ import { failureText, KiokuFailure } from './http.mjs'
6
7
  import { detectPlatform, platformNames, PLATFORMS } from './platforms.mjs'
7
- import { readSettings } from './setup.mjs'
8
+ import { readSettings } from './files.mjs'
9
+ import { plain, shownUrl } from './text.mjs'
8
10
  import { UsageError } from './usage.mjs'
9
11
 
10
12
  export const DOCTOR_USAGE = `用法:kioku doctor [平台]
@@ -16,7 +18,6 @@ export const DOCTOR_USAGE = `用法:kioku doctor [平台]
16
18
  有问题的项以 ✗ 开头,这时退出码为 1。
17
19
  `
18
20
 
19
- const TIMEOUT = 8000
20
21
  // 与管理界面的用词一致
21
22
  const LAYERS = {
22
23
  core: '通用',
@@ -29,21 +30,6 @@ const LAYERS = {
29
30
  const SENSITIVITIES = { public: '公开', internal: '内部', private: '私密', secret: '机密' }
30
31
  const CAPABILITIES = { none: '不可用', use: '取用', manage: '管理' }
31
32
 
32
- // 不由本命令写的文字(服务端给的名字、环境变量里的地址)打印之前压成一行:控制字符、行与段落分隔符、
33
- // 改变显示方向的格式字符都换成空格,免得伪造出一行结果;截断时不切开代理对
34
- function plain(value) {
35
- const text = String(value ?? '')
36
- .replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')
37
- .trim()
38
- return Array.from(text).slice(0, 200).join('')
39
- }
40
-
41
- // 地址只打印协议、主机与路径:写在地址里的账号密码、查询参数不打印
42
- function shownUrl(url) {
43
- const { origin, pathname } = new URL(url)
44
- return plain(origin + pathname.replace(/\/+$/, ''))
45
- }
46
-
47
33
  function named(names, value) {
48
34
  return Object.hasOwn(names, value) ? names[value] : plain(value)
49
35
  }
@@ -53,35 +39,6 @@ function layersText(layers) {
53
39
  return layers.map((layer) => named(LAYERS, layer)).join('、')
54
40
  }
55
41
 
56
- async function whoami({ url, key }) {
57
- let res
58
- let data
59
- try {
60
- res = await fetch(`${url}/v1/whoami`, {
61
- headers: { authorization: `Bearer ${key}` },
62
- // 不跟着跳转走:访问密钥只发给配置的地址
63
- redirect: 'manual',
64
- signal: AbortSignal.timeout(TIMEOUT),
65
- })
66
- data = await res.json().catch(() => null)
67
- } catch (err) {
68
- throw new KiokuFailure(fetchFailure(err, TIMEOUT))
69
- }
70
- if (isRedirect(res.status)) {
71
- throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
72
- }
73
- if (res.status === 401) throw new KiokuFailure('访问密钥无效或已吊销')
74
- if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
75
- if (
76
- typeof data?.app?.runtimeFamily !== 'string' ||
77
- data.scopes === null ||
78
- typeof data.scopes !== 'object'
79
- ) {
80
- throw new KiokuFailure('Kioku 的响应格式不对')
81
- }
82
- return data
83
- }
84
-
85
42
  export function parseDoctorArgs(argv) {
86
43
  const names = []
87
44
  for (const arg of argv) {
@@ -111,8 +68,22 @@ export async function doctor(
111
68
 
112
69
  let who = null
113
70
  try {
114
- const config = await loadConfig(env)
115
- ok(`地址 ${shownUrl(config.url)}`)
71
+ // 平台把地址与访问密钥放在自己的文件里时先读它,没有再看环境变量
72
+ const profile = platform?.readConfig ? await platform.readConfig(env) : null
73
+ let config = profile
74
+ if (!config) {
75
+ try {
76
+ config = await loadConfig(env)
77
+ } catch (err) {
78
+ // 这个平台有自己放配置的地方、却什么都没配:说怎么配,不说别的平台的做法。
79
+ // 环境变量里配了但不对的(地址无效、访问密钥文件读不了)照原样报
80
+ if (platform?.readConfig && err instanceof NotConfigured) {
81
+ throw new KiokuFailure(`还没有给 ${platform.name} 配过:运行 kioku setup ${id}`)
82
+ }
83
+ throw err
84
+ }
85
+ }
86
+ ok(`地址 ${shownUrl(config.url)}${profile ? `(${profile.file})` : ''}`)
116
87
  who = await whoami(config)
117
88
  } catch (err) {
118
89
  bad(failureText(err))
@@ -137,6 +108,17 @@ export async function doctor(
137
108
  out.write(`没有认出平台,只查了地址与访问密钥;要查平台的配置,写上平台:${platformNames()}\n`)
138
109
  return failed ? 1 : 0
139
110
  }
111
+ if (platform.inspect) {
112
+ try {
113
+ await platform.inspect(
114
+ { env, cwd },
115
+ { ok, warn, bad, note: (text) => out.write(` ${text}\n`) },
116
+ )
117
+ } catch (err) {
118
+ bad(failureText(err))
119
+ }
120
+ return failed ? 1 : 0
121
+ }
140
122
  let settings = null
141
123
  try {
142
124
  settings = (await readSettings(platform.settingsFile(env))).settings
package/lib/dsh.mjs ADDED
@@ -0,0 +1,82 @@
1
+ // DeepSeek Harness 这个平台的 kioku setup 与 kioku doctor。
2
+ // 它没有自带的长期记忆要停用;插件与 MCP 客户端都由本仓库的补丁装上,读本机文件里的服务地址与访问密钥。
3
+ // 所以 setup 只做一件事:把服务地址与访问密钥写进本机的文件
4
+
5
+ import { readdir } from 'node:fs/promises'
6
+ import { homedir } from 'node:os'
7
+ import { join } from 'node:path'
8
+
9
+ import { readSettings } from './files.mjs'
10
+ import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
11
+ import { plain } from './text.mjs'
12
+ import { resolveTarget } from './target.mjs'
13
+
14
+ const PACKAGE = 'kioku-plugins'
15
+ const SOURCE = 'github:lonelyman0108/kioku-plugins'
16
+
17
+ export function dshHome(env) {
18
+ return env.DSH_HOME || join(homedir(), '.dsh')
19
+ }
20
+
21
+ // 装了本仓库这个包的 profile 的名字;没有 profile 目录时为空
22
+ async function installedProfiles(env) {
23
+ const root = join(dshHome(env), 'profiles')
24
+ const names = await readdir(root).catch(() => [])
25
+ const found = []
26
+ for (const name of names.sort()) {
27
+ const { settings } = await readSettings(join(root, name, 'package.json')).catch(() => ({}))
28
+ const bundles = settings?.dsh?.profile?.bundles
29
+ if (Array.isArray(bundles) && bundles.includes(PACKAGE)) found.push(name)
30
+ }
31
+ return found
32
+ }
33
+
34
+ const installHint = `dsh plugin --profile <profile> add ${SOURCE}`
35
+
36
+ export async function setupDsh(options, io) {
37
+ const { env, out } = io
38
+ const profile = profileFile('dsh', env)
39
+ if (options.undo) {
40
+ if (options.dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
41
+ else if (await removeProfile('dsh', env)) out.write(`已删掉 ${profile}\n`)
42
+ else out.write(`${profile} 本来就没有\n`)
43
+ out.write(`插件要另外卸载:dsh plugin --profile <profile> remove ${PACKAGE}\n`)
44
+ return 0
45
+ }
46
+ const { url, key, saved } = await resolveTarget(
47
+ { id: 'dsh', name: 'DeepSeek Harness' },
48
+ options,
49
+ io,
50
+ )
51
+ const same = Boolean(saved && saved.url === url && saved.key === key)
52
+ if (same) out.write(`${profile} 不用改\n`)
53
+ else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
54
+ if (options.dryRun) {
55
+ out.write('没有写入(--dry-run)\n')
56
+ return 0
57
+ }
58
+ if (!same) await writeProfile('dsh', { url, key }, env)
59
+ const profiles = await installedProfiles(env)
60
+ out.write('DeepSeek Harness 已配好,重启 dsh 后生效(读写记忆的工具在启动时连上)。\n')
61
+ if (profiles.length) out.write(`装了插件的 profile:${profiles.map(plain).join('、')}\n`)
62
+ else if (io.hints !== false) {
63
+ out.write(`接下来给要用的 profile 装上插件(web、tui 这些各装一次):${installHint}\n`)
64
+ }
65
+ return 0
66
+ }
67
+
68
+ export async function inspectDsh({ env }, { ok, warn, note }) {
69
+ const profile = await readProfile('dsh', env).catch(() => null)
70
+ if (!profile)
71
+ warn('没有 kioku setup dsh 写下的地址与访问密钥,插件不会生效:运行 kioku setup dsh')
72
+ const profiles = await installedProfiles(env)
73
+ if (profiles.length) ok(`装了 kioku 插件的 profile:${profiles.map(plain).join('、')}`)
74
+ else warn(`没有哪个 profile 装了 kioku 的插件:${installHint}`)
75
+ note('插件按 profile 装:没装的 profile 里没有长期记忆')
76
+ ok('DeepSeek Harness 没有自带的长期记忆要停用')
77
+ }
78
+
79
+ // 给向导的面板:有没有哪个 profile 装了插件,dsh 没有自带的长期记忆
80
+ export async function statusDsh({ env }) {
81
+ return { plugin: (await installedProfiles(env)).length > 0, memory: 'none' }
82
+ }
package/lib/files.mjs ADDED
@@ -0,0 +1,92 @@
1
+ // kioku setup 读写平台设置文件的共用部分。设置文件是用户的,里面还有别的工具写的内容,平台自己也随时在改它,
2
+ // 所以:读不懂的不动它,符号链接改它指向的文件,先写临时文件,改名之前确认没有别人刚改过,备份只留第一份
3
+
4
+ import { randomUUID } from 'node:crypto'
5
+ import { constants } from 'node:fs'
6
+ import { copyFile, mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
7
+ import { dirname } from 'node:path'
8
+
9
+ import { errorKind, KiokuFailure } from './http.mjs'
10
+
11
+ // 读文件的原文;没有这个文件时为 null
12
+ export async function readText(file) {
13
+ try {
14
+ return await readFile(file, 'utf8')
15
+ } catch (err) {
16
+ if (err?.code === 'ENOENT') return null
17
+ throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
18
+ }
19
+ }
20
+
21
+ // 读 JSON 的设置文件:没有这个文件、或者文件是空的,按空的设置;内容不是 JSON 对象时不动它,报错。
22
+ // text 是读到的原文,没有这个文件时为 null
23
+ export async function readSettings(file) {
24
+ const text = await readText(file)
25
+ if (text === null) return { settings: {}, text: null }
26
+ // 开头的 BOM 不算内容
27
+ const body = text.replace(/^\uFEFF/, '')
28
+ if (!body.trim()) return { settings: {}, text }
29
+ let settings
30
+ try {
31
+ settings = JSON.parse(body)
32
+ } catch {
33
+ settings = null
34
+ }
35
+ if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) {
36
+ throw new KiokuFailure(`${file} 不是 JSON 对象,没有改动它`)
37
+ }
38
+ return { settings, text }
39
+ }
40
+
41
+ // 沿用原文件的缩进(取第一处,没有就用两个空格)、换行符和结尾有没有换行;别的排版按 JSON 的默认写法
42
+ export function serialize(settings, text) {
43
+ const indent = /\n([ \t]+)"/.exec(text ?? '')?.[1] ?? ' '
44
+ const eol = text?.includes('\r\n') ? '\r\n' : '\n'
45
+ const tail = text === null || !text.trim() || /\n$/.test(text) ? eol : ''
46
+ return JSON.stringify(settings, null, indent).replaceAll('\n', eol) + tail
47
+ }
48
+
49
+ // 把 body 写成设置文件的新内容,返回这次有没有留备份。text 是开始时读到的原文,没有这个文件时为 null。
50
+ // - 设置文件是符号链接时改它指向的文件,不把链接换成普通文件。
51
+ // - 先写临时文件再改名:写到一半被打断时原来的设置还在;失败时临时文件删掉。
52
+ // - 改名之前再读一次,和开始时读到的不一样就不写:别的程序刚改过,写下去会盖掉它的改动。
53
+ // - 备份只留第一份:之后再改时不覆盖,最早的原文件才留得住。原文里有不该多留一份的内容时(backup 为假)不备份。
54
+ // 权限沿用原文件的,新建的只给本人
55
+ export async function safeWrite(file, body, text, { backup = true } = {}) {
56
+ let target = file
57
+ let temp
58
+ try {
59
+ if (text === null) await mkdir(dirname(file), { recursive: true })
60
+ else target = await realpath(file)
61
+ const mode = text === null ? 0o600 : (await stat(target)).mode & 0o777
62
+ temp = `${target}.${randomUUID()}.tmp`
63
+ await writeFile(temp, body, { mode, flag: 'wx' })
64
+ const current = await readFile(target, 'utf8').catch((err) => {
65
+ if (err?.code === 'ENOENT') return null
66
+ throw err
67
+ })
68
+ if (current !== text) {
69
+ throw new KiokuFailure(`${file} 刚被别的程序改过,没有写入:重新运行一次`)
70
+ }
71
+ let backedUp = false
72
+ if (text !== null && backup) {
73
+ try {
74
+ await copyFile(target, `${file}.kioku-backup`, constants.COPYFILE_EXCL)
75
+ backedUp = true
76
+ } catch (err) {
77
+ if (err?.code !== 'EEXIST') throw err
78
+ }
79
+ }
80
+ await rename(temp, target)
81
+ return backedUp
82
+ } catch (err) {
83
+ if (temp) await rm(temp, { force: true }).catch(() => {})
84
+ if (err instanceof KiokuFailure) throw err
85
+ throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
86
+ }
87
+ }
88
+
89
+ // 写回 JSON 的设置文件
90
+ export function writeSettings(file, settings, text) {
91
+ return safeWrite(file, serialize(settings, text), text)
92
+ }