@kodax-ai/kodax 0.7.41 → 0.7.42

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 +89 -1
  2. package/README.md +129 -232
  3. package/README_CN.md +128 -253
  4. package/dist/chunks/chunk-3RKBXWZS.js +2 -0
  5. package/dist/chunks/chunk-7JLYVWAF.js +1033 -0
  6. package/dist/chunks/chunk-CD3R5YBH.js +16 -0
  7. package/dist/chunks/chunk-DKXUY5F2.js +209 -0
  8. package/dist/chunks/chunk-HMYEQJGT.js +31 -0
  9. package/dist/chunks/{chunk-6OB4AJOM.js → chunk-IYJ5EPRV.js} +1 -1
  10. package/dist/chunks/chunk-KUX5LRPP.js +2 -0
  11. package/dist/chunks/{chunk-EQ5DGS2W.js → chunk-OWSKU55I.js} +5 -6
  12. package/dist/chunks/chunk-ZZ4KRK2B.js +465 -0
  13. package/dist/chunks/compaction-config-FIFFP4FT.js +2 -0
  14. package/dist/chunks/{construction-bootstrap-HBCWJFHC.js → construction-bootstrap-J2WOCYEK.js} +1 -1
  15. package/dist/chunks/dist-2ZHWDXMQ.js +2 -0
  16. package/dist/chunks/dist-W4CJWLIH.js +2 -0
  17. package/dist/chunks/utils-A5MWDTWZ.js +2 -0
  18. package/dist/index.d.ts +15 -10
  19. package/dist/index.js +5 -5
  20. package/dist/kodax_cli.js +841 -833
  21. package/dist/sdk-agent.d.ts +9 -93
  22. package/dist/sdk-agent.js +1 -1
  23. package/dist/sdk-coding.d.ts +315 -250
  24. package/dist/sdk-coding.js +1 -1
  25. package/dist/sdk-llm.d.ts +6 -5
  26. package/dist/sdk-llm.js +1 -1
  27. package/dist/sdk-mcp.d.ts +17 -0
  28. package/dist/sdk-mcp.js +2 -0
  29. package/dist/sdk-repl.d.ts +342 -10
  30. package/dist/sdk-repl.js +2 -1
  31. package/dist/sdk-session.d.ts +164 -0
  32. package/dist/sdk-session.js +2 -0
  33. package/dist/sdk-skills.d.ts +72 -4
  34. package/dist/sdk-skills.js +1 -1
  35. package/dist/types-chunks/{bash-prefix-extractor.d-B2iliwdi.d.ts → bash-prefix-extractor.d-CkhaqKkg.d.ts} +237 -98
  36. package/dist/types-chunks/capability.d-3C62G8Eq.d.ts +39 -0
  37. package/dist/types-chunks/config.d-BfJUXxC0.d.ts +41 -0
  38. package/dist/types-chunks/{cost-tracker.d-C4dMlQuV.d.ts → cost-tracker.d-B6vMoLLF.d.ts} +20 -2
  39. package/dist/types-chunks/{history-cleanup.d-q1vAvCss.d.ts → history-cleanup.d-DznrzEiU.d.ts} +221 -12
  40. package/dist/types-chunks/{instance-discovery.d-DZhp77vb.d.ts → instance-discovery.d-BsKnIwpg.d.ts} +31 -258
  41. package/dist/types-chunks/{resolver.d-BwD6TKz7.d.ts → resolver.d-DX9au4NJ.d.ts} +4 -3
  42. package/dist/types-chunks/session-storage.d-Cci897iM.d.ts +68 -0
  43. package/dist/types-chunks/{storage.d-Bv9T99Qu.d.ts → storage.d-Bc5DoAwp.d.ts} +17 -69
  44. package/dist/types-chunks/transport.d-DuyjG30t.d.ts +180 -0
  45. package/dist/types-chunks/{capability.d-BxNgd1-c.d.ts → types.d-B1uGoVTE.d.ts} +72 -40
  46. package/dist/types-chunks/types.d-mM8vqvhT.d.ts +254 -0
  47. package/package.json +9 -1
  48. package/dist/chunks/chunk-5TFLMGER.js +0 -2
  49. package/dist/chunks/chunk-6QO6HWGU.js +0 -30
  50. package/dist/chunks/chunk-HYWVRTFA.js +0 -1233
  51. package/dist/chunks/chunk-SX2IS5JP.js +0 -16
  52. package/dist/chunks/chunk-ZPJPNLBK.js +0 -462
  53. package/dist/chunks/compaction-config-LT5PEXPT.js +0 -2
  54. package/dist/chunks/dist-M57GIWR4.js +0 -2
  55. package/dist/chunks/dist-V3BS2NKB.js +0 -2
  56. package/dist/chunks/utils-FAFUQJ2A.js +0 -2
@@ -1,5 +1,5 @@
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, x as SpanData, w as Span, y as SpanError, A as Agent, q as RunnerLlmReturn, G as Guardrail, t as RunnerToolObserver } from './instance-discovery.d-BsKnIwpg.js';
3
3
 
4
4
  /**
5
5
  * @kodax-ai/agent Constants
@@ -977,14 +977,34 @@ interface RunOptions {
977
977
  */
978
978
  readonly toolObserver?: RunnerToolObserver;
