@kodax-ai/kodax 0.7.41 → 0.7.43

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 (54) hide show
  1. package/CHANGELOG.md +119 -3
  2. package/README.md +214 -286
  3. package/README_CN.md +173 -277
  4. package/dist/chunks/chunk-7G5PSL6C.js +830 -0
  5. package/dist/chunks/{chunk-6OB4AJOM.js → chunk-IYSK7LUK.js} +1 -1
  6. package/dist/chunks/chunk-K75O2CAE.js +31 -0
  7. package/dist/chunks/chunk-UG4262JI.js +502 -0
  8. package/dist/chunks/chunk-VHKAJDQD.js +425 -0
  9. package/dist/chunks/chunk-YMRZBS4G.js +2 -0
  10. package/dist/chunks/{compaction-config-LT5PEXPT.js → compaction-config-3E57ABCT.js} +1 -1
  11. package/dist/chunks/{construction-bootstrap-HBCWJFHC.js → construction-bootstrap-JR63KI5N.js} +4 -4
  12. package/dist/chunks/dist-KWHUKXEL.js +2 -0
  13. package/dist/chunks/dist-XANXEVTU.js +2 -0
  14. package/dist/chunks/utils-HQ2QCKJA.js +2 -0
  15. package/dist/index.d.ts +15 -10
  16. package/dist/index.js +5 -5
  17. package/dist/kodax_cli.js +1084 -1054
  18. package/dist/sdk-agent.d.ts +853 -135
  19. package/dist/sdk-agent.js +1 -1
  20. package/dist/sdk-coding.d.ts +932 -981
  21. package/dist/sdk-coding.js +1 -1
  22. package/dist/sdk-llm.d.ts +8 -5
  23. package/dist/sdk-llm.js +1 -1
  24. package/dist/sdk-mcp.d.ts +17 -0
  25. package/dist/sdk-mcp.js +2 -0
  26. package/dist/sdk-repl.d.ts +343 -10
  27. package/dist/sdk-repl.js +2 -1
  28. package/dist/sdk-session.d.ts +176 -0
  29. package/dist/sdk-session.js +2 -0
  30. package/dist/sdk-skills.d.ts +72 -4
  31. package/dist/sdk-skills.js +1 -1
  32. package/dist/types-chunks/{cost-tracker.d-C4dMlQuV.d.ts → base.d-FUJahC0i.d.ts} +22 -112
  33. package/dist/types-chunks/{bash-prefix-extractor.d-B2iliwdi.d.ts → bash-prefix-extractor.d-DMrGImMl.d.ts} +266 -228
  34. package/dist/types-chunks/capability.d-3C62G8Eq.d.ts +39 -0
  35. package/dist/types-chunks/config.d-BfJUXxC0.d.ts +41 -0
  36. package/dist/types-chunks/cost-tracker.d-wRtyEW9d.d.ts +110 -0
  37. package/dist/types-chunks/{history-cleanup.d-q1vAvCss.d.ts → file-tracker.d-zaLZeNBK.d.ts} +532 -15
  38. package/dist/types-chunks/manager.d-87belpiS.d.ts +370 -0
  39. package/dist/types-chunks/{resolver.d-BwD6TKz7.d.ts → resolver.d-CA68_NeH.d.ts} +150 -5
  40. package/dist/types-chunks/storage.d-DPAEX7zS.d.ts +115 -0
  41. package/dist/types-chunks/{capability.d-BxNgd1-c.d.ts → types.d-B1uGoVTE.d.ts} +72 -40
  42. package/dist/types-chunks/{instance-discovery.d-DZhp77vb.d.ts → types.d-CKJtjo-6.d.ts} +168 -258
  43. package/dist/types-chunks/types.d-mM8vqvhT.d.ts +254 -0
  44. package/dist/types-chunks/{storage.d-Bv9T99Qu.d.ts → utils.d-DkLZD_wa.d.ts} +38 -112
  45. package/package.json +15 -6
  46. package/dist/chunks/chunk-5TFLMGER.js +0 -2
  47. package/dist/chunks/chunk-6QO6HWGU.js +0 -30
  48. package/dist/chunks/chunk-EQ5DGS2W.js +0 -14
  49. package/dist/chunks/chunk-HYWVRTFA.js +0 -1233
  50. package/dist/chunks/chunk-SX2IS5JP.js +0 -16
  51. package/dist/chunks/chunk-ZPJPNLBK.js +0 -462
  52. package/dist/chunks/dist-M57GIWR4.js +0 -2
  53. package/dist/chunks/dist-V3BS2NKB.js +0 -2
  54. package/dist/chunks/utils-FAFUQJ2A.js +0 -2
@@ -1,5 +1,6 @@
1
- import { o as KodaXMessage } from './capability.d-BxNgd1-c.js';
2
- import { a as AgentMessage, a7 as SpanData, a6 as Span, a8 as SpanError, A as Agent, _ as RunnerLlmReturn, G as Guardrail, a1 as RunnerToolObserver } from './instance-discovery.d-DZhp77vb.js';
1
+ import { m as KodaXMessage } from './types.d-B1uGoVTE.js';
2
+ import { a as AgentMessage, V as SpanData, U as Span, W as SpanError, A as Agent, J as RunnerLlmReturn, o as Guardrail, N as RunnerToolObserver, h as CompactionDetails, n as FileOperations } from './types.d-CKJtjo-6.js';
3
+ import { o as KodaXSessionLineage, f as KodaXJsonValue, a as KodaXCompactMemorySeed, l as KodaXSessionEntry, v as KodaXSessionTreeNode, n as KodaXSessionLabelEntry, r as KodaXSessionNavigationOptions, h as KodaXSessionArtifactLedgerEntry } from './types.d-mM8vqvhT.js';
3
4
 
