import { type Agent } from "@caupulican/pi-agent-core/agent"; import type { CompactionResult } from "@caupulican/pi-agent-core/compaction/compaction"; import { type CustomMessage } from "@caupulican/pi-agent-core/messages"; import { type StreamIdleOptions } from "@caupulican/pi-agent-core/reliability"; import type { BranchSummaryEntry, SessionManager } from "@caupulican/pi-agent-core/session"; import type { AgentMessage, AgentState, ThinkingLevel } from "@caupulican/pi-agent-core/types"; import type { Api, ImageContent, Model, TextContent, Usage } from "@caupulican/pi-ai"; import type { CapabilityEnvelope, EvidenceBundle, LearningDecision, WorkerClaim, WorkerRequest } from "./autonomy/contracts.ts"; import type { LaneRecord } from "./autonomy/lane-tracker.ts"; import type { AutonomyDiagnosticSnapshot, AutonomyStatusSnapshot, GateOutcomeHistoryEntry } from "./autonomy/status.ts"; import type { BashResult } from "./bash-executor.ts"; import type { CurationTelemetrySnapshot } from "./context/brain-curator.ts"; import type { ContextAuditReport } from "./context/context-audit.ts"; import { type ContextCompositionReport } from "./context/context-composition.ts"; import type { PromptEnforcementReport } from "./context/context-prompt-enforcement.ts"; import type { PromptPolicyGcCorrelationReport, PromptPolicyShadowReport } from "./context/context-prompt-policy.ts"; import type { MemoryPromptInclusionReport } from "./context/memory-diagnostics.ts"; import type { MemoryProvider as ContextMemoryProvider } from "./context/memory-provider-contract.ts"; import type { MemoryRetrievalReport } from "./context/memory-retrieval.ts"; import type { ContextGcReport } from "./context-gc.ts"; import type { SessionCostSummary } from "./cost/cost-summary.ts"; import type { DailyUsageTotals } from "./cost/daily-usage.ts"; import type { CostGuardDecision, CostGuardSettings } from "./cost-guard.ts"; import type { WorkerDelegationRequest } from "./delegation/worker-delegation-request.ts"; import type { CompactOptions, ContextUsage, ExtensionRunner, ReplacedSessionContext, ToolDefinition, ToolInfo } from "./extensions/index.ts"; import { type ChannelProvider, GatewayRegistry, type JobSchedulerProvider } from "./gateways/channel-provider.ts"; import type { GoalStateRevision } from "./goals/goal-lifecycle.ts"; import type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from "./goals/goal-runtime-snapshot.ts"; import type { GoalState } from "./goals/goal-state.ts"; import type { LearningAuditRecord } from "./learning/learning-audit.ts"; import type { DemandSignals, ReflectionResult } from "./learning/reflection-engine.ts"; import { type CurationProposals } from "./learning/skill-curator.ts"; import type { MemoryProvider } from "./memory/memory-provider.ts"; import { type LaneWorkerRefusal, type ModelCapabilityProfile } from "./model-capability.ts"; import type { ModelRegistry } from "./model-registry.ts"; import type { StoredFitnessReport } from "./models/fitness-store.ts"; import type { PrismLlamaCppRuntime } from "./models/llamacpp-runtime.ts"; import type { OllamaRuntime, TransformersRuntime } from "./models/local-runtime.ts"; import { type PipelineRun } from "./pipelines/index.ts"; import { type PromptTemplate } from "./prompt-templates.ts"; import type { ModelFitnessReport } from "./research/model-fitness.ts"; import type { ResourceLoader } from "./resource-loader.ts"; import type { CredentialManager } from "./secrets/credential-manager.ts"; import type { SettingsManager, SettingsScope } from "./settings-manager.ts"; import { type TaskStepsState } from "./tasks/task-state.ts"; import { type ToolProbeReport } from "./tool-protocol-controller.ts"; import type { BashOperations } from "./tools/bash.ts"; /** * Test hook: override the stream-idle bounds so a stall can be provoked in-suite without a * multi-minute wait. Pass `undefined` to restore the user-locked defaults (connect 120s / * active 180s / quiet 600s, or the user's retry.stall settings). Applies per request — it * may be set or changed at any time before the request that should observe it. */ export declare function setStreamIdleOptionsForTests(opts: Partial | undefined): void; export * from "./agent-session-contracts.ts"; import type { AgentSessionConfig, AgentSessionEventListener, ExtensionBindings, GoalContinuationLoopOptions, GoalContinuationLoopResult, GoalContinuationOnceOptions, GoalContinuationOnceResult, IsolatedCompletionOptions, IsolatedCompletionResult, ModelCycleResult, PromptOptions, ResearchLaneRunOutcome, SessionStats, SpawnedUsageTotals, WorkerDelegationRunOutcome } from "./agent-session-contracts.ts"; export type { ToolProbeReport, ToolProbeResult, ToolProbeVerdict } from "./tool-protocol-controller.ts"; export declare class AgentSession { readonly agent: Agent; readonly sessionManager: SessionManager; readonly settingsManager: SettingsManager; capabilityEnvelope?: CapabilityEnvelope; private _scopedModels; private _unsubscribeAgent?; private _unsubscribeSettingsChanges?; private _eventListeners; private _extensionsChangedListeners; private _steeringMessages; private _followUpMessages; private _queuedExtensionCommands; private _pendingNextTurnMessages; private _streamingPromptSubmissionTail; /** * The last tool set requested via setActiveToolsByName BEFORE model-capability filtering, so * switching from a small-window model back to a large one restores the full requested set. */ private _requestedActiveToolNames; private _unboundToolGrantWarnings; /** Delegate provider-prompt-guideline bounding diagnostics (root-session delegate tool only). */ private _delegatePromptGuidelineWarnings; private _branchSummaryAbortController; private readonly _modelSelection; private readonly _bash; private readonly _profileFilter; private readonly _toolGate; private readonly _toolSelection; private _extensionRunner; private _turnIndex; private _currentForegroundEnvelope?; private _resourceLoader; private _customTools; private _cwd; /** Per-agent persistent shell session identity: stable across runtime reloads, disposed with the session. */ private readonly _shellSessionKey; private _agentDir; private _collectWorkspaceSources; private readonly _localRuntimeController; private readonly _localPrefixWarm; private readonly _toolProtocol; /** Assembles the session's base system prompt from live session state (see * system-prompt-builder.ts); owns the paired _baseSystemPromptOptions. */ private readonly _systemPromptBuilder; /** Autonomy telemetry sink + status/diagnostic snapshots (see autonomy-telemetry.ts); owns * the latest gate outcome and the bounded gate-outcome history. */ private readonly _autonomyTelemetry; /** Goal auto-continue + research lane + recursive worker-agent orchestration + model-fitness probe (see * background-lane-controller.ts); owns the lane timers/guards, the last research-lane skip * reason, the live LaneTracker, and the in-flight research/worker abort controllers. */ private readonly _backgroundLanes; /** Session-local ownership of tool calls transferred after the foreground latency budget. */ private readonly _backgroundToolTasks; private readonly _terminalHandoffs; private readonly _durableCustomMessageTurns; private readonly _humanInput; /** Plug-and-play memory subsystem (see memory-controller.ts); owns the OKF retrieval provider, the * latest retrieval/prompt-inclusion reports, the reload-safe MemoryManager, the recall * effectiveness tracker, and the extension-contributed pending providers. */ private readonly _memory; private readonly _compactionSupport; private readonly _compaction; /** Provider request hook generation, replay-safe planning, admission, and lifecycle commit. */ private readonly _providerRequestRuntime; /** Per-turn context-shaping subsystem (see context-pipeline.ts); owns the latest * audit/policy/correlation/enforcement/gc reports, the brain-curation sidecar + its skip reasons, * and the tool-output artifact store. Invoked stage-by-stage by provider-request planning. */ private readonly _pipeline; private _extensionRunnerRef?; private _initialActiveToolNames?; private _allowedToolNames?; private _excludedToolNames?; private _toolProfileFilter?; private readonly _isExplicitModel; private readonly _isExplicitThinking; private readonly _gatewayRegistry; /** Usage/cost/stats accounting, /context estimate, and session export (see session-analytics.ts); * owns the spawned-usage and daily-usage memo caches. */ private readonly _analytics; private readonly _treeNavigator; private readonly _costGuard; /** Per-turn model-router subsystem (see model-router-controller.ts); owns the transient route/intent, * the cheap-turn session buffer, the escalation/retry flags, and the sticky last-decision/skip-reason * used by the status report. Its parallel routed drive path delegates every turn back to * {@link ForegroundRecoveryController.runAgentPrompt} so the drive loop stays host-side. */ private readonly _modelRouter; private readonly _foregroundLifecycle; private readonly _foregroundRecovery; /** Submission authority inherited by every routed retry within the current prompt lifecycle. */ private _foregroundPromptLease; private readonly _failureCorpus; private readonly _toolRecoveryLogger; private readonly _toolRecoveryEventLogPath; private readonly _skillVault; private _skillCuratorInstance?; private _disposed; private _disposeCompletion; private readonly _reflectionAbort; /** Root-owned version transition state; construction performs no filesystem I/O. */ private readonly _durableLearningState; /** Root current-turn reflection cue + explicit learning-apply/rollback compatibility path. */ private readonly _reflection; /** Durable goal lifecycle, accounting, and raw continuation loop. */ private readonly _goals; private readonly _isChildSession; private _baseToolsOverride?; private _sessionStartEvent; private _extensionUIContext?; private _extensionMode; private _extensionCommandContextActions?; private _extensionShutdownHandler?; private _extensionErrorListener?; private _modelRegistry; /** Tool-registry assembly + the self-modification-safe extension reload (see runtime-builder.ts); * owns the base/wrapped tool definitions, the live tool registry, and the per-tool prompt * snippet/guideline maps. The reload snapshot spans host/agent state reached through its deps. */ private readonly _runtimeBuilder; /** Extension⇄session binding boundary (see extension-binding-controller.ts): `bindExtensions()`, * extension resource discovery, and `bindExtensionCore`'s translation of session identity into * the ExtensionRunner's core API. Owns the abort-handler/error-unsubscriber fields no other * collaborator reads. */ private readonly _extensionBinding; private _baseSystemPrompt; constructor(config: AgentSessionConfig); /** Model registry for API key resolution and model discovery */ get modelRegistry(): ModelRegistry; /** * True when the session's stream fn is the raw `streamSimple` provider entry (directly, or as the * base wrapped by the idle watchdog at construction). Callers use this to decide whether request * auth must be injected explicitly — see {@link RAW_STREAM_MARKER}. */ private _isRawStreamSimple; private _getRequiredRequestAuth; private _getCompactionRequestAuth; private _resolveCompactionModelAndAuth; private _resolveCompactionModel; /** * One bounded diagnostic clause for compaction retry warnings: which summarizer selection won * (and why) plus the input-size estimate the capacity check consumed — the two facts every * gate-failure post-mortem has needed (2026-07-06 field incidents). */ private _describeCompactionSummarizer; private _getLastCompactionSelectionReason; private _resolveCompactionThinkingLevel; /** Latest cost-guard decision (for the host footer/UI to surface a warning). Undefined if disabled. */ getLastCostGuardDecision(): CostGuardDecision | undefined; /** Apply an explicit guard choice and invalidate all prior decision/envelope projections immediately. */ setCostGuardSettings(settings: CostGuardSettings, scope?: SettingsScope): void; private get _skillCurator(); /** * Skill curator (#32): PROPOSE (never auto-apply) archival of stale reflection-promoted skills and * consolidation of overlapping ones. The host surfaces these (e.g. a `/curate` command) for approval. */ proposeSkillCuration(options?: { staleDays?: number; overlapThreshold?: number; }): CurationProposals; /** * Session-start auto-curation (#32, default ON): archive stale reflection-promoted skills in one * locked batch and return the names archived so the host can ANNOUNCE it (never silent). Skipped in * child sessions and when `curator.autoArchive` is disabled. Restorable via `/curate restore`. */ runStartupSkillCuration(): Promise; /** Archive a promoted skill into `skills/.archive/` (restorable, non-destructive). Returns true if moved. */ archivePromotedSkill(name: string): boolean; /** Restore a previously-archived promoted skill. Returns true if moved back. */ restorePromotedSkill(name: string): boolean; private _installAgentTurnRefresh; private _createAgentContextSnapshot; /** Compatibility seam retained for focused auto-probe regressions. */ private _probeToolCallingForModel; /** Compatibility seam retained for focused protocol-selection doctrine regressions. */ private _resolveModelToolProtocol; probeToolCalling(target?: string): Promise; /** Tool-build call-site delegation to {@link ContextPipeline.getToolArtifactStore}. */ private _getToolArtifactStore; private _getSessionImageStore; /** * Provider-plan hot-path delegation to {@link ContextPipeline.runContextAudit}. Kept as a * one-line method so the request context controller owns pass ordering. */ private _runContextAudit; /** Read-only inspection of the context audit (delegates to {@link ContextPipeline.getContextAuditReport}). */ getContextAuditReport(messages?: AgentMessage[]): ContextAuditReport; /** * Provider-plan hot-path delegation to {@link ContextPipeline.runPromptPolicyPlanning}. Kept as a * one-line method so the request context controller owns pass ordering. */ private _runPromptPolicyPlanning; /** Read-only inspection of the shadow policy plan (delegates to {@link ContextPipeline.getPromptPolicyReport}). */ getPromptPolicyReport(messages?: AgentMessage[]): PromptPolicyShadowReport; /** * Provider-plan commit delegation to {@link ContextPipeline.correlatePromptPolicyWithContextGc}. * Kept as a one-line method so the request context controller owns pass ordering. */ private _correlatePromptPolicyWithContextGc; /** Read-only inspection of the latest shadow-plan/legacy-gc correlation, for tests/debugging. */ getPromptPolicyGcCorrelation(): PromptPolicyGcCorrelationReport; /** * Provider-plan hot-path delegation to {@link ContextPipeline.runPromptEnforcement}. Kept as a * one-line method so the request context controller owns pass ordering. */ private _runPromptEnforcement; /** * Provider-plan commit delegation to {@link ContextPipeline.enqueueRelevanceCuration}. Kept as a * one-line method so the request context controller owns pass ordering. */ private _enqueueRelevanceCuration; /** Reflex/curation call-site delegation to {@link ContextPipeline.resolveCurationModelIfFit}. */ private _resolveCurationModelIfFit; /** * Provider-plan commit delegation to {@link ContextPipeline.maybeDrainBrainCuration}. Kept as a * one-line method so the request context controller owns pass ordering. */ private _maybeDrainBrainCuration; /** Compaction call-site delegation to {@link ContextPipeline.buildCompactionPreDigest}. */ private _buildCompactionPreDigest; /** Drop provider-owned request/continuation caches whose prefix was invalidated by compaction. */ private _refreshAfterCompaction; /** * Context composition dashboard data: decomposes the per-request payload (system prompt, tool * schemas, extension contributions, message classes incl. GC/policy stubs and recall pages) * plus background spend, so users can see exactly what their integrations cost per request. * Read-only: uses the GC report path (writePayloads=false), never mutates anything. */ getContextCompositionReport(): ContextCompositionReport; /** Bounded plain-text rendering of {@link getContextCompositionReport} for the /context command. */ formatContextCompositionDashboard(): string; formatToolRepairHealthReport(): string; flushToolRecoveryLogsForTests(): Promise; removeToolRepairRule(model: string, mode: string): boolean; resetToolProtocolCalibration(model: string): boolean; /** Curation status for diagnostics/dashboard: settings, live telemetry, last refusal reason. */ /** Curation status for diagnostics/dashboard (delegates to {@link ContextPipeline.getContextCurationStatus}). */ getContextCurationStatus(): { enabled: boolean; model?: string; telemetry: CurationTelemetrySnapshot; lastSkipReason?: string; lastPreDigestSkipReason?: string; }; /** Read-only inspection of the latest prompt-enforcement report, for tests/debugging. */ getPromptEnforcementReport(): PromptEnforcementReport; /** * Provider-plan hot-path delegation to {@link MemoryController.runMemoryRetrieval}. Kept as a * one-line method so the request context controller owns pass ordering. */ private _runMemoryRetrieval; /** Read-only inspection of the latest memory-retrieval report, for tests/debugging. */ getMemoryRetrievalReport(): MemoryRetrievalReport; /** * Provider-plan hot-path delegation to {@link MemoryController.maybeAppendMemoryEvidenceBlock}. * Kept as a one-line method so the request context controller owns pass ordering. */ private _maybeAppendMemoryEvidenceBlock; /** Read-only inspection of the latest memory-prompt-inclusion decision, for tests/debugging and context_audit. */ getMemoryPromptInclusionReport(): MemoryPromptInclusionReport; /** * Provider-plan hot-path delegation to {@link ContextPipeline.applyContextGc}. Kept as a * one-line method so the request context controller owns pass ordering; * also serves the composition dashboard and {@link getContextGcReport} read-only paths. */ private _applyContextGc; /** Read-only inspection of the latest context-gc report (delegates to {@link ContextPipeline.getContextGcReport}). */ getContextGcReport(messages?: AgentMessage[]): ContextGcReport; private _installAgentToolHooks; /** Persist the guard evidence, retain active work, and force the next pass onto a recovery path. */ private _handleRunawayStop; /** * Evidence-gated native→phone auto-probe for a LOCAL/MANAGED model (never cloud — see * {@link isLocalOrManagedRouterModel}) that just crossed the tool-argument-validation escalation * threshold — repeated identical validation failures with no successful native call in between, * which is exactly the graded evidence {@link Agent.onToolValidationEscalation} already requires * before firing. Runs the SAME probe `/toolprobe` uses ({@link _probeToolCallingForModel}: native * trials first, so a model that can actually tool-call natively still resolves to verdict * "native" and is never phoned) entirely OFF the hot path — fired here but never awaited by the * caller, so a slow or failing probe can never block or throw the user's in-flight turn. * Anti-loop: skipped when this session already auto-probed this model, or a fresh persisted * verdict already exists (enforced by {@link ToolProtocolController}) — otherwise a model that keeps * failing validation every turn would re-fire the (multi-completion) probe every single turn. */ private _maybeAutoProbeOnValidationEscalation; /** * A repeated identical tool-argument-validation failure crossed the escalation threshold * ({@link Agent.toolValidationEscalationThreshold}) — the graded evidence the capability-gate * spine acts on. Always records a session-log/telemetry entry (see {@link * TOOL_VALIDATION_ESCALATION_CUSTOM_TYPE}), then branches on the failing model's class: * - LOCAL/MANAGED ({@link isLocalOrManagedRouterModel}, never cloud): the failure is evidence the * model may lack native tool-calling, so it fires the evidence-gated native→phone auto-probe * off the hot path ({@link _maybeAutoProbeOnValidationEscalation}). Escalating a local model's * ROUTER TIER on a tool-call failure would not fix a capability problem, so this branch never * touches the model router. * - CLOUD (known tool-capable): the failure is evidence the routed tier is too weak for this * request, so it escalates via {@link ModelRouterController.requestValidationFailureEscalation} * — de-conflated from the beforeToolCall mutation gate ({@link * ModelRouterController.maybeEscalateToolCall}/`shouldEscalateModelRouterTool`): repeated * validation failure is grounds to escalate REGARDLESS of the failing tool's mutation status, * so a read-only tool's repeated failure now escalates too (previously a no-op, since the old * code reused the mutation gate verbatim for this unrelated signal). Cloud models are never * probe-gated or phoned by this handler. * If the registry can no longer resolve `event.model`/`event.provider` (e.g. the model was * unregistered mid-session), falls back to the cloud/tier-escalation path — the previously * existing behavior — rather than silently dropping the signal. */ private _handleToolValidationEscalation; /** Emit an event to all listeners */ private _emit; private _emitQueueUpdate; /** * User messages already painted to the UI by an early, synthetic `message_start` fired from * `_promptUnserialized` — before the model-router judge's bounded LLM call — so the prompt * appears immediately instead of hanging until routing finishes. The real agent-loop run emits * its own authoritative `message_start` for the SAME message object once the turn actually * starts; `_handleAgentEvent` consumes (deletes) it from this set to suppress that one duplicate * listener notification. Persistence is untouched: it stays keyed off `message_end`, which is * never added here and never suppressed. */ private _earlyDisplayedUserMessages; /** Internal handler for agent events - shared by subscribe and reconnect */ private _handleAgentEvent; private _willRetryAfterAgentEnd; /** Extract text content from a message */ private _getUserMessageText; /** Find the last assistant message in agent state (including aborted ones) */ private _findLastAssistantMessage; private _replaceMessageInPlace; /** Emit extension events based on agent events */ private _emitExtensionEvent; /** * Subscribe to agent events. * Session persistence is handled internally (saves messages on message_end). * Multiple listeners can be added. Returns unsubscribe function for this listener. */ subscribe(listener: AgentSessionEventListener): () => void; /** * Subscribe to extensions changed events (load/unload live). * Returns unsubscribe function for this listener. */ onExtensionsChanged(cb: () => void): () => void; /** * Notify all extensions-changed listeners. * Called after successful load/unload operations. */ private _notifyExtensionsChanged; /** * Temporarily disconnect from agent events. * User listeners are preserved and will receive events again after resubscribe(). * Used internally during operations that need to pause event processing. */ private _disconnectFromAgent; /** * Reconnect to agent events after _disconnectFromAgent(). * Preserves all existing listeners. */ private _reconnectToAgent; /** * Remove all listeners and disconnect from agent. * Call this when completely done with the session. */ dispose(): void; /** Dispose synchronously-visible state, then await all session-owned asynchronous shutdowns. */ disposeAndWait(): Promise; /** Full agent state */ get state(): AgentState; /** Current model (may be undefined if not yet selected) */ get model(): Model | undefined; /** Current thinking level */ get thinkingLevel(): ThinkingLevel; /** Whether agent is currently streaming a response */ get isStreaming(): boolean; /** Current effective system prompt (includes any per-turn extension modifications) */ get systemPrompt(): string; /** Current retry attempt (0 if not retrying) */ get retryAttempt(): number; /** * Get the names of currently active tools. * Returns the names of tools currently set on the agent. */ getActiveToolNames(): string[]; /** Build a foreground {@link CapabilityEnvelope} from the live session state (active tools, cwd, cost ceiling). */ private _buildForegroundEnvelopeFromState; /** * (Re)build the foreground envelope for the current turn. Visibility only -- the foreground * envelope is NOT enforced this round. Best-effort: never throws into the turn. */ private _refreshForegroundEnvelope; /** The auto-constructed foreground envelope for the current/most-recent turn (visibility only). */ getForegroundEnvelope(): CapabilityEnvelope | undefined; /** * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata. */ getAllTools(): ToolInfo[]; getToolDefinition(name: string): ToolDefinition | undefined; /** * Set active tools by name. * Only tools in the registry can be enabled. Unknown tool names are ignored. * Also rebuilds the system prompt to reflect the new tool set. * Changes take effect on the next agent turn. * * artifact_retrieve is auto-activated as a companion whenever an artifact-producing tool * (grep, find, run_toolkit_script, or ask_question) ends up in the resulting active set and artifact_retrieve * is registered (i.e. not excluded/ * blocked/outside an allowlist -- the registry itself is built with that same filter, * so registry presence already tracks "allowed"). This is enforced here, not just in * the settings/profile refresh flow, because this method is a public, extension- * exposed activation path (`setActiveTools`) on its own: without this, grep/find could * end up active while still being handed an artifact store (gated on "allowed" in * `_buildRuntime`) with no active tool able to resolve the resulting * "Full output: artifact tool-output:" handle. * Other tools, including tool_task, activate only when explicitly requested (or present in the * shared default request) and after surviving model-capability filtering. */ setActiveToolsByName(toolNames: string[]): void; /** Request immediate transfer of one or all currently-running foreground tool calls. */ backgroundRunningToolCalls(toolCallId?: string): number; /** Whether compaction or branch summarization is currently running */ get isCompacting(): boolean; /** All messages including custom types like BashExecutionMessage */ get messages(): AgentMessage[]; /** Current steering mode */ get steeringMode(): "all" | "one-at-a-time"; /** Current follow-up mode */ get followUpMode(): "all" | "one-at-a-time"; /** Current session file path, or undefined if sessions are disabled */ get sessionFile(): string | undefined; /** Current session ID */ get sessionId(): string; /** Current session display name, if set */ get sessionName(): string | undefined; /** Scoped models for cycling (from --models flag) */ get scopedModels(): ReadonlyArray<{ model: Model; thinkingLevel?: ThinkingLevel; }>; /** Update scoped models for cycling */ setScopedModels(scopedModels: Array<{ model: Model; thinkingLevel?: ThinkingLevel; }>): void; /** File-based prompt templates */ get promptTemplates(): ReadonlyArray; private _normalizePromptSnippet; private _normalizePromptGuidelines; private _rebuildSystemPrompt; private _refreshBaseSystemPrompt; /** * Build a system prompt for a specific tool surface WITHOUT touching the session's base prompt * state (used by the router's model swap; see {@link SystemPromptBuilder.buildSystemPromptForToolNames}). */ private _buildSystemPromptForToolNames; /** * Re-enter an interrupted ask_question call from its durable request snapshot. Pending requests * are presented again; already-checkpointed answers are replayed without asking twice. The * original toolCallId is preserved so provider tool-call ordering remains valid on /resume. */ resumePendingHumanInput(): Promise; /** * Shared {@link OllamaRuntime} for a given server, lazily created and cached by baseUrl so every * caller — the router's readiness gate and any host UI's own model-lifecycle commands (e.g. * `/models`) — sees and can stop the SAME pi-managed process instead of each tracking its own * untracked child. Delegates to {@link LocalRuntimeController}. */ getLocalRuntime(baseUrl?: string): OllamaRuntime; getTransformersRuntime(modelId: string, baseUrl?: string): TransformersRuntime; /** Shared {@link PrismLlamaCppRuntime} for pi's own managed prism install — see * {@link LocalRuntimeController.getPrismLlamaCppRuntime}. Delegates so `/models` and the * readiness gate share the SAME cached instance, same contract as getLocalRuntime above. */ getPrismLlamaCppRuntime(): PrismLlamaCppRuntime; /** models.json registers a local model's baseUrl as `/v1` (OpenAI-compat); the runtime's * own health/boot endpoints are on the Ollama-native server root. Delegates to * {@link LocalRuntimeController}; kept here for `_warnIfManualModelChoiceIsRisky`'s own use. */ private _deriveOllamaServerUrl; /** * Router-swap gate (#27): a turn routed to a local model must not dead-end the turn just because * ollama isn't up. Delegates to {@link LocalRuntimeController}; see there for the full * consent-then-escalate contract (which includes the local-model readiness check itself). */ private _ensureRouteModelReady; /** * Every local model the CURRENT (post-reload) configuration could still route a turn to — * the foreground model plus any router tier (cheap/medium/expensive) that still resolves to a * real, authed, non-exhausted model. Fed to {@link LocalRuntimeController.reconcile} via the * `reconcileLocalRuntimes` hook above, ONLY after a reload generation has fully committed, so a * local model dropped from the live configuration has its pi-spawned runtime stopped instead of * leaking a child process, while one still referenced here is left untouched. Read-only — never * used for routing itself. */ private _collectEligibleLocalModelsForReconcile; getModelRouterStatus(formatLabel?: (label: string) => string): string; /** * Send a prompt to the agent. * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming * - Expands file-based prompt templates by default * - During streaming, queues via steer() or followUp() based on streamingBehavior option * - Validates model and API key before sending (when not streaming) * @throws Error if streaming and no streamingBehavior specified * @throws Error if no model selected or no API key available (when not streaming) */ prompt(text: string, options?: PromptOptions): Promise; private _runPromptSubmission; private _promptUnserialized; /** * Try to execute an extension command. Returns true if command was found and executed. */ private _parseCommandName; private _tryExecuteExtensionCommand; /** Route explicit /skill:name through the same host-owned vault as model tool calls. */ private _expandSkillCommand; /** Reject extension commands, then expand a queued message through the shared skill/template path. */ private _prepareQueuedMessageText; /** * Queue a steering message while the agent is running. * Delivered after the current assistant turn finishes executing its tool calls, * before the next LLM call. * Expands skill commands and prompt templates. Errors on extension commands. * @param images Optional image attachments to include with the message * @throws Error if text is an extension command */ steer(text: string, images?: ImageContent[]): Promise; /** * Queue a follow-up message to be processed after the agent finishes. * Delivered only when agent has no more tool calls or steering messages. * Expands skill commands and prompt templates. Errors on extension commands. * @param images Optional image attachments to include with the message * @throws Error if text is an extension command */ followUp(text: string, images?: ImageContent[]): Promise; private _createQueuedUserMessage; /** * Internal: Queue a steering message (already expanded, no extension command check). */ private _queueSteer; /** * Internal: Queue a follow-up message (already expanded, no extension command check). */ private _queueFollowUp; /** * Internal: Queue an extension command to execute after the current agent run. */ private _queueExtensionCommand; private _drainQueuedExtensionCommands; /** * Throw an error if the text is an extension command. */ private _throwIfExtensionCommand; /** * Send a custom message to the session. Creates a CustomMessageEntry. * * Handles three cases: * - Streaming: queues message, processed when loop pulls from queue * - Not streaming + triggerTurn: appends to state/session, starts new turn * - Not streaming + no trigger: appends to state/session, no turn * * @param message Custom message with customType, content, display, details * @param options.triggerTurn If true and not streaming, triggers a new LLM turn * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn" */ sendCustomMessage(message: Pick, "customType" | "content" | "display" | "details">, options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn"; }): Promise; private _sendCustomMessage; /** * Send a user message to the agent. Always triggers a turn. * When the agent is streaming, use deliverAs to specify how to queue the message. * * @param content User message content (string or content array) * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp" */ sendUserMessage(content: string | (TextContent | ImageContent)[], options?: { deliverAs?: "steer" | "followUp"; processSlashCommands?: boolean; }): Promise; /** * Clear all queued messages and return them. * Useful for restoring to editor when user aborts. * @returns Object with steering, followUp, and queued extension command arrays */ clearQueue(): { steering: string[]; followUp: string[]; commands: string[]; }; /** Number of pending messages (includes steering, follow-up, and queued extension commands) */ get pendingMessageCount(): number; /** Get pending steering messages (read-only) */ getSteeringMessages(): readonly string[]; /** Get pending follow-up messages (read-only) */ getFollowUpMessages(): readonly string[]; /** Get pending extension commands (read-only). */ getQueuedExtensionCommands(): readonly string[]; get resourceLoader(): ResourceLoader; /** * Abort current operation and wait for agent to become idle. */ abort(): Promise; setModel(model: Model, options?: { persistSettings?: boolean; }): Promise; /** Re-resolve startup profile model/thinking after allowed extension providers are bound. */ reapplyActiveProfileModelSettings(): Promise; cycleModel(direction?: "forward" | "backward"): Promise; setThinkingLevel(level: ThinkingLevel, options?: { persistSettings?: boolean; }): void; cycleThinkingLevel(): ThinkingLevel | undefined; getAvailableThinkingLevels(): ThinkingLevel[]; supportsThinking(): boolean; /** * Set steering message mode. * Saves to settings. */ setSteeringMode(mode: "all" | "one-at-a-time"): void; /** * Set follow-up message mode. * Saves to settings. */ setFollowUpMode(mode: "all" | "one-at-a-time"): void; /** * Manually compact the session context. * Aborts current agent operation first. * @param customInstructions Optional instructions for the compaction summary */ compact(customInstructions?: string): Promise; /** Start extension-requested compaction without blocking its event or shortcut handler. */ compactForExtension(options?: CompactOptions): void; /** * Cancel in-progress compaction (manual or auto). */ abortCompaction(): void; /** * Cancel in-progress branch summarization. */ abortBranchSummary(): void; /** * Check if compaction is needed and run it. * Called after agent_end and before prompt submission. * * Two cases: * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually) * * @param assistantMessage The assistant message to check * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true */ private _getAdaptedCompactionSettings; private _checkContextWindowUsageWarning; private _checkCompaction; private _measureLiveContextTokensForCompaction; /** * Internal: Run auto-compaction with events. */ private _runAutoCompaction; /** * Run one compaction attempt, retrying retryable provider failures (stream stalls, * 429/5xx, network drops) with the session's retry policy. The reliability kernel * classifies a stall as retryable by design (see withStreamIdleWatchdog); without this * loop a single transient killed the whole compaction while ordinary turns survived the * same failure via auto-retry. Caller aborts are never retried; sleepAbortable rejects * with the abort reason if the signal fires mid-backoff. */ private _compactWithRetry; /** * Toggle auto-compaction setting. */ setAutoCompactionEnabled(enabled: boolean): void; /** Whether auto-compaction is enabled */ get autoCompactionEnabled(): boolean; /** * Activate bundled memory providers (file-store + transcript recall) so the `memory` tool can * register. SDK create calls this before returning; {@link bindExtensions} re-runs it after * extensions have registered additional providers. Profile and orchestration grants still decide * whether the tool activates. */ initializeMemory(): Promise; /** Public entry point delegating to {@link ExtensionBindingController.bindExtensions}. */ bindExtensions(bindings: ExtensionBindings): Promise; private _refreshCurrentModelFromRegistry; /** Register a memory provider contributed by an extension; applied on the next memory (re)init. */ registerMemoryProvider(provider: MemoryProvider): void; registerContextMemoryProvider(provider: ContextMemoryProvider): void; /** The gateway/scheduler registry. A deployment runner registers providers and drives start/stop. */ get gateways(): GatewayRegistry; /** Register a deployment-supplied transport channel (gateway). */ registerChannelProvider(provider: ChannelProvider): void; /** Register a deployment-supplied job scheduler (cron). */ registerJobScheduler(provider: JobSchedulerProvider): void; private _refreshToolRegistry; reload(): Promise; /** * Unload a single extension without full reload. * Runs the extension's session_shutdown lifecycle, unregisters its providers, * disposes its event subscriptions, and rebuilds the runtime. * Falls back to full reload on error. */ unloadExtensionLive(extensionPath: string): Promise; /** * Load a single extension without full reload. * Loads the extension with fresh import, rebuilds the runtime, * and runs the extension's session_start lifecycle. * Falls back to full reload on error. */ loadExtensionLive(extensionPath: string): Promise; /** * Reconcile loaded extensions with the active profile. * Loads extensions that should be enabled but aren't, and unloads extensions that shouldn't be. * Falls back to full reload if any individual load/unload fails. */ reconcileLoadedExtensions(): Promise; /** * Cancel in-progress retry. */ abortRetry(): void; /** Whether auto-retry is currently in progress */ get isRetrying(): boolean; /** Whether auto-retry is enabled */ get autoRetryEnabled(): boolean; /** * Toggle auto-retry setting. */ setAutoRetryEnabled(enabled: boolean): void; executeBash(command: string, onChunk?: (chunk: string) => void, options?: { excludeFromContext?: boolean; operations?: BashOperations; }): Promise; recordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean; }): void; abortBash(): void; /** Whether a bash command is currently running */ get isBashRunning(): boolean; /** Whether there are pending bash messages waiting to be flushed */ get hasPendingBashMessages(): boolean; private _flushPendingBashMessages; /** * Set a display name for the current session. */ setSessionName(name: string): void; navigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string; }): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry; }>; getUserMessagesForForking(): Array<{ entryId: string; text: string; }>; getSessionStats(): SessionStats; getCumulativeUsage(): Usage; addSpawnedUsage(usage: Usage, opts?: { label?: string; sourceSessionId?: string; reportId?: string; }): string | undefined; getSpawnedUsage(): SpawnedUsageTotals; getDailyUsageTotals(now?: Date): DailyUsageTotals; getCostSummary(now?: Date): SessionCostSummary; getDailyUsageBreakdown(formatLabel?: (label: string) => string, now?: Date): string; /** * Save a snapshot of the goal state to the session log. * * @returns the id of the appended custom entry */ saveGoalStateSnapshot(state: GoalState, expected?: GoalStateRevision): string; /** Persist a branch-scoped tombstone and stop goal-owned execution without resurrecting old state. */ clearGoalStateSnapshot(state: GoalState, now: string): string; /** * Retrieve the latest valid goal state snapshot from the session log. */ getGoalStateSnapshot(): GoalState | undefined; /** * Persist one submitted continuation pass's turn and active-wall-clock telemetry. Provider usage * is charged separately at every assistant-response boundary under an identity-bound goal lease. * A no-op when no goal state exists. */ recordGoalContinuationPass(pass: { turns: number; wallClockMs: number; }): void; /** Restore runtime intent, automatically reopening only goals stopped by bounded system guards. */ restoreGoalRuntimeAfterResume(): boolean; /** Save native task-step state to the active session log. */ saveTaskStepsStateSnapshot(state: TaskStepsState): string; /** Retrieve the latest valid native task-step state from the active session log. */ getTaskStepsStateSnapshot(): TaskStepsState | undefined; /** Save the active ICM pipeline run pointer to the session log. */ savePipelineRunSnapshot(run: PipelineRun): string; /** Latest valid pipeline run snapshot on the active branch. */ getPipelineRunSnapshot(): PipelineRun | undefined; /** * Save a snapshot of the evidence bundle to the session log. * * @returns the id of the appended custom entry */ saveEvidenceBundleSnapshot(bundle: EvidenceBundle): string; /** * Retrieve the latest valid evidence bundle snapshot from the active branch. */ getEvidenceBundleSnapshot(): EvidenceBundle | undefined; /** Retrieve all valid evidence bundle snapshots from the active branch. */ getEvidenceBundleSnapshots(): EvidenceBundle[]; /** Live lane records tracked by this process (running and terminal). */ getLaneRecords(): LaneRecord[]; private _emitAutonomyTelemetry; private _recordGateOutcome; /** Copies of the bounded gate-outcome history, oldest first, latest last. */ getGateOutcomeHistory(): GateOutcomeHistoryEntry[]; saveWorkerClaimSnapshot(claim: WorkerClaim, request?: WorkerRequest): string; getWorkerClaimSnapshots(): WorkerClaim[]; saveLearningDecisionSnapshot(decision: LearningDecision): string; getLearningDecisionSnapshots(): LearningDecision[]; /** * The single injection point that makes the goal-continuation snapshot lane-aware: * `laneRecords` feeds BOTH `evaluateGoalContinuation`'s "waiting" branch (a worker dispatched * against an open requirement) and the per-goal worker-spend overlay — read fresh here so BOTH the * goal loop (`GoalLoopController`) and the idle scheduler (`BackgroundLaneController`) see the * same live lane state, since both reach this same method. */ getGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot; /** * Capability profile derived from the CURRENT session model's own metadata (context window), * honoring the modelCapability.mode setting ("off" disables, a class name forces). */ getModelCapabilityProfile(): ModelCapabilityProfile; /** * Whether the CURRENT session model may drive a worktree-sync lane worker (see * `evaluateLaneWorkerRefusal` in model-capability.ts): full capability class, a DECLARED * (registry) context window, an ADVERTISED native tool-call path (`Model.textToolCallProtocol` * unset/false -- `true` means phone-only), and no graded `/toolprobe` demotion to * "text-protocol"/"none" on record. An unprobed model (no verdict on record yet) is eligible on * its advertised support alone. `undefined` means eligible. */ getLaneWorkerRefusal(): LaneWorkerRefusal | undefined; /** * Run one bounded, read-only research pass and persist its results. Delegates to * {@link BackgroundLaneController}; see there for the full gating/budget/dedupe contract. */ runResearchLaneOnce(request?: { query?: string; context?: string; goalId?: string; }): Promise; /** * Run one durable worker-agent turn. Delegates to {@link BackgroundLaneController}; * consumed by the `delegate` tool. */ runWorkerDelegationOnce(request: WorkerDelegationRequest): Promise; /** * Probe a candidate model against the subagent contracts. Delegates to * {@link BackgroundLaneController}; probe spend is reported through spawned-usage accounting. */ runModelFitness(args: { model: string; trials?: number; }): Promise<{ started: true; model: string; report: ModelFitnessReport; } | { started: false; skipReason: string; }>; /** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */ getStoredFitnessReports(): StoredFitnessReport[]; continueGoalOnce(options: GoalContinuationOnceOptions): Promise; /** * Public entry point for BOTH idle autosteer and manual (`/goal start`, `/goal-continue`) * continuation. Delegates to {@link BackgroundLaneController.continueGoalLoopExclusive}, the * single-flight guard that prevents two goal loops from racing to submit prompts through the * same session (which throws "Agent is already processing" from the second submission). Do not * call `this._goals.continueLoop` directly from here — that bypasses the guard. */ continueGoalLoop(options: GoalContinuationLoopOptions): Promise; /** Run one explicit isolated completion for bounded host-owned consumers. */ runIsolatedCompletion(opts: IsolatedCompletionOptions): Promise; /** * Explicit compatibility/application reflection pass. Automatic reflection never calls this * method; it returns null when the demand gate skips or in a child session. */ runReflectionPass(input: { signals: DemandSignals; recentTurnText: string; model?: Model; thinkingLevel?: ThinkingLevel; signal?: AbortSignal; /** Stable id so a duplicate scheduling/retry of the same pass can't double-count its cost. */ reportId?: string; }): Promise; getLearningAuditRecords(): LearningAuditRecord[]; /** Roll back one applied durable learning change. Delegates to {@link ReflectionController}. */ rollbackLearningWrite(auditId: string): Promise<{ ok: boolean; reason: string; }>; getContextUsage(): ContextUsage | undefined; exportToHtml(outputPath?: string): Promise; exportToJsonl(outputPath?: string): string; getLastAssistantText(): string | undefined; getAutonomyStatusSnapshot(): AutonomyStatusSnapshot; /** * Aggregate an effectiveness/autonomy dashboard: what Pi has actually been doing (recent * route choices, latest gate outcome, cost, and any research/delegation/learning/goal * activity). Read-only — combines existing session-log getters, never mutates state or * recomputes a route/gate decision. */ getAutonomyDiagnosticSnapshot(options?: { maxEntriesPerFamily?: number; }): AutonomyDiagnosticSnapshot; createReplacedSessionContext(): ReplacedSessionContext; /** * Check if extensions have handlers for a specific event type. */ hasExtensionHandlers(eventType: string): boolean; /** * Get the extension runner (for setting UI context and error handlers). */ get extensionRunner(): ExtensionRunner; /** Owner control-plane access for the native /secrets TUI. Never exposed as an agent tool. */ get credentialManager(): CredentialManager; } //# sourceMappingURL=agent-session.d.ts.map