import { A as AgentModelConfig, C as resolveModelFallbacks, D as updateAgentIdentity, E as updateAgent, O as AgentBinding, S as resolveDefaultAgentId, T as saveAgentsConfig, _ as removeAgent, a as profileConfigDir, b as resolveAgentIdByBinding, c as ProfileConfig, f as getAgentConfig, g as normalizeAgentId, h as loadAgentsConfig, i as mergeProfileConfig, j as AgentsConfig, k as AgentConfig, l as addAgent, m as listBindings, n as defaultConfigDir, o as CommandRule, p as listAgents, r as loadMergedProfileConfig, s as CommandRuleGroup, t as PROFILE_CONFIG_FILE, u as addBinding, v as removeBindings, w as resolveModelString, x as resolveAgentsConfigPath, y as resolveAgentDir } from "./index-BiTkuxB4.js"; import { $ as AgentTeamScanOptions, $n as PluginHookBeforeCompactionResult, $t as ChangeOperationType, A as AgentRuntimePolicyInput, An as rewriteTranscript, Ar as ReadonlyTranscriptSessionAdapter, At as PluginConfigUiHint, B as filterToolsForAgent, Bn as normalizeSessionStoreName, Br as MemoryProviderStatus, Bt as TurnAccounting, C as TranscriptEntry, Cn as loadChangeOperations, Cr as PluginHookSessionEndEvent, Ct as PluginsConfig, D as AgentDefinitionsStats, Dn as loadSystemPromptSnapshot, Dr as PluginHookToolResultResult, Dt as PluginManifestRegistry, E as AgentDefinitionsContext, En as loadSessionMetadata, Er as PluginHookToolResultEvent, Et as validatePluginsConfig, F as agentVisibility, Fn as systemPromptSnapshotPath, Fr as MemoryProvider, Ft as PluginManifestLoadResult, G as resolveAgentDefinitionsContext, Gn as PluginHookAfterToolCallEvent, Gr as OnLogCallback, Gt as GoalEventSource, H as loadAgentDefinitionsFromDir, Hn as PluginExecutionRuntime, Hr as MemorySearchResult$1, Ht as flushAccounting, I as buildAgentDelegationPrompt, In as toolResultsDir, Ir as MemoryProviderContext, It as PluginOrigin, J as AgentTeamDefinition, Jn as PluginHookAgentStartEvent, Jt as ChangeDocument, K as scanAgentDefinitions, Kn as PluginHookAgentContext, Kt as appendGoalEvent, L as buildAgentTaskPrompt, Ln as transcriptPath, Lr as MemoryProviderFactory, Lt as AccountingFlushResult, M as AgentVisibility, Mn as sessionDir, Mr as MemoryChangedEvent, Mt as PluginDiscoveryResult, N as SYSTEM_AGENTS_DIR, Nn as sessionMemoryPath, Nr as MemoryChangedHandler, Nt as PluginKind, O as AgentDirectoryCandidate, On as loadTranscript, Or as PluginHookTurnEndEvent, Ot as loadPluginManifestRegistry, P as agentDirCandidates, Pn as sessionsDir, Pr as MemoryMaintenanceOptions, Pt as PluginManifest, Q as AgentTeamReferenceValidation, Qn as PluginHookBeforeCompactionEvent, Qt as ChangeOperationName, R as createAgentDefinitionsContext, Rn as updateSessionMetadata, Rr as MemorySearchOptions, Rt as GoalAccounting, S as ThinkingLevel, Sn as listSessions, Sr as PluginHookResourcesDiscoverResult, St as PluginEntryConfig, T as AgentDefinition, Tn as loadSessionContextSnapshot, Tr as PluginHookSessionStartEvent, Tt as normalizePluginsConfig, U as parseAgentDefinition, Un as PluginHookAfterCompactionEvent, Ur as ToolLoopDetectionConfig, Ut as GoalEventAction, V as findAgentDefinition, Vn as RunEventDispatcher, Vr as MemoryRebuildSummary, Vt as WallClockAccounting, W as publicAgentDefinitions, Wn as PluginHookAfterPromptBuildEvent, Wr as AgentLogEntry, Wt as GoalEventRecord, X as AgentTeamDefinitionErrorCode, Xn as PluginHookBeforeAgentStartEvent, Xt as ChangeOperation, Y as AgentTeamDefinitionError, Yn as PluginHookAssistantMessageEndEvent, Yt as ChangeOpInput, Z as AgentTeamDirectoryCandidate, Zn as PluginHookBeforeAgentStartResult, Zt as ChangeOperationInput, _ as CallbackPayload, _n as ensureSession, _r as PluginHookMemoryChangedEvent, _t as loadSkillsWithPluginDirs, a as PluginToolOptions, an as SessionInspection, ar as PluginHookBeforeProviderRequestResult, at as resolveAgentTeamDefinition, b as PiExtensionDialogBridge, bn as inspectSession, br as PluginHookRegistry, bt as LlmApiFormat, c as PluginUiToolOptions, cn as appendChangeOperation, cr as PluginHookContextEvent, ct as AllowedSkills, d as UiToolOptions, dn as artifactsPath, dr as PluginHookDreamGateResult, dt as SkillViewResult, en as CronExecutionRecord, er as PluginHookBeforeModelResolveEvent, et as SYSTEM_AGENT_TEAMS_DIR, f as createUiTool, fn as changesPath, fr as PluginHookHandlerMap, ft as buildSkillsPrompt, g as AgentRunResult, gn as cronExecutionsPath, gr as PluginHookLlmOutputEvent, gt as loadSkillsFromDirs, h as AgentRunParams, hn as createSession, hr as PluginHookLlmInputEvent, ht as loadSkills, in as SessionExport, ir as PluginHookBeforeProviderRequestEvent, it as parseAgentTeamDefinition, j as AgentScanOptions, jn as saveSessionMetadata, jr as MemoryChangeSource, jt as PluginDiagnostic, k as AgentRuntimePolicy, kn as metadataPath, kr as PluginHookTurnStartEvent, kt as PluginCandidate, l as RegisteredPluginTool, ln as appendCronExecutionRecord, lr as PluginHookContextResult, lt as Skill, m as AgentProgressEvent$2, mn as contextSnapshotPath, mr as PluginHookInputResult, mt as loadSkillView, nn as ForkSessionResult, nr as PluginHookBeforePromptBuildEvent, nt as buildAgentTeamPrompt, o as PluginToolRegistry, on as SessionMetadataUpdate, or as PluginHookBeforeToolCallEvent, ot as scanAgentTeamDefinitions, p as defaultUiToolInputSchema, pn as collapseLogPath, pr as PluginHookInputEvent, pt as findSkillByName, q as AgentTeamConfigSource, qn as PluginHookAgentEndEvent, qt as goalEventsPath, rn as MAX_CHANGE_CONTENT_CHARS, rr as PluginHookBeforePromptBuildResult, rt as loadAgentTeamDefinitionsFromDir, s as PluginUiToolDescriptor, sn as SessionPathOptions, sr as PluginHookBeforeToolCallResult, st as validateAgentTeamDefinitionReferences, tn as ForkSessionParams, tr as PluginHookBeforeModelResolveResult, tt as agentTeamDirCandidates, u as UiToolInputSchema, un as appendTranscriptEntry, ur as PluginHookDreamGateEvent, ut as SkillDirectory, v as Channel, vn as exportSession, vr as PluginHookName, vt as skillsDir, w as AgentConfigSource, wn as loadCronExecutionRecords, wr as PluginHookSessionResetEvent, wt as PluginsConfigValidationResult, x as SubagentContext, xn as listSessionSummaries, xr as PluginHookResourcesDiscoverEvent, xt as NormalizedPluginsConfig, y as CompactionEntry, yn as forkSessionFromMessage, yr as PluginHookRegistration, yt as TopicSegmentationConfig, z as filterSkillsForAgent, zn as DEFAULT_SESSION_STORE_NAME, zr as MemoryIndexManager, zt as TokenUsage } from "./loader-CCcKMJve.js"; import { A as LlmChatResult, C as EmbeddingProvider, D as createPluginProgressEmitter, E as PluginProgressEmitter, O as PluginRuntime, S as resolveEmbeddingProvider, T as PluginCustomProgressInput, _ as EmbeddingProviderContext, a as PluginSystemOptions, b as registerEmbeddingProvider, c as preloadPluginSystem, d as PluginRegistry, f as loadPlugins, g as PluginHitlRequest, h as PluginHitlPauseSignal, i as PluginSystem, k as createPluginRuntime, l as PluginApi, m as PluginHitlPauseInput, n as SystemWarmState, o as getPluginSystem, p as PluginHitlApi, r as prepareSystemRuntime, s as initializePluginSystem, t as PrepareSystemRuntimeOptions, u as PluginRecord, v as EmbeddingProviderFactory, w as PluginRuntimeContext, x as resetEmbeddingProviderRegistryForTests, y as EmbeddingProviderRegistration } from "./system-runtime-BrIhfwzM.js"; import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, AgentTaskItem, AgentTaskStatus, AgentTaskUpdatedEvent, ArtifactDocumentV2, ArtifactOperation, ArtifactRecord, ArtifactRecord as ArtifactRecord$1, CallbackEventPayload, Channel as Channel$1, CollapseSpan, CoreMemoryConfig, GoalStatus, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, MemoryCompactionRecallRuntimeState, MemoryRecallRuntimeState, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RecordArtifactsResult, RunResultPayload, SessionContextSnapshot, SessionMemorySnapshot, SessionMetadata, SessionSummary, SnipRecord, ThreadGoal, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult } from "@gencode/shared"; import { Agent, AgentMessage, AgentTool } from "@earendil-works/pi-agent-core"; import { Message, Type } from "@earendil-works/pi-ai"; //#region src/subagent/types.d.ts /** Status of a spawned subagent run */ type SubagentStatus = "running" | "done" | "error" | "killed" | "paused"; /** Record tracking a single subagent run */ type SubagentRunRecord = { runId: string; childSessionId: string; parentSessionId: string; task: string; label?: string; /** Nesting depth: parent is depth N, child is N+1 */ depth: number; status: SubagentStatus; result?: string; error?: string; startedAt: number; endedAt?: number; /** Used to cancel the subagent run */ abortController: AbortController; /** Present when the subagent was paused for HITL. */ pausedInfo?: { requestId: string; kind: string; title: string; }; }; //#endregion //#region src/subagent/registry.d.ts declare const MAX_SUBAGENT_DEPTH = 2; declare const MAX_CHILDREN_PER_SESSION = 5; /** * In-memory registry for subagent runs scoped to a single parent runAgent call. * Child spawns create their own SubagentRegistry instances for their children. */ declare class SubagentRegistry { private readonly entries; /** RunIds whose terminal result has already been delivered to the parent. */ private readonly announced; register(record: SubagentRunRecord, promise: Promise): void; complete(runId: string, result: string): void; fail(runId: string, error: string): void; /** * Marks a run as paused due to HITL. The subagent's runner has already * written `pending-hitl.json` and emitted `hitl_requested`; this method * only updates the in-memory registry so the parent's `subagent_spawn` * tool can detect the pause and re-throw the signal upward. * * Does NOT set `endedAt` — paused is not a terminal state; the subagent * will resume after the user resolves the HITL request. */ pause(runId: string, pausedInfo: { requestId: string; kind: string; title: string; }): void; /** Aborts and marks a specific run as killed. Returns false if not found or already ended. */ kill(runId: string): boolean; /** Aborts all running subagents for the given parent session. Returns count killed. */ killAll(parentSessionId: string): number; /** Lists all runs registered for the given parent session. */ list(parentSessionId: string): SubagentRunRecord[]; /** Returns true if any subagents for this session are still running. */ hasPending(parentSessionId: string): boolean; /** Count of currently running children for a session. */ countActive(parentSessionId: string): number; /** * Waits until all currently-running subagents for the given session settle. * Returns immediately if nothing is pending. */ waitForAll(parentSessionId: string): Promise; /** * Returns all finished runs whose terminal result has not yet been delivered. * This is a read-only snapshot; callers must explicitly mark delivery after * the result has been handed back to the parent. */ peekCompleted(parentSessionId: string): SubagentRunRecord[]; /** * Returns all finished runs that have not yet been returned by this method, * and marks them as announced so they are not returned again. */ consumeCompleted(parentSessionId: string): SubagentRunRecord[]; /** Marks a finished run as already delivered to its parent. */ markAnnounced(runId: string | string[]): void; /** Returns whether a run's terminal result has already been delivered. */ isAnnounced(runId: string): boolean; /** Returns true if there are completed runs not yet returned by consumeCompleted. */ hasUnannounced(parentSessionId: string): boolean; /** * Returns true if the announce loop should run another iteration: * either subagents are still running, or completed runs await announcement. */ needsAnnounce(parentSessionId: string): boolean; /** Checks whether a new child can be spawned given depth and active-children limits. */ checkSpawnAllowed(parentSessionId: string, depth: number): { allowed: true; } | { allowed: false; reason: string; }; /** Returns the current status snapshot for a single run, or null if not found. */ getStatus(runId: string): SubagentStatus | null; private logTerminalStatus; } //#endregion //#region src/runner/title.d.ts type GenerateTitleParams = { message: string; text?: string; llm: Pick; signal?: AbortSignal; hooks?: PluginHookRegistry; hookCtx?: PluginHookAgentContext; onFallback?: (reason: "timeout" | "error") => void; /** * When `false`, skips the LLM title call and returns a truncated first-message * title (fallback). Defaults to enabled (undefined treated as enabled). */ titleGeneration?: { enabled: boolean; }; }; declare function generateSessionTitle(params: GenerateTitleParams): Promise; //#endregion //#region src/runner/runner.d.ts /** * Runs an agent session end-to-end. * Supports multi-agent: subagent_spawn runs subagents as blocking tool calls. * The announce loop remains for records injected by non-tool entry points. * * @param params - Run parameters. * @param _registryForTesting - Internal: inject a pre-populated registry for unit tests. */ declare function runAgent(params: AgentRunParams, _registryForTesting?: SubagentRegistry): Promise; //#endregion //#region src/llm/generate-once.d.ts type GenerateModelResponseParams = { llm: AgentRunParams["llm"]; input: string; system?: string; timeoutMs?: number; abortSignal?: AbortSignal; }; type GenerateModelResponseResult = LlmChatResult & { durationMs: number; }; declare function generateModelResponse(params: GenerateModelResponseParams): Promise; //#endregion //#region src/session/artifact-store.d.ts type RecordSessionArtifactsOptions = { workspaceDir: string; projectDir?: string; workdirAllowlist?: string[]; urlWhitelist?: string[]; sessionPathOptions?: SessionPathOptions; /** Test-only escape hatch for temporary fixture roots. */ allowTemporaryFiles?: boolean; }; declare function recordSessionArtifacts(dataDir: string, sessionId: string, input: unknown, options: RecordSessionArtifactsOptions): Promise; declare function loadArtifactDocumentV2(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; declare function mergeArtifactRecords(current: ArtifactRecord$1[], incoming: ArtifactRecord$1[]): ArtifactRecord$1[]; //#endregion //#region src/session/session-export-snapshots.d.ts /** * @deprecated No-op. Session export snapshots (`session-tools.json`) were * removed and are no longer written to the session directory. The * `systemPrompt` and `tools` fields are ignored by security policy. */ declare function persistSessionExportSnapshots(dataDir: string, sessionId: string, _snapshots: { systemPrompt?: string; tools: AgentTool[]; }, options?: SessionPathOptions): Promise; //#endregion //#region src/session/session-storage.d.ts declare function readSessionFile(filePath: string): Promise; declare function writeSessionFile(filePath: string, content: string, encrypt?: boolean): Promise; declare function appendSessionFile(filePath: string, line: string, encrypt?: boolean): Promise; declare function atomicWriteSessionFile(filePath: string, content: string, encrypt?: boolean): Promise; declare function readSessionFileContent(filePath: string): Promise; //#endregion //#region src/history/messages.d.ts type EntriesToMessagesOptions = { /** When true, replay non-empty historical assistant thinking into message content. */replayThinking?: boolean; /** Provider field name for replayed thinking blocks (e.g. reasoning_content). */ thinkingSignature?: string; }; //#endregion //#region src/context/session-context-store.d.ts type PersistedToolResult = { content: string; reference?: ToolResultReference; }; type SessionContextStore = { findReusableRead(path: string, offset?: number, limit?: number): Promise; recordRead(params: { path: string; content: string; lineCount: number; offset?: number; limit?: number; }): Promise; invalidatePath(path: string): Promise; persistToolResult(params: { toolCallId: string; toolName: string; content: string; thresholdChars?: number; previewChars?: number; }): Promise; recordSnip(record: SnipRecord): Promise; recordCollapse(span: CollapseSpan): Promise; setSessionMemory(snapshot: SessionMemorySnapshot): Promise; recordModelUsage(checkpoint: ModelUsageCheckpoint): Promise; recordAutocompactResult(params: { layer: "L6"; failed: boolean; timestamp: string; }): Promise; getSnapshot(): SessionContextSnapshot; }; type SessionContextStoreOptions = { dataDir: string; sessionId: string; } & SessionPathOptions; declare function createSessionContextStore(options: SessionContextStoreOptions): Promise; //#endregion //#region src/context/context-manager.d.ts type ManageLayeredHistoryParams = { entries: TranscriptEntry[]; modelInfo: { model: string; api: string; }; contextWindowTokens: number; llm: Pick; historyLimit?: number; compactionEnabled?: boolean; pendingUserMessage?: string; topicSegmentation?: TopicSegmentationConfig; /** Conservative token estimate for the base system prompt and visible tool schemas. */ staticInputTokens?: number; signal?: AbortSignal; hooks?: PluginHookRegistry; hookCtx?: PluginHookAgentContext; contextStore?: SessionContextStore; dataDir?: string; sessionId?: string; messageId?: string; sessionStoreName?: string; sessionPathScope?: Pick; channel?: Channel$1; isSubagent?: boolean; entriesToMessagesOptions?: EntriesToMessagesOptions; }; type ManageLayeredHistoryResult = { messages: AgentMessage[]; priorSummary: string | undefined; compactionEntry: CompactionEntry | undefined; stats: { originalCount: number; keptCount: number; estimatedTokens: number; compacted: boolean; }; compactionEvents: AgentProgressEvent$1[]; }; type ContextManager = { getReusableRead(path: string, offset?: number, limit?: number): Promise<{ reused: boolean; lineCount?: number; }>; rememberRead(params: { path: string; content: string; lineCount: number; offset?: number; limit?: number; }): Promise; invalidateReadPath(path: string): Promise; persistToolResult(params: { toolCallId: string; toolName: string; content: string; thresholdChars?: number; previewChars?: number; }): Promise; recordModelUsage(params: { model: string; inputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; outputTokens: number; totalTokens: number; coveredTranscriptEntryCount: number; recordedAt?: string; }): Promise; recordAutocompactResult(params: { failed: boolean; timestamp?: string; }): Promise; manageHistory(params: Omit): Promise; getSnapshot: SessionContextStore["getSnapshot"]; }; declare function createContextManager(params: { dataDir: string; sessionId: string; sessionStoreName?: string; sessionPathScope?: Pick; }): Promise; //#endregion //#region src/bootstrap/bootstrap.d.ts /** Maximum characters per bootstrap file before truncation */ declare const BOOTSTRAP_MAX_CHARS = 20000; /** Maximum total characters across all bootstrap files */ declare const BOOTSTRAP_TOTAL_MAX_CHARS = 150000; /** Names of bootstrap identity files, in injection order */ declare const BOOTSTRAP_FILE_NAMES: readonly ["AGENTS.md", "SOUL.md", "TOOLS.md", "IDENTITY.md", "USER.md", "MEMORY.md", "BOOTSTRAP.md"]; /** A loaded (or missing) bootstrap file */ type BootstrapFile = { name: string; path: string; content: string | null; missing: boolean; }; /** A bootstrap file ready for system prompt injection */ type BootstrapContextFile = { path: string; content: string; }; /** Resolves the base .aimax directory within a data directory */ declare function aimaxDir(dataDir: string): string; /** * Loads all standard bootstrap identity files from the .aimax directory. * Missing files are included as `missing: true` entries. * BOOTSTRAP.md is deleted after loading (one-time use). */ declare function loadBootstrapFiles(dataDir: string, options?: { includeMemory?: boolean; profilePath?: string; }): Promise; /** * Converts loaded bootstrap files into context file entries for system prompt injection. * Applies per-file and total character budget limits. */ declare function buildBootstrapContextFiles(files: BootstrapFile[], opts?: { maxChars?: number; totalMaxChars?: number; warn?: (message: string) => void; }): BootstrapContextFile[]; //#endregion //#region src/bootstrap/bootstrap-layout.d.ts type BootstrapMountResult = { dataDir: string; createdDirs: string[]; skippedDirs: string[]; createdFiles: string[]; skippedFiles: string[]; }; type BootstrapMountStatus = { dataDir: string; ready: boolean; missingDirs: string[]; missingFiles: string[]; }; type BootstrapEnsureResult = { ready: boolean; performedBootstrap: boolean; result?: BootstrapMountResult; }; declare function hasBootstrapSentinel(dataDir: string): Promise; declare function inspectBootstrapMountLayout(dataDir: string): Promise; declare function isBootstrapMountLayoutReady(dataDir: string): Promise; declare function ensureBootstrapMountLayout(dataDir: string): Promise; declare function bootstrapMountLayout(dataDir: string): Promise; //#endregion //#region src/memory/memory.d.ts /** Resolves the memory root path within a data directory */ declare function memoryDir(dataDir: string): string; /** Resolves the primary MEMORY.md path */ declare function primaryMemoryPath(dataDir: string): string; /** A single search result from memory */ type MemorySearchResult = MemorySearchResult$1; type MemoryCallOptions = { providerId?: string; pluginId?: string; sessionId?: string; onMemoryChanged?: MemoryChangedHandler; }; /** * Lists all memory file paths within the memory directory. * Returns MEMORY.md first, then daily files (YYYY-MM-DD.md) sorted by date descending. */ declare function listMemoryFiles(dataDir: string): Promise; /** * Reads a memory file and returns its content. * Returns null if the file does not exist. */ declare function readMemoryFile(filePath: string): Promise; /** * Reads the primary MEMORY.md file. * Returns null if it does not exist. */ declare function readPrimaryMemory(dataDir: string): Promise; /** * Searches memory files for lines matching a query string (case-insensitive substring match). * Returns matching lines with their file path and line number. */ declare function searchMemory(dataDir: string, query: string, options?: MemoryCallOptions, searchOptions?: MemorySearchOptions): Promise; /** * Reads specific line ranges from a memory file. * Returns the requested lines (1-based line numbers), or null if file not found. */ declare function getMemoryLines(dataDir: string, filePath: string, startLine: number, endLine: number, options?: MemoryCallOptions): Promise; /** * Appends content to the primary MEMORY.md file, creating it if necessary. */ declare function appendToMemory(dataDir: string, content: string, options?: MemoryCallOptions): Promise; /** * Appends a daily or session log entry via provider.appendRecent(). * Falls back to appendToMemory() when the provider does not implement appendRecent. */ declare function appendRecentToMemory(dataDir: string, content: string, scope: "daily" | "session", options?: MemoryCallOptions): Promise; declare function replaceMemoryFile(dataDir: string, filePath: string, content: string, options?: MemoryCallOptions): Promise; declare function deleteMemoryFile(dataDir: string, filePath: string, options?: MemoryCallOptions): Promise; //#endregion //#region src/memory/builtin-provider.d.ts declare function createBuiltinMemoryProvider(ctx: MemoryProviderContext, options?: { includeSessions?: boolean; }): MemoryProvider; //#endregion //#region src/memory/provider-registry.d.ts type MemoryProviderRegistration = { id: string; pluginId?: string; create: MemoryProviderFactory; config?: Record; rootDir?: string; source?: string; }; declare function registerMemoryProvider(params: { pluginId: string; create: MemoryProviderFactory; id?: string; config?: Record; rootDir?: string; source?: string; }): string; declare function resolveMemoryProvider(params: { providerId?: string; pluginId?: string; dataDir: string; memoryDir: string; sessionId?: string; sessionStoreName?: string; }): { provider: MemoryProvider; registration: MemoryProviderRegistration; } | null; declare function resetMemoryProviderRegistryForTests(): void; //#endregion //#region src/memory/default-provider.d.ts type DefaultMemoryProviderOptions = { includeSessions?: boolean; }; type ResolveMemoryProviderOrDefaultParams = { providerId?: string; pluginId?: string; dataDir: string; memoryDir: string; sessionId?: string; sessionStoreName?: string; includeSessions?: boolean; }; type ResolvedMemoryProviderOrDefault = { provider: MemoryProvider; registration?: MemoryProviderRegistration; providerId: string; pluginId?: string; providerSource: "plugin" | "builtin"; fallbackToBuiltin: boolean; }; declare function createDefaultMemoryProvider(ctx: MemoryProviderContext, options?: DefaultMemoryProviderOptions): MemoryProvider; declare function resolveMemoryProviderOrDefault(params: ResolveMemoryProviderOrDefaultParams): ResolvedMemoryProviderOrDefault; //#endregion //#region src/auto-skills/paths.d.ts declare function autoSkillsDir(dataDir: string): string; //#endregion //#region src/auto-skills/types.d.ts type AutoSkillSource = "auto"; type AutoSkillStatus = "active" | "archived"; type AutoSkillCategory = { path: string; name: string; description: string; createdBy?: string; }; type AutoSkillIndexEntry = { skillId: string; name: string; description: string; categoryPath: string; source: AutoSkillSource; status: AutoSkillStatus; rootDir: string; skillDir: string; skillFile: string; metadataFile?: string; tags: string[]; relatedSkills: string[]; confidence?: number; createdAt?: string; updatedAt?: string; }; type AutoSkillListItem = { skillId: string; name: string; description: string; categoryPath: string; source: AutoSkillSource; }; type AutoSkillSearchResult = AutoSkillListItem & { score: number; }; type AutoSkillViewResult = AutoSkillListItem & { status: AutoSkillStatus; content: string; path: string; skillDir: string; filePath?: string; tags?: string[]; relatedSkills?: string[]; }; type AutoSkillsLoaderOptions = { dataDir?: string; rootDir?: string; includeArchived?: boolean; maxSkillBytes?: number; maxResourceBytes?: number; }; type AutoSkillListOptions = { categoryPath?: string; recursive?: boolean; }; type AutoSkillSearchOptions = { query: string; limit?: number; }; type AutoSkillViewOptions = { skillId: string; filePath?: string; }; //#endregion //#region src/auto-skills/loader.d.ts declare function createAutoSkillsLoader(options: AutoSkillsLoaderOptions): AutoSkillsLoader; declare class AutoSkillsLoader { readonly rootDir: string; private readonly includeArchived; private readonly maxSkillBytes; private readonly maxResourceBytes; constructor(options: AutoSkillsLoaderOptions); autoSkillCategories(): Promise; autoSkillList(options?: AutoSkillListOptions): Promise; autoSkillSearch(options: AutoSkillSearchOptions): Promise; autoSkillView(options: AutoSkillViewOptions): Promise; loadIndex(): Promise; private loadIndexState; private parseEntriesFromManifest; private visibleEntries; private visibleEntriesFrom; private optionsHash; private loadEntry; } //#endregion //#region src/commands/types.d.ts type SlashCommandSpec = { name: string; description: string; }; type SlashCommandList = { builtin: SlashCommandSpec[]; skillCommands: SlashCommandSpec[]; all: SlashCommandSpec[]; }; //#endregion //#region src/commands/registry.d.ts declare function listAvailableSlashCommands(skills: Skill[], extensionCommands?: Map unknown; }>): SlashCommandList; //#endregion //#region src/commands/goal.d.ts /** Structured multiline template shown in `/goal help`. */ declare const GOAL_MULTILINE_TEMPLATE_EXAMPLE: string; /** Reply text for `/goal help` in chat sessions. */ declare function buildGoalSlashHelpText(): string; /** Extra help appended to `aimax goal --help`. */ declare function buildAimaxGoalCliHelpExtra(): string; //#endregion //#region src/system-prompt/builder.d.ts type PromptMode = "full" | "minimal" | "none"; type MemoryCitationsMode = "off" | "on"; type SystemPromptParams = { dataDir: string; projectDir?: string; projectAgentsFile?: BootstrapContextFile; skills?: Skill[]; contextFiles?: BootstrapContextFile[]; runtimeInfo?: { os?: string; shell?: "bash" | "cmd"; node?: string; model?: string; hostname?: string; }; toolNames?: string[]; toolSummaries?: Record; autoSkillCategories?: AutoSkillCategory[]; promptMode?: PromptMode; bootstrapWarnings?: string[]; memoryCitationsMode?: MemoryCitationsMode; /** Whether durable/cross-session memory is available to this runtime. Defaults to true. */ memoryEnabled?: boolean; sandboxInfo?: { enabled?: boolean; hostWorkspaceDir?: string; containerWorkspaceDir?: string; }; messaging?: { enabled?: boolean; channels?: string[]; }; currentDate?: string; timezone?: string; /** Override for the preset system prompt (opening paragraph). */ presetSystemPrompt?: string; /** Custom agent prompt body used for a named subagent. */ activeAgentSystemPrompt?: string; /** Custom agents visible to the main agent for delegation decisions. */ availableAgents?: AgentDefinition[]; /** Active team context; when set, only its members are advertised for delegation. */ activeAgentTeam?: { definition: AgentTeamDefinition; members: AgentDefinition[]; userInput: string; }; /** * Nesting depth of this agent run (0 = root, 1 = first-level subagent, …). * When > 0, an explicit constraint section is injected to discourage further * subagent spawning. */ subagentDepth?: number; /** * Summary of prior conversation history produced by compaction. * When provided, it is appended to the system prompt so the agent * understands what happened before the retained message window. */ priorConversationSummary?: string; }; /** * Builds the complete system prompt for the agent. * Assembles all sections in the correct order. */ declare function buildSystemPrompt(params: SystemPromptParams): string; //#endregion //#region src/tools/process-registry.d.ts type ProcessStatus = "running" | "completed" | "failed" | "killed" | "timeout"; type ProcessSessionSnapshot = { sessionId: string; scopeKey?: string; command: string; cwd: string; pid?: number; startedAt: number; endedAt?: number; status: ProcessStatus; exitCode?: number | null; exitSignal?: NodeJS.Signals | null; outputTail: string; stdoutTail: string; stderrTail: string; outputTruncated: boolean; }; type ProcessLogSlice = { sessionId: string; status: ProcessStatus; text: string; totalLines: number; totalChars: number; truncated: boolean; exitCode?: number | null; exitSignal?: NodeJS.Signals | null; }; type ProcessOutput = { sessionId: string; status: ProcessStatus; stdout: string; stderr: string; combined: string; truncated: boolean; exitCode?: number | null; exitSignal?: NodeJS.Signals | null; }; type ProcessStartParams = { command: string; cwd: string; env?: Record; /** * Run-level baseline env, applied after `process.env` but before `env`. * Used to carry session-scoped env from the AgentRunParams through to * the spawned child process. */ baseEnv?: Record; timeoutSec: number; scopeKey?: string; }; type ProcessRegistry = { start(params: ProcessStartParams): ProcessSessionSnapshot; get(sessionId: string, scopeKey?: string): ProcessSessionSnapshot | null; list(scopeKey?: string): ProcessSessionSnapshot[]; wait(sessionId: string, scopeKey: string | undefined, timeoutMs?: number): Promise; readLog(params: { sessionId: string; scopeKey?: string; offset?: number; limit?: number; }): ProcessLogSlice | null; readOutput(sessionId: string, scopeKey?: string): ProcessOutput | null; terminate(sessionId: string, scopeKey?: string): Promise; /** * Best-effort teardown of every still-running process at run boundary. Since * children are spawned detached (their own process group on POSIX), the host * process exiting no longer reaps them automatically — a background `server` * the agent never killed would be orphaned. Called from the runner's finally * block so a finished run leaves no live exec processes behind. */ disposeAll(): void; }; //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/schema.d.mts interface TSchema {} //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/array.d.mts /** Represents an Array type. */ interface TArray extends TSchema { '~kind': 'Array'; type: 'array'; items: Type; } //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/object.d.mts /** Represents an Object type. */ interface TObject extends TSchema { '~kind': 'Object'; type: 'object'; properties: Properties; required: TRequiredArray; } //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/engine/helpers/union.d.mts type TUnionToIntersect = (U extends unknown ? (arg: U) => 0 : never) extends ((arg: infer I) => 0) ? I : never; type TUnionLast = TUnionToIntersect 0 : never> extends ((x: infer L) => 0) ? L : never; type TUnionToTuple> = [U] extends [never] ? Result : TUnionToTuple, [Extract, ...Result]>; //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/literal.d.mts type TLiteralTypeName = (Value extends bigint ? 'bigint' : Value extends boolean ? 'boolean' : Value extends number ? 'number' : Value extends string ? 'string' : never); type TLiteralValue = string | number | boolean | bigint; /** Represents a Literal type. */ interface TLiteral extends TSchema { '~kind': 'Literal'; type: TLiteralTypeName; const: Value; } //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/number.d.mts /** Represents a Number type. */ interface TNumber extends TSchema { '~kind': 'Number'; type: 'number'; } //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/string.d.mts /** Represents a String type. */ interface TString extends TSchema { '~kind': 'String'; type: 'string'; } //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/union.d.mts /** Represents a logical Union type. */ interface TUnion extends TSchema { '~kind': 'Union'; anyOf: Types; } //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/_optional.d.mts type TOptional = (Type & { '~optional': true; }); //#endregion //#region ../../node_modules/.pnpm/typebox@1.3.4/node_modules/typebox/build/type/types/properties.d.mts /** Represents a Record structure. */ interface TProperties extends TSchema { [key: PropertyKey]: TSchema; } /** Creates a RequiredArray derived from the given TProperties value. */ type TRequiredArray ? never : Key]: Properties[Key] }, RequiredKeys extends string[] = TUnionToTuple>, Result extends string[] | undefined = (RequiredKeys extends [] ? undefined : RequiredKeys)> = Result; //#endregion //#region src/tools/memory.d.ts type MemoryToolOptions = { providerId?: string; pluginId?: string; sessionId?: string; sessionStoreName?: string; llm?: Pick; onMemoryChanged?: MemoryChangedHandler; }; declare const memorySearchSchema: TObject<{ query: TString; }>; type SearchResult = { matches: Array<{ id?: string; file: string; start_line: number; end_line: number; score: number; text: string; source: string; citation?: string; }>; }; declare function createMemorySearchTool(dataDir: string, options?: MemoryToolOptions): AgentTool; declare const memoryGetSchema: TObject<{ file: TString; start_line: TNumber; end_line: TNumber; }>; type GetResult = { lines: string[] | null; }; declare function createMemoryGetTool(dataDir: string, options?: MemoryToolOptions): AgentTool; declare const memoryAppendSchema: TObject<{ content: TString; }>; /** @deprecated Use createMemoryWriteTool with section omitted for flat append. Kept for backward compat. */ declare function createMemoryAppendTool(dataDir: string, options?: MemoryToolOptions): AgentTool; declare const memoryWriteSchema: Type.TObject<{ section: Type.TOptional; content: Type.TString; mode: Type.TUnion<[Type.TLiteral<"append">, Type.TLiteral<"replace">]>; }>; declare function createMemoryWriteTool(dataDir: string, options?: MemoryToolOptions): AgentTool; declare const memoryLogSchema: Type.TObject<{ content: Type.TString; scope: Type.TOptional, Type.TLiteral<"session">]>>; }>; declare function createMemoryLogTool(dataDir: string, options?: MemoryToolOptions): AgentTool; declare const memoryListSchema: Type.TObject<{ scope: Type.TOptional, Type.TLiteral<"recent">, Type.TLiteral<"all">]>>; }>; declare function createMemoryListTool(dataDir: string, options?: MemoryToolOptions): AgentTool; }>; }>; declare const memoryForgetSchema: Type.TObject<{ id: Type.TOptional; query: Type.TOptional; limit: Type.TOptional; scope: Type.TOptional, Type.TLiteral<"recent">, Type.TLiteral<"all">]>>; }>; declare function createMemoryForgetTool(dataDir: string, options?: MemoryToolOptions): AgentTool; declare const memoryUpdateSchema: Type.TObject<{ id: Type.TString; content: Type.TString; }>; declare function createMemoryUpdateTool(dataDir: string, options?: MemoryToolOptions): AgentTool; //#endregion //#region src/tools/update-task.d.ts type TaskUpdatedReporter = (event: Extract) => Promise; //#endregion //#region src/tools/record-artifacts.d.ts type ArtifactPersistenceState = { failure?: string; /** Successful records produced by record_artifacts calls in this agent loop only. */ artifacts?: ArtifactRecord$1[]; /** File operations successfully audited during this agent loop only. */ operations?: ArtifactOperation[]; }; //#endregion //#region src/tools/exec.d.ts declare const execSchema: Type.TObject<{ command: Type.TString; workdir: Type.TOptional; env: Type.TOptional>; timeout: Type.TOptional; yieldMs: Type.TOptional; background: Type.TOptional; riskLevel: Type.TOptional, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"critical">, Type.TNull]>>; riskReason: Type.TOptional>; isReadOnly: Type.TOptional>; }>; type ExecToolOptions = { sessionId?: string; workspaceDir: string; registry: ProcessRegistry; scopeKey?: string; contextManager?: ContextManager; hitlResume?: AgentRunParams["hitlResume"]; /** * Run-level baseline environment variables, applied after `process.env` * but before any per-call `params.env`. Used to carry session-scoped * env from `AgentRunParams.env` to the spawned child process. */ baseEnv?: Record; /** Additional roots allowed for resolving command working directories. */ allowedWorkdirRoots?: string[]; }; declare function createExecTool(options: ExecToolOptions): AgentTool>; //#endregion //#region src/tools/process.d.ts declare const processSchema: TObject<{ action: TString; sessionId: TOptional; offset: TOptional; limit: TOptional; timeout: TOptional; }>; type ProcessToolOptions = { registry: ProcessRegistry; scopeKey?: string; }; declare function createProcessTool(options: ProcessToolOptions): AgentTool>; //#endregion //#region src/tools/bash.d.ts /** * Backward-compatible alias kept for existing imports. * New code should use createExecTool + createProcessTool directly. */ declare function createBashTool(workspaceDir: string): AgentTool; //#endregion //#region src/tools/files.d.ts type ChangeRecorder = (operation: ChangeOpInput) => Promise; declare const readFileSchema: TObject<{ path: TString; offset: TOptional; limit: TOptional; }>; type ReadFileResult = { content: string; lines: number; truncated: boolean; }; declare function createReadFileTool(workspaceDir: string, contextManager?: ContextManager): AgentTool; declare const writeFileSchema: TObject<{ path: TString; content: TString; }>; declare function createWriteFileTool(workspaceDir: string, contextManager?: ContextManager, changeRecorder?: ChangeRecorder): AgentTool; declare const editFileSchema: TObject<{ path: TString; old_string: TString; new_string: TString; }>; declare function createEditFileTool(workspaceDir: string, contextManager?: ContextManager, changeRecorder?: ChangeRecorder): AgentTool; declare const listDirSchema: TObject<{ path: TOptional; }>; declare function createListDirTool(workspaceDir: string): AgentTool; //#endregion //#region src/tools/apply-patch.d.ts type ApplyPatchSummary = { added: string[]; modified: string[]; deleted: string[]; }; type ApplyPatchDetails = { summary: ApplyPatchSummary; }; declare const applyPatchSchema: Type.TObject<{ input: Type.TString; }>; type ApplyPatchToolOptions = { sessionId?: string; hitlResume?: AgentRunParams["hitlResume"]; changeRecorder?: (operation: ChangeOpInput) => Promise; }; declare function createApplyPatchTool(workspaceDir: string, options?: ApplyPatchToolOptions): AgentTool; //#endregion //#region src/tools/session-search.d.ts declare const sessionSearchSchema: Type.TObject<{ query: Type.TOptional; role_filter: Type.TOptional, Type.TLiteral<"assistant">, Type.TLiteral<"tool_result">]>>; limit: Type.TOptional; summary_mode: Type.TOptional, Type.TLiteral<"off">]>>; }>; type SessionSearchResult = { session_id: string; summary: string; when: string; source: string; meta?: { summary_source?: "llm" | "llm_fallback_extractive" | "extractive" | "extractive_short_circuit"; snippet?: string; score?: number; summary_error?: string; }; }; type SessionSearchDetails = { mode: "recent" | "query"; query?: string; count: number; results: SessionSearchResult[]; }; declare function createSessionSearchTool(dataDir: string, options?: MemoryToolOptions): AgentTool; //#endregion //#region src/tools/skills.d.ts declare const skillListSchema: Type.TObject<{ category: Type.TOptional; }>; declare const skillLoadSchema: Type.TObject<{ name: Type.TString; skillPath: Type.TOptional; }>; type SkillListResult = { skills: Array>; count: number; }; type SkillLoadToolResult = { name: string; description: string; content: string; path: string; version: string; skillFileMtime: string; }; type SkillUsedReporter = (event: Extract) => Promise; declare function createSkillListTool(dataDir: string, pluginDirs: string[], skillsLoadPaths?: string[], allowedSkills?: AllowedSkills): AgentTool; declare function createSkillLoadTool(params: { dataDir: string; pluginDirs: string[]; skillsLoadPaths?: string[]; sessionId: string; reportSkillUsed?: SkillUsedReporter; allowedSkills?: AllowedSkills; }): AgentTool; //#endregion //#region src/tools/auto-skills.d.ts declare const autoSkillCategoriesSchema: Type.TObject<{}>; declare const autoSkillListSchema: Type.TObject<{ categoryPath: Type.TOptional; recursive: Type.TOptional; }>; declare const autoSkillSearchSchema: Type.TObject<{ query: Type.TString; limit: Type.TOptional; }>; declare const autoSkillViewSchema: Type.TObject<{ skillId: Type.TString; filePath: Type.TOptional; }>; type AutoSkillCategoriesToolResult = { categories: AutoSkillCategory[]; count: number; error?: string; }; type AutoSkillListToolResult = { skills: AutoSkillListItem[]; count: number; error?: string; }; type AutoSkillSearchToolResult = { skills: AutoSkillSearchResult[]; count: number; error?: string; }; type AutoSkillViewToolResult = Partial & { error?: string; }; declare function createAutoSkillCategoriesTool(dataDir: string): AgentTool; declare function createAutoSkillListTool(dataDir: string): AgentTool; declare function createAutoSkillSearchTool(dataDir: string): AgentTool; declare function createAutoSkillViewTool(dataDir: string): AgentTool; //#endregion //#region src/tools/image.d.ts declare const imageSchema: Type.TObject<{ image: Type.TString; prompt: Type.TOptional; model: Type.TOptional; maxBytesMb: Type.TOptional; }>; type ImageResult = { implemented: boolean; error?: string; }; declare function createImageTool(): AgentTool; //#endregion //#region src/tools/subagent-spawn.d.ts declare const spawnTaskSchema: TObject<{ task: TString; label: TOptional; agent: TOptional; }>; declare const spawnSchema: TObject<{ task: TString; label: TOptional; agent: TOptional; }>; declare const batchSpawnSchema: TObject<{ tasks: TArray; }>; type SpawnResult = { status: "done"; childSessionId: string; runId: string; result: string; } | { status: "forbidden"; error: string; } | { status: "error"; childSessionId?: string; runId?: string; error: string; } | { status: "killed"; childSessionId: string; runId: string; error: string; } | { status: "paused"; childSessionId: string; runId: string; pausedInfo: { requestId: string; kind: string; title: string; }; }; type BatchSpawnItemResult = SpawnResult & { index: number; task: string; label?: string; }; type BatchSpawnResult = { status: "done" | "partial_error" | "error"; results: BatchSpawnItemResult[]; }; type InheritedRunParams = Pick; /** Formats the announce message injected into the parent session when a subagent completes. */ declare function buildSubagentAnnounceMessage(params: { task: string; label?: string; status: "done" | "error" | "killed" | "paused"; result?: string; error?: string; }): string; /** * Creates the subagent_spawn tool that allows an agent to delegate tasks to subagents. * * @param registry The parent session's subagent registry. * @param parentSessionId Session ID of the agent doing the spawning. * @param parentSessionDir Absolute filesystem path of the spawning session's directory. * Used to correctly nest child session directories under the parent. * @param depth Current nesting depth of the spawning agent (child will be depth+1). * @param dataDir User data directory (shared between parent and child). * @param channel Channel inherited from the parent session. * @param llm LLM config inherited from the parent. * @param loopDetection Tool-loop detection config inherited from the parent. * @param spawnFn Function that actually runs a child agent (injected to avoid circular imports). */ declare function createSubagentSpawnTool(registry: SubagentRegistry, parentSessionId: string, parentSessionDir: string, depth: number, dataDir: string, channel: AgentRunParams["channel"], llm: AgentRunParams["llm"], loopDetection: ToolLoopDetectionConfig | undefined, inheritedRunParams: InheritedRunParams, spawnFn: (params: AgentRunParams) => Promise): AgentTool; declare function createBatchSubagentSpawnTool(registry: SubagentRegistry, parentSessionId: string, parentSessionDir: string, depth: number, dataDir: string, channel: AgentRunParams["channel"], llm: AgentRunParams["llm"], loopDetection: ToolLoopDetectionConfig | undefined, inheritedRunParams: InheritedRunParams, spawnFn: (params: AgentRunParams) => Promise): AgentTool; //#endregion //#region src/tools/subagents.d.ts declare const ACTIONS: readonly ["list", "kill"]; type SubagentsAction = (typeof ACTIONS)[number]; type SubagentDeliveryStatus = "running" | "pending" | "delivered"; declare const subagentsSchema: TObject<{ action: TUnion<[TLiteral<"list">, TLiteral<"kill">]>; target: TOptional; }>; type SubagentsResult = { action: SubagentsAction; runs?: Array<{ index: number; runId: string; label: string; task: string; status: string; deliveryStatus: SubagentDeliveryStatus; depth: number; runtimeMs: number; result?: string; error?: string; }>; killed?: number; error?: string; text: string; }; /** * Creates the subagents tool for listing and killing spawned subagents. */ declare function createSubagentsTool(registry: SubagentRegistry, parentSessionId: string): AgentTool; //#endregion //#region src/tools/ui-tool-signal.d.ts declare class UiToolPauseSignal extends Error { /** The original tool arguments from the LLM. */ readonly toolArgs: Record; /** Discriminator to reliably identify the signal in catch blocks. */ readonly isUiToolPause: true; /** The fully formed request to emit through events. */ readonly request: UiToolRequest; constructor(/** Unique request identifier. */ requestId: string, /** Session identifier. */ sessionId: string, /** The tool name that produced this signal. */ toolName: string, /** The LLM-generated tool call ID. */ toolCallId: string, /** The front-end output schema used for rendering and submission. */ outputSchema: UiToolOutputSchema, /** Optional custom front-end rendering payload. */ extra: UiToolExtra | undefined, /** The original tool arguments from the LLM. */ toolArgs: Record); } /** * Type-guard that checks if an unknown error is a UiToolPauseSignal. * Handles both `instanceof` and duck-typing for cross-module boundaries. */ declare function isUiToolPauseSignal(error: unknown): error is UiToolPauseSignal; //#endregion //#region src/tools/index.d.ts /** Optional context for enabling subagent tools */ type SubagentToolsContext = { sessionId: string; /** * Runtime-local session id, used to record which session actually performed * an artifact operation. Always refers to the currently executing session. */ runtimeSessionId?: string; /** * Absolute filesystem path of the current (spawning) session's directory. * Passed to createSubagentSpawnTool so it can correctly nest child sessions * under the parent's directory at any depth. */ currentSessionDir: string; registry: SubagentRegistry; parentSessionId: string; /** Depth of the current agent (root = 0) */ depth: number; channel: AgentRunParams["channel"]; llm: AgentRunParams["llm"]; inheritedRunParams?: Pick; loopDetection?: ToolLoopDetectionConfig; autoSkillsLoadEnabled?: boolean; memoryOptions?: MemoryToolOptions; pluginSkillDirs?: string[]; skillsLoadPaths?: string[]; reportSkillUsed?: (event: Extract) => Promise; reportTaskUpdated?: TaskUpdatedReporter; contextManager?: ContextManager; hitlResume?: AgentRunParams["hitlResume"]; eventDispatcher?: RunEventDispatcher; /** Callback that runs a child agent; injected to avoid circular imports */ spawnFn: (params: AgentRunParams) => Promise; /** * Run-level baseline env applied to every spawned child process. Sourced * from `AgentRunParams.env` and inherited by subagent runs. */ baseEnv?: Record; artifactPersistenceState?: ArtifactPersistenceState; /** * Optional pre-created process registry. When supplied, exec/process tools * bind to it instead of a fresh one, letting the caller hold the reference * and tear down lingering background processes at run boundary * (registry.disposeAll). When omitted, a registry is created internally. */ processRegistry?: ProcessRegistry; /** * Undefined inherits every effective skill. An empty array is a strict * deny-all policy for a custom agent that declares `skills: []`. */ allowedSkills?: AllowedSkills; }; /** * Creates the full set of agent tools for a given data directory. * File and exec/process tools are scoped to the workspace directory. * Memory tools are scoped to the data directory's .aimax root * (MEMORY.md + memory/*.md). * Subagent tools (subagent_spawn, subagents) are included when ctx is provided. */ declare function createAgentTools(dataDir: string, ctx?: SubagentToolsContext): AgentTool[]; //#endregion //#region src/tools/ui-tool-session-store.d.ts declare function pendingUiToolPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string; declare function readPendingUiTool(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; declare function createPendingUiTool(dataDir: string, sessionId: string, request: UiToolRequest, options?: SessionPathOptions): Promise; declare function resolvePendingUiTool(dataDir: string, sessionId: string, requestId: string, result: UiToolResult, options?: SessionPathOptions): Promise; declare function clearPendingUiTool(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; //#endregion //#region src/subagent/registry-persist.d.ts /** Persistable subagent run record (without AbortController) */ type PersistedSubagentRunRecord = Omit & { version?: number; }; /** * Loads subagent run records from disk. * Returns an empty map if the file doesn't exist or is invalid. */ declare function loadSubagentRegistryFromDisk(dataDir: string): Promise>; /** * Saves subagent run records to disk. * Only records with a valid endedAt timestamp are persisted * (completed runs are kept for history, running runs are not persisted). */ declare function saveSubagentRegistryToDisk(dataDir: string, runs: Map): Promise; /** * Lists subagent runs for a specific parent session from disk. * Useful for querying historical subagent runs. */ declare function listSubagentRunsFromDisk(dataDir: string, parentSessionId: string): Promise; /** * Cleans up old subagent records from disk. * Removes records older than the specified number of days. */ declare function cleanupOldSubagentRecords(dataDir: string, olderThanDays?: number): Promise; //#endregion //#region src/plugins/discovery.d.ts type PluginDiscoveryOptions = { dataDir?: string; workspaceDir?: string; extraPaths?: string[]; bundledDir?: string; ownershipUid?: number | null; }; declare function discoverAIMaxPlugins(options?: PluginDiscoveryOptions): PluginDiscoveryResult; //#endregion //#region src/plugins/manifest.d.ts declare const PLUGIN_MANIFEST_FILENAME = "aimax.plugin.json"; declare const PLUGIN_MANIFEST_FILENAMES: readonly ["aimax.plugin.json"]; declare function resolvePluginManifestPath(rootDir: string): string; declare function loadPluginManifest(rootDir: string, rejectHardlinks?: boolean): PluginManifestLoadResult; //#endregion //#region src/plugins/tool-hooks.d.ts declare function wrapToolsWithHooks(tools: AgentTool[], ctx: PluginHookAgentContext, runtime: PluginExecutionRuntime): AgentTool[]; //#endregion //#region src/session/goal-store.d.ts type GoalStoreOptions = SessionPathOptions & { eventSource?: GoalEventSource; }; /** Returns the `goal/` directory for a session. */ declare function goalDir(dataDir: string, sessionId: string, options?: SessionPathOptions): string; /** Returns the path to `goal/goal.json` for a session. */ declare function goalPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string; /** Returns the path to `goal/objective.md` for a session. */ declare function goalObjectiveMdPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string; /** * Reads the current `goal/goal.json`; returns `null` if none exists. */ declare function readGoal(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** * Resolves the full objective text for a goal. * If the goal uses `objectiveRef`, reads the referenced markdown file. */ declare function resolveGoalObjective(dataDir: string, sessionId: string, goal: ThreadGoal, options?: SessionPathOptions): Promise; /** * Writes `goal/goal.json` atomically (tmp + rename). * * If `objective` exceeds MAX_GOAL_OBJECTIVE_CHARS, spills to `goal/objective.md` * and sets `objectiveRef` to `"goal/objective.md"`. */ declare function writeGoal(dataDir: string, sessionId: string, goal: Omit & { goalId?: string; createdAt?: string; updatedAt?: string; }, options?: GoalStoreOptions): Promise; type GoalPatch = Partial>; /** * Applies a partial update to an existing goal.json. * Returns the updated goal, or null if no goal exists. * * Objective changes must go through `writeGoal()` (handles spill files). */ declare function updateGoal(dataDir: string, sessionId: string, updates: GoalPatch, options?: GoalStoreOptions): Promise; /** * Removes the entire `goal/` directory for a session. * Also clears the goalStatus mirror. */ declare function deleteGoal(dataDir: string, sessionId: string, options?: GoalStoreOptions): Promise; /** * Syncs the `goalStatus` field in `session.json` to match the current goal. * * This is a **mirror** — the source of truth remains `goal/goal.json`. * Call this whenever the goal status changes (set/update/delete/complete). * * Uses `updateSessionMetadata` which is a no-op if `session.json` doesn't exist yet. */ declare function mirrorGoalStatusToSession(dataDir: string, sessionId: string, status: GoalStatus | null, options?: SessionPathOptions): Promise; //#endregion //#region src/goal/workflow-plan.d.ts declare const CLARIFY_TASK_TITLE = "clarify plan and acceptance"; declare const CLARIFY_ACCEPTANCE_TEXT = "\u8865\u9F50\u540E\u7EED task list\u3001\u6BCF\u4E2A task \u7684\u9A8C\u6536\u9879\u548C\u5F53\u524D\u4E0B\u4E00\u6B65"; type ExtractedWorkflowPlan = { interpretation: string; assumptions: string[]; openQuestions: string[]; tasks: GoalWorkflowTask[]; }; /** * Extracts a lightweight linear task plan from a goal objective. */ declare function extractWorkflowPlanFromObjective(objective: string): ExtractedWorkflowPlan; /** * Renders `goal/plan.md` from machine workflow state and optional plan metadata. */ type GoalPlanRenderMeta = { interpretation?: string; assumptions?: string[]; openQuestions?: string[]; taskPlanNotes?: string; progressLog?: string[]; evidence?: string[]; risks?: string[]; finalSummary?: string; criterionEvidence?: Record; }; declare function renderGoalPlanMarkdown(state: GoalWorkflowState, meta?: GoalPlanRenderMeta): string; //#endregion //#region src/session/goal-workflow-store.d.ts declare const GOAL_WORKFLOW_STATE_VERSION = 1; type GoalWorkflowStatus = "active" | "blocked" | "complete"; type GoalWorkflowTaskStatus = "todo" | "doing" | "blocked" | "done"; type GoalWorkflowTaskKind = "clarify" | "execution"; type GoalWorkflowAcceptanceCriterion = { id: string; text: string; required: boolean; }; type GoalWorkflowTask = { id: string; kind: GoalWorkflowTaskKind; title: string; required: boolean; status: GoalWorkflowTaskStatus; acceptanceCriteria: GoalWorkflowAcceptanceCriterion[]; acceptanceEvidence: string[]; evidenceRefs: string[]; blockedReason: string | null; updatedAt: string; }; type GoalWorkflowState = { version: typeof GOAL_WORKFLOW_STATE_VERSION; goalId: string; status: GoalWorkflowStatus; objective: string; currentTaskId: string | null; tasks: GoalWorkflowTask[]; blockedReason: string | null; finalEvidenceRefs: string[]; completedAt: string | null; updatedAt: string; }; type GoalWorkflowSummary = { workflowStatus: GoalWorkflowStatus; currentTaskId: string | null; currentTaskTitle: string | null; currentTaskStatus: GoalWorkflowTaskStatus | null; blockedReason: string | null; openRequiredTasks: number; doneRequiredTasks: number; finalEvidenceRefs: string[]; }; /** Tool-level warning when `goal/goal.json` exists but workflow was never initialized. */ type GoalWorkflowWarning = "workflow_not_initialized"; type GoalToolWorkflowView = { goalState: GoalWorkflowSummary | null; workflowWarning: GoalWorkflowWarning | null; }; declare class CorruptGoalWorkflowStateError extends Error { readonly rawContentPreview?: string; constructor(message: string, options?: { cause?: unknown; rawContentPreview?: string; }); } type RepairGoalWorkflowStateResult = { ok: true; healthy: true; mode: "healthy" | "absent"; } | { ok: true; mode: "reinitialized"; goalId: string; backedUpState: string | null; }; /** * Serializes goal workflow read-modify-write paths within a single process. * Cross-process writers are out of scope. */ declare function withGoalWorkflowLock(dataDir: string, sessionId: string, options: SessionPathOptions | undefined, fn: () => Promise): Promise; declare function goalWorkflowStatePath(dataDir: string, sessionId: string, options?: SessionPathOptions): string; declare function goalWorkflowPlanPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string; declare function goalArtifactsDir(dataDir: string, sessionId: string, options?: SessionPathOptions): string; /** * Reads `goal/state.json`; returns `null` when absent. */ declare function readGoalWorkflowState(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** * Reinitializes corrupt `goal/state.json` from the saved objective. * Must be called while holding `withGoalWorkflowLock` for the same session/store. */ declare function repairGoalWorkflowState(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** * Returns a compact workflow summary for prompts and tool responses. */ declare function readGoalWorkflowSummary(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** * Resolves the fixed `goalState` / `workflowWarning` view for `get_goal` and completion gates. * * When `goal/goal.json` exists but `goal/state.json` is absent, returns * `workflowWarning: "workflow_not_initialized"`. */ declare function resolveGoalToolWorkflowView(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** * Removes workflow files while keeping the V1 goal record and events log. */ declare function deleteGoalWorkflow(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** * Creates or replaces V2-lite workflow files for a newly created/replaced goal. */ declare function initializeGoalWorkflow(dataDir: string, sessionId: string, params: { goalId: string; objective: string; }, options?: GoalStoreOptions): Promise; //#endregion //#region src/commands/goal-recover.d.ts type GoalRecoveryEvidence = { criterionId: string; summary: string; source: string; }; type GoalRecoveryCompletedTask = { taskId: string; evidence: GoalRecoveryEvidence[]; }; declare function recoverGoalCompletion(params: { dataDir: string; sessionId: string; sessionStoreName?: string; recoveryId: string; summary: string; completedTasks: GoalRecoveryCompletedTask[]; risks?: string[]; }): Promise>; //#endregion //#region src/goal/prompts.d.ts /** Workflow snapshot for continuation / steering prompts (read fresh each turn). */ type GoalWorkflowPromptContext = { workflowStatus: GoalWorkflowStatus; currentTaskId: string | null; currentTaskTitle: string | null; currentTaskKind: GoalWorkflowTaskKind | null; currentTaskStatus: GoalWorkflowTaskStatus | null; blockedReason: string | null; taskBlockedReason: string | null; acceptanceCriteria: GoalWorkflowAcceptanceCriterion[]; requiredTasks: Array<{ taskId: string; title: string; status: GoalWorkflowTaskStatus; acceptanceCriteria: GoalWorkflowAcceptanceCriterion[]; }>; openQuestions: string[]; }; declare const FIRST_TURN_GOAL_WORKFLOW_INTRO = "The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below."; type BuildContinuationPromptOptions = { /** Overrides the default intro line; workflow block and rules are unchanged. */introLine?: string; }; /** * Builds the first-turn workflow steering prompt after `/goal` set or pendingGoal init. */ declare function buildFirstTurnGoalWorkflowPrompt(goal: ThreadGoal, objectiveText: string, workflow: GoalWorkflowPromptContext): string; /** * Builds the continuation prompt for an idle goal continuation turn. * * Tells the model: * - The active objective and budget * - Current workflow task, acceptance criteria, and blocked reason (when present) * - To continue working toward the objective / current task * - Not to mark complete merely because budget is exhausted */ declare function buildContinuationPrompt(goal: ThreadGoal, objectiveText: string, workflow?: GoalWorkflowPromptContext | null, options?: BuildContinuationPromptOptions): string; /** * Builds the budget-limit steering prompt. * * Tells the model the token budget has been exhausted. * The model should wrap up the current turn, summarize progress, * and NOT submit goal complete unless truly done. */ declare function buildBudgetLimitPrompt(goal: ThreadGoal, objectiveText: string): string; /** * Builds the objective-updated steering prompt. * * Injected once when the user replaces the goal objective externally (CLI). * Tells the model the objective has changed and supersedes any previous one. */ declare function buildObjectiveUpdatedPrompt(goal: ThreadGoal, objectiveText: string): string; /** * Builds a hidden user-context message item for goal steering. * * The `` wrapper signals that this should NOT be persisted * to transcript.jsonl. */ interface GoalContextItem { role: "user"; content: string; } declare function buildGoalContextItem(prompt: string): GoalContextItem; /** * Checks if a message content string is a goal context fragment. */ declare function isGoalContext(content: string): boolean; //#endregion //#region src/goal/continuation.d.ts /** * Environment variable to disable goal continuation entirely. * Set to "0" (or any falsy value) to disable. */ declare const ENV_GOAL_CONTINUATION = "AIMAX_GOAL_CONTINUATION"; /** * Per-run continuation state. * Tracks how many continuations have been performed in the current runAgent call. */ declare class ContinuationState { continuationCount: number; lastTurnHadOutput: boolean; /** True after the one-shot budget-limit wrap-up turn has run. */ budgetWrapUpDone: boolean; /** Resets the count (used when user sends a new turn). */ reset(): void; } /** * Loads fresh workflow context for continuation prompts. * Must be called on every continuation turn — never cache across turns. */ declare function loadWorkflowPromptContext(dataDir: string, sessionId: string, options?: { storeName?: string; }): Promise; /** * Checks whether goal continuation is globally enabled via environment variable. */ declare function isContinuationEnabled(): boolean; /** * Checks all continuation gates. * * Returns true if continuation should proceed. */ declare function shouldContinueGoal(dataDir: string, sessionId: string, state: ContinuationState, options?: { storeName?: string; }): Promise; type GoalContinuationTurnResult = { text: string; inputTokens: number; outputTokens: number; error?: string; toolResultCount?: number; }; /** True when a continuation turn produced assistant text or tool results. */ declare function continuationTurnHadMeaningfulOutput(turn: GoalContinuationTurnResult): boolean; type GoalContinuationInput = { agent: Agent; dataDir: string; sessionId: string; sessionStoreName?: string; state: ContinuationState; accounting: GoalAccounting; abortSignal?: AbortSignal; /** Callback to execute a turn with the given prompt string */ executeTurn: (prompt: string) => Promise; /** Callback to flush accounting after continuation turn */ flushAccountingAfterTurn?: (usage: TokenUsage) => Promise; }; /** * Attempts to start a goal continuation turn. * * Returns true if a continuation was started, false if gates prevent it. */ declare function maybeContinueGoalIfIdle(input: GoalContinuationInput): Promise; //#endregion //#region src/goal/cli-apply.d.ts declare class GoalConflictError extends Error { readonly existingObjectivePreview: string; constructor(message: string, existingObjectivePreview: string); } type ApplyCliGoalInput = { dataDir: string; sessionId: string; objective: string; /** undefined = leave budget unchanged; null = unlimited */ tokenBudget?: number | null; force?: boolean; storeName?: string; }; type ApplyCliGoalResult = { action: "created"; goal: ThreadGoal; } | { action: "replaced"; goal: ThreadGoal; } | { action: "unchanged"; goal: ThreadGoal; } | { action: "updated"; goal: ThreadGoal; }; /** * Applies an external goal set from CLI `run --goal` / `resume --goal`. * * - No existing goal → create * - Same canonical objective → preserve goalId/progress (optional budget/status patch) * - Different objective → requires `force`, otherwise throws GoalConflictError */ declare function applyCliGoalBeforeRun(input: ApplyCliGoalInput): Promise; //#endregion //#region src/goal/steering.d.ts type ObjectiveUpdatedSteeringPrep = { prompt: string | Message[]; /** True when an objective-updated steering block was prepended (flag not yet cleared). */ hadObjectiveUpdatedSteering: boolean; }; type BlockedWorkflowRecoveryResult = { recovered: boolean; taskId?: string; reason?: string; }; type FirstGoalWorkflowSteeringPrep = { prompt: string | Message[]; hadFirstGoalWorkflowSteering: boolean; }; /** * When the user sends a new turn while workflow is blocked, recover to active * so the model can resume the blocked task with fresh context. */ declare function recoverBlockedWorkflowOnUserTurn(dataDir: string, sessionId: string, options?: { storeName?: string; }): Promise; /** * Prepends first-turn workflow `` when an active goal has workflow state. * Used on the first agent turn after `/goal` set or pendingGoal initialization. */ declare function prependFirstGoalWorkflowSteeringIfNeeded(dataDir: string, sessionId: string, prompt: string | Message[], options?: { storeName?: string; }): Promise; /** * Prepends a one-shot objective-updated `` steering prompt when * `goal.json.pendingObjectiveUpdatedNotice` is set. * * Does **not** clear the flag — call `confirmObjectiveUpdatedSteeringConsumed` * after the first agent turn completes successfully. */ declare function prependObjectiveUpdatedSteeringIfNeeded(dataDir: string, sessionId: string, prompt: string | Message[], options?: { storeName?: string; }): Promise; /** * Clears `pendingObjectiveUpdatedNotice` after steering was consumed by a * successful first agent turn. */ declare function confirmObjectiveUpdatedSteeringConsumed(dataDir: string, sessionId: string, options?: { storeName?: string; }): Promise; //#endregion //#region src/goal/clarify-first-turn-gate.d.ts /** Known tools that mutate workspace, run commands, or write memory. */ declare const CLARIFY_FIRST_TURN_BLOCKED_TOOLS: Set; declare function isClarifyWorkflowTask(workflow: GoalWorkflowPromptContext): boolean; declare function isClarifyFirstTurnBlockedTool(toolName: string): boolean; /** * Registers a before_tool_call hook that blocks deliverable tools when active. * Returns a deactivate function — call once at run boundary in runner finally. */ declare function installClarifyFirstTurnGate(params: { hookRegistry: PluginHookRegistry; isGateActive: () => boolean; }): () => void; //#endregion //#region src/goal/notify.d.ts type GoalUpdatedAction = GoalEventAction | "cleared"; declare function emitGoalUpdatedProgress(eventDispatcher: RunEventDispatcher, sessionId: string, params: { action: GoalUpdatedAction; goal?: ThreadGoal | null; }): Promise; //#endregion //#region src/hitl/types.d.ts /** Information about the tool call that triggered the HITL pause. */ /** Full internal context carried by a HitlPauseSignal. */ type HitlPauseContext = { /** The HITL request to present to the user. */request: HitlRequest$1; /** Tool call context when the pause was triggered from a tool. */ toolContext?: HitlToolContext; /** Checkpoint information for resumption. */ checkpoint: HitlCheckpoint$1; }; /** Options for resuming a paused session. */ type ResumeOptions = { /** The data directory for the user. */dataDir: string; /** The .aimax child directory used to persist this session. */ sessionStoreName?: string; /** The session to resume. */ sessionId: string; /** The request to resolve. */ requestId: string; /** The user's resolution. */ resolution: HitlResolution$1; }; /** Result of attempting to resume a paused session. */ type ResumeValidationResult = { valid: true; state: PausedRunState$1; } | { valid: false; reason: string; }; type ResolveHitlRequestResult = { state: PausedRunState$1; idempotentReplay: boolean; }; //#endregion //#region src/hitl/pause-signal.d.ts declare class HitlPauseSignal extends Error { /** The HITL request to present to the user. */ readonly request: HitlRequest$1; /** Checkpoint information for resumption. */ readonly checkpoint: HitlCheckpoint$1; /** Optional tool call context. */ readonly toolContext?: HitlToolContext; /** * When `true`, this pause is a transparent safety gate (e.g. exec approval * for `rm -rf`). Transparent pauses do NOT leave entries in the transcript * — the tool's real result is recorded only after the user approves and * the tool re-executes. * * When `false` (default), the pause IS the interaction record (e.g. * clarify, request_approval, request_review, and plugin-provided HITL * tools). Plugin tools should leave this as `false` so their tool-call / * tool-result pairs are persisted normally in the transcript. */ readonly transparentPause: boolean; /** * When `true`, this signal was bubbled up from a subagent whose runner * already wrote `pending-hitl.json` and emitted `hitl_requested`. * The parent runner should NOT re-write the pending state or re-emit * the event — it should only patch `context.subagentToolCallId` / * `context.subagentToolArgs` and pause. */ readonly bubbledFromSubagent: boolean; /** Discriminator to reliably identify the signal in catch blocks. */ readonly isHitlPause: true; constructor(/** The HITL request to present to the user. */ request: HitlRequest$1, /** Checkpoint information for resumption. */ checkpoint: HitlCheckpoint$1, /** Optional tool call context. */ toolContext?: HitlToolContext, /** * When `true`, this pause is a transparent safety gate (e.g. exec approval * for `rm -rf`). Transparent pauses do NOT leave entries in the transcript * — the tool's real result is recorded only after the user approves and * the tool re-executes. * * When `false` (default), the pause IS the interaction record (e.g. * clarify, request_approval, request_review, and plugin-provided HITL * tools). Plugin tools should leave this as `false` so their tool-call / * tool-result pairs are persisted normally in the transcript. */ transparentPause?: boolean, /** * When `true`, this signal was bubbled up from a subagent whose runner * already wrote `pending-hitl.json` and emitted `hitl_requested`. * The parent runner should NOT re-write the pending state or re-emit * the event — it should only patch `context.subagentToolCallId` / * `context.subagentToolArgs` and pause. */ bubbledFromSubagent?: boolean); } /** * Type-guard that checks if an unknown error is a HitlPauseSignal. * Handles both `instanceof` and duck-typing for cross-module boundaries. */ declare function isHitlPauseSignal(error: unknown): error is HitlPauseSignal; //#endregion //#region src/hitl/session-store.d.ts /** Returns the path to `pending-hitl.json` for a session. */ declare function pendingHitlPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string; /** Returns the path to `hitl-history.jsonl` for a session. */ declare function hitlHistoryPath(dataDir: string, sessionId: string, options?: SessionPathOptions): string; /** Reads the current `pending-hitl.json`; returns `null` if none exists. */ declare function readPendingHitl(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** Reads all entries from `hitl-history.jsonl`; returns `[]` if none exists. */ declare function readHitlHistory(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; /** * Creates and persists an initial pending HITL state from a request. * Also appends a "requested" entry to the history log. */ declare function createPendingHitl(dataDir: string, sessionId: string, request: HitlRequest, checkpoint: PausedRunState["checkpoint"], context: PausedRunState["context"], toolContext?: HitlToolContext$1, options?: SessionPathOptions): Promise; /** * Transitions the pending HITL to a new status and persists the update. * * Returns the updated state, or `null` if: * - No pending HITL exists * - The request ID doesn't match * - The current status is not "pending" */ declare function transitionHitlStatus(dataDir: string, sessionId: string, requestId: string, newStatus: Exclude, resolution?: HitlResolution, options?: SessionPathOptions): Promise; /** * Removes the `pending-hitl.json` file after the session has fully resumed. * This is a cleanup step — the history log retains the full audit trail. */ declare function clearPendingHitl(dataDir: string, sessionId: string, options?: SessionPathOptions): Promise; //#endregion //#region src/hitl/resume.d.ts /** * Validates a resume attempt against the persisted HITL state. * * Checks performed: * 1. A pending HITL exists for this session * 2. The request ID matches * 3. The session ID matches * 4. The current status is "pending" * 5. The request has not expired */ declare function validateResume(dataDir: string, sessionId: string, requestId: string, sessionStoreName?: string): Promise; /** * Resolves a pending HITL request: validates, transitions to "resolved", * and returns the updated state. * * Returns the resolved PausedRunState on success, or throws on validation failure. */ declare function resolveHitlRequest(options: ResumeOptions): Promise; //#endregion //#region src/hitl/messages.d.ts declare const HITL_MESSAGES: { readonly clarify: { readonly label: "澄清问题"; readonly description: "当你需要更多信息才能继续时,向用户提出澄清问题。提供清晰的问题,并可选给出候选选项。任务会暂停,直到用户回复。"; readonly title: "需要你补充信息"; readonly placeholder: "请输入你的回复"; }; readonly approval: { readonly label: "请求授权"; readonly description: "仅当用户或系统明确要求调用 `request_approval` 时使用。不要把它用于一般确认、澄清或推断式授权检查。说明要执行的动作,以及为什么必须显式授权。任务会暂停,直到用户同意或拒绝。"; readonly choices: { readonly approve: { readonly label: "同意"; readonly description: "允许继续执行该操作"; }; readonly deny: { readonly label: "拒绝"; readonly description: "不允许执行该操作"; }; }; readonly summary: { readonly approved: "已授权。"; readonly denied: "已拒绝。"; readonly timeout: "由于超时,视为拒绝。"; }; }; readonly review: { readonly label: "请求审阅"; readonly description: "在继续之前,将草稿、文档或输出提交给用户审阅。包含需要审阅的内容,以及你希望获得的反馈类型。任务会暂停,直到用户完成审阅并回复。"; readonly choices: { readonly approve: { readonly label: "通过"; readonly description: "内容没有问题,继续执行"; }; readonly revise: { readonly label: "需要修改"; readonly description: "提供反馈后再修改"; }; readonly reject: { readonly label: "拒绝"; readonly description: "放弃当前草稿"; }; }; }; }; declare function approvalSummaryFromResolution(resolution: HitlResolution): string; declare function formatApprovalResolution(resolution: HitlResolution): string; /** * Formats a clarify resolution into a JSON string suitable for the tool * result content in the transcript. The model sees this as the clarify * tool's return value — i.e. the user's answer. */ declare function formatClarifyResolution(resolution: HitlResolution): string; /** * Formats a review resolution into a JSON string suitable for the tool * result content in the transcript. The model sees this as the * request_review tool's return value — i.e. the reviewer's verdict. */ declare function formatReviewResolution(resolution: HitlResolution): string; declare function buildResumeNarration(resolution: HitlResolution, kind: string): string; //#endregion export { type AccountingFlushResult, AgentBinding, AgentConfig, type AgentConfigSource, type AgentCustomProgressEvent, type AgentDefinition, type AgentDefinitionsContext, type AgentDefinitionsStats, type AgentDirectoryCandidate, type AgentLogEntry, AgentModelConfig, type AgentProgressEvent, type AgentRunParams, type AgentRunResult, type AgentRuntimePolicy, type AgentRuntimePolicyInput, type AgentScanOptions, type AgentTaskItem, type AgentTaskStatus, type AgentTaskUpdatedEvent, type AgentTeamConfigSource, type AgentTeamDefinition, AgentTeamDefinitionError, type AgentTeamDefinitionErrorCode, type AgentTeamDirectoryCandidate, type AgentTeamReferenceValidation, type AgentTeamScanOptions, type AgentVisibility, AgentsConfig, type ApplyCliGoalInput, type ApplyCliGoalResult, type ArtifactRecord, type AutoSkillCategory, type AutoSkillIndexEntry, type AutoSkillListItem, type AutoSkillListOptions, type AutoSkillSearchOptions, type AutoSkillSearchResult, type AutoSkillStatus, type AutoSkillViewOptions, type AutoSkillViewResult, AutoSkillsLoader, type AutoSkillsLoaderOptions, BOOTSTRAP_FILE_NAMES, BOOTSTRAP_MAX_CHARS, BOOTSTRAP_TOTAL_MAX_CHARS, type BlockedWorkflowRecoveryResult, type BootstrapContextFile, type BootstrapEnsureResult, type BootstrapFile, type BootstrapMountResult, type BootstrapMountStatus, type BuildContinuationPromptOptions, CLARIFY_ACCEPTANCE_TEXT, CLARIFY_FIRST_TURN_BLOCKED_TOOLS, CLARIFY_TASK_TITLE, type CallbackEventPayload, type CallbackPayload, type ChangeDocument, type ChangeOpInput, type ChangeOperation, type ChangeOperationInput, type ChangeOperationName, type ChangeOperationType, type Channel, CommandRule, CommandRuleGroup, type ContextManager, ContinuationState, type CoreMemoryConfig, CorruptGoalWorkflowStateError, type CronExecutionRecord, DEFAULT_SESSION_STORE_NAME, type DefaultMemoryProviderOptions, ENV_GOAL_CONTINUATION, type EmbeddingProvider, type EmbeddingProviderContext, type EmbeddingProviderFactory, type EmbeddingProviderRegistration, type ExtractedWorkflowPlan, FIRST_TURN_GOAL_WORKFLOW_INTRO, type FirstGoalWorkflowSteeringPrep, type ForkSessionParams, type ForkSessionResult, GOAL_MULTILINE_TEMPLATE_EXAMPLE, GOAL_WORKFLOW_STATE_VERSION, type GenerateModelResponseParams, type GenerateModelResponseResult, GoalAccounting, GoalConflictError, type GoalContinuationTurnResult, type GoalEventAction, type GoalEventRecord, type GoalEventSource, type GoalPatch, type GoalRecoveryCompletedTask, type GoalRecoveryEvidence, type GoalToolWorkflowView, type GoalWorkflowAcceptanceCriterion, type GoalWorkflowPromptContext, type GoalWorkflowState, type GoalWorkflowStatus, type GoalWorkflowSummary, type GoalWorkflowTask, type GoalWorkflowTaskKind, type GoalWorkflowTaskStatus, type GoalWorkflowWarning, HITL_MESSAGES, type HitlPauseContext, HitlPauseSignal, type HitlToolContext, type LlmApiFormat, MAX_CHANGE_CONTENT_CHARS, MAX_CHILDREN_PER_SESSION, MAX_SUBAGENT_DEPTH, type MemoryCallOptions, type MemoryChangeSource, type MemoryChangedEvent, type MemoryChangedHandler, type MemoryCompactionRecallRuntimeState, MemoryIndexManager, type MemoryMaintenanceOptions, type MemoryProvider, type MemoryProviderContext, type MemoryProviderFactory, type MemoryProviderRegistration, type MemoryProviderStatus, type MemoryRebuildSummary, type MemoryRecallRuntimeState, type MemorySearchOptions, type MemorySearchResult, type NormalizedPluginsConfig, type ObjectiveUpdatedSteeringPrep, type OnLogCallback, PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, PROFILE_CONFIG_FILE, type PersistedSubagentRunRecord, type PersistedToolResult, type PiExtensionDialogBridge, type PluginApi, type PluginCandidate, type PluginConfigUiHint, type PluginCustomProgressInput, type PluginDiagnostic, type PluginDiscoveryOptions, type PluginDiscoveryResult, type PluginEntryConfig, type PluginExecutionRuntime, type PluginHitlApi, type PluginHitlPauseInput, type PluginHitlPauseSignal, type PluginHitlRequest, type PluginHookAfterCompactionEvent, type PluginHookAfterPromptBuildEvent, type PluginHookAfterToolCallEvent, type PluginHookAgentContext, type PluginHookAgentEndEvent, type PluginHookAgentStartEvent, type PluginHookAssistantMessageEndEvent, type PluginHookBeforeAgentStartEvent, type PluginHookBeforeAgentStartResult, type PluginHookBeforeCompactionEvent, type PluginHookBeforeCompactionResult, type PluginHookBeforeModelResolveEvent, type PluginHookBeforeModelResolveResult, type PluginHookBeforePromptBuildEvent, type PluginHookBeforePromptBuildResult, type PluginHookBeforeProviderRequestEvent, type PluginHookBeforeProviderRequestResult, type PluginHookBeforeToolCallEvent, type PluginHookBeforeToolCallResult, type PluginHookContextEvent, type PluginHookContextResult, type PluginHookDreamGateEvent, type PluginHookDreamGateResult, type PluginHookHandlerMap, type PluginHookInputEvent, type PluginHookInputResult, type PluginHookLlmInputEvent, type PluginHookLlmOutputEvent, type PluginHookMemoryChangedEvent, type PluginHookName, type PluginHookRegistration, PluginHookRegistry, type PluginHookResourcesDiscoverEvent, type PluginHookResourcesDiscoverResult, type PluginHookSessionEndEvent, type PluginHookSessionResetEvent, type PluginHookSessionStartEvent, type PluginHookToolResultEvent, type PluginHookToolResultResult, type PluginHookTurnEndEvent, type PluginHookTurnStartEvent, type PluginKind, type PluginManifest, type PluginManifestLoadResult, type PluginManifestRegistry, type PluginOrigin, type PluginProgressEmitter, type PluginRecord, type PluginRegistry, type PluginRuntime, type PluginRuntimeContext, type PluginSystem, type PluginSystemOptions, type PluginToolOptions, PluginToolRegistry, type PluginUiToolDescriptor, type PluginUiToolOptions, type PluginsConfig, type PluginsConfigValidationResult, type PrepareSystemRuntimeOptions, ProfileConfig, type ReadonlyTranscriptSessionAdapter, type RecordSessionArtifactsOptions, type RegisteredPluginTool, type ResolveMemoryProviderOrDefaultParams, type ResolvedMemoryProviderOrDefault, type ResumeOptions, type ResumeValidationResult, type RunResultPayload, SYSTEM_AGENTS_DIR, SYSTEM_AGENT_TEAMS_DIR, type SessionContextStore, type SessionExport, type SessionInspection, type SessionMetadata, type SessionMetadataUpdate, type SessionPathOptions, type SessionSummary, type Skill, type SkillDirectory, type SkillViewResult, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type SystemWarmState, type ThinkingLevel, type ToolLoopDetectionConfig, type TranscriptEntry, type TurnAccounting, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, type WallClockAccounting, addAgent, addBinding, agentDirCandidates, agentTeamDirCandidates, agentVisibility, aimaxDir, appendChangeOperation, appendCronExecutionRecord, appendGoalEvent, appendRecentToMemory, appendSessionFile, appendToMemory, appendTranscriptEntry, applyCliGoalBeforeRun, approvalSummaryFromResolution, artifactsPath, atomicWriteSessionFile, autoSkillsDir, bootstrapMountLayout, buildAgentDelegationPrompt, buildAgentTaskPrompt, buildAgentTeamPrompt, buildAimaxGoalCliHelpExtra, buildBootstrapContextFiles, buildBudgetLimitPrompt, buildContinuationPrompt, buildFirstTurnGoalWorkflowPrompt, buildGoalContextItem, buildGoalSlashHelpText, buildObjectiveUpdatedPrompt, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, changesPath, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, confirmObjectiveUpdatedSteeringConsumed, contextSnapshotPath, continuationTurnHadMeaningfulOutput, createAgentDefinitionsContext, createAgentTools, createApplyPatchTool, createAutoSkillCategoriesTool, createAutoSkillListTool, createAutoSkillSearchTool, createAutoSkillViewTool, createAutoSkillsLoader, createBashTool, createBatchSubagentSpawnTool, createBuiltinMemoryProvider, createContextManager, createDefaultMemoryProvider, createEditFileTool, createExecTool, createImageTool, createListDirTool, createMemoryAppendTool, createMemoryForgetTool, createMemoryGetTool, createMemoryListTool, createMemoryLogTool, createMemorySearchTool, createMemoryUpdateTool, createMemoryWriteTool, createPendingHitl, createPendingUiTool, createPluginProgressEmitter, createPluginRuntime, createProcessTool, createReadFileTool, createSession, createSessionContextStore, createSessionSearchTool, createSkillListTool, createSkillLoadTool, createSubagentSpawnTool, createSubagentsTool, createUiTool, createWriteFileTool, cronExecutionsPath, defaultConfigDir, defaultUiToolInputSchema, deleteGoal, deleteGoalWorkflow, deleteMemoryFile, discoverAIMaxPlugins, emitGoalUpdatedProgress, ensureBootstrapMountLayout, ensureSession, exportSession, extractWorkflowPlanFromObjective, filterSkillsForAgent, filterToolsForAgent, findAgentDefinition, findSkillByName, flushAccounting, forkSessionFromMessage, formatApprovalResolution, formatClarifyResolution, formatReviewResolution, generateModelResponse, generateSessionTitle, getAgentConfig, getMemoryLines, getPluginSystem, goalArtifactsDir, goalDir, goalEventsPath, goalObjectiveMdPath, goalPath, goalWorkflowPlanPath, goalWorkflowStatePath, hasBootstrapSentinel, hitlHistoryPath, initializeGoalWorkflow, initializePluginSystem, inspectBootstrapMountLayout, inspectSession, installClarifyFirstTurnGate, isBootstrapMountLayoutReady, isClarifyFirstTurnBlockedTool, isClarifyWorkflowTask, isContinuationEnabled, isGoalContext, isHitlPauseSignal, isUiToolPauseSignal, listAgents, listAvailableSlashCommands, listBindings, listMemoryFiles, listSessionSummaries, listSessions, listSubagentRunsFromDisk, loadAgentDefinitionsFromDir, loadAgentTeamDefinitionsFromDir, loadAgentsConfig, loadArtifactDocumentV2, loadBootstrapFiles, loadChangeOperations, loadCronExecutionRecords, loadMergedProfileConfig, readPendingHitl as loadPendingHitl, readPendingHitl, readPendingUiTool as loadPendingUiTool, readPendingUiTool, loadPluginManifest, loadPluginManifestRegistry, loadPlugins, loadSessionContextSnapshot, loadSessionMetadata, loadSkillView, loadSkills, loadSkillsFromDirs, loadSkillsWithPluginDirs, loadSubagentRegistryFromDisk, loadSystemPromptSnapshot, loadTranscript, loadWorkflowPromptContext, maybeContinueGoalIfIdle, memoryDir, mergeArtifactRecords, mergeProfileConfig, metadataPath, mirrorGoalStatusToSession, normalizeAgentId, normalizePluginsConfig, normalizeSessionStoreName, parseAgentDefinition, parseAgentTeamDefinition, pendingHitlPath, pendingUiToolPath, persistSessionExportSnapshots, preloadPluginSystem, prepareSystemRuntime, prependFirstGoalWorkflowSteeringIfNeeded, prependObjectiveUpdatedSteeringIfNeeded, primaryMemoryPath, profileConfigDir, publicAgentDefinitions, readGoal, readGoalWorkflowState, readGoalWorkflowSummary, readHitlHistory, readMemoryFile, readPrimaryMemory, readSessionFile, readSessionFileContent, recordSessionArtifacts, recoverBlockedWorkflowOnUserTurn, recoverGoalCompletion, registerEmbeddingProvider, registerMemoryProvider, removeAgent, removeBindings, renderGoalPlanMarkdown, repairGoalWorkflowState, replaceMemoryFile, resetEmbeddingProviderRegistryForTests, resetMemoryProviderRegistryForTests, resolveAgentDefinitionsContext, resolveAgentDir, resolveAgentIdByBinding, resolveAgentTeamDefinition, resolveAgentsConfigPath, resolveDefaultAgentId, resolveEmbeddingProvider, resolveGoalObjective, resolveGoalToolWorkflowView, resolveHitlRequest, resolveHitlRequest as resolvePendingHitl, resolveMemoryProvider, resolveMemoryProviderOrDefault, resolveModelFallbacks, resolveModelString, resolvePendingUiTool, resolvePluginManifestPath, rewriteTranscript, runAgent, saveAgentsConfig, saveSessionMetadata, saveSubagentRegistryToDisk, scanAgentDefinitions, scanAgentTeamDefinitions, searchMemory, sessionDir, sessionMemoryPath, sessionsDir, shouldContinueGoal, skillsDir, systemPromptSnapshotPath, toolResultsDir, transcriptPath, transitionHitlStatus, updateAgent, updateAgentIdentity, updateGoal, updateSessionMetadata, validateAgentTeamDefinitionReferences, validatePluginsConfig, validateResume, withGoalWorkflowLock, wrapToolsWithHooks, writeGoal, writeSessionFile };