4
5
  /**
5
6
  * @kodax-ai/agent Constants
@@ -42,7 +43,7 @@ declare function countTokens(text: string): number;
42
43
  * Layer A Primitive: Session / SessionEntry / MessageEntry / SessionExtension
43
44
  *
44
45
  * FEATURE_081 (v0.7.23): Base Session shape. The thick
45
- * `KodaXSessionLineage` lives in `@kodax-ai/session-lineage` and is re-expressed
46
+ * `KodaXSessionLineage` lives in `../session-lineage/index.js` and is re-expressed
46
47
  * as a `LineageExtension` over this base.
47
48
  *
48
49
  * History: extracted to `@kodax-ai/core` in FEATURE_082 (v0.7.24); merged back
@@ -141,7 +142,7 @@ interface InMemorySessionOptions {
141
142
  /**
142
143
  * In-memory Session suitable for tests, examples, and embedded SDK use. Not
143
144
  * durable across process restarts — persistence is provided by coding-specific
144
- * adapters in `@kodax-ai/session-lineage` and `@kodax-ai/agent`.
145
+ * adapters in `../session-lineage/index.js` and `@kodax-ai/agent`.
145
146
  */
146
147
  declare function createInMemorySession(opts?: InMemorySessionOptions): Session;
147
148
 
@@ -154,7 +155,7 @@ declare function createInMemorySession(opts?: InMemorySessionOptions): Session;
154
155
  * - Layer A (here): `CompactionPolicy` interface + `DefaultSummaryCompaction`
155
156
  * — a minimal "token threshold → LLM summary of old messages" policy that
156
157
  * any external Agent can pick up with zero KodaX runtime dependency.
157
- * - Layer B (`@kodax-ai/session-lineage/src/lineage.ts`): `LineageCompaction`
158
+ * - Layer B (`../session-lineage/index.js/src/lineage.ts`): `LineageCompaction`
158
159
  * wraps the full FEATURE_072 lineage-native compaction for the coding
159
160
  * preset.
160
161
  *
@@ -300,6 +301,12 @@ interface TraceOptions {
300
301
  readonly onSpanEnd?: (span: Span) => void;
301
302
  readonly onTraceEnd?: (trace: Trace) => void;
302
303
  }
304
+ /**
305
+ * In-memory Trace implementation. External consumers can replace this with
306
+ * an adapter (OpenTelemetry Trace, Langfuse trace) by registering their own
307
+ * `TracingProcessor`.
308
+ */
309
+ declare function createTrace(opts?: TraceOptions): Trace;
303
310
 
304
311
  /**
305
312
  * Tracer — convenience façade that creates Traces wired to the registered
@@ -333,6 +340,8 @@ declare class Tracer {
333
340
  constructor(options?: TracerOptions);
334
341
  startTrace(opts?: StartTraceOptions): Trace;
335
342
  }
343
+ /** Default tracer shared by the KodaX runtime. External callers can create their own. */
344
+ declare const defaultTracer: Tracer;
336
345
 
337
346
  /**
338
347
  * Layer A Primitive: Quality Invariant + Admission Contract types.
@@ -977,14 +986,34 @@ interface RunOptions {
977
986
  */
978
987
  readonly toolObserver?: RunnerToolObserver;
979
988
  /**
980
- * v0.7.26 parity: compaction hook. Called AFTER each iteration's
981
- * tool_result has been appended to the transcript (or after the
982
- * assistant message when there are no tool calls), before the next
983
- * LLM turn. Return the replacement transcript to trigger compaction;
984
- * return the same array (or undefined) to skip. Legacy agent.ts ran
985
- * `intelligentCompact` on the same boundary, so Runner-driven parity
986
- * requires this hook point. The Runner owns the transcript mutably,
987
- * so this is the only point consumers can insert a compacted view.
989
+ * Compaction hook. Fires at the TOP of every tool-loop iteration,
990
+ * BEFORE the LLM call. Return the replacement transcript to trigger
991
+ * compaction; return the same array (or undefined) to skip. The Runner
992
+ * owns the transcript mutably, so this is the only point consumers can
993
+ * insert a compacted view before the next provider.stream invocation.
994
+ *
995
+ * **Trigger frequency**: every iteration of every Runner.run() call.
996
+ * - Iteration 0 fires BEFORE the first LLM call (covers idle-yield
997
+ * resume / new user activation where the transcript already exceeds
998
+ * threshold from accumulated prior turns).
999
+ * - Iteration N (N≥1) fires after the previous iteration's tool_result
1000
+ * was appended, same "before next LLM call" timing as the legacy
1001
+ * post-tool-result firing point.
1002
+ * - Text-only iterations are covered: the next Runner.run() invocation
1003
+ * (when the user/parent re-engages) runs iter 0 → hook fires before
1004
+ * the new LLM call.
1005
+ *
1006
+ * **Why not after tool_result append (legacy v0.7.26 location)**: that
1007
+ * boundary skipped text-only termination — Runner exits at line ~611
1008
+ * without firing the hook, so idle-yield + text-only end-of-turn
1009
+ * sessions grew unbounded between checks. claudecode (`query.ts:307-454`),
1010
+ * pi-mono (`agent-session.ts:949`), opencode (`processor.ts:609-613`),
1011
+ * and KodaX SA (`run-substrate.ts:621-627`) all check at the per-LLM-
1012
+ * call boundary. FEATURE_179 (v0.7.42) brought the AMA Runner path
1013
+ * into line — the failure scenario was a Worker session that grew
1014
+ * 165K → 180K through text-only end-of-turn + idle-yield, then
1015
+ * triggered at 181K (61K over the 120K threshold) only after the next
1016
+ * tool call landed.
988
1017
  */
989
1018
  readonly compactionHook?: (transcript: readonly AgentMessage[]) => Promise<readonly AgentMessage[] | undefined>;