979
979
  /**
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.
980
+ * Compaction hook. Fires at the TOP of every tool-loop iteration,
981
+ * BEFORE the LLM call. Return the replacement transcript to trigger
982
+ * compaction; return the same array (or undefined) to skip. The Runner
983
+ * owns the transcript mutably, so this is the only point consumers can
984
+ * insert a compacted view before the next provider.stream invocation.
985
+ *
986
+ * **Trigger frequency**: every iteration of every Runner.run() call.
987
+ * - Iteration 0 fires BEFORE the first LLM call (covers idle-yield
988
+ * resume / new user activation where the transcript already exceeds
989
+ * threshold from accumulated prior turns).
990
+ * - Iteration N (N≥1) fires after the previous iteration's tool_result
991
+ * was appended, same "before next LLM call" timing as the legacy
992
+ * post-tool-result firing point.
993
+ * - Text-only iterations are covered: the next Runner.run() invocation
994
+ * (when the user/parent re-engages) runs iter 0 → hook fires before
995
+ * the new LLM call.
996
+ *
997
+ * **Why not after tool_result append (legacy v0.7.26 location)**: that
998
+ * boundary skipped text-only termination — Runner exits at line ~611
999
+ * without firing the hook, so idle-yield + text-only end-of-turn
1000
+ * sessions grew unbounded between checks. claudecode (`query.ts:307-454`),
1001
+ * pi-mono (`agent-session.ts:949`), opencode (`processor.ts:609-613`),
1002
+ * and KodaX SA (`run-substrate.ts:621-627`) all check at the per-LLM-
1003
+ * call boundary. FEATURE_179 (v0.7.42) brought the AMA Runner path
1004
+ * into line — the failure scenario was a Worker session that grew
1005
+ * 165K → 180K through text-only end-of-turn + idle-yield, then
1006
+ * triggered at 181K (61K over the 120K threshold) only after the next
1007
+ * tool call landed.
988
1008
  */
989
1009
  readonly compactionHook?: (transcript: readonly AgentMessage[]) => Promise<readonly AgentMessage[] | undefined>;
990
1010
  /**
@@ -1090,7 +1110,84 @@ interface RunOptions {
1090
1110
  readonly to: Agent;
1091
1111
  readonly iteration: number;
1092
1112
  }) => void | Promise<void>;
1113
+ /**
1114
+ * FEATURE_184 (v0.7.45) — Stop Hook primitive.
1115
+ *
1116
+ * Fires when the model terminates a turn with no `tool_use` blocks
1117
+ * (text-only response). The hook receives the post-output-guardrail
1118
+ * transcript and the final assistant text, and returns one of:
1119
+ *
1120
+ * - `undefined` → accept the termination, fall through to the normal
1121
+ * terminal path (assertTerminal + return). This is the no-op default.
1122
+ * - `string` → "blockingErrors" / reanimate. Runner synthesizes a
1123
+ * `{role: 'user', content: <string>}` message, appends it to the
1124
+ * transcript + session, and continues the loop. Bounded by
1125
+ * `stopHookReanimateBudget` (default 2); exceeded budget converts
1126
+ * the string return to a forced abort.
1127
+ * - `{abort: true, reason}` → preventContinuation / halt-and-surface.
1128
+ * Run returns immediately with `output = reason` and
1129
+ * `stoppedByHook = true`. assertTerminal still fires before the
1130
+ * return so invariant violations on the halted state surface
1131
+ * normally.
1132
+ *
1133
+ * Errors thrown by the hook are caught and treated as `undefined`
1134
+ * (fail-open). A span is emitted for observability. Matches the
1135
+ * `compactionHook` failure semantics — a buggy hook must never
1136
+ * abort the run.
1137
+ *
1138
+ * Design reference: claudecode `query.ts:1282-1305` blockingErrors +
1139
+ * `query.ts:1278` preventContinuation. Generalizes the deterministic
1140
+ * shell-script Stop hook surface to an LLM-driven Sidecar Verifier
1141
+ * (the v0.7.45 first consumer; see FEATURE_184 Phase D).
1142
+ */
1143
+ readonly stopHook?: StopHookFn;
1144
+ /**
1145
+ * FEATURE_184 (v0.7.45) — Reanimate budget for `stopHook`. Default 2.
1146
+ *
1147
+ * When `stopHook` returns a string AND `reanimateCount` has already
1148
+ * reached this budget, the string return is forcibly converted to an
1149
+ * abort with reason `"reanimate budget exhausted: <string>"`. Prevents
1150
+ * unbounded reanimate loops when the hook + model disagree on
1151
+ * completion forever.
1152
+ */
1153
+ readonly stopHookReanimateBudget?: number;
1154
+ }
1155
+ /**
1156
+ * FEATURE_184 (v0.7.45) — Stop hook context handed to the caller's
1157
+ * `stopHook` when the model terminates a turn text-only.
1158
+ */
1159
+ interface StopHookContext {
1160
+ /** Transcript snapshot at the moment the hook fires. Includes the
1161
+ * just-pushed final assistant message. Readonly — the hook must not
1162
+ * mutate; to influence the run return a `string` (reanimate) or
1163
+ * `{abort, reason}` instead. */
1164
+ readonly transcript: readonly AgentMessage[];
1165
+ /** Convenience field: the final assistant message's text content. */
1166
+ readonly lastAssistantText: string;
1167
+ /** Why the turn ended. For Phase A this is always `'natural-end'`
1168
+ * (model emitted no `tool_use`). Future signal sources (explicit
1169
+ * COMPLETE protocol emission, harness-injected stop) can extend
1170
+ * the union without breaking existing hooks. */
1171
+ readonly signal: 'natural-end';
1172
+ /** How many times the hook has already reanimated this run. Starts
1173
+ * at 0; incremented after each `string` return. Hooks can use this
1174
+ * for telemetry but enforcement is Runner-side. */
1175
+ readonly reanimateCount: number;
1176
+ /** Total reanimate budget for this run (`stopHookReanimateBudget`
1177
+ * or default 2). Exposed for transparency. */
1178
+ readonly reanimateBudget: number;
1093
1179
  }
