@kodax-ai/kodax 0.7.42 → 0.7.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +65 -6
  2. package/README.md +87 -56
  3. package/README_CN.md +46 -25
  4. package/dist/chunks/chunk-35BDEEC5.js +2 -0
  5. package/dist/chunks/chunk-4YPL2UVZ.js +848 -0
  6. package/dist/chunks/chunk-DI2G3YWL.js +31 -0
  7. package/dist/chunks/chunk-HHQ7YTGM.js +425 -0
  8. package/dist/chunks/chunk-QHILHQBB.js +519 -0
  9. package/dist/chunks/{chunk-IYJ5EPRV.js → chunk-RUDYNAK7.js} +1 -1
  10. package/dist/chunks/compaction-config-NAPRF7XR.js +2 -0
  11. package/dist/chunks/{construction-bootstrap-J2WOCYEK.js → construction-bootstrap-PHTGBRNU.js} +4 -4
  12. package/dist/chunks/dist-CCYBJJZY.js +2 -0
  13. package/dist/chunks/dist-RHIHZAYX.js +2 -0
  14. package/dist/chunks/utils-TV3UYCHQ.js +2 -0
  15. package/dist/index.d.ts +11 -11
  16. package/dist/index.js +2 -2
  17. package/dist/kodax_cli.js +1159 -1102
  18. package/dist/provider-capabilities.json +167 -0
  19. package/dist/sdk-agent.d.ts +905 -48
  20. package/dist/sdk-agent.js +1 -1
  21. package/dist/sdk-coding.d.ts +995 -755
  22. package/dist/sdk-coding.js +1 -1
  23. package/dist/sdk-llm.d.ts +5 -3
  24. package/dist/sdk-llm.js +1 -1
  25. package/dist/sdk-mcp.d.ts +1 -1
  26. package/dist/sdk-mcp.js +1 -1
  27. package/dist/sdk-repl.d.ts +10 -9
  28. package/dist/sdk-repl.js +1 -1
  29. package/dist/sdk-session.d.ts +23 -11
  30. package/dist/sdk-session.js +1 -1
  31. package/dist/sdk-skills.js +1 -1
  32. package/dist/types-chunks/{cost-tracker.d-B6vMoLLF.d.ts → base.d-FUJahC0i.d.ts} +2 -110
  33. package/dist/types-chunks/{bash-prefix-extractor.d-CkhaqKkg.d.ts → bash-prefix-extractor.d-DdoSeghD.d.ts} +442 -131
  34. package/dist/types-chunks/cost-tracker.d-wRtyEW9d.d.ts +110 -0
  35. package/dist/types-chunks/file-tracker.d-DOfaoCbJ.d.ts +633 -0
  36. package/dist/types-chunks/manager.d-87belpiS.d.ts +370 -0
  37. package/dist/types-chunks/{resolver.d-DX9au4NJ.d.ts → resolver.d-B7ZnVuuf.d.ts} +157 -10
  38. package/dist/types-chunks/{session-storage.d-Cci897iM.d.ts → storage.d-DFD9ln5c.d.ts} +49 -2
  39. package/dist/types-chunks/{history-cleanup.d-DznrzEiU.d.ts → types.d-DM8zEJgF.d.ts} +1084 -282
  40. package/dist/types-chunks/{types.d-mM8vqvhT.d.ts → types.d-HBbWT-iA.d.ts} +41 -3
  41. package/dist/types-chunks/{storage.d-Bc5DoAwp.d.ts → utils.d-C5fzCE9W.d.ts} +25 -47
  42. package/package.json +7 -6
  43. package/dist/chunks/chunk-3RKBXWZS.js +0 -2
  44. package/dist/chunks/chunk-7JLYVWAF.js +0 -1033
  45. package/dist/chunks/chunk-CD3R5YBH.js +0 -16
  46. package/dist/chunks/chunk-DKXUY5F2.js +0 -209
  47. package/dist/chunks/chunk-HMYEQJGT.js +0 -31
  48. package/dist/chunks/chunk-KUX5LRPP.js +0 -2
  49. package/dist/chunks/chunk-OWSKU55I.js +0 -13
  50. package/dist/chunks/chunk-ZZ4KRK2B.js +0 -465
  51. package/dist/chunks/compaction-config-FIFFP4FT.js +0 -2
  52. package/dist/chunks/dist-2ZHWDXMQ.js +0 -2
  53. package/dist/chunks/dist-W4CJWLIH.js +0 -2
  54. package/dist/chunks/utils-A5MWDTWZ.js +0 -2
  55. package/dist/types-chunks/instance-discovery.d-BsKnIwpg.d.ts +0 -990
  56. package/dist/types-chunks/transport.d-DuyjG30t.d.ts +0 -180