990
1019
  /**
@@ -1090,7 +1119,84 @@ interface RunOptions {
1090
1119
  readonly to: Agent;
1091
1120
  readonly iteration: number;
1092
1121
  }) => void | Promise<void>;
1122
+ /**
1123
+ * FEATURE_184 (v0.7.45) — Stop Hook primitive.
1124
+ *
1125
+ * Fires when the model terminates a turn with no `tool_use` blocks
1126
+ * (text-only response). The hook receives the post-output-guardrail
1127
+ * transcript and the final assistant text, and returns one of:
1128
+ *
1129
+ * - `undefined` → accept the termination, fall through to the normal
1130
+ * terminal path (assertTerminal + return). This is the no-op default.
1131
+ * - `string` → "blockingErrors" / reanimate. Runner synthesizes a
1132
+ * `{role: 'user', content: <string>}` message, appends it to the
1133
+ * transcript + session, and continues the loop. Bounded by
1134
+ * `stopHookReanimateBudget` (default 2); exceeded budget converts
1135
+ * the string return to a forced abort.
1136
+ * - `{abort: true, reason}` → preventContinuation / halt-and-surface.
1137
+ * Run returns immediately with `output = reason` and
1138
+ * `stoppedByHook = true`. assertTerminal still fires before the
1139
+ * return so invariant violations on the halted state surface
1140
+ * normally.
1141
+ *
1142
+ * Errors thrown by the hook are caught and treated as `undefined`
1143
+ * (fail-open). A span is emitted for observability. Matches the
1144
+ * `compactionHook` failure semantics — a buggy hook must never
1145
+ * abort the run.
1146
+ *
1147
+ * Design reference: claudecode `query.ts:1282-1305` blockingErrors +
1148
+ * `query.ts:1278` preventContinuation. Generalizes the deterministic
1149
+ * shell-script Stop hook surface to an LLM-driven Sidecar Verifier
1150
+ * (the v0.7.45 first consumer; see FEATURE_184 Phase D).
1151
+ */
1152
+ readonly stopHook?: StopHookFn;
1153
+ /**
1154
+ * FEATURE_184 (v0.7.45) — Reanimate budget for `stopHook`. Default 2.
1155
+ *
1156
+ * When `stopHook` returns a string AND `reanimateCount` has already
1157
+ * reached this budget, the string return is forcibly converted to an
1158
+ * abort with reason `"reanimate budget exhausted: <string>"`. Prevents
1159
+ * unbounded reanimate loops when the hook + model disagree on
1160
+ * completion forever.
1161
+ */
1162
+ readonly stopHookReanimateBudget?: number;
1093
1163
  }
1164
+ /**
1165
+ * FEATURE_184 (v0.7.45) — Stop hook context handed to the caller's
1166
+ * `stopHook` when the model terminates a turn text-only.
1167
+ */
1168
+ interface StopHookContext {
1169
+ /** Transcript snapshot at the moment the hook fires. Includes the
1170
+ * just-pushed final assistant message. Readonly — the hook must not
1171
+ * mutate; to influence the run return a `string` (reanimate) or
1172
+ * `{abort, reason}` instead. */
1173
+ readonly transcript: readonly AgentMessage[];
1174
+ /** Convenience field: the final assistant message's text content. */
1175
+ readonly lastAssistantText: string;
1176
+ /** Why the turn ended. For Phase A this is always `'natural-end'`
1177
+ * (model emitted no `tool_use`). Future signal sources (explicit
1178
+ * COMPLETE protocol emission, harness-injected stop) can extend
1179
+ * the union without breaking existing hooks. */
1180
+ readonly signal: 'natural-end';
1181
+ /** How many times the hook has already reanimated this run. Starts
1182
+ * at 0; incremented after each `string` return. Hooks can use this
1183
+ * for telemetry but enforcement is Runner-side. */
1184
+ readonly reanimateCount: number;
1185
+ /** Total reanimate budget for this run (`stopHookReanimateBudget`
1186
+ * or default 2). Exposed for transparency. */
1187
+ readonly reanimateBudget: number;
1188
+ }
1189
+ /**
1190
+ * FEATURE_184 (v0.7.45) — Stop hook return surface.
1191
+ */
1192
+ type StopHookResult = undefined | string | {
1193
+ readonly abort: true;
1194
+ readonly reason: string;
1195
+ };
1196
+ /**
1197
+ * FEATURE_184 (v0.7.45) — Stop hook signature.
1198
+ */
1199
+ type StopHookFn = (ctx: StopHookContext) => StopHookResult | Promise<StopHookResult>;
1094
1200
  /**
1095
1201
  * Result returned by `Runner.run`.
1096
1202
  */
@@ -1099,6 +1205,12 @@ interface RunResult<TData = unknown> {
1099
1205
  readonly messages: readonly AgentMessage[];
1100
1206
  readonly sessionId?: string;
1101
1207
  readonly data?: TData;
1208
+ /** FEATURE_184 (v0.7.45): `true` when the run terminated because
1209
+ * the caller's `stopHook` returned `{abort: true}` OR because the
1210
+ * hook's `string` return exceeded `stopHookReanimateBudget`. The
1211
+ * abort reason is in `output`. Sidecar Verifier sets this when it
1212
+ * outputs a `blocked` verdict (halt + surface to user). */
1213
+ readonly stoppedByHook?: boolean;
1102
1214
  }
1103
1215
  /**
1104
1216
  * Stream events emitted by `Runner.runStream`. The event surface is
@@ -1203,6 +1315,112 @@ declare class Runner {
1203
1315
  /** @internal Exposed so preset dispatchers can extract the assistant text from a KodaXResult. */
1204
1316
  declare function extractAssistantTextFromMessage(message: AgentMessage): string;
1205
1317
 
