pi-dent-agent 0.2.8 → 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 +25 -2
- package/lib/engine.ts +2 -2
- package/lib/plugin-ui-proxy.ts +495 -0
- package/lib/plugin-ui.ts +117 -33
- package/package.json +1 -1
package/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
type BootSnapshot,
|
|
14
14
|
DispatchEngine,
|
|
15
15
|
hostFromContext,
|
|
16
|
+
inheritedExtensions,
|
|
16
17
|
readBootSnapshot,
|
|
17
18
|
agentsDirFor,
|
|
18
19
|
agentDirForHost,
|
|
@@ -35,6 +36,7 @@ import {
|
|
|
35
36
|
PluginUiController,
|
|
36
37
|
type UiCallableTool,
|
|
37
38
|
} from "./lib/plugin-ui.ts";
|
|
39
|
+
import { PluginUiToolProxy } from "./lib/plugin-ui-proxy.ts";
|
|
38
40
|
import { type Diagnostic, errorMessage, isPlainObject } from "./lib/util.ts";
|
|
39
41
|
import { rebuildInterruptedTasks } from "./lib/task-rebuild.ts";
|
|
40
42
|
import {
|
|
@@ -304,11 +306,24 @@ export default function (pi: ExtensionAPI) {
|
|
|
304
306
|
const questions = askUserRuntime();
|
|
305
307
|
const recap = recapRuntime(boot.config, (data) => pi.appendEntry("pi-dent-recap", data));
|
|
306
308
|
const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
|
|
309
|
+
let currentProjectTrusted = false;
|
|
307
310
|
const pluginUi = new PluginUiController(boot.pluginIndex, {
|
|
308
311
|
ownedTools: () => [...ownedUiTools.values()],
|
|
309
|
-
|
|
310
|
-
|
|
312
|
+
allTools: () => (typeof pi.getAllTools === "function" ? pi.getAllTools() : []),
|
|
313
|
+
activeToolNames: () => (typeof pi.getActiveTools === "function" ? pi.getActiveTools() : []),
|
|
311
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
|
+
},
|
|
312
327
|
});
|
|
313
328
|
let taskWidget: TaskWidgetHandle | undefined;
|
|
314
329
|
// Feeds for an RPC client (task.md Section 4.1, fleet-tool.md Section 6).
|
|
@@ -502,6 +517,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
502
517
|
|
|
503
518
|
pi.on("session_start", async (event, ctx) => {
|
|
504
519
|
recap.abort();
|
|
520
|
+
await pluginUi.disposeProxy();
|
|
521
|
+
currentProjectTrusted =
|
|
522
|
+
typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : false;
|
|
505
523
|
// billing.md Section 4.5: the diagnostics held with no open session go out first.
|
|
506
524
|
sessionUi = ctx.ui;
|
|
507
525
|
for (const diagnostic of heldDiagnostics.splice(0)) showDiagnostic(diagnostic);
|
|
@@ -721,6 +739,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
721
739
|
() => pluginUi.cancelAll("Session ended"),
|
|
722
740
|
reportShutdown,
|
|
723
741
|
);
|
|
742
|
+
try {
|
|
743
|
+
await pluginUi.disposeProxy();
|
|
744
|
+
} catch (error) {
|
|
745
|
+
reportShutdown(`pi-dent: disposing plugin UI tool proxy failed: ${errorMessage(error)}`);
|
|
746
|
+
}
|
|
724
747
|
// The Search tool's continuations of catch-up end with the boot window
|
|
725
748
|
// (search-tool.md Section 2.2).
|
|
726
749
|
shutdownStep("stopping Search", () => search.stop(), reportShutdown);
|
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
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
toolDeclarations,
|
|
24
24
|
} from "./script-tool-types.ts";
|
|
25
25
|
import { errorCode, errorMessage, isPlainObject } from "./util.ts";
|
|
26
|
+
import type { PluginUiToolProxy } from "./plugin-ui-proxy.ts";
|
|
26
27
|
|
|
27
28
|
/**
|
|
28
29
|
* Plugin UI protocol controller (specs/plugin-ui.md): handles `/dent-ui run`
|
|
@@ -155,13 +156,24 @@ export function makeUiToolContext(ctx: ExtensionContext): ExtensionToolContext {
|
|
|
155
156
|
};
|
|
156
157
|
}
|
|
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
|
+
|
|
158
164
|
export interface PluginUiToolDeps {
|
|
159
|
-
/** pi-dent's own registered tools eligible for UI calls. */
|
|
165
|
+
/** pi-dent's own registered tools eligible for direct execution in UI calls. */
|
|
160
166
|
ownedTools: () => readonly UiCallableTool[];
|
|
161
|
-
/**
|
|
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). */
|
|
162
172
|
allToolNames?: () => readonly string[];
|
|
163
173
|
/** `script.tools.allow` (specs/script-tool.md Section 8); absent gives the default. */
|
|
164
174
|
toolsAllow?: () => readonly string[];
|
|
175
|
+
/** Lazily creates the parent session's long-lived tool proxy on the first proxied call. */
|
|
176
|
+
createProxy?: () => PluginUiToolProxy | undefined;
|
|
165
177
|
}
|
|
166
178
|
|
|
167
179
|
export interface PluginUiCommandContext {
|
|
@@ -187,6 +199,7 @@ export class PluginUiController {
|
|
|
187
199
|
private readonly pluginIndex: ReadonlyMap<string, PluginEntry>;
|
|
188
200
|
private readonly toolDeps: PluginUiToolDeps | undefined;
|
|
189
201
|
private readonly active = new Map<string, ActiveUiCall>();
|
|
202
|
+
private proxy: PluginUiToolProxy | undefined;
|
|
190
203
|
|
|
191
204
|
constructor(pluginIndex: ReadonlyMap<string, PluginEntry>, toolDeps?: PluginUiToolDeps) {
|
|
192
205
|
this.pluginIndex = pluginIndex;
|
|
@@ -220,53 +233,124 @@ export class PluginUiController {
|
|
|
220
233
|
}
|
|
221
234
|
}
|
|
222
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
|
+
|
|
223
250
|
private buildRunTools(id: string, ctx: PluginUiCommandContext): ScriptRunTools | undefined {
|
|
224
251
|
if (!this.toolDeps) return undefined;
|
|
225
|
-
const eligible = this.toolDeps
|
|
226
|
-
.ownedTools()
|
|
227
|
-
.filter((tool) => !PLUGIN_UI_EXCLUDED_TOOLS.has(tool.name));
|
|
228
252
|
const allow = this.toolDeps.toolsAllow?.() ?? DEFAULT_TOOLS_ALLOW;
|
|
229
|
-
const
|
|
230
|
-
const
|
|
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);
|
|
231
279
|
const boundSet = new Set(boundNames);
|
|
232
|
-
|
|
280
|
+
|
|
233
281
|
const unavailableSet = new Set<string>();
|
|
234
|
-
for (const
|
|
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?.() ?? []) {
|
|
235
286
|
if (!boundSet.has(name)) unavailableSet.add(name);
|
|
236
287
|
}
|
|
237
|
-
for (const tool of
|
|
288
|
+
for (const tool of ownedList) {
|
|
238
289
|
if (!boundSet.has(tool.name)) unavailableSet.add(tool.name);
|
|
239
290
|
}
|
|
240
291
|
const unavailableNames = [...unavailableSet].toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
292
|
+
|
|
241
293
|
let callSeq = 0;
|
|
242
294
|
return {
|
|
243
295
|
names: boundNames,
|
|
244
296
|
unavailableNames,
|
|
245
|
-
declarations: toolDeclarations({ bound:
|
|
297
|
+
declarations: toolDeclarations({ bound: combined, unbound: [] }),
|
|
246
298
|
call: async (name, args, callSignal) => {
|
|
247
|
-
const
|
|
248
|
-
if (
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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
|
+
);
|
|
253
322
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
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
|
+
};
|
|
270
354
|
},
|
|
271
355
|
};
|
|
272
356
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dent-agent",
|
|
3
|
-
"version": "0.2.
|
|
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",
|