/** * dsh-arc-context — Adaptive Reversible Context (ARC) for the DeepSeek Harness, * delivered as a `CompactionEngine` backend. * * The model decides when and what to compress (pure ARC semantics): * - the `compress` tool durably shadows a surface range with the model-written * summary (no second LLM summarization call — the ARC cost win); * - the original events stay in the append-only session log, so `decompress`, * `search_context`, and replay always work; * - refs are surface seqs carried by the injected nudge's range table (DSH * has no in-memory message rewrite hook — see docs/dsh-porting-verification.md); * - automatic policy never summarizes by itself: it nudges the model. * * Mount it wherever a compaction backend is expected: * * ```yaml * - id: compaction-billion-context * name: 'dsh-arc-context' * config: * modelContextLimit: 128000 * ``` * * The package registers `ctx.compaction` plus the four model tools and the * `/arc` command when the hosting composition provides `ctx.tools` / * `ctx.commands`. * @module dsh-arc-context */ import type { Context } from '@deepseek-ai/cordis'; import Schema from '@deepseek-ai/schemastery'; import { CompactionEngine, type CompactionAgentContext, type CompactionResult, type CompactionTrigger, type ManualCompactAgentContext } from '@deepseek-ai/dsh-compaction'; import { type CompressionCore } from 'acp-kernel'; import type { Agent } from '@deepseek-ai/dsh-agent'; import type { CommandId } from '@deepseek-ai/dsh-commands/brand'; import { ArcStateStore } from './state.ts'; import { type BackendOwnership } from './tools.ts'; import { type ArcPrompts, type ResolvedPrompts } from './prompts.ts'; import { type ArcWindow } from './window.ts'; import { type AdaptiveGovernorConfig } from './governor.ts'; declare const ARC_BACKEND_BRAND: unique symbol; /** * True when `value` is an ARC compaction backend (or a Cordis service facade * over one). The structural brand survives duplicated package instances and * realm isolation; the bridge and `backendOwnership` both resolve takeover * through it. * @param value - any service value resolved for `compaction`. */ export declare function isArcBackend(value: unknown): boolean; export { ArcStateStore } from './state.ts'; export { kernelConfigFor, type KernelConfigInput } from './config.ts'; export { ARC_SYSTEM_PROMPT, ARC_SYSTEM_PROMPT_ORDER } from './system-prompt.ts'; export { DEFAULT_PROMPTS, DEFAULT_RESOLVED, renderSystemPrompt, renderTemplate, resolvePrompts, type ArcPrompts, type NudgePrompts, type PromptInput, type PromptOverride, type RangeTablePrompts, type ResolvedPrompts, type ToolPrompts, } from './prompts.ts'; export { makeTools, type BackendOwnership, type ToolEnvironment } from './tools.ts'; export { arcCommand } from './commands.ts'; export { buildNudge, resolveTokenCount, type NudgeEnvironment, type NudgeOutcome } from './nudge.ts'; export { DEFAULT_CONTEXT_WINDOW, detectContextWindow, windowSourceLabel, type ArcWindow, } from './window.ts'; export { DEFAULT_ADAPTIVE_GOVERNOR, DEFAULT_AUTO_OUTPUT_TOKENS, explicitMaxTokensForAgent, governorCapacity, governedKernelInput, governedMaxTokens, governedOutputReserve, resolveAdaptiveGovernor, shouldRunEmergencyFallback, type AdaptiveGovernorConfig, type GovernorCapacity, type MaxOutputTokensPolicy, type OutputIntentContext, } from './governor.ts'; export { buildEmergencyFallbackSummary, buildManualFallbackSummary, buildModelSummarySafetyIndex, prepareLocalCompaction, resolveShadowedTokenCount, runEmergencyFallback, runLocalCompactionRegion, } from './fallback.ts'; export { AlreadyCompressedRangeError, rebuildBlockLedger, resolveSurfaceRange, runCompactionTransaction, runManualCompactionTransaction, shadowedSeqsOf, findOpenTurn, assertNoActiveCompaction, blockRegistry, blockRefForSummarySeq, compactionIdsOfKernelBlocks, summarySeqOfKernelBlock, expandShadowedSeqs, expandEffectiveSourceSeqs, type ArcBlockLedgerEntry, type CompactionTransactionInput, type ResolvedSurfaceRange, } from './region.ts'; export { eventsToCoreMessages, projectEvent, surfaceEventsOf, extractEventText } from './messages.ts'; export { inspectPresetComposition, isolatesCompaction, type PresetCompatibility, } from './preset-compat.ts'; export interface ArcConfig { /** Refresh tier-2/3 safety appendices from recursively expanded original sources. Default true. */ readonly effectiveSourceSafetyIndex: boolean; /** Body-assembly policy for model-checkpoint safety appendices under budget pressure: 'value' | 'chronological'. Default 'value'. */ readonly safetyIndexRanking: string; /** * The context window used for pressure decisions, in tokens. When omitted, * `autoModelContextLimit` (default true) probes the model's real window via * `agent.ctx.llm.resolveModelInfo(provider, model)`; an explicit value * always wins and disables the probe. */ readonly modelContextLimit?: number; /** Probe the model's real context window from the LLM runtime. Default true. */ readonly autoModelContextLimit: boolean; /** Nudge window lower bound (usage fraction; validation only — the growth-driven trigger has no percentage floor). Kernel default 0.45 — same as billion-context-pi. */ readonly nudgeMinContextLimitPct?: number; /** * Nudge window upper bound — over-limit guarantee line: above this the * kernel injects a nudge regardless of growth or cadence. Engine default * 0.70 (deliberately BELOW the kernel/billion-context-pi default 0.75 and * the host compaction-basic auto-compaction line 0.80, so the forced nudge * always fires first); an explicit value wins. */ readonly nudgeMaxContextLimitPct?: number; /** * Emergency nudge threshold (bypasses the per-turn dedup). Engine default * 0.85 (down from the kernel/billion-context-pi default 0.95: 95% leaves * the model no room to act before the API rejects, and the host's 80% * compaction-basic line shadows it in standard/code/cordis modes). */ readonly nudgeEmergencyThresholdPct?: number; /** Protected-zone size in trailing messages (never compressible). Kernel default 5. * Larger values are safer for tasks that keep re-reading recent output; smaller * ones free more history but risk compressing content still in active use. */ readonly protectedRecentMessages?: number; /** Protected-zone size in trailing tokens (never compressible). Kernel default 5000. */ readonly protectedRecentTokens?: number; /** Minimum total original chars for a compressible range. Kernel default 5000. * Lower values let the model compress small spans early; higher values batch * history into fewer, denser blocks. */ readonly minCompressChars?: number; /** Nudge cadence: minimum turns between normal (non-emergency) nudges. Kernel default 5. * Raise to make pressure notes rarer; 1 makes every over-threshold turn nudge. */ readonly nudgeCadenceTurns?: number; /** Any other acp-kernel Config override (billion-context-pi's `coreOverrides` escape hatch). */ readonly coreOverrides?: Partial; /** * Custom token-count function for the kernel's internal estimation. * Defaults to the kernel's `defaultCountTokens` (CJK: 1 char = 1 token, * other: 4 chars = 1 token — aligns with billion-context-pi). * Can be overridden for provider-specific tokenization, e.g. DeepSeek's * official coefficient: 1 CJK char ≈ 0.6 tokens, 1 other char ≈ 0.3 tokens. * Only affects the kernel's internal estimation (compressible range sizing, * nudge text, growth branch pending); the `projectedTokens` reading from * `sessionProjections` (used for nudge pressure decisions and arc_status) * is provider-anchored and unaffected by this function. */ readonly countTokens?: (text: string) => number; /** Register the four model tools on `ctx.tools`. Default true. */ readonly autoTools: boolean; /** Register the `/arc` command on `ctx.commands`. Default true. */ readonly autoCommand: boolean; /** Inject the nudge into `agent/pre-step` when the kernel recommends it. Default true. */ readonly autoNudge: boolean; /** Per-stage prompt template overrides (nudge / range table / system prompt / tool descriptions). See docs/configurable-prompts-design.md. */ readonly prompts?: ArcPrompts; /** * Optional output-reserve-aware governor. It caps excessive completion * reserve and replaces eager growth nudges with late pressure nudges against * the remaining effective input capacity. Disabled by default while beta. */ readonly adaptiveGovernor?: Partial; } /** Loader-facing configuration type; programmatic-only countTokens is intentionally omitted. */ export type Config = Omit, 'countTokens'>; /** * Official Cordis/Schemastery configuration surface. Defaults make a plain * package install usable; constructor validation still enforces cross-field * relationships such as normal pressure < emergency pressure. */ export declare const Config: Schema; export declare function resolveArcConfig(config?: Partial): ArcConfig; /** * The ARC compaction backend. Subclasses the seam exactly like * `dsh-compaction-basic`; swaps summarization-driven compaction for * model-driven block compression without touching the agent loop. */ export declare class ArcCompactionEngine extends CompactionEngine { /** Cross-scope/cross-module structural brand; Cordis may expose a service facade rather than this exact object. */ readonly [ARC_BACKEND_BRAND] = true; /** The framework-agnostic ARC compression core, reused verbatim. */ readonly kernel: CompressionCore; /** Per-session kernel state. */ readonly store: ArcStateStore; /** Resolved engine configuration. */ readonly config: ArcConfig; /** Resolved prompt templates (validated at construction — fail-fast on template typos). */ readonly prompts: ResolvedPrompts; /** Resolved output-reserve-aware governor configuration. */ readonly adaptiveGovernor: AdaptiveGovernorConfig; private readonly lastNudgeTurn; /** One provider-overflow recovery is allowed per step; pre-step resets it. */ private readonly overflowFallbackUsed; /** Per provider/model route the resolved window (probe failures cached too). */ private readonly windowCache; /** Identify the effective host or preset-isolated compaction provider for one agent. */ backendOwnership(agent: Agent): BackendOwnership; /** Governor must never run as a silent hybrid beside a nearer preset backend. */ assertActiveBackend(agent: Agent): void; private projectedContextWindow; private projectedContext; constructor(ctx: Context, config?: Partial); /** * Resolve the effective context window for an agent. An explicitly * configured `modelContextLimit` always wins (no probe). Otherwise probe the * model's real window via `agent.ctx.llm.resolveModelInfo` (cached per * provider/model route, probe failures cached too) and fall back to * DEFAULT_CONTEXT_WINDOW when auto-detection is disabled or unavailable. */ windowFor(agent: Agent): Promise; /** * Normal operation stays model-driven. Governor mode adds one model-free, * reversible emergency path: at its emergency line (or after a confirmed * provider overflow), archive one old balanced range into ARC cold-storage. */ compactIfNeeded(agent: CompactionAgentContext, trigger: CompactionTrigger, signal: AbortSignal): Promise; /** Explicit idle-session compaction through a local reversible checkpoint. */ compactNow(agent: ManualCompactAgentContext, signal: AbortSignal, sourceCommandId?: CommandId): Promise; /** * Compact one caller-selected range with a bounded local reversible * checkpoint. No auxiliary LLM call is made. */ compactRegion(start: number, end: number, agent: CompactionAgentContext, signal?: AbortSignal): Promise; } /** Product-facing name. The ARC name remains exported for source compatibility. */ export { ArcCompactionEngine as ArcContextEngine }; export default ArcCompactionEngine;