pi-dent-agent 0.2.7 → 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,7 +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";
26
- import { PluginUiController } from "./lib/plugin-ui.ts";
31
+ import {
32
+ asUiCallableTool,
33
+ makeUiToolContext,
34
+ PLUGIN_UI_EXCLUDED_TOOLS,
35
+ PluginUiController,
36
+ type UiCallableTool,
37
+ } from "./lib/plugin-ui.ts";
27
38
  import { type Diagnostic, errorMessage, isPlainObject } from "./lib/util.ts";
28
39
  import { rebuildInterruptedTasks } from "./lib/task-rebuild.ts";
29
40
  import {
@@ -259,6 +270,15 @@ export default function (pi: ExtensionAPI) {
259
270
  },
260
271
  );
261
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
+ };
262
282
  // The Agent tool is registered at load with an empty model catalog; session_start refreshes it.
263
283
  const agentTool = new AgentToolRegistry(
264
284
  {
@@ -270,7 +290,7 @@ export default function (pi: ExtensionAPI) {
270
290
  hostProvider: () => currentHost,
271
291
  cohortFor: (toolCallId) => cohorts.cohortFor(toolCallId),
272
292
  },
273
- (tool) => pi.registerTool(tool),
293
+ (tool) => registerOwnedTool(tool),
274
294
  );
275
295
  agentTool.refresh("");
276
296
  // Schedules live in the process, keyed by session ID, and survive a reload
@@ -283,7 +303,13 @@ export default function (pi: ExtensionAPI) {
283
303
  // Section 2).
284
304
  const questions = askUserRuntime();
285
305
  const recap = recapRuntime(boot.config, (data) => pi.appendEntry("pi-dent-recap", data));
286
- const pluginUi = new PluginUiController(boot.pluginIndex);
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
+ });
287
313
  let taskWidget: TaskWidgetHandle | undefined;
288
314
  // Feeds for an RPC client (task.md Section 4.1, fleet-tool.md Section 6).
289
315
  let taskFeed: FeedHandle | undefined;
@@ -732,7 +758,6 @@ export default function (pi: ExtensionAPI) {
732
758
 
733
759
  // Task browser (task-browser.md): the shortcut opens the overlay; the overlay closes itself on it.
734
760
  const taskBrowserShortcut = parseTaskBrowser(boot.config).shortcut;
735
- const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
736
761
  const toggleTaskBrowser = async (ctx: ExtensionContext): Promise<void> => {
737
762
  if (closeTaskBrowser) {
738
763
  closeTaskBrowser();
@@ -816,16 +841,16 @@ export default function (pi: ExtensionAPI) {
816
841
  });
817
842
  },
818
843
  });
