pi-dent-agent 0.2.8 → 0.2.10
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/index.ts +25 -2
- package/lib/engine.ts +2 -2
- package/lib/plugin-state.ts +484 -0
- package/lib/plugin-ui-proxy.ts +495 -0
- package/lib/plugin-ui.ts +119 -33
- package/lib/script-runner.ts +8 -0
- package/lib/script-tool.ts +3 -0
- package/lib/script-worker.ts +78 -7
- package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/CacheStore.md +11 -0
- package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Client.md +1 -1
- package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Connector.md +9 -2
- package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Dispatcher.md +20 -0
- package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Interceptors.md +13 -3
- package/node_modules/pi-web-access/node_modules/undici/docs/docs/best-practices/mocking-request.md +1 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/api/abort-signal.js +55 -5
- package/node_modules/pi-web-access/node_modules/undici/lib/api/api-connect.js +6 -2
- package/node_modules/pi-web-access/node_modules/undici/lib/api/api-pipeline.js +7 -2
- package/node_modules/pi-web-access/node_modules/undici/lib/api/api-request.js +12 -4
- package/node_modules/pi-web-access/node_modules/undici/lib/api/api-stream.js +6 -2
- package/node_modules/pi-web-access/node_modules/undici/lib/api/api-upgrade.js +6 -2
- package/node_modules/pi-web-access/node_modules/undici/lib/core/request.js +17 -0
- package/node_modules/pi-web-access/node_modules/undici/lib/core/symbols.js +3 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h1.js +24 -0
- package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h2.js +11 -5
- package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client.js +109 -2
- package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher-base.js +6 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher.js +22 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool-base.js +72 -16
- package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool.js +22 -9
- package/node_modules/pi-web-access/node_modules/undici/lib/handler/cache-handler.js +1 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/handler/retry-handler.js +27 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/cache.js +9 -2
- package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/decompress.js +0 -11
- package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/deduplicate.js +4 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/redirect.js +4 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/util/cache.js +1 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/util/timers.js +1 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/index.js +20 -1
- package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/util.js +2 -2
- package/node_modules/pi-web-access/node_modules/undici/package.json +3 -3
- package/node_modules/pi-web-access/node_modules/undici/types/retry-handler.d.ts +1 -1
- package/package.json +1 -1
package/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
type BootSnapshot,
|
|
14
14
|
DispatchEngine,
|
|
15
15
|
hostFromContext,
|
|
16
|
+
inheritedExtensions,
|
|
16
17
|
readBootSnapshot,
|
|
17
18
|
agentsDirFor,
|
|
18
19
|
agentDirForHost,
|
|
@@ -35,6 +36,7 @@ import {
|
|
|
35
36
|
PluginUiController,
|
|
36
37
|
type UiCallableTool,
|
|
37
38
|
} from "./lib/plugin-ui.ts";
|
|
39
|
+
import { PluginUiToolProxy } from "./lib/plugin-ui-proxy.ts";
|
|
38
40
|
import { type Diagnostic, errorMessage, isPlainObject } from "./lib/util.ts";
|
|
39
41
|
import { rebuildInterruptedTasks } from "./lib/task-rebuild.ts";
|
|
40
42
|
import {
|
|
@@ -304,11 +306,24 @@ export default function (pi: ExtensionAPI) {
|
|
|
304
306
|
const questions = askUserRuntime();
|
|
305
307
|
const recap = recapRuntime(boot.config, (data) => pi.appendEntry("pi-dent-recap", data));
|
|
306
308
|
const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
|
|
309
|
+
let currentProjectTrusted = false;
|
|
307
310
|
const pluginUi = new PluginUiController(boot.pluginIndex, {
|
|
308
311
|
ownedTools: () => [...ownedUiTools.values()],
|
|
309
|
-
|
|
310
|
-
|
|
312
|
+
allTools: () => (typeof pi.getAllTools === "function" ? pi.getAllTools() : []),
|
|
313
|
+
activeToolNames: () => (typeof pi.getActiveTools === "function" ? pi.getActiveTools() : []),
|
|
311
314
|
toolsAllow: () => scriptToolsAllow,
|
|
315
|
+
createProxy: () => {
|
|
316
|
+
const host = currentHost;
|
|
317
|
+
if (!host) return;
|
|
318
|
+
const active = typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [];
|
|
319
|
+
const excludeTools = active.includes("bash") ? [] : ["bash"];
|
|
320
|
+
return new PluginUiToolProxy({
|
|
321
|
+
cwd: host.cwd(),
|
|
322
|
+
isProjectTrusted: currentProjectTrusted,
|
|
323
|
+
extensions: inheritedExtensions(host),
|
|
324
|
+
excludeTools,
|
|
325
|
+
});
|
|
326
|
+
},
|
|
312
327
|
});
|
|
313
328
|
let taskWidget: TaskWidgetHandle | undefined;
|
|
314
329
|
// Feeds for an RPC client (task.md Section 4.1, fleet-tool.md Section 6).
|
|
@@ -502,6 +517,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
502
517
|
|
|
503
518
|
pi.on("session_start", async (event, ctx) => {
|
|
504
519
|
recap.abort();
|
|
520
|
+
await pluginUi.disposeProxy();
|
|
521
|
+
currentProjectTrusted =
|
|
522
|
+
typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : false;
|
|
505
523
|
// billing.md Section 4.5: the diagnostics held with no open session go out first.
|
|
506
524
|
sessionUi = ctx.ui;
|
|
507
525
|
for (const diagnostic of heldDiagnostics.splice(0)) showDiagnostic(diagnostic);
|
|
@@ -721,6 +739,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
721
739
|
() => pluginUi.cancelAll("Session ended"),
|
|
722
740
|
reportShutdown,
|
|
723
741
|
);
|
|
742
|
+
try {
|
|
743
|
+
await pluginUi.disposeProxy();
|
|
744
|
+
} catch (error) {
|
|
745
|
+
reportShutdown(`pi-dent: disposing plugin UI tool proxy failed: ${errorMessage(error)}`);
|
|
746
|
+
}
|
|
724
747
|
// The Search tool's continuations of catch-up end with the boot window
|
|
725
748
|
// (search-tool.md Section 2.2).
|
|
726
749
|
shutdownStep("stopping Search", () => search.stop(), reportShutdown);
|
package/lib/engine.ts
CHANGED
|
@@ -509,7 +509,7 @@ export function defaultBuiltinExtensions(): InlineExtension[] {
|
|
|
509
509
|
}
|
|
510
510
|
|
|
511
511
|
/** The longest the child's extension shutdown may take (agent-tool.md Section 3.1). */
|
|
512
|
-
const EXTENSION_SHUTDOWN_TIMEOUT_MS = 1000;
|
|
512
|
+
export const EXTENSION_SHUTDOWN_TIMEOUT_MS = 1000;
|
|
513
513
|
|
|
514
514
|
/** How the child's session-shutdown lifecycle ended (agent-tool.md Section 3.1). */
|
|
515
515
|
type ExtensionShutdownOutcome = "done" | "timeout" | { readonly error: unknown };
|
|
@@ -519,7 +519,7 @@ type ExtensionShutdownOutcome = "done" | "timeout" | { readonly error: unknown }
|
|
|
519
519
|
* (agent-tool.md Section 3.1). A failure after the deadline is reported to
|
|
520
520
|
* stderr, never left unhandled.
|
|
521
521
|
*/
|
|
522
|
-
function extensionShutdown(
|
|
522
|
+
export function extensionShutdown(
|
|
523
523
|
session: AgentSession,
|
|
524
524
|
deadlineMs: number,
|
|
525
525
|
): Promise<ExtensionShutdownOutcome> {
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
openSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
renameSync,
|
|
9
|
+
statSync,
|
|
10
|
+
unlinkSync,
|
|
11
|
+
watch,
|
|
12
|
+
writeFileSync,
|
|
13
|
+
type FSWatcher,
|
|
14
|
+
} from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { isAbsolute, join } from "node:path";
|
|
17
|
+
import { isJsonCompatible } from "./script-render.ts";
|
|
18
|
+
import { errorCode, errorMessage, isPlainObject } from "./util.ts";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Durable per-plugin key-value state store (specs/plugin-state.md): shared by
|
|
22
|
+
* pi-dent's `dent.state` script binding and external callers such as Alpha's
|
|
23
|
+
* `alpha.state` host bridge. Plain JSON on disk, atomic per-key writes via
|
|
24
|
+
* lockfile + rename, cross-process change watching.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
export const PLUGIN_STATE_VERSION = 1;
|
|
28
|
+
export const PLUGIN_STATE_KEY_MAX_LENGTH = 256;
|
|
29
|
+
export const PLUGIN_STATE_VALUE_CAP_BYTES = 262_144;
|
|
30
|
+
export const PLUGIN_STATE_SCOPE_CAP_BYTES = 5_242_880;
|
|
31
|
+
|
|
32
|
+
const LOCK_TIMEOUT_MS = 5000;
|
|
33
|
+
const STALE_LOCK_MS = 30_000;
|
|
34
|
+
const WATCH_POLL_MS = 200;
|
|
35
|
+
|
|
36
|
+
export type PluginStateScope = "workspace" | "user";
|
|
37
|
+
|
|
38
|
+
export interface PluginStateTarget {
|
|
39
|
+
namespace: string;
|
|
40
|
+
scope: PluginStateScope;
|
|
41
|
+
/** Required (and must be absolute) when `scope === "workspace"`. */
|
|
42
|
+
workspaceRoot?: string;
|
|
43
|
+
/** Optional override for user-scope base directory (defaults to PI_DENT_STATE_DIR or ~/.pi/pi-dent). */
|
|
44
|
+
userStateRoot?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface PluginStatePaths {
|
|
48
|
+
storeDir: string;
|
|
49
|
+
storeFile: string;
|
|
50
|
+
dataDir: string;
|
|
51
|
+
gitignoreFile: string | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface PluginStateWatcher {
|
|
55
|
+
close(): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type PluginStateChangeListener = (key: string, value: unknown) => void;
|
|
59
|
+
|
|
60
|
+
/** Active in-process watchers keyed by `storeFile` so own-process writes notify immediately. */
|
|
61
|
+
const inProcessWatchers = new Map<string, Set<() => void>>();
|
|
62
|
+
|
|
63
|
+
function byCodeUnit(a: string, b: string): number {
|
|
64
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isValidNamespace(name: unknown): name is string {
|
|
68
|
+
return (
|
|
69
|
+
typeof name === "string" &&
|
|
70
|
+
name !== "" &&
|
|
71
|
+
name !== "." &&
|
|
72
|
+
name !== ".." &&
|
|
73
|
+
!/\s/.test(name) &&
|
|
74
|
+
!name.includes(":") &&
|
|
75
|
+
!name.includes("/") &&
|
|
76
|
+
!name.includes("\\") &&
|
|
77
|
+
!name.includes("\0")
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function validateTarget(target: PluginStateTarget): void {
|
|
82
|
+
if (!isPlainObject(target) || !isValidNamespace(target.namespace)) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`Invalid plugin namespace: ${JSON.stringify(isPlainObject(target) ? target.namespace : undefined)}`,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
if (target.scope !== "workspace" && target.scope !== "user") {
|
|
88
|
+
throw new Error(`Invalid plugin state scope: ${JSON.stringify(target.scope)}`);
|
|
89
|
+
}
|
|
90
|
+
if (
|
|
91
|
+
target.scope === "workspace" &&
|
|
92
|
+
(typeof target.workspaceRoot !== "string" || !isAbsolute(target.workspaceRoot))
|
|
93
|
+
) {
|
|
94
|
+
throw new Error("Workspace root must be an absolute path");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function validateKey(key: unknown): string {
|
|
99
|
+
if (typeof key !== "string" || key.length === 0) {
|
|
100
|
+
throw new Error("State key must be a non-empty string");
|
|
101
|
+
}
|
|
102
|
+
if (key.length > PLUGIN_STATE_KEY_MAX_LENGTH) {
|
|
103
|
+
throw new Error(`State key exceeds ${PLUGIN_STATE_KEY_MAX_LENGTH} characters`);
|
|
104
|
+
}
|
|
105
|
+
if (key.includes("\0")) {
|
|
106
|
+
throw new Error("State key must not contain null characters");
|
|
107
|
+
}
|
|
108
|
+
return key;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function validateValueJson(value: unknown): string {
|
|
112
|
+
if (!isJsonCompatible(value)) {
|
|
113
|
+
throw new Error("State value must be a JSON value");
|
|
114
|
+
}
|
|
115
|
+
let json: string | undefined;
|
|
116
|
+
try {
|
|
117
|
+
json = JSON.stringify(value);
|
|
118
|
+
} catch {
|
|
119
|
+
throw new Error("State value must be a JSON value");
|
|
120
|
+
}
|
|
121
|
+
if (typeof json !== "string") {
|
|
122
|
+
throw new Error("State value must be a JSON value");
|
|
123
|
+
}
|
|
124
|
+
if (Buffer.byteLength(json, "utf8") > PLUGIN_STATE_VALUE_CAP_BYTES) {
|
|
125
|
+
throw new Error(`State value exceeds ${PLUGIN_STATE_VALUE_CAP_BYTES} bytes`);
|
|
126
|
+
}
|
|
127
|
+
return json;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function resolveUserStateRoot(override?: string): string {
|
|
131
|
+
if (typeof override === "string" && override.length > 0) return override;
|
|
132
|
+
const envDir = process.env.PI_DENT_STATE_DIR;
|
|
133
|
+
if (typeof envDir === "string" && envDir.length > 0) return envDir;
|
|
134
|
+
return join(homedir(), ".pi", "pi-dent");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Resolve all on-disk paths for a plugin state target (specs/plugin-state.md Section 1). */
|
|
138
|
+
export function pluginStatePaths(target: PluginStateTarget): PluginStatePaths {
|
|
139
|
+
validateTarget(target);
|
|
140
|
+
if (target.scope === "workspace") {
|
|
141
|
+
const stateRoot = join(target.workspaceRoot ?? "", ".pi", "pi-dent", "state");
|
|
142
|
+
const storeDir = join(stateRoot, target.namespace);
|
|
143
|
+
return {
|
|
144
|
+
storeDir,
|
|
145
|
+
storeFile: join(storeDir, "state.json"),
|
|
146
|
+
dataDir: join(storeDir, "data"),
|
|
147
|
+
gitignoreFile: join(stateRoot, ".gitignore"),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
const stateRoot = join(resolveUserStateRoot(target.userStateRoot), "state");
|
|
151
|
+
const storeDir = join(stateRoot, target.namespace);
|
|
152
|
+
return {
|
|
153
|
+
storeDir,
|
|
154
|
+
storeFile: join(storeDir, "state.json"),
|
|
155
|
+
dataDir: join(storeDir, "data"),
|
|
156
|
+
gitignoreFile: undefined,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function ensureStoreParentAndGitignore(paths: PluginStatePaths): void {
|
|
161
|
+
mkdirSync(paths.storeDir, { recursive: true });
|
|
162
|
+
if (paths.gitignoreFile !== undefined) {
|
|
163
|
+
try {
|
|
164
|
+
writeFileSync(paths.gitignoreFile, "*\n", { flag: "wx", encoding: "utf8" });
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Ensure the per-plugin `data/` directory exists and return its absolute path. */
|
|
172
|
+
export function ensurePluginStateDataDir(target: PluginStateTarget): string {
|
|
173
|
+
const paths = pluginStatePaths(target);
|
|
174
|
+
ensureStoreParentAndGitignore(paths);
|
|
175
|
+
mkdirSync(paths.dataDir, { recursive: true });
|
|
176
|
+
return paths.dataDir;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
interface ParsedStore {
|
|
180
|
+
exists: boolean;
|
|
181
|
+
entries: Record<string, unknown>;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function readStoreFileRaw(storeFile: string): string | undefined {
|
|
185
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
186
|
+
try {
|
|
187
|
+
return readFileSync(storeFile, "utf8");
|
|
188
|
+
} catch (error) {
|
|
189
|
+
const code = errorCode(error);
|
|
190
|
+
if (code === "ENOENT") return undefined;
|
|
191
|
+
if (attempt === 0 && (code === "EPERM" || code === "EBUSY")) continue;
|
|
192
|
+
throw new Error(`Plugin state store unreadable (${storeFile}): ${errorMessage(error)}`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function readStoreEntries(storeFile: string): ParsedStore {
|
|
199
|
+
const raw = readStoreFileRaw(storeFile);
|
|
200
|
+
if (raw === undefined) {
|
|
201
|
+
return { exists: false, entries: {} };
|
|
202
|
+
}
|
|
203
|
+
let parsed: unknown;
|
|
204
|
+
try {
|
|
205
|
+
parsed = JSON.parse(raw);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
throw new Error(`Plugin state store is corrupt (${storeFile}): ${errorMessage(error)}`);
|
|
208
|
+
}
|
|
209
|
+
if (!isPlainObject(parsed) || parsed.version !== PLUGIN_STATE_VERSION) {
|
|
210
|
+
throw new Error(
|
|
211
|
+
`Plugin state store is corrupt (${storeFile}): expected version ${PLUGIN_STATE_VERSION} object`,
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
if (!isPlainObject(parsed.entries)) {
|
|
215
|
+
throw new Error(`Plugin state store is corrupt (${storeFile}): entries must be a plain object`);
|
|
216
|
+
}
|
|
217
|
+
const entries: Record<string, unknown> = {};
|
|
218
|
+
for (const [k, v] of Object.entries(parsed.entries)) {
|
|
219
|
+
if (!isJsonCompatible(v)) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`Plugin state store is corrupt (${storeFile}): entry ${JSON.stringify(k)} is not a JSON value`,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
entries[k] = v;
|
|
225
|
+
}
|
|
226
|
+
return { exists: true, entries };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function sleep(ms: number): Promise<void> {
|
|
230
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function withStoreLock<T>(paths: PluginStatePaths, fn: () => T): Promise<T> {
|
|
234
|
+
ensureStoreParentAndGitignore(paths);
|
|
235
|
+
const lockPath = join(paths.storeDir, "state.lock");
|
|
236
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
237
|
+
let acquired = false;
|
|
238
|
+
|
|
239
|
+
while (!acquired) {
|
|
240
|
+
try {
|
|
241
|
+
const fd = openSync(lockPath, "wx");
|
|
242
|
+
try {
|
|
243
|
+
writeFileSync(fd, `${process.pid}\n`, "utf8");
|
|
244
|
+
} finally {
|
|
245
|
+
closeSync(fd);
|
|
246
|
+
}
|
|
247
|
+
acquired = true;
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
250
|
+
try {
|
|
251
|
+
const st = statSync(lockPath);
|
|
252
|
+
if (Date.now() - st.mtimeMs > STALE_LOCK_MS) {
|
|
253
|
+
try {
|
|
254
|
+
unlinkSync(lockPath);
|
|
255
|
+
} catch {
|
|
256
|
+
// Another process removed it first.
|
|
257
|
+
}
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
} catch {
|
|
261
|
+
// Lock disappeared between open and stat; retry immediately.
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if (Date.now() >= deadline) {
|
|
265
|
+
throw new Error(`Timed out waiting for plugin state lock (${paths.storeFile})`);
|
|
266
|
+
}
|
|
267
|
+
await sleep(5 + Math.floor(Math.random() * 15));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
try {
|
|
272
|
+
return fn();
|
|
273
|
+
} finally {
|
|
274
|
+
try {
|
|
275
|
+
unlinkSync(lockPath);
|
|
276
|
+
} catch {
|
|
277
|
+
// Best effort.
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function writeStoreAtomic(paths: PluginStatePaths, entries: Record<string, unknown>): void {
|
|
283
|
+
const serialized = JSON.stringify({ version: PLUGIN_STATE_VERSION, entries });
|
|
284
|
+
if (Buffer.byteLength(serialized, "utf8") > PLUGIN_STATE_SCOPE_CAP_BYTES) {
|
|
285
|
+
throw new Error(`State store exceeds ${PLUGIN_STATE_SCOPE_CAP_BYTES} bytes`);
|
|
286
|
+
}
|
|
287
|
+
const tmpName = `.state.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
288
|
+
const tmpPath = join(paths.storeDir, tmpName);
|
|
289
|
+
try {
|
|
290
|
+
writeFileSync(tmpPath, serialized, "utf8");
|
|
291
|
+
renameSync(tmpPath, paths.storeFile);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
try {
|
|
294
|
+
unlinkSync(tmpPath);
|
|
295
|
+
} catch {
|
|
296
|
+
// Best effort.
|
|
297
|
+
}
|
|
298
|
+
throw error;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function notifyInProcessWatchers(storeFile: string): void {
|
|
303
|
+
const watchers = inProcessWatchers.get(storeFile);
|
|
304
|
+
if (!watchers) return;
|
|
305
|
+
for (const refresh of watchers) {
|
|
306
|
+
refresh();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Read one key from a plugin state store (specs/plugin-state.md Sections 1-3). */
|
|
311
|
+
export async function getPluginState(
|
|
312
|
+
target: PluginStateTarget,
|
|
313
|
+
key: string,
|
|
314
|
+
defaultValue?: unknown,
|
|
315
|
+
): Promise<unknown> {
|
|
316
|
+
const paths = pluginStatePaths(target);
|
|
317
|
+
const validKey = validateKey(key);
|
|
318
|
+
const { entries } = readStoreEntries(paths.storeFile);
|
|
319
|
+
if (!Object.hasOwn(entries, validKey)) return defaultValue;
|
|
320
|
+
return entries[validKey];
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Set one key atomically in a plugin state store (specs/plugin-state.md Sections 2-3). */
|
|
324
|
+
export async function setPluginState(
|
|
325
|
+
target: PluginStateTarget,
|
|
326
|
+
key: string,
|
|
327
|
+
value: unknown,
|
|
328
|
+
): Promise<void> {
|
|
329
|
+
const paths = pluginStatePaths(target);
|
|
330
|
+
const validKey = validateKey(key);
|
|
331
|
+
const valueJson = validateValueJson(value);
|
|
332
|
+
await withStoreLock(paths, () => {
|
|
333
|
+
const { entries } = readStoreEntries(paths.storeFile);
|
|
334
|
+
entries[validKey] = JSON.parse(valueJson);
|
|
335
|
+
writeStoreAtomic(paths, entries);
|
|
336
|
+
});
|
|
337
|
+
notifyInProcessWatchers(paths.storeFile);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Delete one key atomically from a plugin state store (specs/plugin-state.md Sections 1-2). */
|
|
341
|
+
export async function deletePluginState(target: PluginStateTarget, key: string): Promise<void> {
|
|
342
|
+
const paths = pluginStatePaths(target);
|
|
343
|
+
const validKey = validateKey(key);
|
|
344
|
+
// Missing store file creates nothing (Section 1).
|
|
345
|
+
if (!existsSync(paths.storeFile)) return;
|
|
346
|
+
let changed = false;
|
|
347
|
+
await withStoreLock(paths, () => {
|
|
348
|
+
const { exists, entries } = readStoreEntries(paths.storeFile);
|
|
349
|
+
if (!exists || !Object.hasOwn(entries, validKey)) return;
|
|
350
|
+
delete entries[validKey];
|
|
351
|
+
writeStoreAtomic(paths, entries);
|
|
352
|
+
changed = true;
|
|
353
|
+
});
|
|
354
|
+
if (changed) notifyInProcessWatchers(paths.storeFile);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** List all keys in ascending UTF-16 code-unit order (specs/plugin-state.md Section 6). */
|
|
358
|
+
export async function listPluginStateKeys(target: PluginStateTarget): Promise<string[]> {
|
|
359
|
+
const paths = pluginStatePaths(target);
|
|
360
|
+
const { entries } = readStoreEntries(paths.storeFile);
|
|
361
|
+
return Object.keys(entries).toSorted(byCodeUnit);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function snapshotOf(entries: Record<string, unknown>): Map<string, string> {
|
|
365
|
+
const map = new Map<string, string>();
|
|
366
|
+
for (const [k, v] of Object.entries(entries)) {
|
|
367
|
+
map.set(k, JSON.stringify(v));
|
|
368
|
+
}
|
|
369
|
+
return map;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Watch a plugin state store across processes (specs/plugin-state.md Section 4).
|
|
374
|
+
* Reports actual value changes from both own-process and cross-process writes in
|
|
375
|
+
* ascending UTF-16 code-unit order of key.
|
|
376
|
+
*/
|
|
377
|
+
export function watchPluginState(
|
|
378
|
+
target: PluginStateTarget,
|
|
379
|
+
listener: PluginStateChangeListener,
|
|
380
|
+
onError?: (error: Error) => void,
|
|
381
|
+
): PluginStateWatcher {
|
|
382
|
+
if (typeof listener !== "function") {
|
|
383
|
+
throw new TypeError("onChange listener must be a function");
|
|
384
|
+
}
|
|
385
|
+
const paths = pluginStatePaths(target);
|
|
386
|
+
let snapshot = new Map<string, string>();
|
|
387
|
+
try {
|
|
388
|
+
snapshot = snapshotOf(readStoreEntries(paths.storeFile).entries);
|
|
389
|
+
} catch (error) {
|
|
390
|
+
onError?.(error instanceof Error ? error : new Error(errorMessage(error)));
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
let closed = false;
|
|
394
|
+
let fsWatcher: FSWatcher | undefined;
|
|
395
|
+
|
|
396
|
+
const refresh = (): void => {
|
|
397
|
+
if (closed) return;
|
|
398
|
+
let next: Map<string, string>;
|
|
399
|
+
try {
|
|
400
|
+
next = snapshotOf(readStoreEntries(paths.storeFile).entries);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
onError?.(error instanceof Error ? error : new Error(errorMessage(error)));
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const allKeys = [...new Set([...snapshot.keys(), ...next.keys()])].toSorted(byCodeUnit);
|
|
406
|
+
const changes: Array<{ key: string; nextJson: string | undefined }> = [];
|
|
407
|
+
for (const key of allKeys) {
|
|
408
|
+
const prevJson = snapshot.get(key);
|
|
409
|
+
const nextJson = next.get(key);
|
|
410
|
+
if (prevJson !== nextJson) {
|
|
411
|
+
changes.push({ key, nextJson });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
snapshot = next;
|
|
415
|
+
for (const change of changes) {
|
|
416
|
+
if (closed) break;
|
|
417
|
+
try {
|
|
418
|
+
listener(
|
|
419
|
+
change.key,
|
|
420
|
+
change.nextJson === undefined ? undefined : JSON.parse(change.nextJson),
|
|
421
|
+
);
|
|
422
|
+
} catch {
|
|
423
|
+
// Listener errors must not stop subsequent notifications (Section 4).
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
const attachFsWatch = (): void => {
|
|
429
|
+
if (closed || fsWatcher !== undefined) return;
|
|
430
|
+
if (!existsSync(paths.storeDir)) return;
|
|
431
|
+
try {
|
|
432
|
+
const watcher = watch(paths.storeDir, { persistent: false }, () => {
|
|
433
|
+
refresh();
|
|
434
|
+
});
|
|
435
|
+
watcher.on("error", () => {
|
|
436
|
+
try {
|
|
437
|
+
watcher.close();
|
|
438
|
+
} catch {
|
|
439
|
+
// Best effort.
|
|
440
|
+
}
|
|
441
|
+
if (fsWatcher === watcher) fsWatcher = undefined;
|
|
442
|
+
});
|
|
443
|
+
fsWatcher = watcher;
|
|
444
|
+
} catch {
|
|
445
|
+
// Directory may have vanished; poll will retry.
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
attachFsWatch();
|
|
450
|
+
const poll = setInterval(() => {
|
|
451
|
+
if (closed) return;
|
|
452
|
+
attachFsWatch();
|
|
453
|
+
refresh();
|
|
454
|
+
}, WATCH_POLL_MS);
|
|
455
|
+
poll.unref();
|
|
456
|
+
|
|
457
|
+
let bucket = inProcessWatchers.get(paths.storeFile);
|
|
458
|
+
if (!bucket) {
|
|
459
|
+
bucket = new Set();
|
|
460
|
+
inProcessWatchers.set(paths.storeFile, bucket);
|
|
461
|
+
}
|
|
462
|
+
bucket.add(refresh);
|
|
463
|
+
|
|
464
|
+
return {
|
|
465
|
+
close(): void {
|
|
466
|
+
if (closed) return;
|
|
467
|
+
closed = true;
|
|
468
|
+
clearInterval(poll);
|
|
469
|
+
if (fsWatcher) {
|
|
470
|
+
try {
|
|
471
|
+
fsWatcher.close();
|
|
472
|
+
} catch {
|
|
473
|
+
// Best effort.
|
|
474
|
+
}
|
|
475
|
+
fsWatcher = undefined;
|
|
476
|
+
}
|
|
477
|
+
const set = inProcessWatchers.get(paths.storeFile);
|
|
478
|
+
if (set) {
|
|
479
|
+
set.delete(refresh);
|
|
480
|
+
if (set.size === 0) inProcessWatchers.delete(paths.storeFile);
|
|
481
|
+
}
|
|
482
|
+
},
|
|
483
|
+
};
|
|
484
|
+
}
|