1180
+ /**
1181
+ * FEATURE_184 (v0.7.45) — Stop hook return surface.
1182
+ */
1183
+ type StopHookResult = undefined | string | {
1184
+ readonly abort: true;
1185
+ readonly reason: string;
1186
+ };
1187
+ /**
1188
+ * FEATURE_184 (v0.7.45) — Stop hook signature.
1189
+ */
1190
+ type StopHookFn = (ctx: StopHookContext) => StopHookResult | Promise<StopHookResult>;
1094
1191
  /**
1095
1192
  * Result returned by `Runner.run`.
1096
1193
  */
@@ -1099,6 +1196,12 @@ interface RunResult<TData = unknown> {
1099
1196
  readonly messages: readonly AgentMessage[];
1100
1197
  readonly sessionId?: string;
1101
1198
  readonly data?: TData;
1199
+ /** FEATURE_184 (v0.7.45): `true` when the run terminated because
1200
+ * the caller's `stopHook` returned `{abort: true}` OR because the
1201
+ * hook's `string` return exceeded `stopHookReanimateBudget`. The
1202
+ * abort reason is in `output`. Sidecar Verifier sets this when it
1203
+ * outputs a `blocked` verdict (halt + surface to user). */
1204
+ readonly stoppedByHook?: boolean;
1102
1205
  }
1103
1206
  /**
1104
1207
  * Stream events emitted by `Runner.runStream`. The event surface is
@@ -1203,6 +1306,112 @@ declare class Runner {
1203
1306
  /** @internal Exposed so preset dispatchers can extract the assistant text from a KodaXResult. */
1204
1307
  declare function extractAssistantTextFromMessage(message: AgentMessage): string;
1205
1308
 
1309
+ /**
1310
+ * v0.7.35.1 FEATURE_145 — Agent config home, 3-tier resolution.
1311
+ *
1312
+ * Centralizes the user-config directory used to be hardcoded across
1313
+ * ~30 sites in 6 packages as `path.join(os.homedir(), '.kodax', ...)`.
1314
+ * That pattern had two problems:
1315
+ *
1316
+ * 1. **Drift**: each new caller in a future feature was a fresh
1317
+ * hardcode site; nothing stopped a caller from using the wrong
1318
+ * string (`'kodax'` instead of `'.kodax'`, etc.).
1319
+ * 2. **Substrate consumer coupling**: when `@kodax-ai/agent` is reused
1320
+ * by a downstream agent (e.g. `@kodax-ai/ops-agent`,
1321
+ * `@kodax-ai/data-analysis-agent`), there was no way to redirect the
1322
+ * runtime config dir — every derivative agent was forced to
1323
+ * share the `~/.kodax/` namespace.
1324
+ *
1325
+ * The helper exposes a 3-tier priority chain:
1326
+ *
1327
+ * 1. **Programmatic override** via {@link setAgentConfigHome} —
1328
+ * highest priority. Substrate consumers call this once at boot,
1329
+ * before any subsystem reads the path.
1330
+ * 2. **`KODAX_HOME` env var** — middle priority. Used by shell / CI /
1331
+ * test isolation / multi-tenant shared machines. (Already honored
1332
+ * historically by `@kodax-ai/llm/src/reasoning-overrides.ts`; this
1333
+ * helper makes it the canonical path for all packages.)
1334
+ * 3. **`~/.kodax/`** — lowest priority. Default for the standalone
1335
+ * kodax CLI. With DI not set + env not set, the resolver returns
1336
+ * the same byte sequence as the prior hardcoded
1337
+ * `path.join(os.homedir(), '.kodax')` calls — so the migration
1338
+ * from hardcoded sites to this helper is byte-equivalent for the
1339
+ * existing user base.
1340
+ *
1341
+ * Why a process-level singleton (and not per-call DI):
1342
+ * the ~30 fs callsites are buried in library helpers (construction /
1343
+ * mcp catalog / oauth tokens / paste-cache etc.). Threading a
1344
+ * `configHome` parameter through every helper would change ~50
1345
+ * function signatures, and every caller would have to remember to
1346
+ * thread it — a single forgotten thread silently falls back to
1347
+ * default. Singleton matches the `process.env.NODE_ENV` pattern: a
1348
+ * process really has a single config home (no legitimate use case
1349
+ * for a process to interleave reads/writes against `~/.kodax/` AND
1350
+ * `~/.opsagent/` simultaneously).
1351
+ *
1352
+ * NOT migrated:
1353
+ * - `@kodax-ai/llm/src/reasoning-overrides.ts:49` keeps its inline
1354
+ * `process.env.KODAX_HOME ?? path.join(os.homedir(), '.kodax')`
1355
+ * fallback because moving it to this helper would create an
1356
+ * `@kodax-ai/llm → @kodax-ai/agent` dependency cycle (agent already
1357
+ * imports ai). The two implementations have identical observable
1358
+ * behavior at the env / default tiers; the programmatic override
1359
+ * tier doesn't apply to ai-layer code.
1360
+ * - **Project-relative** `.kodax/` paths (e.g. `path.join(projectRoot,
1361
+ * '.kodax', 'AGENTS.md')`) are NOT migrated — those name a
1362
+ * different concept (per-project config) and use a different root.
1363
+ * - **CWD-relative** subpath constants like `path.join('.kodax',
1364
+ * 'constructed', '_audit.jsonl')` (joined with a project root by
1365
+ * the caller) are likewise project-scoped and stay as-is.
1366
+ */
1367
+ /**
1368
+ * Set the agent config home programmatically. Highest priority in
1369
+ * {@link getAgentConfigHome}'s 3-tier chain.
1370
+ *
1371
+ * Substrate consumers (e.g. an agent built on top of `@kodax-ai/agent`)
1372
+ * should call this once at process boot, before any subsystem reads
1373
+ * the path. Pass `undefined` to reset (used in tests).
1374
+ */
1375
+ declare function setAgentConfigHome(path: string | undefined): void;
1376
+ /**
1377
+ * Resolve the agent runtime config home directory.
1378
+ *
1379
+ * Priority (high → low):
1380
+ * 1. Programmatic override via {@link setAgentConfigHome}
1381
+ * 2. `KODAX_HOME` env var
1382
+ * 3. `~/.kodax` (hardcoded default)
1383
+ */
1384
+ declare function getAgentConfigHome(): string;
1385
+ /**
1386
+ * Resolve a sub-path under the agent config home.
1387
+ *
1388
+ * Equivalent to `path.join(getAgentConfigHome(), ...segments)` but
1389
+ * shorter at every callsite (which is the entire point of the helper —
1390
+ * 30 callsites of `path.join(os.homedir(), '.kodax', x, y)` collapse to
1391
+ * 30 callsites of `getAgentConfigPath(x, y)`).
1392
+ */
1393
+ declare function getAgentConfigPath(...segments: string[]): string;
1394
+ /**
1395
+ * v0.7.42 — Namespaced data directory for third-party apps embedding the
1396
+ * KodaX SDK (e.g. `KodaX Space` desktop client, IDE extensions).
1397
+ *
1398
+ * Returns `${getAgentConfigHome()}/apps/<appId>/` and creates the directory
1399
+ * if missing. Provides a coordination point so multiple SDK consumers can
1400
+ * share `~/.kodax/` without colliding on path conventions.
1401
+ *
1402
+ * Constraints:
1403
+ * - `appId` must match `^[a-z][a-z0-9-]{1,31}$` (lowercase kebab, 2–32 chars,
1404
+ * no dots, no slashes, no underscores) — keeps the directory name safe
1405
+ * across all filesystems and prevents `../` traversal.
1406
+ * - Reserved prefixes (`kodax`, `kodax-*`) are rejected to leave room
1407
+ * for first-party feature directories that may collide later.
1408
+ *
1409
+ * The convention is intentionally light — no central registry, no manifest.
1410
+ * Apps owning their data dir means SDK upgrades cannot trample on third-party
1411
+ * state. Apps are responsible for migration/cleanup within their own subtree.
1412
+ */
1413
+ declare function getAppDataDir(appId: string): string;
1414
+
1206
1415
  /**
1207
1416
  * History cleanup middleware — CAP-002
1208
1417
  *
@@ -1262,5 +1471,5 @@ declare function validateAndFixToolHistory(messages: KodaXMessage[]): KodaXMessa
1262
1471
  */
