@kioku-memory/cli 0.0.0-stage → 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ kioku-plugins
2
+ Copyright 2026 lonelyman0108
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # Kioku 的命令行
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Kioku](https://github.com/lonelyman0108/kioku) 是自托管的长期记忆服务。这个包提供 `kioku` 命令,要 Node 18 或更新的版本:
4
+
5
+ ```bash
6
+ npx @kioku-memory/cli doctor
7
+ # 或者装到全局
8
+ npm install -g @kioku-memory/cli
9
+ ```
10
+
11
+ Claude Code 的 kioku 插件自带同一个命令,启用插件后在它的 Bash 工具里直接用 `kioku`,不用另装。
12
+
13
+ ## 子命令
14
+
15
+ | 子命令 | 作用 |
16
+ |---|---|
17
+ | `kioku setup <平台>` | 停用平台自带的长期记忆,由 Kioku 接管 |
18
+ | `kioku doctor [平台]` | 检查地址、访问密钥与平台的配置 |
19
+ | `kioku run -e 变量=<标识>#<字段> -- <命令>` | 向 Kioku 取凭据的值,放进环境变量交给命令 |
20
+
21
+ 每个子命令的完整说明:`kioku <子命令> --help`。现在认得的平台:`claude-code`。
22
+
23
+ ## setup
24
+
25
+ ```bash
26
+ kioku setup claude-code --dry-run # 只看要改什么
27
+ kioku setup claude-code # 停用 Claude Code 的自动记忆
28
+ kioku setup claude-code --undo # 改回去
29
+ ```
30
+
31
+ 只改平台的用户设置里和自带记忆有关的几项(Claude Code 是 `~/.claude/settings.json` 的 `autoMemoryEnabled`),设置里的其他内容不动。第一次改之前把原来的文件备份成同目录下的 `settings.json.kioku-backup`(已有备份时不覆盖),改完新开会话生效。本地已有的记忆文件不会被删掉。
32
+
33
+ - 设置文件是符号链接时改它指向的文件;文件会按 JSON 重新排版(缩进、换行符沿用原来的)。
34
+ - 只看用户设置:当前项目的 `.claude/settings.json`、`.claude/settings.local.json` 里又启用了的话会提醒,要在那里一起改;托管的设置查不到。
35
+
36
+ 不停用的话,平台自带的记忆和 Kioku 会各记一份,两边的内容迟早对不上。
37
+
38
+ ## doctor
39
+
40
+ ```bash
41
+ kioku doctor claude-code
42
+ ```
43
+
44
+ 每项一行:`✓` 正常,`!` 要留意,`✗` 有问题(这时退出码为 1)。查的是:地址连不连得上、访问密钥是否有效、它属于哪个应用、能读写哪些归属、最高敏感级与凭据能力,以及平台这一边插件是否启用、自带的长期记忆是否已停用。不写平台时按当前所在的会话认。
45
+
46
+ ## 地址与访问密钥
47
+
48
+ `doctor` 与 `run` 从环境变量读:
49
+
50
+ - `KIOKU_SERVER_URL`:例如 `https://kioku.example.com`,不带 `/v1`
51
+ - `KIOKU_API_KEY`:在 Kioku 管理界面的「应用」页签发的访问密钥;或者用 `KIOKU_API_KEY_FILE` 指向只含访问密钥的文件
52
+
53
+ 在 Claude Code 里,插件在会话开始时已经配好这两项。`setup` 只改本机的设置文件,用不到它们。
54
+
55
+ `kioku run` 的用法与打码的限度见 [Claude Code 插件的说明](https://github.com/lonelyman0108/kioku-plugins/tree/main/plugins/claude-code#kioku-run)。
package/bin/kioku ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ // kioku 命令的入口,实现在 ../lib/kioku.mjs。插件启用期间,Claude Code 把插件的 bin/ 加进 Bash 工具的 PATH。
3
+ // 没有扩展名的文件按 CommonJS 还是 ES 模块执行,取决于 Node 的版本与上层的 package.json,
4
+ // 所以这里只用两边都能用的写法:动态 import,位置从 process.argv[1] 推
5
+ const load = (name) =>
6
+ Promise.all([import('node:fs'), import('node:path'), import('node:url')]).then(
7
+ ([fs, path, url]) => {
8
+ const lib = path.join(path.dirname(fs.realpathSync(process.argv[1])), '..', 'lib')
9
+ return import(url.pathToFileURL(path.join(lib, name)).href)
10
+ },
11
+ )
12
+
13
+ load('kioku.mjs')
14
+ .then((cli) => cli.main(process.argv.slice(2)))
15
+ .then((code) => {
16
+ process.exitCode = code
17
+ })
18
+ .catch((err) => {
19
+ process.exitCode = 2
20
+ // 只给错误类别:错误文字里可能带着环境变量的值。取不到共用的函数时只说一句固定的
21
+ return load('http.mjs').then(
22
+ ({ errorKind }) => process.stderr.write(`kioku:内部错误(${errorKind(err)})\n`),
23
+ () => process.stderr.write('kioku:内部错误\n'),
24
+ )
25
+ })
package/lib/config.mjs ADDED
@@ -0,0 +1,48 @@
1
+ // kioku 命令的地址与访问密钥:从环境变量与访问密钥文件读
2
+
3
+ import { readFile, utimes } from 'node:fs/promises'
4
+
5
+ import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
6
+
7
+ const NOT_CONFIGURED =
8
+ '缺少 Kioku 的地址或访问密钥:在 Claude Code 里启用 kioku 插件、填好配置后新开会话,或者设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY'
9
+
10
+ // 地址与访问密钥。访问密钥先读插件在会话开始时配好的 KIOKU_API_KEY_FILE,读不到再用 KIOKU_API_KEY;
11
+ // 两样都没有才报错,报错只写文件的位置与错误类别
12
+ export async function loadConfig(env) {
13
+ const url = (env.KIOKU_SERVER_URL ?? '').trim().replace(/\/+$/, '')
14
+ const file = env.KIOKU_API_KEY_FILE
15
+ let key = ''
16
+ let fileProblem
17
+ if (file) {
18
+ try {
19
+ key = (await readFile(file, 'utf8')).trim()
20
+ if (!key) fileProblem = '文件是空的'
21
+ } catch (err) {
22
+ fileProblem = errorKind(err)
23
+ }
24
+ // 用的时候更新修改时间:会话开始时会删掉很久没用过的访问密钥文件
25
+ if (key) await utimes(file, new Date(), new Date()).catch(() => {})
26
+ }
27
+ if (!key) key = (env.KIOKU_API_KEY ?? '').trim()
28
+ if (!url) throw new KiokuFailure(NOT_CONFIGURED)
29
+ if (!key) {
30
+ throw new KiokuFailure(
31
+ fileProblem
32
+ ? `无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`
33
+ : NOT_CONFIGURED,
34
+ )
35
+ }
36
+ let protocol
37
+ try {
38
+ protocol = new URL(url).protocol
39
+ } catch {
40
+ throw new KiokuFailure('KIOKU_SERVER_URL 不是有效的地址')
41
+ }
42
+ if (protocol !== 'http:' && protocol !== 'https:') {
43
+ throw new KiokuFailure('KIOKU_SERVER_URL 要以 http:// 或 https:// 开头')
44
+ }
45
+ const problem = keyFormatError(key)
46
+ if (problem) throw new KiokuFailure(problem)
47
+ return { url, key }
48
+ }
package/lib/doctor.mjs ADDED
@@ -0,0 +1,163 @@
1
+ // kioku doctor:检查地址与访问密钥能不能用、访问密钥的权限,以及平台这一边配好没有。
2
+ // 每项一行:✓ 正常,! 要留意,✗ 有问题;有 ✗ 时退出码为 1
3
+
4
+ import { loadConfig } from './config.mjs'
5
+ import { failureText, fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
6
+ import { detectPlatform, platformNames, PLATFORMS } from './platforms.mjs'
7
+ import { readSettings } from './setup.mjs'
8
+ import { UsageError } from './usage.mjs'
9
+
10
+ export const DOCTOR_USAGE = `用法:kioku doctor [平台]
11
+
12
+ 检查 Kioku 的地址与访问密钥、访问密钥的权限,以及平台的配置(插件是否启用、自带的长期记忆是否已停用)。
13
+
14
+ [平台] ${platformNames()};不写时按当前所在的会话认,认不出就只查地址与访问密钥
15
+
16
+ 有问题的项以 ✗ 开头,这时退出码为 1。
17
+ `
18
+
19
+ const TIMEOUT = 8000
20
+ // 与管理界面的用词一致
21
+ const LAYERS = {
22
+ core: '通用',
23
+ persona: '人格',
24
+ app: '应用',
25
+ user: '本人',
26
+ subject: '联系人',
27
+ episode: '会话',
28
+ }
29
+ const SENSITIVITIES = { public: '公开', internal: '内部', private: '私密', secret: '机密' }
30
+ const CAPABILITIES = { none: '不可用', use: '取用', manage: '管理' }
31
+
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
+ function named(names, value) {
48
+ return Object.hasOwn(names, value) ? names[value] : plain(value)
49
+ }
50
+
51
+ function layersText(layers) {
52
+ if (!Array.isArray(layers) || !layers.length) return '无'
53
+ return layers.map((layer) => named(LAYERS, layer)).join('、')
54
+ }
55
+
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
+ export function parseDoctorArgs(argv) {
86
+ const names = []
87
+ for (const arg of argv) {
88
+ if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
89
+ names.push(arg)
90
+ }
91
+ if (names.length > 1) throw new UsageError('最多写一个平台')
92
+ if (names.length && !Object.hasOwn(PLATFORMS, names[0])) {
93
+ throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
94
+ }
95
+ return { platform: names[0] ?? null }
96
+ }
97
+
98
+ export async function doctor(
99
+ argv,
100
+ { env = process.env, out = process.stdout, cwd = process.cwd() } = {},
101
+ ) {
102
+ const id = parseDoctorArgs(argv).platform ?? detectPlatform(env)
103
+ const platform = id ? PLATFORMS[id] : null
104
+ let failed = false
105
+ const ok = (text) => out.write(`✓ ${text}\n`)
106
+ const warn = (text) => out.write(`! ${text}\n`)
107
+ const bad = (text) => {
108
+ failed = true
109
+ out.write(`✗ ${text}\n`)
110
+ }
111
+
112
+ let who = null
113
+ try {
114
+ const config = await loadConfig(env)
115
+ ok(`地址 ${shownUrl(config.url)}`)
116
+ who = await whoami(config)
117
+ } catch (err) {
118
+ bad(failureText(err))
119
+ }
120
+ if (who) {
121
+ const { app, scopes } = who
122
+ ok(
123
+ `访问密钥可用:应用 ${plain(app.name)}(${plain(app.slug)}),运行时 ${plain(app.runtimeFamily)}`,
124
+ )
125
+ out.write(` 读:${layersText(scopes.readLayers)}\n`)
126
+ out.write(` 写:${layersText(scopes.writeLayers)}\n`)
127
+ out.write(` 最高敏感级:${named(SENSITIVITIES, scopes.maxSensitivity)}\n`)
128
+ out.write(` 凭据:${named(CAPABILITIES, scopes.credentials ?? 'none')}\n`)
129
+ if (platform && app.runtimeFamily !== platform.runtimeFamily) {
130
+ warn(
131
+ `这个应用的运行时不是 ${platform.runtimeFamily},注入的内容不按 ${platform.name} 的格式:在管理界面为 ${platform.name} 另建一个应用`,
132
+ )
133
+ }
134
+ }
135
+
136
+ if (!platform) {
137
+ out.write(`没有认出平台,只查了地址与访问密钥;要查平台的配置,写上平台:${platformNames()}\n`)
138
+ return failed ? 1 : 0
139
+ }
140
+ let settings = null
141
+ try {
142
+ settings = (await readSettings(platform.settingsFile(env))).settings
143
+ } catch (err) {
144
+ bad(failureText(err))
145
+ }
146
+ if (settings) {
147
+ if (platform.pluginActive(settings, env)) ok(`${platform.name} 的 kioku 插件已启用`)
148
+ else warn(`用户设置里没有启用 ${platform.name} 的 kioku 插件:${platform.pluginHint}`)
149
+ const by = platform.memory.disabledBy(settings, env)
150
+ const again = by ? await platform.memory.enabledBy(env, cwd) : null
151
+ if (again) {
152
+ warn(
153
+ `${platform.name} 的${platform.memory.name}在${by}里停用了,${again}又启用了它:要在那里一起改`,
154
+ )
155
+ } else if (by) ok(`${platform.name} 的${platform.memory.name}已停用(${by})`)
156
+ else {
157
+ warn(
158
+ `${platform.name} 的${platform.memory.name}还开着,会和 Kioku 各记一份:运行 kioku setup ${id} 停用它`,
159
+ )
160
+ }
161
+ }
162
+ return failed ? 1 : 0
163
+ }
package/lib/http.mjs ADDED
@@ -0,0 +1,57 @@
1
+ // 钩子与 kioku 命令共用的访问密钥检查与报错。报错只给插件自己写的文字或错误类别:
2
+ // fetch 的报错会带上整个 Authorization 请求头,响应解析失败的文字会带上响应的开头
3
+
4
+ // 访问密钥只能是可见的 ASCII 字符:别的字符放不进请求头,fetch 报错时会把整个请求头写进错误文字
5
+ const KEY = /^[\x21-\x7e]+$/
6
+ // 错误码(ECONNREFUSED、UND_ERR_SOCKET 这类)与错误类名(TypeError 这类)的样子
7
+ const CODE = /^[A-Z][A-Z0-9_]*$/
8
+ const NAME = /^[A-Z][A-Za-z]*$/
9
+
10
+ // 文字由插件自己写、不含值和访问密钥的失败,可以原样打印
11
+ export class KiokuFailure extends Error {}
12
+
13
+ // 访问密钥的格式不对时返回原因,否则为 null
14
+ export function keyFormatError(key) {
15
+ return KEY.test(key) ? null : '访问密钥的格式不对:只能是可见的 ASCII 字符,不能有空白'
16
+ }
17
+
18
+ // 错误的类别:只取 code 或 name,不取文字
19
+ export function errorKind(err) {
20
+ if (typeof err?.code === 'string' && CODE.test(err.code)) return err.code
21
+ if (typeof err?.name === 'string' && NAME.test(err.name)) return err.name
22
+ return '未知错误'
23
+ }
24
+
25
+ // fetch 失败的原因:超时,或者连不上(附 cause 的错误码)
26
+ export function fetchFailure(err, timeoutMs) {
27
+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
28
+ return `连接 Kioku 超时(${timeoutMs / 1000} 秒)`
29
+ }
30
+ const code = err?.cause?.code
31
+ return typeof code === 'string' && CODE.test(code)
32
+ ? `无法连接 Kioku(${code})`
33
+ : '无法连接 Kioku'
34
+ }
35
+
36
+ // 收到跳转(3xx)时的报错:说明要把地址改成跳转之后的地址。请求都不跟着跳转走,访问密钥只发给配置的地址;
37
+ // 跳转目标只给协议与主机,路径与查询参数里可能带着令牌;跳到同一个主机、或者没给目标时不举例
38
+ export function redirectError(status, location, url) {
39
+ let origin
40
+ try {
41
+ const target = new URL(location ?? '', `${url}/`)
42
+ const web = target.protocol === 'https:' || target.protocol === 'http:'
43
+ if (web && target.origin !== new URL(url).origin) origin = target.origin
44
+ } catch {
45
+ // 跳转目标解析不了时不举例
46
+ }
47
+ return `Kioku 返回了跳转(${status}),把地址改成跳转之后的地址${origin ? `(例如 ${origin})` : ''}`
48
+ }
49
+
50
+ export function isRedirect(status) {
51
+ return status >= 300 && status < 400
52
+ }
53
+
54
+ // 要打印的失败原因:插件自己写的原样给出,别的只给类别
55
+ export function failureText(err) {
56
+ return err instanceof KiokuFailure ? err.message : errorKind(err)
57
+ }