@@ -1,12 +1,129 @@
1
- export { K as KodaXCompactMemoryProgress, a as KodaXCompactMemorySeed, b as KodaXExtensionSessionRecord, c as KodaXExtensionSessionState, d as KodaXExtensionStore, e as KodaXExtensionStoreEntry, f as KodaXJsonValue, g as KodaXSessionArchiveMarkerEntry, h as KodaXSessionArtifactLedgerEntry, i as KodaXSessionBranchSummaryEntry, j as KodaXSessionCompactionEntry, k as KodaXSessionData, l as KodaXSessionEntry, m as KodaXSessionEntryBase, n as KodaXSessionLabelEntry, o as KodaXSessionLineage, p as KodaXSessionMessageEntry, q as KodaXSessionMeta, r as KodaXSessionNavigationOptions, s as KodaXSessionRuntimeInfo, t as KodaXSessionScope, u as KodaXSessionStorage, v as KodaXSessionTreeNode, w as KodaXSessionUiHistoryItem, x as KodaXSessionUiHistoryItemType, y as KodaXSessionWorkspaceKind, S as SessionErrorMetadata } from './types-chunks/types.d-mM8vqvhT.js';
2
- import { d as AgentManifest, M as ManifestPatch, k as InvariantId, Q as QualityInvariant } from './types-chunks/history-cleanup.d-DznrzEiU.js';
3
- export { A as AdmissionAuditOptions, a as AdmissionCtx, b as AdmissionVerdict, c as AdmittedHandle, C as CompactionContext, e as CompactionEntry, f as CompactionEntryPayload, g as CompactionPolicy, D as DEFAULT_SYSTEM_CAP, h as DefaultSummaryCompaction, i as DefaultSummaryCompactionOptions, j as Deliverable, I as InMemorySessionOptions, l as InvariantResult, m as InvariantSession, K as KODAX_API_MIN_INTERVAL, n as KODAX_DEFAULT_TIMEOUT, o as KODAX_HARD_TIMEOUT, p as KODAX_MAX_INCOMPLETE_RETRIES, q as KODAX_MAX_MAXTOKENS_RETRIES, r as KODAX_MAX_RETRIES, s as KODAX_MAX_TOKENS, t as KODAX_RETRY_BASE_DELAY, u as KODAX_STAGGER_DELAY, v as MessageEntry, O as ObserveCtx, P as PROMISE_PATTERN, w as PolicyCompactionResult, x as PresetDispatcher, y as PresetTracingContext, R as ReadonlyMutationTracker, z as ReadonlyRecorder, B as RunEvent, E as RunOptions, F as RunResult, G as Runner, H as RunnerEvent, S as Session, J as SessionDispatchResult, L as SessionEntry, N as SessionExtension, T as SessionForkOptions, U as StopHookContext, V as StopHookFn, W as StopHookResult, X as SystemCap, Y as TerminalCtx, Z as ToolCapability, _ as ToolPermission, $ as _resetAdmittedAgentBindings, a0 as _resetPresetDispatchers, a1 as buildSystemPrompt, a2 as cleanupIncompleteToolCalls, a3 as countTokens, a4 as createInMemorySession, a5 as createInvariantSessionForAgent, a6 as detectInstructionsInjection, a7 as estimateTokens, a8 as extractAssistantTextFromMessage, a9 as getAdmittedAgentBindings, aa as getAgentConfigHome, ab as getAgentConfigPath, ac as getAppDataDir, ad as registerPresetDispatcher, ae as runAdmissionAudit, af as setAdmittedAgentBindings, ag as setAgentConfigHome, ah as validateAndFixToolHistory } from './types-chunks/history-cleanup.d-DznrzEiU.js';
4
- import { A as Agent, H as Handoff, r as RunnerToolCall, u as RunnerToolResult, w as Span, a as AgentMessage, C as ChildTaskRegistry, D as DiscoveredInstance, S as SessionMeta, v as SessionStateSnapshot, B as StateWriterFs, k as InstanceDiscoveryFs, z as StateWriter } from './types-chunks/instance-discovery.d-BsKnIwpg.js';
5
- export { b as AgentMiddlewareDeclaration, c as AgentReasoningProfile, d as AgentTool, e as CurrentTodoSummary, f as DiscoveryOptions, G as Guardrail, g as GuardrailBlockedError, h as GuardrailContext, i as GuardrailEscalateError, j as GuardrailVerdict, I as InputGuardrail, M as MAX_TOOL_LOOP_ITERATIONS, O as OutputGuardrail, P as PersistedSessionState, R as ReasoningDepth, l as RecentlyModifiedFile, m as RequestTaskStopOptions, n as RequestTaskStopResult, o as RunnableTool, p as RunnerLlmResult, q as RunnerLlmReturn, s as RunnerToolContext, t as RunnerToolObserver, E as StateWriterOptions, T as TaskAbortRegistry, F as ToolBeforeOutcome, J as ToolGuardrail, K as buildAssistantMessageFromLlmResult, L as buildToolResultMessage, N as collectGuardrails, Q as createAgent, U as createHandoff, V as createStateWriter, W as discoverInstances, X as executeRunnerToolCall, Y as isRunnableTool, Z as isRunnerLlmResult, _ as registerChildTask, $ as requestTaskStop, a0 as runInputGuardrails, a1 as runOutputGuardrails, a2 as runToolAfterGuardrails, a3 as runToolBeforeGuardrails } from './types-chunks/instance-discovery.d-BsKnIwpg.js';
1
+ import { s as KodaXSessionLineage, g as KodaXGoalState, f as KodaXGoalEventType, o as KodaXSessionEntry, q as KodaXSessionGoalEntry, k as KodaXSessionArtifactLedgerEntry, d as KodaXExtensionStore, e as KodaXExtensionStoreEntry, i as KodaXJsonValue } from './types-chunks/types.d-HBbWT-iA.js';
2
+ export { K as KodaXCompactMemoryProgress, a as KodaXCompactMemorySeed, b as KodaXExtensionSessionRecord, c as KodaXExtensionSessionState, h as KodaXGoalStatus, j as KodaXSessionArchiveMarkerEntry, l as KodaXSessionBranchSummaryEntry, m as KodaXSessionCompactionEntry, n as KodaXSessionData, p as KodaXSessionEntryBase, r as KodaXSessionLabelEntry, t as KodaXSessionMessageEntry, u as KodaXSessionMeta, v as KodaXSessionNavigationOptions, w as KodaXSessionRuntimeInfo, x as KodaXSessionScope, y as KodaXSessionStorage, z as KodaXSessionTreeNode, A as KodaXSessionUiHistoryItem, B as KodaXSessionUiHistoryItemType, C as KodaXSessionWorkspaceKind, S as SessionErrorMetadata } from './types-chunks/types.d-HBbWT-iA.js';
3
+ export { C as CompactionContext, a as CompactionEntry, b as CompactionEntryPayload, c as CompactionPolicy, D as DefaultSummaryCompaction, d as DefaultSummaryCompactionOptions, K as KODAX_API_MIN_INTERVAL, e as KODAX_DEFAULT_TIMEOUT, f as KODAX_HARD_TIMEOUT, g as KODAX_MAX_INCOMPLETE_RETRIES, h as KODAX_MAX_MAXTOKENS_RETRIES, i as KODAX_MAX_RETRIES, j as KODAX_MAX_TOKENS, k as KODAX_RETRY_BASE_DELAY, l as KODAX_STAGGER_DELAY, L as LINEAGE_ENTRY_TYPES, m as LineageArtifactLedgerPayload, n as LineageCompaction, o as LineageCompactionDelegates, p as LineageEntryType, q as LineageExtension, r as LineageLabelPayload, s as LineageTreeNode, P as PROMISE_PATTERN, t as PolicyCompactionResult, u as appendSessionLineageLabel, v as applyLineageTruncation, w as applySessionCompaction, x as archiveOldIslands, y as buildSessionTree, z as cleanupIncompleteToolCalls, A as countActiveLineageMessages, B as countTokens, E as createSessionLineage, F as estimateTokens, G as extractArtifactLedger, H as extractFileOps, I as extractTitleFromMessages, J as findPreviousUserEntryId, M as forkSessionLineage, N as generateSessionId, O as getAgentConfigHome, Q as getAgentConfigPath, R as getAppDataDir, S as getSessionLineagePath, T as getSessionMessagesFromLineage, U as mergeArtifactLedger, V as mergeFileOps, W as resolveSessionLineageTarget, X as rewindSessionLineage, Y as setAgentConfigHome, Z as setSessionLineageActiveEntry, _ as validateAndFixToolHistory } from './types-chunks/file-tracker.d-DOfaoCbJ.js';
4
+ import { al as Span, aG as Trace, d as Agent, H as Handoff, aa as RunnerToolCall, ad as RunnerToolResult, f as AgentMessage, e as AgentManifest, Q as ManifestPatch, M as InvariantId, X as QualityInvariant, C as ChildTaskRegistry, s as DiscoveredInstance, aj as SessionMeta, ak as SessionStateSnapshot, as as StateWriterFs, L as InstanceDiscoveryFs, ar as StateWriter, m as CompactionDetails, l as CompactionConfig, n as CompactionResult } from './types-chunks/types.d-DM8zEJgF.js';
5
+ export { A as AdmissionAuditOptions, a as AdmissionCtx, b as AdmissionVerdict, c as AdmittedHandle, g as AgentMiddlewareDeclaration, h as AgentReasoningProfile, i as AgentSpanData, j as AgentTool, k as CompactionAnchor, o as CompactionSpanData, p as CompactionUpdate, q as CurrentTodoSummary, D as DEFAULT_SYSTEM_CAP, r as Deliverable, t as DiscoveryOptions, E as EvidenceSpanData, F as FanoutSpanData, u as FileOperations, G as GenerationSpanData, v as Guardrail, w as GuardrailBlockedError, x as GuardrailContext, y as GuardrailEscalateError, z as GuardrailSpanData, B as GuardrailVerdict, I as HandoffSpanData, J as InMemorySessionOptions, K as InputGuardrail, N as InvariantResult, O as InvariantSession, P as MAX_TOOL_LOOP_ITERATIONS, R as MessageEntry, S as ObserveCtx, T as OutputGuardrail, U as PersistedSessionState, V as PresetDispatcher, W as PresetTracingContext, Y as ReadonlyMutationTracker, Z as ReadonlyRecorder, _ as ReasoningDepth, $ as RecentlyModifiedFile, a0 as RequestTaskStopOptions, a1 as RequestTaskStopResult, a2 as RunEvent, a3 as RunOptions, a4 as RunResult, a5 as RunnableTool, a6 as Runner, a7 as RunnerEvent, a8 as RunnerLlmResult, a9 as RunnerLlmReturn, ab as RunnerToolContext, ac as RunnerToolObserver, ae as Session, af as SessionDispatchResult, ag as SessionEntry, ah as SessionExtension, ai as SessionForkOptions, am as SpanData, an as SpanError, ao as SpanImpl, ap as SpanImplOptions, aq as StartTraceOptions, at as StateWriterOptions, au as StopHookContext, av as StopHookFn, aw as StopHookResult, ax as StopHookSpanData, ay as SystemCap, az as TaskAbortRegistry, aA as TerminalCtx, aB as ToolBeforeOutcome, aC as ToolCallSpanData, aD as ToolCapability, aE as ToolGuardrail, aF as ToolPermission, aH as TraceOptions, aI as Tracer, aJ as TracerOptions, aK as _resetAdmittedAgentBindings, aL as _resetPresetDispatchers, aM as buildAssistantMessageFromLlmResult, aN as buildSystemPrompt, aO as buildToolResultMessage, aP as collectGuardrails, aQ as createAgent, aR as createHandoff, aS as createInMemorySession, aT as createInvariantSessionForAgent, aU as createStateWriter, aV as createTrace, aW as defaultTracer, aX as detectInstructionsInjection, aY as discoverInstances, aZ as executeRunnerToolCall, a_ as extractAssistantTextFromMessage, a$ as getAdmittedAgentBindings, b0 as isRunnableTool, b1 as isRunnerLlmResult, b2 as registerChildTask, b3 as registerPresetDispatcher, b4 as requestTaskStop, b5 as runAdmissionAudit, b6 as runInputGuardrails, b7 as runOutputGuardrails, b8 as runToolAfterGuardrails, b9 as runToolBeforeGuardrails, ba as setAdmittedAgentBindings } from './types-chunks/types.d-DM8zEJgF.js';
6
6
  import { m as KodaXMessage } from './types-chunks/types.d-B1uGoVTE.js';
7
7
  export { e as KodaXAssuranceIntent, g as KodaXContentBlock, i as KodaXExecutionMode, j as KodaXExecutionPattern, l as KodaXImageBlock, o as KodaXMutationSurface, r as KodaXProviderConfig, z as KodaXProviderStreamOptions, C as KodaXReasoningCapability, D as KodaXReasoningMode, F as KodaXReasoningRequest, G as KodaXRedactedThinkingBlock, I as KodaXRiskLevel, J as KodaXStreamResult, L as KodaXTaskActionability, M as KodaXTaskBudgetOverrides, N as KodaXTaskComplexity, O as KodaXTaskFamily, P as KodaXTaskRoutingDecision, Q as KodaXTaskType, R as KodaXTaskWorkIntent, S as KodaXTextBlock, T as KodaXThinkingBlock, U as KodaXThinkingBudgetMap, V as KodaXThinkingDepth, W as KodaXTokenUsage, X as KodaXToolDefinition, Y as KodaXToolResultBlock, a0 as KodaXToolUseBlock } from './types-chunks/types.d-B1uGoVTE.js';
8
8
  export { C as CapabilityKind, a as CapabilityProvider, b as CapabilityResult } from './types-chunks/capability.d-3C62G8Eq.js';
9
9
  import { Q as QueueEventListener, b as QueuedMessage, E as EnqueueInput, D as DequeueFilter, a as MessagePriority, M as MessageMode } from './types-chunks/types.d-C5mHR87z.js';
