pi-dent-agent 0.2.6 → 0.2.7

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 CHANGED
@@ -23,6 +23,7 @@ import { runFleetCommand } from "./lib/fleet-command.ts";
23
23
  import { recapRuntime } from "./lib/recap.ts";
24
24
  import { renderRecapEntry } from "./lib/recap-render.ts";
25
25
  import { appendPluginContext, renderPluginCommand } from "./lib/plugins.ts";
26
+ import { PluginUiController } from "./lib/plugin-ui.ts";
26
27
  import { type Diagnostic, errorMessage, isPlainObject } from "./lib/util.ts";
27
28
  import { rebuildInterruptedTasks } from "./lib/task-rebuild.ts";
28
29
  import {
@@ -282,6 +283,7 @@ export default function (pi: ExtensionAPI) {
282
283
  // Section 2).
283
284
  const questions = askUserRuntime();
284
285
  const recap = recapRuntime(boot.config, (data) => pi.appendEntry("pi-dent-recap", data));
286
+ const pluginUi = new PluginUiController(boot.pluginIndex);
285
287
  let taskWidget: TaskWidgetHandle | undefined;
286
288
  // Feeds for an RPC client (task.md Section 4.1, fleet-tool.md Section 6).
287
289
  let taskFeed: FeedHandle | undefined;
@@ -688,6 +690,11 @@ export default function (pi: ExtensionAPI) {
688
690
  }
689
691
  shutdownStep("ending owned tasks", () => engine.registry.end(), reportShutdown);
690
692
  shutdownStep("cancelling owned task runs", () => engine.cancelAll(), reportShutdown);
693
+ shutdownStep(
694
+ "cancelling plugin UI calls",
695
+ () => pluginUi.cancelAll("Session ended"),
696
+ reportShutdown,
697
+ );
691
698
  // The Search tool's continuations of catch-up end with the boot window
692
699
  // (search-tool.md Section 2.2).
693
700
  shutdownStep("stopping Search", () => search.stop(), reportShutdown);
@@ -899,6 +906,17 @@ export default function (pi: ExtensionAPI) {
899
906
  }
900
907
  }
901
908
 
909
+ pi.registerCommand("dent-ui", {
910
+ description: "Run and cancel plugin UI script calls",
911
+ handler: async (args, ctx) => {
912
+ if (ctx.mode !== "rpc") return;
913
+ pluginUi.handleCommand(args, {
914
+ cwd: ctx.cwd ?? currentHost?.cwd() ?? process.cwd(),
915
+ setWidget: (key, lines) => ctx.ui.setWidget(key, lines),
916
+ });
917
+ },
918
+ });
919
+
902
920
  pi.registerCommand("dent", {
903
921
  description: "Confirm the pi-dent extension is loaded",
904
922
  handler: async (_args, ctx) => {
@@ -0,0 +1,237 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { bundledAliases } from "./bundled.ts";
3
+ import type { PluginEntry } from "./plugins.ts";
4
+ import { resolvePluginScriptPath } from "./plugins.ts";
5
+ import { runScript, type ScriptRunHandle, type ScriptRunResult } from "./script-runner.ts";
6
+ import { errorCode, errorMessage, isPlainObject } from "./util.ts";
7
+
8
+ /**
9
+ * Plugin UI protocol controller (specs/plugin-ui.md): handles `/dent-ui run`
10
+ * and `/dent-ui cancel`, executes plugin scripts with `dent.ui.send` and no
11
+ * time limit or tool functions, and emits `message` and `reply` records on the
12
+ * `pi-dent-ui` widget feed.
13
+ */
14
+
15
+ export const PLUGIN_UI_WIDGET_KEY = "pi-dent-ui";
16
+ export const PLUGIN_UI_PROTOCOL = "ui/1";
17
+ export const PLUGIN_UI_PAYLOAD_CAP_BYTES = 262_144;
18
+
19
+ export interface PluginUiCommandContext {
20
+ cwd: string;
21
+ setWidget(key: string, lines: string[] | undefined): void;
22
+ extraEnv?: Record<string, string>;
23
+ }
24
+
25
+ interface ActiveUiCall {
26
+ handle: ScriptRunHandle;
27
+ cancelReason?: string;
28
+ }
29
+
30
+ function formatThrownError(
31
+ error: { name: string; message: string; stack: string } | undefined,
32
+ ): string {
33
+ if (!error) return "Script threw an error";
34
+ return error.message === "" ? error.name : `${error.name}: ${error.message}`;
35
+ }
36
+
37
+ export class PluginUiController {
38
+ private readonly pluginIndex: ReadonlyMap<string, PluginEntry>;
39
+ private readonly active = new Map<string, ActiveUiCall>();
40
+
41
+ constructor(pluginIndex: ReadonlyMap<string, PluginEntry>) {
42
+ this.pluginIndex = pluginIndex;
43
+ }
44
+
45
+ /** Number of UI calls currently executing. */
46
+ activeCount(): number {
47
+ return this.active.size;
48
+ }
49
+
50
+ /** Handle one `/dent-ui <args>` command (specs/plugin-ui.md Sections 1-3). */
51
+ handleCommand(args: string, ctx: PluginUiCommandContext): void {
52
+ const trimmed = args.trim();
53
+ if (trimmed === "") return;
54
+ const space = trimmed.search(/\s/);
55
+ const subcommand = space === -1 ? trimmed : trimmed.slice(0, space);
56
+ const payload = space === -1 ? "" : trimmed.slice(space).trim();
57
+ if (subcommand === "run") {
58
+ this.handleRun(payload, ctx);
59
+ } else if (subcommand === "cancel") {
60
+ this.handleCancel(payload);
61
+ }
62
+ }
63
+
64
+ /** Cancel every executing UI call (specs/plugin-ui.md Section 6). */
65
+ cancelAll(reason = "Session ended"): void {
66
+ for (const entry of this.active.values()) {
67
+ entry.cancelReason = reason;
68
+ entry.handle.cancel("killed");
69
+ }
70
+ }
71
+
72
+ private handleRun(rawJson: string, ctx: PluginUiCommandContext): void {
73
+ let parsed: unknown;
74
+ try {
75
+ parsed = JSON.parse(rawJson);
76
+ } catch {
77
+ return;
78
+ }
79
+ if (!isPlainObject(parsed) || typeof parsed.id !== "string" || parsed.id === "") {
80
+ return;
81
+ }
82
+ const id = parsed.id;
83
+ const emitLine = (line: string): void => {
84
+ try {
85
+ ctx.setWidget(PLUGIN_UI_WIDGET_KEY, [line]);
86
+ } catch {
87
+ // Widget update failures are unreported per specs/AGENTS.md.
88
+ }
89
+ };
90
+ const emitMessageJson = (dataJson: string): void => {
91
+ emitLine(
92
+ `{"piDent":${JSON.stringify(PLUGIN_UI_PROTOCOL)},"type":"message","id":${JSON.stringify(id)},"data":${dataJson}}`,
93
+ );
94
+ };
95
+ const emitReplyOkJson = (valueJson: string): void => {
96
+ emitLine(
97
+ `{"piDent":${JSON.stringify(PLUGIN_UI_PROTOCOL)},"type":"reply","id":${JSON.stringify(id)},"ok":true,"value":${valueJson}}`,
98
+ );
99
+ };
100
+ const emitReplyError = (error: string): void => {
101
+ emitLine(
102
+ JSON.stringify({
103
+ piDent: PLUGIN_UI_PROTOCOL,
104
+ type: "reply",
105
+ id,
106
+ ok: false,
107
+ error,
108
+ }),
109
+ );
110
+ };
111
+
112
+ if (this.active.has(id)) {
113
+ emitReplyError(`UI call "${id}" is already running`);
114
+ return;
115
+ }
116
+ if (typeof parsed.namespace !== "string" || parsed.namespace === "") {
117
+ emitReplyError("Invalid plugin namespace");
118
+ return;
119
+ }
120
+ const plugin = this.pluginIndex.get(parsed.namespace);
121
+ if (!plugin) {
122
+ emitReplyError(`Unknown plugin "${parsed.namespace}"`);
123
+ return;
124
+ }
125
+ if (typeof parsed.root !== "string" || parsed.root !== plugin.root) {
126
+ emitReplyError(`Plugin "${parsed.namespace}" root mismatch`);
127
+ return;
128
+ }
129
+ if (typeof parsed.path !== "string" || parsed.path.trim() === "") {
130
+ emitReplyError("Invalid script path");
131
+ return;
132
+ }
133
+ const resolved = resolvePluginScriptPath(plugin.root, parsed.path);
134
+ if ("error" in resolved) {
135
+ emitReplyError(`plugin "${parsed.namespace}": ${resolved.error}`);
136
+ return;
137
+ }
138
+ let code: string;
139
+ try {
140
+ code = readFileSync(resolved.path, "utf8");
141
+ } catch (error) {
142
+ const codeName = errorCode(error);
143
+ emitReplyError(
144
+ codeName === "ENOENT"
145
+ ? `plugin "${parsed.namespace}": missing script ${resolved.path}`
146
+ : `plugin "${parsed.namespace}": failed to read ${resolved.path}: ${codeName ?? errorMessage(error)}`,
147
+ );
148
+ return;
149
+ }
150
+
151
+ const data = parsed.data === undefined ? null : parsed.data;
152
+ let handle: ScriptRunHandle;
153
+ try {
154
+ handle = runScript({
155
+ code,
156
+ filename: resolved.path,
157
+ cwd: ctx.cwd,
158
+ input: { ui: data },
159
+ aliases: bundledAliases(),
160
+ uiCall: true,
161
+ ...(ctx.extraEnv && Object.keys(ctx.extraEnv).length > 0 ? { extraEnv: ctx.extraEnv } : {}),
162
+ onUiMessage: (dataJson) => {
163
+ emitMessageJson(dataJson);
164
+ },
165
+ });
166
+ } catch (error) {
167
+ emitReplyError(`Failed to start script: ${errorMessage(error)}`);
168
+ return;
169
+ }
170
+
171
+ const entry: ActiveUiCall = { handle };
172
+ this.active.set(id, entry);
173
+
174
+ void handle.promise
175
+ .then((result) => {
176
+ this.active.delete(id);
177
+ this.emitSettlementReply(result, entry, emitReplyOkJson, emitReplyError);
178
+ })
179
+ .catch((error: unknown) => {
180
+ this.active.delete(id);
181
+ emitReplyError(errorMessage(error));
182
+ });
183
+ }
184
+
185
+ private emitSettlementReply(
186
+ result: ScriptRunResult,
187
+ entry: ActiveUiCall,
188
+ emitOkJson: (valueJson: string) => void,
189
+ emitError: (error: string) => void,
190
+ ): void {
191
+ switch (result.exitReason) {
192
+ case "ok":
193
+ if (result.uiReturn?.ok === true) {
194
+ emitOkJson(result.uiReturn.json);
195
+ } else if (result.uiReturn?.ok === false) {
196
+ emitError(result.uiReturn.error);
197
+ } else {
198
+ emitOkJson("null");
199
+ }
200
+ return;
201
+ case "exit-called":
202
+ if ((result.exitCode ?? 0) === 0) {
203
+ emitOkJson("null");
204
+ } else {
205
+ emitError(`Script exited with code ${result.exitCode}`);
206
+ }
207
+ return;
208
+ case "threw":
209
+ emitError(formatThrownError(result.error));
210
+ return;
211
+ case "killed":
212
+ case "aborted":
213
+ emitError(entry.cancelReason ?? "UI call was cancelled");
214
+ return;
215
+ case "timeout":
216
+ emitError("UI call timed out");
217
+ return;
218
+ }
219
+ }
220
+
221
+ private handleCancel(rawJson: string): void {
222
+ let parsed: unknown;
223
+ try {
224
+ parsed = JSON.parse(rawJson);
225
+ } catch {
226
+ return;
227
+ }
228
+ if (!isPlainObject(parsed) || !Array.isArray(parsed.ids)) return;
229
+ for (const id of parsed.ids) {
230
+ if (typeof id !== "string") continue;
231
+ const entry = this.active.get(id);
232
+ if (!entry) continue;
233
+ entry.cancelReason = "UI call was cancelled";
234
+ entry.handle.cancel("killed");
235
+ }
236
+ }
237
+ }
@@ -4,7 +4,7 @@ import type { ToolCallReply } from "./script-tool-calls.ts";
4
4
  import { toolDeclarations } from "./script-tool-types.ts";
5
5
  import { applySessionTmp } from "./session-tmp.ts";
6
6
  import { killTreeWindows, prefixBytes, signalGroup } from "./tool-common.ts";
7
- import { errorCode, errorMessage } from "./util.ts";
7
+ import { errorCode, errorMessage, isPlainObject } from "./util.ts";
8
8
  import { typeStrippingOptions } from "./worker-options.ts";
9
9
 
10
10
  /**
@@ -92,8 +92,15 @@ export interface ScriptRunRequest {
92
92
  extraEnv?: Record<string, string>;
93
93
  /** The tool functions (Section 10); absent binds none. */
94
94
  tools?: ScriptRunTools;
95
+ /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
96
+ uiCall?: boolean;
97
+ /** Fired with each validated UI message JSON payload before settlement. */
98
+ onUiMessage?: (json: string) => void;
95
99
  }
96
100
 
101
+ /** Pre-validated return outcome of a plugin UI call (specs/plugin-ui.md Section 5). */
102
+ export type UiReturnOutcome = { ok: true; json: string } | { ok: false; error: string };
103
+
97
104
  /** The tool functions of a run (Section 10.3). */
98
105
  export interface ScriptRunTools {
99
106
  /** Bound tool names, in declaration order. */
@@ -119,6 +126,8 @@ export interface ScriptRunResult {
119
126
  exitCode?: number;
120
127
  durationMs: number;
121
128
  error?: { name: string; message: string; stack: string };
129
+ /** Pre-validated return outcome of a plugin UI call (specs/plugin-ui.md Section 5). */
130
+ uiReturn?: UiReturnOutcome;
122
131
  }
123
132
 
124
133
  export interface ScriptRunHandle {
@@ -133,6 +142,18 @@ export interface ScriptRunHandle {
133
142
  stderrLine: (line: string) => boolean;
134
143
  }
135
144
 
145
+ /** Parse a worker's `uiReturn` payload without type assertions. */
146
+ function parseUiReturn(value: unknown): UiReturnOutcome | undefined {
147
+ if (!isPlainObject(value)) return undefined;
148
+ if (value.ok === true && typeof value.json === "string") {
149
+ return { ok: true, json: value.json };
150
+ }
151
+ if (value.ok === false && typeof value.error === "string") {
152
+ return { ok: false, error: value.error };
153
+ }
154
+ return undefined;
155
+ }
156
+
136
157
  /** Signal one spawned child by its process ID (Windows: its tree with taskkill /T /F). */
137
158
  function signalChild(pid: number, signal: NodeJS.Signals): void {
138
159
  if (process.platform === "win32") {
@@ -296,6 +317,7 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
296
317
  aliases: req.aliases,
297
318
  toolNames: req.tools?.names ?? [],
298
319
  toolTypes: req.tools?.declarations ?? toolDeclarations({ bound: [], unbound: [] }),
320
+ uiCall: req.uiCall === true,
299
321
  },
300
322
  env: workerEnv,
301
323
  });
@@ -335,6 +357,9 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
335
357
  case "tool-call":
336
358
  if (!settled) startNestedCall(msg.id, String(msg.name), msg.args);
337
359
  break;
360
+ case "ui-message":
361
+ if (!settled && typeof msg.json === "string") req.onUiMessage?.(msg.json);
362
+ break;
338
363
  case "exit-called":
339
364
  settle({ exitReason: "exit-called", exitCode: msg.code ?? 0 });
340
365
  break;
@@ -350,15 +375,18 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
350
375
  },
351
376
  });
352
377
  break;
353
- case "result":
378
+ case "result": {
379
+ const uiReturn = parseUiReturn(msg.uiReturn);
354
380
  settle({
355
381
  exitReason: "ok",
356
382
  returnValue: msg.returnValue,
357
383
  rendered: msg.rendered,
358
384
  render: msg.render,
359
385
  json: msg.json,
386
+ ...(uiReturn === undefined ? {} : { uiReturn }),
360
387
  });
361
388
  break;
389
+ }
362
390
  }
