pi-dent-agent 0.2.10 → 0.2.11
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/lib/plugin-state.ts +192 -89
- package/package.json +1 -1
package/lib/plugin-state.ts
CHANGED
|
@@ -1,17 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
-
|
|
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";
|
|
2
|
+
import { existsSync, mkdirSync, watch, writeFileSync, type FSWatcher } from "node:fs";
|
|
3
|
+
import { access, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
15
4
|
import { homedir } from "node:os";
|
|
16
5
|
import { isAbsolute, join } from "node:path";
|
|
17
6
|
import { isJsonCompatible } from "./script-render.ts";
|
|
@@ -21,7 +10,7 @@ import { errorCode, errorMessage, isPlainObject } from "./util.ts";
|
|
|
21
10
|
* Durable per-plugin key-value state store (specs/plugin-state.md): shared by
|
|
22
11
|
* pi-dent's `dent.state` script binding and external callers such as Alpha's
|
|
23
12
|
* `alpha.state` host bridge. Plain JSON on disk, atomic per-key writes via
|
|
24
|
-
* lockfile + rename, cross-process change watching.
|
|
13
|
+
* async lockfile + rename, cross-process change watching.
|
|
25
14
|
*/
|
|
26
15
|
|
|
27
16
|
export const PLUGIN_STATE_VERSION = 1;
|
|
@@ -35,6 +24,28 @@ const WATCH_POLL_MS = 200;
|
|
|
35
24
|
|
|
36
25
|
export type PluginStateScope = "workspace" | "user";
|
|
37
26
|
|
|
27
|
+
export type PluginStateErrorCode =
|
|
28
|
+
| "INVALID_NAMESPACE"
|
|
29
|
+
| "INVALID_SCOPE"
|
|
30
|
+
| "INVALID_WORKSPACE_ROOT"
|
|
31
|
+
| "INVALID_KEY"
|
|
32
|
+
| "INVALID_VALUE"
|
|
33
|
+
| "VALUE_TOO_LARGE"
|
|
34
|
+
| "STORE_TOO_LARGE"
|
|
35
|
+
| "STORE_UNREADABLE"
|
|
36
|
+
| "STORE_CORRUPT"
|
|
37
|
+
| "LOCK_TIMEOUT";
|
|
38
|
+
|
|
39
|
+
export class PluginStateError extends Error {
|
|
40
|
+
readonly code: PluginStateErrorCode;
|
|
41
|
+
|
|
42
|
+
constructor(code: PluginStateErrorCode, message: string) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "PluginStateError";
|
|
45
|
+
this.code = code;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
38
49
|
export interface PluginStateTarget {
|
|
39
50
|
namespace: string;
|
|
40
51
|
scope: PluginStateScope;
|
|
@@ -57,13 +68,19 @@ export interface PluginStateWatcher {
|
|
|
57
68
|
|
|
58
69
|
export type PluginStateChangeListener = (key: string, value: unknown) => void;
|
|
59
70
|
|
|
71
|
+
export type PluginStateEntryResult = { found: true; value: unknown } | { found: false };
|
|
72
|
+
|
|
60
73
|
/** Active in-process watchers keyed by `storeFile` so own-process writes notify immediately. */
|
|
61
|
-
const inProcessWatchers = new Map<string, Set<() => void
|
|
74
|
+
const inProcessWatchers = new Map<string, Set<() => Promise<void>>>();
|
|
62
75
|
|
|
63
76
|
function byCodeUnit(a: string, b: string): number {
|
|
64
77
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
65
78
|
}
|
|
66
79
|
|
|
80
|
+
function storeLabel(target: PluginStateTarget): string {
|
|
81
|
+
return `${target.scope}/${target.namespace}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
67
84
|
function isValidNamespace(name: unknown): name is string {
|
|
68
85
|
return (
|
|
69
86
|
typeof name === "string" &&
|
|
@@ -80,49 +97,59 @@ function isValidNamespace(name: unknown): name is string {
|
|
|
80
97
|
|
|
81
98
|
function validateTarget(target: PluginStateTarget): void {
|
|
82
99
|
if (!isPlainObject(target) || !isValidNamespace(target.namespace)) {
|
|
83
|
-
throw new
|
|
100
|
+
throw new PluginStateError(
|
|
101
|
+
"INVALID_NAMESPACE",
|
|
84
102
|
`Invalid plugin namespace: ${JSON.stringify(isPlainObject(target) ? target.namespace : undefined)}`,
|
|
85
103
|
);
|
|
86
104
|
}
|
|
87
105
|
if (target.scope !== "workspace" && target.scope !== "user") {
|
|
88
|
-
throw new
|
|
106
|
+
throw new PluginStateError(
|
|
107
|
+
"INVALID_SCOPE",
|
|
108
|
+
`Invalid plugin state scope: ${JSON.stringify(target.scope)}`,
|
|
109
|
+
);
|
|
89
110
|
}
|
|
90
111
|
if (
|
|
91
112
|
target.scope === "workspace" &&
|
|
92
113
|
(typeof target.workspaceRoot !== "string" || !isAbsolute(target.workspaceRoot))
|
|
93
114
|
) {
|
|
94
|
-
throw new
|
|
115
|
+
throw new PluginStateError("INVALID_WORKSPACE_ROOT", "Workspace root must be an absolute path");
|
|
95
116
|
}
|
|
96
117
|
}
|
|
97
118
|
|
|
98
119
|
function validateKey(key: unknown): string {
|
|
99
120
|
if (typeof key !== "string" || key.length === 0) {
|
|
100
|
-
throw new
|
|
121
|
+
throw new PluginStateError("INVALID_KEY", "State key must be a non-empty string");
|
|
101
122
|
}
|
|
102
123
|
if (key.length > PLUGIN_STATE_KEY_MAX_LENGTH) {
|
|
103
|
-
throw new
|
|
124
|
+
throw new PluginStateError(
|
|
125
|
+
"INVALID_KEY",
|
|
126
|
+
`State key exceeds ${PLUGIN_STATE_KEY_MAX_LENGTH} characters`,
|
|
127
|
+
);
|
|
104
128
|
}
|
|
105
129
|
if (key.includes("\0")) {
|
|
106
|
-
throw new
|
|
130
|
+
throw new PluginStateError("INVALID_KEY", "State key must not contain null characters");
|
|
107
131
|
}
|
|
108
132
|
return key;
|
|
109
133
|
}
|
|
110
134
|
|
|
111
135
|
function validateValueJson(value: unknown): string {
|
|
112
136
|
if (!isJsonCompatible(value)) {
|
|
113
|
-
throw new
|
|
137
|
+
throw new PluginStateError("INVALID_VALUE", "State value must be a JSON value");
|
|
114
138
|
}
|
|
115
139
|
let json: string | undefined;
|
|
116
140
|
try {
|
|
117
141
|
json = JSON.stringify(value);
|
|
118
142
|
} catch {
|
|
119
|
-
throw new
|
|
143
|
+
throw new PluginStateError("INVALID_VALUE", "State value must be a JSON value");
|
|
120
144
|
}
|
|
121
145
|
if (typeof json !== "string") {
|
|
122
|
-
throw new
|
|
146
|
+
throw new PluginStateError("INVALID_VALUE", "State value must be a JSON value");
|
|
123
147
|
}
|
|
124
148
|
if (Buffer.byteLength(json, "utf8") > PLUGIN_STATE_VALUE_CAP_BYTES) {
|
|
125
|
-
throw new
|
|
149
|
+
throw new PluginStateError(
|
|
150
|
+
"VALUE_TOO_LARGE",
|
|
151
|
+
`State value exceeds ${PLUGIN_STATE_VALUE_CAP_BYTES} bytes`,
|
|
152
|
+
);
|
|
126
153
|
}
|
|
127
154
|
return json;
|
|
128
155
|
}
|
|
@@ -157,7 +184,7 @@ export function pluginStatePaths(target: PluginStateTarget): PluginStatePaths {
|
|
|
157
184
|
};
|
|
158
185
|
}
|
|
159
186
|
|
|
160
|
-
function
|
|
187
|
+
function ensureStoreParentAndGitignoreSync(paths: PluginStatePaths): void {
|
|
161
188
|
mkdirSync(paths.storeDir, { recursive: true });
|
|
162
189
|
if (paths.gitignoreFile !== undefined) {
|
|
163
190
|
try {
|
|
@@ -168,10 +195,21 @@ function ensureStoreParentAndGitignore(paths: PluginStatePaths): void {
|
|
|
168
195
|
}
|
|
169
196
|
}
|
|
170
197
|
|
|
171
|
-
|
|
198
|
+
async function ensureStoreParentAndGitignore(paths: PluginStatePaths): Promise<void> {
|
|
199
|
+
await mkdir(paths.storeDir, { recursive: true });
|
|
200
|
+
if (paths.gitignoreFile !== undefined) {
|
|
201
|
+
try {
|
|
202
|
+
await writeFile(paths.gitignoreFile, "*\n", { flag: "wx", encoding: "utf8" });
|
|
203
|
+
} catch (error) {
|
|
204
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Ensure the per-plugin `data/` directory exists and return its absolute path (scripts only). */
|
|
172
210
|
export function ensurePluginStateDataDir(target: PluginStateTarget): string {
|
|
173
211
|
const paths = pluginStatePaths(target);
|
|
174
|
-
|
|
212
|
+
ensureStoreParentAndGitignoreSync(paths);
|
|
175
213
|
mkdirSync(paths.dataDir, { recursive: true });
|
|
176
214
|
return paths.dataDir;
|
|
177
215
|
}
|
|
@@ -181,22 +219,25 @@ interface ParsedStore {
|
|
|
181
219
|
entries: Record<string, unknown>;
|
|
182
220
|
}
|
|
183
221
|
|
|
184
|
-
function readStoreFileRaw(storeFile: string): string | undefined {
|
|
222
|
+
async function readStoreFileRaw(storeFile: string, label: string): Promise<string | undefined> {
|
|
185
223
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
186
224
|
try {
|
|
187
|
-
return
|
|
225
|
+
return await readFile(storeFile, "utf8");
|
|
188
226
|
} catch (error) {
|
|
189
227
|
const code = errorCode(error);
|
|
190
228
|
if (code === "ENOENT") return undefined;
|
|
191
229
|
if (attempt === 0 && (code === "EPERM" || code === "EBUSY")) continue;
|
|
192
|
-
throw new
|
|
230
|
+
throw new PluginStateError(
|
|
231
|
+
"STORE_UNREADABLE",
|
|
232
|
+
`Plugin state store unreadable (${label}): ${code ?? errorMessage(error)}`,
|
|
233
|
+
);
|
|
193
234
|
}
|
|
194
235
|
}
|
|
195
236
|
return undefined;
|
|
196
237
|
}
|
|
197
238
|
|
|
198
|
-
function readStoreEntries(storeFile: string): ParsedStore {
|
|
199
|
-
const raw = readStoreFileRaw(storeFile);
|
|
239
|
+
async function readStoreEntries(storeFile: string, label: string): Promise<ParsedStore> {
|
|
240
|
+
const raw = await readStoreFileRaw(storeFile, label);
|
|
200
241
|
if (raw === undefined) {
|
|
201
242
|
return { exists: false, entries: {} };
|
|
202
243
|
}
|
|
@@ -204,21 +245,29 @@ function readStoreEntries(storeFile: string): ParsedStore {
|
|
|
204
245
|
try {
|
|
205
246
|
parsed = JSON.parse(raw);
|
|
206
247
|
} catch (error) {
|
|
207
|
-
throw new
|
|
248
|
+
throw new PluginStateError(
|
|
249
|
+
"STORE_CORRUPT",
|
|
250
|
+
`Plugin state store is corrupt (${label}): ${errorMessage(error)}`,
|
|
251
|
+
);
|
|
208
252
|
}
|
|
209
253
|
if (!isPlainObject(parsed) || parsed.version !== PLUGIN_STATE_VERSION) {
|
|
210
|
-
throw new
|
|
211
|
-
|
|
254
|
+
throw new PluginStateError(
|
|
255
|
+
"STORE_CORRUPT",
|
|
256
|
+
`Plugin state store is corrupt (${label}): expected version ${PLUGIN_STATE_VERSION} object`,
|
|
212
257
|
);
|
|
213
258
|
}
|
|
214
259
|
if (!isPlainObject(parsed.entries)) {
|
|
215
|
-
throw new
|
|
260
|
+
throw new PluginStateError(
|
|
261
|
+
"STORE_CORRUPT",
|
|
262
|
+
`Plugin state store is corrupt (${label}): entries must be a plain object`,
|
|
263
|
+
);
|
|
216
264
|
}
|
|
217
265
|
const entries: Record<string, unknown> = {};
|
|
218
266
|
for (const [k, v] of Object.entries(parsed.entries)) {
|
|
219
267
|
if (!isJsonCompatible(v)) {
|
|
220
|
-
throw new
|
|
221
|
-
|
|
268
|
+
throw new PluginStateError(
|
|
269
|
+
"STORE_CORRUPT",
|
|
270
|
+
`Plugin state store is corrupt (${label}): entry ${JSON.stringify(k)} is not a JSON value`,
|
|
222
271
|
);
|
|
223
272
|
}
|
|
224
273
|
entries[k] = v;
|
|
@@ -230,28 +279,32 @@ function sleep(ms: number): Promise<void> {
|
|
|
230
279
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
231
280
|
}
|
|
232
281
|
|
|
233
|
-
async function withStoreLock<T>(
|
|
234
|
-
|
|
282
|
+
async function withStoreLock<T>(
|
|
283
|
+
paths: PluginStatePaths,
|
|
284
|
+
label: string,
|
|
285
|
+
fn: () => Promise<T>,
|
|
286
|
+
): Promise<T> {
|
|
287
|
+
await ensureStoreParentAndGitignore(paths);
|
|
235
288
|
const lockPath = join(paths.storeDir, "state.lock");
|
|
236
289
|
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
237
290
|
let acquired = false;
|
|
238
291
|
|
|
239
292
|
while (!acquired) {
|
|
240
293
|
try {
|
|
241
|
-
const
|
|
294
|
+
const handle = await open(lockPath, "wx");
|
|
242
295
|
try {
|
|
243
|
-
|
|
296
|
+
await handle.writeFile(`${process.pid}\n`, "utf8");
|
|
244
297
|
} finally {
|
|
245
|
-
|
|
298
|
+
await handle.close();
|
|
246
299
|
}
|
|
247
300
|
acquired = true;
|
|
248
301
|
} catch (error) {
|
|
249
302
|
if (errorCode(error) !== "EEXIST") throw error;
|
|
250
303
|
try {
|
|
251
|
-
const st =
|
|
304
|
+
const st = await stat(lockPath);
|
|
252
305
|
if (Date.now() - st.mtimeMs > STALE_LOCK_MS) {
|
|
253
306
|
try {
|
|
254
|
-
|
|
307
|
+
await unlink(lockPath);
|
|
255
308
|
} catch {
|
|
256
309
|
// Another process removed it first.
|
|
257
310
|
}
|
|
@@ -262,36 +315,45 @@ async function withStoreLock<T>(paths: PluginStatePaths, fn: () => T): Promise<T
|
|
|
262
315
|
continue;
|
|
263
316
|
}
|
|
264
317
|
if (Date.now() >= deadline) {
|
|
265
|
-
throw new
|
|
318
|
+
throw new PluginStateError(
|
|
319
|
+
"LOCK_TIMEOUT",
|
|
320
|
+
`Timed out waiting for plugin state lock (${label})`,
|
|
321
|
+
);
|
|
266
322
|
}
|
|
267
323
|
await sleep(5 + Math.floor(Math.random() * 15));
|
|
268
324
|
}
|
|
269
325
|
}
|
|
270
326
|
|
|
271
327
|
try {
|
|
272
|
-
return fn();
|
|
328
|
+
return await fn();
|
|
273
329
|
} finally {
|
|
274
330
|
try {
|
|
275
|
-
|
|
331
|
+
await unlink(lockPath);
|
|
276
332
|
} catch {
|
|
277
333
|
// Best effort.
|
|
278
334
|
}
|
|
279
335
|
}
|
|
280
336
|
}
|
|
281
337
|
|
|
282
|
-
function writeStoreAtomic(
|
|
338
|
+
async function writeStoreAtomic(
|
|
339
|
+
paths: PluginStatePaths,
|
|
340
|
+
entries: Record<string, unknown>,
|
|
341
|
+
): Promise<void> {
|
|
283
342
|
const serialized = JSON.stringify({ version: PLUGIN_STATE_VERSION, entries });
|
|
284
343
|
if (Buffer.byteLength(serialized, "utf8") > PLUGIN_STATE_SCOPE_CAP_BYTES) {
|
|
285
|
-
throw new
|
|
344
|
+
throw new PluginStateError(
|
|
345
|
+
"STORE_TOO_LARGE",
|
|
346
|
+
`State store exceeds ${PLUGIN_STATE_SCOPE_CAP_BYTES} bytes`,
|
|
347
|
+
);
|
|
286
348
|
}
|
|
287
349
|
const tmpName = `.state.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
288
350
|
const tmpPath = join(paths.storeDir, tmpName);
|
|
289
351
|
try {
|
|
290
|
-
|
|
291
|
-
|
|
352
|
+
await writeFile(tmpPath, serialized, "utf8");
|
|
353
|
+
await rename(tmpPath, paths.storeFile);
|
|
292
354
|
} catch (error) {
|
|
293
355
|
try {
|
|
294
|
-
|
|
356
|
+
await unlink(tmpPath);
|
|
295
357
|
} catch {
|
|
296
358
|
// Best effort.
|
|
297
359
|
}
|
|
@@ -299,25 +361,32 @@ function writeStoreAtomic(paths: PluginStatePaths, entries: Record<string, unkno
|
|
|
299
361
|
}
|
|
300
362
|
}
|
|
301
363
|
|
|
302
|
-
function notifyInProcessWatchers(storeFile: string): void {
|
|
364
|
+
async function notifyInProcessWatchers(storeFile: string): Promise<void> {
|
|
303
365
|
const watchers = inProcessWatchers.get(storeFile);
|
|
304
366
|
if (!watchers) return;
|
|
305
|
-
|
|
306
|
-
refresh();
|
|
307
|
-
}
|
|
367
|
+
await Promise.all([...watchers].map((refresh) => refresh()));
|
|
308
368
|
}
|
|
309
369
|
|
|
310
|
-
/** Read one
|
|
370
|
+
/** Read one entry, distinguishing absent keys from stored values (specs/plugin-state.md Section 5). */
|
|
371
|
+
export async function readPluginStateEntry(
|
|
372
|
+
target: PluginStateTarget,
|
|
373
|
+
key: string,
|
|
374
|
+
): Promise<PluginStateEntryResult> {
|
|
375
|
+
const paths = pluginStatePaths(target);
|
|
376
|
+
const validKey = validateKey(key);
|
|
377
|
+
const { entries } = await readStoreEntries(paths.storeFile, storeLabel(target));
|
|
378
|
+
if (!Object.hasOwn(entries, validKey)) return { found: false };
|
|
379
|
+
return { found: true, value: entries[validKey] };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Read one key from a plugin state store; returns `defaultValue` by identity when absent. */
|
|
311
383
|
export async function getPluginState(
|
|
312
384
|
target: PluginStateTarget,
|
|
313
385
|
key: string,
|
|
314
386
|
defaultValue?: unknown,
|
|
315
387
|
): Promise<unknown> {
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
const { entries } = readStoreEntries(paths.storeFile);
|
|
319
|
-
if (!Object.hasOwn(entries, validKey)) return defaultValue;
|
|
320
|
-
return entries[validKey];
|
|
388
|
+
const entry = await readPluginStateEntry(target, key);
|
|
389
|
+
return entry.found ? entry.value : defaultValue;
|
|
321
390
|
}
|
|
322
391
|
|
|
323
392
|
/** Set one key atomically in a plugin state store (specs/plugin-state.md Sections 2-3). */
|
|
@@ -327,37 +396,43 @@ export async function setPluginState(
|
|
|
327
396
|
value: unknown,
|
|
328
397
|
): Promise<void> {
|
|
329
398
|
const paths = pluginStatePaths(target);
|
|
399
|
+
const label = storeLabel(target);
|
|
330
400
|
const validKey = validateKey(key);
|
|
331
401
|
const valueJson = validateValueJson(value);
|
|
332
|
-
await withStoreLock(paths, () => {
|
|
333
|
-
const { entries } = readStoreEntries(paths.storeFile);
|
|
402
|
+
await withStoreLock(paths, label, async () => {
|
|
403
|
+
const { entries } = await readStoreEntries(paths.storeFile, label);
|
|
334
404
|
entries[validKey] = JSON.parse(valueJson);
|
|
335
|
-
writeStoreAtomic(paths, entries);
|
|
405
|
+
await writeStoreAtomic(paths, entries);
|
|
336
406
|
});
|
|
337
|
-
notifyInProcessWatchers(paths.storeFile);
|
|
407
|
+
await notifyInProcessWatchers(paths.storeFile);
|
|
338
408
|
}
|
|
339
409
|
|
|
340
410
|
/** Delete one key atomically from a plugin state store (specs/plugin-state.md Sections 1-2). */
|
|
341
411
|
export async function deletePluginState(target: PluginStateTarget, key: string): Promise<void> {
|
|
342
412
|
const paths = pluginStatePaths(target);
|
|
413
|
+
const label = storeLabel(target);
|
|
343
414
|
const validKey = validateKey(key);
|
|
344
415
|
// Missing store file creates nothing (Section 1).
|
|
345
|
-
|
|
416
|
+
try {
|
|
417
|
+
await access(paths.storeFile);
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if (errorCode(error) === "ENOENT") return;
|
|
420
|
+
}
|
|
346
421
|
let changed = false;
|
|
347
|
-
await withStoreLock(paths, () => {
|
|
348
|
-
const { exists, entries } = readStoreEntries(paths.storeFile);
|
|
422
|
+
await withStoreLock(paths, label, async () => {
|
|
423
|
+
const { exists, entries } = await readStoreEntries(paths.storeFile, label);
|
|
349
424
|
if (!exists || !Object.hasOwn(entries, validKey)) return;
|
|
350
425
|
delete entries[validKey];
|
|
351
|
-
writeStoreAtomic(paths, entries);
|
|
426
|
+
await writeStoreAtomic(paths, entries);
|
|
352
427
|
changed = true;
|
|
353
428
|
});
|
|
354
|
-
if (changed) notifyInProcessWatchers(paths.storeFile);
|
|
429
|
+
if (changed) await notifyInProcessWatchers(paths.storeFile);
|
|
355
430
|
}
|
|
356
431
|
|
|
357
432
|
/** List all keys in ascending UTF-16 code-unit order (specs/plugin-state.md Section 6). */
|
|
358
433
|
export async function listPluginStateKeys(target: PluginStateTarget): Promise<string[]> {
|
|
359
434
|
const paths = pluginStatePaths(target);
|
|
360
|
-
const { entries } = readStoreEntries(paths.storeFile);
|
|
435
|
+
const { entries } = await readStoreEntries(paths.storeFile, storeLabel(target));
|
|
361
436
|
return Object.keys(entries).toSorted(byCodeUnit);
|
|
362
437
|
}
|
|
363
438
|
|
|
@@ -371,37 +446,44 @@ function snapshotOf(entries: Record<string, unknown>): Map<string, string> {
|
|
|
371
446
|
|
|
372
447
|
/**
|
|
373
448
|
* Watch a plugin state store across processes (specs/plugin-state.md Section 4).
|
|
374
|
-
*
|
|
375
|
-
*
|
|
449
|
+
* Invalid targets and non-function listeners throw synchronously. Existing keys
|
|
450
|
+
* at watch start are snapshotted and not emitted; subsequent changes from both
|
|
451
|
+
* own-process and cross-process writes emit in ascending UTF-16 code-unit order.
|
|
376
452
|
*/
|
|
377
453
|
export function watchPluginState(
|
|
378
454
|
target: PluginStateTarget,
|
|
379
455
|
listener: PluginStateChangeListener,
|
|
380
456
|
onError?: (error: Error) => void,
|
|
381
457
|
): PluginStateWatcher {
|
|
458
|
+
const paths = pluginStatePaths(target);
|
|
382
459
|
if (typeof listener !== "function") {
|
|
383
460
|
throw new TypeError("onChange listener must be a function");
|
|
384
461
|
}
|
|
385
|
-
const
|
|
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
|
-
}
|
|
462
|
+
const label = storeLabel(target);
|
|
392
463
|
|
|
464
|
+
let snapshot = new Map<string, string>();
|
|
465
|
+
let initialized = false;
|
|
393
466
|
let closed = false;
|
|
394
467
|
let fsWatcher: FSWatcher | undefined;
|
|
468
|
+
let runningPromise: Promise<void> | undefined;
|
|
469
|
+
let pendingRefresh = false;
|
|
395
470
|
|
|
396
|
-
const
|
|
471
|
+
const runRefresh = async (): Promise<void> => {
|
|
397
472
|
if (closed) return;
|
|
398
473
|
let next: Map<string, string>;
|
|
399
474
|
try {
|
|
400
|
-
next = snapshotOf(readStoreEntries(paths.storeFile).entries);
|
|
475
|
+
next = snapshotOf((await readStoreEntries(paths.storeFile, label)).entries);
|
|
401
476
|
} catch (error) {
|
|
477
|
+
initialized = true;
|
|
402
478
|
onError?.(error instanceof Error ? error : new Error(errorMessage(error)));
|
|
403
479
|
return;
|
|
404
480
|
}
|
|
481
|
+
if (closed) return;
|
|
482
|
+
if (!initialized) {
|
|
483
|
+
initialized = true;
|
|
484
|
+
snapshot = next;
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
405
487
|
const allKeys = [...new Set([...snapshot.keys(), ...next.keys()])].toSorted(byCodeUnit);
|
|
406
488
|
const changes: Array<{ key: string; nextJson: string | undefined }> = [];
|
|
407
489
|
for (const key of allKeys) {
|
|
@@ -425,12 +507,31 @@ export function watchPluginState(
|
|
|
425
507
|
}
|
|
426
508
|
};
|
|
427
509
|
|
|
510
|
+
const triggerRefresh = (): Promise<void> => {
|
|
511
|
+
if (closed) return Promise.resolve();
|
|
512
|
+
if (runningPromise) {
|
|
513
|
+
pendingRefresh = true;
|
|
514
|
+
return runningPromise;
|
|
515
|
+
}
|
|
516
|
+
runningPromise = (async () => {
|
|
517
|
+
try {
|
|
518
|
+
do {
|
|
519
|
+
pendingRefresh = false;
|
|
520
|
+
await runRefresh();
|
|
521
|
+
} while (pendingRefresh && !closed);
|
|
522
|
+
} finally {
|
|
523
|
+
runningPromise = undefined;
|
|
524
|
+
}
|
|
525
|
+
})();
|
|
526
|
+
return runningPromise;
|
|
527
|
+
};
|
|
528
|
+
|
|
428
529
|
const attachFsWatch = (): void => {
|
|
429
530
|
if (closed || fsWatcher !== undefined) return;
|
|
430
531
|
if (!existsSync(paths.storeDir)) return;
|
|
431
532
|
try {
|
|
432
533
|
const watcher = watch(paths.storeDir, { persistent: false }, () => {
|
|
433
|
-
|
|
534
|
+
triggerRefresh();
|
|
434
535
|
});
|
|
435
536
|
watcher.on("error", () => {
|
|
436
537
|
try {
|
|
@@ -446,11 +547,13 @@ export function watchPluginState(
|
|
|
446
547
|
}
|
|
447
548
|
};
|
|
448
549
|
|
|
550
|
+
// Take the initial snapshot asynchronously so watch start never blocks the event loop.
|
|
551
|
+
triggerRefresh();
|
|
449
552
|
attachFsWatch();
|
|
450
553
|
const poll = setInterval(() => {
|
|
451
554
|
if (closed) return;
|
|
452
555
|
attachFsWatch();
|
|
453
|
-
|
|
556
|
+
triggerRefresh();
|
|
454
557
|
}, WATCH_POLL_MS);
|
|
455
558
|
poll.unref();
|
|
456
559
|
|
|
@@ -459,7 +562,7 @@ export function watchPluginState(
|
|
|
459
562
|
bucket = new Set();
|
|
460
563
|
inProcessWatchers.set(paths.storeFile, bucket);
|
|
461
564
|
}
|
|
462
|
-
bucket.add(
|
|
565
|
+
bucket.add(triggerRefresh);
|
|
463
566
|
|
|
464
567
|
return {
|
|
465
568
|
close(): void {
|
|
@@ -476,7 +579,7 @@ export function watchPluginState(
|
|
|
476
579
|
}
|
|
477
580
|
const set = inProcessWatchers.get(paths.storeFile);
|
|
478
581
|
if (set) {
|
|
479
|
-
set.delete(
|
|
582
|
+
set.delete(triggerRefresh);
|
|
480
583
|
if (set.size === 0) inProcessWatchers.delete(paths.storeFile);
|
|
481
584
|
}
|
|
482
585
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dent-agent",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.11",
|
|
4
4
|
"description": "A generic coding agent as a pi extension: Bash, Task, Agent, Fleet, Script, Search, Markdown and more tools, with billing and terms extensions bundled",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"coding-agent",
|