@jetcrab/pi-desk-sdk 1.1.16-dev → 1.1.19-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 +4 -0
- package/dist/browser.d.ts +17 -0
- package/dist/config-api.d.ts +8 -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 +4 -0
- package/dist/config-storage.js +161 -0
- package/dist/config-store.d.ts +13 -0
- package/dist/config-store.js +98 -0
- package/dist/config.d.ts +8 -0
- package/dist/config.js +28 -0
- package/dist/entry.d.ts +6 -0
- package/dist/events.d.ts +35 -0
- package/dist/events.js +1 -0
- package/dist/host-runtime/base.js +34 -9
- package/dist/index.d.ts +1 -0
- 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 +69 -0
- package/dist/secrets.d.ts +15 -0
- package/dist/secrets.js +245 -0
- package/dist/session.d.ts +3 -0
- package/dist/session.js +2 -0
- package/package.json +23 -2
package/README.md
CHANGED
|
@@ -2,4 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
包名:`@jetcrab/pi-desk-sdk`。公开接口以本版本 `package.json` 的 exports 和对应 TypeScript 声明为准。
|
|
4
4
|
|
|
5
|
+
Node 与 Session 插件通过绑定身份的 `plugin.config` 使用 `encrypt`、`decrypt`、`set`、`get` 四接口;用户级配置统一保存在 `<AgentDir>/config/pi-desk.yaml`,可按 JSON Pointer 与 `*` 路径选择加解密。密文内联,系统仅托管主密钥。`/config` 提供宿主装配和文件级工具,`/secrets` 保留旧凭据接口供现有项目配置使用。旧全局配置不迁移、不删除、不回退读取;原生 Pi 配置与项目配置位置保持不变。
|
|
6
|
+
|
|
7
|
+
SDK 的运行依赖为 Zod(协议 Schema)、`yaml`(统一配置)、`proper-lockfile`(Node 跨进程锁)和 `@napi-rs/keyring`(Node 系统持久密钥存储)。协议与 Browser 子入口不加载这些 Node 配置或凭据能力,非 React 使用不要求安装公共 UI 库。
|
|
8
|
+
|
|
5
9
|
本包自有代码使用 Apache-2.0,见 [LICENSE](./LICENSE)。第三方代码继续遵循其原有许可,构建时保留上游法律注释。
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { BrowserApplicationContext, PluginDisposer, PluginJsonObject, PluginNotificationLevel, PluginSource, PluginWorkSession } from './shared.js';
|
|
2
2
|
import type { PluginPushMessage } from './entry.js';
|
|
3
3
|
import type { HostSettings } from './settings.js';
|
|
4
|
+
import type { BrowserHostEventMap, HostEvents } from './events.js';
|
|
4
5
|
export type { HostRegion, HostSettings, HostSettingsSnapshot } from './settings.js';
|
|
6
|
+
export type { BrowserHostEventMap, ChatSubmitResult, HostEventListener, HostEvents, WorkbenchContext } from './events.js';
|
|
5
7
|
export type { BrowserApplicationContext, BrowserBuiltinIconName, BrowserContributionIcon, PluginDisposer, PluginJsonObject, PluginJsonValue, PluginNotificationLevel, PluginSource, PluginWorkSession } from './shared.js';
|
|
6
8
|
export type { PluginPushMessage, PluginPushTarget } from './entry.js';
|
|
7
9
|
export type BrowserContributionKind = 'application' | 'composer-panel' | 'settings-page' | 'message-view' | 'session-sidebar-tab';
|
|
@@ -177,7 +179,22 @@ export interface BrowserTunnelHost {
|
|
|
177
179
|
remotePort: number;
|
|
178
180
|
}): BrowserTunnelHandle;
|
|
179
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
|
+
}
|
|
180
195
|
export interface BrowserPluginHost {
|
|
196
|
+
readonly floating: BrowserFloatingHost;
|
|
197
|
+
readonly events: HostEvents<BrowserHostEventMap>;
|
|
181
198
|
readonly settings: HostSettings;
|
|
182
199
|
/** 映射当前工作台后端的已发布 TCP 端口;旧宿主或无原生能力时不可用。 */
|
|
183
200
|
readonly tunnels?: BrowserTunnelHost;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PluginJsonObject, PluginJsonValue } from './shared.js';
|
|
2
|
+
/** 宿主按插件身份绑定;不暴露文件位置或密钥。 */
|
|
3
|
+
export interface PluginConfig {
|
|
4
|
+
encrypt(value: PluginJsonValue): Promise<string>;
|
|
5
|
+
decrypt(value: string): Promise<PluginJsonValue>;
|
|
6
|
+
set(conf: PluginJsonObject, encryptPaths?: readonly string[]): Promise<void>;
|
|
7
|
+
get(decryptPaths?: readonly string[]): Promise<PluginJsonObject>;
|
|
8
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function ensureStorageDirectory(path: string): void;
|
|
2
|
+
export declare function readStorageFile(path: string, maximumBytes?: number): Buffer | null;
|
|
3
|
+
export declare function writeStorageFile(path: string, content: Buffer, expected: Buffer | null): void;
|
|
4
|
+
export declare function withStorageLock<T>(path: string, action: (assertLocked: () => void) => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
import lockfile from 'proper-lockfile';
|
|
5
|
+
function errorCode(error) {
|
|
6
|
+
return error.code ?? 'UNKNOWN';
|
|
7
|
+
}
|
|
8
|
+
function storageError(operation, path, error) {
|
|
9
|
+
return new Error(`${operation}失败:${path}(${errorCode(error)})`);
|
|
10
|
+
}
|
|
11
|
+
// 只创建目标文件需要的目录;AgentDir 及其他已有目录仍由调用方管理。
|
|
12
|
+
export function ensureStorageDirectory(path) {
|
|
13
|
+
assertDirectories(path);
|
|
14
|
+
try {
|
|
15
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
throw storageError('创建配置目录', path, error);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function assertDirectories(path) {
|
|
22
|
+
const parent = dirname(path);
|
|
23
|
+
if (parent !== path)
|
|
24
|
+
assertDirectories(parent);
|
|
25
|
+
try {
|
|
26
|
+
if (!lstatSync(path).isDirectory())
|
|
27
|
+
throw new Error(`配置目录不是普通目录:${path}`);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (errorCode(error) === 'ENOENT')
|
|
31
|
+
return;
|
|
32
|
+
if (error instanceof Error && error.message.startsWith('配置目录'))
|
|
33
|
+
throw error;
|
|
34
|
+
throw storageError('检查配置目录', path, error);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function readStorageFile(path, maximumBytes) {
|
|
38
|
+
assertDirectories(dirname(path));
|
|
39
|
+
let descriptor;
|
|
40
|
+
try {
|
|
41
|
+
const stat = lstatSync(path);
|
|
42
|
+
if (!stat.isFile())
|
|
43
|
+
throw new Error(`拒绝读取非普通配置文件或符号链接:${path}`);
|
|
44
|
+
if (maximumBytes !== undefined && stat.size > maximumBytes) {
|
|
45
|
+
throw new Error(`拒绝读取超过容量限制的配置文件:${path}`);
|
|
46
|
+
}
|
|
47
|
+
descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
48
|
+
const opened = fstatSync(descriptor);
|
|
49
|
+
if (!opened.isFile() || opened.ino !== stat.ino || opened.dev !== stat.dev) {
|
|
50
|
+
throw new Error(`读取期间配置文件已变化:${path}`);
|
|
51
|
+
}
|
|
52
|
+
return readFileSync(descriptor);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (errorCode(error) === 'ENOENT')
|
|
56
|
+
return null;
|
|
57
|
+
if (error instanceof Error && /^(拒绝读取|读取期间)/u.test(error.message))
|
|
58
|
+
throw error;
|
|
59
|
+
throw storageError('读取配置文件', path, error);
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
if (descriptor !== undefined)
|
|
63
|
+
closeSync(descriptor);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function assertFileUnchanged(path, expected) {
|
|
67
|
+
const actual = readStorageFile(path);
|
|
68
|
+
if (expected === null ? actual !== null : actual === null || !actual.equals(expected)) {
|
|
69
|
+
throw new Error(`配置文件已变化,拒绝覆盖:${path}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function syncDirectory(path) {
|
|
73
|
+
// Windows 不支持以普通文件描述符 fsync 目录;文件本身始终先 fsync。
|
|
74
|
+
if (process.platform === 'win32')
|
|
75
|
+
return;
|
|
76
|
+
const descriptor = openSync(path, constants.O_RDONLY);
|
|
77
|
+
try {
|
|
78
|
+
fsyncSync(descriptor);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
closeSync(descriptor);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export function writeStorageFile(path, content, expected) {
|
|
85
|
+
const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
86
|
+
let descriptor;
|
|
87
|
+
let committed = false;
|
|
88
|
+
try {
|
|
89
|
+
const mode = expected !== null && process.platform !== 'win32' ? lstatSync(path).mode & 0o600 : 0o600;
|
|
90
|
+
descriptor = openSync(temporary, 'wx', mode);
|
|
91
|
+
writeFileSync(descriptor, content);
|
|
92
|
+
fsyncSync(descriptor);
|
|
93
|
+
closeSync(descriptor);
|
|
94
|
+
descriptor = undefined;
|
|
95
|
+
assertFileUnchanged(path, expected);
|
|
96
|
+
if (expected === null) {
|
|
97
|
+
// 硬链接发布保证目标在锁外被创建时也不会被覆盖。
|
|
98
|
+
linkSync(temporary, path);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
renameSync(temporary, path);
|
|
102
|
+
}
|
|
103
|
+
syncDirectory(dirname(path));
|
|
104
|
+
const actual = readStorageFile(path);
|
|
105
|
+
if (!actual?.equals(content))
|
|
106
|
+
throw new Error(`配置文件写入校验失败:${path}`);
|
|
107
|
+
committed = true;
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (error instanceof Error && error.message.startsWith('配置文件'))
|
|
111
|
+
throw error;
|
|
112
|
+
throw storageError('原子写入配置文件', path, error);
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
if (descriptor !== undefined)
|
|
116
|
+
closeSync(descriptor);
|
|
117
|
+
try {
|
|
118
|
+
unlinkSync(temporary);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (errorCode(error) !== 'ENOENT') {
|
|
122
|
+
const status = committed ? '配置已提交,不应回收其引用的凭据' : '配置写入失败,保留原始错误';
|
|
123
|
+
console.warn(`${storageError('清理配置临时文件', temporary, error).message};${status},请清理该临时文件`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const lockOptions = { realpath: false, stale: 120_000, update: 10_000 };
|
|
129
|
+
export async function withStorageLock(path, action) {
|
|
130
|
+
let compromised = false;
|
|
131
|
+
let release;
|
|
132
|
+
try {
|
|
133
|
+
release = await lockfile.lock(path, {
|
|
134
|
+
...lockOptions,
|
|
135
|
+
retries: { retries: 150, minTimeout: 100, maxTimeout: 100, randomize: false },
|
|
136
|
+
onCompromised() {
|
|
137
|
+
compromised = true;
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
throw storageError('获取配置文件锁', path, error);
|
|
143
|
+
}
|
|
144
|
+
const assertLocked = () => {
|
|
145
|
+
if (compromised)
|
|
146
|
+
throw new Error(`配置文件锁已失效:${path}`);
|
|
147
|
+
};
|
|
148
|
+
try {
|
|
149
|
+
const result = await action(assertLocked);
|
|
150
|
+
assertLocked();
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
try {
|
|
155
|
+
await release();
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
console.warn(`${storageError('释放配置文件锁', path, error).message};操作结果不回滚,请检查锁目录`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -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,98 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { parseDocument } from 'yaml';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { getConfigPath } 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
|
+
/** 宿主同步启动读取普通配置;插件业务使用四接口,不从这里解密。 */
|
|
30
|
+
export function readConfigSection(namespace, name, agentDir) {
|
|
31
|
+
const { root } = readDocument(getUnifiedConfigPath(agentDir));
|
|
32
|
+
return dictionary.parse(dictionary.parse(root[namespace] ?? {})[name] ?? {});
|
|
33
|
+
}
|
|
34
|
+
/** 供宿主装配与原生绑定使用,业务插件直接使用绑定后的 plugin.config。 */
|
|
35
|
+
export function bindConfigStore(namespace, name, options = {}) {
|
|
36
|
+
name = normalizePluginIdentifier(name, 'pluginName');
|
|
37
|
+
const path = getUnifiedConfigPath(options.agentDir);
|
|
38
|
+
const assertActive = () => options.assertActive?.();
|
|
39
|
+
async function access(action) {
|
|
40
|
+
assertActive();
|
|
41
|
+
ensureStorageDirectory(dirname(path));
|
|
42
|
+
return withStorageLock(path, async (assertLocked) => {
|
|
43
|
+
const assertCurrent = () => {
|
|
44
|
+
assertLocked();
|
|
45
|
+
assertActive();
|
|
46
|
+
};
|
|
47
|
+
assertCurrent();
|
|
48
|
+
const state = readDocument(path);
|
|
49
|
+
let loadedKey;
|
|
50
|
+
try {
|
|
51
|
+
return await action(state, async (required) => {
|
|
52
|
+
loadedKey ??= await loadConfigKey(path, required || hasEncryptedConfigValue(state.root), options, assertCurrent);
|
|
53
|
+
assertCurrent();
|
|
54
|
+
return loadedKey;
|
|
55
|
+
}, assertCurrent);
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
loadedKey?.fill(0);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
async encrypt(value) {
|
|
64
|
+
return access(async (_state, key) => encryptConfigValue(value, await key(false)));
|
|
65
|
+
},
|
|
66
|
+
async decrypt(value) {
|
|
67
|
+
return access(async (_state, key) => decryptConfigValue(value, await key(true)));
|
|
68
|
+
},
|
|
69
|
+
async set(conf, encryptPaths = []) {
|
|
70
|
+
const next = dictionary.parse(conf);
|
|
71
|
+
const locations = configValueLocations(next, encryptPaths);
|
|
72
|
+
await access(async (state, key, assertCurrent) => {
|
|
73
|
+
for (const location of locations) {
|
|
74
|
+
setConfigLocation(location, encryptConfigValue(getConfigLocation(location), await key(false)));
|
|
75
|
+
}
|
|
76
|
+
state.document.setIn([namespace, name], next);
|
|
77
|
+
const content = Buffer.from(state.document.toString());
|
|
78
|
+
if (content.byteLength > maxConfigBytes)
|
|
79
|
+
throw new Error('统一配置文件不能超过 8 MiB');
|
|
80
|
+
assertCurrent();
|
|
81
|
+
writeStorageFile(path, content, state.previous);
|
|
82
|
+
});
|
|
83
|
+
},
|
|
84
|
+
async get(decryptPaths = []) {
|
|
85
|
+
return access(async ({ root }, key) => {
|
|
86
|
+
const section = dictionary.parse(root[namespace] ?? {});
|
|
87
|
+
const conf = dictionary.parse(section[name] ?? {});
|
|
88
|
+
for (const location of configValueLocations(conf, decryptPaths)) {
|
|
89
|
+
const value = getConfigLocation(location);
|
|
90
|
+
if (isEncryptedConfigValue(value)) {
|
|
91
|
+
setConfigLocation(location, decryptConfigValue(value, await key(true)));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return conf;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type { PluginConfig } from './config-api.js';
|
|
2
|
+
export { bindConfigStore, getUnifiedConfigPath, readConfigSection, type ConfigStoreOptions } from './config-store.ts';
|
|
3
|
+
export declare function getConfigDirectory(agentDir?: string): string;
|
|
4
|
+
export declare function getConfigPath(filename: string, agentDir?: string): string;
|
|
5
|
+
/** 串行保护同一目标的完整读改写;操作内不能嵌套获取同一目标锁。 */
|
|
6
|
+
export declare function withConfigTransaction<T>(targetPath: string, operation: () => Promise<T>): Promise<T>;
|
|
7
|
+
/** 原子发布 UTF-8 配置;读改写应置于 withConfigTransaction 内,本方法不重复加锁。 */
|
|
8
|
+
export declare function writeConfigTextAtomic(path: string, content: string): void;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export { bindConfigStore, getUnifiedConfigPath, readConfigSection } from "./config-store.js";
|
|
2
|
+
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { ensureStorageDirectory, readStorageFile, withStorageLock, writeStorageFile } from "./config-storage.js";
|
|
5
|
+
export function getConfigDirectory(agentDir) {
|
|
6
|
+
return join(agentDir ?? getAgentDir(), 'config');
|
|
7
|
+
}
|
|
8
|
+
export function getConfigPath(filename, agentDir) {
|
|
9
|
+
if (!filename || filename === '.' || filename === '..' || /[/\\:\x00-\x1f]/u.test(filename)) {
|
|
10
|
+
throw new Error('配置文件名必须是单个文件名');
|
|
11
|
+
}
|
|
12
|
+
return join(getConfigDirectory(agentDir), filename);
|
|
13
|
+
}
|
|
14
|
+
/** 串行保护同一目标的完整读改写;操作内不能嵌套获取同一目标锁。 */
|
|
15
|
+
export async function withConfigTransaction(targetPath, operation) {
|
|
16
|
+
const target = resolve(targetPath);
|
|
17
|
+
ensureStorageDirectory(dirname(target));
|
|
18
|
+
return withStorageLock(target, async () => {
|
|
19
|
+
readStorageFile(target);
|
|
20
|
+
return operation();
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** 原子发布 UTF-8 配置;读改写应置于 withConfigTransaction 内,本方法不重复加锁。 */
|
|
24
|
+
export function writeConfigTextAtomic(path, content) {
|
|
25
|
+
const target = resolve(path);
|
|
26
|
+
ensureStorageDirectory(dirname(target));
|
|
27
|
+
writeStorageFile(target, Buffer.from(content, 'utf8'), readStorageFile(target));
|
|
28
|
+
}
|
package/dist/entry.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import type { PluginConfig } from './config-api.js';
|
|
2
|
+
export type { PluginConfig } from './config-api.js';
|
|
1
3
|
import type { CapabilityDeclarations } from './capabilities.js';
|
|
2
4
|
import type { HostSettings } from './settings.js';
|
|
5
|
+
import type { HostEvents, NodeHostEventMap } from './events.js';
|
|
3
6
|
export type { HostRegion, HostSettings, HostSettingsSnapshot } from './settings.js';
|
|
7
|
+
export type { ChatInputAccepted, HostEventListener, HostEvents, NodeHostEventMap } from './events.js';
|
|
4
8
|
import { type PluginDisposer, type PluginJsonObject, type PluginJsonValue, type PluginNotificationLevel, type PluginSource, type PluginWorkSession } from './shared.ts';
|
|
5
9
|
export type { BrowserBuiltinIconName, BrowserContributionIcon, PluginDisposer, PluginJsonObject, PluginJsonValue, PluginNotificationLevel, PluginSource, PluginWorkSession } from './shared.js';
|
|
6
10
|
export interface GlobalPluginMethodContext {
|
|
@@ -33,6 +37,7 @@ export interface PiDeskWorkSessionCapability {
|
|
|
33
37
|
listWorkSessions(): Promise<readonly PluginWorkSession[]>;
|
|
34
38
|
}
|
|
35
39
|
export interface PiDeskPluginHost {
|
|
40
|
+
readonly events: HostEvents<NodeHostEventMap>;
|
|
36
41
|
readonly settings: HostSettings;
|
|
37
42
|
readonly workSessions: PiDeskWorkSessionCapability;
|
|
38
43
|
}
|
|
@@ -113,6 +118,7 @@ export interface PluginMessageDeclaration {
|
|
|
113
118
|
}
|
|
114
119
|
export interface PiDeskPluginFacade {
|
|
115
120
|
readonly name: string;
|
|
121
|
+
readonly config: PluginConfig;
|
|
116
122
|
readonly host: PiDeskPluginHost;
|
|
117
123
|
readonly notifications: PiDeskPluginNotifications;
|
|
118
124
|
setState(state: PluginJsonObject | null): void;
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { BrowserConnectionSnapshot, BrowserThemeSnapshot } from './browser.js';
|
|
2
|
+
import type { HostSettingsSnapshot } from './settings.js';
|
|
3
|
+
import type { BrowserApplicationContext, PluginJsonObject, PluginSource, PluginWorkSession } from './shared.js';
|
|
4
|
+
export type HostEventListener<T> = (data: Readonly<T>) => void | Promise<void>;
|
|
5
|
+
export interface HostEvents<Events> {
|
|
6
|
+
on<K extends keyof Events & string>(name: K, handler: HostEventListener<Events[K]>): () => void;
|
|
7
|
+
onPlugin(pluginName: string, name: string, handler: HostEventListener<PluginJsonObject>): () => void;
|
|
8
|
+
emit(name: string, data: PluginJsonObject): void;
|
|
9
|
+
}
|
|
10
|
+
export type WorkbenchContext = BrowserApplicationContext | null;
|
|
11
|
+
export interface ChatInputAccepted {
|
|
12
|
+
source: PluginSource;
|
|
13
|
+
tempId: string;
|
|
14
|
+
}
|
|
15
|
+
export type ChatSubmitResult = (ChatInputAccepted & {
|
|
16
|
+
status: 'accepted';
|
|
17
|
+
}) | {
|
|
18
|
+
source: PluginSource;
|
|
19
|
+
status: 'failed' | 'unknown';
|
|
20
|
+
message: string;
|
|
21
|
+
};
|
|
22
|
+
export interface BrowserHostEventMap {
|
|
23
|
+
'workbench-context': WorkbenchContext;
|
|
24
|
+
'work-sessions': readonly PluginWorkSession[];
|
|
25
|
+
connection: BrowserConnectionSnapshot;
|
|
26
|
+
settings: HostSettingsSnapshot;
|
|
27
|
+
theme: BrowserThemeSnapshot;
|
|
28
|
+
'plugin-state': PluginJsonObject | null;
|
|
29
|
+
'chat-submit-result': ChatSubmitResult;
|
|
30
|
+
}
|
|
31
|
+
export interface NodeHostEventMap {
|
|
32
|
+
'work-sessions': readonly PluginWorkSession[];
|
|
33
|
+
settings: HostSettingsSnapshot;
|
|
34
|
+
'chat-input-accepted': ChatInputAccepted;
|
|
35
|
+
}
|
package/dist/events.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|