10
+ export { M as McpConnectMode, a as McpServerConfig, b as McpServersConfig, c as McpTransportKind } from './types-chunks/config.d-BfJUXxC0.js';
11
+ export { M as McpCapabilityDescriptor, a as McpCapabilityKind, b as McpCapabilityProvider, c as McpCapabilityRisk, d as McpCatalogItem, e as McpManager, f as McpProviderOptions, g as McpServerCatalog, h as McpServerCatalogSnapshot, i as McpServerLogs, j as McpServerRuntime, k as McpServerRuntimeDiagnostics, l as McpServerStatus, m as McpServerToolList, n as McpTransport, o as McpTransportEvents, p as createMcpCapabilityId, q as createMcpManager, r as createMcpTransport, s as defaultMcpCacheDir, t as getMcpCachePaths, u as parseMcpCapabilityId, v as searchMcpCatalog } from './types-chunks/manager.d-87belpiS.js';
12
+ export { createMcpTestServerFixture } from './sdk-mcp.js';
13
+ export { DiscoveryResult, ExecutionMode, ExecutionOptions, ISkillRegistry, IVariableResolver, Skill, SkillArtifact, SkillContext, SkillDynamicContextExecutor, SkillExecutor, SkillExpansionResult, SkillFile, SkillFrontmatter, SkillHook, SkillHooks, SkillMetadata, SkillPathsConfig, SkillRegistry, SkillResult, SkillSource, VariableResolver, clearPluginSkillPaths, createExecutor, createResolver, discoverSkills, discoverSkillsWithMonorepo, executeSkill, expandSkillForLLM, formatSkillActivationMessage, getDefaultSkillPaths, getNestedSkillPaths, getSkillPathsFlat, getSkillRegistry, initializeSkillRegistry, listPluginSkillPaths, loadFullSkill, loadSkillFileContent, loadSkillMetadata, parseArguments, parseSkillMarkdown, registerPluginSkillPath, resetSkillRegistry, resolveSkillContent, unregisterPluginSkillPath } from './sdk-skills.js';
14
+ import { K as KodaXBaseProvider } from './types-chunks/base.d-FUJahC0i.js';
15
+
16
+ /**
17
+ * TracingProcessor — sink for span/trace lifecycle events.
18
+ *
19
+ * FEATURE_083 (v0.7.24): minimal processor contract modeled after
20
+ * openai-agents-python. External adapters (OpenTelemetry, Langfuse, custom
21
+ * telemetry) implement this interface and register via
22
+ * `addTracingProcessor` / `setTracingProcessors`.
23
+ *
24
+ * Lifecycle:
25
+ * - `onSpanStart(span)` fires when a span is created and attached to its
26
+ * parent. Called synchronously; implementations should defer I/O.
27
+ * - `onSpanEnd(span)` fires on `span.end()`. The span's `endedAt`,
28
+ * `error`, and final children list are authoritative at this point.
29
+ * - `onTraceEnd(trace)` fires on `trace.end()` after the root span ends.
30
+ * - `shutdown()` is optional; called when the host wants processors to
31
+ * flush pending work (e.g. batch buffers).
32
+ */
33
+
34
+ interface TracingProcessor {
35
+ onSpanStart(span: Span): void;
36
+ onSpanEnd(span: Span): void;
37
+ onTraceEnd(trace: Trace): void;
38
+ shutdown?(): Promise<void>;
39
+ }
40
+ /**
41
+ * Register a tracing processor. Returns an unregister function.
42
+ *
43
+ * Consumers typically call this at app startup:
44
+ *
45
+ * addTracingProcessor(new ConsoleTracingProcessor());
46
+ */
47
+ declare function addTracingProcessor(p: TracingProcessor): () => void;
48
+ /**
49
+ * Replace the current processor list. Useful in tests where you want a
50
+ * deterministic set of sinks.
51
+ */
52
+ declare function setTracingProcessors(ps: TracingProcessor[]): void;
53
+ /** @internal */
54
+ declare function _getRegisteredProcessors(): readonly TracingProcessor[];
55
+ /** @internal */
56
+ declare function _emitSpanStart(span: Span): void;
57
+ /** @internal */
58
+ declare function _emitSpanEnd(span: Span): void;
59
+ /** @internal */
60
+ declare function _emitTraceEnd(trace: Trace): void;
61
+ /**
62
+ * Flush-and-shutdown all registered processors. Callers can await this on
63
+ * process shutdown.
64
+ */
65
+ declare function shutdownTracing(): Promise<void>;
66
+
67
+ /**
68
+ * ConsoleTracingProcessor — writes span lifecycle lines to stdout.
69
+ *
70
+ * FEATURE_083 (v0.7.24): handy for local development. Not intended for
71
+ * production traffic.
72
+ *
73
+ * Output format (one line per event):
74
+ *
75
+ * [span:start] traceId=... spanId=... name=... kind=...
76
+ * [span:end] traceId=... spanId=... name=... kind=... durationMs=...
77
+ * [trace:end] traceId=... rootName=... durationMs=...
78
+ */
79
+
80
+ type WriteFn = (line: string) => void;
81
+ interface ConsoleTracingProcessorOptions {
82
+ /**
83
+ * Writer override. Defaults to `process.stdout.write`. Useful in tests so
84
+ * output goes to a capture buffer instead of the real stdout.
85
+ */
86
+ readonly write?: WriteFn;
87
+ }
88
+ declare class ConsoleTracingProcessor implements TracingProcessor {
89
+ private readonly write;
90
+ constructor(opts?: ConsoleTracingProcessorOptions);
91
+ onSpanStart(span: Span): void;
92
+ onSpanEnd(span: Span): void;
93
+ onTraceEnd(trace: Trace): void;
94
+ }
95
+
96
+ /**
97
+ * FileTracingProcessor — writes JSONL records to `.kodax/.traces/{traceId}.jsonl`.
98
+ *
99
+ * FEATURE_083 (v0.7.24): simple append-only log for offline analysis. Each
100
+ * span start / end / trace end becomes a separate JSON line.
101
+ *
102
+ * The processor buffers per-trace writes to the file system; call
103
+ * `shutdown()` on process exit to flush pending writes.
104
+ */
105
+
106
+ interface FileTracingProcessorOptions {
107
+ /**
108
+ * Directory for trace files. Defaults to `./.kodax/.traces`. Must be an
109
+ * absolute path or resolvable relative to `process.cwd()`.
110
+ */
111
+ readonly traceDir?: string;
112
+ }
113
+ declare class FileTracingProcessor implements TracingProcessor {
114
+ private readonly traceDir;
115
+ private readonly queues;
116
+ private writeChain;
117
+ private ensuredDir;
118
+ constructor(opts?: FileTracingProcessorOptions);
119
+ onSpanStart(span: Span): void;
120
+ onSpanEnd(span: Span): void;
121
+ onTraceEnd(trace: Trace): void;
122
+ shutdown(): Promise<void>;
123
+ private scheduleFlush;
124
+ private enqueue;
125
+ private flushTrace;
126
+ }
10
127
 
11
128
  /**
12
129
  * Runner Handoff Helpers — FEATURE_084 Shard 4 (v0.7.26).
@@ -605,9 +722,22 @@ interface IdleYieldSnapshot {
605
722
  /**
606
723
  * True if the run's managed-protocol payload has been populated
607
724
  * with a handoff (typically `emit_handoff` for the worker→evaluator
608
- * boundary). False = the run ended without a handoff. Idle-yield
609
- * REQUIRES this to be false; otherwise the handoff target already
610
- * owns the next step.
725
+ * boundary in legacy V1 / V2 chains). False = the run ended without
726
+ * a handoff. Idle-yield REQUIRES this to be false; otherwise the
727
+ * handoff target already owns the next step.
728
+ *
729
+ * **FEATURE_184 (v0.7.45) + FEATURE_190 (v0.7.43)**: the Evaluator
730
+ * role was retired and Worker/Generator are now terminal. Under the
731
+ * Sidecar Verifier architecture, the CANONICAL post-F184 terminal
732
+ * signal is text-only termination — Worker produces a final text
733
+ * message with no `tool_use` block, Runner.run exits via the no-
734
+ * tool-calls branch, and this snapshot reads `hasEmittedHandoff:
735
+ * false` + `lastAssistantToolCallCount: 0`. `detectIdleYield`
736
+ * correctly returns false in that state (no pending child, no
737
+ * pending banner) → the outer loop breaks. So text-only termination
738
+ * is a first-class exit path; `hasEmittedHandoff` retained only for
739
+ * the pre-FEATURE_190 Phase 3 legacy `emit_handoff` tool that
740
+ * remains in scope through the cleanup window.
611
741
  */
612
742
  readonly hasEmittedHandoff: boolean;
613
743
  /**
@@ -660,44 +790,6 @@ interface IdleYieldSnapshot {
660
790
  * resume gate (fast-child race recovery; see field docs).
661
791
  */
662
792
  declare function detectIdleYield(snapshot: IdleYieldSnapshot): boolean;
663
- /**
664
- * FEATURE_167 (v0.7.41) — terminal-verdict-missing predicate.
665
- *
666
- * Companion to `detectIdleYield`, gating the OPPOSITE half of the
667
- * outer-loop exit decision: when the inner Runner.run loop exits
668
- * with no tool calls AFTER a handoff has fired but BEFORE the
669
- * Evaluator has emitted a terminal verdict, the run is structurally
670
- * INCOMPLETE — the audit step is missing. `detectIdleYield` correctly
671
- * returns false in this state (the gate at line 174 short-circuits on
672
- * `hasEmittedHandoff`), so the outer loop currently terminates with
673
- * `recorder.verdict === undefined`. Downstream `deriveFinalStatus`
674
- * then falls back to `signal:'COMPLETE'`, falsely reporting success
675
- * for a failed audit (production session 20260515_185354).
676
- *
677
- * This predicate identifies that exact missing-verdict state so the
678
- * outer loop can branch into a retry path (inject a "call emit_verdict"
679
- * prompt and re-invoke the Evaluator) before falling through to a
680
- * synthesized fallback verdict.
681
- *
682
- * **Disjoint from `detectIdleYield`** by construction:
683
- *
684
- * - `detectIdleYield` requires `!hasEmittedHandoff`
685
- * - `detectMissingTerminalVerdict` requires `hasEmittedHandoff`
686
- *
687
- * Both also require `lastAssistantToolCallCount === 0`. Both gate on
688
- * `!hasEmittedTerminalVerdict`. The two predicates partition the
689
- * "Evaluator turn just exited text-only" space cleanly — no run can
690
- * satisfy both.
691
- *
692
- * **Pending children take precedence over verdict retry.** Predicate
693
- * is intentionally `pendingChildTaskCount <= 0 && !hasPendingBackgroundMessages`
694
- * so that if Evaluator dispatched audit children and is correctly
695
- * idle-yielding for them (FEATURE_155 Bug C discipline), the
696
- * verdict-missing retry does NOT fire — `detectIdleYield` handles
697
- * that path instead. Only when there's nothing left to wait on does
698
- * the verdict-missing branch take over.
699
- */
700
- declare function detectMissingTerminalVerdict(snapshot: IdleYieldSnapshot): boolean;
701
793
  /**
702
794
  * Discriminated union surfacing the reason a wake completed.
703
795
  *
@@ -1376,5 +1468,770 @@ declare function getActiveTeamModeWriter(): StateWriter | null;
1376
1468
  */
1377
1469
  declare function updateActiveTeamMode(patch: Partial<SessionStateSnapshot>): void;
1378
1470
 
