pi-dent-agent 0.2.9 → 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.
Files changed (39) hide show
  1. package/lib/plugin-state.ts +587 -0
  2. package/lib/plugin-ui.ts +2 -0
  3. package/lib/script-runner.ts +8 -0
  4. package/lib/script-tool.ts +3 -0
  5. package/lib/script-worker.ts +78 -7
  6. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/CacheStore.md +11 -0
  7. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Client.md +1 -1
  8. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Connector.md +9 -2
  9. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Dispatcher.md +20 -0
  10. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Interceptors.md +13 -3
  11. package/node_modules/pi-web-access/node_modules/undici/docs/docs/best-practices/mocking-request.md +1 -1
  12. package/node_modules/pi-web-access/node_modules/undici/lib/api/abort-signal.js +55 -5
  13. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-connect.js +6 -2
  14. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-pipeline.js +7 -2
  15. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-request.js +12 -4
  16. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-stream.js +6 -2
  17. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-upgrade.js +6 -2
  18. package/node_modules/pi-web-access/node_modules/undici/lib/core/request.js +17 -0
  19. package/node_modules/pi-web-access/node_modules/undici/lib/core/symbols.js +3 -1
  20. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h1.js +24 -0
  21. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h2.js +11 -5
  22. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client.js +109 -2
  23. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher-base.js +6 -1
  24. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher.js +22 -1
  25. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool-base.js +72 -16
  26. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool.js +22 -9
  27. package/node_modules/pi-web-access/node_modules/undici/lib/handler/cache-handler.js +1 -1
  28. package/node_modules/pi-web-access/node_modules/undici/lib/handler/retry-handler.js +27 -1
  29. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/cache.js +9 -2
  30. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/decompress.js +0 -11
  31. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/deduplicate.js +4 -1
  32. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/redirect.js +4 -1
  33. package/node_modules/pi-web-access/node_modules/undici/lib/util/cache.js +1 -1
  34. package/node_modules/pi-web-access/node_modules/undici/lib/util/timers.js +1 -1
  35. package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/index.js +20 -1
  36. package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/util.js +2 -2
  37. package/node_modules/pi-web-access/node_modules/undici/package.json +3 -3
  38. package/node_modules/pi-web-access/node_modules/undici/types/retry-handler.d.ts +1 -1
  39. package/package.json +1 -1