1318
+ /**
1319
+ * v0.7.35.1 FEATURE_145 — Agent config home, 3-tier resolution.
1320
+ *
1321
+ * Centralizes the user-config directory used to be hardcoded across
1322
+ * ~30 sites in 6 packages as `path.join(os.homedir(), '.kodax', ...)`.
1323
+ * That pattern had two problems:
1324
+ *
1325
+ * 1. **Drift**: each new caller in a future feature was a fresh
1326
+ * hardcode site; nothing stopped a caller from using the wrong
1327
+ * string (`'kodax'` instead of `'.kodax'`, etc.).
1328
+ * 2. **Substrate consumer coupling**: when `@kodax-ai/agent` is reused
1329
+ * by a downstream agent (e.g. `@kodax-ai/ops-agent`,
1330
+ * `@kodax-ai/data-analysis-agent`), there was no way to redirect the
1331
+ * runtime config dir — every derivative agent was forced to
1332
+ * share the `~/.kodax/` namespace.
1333
+ *
1334
+ * The helper exposes a 3-tier priority chain:
1335
+ *
1336
+ * 1. **Programmatic override** via {@link setAgentConfigHome} —
1337
+ * highest priority. Substrate consumers call this once at boot,
1338
+ * before any subsystem reads the path.
1339
+ * 2. **`KODAX_HOME` env var** — middle priority. Used by shell / CI /
1340
+ * test isolation / multi-tenant shared machines. (Already honored
1341
+ * historically by `@kodax-ai/llm/src/reasoning-overrides.ts`; this
1342
+ * helper makes it the canonical path for all packages.)
1343
+ * 3. **`~/.kodax/`** — lowest priority. Default for the standalone
1344
+ * kodax CLI. With DI not set + env not set, the resolver returns
1345
+ * the same byte sequence as the prior hardcoded
1346
+ * `path.join(os.homedir(), '.kodax')` calls — so the migration
1347
+ * from hardcoded sites to this helper is byte-equivalent for the
1348
+ * existing user base.
1349
+ *
1350
+ * Why a process-level singleton (and not per-call DI):
1351
+ * the ~30 fs callsites are buried in library helpers (construction /
1352
+ * mcp catalog / oauth tokens / paste-cache etc.). Threading a
1353
+ * `configHome` parameter through every helper would change ~50
1354
+ * function signatures, and every caller would have to remember to
1355
+ * thread it — a single forgotten thread silently falls back to
1356
+ * default. Singleton matches the `process.env.NODE_ENV` pattern: a
1357
+ * process really has a single config home (no legitimate use case
1358
+ * for a process to interleave reads/writes against `~/.kodax/` AND
1359
+ * `~/.opsagent/` simultaneously).
1360
+ *
1361
+ * NOT migrated:
1362
+ * - `@kodax-ai/llm/src/reasoning-overrides.ts:49` keeps its inline
1363
+ * `process.env.KODAX_HOME ?? path.join(os.homedir(), '.kodax')`
1364
+ * fallback because moving it to this helper would create an
1365
+ * `@kodax-ai/llm → @kodax-ai/agent` dependency cycle (agent already
1366
+ * imports ai). The two implementations have identical observable
1367
+ * behavior at the env / default tiers; the programmatic override
1368
+ * tier doesn't apply to ai-layer code.
1369
+ * - **Project-relative** `.kodax/` paths (e.g. `path.join(projectRoot,
1370
+ * '.kodax', 'AGENTS.md')`) are NOT migrated — those name a
1371
+ * different concept (per-project config) and use a different root.
1372
+ * - **CWD-relative** subpath constants like `path.join('.kodax',
1373
+ * 'constructed', '_audit.jsonl')` (joined with a project root by
1374
+ * the caller) are likewise project-scoped and stay as-is.
1375
+ */
1376
+ /**
1377
+ * Set the agent config home programmatically. Highest priority in
1378
+ * {@link getAgentConfigHome}'s 3-tier chain.
1379
+ *
1380
+ * Substrate consumers (e.g. an agent built on top of `@kodax-ai/agent`)
1381
+ * should call this once at process boot, before any subsystem reads
1382
+ * the path. Pass `undefined` to reset (used in tests).
1383
+ */
1384
+ declare function setAgentConfigHome(path: string | undefined): void;
1385
+ /**
1386
+ * Resolve the agent runtime config home directory.
1387
+ *
1388
+ * Priority (high → low):
1389
+ * 1. Programmatic override via {@link setAgentConfigHome}
1390
+ * 2. `KODAX_HOME` env var
1391
+ * 3. `~/.kodax` (hardcoded default)
1392
+ */
1393
+ declare function getAgentConfigHome(): string;
1394
+ /**
1395
+ * Resolve a sub-path under the agent config home.
1396
+ *
1397
+ * Equivalent to `path.join(getAgentConfigHome(), ...segments)` but
1398
+ * shorter at every callsite (which is the entire point of the helper —
1399
+ * 30 callsites of `path.join(os.homedir(), '.kodax', x, y)` collapse to
1400
+ * 30 callsites of `getAgentConfigPath(x, y)`).
1401
+ */
1402
+ declare function getAgentConfigPath(...segments: string[]): string;
1403
+ /**
1404
+ * v0.7.42 — Namespaced data directory for third-party apps embedding the
1405
+ * KodaX SDK (e.g. `KodaX Space` desktop client, IDE extensions).
1406
+ *
1407
+ * Returns `${getAgentConfigHome()}/apps/<appId>/` and creates the directory
1408
+ * if missing. Provides a coordination point so multiple SDK consumers can
1409
+ * share `~/.kodax/` without colliding on path conventions.
1410
+ *
1411
+ * Constraints:
1412
+ * - `appId` must match `^[a-z][a-z0-9-]{1,31}$` (lowercase kebab, 2–32 chars,
1413
+ * no dots, no slashes, no underscores) — keeps the directory name safe
1414
+ * across all filesystems and prevents `../` traversal.
1415
+ * - Reserved prefixes (`kodax`, `kodax-*`) are rejected to leave room
1416
+ * for first-party feature directories that may collide later.
1417
+ *
1418
+ * The convention is intentionally light — no central registry, no manifest.
1419
+ * Apps owning their data dir means SDK upgrades cannot trample on third-party
1420
+ * state. Apps are responsible for migration/cleanup within their own subtree.
1421
+ */
1422
+ declare function getAppDataDir(appId: string): string;
1423
+
1206
1424
  /**
1207
1425
  * History cleanup middleware — CAP-002
1208
1426
  *
@@ -1262,5 +1480,304 @@ declare function validateAndFixToolHistory(messages: KodaXMessage[]): KodaXMessa
1262
1480
  */
