@kioku-memory/plugin-opencode 0.0.0-stage → 0.1.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,128 @@
1
+ // 各平台的钩子共用的生命周期转发:把 session.start、prompt.submit、turn.end 交给 Kioku 的生命周期端点。
2
+ // 这里不放提示词和格式逻辑,都由服务端决定;怎么从平台取输入、怎么把结果交还平台,由各插件自己写。
3
+ // 报错和 kioku 命令一样不带访问密钥:格式不对的访问密钥不发出去,fetch 的报错只取类别,
4
+ // 也不跟着跳转走,访问密钥只发给配置的地址
5
+
6
+ import { execFile, execFileSync } from 'node:child_process'
7
+ import { basename } from 'node:path'
8
+
9
+ import { fetchFailure, isRedirect, keyFormatError, KiokuFailure, redirectError } from './http.mjs'
10
+
11
+ // 各事件等待服务端的上限(毫秒),要比平台给钩子的时限短
12
+ export const TIMEOUTS = { 'session.start': 8000, 'prompt.submit': 5000, 'turn.end': 5000 }
13
+ // 与服务端 contracts 的上限一致
14
+ export const MAX_PROMPT = 20_000
15
+ export const MAX_REPLY = 20_000
16
+ export const MAX_SESSION_ID = 200
17
+ const MAX_NAME = 128
18
+
19
+ // 配置写错了:访问密钥格式不对(kind 为 key),或者服务地址返回跳转(kind 为 url)。
20
+ // 和没有配置一样,平台可以在会话开始时提示一次;文字不带访问密钥
21
+ export class Misconfigured extends KiokuFailure {
22
+ constructor(message, kind) {
23
+ super(message)
24
+ this.kind = kind
25
+ }
26
+ }
27
+
28
+ // 服务地址去掉首尾空白与结尾的斜杠
29
+ export function normalizeBase(url) {
30
+ return (url ?? '').trim().replace(/\/+$/, '')
31
+ }
32
+
33
+ // 访问密钥的格式不对时抛 Misconfigured
34
+ export function assertKeyFormat(key) {
35
+ const problem = keyFormatError(key)
36
+ if (problem) throw new Misconfigured(problem, 'key')
37
+ }
38
+
39
+ // 按长度截断时不切开代理对(表情这类字符):落单的半个到了服务端会变成替换字符
40
+ export function clip(text, max) {
41
+ if (text.length <= max) return text
42
+ const code = text.charCodeAt(max - 1)
43
+ return text.slice(0, code >= 0xd800 && code <= 0xdbff ? max - 1 : max)
44
+ }
45
+
46
+ // 当前项目的目录名与 git 仓库名,服务端用它们召回与项目相关的记忆;取不到的就不带
47
+ export function projectOf(cwd) {
48
+ const project = {}
49
+ const dirName = basename(cwd)
50
+ if (dirName) project.dirName = dirName.slice(0, MAX_NAME)
51
+ try {
52
+ const remote = execFileSync('git', ['-C', cwd, 'remote', 'get-url', 'origin'], {
53
+ encoding: 'utf8',
54
+ timeout: 1500,
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ }).trim()
57
+ const repoName = /([^/:]+?)(?:\.git)?$/.exec(remote)?.[1]
58
+ if (repoName) project.repoName = repoName.slice(0, MAX_NAME)
59
+ } catch {
60
+ // 不是 git 仓库或没有 origin
61
+ }
62
+ return project
63
+ }
64
+
65
+ // 同上,不堵住事件循环:给在宿主进程里跑的扩展用(同步的那个会让宿主的界面停住)
66
+ export function projectOfAsync(cwd) {
67
+ const project = {}
68
+ const dirName = basename(cwd)
69
+ if (dirName) project.dirName = dirName.slice(0, MAX_NAME)
70
+ return new Promise((resolve) => {
71
+ execFile(
72
+ 'git',
73
+ ['-C', cwd, 'remote', 'get-url', 'origin'],
74
+ { encoding: 'utf8', timeout: 1500 },
75
+ (err, stdout) => {
76
+ const repoName = err ? undefined : /([^/:]+?)(?:\.git)?$/.exec(stdout.trim())?.[1]
77
+ if (repoName) project.repoName = repoName.slice(0, MAX_NAME)
78
+ resolve(project)
79
+ },
80
+ )
81
+ })
82
+ }
83
+
84
+ // 服务端要注入的上下文文本;没有时为 undefined。只取文本,输出里的其他字段一律不用:
85
+ // 记忆服务能决定注入什么内容,但不能挡住用户的输入或改变会话
86
+ export function contextOf(hostOutput) {
87
+ if (hostOutput?.mode === 'stdout_json') {
88
+ return (
89
+ hostOutput.value?.hookSpecificOutput?.additionalContext ??
90
+ hostOutput.value?.injectSteps?.[0]?.systemMessage?.systemMessage
91
+ )
92
+ }
93
+ if (hostOutput?.mode === 'stdout_text') return hostOutput.value
94
+ // 没有专门输出格式的运行时:服务端直接给文本
95
+ if (hostOutput?.mode === 'return_value') {
96
+ return (
97
+ hostOutput.value?.systemContext ??
98
+ hostOutput.value?.promptContext ??
99
+ hostOutput.value?.context
100
+ )
101
+ }
102
+ return undefined
103
+ }
104
+
105
+ // 把一个生命周期事件交给服务端;连不上、超时、取消、跳转与非 2xx 都以 KiokuFailure 抛出
106
+ export async function postEvent(base, key, body, timeout, signal) {
107
+ let res
108
+ try {
109
+ res = await fetch(`${base}/v1/lifecycle/event`, {
110
+ method: 'POST',
111
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
112
+ body: JSON.stringify(body),
113
+ redirect: 'manual',
114
+ // 宿主给了中止信号时(用户取消了这次输入)一起听
115
+ signal: signal
116
+ ? AbortSignal.any([AbortSignal.timeout(timeout), signal])
117
+ : AbortSignal.timeout(timeout),
118
+ })
119
+ } catch (err) {
120
+ if (signal?.aborted) throw new KiokuFailure('已取消')
121
+ throw new KiokuFailure(fetchFailure(err, timeout))
122
+ }
123
+ if (isRedirect(res.status)) {
124
+ throw new Misconfigured(redirectError(res.status, res.headers.get('location'), base), 'url')
125
+ }
126
+ if (!res.ok) throw new KiokuFailure(`HTTP ${res.status}`)
127
+ return res
128
+ }
package/lib/local.mjs ADDED
@@ -0,0 +1,294 @@
1
+ // 向导里的「本机起一个 Kioku」:在一个目录里放好 compose.yaml 与 .env,用 Docker 起服务,等它就绪,
2
+ // 再等用户在管理界面建好第一个管理员。已有的文件不覆盖;端口被占时只说明,不动别的进程
3
+
4
+ import { randomBytes } from 'node:crypto'
5
+ import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
6
+ import { connect, createServer } from 'node:net'
7
+ import { homedir } from 'node:os'
8
+ import { join, resolve } from 'node:path'
9
+
10
+ import { capture } from './command.mjs'
11
+ import { errorKind, KiokuFailure } from './http.mjs'
12
+
13
+ const REPO = 'lonelyman0108/kioku'
14
+ export const LATEST_RELEASE_URL = `https://api.github.com/repos/${REPO}/releases/latest`
15
+
16
+ // 仓库里某个版本(tag 或分支)的文件
17
+ export function rawUrl(ref, file) {
18
+ return `https://raw.githubusercontent.com/${REPO}/${ref}/${file}`
19
+ }
20
+
21
+ // 用哪个版本:最新的正式版,compose.yaml、.env.example 从它的 tag 取,镜像固定在这个版本号;
22
+ // 取不到时退回 main 上的文件与 edge 镜像(main 上最新的提交),problem 写明原因。
23
+ // 返回 { ref, imageTag, release, problem? }
24
+ export async function latestRelease({ fetchImpl = fetch } = {}) {
25
+ let problem
26
+ try {
27
+ const res = await fetchImpl(LATEST_RELEASE_URL, {
28
+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'kioku-cli' },
29
+ signal: AbortSignal.timeout(10_000),
30
+ })
31
+ const data = res.ok ? await res.json().catch(() => null) : null
32
+ const tag = typeof data?.tag_name === 'string' ? data.tag_name : ''
33
+ const match = /^v?(\d+\.\d+\.\d+)$/.exec(tag)
34
+ if (match) return { ref: tag, imageTag: match[1], release: true }
35
+ problem = res.ok ? '版本号认不出' : `HTTP ${res.status}`
36
+ } catch (err) {
37
+ problem = networkReason(err)
38
+ }
39
+ return { ref: 'main', imageTag: 'edge', release: false, problem }
40
+ }
41
+
42
+ // fetch 失败的原因:超时、错误码,或者笼统的网络错误
43
+ function networkReason(err) {
44
+ const code = err?.cause?.code
45
+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') return '超时'
46
+ return typeof code === 'string' && /^[A-Z][A-Z0-9_]*$/.test(code) ? code : '网络错误'
47
+ }
48
+ export const LOCAL_PORT = 18920
49
+ export const LOCAL_URL = `http://127.0.0.1:${LOCAL_PORT}`
50
+
51
+ export function defaultLocalDir(env) {
52
+ return join(env.HOME || homedir(), 'kioku')
53
+ }
54
+
55
+ // 目录:~ 开头的换成主目录
56
+ export function expandDir(dir, env) {
57
+ const home = env.HOME || homedir()
58
+ return resolve(dir === '~' ? home : dir.replace(/^~(?=[/\\])/, home))
59
+ }
60
+
61
+ // .env 里要生成的几项:两个数据库密码是 24 字节的十六进制(openssl rand -hex 24,只用十六进制字符,
62
+ // 拼进连接串不出问题),主密钥是 32 字节的 base64,初始化码是 16 字节的十六进制
63
+ export function generateSecrets(random = randomBytes) {
64
+ return {
65
+ POSTGRES_PASSWORD: random(24).toString('hex'),
66
+ KIOKU_DB_PASSWORD: random(24).toString('hex'),
67
+ KIOKU_MASTER_KEY: random(32).toString('base64'),
68
+ KIOKU_SETUP_CODE: random(16).toString('hex'),
69
+ }
70
+ }
71
+
72
+ // 只在本机用的设置:管理界面走 http://127.0.0.1,登录 Cookie 不能要求 HTTPS;端口只发布在本机
73
+ export const LOCAL_SETTINGS = { KIOKU_COOKIE_SECURE: 'false', KIOKU_BIND: '127.0.0.1' }
74
+
75
+ // 照着 .env.example 填:示例里有这一项就在原处填上;只有注释掉的(「# 名字=」)才填在注释那一行,
76
+ // 免得说明里举的例子被填上、真正的那一行还空着(后出现的那行生效)。示例里没有的加在最后
77
+ export function fillEnv(template, values) {
78
+ const lines = template.split(/\r?\n/)
79
+ const nameOf = (line, commented) =>
80
+ (commented ? /^\s*#\s*([A-Z][A-Z0-9_]*)=/ : /^\s*([A-Z][A-Z0-9_]*)=/).exec(line)?.[1]
81
+ const done = new Set()
82
+ const next = [...lines]
83
+ for (const commented of [false, true]) {
84
+ next.forEach((line, index) => {
85
+ const name = nameOf(line, commented)
86
+ if (!name || !Object.hasOwn(values, name) || done.has(name)) return
87
+ done.add(name)
88
+ next[index] = `${name}=${values[name]}`
89
+ })
90
+ }
91
+ while (next.length && next.at(-1) === '') next.pop()
92
+ for (const [name, value] of Object.entries(values)) {
93
+ if (!done.has(name)) next.push(`${name}=${value}`)
94
+ }
95
+ return `${next.join('\n')}\n`
96
+ }
97
+
98
+ // .env 里写的一项的值;没有为 null
99
+ export function envValue(text, name) {
100
+ for (const line of text.split(/\r?\n/)) {
101
+ const match = /^\s*([A-Z][A-Z0-9_]*)=(.*)$/.exec(line)
102
+ if (match?.[1] === name) return match[2].trim().replace(/^(["'])(.*)\1$/, '$2')
103
+ }
104
+ return null
105
+ }
106
+
107
+ // .env 里 KIOKU_TAG 上面的说明
108
+ function tagNote(imageTag) {
109
+ return imageTag === 'edge'
110
+ ? '# 没取到最新的正式版,用的是 main 上最新的提交(edge),不保证稳定;改成版本号(如 0.1.0)固定下来'
111
+ : `# 固定在 ${imageTag}(生成时的最新正式版)。升级时改这里,再 docker compose pull && docker compose up -d`
112
+ }
113
+
114
+ // 写 .env:只给本人读写,已有的不覆盖。imageTag 给了时 KIOKU_TAG 写成它,上面加一行说明。
115
+ // 返回 { written, file, setupCode }:已有的文件不动,初始化码取它里面写的(没写为 null,要看日志)
116
+ export async function writeEnvFile(dir, template, { random, imageTag } = {}) {
117
+ const file = join(dir, '.env')
118
+ const existing = await readFile(file, 'utf8').catch((err) => {
119
+ if (err?.code === 'ENOENT') return null
120
+ throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
121
+ })
122
+ if (existing !== null) {
123
+ return { written: false, file, setupCode: envValue(existing, 'KIOKU_SETUP_CODE') || null }
124
+ }
125
+ const secrets = generateSecrets(random)
126
+ let body = fillEnv(template, {
127
+ ...secrets,
128
+ ...LOCAL_SETTINGS,
129
+ ...(imageTag ? { KIOKU_TAG: imageTag } : {}),
130
+ })
131
+ if (imageTag) body = body.replace(/^KIOKU_TAG=/m, `${tagNote(imageTag)}\nKIOKU_TAG=`)
132
+ try {
133
+ // wx:写的这一刻别人刚建了也不覆盖
134
+ await writeFile(file, body, { mode: 0o600, flag: 'wx' })
135
+ await chmod(file, 0o600)
136
+ } catch (err) {
137
+ if (err?.code === 'EEXIST') return writeEnvFile(dir, template, { random, imageTag })
138
+ await rm(file, { force: true }).catch(() => {})
139
+ throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
140
+ }
141
+ return { written: true, file, setupCode: secrets.KIOKU_SETUP_CODE }
142
+ }
143
+
144
+ // 下载一个文件放进目录;已有的不覆盖,返回 'kept',下载了返回 'downloaded'。失败时抛 KiokuFailure
145
+ export async function download(url, file, { fetchImpl = fetch } = {}) {
146
+ if (
147
+ await readFile(file).then(
148
+ () => true,
149
+ () => false,
150
+ )
151
+ )
152
+ return 'kept'
153
+ let text
154
+ try {
155
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(20_000) })
156
+ if (!res.ok) throw new KiokuFailure(`下载 ${url} 失败(HTTP ${res.status})`)
157
+ text = await res.text()
158
+ } catch (err) {
159
+ if (err instanceof KiokuFailure) throw err
160
+ throw new KiokuFailure(`下载 ${url} 失败(${networkReason(err)})`)
161
+ }
162
+ try {
163
+ await writeFile(file, text, { flag: 'wx' })
164
+ } catch (err) {
165
+ if (err?.code === 'EEXIST') return 'kept'
166
+ throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
167
+ }
168
+ return 'downloaded'
169
+ }
170
+
171
+ // 下载失败时让用户自己运行的命令
172
+ export function manualDownload(dir, ref = 'main') {
173
+ return [
174
+ `mkdir -p ${dir} && cd ${dir}`,
175
+ `curl -fsSLO ${rawUrl(ref, 'compose.yaml')}`,
176
+ `curl -fsSL -o .env.example ${rawUrl(ref, '.env.example')}`,
177
+ ].join('\n')
178
+ }
179
+
180
+ // 准备目录:建目录、从 release.ref 下载 compose.yaml 与 .env.example、生成 .env(镜像固定在 release.imageTag)。
181
+ // 返回 { files, env }
182
+ export async function prepareDir(dir, release, { fetchImpl, random } = {}) {
183
+ try {
184
+ await mkdir(dir, { recursive: true })
185
+ } catch (err) {
186
+ throw new KiokuFailure(`无法创建目录 ${dir}(${errorKind(err)})`)
187
+ }
188
+ const fetchFile = (name, file) => download(rawUrl(release.ref, name), file, { fetchImpl })
189
+ const compose = await fetchFile('compose.yaml', join(dir, 'compose.yaml'))
190
+ const example = await fetchFile('.env.example', join(dir, '.env.example'))
191
+ const template = await readFile(join(dir, '.env.example'), 'utf8')
192
+ const env = await writeEnvFile(dir, template, { random, imageTag: release.imageTag })
193
+ return { files: { compose, example }, env }
194
+ }
195
+
196
+ // 这个目录里的 .env 写的初始化码;没有为 null
197
+ export async function setupCodeIn(dir) {
198
+ const text = await readFile(join(dir, '.env'), 'utf8').catch(() => null)
199
+ return (text && envValue(text, 'KIOKU_SETUP_CODE')) || null
200
+ }
201
+
202
+ // 这个目录的 compose 项目里有没有 kioku 服务:'none'(没有 compose.yaml,或者没建过容器)、
203
+ // 'stopped'(建过、没在运行)、'running'。查不了的按 'none' 算
204
+ export async function composeState(dir, env) {
205
+ if (!(await stat(join(dir, 'compose.yaml')).catch(() => null))) return 'none'
206
+ const base = ['compose', '-f', join(dir, 'compose.yaml'), '--project-directory', dir, 'ps']
207
+ const services = async (args) => {
208
+ const result = await capture('docker', [...base, ...args], env, { timeout: 30_000 })
209
+ return result.found && result.ok ? result.stdout.split(/\r?\n/).map((line) => line.trim()) : []
210
+ }
211
+ if (!(await services(['-a', '--services'])).includes('kioku')) return 'none'
212
+ return (await services(['--services', '--status', 'running'])).includes('kioku')
213
+ ? 'running'
214
+ : 'stopped'
215
+ }
216
+
217
+ // docker compose 能不能用
218
+ export async function hasCompose(env) {
219
+ const result = await capture('docker', ['compose', 'version'], env, { timeout: 20_000 })
220
+ return Boolean(result.found && result.ok)
221
+ }
222
+
223
+ // 端口有没有被别的程序占着:连得上,或者绑不上。只试绑 127.0.0.1 不够:别的程序听着 [::] 或 0.0.0.0 时
224
+ // 有的系统照样让绑更具体的地址
225
+ export async function portBusy(port, host = '127.0.0.1') {
226
+ const answers = await new Promise((done) => {
227
+ const socket = connect({ port, host })
228
+ socket.setTimeout(1000)
229
+ const finish = (value) => {
230
+ socket.destroy()
231
+ done(value)
232
+ }
233
+ socket.once('connect', () => finish(true))
234
+ socket.once('timeout', () => finish(false))
235
+ socket.once('error', () => finish(false))
236
+ })
237
+ if (answers) return true
238
+ return new Promise((done) => {
239
+ const server = createServer()
240
+ server.once('error', (err) => done(err?.code === 'EADDRINUSE'))
241
+ server.once('listening', () => server.close(() => done(false)))
242
+ server.listen(port, host)
243
+ })
244
+ }
245
+
246
+ // docker compose up -d:用这个目录的 compose.yaml 与 .env。失败时抛 KiokuFailure,输出只取最后几行
247
+ export async function composeUp(dir, env) {
248
+ const result = await capture(
249
+ 'docker',
250
+ ['compose', '-f', join(dir, 'compose.yaml'), '--project-directory', dir, 'up', '-d'],
251
+ env,
252
+ { timeout: 30 * 60_000 },
253
+ )
254
+ if (!result.found) throw new KiokuFailure('没有找到 docker 命令')
255
+ if (!result.ok) {
256
+ const tail = result.output.trim().split(/\r?\n/).slice(-5).join('\n')
257
+ throw new KiokuFailure(`docker compose up 没有成功:\n${tail}`)
258
+ }
259
+ }
260
+
261
+ // 轮询直到 check 返回真,或者到时限;返回有没有等到
262
+ export async function waitUntil(
263
+ check,
264
+ { timeoutMs, intervalMs = 2000, sleep, now = () => Date.now() },
265
+ ) {
266
+ const pause = sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)))
267
+ const deadline = now() + timeoutMs
268
+ while (now() < deadline) {
269
+ if (await check().catch(() => false)) return true
270
+ await pause(intervalMs)
271
+ }
272
+ return false
273
+ }
274
+
275
+ // /v1/health 回 200
276
+ export async function healthy(url) {
277
+ try {
278
+ const res = await fetch(`${url}/v1/health`, { signal: AbortSignal.timeout(3000) })
279
+ return res.status === 200
280
+ } catch {
281
+ return false
282
+ }
283
+ }
284
+
285
+ // 第一个管理员建好了没有(/v1/setup/status 的 needsSetup 变成 false)
286
+ export async function setupDone(url) {
287
+ try {
288
+ const res = await fetch(`${url}/v1/setup/status`, { signal: AbortSignal.timeout(3000) })
289
+ const data = await res.json()
290
+ return res.status === 200 && data?.needsSetup === false
291
+ } catch {
292
+ return false
293
+ }
294
+ }