import { guidancePanelAssets } from "./guidance-panel.ts"; import { guidanceLines, guidanceProbeStatusLines } from "./guidance-view.ts"; /** * acon console plugin for agent-hub (#935, plan entelecheia/ai-workspace#60 ยง2.5). * * D1: the provider lifts the manager's project listing and forwarding (`projectConsole` in src/hub/manager.ts): * Registry + ControlClient.connect(stateDir, {role: "console"}) -> ui_snapshot / ui_action. It adds no protocol and * no action: every action is checked against the manager's own whitelist, and every view against DASHBOARD_VIEWS. * D2: the panel is the `ahub ui` dashboard itself, built from renderDashboard(), with post() routed to the host. * * Contract: @staix/agent-console api 1. The manifest type is acon's own, imported type-only (#1375); the provider and item * shapes below stay structural so agent-hub keeps zero runtime dependencies. */ import type { VisualPayload, VisualSide, ActionMeta, ConsolePanelManifest } from "@staix/agent-console/contract"; import { createHash } from "node:crypto"; import { join } from "node:path"; import { Registry } from "../hub/registry.ts"; import { projectConsole, type Lifecycle, type ManagerOptions } from "../hub/manager.ts"; // lifecycle.ts reaches the whole daemon; it is imported only when a project is inspected, started or stopped. import { DASHBOARD_VIEWS, renderDashboard } from "../hub/ui.ts"; import { parseLineageResult } from "../hub/execution-lineage.ts"; import { executionLineageLines } from "./lineage-view.ts"; import { officeModel, type OfficeScene } from "./office-model.ts"; import { instructedAnswerItem, personEvidence, questionItem, QUESTION_ITEM, type InboxAnswers, type QuestionRowView } from "./plugin-questions.ts"; import { canPublishResults, receiptEvidence, resultItem, RESULT_ACTIONS, RESULT_ITEM, type ResultAction, type ResultRowView } from "./plugin-results.ts"; import { mergeSpaces, officeSpace } from "./office-space.ts"; import type { DeliverablePorts } from "../hub/deliverable-files.ts"; import type { VisualFile } from "../hub/visual.ts"; import { matchesPolicy } from "../hub/path-policy.ts"; import { VERSION as version } from "../version.ts"; type Tone = "ok" | "warn" | "err" | "neutral"; interface InboxItem { id: string; group: "decision" | "review" | "result" | "candidate" | "alert"; kind: string; title: string; detail?: string; actor?: string; project?: string; at: string; chip?: { text: string; tone: Tone }; verbs: { id: string; label: string; primary?: boolean; destructive?: boolean; reason?: "optional" | "required" }[]; link: { panel: string; params?: Record }; /** #1054: a `result` item carries the action acon runs once the person has seen it. */ seen?: { action: string }; } type ActionResult = | ({ ok: true } & Record) | { ok: false; error: string; unconfirmed?: true } | { ok: false; needsConfirm: true; preview: string[]; fingerprint: string; verb?: string; warnings?: string[] }; export interface ConsoleProvider { assets: { js: string; css?: string }; snapshot(input: { after: number; panel: string } & Record): Promise>; action(input: { action: string; confirmed?: true; fingerprint?: string } & Record, meta?: ActionMeta): Promise; asset?(input: { id: string }): Promise<{ bytes: Uint8Array; mime: string; name: string } | null>; close?(): Promise; } export interface ConsolePlugin { /** acon's own manifest type, imported type-only: a field or bound the console does not know fails typecheck here (#1375). */ manifest: ConsolePanelManifest; open(ctx: { home: string; log(line: string): void; features?: readonly string[] }): Promise; } const TITLES: Record<(typeof DASHBOARD_VIEWS)[number], string> = { board: "Board", office: "Office", stream: "Stream", agents: "Agents", message: "Message", memory: "Memory", settings: "Settings", roadmap: "Roadmap" }; /** The dashboard's own actions plus the inbox verbs; the manager whitelist is still applied to each forwarded call. */ const FORWARDED = ["start", "stop", "send", "pause", "resume", "permit", "propose", "intake", "assign", "backlog_pull", "backlog_return", "planning", "planning_undo", "planner_pull", "backlog_split", "release_new", "release_change", "setting", "setting_undo", "setting_preview", "model_preview", "model_confirm", "setting_reload", "config_edit_preview", "config_edit_apply", "start_peer", "sdlc_queue", "sdlc_release", "worktree_override_set", "worktree_override_clear", "worktrees_refresh_prs", // #1483 R5: the roadmap view's writes and reads. The writes raise authority as the person and are confirmed like the // other person actions; the three reads are bounded GitHub passes. "roadmap_new", "roadmap_edit", "roadmap_link", "roadmap_unlink", "roadmap_move", "roadmap_state", "roadmap_accept", "roadmap_reject", "roadmap_check", "roadmap_unplaced", "roadmap_triage"] as const; /** Advertised so acon lets the page send it, never forwarded: `action()` answers it through its own port (`answerVerb`), after the console's person meta is checked (#1053 T5). */ const QUESTION_ACTIONS = ["answer"] as const; /** #1054 T6: the receipt actions, advertised so acon lets the inbox and the page send them, never forwarded: `action()` checks the console's person meta, then calls the dedicated `projectConsole(...).receipt` port (`receiptVerb`). */ const RESULT_ADVERTISED = RESULT_ACTIONS; const REVIEW_ACTIONS = ["review_comment_put", "review_comment_delete", "review_comment_send"] as const; /** #1221 T2 AC5: the two verbs an advisory supervision row offers; both reach the hub's own `decide`, as the person. */ const SUPERVISION_VERBS = ["supervision_accept", "supervision_dismiss"] as const; const SUPERVISION_ITEM = /^supervision:([^:]+):(sup-[0-9a-f]{12})$/; const INBOX_VERBS = ["approve", "deny", "open", ...SUPERVISION_VERBS] as const; /** Outward or destructive: answered needsConfirm first (agent-console AGENTS.md); previews are read-only and stay direct. */ // A supervision acceptance runs the proposal's existing action, so it is confirmed like an approval; a dismissal runs nothing and is not. const CONFIRMED = new Set(["review_comment_delete", "review_comment_send", "stop", "permit", "setting", "setting_undo", "setting_reload", "config_edit_apply", "start_peer", "backlog_split", "send", "approve", "deny", "worktree_override_set", "worktrees_refresh_prs", "supervision_accept"]); const fingerprintOf = (input: Record) => { const { confirmed: _c, fingerprint: _f, reason: _r, ...rest } = input; return createHash("sha256").update(JSON.stringify(Object.keys(rest).sort().map((key) => [key, rest[key]]))).digest("hex"); }; /** The `ahub ui` dashboard as an acon panel module. Each rewrite must match exactly once, so drift fails loudly. */ export function panelAssets(): { js: string; css: string } { const { styles, markup, script } = renderDashboard(); const swap = (source: string, from: string, to: string) => { const at = source.indexOf(from); if (at < 0 || source.indexOf(from, at + 1) >= 0) throw new Error(`acon panel: expected exactly one ${JSON.stringify(from.slice(0, 60))}`); return source.slice(0, at) + to + source.slice(at + from.length); }; let body = script; // Preferences stay in the panel's memory: the shell's origin has its own cookies and storage. body = swap(body, " get: (name, fallback = '') => { try { return document.cookie.split(';').map(value => value.trim()).find(value => value.startsWith(name + '='))?.slice(name.length + 1) ?? fallback; } catch { return fallback; } },\n set: (name, value) => { try { document.cookie = `${name}=${value}; Path=/; Max-Age=31536000; SameSite=Strict`; } catch {} }", " get: (name, fallback = '') => prefs.has(name) ? prefs.get(name) : fallback,\n set: (name, value) => { prefs.set(name, value); }"); body = body.replaceAll("document.getElementById(", () => "$$("); // The shell owns the URL, cookies-free state and its own theme; the panel never touches history or the page theme. body = swap(body, "let ticket = location.hash.slice(1);\nhistory.replaceState(null, '', location.pathname);", "let ticket = '';"); body = swap(body, "const apply = () => { document.documentElement.dataset.theme = choice; };", "const apply = () => {};"); body = swap(body, "const $ = (id) => $$(id);", "const $ = $$;"); body = swap(body, "const reviewKit = null;", "const reviewKit = typeof host.ui.review === 'function' ? {render:host.ui.review.bind(host.ui),snapshot:input=>host.snapshot(input)} : null;"); body = swap(body, "const visualKit = null;", "const visualKit = typeof host.ui.visual === 'function' ? host.ui.visual.bind(host.ui) : null;"); // post() goes to the host: /projects is the manager listing, /snapshot and /action are the plugin's panel calls. body = swap(body, "async function post(path, body) {\n const response = await fetch(path, {method:'POST', credentials:'same-origin', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body)});\n if (response.status === 401) { expire(); throw new Error('Run ahub ui to start a new session.'); }\n const result = await response.json();", "async function post(path, body) {\n const result = path === '/projects' ? await host.snapshot({ panel: 'board' }) : path === '/snapshot' ? await host.snapshot({ ...body, panel: 'board' }) : await host.action(body);\n if (!result) { expire(); throw new Error('The console session ended.'); }\n const response = { ok: result.ok !== false, status: 200 };"); // Polling stops with the panel; the shell keeps its own clock. body = swap(body, "function expire() { stopped = true;", "function expire() { stopped = true; host.toast?.('The agent-hub panel stopped. Reload the console to reconnect.');"); body = body.replaceAll("document.querySelectorAll(", "root.querySelectorAll("); // The view keys listen inside the panel only (the shell owns global keys), and the page title belongs to the shell. body = swap(body, "document.addEventListener('keydown', dashboardKey);", "root.addEventListener('keydown', dashboardKey);"); body = swap(body, "if(document.title!==title)document.title=title;", ""); // An inbox link names the project that owns the item; the next project refresh selects it. body = swap(body, "if (!selectedProjectId && typeof result.selectedProjectId === 'string') selectedProjectId = result.selectedProjectId;", "if (wantProject && projectList.some((p) => p && p.id === wantProject)) selectedProjectId = wantProject;\n else if (!selectedProjectId && typeof result.selectedProjectId === 'string') selectedProjectId = result.selectedProjectId;\n wantProject = '';"); // The shell owns the page's landmarks and the view tabs (its panel tabs are DASHBOARD_VIEWS): the panel's
, //
and