A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): host-owned extension ctx timers (#2095)
Sebastian Müller5d66ab91326d
diff --git a/packages/coding-agent/.changes/res-1315-extension-host-timers.md b/packages/coding-agent/.changes/res-1315-extension-host-timers.mdnew file mode 100644index 0000000000..d5f84ba2da--- /dev/null+++ b/packages/coding-agent/.changes/res-1315-extension-host-timers.md@@ -0,0 +1 @@+- Added host-owned `ctx.setTimeout`/`ctx.setInterval` (plus matching clears) for extensions: throwing callbacks are reported through the extension error boundary instead of crashing the process, and pending timers are cancelled on unload. Raw global timers remain unsupported for scheduling extension work.diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.mdindex be11c260d5..6ec2c9923c 100644--- a/packages/coding-agent/README.md+++ b/packages/coding-agent/README.md@@ -386,6 +386,8 @@ export default function (pi: ExtensionAPI) {The default export can also be `async`. Prime Agent waits for async extension factories before startup continues, which is useful for one-time initialization such as fetching remote model lists before calling `pi.registerProvider()`.+Schedule timers via `ctx.setTimeout`/`ctx.setInterval` (error-isolated, auto-cancelled on unload); raw global timers are unsupported for scheduling extension work.+**What's possible:**- Custom tools (or replace built-in tools entirely)- Additional orchestration workflows and plan modesdiff --git a/packages/coding-agent/docs/extensions.md b/packages/coding-agent/docs/extensions.mdindex 637386beb2..fd6e61d380 100644--- a/packages/coding-agent/docs/extensions.md+++ b/packages/coding-agent/docs/extensions.md@@ -1005,6 +1005,20 @@ pi.on("before_agent_start", (event, ctx) => {});```+### ctx.setTimeout() / ctx.setInterval()++Host-owned timers for scheduling extension work. Unlike the raw globals, a throwing (or rejecting) callback is reported through the extension error boundary instead of crashing the process, and all pending timers are cancelled automatically when the extension host unloads (session dispose, reload, or replacement). Handles work with `ctx.clearTimeout()` / `ctx.clearInterval()`.++Raw global `setTimeout`/`setInterval` are unsupported for scheduling extension work: an uncaught error in a global timer callback can kill the whole process (including daemon session workers), and nothing cancels them on unload.++```typescript+pi.on("session_start", (_event, ctx) => {+ const timer = ctx.setInterval(() => pollSomething(), 2000);+ // Optional: unload cancels it automatically, or clear it yourself:+ // ctx.clearInterval(timer);+});+```+## ExtensionCommandContextCommand handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.@@ -2187,7 +2201,7 @@ For more control (e.g., to distinguish timeout from user cancel), use `AbortSign```typescriptconst controller = new AbortController();-const timeoutId = setTimeout(() => controller.abort(), 5000);+const timeoutId = ctx.setTimeout(() => controller.abort(), 5000);const confirmed = await ctx.ui.confirm("Timed Confirmation",@@ -2195,7 +2209,7 @@ const confirmed = await ctx.ui.confirm({ signal: controller.signal });-clearTimeout(timeoutId);+ctx.clearTimeout(timeoutId);if (confirmed) {// User confirmeddiff --git a/packages/coding-agent/examples/extensions/border-status-editor.ts b/packages/coding-agent/examples/extensions/border-status-editor.tsindex dce9e59596..2ae5d108f6 100644--- a/packages/coding-agent/examples/extensions/border-status-editor.ts+++ b/packages/coding-agent/examples/extensions/border-status-editor.ts@@ -75,31 +75,31 @@ export default function (pi: ExtensionAPI) {let activeTui: TUI | undefined;const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];- const stopSpinner = () => {+ const stopSpinner = (ctx: ExtensionContext) => {if (spinnerTimer) {- clearInterval(spinnerTimer);+ ctx.clearInterval(spinnerTimer);spinnerTimer = undefined;}};- pi.on("agent_start", () => {+ pi.on("agent_start", (_event, ctx) => {isWorking = true;- stopSpinner();- spinnerTimer = setInterval(() => {+ stopSpinner(ctx);+ spinnerTimer = ctx.setInterval(() => {spinnerIndex = (spinnerIndex + 1) % spinnerFrames.length;activeTui?.requestRender();}, 80);activeTui?.requestRender();});- pi.on("agent_end", () => {+ pi.on("agent_end", (_event, ctx) => {isWorking = false;- stopSpinner();+ stopSpinner(ctx);activeTui?.requestRender();});- pi.on("session_shutdown", () => {- stopSpinner();+ pi.on("session_shutdown", (_event, ctx) => {+ stopSpinner(ctx);activeTui = undefined;});diff --git a/packages/coding-agent/examples/extensions/mac-system-theme.ts b/packages/coding-agent/examples/extensions/mac-system-theme.tsindex c2095cf78f..d5ef04865b 100644--- a/packages/coding-agent/examples/extensions/mac-system-theme.ts+++ b/packages/coding-agent/examples/extensions/mac-system-theme.ts@@ -29,7 +29,7 @@ export default function (pi: ExtensionAPI) {let currentTheme = (await isDarkMode()) ? "dark" : "light";ctx.ui.setTheme(currentTheme);- intervalId = setInterval(async () => {+ intervalId = ctx.setInterval(async () => {const newTheme = (await isDarkMode()) ? "dark" : "light";if (newTheme !== currentTheme) {currentTheme = newTheme;@@ -38,9 +38,9 @@ export default function (pi: ExtensionAPI) {}, 2000);});- pi.on("session_shutdown", () => {+ pi.on("session_shutdown", (_event, ctx) => {if (intervalId) {- clearInterval(intervalId);+ ctx.clearInterval(intervalId);intervalId = null;}});diff --git a/packages/coding-agent/examples/extensions/timed-confirm.ts b/packages/coding-agent/examples/extensions/timed-confirm.tsindex 1ab86e55b2..7ec65ca259 100644--- a/packages/coding-agent/examples/extensions/timed-confirm.ts+++ b/packages/coding-agent/examples/extensions/timed-confirm.ts@@ -46,7 +46,7 @@ export default function (pi: ExtensionAPI) {description: "Show a timed confirm using AbortSignal (manual approach)",handler: async (_args, ctx) => {const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 5000);+ const timeoutId = ctx.setTimeout(() => controller.abort(), 5000);ctx.ui.notify("Dialog will auto-cancel in 5 seconds...", "info");@@ -56,7 +56,7 @@ export default function (pi: ExtensionAPI) {{ signal: controller.signal },);- clearTimeout(timeoutId);+ ctx.clearTimeout(timeoutId);if (confirmed) {ctx.ui.notify("Confirmed by user!", "info");diff --git a/packages/coding-agent/examples/extensions/titlebar-spinner.ts b/packages/coding-agent/examples/extensions/titlebar-spinner.tsindex 51467acb6d..94b92792c8 100644--- a/packages/coding-agent/examples/extensions/titlebar-spinner.ts+++ b/packages/coding-agent/examples/extensions/titlebar-spinner.ts@@ -25,7 +25,7 @@ export default function (pi: ExtensionAPI) {function stopAnimation(ctx: ExtensionContext) {if (timer) {- clearInterval(timer);+ ctx.clearInterval(timer);timer = null;}frameIndex = 0;@@ -34,7 +34,7 @@ export default function (pi: ExtensionAPI) {function startAnimation(ctx: ExtensionContext) {stopAnimation(ctx);- timer = setInterval(() => {+ timer = ctx.setInterval(() => {const frame = BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length];const cwd = path.basename(process.cwd());const session = pi.getSessionName();diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex edd6e1c10c..b9b06fa239 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -5709,7 +5709,7 @@ export class AgentSession {const command = this._extensionRunner.getCommand(commandName);if (!command) return undefined;- const context = this._extensionRunner.createCommandContext();+ const context = this._extensionRunner.createCommandContext(command.sourceInfo.path);return Promise.resolve().then(() => command.handler(args, context))@@ -10096,6 +10096,7 @@ export class AgentSession {extensionsResult.runtime.getExecEnv = this._execEnvProvider;}+ const previousRunner: ExtensionRunner | undefined = this._extensionRunner;this._extensionRunner = new ExtensionRunner(extensionsResult.extensions,extensionsResult.runtime,@@ -10103,6 +10104,14 @@ export class AgentSession {this.sessionManager,this._modelRegistry,);+ // Retire only when the extension world restarts (reload); runtime-only rebuilds adopt the timer host instead, so session_start timers survive and unload still cancels them.+ if (previousRunner) {+ if (previousRunner.builtFromSameExtensions(extensionsResult.extensions)) {+ this._extensionRunner.adoptHostTimers(previousRunner);+ } else {+ previousRunner.retire();+ }+ }if (this._extensionRunnerRef) {this._extensionRunnerRef.current = this._extensionRunner;}@@ -13431,9 +13440,10 @@ export class AgentSession {// =========================================================================createReplacedSessionContext(): ReplacedSessionContext {+ // The initiating extension is not in scope here; label timers with the context kind instead.const context = Object.defineProperties({},- Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()),+ Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext("<session-replacement>")),) as ReplacedSessionContext;context.sendMessage = (message, options) => this.sendCustomMessage(message, options);context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);diff --git a/packages/coding-agent/src/core/extensions/runner.ts b/packages/coding-agent/src/core/extensions/runner.tsindex 1d94d88efc..778be1ea49 100644--- a/packages/coding-agent/src/core/extensions/runner.ts+++ b/packages/coding-agent/src/core/extensions/runner.ts@@ -257,6 +257,12 @@ export class ExtensionRunner {private shortcutDiagnostics: ResourceDiagnostic[] = [];private commandDiagnostics: ResourceDiagnostic[] = [];private staleMessage: string | undefined;+ // WeakRefs let GC drop globally cleared timers; pending timers stay reachable via Node's active-timer list.+ private timerHost: {+ current: ExtensionRunner;+ timers: Set<WeakRef<ReturnType<typeof setTimeout>>>;+ refs: WeakMap<ReturnType<typeof setTimeout>, WeakRef<ReturnType<typeof setTimeout>>>;+ };constructor(extensions: Extension[],@@ -265,6 +271,7 @@ export class ExtensionRunner {sessionManager: SessionManager,modelRegistry: ModelRegistry,) {+ this.timerHost = { current: this, timers: new Set(), refs: new WeakMap() };this.extensions = extensions;this.runtime = runtime;this.uiContext = noOpUIContext;@@ -471,11 +478,35 @@ export class ExtensionRunner {message = "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",): void {if (!this.staleMessage) {- this.staleMessage = message;+ this.retire(message);this.runtime.invalidate(message);}}+ /** True when this runner was built from exactly this extensions load (identity check). */+ builtFromSameExtensions(extensions: Extension[]): boolean {+ return this.extensions === extensions;+ }++ /** Take over the previous runner's timer host: adopted timers report through, and are gated by, this runner. */+ adoptHostTimers(previous: ExtensionRunner): void {+ this.timerHost = previous.timerHost;+ this.timerHost.current = this;+ }++ /** Retire a replaced runner: ctx goes stale and no host timer outlives it, while the possibly shared/reused runtime stays live. */+ retire(+ message = "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",+ ): void {+ if (this.staleMessage) return;+ this.staleMessage = message;+ for (const ref of this.timerHost.timers) {+ const handle = ref.deref();+ if (handle) clearTimeout(handle);+ }+ this.timerHost.timers.clear();+ }+private assertActive(): void {if (this.staleMessage) {throw new Error(this.staleMessage);@@ -493,6 +524,75 @@ export class ExtensionRunner {}}+ /** Host-owned ctx timers: callbacks run through the same error boundary as event handlers. */+ createTimerBindings(+ ownerPath?: string,+ ): Pick<ExtensionContext, "setTimeout" | "clearTimeout" | "setInterval" | "clearInterval"> {+ return {+ setTimeout: (callback, ms) => {+ this.assertActive();+ return this.scheduleHostTimer("setTimeout", ownerPath, callback, ms);+ },+ clearTimeout: (handle) => this.clearHostTimer(handle),+ setInterval: (callback, ms) => {+ this.assertActive();+ return this.scheduleHostTimer("setInterval", ownerPath, callback, ms);+ },+ clearInterval: (handle) => this.clearHostTimer(handle),+ };+ }++ private scheduleHostTimer(+ kind: "setTimeout" | "setInterval",+ ownerPath: string | undefined,+ callback: () => void | Promise<void>,+ ms: number,+ ): ReturnType<typeof setTimeout> {+ // Scheduling authority is the current host owner: a ctx captured before a reload cannot arm work for an unloaded extension world.+ this.timerHost.current.assertActive();+ const host = this.timerHost;+ const run = () => {+ // A fired timeout is dead: clearTimeout makes handle.refresh() a permanent no-op, so nothing revives it past unload.+ if (kind === "setTimeout") {+ this.untrackHostTimer(handle);+ clearTimeout(handle);+ }+ try {+ // Promise.resolve is thenable-safe: rejections from cross-realm promises and userland thenables land in the boundary instead of an unhandled rejection.+ Promise.resolve(callback()).catch((err) => host.current.emitHostTimerError(kind, ownerPath, err));+ } catch (err) {+ host.current.emitHostTimerError(kind, ownerPath, err);+ }+ };+ const handle = kind === "setTimeout" ? setTimeout(run, ms) : setInterval(run, ms);+ // No sweep here: dead WeakRef shells from globally cleared timers are tiny and freed at unload; sweeping per schedule would be quadratic.+ const ref = new WeakRef(handle);+ host.timers.add(ref);+ host.refs.set(handle, ref);+ return handle;+ }++ private untrackHostTimer(handle: ReturnType<typeof setTimeout>): void {+ const ref = this.timerHost.refs.get(handle);+ if (ref) this.timerHost.timers.delete(ref);+ this.timerHost.refs.delete(handle);+ }++ private emitHostTimerError(kind: "setTimeout" | "setInterval", ownerPath: string | undefined, err: unknown): void {+ this.emitError({+ extensionPath: ownerPath ?? "unknown",+ event: kind,+ error: err instanceof Error ? err.message : String(err),+ stack: err instanceof Error ? err.stack : undefined,+ });+ }++ private clearHostTimer(handle: ReturnType<typeof setTimeout> | undefined): void {+ if (handle === undefined) return;+ this.untrackHostTimer(handle);+ clearTimeout(handle);+ }+hasHandlers(eventType: string): boolean {for (const ext of this.extensions) {const handlers = ext.handlers.get(eventType);@@ -574,10 +674,11 @@ export class ExtensionRunner {* Create an ExtensionContext for use in event handlers and tool execution.* Context values are resolved at call time, so changes via bindCore/bindUI are reflected.*/- createContext(): ExtensionContext {+ createContext(ownerPath?: string): ExtensionContext {const runner = this;const getModel = this.getModel;return {+ ...this.createTimerBindings(ownerPath),get ui() {runner.assertActive();return runner.uiContext;@@ -637,13 +738,13 @@ export class ExtensionRunner {};}- createCommandContext(): ExtensionCommandContext {+ createCommandContext(ownerPath?: string): ExtensionCommandContext {// Use property descriptors instead of object spread so the guarded getters from// createContext() stay lazy. A spread would eagerly read them once and freeze the// old values into the returned object, bypassing stale-instance checks.const context = Object.defineProperties({},- Object.getOwnPropertyDescriptors(this.createContext()),+ Object.getOwnPropertyDescriptors(this.createContext(ownerPath)),) as ExtensionCommandContext;context.waitForIdle = () => {this.assertActive();@@ -683,12 +784,12 @@ export class ExtensionRunner {}async emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {- const ctx = this.createContext();let result: SessionBeforeEventResult | undefined;for (const ext of this.extensions) {const handlers = ext.handlers.get(event.type);if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {try {@@ -717,13 +818,13 @@ export class ExtensionRunner {}async emitMessageEnd(event: MessageEndEvent): Promise<AgentMessage | undefined> {- const ctx = this.createContext();let currentMessage = event.message;let modified = false;for (const ext of this.extensions) {const handlers = ext.handlers.get("message_end");if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {try {@@ -759,13 +860,13 @@ export class ExtensionRunner {}async emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {- const ctx = this.createContext();const currentEvent: ToolResultEvent = { ...event };let modified = false;for (const ext of this.extensions) {const handlers = ext.handlers.get("tool_result");if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {try {@@ -809,12 +910,12 @@ export class ExtensionRunner {}async emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {- const ctx = this.createContext();let result: ToolCallEventResult | undefined;for (const ext of this.extensions) {const handlers = ext.handlers.get("tool_call");if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {const handlerResult = await handler(event, ctx);@@ -832,11 +933,10 @@ export class ExtensionRunner {}async emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {- const ctx = this.createContext();-for (const ext of this.extensions) {const handlers = ext.handlers.get("user_bash");if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {try {@@ -861,12 +961,12 @@ export class ExtensionRunner {}async emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {- const ctx = this.createContext();let currentMessages = structuredClone(messages);for (const ext of this.extensions) {const handlers = ext.handlers.get("context");if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {try {@@ -893,12 +993,12 @@ export class ExtensionRunner {}async emitBeforeProviderRequest(payload: unknown): Promise<unknown> {- const ctx = this.createContext();let currentPayload = payload;for (const ext of this.extensions) {const handlers = ext.handlers.get("before_provider_request");if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {try {@@ -933,20 +1033,20 @@ export class ExtensionRunner {systemPromptOptions: BuildSystemPromptOptions,): Promise<BeforeAgentStartCombinedResult | undefined> {let currentSystemPrompt = systemPrompt;- const ctx = Object.defineProperties(- {},- Object.getOwnPropertyDescriptors(this.createContext()),- ) as ExtensionContext;- ctx.getSystemPrompt = () => {- this.assertActive();- return currentSystemPrompt;- };const messages: NonNullable<BeforeAgentStartEventResult["message"]>[] = [];let systemPromptModified = false;for (const ext of this.extensions) {const handlers = ext.handlers.get("before_agent_start");if (!handlers || handlers.length === 0) continue;+ const ctx = Object.defineProperties(+ {},+ Object.getOwnPropertyDescriptors(this.createContext(ext.path)),+ ) as ExtensionContext;+ ctx.getSystemPrompt = () => {+ this.assertActive();+ return currentSystemPrompt;+ };for (const handler of handlers) {try {@@ -1000,7 +1100,6 @@ export class ExtensionRunner {promptPaths: Array<{ path: string; extensionPath: string }>;themePaths: Array<{ path: string; extensionPath: string }>;}> {- const ctx = this.createContext();const skillPaths: Array<{ path: string; extensionPath: string }> = [];const promptPaths: Array<{ path: string; extensionPath: string }> = [];const themePaths: Array<{ path: string; extensionPath: string }> = [];@@ -1008,6 +1107,7 @@ export class ExtensionRunner {for (const ext of this.extensions) {const handlers = ext.handlers.get("resources_discover");if (!handlers || handlers.length === 0) continue;+ const ctx = this.createContext(ext.path);for (const handler of handlers) {try {@@ -1042,11 +1142,11 @@ export class ExtensionRunner {/** Emit input event. Transforms chain, "handled" short-circuits. */async emitInput(text: string, images: ImageContent[] | undefined, source: InputSource): Promise<InputEventResult> {- const ctx = this.createContext();let currentText = text;let currentImages = images;for (const ext of this.extensions) {+ const ctx = this.createContext(ext.path);for (const handler of ext.handlers.get("input") ?? []) {try {const event: InputEvent = { type: "input", text: currentText, images: currentImages, source };diff --git a/packages/coding-agent/src/core/extensions/types.ts b/packages/coding-agent/src/core/extensions/types.tsindex 21abe7a16a..22b6e21f0a 100644--- a/packages/coding-agent/src/core/extensions/types.ts+++ b/packages/coding-agent/src/core/extensions/types.ts@@ -308,6 +308,18 @@ export interface ExtensionContext {compact(options?: CompactOptions): void;/** Get the current effective system prompt. */getSystemPrompt(): string;+ /**+ * Schedule a callback on a host-owned timer. Unlike the global `setTimeout`, thrown+ * errors are reported through the extension error boundary instead of crashing the+ * process, and pending timers are cancelled when the extension host unloads.+ */+ setTimeout(callback: () => void | Promise<void>, ms: number): ReturnType<typeof setTimeout>;+ /** Cancel a timer created with `ctx.setTimeout`. Accepts undefined like the global `clearTimeout`. */+ clearTimeout(handle: ReturnType<typeof setTimeout> | undefined): void;+ /** Schedule a repeating callback on a host-owned timer. Same guarantees as `ctx.setTimeout`. */+ setInterval(callback: () => void | Promise<void>, ms: number): ReturnType<typeof setInterval>;+ /** Cancel a timer created with `ctx.setInterval`. Accepts undefined like the global `clearInterval`. */+ clearInterval(handle: ReturnType<typeof setInterval> | undefined): void;}/**diff --git a/packages/coding-agent/src/core/extensions/wrapper.ts b/packages/coding-agent/src/core/extensions/wrapper.tsindex 3a852f0e97..65a8c86d44 100644--- a/packages/coding-agent/src/core/extensions/wrapper.ts+++ b/packages/coding-agent/src/core/extensions/wrapper.ts@@ -6,7 +6,7 @@*/import type { AgentTool } from "@earendil-works/pi-agent-core";-import { wrapToolDefinition, wrapToolDefinitions } from "../tools/tool-definition-wrapper.js";+import { wrapToolDefinition } from "../tools/tool-definition-wrapper.js";import type { ExtensionRunner } from "./runner.js";import type { RegisteredTool } from "./types.js";@@ -22,7 +22,9 @@ function toRunnerGetter(source: RunnerSource): () => ExtensionRunner {*/export function wrapRegisteredTool(registeredTool: RegisteredTool, runner: RunnerSource): AgentTool {const getRunner = toRunnerGetter(runner);- return wrapToolDefinition(registeredTool.definition, () => getRunner().createContext());+ return wrapToolDefinition(registeredTool.definition, () =>+ getRunner().createContext(registeredTool.sourceInfo.path),+ );}/**@@ -30,9 +32,5 @@ export function wrapRegisteredTool(registeredTool: RegisteredTool, runner: Runne* Uses the runner's createContext() for consistent context across tools and event handlers.*/export function wrapRegisteredTools(registeredTools: RegisteredTool[], runner: RunnerSource): AgentTool[] {- const getRunner = toRunnerGetter(runner);- return wrapToolDefinitions(- registeredTools.map((registeredTool) => registeredTool.definition),- () => getRunner().createContext(),- );+ return registeredTools.map((registeredTool) => wrapRegisteredTool(registeredTool, runner));}diff --git a/packages/coding-agent/src/core/tools/tool-definition-wrapper.ts b/packages/coding-agent/src/core/tools/tool-definition-wrapper.tsindex 1aca3f309a..aa5617e93d 100644--- a/packages/coding-agent/src/core/tools/tool-definition-wrapper.ts+++ b/packages/coding-agent/src/core/tools/tool-definition-wrapper.ts@@ -18,14 +18,6 @@ export function wrapToolDefinition<TDetails = unknown>(};}-/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */-export function wrapToolDefinitions(- definitions: ToolDefinition<any, any>[],- ctxFactory?: () => ExtensionContext,-): AgentTool<any>[] {- return definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));-}-/*** Synthesize a minimal ToolDefinition from an AgentTool.*diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex b76757978a..c6eb0cf5f2 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -3214,7 +3214,8 @@ export class InteractiveMode {if (shortcuts.size === 0) return;const localSessionHost = this.getLocalSessionHost();- const createContext = (): ExtensionContext => ({+ const createContext = (ownerPath: string): ExtensionContext => ({+ ...extensionRunner.createTimerBindings(ownerPath),ui: this.createExtensionUIContext(),hasUI: true,cwd: this.getCurrentCwd(),@@ -3246,7 +3247,7 @@ export class InteractiveMode {this.defaultEditor.onExtensionShortcut = (data: string) => {for (const [shortcutStr, shortcut] of shortcuts) {if (matchesKey(data, shortcutStr as KeyId)) {- Promise.resolve(shortcut.handler(createContext())).catch((err) => {+ Promise.resolve(shortcut.handler(createContext(shortcut.extensionPath))).catch((err) => {this.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);});return true;diff --git a/packages/coding-agent/test/agent-session-dynamic-tools.test.ts b/packages/coding-agent/test/agent-session-dynamic-tools.test.tsindex 5185c8cc54..df902627db 100644--- a/packages/coding-agent/test/agent-session-dynamic-tools.test.ts+++ b/packages/coding-agent/test/agent-session-dynamic-tools.test.ts@@ -3,7 +3,10 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { getModel } from "@earendil-works/pi-ai";import { Type } from "typebox";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { AuthStorage } from "../src/core/auth-storage.js";+import type { ExtensionContext } from "../src/core/extensions/types.js";+import { McpManager } from "../src/core/mcp/mcp-manager.js";import { DefaultResourceLoader } from "../src/core/resource-loader.js";import { createAgentSession } from "../src/core/sdk.js";import { SessionManager } from "../src/core/session-manager.js";@@ -179,4 +182,67 @@ describe("AgentSession dynamic tool registration", () => {session.dispose();});++ it("keeps session_start ctx timers running across a runtime-only MCP set change", async () => {+ const settingsManager = SettingsManager.create(tempDir, agentDir);+ const sessionManager = SessionManager.inMemory();+ const authStorage = AuthStorage.create(join(agentDir, "auth.json"));+ let ticks = 0;+ let scheduled = false;+ let capturedCtx: ExtensionContext | undefined;+ const resourceLoader = new DefaultResourceLoader({+ cwd: tempDir,+ agentDir,+ settingsManager,+ extensionFactories: [+ (pi) => {+ pi.on("session_start", (_event, ctx) => {+ capturedCtx = ctx;+ if (scheduled) return;+ scheduled = true;+ ctx.setInterval(() => {+ ticks++;+ }, 5);+ });+ },+ ],+ });+ await resourceLoader.reload();++ const { session } = await createAgentSession({+ cwd: tempDir,+ agentDir,+ model: getModel("anthropic", "claude-sonnet-4-5")!,+ settingsManager,+ sessionManager,+ authStorage,+ resourceLoader,+ });+ Reflect.set(session, "_mcpManager", new McpManager({ authStorage }));++ vi.useFakeTimers();+ try {+ await session.bindExtensions({});+ await vi.advanceTimersByTimeAsync(20);+ const ticksBeforeRebuild = ticks;+ const preRebuildCtx = capturedCtx;++ session.replaceAcpMcpServers(+ [{ name: "task", type: "http", url: "https://task.example/mcp", headers: {} }],+ "owner-a",+ );+ await vi.advanceTimersByTimeAsync(50);+ expect(ticks).toBeGreaterThan(ticksBeforeRebuild);++ await session.reload();+ const ticksAtReload = ticks;+ await vi.advanceTimersByTimeAsync(200);+ expect(ticks).toBe(ticksAtReload);+ expect(() => preRebuildCtx?.setTimeout(() => undefined, 5)).toThrow(/stale/);+ } finally {+ vi.useRealTimers();+ }++ session.dispose();+ });});diff --git a/packages/coding-agent/test/extensions-runner.test.ts b/packages/coding-agent/test/extensions-runner.test.tsindex a9737593ed..2447d17ae9 100644--- a/packages/coding-agent/test/extensions-runner.test.ts+++ b/packages/coding-agent/test/extensions-runner.test.ts@@ -500,6 +500,183 @@ describe("ExtensionRunner", () => {});});+ describe("host timers", () => {+ it("reports a throwing ctx timer callback and keeps other extensions' timers running", async () => {+ const firedMarker = path.join(tempDir, "other-timer-fired");+ fs.writeFileSync(+ path.join(extensionsDir, "throwing-timer.ts"),+ `export default function(pi) {+ pi.on("context", async (_event, ctx) => {+ ctx.setTimeout(() => { throw new Error("timer boom"); }, 5);+ // Userland thenable (not a native Promise): its rejection must land in the boundary too.+ ctx.setTimeout(() => ({ then(_resolve, reject) { reject(new Error("thenable boom")); } }), 5);+ });+ }`,+ );+ fs.writeFileSync(+ path.join(extensionsDir, "healthy-timer.ts"),+ `import * as fs from "node:fs";+ export default function(pi) {+ pi.on("context", async (_event, ctx) => {+ ctx.setTimeout(() => fs.writeFileSync(${JSON.stringify(firedMarker)}, "fired"), 5);+ });+ }`,+ );++ const result = await discoverAndLoadExtensions([], tempDir, tempDir);+ const runner = new ExtensionRunner(result.extensions, result.runtime, tempDir, sessionManager, modelRegistry);+ const errors: Array<{ extensionPath: string; event: string; error: string }> = [];+ runner.onError((err) => errors.push(err));++ vi.useFakeTimers();+ try {+ await runner.emitContext([]);+ await expect(vi.advanceTimersByTimeAsync(10)).resolves.not.toThrow();+ } finally {+ vi.useRealTimers();+ }++ expect(errors).toHaveLength(2);+ for (const error of errors) {+ expect(error.extensionPath).toContain("throwing-timer");+ expect(error.event).toBe("setTimeout");+ }+ expect(errors.map((error) => error.error).sort()).toEqual(["thenable boom", "timer boom"]);+ expect(fs.existsSync(firedMarker)).toBe(true);+ });++ it("reports a throwing adopted timer callback through the adopting runner", async () => {+ fs.writeFileSync(+ path.join(extensionsDir, "adopted-throwing-timer.ts"),+ `export default function(pi) {+ pi.on("context", async (_event, ctx) => {+ ctx.setTimeout(() => { throw new Error("adopted boom"); }, 5);+ });+ }`,+ );++ const result = await discoverAndLoadExtensions([], tempDir, tempDir);+ const oldRunner = new ExtensionRunner(+ result.extensions,+ result.runtime,+ tempDir,+ sessionManager,+ modelRegistry,+ );+ const newRunner = new ExtensionRunner(+ result.extensions,+ result.runtime,+ tempDir,+ sessionManager,+ modelRegistry,+ );+ const oldErrors: string[] = [];+ const newErrors: string[] = [];+ oldRunner.onError((err) => oldErrors.push(err.error));+ newRunner.onError((err) => newErrors.push(err.error));++ vi.useFakeTimers();+ try {+ await oldRunner.emitContext([]);+ newRunner.adoptHostTimers(oldRunner);+ vi.advanceTimersByTime(10);+ } finally {+ vi.useRealTimers();+ }++ expect(oldErrors).toEqual([]);+ expect(newErrors).toEqual(["adopted boom"]);+ });++ it("cancels pending ctx timers on invalidate so nothing fires after unload", async () => {+ const firedMarker = path.join(tempDir, "post-unload-fired");+ fs.writeFileSync(+ path.join(extensionsDir, "pending-timers.ts"),+ `import * as fs from "node:fs";+ export default function(pi) {+ pi.on("context", async (_event, ctx) => {+ const fire = () => fs.writeFileSync(${JSON.stringify(firedMarker)}, "fired");+ ctx.setTimeout(fire, 5);+ ctx.setInterval(fire, 5);+ });+ }`,+ );++ const result = await discoverAndLoadExtensions([], tempDir, tempDir);+ const runner = new ExtensionRunner(result.extensions, result.runtime, tempDir, sessionManager, modelRegistry);++ vi.useFakeTimers();+ try {+ await runner.emitContext([]);+ runner.invalidate();+ vi.advanceTimersByTime(50);+ } finally {+ vi.useRealTimers();+ }++ expect(fs.existsSync(firedMarker)).toBe(false);+ });++ it("cannot reactivate a fired ctx timeout via handle.refresh()", async () => {+ // Real timers on purpose: the guarantee rides on native Node clearTimeout semantics, which fake timers do not reproduce.+ const countFile = path.join(tempDir, "refresh-fire-count");+ fs.writeFileSync(+ path.join(extensionsDir, "refreshing-timer.ts"),+ `import * as fs from "node:fs";+ export default function(pi) {+ let handle;+ pi.on("context", async (_event, ctx) => {+ if (!handle) {+ handle = ctx.setTimeout(() => {+ const count = fs.existsSync(${JSON.stringify(countFile)}) ? Number(fs.readFileSync(${JSON.stringify(countFile)}, "utf8")) : 0;+ fs.writeFileSync(${JSON.stringify(countFile)}, String(count + 1));+ }, 5);+ } else {+ handle.refresh();+ }+ });+ }`,+ );++ const result = await discoverAndLoadExtensions([], tempDir, tempDir);+ const runner = new ExtensionRunner(result.extensions, result.runtime, tempDir, sessionManager, modelRegistry);++ await runner.emitContext([]);+ await vi.waitFor(() => expect(fs.existsSync(countFile)).toBe(true));+ await runner.emitContext([]);+ await new Promise((resolve) => setTimeout(resolve, 40));++ expect(fs.readFileSync(countFile, "utf8")).toBe("1");+ });++ it("clears a pending timer via ctx.clearTimeout", async () => {+ const firedMarker = path.join(tempDir, "cleared-timer-fired");+ fs.writeFileSync(+ path.join(extensionsDir, "clearing-timer.ts"),+ `import * as fs from "node:fs";+ export default function(pi) {+ pi.on("context", async (_event, ctx) => {+ const handle = ctx.setTimeout(() => fs.writeFileSync(${JSON.stringify(firedMarker)}, "fired"), 5);+ ctx.clearTimeout(handle);+ });+ }`,+ );++ const result = await discoverAndLoadExtensions([], tempDir, tempDir);+ const runner = new ExtensionRunner(result.extensions, result.runtime, tempDir, sessionManager, modelRegistry);++ vi.useFakeTimers();+ try {+ await runner.emitContext([]);+ vi.advanceTimersByTime(50);+ } finally {+ vi.useRealTimers();+ }++ expect(fs.existsSync(firedMarker)).toBe(false);+ });+ });+describe("message renderers", () => {it("gets message renderer by type", async () => {const extCode = `diff --git a/packages/coding-agent/test/trigger-compact-extension.test.ts b/packages/coding-agent/test/trigger-compact-extension.test.tsindex 92d2ce9560..8a7791d256 100644--- a/packages/coding-agent/test/trigger-compact-extension.test.ts+++ b/packages/coding-agent/test/trigger-compact-extension.test.ts@@ -18,6 +18,10 @@ function createContext(tokens: number | null, compact = vi.fn()): ExtensionContegetContextUsage: () => ({ tokens, contextWindow: 200_000, percent: tokens === null ? null : tokens / 2000 }),compact,getSystemPrompt: () => "",+ setTimeout: (callback, ms) => setTimeout(callback, ms),+ clearTimeout: (handle) => clearTimeout(handle),+ setInterval: (callback, ms) => setInterval(callback, ms),+ clearInterval: (handle) => clearInterval(handle),};}