1263
1472
  declare function cleanupIncompleteToolCalls(messages: KodaXMessage[]): KodaXMessage[];
1264
1473
 
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 };
1474
+ export { _resetAdmittedAgentBindings as $, DEFAULT_SYSTEM_CAP as D, Runner as G, KODAX_API_MIN_INTERVAL as K, PROMISE_PATTERN as P, _resetPresetDispatchers as a0, buildSystemPrompt as a1, cleanupIncompleteToolCalls as a2, countTokens as a3, createInMemorySession as a4, createInvariantSessionForAgent as a5, detectInstructionsInjection as a6, estimateTokens as a7, extractAssistantTextFromMessage as a8, getAdmittedAgentBindings as a9, getAgentConfigHome as aa, getAgentConfigPath as ab, getAppDataDir as ac, registerPresetDispatcher as ad, runAdmissionAudit as ae, setAdmittedAgentBindings as af, setAgentConfigHome as ag, validateAndFixToolHistory as ah, 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 };
1475
+ 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, StopHookContext as U, StopHookFn as V, StopHookResult as W, SystemCap as X, TerminalCtx as Y, ToolCapability as Z, ToolPermission as _, 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 };
@@ -1,255 +1,4 @@
1
- import { o as KodaXMessage, _ as KodaXToolDefinition, G as KodaXReasoningMode, W as KodaXThinkingBlock, J as KodaXRedactedThinkingBlock } from './capability.d-BxNgd1-c.js';
2
-
3
- /**
4
- * @kodax-ai/agent Types
5
- *
6
- * 通用 Agent 类型定义
7
- */
8
-
9
- type KodaXJsonPrimitive = string | number | boolean | null;
10
- type KodaXJsonValue = KodaXJsonPrimitive | KodaXJsonValue[] | {
11
- [key: string]: KodaXJsonValue;
12
- };
13
- /**
14
- * Session error metadata - 会话错误元数据
15
- * Used for error recovery and session cleanup - 用于错误恢复和会话清理
16
- */
17
- interface SessionErrorMetadata {
18
- /** Last error message - 最后的错误消息 */
19
- lastError?: string;
20
- /** Last error timestamp - 最后错误时间戳 */
21
- lastErrorTime?: number;
22
- /** Consecutive error count - 连续错误计数 */
23
- consecutiveErrors: number;
24
- }
25
- interface KodaXExtensionSessionRecord {
26
- id: string;
27
- extensionId: string;
28
- type: string;
29
- ts: number;
30
- data?: KodaXJsonValue;
31
- dedupeKey?: string;
32
- }
33
- type KodaXExtensionSessionState = Record<string, Record<string, KodaXJsonValue>>;
34
- interface KodaXSessionEntryBase {
35
- id: string;
36
- parentId: string | null;
37
- timestamp: string;
38
- }
39
- interface KodaXSessionMessageEntry extends KodaXSessionEntryBase {
40
- type: 'message';
41
- message: KodaXMessage;
42
- }
43
- interface KodaXSessionCompactionEntry extends KodaXSessionEntryBase {
44
- type: 'compaction';
45
- summary: string;
46
- firstKeptEntryId?: string;
47
- tokensBefore?: number;
48
- tokensAfter?: number;
49
- artifactLedgerId?: string;
50
- reason?: string;
51
- details?: KodaXJsonValue;
52
- memorySeed?: KodaXCompactMemorySeed;
53
- /**
54
- * FEATURE_072: post-compact ledger summary + file-content messages that
55
- * are inlined after the compaction summary at slicer time
56
- * (`getSessionMessagesFromLineage`). Stored here so they leave the active
57
- * path automatically when a new compaction entry is appended.
58
- *
59
- * NOTE: attachments are emitted by the slicer, NOT by `getContextMessagesForEntry`
60
- * — preserving the latter's 1-to-1 contract that `entryMatchesContextMessage`
61
- * and FEATURE_073's future slicing both depend on.
62
- */
63
- postCompactAttachments?: readonly KodaXMessage[];
64
- }
65
- interface KodaXSessionBranchSummaryEntry extends KodaXSessionEntryBase {
66
- type: 'branch_summary';
67
- summary: string;
68
- fromId?: string;
69
- details?: KodaXJsonValue;
70
- }
71
- interface KodaXSessionLabelEntry extends KodaXSessionEntryBase {
72
- type: 'label';
73
- targetId: string;
74
- label?: string;
75
- }
76
- interface KodaXSessionArchiveMarkerEntry extends KodaXSessionEntryBase {
77
- type: 'archive_marker';
78
- /** Links to the corresponding batch in the .archive.jsonl sidecar file */
79
- archiveBatchId: string;
80
- /** Number of entries that were archived in this batch */
81
- archivedEntryCount: number;
82
- /** Brief summary of the archived content */
83
- summary: string;
84
- }
85
- type KodaXSessionEntry = KodaXSessionMessageEntry | KodaXSessionCompactionEntry | KodaXSessionBranchSummaryEntry | KodaXSessionLabelEntry | KodaXSessionArchiveMarkerEntry;
86
- interface KodaXSessionArtifactLedgerEntry {
87
- id: string;
88
- kind: 'file_read' | 'file_modified' | 'file_created' | 'file_deleted' | 'path_scope' | 'search_scope' | 'command_scope' | 'check_result' | 'decision' | 'image_input' | 'tombstone';
89
- sourceTool?: string;
90
- action?: string;
91
- target: string;
92
- displayTarget?: string;
93
- summary?: string;
94
- sessionEntryId?: string;
95
- timestamp: string;
96
- metadata?: Record<string, KodaXJsonValue>;
97
- }
98
- interface KodaXCompactMemoryProgress {
99
- completed: string[];
100
- inProgress: string[];
101
- blockers: string[];
102
- }
103
- interface KodaXCompactMemorySeed {
104
- objective?: string;
105
- constraints: string[];
106
- progress: KodaXCompactMemoryProgress;
107
- keyDecisions: string[];
108
- nextSteps: string[];
109
- keyContext: string[];
110
- importantTargets: string[];
111
- tombstones: string[];
112
- }
113
- interface KodaXSessionLineage {
114
- version: 2;
115
- activeEntryId: string | null;
116
- entries: KodaXSessionEntry[];
117
- }
118
- interface KodaXSessionNavigationOptions {
119
- summarizeCurrentBranch?: boolean;
120
- }
121
- interface KodaXSessionTreeNode {
122
- entry: Exclude<KodaXSessionEntry, KodaXSessionLabelEntry>;
123
- children: KodaXSessionTreeNode[];
124
- label?: string;
125
- active: boolean;
126
- }
127
- type KodaXSessionScope = 'user' | 'managed-task-worker';
128
- type KodaXSessionUiHistoryItemType = 'user' | 'assistant' | 'system' | 'thinking' | 'error' | 'event' | 'info' | 'hint';
129
- interface KodaXSessionUiHistoryItem {
130
- type: KodaXSessionUiHistoryItemType;
131
- text: string;
132
- icon?: string;
133
- compactText?: string;
134
- }
135
- type KodaXSessionWorkspaceKind = 'detected' | 'managed';
136
- interface KodaXSessionRuntimeInfo {
137
- canonicalRepoRoot?: string;
138
- workspaceRoot?: string;
139
- executionCwd?: string;
140
- branch?: string;
141
- workspaceKind?: KodaXSessionWorkspaceKind;
142
- }
143
- interface KodaXSessionData {
144
- messages: KodaXMessage[];
145
- title: string;
146
- gitRoot: string;
147
- runtimeInfo?: KodaXSessionRuntimeInfo;
148
- scope?: KodaXSessionScope;
149
- uiHistory?: KodaXSessionUiHistoryItem[];
150
- errorMetadata?: SessionErrorMetadata;
151
- extensionState?: KodaXExtensionSessionState;
152
- extensionRecords?: KodaXExtensionSessionRecord[];
153
- lineage?: KodaXSessionLineage;
154
- artifactLedger?: KodaXSessionArtifactLedgerEntry[];
155
- }
156
- interface KodaXSessionMeta {
157
- _type: 'meta';
158
- title: string;
159
- id: string;
160
- gitRoot: string;
161
- runtimeInfo?: KodaXSessionRuntimeInfo;
162
- createdAt: string;
163
- scope?: KodaXSessionScope;
164
- uiHistory?: KodaXSessionUiHistoryItem[];
165
- extensionState?: KodaXExtensionSessionState;
166
- extensionRecordCount?: number;
167
- artifactLedgerCount?: number;
168
- lineageVersion?: 2;
169
- activeEntryId?: string | null;
170
- lineageEntryCount?: number;
171
- activeMessageCount?: number;
172
- /** Error metadata for recovery - 错误元数据用于恢复 */
173
- errorMetadata?: SessionErrorMetadata;
174
- }
175
- /**
176
- * Extension-scoped persistence entry.
177
- *
178
- * Each entry belongs to a namespace (extensionId) and carries
179
- * a string key, a JSON-safe value, and an opaque version tag
180
- * used for optimistic concurrency control.
181
- */
182
- interface KodaXExtensionStoreEntry {
183
- key: string;
184
- value: KodaXJsonValue;
185
- version: string;
186
- updatedAt: number;
187
- }
188
- /**
189
- * Extension persistence store interface (FEATURE_034 manual persistence).
190
- *
191
- * Implementations provide a durable key-value store scoped to a single
192
- * extension identity. The store is independent of session lifecycle —
193
- * data survives across sessions and restarts.
194
- */
195
- interface KodaXExtensionStore {
196
- /**
197
- * Read a single key.
198
- * Returns `undefined` when the key does not exist.
199
- */
200
- get(key: string): Promise<KodaXExtensionStoreEntry | undefined>;
201
- /**
202
- * Write a key-value pair.
203
- *
204
- * When `expectedVersion` is provided the write only succeeds when the
205
- * stored entry's version still matches (optimistic concurrency).
206
- * Returns the new entry on success, or `false` on version mismatch.
207
- */
208
- put(key: string, value: KodaXJsonValue, options?: {
209
- expectedVersion?: string;
210
- }): Promise<KodaXExtensionStoreEntry | false>;
211
- /**
212
- * Remove a key.
213
- * Returns `true` when the key existed and was removed.
214
- */
215
- delete(key: string): Promise<boolean>;
216
- /**
217
- * List all keys (optionally filtered by prefix).
218
- */
219
- list(options?: {
220
- prefix?: string;
221
- }): Promise<string[]>;
222
- /**
223
- * Clear all keys (optionally filtered by prefix).
224
- * Returns the number of entries removed.
225
- */
226
- clear(options?: {
227
- prefix?: string;
228
- }): Promise<number>;
229
- }
230
- interface KodaXSessionStorage {
231
- save(id: string, data: KodaXSessionData): Promise<void>;
232
- load(id: string): Promise<KodaXSessionData | null>;
233
- getLineage?(id: string): Promise<KodaXSessionLineage | null>;
234
- setActiveEntry?(id: string, selector: string, options?: KodaXSessionNavigationOptions): Promise<KodaXSessionData | null>;
235
- setLabel?(id: string, selector: string, label?: string): Promise<KodaXSessionData | null>;
236
- rewind?(id: string, selector?: string): Promise<KodaXSessionData | null>;
237
- fork?(id: string, selector?: string, options?: {
238
- sessionId?: string;
239
- title?: string;
240
- }): Promise<{
241
- sessionId: string;
242
- data: KodaXSessionData;
243
- } | null>;
244
- list?(gitRoot?: string): Promise<Array<{
245
- id: string;
246
- title: string;
247
- msgCount: number;
248
- runtimeInfo?: KodaXSessionRuntimeInfo;
249
- }>>;
250
- delete?(id: string): Promise<void>;
251
- deleteAll?(gitRoot?: string): Promise<void>;
252
- }
1
+ import { X as KodaXToolDefinition, m as KodaXMessage, D as KodaXReasoningMode, Z as KodaXToolResultContentItem, T as KodaXThinkingBlock, G as KodaXRedactedThinkingBlock } from './types.d-B1uGoVTE.js';
253
2
 
