pi-dent-agent 0.2.9 → 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.
Files changed (39) hide show
  1. package/lib/plugin-state.ts +484 -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,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
+ }
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;
@@ -6,6 +6,18 @@ import { ChildProcess } from "node:child_process";
6
6
  import * as vm from "node:vm";
7
7
  import { Writable } from "node:stream";
8
8
  import { isJsonCompatible, renderReturn } from "./script-render.ts";
9
+ import {
10
+ deletePluginState,
11
+ ensurePluginStateDataDir,
12
+ getPluginState,
13
+ listPluginStateKeys,
14
+ setPluginState,
15
+ watchPluginState,
16
+ type PluginStateChangeListener,
17
+ type PluginStateScope,
18
+ type PluginStateTarget,
19
+ type PluginStateWatcher,
20
+ } from "./plugin-state.ts";
9
21
  import { TEMP_VARIABLES } from "./session-tmp.ts";
10
22
  import { parentPort, workerData } from "node:worker_threads";
11
23
  import { createJiti } from "jiti";
@@ -34,6 +46,10 @@ interface ScriptWorkerData {
34
46
  toolTypes: string;
35
47
  /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
36
48
  uiCall?: boolean;
49
+ /** Plugin namespace when running a plugin script (specs/plugin-state.md Section 6). */
50
+ pluginNamespace?: string;
51
+ /** Workspace root for `dent.state` (defaults to `cwd`). */
52
+ stateWorkspaceRoot?: string;
37
53
  }
38
54
 
39
55
  const port = parentPort;
@@ -55,9 +71,22 @@ class ScriptExit extends Error {}
55
71
 
56
72
  const isScriptExit = (value: unknown): boolean => value instanceof ScriptExit;
57
73
 
74
+ const activeStateWatchers = new Set<PluginStateWatcher>();
75
+ const closeStateWatchers = (): void => {
76
+ for (const watcher of activeStateWatchers) {
77
+ try {
78
+ watcher.close();
79
+ } catch {
80
+ // Best effort.
81
+ }
82
+ }
83
+ activeStateWatchers.clear();
84
+ };
85
+
58
86
  /** Settle `exit-called` and end the script's flow (Section 3). */