363
391
  });
364
392
 
@@ -30,6 +30,8 @@ interface ScriptWorkerData {
30
30
  toolNames: string[];
31
31
  /** The tool declarations (Section 10.2). */
32
32
  toolTypes: string;
33
+ /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
34
+ uiCall?: boolean;
33
35
  }
34
36
 
35
37
  const port = parentPort;
@@ -209,7 +211,41 @@ const toolFunction =
209
211
  const scriptTools: Record<string, unknown> = Object.freeze(
210
212
  Object.fromEntries(data.toolNames.map((name) => [name, toolFunction(name)])),
211
213
  );
212
- const scriptDent = Object.freeze({ toolTypes: (): string => data.toolTypes });
214
+ const UI_PAYLOAD_CAP_BYTES = 262_144;
215
+ const serializeUiJson = (value: unknown, label: string): string => {
216
+ if (!isJsonCompatible(value)) {
217
+ throw new Error(`${label} must be a JSON value`);
218
+ }
219
+ let json: string | undefined;
220
+ try {
221
+ json = JSON.stringify(value);
222
+ } catch {
223
+ throw new Error(`${label} must be a JSON value`);
224
+ }
225
+ if (typeof json !== "string") {
226
+ throw new Error(`${label} must be a JSON value`);
227
+ }
228
+ if (Buffer.byteLength(json, "utf8") > UI_PAYLOAD_CAP_BYTES) {
229
+ throw new Error(`${label} exceeds ${UI_PAYLOAD_CAP_BYTES} bytes`);
230
+ }
231
+ return json;
232
+ };
233
+ const sendUiMessage = (payload: unknown): void => {
234
+ const json = serializeUiJson(payload, "UI message data");
235
+ if (exitCalled) return;
236
+ try {
237
+ port.postMessage({ type: "ui-message", json });
238
+ } catch {
239
+ // Port closed.
240
+ }
241
+ };
242
+ const scriptDent =
243
+ data.uiCall === true
244
+ ? Object.freeze({
245
+ toolTypes: (): string => data.toolTypes,
246
+ ui: Object.freeze({ send: sendUiMessage }),
247
+ })
248
+ : Object.freeze({ toolTypes: (): string => data.toolTypes });
213
249
  Object.defineProperty(globalThis, "tools", {
214
250
  value: scriptTools,
215
251
  writable: true,
@@ -1057,6 +1093,31 @@ void (async () => {
1057
1093
  // A script that caught the exit's error reaches its own end; its run already
1058
1094
  // settled as exit-called, so there is no result to report.
1059
1095
  if (exitCalled) return;
1096
+ // Plugin UI calls classify the raw return value before structured cloning,
1097
+ // so non-cloneable values (functions, symbols) are never turned into strings
1098
+ // and `undefined` maps to `null` (specs/plugin-ui.md Section 5).
1099
+ if (data.uiCall === true) {
1100
+ const rawExported: unknown = mod?.default;
1101
+ let uiReturn: { ok: true; json: string } | { ok: false; error: string };
1102
+ if (rawExported === undefined) {
1103
+ uiReturn = { ok: true, json: "null" };
1104
+ } else {
1105
+ try {
1106
+ uiReturn = { ok: true, json: serializeUiJson(rawExported, "Return value") };
1107
+ } catch (err) {
1108
+ uiReturn = {
1109
+ ok: false,
1110
+ error: err instanceof Error ? err.message : String(err),
1111
+ };
1112
+ }
1113
+ }
1114
+ try {
1115
+ port.postMessage({ type: "result", uiReturn });
1116
+ } catch {
1117
+ // Port closed.
1118
+ }
1119
+ return;
1120
+ }
1060
1121
  // Section 4: a return value that cannot be structured-cloned degrades, without
1061
1122
  // failing the run, to the `<non-cloneable: <error>>` marker string. The check
1062
1123
  // happens here, where the original value still exists. A value that clones
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dent-agent",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
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",