1263
1481
  declare function cleanupIncompleteToolCalls(messages: KodaXMessage[]): KodaXMessage[];
1264
1482
 
1265
- export { cleanupIncompleteToolCalls as $, DEFAULT_SYSTEM_CAP as D, Runner as G, KODAX_API_MIN_INTERVAL as K, PROMISE_PATTERN as P, _resetPresetDispatchers as Y, buildSystemPrompt as Z, _resetAdmittedAgentBindings as _, countTokens as a0, createInMemorySession as a1, createInvariantSessionForAgent as a2, detectInstructionsInjection as a3, estimateTokens as a4, extractAssistantTextFromMessage as a5, getAdmittedAgentBindings as a6, registerPresetDispatcher as a7, runAdmissionAudit as a8, setAdmittedAgentBindings as a9, validateAndFixToolHistory as aa, DefaultSummaryCompaction as h, InvariantSession as m, KODAX_DEFAULT_TIMEOUT as n, KODAX_HARD_TIMEOUT as o, KODAX_MAX_INCOMPLETE_RETRIES as p, KODAX_MAX_MAXTOKENS_RETRIES as q, KODAX_MAX_RETRIES as r, KODAX_MAX_TOKENS as s, KODAX_RETRY_BASE_DELAY as t, KODAX_STAGGER_DELAY as u };
1266
- export type { AdmissionAuditOptions as A, RunEvent as B, CompactionContext as C, RunOptions as E, RunResult as F, RunnerEvent as H, InMemorySessionOptions as I, SessionDispatchResult as J, SessionEntry as L, ManifestPatch as M, SessionExtension as N, ObserveCtx as O, QualityInvariant as Q, ReadonlyMutationTracker as R, Session as S, SessionForkOptions as T, SystemCap as U, TerminalCtx as V, ToolCapability as W, ToolPermission as X, AdmissionCtx as a, AdmissionVerdict as b, AdmittedHandle as c, AgentManifest as d, CompactionEntry as e, CompactionEntryPayload as f, CompactionPolicy as g, DefaultSummaryCompactionOptions as i, Deliverable as j, InvariantId as k, InvariantResult as l, MessageEntry as v, PolicyCompactionResult as w, PresetDispatcher as x, PresetTracingContext as y, ReadonlyRecorder as z };
1483
+ /**
1484
+ * LineageExtension SessionExtension façade over lineage semantics.
1485
+ *
1486
+ * FEATURE_081 (v0.7.23): expresses today's `KodaXSessionLineage` operations
1487
+ * (label, rewind, compaction ledger, branch summary) as a
1488
+ * `SessionExtension` over the base `Session` primitive.
1489
+ *
1490
+ * FEATURE_082 (v0.7.24): moved from `@kodax-ai/coding/src/extensions/lineage.ts`
1491
+ * to this package. Depends on `../index.js` for `Session` / `SessionEntry` /
1492
+ * `SessionExtension` (Layer A primitives — extracted to `@kodax-ai/core` in
1493
+ * FEATURE_082, merged back into `../index.js` in v0.7.35.1 FEATURE_142).
1494
+ * `@kodax-ai/coding` keeps a barrel re-export.
1495
+ *
1496
+ * Scope:
1497
+ * - Declare the extension object.
1498
+ * - Implement `label` and `attachArtifact` operators that append standard
1499
+ * entries to a Session.
1500
+ * - Implement a `buildLineageTree` reducer that projects an entry stream
1501
+ * back to a navigable tree.
1502
+ * - NOT re-implemented here: `branch`, `rewind`, full compaction. Those
1503
+ * stay in `../index.js/session-lineage.ts` for coding-preset use; the
1504
+ * `LineageCompaction` policy in this package is the thin wrapper that
1505
+ * adapts them to the Layer A `CompactionPolicy` contract.
1506
+ */
1507
+
1508
+ /**
1509
+ * Entry types claimed by `LineageExtension`. Mirrors the legacy
1510
+ * `KodaXSessionEntry` tagged union plus a `rewind_marker` placeholder (the
1511
+ * legacy lineage records rewinds via `activeEntryId` mutation; Session is
1512
+ * linear, so a marker entry is the equivalent).
1513
+ */
1514
+ declare const LINEAGE_ENTRY_TYPES: readonly ["message", "label", "compaction", "branch_summary", "archive_marker", "rewind_marker", "artifact_ledger"];
1515
+ type LineageEntryType = (typeof LINEAGE_ENTRY_TYPES)[number];
1516
+ /**
1517
+ * Payload shape for a `label` entry. Mirrors
1518
+ * `KodaXSessionLabelEntry.targetId`/`label` fields on the legacy lineage.
1519
+ */
1520
+ interface LineageLabelPayload {
1521
+ readonly targetId: string;
1522
+ readonly label?: string;
1523
+ }
1524
+ /**
1525
+ * Payload shape for an `artifact_ledger` entry. Mirrors a minimal subset of
1526
+ * `KodaXSessionArtifactLedgerEntry`; full semantic fidelity is kept on the
1527
+ * legacy side for now and normalised in FEATURE_082.
1528
+ */
1529
+ interface LineageArtifactLedgerPayload {
1530
+ readonly ref: string;
1531
+ readonly kind?: string;
1532
+ readonly summary?: string;
1533
+ }
1534
+ /**
1535
+ * Projected tree node. Mirrors the navigation shape of
1536
+ * `KodaXSessionTreeNode` from `../index.js/types.ts`, restricted to the
1537
+ * fields the base Session can supply.
1538
+ */
1539
+ interface LineageTreeNode {
1540
+ readonly entry: SessionEntry;
1541
+ readonly children: LineageTreeNode[];
1542
+ readonly label?: string;
1543
+ }
1544
+ /**
1545
+ * The exported extension. Operators write standard-shaped entries; the
1546
+ * reducer projects an entry stream back to a navigable tree.
1547
+ *
1548
+ * Immutability: top-level object, `operators`, and `reducers` are all
1549
+ * frozen. Freezes are shallow — the functions stored inside `operators`
1550
+ * and `reducers` are immutable by nature (closures reference only
1551
+ * module-private state). External code must not mutate the extension;
1552
+ * doing so is a programmer error that the type-level `readonly` already
1553
+ * disallows without a cast.
1554
+ */
1555
+ declare const LineageExtension: SessionExtension;
1556
+
1557
+ /**
1558
+ * LineageCompaction — `CompactionPolicy` adapter for the coding preset's
1559
+ * FEATURE_072 lineage-native compaction runtime.
1560
+ *
1561
+ * FEATURE_082 (v0.7.24): introduced alongside the lineage extraction so the
1562
+ * coding preset can implement `CompactionPolicy` without re-implementing the
1563
+ * compaction loop. The actual compaction runtime (microcompaction, post-
1564
+ * compact reconstruction, summary generation) stays in
1565
+ * `../index.js/src/compaction/` until FEATURE_084 (v0.7.26) consolidates it.
1566
+ *
1567
+ * Usage (inside @kodax-ai/coding):
1568
+ *
1569
+ * const policy = new LineageCompaction({
1570
+ * shouldCompact: (session, used, budget) => runFeature072Heuristic(used, budget),
1571
+ * compact: async (session, ctx) => runFeature072Compaction(session, ctx),
1572
+ * });
1573
+ *
1574
+ * The injected delegates keep this package free of coding-specific imports,
1575
+ * preserving the dependency direction
1576
+ * `@kodax-ai/coding -> @kodax-ai/session-lineage -> ../index.js`.
1577
+ */
1578
+
1579
+ /**
1580
+ * Delegates required to implement `LineageCompaction`. The coding preset
1581
+ * supplies implementations that bridge to the existing FEATURE_072 code
1582
+ * paths.
1583
+ */
1584
+ interface LineageCompactionDelegates {
1585
+ readonly shouldCompact: (session: Session, tokensUsed: number, budget: number) => boolean;
1586
+ readonly compact: (session: Session, ctx: CompactionContext) => Promise<PolicyCompactionResult>;
1587
+ readonly restore?: (session: Session, hint: unknown) => Promise<void>;
1588
+ }
1589
+ /**
1590
+ * `CompactionPolicy` implementation that preserves FEATURE_072 lineage-native
1591
+ * compaction semantics by delegating to injected coding-preset functions.
1592
+ */
1593
+ declare class LineageCompaction implements CompactionPolicy {
1594
+ readonly name = "lineage-compaction";
1595
+ private readonly delegates;
1596
+ constructor(delegates: LineageCompactionDelegates);
1597
+ shouldCompact(session: Session, tokensUsed: number, budget: number): boolean;
1598
+ compact(session: Session, ctx: CompactionContext): Promise<PolicyCompactionResult>;
1599
+ restore(session: Session, hint: unknown): Promise<void>;
1600
+ }
1601
+
1602
+ /**
1603
+ * ../index.js Session
1604
+ *
1605
+ * 会话管理 - Session ID 生成和消息处理
1606
+ */
1607
+
1608
+ /**
1609
+ * 生成会话 ID
1610
+ * 格式: YYYYMMDD_HHMMSS
1611
+ */
1612
+ declare function generateSessionId(): Promise<string>;
1613
+ /**
1614
+ * 从消息中提取标题
1615
+ * 取第一条用户消息的前50个字符
1616
+ */
1617
+ declare function extractTitleFromMessages(messages: KodaXMessage[]): string;
1618
+
1619
+ type NavigableSessionEntry = Exclude<KodaXSessionEntry, KodaXSessionLabelEntry>;
1620
+ /**
1621
+ * Reconcile a linear message list against an existing lineage tree.
1622
+ *
1623
+ * Existing matching entries are reused when possible, and only the missing
1624
+ * tail is appended as new message entries.
1625
+ */
1626
+ declare function createSessionLineage(messages: KodaXMessage[], previous?: KodaXSessionLineage): KodaXSessionLineage;
1627
+ /**
1628
+ * Walk the lineage from a target entry back to the root.
1629
+ *
1630
+ * Traversal stops safely if malformed data introduces a parent cycle.
1631
+ */
1632
+ declare function getSessionLineagePath(lineage: KodaXSessionLineage, targetId?: string | null): NavigableSessionEntry[];
1633
+ /**
1634
+ * Build the effective LLM-visible message context for the active lineage path.
1635
+ *
1636
+ * FEATURE_072: for non-rewind compaction entries that carry
1637
+ * `postCompactAttachments`, the slicer inlines attachments immediately after
1638
+ * the summary. `getContextMessagesForEntry` stays 1-to-1 — attachments are a
1639
+ * slicer-layer concern, which preserves the contract
1640
+ * `entryMatchesContextMessage` and FEATURE_073's future firstKeptEntryId-based
1641
+ * slicing both depend on.
1642
+ */
1643
+ declare function getSessionMessagesFromLineage(lineage: KodaXSessionLineage, targetId?: string | null): KodaXMessage[];
1644
+ /**
1645
+ * Resolve an entry selector using either a direct entry id or the latest label.
1646
+ */
1647
+ declare function resolveSessionLineageTarget(lineage: KodaXSessionLineage, selector: string): NavigableSessionEntry | undefined;
1648
+ /**
1649
+ * Move the active leaf to a selected target, optionally appending a
1650
+ * branch-summary node that captures the abandoned path.
1651
+ */
1652
+ declare function setSessionLineageActiveEntry(lineage: KodaXSessionLineage, selector: string, options?: KodaXSessionNavigationOptions): KodaXSessionLineage | null;
1653
+ /**
1654
+ * Append a label change entry that bookmarks a lineage node.
1655
+ */
1656
+ declare function appendSessionLineageLabel(lineage: KodaXSessionLineage, selector: string, label?: string): KodaXSessionLineage | null;
1657
+ /**
1658
+ * Apply a compaction event to the lineage.
1659
+ *
1660
+ * FEATURE_072 signature change: `keptMessages` (the post-summary tail that
1661
+ * will become lineage entries) and `postCompactAttachments` (ledger +
1662
+ * file-content messages that live on the CompactionEntry itself) are now
1663
+ * separate parameters. The kept tail MUST NOT include attachments — otherwise
1664
+ * they would be double-stored (once as message entries in lineage, once on
1665
+ * the compaction entry). Phase A keeps `postCompactAttachments` optional so
1666
+ * current callers that pass `[]` (or omit it) behave identically to today.
1667
+ * Phase B migrates callers to supply real attachments.
1668
+ */
1669
+ declare function applySessionCompaction(lineage: KodaXSessionLineage | undefined, compactedMessages: KodaXMessage[], anchor: {
1670
+ summary: string;
1671
+ tokensBefore?: number;
1672
+ tokensAfter?: number;
1673
+ artifactLedgerId?: string;
1674
+ reason?: string;
1675
+ details?: KodaXJsonValue | CompactionDetails;
1676
+ memorySeed?: KodaXCompactMemorySeed;
1677
+ }, postCompactAttachments?: readonly KodaXMessage[]): KodaXSessionLineage;
1678
+ /**
1679
+ * FEATURE_072 §7a: reconcile lineage after graceful-degradation trimming.
1680
+ *
1681
+ * Unlike `applySessionCompaction` (which creates a new island with a summary
1682
+ * CompactionEntry), graceful degradation is atomic-block trimming — no LLM
1683
+ * summary, no ledger re-injection. Routing it through `applySessionCompaction`
1684
+ * would produce a degenerate CompactionEntry with `summary: ''` that pollutes
1685
+ * the lineage view and session-tree UI.
1686
+ *
1687
+ * Instead, `applyLineageTruncation` reconciles the lineage against the trimmed
1688
+ * flat messages via `createSessionLineage`, which will:
1689
+ * - Match surviving messages to existing entries (reference or fingerprint)
1690
+ * - Drop unmatched entries from the active path
1691
+ * Fingerprint lookup handles the "trimmed tool_result content changed" case:
1692
+ * the trimmed message gets a new entry id under the same parent chain.
1693
+ *
1694
+ * This is distinct from `applySessionCompaction`: no new CompactionEntry is
1695
+ * appended, no summary is written, no island root is created. The lineage
1696
+ * stays on the same island; only the tail shape changes.
1697
+ *
1698
+ * Reserved for a future caller (v0.7.20 Phase C / v0.7.25 FEATURE_073). Phase B
1699
+ * defines the helper; no production caller yet.
1700
+ */
1701
+ declare function applyLineageTruncation(lineage: KodaXSessionLineage | undefined, trimmedMessages: KodaXMessage[]): KodaXSessionLineage;
1702
+ /**
1703
+ * Rewind the current session lineage to a target entry, truncating all entries after it.
1704
+ * Records a rewind event in the lineage for auditability.
1705
+ * Returns null if targetEntryId is not found.
1706
+ *
1707
+ * @param lineage - The session lineage to rewind
1708
+ * @param targetEntryId - The entry ID to rewind to (inclusive)
1709
+ * @returns A new lineage with entries truncated after the target, or null if target not found
1710
+ */
1711
+ /**
1712
+ * Find the entry ID of the second-to-last user message in the lineage.
1713
+ * Used by `/rewind` (no argument) to go back one conversational turn.
1714
+ * Returns null if fewer than 2 user messages exist.
1715
+ */
1716
+ declare function findPreviousUserEntryId(lineage: KodaXSessionLineage): string | null;
1717
+ declare function rewindSessionLineage(lineage: KodaXSessionLineage, targetEntryId: string): KodaXSessionLineage | null;
1718
+ declare function forkSessionLineage(lineage: KodaXSessionLineage, selector?: string): KodaXSessionLineage | null;
1719
+ /**
1720
+ * Convert a lineage into a nested tree structure for UI presentation.
1721
+ */
1722
+ declare function buildSessionTree(lineage: KodaXSessionLineage): KodaXSessionTreeNode[];
1723
+ /**
1724
+ * Count the effective context messages on the active lineage path.
1725
+ */
1726
+ declare function countActiveLineageMessages(lineage: KodaXSessionLineage): number;
1727
+ /**
1728
+ * Archive message entries from old "islands" (disconnected subtrees).
1729
+ *
1730
+ * Each compaction entry has parentId: null, creating an independent island.
1731
+ * The active leaf lives in one island (the "current" island). All other
1732
+ * islands are considered "old" and eligible for archival.
1733
+ *
1734
+ * A "preserve closure" is computed first:
1735
+ * - All entries in the current island (active path + recent branches)
1736
+ * - Label targets and their ancestor chains
1737
+ * - Non-message entries and their ancestor chains (prevents tree drift)
1738
+ *
1739
+ * Only entries outside the preserve closure are archived.
1740
+ */
1741
+ declare function archiveOldIslands(lineage: KodaXSessionLineage): {
1742
+ slimmedLineage: KodaXSessionLineage;
1743
+ archivedEntries: KodaXSessionEntry[];
1744
+ archivedCount: number;
1745
+ archiveBatchId: string;
1746
+ };
1747
+
1748
+ /**
1749
+ * ../../index.js File Tracking — artifactLedger extraction.
1750
+ *
1751
+ * FEATURE_185 (v0.7.42) extends the previous input-only extractor to also
1752
+ * read each tool_use's matching tool_result, enriching `metadata` with parsed
1753
+ * hits / matchedPaths / exitCode / tail. Pipeline:
1754
+ *
1755
+ * Round end (REPL: repl.ts:1279/1371)
1756
+ * → extractArtifactLedger(result.messages)
1757
+ * → tool_result still raw (top-of-loop microcompact hasn't run on these)
1758
+ * → buildArtifactEntry parses result content into metadata
1759
+ * → mergeArtifactLedger commits enrichment to context.artifactLedger
1760
+ * → storage.save persists the enriched ledger
1761
+ *
1762
+ * Top-of-loop microcompact (run-substrate.ts:621, iteration N+1)
1763
+ * → clears tool_result.content older than maxAge to `[Cleared: ...]`
1764
+ *
1765
+ * Compaction time (compaction.ts:257)
1766
+ * → extractArtifactLedger(toProcess) re-runs on cleared messages
1767
+ * → buildArtifactEntry's parsers refuse `[Cleared: ...]` → no fresh hits
1768
+ * → mergeArtifactLedger preserves the round-end enrichment via
1769
+ * per-key non-empty preference (see `mergeLedgerMetadata`).
1770
+ *
1771
+ * The metadata-aware merge is the keystone — without it, every compaction
1772
+ * would silently downgrade ledger entries to input-only. End-to-end
1773
+ * preservation is exercised by the "end-to-end enrichment survives
1774
+ * microcompact" tests in file-tracker.test.ts.
1775
+ */
1776
+
1777
+ declare function extractFileOps(messages: KodaXMessage[]): FileOperations;
1778
+ declare function mergeFileOps(ops1: FileOperations, ops2: FileOperations): FileOperations;
1779
+ declare function extractArtifactLedger(messages: KodaXMessage[]): KodaXSessionArtifactLedgerEntry[];
1780
+ declare function mergeArtifactLedger(existing: KodaXSessionArtifactLedgerEntry[], next: KodaXSessionArtifactLedgerEntry[]): KodaXSessionArtifactLedgerEntry[];
1781
+
1782
+ export { DEFAULT_SYSTEM_CAP as D, KODAX_API_MIN_INTERVAL as K, LINEAGE_ENTRY_TYPES as L, PROMISE_PATTERN as P, Runner as V, generateSessionId as aA, getAdmittedAgentBindings as aB, getAgentConfigHome as aC, getAgentConfigPath as aD, getAppDataDir as aE, getSessionLineagePath as aF, getSessionMessagesFromLineage as aG, mergeArtifactLedger as aH, mergeFileOps as aI, registerPresetDispatcher as aJ, resolveSessionLineageTarget as aK, rewindSessionLineage as aL, runAdmissionAudit as aM, setAdmittedAgentBindings as aN, setAgentConfigHome as aO, setSessionLineageActiveEntry as aP, validateAndFixToolHistory as aQ, Tracer as aa, _resetAdmittedAgentBindings as ac, _resetPresetDispatchers as ad, appendSessionLineageLabel as ae, applyLineageTruncation as af, applySessionCompaction as ag, archiveOldIslands as ah, buildSessionTree as ai, buildSystemPrompt as aj, cleanupIncompleteToolCalls as ak, countActiveLineageMessages as al, countTokens as am, createInMemorySession as an, createInvariantSessionForAgent as ao, createSessionLineage as ap, createTrace as aq, defaultTracer as ar, detectInstructionsInjection as as, estimateTokens as at, extractArtifactLedger as au, extractAssistantTextFromMessage as av, extractFileOps as aw, extractTitleFromMessages as ax, findPreviousUserEntryId as ay, forkSessionLineage as az, DefaultSummaryCompaction as h, InvariantSession as m, KODAX_DEFAULT_TIMEOUT as n, KODAX_HARD_TIMEOUT as o, KODAX_MAX_INCOMPLETE_RETRIES as p, KODAX_MAX_MAXTOKENS_RETRIES as q, KODAX_MAX_RETRIES as r, KODAX_MAX_TOKENS as s, KODAX_RETRY_BASE_DELAY as t, KODAX_STAGGER_DELAY as u, LineageCompaction as w, LineageExtension as z };
1783
+ export type { SessionForkOptions as $, AdmissionAuditOptions as A, LineageLabelPayload as B, CompactionContext as C, LineageTreeNode as E, MessageEntry as F, PolicyCompactionResult as G, PresetDispatcher as H, InMemorySessionOptions as I, PresetTracingContext as J, ManifestPatch as M, ReadonlyRecorder as N, ObserveCtx as O, QualityInvariant as Q, ReadonlyMutationTracker as R, RunEvent as S, RunOptions as T, RunResult as U, RunnerEvent as W, Session as X, SessionDispatchResult as Y, SessionEntry as Z, SessionExtension as _, AdmissionCtx as a, StartTraceOptions as a0, StopHookContext as a1, StopHookFn as a2, StopHookResult as a3, SystemCap as a4, TerminalCtx as a5, ToolCapability as a6, ToolPermission as a7, Trace as a8, TraceOptions as a9, TracerOptions as ab, AdmissionVerdict as b, AdmittedHandle as c, AgentManifest as d, CompactionEntry as e, CompactionEntryPayload as f, CompactionPolicy as g, DefaultSummaryCompactionOptions as i, Deliverable as j, InvariantId as k, InvariantResult as l, LineageArtifactLedgerPayload as v, LineageCompactionDelegates as x, LineageEntryType as y };