#!/usr/bin/env bun import { INSTRUCTION_CONTROL_TIMEOUT_MS } from "../hub/instructed-exact.ts"; import { assertConductorOperationLocal, authorizeConductorOperation, authorizeConductorLaunch, issueConductorOperation, preflightConductorRecovery, retireConductorOperation } from "./conductor-recovery.ts"; import { runtimePruneHealth } from "../hub/runtime-prune-health.ts"; import { conductorLocalOperation, conductorOperation, OPERATIONAL_PERSON_GUIDANCE } from "../hub/operational-authority.ts"; import { sayRecipients } from "./say-input.ts"; import { parseAnswerArgs } from "./answer-args.ts"; import { parseRoadmapArgs, renderRoadmap } from "./roadmap.ts"; import { roadmapWorktree, writeRoadmap } from "./roadmap-write.ts"; import type { DeliverableRow } from "../hub/tasks.ts"; import { kimiSourceRow } from "../hub/budget-notes.ts"; import { hubGitSync, hubGitEnv } from "../hub/git.ts"; import { parseReleaseGuardArgv, parseReleasePushUpdates } from "./sdlc-release-guard.ts"; import { validReleaseVersion } from "../hub/sdlc-release-authorization.ts"; import { agentVersions, runAgents } from "./agents.ts"; import { assessVersion, COMPAT, configuredCommands } from "../adapters/compat.ts"; import { claudePeer as defaultChannelPeer } from "../hub/claude-state.ts"; import { effectiveInstanceRoles } from "../hub/instances.ts"; import { resolveInstanceExecutionCwd } from "../hub/instance-execution.ts"; import { readInstanceRoleConfig, readInstanceConfig, readInstanceConfigLayers, type InstanceRoleConfig } from "../hub/instance-config.ts"; import { staleInstanceKey, rosterAllows } from "../hub/roster.ts"; import { parseConfiguredAcpArguments, runConfiguredAcpEntry, requireActiveConfiguredAcp } from "./configured-acp-entry.ts"; import type { NativeCliEntryContext } from "../adapters/definitions/native-cli-entry-types.ts"; import { BUILTIN_CLI_ENTRIES, createProjectAdapterCatalog, definitionOf, DOCTOR_TOOL_PROBES, DOCTOR_MEMORY_CAPTURE_PEERS, DOCTOR_PLUGIN_PROBE, nativeDoctorCheck, nativeMemoryCaptureRow, type MemorySetupReading, nativeDoctorRecoveryIdentity, nativeDoctorOptionalProbes } from "../adapters/registry.ts"; import { parsePiFlags } from "../adapters/definitions/native-cli-pi.ts"; import { supportsBoardReleaseFilter, supportsBoardColumnMetadata, readAllTasks } from "./board-read.ts"; import { matchesPolicy } from "../hub/path-policy.ts"; import { projectedDiff } from "../hub/projected-diff.ts"; import { TextProjections, type ProjectedText } from "../hub/text-projection.ts"; import { fetchSourceUrl, MAX_SOURCE_BYTES, publicSourceView, screenRegistration, sourceProjectionReceipt, SourceRegistry, validSourceId, type SourceMeta } from "../hub/sources.ts"; import { renderSourceAdd, renderSourceList } from "./source-output.ts"; import { renderScheduleChange, renderScheduleList, renderScheduleRun } from "./schedule-output.ts"; import { renderIntake, renderIntakeChange } from "./intake-output.ts"; import { renderLearnChange, renderLearnList } from "./learn-output.ts"; import { renderCapabilities } from "./capabilities-output.ts"; import { parseSynthesisManifest, synthesisManifestHash } from "../hub/synthesis-readiness.ts"; import { parseStudyArgs } from "./study.ts"; import { parseBacklogReturn } from "./backlog-return-args.ts"; import { parseResultsArgs } from "./results-args.ts"; import { renderStudyEvidence, renderSynthesisReadiness, renderExperiments, renderStudyList, renderStudyReceipt, renderStudyShow } from "./study-output.ts"; import { renderHandoffReceipt, renderHandoffs } from "./handoff-output.ts"; import { parseHandoffArgs } from "./handoff-args.ts"; import { terminalText } from "./console-state.ts"; import { parseSettingsEditArgs, runSettingsEdit, SETTINGS_EDIT_USAGE } from "./settings-edit.ts"; import { autonomyEnvironment, runAutonomy } from "./autonomy.ts"; import { readAutonomyDefaults, writeAutonomyDefaults } from "../hub/autonomy-defaults.ts"; import { inheritMachineAutonomy, prepareAutonomyProject, runAllProjectAutonomy, type PreparedAutonomyProject } from "./autonomy-projects.ts"; import { offlineAutonomyStatus } from "./autonomy-offline.ts"; import { autonomyHomeStatus, usedClaudeHomes } from "./autonomy-homes.ts"; import { shellQuote } from "./shell-quote.ts"; import { discoverClaudeHomes } from "./claude-homes.ts"; import { setupClaudeHomes } from "./setup-homes.ts"; import { setupResearchDefault } from "./setup-research.ts"; import { registerAconPlugin } from "./acon-register.ts"; import { petView, readPet, renderPet } from "./pet.ts"; import { PET_WINDOW_RETIRED_NOTICE, petPalette } from "../pet/config.ts"; import { loadPetConfig } from "./pet-config.ts"; import { projectProfile, resolveProfile } from "../hub/profiles.ts"; import { catalogAssignments, loadRoleCatalog, selectedRoles } from "../hub/roles.ts"; import { attachWatch } from "./watch.ts"; import { verifiedJcodeCommand } from "../adapters/jcode.ts"; import { configureJcodeMcp, jcodeExtraMcpServers, splitJcodeMcpServers } from "./jcode-mcp.ts"; import { qwenSessionId } from "../hub/crash.ts"; import { isPermissionMode } from "../hub/permission-mode.ts"; import { parseSettingText, settingDef, settingText, undoableDef, type SettingRow } from "../hub/settings.ts"; import { startModeOf } from "../hub/start-mode.ts"; import { rolesRow } from "./role-doctor.ts"; import { classListRow, currentRouting, loadRouting, OVERLAY_FILE, parseOverlay, parseRouting, routingText, type Routing, type RoutingOverlay } from "../hub/routing.ts"; import { spawn, spawnSync } from "node:child_process"; import { chmodSync, closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; import { homedir } from "node:os"; import { basename, dirname, join, relative, resolve } from "node:path"; import { retryLaunchConnect, ControlClient, readControl } from "../hub/control-client.ts"; import { loadConfig } from "../hub/daemon.ts"; import { factsHook } from "./facts-hook.ts"; import { parseInstructionHook } from "./instruction-hook.ts"; import { hubHome, projectContext, projectRoot, realPath } from "../hub/project.ts"; import { Registry, type Project } from "../hub/registry.ts"; import { datasetInputFor, exportResearchDataset, projectFamilyOf } from "../hub/research-dataset.ts"; import { readEvidence } from "../hub/research-record.ts"; import { inspectProject, startProject, stopProject, runProjectDaemon } from "../hub/lifecycle.ts"; import { processLiveness, processSignature } from "../pi/process-signature.ts"; import { openManager, startManager, stopManager } from "../hub/manager.ts"; import { OmniRoute } from "../omniroute/client.ts"; import { autonomyInheritanceChange, init, initNextSteps, initResearchDefault, withInitResearch, initSettingRows, planInit, sharedConfigRow } from "./init.ts"; import { discoverInitChecks, withInitChecks } from "./init-required-checks.ts"; import { INIT_USAGE, parseInitSettings } from "./init-settings.ts"; import { installedPeers } from "./init-roles.ts"; import { promptGate, runInitPrompt, settingLines, shadowOffered, type InitAnswers } from "./init-prompt.ts"; import { loadPacks } from "../hub/packs.ts"; import { launcherPreview } from "./preview.ts"; import { instanceLaunchArguments, requirePeerInstances, requireActiveInstance, cleanupStaleClaudeSettings, cleanupClaudeSettings, buildLaunch, buildKimiTuiLaunch, claudeObservationHooks, nativeLaunchEnv, recordClaudeLaunch, runClaudeLaunch, type ClaudeLaunchRecord, UNATTENDED_WARNING } from "./launch.ts"; import { configureKimiMcp } from "./kimi-mcp.ts"; import { HUB_SKILL_NAMES, hubSkillsPresent, nextStep, parseList, pluginState, type InstalledPlugin, type Marketplace } from "./setup.ts"; import { installHubSkills, skillHostStates, skillStateRow } from "./skills-install.ts"; import { applyJcodeHome, installHubSkillsInJcodeHomes, installSkillsInJcodeHome, jcodeHomeBlocked, jcodeHomeSkillStates, jcodeSkillHomes, planJcodeHomeInit, rosterPreflight, rosterPreflightLines, writeJcodeHomeConfig } from "../adapters/definitions/native-cli-jcode-home-init.ts"; import { CLASSES } from "../hub/board.ts"; import { VERSION } from "../version.ts"; import { freeText, unknownOption, unknownOptionRefusal, withoutSeparator } from "./free-text.ts"; import { createInterface } from "node:readline/promises"; import { createInterface as lineReader } from "node:readline"; import { activeOperation, assertLifecycleAvailable, operationIdPattern, readOperation, writeOperation, recoveryLock, recoveryRunner, signedRunner, stopSignedRunner, supportsAction } from "../hub/recovery-store.ts"; import { childEnv, personEnv } from "../hub/child-process.ts"; import { abortRecovery, createOperation, disposeRecovery, recordRecoveryDelegation, repairedFreshSession, reattachRecovery, liveProjects, nextChoices, nextActionsText, publicOperation, recoveryCommand, registeredProjects, runRecovery, type RecoveryOperation, type Inspection } from "./upgrade.ts"; import { endPlannedPeer, makeRecoveryDriver, makeUpgradePlan, preserveSource, reattachPlannedTerminals } from "./upgrade-runtime.ts"; import { exactVersion, latestRelease, newerVersion } from "./recovery-package.ts"; import { applyStoppedRetargets, planStoppedRetargets } from "./upgrade-stopped.ts"; import { awaitOperationEnd } from "./upgrade-wait.ts"; import { globalUpdateAdvice, runtimeVersionWarnings } from "./runtime-version-warning.ts"; import { operationScreen, planScreen, type ScreenIO, type UpgradeHost } from "./upgrade-interactive.ts"; import { readRecoveryPresentationFlags } from "./upgrade-presentation-flags.ts"; import { renderOperation, renderBlocked, renderSummary, type RecoveryPresentationOptions } from "./upgrade-presentation.ts"; import { renderBudgetResult, renderRecoveryStatus, renderStoppedPlan, renderStoppedResults, renderUpgradePlan } from "./upgrade-output.ts"; import { recordTerminalLaunch, prepareTerminalLaunch, registerTerminalLaunch, type TerminalPeer } from "./terminal-recovery.ts"; import { effectiveStartAgents, inheritMachineStart, setupStartAgents, startProjectAgents } from "./start-agents-run.ts"; import { ensureMlx, inspectMlx, stopMlx } from "../models/mlx.ts"; import { setupOllamaModel } from "./models-setup.ts"; import { contextLine, type PeerRow } from "./status-lines.ts"; import { parseSince, readEvents } from "../hub/events.ts"; import { armRuns, benchCompare, benchCsv, benchReport, formatCompare, formatReport as formatBenchReport, formatRuns, MEMORY_MODES, readRuns, runSummary, sameSuite, type MemoryMode } from "../hub/bench.ts"; import { benchPreflight, defaultIo, runBench } from "./bench.ts"; import { ADDONS, isAddon, type AddonName } from "../hub/tooling.ts"; import { goalCommand, memoryCommand, memoryStaleAnchorsCommand } from "./memory.ts"; import { runSpecs, runSpecsStamp } from "./specs.ts"; import { confirmTidy, planTidy, realTidyGit, rowsFromReply, type TidyGit } from "./worktree-tidy.ts"; import { renderTidyPreview, renderTidyResult, renderWorktrees } from "./worktrees-output.ts"; import { formatMemoryStaleAnchors } from "../hub/memory-stale-anchors.ts"; import { AGENT_MEM_REFUSAL, AGENT_MEM_VERSION, memoryIndexExists, selectedMemoryProfile } from "../hub/memory-profile.ts"; import { checkMemoryProfiles, formatMemoryProfileCheck } from "../hub/memory-profile-check.ts"; import { addonReport, appendRecords, closedAtOf, formatAddons, formatResearch, LABELS, labelTarget, RESEARCH_SCHEMA, projectKey, readStores, researchReport, taskRecords, toCsv, type Label, type TaskRecord } from "../hub/research.ts"; import { summarize, summarizeByTask } from "../hub/report.ts"; import { readDogfood } from "../hub/dogfood-read.ts"; import { dogfoodSince, formatDogfood } from "../hub/dogfood.ts"; import { USAGE_GROUPS, LIMITS_MAX } from "../hub/usage-rollup.ts"; import { hasTree, planUndo, repoOf, restore, Turns } from "../hub/snapshots.ts"; import { pathWarnings } from "../hub/conflicts.ts"; import { COMPLETION_SHELLS, completionScript } from "./completion.ts"; import { agentShellCause, classifyPeerCommand, cliCommandLabel, detectCliIdentity, LIVE_TEST_PERSON_REFUSAL, liveTestRefusal, peerCommandRefusal } from "./identity.ts"; import { recordCliAudit, recordDelegatedCliAudit } from "./identity-audit.ts"; import { runConsole } from "./console.ts"; import { installedVersions } from "./console-versions.ts"; import { errorLines, failureExitCode } from "./error-format.ts"; import { asciiMarkers, paint, permissionBoundary, resolveColor, streamEnv, wrap, type Span } from "./console-state.ts"; import { queueResolveArgsValid } from "../hub/person-command.ts"; import { outputWidth, renderRuntimeModels, renderRoster, renderRoles, rolesView,renderStatus, renderStatusDefault, renderBoard, renderBacklog, renderBoardColumns, boardColumnModel, renderBudget, renderDoctor, renderProjects, renderQueue, renderTurns, renderOrphans, renderOrphanCleanup, renderQueueShow, renderModelsStatus, renderExecutionBudgetStatus, renderReport, renderUsage, renderLimits, renderTotal, type DoctorCheck } from "./output.ts"; import { renderHelp, configuredAcpHelp, guidanceProbeUsage, listsSubcommand, subcommandUsage } from "./help.ts"; import { renderBacklogResult, renderGroom, renderReleaseChange, renderReleaseList, renderReleaseNew, renderReleaseShow, renderTaskCancel, renderTaskShow } from "./task-output.ts"; import { SURVEY_FOCUS } from "../hub/advisor-survey.ts"; import { renderAuthorization, renderSdlcCosts, renderSdlcExplain, renderSdlcMerge, renderSdlcMetrics, renderSdlcQueue, renderSdlcRelease, renderSdlcStatus, renderSdlcAudit, renderSdlcConfiguration, renderSdlcSurvey } from "./sdlc-output.ts"; import { renderTailEvent } from "./tail-render.ts"; import { archiveProblem, archiveState, damagedState, failureText, MANIFEST, planReset, resetLines, resetRuntime, startState, type ResetPlan } from "./reset.ts"; /** `--since 7d|24h|` for export and report; everything when absent. */ const since = (): number => { const at = args.indexOf("--since"); if (at < 0) return 0; const t = parseSince(args[at + 1] ?? ""); if (t === undefined) fail("--since takes 7d, 24h, 90m or an ISO date"); return t; }; const argv = process.argv.slice(2); let selector: string | undefined; let liveTest = false; while (argv[0] === "--project" || argv[0] === "--live-test") { if (argv.shift() === "--live-test") { if (liveTest) fail("--live-test may appear only once"); liveTest = true; } else { if (selector !== undefined) fail("--project may appear only once"); selector = argv.shift(); if (!selector || selector.startsWith("--")) fail("--project needs a path or project ID"); } } // Upgrade accepts its documented command-local selector as well as the leading global form. if (argv[0] === "upgrade") { const at = argv.indexOf("--project", 1); if (at >= 0) { if (selector !== undefined || argv.indexOf("--project", at + 1) >= 0) fail("--project may appear only once"); selector = argv[at + 1]; if (!selector || selector.startsWith("--")) fail("--project needs a path or project ID"); argv.splice(at, 2); } } const [given = "help", ...rest] = argv; let selected: { root: string; stateDir: string }; try { if (selector) { const projects = registeredProjects(); { const known = projects.find((p) => p.id === selector); const context = known ?? projectContext(selector, {}); const registered = known ?? projects.find((p) => p.root === context.root); selected = registered ?? context; } } else { const markedPeer = process.env.AGENTHUB_PEER_ID, markedRoot = process.env.AGENTHUB_PROJECT_DIR; const markedConfig = markedPeer && markedRoot && !definitionOf(markedPeer) ? readInstanceConfig(realPath(markedRoot)) : undefined; const declarations = markedConfig?.instances; if (markedPeer && markedRoot && markedConfig && declarations && Object.hasOwn(declarations, markedPeer)) { const canonicalRoot = realPath(markedRoot), config = loadConfig(canonicalRoot); const executionCwd = resolveInstanceExecutionCwd(canonicalRoot, markedPeer, declarations, effectiveInstanceRoles(markedPeer, declarations, config.roles, markedConfig.catalog), markedConfig.catalog); if (realPath(projectRoot(process.cwd())) !== realPath(executionCwd)) fail("native instance workspace does not match its declared checkout"); selected = projectContext(canonicalRoot); } else selected = projectContext(process.cwd()); } } catch (error) { fail(startupDiagnostic(error)); } const cwd = selected.root; let peerConfig: ReturnType; const needsProjectDeclarations = cliCommandLabel(given, rest) === "unknown" || rest.some(arg => arg === "--as" || arg.startsWith("--as=")) || !!process.env.AGENTHUB_PEER_ID && !definitionOf(process.env.AGENTHUB_PEER_ID) || given === "help" && !!rest[0] && cliCommandLabel(rest[0], []) === "unknown"; try { peerConfig = needsProjectDeclarations ? readInstanceConfig(cwd) : { catalog: createProjectAdapterCatalog(), ignored: [] }; } catch (error) { fail(startupDiagnostic(error)); } /** Local declarations for a command the running daemon answers. A config file that is mid-edit or invalid must not * block it (lowering a permission, listing or reloading settings): such a read falls back to builtins and keeps its * diagnostic for a key that only a declaration could define. */ function localDeclarations(): { scope: Pick; error?: string } { try { return { scope: readInstanceRoleConfig(cwd) }; } catch (error) { return { scope: { catalog: createProjectAdapterCatalog() }, error: startupDiagnostic(error) }; } } const projectCatalog = peerConfig.catalog; const configuredCommand = !definitionOf(given) && (projectCatalog.definitionOf(given)?.permission.genericAcp !== undefined || peerConfig.declaredExternalInstances?.some(row => row.kind === given) === true); const unboundCaller = detectCliIdentity(process.env); const markerNeedsDeclaration = unboundCaller.role === "invalid" && unboundCaller.reason === "AGENTHUB_PEER_ID conflicts with native agent marker" && process.env.AGENTHUB_PEER_ID !== undefined && !definitionOf(process.env.AGENTHUB_PEER_ID); const needsInstances = definitionOf(given) && rest.some(arg => arg === "--as" || arg.startsWith("--as=")) || markerNeedsDeclaration; let declaredInstances: ReturnType["instances"]; let nativeSelection: ReturnType; try { declaredInstances = needsInstances || configuredCommand ? peerConfig.instances : undefined; if (configuredCommand && !(rest.length === 1 && ["--help", "-h"].includes(rest[0]!))) { const selection = parseConfiguredAcpArguments(given, rest, projectCatalog, declaredInstances, peerConfig.declaredExternalInstances); nativeSelection = { ...(selection.peer !== given ? { instance: selection.peer } : {}), args: [...rest] }; } else nativeSelection = instanceLaunchArguments(given, rest, declaredInstances); } catch (error) { fail(startupDiagnostic(error)); } const selectedInstance = nativeSelection.instance; // `ahub -h` alone asks for that command's help instead of running it, and so does `ahub -h` when the help lists that subcommand (#1433: `ahub task propose --help` once // filed a task titled --help). Elsewhere `-h` may be message text (`ahub say try ls -h`), and claude and codex pass their arguments on to the agent. const asksHelp = (a: string | undefined) => a === "--help" || a === "-h"; const subcommandHelp = !!given && nativeSelection.args.length === 2 && asksHelp(nativeSelection.args[1]) && listsSubcommand(given, nativeSelection.args[0]!); const cmd = asksHelp(given) || (definitionOf(given)?.start.passthrough !== true && ((nativeSelection.args.length === 1 && asksHelp(nativeSelection.args[0])) || subcommandHelp)) ? "help" : given; const args = cmd === "help" && given !== "help" && !asksHelp(given) ? [given] : nativeSelection.args; /** Resolve a named peer only against this project's current trusted declarations. */ const peerDefinition = (peer: unknown) => { if (typeof peer !== "string") return undefined; const bound = projectCatalog.definitionOf(peer, peerConfig.instances); if (bound) return bound; const current = readInstanceConfig(cwd); return current.catalog.definitionOf(peer, current.instances); }; const requireNamedPeerFeature = (hub: ControlClient, peer: string | undefined) => { if (peer !== undefined && !definitionOf(peer)) { const adapter = peerDefinition(peer); if (adapter?.permission.genericAcp !== undefined && !hub.features.includes("configured_acp")) throw new Error("running hub lacks configured_acp; upgrade and restart it first"); if (adapter?.kind !== peer) requirePeerInstances(hub.features); } }; /** The project config, saying on stderr which machine-local fields it had to ignore (issue #17). */ const projectConfig = () => { const config = loadConfig(cwd); for (const line of config.ignored ?? []) console.error(`note: ${line}; only a config file nobody committed may set it`); for (const line of config.releasePolicyNotices ?? []) console.error(`note: ${line}`); return config; }; const stateDir = selected.stateDir; var operationalAuditReady=false, operationalRefusalRecorded=false; const caller = declaredInstances ? detectCliIdentity(process.env, declaredInstances) : unboundCaller; const commandLabel = cmd === "guidance" && args[0] === "probe" && ["register", "start", "show", "receipts", "cancel"].includes(args[1] ?? "") ? `guidance probe ${args[1]}` : cliCommandLabel(cmd, args, projectCatalog); let commandAccess = classifyPeerCommand(cmd, args, projectCatalog); const continuationPeer = process.env.AGENTHUB_RECOVERY_CONDUCTOR; const continuationId = process.env.AGENTHUB_RECOVERY_OPERATION; let recoveryLauncher = false, recoveryRunnerContinuation = false; let recoveryLauncherCurrent: (() => void) | undefined; if (continuationPeer !== undefined) { if (caller.role !== "tools" || caller.peer !== continuationPeer || !continuationId || !operationIdPattern.test(continuationId) || liveTest) fail("conductor recovery authority unavailable; the person runs it in ahub console or a terminal"); let operation: RecoveryOperation; try { operation = readOperation(continuationId); } catch { fail("conductor recovery authority unavailable; the person runs it in ahub console or a terminal"); } if (!operation || operation.id !== continuationId || typeof operation.sourceRoot !== "string") fail("conductor recovery authority unavailable; the person runs it in ahub console or a terminal"); if (cmd === "recovery-run" && args.length === 1 && args[0] === continuationId) { await authorizeConductorOperation(operation, continuationPeer); if (realPath(operation.sourceRoot) !== realPath(resolve(import.meta.dir, "../.."))) fail("conductor recovery authority unavailable; the person runs it in ahub console or a terminal"); recoveryRunnerContinuation = true; commandAccess = "conductor"; } else if (process.env.AGENTHUB_RECOVERY_CONTINUATION === continuationId) { await authorizeConductorLaunch(operation, continuationPeer, cwd, resolve(import.meta.dir, "../.."), cmd, args); recoveryLauncher = true; recoveryLauncherCurrent = () => assertConductorOperationLocal(operation, continuationPeer); } else fail("conductor recovery authority unavailable; the person runs it in ahub console or a terminal"); } const conductorPeer = !liveTest && caller.role === "tools" && (recoveryRunnerContinuation || ["restart", "upgrade", "recovery"].includes(cmd) && commandAccess === "conductor") ? caller.peer : undefined; // Agent-authored content keeps its peer. Operational starts/holds may borrow console authority for live verification. const guidanceProbeDelegationRefused = liveTest && caller.role === "tools" && cmd === "guidance" && args[0] === "probe" && ["register", "start", "show", "receipts", "cancel"].includes(args[1] ?? ""); const delegationRefused = liveTest && caller.role === "tools" && commandAccess !== "allowed" && (liveTestRefusal(cmd, args) || guidanceProbeDelegationRefused); const delegatedPeer = liveTest && caller.role === "tools" && commandAccess !== "allowed" && !delegationRefused ? caller.peer : undefined; const identity = delegatedPeer || recoveryLauncher ? { role: "console" as const } : caller; operationalAuditReady=identity.role==="tools" && commandAccess==="conductor" && conductorOperation(cmd,args)!==undefined; function audit(outcome: "run" | "refused" | "invalid"): void { if (caller.role === "console") return; if(outcome==="refused" && operationalAuditReady){if(operationalRefusalRecorded)return;operationalRefusalRecorded=true;} try { recordCliAudit(stateDir, caller.role === "tools" ? caller.peer : "unknown", commandLabel, outcome, cmd === "answer" && args.includes("--instructed")); } catch { if (delegatedPeer) fail("live-test delegation audit unavailable; nothing was executed"); console.error("ahub: CLI audit could not be recorded (outbox unavailable or full)"); } } if (identity.role === "invalid") { audit("invalid"); fail(`${identity.reason}; use ahub console or a terminal with no agent markers`); } if (delegationRefused && cmd === "answer" && args.includes("--instructed")) { audit("refused"); fail(`${LIVE_TEST_PERSON_REFUSAL}; the person can answer with ahub console`); } if (delegationRefused) { audit("refused"); fail(LIVE_TEST_PERSON_REFUSAL); } if (identity.role === "tools" && commandAccess === "console") { audit("refused"); fail(peerCommandRefusal(identity.peer, commandLabel)); } // Recovery keeps its authoritative delegation audit in the operation receipt, independent of an old source drain. // With no daemon manifest, local bootstrap commands have no consumer to negotiate with; use the compatible outcome. const recoveryAudit = ["upgrade", "restart", "recovery", "recovery-run"].includes(cmd); const noAuditConsumer = !existsSync(join(stateDir, "status.json")) && !existsSync(join(stateDir, "hub.pid")); let delegatedAuditHub: ControlClient | undefined; let delegatedConnectionTaken = false; let releaseAuditInstance: (() => void) | undefined; if (delegatedPeer && !recoveryAudit && !noAuditConsumer) { let published = false; try { const auditId = await recordDelegatedCliAudit(stateDir, delegatedPeer, commandLabel, async () => { // The validated invocation already has operational console authority; a tools hello would add a roster gate. delegatedAuditHub = await ControlClient.connect(stateDir, { role: "console", projectRoot: cwd }); return delegatedAuditHub.instanceId ? delegatedAuditHub.features : []; }); published = true; releaseAuditInstance = ControlClient.pinInstance(stateDir, delegatedAuditHub!.instanceId!); assertDelegatedAuditConsumer(); const retained = await delegatedAuditHub!.request({ t: "cli_audit_ack", auditId }, 3000); if (retained.ok !== true || retained.auditId !== auditId || retained.instanceId !== delegatedAuditHub!.instanceId) { throw new Error("live-test audit retention was not confirmed; nothing was executed; inspect the hub or upgrade it before retrying"); } } catch (error) { releaseAuditInstance?.(); delegatedAuditHub?.close(); if (published) { try { recordCliAudit(stateDir, delegatedPeer, commandLabel, "refused"); } catch { fail("live-test delegation audit unavailable; nothing was executed"); } } fail((error as Error).message); } } else if ((identity.role === "tools" || delegatedPeer) && !operationalAuditReady) audit("run"); function assertDelegatedAuditConsumer(): void { if (delegatedAuditHub && ((!delegatedConnectionTaken && !delegatedAuditHub.isOpen) || readControl(stateDir)?.instanceId !== delegatedAuditHub.instanceId)) { throw new Error("delegated audit consumer changed; refusing further actions; inspect the result before retrying"); } } // Forward only to ahub's own continuation commands, never to native agent argv or an environment flag. const liveTestArgs = liveTest ? ["--live-test"] : []; const invokedFrom = process.cwd(); // relative paths a person types (a bench suite) are theirs, not the project's try { process.chdir(cwd); } catch { fail(`project directory is unavailable: ${cwd}`); } /** One-shot output flags do not alter the fetched JSON document. */ function outputOptions(source: readonly string[] = args) { const flags = source.filter(arg => arg.startsWith("--color=")); if (flags.length > 1 || source.includes("--color")) fail(`usage: ahub ${cmd} [--color=auto|always|never] [--json] [--full]`); const color = resolveColor(flags[0]?.slice("--color=".length), streamEnv(!!process.stdout.isTTY), "ahub"); if (color instanceof Error) fail(`usage: ahub ${cmd} [--color=auto|always|never] [--json] [--full]`); return { color: color === true, json: source.includes("--json"), full: source.includes("--full"), verbose: source.includes("--verbose"), columns: outputWidth({ isTTY: !!process.stdout.isTTY, columns: process.stdout.columns, COLUMNS: process.env.COLUMNS }) }; } /** * #814 T2: split `--json`, `--full` and `--color=` from a command that also takes free text. A value flag's value is never a * presentation flag (`task cancel --reason --json` records the reason `--json`), and with `edges` only a leading or trailing run * counts, so a reason that mentions `--json` in the middle of a sentence keeps its words. A reason that ENDS in a bare * presentation flag loses it: the documented cost of accepting the flag after the reason. */ function splitPresentation(argv: readonly string[], opts: { valueFlags?: readonly string[]; edges?: boolean } = {}): { operands: string[]; flags: string[] } { const isFlag = (arg: string) => arg === "--json" || arg === "--full" || arg.startsWith("--color="); const operands: string[] = [], flags: string[] = [], value = new Set(opts.valueFlags ?? []); let lead = true; const middle: string[] = []; for (let i = 0; i < argv.length; i++) { const arg = argv[i]!; if (value.has(arg)) { (opts.edges ? middle : operands).push(arg); if (i + 1 < argv.length) (opts.edges ? middle : operands).push(argv[++i]!); lead = false; continue; } if (!isFlag(arg)) { (opts.edges ? middle : operands).push(arg); lead = false; continue; } if (!opts.edges || lead) flags.push(arg); else middle.push(arg); } if (!opts.edges) return { operands, flags }; // a trailing run of presentation flags moves out of the middle; anything earlier stays operand text let end = middle.length; const trailing: string[] = []; while (end > 0 && isFlag(middle[end - 1]!) && !value.has(middle[end - 2] ?? "")) trailing.unshift(middle[--end]!); return { operands: middle.slice(0, end), flags: [...flags, ...trailing] }; } /** Remove only presentation flags from read-only command positional arguments. */ function outputArguments(): string[] { return args.filter(arg => arg !== "--json" && arg !== "--full" && !arg.startsWith("--color=")); } /** `sdlc` operands: the read subcommands that print for a person (#814) drop `--json`, `--full` and `--color=`; every other subcommand keeps its argv exactly. */ /** The daemon answers a missing task id with a JSON string (`"no task #N"`), a found task with an object: the sentence for a missing one, otherwise undefined. */ function missingTaskText(text: string): string | undefined { try { const value: unknown = JSON.parse(text); return typeof value === "string" && /^no task #\d+$/.test(value) ? value : undefined; } catch { return undefined; } } /** A hub tool answers JSON text. Text that does not parse is printed as it came: a renderer never sees it, so it cannot read as an empty report. */ function showToolText(render: (data: any, columns?: number, now?: number) => Span[][], text: string, present: ReturnType): void { let data: unknown; try { data = JSON.parse(text); } catch { return console.log(text); } if (present.json) return console.log(text); printOutput(render(data, present.columns, Date.now()), present.color); } const SDLC_READ = ["status", "explain", "queue", "release", "metrics", "costs", "authorize-release", "audit", "configure", "survey"]; function sdlcOperands(): string[] { return SDLC_READ.includes(args[0] ?? "") ? outputArguments() : args; } function printOutput(lines: Span[][], color: boolean): void { for (const line of lines) console.log(paint(line, color)); } const unattendedEnv = process.env.AGENTHUB_UNATTENDED === "1"; const lifecycle = { inspectProject, startProject, stopProject }; const connect = async (timeoutMs = 3000) => { assertDelegatedAuditConsumer(); if (delegatedAuditHub && !delegatedConnectionTaken) { delegatedConnectionTaken = true; return delegatedAuditHub; } return ControlClient.connect(stateDir, identity.role === "tools" ? { role: "tools", peer: identity.peer, projectRoot: cwd } : { role: "console", projectRoot: cwd, ...(delegatedAuditHub ? { instanceId: delegatedAuditHub.instanceId } : {}) }, timeoutMs); }; const connectLaunch = () => retryLaunchConnect(connect, () => console.error("hub busy, retrying")); /** #1627 A: what init does for the hub-owned jcode home, read-only. */ function initJcodeHome() { const config = loadConfig(cwd); return planJcodeHomeInit({ cwd, stateDir, bundle: join(import.meta.dir, "..", "..", "plugins", "agent-hub", "server.js"), hubHome: hubHome(), config, env: process.env, installed: !!Bun.which(config.jcode_cmd[0] ?? "jcode") }); } function registeredProject(): Project { const registry = new Registry(); try { return registry.register(cwd, stateDir); } finally { registry.close(); } } /** #247: this project's registration for its research records; writing needs `research.enabled` in its config. */ function researchProject(writes = true): Project { const project = matchingProject() ?? fail("this project has no hub registration; run ahub up here once first"); if (writes && !loadConfig(cwd).research.enabled) fail('research records are off for this project; set "research": { "enabled": true } in .agenthub/config.json first'); return project; } /** The registration of exactly this root and state directory, the only one kill and reset act on; never registers. */ function matchingProject(): Project | undefined { const registry = new Registry(); try { return registry.list().find((p) => p.root === cwd && p.stateDir === stateDir); } finally { registry.close(); } } const hubManifest = () => !!readControl(stateDir) || existsSync(join(stateDir, "hub.pid")); /** A reset is never part of an upgrade or recovery: this project's or a legacy machine hold refuses it, whatever * AGENTHUB_RECOVERY_OPERATION says (assertLifecycleAvailable lets that operation's own processes through). */ function resetLockFree(): void { const owner = recoveryLock(undefined, cwd); if (owner) throw new Error(`${activeOperation(owner)}; nothing was changed`); } /** A manifest whose daemon is alive or uncertain, by inspectProject's rule; a crashed daemon's leftovers do not count. */ function liveManifest(): boolean { const control = readControl(stateDir); if (control && processLiveness(control.pid, control.pidSignature) !== "gone") return true; // A signed manifest is this release's daemon, which writes no hub.pid: one beside it is an older run's leftover. if (control?.pidSignature) return false; let text: string; // Only daemons up to 0.12.20 wrote hub.pid (#226): an unsigned legacy record. try { text = readFileSync(join(stateDir, "hub.pid"), "utf8").trim(); } catch { return false; } if (/^\d+$/.test(text)) return processLiveness(Number(text)) !== "gone"; // Empty or garbled: beside a dead daemon's status it is that daemon's leftover too; alone it proves nothing. return !control; } async function healthy(): Promise { let hub: ControlClient | undefined; try { hub = await connect(); const reply = await hub.request({ t: "status" }, 3000); return reply.status?.cwd === cwd; } catch { return false; } finally { hub?.close(); } } function exec(bin: string, argv: string[], tool?: "claude" | "codex" | "kimi", executionCwd = cwd): never { const env = tool ? nativeLaunchEnv(selectedInstance ?? tool, childEnv(), declaredInstances) : childEnv(); const res = spawnSync(bin, argv, { cwd: executionCwd, stdio: "inherit", env: { ...env, AGENTHUB_STATE_DIR: stateDir, AGENTHUB_PROJECT_DIR: cwd } }); if (res.error) fail(`cannot run ${bin}: ${res.error.message}`); process.exit(res.status ?? 1); } function execWithEnv(bin: string, argv: string[], extra: NodeJS.ProcessEnv, peer: string, executionCwd = cwd): never { const env: NodeJS.ProcessEnv = { ...nativeLaunchEnv(peer, extra, declaredInstances), AGENTHUB_STATE_DIR: stateDir, AGENTHUB_PROJECT_DIR: cwd }; delete env.AGENTHUB_RECOVERY_OPERATION; delete env.AGENTHUB_UNATTENDED; const res = spawnSync(bin, argv, { cwd: executionCwd, stdio: "inherit", env }); if (res.error) fail(`cannot run ${bin}: ${res.error.message}`); process.exit(res.status ?? 1); } /** `mode` is absent when no flag chose one: the caller takes the configured start mode (#269). `--headless` is `--mode headless`. */ const piFlags = () => parsePiFlags(args, fail); async function projectRows() { const registry = new Registry(); try { return await Promise.all(registry.list().map(async (project) => ({ ...project, ...await inspectProject(project) }))); } finally { registry.close(); } } async function printProjects(options: ReturnType) { const projects = await projectRows(); if (options.json) return console.log(JSON.stringify(projects, null, 2)); printOutput(renderProjects(projects, options.columns, Date.now()), options.color); } /** Full command line of a live process, undefined once it is gone. */ function processCommandLine(pid: number): string | undefined { const res = spawnSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }); if (res.status !== 0) return undefined; return res.stdout.trim() || undefined; } /** * A bare PID is never enough to kill on: it must belong to this project's hub daemon. * The daemon argv is ` .../cli/main.ts --project daemon [--unattended]`, built by * startProject from the registry row. ps joins argv with spaces and drops quoting, so the * token after `--project` must equal the root exactly: a substring check would let an orphan * rooted at /tmp/foo match a healthy hub launched with --project /tmp/foo2, and a root whose * path contains a space simply can never be verified this way and is refused (issue #56). */ function hubDaemonCommand(pid: number, root: string): string | undefined { const command = processCommandLine(pid); if (!command) return undefined; const tokens = command.split(/\s+/); const project = tokens.indexOf("--project"); if (project < 1 || tokens[project + 1] !== root || tokens[project + 2] !== "daemon") return undefined; return command; } /** Live PID candidates for a registration whose project root is gone: the claim, the manifest, the legacy pid file. */ function orphanPids(project: Project): number[] { // #226: a recorded pid counts only while its signature (when one was recorded) still names its process. const candidates = new Set(); if (typeof project.pid === "number" && processLiveness(project.pid, project.pidSignature) === "live") candidates.add(project.pid); const control = readControl(project.stateDir); if (control && Number.isSafeInteger(control.pid) && processLiveness(control.pid, control.pidSignature) === "live") candidates.add(control.pid!); try { const pid = Number(readFileSync(join(project.stateDir, "hub.pid"), "utf8").trim()); if (Number.isSafeInteger(pid) && pid > 0) candidates.add(pid); } catch { /* no legacy pid file */ } return [...candidates].filter((pid) => processLiveness(pid) === "live"); } const processGone = (pid: number): boolean => !processCommandLine(pid); async function killOrphan(pid: number, root: string, diagnostic: (text: string) => void = text => console.log(text)): Promise { if (!hubDaemonCommand(pid, root)) { diagnostic(` pid ${pid}: command line is not this project's hub daemon; refusing to kill`); return false; } try { process.kill(pid, "SIGTERM"); } catch { return true; } // exited meanwhile const graceful = Date.now() + 3_000; while (Date.now() < graceful && !processGone(pid)) await Bun.sleep(100); if (processGone(pid)) { diagnostic(` pid ${pid}: stopped with SIGTERM`); return true; } // The PID may have been reused since SIGTERM; verify identity again before escalating. if (!hubDaemonCommand(pid, root)) { diagnostic(` pid ${pid}: identity changed after SIGTERM; refusing SIGKILL`); return false; } try { process.kill(pid, "SIGKILL"); } catch { return true; } const hard = Date.now() + 2_000; while (Date.now() < hard && !processGone(pid)) await Bun.sleep(100); if (!processGone(pid)) { diagnostic(` pid ${pid}: still alive after SIGKILL`); return false; } diagnostic(` pid ${pid}: killed with SIGKILL`); return true; } async function orphanDoctor(kill: boolean, options: ReturnType): Promise { const orphans = registeredProjects().filter(project => !existsSync(project.root)).map(project => ({ project, pids: orphanPids(project) })); if (options.json) console.log(JSON.stringify(orphans, null, 2)); else printOutput(renderOrphans(orphans, options.columns, Date.now(), kill), options.color); let failed = 0; const diagnostic = (text: string) => options.json ? console.error(paint([{ text }], false)) : printOutput(wrap(text, options.columns ?? Infinity).map(text => [{ text }]), options.color); if (kill) for (const { project, pids } of orphans) for (const pid of pids) if (!(await killOrphan(pid, project.root, diagnostic))) failed++; if (failed) fail(`${failed} orphaned hub process(es) could not be stopped`); } /** Startup refusals remain single-line and bounded even for malformed local declarations. */ function startupDiagnostic(error: unknown): string { const message = error instanceof Error ? error.message : "invalid startup configuration"; return message.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 512) || "invalid startup configuration"; } /** * CLI output standard v1, Messages: `ahub: : ` on stderr; with a terminal on stderr it leads with the fail marker, and a piped line * keeps the plain `ahub: ` form so a script or agent matching it still works. `next` is a complete, copyable command printed on a second line (ASCII * `->` when the locale is not UTF-8); a caller passes it only where the fix is known, and a daemon refusal is passed through without one. * A usage error exits 2, any other failure 1; a usage error is one whose text starts with `usage:` (the form every call site already uses) or names an unknown command. */ function fail(message: string, refusalAudited=false, authorityRefused?:boolean, next?: string): never { if(operationalAuditReady && authorityRefused!==false){if(refusalAudited)operationalRefusalRecorded=true;if(!operationalRefusalRecorded)audit("refused");} console.error(errorLines(message, next, !!process.stderr.isTTY, asciiMarkers(process.env, process.argv.includes("--ascii"))).join("\n")); process.exit(failureExitCode(message)); } function operationalIncomplete(result: {complete?:boolean;incompleteReason?:unknown;truncated?:boolean}, history: "log"|"event"): void { if(result.complete===false)console.error(`ahub: operational output is incomplete: ${typeof result.incompleteReason==="string"?terminalText(result.incompleteReason).replace(/[\r\n]+/g," ").slice(0,200):"public privacy or history coverage unavailable"}`); else if(result.truncated)console.error(`ahub: operational ${history} history is truncated`); } async function taskOp(op: string, a: Record, throwOnError = false, connection?: ControlClient, timeoutMs?: number): Promise { const hub = connection ?? await connect(); try { if (op === "hub_task_cancel" && !hub.features.includes("task_cancel")) fail("this daemon does not support task cancellation; upgrade it first"); if ((op === "study_evidence" || op === "study_check" || op === "claim_verdict" && a.synthesis !== undefined) && !hub.features.includes("research_synthesis")) fail("running hub lacks research_synthesis; upgrade and restart the hub before requesting synthesis evidence or recording a manifest-bound verdict"); const res = await hub.request({ t: "task", op, args: a }, timeoutMs ?? (op === "github_import" ? 60_000 : 30_000)); if (!res.ok) { if (throwOnError) throw new Error(res.error); if(res.refusalAudited===true)operationalRefusalRecorded=true; if(operationalAuditReady ? res.authorityRefused!==false : res.authorityRefused===true)audit("refused"); // a domain error is not a refusal (#1547) // #711: an agent shell refused something only the person may do is told why it counts as an agent. The refusal and the authority stay as they were. const cause = agentShellCause(identity, String(res.error)); if (cause) console.error(`ahub: ${res.error}\n${cause}`), process.exit(1); fail(res.error,res.refusalAudited===true,res.authorityRefused); } return res.text; } finally { if (!connection) hub.close(); } } /** Reads hub.db's turn records; `none` when the hub never kept one (snapshots off, no git work tree, an older hub). */ function turnRecords(read: (turns: Turns) => T, none: T): T { const db = join(stateDir, "hub.db"); if (!existsSync(db)) return none; let turns: Turns | undefined; try { turns = new Turns(db, true); return read(turns); } catch (error) { if (/no such table/.test((error as Error).message)) return none; throw error; } finally { turns?.close(); } } /** `--flag value` pairs pulled out of an argument list; the rest keeps its order. */ function takeFlags(argv: string[], single: string[], repeated: string[]) { const one: Record = {}; const many: Record = {}; const rest: string[] = []; for (let i = 0; i < argv.length; i++) { const a = argv[i]!; if (single.includes(a)) one[a] = argv[++i] ?? fail(`${a} needs a value`); else if (repeated.includes(a)) (many[a] ??= []).push(argv[++i] ?? fail(`${a} needs a value`)); else rest.push(a); } return { one, many, rest }; } async function hold(t: "pause" | "resume"): Promise { if (!args[0]) fail(`usage: hub ${t} `); const hub = await connect(); const res = await hub.request({ t, peer: args[0] }); hub.close(); if (!res.ok) fail(res.error); console.log(`${args[0]} is ${res.state}`); } function recoveryDisplay() { // A terminal gives its own width; a pipe gives COLUMNS when set, else 80 (#814: a person reads a pipe too). const width = process.stdout.columns ?? outputWidth({ isTTY: false, COLUMNS: process.env.COLUMNS }) ?? 80; return readRecoveryPresentationFlags(args, { ...streamEnv(!!process.stdout.isTTY), columns: width }); } const humanRecovery = (json: boolean) => !json && !!process.stdin.isTTY && !!process.stdout.isTTY; const printRecovery = (lines: readonly string[]) => { for (const line of lines) console.log(line); }; function recoveryFormatting(entry: string, presentation: RecoveryPresentationOptions): string[] { // ponytail: old retained coordinators have no presentation parser; capability metadata can replace this display-only module-presence check. return existsSync(join(dirname(entry), "upgrade-presentation-flags.ts")) ? [`--color=${presentation.color ? "always" : "never"}`, ...(presentation.verbose ? ["--verbose"] : [])] : []; } function printRecoveryStatus(op: RecoveryOperation, message: string, presentation: RecoveryPresentationOptions): void { printRecovery(wrap(message, presentation.columns)); printRecovery(wrap(`ahub recovery status ${op.id}`, presentation.columns)); if (presentation.verbose) { printRecovery(wrap("Retained bun coordinator (main.js), wrapped command:", presentation.columns)); printRecovery(wrap(recoveryCommand(op, "status"), presentation.columns)); } } async function recoveryEndInspection(op: RecoveryOperation): Promise> { const driver = makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer); return Object.fromEntries(await Promise.all(op.plan.projects.map(async planned => [planned.project.id, await driver.inspect(planned.project).catch(() => undefined)] as const))); } function spawnRecovery(operation: RecoveryOperation, quiet = false, presentation?: RecoveryPresentationOptions): void { const child = spawn(process.execPath, [join(operation.sourceRoot, "src/cli/main.js"), ...liveTestArgs, "recovery-run", operation.id], { cwd, detached: true, stdio: "ignore", env: { ...process.env, AGENTHUB_RECOVERY_OPERATION: operation.id, ...(conductorPeer ? { AGENTHUB_PEER_ID: conductorPeer, AGENTHUB_RECOVERY_CONDUCTOR: conductorPeer } : {}) }, }); child.on("error", () => console.error(`runner launch failed; use ${recoveryCommand(operation, "resume")}`)); child.unref(); // #215: the operation's own coordinator, which has every recovery command; the global ahub may be older mid-upgrade. if (!quiet) { if (presentation) { printRecovery(wrap(`Recovery operation ${operation.id} scheduled.`, presentation.columns)); printRecovery(wrap(`ahub recovery status ${operation.id}`, presentation.columns)); if (presentation.verbose) printRecovery(wrap(recoveryCommand(operation, "status"), presentation.columns)); } else console.log(`Recovery operation ${operation.id} scheduled.\n${recoveryCommand(operation, "status")}`); } } /** #272: a terminal session for the interactive screens. One line reader for the whole session, in the terminal's own * line mode, so Ctrl+C stays a signal: from then on every question answers null and the screens leave. The terminal * is not read again after it (a parent that died on the same Ctrl+C may have handed it back to the shell), and no * runner is ever stopped by it. */ async function onTerminal(screens: (io: ScreenIO) => Promise, presentation?: RecoveryPresentationOptions): Promise { const rl = lineReader({ input: process.stdin, terminal: false }); const lines: string[] = [], waiters: ((line: string | null) => void)[] = []; let ended = false, interrupted = false; rl.on("line", (line) => { const next = waiters.shift(); if (next) next(line.trim()); else lines.push(line.trim()); }); rl.on("close", () => { ended = true; for (const waiter of waiters.splice(0)) waiter(null); }); const onInterrupt = () => { interrupted = true; for (const waiter of waiters.splice(0)) waiter(null); }; process.on("SIGINT", onInterrupt); try { await screens({ ...(presentation ? { presentation: { ...presentation, get columns() { return process.stdout.columns ?? presentation.columns; } } } : {}), ask: (question) => { if (interrupted) return Promise.resolve(null); process.stdout.write(question); const typed = lines.shift(); return typed !== undefined ? Promise.resolve(typed) : ended ? Promise.resolve(null) : new Promise((resolve) => waiters.push(resolve)); }, out: (line) => console.log(line), run: (argv) => new Promise((resolve) => { // The command owns the terminal while it runs; a reader whose input already ended has nothing to pause. if (!ended) rl.pause(); const done = (code: number) => { if (!ended) rl.resume(); resolve(code); }; const formatting = presentation && argv[1] === "recovery" ? recoveryFormatting(argv[0]!, presentation) : []; // A capable screen child updates the receipt; its parent owns the human view after the action. // Older coordinators keep their existing terminal contract and receive no unsupported JSON flag. const quiet = formatting.length > 0; const child = spawn(process.execPath, [argv[0]!, ...liveTestArgs, ...argv.slice(1), ...formatting, ...(quiet ? ["--json"] : [])], { cwd, stdio: quiet ? ["inherit", "ignore", "inherit"] : "inherit", }); child.on("error", () => done(1)); child.on("close", (code) => done(code ?? 1)); }), sleep: (ms) => Bun.sleep(ms), interrupted: () => interrupted, // Scripted input (a pipe) is answers typed ahead for the next question; only a terminal's line is a key press. typed: () => !ended && lines.splice(0).length > 0, }); } finally { process.off("SIGINT", onInterrupt); rl.close(); } } function upgradeHost(kind: "restart" | "upgrade", version: string): UpgradeHost { const scope = cwd; return { plan: () => makeUpgradePlan(kind, version, scope), apply: async (plan, interrupted) => { assertLifecycleAvailable(cwd); const current = await makeUpgradePlan(kind, plan.version, scope); if (current.fingerprint !== plan.fingerprint) throw new Error("the plan changed during review; review it again"); // The check above takes seconds: a Ctrl+C in that time is still a no. if (interrupted()) throw new Error("interrupted; nothing was started"); const operation = createOperation(plan, preserveSource(plan), undefined, delegatedPeer ? { peer: delegatedPeer, command: kind } : undefined); spawnRecovery(operation, true); return operation; }, lock: (projectRoot = cwd) => recoveryLock(undefined, projectRoot), read: (id) => readOperation(id), runner: recoveryRunner, live: (op) => liveProjects(op, makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer).inspect), endInspection: recoveryEndInspection, afterCompleted: (op) => globalUpdateLines(op.plan.version), endPeer: (planned, peer) => endPlannedPeer(planned, peer), reattachTerminals: (planned, terminals) => reattachPlannedTerminals(planned, terminals), runnerStoppable: (id) => signedRunner(id) !== undefined, stopRunner: (id) => stopSignedRunner(id), entry: join(import.meta.dir, "main.js"), version: VERSION, }; } /** * #718 (#1179): the step for the global CLI and the shared Claude plugin, when either is older than the daemon `target` installs. The plugin version comes from the same `claude plugin list` * probe `ahub doctor` reads (10 s, no shell); a missing `claude`, a failure or an unreadable list is an unknown plugin, which is never a claim. The CLI is this process, or, when an older CLI handed the * upgrade to this release's own coordinator (`AGENTHUB_UPGRADE_HANDOVER=1`), the older one that started it. Advice only: nothing here can fail an upgrade. */ function globalUpdateLines(target: string): string[] { return globalUpdateAdvice({ target, cli: VERSION, handedOver: process.env.AGENTHUB_UPGRADE_HANDOVER === "1", packageRoot: join(import.meta.dir, "..", ".."), probe: () => spawnSync(DOCTOR_PLUGIN_PROBE.command, [...DOCTOR_PLUGIN_PROBE.argv], { encoding: "utf8", timeout: 10_000 }) }); } /** * #1540: `ahub upgrade` for a project whose hub is stopped (this one, or every registered one with `--all-stopped`): the runtime selection is rewritten and nothing else is started or recorded. * True when it handled the command. A single project whose hub is running, or that is not registered, is left to the ordinary recovery plan. */ async function stoppedUpgrade(to: string, all: boolean, display: ReturnType, yes: boolean, dry: boolean): Promise { let plan: Awaited>; try { plan = await planStoppedRetargets(to, all ? "all" : { root: cwd }); } catch (error) { return fail((error as Error).message); } // One project whose hub is not positively stopped (or missing) keeps the ordinary plan, with its own blockers; "unknown" is never read as stopped. if (!all && !plan.rows.some((row) => row.inspected === "stopped" || row.inspected === "missing")) return false; if (display.json) { if (!yes || dry) console.log(JSON.stringify(plan, null, 2)); for (const blocker of plan.blockers) console.error(`ahub: blocker: ${blocker}`); } else printRecovery(renderStoppedPlan(plan, VERSION, display.options, yes && !dry)); if (dry) return true; if (plan.blockers.length) fail("plan has blockers; no runtime was changed"); const retargets = plan.rows.filter((row) => row.outcome === "retarget"); // Nothing to retarget is still an outcome: a JSON consumer of an idempotent `--yes` run gets the same results document the apply path prints, with no results. if (!retargets.length) { if (display.json && yes) console.log(JSON.stringify({ version: plan.version, results: [] }, null, 2)); return true; } // The runtime selection decides which code runs a project next: that is the person's choice, as the plan of a running hub is for a conductor only with its source-issued proof. if (conductorPeer || delegatedPeer) fail("retargeting a stopped project's runtime is the person's: run it in ahub console or a terminal; no runtime was changed"); if (!yes) { if (!process.stdin.isTTY) fail("review --dry-run and use --yes in non-interactive sessions"); const rl = createInterface({ input: process.stdin, output: process.stdout }); try { if (!/^(y|yes)$/i.test((await rl.question(`Retarget ${retargets.length} stopped project${retargets.length === 1 ? "" : "s"} without starting ${retargets.length === 1 ? "its hub" : "their hubs"}? [y/N] `)).trim())) return true; } finally { rl.close(); } const current = await planStoppedRetargets(to, all ? "all" : { root: cwd }); if (current.fingerprint !== plan.fingerprint) fail("plan changed during review; run the command again"); } const results = await applyStoppedRetargets(plan); const failed = results.filter((result) => result.outcome === "failed"); if (display.json) console.log(JSON.stringify({ version: plan.version, results }, null, 2)); else { printRecovery(renderStoppedResults(results, display.options)); if (!failed.length) printRecovery(globalUpdateLines(plan.version)); } if (failed.length) fail(`${failed.length} of ${results.length} planned retarget${results.length === 1 ? "" : "s"} failed (${failed.map((result) => result.id).join(", ")}); the others stay retargeted`); return true; } async function upgrade(kind: "restart" | "upgrade"): Promise { const display = recoveryDisplay(); const { one, rest } = takeFlags(display.args, ["--to"], []); if (rest.some((a) => !["--dry-run", "--yes", ...(kind === "upgrade" ? ["--all-stopped"] : [])].includes(a)) || (kind === "restart" && one["--to"])) fail("usage: ahub upgrade [--project | --all-stopped] [--to ] [--dry-run] [--yes] | ahub restart [--dry-run] [--yes]"); const yes = rest.includes("--yes"), dry = rest.includes("--dry-run") || (display.json && !yes); const allStopped = rest.includes("--all-stopped"); if (allStopped && selector !== undefined) fail("--all-stopped and --project are conflicting selectors: --all-stopped covers every registered stopped project"); // #272: on a terminal, with neither flag, the plan is reviewed, applied and followed in one session. const interactive = !dry && !yes && humanRecovery(display.json); let to = one["--to"]; if (kind === "upgrade" && !to) { if (yes || (!dry && !interactive)) fail("upgrade requires --to "); to = await latestRelease(); console.error(`ahub: the latest release is ${to}`); } // Before the value reaches a package spec or the registry: a range such as 0.13 would resolve to whatever matches. if (to !== undefined) { try { exactVersion(to); } catch (error) { fail((error as Error).message); } } // An older CLI must not coordinate a newer target (docs/operations.md): the target's own coordinator takes over. if (conductorPeer && kind === "upgrade" && newerVersion(to!, VERSION)) fail("a supporting target coordinator is required; the person runs it in ahub console or a terminal"); if (kind === "upgrade" && newerVersion(to!, VERSION) && process.env.AGENTHUB_UPGRADE_HANDOVER !== "1") { const argv = ["x", "--package", `@staix/agent-hub@${to}`, "ahub", ...(allStopped ? [] : ["--project", cwd]), ...liveTestArgs, "upgrade", "--to", to!, ...rest, ...display.flags, ...(dry && !rest.includes("--dry-run") ? ["--dry-run"] : [])]; console.error(`ahub: ${to} is newer than this CLI (${VERSION}), so its own coordinator runs the upgrade: bun ${argv.join(" ")}`); if (interactive) { const rl = createInterface({ input: process.stdin, output: process.stdout }); try { if (!/^(|y|yes)$/i.test((await rl.question("Continue? [Y/n] ")).trim())) return; } finally { rl.close(); } } // The coordinator owns the terminal from here. This process only waits, and a Ctrl+C meant for that session must not // end it first and hand the terminal back to the shell under it. process.on("SIGINT", () => {}); const code = await new Promise((resolve) => { const child = spawn(process.execPath, argv, { cwd, stdio: "inherit", env: { ...process.env, AGENTHUB_UPGRADE_HANDOVER: "1" } }); child.on("error", (error) => { console.error(`ahub: cannot run bun x: ${error.message}`); resolve(1); }); child.on("close", (status) => resolve(status ?? 1)); }); process.exit(code); } if (kind === "upgrade" && await stoppedUpgrade(to!, allStopped, display, yes, dry)) return; if (kind === "upgrade") console.error("ahub: Kimi now defaults to its own TUI (pull-only) in projects without peers.kimi.start_mode. To keep ACP: ahub settings set peers.kimi.start_mode headless"); if (interactive) return onTerminal((io) => planScreen(upgradeHost(kind, to ?? VERSION), io), display.options); const plan = await makeUpgradePlan(kind, to ?? VERSION, cwd, undefined, conductorPeer); if (conductorPeer) await preflightConductorRecovery(plan, conductorPeer); const jsonApply = display.json && yes && !dry; // #814: a person reading a pipe or a dry run gets the plan screen's rows, with every blocker, reconnect-only session and // fresh start in them. `--json` keeps the document and the stderr lines (#206) exactly as they were. if (display.json) { if (!jsonApply) console.log(JSON.stringify(plan, null, 2)); for (const p of plan.projects) for (const peer of p.reconnectOnly ?? []) console.error(`ahub: ${p.project.id}: ${peer} is reconnect-only (unmanaged session): its plugin reattaches to the new hub; no terminal is closed or relaunched`); for (const p of plan.projects) for (const peer of p.freshStart ?? []) console.error(`ahub: ${p.project.id}: ${peer} restarts as a new session: its thread has no rollout and the hub recorded no turn on it, so nothing is lost`); } else printRecovery(renderUpgradePlan(plan, VERSION, display.options, yes && !dry)); const blockers = [...plan.blockers, ...plan.projects.flatMap((p) => p.blockers.map((b) => `${p.project.id}: ${b}`))]; if (display.json) for (const blocker of blockers) console.error(`ahub: blocker: ${blocker}`); if (dry) return; if (blockers.length) { if (jsonApply) console.log(JSON.stringify(plan, null, 2)); fail(conductorPeer ? "conductor recovery cannot prove this plan; no runtime was changed; the person runs it in ahub console or a terminal" : "plan has blockers; no runtime was changed"); } assertLifecycleAvailable(cwd); if (!yes) { if (!process.stdin.isTTY) fail("review --dry-run and use --yes in non-interactive sessions"); const rl = createInterface({ input: process.stdin, output: process.stdout }); try { if (!/^(y|yes)$/i.test((await rl.question("Apply this project list and restore its sessions? [y/N] ")).trim())) return; } finally { rl.close(); } } const current = await makeUpgradePlan(kind, plan.version, cwd, undefined, conductorPeer); if (current.fingerprint !== plan.fingerprint) fail("plan changed during review; run the command again"); const routingDefaults = conductorPeer ? await preflightConductorRecovery(plan, conductorPeer) : undefined; const sourceRoot = preserveSource(plan); let operation: RecoveryOperation; if (conductorPeer) { const id = randomUUID(); const pending: RecoveryOperation = { schema: 3, id, plan, sourceRoot, createdAt: Date.now(), updatedAt: Date.now(), phase: "pending", step: "stage", ...(routingDefaults ? { conductorRoutingDefaults: routingDefaults } : {}), projects: plan.projects.map(row => ({ id: row.project.id, phase: "pending", terminals: {} })) }; const target = await makeRecoveryDriver().stage(pending); pending.targetRoot = target.root; pending.targetDigest = target.digest; pending.targetFeatures = target.targetFeatures; await issueConductorOperation(pending, conductorPeer); operation = createOperation(plan, sourceRoot, undefined, { peer: conductorPeer, command: kind }, id); operation.targetRoot = target.root; operation.targetDigest = target.digest; operation.targetFeatures = target.targetFeatures; operation.conductorRoutingDefaults = routingDefaults; writeOperation(id, operation); } else operation = createOperation(plan, sourceRoot, undefined, delegatedPeer ? { peer: delegatedPeer, command: kind } : undefined); if (display.json) { spawnRecovery(operation, true); console.log(JSON.stringify(publicOperation(operation), null, 2)); } else { spawnRecovery(operation, false, humanRecovery(false) ? display.options : undefined); // #718: the upgrade is only scheduled here, but the step is already known: the CLI and the plugin are compared with the daemon this upgrade installs. Never in --json, which stays the raw document. if (kind === "upgrade") printRecovery(globalUpdateLines(plan.version)); } if (kind === "upgrade" && yes && !process.stdout.isTTY) { const ended = await awaitOperationEnd(operation, { read: (id) => readOperation(id), runner: (id) => recoveryRunner(id), now: Date.now, sleep: Bun.sleep }); if (ended.phase === "completed") { if (!display.json) console.log(`${kind} to ${plan.version} completed`); return; } fail(ended.phase === "blocked" || ended.phase === "cancelled" ? `${kind} operation ${operation.id} is ${ended.phase}${ended.error ? `: ${ended.error.split("; next actions: ")[0]}` : ""}; ${nextActionsText(ended)}` : `operation ${operation.id} did not finish (its runner stopped, or is still working after the wait limit); ${recoveryCommand(operation, "status")}`); } } /** Strict person command: recorded identity only, no session or terminal overrides. */ function parseRecoveryReattach(argv: readonly string[]): { id: string; peer: TerminalPeer } | undefined { if (argv.length !== 3 || argv[0] !== "reattach" || !operationIdPattern.test(argv[1]!) || !/^[a-z][a-z0-9-]{0,31}$/.test(argv[2]!)) return undefined; const builtin = definitionOf(argv[2]!); if (builtin && builtin.session.launchRecord !== true) return undefined; // Extra peers are resolved against the operation's canonical project by the recovery core, never by suffix. return { id: argv[1]!, peer: argv[2] as TerminalPeer }; } /** #248: `ahub bench run` arguments, checked before anything runs (#933: also before the conductor's admission writes its audit row). */ function benchRunArgs(rest: string[]) { const { one, many, rest: positional } = takeFlags(rest, ["--arm", "--repeat", "--tasks", "--memory"], ["--addon"]); if (one["--memory"] !== undefined && !(MEMORY_MODES as readonly string[]).includes(one["--memory"])) fail(`--memory takes ${MEMORY_MODES.join(", ")}`); // #248: `--addon ripwire=off` declares the arm's add-on state; the run refuses peers that do not match it. const addons: Partial> = {}; for (const spec of many["--addon"] ?? []) { const [name, state] = spec.split("="); if (!name || !isAddon(name) || (state !== "on" && state !== "off") || addons[name]) fail(`--addon takes =on|off once per add-on, name one of ${ADDONS.join(", ")}`); addons[name] = state; } const suite = positional[0]; const repeat = one["--repeat"] === undefined ? 1 : Number(one["--repeat"]); if (!suite || positional.length !== 1 || !one["--arm"]?.trim() || !Number.isSafeInteger(repeat) || repeat < 1 || repeat > 100) { fail("usage: ahub bench run --arm