254
3
  /**
255
4
  * Layer A Primitive: Agent / Handoff / Guardrail / AgentReasoningProfile
@@ -508,12 +257,29 @@ interface FanoutSpanData {
508
257
  readonly winnerChildId?: string;
509
258
  readonly cancelledChildIds?: readonly string[];
510
259
  }
260
+ /**
261
+ * FEATURE_184 (v0.7.45) — Stop hook observability.
262
+ *
263
+ * Emitted when the Runner's `RunOptions.stopHook` is invoked or fails.
264
+ * `outcome` records what the hook returned (or `'error'` for thrown
265
+ * exceptions — fail-open path), `reanimateCount` is the running count
266
+ * after this invocation. `reason` carries the abort/reanimate text
267
+ * when relevant, truncated by consumers as needed.
268
+ */
269
+ interface StopHookSpanData {
270
+ readonly kind: 'stop-hook';
271
+ readonly outcome: 'accept' | 'reanimate' | 'abort' | 'budget-exhausted' | 'error';
272
+ readonly reanimateCount: number;
273
+ readonly reanimateBudget: number;
274
+ readonly reason?: string;
275
+ readonly error?: string;
276
+ }
511
277
  /**
512
278
  * Discriminated union of all span payload shapes. Additional variants may
513
279
  * be added in future features — consumers should check `kind` before
514
280
  * reading specific fields.
515
281
  */
