@jetcrab/pi-desk-sdk 1.1.18-dev → 1.1.20-dev
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/README.md +26 -2
- package/dist/browser.d.ts +14 -0
- package/dist/config-api.d.ts +20 -0
- package/dist/config-api.js +1 -0
- package/dist/config-encryption.d.ts +10 -0
- package/dist/config-encryption.js +114 -0
- package/dist/config-paths.d.ts +9 -0
- package/dist/config-paths.js +50 -0
- package/dist/config-storage.d.ts +1 -1
- package/dist/config-storage.js +6 -2
- package/dist/config-store.d.ts +13 -0
- package/dist/config-store.js +139 -0
- package/dist/config.d.ts +4 -0
- package/dist/config.js +11 -1
- package/dist/entry.d.ts +3 -0
- package/dist/host-runtime/base.js +36 -9
- package/dist/react-base.d.ts +1 -0
- package/dist/react-base.js +1 -0
- package/dist/react-status-capsule.d.ts +16 -0
- package/dist/react-status-capsule.js +74 -0
- package/dist/session.d.ts +3 -0
- package/dist/session.js +2 -0
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -2,8 +2,32 @@
|
|
|
2
2
|
|
|
3
3
|
包名:`@jetcrab/pi-desk-sdk`。公开接口以本版本 `package.json` 的 exports 和对应 TypeScript 声明为准。
|
|
4
4
|
|
|
5
|
-
Node
|
|
5
|
+
Node 与 Session 插件通过绑定身份的 `plugin.config` 使用以下四个异步接口,配置按 JSON Pointer 与 `*` 路径选择加解密:
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
```ts
|
|
8
|
+
await plugin.config.set(
|
|
9
|
+
{ server: { port: 2222, password: 'example-password' } },
|
|
10
|
+
{ cwd, encryptPaths: ['/server/password'] }
|
|
11
|
+
)
|
|
12
|
+
const conf = await plugin.config.get({
|
|
13
|
+
cwd,
|
|
14
|
+
defaults: { server: { host: 'localhost', port: 22 } },
|
|
15
|
+
decryptPaths: ['/server/password']
|
|
16
|
+
})
|
|
17
|
+
const encrypted = await plugin.config.encrypt({ token: 'example-token' })
|
|
18
|
+
const value = await plugin.config.decrypt(encrypted)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- `set(conf, options?)`:选项为 `{ cwd?: string, encryptPaths?: readonly string[] }`。仅整体替换选定文件内自身分组,保留其他分组和注释,不保存默认值或继承值。
|
|
22
|
+
- `get(options?)`:选项为 `{ cwd?: string, defaults?: PluginJsonObject, decryptPaths?: readonly string[], inherit?: boolean }`。默认按默认值 → 全局 → 项目递归覆盖对象字段;数组、标量和 `null` 整体替换,`false`、`0`、`''`、`[]` 均有效,空对象继承已有字段。`inherit: false` 只读选定层,不应用 `defaults` 或额外全局继承,供配置编辑和项目发现使用,不增加第五个接口。
|
|
23
|
+
- 不传 `cwd` 时只使用 `<AgentDir>/config/pi-desk.yaml`;传入时项目层固定为 `<cwd>/.pi/pi-desk.yaml`。`cwd` 必须是已存在的绝对普通目录,不读取进程工作目录、不搜索父目录。调用方负责确认项目信任;没有可信项目上下文时不传 `cwd`。
|
|
24
|
+
- 各持久层先按 `decryptPaths` 解密再合并;未指定路径上的密文原样参与覆盖。默认值不自动解密,读取不回写,不修改输入。文件缺失视为空层;YAML、权限或解密错误明确失败,不回退旧格式。
|
|
25
|
+
- 密文内联,系统仅托管主密钥;项目加解密始终使用全局 AgentDir 配置目录的密钥身份。路径数组参数旧调用不再支持。
|
|
26
|
+
|
|
27
|
+
`/config` 提供宿主装配和文件级工具,`getProjectConfigPath(cwd)` 返回固定项目文件位置,`readConfigSection()` 保持全局同步读取合同,不作为第五个插件方法。`/config` 的旧文件级工具与 `/secrets` 的旧凭据接口作为历史工具兼容 API 保留;Pi Desk 自有新版功能不消费旧配置。旧文件不迁移、不删除、不回退读取;原生 Pi 配置位置和格式保持不变,Markdown Agent 定义与 Skills 等资源仍独立。共享 YAML 继续使用跨进程锁、原子写入、Owner 校验、8 MiB 容量限制及符号链接边界。
|
|
28
|
+
|
|
29
|
+
宿主统一备份全局和既有项目的 `pi-desk.yaml`,动态识别 `enc:v1:` 内联密文,并在恢复时用目标 AgentDir 的主密钥重新加密。插件不重复声明共享文件归属,仍可通过 `piDesk.environment.files` 声明自有 data 与配套资源。完整调用与路径合同见[插件指南](../../docs/plugins.md#配置与凭据node)。
|
|
30
|
+
|
|
31
|
+
SDK 的运行依赖为 Zod(协议 Schema)、`yaml`(统一配置)、`proper-lockfile`(Node 跨进程锁)和 `@napi-rs/keyring`(Node 系统持久密钥存储)。协议与 Browser 子入口不加载这些 Node 配置或凭据能力,非 React 使用不要求安装公共 UI 库。
|
|
8
32
|
|
|
9
33
|
本包自有代码使用 Apache-2.0,见 [LICENSE](./LICENSE)。第三方代码继续遵循其原有许可,构建时保留上游法律注释。
|
package/dist/browser.d.ts
CHANGED
|
@@ -179,7 +179,21 @@ export interface BrowserTunnelHost {
|
|
|
179
179
|
remotePort: number;
|
|
180
180
|
}): BrowserTunnelHandle;
|
|
181
181
|
}
|
|
182
|
+
export interface BrowserFloatingHandle {
|
|
183
|
+
close(): void;
|
|
184
|
+
}
|
|
185
|
+
export interface BrowserFloatingImplementation {
|
|
186
|
+
mount: BrowserMount<BrowserFloatingHandle>;
|
|
187
|
+
}
|
|
188
|
+
export interface BrowserFloatingOpenInput {
|
|
189
|
+
id: string;
|
|
190
|
+
load(): Promise<BrowserFloatingImplementation>;
|
|
191
|
+
}
|
|
192
|
+
export interface BrowserFloatingHost {
|
|
193
|
+
open(input: BrowserFloatingOpenInput): BrowserFloatingHandle;
|
|
194
|
+
}
|
|
182
195
|
export interface BrowserPluginHost {
|
|
196
|
+
readonly floating: BrowserFloatingHost;
|
|
183
197
|
readonly events: HostEvents<BrowserHostEventMap>;
|
|
184
198
|
readonly settings: HostSettings;
|
|
185
199
|
/** 映射当前工作台后端的已发布 TCP 端口;旧宿主或无原生能力时不可用。 */
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { PluginJsonObject, PluginJsonValue } from './shared.js';
|
|
2
|
+
/** cwd 由调用方确认可信;仅使用该项目,不搜索父目录。 */
|
|
3
|
+
export interface PluginConfigGetOptions {
|
|
4
|
+
cwd?: string;
|
|
5
|
+
/** false 时只读目标层,不应用全局继承或 defaults。 */
|
|
6
|
+
inherit?: boolean;
|
|
7
|
+
defaults?: PluginJsonObject;
|
|
8
|
+
decryptPaths?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
export interface PluginConfigSetOptions {
|
|
11
|
+
cwd?: string;
|
|
12
|
+
encryptPaths?: readonly string[];
|
|
13
|
+
}
|
|
14
|
+
/** 宿主按插件身份绑定;不暴露任意文件位置或密钥。 */
|
|
15
|
+
export interface PluginConfig {
|
|
16
|
+
encrypt(value: PluginJsonValue): Promise<string>;
|
|
17
|
+
decrypt(value: string): Promise<PluginJsonValue>;
|
|
18
|
+
set(conf: PluginJsonObject, options?: PluginConfigSetOptions): Promise<void>;
|
|
19
|
+
get(options?: PluginConfigGetOptions): Promise<PluginJsonObject>;
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { PluginJsonValue } from './shared.js';
|
|
2
|
+
export interface ConfigKeyOptions {
|
|
3
|
+
/** 仅由宿主或隔离测试注入,不属于插件配置接口。 */
|
|
4
|
+
keyProvider?: () => Promise<Uint8Array>;
|
|
5
|
+
}
|
|
6
|
+
export declare function isEncryptedConfigValue(value: unknown): value is string;
|
|
7
|
+
export declare function hasEncryptedConfigValue(value: PluginJsonValue): boolean;
|
|
8
|
+
export declare function loadConfigKey(path: string, encryptedExists: boolean, options: ConfigKeyOptions, assertActive: () => void): Promise<Buffer>;
|
|
9
|
+
export declare function encryptConfigValue(value: PluginJsonValue, key: Buffer): string;
|
|
10
|
+
export declare function decryptConfigValue(value: string, key: Buffer): PluginJsonValue;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { readStorageFile } from "./config-storage.js";
|
|
6
|
+
const prefix = 'enc:v1:';
|
|
7
|
+
const aad = Buffer.from('pi-desk/config/v1');
|
|
8
|
+
export function isEncryptedConfigValue(value) {
|
|
9
|
+
return typeof value === 'string' && value.startsWith(prefix);
|
|
10
|
+
}
|
|
11
|
+
export function hasEncryptedConfigValue(value) {
|
|
12
|
+
if (isEncryptedConfigValue(value))
|
|
13
|
+
return true;
|
|
14
|
+
return value !== null && typeof value === 'object'
|
|
15
|
+
? Object.values(value).some(hasEncryptedConfigValue)
|
|
16
|
+
: false;
|
|
17
|
+
}
|
|
18
|
+
function keyBytes(value) {
|
|
19
|
+
if (!(value instanceof Uint8Array) || value.byteLength !== 32) {
|
|
20
|
+
throw new Error('配置主密钥必须是原始 32 字节');
|
|
21
|
+
}
|
|
22
|
+
return Buffer.from(value);
|
|
23
|
+
}
|
|
24
|
+
export async function loadConfigKey(path, encryptedExists, options, assertActive) {
|
|
25
|
+
if (options.keyProvider)
|
|
26
|
+
return keyBytes(await options.keyProvider());
|
|
27
|
+
const file = process.env.PI_DESK_SECRET_KEY_FILE;
|
|
28
|
+
if (file !== undefined) {
|
|
29
|
+
if (!file)
|
|
30
|
+
throw new Error('PI_DESK_SECRET_KEY_FILE 必须指定外部密钥文件');
|
|
31
|
+
const bytes = readStorageFile(resolve(file));
|
|
32
|
+
if (bytes === null)
|
|
33
|
+
throw new Error('配置外部密钥文件不存在');
|
|
34
|
+
try {
|
|
35
|
+
return keyBytes(bytes);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
bytes.fill(0);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const { Entry } = await import('@napi-rs/keyring');
|
|
43
|
+
const directory = realpathSync(dirname(path));
|
|
44
|
+
const identity = process.platform === 'win32' ? directory.toLowerCase() : directory;
|
|
45
|
+
const account = createHash('sha256').update(identity).digest('hex');
|
|
46
|
+
const entry = new Entry('pi-desk.config', account, { linux: { store: 'secret-service' } });
|
|
47
|
+
const stored = entry.getPassword();
|
|
48
|
+
if (stored !== null) {
|
|
49
|
+
const key = Buffer.from(stored, 'base64');
|
|
50
|
+
if (key.length !== 32 || key.toString('base64') !== stored) {
|
|
51
|
+
key.fill(0);
|
|
52
|
+
throw new Error('配置主密钥格式无效');
|
|
53
|
+
}
|
|
54
|
+
return key;
|
|
55
|
+
}
|
|
56
|
+
if (encryptedExists)
|
|
57
|
+
throw new Error('配置密文已存在但主密钥缺失,拒绝生成替代密钥');
|
|
58
|
+
assertActive();
|
|
59
|
+
const key = randomBytes(32);
|
|
60
|
+
try {
|
|
61
|
+
entry.setPassword(key.toString('base64'));
|
|
62
|
+
if (entry.getPassword() !== key.toString('base64'))
|
|
63
|
+
throw new Error('主密钥回读失败');
|
|
64
|
+
return key;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
key.fill(0);
|
|
68
|
+
throw new Error('保存配置主密钥失败');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (cause) {
|
|
72
|
+
// 系统原生错误可能带凭据正文,不向插件转发。
|
|
73
|
+
const message = cause instanceof Error && /^配置(密文|主密钥)/u.test(cause.message)
|
|
74
|
+
? cause.message
|
|
75
|
+
: '系统钥匙串不可用,无法取得配置主密钥';
|
|
76
|
+
throw new Error(message);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export function encryptConfigValue(value, key) {
|
|
80
|
+
const nonce = randomBytes(12);
|
|
81
|
+
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
|
82
|
+
cipher.setAAD(aad);
|
|
83
|
+
const plaintext = Buffer.from(JSON.stringify(z.json().parse(value)));
|
|
84
|
+
try {
|
|
85
|
+
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
86
|
+
return prefix + Buffer.concat([nonce, cipher.getAuthTag(), encrypted]).toString('base64');
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
plaintext.fill(0);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function decryptConfigValue(value, key) {
|
|
93
|
+
try {
|
|
94
|
+
if (!isEncryptedConfigValue(value))
|
|
95
|
+
throw new Error();
|
|
96
|
+
const encoded = value.slice(prefix.length);
|
|
97
|
+
const bytes = Buffer.from(encoded, 'base64');
|
|
98
|
+
if (bytes.length < 29 || bytes.toString('base64') !== encoded)
|
|
99
|
+
throw new Error();
|
|
100
|
+
const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12));
|
|
101
|
+
decipher.setAAD(aad);
|
|
102
|
+
decipher.setAuthTag(bytes.subarray(12, 28));
|
|
103
|
+
const plaintext = Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]);
|
|
104
|
+
try {
|
|
105
|
+
return z.json().parse(JSON.parse(plaintext.toString('utf8')));
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
plaintext.fill(0);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
throw new Error('配置密文认证失败或格式无效');
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PluginJsonObject, PluginJsonValue } from './shared.js';
|
|
2
|
+
export interface ConfigValueLocation {
|
|
3
|
+
parent: PluginJsonObject | PluginJsonValue[];
|
|
4
|
+
key: string;
|
|
5
|
+
parts: string[];
|
|
6
|
+
}
|
|
7
|
+
export declare function configValueLocations(conf: PluginJsonObject, paths: readonly string[]): ConfigValueLocation[];
|
|
8
|
+
export declare function getConfigLocation(location: ConfigValueLocation): PluginJsonValue;
|
|
9
|
+
export declare function setConfigLocation(location: ConfigValueLocation, value: PluginJsonValue): void;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export function configValueLocations(conf, paths) {
|
|
2
|
+
const found = new Map();
|
|
3
|
+
for (const path of paths) {
|
|
4
|
+
if (typeof path !== 'string' || !path.startsWith('/') || /~(?![01])/u.test(path)) {
|
|
5
|
+
throw new Error('配置路径必须是非根 JSON Pointer,可用 * 匹配当前层所有成员');
|
|
6
|
+
}
|
|
7
|
+
const parts = path
|
|
8
|
+
.slice(1)
|
|
9
|
+
.split('/')
|
|
10
|
+
.map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'));
|
|
11
|
+
function visit(value, index, prefix) {
|
|
12
|
+
if (value === null || typeof value !== 'object')
|
|
13
|
+
return;
|
|
14
|
+
const part = parts[index];
|
|
15
|
+
for (const key of part === '*' ? Object.keys(value) : [part]) {
|
|
16
|
+
if (!Object.prototype.propertyIsEnumerable.call(value, key))
|
|
17
|
+
continue;
|
|
18
|
+
const location = [...prefix, key];
|
|
19
|
+
if (index === parts.length - 1) {
|
|
20
|
+
found.set(JSON.stringify(location), { parent: value, key, parts: location });
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
const child = Array.isArray(value) ? value[Number(key)] : value[key];
|
|
24
|
+
visit(child, index + 1, location);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
visit(conf, 0, []);
|
|
29
|
+
}
|
|
30
|
+
const locations = [...found.values()];
|
|
31
|
+
for (const current of locations) {
|
|
32
|
+
for (let length = 1; length < current.parts.length; length += 1) {
|
|
33
|
+
if (found.has(JSON.stringify(current.parts.slice(0, length)))) {
|
|
34
|
+
throw new Error('配置加解密路径不能同时包含父节点和子节点');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return locations;
|
|
39
|
+
}
|
|
40
|
+
export function getConfigLocation(location) {
|
|
41
|
+
return Array.isArray(location.parent)
|
|
42
|
+
? location.parent[Number(location.key)]
|
|
43
|
+
: location.parent[location.key];
|
|
44
|
+
}
|
|
45
|
+
export function setConfigLocation(location, value) {
|
|
46
|
+
if (Array.isArray(location.parent))
|
|
47
|
+
location.parent[Number(location.key)] = value;
|
|
48
|
+
else
|
|
49
|
+
location.parent[location.key] = value;
|
|
50
|
+
}
|
package/dist/config-storage.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export declare function ensureStorageDirectory(path: string): void;
|
|
2
|
-
export declare function readStorageFile(path: string): Buffer | null;
|
|
2
|
+
export declare function readStorageFile(path: string, maximumBytes?: number): Buffer | null;
|
|
3
3
|
export declare function writeStorageFile(path: string, content: Buffer, expected: Buffer | null): void;
|
|
4
4
|
export declare function withStorageLock<T>(path: string, action: (assertLocked: () => void) => Promise<T>): Promise<T>;
|
package/dist/config-storage.js
CHANGED
|
@@ -34,13 +34,16 @@ function assertDirectories(path) {
|
|
|
34
34
|
throw storageError('检查配置目录', path, error);
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
-
export function readStorageFile(path) {
|
|
37
|
+
export function readStorageFile(path, maximumBytes) {
|
|
38
38
|
assertDirectories(dirname(path));
|
|
39
39
|
let descriptor;
|
|
40
40
|
try {
|
|
41
41
|
const stat = lstatSync(path);
|
|
42
42
|
if (!stat.isFile())
|
|
43
43
|
throw new Error(`拒绝读取非普通配置文件或符号链接:${path}`);
|
|
44
|
+
if (maximumBytes !== undefined && stat.size > maximumBytes) {
|
|
45
|
+
throw new Error(`拒绝读取超过容量限制的配置文件:${path}`);
|
|
46
|
+
}
|
|
44
47
|
descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
45
48
|
const opened = fstatSync(descriptor);
|
|
46
49
|
if (!opened.isFile() || opened.ino !== stat.ino || opened.dev !== stat.dev) {
|
|
@@ -83,7 +86,8 @@ export function writeStorageFile(path, content, expected) {
|
|
|
83
86
|
let descriptor;
|
|
84
87
|
let committed = false;
|
|
85
88
|
try {
|
|
86
|
-
|
|
89
|
+
const mode = expected !== null && process.platform !== 'win32' ? lstatSync(path).mode & 0o600 : 0o600;
|
|
90
|
+
descriptor = openSync(temporary, 'wx', mode);
|
|
87
91
|
writeFileSync(descriptor, content);
|
|
88
92
|
fsyncSync(descriptor);
|
|
89
93
|
closeSync(descriptor);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { PluginConfig } from './config-api.js';
|
|
2
|
+
import { type ConfigKeyOptions } from './config-encryption.ts';
|
|
3
|
+
import { type PluginJsonObject } from './shared.ts';
|
|
4
|
+
export interface ConfigStoreOptions extends ConfigKeyOptions {
|
|
5
|
+
agentDir?: string;
|
|
6
|
+
/** 宿主 Owner 失效后禁止新操作及尚未发布的写入。 */
|
|
7
|
+
assertActive?: () => void;
|
|
8
|
+
}
|
|
9
|
+
export declare function getUnifiedConfigPath(agentDir?: string): string;
|
|
10
|
+
/** 宿主同步启动读取普通配置;插件业务使用四接口,不从这里解密。 */
|
|
11
|
+
export declare function readConfigSection(namespace: 'pi-desk' | 'plugins', name: string, agentDir?: string): PluginJsonObject;
|
|
12
|
+
/** 供宿主装配与原生绑定使用,业务插件直接使用绑定后的 plugin.config。 */
|
|
13
|
+
export declare function bindConfigStore(namespace: 'pi-desk' | 'plugins', name: string, options?: ConfigStoreOptions): PluginConfig;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { parseDocument } from 'yaml';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { getConfigPath, getProjectConfigPath } from "./config.js";
|
|
5
|
+
import { ensureStorageDirectory, readStorageFile, withStorageLock, writeStorageFile } from "./config-storage.js";
|
|
6
|
+
import { configValueLocations, getConfigLocation, setConfigLocation } from "./config-paths.js";
|
|
7
|
+
import { decryptConfigValue, encryptConfigValue, hasEncryptedConfigValue, isEncryptedConfigValue, loadConfigKey } from "./config-encryption.js";
|
|
8
|
+
import { normalizePluginIdentifier } from "./shared.js";
|
|
9
|
+
const dictionary = z.record(z.string(), z.json());
|
|
10
|
+
const maxConfigBytes = 8 * 1024 * 1024;
|
|
11
|
+
export function getUnifiedConfigPath(agentDir) {
|
|
12
|
+
return getConfigPath('pi-desk.yaml', agentDir);
|
|
13
|
+
}
|
|
14
|
+
function readDocument(path) {
|
|
15
|
+
const previous = readStorageFile(path, maxConfigBytes);
|
|
16
|
+
const document = parseDocument(previous?.toString('utf8') ?? '{}\n', {
|
|
17
|
+
uniqueKeys: true,
|
|
18
|
+
schema: 'core'
|
|
19
|
+
});
|
|
20
|
+
if (document.errors.length)
|
|
21
|
+
throw new Error(`统一配置 YAML 无法解析:${path}`);
|
|
22
|
+
const root = dictionary.parse(document.toJS({ maxAliasCount: 100 }) ?? {});
|
|
23
|
+
for (const namespace of ['pi-desk', 'plugins']) {
|
|
24
|
+
if (Object.hasOwn(root, namespace))
|
|
25
|
+
dictionary.parse(root[namespace]);
|
|
26
|
+
}
|
|
27
|
+
return { previous, document, root };
|
|
28
|
+
}
|
|
29
|
+
function isObject(value) {
|
|
30
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
31
|
+
}
|
|
32
|
+
function mergeConfig(base, override) {
|
|
33
|
+
return {
|
|
34
|
+
...base,
|
|
35
|
+
...Object.fromEntries(Object.entries(override).map(([key, value]) => {
|
|
36
|
+
const previous = Object.hasOwn(base, key) ? base[key] : undefined;
|
|
37
|
+
return [key, isObject(previous) && isObject(value) ? mergeConfig(previous, value) : value];
|
|
38
|
+
}))
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** 宿主同步启动读取普通配置;插件业务使用四接口,不从这里解密。 */
|
|
42
|
+
export function readConfigSection(namespace, name, agentDir) {
|
|
43
|
+
const { root } = readDocument(getUnifiedConfigPath(agentDir));
|
|
44
|
+
return dictionary.parse(dictionary.parse(root[namespace] ?? {})[name] ?? {});
|
|
45
|
+
}
|
|
46
|
+
/** 供宿主装配与原生绑定使用,业务插件直接使用绑定后的 plugin.config。 */
|
|
47
|
+
export function bindConfigStore(namespace, name, options = {}) {
|
|
48
|
+
name = normalizePluginIdentifier(name, 'pluginName');
|
|
49
|
+
const globalPath = getUnifiedConfigPath(options.agentDir);
|
|
50
|
+
const assertActive = () => options.assertActive?.();
|
|
51
|
+
async function access(path, action) {
|
|
52
|
+
assertActive();
|
|
53
|
+
ensureStorageDirectory(dirname(globalPath));
|
|
54
|
+
ensureStorageDirectory(dirname(path));
|
|
55
|
+
return withStorageLock(path, async (assertLocked) => {
|
|
56
|
+
const assertCurrent = () => {
|
|
57
|
+
assertLocked();
|
|
58
|
+
assertActive();
|
|
59
|
+
};
|
|
60
|
+
assertCurrent();
|
|
61
|
+
const state = readDocument(path);
|
|
62
|
+
let loadedKey;
|
|
63
|
+
try {
|
|
64
|
+
return await action(state, async (required) => {
|
|
65
|
+
const loadKey = async (assertKeyLocked) => {
|
|
66
|
+
const assertKeyCurrent = () => {
|
|
67
|
+
assertKeyLocked();
|
|
68
|
+
assertCurrent();
|
|
69
|
+
};
|
|
70
|
+
assertKeyCurrent();
|
|
71
|
+
return loadConfigKey(globalPath, required ||
|
|
72
|
+
hasEncryptedConfigValue(state.root) ||
|
|
73
|
+
(path !== globalPath && hasEncryptedConfigValue(readDocument(globalPath).root)), options, assertKeyCurrent);
|
|
74
|
+
};
|
|
75
|
+
// 不同项目共享主密钥;首次创建也必须按全局身份跨进程序列化。
|
|
76
|
+
loadedKey ??=
|
|
77
|
+
path === globalPath
|
|
78
|
+
? await loadKey(assertCurrent)
|
|
79
|
+
: await withStorageLock(globalPath, loadKey);
|
|
80
|
+
assertCurrent();
|
|
81
|
+
return loadedKey;
|
|
82
|
+
}, assertCurrent);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
loadedKey?.fill(0);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
async encrypt(value) {
|
|
91
|
+
return access(globalPath, async (_state, key) => encryptConfigValue(value, await key(false)));
|
|
92
|
+
},
|
|
93
|
+
async decrypt(value) {
|
|
94
|
+
return access(globalPath, async (_state, key) => decryptConfigValue(value, await key(true)));
|
|
95
|
+
},
|
|
96
|
+
async set(conf, setOptions = {}) {
|
|
97
|
+
assertActive();
|
|
98
|
+
const path = setOptions.cwd === undefined ? globalPath : getProjectConfigPath(setOptions.cwd);
|
|
99
|
+
const next = structuredClone(dictionary.parse(conf));
|
|
100
|
+
const locations = configValueLocations(next, setOptions.encryptPaths ?? []);
|
|
101
|
+
await access(path, async (state, key, assertCurrent) => {
|
|
102
|
+
for (const location of locations) {
|
|
103
|
+
setConfigLocation(location, encryptConfigValue(getConfigLocation(location), await key(false)));
|
|
104
|
+
}
|
|
105
|
+
state.document.setIn([namespace, name], next);
|
|
106
|
+
const content = Buffer.from(state.document.toString());
|
|
107
|
+
if (content.byteLength > maxConfigBytes)
|
|
108
|
+
throw new Error('统一配置文件不能超过 8 MiB');
|
|
109
|
+
assertCurrent();
|
|
110
|
+
writeStorageFile(path, content, state.previous);
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
async get(getOptions = {}) {
|
|
114
|
+
assertActive();
|
|
115
|
+
const projectPath = getOptions.cwd === undefined ? undefined : getProjectConfigPath(getOptions.cwd);
|
|
116
|
+
const paths = getOptions.inherit === false
|
|
117
|
+
? [projectPath ?? globalPath]
|
|
118
|
+
: projectPath === undefined
|
|
119
|
+
? [globalPath]
|
|
120
|
+
: [globalPath, projectPath];
|
|
121
|
+
let result = structuredClone(dictionary.parse(getOptions.inherit === false ? {} : (getOptions.defaults ?? {})));
|
|
122
|
+
for (const path of paths) {
|
|
123
|
+
const layer = await access(path, async ({ root }, key) => {
|
|
124
|
+
const section = dictionary.parse(root[namespace] ?? {});
|
|
125
|
+
const conf = dictionary.parse(section[name] ?? {});
|
|
126
|
+
for (const location of configValueLocations(conf, getOptions.decryptPaths ?? [])) {
|
|
127
|
+
const value = getConfigLocation(location);
|
|
128
|
+
if (isEncryptedConfigValue(value)) {
|
|
129
|
+
setConfigLocation(location, decryptConfigValue(value, await key(true)));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return conf;
|
|
133
|
+
});
|
|
134
|
+
result = mergeConfig(result, layer);
|
|
135
|
+
}
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
}
|
package/dist/config.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
export type { PluginConfig, PluginConfigGetOptions, PluginConfigSetOptions } from './config-api.js';
|
|
2
|
+
export { bindConfigStore, getUnifiedConfigPath, readConfigSection, type ConfigStoreOptions } from './config-store.ts';
|
|
1
3
|
export declare function getConfigDirectory(agentDir?: string): string;
|
|
2
4
|
export declare function getConfigPath(filename: string, agentDir?: string): string;
|
|
5
|
+
/** 显式项目目录必须已存在;不使用进程 CWD 或搜索父目录。 */
|
|
6
|
+
export declare function getProjectConfigPath(cwd: string): string;
|
|
3
7
|
/** 串行保护同一目标的完整读改写;操作内不能嵌套获取同一目标锁。 */
|
|
4
8
|
export declare function withConfigTransaction<T>(targetPath: string, operation: () => Promise<T>): Promise<T>;
|
|
5
9
|
/** 原子发布 UTF-8 配置;读改写应置于 withConfigTransaction 内,本方法不重复加锁。 */
|
package/dist/config.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
export { bindConfigStore, getUnifiedConfigPath, readConfigSection } from "./config-store.js";
|
|
1
2
|
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
2
|
-
import {
|
|
3
|
+
import { lstatSync } from 'node:fs';
|
|
4
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
3
5
|
import { ensureStorageDirectory, readStorageFile, withStorageLock, writeStorageFile } from "./config-storage.js";
|
|
4
6
|
export function getConfigDirectory(agentDir) {
|
|
5
7
|
return join(agentDir ?? getAgentDir(), 'config');
|
|
@@ -10,6 +12,14 @@ export function getConfigPath(filename, agentDir) {
|
|
|
10
12
|
}
|
|
11
13
|
return join(getConfigDirectory(agentDir), filename);
|
|
12
14
|
}
|
|
15
|
+
/** 显式项目目录必须已存在;不使用进程 CWD 或搜索父目录。 */
|
|
16
|
+
export function getProjectConfigPath(cwd) {
|
|
17
|
+
if (!isAbsolute(cwd))
|
|
18
|
+
throw new Error('项目配置 cwd 必须是绝对目录');
|
|
19
|
+
if (!lstatSync(cwd).isDirectory())
|
|
20
|
+
throw new Error('项目配置 cwd 必须是普通目录');
|
|
21
|
+
return join(cwd, '.pi', 'pi-desk.yaml');
|
|
22
|
+
}
|
|
13
23
|
/** 串行保护同一目标的完整读改写;操作内不能嵌套获取同一目标锁。 */
|
|
14
24
|
export async function withConfigTransaction(targetPath, operation) {
|
|
15
25
|
const target = resolve(targetPath);
|
package/dist/entry.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { PluginConfig } from './config-api.js';
|
|
2
|
+
export type { PluginConfig, PluginConfigGetOptions, PluginConfigSetOptions } from './config-api.js';
|
|
1
3
|
import type { CapabilityDeclarations } from './capabilities.js';
|
|
2
4
|
import type { HostSettings } from './settings.js';
|
|
3
5
|
import type { HostEvents, NodeHostEventMap } from './events.js';
|
|
@@ -116,6 +118,7 @@ export interface PluginMessageDeclaration {
|
|
|
116
118
|
}
|
|
117
119
|
export interface PiDeskPluginFacade {
|
|
118
120
|
readonly name: string;
|
|
121
|
+
readonly config: PluginConfig;
|
|
119
122
|
readonly host: PiDeskPluginHost;
|
|
120
123
|
readonly notifications: PiDeskPluginNotifications;
|
|
121
124
|
setState(state: PluginJsonObject | null): void;
|