819
- pi.registerTool(makeTaskTool({ registry: () => engine.registry }));
820
- pi.registerTool(makePluginTool(boot));
821
- pi.registerTool(makeFleetTool({ fleet, hostProvider: () => currentHost }));
822
- pi.registerTool(
844
+ registerOwnedTool(makeTaskTool({ registry: () => engine.registry }));
845
+ registerOwnedTool(makePluginTool(boot));
846
+ registerOwnedTool(makeFleetTool({ fleet, hostProvider: () => currentHost }));
847
+ registerOwnedTool(
823
848
  makeSessionTool({ boot, hostProvider: () => currentHost, billing: guidanceCtl.billing }),
824
849
  );
825
850
  // The main session binds `Skill` and carries the skill catalog like any
826
851
  // child whose tool cap includes it (skill-tool.md Section 1). Plugin context
827
852
  // blocks follow the skill catalog on every turn (plugin.md Section 10).
828
- if (boot.skills.length > 0) pi.registerTool(makeSkillTool(boot));
853
+ if (boot.skills.length > 0) registerOwnedTool(makeSkillTool(boot));
829
854
  if (boot.skills.length > 0 || boot.plugins.some((plugin) => plugin.context !== undefined)) {
830
855
  pi.on("before_agent_start", async (event) => {
831
856
  const withSkills =
@@ -847,7 +872,7 @@ export default function (pi: ExtensionAPI) {
847
872
  toolsAllow: () => scriptToolsAllow,
848
873
  }),
849
874
  );
850
- pi.registerTool(
875
+ registerOwnedTool(
851
876
  makeBashTool({
852
877
  registry: () => engine.registry,
853
878
  hostProvider: () => currentHost,
@@ -860,13 +885,13 @@ export default function (pi: ExtensionAPI) {
860
885
  );
861
886
  // The main session schedules into itself; a child never binds Schedule
862
887
  // (agent-tool.md Section 3.1).
863
- pi.registerTool(makeScheduleTool(schedules));
888
+ registerOwnedTool(makeScheduleTool(schedules));
864
889
  // The main session asks the user; a child never binds AskUserQuestion
865
890
  // (agent-tool.md Section 3.1).
866
891
  pi.registerTool(makeAskUserQuestionTool(questions));
867
892
  // `Search` is registered for the main session, which reaches its own session
868
893
  // tree and, on request, its project (search-tool.md Section 1).
869
- pi.registerTool(
894
+ registerOwnedTool(
870
895
  makeSearchTool({
871
896
  runtime: search,
872
897
  host: (ctx) => {
@@ -879,7 +904,7 @@ export default function (pi: ExtensionAPI) {
879
904
  // `Markdown` reads and restructures one Markdown file by its headings
880
905
  // (pi-dent-markdown specs/markdown-tool.md Section 1); a child session binds it under the tool cap
881
906
  // (agent-tool.md Section 3.1).
882
- pi.registerTool(makeMarkdownTool(markdownRuntime()));
907
+ registerOwnedTool(makeMarkdownTool(markdownRuntime()));
883
908
 
884
909
  // Plugin slash commands (specs/plugin.md Section 5): one command per
885
910
  // commands/*.md resource of the first-admitted plugin per namespace,
@@ -913,6 +938,7 @@ export default function (pi: ExtensionAPI) {
913
938
  pluginUi.handleCommand(args, {
914
939
  cwd: ctx.cwd ?? currentHost?.cwd() ?? process.cwd(),
915
940
  setWidget: (key, lines) => ctx.ui.setWidget(key, lines),
941
+ toolContext: makeUiToolContext(ctx),
916
942
  });
917
943
  },
918
944
  });
package/lib/plugin-ui.ts CHANGED
@@ -1,14 +1,33 @@
1
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";
2
9
  import { bundledAliases } from "./bundled.ts";
3
10
  import type { PluginEntry } from "./plugins.ts";
4
11
  import { resolvePluginScriptPath } from "./plugins.ts";
5
- import { runScript, type ScriptRunHandle, type ScriptRunResult } from "./script-runner.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";
6
25
  import { errorCode, errorMessage, isPlainObject } from "./util.ts";
7
26
 
8
27
  /**
9
28
  * 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
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
12
31
  * `pi-dent-ui` widget feed.
13
32
  */
14
33
 
@@ -16,9 +35,139 @@ export const PLUGIN_UI_WIDGET_KEY = "pi-dent-ui";
16
35
  export const PLUGIN_UI_PROTOCOL = "ui/1";
17
36
  export const PLUGIN_UI_PAYLOAD_CAP_BYTES = 262_144;
18
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
+
19
167
  export interface PluginUiCommandContext {
20
168
  cwd: string;
21
169
  setWidget(key: string, lines: string[] | undefined): void;
170
+ toolContext?: ExtensionToolContext;
22
171
  extraEnv?: Record<string, string>;
23
172
  }
24
173
 
@@ -36,10 +185,12 @@ function formatThrownError(
36
185
 
37
186
  export class PluginUiController {
38
187
  private readonly pluginIndex: ReadonlyMap<string, PluginEntry>;
188
+ private readonly toolDeps: PluginUiToolDeps | undefined;
39
189
  private readonly active = new Map<string, ActiveUiCall>();
40
190
 
41
- constructor(pluginIndex: ReadonlyMap<string, PluginEntry>) {
191
+ constructor(pluginIndex: ReadonlyMap<string, PluginEntry>, toolDeps?: PluginUiToolDeps) {
42
192
  this.pluginIndex = pluginIndex;
193
+ this.toolDeps = toolDeps;
43
194
  }
44
195
 
45
196
  /** Number of UI calls currently executing. */
@@ -69,6 +220,57 @@ export class PluginUiController {
69
220
  }
70
221
  }
71
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
+
72
274
  private handleRun(rawJson: string, ctx: PluginUiCommandContext): void {
73
275
  let parsed: unknown;
74
276
  try {
@@ -149,6 +351,7 @@ export class PluginUiController {
149
351
  }
150
352
 
151
353
  const data = parsed.data === undefined ? null : parsed.data;
354
+ const tools = this.buildRunTools(id, ctx);
152
355
  let handle: ScriptRunHandle;
153
356
  try {
154
357
  handle = runScript({
@@ -158,6 +361,7 @@ export class PluginUiController {
158
361
  input: { ui: data },
159
362
  aliases: bundledAliases(),
160
363
  uiCall: true,
364
+ ...(tools === undefined ? {} : { tools }),
161
365
  ...(ctx.extraEnv && Object.keys(ctx.extraEnv).length > 0 ? { extraEnv: ctx.extraEnv } : {}),
162
366
  onUiMessage: (dataJson) => {
163
367
  emitMessageJson(dataJson);
@@ -105,6 +105,8 @@ export type UiReturnOutcome = { ok: true; json: string } | { ok: false; error: s
105
105
  export interface ScriptRunTools {
106
106
  /** Bound tool names, in declaration order. */
107
107
  names: string[];
108
+ /** Session tool names bound as rejecting stubs (specs/plugin-ui.md Section 4.2). */
109
+ unavailableNames?: string[];
108
110
  /** The tool declarations (Section 10.2), returned by `dent.toolTypes()`. */
109
111
  declarations: string;
110
112
  /** Runs one nested call; the signal aborts at settlement. */
@@ -316,6 +318,7 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
316
318
  input: req.input,
317
319
  aliases: req.aliases,
318
320
  toolNames: req.tools?.names ?? [],
321
+ unavailableToolNames: req.tools?.unavailableNames ?? [],
319
322
  toolTypes: req.tools?.declarations ?? toolDeclarations({ bound: [], unbound: [] }),
320
323
  uiCall: req.uiCall === true,
321
324
  },
@@ -28,6 +28,8 @@ 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;
33
35
  /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
@@ -208,8 +210,17 @@ const toolFunction =
208
210
  });
209
211
  };
210
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);
211
217
  const scriptTools: Record<string, unknown> = Object.freeze(
212
- 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
+ ]),
213
224
  );
214
225
  const UI_PAYLOAD_CAP_BYTES = 262_144;
215
226
  const serializeUiJson = (value: unknown, label: string): string => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dent-agent",
3
- "version": "0.2.7",
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",