1379
- export { Agent, AgentManifest, AgentMessage, CORE_INVARIANTS, ChildTaskRegistry, DEFAULT_IDLE_YIELD_MAX_ITERATIONS, DequeueFilter, DiscoveredInstance, EnqueueInput, Handoff, InstanceDiscoveryFs, InvariantId, KodaXMessage, ManifestPatch, MessageMode, MessagePriority, MessageQueue, QualityInvariant, QueuedMessage, RunnerToolCall, RunnerToolResult, SessionMeta, SessionStateSnapshot, StateWriter, StateWriterFs, YIELD_TOOL_NAMES, _resetAdmissionMetrics, _resetInvariantRegistry, _resetMessageQueueForTests, applyManifestPatch, bootstrapTeamMode, buildOtherInstancesPromptBlock, composeIdleYieldUserMessage, composePatches, countLastAssistantToolCalls, detectHandoffSignal, detectIdleYield, detectMissingTerminalVerdict, emitHandoffSpan, enqueueChildTaskNotification, evidenceTrail, finalOwner, getActiveTeamModeWriter, getAdmissionMetricsSnapshot, getInvariant, getMessageQueue, handoffLegality, isAdmissionDebugEnabled, isIdleYieldEnabled, listRegisteredInvariants, maybeDrainMidTurn, midTurnDrainPriority, registerCoreInvariants, registerInvariant, replaceSystemMessage, resolveEffectiveInvariants, resolveRequiredInvariants, routeMessage, runFanOut, runWithIdleYield, setActiveTeamModeWriter, updateActiveTeamMode, waitForWakeEvent };
1380
- export type { AdmissionMetricsSnapshot, EnqueueChildTaskNotificationInput, EnvelopeAggregateEnforcer, FanOutOutcome, FanOutProgressEvent, HandoffSignal, IdleYieldSnapshot, MaybeDrainMidTurnInput, RenderOptions, RouteMessageOptions, RouteMessageResult, RunFanOutOptions, RunFanOutResult, RunWithIdleYieldOptions, RunWithIdleYieldRunResult, TeamModeBootstrapOptions, TeamModeHandle, WaitForWakeEventOptions, WakeEvent };
1471
+ /**
1472
+ * FEATURE_124 (v0.7.43) Memory System Alignment: path resolver.
1473
+ *
1474
+ * Per-project isolated memory directory under
1475
+ * `<agentConfigHome>/projects/<sanitized-project-key>/memory/`. Mirrors
1476
+ * claudecode `src/memdir/paths.ts` per-project layout so the same repo
1477
+ * gets the same memory directory across worktrees / machines.
1478
+ *
1479
+ * Resolution order:
1480
+ * 1. `git config --get remote.origin.url` (when present) — stable across
1481
+ * worktrees + clones, matches claudecode's `findCanonicalGitRoot`
1482
+ * semantic without re-implementing git plumbing.
1483
+ * 2. `local-<sha256(cwd)>` fallback — for repos without a remote, or
1484
+ * when git is unavailable. Stable within a single clone path.
1485
+ *
1486
+ * Reuses `getAgentConfigPath('projects', key, 'memory')` from
1487
+ * `runtime/agent-home.ts` (v0.7.35.1 FEATURE_145) so substrate consumers
1488
+ * who override `setAgentConfigHome()` automatically get a fresh memory
1489
+ * directory tree under their override root.
1490
+ */
1491
+ /**
1492
+ * Sanitize a git remote URL to a filesystem-safe project key.
1493
+ *
1494
+ * Strips protocol / SSH user prefix, lowercases host, replaces `:`, `@`,
1495
+ * `/` with `-`, drops trailing `.git`. The result is deterministic and
1496
+ * collision-free for distinct repos (different host or path → different
1497
+ * key) and stable across clones of the same repo (same remote → same key).
1498
+ *
1499
+ * Examples:
1500
+ * `https://github.com/user/repo.git` → `github.com-user-repo`
1501
+ * `git@github.com:user/repo.git` → `github.com-user-repo`
1502
+ * `ssh://git@gitlab.example.com/team/repo` → `gitlab.example.com-team-repo`
1503
+ *
1504
+ * Note: hosts `github.com` over HTTPS and `git@github.com:` over SSH
1505
+ * intentionally produce the same key — they identify the same repo,
1506
+ * just different access protocols.
1507
+ */
1508
+ declare function sanitizeProjectKey(remoteUrl: string): string;
1509
+ /**
1510
+ * SHA-256 hash of an absolute cwd, truncated to 16 hex chars. Used as
1511
+ * the project key fallback when `git config --get remote.origin.url`
1512
+ * returns nothing.
1513
+ *
1514
+ * Path is normalized + lowercased before hashing so case-insensitive
1515
+ * filesystems (macOS default, Windows) produce the same key for
1516
+ * `/Users/X/repo` and `/users/x/repo`.
1517
+ */
1518
+ declare function hashCwd(cwd: string): string;
1519
+ /**
1520
+ * Read `git config --get remote.origin.url` from the given cwd. Returns
1521
+ * `undefined` on any failure (no git installed / not a repo / no remote
1522
+ * configured / git timed out). NEVER throws.
1523
+ *
1524
+ * 1000ms timeout — guards against pathological git hangs on broken
1525
+ * .git/config without blocking session startup.
1526
+ */
1527
+ declare function tryGitRemote(cwd: string): string | undefined;
1528
+ /**
1529
+ * Resolve the memory directory for the given cwd.
1530
+ *
1531
+ * `<agentConfigHome>/projects/<key>/memory/` where key is:
1532
+ * - sanitized git remote URL when available
1533
+ * - `local-<sha256(cwd)[:16]>` fallback otherwise
1534
+ */
1535
+ declare function resolveMemoryRoot(cwd: string): string;
1536
+ /**
1537
+ * Path of the MEMORY.md index file inside a resolved memory root.
1538
+ */
1539
+ declare function resolveMemoryEntrypoint(cwd: string): string;
1540
+ /**
1541
+ * Check whether a given absolute path is inside ANY memory directory
1542
+ * (under `<agentConfigHome>/projects/*​/memory/`). Used by the REPL
1543
+ * transcript renderer to badge memory writes / reads, and by future
1544
+ * tool-permission carve-outs.
1545
+ *
1546
+ * Returns true only for `.md` files inside a `memory/` directory whose
1547
+ * parent is the agent config home's `projects/<key>/` tree. Path
1548
+ * traversal (`..`) is normalized before the check.
1549
+ *
1550
+ * The check is path-prefix only — it does NOT verify the file exists
1551
+ * on disk. A planned write to `<memoryRoot>/feedback_X.md` returns true
1552
+ * even before the file is created.
1553
+ */
1554
+ declare function isAutoManagedMemoryFile(filePath: string): boolean;
1555
+ /**
1556
+ * Best-effort filename-based type guess for badge rendering. Mirrors the
1557
+ * 4-type taxonomy: `feedback_*.md` → `feedback`, etc. Returns `undefined`
1558
+ * for filenames that don't follow the convention — UI should fall back
1559
+ * to reading frontmatter or showing a generic `[memory]` badge.
1560
+ *
1561
+ * This is a HEURISTIC for cheap UI display. Authoritative type lives in
1562
+ * the file's YAML frontmatter (see `frontmatter.ts`).
1563
+ */
1564
+ declare function parseMemoryTypeFromFilename(filePath: string): 'user' | 'feedback' | 'project' | 'reference' | undefined;
1565
+
1566
+ /**
1567
+ * FEATURE_124 (v0.7.43) — Memory frontmatter parser.
1568
+ *
1569
+ * Minimal YAML frontmatter subset for memory files:
1570
+ *
1571
+ * ---
1572
+ * name: User role
1573
+ * description: Senior backend engineer, Go/PostgreSQL focus
1574
+ * type: user
1575
+ * ---
1576
+ *
1577
+ * <body markdown>
1578
+ *
1579
+ * Why a hand-rolled parser instead of `yaml` dep:
1580
+ * - `@kodax-ai/agent` is the substrate package; adding a runtime YAML
1581
+ * dependency would propagate to every consumer (kodax CLI, downstream
1582
+ * `@kodax-ai/data-analysis-agent`, etc.). Frontmatter has only 3
1583
+ * scalar string fields — a 40-line regex parser is the appropriate
1584
+ * scope.
1585
+ * - Degraded-tolerant: corrupt YAML / unknown type / missing
1586
+ * frontmatter MUST NOT throw — the file remains readable as
1587
+ * `{ raw: <full content>, type: undefined }`. Memory directories
1588
+ * accumulate files over months; one bad file cannot break session
1589
+ * startup.
1590
+ *
1591
+ * Contract guarantees (verified by frontmatter.test.ts):
1592
+ * - Parser NEVER throws.
1593
+ * - Unknown / mistyped `type:` → `type: undefined` (still readable).
1594
+ * - Missing frontmatter → `{ name: undefined, description: undefined,
1595
+ * type: undefined, body: <full content> }`.
1596
+ * - Body extraction strips the frontmatter block + leading newlines.
1597
+ */
1598
+ type MemoryType = 'user' | 'feedback' | 'project' | 'reference';
1599
+ interface MemoryFrontmatter {
1600
+ /** Human-readable short title. May be undefined when frontmatter is malformed or missing. */
1601
+ readonly name: string | undefined;
1602
+ /** One-line search hint. May be undefined when frontmatter is malformed or missing. */
1603
+ readonly description: string | undefined;
1604
+ /** 4-type taxonomy; undefined for unknown / missing types (degraded tolerant). */
1605
+ readonly type: MemoryType | undefined;
1606
+ }
1607
+ interface ParsedMemoryFile {
1608
+ readonly frontmatter: MemoryFrontmatter;
1609
+ /** Body content WITHOUT the frontmatter block. May be empty. */
1610
+ readonly body: string;
1611
+ }
1612
+ /**
1613
+ * Coerce a raw frontmatter value to the closed 4-type taxonomy.
1614
+ * Returns `undefined` for unknown types — degraded tolerance lets the
1615
+ * file remain in the directory without breaking the index or session
1616
+ * startup.
1617
+ */
1618
+ declare function parseMemoryType(raw: unknown): MemoryType | undefined;
1619
+ /**
1620
+ * Parse a memory file's raw text into frontmatter + body. NEVER throws.
1621
+ *
1622
+ * Behavior:
1623
+ * - No frontmatter block → all fields undefined, body = full input.
1624
+ * - Frontmatter present + parseable → fields populated where possible,
1625
+ * unknown / mistyped fields → undefined. Body = content after the
1626
+ * closing `---` line.
1627
+ * - Frontmatter block syntactically present but no parseable
1628
+ * `key: value` lines → all fields undefined, body = content after
1629
+ * closing `---`. (Garbage frontmatter is not an error.)
1630
+ */
1631
+ declare function parseMemoryFile(raw: string): ParsedMemoryFile;
1632
+ /**
1633
+ * Parse `key: value` scalar lines from a YAML block. Supports:
1634
+ * - bare strings: `name: Hello world`
1635
+ * - single-quoted strings: `name: 'Hello: world'`
1636
+ * - double-quoted strings: `name: "Hello: world"`
1637
+ *
1638
+ * Does NOT support: nested objects, sequences (lists), multiline scalars,
1639
+ * YAML anchors / aliases / tags. Lines that don't match the simple
1640
+ * scalar shape are silently skipped (degraded tolerance).
1641
+ *
1642
+ * Visibility: exported only for testing; consumers use `parseMemoryFile`.
1643
+ */
1644
+ declare function parseScalarFields(yamlBlock: string): Record<string, string>;
1645
+
1646
+ /**
1647
+ * FEATURE_124 (v0.7.43) — MEMORY.md entrypoint truncation.
1648
+ *
1649
+ * Mirrors claudecode `src/memdir/memdir.ts` `truncateEntrypointContent`
1650
+ * (caps + warning text) byte-for-byte semantically — verified by
1651
+ * truncate.test.ts text-mirror assertion against the claudecode-shape
1652
+ * warning string. Mirroring the caps + warning is intentional: it pins
1653
+ * the same context-budget invariant (≤25KB SP overhead from MEMORY.md)
1654
+ * across both agents and inherits claudecode's empirical line/byte
1655
+ * tuning without re-deriving thresholds.
1656
+ *
1657
+ * Two-stage truncation:
1658
+ * 1. If `lineCount > MAX_ENTRYPOINT_LINES`, slice the array to that
1659
+ * many lines and re-join.
1660
+ * 2. If the resulting (or original, when no line truncation) string is
1661
+ * still > MAX_ENTRYPOINT_BYTES, find the last newline at or before
1662
+ * the byte cap and slice there. Falls back to a hard byte slice if
1663
+ * no newline is found within the cap (one giant line worse-case).
1664
+ *
1665
+ * Warning is appended only when at least one cap fired. Warning text
1666
+ * mirrors claudecode line 87-97; the test asserts the literal string.
1667
+ */
1668
+ declare const MAX_ENTRYPOINT_LINES = 200;
1669
+ declare const MAX_ENTRYPOINT_BYTES = 25000;
1670
+ interface EntrypointTruncation {
1671
+ /** Truncated content with claudecode-shape WARNING line appended (if any cap fired). */
1672
+ readonly content: string;
1673
+ /** Original line count BEFORE truncation. */
1674
+ readonly lineCount: number;
1675
+ /** Original byte count BEFORE truncation. */
1676
+ readonly byteCount: number;
1677
+ readonly wasLineTruncated: boolean;
1678
+ readonly wasByteTruncated: boolean;
1679
+ }
1680
+ /**
1681
+ * Truncate MEMORY.md content to the line AND byte caps, appending a
1682
+ * claudecode-shape WARNING when truncated. Pass-through when within caps.
1683
+ *
1684
+ * Input MAY be trimmed of leading/trailing whitespace before measurement
1685
+ * (matches claudecode). Returns a `content` string ready for direct SP
1686
+ * injection.
1687
+ */
1688
+ declare function truncateEntrypointContent(raw: string): EntrypointTruncation;
1689
+
1690
+ /**
1691
+ * FEATURE_192 v0.7.44 — goal-entry helpers for session lineage.
1692
+ *
1693
+ * Goals live in `lineage.entries` as `KodaXSessionGoalEntry` records
1694
+ * (non-navigable, like labels). Each lifecycle event appends a new
1695
+ * goal entry whose `parentId` references the message entry the goal
1696
+ * was attached AT — so a fork/rewind that abandons that message
1697
+ * also abandons the goal entry attached to it.
1698
+ *
1699
+ * **Active-branch resolution**: a goal entry counts as "on the active
1700
+ * branch" iff its `parentId` is the id of some entry on the active
1701
+ * lineage path. Latest-on-branch wins (largest timestamp).
1702
+ *
1703
+ * This module is intentionally tiny — it does NOT define goal
1704
+ * lifecycle policy (creation rules, completion gates, accounting).
1705
+ * Those live in `packages/coding/src/goal/` where the runtime
1706
+ * middleware composes them. The agent-layer concern is just "given a
1707
+ * lineage, what is the current goal?".
1708
+ */
1709
+
1710
+ /**
1711
+ * Walk the active branch (root → activeEntryId), collect every goal
1712
+ * entry whose parentId appears on that path, and return the latest
1713
+ * one (largest timestamp string). Returns `null` when no goal entry
1714
+ * is attached to the active branch.
1715
+ *
1716
+ * "Cleared" goals are still returned — callers check `entry.event`
1717
+ * / `entry.goal === null` to detect the cleared state. This lets the
1718
+ * UI distinguish "never set a goal" (returns null) from "user
1719
+ * explicitly cleared the goal" (returns a cleared entry).
1720
+ */
1721
+ declare function readLatestGoalFromBranch(lineage: KodaXSessionLineage): KodaXSessionGoalEntry | null;
1722
+ /**
1723
+ * Convenience accessor: return just the goal STATE (or null) without
1724
+ * the wrapping entry. Callers that don't care which event produced
1725
+ * the state use this.
1726
+ */
1727
+ declare function readLatestGoalState(lineage: KodaXSessionLineage): KodaXGoalState | null;
1728
+ /**
1729
+ * Append a new goal entry to `lineage.entries`, attaching it to the
1730
+ * current activeEntryId. Returns a fresh `KodaXSessionLineage` —
1731
+ * caller is responsible for persisting the updated lineage.
1732
+ *
1733
+ * `goal` may be `null` only when `event === 'cleared'`; the validator
1734
+ * enforces this invariant so callers can't accidentally append a
1735
+ * non-cleared entry without a state snapshot.
1736
+ */
1737
+ declare function appendGoalEntry(lineage: KodaXSessionLineage, goal: KodaXGoalState | null, event: KodaXGoalEventType, options?: {
1738
+ timestamp?: string;
1739
+ id?: string;
1740
+ }): KodaXSessionLineage;
1741
+ /**
1742
+ * Visible for tests / debugging: predicate matching goal entries.
1743
+ */
1744
+ declare function isGoalEntry(entry: KodaXSessionEntry): entry is KodaXSessionGoalEntry;
1745
+
1746
+ /**
1747
+ * ../../index.js Compaction Utils
1748
+ *
1749
+ * 消息序列化工具 - 将消息转换为结构化文本格式
1750
+ */
1751
+
1752
+ /**
1753
+ * 序列化对话为文本
1754
+ *
1755
+ * 将消息转换为结构化文本格式,保留完整内容不截断
1756
+ * 参考 pi-mono 的实现:让 LLM 决定重点,不通过截断丢失信息
1757
+ *
1758
+ * 输出格式:
1759
+ * ```
1760
+ * [User]: 用户说的内容
1761
+ * [Assistant thinking]: 内部推理
1762
+ * [Assistant]: 响应文本
1763
+ * [Assistant tool calls]: read(path="foo.ts"); edit(path="bar.ts", ...)
1764
+ * [Tool result]: 工具输出
1765
+ * ```
1766
+ *
1767
+ * @param messages - 消息列表
1768
+ * @returns 序列化后的文本
1769
+ */
1770
+ declare function serializeConversation(messages: KodaXMessage[]): string;
1771
+
1772
+ /**
1773
+ * ../../index.js Compaction Summary Generator
1774
+ *
1775
+ * Generates continuation-oriented summaries for compacted conversations.
1776
+ */
1777
+
1778
+ /**
1779
+ * Default neutral compaction summary prompts (v0.7.35.1 FEATURE_142 B-R1).
1780
+ *
1781
+ * These are the *generic* defaults shipped with @kodax-ai/session-lineage.
1782
+ * They are the "candidate-a-conservative" winner from the prompt eval
1783
+ * (`tests/compaction-prompt.eval.ts`, 150 cells over 5 aliases × 10
1784
+ * fixtures × 3 candidates) — schema-stable and high-recall on both
1785
+ * coding and non-coding fixtures, with domain-neutral wording.
1786
+ *
1787
+ * The prior coding-flavored prompts (referencing "coding agent",
1788
+ * "file paths, function names", "HTTP status codes", "## Files & Changes")
1789
+ * have moved to `@kodax-ai/coding` as `CODING_SUMMARY_PROMPT` /
1790
+ * `CODING_UPDATE_SUMMARY_PROMPT`. Coding callers pass them via the
1791
+ * `summaryPrompt` / `updateSummaryPrompt` parameters of
1792
+ * `buildCompactionPromptSnapshot()` and `generateSummary()` / `compact()`
1793
+ * to preserve the v0.7.35 behavior byte-equivalent on the coding path.
1794
+ *
1795
+ * Why this split (per ADR-021): @kodax-ai/session-lineage is the generic
1796
+ * compaction primitive package. Its public surface must not assume the
1797
+ * caller is a coding agent — domain-specific prompt language belongs
1798
+ * one layer up.
1799
+ */
1800
+ declare const DEFAULT_SUMMARY_PROMPT = "Create a structured summary for the conversation below.\n\nThis summary will be handed to another agent so it can continue the same task with minimal context.\nKeep only information that is still useful for continuing the work.\n\nYou may drop:\n- completed low-value micro-steps\n- repetitive thinking\n- stale intermediate plans\n- verbose tool output details\n\nYou must keep:\n- the current goal\n- user constraints and preferences\n- current progress and unfinished work\n- blockers or unresolved questions\n- the most important next steps\n- EXACT identifiers, references, and concrete locations the agent operated on or referenced\n- EXACT error messages, status codes, and exception types\n- EXACT configuration values, parameter values, and external resource names mentioned\n- key decisions WITH reasoning (not just the choice)\n\nCRITICAL: Every user REQUEST and DECISION must be preserved verbatim or near-verbatim.\nNever reduce \"user asked to upgrade dependency X to v3.4 to resolve incompatibility with system Y\"\nto \"user asked to fix an issue\".\n\nKeep the summary concise and high-signal. Do not mechanically preserve every historical detail.\n\nFirst, wrap your analysis in <analysis> tags:\n- Walk through messages chronologically\n- Note exact identifiers, references, error codes, configuration values\n- Identify user's explicit requests vs inferred intent\n- Flag technical details that MUST survive compression\n\nThen output the structured summary in <summary> tags.\n\nOutput format (strict markdown, inside <summary> tags):\n\n## Goal\n[1-2 sentences describing the active goal]\n\n## Constraints & Preferences\n- [One item per line]\n- [Write \"None\" if there are no explicit constraints]\n\n## Progress\n### Completed\n- [x] [Completed work that still matters for context]\n\n### In Progress\n- [ ] [Current work that is actively underway]\n\n### Blockers\n- [Current blockers, or \"None\"]\n\n## Key Decisions\n- **[Decision]**: [Short reason]\n\n## Next Steps\n1. [Highest-priority next action]\n\n## Key Context\n- [Critical context needed to continue]\n\n---\n\n<read-files>\n[One reference per line \u2014 file paths, URLs, IDs, or other locations the agent read; leave empty if none]\n</read-files>\n\n<modified-files>\n[One reference per line \u2014 locations the agent modified; leave empty if none]\n</modified-files>\n\nConversation:\n";
1801
+ declare const DEFAULT_UPDATE_SUMMARY_PROMPT = "Merge the new conversation content above into <previous-summary>.\n\nUpdate the structured summary so another agent can continue the task immediately.\nKeep only the information needed to continue the work.\n\nYou may remove:\n- repetitive or superseded plans\n- completed low-value steps\n- outdated blockers\n- noisy tool output details\n\nYou must preserve or update:\n- the current goal\n- user constraints and preferences\n- current progress and unfinished work\n- blockers that still matter\n- next steps based on the latest state\n- EXACT identifiers, references, and concrete locations\n- EXACT error messages, status codes, and exception types\n- EXACT configuration values, parameter values, and external resource names\n- key decisions WITH reasoning\n\nCRITICAL: Every user REQUEST and DECISION must be preserved verbatim or near-verbatim.\n\nDo not accumulate every past detail. Compress aggressively while keeping continuation-critical context.\n\nFirst, wrap your analysis in <analysis> tags, then output the summary in <summary> tags.\n\nOutput format (strict markdown, inside <summary> tags):\n\n## Goal\n[Updated goal]\n\n## Constraints & Preferences\n- [Relevant constraints only]\n\n## Progress\n### Completed\n- [x] [Completed work that still matters]\n\n### In Progress\n- [ ] [Active work in the latest state]\n\n### Blockers\n- [Current blockers, or \"None\"]\n\n## Key Decisions\n- **[Decision]**: [Short reason]\n\n## Next Steps\n1. [Most relevant next action]\n\n## Key Context\n- [Critical context needed to continue]\n\n---\n\n<read-files>\n[One reference per line \u2014 file paths, URLs, IDs, or other locations the agent read; leave empty if none]\n</read-files>\n\n<modified-files>\n[One reference per line \u2014 locations the agent modified; leave empty if none]\n</modified-files>\n\nKeep every section concise.";
1802
+ type KodaXCompactionPromptVariant = 'initial-summary' | 'update-summary';
1803
+ interface KodaXCompactionPromptSection {
1804
+ id: string;
1805
+ title: string;
1806
+ owner: 'compaction';
1807
+ /**
1808
+ * Provenance label — opaque string identifying which feature ticket
1809
+ * authored this section, used by debug tooling and prompt-eval
1810
+ * provenance traces. v0.7.35.1 FEATURE_142: widened from coding-side
1811
+ * `'FEATURE_044' | 'FEATURE_050'` literal union per ADR-021 — the
1812
+ * session-lineage package is generic and must not enumerate coding
1813
+ * feature IDs in its public type surface.
1814
+ */
1815
+ feature: string;
1816
+ slot: 'conversation' | 'history' | 'instructions' | 'tracking';
1817
+ order: number;
1818
+ stability: 'stable' | 'dynamic' | 'specialist';
1819
+ inclusionReason: string;
1820
+ content: string;
1821
+ }
1822
+ interface KodaXCompactionPromptSnapshot {
1823
+ kind: 'specialist';
1824
+ specialist: 'compaction-summary';
1825
+ variant: KodaXCompactionPromptVariant;
1826
+ systemPrompt: string;
1827
+ userPrompt: string;
1828
+ sections: KodaXCompactionPromptSection[];
1829
+ hash: string;
1830
+ }
1831
+ declare function buildCompactionPromptSnapshot(args: {
1832
+ messages: KodaXMessage[];
1833
+ details: CompactionDetails;
1834
+ customInstructions?: string;
1835
+ systemPrompt?: string;
1836
+ previousSummary?: string;
1837
+ /**
1838
+ * Override the initial-summary instructions. When omitted, falls back
1839
+ * to {@link DEFAULT_SUMMARY_PROMPT}. Coding callers pass
1840
+ * `CODING_SUMMARY_PROMPT` (from @kodax-ai/coding) here to preserve the
1841
+ * v0.7.35 byte-equivalent prompt on the coding path.
1842
+ */
1843
+ summaryPrompt?: string;
1844
+ /**
1845
+ * Override the update-summary instructions. When omitted, falls back
1846
+ * to {@link DEFAULT_UPDATE_SUMMARY_PROMPT}. Coding callers pass
1847
+ * `CODING_UPDATE_SUMMARY_PROMPT` (from @kodax-ai/coding) here.
1848
+ */
1849
+ updateSummaryPrompt?: string;
1850
+ }): KodaXCompactionPromptSnapshot;
1851
+ declare function generateSummary(messages: KodaXMessage[], provider: KodaXBaseProvider, details: CompactionDetails, customInstructions?: string, systemPrompt?: string, previousSummary?: string, summaryPrompt?: string, updateSummaryPrompt?: string): Promise<string>;
1852
+
1853
+ /**
1854
+ * ../../index.js Compaction Core
1855
+ *
1856
+ * Progressive compaction with lightweight tool-result pruning and rolling
1857
+ * summarization to an internal low-water mark.
1858
+ */
1859
+
1860
+ /**
1861
+ * Exported as the canonical PROTECTED set so peer modules
1862
+ * (microcompaction.ts default config, registry-parity test, future
1863
+ * Stage 3 ledger work) can pull a single source-of-truth.
1864
+ */
1865
+ declare const PROTECTED_TOOL_NAMES: ReadonlySet<string>;
1866
+ /**
1867
+ * Marker prefix on the synthesized summary system message. Other packages
1868
+ * use this literal as the discriminator to tell CompactionSummary system
1869
+ * messages apart from role-prompt system messages \u2014 exported so callers
1870
+ * (notably `@kodax-ai/coding`'s `preserveTranscriptForRoundExit`) cannot
1871
+ * drift from the producer side.
1872
+ */
1873
+ declare const COMPACTION_SUMMARY_PREFIX = "[\u5BF9\u8BDD\u5386\u53F2\u6458\u8981]\n\n";
1874
+ /**
1875
+ * FEATURE_181 (v0.7.42): detect LLM "I have no content to summarize" output.
1876
+ *
1877
+ * Empty-like markers observed across 788 sessions (7.8% of compactions):
1878
+ * - "No active goal" / "no active goal"
1879
+ * - "conversation is empty" / "The conversation is empty"
1880
+ * - "no prior context"
1881
+ * - "nothing to summarize" / "no content to summarize"
1882
+ *
1883
+ * Also catches very short outputs (< 80 chars) — a meaningful goal summary
1884
+ * is empirically ≥150 chars even for simple tasks. Conservative threshold:
1885
+ * false positives only cause us to KEEP the previous summary, never lose
1886
+ * information.
1887
+ *
1888
+ * Exported for unit testing.
1889
+ */
1890
+ declare function isEmptyLikeSummary(summary: string): boolean;
1891
+ declare function needsCompaction(messages: KodaXMessage[], config: CompactionConfig, contextWindow?: number, tokenCountOverride?: number): boolean;
1892
+ declare function compact(messages: KodaXMessage[], config: CompactionConfig, provider: KodaXBaseProvider, contextWindow?: number, customInstructions?: string, systemPrompt?: string, tokenCountOverride?: number, summaryPrompt?: string, updateSummaryPrompt?: string): Promise<CompactionResult>;
1893
+
1894
+ /**
1895
+ * KodaX Microcompaction - Time-driven context cleanup
1896
+ *
1897
+ * Clears old tool result content from messages to slow context growth.
1898
+ * Pure function, no LLM calls, runs after each agent turn.
1899
+ *
1900
+ * Design:
1901
+ * - Tracks "turns" (role switches from assistant to user)
1902
+ * - Clears tool_result blocks older than maxAge turns
1903
+ * - Preserves thinking blocks (token cost is marginal; Kimi requires non-empty
1904
+ * reasoning_content on every tool-call assistant message)
1905
+ * - Preserves image blocks (replacing them invalidates Anthropic prompt-cache
1906
+ * prefixes and discards multimodal context; all reference agents — claudecode,
1907
+ * pi-mono, opencode — also preserve images at this layer. Token cost is handled
1908
+ * by the LLM compaction layer that produces a summary when budget pressure hits.)
1909
+ * - Preserves protected tools (e.g., ask_user_question)
1910
+ * - Placeholder format matches compaction pruning: `[Cleared: grep src/auth.ts "pattern"]`
1911
+ * - Immutable: returns new array, never mutates input
1912
+ */
1913
+
1914
+ interface MicrocompactionConfig {
1915
+ readonly enabled: boolean;
1916
+ readonly maxAge: number;
1917
+ readonly protectedTools: readonly string[];
1918
+ }
1919
+ /**
1920
+ * FEATURE_183 (v0.7.42): align `protectedTools` with the canonical
1921
+ * PROTECTED_TOOL_NAMES from compaction.ts so microcompact and the
1922
+ * slow-path pruneToolResults agree on which tools are off-limits. Pre-F183
1923
+ * the two sets had drifted (microcompact = `['ask_user_question']`, prune
1924
+ * = `['skill']`), meaning a tool could be cleared by one path and
1925
+ * protected by the other depending on whether maxAge or pruning ran
1926
+ * first — semantically incoherent.
1927
+ */
1928
+ declare const DEFAULT_MICROCOMPACTION_CONFIG: MicrocompactionConfig;
1929
+ /**
1930
+ * Microcompact messages by clearing old tool result content.
1931
+ * Returns a new array - does NOT mutate the input.
1932
+ *
1933
+ * Placeholder format reuses the same rich preview as compaction pruning:
1934
+ * - bash: `[Cleared: git status]`
1935
+ * - grep: `[Cleared: grep src/auth.ts "pattern"]`
1936
+ * - read: `[Cleared: read auth.ts]`
1937
+ * - edit: `[Cleared: edit auth.ts]`
1938
+ *
1939
+ * @param messages - The input messages to microcompact
1940
+ * @param config - Configuration (defaults to DEFAULT_MICROCOMPACTION_CONFIG)
1941
+ * @returns A new message array with old tool results cleared, or original if unchanged
1942
+ */
1943
+ declare function microcompact(messages: readonly KodaXMessage[], config?: MicrocompactionConfig): readonly KodaXMessage[];
1944
+
1945
+ /**
1946
+ * Post-Compact Reconstruction
1947
+ *
1948
+ * After compaction, injects artifact ledger summary and recently modified
1949
+ * file content back into the context so the agent remembers what it
1950
+ * operated on without re-reading files.
1951
+ *
1952
+ * Budget rule: total post-compact attachments are capped by the smaller of
1953
+ * (freed tokens × budgetRatio) and POST_COMPACT_TOKEN_BUDGET (absolute cap).
1954
+ * The absolute cap mirrors Claude Code's `POST_COMPACT_TOKEN_BUDGET = 50_000`
1955
+ * and prevents re-inflation when a single compaction frees a huge chunk.
1956
+ * Within the budget: ledger gets ≤15%, rest goes to file content
1957
+ * (per-file cap = min(perFileShare × total, POST_COMPACT_MAX_TOKENS_PER_FILE),
1958
+ * max 5 files).
1959
+ *
1960
+ * Idempotence: `injectPostCompactAttachments` strips any prior
1961
+ * `[Post-compact: ...]` system messages before inserting new ones, so a flat
1962
+ * messages array that survives across compaction rounds does not accumulate
1963
+ * multiple generations of post-compact attachments.
1964
+ */
1965
+
1966
+ /**
1967
+ * Absolute cap on total post-compact attachment tokens.
1968
+ * Mirrors Claude Code's POST_COMPACT_TOKEN_BUDGET (services/compact/compact.ts).
1969
+ */
1970
+ declare const POST_COMPACT_TOKEN_BUDGET = 50000;
1971
+ /**
1972
+ * Per-file hard cap on content tokens.
1973
+ * Mirrors Claude Code's POST_COMPACT_MAX_TOKENS_PER_FILE.
1974
+ */
1975
+ declare const POST_COMPACT_MAX_TOKENS_PER_FILE = 5000;
1976
+ interface PostCompactConfig {
1977
+ /** Ratio of freed tokens to use for post-compact attachments. Default 0.5. */
1978
+ readonly budgetRatio: number;
1979
+ /** Maximum files to inject. Default 5. */
1980
+ readonly maxFiles: number;
1981
+ /** Ledger share as fraction of total budget. Default 0.15. */
1982
+ readonly ledgerShare: number;
1983
+ /** Per-file share as fraction of total budget. Default 0.20. */
1984
+ readonly perFileShare: number;
1985
+ }
1986
+ declare const DEFAULT_POST_COMPACT_CONFIG: PostCompactConfig;
1987
+ interface PostCompactAttachments {
1988
+ readonly ledgerMessage: KodaXMessage | null;
1989
+ readonly fileMessages: readonly KodaXMessage[];
1990
+ readonly totalTokens: number;
1991
+ }
1992
+ /**
1993
+ * Build post-compact system messages from the artifact ledger.
1994
+ * Does NOT read files from disk — that is the caller's responsibility.
1995
+ *
1996
+ * @param ledger - The artifact ledger from compaction
1997
+ * @param freedTokens - Tokens freed by compaction (tokensBefore - tokensAfter)
1998
+ * @param config - Budget configuration
1999
+ * @returns Attachments to inject after the compacted messages
2000
+ */
2001
+ declare function buildPostCompactAttachments(ledger: readonly KodaXSessionArtifactLedgerEntry[], freedTokens: number, config?: PostCompactConfig): PostCompactAttachments;
2002
+ /**
2003
+ * Inject post-compact attachments into the compacted message array.
2004
+ *
2005
+ * Inserts after the compaction summary (first system message with the
2006
+ * summary prefix) and before the protected tail. Any existing post-compact
2007
+ * attachment messages in the input are stripped first to keep the injection
2008
+ * idempotent — without this, compaction repeated across iterations would
2009
+ * stack N generations of attachments, causing monotonic context growth.
2010
+ */
2011
+ declare function injectPostCompactAttachments(messages: KodaXMessage[], attachments: PostCompactAttachments): KodaXMessage[];
2012
+ /**
2013
+ * Read recently modified files from disk and build system messages for
2014
+ * post-compact context restoration.
2015
+ *
2016
+ * @param ledger - Artifact ledger from compaction
2017
+ * @param budgetTokens - Remaining token budget after ledger injection
2018
+ * @param config - Budget configuration
2019
+ * @returns File content messages to merge into PostCompactAttachments.fileMessages
2020
+ */
2021
+ declare function buildFileContentMessages(ledger: readonly KodaXSessionArtifactLedgerEntry[], budgetTokens: number, config?: PostCompactConfig): Promise<readonly KodaXMessage[]>;
2022
+
2023
+ /**
2024
+ * ../index.js Extension Persistence Store
2025
+ *
2026
+ * JSONL-backed key-value store scoped to a single extension identity.
2027
+ * Each store instance owns one `.jsonl` file inside the extension store
2028
+ * directory. All I/O is async and safe for single-writer use.
2029
+ *
2030
+ * File format (one JSON object per line):
2031
+ *
2032
+ * {"_type":"entry","key":"...","value":...,"version":"...","updatedAt":...}
2033
+ */
2034
+
2035
+ /**
2036
+ * JSONL-backed implementation of {@link KodaXExtensionStore}.
2037
+ *
2038
+ * All data for a single extension namespace lives in one JSONL file under
2039
+ * `~/.kodax/extension-store/<namespace>/store.jsonl`. The file is rewritten
2040
+ * atomically on every mutation (replace-then-rename).
2041
+ */
2042
+ declare class FileExtensionStore implements KodaXExtensionStore {
2043
+ private readonly filePath;
2044
+ constructor(namespaceId: string);
2045
+ get(key: string): Promise<KodaXExtensionStoreEntry | undefined>;
2046
+ put(key: string, value: KodaXJsonValue, options?: {
2047
+ expectedVersion?: string;
2048
+ }): Promise<KodaXExtensionStoreEntry | false>;
2049
+ delete(key: string): Promise<boolean>;
2050
+ list(options?: {
2051
+ prefix?: string;
2052
+ }): Promise<string[]>;
2053
+ clear(options?: {
2054
+ prefix?: string;
2055
+ }): Promise<number>;
2056
+ private readAllEntries;
2057
+ private writeAllEntries;
2058
+ }
2059
+ /**
2060
+ * Create a {@link FileExtensionStore} for the given extension namespace.
2061
+ *
2062
+ * The namespace is typically the `extensionId` (e.g. `cli:extension:/path/to/ext.mjs`).
2063
+ */
2064
+ declare function createExtensionStore(namespaceId: string): KodaXExtensionStore;
2065
+
2066
+ /**
2067
+ * Compaction trigger decision — CAP-059
2068
+ *
2069
+ * Capability inventory: docs/features/v0.7.29-capability-inventory.md#cap-059-compaction-trigger-decision
2070
+ *
2071
+ * Class 1 (substrate). Per-turn predicate read BEFORE the provider
2072
+ * stream call to decide whether the compaction lifecycle (CAP-060)
2073
+ * should run this turn. Time-ordering: AFTER microcompact (CAP-014);
2074
+ * BEFORE intelligentCompact orchestration (CAP-060).
2075
+ *
2076
+ * The wrapper preserves the historical short-circuit `compactionConfig.enabled`
2077
+ * gate from `agent.ts` even though the underlying `needsCompaction`
2078
+ * helper already returns `false` when the config is disabled. The
2079
+ * double-gate matches the pre-FEATURE_100 baseline byte-for-byte —
2080
+ * removing the redundancy is a P3.6 cleanup concern, not a P3.4
2081
+ * extraction concern.
2082
+ *
2083
+ * Migration history:
2084
+ * - extracted from `agent.ts:598-600` — pre-FEATURE_100 baseline —
2085
+ * during FEATURE_100 P3.4a.
2086
+ * - moved from `../../index.js/src/runtime-middleware/` to
2087
+ * `@kodax-ai/session-lineage/src/runtime-middleware/` in v0.7.36 to
2088
+ * break the build cycle introduced by FEATURE_142 Batch D
2089
+ * (agent → session-lineage → agent). session-lineage already
2090
+ * depends on agent, so this direction is acyclic. Semantically
2091
+ * this also reflects that compaction trigger is part of the
2092
+ * compaction lifecycle, which is session-lineage's domain.
2093
+ */
2094
+
2095
+ interface ShouldCompactInput {
2096
+ readonly messages: KodaXMessage[];
2097
+ readonly compactionConfig: CompactionConfig;
2098
+ readonly contextWindow: number;
2099
+ readonly currentTokens: number;
2100
+ }
2101
+ /**
2102
+ * Returns `true` iff the compaction lifecycle should run this turn.
2103
+ * Combines the config-enabled gate with the underlying trigger
2104
+ * threshold check from `@kodax-ai/session-lineage`'s `needsCompaction`.
2105
+ */
2106
+ declare function shouldCompact(input: ShouldCompactInput): boolean;
2107
+
2108
+ /**
2109
+ * Graceful compaction degradation — CAP-028
2110
+ *
2111
+ * Capability inventory: docs/features/v0.7.29-capability-inventory.md#cap-028-graceful-compaction-degradation
2112
+ *
2113
+ * Class 1 (substrate middleware). Truncation-based fallback that fires
2114
+ * when the primary FEATURE_072 lineage compaction fails (LLM error,
2115
+ * token overflow during summarization, etc.) so the run can continue
2116
+ * instead of hard-failing.
2117
+ *
2118
+ * Strategy: drop the oldest atomic blocks (tool_use + tool_result
2119
+ * pairs) one at a time from the front until token estimate is below
2120
+ * the target threshold (`triggerPercent * 80%` of context window).
2121
+ * Three invariants are load-bearing:
2122
+ *
2123
+ * 1. **Summary preservation** — if the very first message is a
2124
+ * `system` message OR a `user` message containing `'[对话历史摘要]'`
2125
+ * (the FEATURE_072 lineage marker), `startIdx = 1` so the
2126
+ * summary itself is never dropped.
2127
+ *
2128
+ * 2. **Tool pairing** — `tool_use` blocks (assistant) and
2129
+ * `tool_result` blocks (user) MUST stay paired. If we encounter
2130
+ * a `tool_use` without a following `tool_result` (or a
2131
+ * `tool_result` without a preceding `tool_use`), we skip past
2132
+ * it rather than orphaning its partner. This is critical because
2133
+ * providers reject unpaired tool blocks with `400` errors.
2134
+ *
2135
+ * 3. **Recent-context preservation** — the loop terminates as soon
2136
+ * as the running token estimate dips below the target, so the
2137
+ * tail of the conversation (most-recent messages) is preserved.
2138
+ *
2139
+ * The function is INTENTIONALLY destructive — it returns a NEW array
2140
+ * with the dropped messages removed. Callers do not mutate the input
2141
+ * array directly (the `messages = [...messages.slice(...)]` pattern
2142
+ * inside the loop ensures each iteration starts from a fresh copy).
2143
+ *
2144
+ * The two content-block predicates (`isTypedContentBlock`,
2145
+ * `isToolResultContentBlock`) are private helpers carried over with
2146
+ * this function — by the time this batch ran, prior batches had
2147
+ * already migrated `validateAndFixToolHistory` (the only other
2148
+ * consumer of these predicates in HEAD `agent.ts`) into
2149
+ * `agent-runtime/history-cleanup.ts` along with its own local copies
2150
+ * of the predicates (CAP-002). So at the point of extraction, the
2151
+ * predicates' only remaining `agent.ts` consumer was
2152
+ * `gracefulCompactDegradation` itself. Co-locating them here keeps
2153
+ * the module self-contained.
2154
+ *
2155
+ * (The original `agent.ts` also defined `isToolUseContentBlock` next
2156
+ * to these. In HEAD it had 2 callers inside
2157
+ * `validateAndFixToolHistory`; those callers moved with the function
2158
+ * to `history-cleanup.ts` (CAP-002) and the agent.ts copy of
2159
+ * `isToolUseContentBlock` was left without callers. It is therefore
2160
+ * intentionally NOT carried over to this module. The dispatcher's
2161
+ * tool-use checks elsewhere in `agent.ts` use the inline pattern
2162
+ * `isTypedContentBlock(b) && b.type === 'tool_use'` instead.)
2163
+ *
2164
+ * Migration history:
2165
+ * - extracted from `agent.ts:185-187` + `195-199` (the two carried
2166
+ * predicates) + `agent.ts:201-266` (`gracefulCompactDegradation`
2167
+ * with its docstring) — pre-FEATURE_100 baseline — during
2168
+ * FEATURE_100 P2.
2169
+ * - moved from `../../index.js/src/runtime-middleware/` to
2170
+ * `@kodax-ai/session-lineage/src/runtime-middleware/` in v0.7.36 to
2171
+ * break the build cycle introduced by FEATURE_142 Batch D
2172
+ * (agent → session-lineage → agent). Semantically this also
2173
+ * reflects that compaction degradation is part of the compaction
2174
+ * lifecycle, which is session-lineage's domain.
2175
+ */
2176
+
2177
+ /**
2178
+ * Graceful compact degradation: drop oldest atomic blocks (tool_use + tool_result pairs)
2179
+ * one at a time from the front until tokens are below the target threshold.
2180
+ * Preserves summary messages, message structure integrity, and recent context.
2181
+ */
2182
+ declare function gracefulCompactDegradation(messages: KodaXMessage[], contextWindow: number, config: CompactionConfig): KodaXMessage[];
2183
+
2184
+ /**
2185
+ * Effective context-window resolver — CAP-056
2186
+ *
2187
+ * Capability inventory: docs/features/v0.7.29-capability-inventory.md#cap-056-effective-context-window-resolution-cascade
2188
+ *
2189
+ * Class 1 (substrate middleware). Pure four-step cascade evaluated at
2190
+ * the start of every turn (after per-turn provider re-resolution,
2191
+ * before the compaction trigger decision). The cascade order is
2192
+ * load-bearing — earlier sources override later ones:
2193
+ *
2194
+ * 1. **`compactionConfig.contextWindow`** (user-supplied) — wins
2195
+ * unconditionally so an operator can pin a smaller window for
2196
+ * cost / latency reasons even if the provider would advertise a
2197
+ * larger one.
2198
+ * 2. **`provider.getEffectiveContextWindow?.(model)`** — model-
2199
+ * specific window when the provider exposes it (e.g.
2200
+ * `claude-3-5-sonnet-20241022` advertises 200000, while a
2201
+ * provider with multiple models returns a per-model value).
2202
+ * 3. **`provider.getContextWindow?.()`** — provider-level default
2203
+ * (used when the provider only exposes a single window).
2204
+ * 4. **`200000`** — hard fallback. Mirrors Anthropic's standard
2205
+ * Claude window; safe default for providers that don't implement
2206
+ * either capability check.
2207
+ *
2208
+ * The optional-chained calls are load-bearing — providers that don't
2209
+ * implement `getEffectiveContextWindow` / `getContextWindow` simply
2210
+ * skip to the next step in the cascade rather than throwing.
2211
+ *
2212
+ * P3 note: per inventory's stated migration target this module is
2213
+ * "shared with CAP-055" (per-turn provider re-resolution). CAP-055
2214
+ * lives inline in `runKodaX`'s for-loop today; once P3 substrate
2215
+ * adoption lands and the per-turn block lives inside the Runner
2216
+ * frame, both helpers will likely co-locate in
2217
+ * `per-turn-provider-resolution.ts`. For P2 this single-cascade
2218
+ * helper is the only piece tractable as a discrete extraction.
2219
+ *
2220
+ * Migration history:
2221
+ * - extracted from `agent.ts:1700-1703` — pre-FEATURE_100 baseline
2222
+ * — during FEATURE_100 P2.
2223
+ * - moved from `../../index.js/src/runtime-middleware/` to
2224
+ * `@kodax-ai/session-lineage/src/runtime-middleware/` in v0.7.36 to
2225
+ * break the build cycle introduced by FEATURE_142 Batch D
2226
+ * (agent → session-lineage → agent). Semantically this also
2227
+ * reflects that the resolver consumes session-lineage's
2228
+ * `CompactionConfig`, so its canonical home is alongside
2229
+ * compaction policy types.
2230
+ */
2231
+
2232
+ /** Hard fallback. Mirrors Anthropic standard Claude window. */
2233
+ declare const DEFAULT_CONTEXT_WINDOW = 200000;
2234
+ declare function resolveContextWindow(compactionConfig: CompactionConfig, provider: KodaXBaseProvider, modelOverride: string | undefined): number;
2235
+
2236
+ export { Agent, AgentManifest, AgentMessage, COMPACTION_SUMMARY_PREFIX, CORE_INVARIANTS, ChildTaskRegistry, CompactionConfig, CompactionDetails, CompactionResult, ConsoleTracingProcessor, DEFAULT_CONTEXT_WINDOW, DEFAULT_IDLE_YIELD_MAX_ITERATIONS, DEFAULT_MICROCOMPACTION_CONFIG, DEFAULT_POST_COMPACT_CONFIG, DEFAULT_SUMMARY_PROMPT, DEFAULT_UPDATE_SUMMARY_PROMPT, DequeueFilter, DiscoveredInstance, EnqueueInput, FileExtensionStore, FileTracingProcessor, Handoff, InstanceDiscoveryFs, InvariantId, KodaXExtensionStore, KodaXExtensionStoreEntry, KodaXGoalEventType, KodaXGoalState, KodaXJsonValue, KodaXMessage, KodaXSessionArtifactLedgerEntry, KodaXSessionEntry, KodaXSessionGoalEntry, KodaXSessionLineage, MAX_ENTRYPOINT_BYTES, MAX_ENTRYPOINT_LINES, ManifestPatch, MessageMode, MessagePriority, MessageQueue, POST_COMPACT_MAX_TOKENS_PER_FILE, POST_COMPACT_TOKEN_BUDGET, PROTECTED_TOOL_NAMES, QualityInvariant, QueuedMessage, RunnerToolCall, RunnerToolResult, SessionMeta, SessionStateSnapshot, Span, StateWriter, StateWriterFs, Trace, YIELD_TOOL_NAMES, _emitSpanEnd, _emitSpanStart, _emitTraceEnd, _getRegisteredProcessors, _resetAdmissionMetrics, _resetInvariantRegistry, _resetMessageQueueForTests, addTracingProcessor, appendGoalEntry, applyManifestPatch, bootstrapTeamMode, buildCompactionPromptSnapshot, buildFileContentMessages, buildOtherInstancesPromptBlock, buildPostCompactAttachments, compact, composeIdleYieldUserMessage, composePatches, countLastAssistantToolCalls, createExtensionStore, detectHandoffSignal, detectIdleYield, emitHandoffSpan, enqueueChildTaskNotification, evidenceTrail, finalOwner, generateSummary, getActiveTeamModeWriter, getAdmissionMetricsSnapshot, getInvariant, getMessageQueue, gracefulCompactDegradation, handoffLegality, hashCwd, injectPostCompactAttachments, isAdmissionDebugEnabled, isAutoManagedMemoryFile, isEmptyLikeSummary, isGoalEntry, isIdleYieldEnabled, listRegisteredInvariants, maybeDrainMidTurn, microcompact, midTurnDrainPriority, needsCompaction, parseMemoryFile, parseMemoryType, parseMemoryTypeFromFilename, parseScalarFields, readLatestGoalFromBranch, readLatestGoalState, registerCoreInvariants, registerInvariant, replaceSystemMessage, resolveContextWindow, resolveEffectiveInvariants, resolveMemoryEntrypoint, resolveMemoryRoot, resolveRequiredInvariants, routeMessage, runFanOut, runWithIdleYield, sanitizeProjectKey, serializeConversation, setActiveTeamModeWriter, setTracingProcessors, shouldCompact, shutdownTracing, truncateEntrypointContent, tryGitRemote, updateActiveTeamMode, waitForWakeEvent };
2237
+ export type { AdmissionMetricsSnapshot, ConsoleTracingProcessorOptions, EnqueueChildTaskNotificationInput, EntrypointTruncation, EnvelopeAggregateEnforcer, FanOutOutcome, FanOutProgressEvent, FileTracingProcessorOptions, HandoffSignal, IdleYieldSnapshot, KodaXCompactionPromptSection, KodaXCompactionPromptSnapshot, KodaXCompactionPromptVariant, MaybeDrainMidTurnInput, MemoryFrontmatter, MemoryType, MicrocompactionConfig, ParsedMemoryFile, PostCompactAttachments, PostCompactConfig, RenderOptions, RouteMessageOptions, RouteMessageResult, RunFanOutOptions, RunFanOutResult, RunWithIdleYieldOptions, RunWithIdleYieldRunResult, ShouldCompactInput, TeamModeBootstrapOptions, TeamModeHandle, TracingProcessor, WaitForWakeEventOptions, WakeEvent };