import { type AgentMessage, type AgentTelemetryConfig, ThinkingLevel } from "@gajae-code/agent-core"; import { type AuthCredentialSelector, type Model, type ProviderSessionState } from "@gajae-code/ai/core"; import { createAppendOnlyContextManager, providerSupportsAppendOnlyAuto, resolveAppendOnlyMode } from "../append-only-mode"; import { AsyncJobManager } from "../async"; import { type Rule } from "../capability/rule"; import { ModelRegistry } from "../config/model-registry"; import { type ScopedModelSelection } from "../config/model-resolver"; import { type PromptTemplate } from "../config/prompt-templates"; import { Settings, type SkillsSettings } from "../config/settings"; import type { BashRestrictionProfile } from "../tools/bash-allowed-prefixes"; import "../discovery"; import type { CustomCommandsLoadResult } from "../extensibility/custom-commands"; import type { CustomTool } from "../extensibility/custom-tools/types"; import { type ExtensionFactory, type ExtensionUIContext, type LoadExtensionsResult, type ToolDefinition } from "../extensibility/extensions"; import { type ConstrainedPluginHook } from "../extensibility/gjc-plugins/constrained-hooks"; import { type GjcRuntimeSnapshotProvider } from "../extensibility/gjc-plugins/runtime-quarantine"; import { type Skill, type SkillWarning } from "../extensibility/skills"; import type { FileSlashCommand } from "../extensibility/slash-commands"; import type { HindsightSessionState } from "../hindsight/state"; import { type LocalProtocolOptions } from "../internal-urls"; import type { LspStartupServerInfo } from "../lsp"; import { AgentRegistry } from "../registry/agent-registry"; import { type OptionalRuntimeServicesOverrides } from "../runtime/optional-runtime-services"; import { MCPManager } from "../runtime-mcp"; import { AgentSession, type ForkContextSeed } from "../session/agent-session"; import { AuthStorage } from "../session/auth-storage"; import { SessionManager } from "../session/session-manager"; import { type StartupAuthConfigSnapshot } from "../session/startup-auth-config"; import { type BuildSystemPromptResult } from "../system-prompt"; import { type AutomationTools, BUILTIN_TOOLS, createTools, HIDDEN_TOOLS, type Tool, type ToolSession } from "../tools"; import { EventBus } from "../utils/event-bus"; import type { WorkspaceTree } from "../workspace-tree"; export type { AutomationToolName, AutomationTools } from "../tools"; /** Capture the cursor edit grant before the model-facing edit entry is removed. */ export declare function captureCursorEditTool(toolRegistry: ReadonlyMap, createReplaceTool: () => T): T | undefined; /** * Reconcile a resumed transcript that ends on an unpaired tool call. * * When a subagent finishes by calling `yield` (or any turn is torn down right * after a tool executes), the terminating abort can land before the tool * result is persisted, leaving the saved session ending on an assistant * `toolCall` with no matching `toolResult`. Replaying that history verbatim on * resume produces an invalid provider request (a tool_use not followed by a * tool_result) and the resumed turn fails immediately. Synthesize a placeholder * result for any such trailing unpaired tool call so a resumed session always * starts from a valid, paired history. No-op for well-formed transcripts. */ /** Whether the cached SDK-only reconciliation store still matches the current * session identity. session_switch/session_branch can move to a DIFFERENT * transcript that retains the same copied session id, so the cache is keyed * by BOTH the session id and the session-file path (including a null-to-file * transition); a mismatch means the store must be recreated or the successor * reads/writes the predecessor's reconciliation file (review thread P2). */ export declare function sdkOnlyStoreMatches(cached: { sessionId: string; sessionFile: string | undefined; } | undefined, sessionId: string, sessionFile: string | undefined): boolean; export declare function reconcileTrailingToolCalls(messages: AgentMessage[]): AgentMessage[]; export interface CreateAgentSessionOptions { /** Working directory for project-local discovery. Default: getProjectDir() */ cwd?: string; /** Global config directory. Default: ~/.gjc/agent */ agentDir?: string; /** Spawns to allow. Default: "*" */ spawns?: string; /** Auth storage for credentials. Default: discoverAuthStorage(agentDir) */ authStorage?: AuthStorage; /** Model registry. Default: discoverModels(authStorage, agentDir) */ modelRegistry?: ModelRegistry; /** Model to use. Default: from settings, else first available */ model?: Model; /** Raw model pattern string (e.g. from --model CLI flag) to resolve after extensions load. * Used when model lookup is deferred because extension-provided models aren't registered yet. */ modelPattern?: string; /** Active profile inherited by a nested SDK/subagent session. */ activeModelProfile?: string; /** Thinking selector. Default: from settings, else unset */ thinkingLevel?: ThinkingLevel; /** Runtime substitution metadata for the initial model_change session event. */ modelSubstitution?: { requestedModel: Model; reason: string; }; /** Models available for cycling (Alt+N in interactive mode) */ scopedModels?: ScopedModelSelection[]; /** System prompt blocks. Array replaces default, function receives default blocks and returns final blocks. */ systemPrompt?: string[] | ((defaultPrompt: string[]) => string[]); /** Optional provider-facing session identifier for prompt caches and sticky auth selection. * Keeps persisted session files isolated while reusing provider-side caches. */ providerSessionId?: string; /** Optional credential-selection session identity, distinct from provider transport/cache identity. */ credentialSessionId?: string; /** Runtime credential selector for multi-account auth pools. */ credentialSelector?: { provider?: string; selector: AuthCredentialSelector; raw: string; }; /** Soft runtime credential preference; quota/rate-limit failures may rotate away from it. */ preferredCredentialSelector?: { provider?: string; selector: AuthCredentialSelector; raw: string; }; /** Durable global pin intent loaded from startup-auth config; session bootstrap resolves it without mutating shared storage. */ startupAuthConfig?: StartupAuthConfigSnapshot; /** Custom tools to register (in addition to built-in tools). Accepts both CustomTool and ToolDefinition. */ customTools?: (CustomTool | ToolDefinition)[]; /** * Host-owned implementations for the built-in `browser` and `computer` * surfaces. These are materialized as built-ins, retain built-in provenance * and activation behavior, and receive cancellation through AgentTool's * AbortSignal. A matching custom or extension tool is rejected. */ automationTools?: AutomationTools; /** Explicit parent/phase used to load active GJC sub-skill tools for this session. */ gjcSubskillToolContext?: { parent: string; phase: string; sessionId?: string; cwd?: string; }; /** Inline extensions (merged with discovery). */ extensions?: ExtensionFactory[]; /** Additional extension paths to load (merged with discovery). */ additionalExtensionPaths?: string[]; /** Explicit hook module paths to load in addition to native discovery. */ hookPaths?: string[]; /** Disable extension discovery (explicit paths still load). */ disableExtensionDiscovery?: boolean; /** * Pre-loaded extensions (skips file discovery). * @internal Used by CLI when extensions are loaded early to parse custom flags. */ preloadedExtensions?: LoadExtensionsResult; /** Shared event bus for tool/extension communication. Default: creates new bus. */ eventBus?: EventBus; /** Skills. Default: bundled GJC defaults, plus filesystem skills when enabled */ skills?: Skill[]; /** Rules. Default: discovered from multiple locations */ rules?: Rule[]; /** Context files (AGENTS.md content). Default: discovered walking up from cwd */ contextFiles?: Array<{ path: string; content: string; }>; /** Pre-built workspace tree (skips re-scanning; passed by parents to subagents). */ workspaceTree?: WorkspaceTree; /** Prompt templates. Default: discovered from cwd/.gjc/prompts/ + agentDir/prompts/ */ promptTemplates?: PromptTemplate[]; /** File-based slash commands. Default: discovered from commands/ directories */ slashCommands?: FileSlashCommand[]; /** @deprecated MCP runtime discovery is quarantined and ignored. */ enableMCP?: boolean; /** Existing MCP manager to reuse (skips discovery, propagates to toolSession). * Mutually exclusive with mcpConfigPath. */ mcpManager?: MCPManager; /** Load MCP tools for a top-level session only from this caller-owned absolute config file path. * Mutually exclusive with mcpManager. */ mcpConfigPath?: string; /** * Whether conventional MCP autoload is enabled for a top-level standalone * session (default: true). When false, native user `~/.gjc/agent/mcp.json` * and project `.gjc/mcp.json` registrations are not discovered or connected * at startup. Plugin-bundle MCPs and `mcpConfigPath` exact-file sessions * are unaffected. CLI: `--no-mcp`. */ enableMcpAutoload?: boolean; /** * Defer connecting an exact MCP config until the interactive UI is ready. * @internal CLI-only startup optimization; SDK callers retain synchronous loading by default. */ deferMcpConfigStartup?: boolean; /** * Defer memory backend startup until the caller has applied startup model profiles. * @internal CLI-only ordering guard; SDK callers retain immediate startup by default. */ deferMemoryBackendStartup?: boolean; /** Enable LSP integration (tool, formatting, diagnostics, warmup). Default: true */ enableLsp?: boolean; /** Skip Python kernel availability check and prelude warmup */ skipPythonPreflight?: boolean; /** Tool names explicitly requested (enables disabled-by-default tools) */ toolNames?: string[]; /** Output schema for structured completion (subagents) */ outputSchema?: unknown; /** Whether to include the yield tool by default */ requireYieldTool?: boolean; /** Task recursion depth (for subagent sessions). Default: 0 */ taskDepth?: number; /** Current role-agent type/name for nested task sessions. */ currentAgentType?: string; /** Parent Hindsight state to alias for subagent private memory backend compatibility. */ parentHindsightSessionState?: HindsightSessionState; /** Pre-allocated agent identity for IRC routing. Default: "0-Main" for top-level, parentTaskPrefix-derived for sub. */ agentId?: string; /** Display name for the agent in IRC. Default: "main" or "sub". */ agentDisplayName?: string; /** Compact task label for hidden IRC roster reminders. */ agentRosterLabel?: string; /** Optional restricted bash command prefixes for read-only role agents. */ bashAllowedPrefixes?: string[]; /** Restriction policy paired with bashAllowedPrefixes. */ bashRestrictionProfile?: BashRestrictionProfile; /** Optional per-session restriction for goal tool operations. */ goalToolAllowedOps?: readonly ("create" | "get" | "complete" | "resume" | "drop" | "pause")[]; /** Optional per-session allowlist for tools exposed through search_tool_bm25. */ discoverableToolAllowedNames?: readonly string[]; /** * Discoverable built-in tools that must stay in the initial active set even when * `tools.discoveryMode === "all"` would otherwise hide them behind `search_tool_bm25`. * Used for coordination tools (e.g. `irc`) that a subagent must be able to use * immediately without first spending a discovery round-trip to find them. */ alwaysActiveToolNames?: readonly string[]; /** Optional shared agent registry for IRC routing. Default: AgentRegistry.global(). */ agentRegistry?: AgentRegistry; /** Parent task ID prefix for nested artifact naming (e.g., "6-Extensions") */ parentTaskPrefix?: string; /** Parent manager borrowed by a child session; never disposed by the child. */ inheritedAsyncJobManager?: AsyncJobManager; /** * W6b: the parent's scope-held MCP facade, handed to a canonical sub-session so * it can inherit always-on MCP tools without owning the manager. Replaces the * removed `MCPManager.instance()` inheritance path; the sub-session never * connects, registers callbacks, or disposes this manager. */ inheritedMcpManager?: import("../runtime-mcp/manager").MCPManager; /** Session manager. Default: session stored under the configured agentDir sessions root */ sessionManager?: SessionManager; /** Override local:// protocol options for subagent local:// sharing. Default: uses the session's own artifacts dir and session ID. */ localProtocolOptions?: LocalProtocolOptions; /** Settings instance. Default: a scope-local Settings.loadForScope({ cwd, agentDir }). */ settings?: Settings; /** Internal/advanced runtime-service injection. Omitted services use session defaults. */ runtimeServices?: OptionalRuntimeServicesOverrides; /** Whether UI is available (enables interactive tools like ask). Default: false */ hasUI?: boolean; /** Whether this host mode can own a notification session endpoint. Default: true. */ notificationHostModeSupported?: boolean; /** Whether this host mode can own the root SDK endpoint. Default: true. */ sdkHostModeSupported?: boolean; /** Override configured Discord/Slack daemon readiness, primarily for embedded hosts and deterministic tests. */ ensureNotificationProviderDaemon?: (provider: "discord" | "slack", settings: Settings) => Promise; /** * Opt-in OpenTelemetry instrumentation forwarded to the underlying Agent. * Passing `{}` enables the loop's GenAI-semantic-convention spans. See * {@link AgentTelemetryConfig} for the full surface (hooks, content capture, * cost estimator, agent identity). * * Safe to enable without an OTEL SDK registered in the host: the * `@opentelemetry/api` package returns a no-op tracer in that case. */ telemetry?: AgentTelemetryConfig; /** Optional fork-context seed used to initialize a child session before its first prompt. */ forkContextSeed?: ForkContextSeed; /** Optional provider state override. Fork-context children should omit this by default. */ providerSessionState?: Map; /** Cooperative pause checkpoint passed through to Agent. */ shouldPause?: () => boolean; } /** Result from createAgentSession */ export interface CreateAgentSessionResult { /** The created session */ session: AgentSession; /** Extensions result (loaded extensions + runtime) */ extensionsResult: LoadExtensionsResult; /** Update tool UI context (interactive mode) */ setToolUIContext: (uiContext: ExtensionUIContext, hasUI: boolean) => void; /** MCP manager for server lifecycle management (undefined if MCP disabled or an exact tools-only config is session-owned) */ mcpManager?: MCPManager; /** Starts a deferred exact-config MCP connection. Present only when deferMcpConfigStartup was requested. */ startDeferredMcpConfig?: () => Promise; /** Starts a deferred memory backend. Present only when deferMemoryBackendStartup was requested. */ startDeferredMemoryBackend?: () => Promise; /** Warning if session was restored with a different model than saved */ modelFallbackMessage?: string; /** LSP servers configured for lazy startup in interactive mode */ lspServers?: LspStartupServerInfo[]; /** Shared event bus for tool/extension communication */ eventBus: EventBus; /** * Read-only view of GJC bundle runtime evidence for the activation generation * this session published. Undefined when no GJC bundles participated. */ gjcRuntimeSnapshot?: GjcRuntimeSnapshotProvider; } export interface DeferredMcpConfigStartupResult { loadedToolCount: number; hasErrors: boolean; } export type { PromptTemplate } from "../config/prompt-templates"; export { Settings, type SkillsSettings } from "../config/settings"; export type { CustomCommand, CustomCommandFactory } from "../extensibility/custom-commands/types"; export type { CustomTool, CustomToolFactory } from "../extensibility/custom-tools/types"; export type * from "../extensibility/extensions"; export type { Skill } from "../extensibility/skills"; export type { FileSlashCommand } from "../extensibility/slash-commands"; export type { Tool } from "../tools"; export { buildDirectoryTree, buildWorkspaceTree, type DirectoryTree, type WorkspaceTree } from "../workspace-tree"; export { BUILTIN_TOOLS, createTools, HIDDEN_TOOLS, type ToolSession }; export declare function loadSshTool(session: ToolSession): Promise; /** * Create an AuthStorage instance. * * Default: local SQLite store at `/agent.db`. * * Broker mode: when `GJC_AUTH_BROKER_URL` is set, credentials are pulled from * a remote auth-broker over the wire. Refresh tokens never leave the broker; * the client receives access tokens with `refresh = "__remote__"` and calls * back into the broker through the {@link AuthStorageOptions.refreshOAuthCredential} * override to re-mint access tokens when needed. */ export declare function discoverAuthStorage(agentDir?: string, startupAuth?: StartupAuthConfigSnapshot): Promise; /** Ranking is resolved as part of the typed startup-auth snapshot. */ /** * Discover extensions from cwd. */ export declare function discoverExtensions(_cwd?: string): Promise; /** * Discover skills from cwd and agentDir. */ export declare function discoverSkills(_cwd?: string, _agentDir?: string, _settings?: SkillsSettings): Promise<{ skills: Skill[]; warnings: SkillWarning[]; }>; /** * Discover context files (AGENTS.md) walking up from cwd. * Returns files sorted by depth (farther from cwd first, so closer files appear last/more prominent). */ export declare function discoverContextFiles(cwd?: string, _agentDir?: string): Promise>; /** * Discover prompt templates from cwd and agentDir. */ export declare function discoverPromptTemplates(cwd?: string, agentDir?: string): Promise; /** * Discover file-based slash commands from commands/ directories. */ export declare function discoverSlashCommands(_cwd?: string): Promise; /** * Discover custom commands (TypeScript slash commands) from cwd and agentDir. */ export declare function discoverCustomTSCommands(_cwd?: string, _agentDir?: string): Promise; export interface BuildSystemPromptOptions { tools?: Tool[]; skills?: Skill[]; contextFiles?: Array<{ path: string; content: string; }>; cwd?: string; appendPrompt?: string; repeatToolDescriptions?: boolean; } /** * Build the default provider-facing system prompt blocks. * * The returned `systemPrompt` preserves the stable harness prompt and dynamic project context * as separate entries so providers can cache prompt prefixes without concatenating blocks. */ export declare function buildSystemPrompt(options?: BuildSystemPromptOptions): Promise; export { createAppendOnlyContextManager, providerSupportsAppendOnlyAuto, resolveAppendOnlyMode }; export declare function createPluginHooksExtension(hooks: ConstrainedPluginHook[]): ExtensionFactory; /** * Intent tracing (`_i`) is a model-facing reasoning aid, not a UI feature: it * makes the model state a tool call's purpose before the call executes, and the * loop turns that string into `tool_execution_start.intent` for every consumer * (TUI transcript, ACP `tool_call.title`, telemetry, session dumps). * * The per-call token cost is only worth forcing on the operator-facing session, * so canonical sub-sessions (role agents spawned through `task`) stay omitted. * Surface shape must not decide this — an ACP or print-mode top-level session is * the same conversation the operator would have run in the TUI. */ export declare function resolveIntentTracingEnabled(intentTracingSetting: boolean | undefined, options: { subSession: boolean; }): boolean; export declare function createAgentSession(options?: CreateAgentSessionOptions): Promise;