59
87
  const postExit = (code?: number): never => {
60
88
  exitCalled = true;
89
+ closeStateWatchers();
61
90
  try {
62
91
  port.postMessage({ type: "exit-called", code: code ?? 0 });
63
92
  } catch {
@@ -250,13 +279,53 @@ const sendUiMessage = (payload: unknown): void => {
250
279
  // Port closed.
251
280
  }
252
281
  };
253
- const scriptDent =
254
- data.uiCall === true
255
- ? Object.freeze({
256
- toolTypes: (): string => data.toolTypes,
257
- ui: Object.freeze({ send: sendUiMessage }),
258
- })
259
- : Object.freeze({ toolTypes: (): string => data.toolTypes });
282
+ const makeStateScopeBinding = (namespace: string, scope: PluginStateScope) => {
283
+ const target: PluginStateTarget =
284
+ scope === "workspace"
285
+ ? { namespace, scope, workspaceRoot: data.stateWorkspaceRoot ?? data.cwd }
286
+ : { namespace, scope };
287
+ const binding = {
288
+ get: (key: string, defaultValue?: unknown): Promise<unknown> =>
289
+ getPluginState(target, key, defaultValue),
290
+ set: (key: string, value: unknown): Promise<void> => setPluginState(target, key, value),
291
+ delete: (key: string): Promise<void> => deletePluginState(target, key),
292
+ keys: (): Promise<string[]> => listPluginStateKeys(target),
293
+ onChange: (listener: PluginStateChangeListener): (() => void) => {
294
+ if (typeof listener !== "function") {
295
+ throw new TypeError("onChange listener must be a function");
296
+ }
297
+ const watcher = watchPluginState(target, (key, value) => {
298
+ if (exitCalled) return;
299
+ listener(key, value);
300
+ });
301
+ activeStateWatchers.add(watcher);
302
+ return () => {
303
+ watcher.close();
304
+ activeStateWatchers.delete(watcher);
305
+ };
306
+ },
307
+ get dir(): string {
308
+ return ensurePluginStateDataDir(target);
309
+ },
310
+ };
311
+ return binding;
312
+ };
313
+
314
+ const scriptState =
315
+ typeof data.pluginNamespace === "string" && data.pluginNamespace !== ""
316
+ ? (() => {
317
+ const ws = makeStateScopeBinding(data.pluginNamespace, "workspace");
318
+ const user = Object.freeze(makeStateScopeBinding(data.pluginNamespace, "user"));
319
+ Object.defineProperty(ws, "user", { value: user, enumerable: true });
320
+ return Object.freeze(ws);
321
+ })()
322
+ : undefined;
323
+
324
+ const scriptDent = Object.freeze({
325
+ toolTypes: (): string => data.toolTypes,
326
+ ...(data.uiCall === true ? { ui: Object.freeze({ send: sendUiMessage }) } : {}),
327
+ ...(scriptState === undefined ? {} : { state: scriptState }),
328
+ });
260
329
  Object.defineProperty(globalThis, "tools", {
261
330
  value: scriptTools,
262
331
  writable: true,
@@ -1094,6 +1163,7 @@ void (async () => {
1094
1163
  mod = { default: completion };
1095
1164
  }
1096
1165
  } catch (err) {
1166
+ closeStateWatchers();
1097
1167
  // The exit already settled the run (Section 3); the worker stays up for the
1098
1168
  // runner's termination and the reaping of the tree it kills (Section 6).
1099
1169
  if (exitCalled || isScriptExit(err)) return;
@@ -1101,6 +1171,7 @@ void (async () => {
1101
1171
  reportError(e);
1102
1172
  return;
1103
1173
  }
1174
+ closeStateWatchers();
1104
1175
  // A script that caught the exit's error reaches its own end; its run already
1105
1176
  // settled as exit-called, so there is no result to report.
1106
1177
  if (exitCalled) return;
@@ -203,6 +203,16 @@ added: v7.0.0
203
203
  integers; a `TypeError` is thrown otherwise, or if `maxEntrySize` is greater
204
204
  than 2 GB.
205
205
 
206
+ The database is not encrypted, and nothing in it is hashed. The request URL
207
+ (including the query string), the response headers and body, and the values of
208
+ any request headers named in the response's `Vary` header (for example
209
+ `Authorization` or `Cookie`) are written as plain text to `location`. Protect
210
+ that file like any other sensitive data, or use `':memory:'`. A response to a
211
+ request that carries `Authorization` is only stored when the response allows it
212
+ with `public`, `s-maxage`, or `must-revalidate` (see [RFC 9111, Section 3.5][]);
213
+ servers can send `Cache-Control: no-store` to keep a response out of the cache
214
+ entirely.
215
+
206
216
  ### `sqliteCacheStore.close()`
207
217
 
208
218
  <!-- YAML
@@ -372,4 +382,5 @@ The value returned by `get`. It contains every field of
372
382
  body. (optional)
373
383
 
374
384
  [RFC&nbsp;9111]: https://www.rfc-editor.org/rfc/rfc9111.html
385
+ [RFC 9111, Section 3.5]: https://www.rfc-editor.org/rfc/rfc9111.html#section-3.5
375
386
  [`node:sqlite`]: https://nodejs.org/api/sqlite.html
@@ -217,7 +217,7 @@ import { Client, buildConnector } from 'undici'
217
217
  const connector = buildConnector({ rejectUnauthorized: false })
218
218
  const client = new Client('https://localhost:3000', {
219
219
  connect (opts, cb) {
220
- connector(opts, (err, socket) => {
220
+ return connector(opts, (err, socket) => {
221
221
  if (err) {
222
222
  cb(err)
223
223
  } else {