516
- type SpanData = AgentSpanData | GenerationSpanData | ToolCallSpanData | HandoffSpanData | CompactionSpanData | GuardrailSpanData | EvidenceSpanData | FanoutSpanData;
282
+ type SpanData = AgentSpanData | GenerationSpanData | ToolCallSpanData | HandoffSpanData | CompactionSpanData | GuardrailSpanData | EvidenceSpanData | FanoutSpanData | StopHookSpanData;
517
283
 
518
284
  /**
519
285
  * Span — a single timed unit of work inside a Trace.
@@ -644,11 +410,18 @@ interface RunnerToolContext {
644
410
  readonly toolCallId?: string;
645
411
  }
646
412
  /**
647
- * Value returned by `RunnableTool.execute`. The `content` string is what the
648
- * LLM sees in the next turn as `tool_result`.
413
+ * Value returned by `RunnableTool.execute`. The `content` is what the LLM
414
+ * sees in the next turn as `tool_result`:
415
+ *
416
+ * - `string` — plain text (the default for most tools).
417
+ * - `readonly KodaXToolResultContentItem[]` — an array of typed items
418
+ * (text + image), used by multimodal tools like `read` on an image
419
+ * path. Provider serializers lower each item to the wire format
420
+ * (Anthropic accepts inline; OpenAI-compat downgrades image to text
421
+ * placeholder).
649
422
  */
