import { showWorkspaceAttached } from "./workspace-notice.ts"; import { reportLoadedVersion } from "./runtime-version.ts"; import { showReloadNotice } from "./reload-notice.ts"; import { homedir, tmpdir } from "node:os"; import { readdir, readFile } from "node:fs/promises"; import { join, resolve, sep } from "node:path"; import { Type } from "typebox"; import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; const NewWorktree = Type.Object({ repository: Type.String({ description: "Absolute source repository path returned by radar_workspace_context" }), branch_mode: Type.Unsafe<"new">({ type: "string", enum: ["new"] }), name: Type.String({ description: "Workspace and new branch name (Radar sanitizes it)" }), base: Type.String({ description: "Base revision returned by radar_repository_refs, for example origin/main" }), }, { additionalProperties: false }); const ExistingWorktree = Type.Object({ repository: Type.String({ description: "Absolute source repository path returned by radar_workspace_context" }), branch_mode: Type.Unsafe<"existing">({ type: "string", enum: ["existing"] }), branch: Type.String({ description: "Existing local or origin branch returned by radar_repository_refs" }), }, { additionalProperties: false }); const SandboxPort = Type.Object({ host_port: Type.Integer({ minimum: 1, maximum: 65535, description: "IPv4 loopback host port" }), sandbox_port: Type.Integer({ minimum: 1, maximum: 65535, description: "TCP port inside the sandbox" }), }, { additionalProperties: false }); const SandboxMount = Type.Object({ path: Type.String({ description: "Absolute host directory to mount into the sandbox" }), read_only: Type.Optional(Type.Boolean({ description: "Mount read-only; defaults to true when omitted", default: true })), }, { additionalProperties: false }); const DesiredSandbox = Type.Object({ additional_mounts: Type.Array(SandboxMount, { description: "Complete agent-requested additional mount set; Radar-managed mounts are separate" }), ports: Type.Array(SandboxPort, { description: "Complete desired IPv4-loopback TCP port set" }), }, { additionalProperties: false }); const DesiredWorkspace = Type.Object({ note: Type.Union([Type.Object({ path: Type.String({ description: "Absolute canonical Obsidian task note path" }), linking_key: Type.String({ description: "The note's source identity, such as obsidian:task:" }), }, { additionalProperties: false }), Type.Null()], { description: "Existing note to retain or attach; null leaves the note unchanged. Notes cannot be replaced or detached.", }), worktrees: Type.Array(Type.Union([NewWorktree, ExistingWorktree]), { description: "Complete desired Git worktree membership, including every unchanged member; an empty list is valid", }), sandbox: Type.Union([DesiredSandbox, Type.Null()], { description: "Complete desired sandbox mounts/ports. An object explicitly attaches SBX when sandbox_attachment is true; null leaves an unsandboxed workspace unchanged. Detachment is not supported.", }), }, { additionalProperties: false }); const ReconcileParameters = Type.Object({ revision: Type.String({ description: "Revision returned by the latest radar_workspace_context call" }), desired: DesiredWorkspace, }, { additionalProperties: false }); const NoParameters = Type.Object({}, { additionalProperties: false }); const RepositoryParameters = Type.Object({ repository: Type.String({ description: "Absolute repository path returned by radar_workspace_context" }), }, { additionalProperties: false }); type Change = { action: "add" | "remove" | "replace" | "recreate"; resource: "worktree" | "sandbox" | "sandbox_mount" | "sandbox_port"; summary: string; path?: string; }; type Plan = { workspace_name: string; revision: string; next_revision: string; plan_id: string; auto_confirm?: boolean; effective_sandbox_mount_count?: number; changes: Change[]; warnings?: string[]; }; type WorkspaceMember = { repository: string; path: string; instruction_files?: string[]; skill_paths?: string[]; }; type WorkspaceContextResult = { workspace_path?: string; note?: { path: string; workspace_path: string }; sandbox?: { name?: string; shared_directory?: string; shared_directory_ready: boolean }; members?: WorkspaceMember[]; [key: string]: unknown; }; const ProcessSharedDirectoriesKey = Symbol.for("@christianmoesl/pi-radar/shared-directories"); // In-process subagents and independently loaded modules share process.env. // Each extension may release only its own directory, not another live session's. function sharedDirectoryTracker() { const shared = globalThis as typeof globalThis & { [ProcessSharedDirectoriesKey]?: Map }; const directories = shared[ProcessSharedDirectoriesKey] ??= new Map(); const session = Symbol("Radar shared directory session"); let stopped = false; function configure(context: WorkspaceContextResult | undefined) { if (stopped) return; const directory = context?.sandbox?.shared_directory_ready ? context.sandbox.shared_directory : undefined; directories.delete(session); if (directory) { // Change only Pi's host process, not tmux or Linux tools in SBX. Preserve // the host root for Radar subprocesses allocating other workspaces. process.env.RADAR_HOST_TMPDIR ||= tmpdir(); directories.set(session, directory); } const active = [...directories.values()].at(-1); if (active) process.env.TMPDIR = active; else if (process.env.RADAR_HOST_TMPDIR) process.env.TMPDIR = process.env.RADAR_HOST_TMPDIR; } return { configure, shutdown() { configure(undefined); stopped = true; }, }; } type ResourceSnapshot = { contextPaths: string[]; skillPaths: string[] }; type ReconcileResult = { ok?: boolean; retryable?: boolean; reconfirm_required?: boolean; reason?: string; plan?: Plan; error?: string; sandbox_reconciled?: boolean; worktrees_added?: number; worktrees_removed?: number; ports_published?: number; ports_unpublished?: number; [key: string]: unknown; }; const MaxReconcileConfirmations = 3; const ResourceEntry = "radar-workspace-resources"; type Activity = "idle" | "busy" | "waiting"; type ProcessActivity = { sessions: Map; published?: Activity; pending: Promise; }; // In-process subagents load independent copies of this extension, but all // publish to the process's tmux pane. Share state across Pi's module loaders // and reloads, not just across invocations of a single cached factory. const ProcessActivityKey = Symbol.for("@christianmoesl/pi-radar/activity"); function activityTracker(pi: ExtensionAPI) { const shared = globalThis as typeof globalThis & { [ProcessActivityKey]?: ProcessActivity }; const processActivity: ProcessActivity = shared[ProcessActivityKey] ??= { sessions: new Map(), pending: Promise.resolve() }; const session = Symbol("Radar activity session"); let running = false; let promptOpen = false; let stopped = false; function publish(force = false) { if (stopped) processActivity.sessions.delete(session); else processActivity.sessions.set(session, promptOpen ? "waiting" : running ? "busy" : "idle"); const activities = [...processActivity.sessions.values()]; const activity: Activity = activities.includes("waiting") ? "waiting" : activities.includes("busy") ? "busy" : "idle"; // Pi does not await prompt hooks. All sessions must share the write queue // and deduplication state: a child's idle/shutdown cannot clear its parent // or siblings, nor can a slow write overtake another session's transition. processActivity.pending = processActivity.pending.then(async () => { if (!force && activity === processActivity.published) return; const binary = process.env.RADAR_BINARY?.trim() || "radar"; try { const result = await pi.exec(binary, ["activity", activity], { timeout: 5000 }); processActivity.published = result.code === 0 ? activity : undefined; } catch { processActivity.published = undefined; // Activity is informational: never interfere with prompts or tools. } }); return processActivity.pending; } return { start: () => publish(true), running(value: boolean) { if (stopped) return processActivity.pending; running = value; return publish(); }, prompt(value: boolean) { if (stopped) return processActivity.pending; // Pi coalesces nested/overlapping prompts into one outer span. promptOpen = value; return publish(); }, shutdown() { if (stopped) return processActivity.pending; stopped = true; running = promptOpen = false; return publish(true); }, }; } function reconcileArgs(params: Record, cwd: string, preview: boolean, plan?: Plan): string[] { const args = ["reconcile-workspace", "--workspace", cwd, "--request", JSON.stringify(params), "--json"]; if (preview) args.push("--preview"); if (plan) args.push("--plan", plan.plan_id, "--plan-changes", String(plan.changes.length)); return args; } function parseJSON(toolName: string, stdout: string, phase: string): T { try { return JSON.parse(stdout) as T; } catch (error) { throw new Error(`${toolName} ${phase} returned malformed JSON: ${error instanceof Error ? error.message : error}`); } } function commandFailure(toolName: string, phase: string, result: { code: number; stdout: string; stderr: string }): Error { const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.code}`; return new Error(`${toolName} ${phase} failed: ${detail}`); } function homeRelativePath(path: string): string { const home = homedir(); if (!home) return path; if (path === home) return "~"; if (path.startsWith(home + sep)) return `~${path.slice(home.length)}`; return path; } function radarInstructionsPath(): string { const configHome = process.env.XDG_CONFIG_HOME?.trim() || join(homedir(), ".config"); return join(configHome, "radar", "AGENTS.md"); } async function loadRadarInstructions(): Promise { const path = radarInstructionsPath(); try { const instructions = await readFile(path, "utf8"); return `\n${instructions}\n`; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; } } function displayChangeSummary(change: Change): string { if (!change.path) return change.summary; const shortened = homeRelativePath(change.path); if (shortened === change.path) return change.summary; return change.summary.replace(change.path, shortened); } function confirmation(plan: Plan): string { const lines = [`Radar workspace: ${plan.workspace_name}`]; if (plan.changes.length === 0) lines.push("No changes are required."); for (const change of plan.changes) { const marker = change.action === "add" ? "+" : change.action === "remove" ? "-" : "~"; lines.push(`${marker} ${displayChangeSummary(change)}`); } for (const warning of plan.warnings ?? []) lines.push(`WARNING: ${warning}`); return lines.join("\n"); } function countLabel(count: number, singular: string): string { return `${count} ${singular}${count === 1 ? "" : "s"}`; } function retryableResultText(result: ReconcileResult): string { const progress: string[] = []; const added = Number(result.worktrees_added ?? 0); const removed = Number(result.worktrees_removed ?? 0); if (added > 0) progress.push(`${countLabel(added, "worktree")} added`); if (removed > 0) progress.push(`${countLabel(removed, "worktree")} removed`); let failure = "workspace reconciliation did not finish"; if (result.sandbox_reconciled !== true) { failure = "sandbox recreation failed"; } else if (Number(result.ports_published ?? 0) > 0 || Number(result.ports_unpublished ?? 0) > 0) { failure = "sandbox port reconciliation failed"; } const prefix = progress.length > 0 ? `${progress.join(", ")}; ` : ""; return `${prefix}${failure}. Re-inspect and retry.\n${JSON.stringify(result)}`; } async function runRadar(pi: ExtensionAPI, binary: string, args: string[], signal: AbortSignal | undefined, toolName: string, phase: string) { const result = await pi.exec(binary, args, { signal }); if (result.code !== 0) throw commandFailure(toolName, phase, result); return result.stdout; } async function inspectWorkspace(pi: ExtensionAPI, cwd: string, signal?: AbortSignal): Promise { const binary = process.env.RADAR_BINARY?.trim() || "radar"; const text = await runRadar(pi, binary, ["workspace-context", "--workspace", resolve(cwd), "--json"], signal, "radar_workspace_context", "inspect"); return parseJSON("radar_workspace_context", text, "inspect"); } async function skillFiles(root: string): Promise { const found: string[] = []; async function visit(directory: string) { let entries; try { entries = await readdir(directory, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const path = join(directory, entry.name); if (entry.isDirectory()) await visit(path); else if (entry.isFile() && (entry.name === "SKILL.md" || (directory === root && root.includes(`${sep}.pi${sep}`) && entry.name.endsWith(".md")))) found.push(path); } } await visit(root); return found.sort(); } async function skillName(path: string): Promise { try { const text = await readFile(path, "utf8"); if (!text.startsWith("---\n")) return undefined; const end = text.indexOf("\n---", 4); if (end < 0) return undefined; const match = text.slice(4, end).match(/^name:\s*['\"]?([^'\"\n]+)['\"]?\s*$/m); return match?.[1]?.trim(); } catch { return undefined; } } async function discoverResources(context: WorkspaceContextResult, notify?: (message: string, level: "info" | "warning" | "error") => void): Promise { const contextPaths = [...new Set((context.members ?? []).flatMap((member) => member.instruction_files ?? []))].sort(); const roots = new Map(); for (const member of context.members ?? []) { for (const root of member.skill_paths ?? []) if (!roots.has(root)) roots.set(root, member); } const candidates = (await Promise.all([...roots].map(async ([root, member]) => (await skillFiles(root)).map((path) => ({ path, member })), ))).flat(); const firstMembers = new Map>(); const selectedPaths: string[] = []; const byName = new Map(); for (const { path, member } of candidates) { const name = await skillName(path); if (name && member.repository) { const skills = firstMembers.get(member.repository) ?? new Map(); const firstMember = skills.get(name); // Member order determines precedence, not the final sorted resource paths. // Keep collisions within the chosen worktree so they still produce warnings. if (firstMember !== undefined && firstMember !== member.path) continue; skills.set(name, member.path); firstMembers.set(member.repository, skills); } selectedPaths.push(path); if (name) byName.set(name, [...(byName.get(name) ?? []), path]); } const duplicates = [...byName.entries()].filter(([, paths]) => paths.length > 1); for (const [name, paths] of duplicates) notify?.(`Radar did not load duplicate skill ${name}: ${paths.join(", ")}`, "warning"); const duplicatePaths = new Set(duplicates.flatMap(([, paths]) => paths)); const skillPaths = selectedPaths.filter((path) => !duplicatePaths.has(path)).sort(); return { contextPaths, skillPaths }; } function resourceChanges(previous: ResourceSnapshot, next: ResourceSnapshot): string[] { const lines: string[] = []; for (const path of next.contextPaths.filter((path) => !previous.contextPaths.includes(path))) lines.push(`added context ${path}`); for (const path of previous.contextPaths.filter((path) => !next.contextPaths.includes(path))) lines.push(`removed context ${path}`); for (const path of next.skillPaths.filter((path) => !previous.skillPaths.includes(path))) lines.push(`added skill ${path}`); for (const path of previous.skillPaths.filter((path) => !next.skillPaths.includes(path))) lines.push(`removed skill ${path}`); return lines; } export default function radarExtension(pi: ExtensionAPI) { let activated = false; pi.on("session_start", async (event, ctx) => { if (activated) return; // Query only the registry: broken Git/SBX resources must not prevent loading // the tools used to inspect and repair an otherwise registered workspace. const binary = process.env.RADAR_BINARY?.trim() || "radar"; try { const result = await pi.exec(binary, ["workspace-context", "--registration-only", "--workspace", resolve(ctx.cwd), "--json"], { timeout: 5000 }); if (result.code !== 0 || JSON.parse(result.stdout)?.registered !== true) return; } catch { // A global installation is inert when Radar is absent or cannot establish // membership. No instructions, skills, tools or activity are installed. return; } activated = true; await reportLoadedVersion(pi, ctx); await showReloadNotice(pi, ctx); await activateRadar(pi, ctx); if (event.reason !== "reload") await showWorkspaceAttached(pi, ctx); }); } // Pi recreates extension instances on reload and session replacement. Register // workspace-only resources after session_start supplies the actual session cwd. function activateRadar(pi: ExtensionAPI, ctx: ExtensionContext) { const activity = activityTracker(pi); const sharedDirectory = sharedDirectoryTracker(); let previousResources: ResourceSnapshot = { contextPaths: [], skillPaths: [] }; let knownContext: WorkspaceContextResult | undefined; let sandboxRoutingAccepted=true; function requireSandboxRouting(context:WorkspaceContextResult) { const name=context.sandbox?.name; if(!name) return; sandboxRoutingAccepted=false; pi.events.emit("pi-sbx:require",{name,acknowledge:()=>{sandboxRoutingAccepted=true}}); } pi.on("tool_call",(event)=>{ if(!sandboxRoutingAccepted && ["read","write","edit","bash","find","grep","ls"].includes(event.toolName)) return {block:true,reason:"This workspace requires pi-sbx 0.7.0+; update/enable it and reload Pi. No host fallback."}; }); pi.on("user_bash",()=>{ if(!sandboxRoutingAccepted) return {operations:{exec:async()=>{throw new Error("Required pi-sbx provider is unavailable; update/enable pi-sbx 0.7.0+ and reload Pi.")}}}; }); for (const entry of ctx.sessionManager.getEntries()) { if (entry.type === "custom" && entry.customType === ResourceEntry) { previousResources = entry.data as ResourceSnapshot; } } pi.on("resources_discover", async (event, ctx) => { try { knownContext = await inspectWorkspace(pi, event.cwd); sharedDirectory.configure(knownContext); requireSandboxRouting(knownContext); const discovered = await discoverResources(knownContext, (message, level) => ctx.ui.notify(message, level)); const resources = ctx.isProjectTrusted() ? discovered : { ...discovered, skillPaths: [] }; if (!ctx.isProjectTrusted() && discovered.skillPaths.length > 0) ctx.ui.notify("Radar did not load member skills because the workspace is not trusted", "warning"); const changes = resourceChanges(previousResources, resources); if (event.reason === "reload" && changes.length > 0) ctx.ui.notify(`Radar workspace resources refreshed: ${changes.join("; ")}`, "info"); previousResources = resources; pi.appendEntry(ResourceEntry, resources); return { skillPaths: resources.skillPaths }; } catch (error) { sharedDirectory.configure(undefined); if (event.reason === "reload") ctx.ui.notify(`Radar workspace resource refresh failed; keeping the previous resource set: ${error instanceof Error ? error.message : error}`, "warning"); return { skillPaths: previousResources.skillPaths }; } }); pi.on("before_agent_start", async (event, ctx) => { let radarInstructions: string | undefined; try { radarInstructions = await loadRadarInstructions(); } catch (error) { ctx.ui.notify(`Radar could not load ${radarInstructionsPath()}: ${error instanceof Error ? error.message : error}`, "warning"); } try { knownContext = await inspectWorkspace(pi, ctx.cwd, ctx.signal); sharedDirectory.configure(knownContext); requireSandboxRouting(knownContext); const resources = await discoverResources(knownContext); const blocks: string[] = []; for (const path of resources.contextPaths) { try { blocks.push(`\n${await readFile(path, "utf8")}\n`); } catch { // A later reload will report files that disappeared during the turn. } } const guidelines = [ "Radar workspace instructions:", knownContext.sandbox?.shared_directory_ready ? `- Shared host/sandbox directory: ${knownContext.sandbox.shared_directory}. It is mounted read/write at the same absolute path in both environments. Save and share screenshots here (use unique filenames), not /tmp/screenshots. Pi saves pasted clipboard images here. Keep the sandbox's TMPDIR and /tmp local; pass the shared output path explicitly to screenshot tools. These files are temporary and are removed during workspace cleanup; copy anything worth retaining into the workspace.` : "", knownContext.sandbox && !knownContext.sandbox.shared_directory_ready ? "- The workspace shared screenshot directory is not ready. Reconcile the workspace and reload Pi before using it; do not assume host temporary paths are accessible in the sandbox." : "", knownContext.note ? `- notes.md is the canonical Obsidian task note at ${knownContext.note.path}. Its body may be empty. Do not invent a template unless the user asks or the work requires one.` : "", knownContext.note ? "- notes.md contains user and agent content. Radar task identity, title, lifecycle, priority and preferences live in SQLite. Read the existing note before editing and preserve user content and user-owned frontmatter unless the requested edit changes them. Do not add radar-* metadata or replace the whole note with a summary or template." : "", knownContext.note ? "- Change task state through Radar commands, not Markdown metadata. Use radar task title for the display title, and radar task done/reopen/priority/mute/unmute for task decisions. Missing frontmatter is normal." : "", "- Member worktrees are direct children of the workspace. Use Radar's typed tools for membership, sandbox mount, and port changes.", "- Instructions from Radar's user AGENTS.md apply to workspace and resource management across every member repository.", "- Instructions from a member repository context file apply only to files under that repository. Nested context files apply to their containing subtree. The most specific applicable directory wins. Global and workspace instructions apply to every member.", ].filter(Boolean).join("\n"); return { systemPrompt: [event.systemPrompt, guidelines, radarInstructions, ...blocks].filter(Boolean).join("\n\n") }; } catch { sharedDirectory.configure(undefined); if (radarInstructions) return { systemPrompt: [event.systemPrompt, radarInstructions].join("\n\n") }; return undefined; } }); pi.registerCommand("radar-reload-workspace-resources", { description: "Reload member repository context and skills after workspace reconciliation", handler: async (_args, ctx) => { await ctx.reload(); return; }, }); pi.on("agent_start", () => activity.running(true)); pi.on("agent_settled", () => activity.running(false)); pi.on("ui_prompt_start", () => activity.prompt(true)); pi.on("ui_prompt_end", () => activity.prompt(false)); pi.on("session_shutdown", async () => { sharedDirectory.shutdown(); await activity.shutdown(); }); pi.registerTool({ name: "radar_documentation", label: "Read Radar Documentation", description: "Read the documentation embedded in the installed host Radar CLI, offline and without configuration or secrets. Omit topic for a source-path/title index; pass an exact source path to read that Markdown document. Results identify the CLI version and commit. Works in sandboxed workspaces without mounts or a source checkout.", promptSnippet: "Read version-matched Radar capabilities, configuration and usage documentation", promptGuidelines: [ "For questions about Radar capabilities, configuration or behavior, consult radar_documentation before answering; retrieve relevant topics rather than the entire manual.", "Use exact source paths from the documentation index. Resolve relative Markdown links against the returned document source; omit #anchors when requesting a document.", "Cite the documentation source and distinguish documented defaults from the user's actual settings. Documentation describes the returned CLI version, not necessarily the loaded extension version; it does not authorize configuration changes.", ], parameters: Type.Object({ topic: Type.Optional(Type.String({ description: "Canonical source path from the index, e.g. docs/configuration.md; omit to list topics", maxLength: 256 })), }, { additionalProperties: false }), async execute(_toolCallId, params, signal) { const topic = (params as { topic?: string }).topic; const binary = process.env.RADAR_BINARY?.trim() || "radar"; const args = ["documentation", "--json", ...(topic === undefined ? [] : ["--topic", topic])]; const response = await pi.exec(binary, args, { signal, timeout: 5000 }); if (response.code !== 0) throw commandFailure("radar_documentation", "read (update the Radar CLI if this command is unavailable)", response); const result = parseJSON<{ version: string; commit: string; topics?: { source: string; title: string }[]; document?: { source: string; title: string; content: string } }>("radar_documentation", response.stdout, "read"); if (!result || typeof result.version !== "string" || typeof result.commit !== "string" || (topic ? !result.document || result.document.source !== topic || typeof result.document.title !== "string" || typeof result.document.content !== "string" : !Array.isArray(result.topics) || !result.topics.every(item => item && typeof item.source === "string" && typeof item.title === "string"))) { throw new Error("radar_documentation returned an invalid documentation response"); } return { content: [{ type: "text", text: JSON.stringify(result) }], details: result }; }, }); pi.registerTool({ name: "radar_workspace_context", label: "Inspect Radar Workspace", description: "Inspect the current logical Radar workspace from the host. Returns a revision, capabilities, complete desired state, member branches and dirty status, current host resources, and repositories discovered through Radar configuration.", promptSnippet: "Inspect the current Radar workspace and obtain its revision and desired state before reconciling host resources", promptGuidelines: [ "Use radar_workspace_context before radar_reconcile_workspace and copy its complete desired state before modifying only the requested resources.", "Use the absolute repository paths returned by radar_workspace_context; do not guess host paths from sandbox-visible directories.", "Respect capabilities: request attachment only when sandbox_attachment is true; otherwise leave sandbox null when sandbox is false.", ], parameters: NoParameters, executionMode: "sequential", async execute(_toolCallId, _params, signal, _onUpdate, ctx: ExtensionContext) { const toolName = "radar_workspace_context"; const binary = process.env.RADAR_BINARY?.trim() || "radar"; const text = await runRadar(pi, binary, ["workspace-context", "--workspace", resolve(ctx.cwd), "--json"], signal, toolName, "inspect"); const result = parseJSON>(toolName, text, "inspect"); return { content: [{ type: "text", text: JSON.stringify(result) }], details: result }; }, }); pi.registerTool({ name: "radar_repository_refs", label: "Inspect Radar Repository Refs", description: "Try to fetch and prune origin for one host repository, then return its default branch, valid base refs, canonical local/origin branches, and checkout paths. If the fetch fails, return locally cached refs with a warning.", promptSnippet: "Inspect branches and valid base refs for a repository selected from radar_workspace_context", promptGuidelines: [ "Use radar_repository_refs after selecting a repository from radar_workspace_context when the branch or new-branch base is not already known exactly.", "Pass a canonical branch name or base ref from radar_repository_refs in radar_reconcile_workspace desired worktrees.", ], parameters: RepositoryParameters, executionMode: "sequential", async execute(_toolCallId, params, signal, _onUpdate, _ctx: ExtensionContext) { const toolName = "radar_repository_refs"; const binary = process.env.RADAR_BINARY?.trim() || "radar"; const repository = String((params as { repository: string }).repository); const text = await runRadar(pi, binary, ["repository-refs", "--repo", repository, "--json"], signal, toolName, "inspect"); const result = parseJSON>(toolName, text, "inspect"); return { content: [{ type: "text", text: JSON.stringify(result) }], details: result }; }, }); pi.registerTool({ name: "radar_reconcile_workspace", label: "Reconcile Radar Workspace", description: "Preview and reconcile the complete desired host workspace state. The tool applies Radar's configured confirmation policy internally. It can attach an existing canonical Obsidian note, add or remove clean member worktrees, including the last one, and explicitly attach a native SBX sandbox when sandbox_attachment is true, with complete additional host mounts and IPv4-loopback TCP ports. Sandbox detachment is not supported.", promptSnippet: "Reconcile typed worktree and optional sandbox mount/port desired state", promptGuidelines: [ "Use radar_reconcile_workspace for host workspace changes instead of direct git, tmux, or sbx commands because Radar must validate and persist the complete resource bundle.", "Do not ask for user confirmation before calling radar_reconcile_workspace. The tool applies the configured confirmation policy itself.", "Always start from the latest radar_workspace_context revision and complete desired object; omitted worktrees, additional mounts, and ports are removals.", "radar_reconcile_workspace supports multiple branches from one repository, but each repository-and-branch pair must be unique.", "radar_reconcile_workspace cannot replace or detach notes. Use the note's source identity when attaching an existing Obsidian task note; never invent one.", "Before omitting a worktree, check its dirty status from radar_workspace_context; dirty worktrees cannot be removed until their changes are committed, stashed, or discarded.", "Use read_only true for radar_reconcile_workspace additional mounts unless writable host access is necessary and explicitly intended.", "When exposing a service, first use its configured port as host_port. If apply fails because that host port is unavailable, call radar_workspace_context again and retry with a randomly selected host_port from 49152 through 65535 while keeping sandbox_port unchanged.", "For explicit attachment, sandbox_attachment must be true; send a complete sandbox object. Otherwise preserve sandbox null for unsandboxed workspaces. Sandbox-less worktree reconciliation remains supported.", ], parameters: ReconcileParameters, executionMode: "sequential", async execute(_toolCallId, params, signal, _onUpdate, ctx: ExtensionContext) { const binary = process.env.RADAR_BINARY?.trim() || "radar"; const input = params as unknown as Record; const cwd = resolve(ctx.cwd); const previewText = await runRadar(pi, binary, reconcileArgs(input, cwd, true), signal, "radar_reconcile_workspace", "preview"); let plan = parseJSON("radar_reconcile_workspace", previewText, "preview"); const plans: Plan[] = [plan]; const autoConfirm = plan.auto_confirm === true; if (!autoConfirm && !ctx.hasUI) { throw new Error("radar_reconcile_workspace requires an interactive confirmation channel unless workspace.auto_confirm is enabled; no changes were applied"); } for (let confirmationAttempt = 0; confirmationAttempt < MaxReconcileConfirmations; confirmationAttempt++) { if (plan.changes.length === 0) { return { content: [{ type: "text", text: JSON.stringify({ ok: true, unchanged: true, revision: plan.revision }) }], details: { plans, unchanged: true } }; } if (!autoConfirm) { const title = confirmationAttempt === 0 ? "Reconcile Radar workspace?" : "Workspace plan changed. Reconcile updated plan?"; const approved = await ctx.ui.confirm(title, confirmation(plan)); if (!approved) { return { content: [{ type: "text", text: JSON.stringify({ ok: false, cancelled: true }) }], details: { cancelled: true, plans } }; } } const resultText = await runRadar(pi, binary, reconcileArgs(input, cwd, false, plan), signal, "radar_reconcile_workspace", "apply"); const result = parseJSON("radar_reconcile_workspace", resultText, "apply"); if ((input.desired as {sandbox?:unknown} | undefined)?.sandbox) { sandboxRoutingAccepted=false; try {knownContext=await inspectWorkspace(pi,cwd,signal);requireSandboxRouting(knownContext)} catch { /* Keep ordinary tools blocked until context can be refreshed. */ } } if (result.ok !== true && result.reconfirm_required === true && result.reason === "plan_changed") { if (!result.plan) { throw new Error(`radar_reconcile_workspace requested reconfirmation without an updated plan\n${resultText.trim()}`); } plan = result.plan; plans.push(plan); continue; } if (result.ok !== true && result.retryable === true) { if (Number(result.worktrees_added ?? 0) > 0 || Number(result.worktrees_removed ?? 0) > 0) { pi.sendUserMessage("/radar-reload-workspace-resources", { deliverAs: "followUp", expandPromptTemplates: true }); } const partial = retryableResultText(result); return { content: [{ type: "text", text: partial }], details: { plans, result, partial } }; } if (result.ok !== true) { throw new Error(`radar_reconcile_workspace apply did not converge: ${String(result.error ?? "unknown error")}\n${resultText.trim()}`); } if (Number(result.worktrees_added ?? 0) > 0 || Number(result.worktrees_removed ?? 0) > 0) { pi.sendUserMessage("/radar-reload-workspace-resources", { deliverAs: "followUp", expandPromptTemplates: true }); } return { content: [{ type: "text", text: JSON.stringify(result) }], details: { plans, result } }; } throw new Error(`radar_reconcile_workspace plan changed after ${MaxReconcileConfirmations} confirmations; call radar_workspace_context and retry`); }, }); return activity.start(); }