pi-dent-agent 0.2.6 → 0.2.8

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
@@ -2,7 +2,12 @@
2
2
  * pi-dent - a generic coding agent, built as a pi extension.
3
3
  */
4
4
 
5
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import type {
6
+ ExtensionAPI,
7
+ ExtensionContext,
8
+ ToolDefinition,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import type { TSchema } from "typebox";
6
11
  import { highlightCode as hostHighlightCode } from "@earendil-works/pi-coding-agent";
7
12
  import {
8
13
  type BootSnapshot,
@@ -23,6 +28,13 @@ import { runFleetCommand } from "./lib/fleet-command.ts";
23
28
  import { recapRuntime } from "./lib/recap.ts";
24
29
  import { renderRecapEntry } from "./lib/recap-render.ts";
25
30
  import { appendPluginContext, renderPluginCommand } from "./lib/plugins.ts";
31
+ import {
32
+ asUiCallableTool,
33
+ makeUiToolContext,
34
+ PLUGIN_UI_EXCLUDED_TOOLS,
35
+ PluginUiController,
36
+ type UiCallableTool,
37
+ } from "./lib/plugin-ui.ts";
26
38
  import { type Diagnostic, errorMessage, isPlainObject } from "./lib/util.ts";
27
39
  import { rebuildInterruptedTasks } from "./lib/task-rebuild.ts";
28
40
  import {
@@ -258,6 +270,15 @@ export default function (pi: ExtensionAPI) {
258
270
  },
259
271
  );
260
272
  const cohorts = new CohortTracker();
273
+ const ownedUiTools = new Map<string, UiCallableTool>();
274
+ const registerOwnedTool = <TParams extends TSchema, TDetails = unknown>(
275
+ tool: ToolDefinition<TParams, TDetails>,
276
+ ): void => {
277
+ pi.registerTool(tool);
278
+ if (!PLUGIN_UI_EXCLUDED_TOOLS.has(tool.name)) {
279
+ ownedUiTools.set(tool.name, asUiCallableTool(tool));
280
+ }
281
+ };
261
282
  // The Agent tool is registered at load with an empty model catalog; session_start refreshes it.
262
283
  const agentTool = new AgentToolRegistry(
263
284
  {
@@ -269,7 +290,7 @@ export default function (pi: ExtensionAPI) {
269
290
  hostProvider: () => currentHost,
270
291
  cohortFor: (toolCallId) => cohorts.cohortFor(toolCallId),
271
292
  },
272
- (tool) => pi.registerTool(tool),
293
+ (tool) => registerOwnedTool(tool),
273
294
  );
274
295
  agentTool.refresh("");
275
296
  // Schedules live in the process, keyed by session ID, and survive a reload
@@ -282,6 +303,13 @@ export default function (pi: ExtensionAPI) {
282
303
  // Section 2).
283
304
  const questions = askUserRuntime();
284
305
  const recap = recapRuntime(boot.config, (data) => pi.appendEntry("pi-dent-recap", data));
306
+ const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
307
+ const pluginUi = new PluginUiController(boot.pluginIndex, {
308
+ ownedTools: () => [...ownedUiTools.values()],
309
+ allToolNames: () =>
310
+ typeof pi.getAllTools === "function" ? pi.getAllTools().map((t) => t.name) : [],
311
+ toolsAllow: () => scriptToolsAllow,
312
+ });
285
313
  let taskWidget: TaskWidgetHandle | undefined;
286
314
  // Feeds for an RPC client (task.md Section 4.1, fleet-tool.md Section 6).
287
315
  let taskFeed: FeedHandle | undefined;
@@ -688,6 +716,11 @@ export default function (pi: ExtensionAPI) {
688
716
  }
689
717
  shutdownStep("ending owned tasks", () => engine.registry.end(), reportShutdown);
690
718
  shutdownStep("cancelling owned task runs", () => engine.cancelAll(), reportShutdown);
719
+ shutdownStep(
720
+ "cancelling plugin UI calls",
721
+ () => pluginUi.cancelAll("Session ended"),
722
+ reportShutdown,
723
+ );
691
724
  // The Search tool's continuations of catch-up end with the boot window
692
725
  // (search-tool.md Section 2.2).
693
726
  shutdownStep("stopping Search", () => search.stop(), reportShutdown);
@@ -725,7 +758,6 @@ export default function (pi: ExtensionAPI) {
725
758
 
726
759
  // Task browser (task-browser.md): the shortcut opens the overlay; the overlay closes itself on it.
727
760
  const taskBrowserShortcut = parseTaskBrowser(boot.config).shortcut;
728
- const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
729
761
  const toggleTaskBrowser = async (ctx: ExtensionContext): Promise<void> => {
730
762
  if (closeTaskBrowser) {
731
763
  closeTaskBrowser();
@@ -809,16 +841,16 @@ export default function (pi: ExtensionAPI) {
809
841
  });
810
842
  },
811
843
  });
812
- pi.registerTool(makeTaskTool({ registry: () => engine.registry }));
813
- pi.registerTool(makePluginTool(boot));
814
- pi.registerTool(makeFleetTool({ fleet, hostProvider: () => currentHost }));
815
- pi.registerTool(
844
+ registerOwnedTool(makeTaskTool({ registry: () => engine.registry }));
845
+ registerOwnedTool(makePluginTool(boot));
846
+ registerOwnedTool(makeFleetTool({ fleet, hostProvider: () => currentHost }));
847
+ registerOwnedTool(
816
848
  makeSessionTool({ boot, hostProvider: () => currentHost, billing: guidanceCtl.billing }),
817
849
  );
818
850
  // The main session binds `Skill` and carries the skill catalog like any
819
851
  // child whose tool cap includes it (skill-tool.md Section 1). Plugin context
820
852
  // blocks follow the skill catalog on every turn (plugin.md Section 10).
821
- if (boot.skills.length > 0) pi.registerTool(makeSkillTool(boot));
853
+ if (boot.skills.length > 0) registerOwnedTool(makeSkillTool(boot));
822
854
  if (boot.skills.length > 0 || boot.plugins.some((plugin) => plugin.context !== undefined)) {
823
855
  pi.on("before_agent_start", async (event) => {
824
856
  const withSkills =
@@ -840,7 +872,7 @@ export default function (pi: ExtensionAPI) {
840
872
  toolsAllow: () => scriptToolsAllow,
841
873
  }),
842
874
  );
843
- pi.registerTool(
875
+ registerOwnedTool(
844
876
  makeBashTool({
845
877
  registry: () => engine.registry,
846
878
  hostProvider: () => currentHost,
@@ -853,13 +885,13 @@ export default function (pi: ExtensionAPI) {
853
885
  );
854
886
  // The main session schedules into itself; a child never binds Schedule
855
887
  // (agent-tool.md Section 3.1).
856
- pi.registerTool(makeScheduleTool(schedules));
888
+ registerOwnedTool(makeScheduleTool(schedules));
857
889
  // The main session asks the user; a child never binds AskUserQuestion
858
890
  // (agent-tool.md Section 3.1).
859
891
  pi.registerTool(makeAskUserQuestionTool(questions));
860
892
  // `Search` is registered for the main session, which reaches its own session
861
893
  // tree and, on request, its project (search-tool.md Section 1).
862
- pi.registerTool(
894
+ registerOwnedTool(
863
895
  makeSearchTool({
864
896
  runtime: search,
865
897
  host: (ctx) => {
@@ -872,7 +904,7 @@ export default function (pi: ExtensionAPI) {
872
904
  // `Markdown` reads and restructures one Markdown file by its headings
873
905
  // (pi-dent-markdown specs/markdown-tool.md Section 1); a child session binds it under the tool cap
874
906
  // (agent-tool.md Section 3.1).
875
- pi.registerTool(makeMarkdownTool(markdownRuntime()));
907
+ registerOwnedTool(makeMarkdownTool(markdownRuntime()));
876
908
 
877
909
  // Plugin slash commands (specs/plugin.md Section 5): one command per
878
910
  // commands/*.md resource of the first-admitted plugin per namespace,
@@ -899,6 +931,18 @@ export default function (pi: ExtensionAPI) {
899
931
  }
900
932
  }
901
933
 
934
+ pi.registerCommand("dent-ui", {
935
+ description: "Run and cancel plugin UI script calls",
936
+ handler: async (args, ctx) => {
937
+ if (ctx.mode !== "rpc") return;
938
+ pluginUi.handleCommand(args, {
939
+ cwd: ctx.cwd ?? currentHost?.cwd() ?? process.cwd(),
940
+ setWidget: (key, lines) => ctx.ui.setWidget(key, lines),
941
+ toolContext: makeUiToolContext(ctx),
942
+ });
943
+ },
944
+ });
945
+
902
946
  pi.registerCommand("dent", {
903
947
  description: "Confirm the pi-dent extension is loaded",
904
948
  handler: async (_args, ctx) => {
@@ -0,0 +1,441 @@
1
+ import { readFileSync } from "node:fs";
2
+ import type { Static, TSchema } from "typebox";
3
+ import { type JsonObject, type JsonValue, validateToolArguments } from "@earendil-works/pi-ai";
4
+ import type {
5
+ ExtensionContext,
6
+ ExtensionToolContext,
7
+ ToolDefinition,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { bundledAliases } from "./bundled.ts";
10
+ import type { PluginEntry } from "./plugins.ts";
11
+ import { resolvePluginScriptPath } from "./plugins.ts";
12
+ import {
13
+ runScript,
14
+ type ScriptRunHandle,
15
+ type ScriptRunResult,
16
+ type ScriptRunTools,
17
+ } from "./script-runner.ts";
18
+ import { callBoundTool, type NestedCallOutcome } from "./script-tool-calls.ts";
19
+ import {
20
+ type CallableTool,
21
+ DEFAULT_TOOLS_ALLOW,
22
+ selectTools,
23
+ toolDeclarations,
24
+ } from "./script-tool-types.ts";
25
+ import { errorCode, errorMessage, isPlainObject } from "./util.ts";
26
+
27
+ /**
28
+ * Plugin UI protocol controller (specs/plugin-ui.md): handles `/dent-ui run`
29
+ * and `/dent-ui cancel`, executes plugin scripts with `dent.ui.send`, pi-dent's
30
+ * own tools, and no time limit, and emits `message` and `reply` records on the
31
+ * `pi-dent-ui` widget feed.
32
+ */
33
+
34
+ export const PLUGIN_UI_WIDGET_KEY = "pi-dent-ui";
35
+ export const PLUGIN_UI_PROTOCOL = "ui/1";
36
+ export const PLUGIN_UI_PAYLOAD_CAP_BYTES = 262_144;
37
+
38
+ /** Tools pi-dent registers that are never callable from a plugin UI call (Section 4.2). */
39
+ export const PLUGIN_UI_EXCLUDED_TOOLS: ReadonlySet<string> = new Set(["Script", "AskUserQuestion"]);
40
+
41
+ /** One pi-dent tool adapted for execution from a plugin UI call (Section 4.2). */
42
+ export interface UiCallableTool extends CallableTool {
43
+ execute(
44
+ toolCallId: string,
45
+ params: unknown,
46
+ signal: AbortSignal | undefined,
47
+ ctx: ExtensionToolContext | undefined,
48
+ ): Promise<NestedCallOutcome>;
49
+ }
50
+
51
+ function toJsonValue(value: unknown): JsonValue | undefined {
52
+ if (value === null || typeof value === "boolean" || typeof value === "string") return value;
53
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
54
+ if (Array.isArray(value)) {
55
+ const out: JsonValue[] = [];
56
+ for (const item of value) {
57
+ const converted = toJsonValue(item);
58
+ if (converted === undefined) return undefined;
59
+ out.push(converted);
60
+ }
61
+ return out;
62
+ }
63
+ if (isPlainObject(value)) {
64
+ const out: JsonObject = {};
65
+ for (const [k, v] of Object.entries(value)) {
66
+ const converted = toJsonValue(v);
67
+ if (converted === undefined) return undefined;
68
+ out[k] = converted;
69
+ }
70
+ return out;
71
+ }
72
+ return undefined;
73
+ }
74
+
75
+ function toJsonObject(value: unknown): JsonObject {
76
+ if (!isPlainObject(value)) return {};
77
+ const converted = toJsonValue(value);
78
+ return converted !== undefined && isPlainObject(converted) ? converted : {};
79
+ }
80
+
81
+ /**
82
+ * Adapt a pi `ToolDefinition` for direct execution from a plugin UI call:
83
+ * validates arguments with pi's `validateToolArguments` and normalises the
84
+ * returned `AgentToolResult` into a `NestedCallOutcome`.
85
+ */
86
+ export function asUiCallableTool<TParams extends TSchema, TDetails = unknown>(
87
+ tool: ToolDefinition<TParams, TDetails>,
88
+ ): UiCallableTool {
89
+ return {
90
+ name: tool.name,
91
+ description: tool.description,
92
+ parameters: tool.parameters,
93
+ ...(tool.outputSchema === undefined ? {} : { outputSchema: tool.outputSchema }),
94
+ async execute(toolCallId, params, signal, ctx) {
95
+ const raw = isPlainObject(params) ? params : {};
96
+ const prepared = tool.prepareArguments ? tool.prepareArguments(raw) : raw;
97
+ const validated: Static<TParams> = validateToolArguments(
98
+ { name: tool.name, description: tool.description, parameters: tool.parameters },
99
+ { type: "toolCall", id: toolCallId, name: tool.name, arguments: toJsonObject(prepared) },
100
+ );
101
+ if (ctx === undefined) {
102
+ return {
103
+ result: {
104
+ content: [{ type: "text", text: "No host context available for tool call" }],
105
+ },
106
+ isError: true,
107
+ };
108
+ }
109
+ const result = await tool.execute(toolCallId, validated, signal, undefined, ctx);
110
+ const structured = "structuredContent" in result ? result.structuredContent : undefined;
111
+ return {
112
+ result: {
113
+ content: result.content,
114
+ details: result.details,
115
+ ...(structured === undefined ? {} : { structuredContent: structured }),
116
+ },
117
+ isError: "isError" in result && result.isError === true,
118
+ };
119
+ },
120
+ };
121
+ }
122
+
123
+ /** Build an `ExtensionToolContext` from a command/session `ExtensionContext`. */
124
+ export function makeUiToolContext(ctx: ExtensionContext): ExtensionToolContext {
125
+ return {
126
+ ui: ctx.ui,
127
+ mode: ctx.mode,
128
+ hasUI: ctx.hasUI,
129
+ cwd: ctx.cwd,
130
+ sessionManager: ctx.sessionManager,
131
+ modelRegistry: ctx.modelRegistry,
132
+ model: ctx.model,
133
+ scopedModels: ctx.scopedModels,
134
+ ...(ctx.thinkingLevel === undefined ? {} : { thinkingLevel: ctx.thinkingLevel }),
135
+ isIdle: () => ctx.isIdle(),
136
+ isProjectTrusted: () => ctx.isProjectTrusted(),
137
+ signal: ctx.signal,
138
+ abort: () => ctx.abort(),
139
+ hasPendingMessages: () => ctx.hasPendingMessages(),
140
+ shutdown: () => ctx.shutdown(),
141
+ getContextUsage: () => ctx.getContextUsage(),
142
+ compact: (options) => ctx.compact(options),
143
+ getSystemPrompt: () => ctx.getSystemPrompt(),
144
+ tools: [],
145
+ executeTool: async (name) => ({
146
+ toolCall: { type: "toolCall", id: "ui:unsupported", name, arguments: {} },
147
+ result: {
148
+ content: [
149
+ { type: "text", text: "Nested tool calls are not available in a plugin UI call" },
150
+ ],
151
+ details: {},
152
+ },
153
+ isError: true,
154
+ }),
155
+ };
156
+ }
157
+
158
+ export interface PluginUiToolDeps {
159
+ /** pi-dent's own registered tools eligible for UI calls. */
160
+ ownedTools: () => readonly UiCallableTool[];
161
+ /** Names of all tools configured in the session (from `pi.getAllTools()`). */
162
+ allToolNames?: () => readonly string[];
163
+ /** `script.tools.allow` (specs/script-tool.md Section 8); absent gives the default. */
164
+ toolsAllow?: () => readonly string[];
165
+ }
166
+
167
+ export interface PluginUiCommandContext {
168
+ cwd: string;
169
+ setWidget(key: string, lines: string[] | undefined): void;
170
+ toolContext?: ExtensionToolContext;
171
+ extraEnv?: Record<string, string>;
172
+ }
173
+
174
+ interface ActiveUiCall {
175
+ handle: ScriptRunHandle;
176
+ cancelReason?: string;
177
+ }
178
+
179
+ function formatThrownError(
180
+ error: { name: string; message: string; stack: string } | undefined,
181
+ ): string {
182
+ if (!error) return "Script threw an error";
183
+ return error.message === "" ? error.name : `${error.name}: ${error.message}`;
184
+ }
185
+
186
+ export class PluginUiController {
187
+ private readonly pluginIndex: ReadonlyMap<string, PluginEntry>;
188
+ private readonly toolDeps: PluginUiToolDeps | undefined;
189
+ private readonly active = new Map<string, ActiveUiCall>();
190
+
191
+ constructor(pluginIndex: ReadonlyMap<string, PluginEntry>, toolDeps?: PluginUiToolDeps) {
192
+ this.pluginIndex = pluginIndex;
193
+ this.toolDeps = toolDeps;
194
+ }
195
+
196
+ /** Number of UI calls currently executing. */
197
+ activeCount(): number {
198
+ return this.active.size;
199
+ }
200
+
201
+ /** Handle one `/dent-ui <args>` command (specs/plugin-ui.md Sections 1-3). */
202
+ handleCommand(args: string, ctx: PluginUiCommandContext): void {
203
+ const trimmed = args.trim();
204
+ if (trimmed === "") return;
205
+ const space = trimmed.search(/\s/);
206
+ const subcommand = space === -1 ? trimmed : trimmed.slice(0, space);
207
+ const payload = space === -1 ? "" : trimmed.slice(space).trim();
208
+ if (subcommand === "run") {
209
+ this.handleRun(payload, ctx);
210
+ } else if (subcommand === "cancel") {
211
+ this.handleCancel(payload);
212
+ }
213
+ }
214
+
215
+ /** Cancel every executing UI call (specs/plugin-ui.md Section 6). */
216
+ cancelAll(reason = "Session ended"): void {
217
+ for (const entry of this.active.values()) {
218
+ entry.cancelReason = reason;
219
+ entry.handle.cancel("killed");
220
+ }
221
+ }
222
+
223
+ private buildRunTools(id: string, ctx: PluginUiCommandContext): ScriptRunTools | undefined {
224
+ if (!this.toolDeps) return undefined;
225
+ const eligible = this.toolDeps
226
+ .ownedTools()
227
+ .filter((tool) => !PLUGIN_UI_EXCLUDED_TOOLS.has(tool.name));
228
+ const allow = this.toolDeps.toolsAllow?.() ?? DEFAULT_TOOLS_ALLOW;
229
+ const selection = selectTools(eligible, allow);
230
+ const boundNames = selection.bound.map((tool) => tool.name);
231
+ const boundSet = new Set(boundNames);
232
+ const sessionNames = this.toolDeps.allToolNames?.() ?? [];
233
+ const unavailableSet = new Set<string>();
234
+ for (const name of sessionNames) {
235
+ if (!boundSet.has(name)) unavailableSet.add(name);
236
+ }
237
+ for (const tool of this.toolDeps.ownedTools()) {
238
+ if (!boundSet.has(tool.name)) unavailableSet.add(tool.name);
239
+ }
240
+ const unavailableNames = [...unavailableSet].toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0));
241
+ let callSeq = 0;
242
+ return {
243
+ names: boundNames,
244
+ unavailableNames,
245
+ declarations: toolDeclarations({ bound: selection.bound, unbound: [] }),
246
+ call: async (name, args, callSignal) => {
247
+ const tool = selection.bound.find((candidate) => candidate.name === name);
248
+ if (tool === undefined) {
249
+ return {
250
+ ok: false,
251
+ error: { name: "Error", message: `tool ${name} is unavailable in a plugin UI call` },
252
+ };
253
+ }
254
+ const toolCallId = `ui:${id}/${++callSeq}`;
255
+ return callBoundTool(
256
+ tool,
257
+ args,
258
+ async (_toolName, toolArgs, options) => {
259
+ try {
260
+ return await tool.execute(toolCallId, toolArgs, options.signal, ctx.toolContext);
261
+ } catch (error) {
262
+ return {
263
+ result: { content: [{ type: "text", text: errorMessage(error) }] },
264
+ isError: true,
265
+ };
266
+ }
267
+ },
268
+ callSignal,
269
+ );
270
+ },
271
+ };
272
+ }
273
+
274
+ private handleRun(rawJson: string, ctx: PluginUiCommandContext): void {
275
+ let parsed: unknown;
276
+ try {
277
+ parsed = JSON.parse(rawJson);
278
+ } catch {
279
+ return;
280
+ }
281
+ if (!isPlainObject(parsed) || typeof parsed.id !== "string" || parsed.id === "") {
282
+ return;
283
+ }
284
+ const id = parsed.id;
285
+ const emitLine = (line: string): void => {
286
+ try {
287
+ ctx.setWidget(PLUGIN_UI_WIDGET_KEY, [line]);
288
+ } catch {
289
+ // Widget update failures are unreported per specs/AGENTS.md.
290
+ }
291
+ };
292
+ const emitMessageJson = (dataJson: string): void => {
293
+ emitLine(
294
+ `{"piDent":${JSON.stringify(PLUGIN_UI_PROTOCOL)},"type":"message","id":${JSON.stringify(id)},"data":${dataJson}}`,
295
+ );
296
+ };
297
+ const emitReplyOkJson = (valueJson: string): void => {
298
+ emitLine(
299
+ `{"piDent":${JSON.stringify(PLUGIN_UI_PROTOCOL)},"type":"reply","id":${JSON.stringify(id)},"ok":true,"value":${valueJson}}`,
300
+ );
301
+ };
302
+ const emitReplyError = (error: string): void => {
303
+ emitLine(
304
+ JSON.stringify({
305
+ piDent: PLUGIN_UI_PROTOCOL,
306
+ type: "reply",
307
+ id,
308
+ ok: false,
309
+ error,
310
+ }),
311
+ );
312
+ };
313
+
314
+ if (this.active.has(id)) {
315
+ emitReplyError(`UI call "${id}" is already running`);
316
+ return;
317
+ }
318
+ if (typeof parsed.namespace !== "string" || parsed.namespace === "") {
319
+ emitReplyError("Invalid plugin namespace");
320
+ return;
321
+ }
322
+ const plugin = this.pluginIndex.get(parsed.namespace);
323
+ if (!plugin) {
324
+ emitReplyError(`Unknown plugin "${parsed.namespace}"`);
325
+ return;
326
+ }
327
+ if (typeof parsed.root !== "string" || parsed.root !== plugin.root) {
328
+ emitReplyError(`Plugin "${parsed.namespace}" root mismatch`);
329
+ return;
330
+ }
331
+ if (typeof parsed.path !== "string" || parsed.path.trim() === "") {
332
+ emitReplyError("Invalid script path");
333
+ return;
334
+ }
335
+ const resolved = resolvePluginScriptPath(plugin.root, parsed.path);
336
+ if ("error" in resolved) {
337
+ emitReplyError(`plugin "${parsed.namespace}": ${resolved.error}`);
338
+ return;
339
+ }
340
+ let code: string;
341
+ try {
342
+ code = readFileSync(resolved.path, "utf8");
343
+ } catch (error) {
344
+ const codeName = errorCode(error);
345
+ emitReplyError(
346
+ codeName === "ENOENT"
347
+ ? `plugin "${parsed.namespace}": missing script ${resolved.path}`
348
+ : `plugin "${parsed.namespace}": failed to read ${resolved.path}: ${codeName ?? errorMessage(error)}`,
349
+ );
350
+ return;
351
+ }
352
+
353
+ const data = parsed.data === undefined ? null : parsed.data;
354
+ const tools = this.buildRunTools(id, ctx);
355
+ let handle: ScriptRunHandle;
356
+ try {
357
+ handle = runScript({
358
+ code,
359
+ filename: resolved.path,
360
+ cwd: ctx.cwd,
361
+ input: { ui: data },
362
+ aliases: bundledAliases(),
363
+ uiCall: true,
364
+ ...(tools === undefined ? {} : { tools }),
365
+ ...(ctx.extraEnv && Object.keys(ctx.extraEnv).length > 0 ? { extraEnv: ctx.extraEnv } : {}),
366
+ onUiMessage: (dataJson) => {
367
+ emitMessageJson(dataJson);
368
+ },
369
+ });
370
+ } catch (error) {
371
+ emitReplyError(`Failed to start script: ${errorMessage(error)}`);
372
+ return;
373
+ }
374
+
375
+ const entry: ActiveUiCall = { handle };
376
+ this.active.set(id, entry);
377
+
378
+ void handle.promise
379
+ .then((result) => {
380
+ this.active.delete(id);
381
+ this.emitSettlementReply(result, entry, emitReplyOkJson, emitReplyError);
382
+ })
383
+ .catch((error: unknown) => {
384
+ this.active.delete(id);
385
+ emitReplyError(errorMessage(error));
386
+ });
387
+ }
388
+
389
+ private emitSettlementReply(
390
+ result: ScriptRunResult,
391
+ entry: ActiveUiCall,
392
+ emitOkJson: (valueJson: string) => void,
393
+ emitError: (error: string) => void,
394
+ ): void {
395
+ switch (result.exitReason) {
396
+ case "ok":
397
+ if (result.uiReturn?.ok === true) {
398
+ emitOkJson(result.uiReturn.json);
399
+ } else if (result.uiReturn?.ok === false) {
400
+ emitError(result.uiReturn.error);
401
+ } else {
402
+ emitOkJson("null");
403
+ }
404
+ return;
405
+ case "exit-called":
406
+ if ((result.exitCode ?? 0) === 0) {
407
+ emitOkJson("null");
408
+ } else {
409
+ emitError(`Script exited with code ${result.exitCode}`);
410
+ }
411
+ return;
412
+ case "threw":
413
+ emitError(formatThrownError(result.error));
414
+ return;
415
+ case "killed":
416
+ case "aborted":
417
+ emitError(entry.cancelReason ?? "UI call was cancelled");
418
+ return;
419
+ case "timeout":
420
+ emitError("UI call timed out");
421
+ return;
422
+ }
423
+ }
424
+
425
+ private handleCancel(rawJson: string): void {
426
+ let parsed: unknown;
427
+ try {
428
+ parsed = JSON.parse(rawJson);
429
+ } catch {
430
+ return;
431
+ }
432
+ if (!isPlainObject(parsed) || !Array.isArray(parsed.ids)) return;
433
+ for (const id of parsed.ids) {
434
+ if (typeof id !== "string") continue;
435
+ const entry = this.active.get(id);
436
+ if (!entry) continue;
437
+ entry.cancelReason = "UI call was cancelled";
438
+ entry.handle.cancel("killed");
439
+ }
440
+ }
441
+ }
@@ -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,12 +92,21 @@ 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. */
100
107
  names: string[];
108
+ /** Session tool names bound as rejecting stubs (specs/plugin-ui.md Section 4.2). */
109
+ unavailableNames?: string[];
101
110
  /** The tool declarations (Section 10.2), returned by `dent.toolTypes()`. */
102
111
  declarations: string;
103
112
  /** Runs one nested call; the signal aborts at settlement. */
@@ -119,6 +128,8 @@ export interface ScriptRunResult {
119
128
  exitCode?: number;
120
129
  durationMs: number;
121
130
  error?: { name: string; message: string; stack: string };
131
+ /** Pre-validated return outcome of a plugin UI call (specs/plugin-ui.md Section 5). */
132
+ uiReturn?: UiReturnOutcome;
122
133
  }
123
134
 
124
135
  export interface ScriptRunHandle {
@@ -133,6 +144,18 @@ export interface ScriptRunHandle {
133
144
  stderrLine: (line: string) => boolean;
134
145
  }
135
146
 
147
+ /** Parse a worker's `uiReturn` payload without type assertions. */
148
+ function parseUiReturn(value: unknown): UiReturnOutcome | undefined {
149
+ if (!isPlainObject(value)) return undefined;
150
+ if (value.ok === true && typeof value.json === "string") {
151
+ return { ok: true, json: value.json };
152
+ }
153
+ if (value.ok === false && typeof value.error === "string") {
154
+ return { ok: false, error: value.error };
155
+ }
156
+ return undefined;
157
+ }
158
+
136
159
  /** Signal one spawned child by its process ID (Windows: its tree with taskkill /T /F). */
137
160
  function signalChild(pid: number, signal: NodeJS.Signals): void {
138
161
  if (process.platform === "win32") {
@@ -295,7 +318,9 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
295
318
  input: req.input,
296
319
  aliases: req.aliases,
297
320
  toolNames: req.tools?.names ?? [],
321
+ unavailableToolNames: req.tools?.unavailableNames ?? [],
298
322
  toolTypes: req.tools?.declarations ?? toolDeclarations({ bound: [], unbound: [] }),
323
+ uiCall: req.uiCall === true,
299
324
  },
300
325
  env: workerEnv,
301
326
  });
@@ -335,6 +360,9 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
335
360
  case "tool-call":
336
361
  if (!settled) startNestedCall(msg.id, String(msg.name), msg.args);
337
362
  break;
363
+ case "ui-message":
364
+ if (!settled && typeof msg.json === "string") req.onUiMessage?.(msg.json);
365
+ break;
338
366
  case "exit-called":
339
367
  settle({ exitReason: "exit-called", exitCode: msg.code ?? 0 });
340
368
  break;
@@ -350,15 +378,18 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
350
378
  },
351
379
  });
352
380
  break;
353
- case "result":
381
+ case "result": {
382
+ const uiReturn = parseUiReturn(msg.uiReturn);
354
383
  settle({
355
384
  exitReason: "ok",
356
385
  returnValue: msg.returnValue,
357
386
  rendered: msg.rendered,
358
387
  render: msg.render,
359
388
  json: msg.json,
389
+ ...(uiReturn === undefined ? {} : { uiReturn }),
360
390
  });
361
391
  break;
392
+ }
362
393
  }
363
394
  });
364
395
 
@@ -28,8 +28,12 @@ interface ScriptWorkerData {
28
28
  aliases: Record<string, string>;
29
29
  /** Bound tool names, in declaration order (Section 10.3). */
30
30
  toolNames: string[];
31
+ /** Session tool names unavailable in a plugin UI call (specs/plugin-ui.md Section 4.2). */
32
+ unavailableToolNames?: string[];
31
33
  /** The tool declarations (Section 10.2). */
32
34
  toolTypes: string;
35
+ /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
36
+ uiCall?: boolean;
33
37
  }
34
38
 
35
39
  const port = parentPort;
@@ -206,10 +210,53 @@ const toolFunction =
206
210
  });
207
211
  };
208
212
 
213
+ const unavailableToolFunction = (name: string) => (): Promise<never> =>
214
+ Promise.reject(new Error(`tool ${name} is unavailable in a plugin UI call`));
215
+
216
+ const boundToolNameSet = new Set(data.toolNames);
209
217
  const scriptTools: Record<string, unknown> = Object.freeze(
210
- Object.fromEntries(data.toolNames.map((name) => [name, toolFunction(name)])),
218
+ Object.fromEntries([
219
+ ...data.toolNames.map((name) => [name, toolFunction(name)]),
220
+ ...(data.unavailableToolNames ?? [])
221
+ .filter((name) => !boundToolNameSet.has(name))
222
+ .map((name) => [name, unavailableToolFunction(name)]),
223
+ ]),
211
224
  );
212
- const scriptDent = Object.freeze({ toolTypes: (): string => data.toolTypes });
225
+ const UI_PAYLOAD_CAP_BYTES = 262_144;
226
+ const serializeUiJson = (value: unknown, label: string): string => {
227
+ if (!isJsonCompatible(value)) {
228
+ throw new Error(`${label} must be a JSON value`);
229
+ }
230
+ let json: string | undefined;
231
+ try {
232
+ json = JSON.stringify(value);
233
+ } catch {
234
+ throw new Error(`${label} must be a JSON value`);
235
+ }
236
+ if (typeof json !== "string") {
237
+ throw new Error(`${label} must be a JSON value`);
238
+ }
239
+ if (Buffer.byteLength(json, "utf8") > UI_PAYLOAD_CAP_BYTES) {
240
+ throw new Error(`${label} exceeds ${UI_PAYLOAD_CAP_BYTES} bytes`);
241
+ }
242
+ return json;
243
+ };
244
+ const sendUiMessage = (payload: unknown): void => {
245
+ const json = serializeUiJson(payload, "UI message data");
246
+ if (exitCalled) return;
247
+ try {
248
+ port.postMessage({ type: "ui-message", json });
249
+ } catch {
250
+ // Port closed.
251
+ }
252
+ };
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 });
213
260
  Object.defineProperty(globalThis, "tools", {
214
261
  value: scriptTools,
215
262
  writable: true,
@@ -1057,6 +1104,31 @@ void (async () => {
1057
1104
  // A script that caught the exit's error reaches its own end; its run already
1058
1105
  // settled as exit-called, so there is no result to report.
1059
1106
  if (exitCalled) return;
1107
+ // Plugin UI calls classify the raw return value before structured cloning,
1108
+ // so non-cloneable values (functions, symbols) are never turned into strings
1109
+ // and `undefined` maps to `null` (specs/plugin-ui.md Section 5).
1110
+ if (data.uiCall === true) {
1111
+ const rawExported: unknown = mod?.default;
1112
+ let uiReturn: { ok: true; json: string } | { ok: false; error: string };
1113
+ if (rawExported === undefined) {
1114
+ uiReturn = { ok: true, json: "null" };
1115
+ } else {
1116
+ try {
1117
+ uiReturn = { ok: true, json: serializeUiJson(rawExported, "Return value") };
1118
+ } catch (err) {
1119
+ uiReturn = {
1120
+ ok: false,
1121
+ error: err instanceof Error ? err.message : String(err),
1122
+ };
1123
+ }
1124
+ }
1125
+ try {
1126
+ port.postMessage({ type: "result", uiReturn });
1127
+ } catch {
1128
+ // Port closed.
1129
+ }
1130
+ return;
1131
+ }
1060
1132
  // Section 4: a return value that cannot be structured-cloned degrades, without
1061
1133
  // failing the run, to the `<non-cloneable: <error>>` marker string. The check
1062
1134
  // 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.8",
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",