650
423
  interface RunnerToolResult {
651
- readonly content: string;
424
+ readonly content: string | readonly KodaXToolResultContentItem[];
652
425
  readonly isError?: boolean;
653
426
  readonly metadata?: Record<string, unknown>;
654
427
  }
@@ -1213,5 +986,5 @@ interface DiscoveryOptions {
1213
986
  */
1214
987
  declare function discoverInstances(options?: DiscoveryOptions): DiscoveredInstance[];
1215
988
 
1216
- export { MAX_TOOL_LOOP_ITERATIONS as R, buildAssistantMessageFromLlmResult as af, buildToolResultMessage as ag, collectGuardrails as ah, createAgent as ai, createHandoff as aj, createStateWriter as ak, discoverInstances as al, executeRunnerToolCall as am, isRunnableTool as an, isRunnerLlmResult as ao, registerChildTask as ap, requestTaskStop as aq, runInputGuardrails as ar, runOutputGuardrails as as, runToolAfterGuardrails as at, runToolBeforeGuardrails as au, GuardrailBlockedError as g, GuardrailEscalateError as i };
1217
- export type { RunnerToolCall as $, Agent as A, KodaXSessionMessageEntry as B, ChildTaskRegistry as C, DiscoveredInstance as D, KodaXSessionMeta as E, KodaXSessionNavigationOptions as F, Guardrail as G, Handoff as H, InputGuardrail as I, KodaXSessionRuntimeInfo as J, KodaXCompactMemoryProgress as K, KodaXSessionScope as L, KodaXSessionStorage as M, KodaXSessionTreeNode as N, KodaXSessionUiHistoryItem as O, KodaXSessionUiHistoryItemType as P, KodaXSessionWorkspaceKind as Q, OutputGuardrail as S, PersistedSessionState as T, ReasoningDepth as U, RecentlyModifiedFile as V, RequestTaskStopOptions as W, RequestTaskStopResult as X, RunnableTool as Y, RunnerLlmResult as Z, RunnerLlmReturn as _, AgentMessage as a, RunnerToolContext as a0, RunnerToolObserver as a1, RunnerToolResult as a2, SessionErrorMetadata as a3, SessionMeta as a4, SessionStateSnapshot as a5, Span as a6, SpanData as a7, SpanError as a8, StateWriter as a9, StateWriterFs as aa, StateWriterOptions as ab, TaskAbortRegistry as ac, ToolBeforeOutcome as ad, ToolGuardrail as ae, AgentMiddlewareDeclaration as b, AgentReasoningProfile as c, AgentTool as d, CurrentTodoSummary as e, DiscoveryOptions as f, GuardrailContext as h, GuardrailVerdict as j, InstanceDiscoveryFs as k, KodaXCompactMemorySeed as l, KodaXExtensionSessionRecord as m, KodaXExtensionSessionState as n, KodaXExtensionStore as o, KodaXExtensionStoreEntry as p, KodaXJsonValue as q, KodaXSessionArchiveMarkerEntry as r, KodaXSessionArtifactLedgerEntry as s, KodaXSessionBranchSummaryEntry as t, KodaXSessionCompactionEntry as u, KodaXSessionData as v, KodaXSessionEntry as w, KodaXSessionEntryBase as x, KodaXSessionLabelEntry as y, KodaXSessionLineage as z };
989
+ export { requestTaskStop as $, buildAssistantMessageFromLlmResult as K, buildToolResultMessage as L, MAX_TOOL_LOOP_ITERATIONS as M, collectGuardrails as N, createAgent as Q, createHandoff as U, createStateWriter as V, discoverInstances as W, executeRunnerToolCall as X, isRunnableTool as Y, isRunnerLlmResult as Z, registerChildTask as _, runInputGuardrails as a0, runOutputGuardrails as a1, runToolAfterGuardrails as a2, runToolBeforeGuardrails as a3, GuardrailBlockedError as g, GuardrailEscalateError as i };
990
+ export type { Agent as A, StateWriterFs as B, ChildTaskRegistry as C, DiscoveredInstance as D, StateWriterOptions as E, ToolBeforeOutcome as F, Guardrail as G, Handoff as H, InputGuardrail as I, ToolGuardrail as J, OutputGuardrail as O, PersistedSessionState as P, ReasoningDepth as R, SessionMeta as S, TaskAbortRegistry as T, AgentMessage as a, AgentMiddlewareDeclaration as b, AgentReasoningProfile as c, AgentTool as d, CurrentTodoSummary as e, DiscoveryOptions as f, GuardrailContext as h, GuardrailVerdict as j, InstanceDiscoveryFs as k, RecentlyModifiedFile as l, RequestTaskStopOptions as m, RequestTaskStopResult as n, RunnableTool as o, RunnerLlmResult as p, RunnerLlmReturn as q, RunnerToolCall as r, RunnerToolContext as s, RunnerToolObserver as t, RunnerToolResult as u, SessionStateSnapshot as v, Span as w, SpanData as x, SpanError as y, StateWriter as z };
@@ -1,6 +1,6 @@
1
- import { G as KodaXReasoningMode, X as KodaXThinkingBudgetMap, Y as KodaXThinkingDepth, t as KodaXProviderConfig, F as KodaXReasoningCapability, I as KodaXReasoningRequest, T as KodaXTaskType, H as KodaXReasoningOverride, _ as KodaXToolDefinition, o as KodaXMessage, B as KodaXProviderStreamOptions, N as KodaXStreamResult, s as KodaXProviderCapabilityProfile, j as KodaXCustomProviderConfig } from './capability.d-BxNgd1-c.js';
1
+ import { D as KodaXReasoningMode, U as KodaXThinkingBudgetMap, V as KodaXThinkingDepth, r as KodaXProviderConfig, C as KodaXReasoningCapability, F as KodaXReasoningRequest, Q as KodaXTaskType, E as KodaXReasoningOverride, X as KodaXToolDefinition, m as KodaXMessage, z as KodaXProviderStreamOptions, J as KodaXStreamResult, q as KodaXProviderCapabilityProfile, h as KodaXCustomProviderConfig } from './types.d-B1uGoVTE.js';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
- import { K as KodaXBaseProvider } from './cost-tracker.d-C4dMlQuV.js';
3
+ import { K as KodaXBaseProvider } from './cost-tracker.d-B6vMoLLF.js';
4
4
  import OpenAI from 'openai';
5
5
 
6
6
  /**
@@ -189,6 +189,7 @@ declare function isProviderName(name: string): name is ProviderName;
189
189
  * Supports both OpenAI and Anthropic protocol families.
190
190
  */
191
191
 
192
+ declare function validateCustomProviderConfig(custom: KodaXCustomProviderConfig): void;
192
193
  declare function createCustomProvider(custom: KodaXCustomProviderConfig): KodaXBaseProvider;
193
194
 
194
195
  /**
@@ -258,5 +259,5 @@ declare function isKnownProvider(name: string): boolean;
258
259
  */
259
260
  declare function getAvailableProviderNames(): string[];
260
261
 
261
- export { getProviderList as A, getProviderModel as B, getProviderModels as C, getReasoningCapability as D, getRuntimeModelProvider as E, getRuntimeModelProviderNames as F, isCustomProviderName as G, isKnownProvider as H, isProviderConfigured as I, isProviderName as J, KODAX_DEFAULT_PROVIDER as K, isReasoningEnabled as L, isRuntimeModelProviderName as M, loadReasoningOverride as N, mapDepthToOpenAIReasoningEffort as O, normalizeReasoningRequest as Q, reasoningCapabilityToOverride as R, reasoningOverrideToCapability as S, registerCustomProviders as T, registerModelProvider as U, resolveProvider as V, resolveThinkingBudget as W, saveReasoningOverride as X, KODAX_DEFAULT_THINKING_BUDGETS as a, KODAX_PROVIDERS as b, KODAX_PROVIDER_SNAPSHOTS as c, KODAX_REASONING_MODE_SEQUENCE as d, KODAX_REASONING_SAFETY_RESERVE as e, KodaXAnthropicCompatProvider as f, KodaXError as g, KodaXNetworkError as h, KodaXOpenAICompatProvider as i, KodaXProviderError as j, KodaXRateLimitError as k, KodaXToolCallIdError as l, buildReasoningOverrideKey as m, clampThinkingBudget as n, clearReasoningOverride as o, clearRuntimeModelProviders as p, createCustomProvider as q, getAvailableProviderNames as r, getCustomProvider as s, getCustomProviderList as t, getCustomProviderModels as u, getCustomProviderNames as v, getDefaultThinkingDepthForMode as w, getProvider as x, getProviderConfiguredCapabilityProfile as y, getProviderConfiguredReasoningCapability as z };
262
+ export { getProviderList as A, getProviderModel as B, getProviderModels as C, getReasoningCapability as D, getRuntimeModelProvider as E, getRuntimeModelProviderNames as F, isCustomProviderName as G, isKnownProvider as H, isProviderConfigured as I, isProviderName as J, KODAX_DEFAULT_PROVIDER as K, isReasoningEnabled as L, isRuntimeModelProviderName as M, loadReasoningOverride as N, mapDepthToOpenAIReasoningEffort as O, normalizeReasoningRequest as Q, reasoningCapabilityToOverride as R, reasoningOverrideToCapability as S, registerCustomProviders as T, registerModelProvider as U, resolveProvider as V, resolveThinkingBudget as W, saveReasoningOverride as X, validateCustomProviderConfig as Y, KODAX_DEFAULT_THINKING_BUDGETS as a, KODAX_PROVIDERS as b, KODAX_PROVIDER_SNAPSHOTS as c, KODAX_REASONING_MODE_SEQUENCE as d, KODAX_REASONING_SAFETY_RESERVE as e, KodaXAnthropicCompatProvider as f, KodaXError as g, KodaXNetworkError as h, KodaXOpenAICompatProvider as i, KodaXProviderError as j, KodaXRateLimitError as k, KodaXToolCallIdError as l, buildReasoningOverrideKey as m, clampThinkingBudget as n, clearReasoningOverride as o, clearRuntimeModelProviders as p, createCustomProvider as q, getAvailableProviderNames as r, getCustomProvider as s, getCustomProviderList as t, getCustomProviderModels as u, getCustomProviderNames as v, getDefaultThinkingDepthForMode as w, getProvider as x, getProviderConfiguredCapabilityProfile as y, getProviderConfiguredReasoningCapability as z };
262
263
  export type { ProviderName as P };