Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(composer): isolate file line prefetches and gate view capability

Linuxdazhao297ddcec0f18
diff --git a/apps/desktop/electron/main/file-line-reference.ts b/apps/desktop/electron/main/file-line-reference.ts
index ed50c6481..ce6822360 100644
--- a/apps/desktop/electron/main/file-line-reference.ts
+++ b/apps/desktop/electron/main/file-line-reference.ts
@@ -9,6 +9,24 @@ import { projectFolderPaths } from "./workspace-roots.ts";
export const FILE_LINES_VIEW_KEY = "pi.file-manager/manager";
+type LoadedPlugin = NonNullable<ReturnType<PluginRuntime["getLoaded"]>>;
+
+export function canUseFileLineView(loaded: LoadedPlugin | undefined): loaded is LoadedPlugin {
+ return !!loaded && !loaded.development && !loaded.disposing &&
+ loaded.permissions.has("fs.read") && loaded.permissions.has("ui.view");
+}
+
+export async function isRegisteredFileLineView(
+ host: Pick<HostProcess, "call"> | null,
+ pluginId: string,
+ version: string,
+): Promise<boolean> {
+ const registry = await host?.call<{
+ plugins: Array<{ id: string; enabled: boolean; version: string }>;
+ }>("plugins.list");
+ return registry?.plugins.some(item => item.id === pluginId && item.enabled && item.version === version) ?? false;
+}
+
type FileLineBridge = {
plugins: Pick<PluginRuntime, "getLoaded">;
pluginViews: Pick<PluginViewHost, "isVisibleViewSender">;
@@ -26,35 +44,37 @@ export async function addFileLinesFromView(
bridge: FileLineBridge,
): Promise<{ ok: true }> {
const reference = parseFileLineReference(payload);
+ if (!reference) throw new Error("Invalid file line selection.");
const currentTarget = () => {
const loaded = bridge.plugins.getLoaded(pluginId);
const selected = bridge.pluginSession.snapshot();
if (
- !reference || !selected || !loaded || loaded.development || loaded.disposing ||
- !loaded.permissions.has("fs.read") || !loaded.permissions.has("ui.view") ||
+ !selected || !canUseFileLineView(loaded) ||
!bridge.pluginViews.isVisibleViewSender(senderId, FILE_LINES_VIEW_KEY) ||
!bridge.pluginActiveInProject(pluginId, selected.projectPath) ||
- reference.workspace !== bridge.getWorkspacePath() ||
- !fileLinePathInProject(reference.path, selected.projectPath)
+ reference.workspace !== bridge.getWorkspacePath()
) return null;
return { loaded, selected };
};
const target = currentTarget();
- if (!reference || !target) throw new Error("The file selection is outside the active project or session.");
+ if (!target) throw new Error("The File Manager view or target session is no longer active.");
+ if (!fileLinePathInProject(reference.path, target.selected.projectPath)) {
+ throw new Error("The file selection is outside the active project.");
+ }
const host = bridge.getHost();
- const registry = await host?.call<{
- plugins: Array<{ id: string; enabled: boolean; version: string }>;
- }>("plugins.list");
+ if (!await isRegisteredFileLineView(host, pluginId, target.loaded.manifest.version)) {
+ throw new Error("The File Manager is not enabled in the Host registry.");
+ }
const current = currentTarget();
if (
bridge.getHost() !== host || !current || current.loaded !== target.loaded ||
current.selected.sessionId !== target.selected.sessionId ||
- current.selected.projectPath !== target.selected.projectPath ||
- !registry?.plugins.some(item =>
- item.id === pluginId && item.enabled && item.version === target.loaded.manifest.version
- )
+ current.selected.projectPath !== target.selected.projectPath
) throw new Error("The File Manager or target session is no longer active.");
+ if (!fileLinePathInProject(reference.path, current.selected.projectPath)) {
+ throw new Error("The file selection is outside the active project.");
+ }
bridge.publish({ sessionId: target.selected.sessionId, reference });
return { ok: true };
diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
index 8b6631813..fcc228b11 100644
--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
@@ -18,9 +18,12 @@ import {
type PluginComposerSuggestionRefusal,
} from "@pi-desktop/plugin-sdk";
import type { ComposerSuggestionAnswer } from "../services/composer-suggestion";
+import { canUseFileLineView, FILE_LINES_VIEW_KEY, isRegisteredFileLineView } from "../file-line-reference";
+import type { HostProcess } from "../host-process";
export type PluginUiIpcDependencies = {
registrar: IpcRegistrar;
+ getHost: () => HostProcess | null;
plugins: PluginRuntime;
browserHost: BrowserHost;
pluginViews: PluginViewHost;
@@ -44,6 +47,7 @@ export type PluginUiIpcDependencies = {
/** Register plugin panels, work-panel views, themes and services. */
export function registerPluginUiIpc({
registrar,
+ getHost,
plugins,
browserHost,
pluginViews,
@@ -318,12 +322,23 @@ export function registerPluginUiIpc({
if (isBrowserView && sessionId) {
browserHost.setChromeSession(sessionId, typeof payload.tabId === "string" ? payload.tabId : undefined, location);
}
+ let composerFileLines = false;
+ if (pluginViewKey(pluginId, viewId) === FILE_LINES_VIEW_KEY && canUseFileLineView(loaded)) {
+ const host = getHost();
+ composerFileLines = await isRegisteredFileLineView(host, pluginId, loaded.manifest.version).catch(() => false);
+ if (plugins.getLoaded(pluginId) !== loaded || loaded.disposing ||
+ !loaded.permissions.has("ui.view") || !pluginActiveInProject(pluginId, currentWorkspacePath())) {
+ throw new Error("plugin is no longer active in this project");
+ }
+ composerFileLines = composerFileLines && getHost() === host && canUseFileLineView(loaded);
+ }
pluginViews.open({
pluginId,
viewId,
locale: getUpdaterLocale(),
theme: getPluginPanelTheme(),
htmlPath,
+ composerFileLines,
netDomains: loaded.manifest.net?.domains?.map((domain) => String(domain)),
netAnyHost: loaded.permissions.has("net.anyHost"),
// The browser view owns an address bar and its own history, so its
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 46ac96974..ae57d68a4 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -515,6 +515,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
registerPluginUiIpc({
registrar,
+ getHost,
plugins,
browserHost,
pluginViews,
diff --git a/apps/desktop/electron/main/plugin-view-host.ts b/apps/desktop/electron/main/plugin-view-host.ts
index 57deb5e78..5511e726d 100644
--- a/apps/desktop/electron/main/plugin-view-host.ts
+++ b/apps/desktop/electron/main/plugin-view-host.ts
@@ -32,7 +32,6 @@ import {
PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX,
type PluginPanelTheme,
} from "../shared/plugin-panel-chrome";
-import { FILE_LINES_VIEW_KEY } from "./file-line-reference";
/**
* Re-exported so the location contract stays addressable through the module
@@ -67,6 +66,7 @@ export type PluginViewOpenRequest = {
theme: PluginPanelTheme;
/** Absolute path to the view's HTML entry. */
htmlPath: string;
+ composerFileLines?: boolean;
/** Egress allowlist from `manifest.net.domains`. */
netDomains?: readonly string[];
/** The install-time `net.anyHost` grant, passed through to the egress policy. */
@@ -537,7 +537,7 @@ export class PluginViewHost {
`${PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX}${encodeURIComponent(request.locale)}`,
`--pi-plugin-panel-theme=${request.theme}`,
PLUGIN_PANEL_EMBEDDED_ARGUMENT,
- ...(pluginViewKey(request.pluginId, request.viewId) === FILE_LINES_VIEW_KEY
+ ...(request.composerFileLines
? [PLUGIN_PANEL_COMPOSER_FILE_LINES_ARGUMENT]
: []),
],
diff --git a/apps/desktop/test/file-line-bridge.test.mjs b/apps/desktop/test/file-line-bridge.test.mjs
index 998e8462d..e5196c9ca 100644
--- a/apps/desktop/test/file-line-bridge.test.mjs
+++ b/apps/desktop/test/file-line-bridge.test.mjs
@@ -43,12 +43,12 @@ test("an installed File Manager can add lines only to the session that authorize
assert.deepEqual(await addFileLinesFromView(pluginId, 123, payload, bridge), { ok: true });
assert.deepEqual(deliveries, [{ sessionId: "selected", reference: payload }]);
- await assert.rejects(addFileLinesFromView(pluginId, 321, payload, bridge), /outside the active project or session/);
+ await assert.rejects(addFileLinesFromView(pluginId, 321, payload, bridge), /no longer active/);
loaded.permissions.delete("fs.read");
- await assert.rejects(addFileLinesFromView(pluginId, 123, payload, bridge), /outside the active project or session/);
+ await assert.rejects(addFileLinesFromView(pluginId, 123, payload, bridge), /no longer active/);
loaded.permissions.add("fs.read");
record.enabled = false;
- await assert.rejects(addFileLinesFromView(pluginId, 123, payload, bridge), /no longer active/);
+ await assert.rejects(addFileLinesFromView(pluginId, 123, payload, bridge), /not enabled in the Host registry/);
record.enabled = true;
const pending = addFileLinesFromView(pluginId, 123, payload, bridge);
diff --git a/apps/desktop/test/plugin-provider-catalog-ipc.test.mjs b/apps/desktop/test/plugin-provider-catalog-ipc.test.mjs
index b5bff9e61..61f65716f 100644
--- a/apps/desktop/test/plugin-provider-catalog-ipc.test.mjs
+++ b/apps/desktop/test/plugin-provider-catalog-ipc.test.mjs
@@ -6,6 +6,7 @@ import { IPC } from "../../../packages/shared/src/protocol.ts";
import { pluginProviderCatalogEntries } from "../electron/main/plugin-provider-catalog.ts";
import { createSessionPushGate } from "../electron/main/plugin-session-push-gate.ts";
import { normalizeLauncherLaunch } from "../electron/main/ipc/plugin-launcher-ipc.ts";
+import * as fileLineReference from "../electron/main/file-line-reference.ts";
/** Load the real main-process registration function with unrelated hosts stubbed. */
function loadPluginUiIpc({ gateFactory = () => () => ({ ignored: false }) } = {}) {
@@ -29,6 +30,7 @@ function loadPluginUiIpc({ gateFactory = () => () => ({ ignored: false }) } = {}
"../plugin-runtime": { resolveInsidePlugin: () => "/plugin/index.html" },
"../plugin-view-host": { pluginViewKey: (...parts) => parts.join("/") },
"../plugin-panel-host": {},
+ "../file-line-reference": fileLineReference,
"../plugin-provider-catalog": { pluginProviderCatalogEntries },
"../plugin-session-push-gate": { createSessionPushGate: gateFactory },
/**
@@ -48,6 +50,47 @@ function loadPluginUiIpc({ gateFactory = () => () => ({ ignored: false }) } = {}
return module.exports.registerPluginUiIpc;
}
+test("only the enabled, registered File Manager with both grants advertises Composer line references", async () => {
+ const handlers = new Map();
+ const views = [];
+ const loaded = {
+ development: false,
+ disposing: false,
+ permissions: new Set(["ui.view", "fs.read"]),
+ path: "/plugins/file-manager",
+ manifest: { version: "0.9.0", contributes: { views: [{ id: "manager", entry: "index.html" }] } },
+ };
+ const record = { id: "pi.file-manager", enabled: true, version: "0.9.0" };
+ const host = { call: async () => ({ plugins: [record] }) };
+ loadPluginUiIpc()({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ plugins: { getLoaded: () => loaded },
+ getHost: () => host,
+ pluginViews: { open: (view) => views.push(view) },
+ pluginActiveInProject: () => true,
+ currentWorkspacePath: () => "/project",
+ getUpdaterLocale: () => "en",
+ getPluginPanelTheme: () => "dark",
+ });
+ const open = async (pluginId = "pi.file-manager") => {
+ await handlers.get(IPC.invoke.pluginViewOpen)({ pluginId, viewId: "manager" });
+ return views.at(-1).composerFileLines;
+ };
+ assert.equal(await open(), true);
+ assert.equal(await open("other.plugin"), false);
+ loaded.development = true;
+ assert.equal(await open(), false);
+ loaded.development = false;
+ record.enabled = false;
+ assert.equal(await open(), false);
+ record.enabled = true;
+ record.version = "0.8.0";
+ assert.equal(await open(), false);
+ record.version = "0.9.0";
+ loaded.permissions.delete("fs.read");
+ assert.equal(await open(), false);
+});
+
test("the plugin Add Service IPC returns declared categories through the Host handler", async () => {
const handlers = new Map();
const plugin = (id, name, permissions, category) => ({
diff --git a/docs/adr/file-manager-line-references.md b/docs/adr/file-manager-line-references.md
index b261f31cf..0baedfd89 100644
--- a/docs/adr/file-manager-line-references.md
+++ b/docs/adr/file-manager-line-references.md
@@ -22,8 +22,9 @@ The selected text is never used as the model payload for a reference. Main
validates the reference path against the Session project folders. At prompt
execution, the Agent runtime invokes the existing Read tool with the inclusive
range converted to its zero-based offset and line count. The Host continues
-to authorize the tool call and enforce its output limits. The bounded result
-or read failure is included as file context in the provider prompt.
+to authorize the tool call and enforce its output limits. A successful result
+is included as file context. A blocked or failed read is reported separately
+in the provider prompt. Prefetches do not create assistant tool history.
## Consequences
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index f06ae9b1f..b8d8d1dfe 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -162,7 +162,10 @@ transcript-read API. The core runs no title completion of its own.
A validated File Manager `lineRange` travels as file attachment metadata.
The runtime executes one workspace-only Read per distinct range through
the normal tool hooks and quotes its bounded result as file context for
- the provider turn. Restoring the reference does not run a Read.
+ the provider turn. Permission blocks and read failures use a separate
+ `file_reference_error` block with a `blocked` or `failed` status. The
+ prefetch runs outside assistant tool batches and creates no tool transcript
+ row. Restoring the reference preserves its path and range metadata.
7. snapshot the effective shell ID and dialect for the turn
8. start pi turn with the resolved session configuration and effective
thinking level; HTTP 429 setup and stream failures use the runtime-owned
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 94623220d..b7ecf416e 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -20113,11 +20113,18 @@ the same chip appears, while paste into an ordinary editor yields the selected
text. End a selection at the start of the next line and verify that line is
excluded. A one-line selection displays one line number.
+Open the same view from a development-loaded File Manager and verify that
+the host does not advertise `composerFileLines`.
+
Insert an unsaved line before the range. Copying still pastes the original
text and the selection menu has no **Add to chat** action. Save the file and
verify that both actions use the new saved line numbers.
Change the saved text after adding the chip, then send it. Observe one scoped
-Read with offset 84 and limit 2, the saved result in the model request, and a
-normal failure when the file disappears. Repeat with a queued turn and a
-project switch. A different project's clipboard metadata cannot add the chip.
+Read with offset 84 and limit 2 and the saved result in the model request.
+Restart and verify the reference is still visible and there is no synthetic
+Read in the transcript or restored model history. Submit again after deleting
+the file and verify a failed reference marker in the model request. Repeat
+with Read permission denied and verify a blocked marker. Neither marker is
+quoted as file content. Repeat with a queued turn and a project switch. A
+different project's clipboard metadata cannot add the chip.
diff --git a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
index 59dbe8aa4..895593b89 100644
--- a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
+++ b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
@@ -145,7 +145,9 @@ Panel bridge fixed channels also include `app.setTheme`, `themes.upsert`,
no file or session access.
The docked File Manager (`pi.file-manager/manager`) receives
-`pluginBridge.capabilities.composerFileLines`. It can invoke
+`pluginBridge.capabilities.composerFileLines` when its loaded version matches
+an enabled Host registry entry and holds both `ui.view` and `fs.read`.
+Development-loaded views do not advertise the capability. An eligible view can invoke
`composer.addFileLines` with `{ workspace, path, start, end }`, where paths are
absolute and lines are one-based and inclusive. The host requires the visible
view of an enabled, registered File Manager with `ui.view` and `fs.read`, a
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 4f091f75b..bcb7b3e20 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -228,10 +228,14 @@ function createRuntime(
}
it("reads each explicit file line range once before passing its text to the model", async () => {
- const call = vi.fn(async (method: string) => method === "tools.execute"
- ? { ok: true, content: { content: "85: saved first\n86: saved second", totalLines: 100 } }
- : undefined);
- const runtime = createRuntime({ host: { call }, projectPath: "/project", workspaceRoot: "/project" });
+ const call = vi.fn(async (method: string, _params: unknown) => {
+ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: true };
+ if (method === "tools.fileBatchRegister") return { ticket: "test-ticket" };
+ if (method === "tools.fileBatchSeal") return { ok: true };
+ if (method === "tools.execute") return { ok: true, content: { content: "85: saved first\n86: saved second", totalLines: 100 } };
+ });
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ host: { call }, onEvent, projectPath: "/project", workspaceRoot: "/project" });
const agent = (runtime as unknown as { agent: Agent }).agent;
const model = vi.spyOn(agent, "prompt").mockResolvedValue(undefined);
const reference = { kind: "file" as const, path: "/project/src/gpt.py", name: "gpt.py", lineRange: { start: 85, end: 86 } };
@@ -250,6 +254,31 @@ it("reads each explicit file line range once before passing its text to the mode
content: expect.stringContaining("85: saved first"),
}));
expect(model).toHaveBeenCalledWith(expect.objectContaining({ content: expect.stringContaining("86: saved second") }));
+ expect(call.mock.calls.map(([method]) => method)).not.toContain("tools.fileBatchRegister");
+ expect(onEvent.mock.calls.map(([event]) => event.type)).not.toContain("tool_end");
+ } finally {
+ await runtime.dispose();
+ }
+});
+
+it.each([
+ { denied: true, status: "blocked", reason: "Read denied" },
+ { denied: false, status: "failed", reason: "File not found" },
+])("labels a $status file reference separately from file content", async ({ denied, status, reason }) => {
+ const call = vi.fn(async (method: string) => {
+ if (method === "tools.execute") return { ok: false, denied, content: reason };
+ });
+ const runtime = createRuntime({ host: { call }, projectPath: "/project", workspaceRoot: "/project" });
+ const agent = (runtime as unknown as { agent: Agent }).agent;
+ const model = vi.spyOn(agent, "prompt").mockResolvedValue(undefined);
+ const reference = { kind: "file" as const, path: "/project/sample.txt", name: "sample.txt", lineRange: { start: 2, end: 2 } };
+ try {
+ await runtime.prompt({ text: "Explain this line", attachments: [reference] });
+ const message = model.mock.calls[0]?.[0];
+ expect(message).toMatchObject({
+ content: expect.stringContaining(`status="${status}">\n${reason}\n</file_reference_error>`),
+ });
+ expect(message).not.toMatchObject({ content: expect.stringContaining("<file_lines") });
} finally {
await runtime.dispose();
}
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index c13cbb991..e07551e8e 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -334,6 +334,8 @@ export type RuntimePromptAttachment = Omit<AgentPromptAttachment, "kind"> & {
data?: string;
/** Bounded excerpt of a referenced conversation (`kind: "session"`). */
text?: string;
+ /** Set by the runtime when an explicit line reference could not be read. */
+ fileReferenceError?: "blocked" | "failed";
};
export type RuntimePrompt = {
@@ -359,7 +361,13 @@ function promptText(input: RuntimePrompt): string {
.filter((block): block is string => block !== null);
const fileLines = attachments.filter(attachment => attachment.lineRange && attachment.text !== undefined)
.slice(0, MAX_FILE_LINE_REFERENCES)
- .map(attachment => `<file_lines source="${escapeAttribute(fileLineLabel(attachment.path, attachment.lineRange!))}">\n${attachment.text!.replaceAll("<", "&lt;")}\n</file_lines>`);
+ .map(attachment => {
+ const source = escapeAttribute(fileLineLabel(attachment.path, attachment.lineRange!));
+ const text = attachment.text!.replaceAll("<", "&lt;");
+ return attachment.fileReferenceError
+ ? `<file_reference_error source="${source}" status="${attachment.fileReferenceError}">\n${text}\n</file_reference_error>`
+ : `<file_lines source="${source}">\n${text}\n</file_lines>`;
+ });
const references = [...sessions, ...fileLines];
return references.length
? `${input.text}\n\n${references.join("\n\n")}`.trim()
@@ -2039,7 +2047,7 @@ export class DesktopAgentRuntime {
* signal it was handed never fires, or the stop RPC stays pending forever.
*/
private activeToolAborts = new Set<() => void>();
- private fileLineReadCalls = new Set<string>();
+ private fileLineReadCalls = new Map<string, { blocked: boolean }>();
private hostCloseUnsubscribe?: () => void;
private turnSubagentUsage?: MessageUsage;
private compactionRequestShape?: CompactionRequestShape;
@@ -2664,7 +2672,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const blocked = await this.extensionToolCall(context);
if (blocked?.block) return blocked;
await this.preparePathToolCall(context);
- await this.registerBatchCall(context);
+ // Composer prefetches run serially outside the assistant's tool batches.
+ if (!this.fileLineReadCalls.has(context.toolCall.id)) await this.registerBatchCall(context);
return undefined;
}
const enterKind = enterToolKind(context.toolCall.name);
@@ -3718,6 +3727,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
if (executionFailed) throw executionError;
if (!result) throw new Error("tool execution returned no result");
const recordParams = isRecord(params) ? params : undefined;
+ const fileLineRead = this.fileLineReadCalls.get(toolCallId);
+ if (fileLineRead && (result.denied || result.errorCode === "PERMISSION_DENIED")) {
+ fileLineRead.blocked = true;
+ }
const failedToolExecution = !result.ok && result.denied !== true;
const failedEditPath =
toolName === "Edit" &&
@@ -9170,7 +9183,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
/** Execute the ordinary Host Read for explicit composer references before model input. */
async resolveFileLineReferences(input: RuntimePrompt): Promise<RuntimePrompt> {
if (!input.attachments?.some(attachment => attachment.lineRange !== undefined)) return input;
- const read = this.activeTools().find(tool => tool.name === "Read");
+ const read = this.activeTools().find(tool => tool.name === "Read" && this.builtinTools.has(tool));
const turnId = this.turnId;
const attachments: RuntimePromptAttachment[] = [];
const seen = new Set<string>();
@@ -9193,8 +9206,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const toolCall = { type: "toolCall" as const, id: randomUUID(), name: "Read", arguments: args };
const timestamp = Date.now();
const tools = read ? [read] : [];
- this.emit({ type: "tool_start", toolCallId: toolCall.id, toolName: toolCall.name, args }, turnId);
- this.fileLineReadCalls.add(toolCall.id);
+ const prefetch = { blocked: !read };
+ this.fileLineReadCalls.set(toolCall.id, prefetch);
const { result, isError } = await runToolCall(toolCall, {
tools,
assistantMessage: {
@@ -9202,13 +9215,19 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
model: this.model.id, usage: usageToPi(undefined), stopReason: "toolUse", timestamp,
},
context: { messages: this.agent.state.messages, tools },
- beforeToolCall: context => this.beforeToolCall(context),
+ beforeToolCall: async context => {
+ const decision = await this.beforeToolCall(context);
+ if (decision?.block) prefetch.blocked = true;
+ return decision;
+ },
afterToolCall: context => this.afterToolCall(context),
}).finally(() => this.fileLineReadCalls.delete(toolCall.id));
- this.emit({ type: "tool_end", toolCallId: toolCall.id, result, isError }, turnId);
const text = result.content.flatMap(part => part.type === "text" ? [part.text] : []).join("\n");
if (this.runCancelled || this.disposed || turnId !== this.turnId) throw turnAbortedError("Turn ended during file reference reads");
- attachments.push({ ...attachment, lineRange: range, text });
+ attachments.push({
+ ...attachment, lineRange: range, text,
+ fileReferenceError: isError ? (prefetch.blocked ? "blocked" : "failed") : undefined,
+ });
}
return { ...input, attachments };
}
diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.ts
index c82336a52..217e20ca0 100644
--- a/packages/shared/src/types/messages.ts
+++ b/packages/shared/src/types/messages.ts
@@ -52,7 +52,7 @@ export type MessageAttachment = {
lineRange?: import("../file-line-reference.js").FileLineRange;
kind: "image" | "file" | "session";
name: string;
- /** Workspace-relative path, session-scratch absolute path, or a session id. */
+ /** Workspace-relative path, absolute scratch or project line-reference path, or a session id. */
ref: string;
mimeType?: string;
size?: number;