pi-dent-agent 0.2.7 → 0.2.9

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,12 +2,18 @@
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,
9
14
  DispatchEngine,
10
15
  hostFromContext,
16
+ inheritedExtensions,
11
17
  readBootSnapshot,
12
18
  agentsDirFor,
13
19
  agentDirForHost,
@@ -23,7 +29,14 @@ import { runFleetCommand } from "./lib/fleet-command.ts";
23
29
  import { recapRuntime } from "./lib/recap.ts";
24
30
  import { renderRecapEntry } from "./lib/recap-render.ts";
25
31
  import { appendPluginContext, renderPluginCommand } from "./lib/plugins.ts";
26
- import { PluginUiController } from "./lib/plugin-ui.ts";
32
+ import {
33
+ asUiCallableTool,
34
+ makeUiToolContext,
35
+ PLUGIN_UI_EXCLUDED_TOOLS,
36
+ PluginUiController,
37
+ type UiCallableTool,
38
+ } from "./lib/plugin-ui.ts";
39
+ import { PluginUiToolProxy } from "./lib/plugin-ui-proxy.ts";
27
40
  import { type Diagnostic, errorMessage, isPlainObject } from "./lib/util.ts";
28
41
  import { rebuildInterruptedTasks } from "./lib/task-rebuild.ts";
29
42
  import {
@@ -259,6 +272,15 @@ export default function (pi: ExtensionAPI) {
259
272
  },
260
273
  );
261
274
  const cohorts = new CohortTracker();
275
+ const ownedUiTools = new Map<string, UiCallableTool>();
276
+ const registerOwnedTool = <TParams extends TSchema, TDetails = unknown>(
277
+ tool: ToolDefinition<TParams, TDetails>,
278
+ ): void => {
279
+ pi.registerTool(tool);
280
+ if (!PLUGIN_UI_EXCLUDED_TOOLS.has(tool.name)) {
281
+ ownedUiTools.set(tool.name, asUiCallableTool(tool));
282
+ }
283
+ };
262
284
  // The Agent tool is registered at load with an empty model catalog; session_start refreshes it.