@@ -0,0 +1,587 @@
1
+ import { randomBytes } from "node:crypto";
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";
4
+ import { homedir } from "node:os";
5
+ import { isAbsolute, join } from "node:path";
6
+ import { isJsonCompatible } from "./script-render.ts";
7
+ import { errorCode, errorMessage, isPlainObject } from "./util.ts";
8
+
9
+ /**
10
+ * Durable per-plugin key-value state store (specs/plugin-state.md): shared by
11
+ * pi-dent's `dent.state` script binding and external callers such as Alpha's
12
+ * `alpha.state` host bridge. Plain JSON on disk, atomic per-key writes via
13
+ * async lockfile + rename, cross-process change watching.
14
+ */
15
+
16
+ export const PLUGIN_STATE_VERSION = 1;
17
+ export const PLUGIN_STATE_KEY_MAX_LENGTH = 256;
18
+ export const PLUGIN_STATE_VALUE_CAP_BYTES = 262_144;
19
+ export const PLUGIN_STATE_SCOPE_CAP_BYTES = 5_242_880;
20
+
21
+ const LOCK_TIMEOUT_MS = 5000;
22
+ const STALE_LOCK_MS = 30_000;
23
+ const WATCH_POLL_MS = 200;
24
+
25
+ export type PluginStateScope = "workspace" | "user";
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
+
49
+ export interface PluginStateTarget {
50
+ namespace: string;
51
+ scope: PluginStateScope;
52
+ /** Required (and must be absolute) when `scope === "workspace"`. */
53
+ workspaceRoot?: string;
54
+ /** Optional override for user-scope base directory (defaults to PI_DENT_STATE_DIR or ~/.pi/pi-dent). */
55
+ userStateRoot?: string;
56
+ }
57
+
58
+ export interface PluginStatePaths {
59
+ storeDir: string;
60
+ storeFile: string;
61
+ dataDir: string;
62
+ gitignoreFile: string | undefined;
63
+ }
64
+
65
+ export interface PluginStateWatcher {
66
+ close(): void;
67
+ }
68
+
69
+ export type PluginStateChangeListener = (key: string, value: unknown) => void;
70
+
71
+ export type PluginStateEntryResult = { found: true; value: unknown } | { found: false };
72
+
73
+ /** Active in-process watchers keyed by `storeFile` so own-process writes notify immediately. */
74
+ const inProcessWatchers = new Map<string, Set<() => Promise<void>>>();
75
+
76
+ function byCodeUnit(a: string, b: string): number {
77
+ return a < b ? -1 : a > b ? 1 : 0;
78
+ }
79
+
80
+ function storeLabel(target: PluginStateTarget): string {
81
+ return `${target.scope}/${target.namespace}`;
82
+ }
83
+
84
+ function isValidNamespace(name: unknown): name is string {
85
+ return (
86
+ typeof name === "string" &&
87
+ name !== "" &&
88
+ name !== "." &&
89
+ name !== ".." &&
90
+ !/\s/.test(name) &&
91
+ !name.includes(":") &&
92
+ !name.includes("/") &&
93
+ !name.includes("\\") &&
94
+ !name.includes("\0")
95
+ );
96
+ }
97
+
98
+ function validateTarget(target: PluginStateTarget): void {
99
+ if (!isPlainObject(target) || !isValidNamespace(target.namespace)) {
100
+ throw new PluginStateError(
101
+ "INVALID_NAMESPACE",
102
+ `Invalid plugin namespace: ${JSON.stringify(isPlainObject(target) ? target.namespace : undefined)}`,
103
+ );
104
+ }
105
+ if (target.scope !== "workspace" && target.scope !== "user") {
106
+ throw new PluginStateError(
107
+ "INVALID_SCOPE",
108
+ `Invalid plugin state scope: ${JSON.stringify(target.scope)}`,
109
+ );
110
+ }
111
+ if (
112
+ target.scope === "workspace" &&
113
+ (typeof target.workspaceRoot !== "string" || !isAbsolute(target.workspaceRoot))
114
+ ) {
115
+ throw new PluginStateError("INVALID_WORKSPACE_ROOT", "Workspace root must be an absolute path");
116
+ }
117
+ }
118
+
119
+ function validateKey(key: unknown): string {
120
+ if (typeof key !== "string" || key.length === 0) {
121
+ throw new PluginStateError("INVALID_KEY", "State key must be a non-empty string");
122
+ }
123
+ if (key.length > PLUGIN_STATE_KEY_MAX_LENGTH) {
124
+ throw new PluginStateError(
125
+ "INVALID_KEY",
126
+ `State key exceeds ${PLUGIN_STATE_KEY_MAX_LENGTH} characters`,
127
+ );
128
+ }
129
+ if (key.includes("\0")) {
130
+ throw new PluginStateError("INVALID_KEY", "State key must not contain null characters");
131
+ }
132
+ return key;
133
+ }
134
+
135
+ function validateValueJson(value: unknown): string {
136
+ if (!isJsonCompatible(value)) {
137
+ throw new PluginStateError("INVALID_VALUE", "State value must be a JSON value");
138
+ }
139
+ let json: string | undefined;
140
+ try {
141
+ json = JSON.stringify(value);
142
+ } catch {
143
+ throw new PluginStateError("INVALID_VALUE", "State value must be a JSON value");
144
+ }
145
+ if (typeof json !== "string") {
146
+ throw new PluginStateError("INVALID_VALUE", "State value must be a JSON value");
147
+ }
148
+ if (Buffer.byteLength(json, "utf8") > PLUGIN_STATE_VALUE_CAP_BYTES) {
149
+ throw new PluginStateError(
150
+ "VALUE_TOO_LARGE",
151
+ `State value exceeds ${PLUGIN_STATE_VALUE_CAP_BYTES} bytes`,
152
+ );
153
+ }
154
+ return json;
155
+ }
156
+
157
+ function resolveUserStateRoot(override?: string): string {
158
+ if (typeof override === "string" && override.length > 0) return override;
159
+ const envDir = process.env.PI_DENT_STATE_DIR;
160
+ if (typeof envDir === "string" && envDir.length > 0) return envDir;
161
+ return join(homedir(), ".pi", "pi-dent");
162
+ }
163
+
164
+ /** Resolve all on-disk paths for a plugin state target (specs/plugin-state.md Section 1). */
165
+ export function pluginStatePaths(target: PluginStateTarget): PluginStatePaths {
166
+ validateTarget(target);
167
+ if (target.scope === "workspace") {
168
+ const stateRoot = join(target.workspaceRoot ?? "", ".pi", "pi-dent", "state");
169
+ const storeDir = join(stateRoot, target.namespace);
170
+ return {
171
+ storeDir,
172
+ storeFile: join(storeDir, "state.json"),
173
+ dataDir: join(storeDir, "data"),
174
+ gitignoreFile: join(stateRoot, ".gitignore"),
175
+ };
176
+ }
177
+ const stateRoot = join(resolveUserStateRoot(target.userStateRoot), "state");
178
+ const storeDir = join(stateRoot, target.namespace);
179
+ return {
180
+ storeDir,
181
+ storeFile: join(storeDir, "state.json"),
182
+ dataDir: join(storeDir, "data"),
183
+ gitignoreFile: undefined,
184
+ };
185
+ }
186
+
187
+ function ensureStoreParentAndGitignoreSync(paths: PluginStatePaths): void {
188
+ mkdirSync(paths.storeDir, { recursive: true });
189
+ if (paths.gitignoreFile !== undefined) {
190
+ try {
191
+ writeFileSync(paths.gitignoreFile, "*\n", { flag: "wx", encoding: "utf8" });
192
+ } catch (error) {
193
+ if (errorCode(error) !== "EEXIST") throw error;
194
+ }
195
+ }
196
+ }
197
+
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). */
210
+ export function ensurePluginStateDataDir(target: PluginStateTarget): string {
211
+ const paths = pluginStatePaths(target);
212
+ ensureStoreParentAndGitignoreSync(paths);
213
+ mkdirSync(paths.dataDir, { recursive: true });
214
+ return paths.dataDir;
215
+ }
216
+
217
+ interface ParsedStore {
218
+ exists: boolean;
219
+ entries: Record<string, unknown>;
220
+ }
221
+
222
+ async function readStoreFileRaw(storeFile: string, label: string): Promise<string | undefined> {
223
+ for (let attempt = 0; attempt < 2; attempt++) {
224
+ try {
225
+ return await readFile(storeFile, "utf8");
226
+ } catch (error) {
227
+ const code = errorCode(error);
228
+ if (code === "ENOENT") return undefined;
229
+ if (attempt === 0 && (code === "EPERM" || code === "EBUSY")) continue;
230
+ throw new PluginStateError(
231
+ "STORE_UNREADABLE",
232
+ `Plugin state store unreadable (${label}): ${code ?? errorMessage(error)}`,
233
+ );
234
+ }
235
+ }
236
+ return undefined;
237
+ }
238
+
239
+ async function readStoreEntries(storeFile: string, label: string): Promise<ParsedStore> {
240
+ const raw = await readStoreFileRaw(storeFile, label);
241
+ if (raw === undefined) {
242
+ return { exists: false, entries: {} };
243
+ }
244
+ let parsed: unknown;
245
+ try {
246
+ parsed = JSON.parse(raw);
247
+ } catch (error) {
248
+ throw new PluginStateError(
249
+ "STORE_CORRUPT",
250
+ `Plugin state store is corrupt (${label}): ${errorMessage(error)}`,
251
+ );
252
+ }
253
+ if (!isPlainObject(parsed) || parsed.version !== PLUGIN_STATE_VERSION) {
254
+ throw new PluginStateError(
255
+ "STORE_CORRUPT",
256
+ `Plugin state store is corrupt (${label}): expected version ${PLUGIN_STATE_VERSION} object`,
257
+ );
258
+ }
259
+ if (!isPlainObject(parsed.entries)) {
260
+ throw new PluginStateError(
261
+ "STORE_CORRUPT",
262
+ `Plugin state store is corrupt (${label}): entries must be a plain object`,
263
+ );
264
+ }
265
+ const entries: Record<string, unknown> = {};
266
+ for (const [k, v] of Object.entries(parsed.entries)) {
267
+ if (!isJsonCompatible(v)) {
268
+ throw new PluginStateError(
269
+ "STORE_CORRUPT",
270
+ `Plugin state store is corrupt (${label}): entry ${JSON.stringify(k)} is not a JSON value`,
271
+ );
272
+ }
273
+ entries[k] = v;
274
+ }
275
+ return { exists: true, entries };
276
+ }
277
+
278
+ function sleep(ms: number): Promise<void> {
279
+ return new Promise((resolve) => setTimeout(resolve, ms));
280
+ }
281
+
282
+ async function withStoreLock<T>(
283
+ paths: PluginStatePaths,
284
+ label: string,
285
+ fn: () => Promise<T>,
286
+ ): Promise<T> {
287
+ await ensureStoreParentAndGitignore(paths);
288
+ const lockPath = join(paths.storeDir, "state.lock");
289
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
290
+ let acquired = false;
291
+
292
+ while (!acquired) {
293
+ try {
294
+ const handle = await open(lockPath, "wx");
295
+ try {
296
+ await handle.writeFile(`${process.pid}\n`, "utf8");
297
+ } finally {
298
+ await handle.close();
299
+ }
300
+ acquired = true;
301
+ } catch (error) {
302
+ if (errorCode(error) !== "EEXIST") throw error;
303
+ try {
304
+ const st = await stat(lockPath);
305
+ if (Date.now() - st.mtimeMs > STALE_LOCK_MS) {
306
+ try {
307
+ await unlink(lockPath);
308
+ } catch {
309
+ // Another process removed it first.
310
+ }
311
+ continue;
312
+ }
313
+ } catch {
314
+ // Lock disappeared between open and stat; retry immediately.
315
+ continue;
316
+ }
317
+ if (Date.now() >= deadline) {
318
+ throw new PluginStateError(
319
+ "LOCK_TIMEOUT",
320
+ `Timed out waiting for plugin state lock (${label})`,
321
+ );
322
+ }
323
+ await sleep(5 + Math.floor(Math.random() * 15));
324
+ }
325
+ }
326
+
327
+ try {
328
+ return await fn();
329
+ } finally {
330
+ try {
331
+ await unlink(lockPath);
332
+ } catch {
333
+ // Best effort.
334
+ }
335
+ }
336
+ }
337
+
338
+ async function writeStoreAtomic(
339
+ paths: PluginStatePaths,
340
+ entries: Record<string, unknown>,
341
+ ): Promise<void> {
342
+ const serialized = JSON.stringify({ version: PLUGIN_STATE_VERSION, entries });
343
+ if (Buffer.byteLength(serialized, "utf8") > PLUGIN_STATE_SCOPE_CAP_BYTES) {
344
+ throw new PluginStateError(
345
+ "STORE_TOO_LARGE",
346
+ `State store exceeds ${PLUGIN_STATE_SCOPE_CAP_BYTES} bytes`,
347
+ );
348
+ }
349
+ const tmpName = `.state.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
350
+ const tmpPath = join(paths.storeDir, tmpName);
351
+ try {
352
+ await writeFile(tmpPath, serialized, "utf8");
353
+ await rename(tmpPath, paths.storeFile);
354
+ } catch (error) {
355
+ try {
356
+ await unlink(tmpPath);
357
+ } catch {
358
+ // Best effort.
359
+ }
360
+ throw error;
361
+ }
362
+ }
363
+
364
+ async function notifyInProcessWatchers(storeFile: string): Promise<void> {
365
+ const watchers = inProcessWatchers.get(storeFile);
366
+ if (!watchers) return;
367
+ await Promise.all([...watchers].map((refresh) => refresh()));
368
+ }
369
+
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. */
383
+ export async function getPluginState(
384
+ target: PluginStateTarget,
385
+ key: string,
386
+ defaultValue?: unknown,
387
+ ): Promise<unknown> {
388
+ const entry = await readPluginStateEntry(target, key);
389
+ return entry.found ? entry.value : defaultValue;
390
+ }
391
+
392
+ /** Set one key atomically in a plugin state store (specs/plugin-state.md Sections 2-3). */
393
+ export async function setPluginState(
394
+ target: PluginStateTarget,
395
+ key: string,
396
+ value: unknown,
397
+ ): Promise<void> {
398
+ const paths = pluginStatePaths(target);
399
+ const label = storeLabel(target);
400
+ const validKey = validateKey(key);
401
+ const valueJson = validateValueJson(value);
402
+ await withStoreLock(paths, label, async () => {
403
+ const { entries } = await readStoreEntries(paths.storeFile, label);
404
+ entries[validKey] = JSON.parse(valueJson);
405
+ await writeStoreAtomic(paths, entries);
406
+ });
407
+ await notifyInProcessWatchers(paths.storeFile);
408
+ }
409
+
410
+ /** Delete one key atomically from a plugin state store (specs/plugin-state.md Sections 1-2). */
411
+ export async function deletePluginState(target: PluginStateTarget, key: string): Promise<void> {
412
+ const paths = pluginStatePaths(target);
413
+ const label = storeLabel(target);
414
+ const validKey = validateKey(key);
415
+ // Missing store file creates nothing (Section 1).
416
+ try {
417
+ await access(paths.storeFile);
418
+ } catch (error) {
419
+ if (errorCode(error) === "ENOENT") return;
420
+ }
421
+ let changed = false;
422
+ await withStoreLock(paths, label, async () => {
423
+ const { exists, entries } = await readStoreEntries(paths.storeFile, label);
424
+ if (!exists || !Object.hasOwn(entries, validKey)) return;
425
+ delete entries[validKey];
426
+ await writeStoreAtomic(paths, entries);
427
+ changed = true;
428
+ });
429
+ if (changed) await notifyInProcessWatchers(paths.storeFile);
430
+ }
431
+
432
+ /** List all keys in ascending UTF-16 code-unit order (specs/plugin-state.md Section 6). */
433
+ export async function listPluginStateKeys(target: PluginStateTarget): Promise<string[]> {
434
+ const paths = pluginStatePaths(target);
435
+ const { entries } = await readStoreEntries(paths.storeFile, storeLabel(target));
436
+ return Object.keys(entries).toSorted(byCodeUnit);
437
+ }
438
+
439
+ function snapshotOf(entries: Record<string, unknown>): Map<string, string> {
440
+ const map = new Map<string, string>();
441
+ for (const [k, v] of Object.entries(entries)) {
442
+ map.set(k, JSON.stringify(v));
443
+ }
444
+ return map;
445
+ }
446
+
447
+ /**
448
+ * Watch a plugin state store across processes (specs/plugin-state.md Section 4).
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.
452
+ */
453
+ export function watchPluginState(
454
+ target: PluginStateTarget,
455
+ listener: PluginStateChangeListener,
456
+ onError?: (error: Error) => void,
457
+ ): PluginStateWatcher {
458
+ const paths = pluginStatePaths(target);
459
+ if (typeof listener !== "function") {
460
+ throw new TypeError("onChange listener must be a function");
461
+ }
462
+ const label = storeLabel(target);
463
+
464
+ let snapshot = new Map<string, string>();
465
+ let initialized = false;
466
+ let closed = false;
467
+ let fsWatcher: FSWatcher | undefined;
468
+ let runningPromise: Promise<void> | undefined;
469
+ let pendingRefresh = false;
470
+
471
+ const runRefresh = async (): Promise<void> => {
472
+ if (closed) return;
473
+ let next: Map<string, string>;
474
+ try {
475
+ next = snapshotOf((await readStoreEntries(paths.storeFile, label)).entries);
476
+ } catch (error) {
477
+ initialized = true;
478
+ onError?.(error instanceof Error ? error : new Error(errorMessage(error)));
479
+ return;
480
+ }
481
+ if (closed) return;
482
+ if (!initialized) {
483
+ initialized = true;
484
+ snapshot = next;
485
+ return;
486
+ }
487
+ const allKeys = [...new Set([...snapshot.keys(), ...next.keys()])].toSorted(byCodeUnit);
488
+ const changes: Array<{ key: string; nextJson: string | undefined }> = [];
489
+ for (const key of allKeys) {
490
+ const prevJson = snapshot.get(key);
491
+ const nextJson = next.get(key);
492
+ if (prevJson !== nextJson) {
493
+ changes.push({ key, nextJson });
494
+ }
495
+ }
496
+ snapshot = next;
497
+ for (const change of changes) {
498
+ if (closed) break;
499
+ try {
500
+ listener(
501
+ change.key,
502
+ change.nextJson === undefined ? undefined : JSON.parse(change.nextJson),
503
+ );
504
+ } catch {
505
+ // Listener errors must not stop subsequent notifications (Section 4).
506
+ }
507
+ }
508
+ };
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
+
529
+ const attachFsWatch = (): void => {
530
+ if (closed || fsWatcher !== undefined) return;
531
+ if (!existsSync(paths.storeDir)) return;
532
+ try {
533
+ const watcher = watch(paths.storeDir, { persistent: false }, () => {
534
+ triggerRefresh();
535
+ });
536
+ watcher.on("error", () => {
537
+ try {
538
+ watcher.close();
539
+ } catch {
540
+ // Best effort.
541
+ }
542
+ if (fsWatcher === watcher) fsWatcher = undefined;
543
+ });
544
+ fsWatcher = watcher;
545
+ } catch {
546
+ // Directory may have vanished; poll will retry.
547
+ }
548
+ };
549
+
550
+ // Take the initial snapshot asynchronously so watch start never blocks the event loop.
551
+ triggerRefresh();
552
+ attachFsWatch();
553
+ const poll = setInterval(() => {
554
+ if (closed) return;
555
+ attachFsWatch();
556
+ triggerRefresh();
557
+ }, WATCH_POLL_MS);
558
+ poll.unref();
559
+
560
+ let bucket = inProcessWatchers.get(paths.storeFile);
561
+ if (!bucket) {
562
+ bucket = new Set();
563
+ inProcessWatchers.set(paths.storeFile, bucket);
564
+ }
565
+ bucket.add(triggerRefresh);
566
+
567
+ return {
568
+ close(): void {
569
+ if (closed) return;
570
+ closed = true;
571
+ clearInterval(poll);
572
+ if (fsWatcher) {
573
+ try {
574
+ fsWatcher.close();
575
+ } catch {
576
+ // Best effort.
577
+ }
578
+ fsWatcher = undefined;
579
+ }
580
+ const set = inProcessWatchers.get(paths.storeFile);
581
+ if (set) {
582
+ set.delete(triggerRefresh);
583
+ if (set.size === 0) inProcessWatchers.delete(paths.storeFile);
584
+ }
585
+ },
586
+ };
587
+ }
package/lib/plugin-ui.ts CHANGED
@@ -445,6 +445,8 @@ export class PluginUiController {
445
445
  input: { ui: data },
446
446
  aliases: bundledAliases(),
447
447
  uiCall: true,
448
+ pluginNamespace: plugin.name,
449
+ stateWorkspaceRoot: ctx.cwd,
448
450
  ...(tools === undefined ? {} : { tools }),
449
451
  ...(ctx.extraEnv && Object.keys(ctx.extraEnv).length > 0 ? { extraEnv: ctx.extraEnv } : {}),
450
452
  onUiMessage: (dataJson) => {
@@ -96,6 +96,10 @@ export interface ScriptRunRequest {
96
96
  uiCall?: boolean;
97
97
  /** Fired with each validated UI message JSON payload before settlement. */
98
98
  onUiMessage?: (json: string) => void;
99
+ /** Plugin namespace when running a plugin script (specs/plugin-state.md Section 6). */
100
+ pluginNamespace?: string;
101
+ /** Workspace root for `dent.state` (defaults to `cwd`). */
102
+ stateWorkspaceRoot?: string;
99
103
  }
100
104
 
101
105
  /** Pre-validated return outcome of a plugin UI call (specs/plugin-ui.md Section 5). */
@@ -321,6 +325,10 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
321
325
  unavailableToolNames: req.tools?.unavailableNames ?? [],
322
326
  toolTypes: req.tools?.declarations ?? toolDeclarations({ bound: [], unbound: [] }),
323
327
  uiCall: req.uiCall === true,
328
+ ...(req.pluginNamespace === undefined ? {} : { pluginNamespace: req.pluginNamespace }),
329
+ ...(req.stateWorkspaceRoot === undefined
330
+ ? {}
331
+ : { stateWorkspaceRoot: req.stateWorkspaceRoot }),
324
332
  },
325
333
  env: workerEnv,
326
334
  });
@@ -452,6 +452,9 @@ export function makeScriptTool(deps: ScriptToolDeps) {
452
452
  cwd,
453
453
  input: params.input,
454
454
  aliases: bundledAliases(),
455
+ ...(shape.kind === "plugin"
456
+ ? { pluginNamespace: shape.plugin, stateWorkspaceRoot: host.cwd() }
457
+ : {}),
455
458
  };
456
459
  if (timeoutMs !== undefined) request.timeoutMs = timeoutMs;
457
460
  if (!background && signal !== undefined) request.signal = signal;