263
285
  const agentTool = new AgentToolRegistry(
264
286
  {
@@ -270,7 +292,7 @@ export default function (pi: ExtensionAPI) {
270
292
  hostProvider: () => currentHost,
271
293
  cohortFor: (toolCallId) => cohorts.cohortFor(toolCallId),
272
294
  },
273
- (tool) => pi.registerTool(tool),
295
+ (tool) => registerOwnedTool(tool),
274
296
  );
275
297
  agentTool.refresh("");
276
298
  // Schedules live in the process, keyed by session ID, and survive a reload
@@ -283,7 +305,26 @@ export default function (pi: ExtensionAPI) {
283
305
  // Section 2).
284
306
  const questions = askUserRuntime();
285
307
  const recap = recapRuntime(boot.config, (data) => pi.appendEntry("pi-dent-recap", data));
286
- const pluginUi = new PluginUiController(boot.pluginIndex);
308
+ const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
309
+ let currentProjectTrusted = false;
310
+ const pluginUi = new PluginUiController(boot.pluginIndex, {
311
+ ownedTools: () => [...ownedUiTools.values()],
312
+ allTools: () => (typeof pi.getAllTools === "function" ? pi.getAllTools() : []),
313
+ activeToolNames: () => (typeof pi.getActiveTools === "function" ? pi.getActiveTools() : []),
314
+ toolsAllow: () => scriptToolsAllow,
315
+ createProxy: () => {
316
+ const host = currentHost;
317
+ if (!host) return;
318
+ const active = typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [];
319
+ const excludeTools = active.includes("bash") ? [] : ["bash"];
320
+ return new PluginUiToolProxy({
321
+ cwd: host.cwd(),
322
+ isProjectTrusted: currentProjectTrusted,
323
+ extensions: inheritedExtensions(host),
324
+ excludeTools,
325
+ });
326
+ },
327
+ });
287
328
  let taskWidget: TaskWidgetHandle | undefined;
288
329
  // Feeds for an RPC client (task.md Section 4.1, fleet-tool.md Section 6).
289
330
  let taskFeed: FeedHandle | undefined;
@@ -476,6 +517,9 @@ export default function (pi: ExtensionAPI) {
476
517
 
477
518
  pi.on("session_start", async (event, ctx) => {
478
519
  recap.abort();
520
+ await pluginUi.disposeProxy();
521
+ currentProjectTrusted =
522
+ typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : false;
479
523
  // billing.md Section 4.5: the diagnostics held with no open session go out first.
480
524
  sessionUi = ctx.ui;
481
525
  for (const diagnostic of heldDiagnostics.splice(0)) showDiagnostic(diagnostic);
@@ -695,6 +739,11 @@ export default function (pi: ExtensionAPI) {
695
739
  () => pluginUi.cancelAll("Session ended"),
696
740
  reportShutdown,
697
741
  );
742
+ try {
743
+ await pluginUi.disposeProxy();
744
+ } catch (error) {
745
+ reportShutdown(`pi-dent: disposing plugin UI tool proxy failed: ${errorMessage(error)}`);
746
+ }
698
747
  // The Search tool's continuations of catch-up end with the boot window
699
748
  // (search-tool.md Section 2.2).
700
749
  shutdownStep("stopping Search", () => search.stop(), reportShutdown);
@@ -732,7 +781,6 @@ export default function (pi: ExtensionAPI) {
732
781
 
733
782
  // Task browser (task-browser.md): the shortcut opens the overlay; the overlay closes itself on it.
734
783
  const taskBrowserShortcut = parseTaskBrowser(boot.config).shortcut;
735
- const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
736
784
  const toggleTaskBrowser = async (ctx: ExtensionContext): Promise<void> => {
737
785
  if (closeTaskBrowser) {
738
786
  closeTaskBrowser();
@@ -816,16 +864,16 @@ export default function (pi: ExtensionAPI) {
816
864
  });
817
865
  },
818
866
  });
819
- pi.registerTool(makeTaskTool({ registry: () => engine.registry }));
820
- pi.registerTool(makePluginTool(boot));
821
- pi.registerTool(makeFleetTool({ fleet, hostProvider: () => currentHost }));
822
- pi.registerTool(
867
+ registerOwnedTool(makeTaskTool({ registry: () => engine.registry }));
868
+ registerOwnedTool(makePluginTool(boot));
869
+ registerOwnedTool(makeFleetTool({ fleet, hostProvider: () => currentHost }));
870
+ registerOwnedTool(
823
871
  makeSessionTool({ boot, hostProvider: () => currentHost, billing: guidanceCtl.billing }),
824
872
  );
825
873
  // The main session binds `Skill` and carries the skill catalog like any
826
874
  // child whose tool cap includes it (skill-tool.md Section 1). Plugin context
827
875
  // blocks follow the skill catalog on every turn (plugin.md Section 10).
828
- if (boot.skills.length > 0) pi.registerTool(makeSkillTool(boot));
876
+ if (boot.skills.length > 0) registerOwnedTool(makeSkillTool(boot));
829
877
  if (boot.skills.length > 0 || boot.plugins.some((plugin) => plugin.context !== undefined)) {
830
878
  pi.on("before_agent_start", async (event) => {
831
879
  const withSkills =
@@ -847,7 +895,7 @@ export default function (pi: ExtensionAPI) {
847
895
  toolsAllow: () => scriptToolsAllow,
848
896
  }),
849
897
  );
850
- pi.registerTool(
898
+ registerOwnedTool(
851
899
  makeBashTool({
852
900
  registry: () => engine.registry,
853
901
  hostProvider: () => currentHost,
@@ -860,13 +908,13 @@ export default function (pi: ExtensionAPI) {
860
908
  );
861
909
  // The main session schedules into itself; a child never binds Schedule
862
910
  // (agent-tool.md Section 3.1).
863
- pi.registerTool(makeScheduleTool(schedules));
911
+ registerOwnedTool(makeScheduleTool(schedules));
864
912
  // The main session asks the user; a child never binds AskUserQuestion
865
913
  // (agent-tool.md Section 3.1).
866
914
  pi.registerTool(makeAskUserQuestionTool(questions));
867
915
  // `Search` is registered for the main session, which reaches its own session
868
916
  // tree and, on request, its project (search-tool.md Section 1).
869
- pi.registerTool(
917
+ registerOwnedTool(
870
918
  makeSearchTool({
871
919
  runtime: search,
872
920
  host: (ctx) => {
@@ -879,7 +927,7 @@ export default function (pi: ExtensionAPI) {
879
927
  // `Markdown` reads and restructures one Markdown file by its headings
880
928
  // (pi-dent-markdown specs/markdown-tool.md Section 1); a child session binds it under the tool cap
881
929
  // (agent-tool.md Section 3.1).
882
- pi.registerTool(makeMarkdownTool(markdownRuntime()));
930
+ registerOwnedTool(makeMarkdownTool(markdownRuntime()));
883
931
 
884
932
  // Plugin slash commands (specs/plugin.md Section 5): one command per
885
933
  // commands/*.md resource of the first-admitted plugin per namespace,
@@ -913,6 +961,7 @@ export default function (pi: ExtensionAPI) {
913
961
  pluginUi.handleCommand(args, {
914
962
  cwd: ctx.cwd ?? currentHost?.cwd() ?? process.cwd(),
915
963
  setWidget: (key, lines) => ctx.ui.setWidget(key, lines),
964
+ toolContext: makeUiToolContext(ctx),
916
965
  });
917
966
  },
918
967
  });
package/lib/engine.ts CHANGED
@@ -509,7 +509,7 @@ export function defaultBuiltinExtensions(): InlineExtension[] {
509
509
  }
510
510
 
511
511
  /** The longest the child's extension shutdown may take (agent-tool.md Section 3.1). */
512
- const EXTENSION_SHUTDOWN_TIMEOUT_MS = 1000;
512
+ export const EXTENSION_SHUTDOWN_TIMEOUT_MS = 1000;
513
513
 
514
514
  /** How the child's session-shutdown lifecycle ended (agent-tool.md Section 3.1). */
515
515
  type ExtensionShutdownOutcome = "done" | "timeout" | { readonly error: unknown };
@@ -519,7 +519,7 @@ type ExtensionShutdownOutcome = "done" | "timeout" | { readonly error: unknown }
519
519
  * (agent-tool.md Section 3.1). A failure after the deadline is reported to
520
520
  * stderr, never left unhandled.
521
521
  */
522
- function extensionShutdown(
522
+ export function extensionShutdown(
523
523
  session: AgentSession,
524
524
  deadlineMs: number,
525
525
  ): Promise<ExtensionShutdownOutcome> {
@@ -0,0 +1,495 @@
1
+ import { realpathSync } from "node:fs";
2
+ import {
3
+ createAgentSession,
4
+ DefaultResourceLoader,
5
+ getAgentDir,
6
+ ModelRuntime,
7
+ SessionManager,
8
+ SettingsManager,
9
+ type AgentSession,
10
+ type ExtensionFactory,
11
+ type InlineExtension,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import {
14
+ createAssistantMessageEventStream,
15
+ type AssistantMessage,
16
+ type JsonObject,
17
+ type JsonValue,
18
+ } from "@earendil-works/pi-ai";
19
+ import {
20
+ defaultBuiltinExtensions,
21
+ EXTENSION_SHUTDOWN_TIMEOUT_MS,
22
+ extensionShutdown,
23
+ type InheritedExtensions,
24
+ } from "./engine.ts";
25
+ import type { NestedCallOutcome } from "./script-tool-calls.ts";
26
+ import { errorMessage, isPlainObject } from "./util.ts";
27
+
28
+ /**
29
+ * Plugin UI tool proxy (specs/plugin-ui.md Section 4.3): one lazily created,
30
+ * long-lived in-memory proxy `AgentSession` per parent session on a scripted
31
+ * `streamSimple` provider. Executes non-pi-dent tools (built-in host tools,
32
+ * MCP tools, other extensions' tools) through pi's real tool pipeline with
33
+ * zero LLM calls, zero disk/index/task footprint, and FIFO serialization.
34
+ */
35
+
36
+ const PROXY_PROVIDER = "pi-dent-ui-proxy";
37
+ const PROXY_MODEL_ID = "proxy";
38
+ const PROXY_API = "pi-dent-ui-proxy-api";
39
+
40
+ export interface PluginUiToolProxyOptions {
41
+ cwd: string;
42
+ isProjectTrusted: boolean;
43
+ extensions: InheritedExtensions;
44
+ /** Tool names to exclude from the proxy session (e.g. deactivated built-ins like `bash`). */
45
+ excludeTools?: readonly string[];
46
+ /** Built-in extension factories; defaults to `defaultBuiltinExtensions()`. */
47
+ builtinExtensions?: readonly InlineExtension[];
48
+ /** Additional inline extension factories (used by tests to inject stand-in tools/extensions). */
49
+ extraExtensionFactories?: readonly ExtensionFactory[];
50
+ /** Override for bounded extension shutdown wait (defaults to `EXTENSION_SHUTDOWN_TIMEOUT_MS`). */
51
+ shutdownTimeoutMs?: number;
52
+ }
53
+
54
+ interface PendingProxyCall {
55
+ id: string;
56
+ name: string;
57
+ args: JsonObject;
58
+ }
59
+
60
+ interface QueuedProxyItem {
61
+ name: string;
62
+ args: unknown;
63
+ signal: AbortSignal;
64
+ resolve: (outcome: NestedCallOutcome) => void;
65
+ reject: (error: Error) => void;
66
+ onQueuedAbort: () => void;
67
+ }
68
+
69
+ function realPathSafe(path: string): string {
70
+ try {
71
+ return realpathSync(path);
72
+ } catch {
73
+ return path;
74
+ }
75
+ }
76
+
77
+ function toJsonValue(value: unknown): JsonValue | undefined {
78
+ if (value === null || typeof value === "boolean" || typeof value === "string") return value;
79
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
80
+ if (Array.isArray(value)) {
81
+ const out: JsonValue[] = [];
82
+ for (const item of value) {
83
+ const converted = toJsonValue(item);
84
+ if (converted === undefined) return undefined;
85
+ out.push(converted);
86
+ }
87
+ return out;
88
+ }
89
+ if (isPlainObject(value)) {
90
+ const out: JsonObject = {};
91
+ for (const [k, v] of Object.entries(value)) {
92
+ const converted = toJsonValue(v);
93
+ if (converted === undefined) return undefined;
94
+ out[k] = converted;
95
+ }
96
+ return out;
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ function toJsonObject(value: unknown): JsonObject {
102
+ if (!isPlainObject(value)) return {};
103
+ const converted = toJsonValue(value);
104
+ return converted !== undefined && isPlainObject(converted) ? converted : {};
105
+ }
106
+
107
+ function emptyUsage(): AssistantMessage["usage"] {
108
+ return {
109
+ input: 0,
110
+ output: 0,
111
+ cacheRead: 0,
112
+ cacheWrite: 0,
113
+ totalTokens: 0,
114
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
115
+ };
116
+ }
117
+
118
+ function makeAssistantMessage(
119
+ content: AssistantMessage["content"],
120
+ stopReason: "stop" | "toolUse",
121
+ ): AssistantMessage {
122
+ return {
123
+ role: "assistant",
124
+ content,
125
+ api: PROXY_API,
126
+ provider: PROXY_PROVIDER,
127
+ model: PROXY_MODEL_ID,
128
+ usage: emptyUsage(),
129
+ stopReason,
130
+ timestamp: Date.now(),
131
+ };
132
+ }
133
+
134
+ function extractOutcomeFromResult(rawResult: unknown, isError: boolean): NestedCallOutcome {
135
+ if (!isPlainObject(rawResult)) {
136
+ return { result: { content: [] }, isError };
137
+ }
138
+ const content = Array.isArray(rawResult.content) ? rawResult.content : [];
139
+ const details = rawResult.details;
140
+ const structuredContent = rawResult.structuredContent;
141
+ return {
142
+ result: {
143
+ content,
144
+ ...(details === undefined ? {} : { details }),
145
+ ...(structuredContent === undefined ? {} : { structuredContent }),
146
+ },
147
+ isError,
148
+ };
149
+ }
150
+
151
+ export class PluginUiToolProxy {
152
+ private readonly options: PluginUiToolProxyOptions;
153
+ private session: AgentSession | undefined;
154
+ private startPromise: Promise<AgentSession> | undefined;
155
+ private failedTools = new Map<string, string>();
156
+ private queue: QueuedProxyItem[] = [];
157
+ private pumping = false;
158
+ private disposed = false;
159
+ private callSeq = 0;
160
+
161
+ /** Shared per-turn handoff between `runOne` and the scripted `streamSimple` provider. */
162
+ private pendingCall: PendingProxyCall | undefined;
163
+ private capturedOutcome: NestedCallOutcome | undefined;
164
+
165
+ constructor(options: PluginUiToolProxyOptions) {
166
+ this.options = options;
167
+ }
168
+
169
+ /** Whether the proxy session has been instantiated. */
170
+ isStarted(): boolean {
171
+ return this.session !== undefined;
172
+ }
173
+
174
+ /** Execute one proxied tool call on the FIFO queue (specs/plugin-ui.md Section 4.3). */
175
+ call(name: string, args: unknown, signal: AbortSignal): Promise<NestedCallOutcome> {
176
+ if (this.disposed) {
177
+ return Promise.reject(new Error("Plugin UI proxy session ended"));
178
+ }
179
+ if (signal.aborted) {
180
+ return Promise.reject(new Error("Tool call aborted"));
181
+ }
182
+ return new Promise<NestedCallOutcome>((resolve, reject) => {
183
+ const item: QueuedProxyItem = {
184
+ name,
185
+ args,
186
+ signal,
187
+ resolve,
188
+ reject,
189
+ onQueuedAbort: () => {
190
+ const idx = this.queue.indexOf(item);
191
+ if (idx !== -1) {
192
+ this.queue.splice(idx, 1);
193
+ reject(new Error("Tool call aborted"));
194
+ }
195
+ },
196
+ };
197
+ signal.addEventListener("abort", item.onQueuedAbort, { once: true });
198
+ this.queue.push(item);
199
+ void this.pump();
200
+ });
201
+ }
202
+
203
+ /** Abort any in-flight call, reject queued calls, and shut down the proxy session. */
204
+ async dispose(): Promise<void> {
205
+ if (this.disposed) return;
206
+ this.disposed = true;
207
+ const queued = this.queue.splice(0);
208
+ for (const item of queued) {
209
+ item.signal.removeEventListener("abort", item.onQueuedAbort);
210
+ item.reject(new Error("Plugin UI proxy session ended"));
211
+ }
212
+ const session = this.session;
213
+ this.session = undefined;
214
+ if (session) {
215
+ try {
216
+ await session.abort();
217
+ } catch {
218
+ // Best effort.
219
+ }
220
+ await extensionShutdown(
221
+ session,
222
+ this.options.shutdownTimeoutMs ?? EXTENSION_SHUTDOWN_TIMEOUT_MS,
223
+ );
224
+ try {
225
+ session.dispose();
226
+ } catch {
227
+ // Best effort.
228
+ }
229
+ }
230
+ }
231
+
232
+ private async ensureStarted(): Promise<AgentSession> {
233
+ if (this.disposed) throw new Error("Plugin UI proxy session ended");
234
+ if (this.session) return this.session;
235
+ if (this.startPromise) return this.startPromise;
236
+ this.startPromise = this.startSession().catch((error: unknown) => {
237
+ this.startPromise = undefined;
238
+ throw error;
239
+ });
240
+ return this.startPromise;
241
+ }
242
+
243
+ private async startSession(): Promise<AgentSession> {
244
+ const { cwd, isProjectTrusted, extensions } = this.options;
245
+ const settingsManager = SettingsManager.create(cwd, getAgentDir());
246
+ settingsManager.setProjectTrusted(isProjectTrusted);
247
+
248
+ const providerFactory: ExtensionFactory = (pi) => {
249
+ pi.registerProvider(PROXY_PROVIDER, {
250
+ baseUrl: "http://127.0.0.1:0",
251
+ api: PROXY_API,
252
+ apiKey: "unused",
253
+ models: [
254
+ {
255
+ id: PROXY_MODEL_ID,
256
+ name: PROXY_MODEL_ID,
257
+ reasoning: false,
258
+ input: ["text"],
259
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
260
+ contextWindow: 128000,
261
+ maxTokens: 4096,
262
+ },
263
+ ],
264
+ streamSimple: (_model, context) => {
265
+ const stream = createAssistantMessageEventStream();
266
+ queueMicrotask(() => {
267
+ const last = context.messages[context.messages.length - 1];
268
+ if (last && last.role === "toolResult") {
269
+ if (this.capturedOutcome === undefined) {
270
+ this.capturedOutcome = extractOutcomeFromResult(last, last.isError);
271
+ }
272
+ stream.push({
273
+ type: "done",
274
+ reason: "stop",
275
+ message: makeAssistantMessage([{ type: "text", text: "ok" }], "stop"),
276
+ });
277
+ return;
278
+ }
279
+ const call = this.pendingCall;
280
+ this.pendingCall = undefined;
281
+ if (!call) {
282
+ stream.push({
283
+ type: "done",
284
+ reason: "stop",
285
+ message: makeAssistantMessage([{ type: "text", text: "noop" }], "stop"),
286
+ });
287
+ return;
288
+ }
289
+ stream.push({
290
+ type: "done",
291
+ reason: "toolUse",
292
+ message: makeAssistantMessage(
293
+ [{ type: "toolCall", id: call.id, name: call.name, arguments: call.args }],
294
+ "toolUse",
295
+ ),
296
+ });
297
+ });
298
+ return stream;
299
+ },
300
+ });
301
+ };
302
+
303
+ const loader = new DefaultResourceLoader({
304
+ cwd,
305
+ agentDir: getAgentDir(),
306
+ settingsManager,
307
+ noExtensions: true,
308
+ additionalExtensionPaths: [...extensions.sources],
309
+ extensionFactories: [
310
+ ...(this.options.builtinExtensions ?? defaultBuiltinExtensions()),
311
+ ...(this.options.extraExtensionFactories ?? []),
312
+ providerFactory,
313
+ ],
314
+ noSkills: true,
315
+ skillsOverride: () => ({ skills: [], diagnostics: [] }),
316
+ promptsOverride: () => ({ prompts: [], diagnostics: [] }),
317
+ themesOverride: () => ({ themes: [], diagnostics: [] }),
318
+ noPromptTemplates: true,
319
+ noThemes: true,
320
+ noContextFiles: true,
321
+ systemPrompt: "Plugin UI tool proxy.",
322
+ });
323
+
324
+ await loader.reload();
325
+ const loaded = loader.getExtensions();
326
+ this.recordLoadFailures(extensions, loaded);
327
+
328
+ const runtime = await ModelRuntime.create({ refreshOnCreate: false });
329
+ const sessionManager = SessionManager.inMemory(cwd);
330
+ const created = await createAgentSession({
331
+ cwd,
332
+ modelRuntime: runtime,
333
+ resourceLoader: loader,
334
+ sessionManager,
335
+ settingsManager,
336
+ ...(this.options.excludeTools && this.options.excludeTools.length > 0
337
+ ? { excludeTools: [...this.options.excludeTools] }
338
+ : {}),
339
+ });
340
+ const session = created.session;
341
+ if (this.disposed) {
342
+ session.dispose();
343
+ throw new Error("Plugin UI proxy session ended");
344
+ }
345
+
346
+ await session.bindExtensions({});
347
+ const proxyModel = session.modelRuntime
348
+ .getModels()
349
+ .find((m) => m.provider === PROXY_PROVIDER && m.id === PROXY_MODEL_ID);
350
+ if (!proxyModel) {
351
+ session.dispose();
352
+ throw new Error("Proxy provider model was not registered");
353
+ }
354
+ await session.setModel(proxyModel);
355
+
356
+ // Subscribe to tool_execution_end to capture full result including structuredContent.
357
+ session.subscribe((event) => {
358
+ if (event.type === "tool_execution_end") {
359
+ this.capturedOutcome = extractOutcomeFromResult(event.result, event.isError);
360
+ }
361
+ });
362
+
363
+ if (this.disposed) {
364
+ await extensionShutdown(
365
+ session,
366
+ this.options.shutdownTimeoutMs ?? EXTENSION_SHUTDOWN_TIMEOUT_MS,
367
+ );
368
+ session.dispose();
369
+ throw new Error("Plugin UI proxy session ended");
370
+ }
371
+
372
+ this.session = session;
373
+ return session;
374
+ }
375
+
376
+ private recordLoadFailures(
377
+ extensions: InheritedExtensions,
378
+ loaded: {
379
+ readonly extensions: readonly { readonly path: string; readonly resolvedPath: string }[];
380
+ readonly errors: readonly { readonly path: string; readonly error: string }[];
381
+ },
382
+ ): void {
383
+ const loadedKeys = new Set<string>();
384
+ for (const ext of loaded.extensions) {
385
+ loadedKeys.add(realPathSafe(ext.path));
386
+ loadedKeys.add(realPathSafe(ext.resolvedPath));
387
+ }
388
+ const sourceErrors = new Map<string, string>();
389
+ for (const err of loaded.errors) {
390
+ const key = realPathSafe(err.path);
391
+ if (!loadedKeys.has(key) && !sourceErrors.has(key)) {
392
+ sourceErrors.set(key, err.error);
393
+ }
394
+ }
395
+ for (const source of extensions.sources) {
396
+ const key = realPathSafe(source);
397
+ if (!loadedKeys.has(key) && !sourceErrors.has(key)) {
398
+ sourceErrors.set(key, `extension "${source}" was not loaded`);
399
+ }
400
+ }
401
+ this.failedTools.clear();
402
+ for (const tool of extensions.tools) {
403
+ const err = sourceErrors.get(realPathSafe(tool.source));
404
+ if (err !== undefined) {
405
+ this.failedTools.set(tool.name, err);
406
+ }
407
+ }
408
+ }
409
+
410
+ private async pump(): Promise<void> {
411
+ if (this.pumping) return;
412
+ this.pumping = true;
413
+ try {
414
+ while (!this.disposed && this.queue.length > 0) {
415
+ const item = this.queue.shift();
416
+ if (!item) continue;
417
+ item.signal.removeEventListener("abort", item.onQueuedAbort);
418
+ if (item.signal.aborted) {
419
+ item.reject(new Error("Tool call aborted"));
420
+ continue;
421
+ }
422
+ try {
423
+ const outcome = await this.runOne(item);
424
+ item.resolve(outcome);
425
+ } catch (error) {
426
+ item.reject(error instanceof Error ? error : new Error(errorMessage(error)));
427
+ }
428
+ }
429
+ } finally {
430
+ this.pumping = false;
431
+ }
432
+ }
433
+
434
+ private async runOne(item: QueuedProxyItem): Promise<NestedCallOutcome> {
435
+ let session: AgentSession;
436
+ try {
437
+ session = await this.ensureStarted();
438
+ } catch (error) {
439
+ throw new Error(`Proxy session failed to start: ${errorMessage(error)}`);
440
+ }
441
+
442
+ const failedExtError = this.failedTools.get(item.name);
443
+ if (failedExtError !== undefined) {
444
+ return {
445
+ result: {
446
+ content: [
447
+ {
448
+ type: "text",
449
+ text: `Extension for tool "${item.name}" failed to load in proxy: ${failedExtError}`,
450
+ },
451
+ ],
452
+ },
453
+ isError: true,
454
+ };
455
+ }
456
+
457
+ if (this.disposed) throw new Error("Plugin UI proxy session ended");
458
+ if (item.signal.aborted) throw new Error("Tool call aborted");
459
+
460
+ const callId = `ui-proxy-${++this.callSeq}`;
461
+ this.pendingCall = { id: callId, name: item.name, args: toJsonObject(item.args) };
462
+ this.capturedOutcome = undefined;
463
+
464
+ const onAbort = (): void => {
465
+ void session.abort();
466
+ };
467
+ item.signal.addEventListener("abort", onAbort, { once: true });
468
+
469
+ try {
470
+ await session.prompt(`proxy:${callId}`);
471
+ } catch (error) {
472
+ if (item.signal.aborted) throw new Error("Tool call aborted");
473
+ throw error;
474
+ } finally {
475
+ item.signal.removeEventListener("abort", onAbort);
476
+ this.pendingCall = undefined;
477
+ try {
478
+ session.agent.state.messages = [];
479
+ } catch {
480
+ // Best effort history reset.
481
+ }
482
+ }
483
+
484
+ if (item.signal.aborted) throw new Error("Tool call aborted");
485
+ if (this.capturedOutcome !== undefined) {
486
+ return this.capturedOutcome;
487
+ }
488
+ return {
489
+ result: {
490
+ content: [{ type: "text", text: `Proxy tool "${item.name}" produced no result` }],
491
+ },
492
+ isError: true,
493
+ };
494
+ }
495
+ }
package/lib/plugin-ui.ts CHANGED
@@ -1,14 +1,34 @@
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";
26
+ import type { PluginUiToolProxy } from "./plugin-ui-proxy.ts";
7
27
 
8
28
  /**
9
29
  * 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
30
+ * and `/dent-ui cancel`, executes plugin scripts with `dent.ui.send`, pi-dent's
31
+ * own tools, and no time limit, and emits `message` and `reply` records on the
12
32
  * `pi-dent-ui` widget feed.
13
33
  */
14
34
 
@@ -16,9 +36,150 @@ export const PLUGIN_UI_WIDGET_KEY = "pi-dent-ui";
16
36
  export const PLUGIN_UI_PROTOCOL = "ui/1";
17
37
  export const PLUGIN_UI_PAYLOAD_CAP_BYTES = 262_144;
18
38
 
39
+ /** Tools pi-dent registers that are never callable from a plugin UI call (Section 4.2). */
40
+ export const PLUGIN_UI_EXCLUDED_TOOLS: ReadonlySet<string> = new Set(["Script", "AskUserQuestion"]);
41
+
42
+ /** One pi-dent tool adapted for execution from a plugin UI call (Section 4.2). */
43
+ export interface UiCallableTool extends CallableTool {
44
+ execute(
45
+ toolCallId: string,
46
+ params: unknown,
47
+ signal: AbortSignal | undefined,
48
+ ctx: ExtensionToolContext | undefined,
49
+ ): Promise<NestedCallOutcome>;
50
+ }
51
+
52
+ function toJsonValue(value: unknown): JsonValue | undefined {
53
+ if (value === null || typeof value === "boolean" || typeof value === "string") return value;
54
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
55
+ if (Array.isArray(value)) {
56
+ const out: JsonValue[] = [];
57
+ for (const item of value) {
58
+ const converted = toJsonValue(item);
59
+ if (converted === undefined) return undefined;
60
+ out.push(converted);
61
+ }
62
+ return out;
63
+ }
64
+ if (isPlainObject(value)) {
65
+ const out: JsonObject = {};
66
+ for (const [k, v] of Object.entries(value)) {
67
+ const converted = toJsonValue(v);
68
+ if (converted === undefined) return undefined;
69
+ out[k] = converted;
70
+ }
71
+ return out;
72
+ }
73
+ return undefined;
74
+ }
75
+
76
+ function toJsonObject(value: unknown): JsonObject {
77
+ if (!isPlainObject(value)) return {};
78
+ const converted = toJsonValue(value);
79
+ return converted !== undefined && isPlainObject(converted) ? converted : {};
80
+ }
81
+
82
+ /**
83
+ * Adapt a pi `ToolDefinition` for direct execution from a plugin UI call:
84
+ * validates arguments with pi's `validateToolArguments` and normalises the
85
+ * returned `AgentToolResult` into a `NestedCallOutcome`.
86
+ */
87
+ export function asUiCallableTool<TParams extends TSchema, TDetails = unknown>(
88
+ tool: ToolDefinition<TParams, TDetails>,
89
+ ): UiCallableTool {
90
+ return {
91
+ name: tool.name,
92
+ description: tool.description,
93
+ parameters: tool.parameters,
94
+ ...(tool.outputSchema === undefined ? {} : { outputSchema: tool.outputSchema }),
95
+ async execute(toolCallId, params, signal, ctx) {
96
+ const raw = isPlainObject(params) ? params : {};
97
+ const prepared = tool.prepareArguments ? tool.prepareArguments(raw) : raw;
98
+ const validated: Static<TParams> = validateToolArguments(
99
+ { name: tool.name, description: tool.description, parameters: tool.parameters },
100
+ { type: "toolCall", id: toolCallId, name: tool.name, arguments: toJsonObject(prepared) },
101
+ );
102
+ if (ctx === undefined) {
103
+ return {
104
+ result: {
105
+ content: [{ type: "text", text: "No host context available for tool call" }],
106
+ },
107
+ isError: true,
108
+ };
109
+ }
110
+ const result = await tool.execute(toolCallId, validated, signal, undefined, ctx);
111
+ const structured = "structuredContent" in result ? result.structuredContent : undefined;
112
+ return {
113
+ result: {
114
+ content: result.content,
115
+ details: result.details,
116
+ ...(structured === undefined ? {} : { structuredContent: structured }),
117
+ },
118
+ isError: "isError" in result && result.isError === true,
119
+ };
120
+ },
121
+ };
122
+ }
123
+
124
+ /** Build an `ExtensionToolContext` from a command/session `ExtensionContext`. */
125
+ export function makeUiToolContext(ctx: ExtensionContext): ExtensionToolContext {
126
+ return {
127
+ ui: ctx.ui,
128
+ mode: ctx.mode,
129
+ hasUI: ctx.hasUI,
130
+ cwd: ctx.cwd,
131
+ sessionManager: ctx.sessionManager,
132
+ modelRegistry: ctx.modelRegistry,
133
+ model: ctx.model,
134
+ scopedModels: ctx.scopedModels,
135
+ ...(ctx.thinkingLevel === undefined ? {} : { thinkingLevel: ctx.thinkingLevel }),
136
+ isIdle: () => ctx.isIdle(),
137
+ isProjectTrusted: () => ctx.isProjectTrusted(),
138
+ signal: ctx.signal,
139
+ abort: () => ctx.abort(),
140
+ hasPendingMessages: () => ctx.hasPendingMessages(),
141
+ shutdown: () => ctx.shutdown(),
142
+ getContextUsage: () => ctx.getContextUsage(),
143
+ compact: (options) => ctx.compact(options),
144
+ getSystemPrompt: () => ctx.getSystemPrompt(),
145
+ tools: [],
146
+ executeTool: async (name) => ({
147
+ toolCall: { type: "toolCall", id: "ui:unsupported", name, arguments: {} },
148
+ result: {
149
+ content: [
150
+ { type: "text", text: "Nested tool calls are not available in a plugin UI call" },
151
+ ],
152
+ details: {},
153
+ },
154
+ isError: true,
155
+ }),
156
+ };
157
+ }
158
+
159
+ /** Minimal shape of a tool from `pi.getAllTools()` needed for proxy binding. */
160
+ export interface SessionToolInfo extends CallableTool {
161
+ exposure?: string | undefined;
162
+ }
163
+
164
+ export interface PluginUiToolDeps {
165
+ /** pi-dent's own registered tools eligible for direct execution in UI calls. */
166
+ ownedTools: () => readonly UiCallableTool[];
167
+ /** All tools configured in the session (from `pi.getAllTools()`). */
168
+ allTools?: () => readonly SessionToolInfo[];
169
+ /** Active tool names in the session (from `pi.getActiveTools()`). */
170
+ activeToolNames?: () => readonly string[];
171
+ /** Fallback list of session tool names when `allTools` is omitted (used by unit tests). */
172
+ allToolNames?: () => readonly string[];
173
+ /** `script.tools.allow` (specs/script-tool.md Section 8); absent gives the default. */
174
+ toolsAllow?: () => readonly string[];
175
+ /** Lazily creates the parent session's long-lived tool proxy on the first proxied call. */
176
+ createProxy?: () => PluginUiToolProxy | undefined;
177
+ }
178
+
19
179
  export interface PluginUiCommandContext {
20
180
  cwd: string;
21
181
  setWidget(key: string, lines: string[] | undefined): void;
182
+ toolContext?: ExtensionToolContext;
22
183
  extraEnv?: Record<string, string>;
23
184
  }
24
185
 
@@ -36,10 +197,13 @@ function formatThrownError(
36
197
 
37
198
  export class PluginUiController {
38
199
  private readonly pluginIndex: ReadonlyMap<string, PluginEntry>;
200
+ private readonly toolDeps: PluginUiToolDeps | undefined;
39
201
  private readonly active = new Map<string, ActiveUiCall>();
202
+ private proxy: PluginUiToolProxy | undefined;
40
203
 
41
- constructor(pluginIndex: ReadonlyMap<string, PluginEntry>) {
204
+ constructor(pluginIndex: ReadonlyMap<string, PluginEntry>, toolDeps?: PluginUiToolDeps) {
42
205
  this.pluginIndex = pluginIndex;
206
+ this.toolDeps = toolDeps;
43
207
  }
44
208
 
45
209
  /** Number of UI calls currently executing. */
@@ -69,6 +233,128 @@ export class PluginUiController {
69
233
  }
70
234
  }
71
235
 
236
+ /** Dispose the parent session's tool proxy, if one was created (specs/plugin-ui.md Section 4.3). */
237
+ async disposeProxy(): Promise<void> {
238
+ const current = this.proxy;
239
+ this.proxy = undefined;
240
+ if (current) await current.dispose();
241
+ }
242
+
243
+ private getOrCreateProxy(): PluginUiToolProxy | undefined {
244
+ if (this.proxy) return this.proxy;
245
+ const created = this.toolDeps?.createProxy?.();
246
+ if (created) this.proxy = created;
247
+ return this.proxy;
248
+ }
249
+
250
+ private buildRunTools(id: string, ctx: PluginUiCommandContext): ScriptRunTools | undefined {
251
+ if (!this.toolDeps) return undefined;
252
+ const allow = this.toolDeps.toolsAllow?.() ?? DEFAULT_TOOLS_ALLOW;
253
+ const ownedList = this.toolDeps.ownedTools();
254
+ const directCandidates = ownedList.filter((tool) => !PLUGIN_UI_EXCLUDED_TOOLS.has(tool.name));
255
+ const directSelection = selectTools(directCandidates, allow);
256
+ const directMap = new Map<string, UiCallableTool>();
257
+ for (const tool of directSelection.bound) directMap.set(tool.name, tool);
258
+
259
+ const allSessionTools = this.toolDeps.allTools?.() ?? [];
260
+ const proxiedMap = new Map<string, CallableTool>();
261
+ if (this.toolDeps.createProxy && allSessionTools.length > 0) {
262
+ const activeNames = this.toolDeps.activeToolNames?.();
263
+ const activeSet = activeNames ? new Set(activeNames) : undefined;
264
+ const proxiedCandidates = allSessionTools.filter((tool) => {
265
+ if (directMap.has(tool.name) || PLUGIN_UI_EXCLUDED_TOOLS.has(tool.name)) return false;
266
+ const exposure = tool.exposure ?? "direct";
267
+ if (exposure === "codemode" || exposure === "deferred") return true;
268
+ if (exposure === "direct") return activeSet === undefined || activeSet.has(tool.name);
269
+ return false;
270
+ });
271
+ const proxiedSelection = selectTools(proxiedCandidates, allow);
272
+ for (const tool of proxiedSelection.bound) proxiedMap.set(tool.name, tool);
273
+ }
274
+
275
+ const combined: CallableTool[] = [...directSelection.bound, ...proxiedMap.values()].toSorted(
276
+ (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
277
+ );
278
+ const boundNames = combined.map((tool) => tool.name);
279
+ const boundSet = new Set(boundNames);
280
+
281
+ const unavailableSet = new Set<string>();
282
+ for (const tool of allSessionTools) {
283
+ if (!boundSet.has(tool.name)) unavailableSet.add(tool.name);
284
+ }
285
+ for (const name of this.toolDeps.allToolNames?.() ?? []) {
286
+ if (!boundSet.has(name)) unavailableSet.add(name);
287
+ }
288
+ for (const tool of ownedList) {
289
+ if (!boundSet.has(tool.name)) unavailableSet.add(tool.name);
290
+ }
291
+ const unavailableNames = [...unavailableSet].toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0));
292
+
293
+ let callSeq = 0;
294
+ return {
295
+ names: boundNames,
296
+ unavailableNames,
297
+ declarations: toolDeclarations({ bound: combined, unbound: [] }),
298
+ call: async (name, args, callSignal) => {
299
+ const directTool = directMap.get(name);
300
+ if (directTool !== undefined) {
301
+ const toolCallId = `ui:${id}/${++callSeq}`;
302
+ return callBoundTool(
303
+ directTool,
304
+ args,
305
+ async (_toolName, toolArgs, options) => {
306
+ try {
307
+ return await directTool.execute(
308
+ toolCallId,
309
+ toolArgs,
310
+ options.signal,
311
+ ctx.toolContext,
312
+ );
313
+ } catch (error) {
314
+ return {
315
+ result: { content: [{ type: "text", text: errorMessage(error) }] },
316
+ isError: true,
317
+ };
318
+ }
319
+ },
320
+ callSignal,
321
+ );
322
+ }
323
+
324
+ const proxiedTool = proxiedMap.get(name);
325
+ if (proxiedTool !== undefined) {
326
+ const proxy = this.getOrCreateProxy();
327
+ if (proxy === undefined) {
328
+ return {
329
+ ok: false,
330
+ error: { name: "Error", message: "No live host session for proxied tool call" },
331
+ };
332
+ }
333
+ return callBoundTool(
334
+ proxiedTool,
335
+ args,
336
+ async (_toolName, toolArgs, options) => {
337
+ try {
338
+ return await proxy.call(name, toolArgs, options.signal);
339
+ } catch (error) {
340
+ return {
341
+ result: { content: [{ type: "text", text: errorMessage(error) }] },
342
+ isError: true,
343
+ };
344
+ }
345
+ },
346
+ callSignal,
347
+ );
348
+ }
349
+
350
+ return {
351
+ ok: false,
352
+ error: { name: "Error", message: `tool ${name} is unavailable in a plugin UI call` },
353
+ };
354
+ },
355
+ };
356
+ }
357
+
72
358
  private handleRun(rawJson: string, ctx: PluginUiCommandContext): void {
73
359
  let parsed: unknown;
74
360
  try {
@@ -149,6 +435,7 @@ export class PluginUiController {
149
435
  }
150
436
 
151
437
  const data = parsed.data === undefined ? null : parsed.data;
438
+ const tools = this.buildRunTools(id, ctx);
152
439
  let handle: ScriptRunHandle;
153
440
  try {
154
441
  handle = runScript({
@@ -158,6 +445,7 @@ export class PluginUiController {
158
445
  input: { ui: data },
159
446
  aliases: bundledAliases(),
160
447
  uiCall: true,
448
+ ...(tools === undefined ? {} : { tools }),
161
449
  ...(ctx.extraEnv && Object.keys(ctx.extraEnv).length > 0 ? { extraEnv: ctx.extraEnv } : {}),
162
450
  onUiMessage: (dataJson) => {
163
451
  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.9",
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",