@codex-native/sdk 0.0.13 → 0.0.18

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.
package/dist/index.d.ts CHANGED
@@ -1,488 +1,2293 @@
1
- /* auto-generated by NAPI-RS */
2
- /* eslint-disable */
3
- export declare class AgentOrchestrator {
4
- constructor()
5
- addAgent(id: string, config: AgentConfig): void
6
- removeAgent(id: string): void
7
- setViewMode(mode: string): void
8
- switchToAgent(id: string): void
1
+ import { ContentBlock } from '@modelcontextprotocol/sdk/types.js';
2
+ import { Diagnostic } from 'vscode-languageserver-types';
3
+ import { ModelProvider, Model, StreamEvent } from '@openai/agents-core';
4
+ import { tool } from '@openai/agents';
5
+ import { OpencodeClient, Event } from '@opencode-ai/sdk';
6
+
7
+ /** The status of a command execution. */
8
+ type CommandExecutionStatus = "in_progress" | "completed" | "failed";
9
+ /** A command executed by the agent. */
10
+ type CommandExecutionItem = {
11
+ id: string;
12
+ type: "command_execution";
13
+ /** The command line executed by the agent. */
14
+ command: string;
15
+ /** Aggregated stdout and stderr captured while the command was running. */
16
+ aggregated_output: string;
17
+ /** Set when the command exits; omitted while still running. */
18
+ exit_code?: number;
19
+ /** Current status of the command execution. */
20
+ status: CommandExecutionStatus;
21
+ };
22
+ /** Indicates the type of the file change. */
23
+ type PatchChangeKind = "add" | "delete" | "update";
24
+ /** A set of file changes by the agent. */
25
+ type FileUpdateChange = {
26
+ path: string;
27
+ kind: PatchChangeKind;
28
+ };
29
+ /** The status of a file change. */
30
+ type PatchApplyStatus = "completed" | "failed";
31
+ /** A set of file changes by the agent. Emitted once the patch succeeds or fails. */
32
+ type FileChangeItem = {
33
+ id: string;
34
+ type: "file_change";
35
+ /** Individual file changes that comprise the patch. */
36
+ changes: FileUpdateChange[];
37
+ /** Whether the patch ultimately succeeded or failed. */
38
+ status: PatchApplyStatus;
39
+ };
40
+ /** The status of an MCP tool call. */
41
+ type McpToolCallStatus = "in_progress" | "completed" | "failed";
42
+ /**
43
+ * Represents a call to an MCP tool. The item starts when the invocation is dispatched
44
+ * and completes when the MCP server reports success or failure.
45
+ */
46
+ type McpToolCallItem = {
47
+ id: string;
48
+ type: "mcp_tool_call";
49
+ /** Name of the MCP server handling the request. */
50
+ server: string;
51
+ /** The tool invoked on the MCP server. */
52
+ tool: string;
53
+ /** Arguments forwarded to the tool invocation. */
54
+ arguments: unknown;
55
+ /** Result payload returned by the MCP server for successful calls. */
56
+ result?: {
57
+ content: ContentBlock[];
58
+ structured_content: unknown;
59
+ };
60
+ /** Error message reported for failed calls. */
61
+ error?: {
62
+ message: string;
63
+ };
64
+ /** Current status of the tool invocation. */
65
+ status: McpToolCallStatus;
66
+ };
67
+ /** Response from the agent. Either natural-language text or JSON when structured output is requested. */
68
+ type AgentMessageItem = {
69
+ id: string;
70
+ type: "agent_message";
71
+ /** Either natural-language text or JSON when structured output is requested. */
72
+ text: string;
73
+ };
74
+ /** Agent's reasoning summary. */
75
+ type ReasoningItem = {
76
+ id: string;
77
+ type: "reasoning";
78
+ text: string;
79
+ };
80
+ /** Captures a web search request. Completes when results are returned to the agent. */
81
+ type WebSearchItem = {
82
+ id: string;
83
+ type: "web_search";
84
+ query: string;
85
+ };
86
+ /** Describes a non-fatal error surfaced as an item. */
87
+ type ErrorItem = {
88
+ id: string;
89
+ type: "error";
90
+ message: string;
91
+ };
92
+ /** An item in the agent's to-do list. */
93
+ type TodoItem = {
94
+ text: string;
95
+ completed: boolean;
96
+ };
97
+ /**
98
+ * Tracks the agent's running to-do list. Starts when the plan is issued, updates as steps change,
99
+ * and completes when the turn ends.
100
+ */
101
+ type TodoListItem = {
102
+ id: string;
103
+ type: "todo_list";
104
+ items: TodoItem[];
105
+ };
106
+ /** Canonical union of thread items and their type-specific payloads. */
107
+ type ThreadItem = AgentMessageItem | ReasoningItem | CommandExecutionItem | FileChangeItem | McpToolCallItem | WebSearchItem | TodoListItem | ErrorItem;
108
+
109
+ /** Emitted when a new thread is started as the first event. */
110
+ type ThreadStartedEvent = {
111
+ type: "thread.started";
112
+ /** The identifier of the new thread. Can be used to resume the thread later. */
113
+ thread_id: string;
114
+ };
115
+ /**
116
+ * Emitted when a turn is started by sending a new prompt to the model.
117
+ * A turn encompasses all events that happen while the agent is processing the prompt.
118
+ */
119
+ type TurnStartedEvent = {
120
+ type: "turn.started";
121
+ };
122
+ /** Describes the usage of tokens during a turn. */
123
+ type Usage = {
124
+ /** The number of input tokens used during the turn. */
125
+ input_tokens: number;
126
+ /** The number of cached input tokens used during the turn. */
127
+ cached_input_tokens: number;
128
+ /** The number of output tokens used during the turn. */
129
+ output_tokens: number;
130
+ };
131
+ /** Emitted when a turn is completed. Typically right after the assistant's response. */
132
+ type TurnCompletedEvent = {
133
+ type: "turn.completed";
134
+ usage: Usage;
135
+ };
136
+ /** Indicates that a turn failed with an error. */
137
+ type TurnFailedEvent = {
138
+ type: "turn.failed";
139
+ error: ThreadError;
140
+ };
141
+ /** Background notification emitted during an active turn. */
142
+ type BackgroundEvent = {
143
+ type: "background_event";
144
+ message: string;
145
+ };
146
+ /** Emitted when a new item is added to the thread. Typically the item is initially "in progress". */
147
+ type ItemStartedEvent = {
148
+ type: "item.started";
149
+ item: ThreadItem;
150
+ };
151
+ /** Emitted when an item is updated. */
152
+ type ItemUpdatedEvent = {
153
+ type: "item.updated";
154
+ item: ThreadItem;
155
+ };
156
+ /** Signals that an item has reached a terminal state—either success or failure. */
157
+ type ItemCompletedEvent = {
158
+ type: "item.completed";
159
+ item: ThreadItem;
160
+ };
161
+ /** Fatal error emitted by the stream. */
162
+ type ThreadError = {
163
+ message: string;
164
+ };
165
+ /** Represents an unrecoverable error emitted directly by the event stream. */
166
+ type ThreadErrorEvent = {
167
+ type: "error";
168
+ message: string;
169
+ };
170
+ /** Review finding with code location */
171
+ type ReviewFinding = {
172
+ title: string;
173
+ body: string;
174
+ confidence_score: number;
175
+ priority: number;
176
+ code_location: {
177
+ absolute_file_path: string;
178
+ line_range: {
179
+ start: number;
180
+ end: number;
181
+ };
182
+ };
183
+ };
184
+ /** Structured review output */
185
+ type ReviewOutputEvent = {
186
+ findings: ReviewFinding[];
187
+ overall_correctness: string;
188
+ overall_explanation: string;
189
+ overall_confidence_score: number;
190
+ };
191
+ /** Emitted when exiting review mode with optional structured results */
192
+ type ExitedReviewModeEvent = {
193
+ type: "exited_review_mode";
194
+ review_output: ReviewOutputEvent | null;
195
+ };
196
+ /** Top-level JSONL events emitted by codex exec. */
197
+ type ThreadEvent = ThreadStartedEvent | TurnStartedEvent | TurnCompletedEvent | TurnFailedEvent | BackgroundEvent | ItemStartedEvent | ItemUpdatedEvent | ItemCompletedEvent | ExitedReviewModeEvent | ThreadErrorEvent | RawThreadEvent;
198
+ /** Raw protocol event forwarded without transformation. */
199
+ type RawThreadEvent = {
200
+ type: "raw_event";
201
+ raw: unknown;
202
+ };
203
+
204
+ type SkillDefinition = {
205
+ /**
206
+ * Skill name referenced via `$<name>` (default) or `@<name>` in prompts.
207
+ */
208
+ name: string;
209
+ /**
210
+ * Optional human description (not currently injected automatically).
211
+ */
212
+ description?: string;
213
+ /**
214
+ * The skill body/instructions that will be injected when referenced.
215
+ */
216
+ contents: string;
217
+ };
218
+ type SkillMentionTrigger = "$" | "@";
219
+
220
+ type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted";
221
+ type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
222
+ /**
223
+ * Reasoning effort level for reasoning-capable models (e.g., o1, o3).
224
+ * See https://platform.openai.com/docs/guides/reasoning
225
+ *
226
+ * @default "medium" - When undefined, codex uses "medium" as the default
227
+ */
228
+ type ReasoningEffort = "minimal" | "low" | "medium" | "high" | "xhigh";
229
+ /**
230
+ * Controls whether reasoning summaries are included for reasoning-capable models.
231
+ * See https://platform.openai.com/docs/guides/reasoning#reasoning-summaries
232
+ *
233
+ * @default "auto" - When undefined, codex uses "auto" as the default
234
+ */
235
+ type ReasoningSummary = "auto" | "concise" | "detailed" | "none";
236
+ type WorkspaceWriteOptions = {
237
+ /** Enable network access in workspace-write mode. Default: false */
238
+ networkAccess?: boolean;
239
+ /** Additional directories that should be writable */
240
+ writableRoots?: string[];
241
+ /** Exclude the TMPDIR environment variable from writable roots. Default: false */
242
+ excludeTmpdirEnvVar?: boolean;
243
+ /** Exclude /tmp from writable roots on Unix. Default: false */
244
+ excludeSlashTmp?: boolean;
245
+ };
246
+ type ThreadOptions = {
247
+ model?: string;
248
+ /** Override the model provider declared in config.toml */
249
+ modelProvider?: string;
250
+ /** Use local OSS provider via Ollama (pulls models as needed) */
251
+ oss?: boolean;
252
+ sandboxMode?: SandboxMode;
253
+ /** Approval policy for command execution */
254
+ approvalMode?: ApprovalMode;
255
+ /** Options for workspace-write sandbox mode */
256
+ workspaceWriteOptions?: WorkspaceWriteOptions;
257
+ workingDirectory?: string;
258
+ skipGitRepoCheck?: boolean;
259
+ /** Reasoning effort level (only honored for reasoning-capable models). Defaults to "medium" when undefined. */
260
+ reasoningEffort?: ReasoningEffort;
261
+ /** Reasoning summary preference (only honored for reasoning-capable models). Defaults to "auto" when undefined. */
262
+ reasoningSummary?: ReasoningSummary;
263
+ /** @deprecated Use sandboxMode and approvalMode instead */
264
+ fullAuto?: boolean;
265
+ /**
266
+ * Programmatically registered skills (no SKILL.md files required) for this thread.
267
+ * These augment any skills registered on the parent Codex instance.
268
+ */
269
+ skills?: SkillDefinition[] | Record<string, string | Omit<SkillDefinition, "name">>;
270
+ /**
271
+ * Prefixes that activate skills when present immediately before the skill name.
272
+ *
273
+ * Defaults to `["$"]` when omitted.
274
+ */
275
+ skillMentionTriggers?: SkillMentionTrigger[];
276
+ };
277
+
278
+ type TurnOptions = {
279
+ /** JSON schema describing the expected agent output. */
280
+ outputSchema?: unknown;
281
+ /** Whether to use OSS mode with Ollama models */
282
+ oss?: boolean;
283
+ /** Override the model provider for this specific turn. */
284
+ modelProvider?: string;
285
+ };
286
+
287
+ type NativeConversationSummary = {
288
+ id: string;
289
+ path: string;
290
+ createdAt?: string;
291
+ updatedAt?: string;
292
+ };
293
+ type NativeConversationListPage = {
294
+ conversations: NativeConversationSummary[];
295
+ nextCursor?: string;
296
+ numScannedFiles: number;
297
+ reachedScanCap: boolean;
298
+ };
299
+ type NativeTuiRequest = {
300
+ prompt?: string;
301
+ images?: string[];
302
+ model?: string;
303
+ modelProvider?: string;
304
+ oss?: boolean;
305
+ sandboxMode?: SandboxMode;
306
+ approvalMode?: ApprovalMode;
307
+ resumeSessionId?: string;
308
+ resumeLast?: boolean;
309
+ resumePicker?: boolean;
310
+ fullAuto?: boolean;
311
+ dangerouslyBypassApprovalsAndSandbox?: boolean;
312
+ workingDirectory?: string;
313
+ configProfile?: string;
314
+ configOverrides?: string[];
315
+ addDir?: string[];
316
+ webSearch?: boolean;
317
+ linuxSandboxPath?: string;
318
+ baseUrl?: string;
319
+ apiKey?: string;
320
+ reasoningEffort?: ReasoningEffort;
321
+ reasoningSummary?: ReasoningSummary;
322
+ };
323
+ type NativeTokenUsage = {
324
+ inputTokens: number;
325
+ cachedInputTokens: number;
326
+ outputTokens: number;
327
+ reasoningOutputTokens: number;
328
+ totalTokens: number;
329
+ };
330
+ type NativeUpdateActionKind = "npmGlobalLatest" | "bunGlobalLatest" | "brewUpgrade";
331
+ type NativeUpdateActionInfo = {
332
+ kind: NativeUpdateActionKind;
333
+ command: string;
334
+ };
335
+ type NativeTuiExitInfo = {
336
+ tokenUsage: NativeTokenUsage;
337
+ conversationId?: string;
338
+ updateAction?: NativeUpdateActionInfo;
339
+ };
340
+ type RepoDiffFileChange = {
341
+ path: string;
342
+ status: string;
343
+ diff: string;
344
+ truncated: boolean;
345
+ previousPath?: string | null;
346
+ };
347
+ type RepoDiffSummary = {
348
+ repoPath: string;
349
+ branch: string;
350
+ baseBranch: string;
351
+ upstreamRef?: string | null;
352
+ mergeBase: string;
353
+ statusSummary: string;
354
+ diffStat: string;
355
+ recentCommits: string;
356
+ changedFiles: RepoDiffFileChange[];
357
+ totalChangedFiles: number;
358
+ };
359
+ type RepoDiffSummaryOptions = {
360
+ cwd?: string;
361
+ baseBranchOverride?: string;
362
+ maxFiles?: number;
363
+ diffContextLines?: number;
364
+ diffCharLimit?: number;
365
+ };
366
+ type ReverieConversation = {
367
+ id: string;
368
+ path: string;
369
+ createdAt?: string;
370
+ updatedAt?: string;
371
+ headRecords: string[];
372
+ tailRecords: string[];
373
+ headRecordsToon: string[];
374
+ tailRecordsToon: string[];
375
+ };
376
+ type ReverieSearchResult = {
377
+ conversation: ReverieConversation;
378
+ relevanceScore: number;
379
+ matchingExcerpts: string[];
380
+ insights: string[];
381
+ rerankerScore?: number;
382
+ };
383
+ type FastEmbedRerankerModelCode = "BAAI/bge-reranker-base" | "rozgo/bge-reranker-v2-m3" | "jinaai/jina-reranker-v1-turbo-en" | "jinaai/jina-reranker-v2-base-multilingual";
384
+ type ReverieSemanticSearchOptions = {
385
+ limit?: number;
386
+ maxCandidates?: number;
387
+ projectRoot?: string;
388
+ batchSize?: number;
389
+ normalize?: boolean;
390
+ cache?: boolean;
391
+ rerankerModel?: FastEmbedRerankerModelCode;
392
+ rerankerCacheDir?: string;
393
+ rerankerMaxLength?: number;
394
+ rerankerShowProgress?: boolean;
395
+ rerankerBatchSize?: number;
396
+ rerankerTopK?: number;
397
+ };
398
+ type ReverieSemanticIndexStats = {
399
+ conversationsIndexed: number;
400
+ documentsEmbedded: number;
401
+ batches: number;
402
+ };
403
+ type FastEmbedInitOptions = {
404
+ model?: string;
405
+ cacheDir?: string;
406
+ maxLength?: number;
407
+ showDownloadProgress?: boolean;
408
+ };
409
+ type FastEmbedEmbedRequest = {
410
+ inputs: string[];
411
+ batchSize?: number;
412
+ normalize?: boolean;
413
+ projectRoot?: string;
414
+ cache?: boolean;
415
+ };
416
+ type TokenizerOptions = {
417
+ model?: string;
418
+ encoding?: "o200k_base" | "cl100k_base";
419
+ };
420
+ type TokenizerEncodeOptions = TokenizerOptions & {
421
+ withSpecialTokens?: boolean;
422
+ };
423
+ type NativeToolInfo = {
424
+ name: string;
425
+ description?: string;
426
+ parameters?: unknown;
427
+ strict?: boolean;
428
+ supportsParallel?: boolean;
429
+ };
430
+ type NativeToolInvocation = {
431
+ toolName: string;
432
+ callId: string;
433
+ arguments?: string;
434
+ input?: string;
435
+ };
436
+ type NativeToolResult = {
437
+ output?: string;
438
+ success?: boolean;
439
+ error?: string;
440
+ };
441
+ type NativeForkResult = {
442
+ threadId: string;
443
+ rolloutPath: string;
444
+ };
445
+ type ApprovalRequest = {
446
+ type: "shell" | "file_write" | "network_access";
447
+ details?: unknown;
448
+ context?: string;
449
+ };
450
+ declare function reverieListConversations(codexHomePath: string, limit?: number, offset?: number): Promise<ReverieConversation[]>;
451
+ declare function reverieSearchConversations(codexHomePath: string, query: string, limit?: number): Promise<ReverieSearchResult[]>;
452
+ declare function reverieSearchSemantic(codexHomePath: string, context: string, options?: ReverieSemanticSearchOptions): Promise<ReverieSearchResult[]>;
453
+ declare function reverieIndexSemantic(codexHomePath: string, options?: ReverieSemanticSearchOptions): Promise<ReverieSemanticIndexStats>;
454
+ declare function reverieGetConversationInsights(conversationPath: string, query?: string): Promise<string[]>;
455
+ declare function encodeToToon(value: unknown): string;
456
+ declare function fastEmbedInit(options: FastEmbedInitOptions): Promise<void>;
457
+ declare function fastEmbedEmbed(request: FastEmbedEmbedRequest): Promise<number[][]>;
458
+ declare function tokenizerCount(text: string, options?: TokenizerOptions): number;
459
+ declare function tokenizerEncode(text: string, options?: TokenizerEncodeOptions): number[];
460
+ declare function tokenizerDecode(tokens: number[], options?: TokenizerOptions): string;
461
+ declare function collectRepoDiffSummary(options?: RepoDiffSummaryOptions): Promise<RepoDiffSummary>;
462
+
463
+ interface TuiSession {
464
+ wait(): Promise<NativeTuiExitInfo>;
465
+ shutdown(): void;
466
+ readonly closed: boolean;
9
467
  }
10
-
11
- export declare class AgentView {
12
- constructor(threadId: string, title?: string | undefined | null)
13
- sendMessage(message: string): void
14
- receiveMessage(message: string): void
15
- updateStatus(status: string): void
16
- appendOutput(output: string): void
17
- }
18
-
19
- export declare class LayoutManager {
20
- constructor()
21
- setSplit(orientation: string, ratio: number, leftId: string, rightId: string): void
22
- }
23
-
24
- export declare class StatusBoard {
25
- constructor(layout?: string | undefined | null)
26
- addTextTile(id: string, title: string, value: string): void
27
- addProgressTile(id: string, title: string, value: number): void
28
- updateTile(id: string, value: string): void
29
- }
30
-
31
- export declare class TuiApp {
32
- constructor(title?: string | undefined | null, width?: number | undefined | null, height?: number | undefined | null)
33
- addComponent(id: string, componentType: WidgetType): void
34
- startTerminal(): void
35
- stopTerminal(): void
468
+ interface RunTuiOptions {
469
+ signal?: AbortSignal;
36
470
  }
37
-
38
- export declare class TuiSession {
39
- wait(): Promise<TuiExitInfo>
40
- shutdown(): void
41
- get closed(): boolean
42
- }
43
-
44
- export interface AgentConfig {
45
- name: string
46
- model?: string
47
- task?: string
48
- }
49
-
50
- export declare function callToolBuiltin(token: string, invocation?: JsToolInvocation): Promise<NativeToolResponse>
51
-
52
- export declare function clearRegisteredTools(): void
53
-
54
- export declare function cloudTasksApply(taskId: string, diffOverride?: string | undefined | null, baseUrl?: string | undefined | null, apiKey?: string | undefined | null): Promise<string>
55
-
56
- export declare function cloudTasksApplyPreflight(taskId: string, diffOverride?: string | undefined | null, baseUrl?: string | undefined | null, apiKey?: string | undefined | null): Promise<string>
57
-
58
- export declare function cloudTasksCreate(envId: string, prompt: string, gitRef?: string | undefined | null, qaMode?: boolean | undefined | null, bestOfN?: number | undefined | null, baseUrl?: string | undefined | null, apiKey?: string | undefined | null): Promise<string>
59
-
60
- export declare function cloudTasksGetDiff(taskId: string, baseUrl?: string | undefined | null, apiKey?: string | undefined | null): Promise<string>
61
-
62
- export declare function cloudTasksList(envFilter?: string | undefined | null, baseUrl?: string | undefined | null, apiKey?: string | undefined | null): Promise<string>
63
-
64
- export declare function collectRepoDiffSummary(cwd: string, baseBranchOverride?: string | undefined | null, options?: RepoDiffOptions | undefined | null): Promise<RepoDiffSummary>
65
-
66
- export declare function compactThread(req: RunRequest): Promise<Array<string>>
67
-
68
- export interface ConversationConfigRequest {
69
- model?: string
70
- modelProvider?: string
71
- oss?: boolean
72
- sandboxMode?: string
73
- approvalMode?: string
74
- workspaceWriteOptions?: WorkspaceWriteOptions
75
- workingDirectory?: string
76
- skipGitRepoCheck?: boolean
77
- baseUrl?: string
78
- apiKey?: string
79
- linuxSandboxPath?: string
80
- reasoningEffort?: string
81
- reasoningSummary?: string
82
- fullAuto?: boolean
83
- }
84
-
85
- export interface ConversationListPage {
86
- conversations: Array<ConversationSummary>
87
- nextCursor?: string
88
- numScannedFiles: number
89
- reachedScanCap: boolean
90
- }
91
-
92
- export interface ConversationSummary {
93
- id: string
94
- path: string
95
- createdAt?: string
96
- updatedAt?: string
97
- }
98
-
99
- export declare function deleteConversation(req: DeleteConversationRequest): Promise<DeleteConversationResult>
100
-
101
- export interface DeleteConversationRequest {
102
- id: string
103
- config?: ConversationConfigRequest
104
- }
105
-
106
- export interface DeleteConversationResult {
107
- deleted: boolean
108
- }
109
-
110
- export interface Dimensions {
111
- width: number
112
- height: number
113
- x: number
114
- y: number
115
- }
116
-
117
- export declare function emitBackgroundEvent(req: JsEmitBackgroundEventRequest): void
118
-
119
- export declare function emitPlanUpdate(req: JsEmitPlanUpdateRequest): void
120
-
121
- export declare function ensureTokioRuntime(): void
122
-
123
- export declare function evAssistantMessage(id: string, text: string): string
124
-
125
- export declare function evCompleted(id: string): string
126
-
127
- export declare function evFunctionCall(callId: string, name: string, args: string): string
128
-
129
- export declare function evResponseCreated(id: string): string
130
-
131
- export declare function fastEmbedEmbed(req: FastEmbedEmbedRequest): Promise<Array<Array<number>>>
132
-
133
- export interface FastEmbedEmbedRequest {
134
- inputs: Array<string>
135
- batchSize?: number
136
- normalize?: boolean
137
- projectRoot?: string
138
- cache?: boolean
139
- }
140
-
141
- export declare function fastEmbedInit(opts: FastEmbedInitOptions): Promise<void>
142
-
143
- export interface FastEmbedInitOptions {
144
- model?: string
145
- cacheDir?: string
146
- maxLength?: number
147
- showDownloadProgress?: boolean
148
- /** Enable CoreML execution provider for Metal/ANE acceleration on macOS */
149
- useCoreml?: boolean
150
- /** Use Apple Neural Engine only (vs ANE + GPU) */
151
- coremlAneOnly?: boolean
152
- }
153
-
154
- export interface ForkRequest {
155
- threadId: string
156
- nthUserMessage?: number
157
- model?: string
158
- modelProvider?: string
159
- oss?: boolean
160
- sandboxMode?: string
161
- approvalMode?: string
162
- workspaceWriteOptions?: WorkspaceWriteOptions
163
- workingDirectory?: string
164
- skipGitRepoCheck?: boolean
165
- baseUrl?: string
166
- apiKey?: string
167
- linuxSandboxPath?: string
168
- reasoningEffort?: string
169
- reasoningSummary?: string
170
- fullAuto?: boolean
171
- }
172
-
173
- export interface ForkResult {
174
- threadId: string
175
- rolloutPath: string
471
+ /**
472
+ * Starts the Codex TUI (Terminal User Interface) and returns a controllable session handle.
473
+ *
474
+ * Use {@link TuiSession.wait} to await completion or {@link TuiSession.shutdown} to
475
+ * request a graceful exit from another part of your program.
476
+ */
477
+ declare function startTui(request: NativeTuiRequest): TuiSession;
478
+ /**
479
+ * Launches the Codex TUI and waits for it to exit. Supports optional cancellation via AbortSignal.
480
+ */
481
+ declare function runTui(request: NativeTuiRequest, options?: RunTuiOptions): Promise<NativeTuiExitInfo>;
482
+
483
+ /** Completed turn. */
484
+ type Turn = {
485
+ items: ThreadItem[];
486
+ finalResponse: string;
487
+ usage: Usage | null;
488
+ };
489
+ /** Alias for `Turn` to describe the result of `run()`. */
490
+ type RunResult = Turn;
491
+ /** The result of the `runStreamed` method. */
492
+ type StreamedTurn = {
493
+ events: AsyncGenerator<ThreadEvent>;
494
+ };
495
+ /** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */
496
+ type RunStreamedResult = StreamedTurn;
497
+ /** An input to send to the agent. */
498
+ type UserInput = {
499
+ type: "text";
500
+ text: string;
501
+ } | {
502
+ type: "local_image";
503
+ path: string;
504
+ };
505
+ type Input = string | UserInput[];
506
+ type ForkOptions = {
507
+ nthUserMessage: number;
508
+ threadOptions?: Partial<ThreadOptions>;
509
+ };
510
+ /** Respesent a thread of conversation with the agent. One thread can have multiple consecutive turns. */
511
+ declare class Thread {
512
+ private _exec;
513
+ private _options;
514
+ private _id;
515
+ private _threadOptions;
516
+ private _eventListeners;
517
+ private _approvalHandler;
518
+ private readonly _skills;
519
+ private readonly _skillMentionTriggers;
520
+ private readonly _codexSkills?;
521
+ /** Returns the ID of the thread. Populated after the first turn starts. */
522
+ get id(): string | null;
523
+ /**
524
+ * Register an event listener for thread events.
525
+ * @param listener Callback function that receives ThreadEvent objects
526
+ * @returns Unsubscribe function to remove the listener
527
+ */
528
+ onEvent(listener: (event: ThreadEvent) => void): () => void;
529
+ /**
530
+ * Remove an event listener.
531
+ * @param listener The listener function to remove
532
+ */
533
+ offEvent(listener: (event: ThreadEvent) => void): void;
534
+ /**
535
+ * Register a callback to handle approval requests from the agent.
536
+ * The handler should return true to approve the action, false to deny it.
537
+ *
538
+ * @param handler Callback function that receives ApprovalRequest and returns approval decision
539
+ * @example
540
+ * ```typescript
541
+ * thread.onApprovalRequest(async (request) => {
542
+ * console.log(`Approval requested for ${request.type}`);
543
+ * return true; // Auto-approve
544
+ * });
545
+ * ```
546
+ */
547
+ onApprovalRequest(handler: (request: ApprovalRequest) => boolean | Promise<boolean>): void;
548
+ /**
549
+ * Emit a background notification while the agent is running the current turn.
550
+ * The message is surfaced to event subscribers but does not modify the user input queue.
551
+ *
552
+ * @throws Error if the thread has not been started yet.
553
+ */
554
+ sendBackgroundEvent(message: string): Promise<void>;
555
+ /**
556
+ * Programmatically update the agent's plan/todo list.
557
+ * The plan will be applied at the start of the next turn.
558
+ *
559
+ * @param args The plan update arguments
560
+ * @throws Error if no thread ID is available
561
+ */
562
+ updatePlan(args: {
563
+ explanation?: string;
564
+ plan: Array<{
565
+ step: string;
566
+ status: "pending" | "in_progress" | "completed";
567
+ }>;
568
+ }): void;
569
+ /**
570
+ * Modify the agent's plan/todo list with granular operations.
571
+ * Changes will be applied at the start of the next turn.
572
+ *
573
+ * @param operations Array of operations to perform on the plan
574
+ * @throws Error if no thread ID is available
575
+ */
576
+ modifyPlan(operations: Array<{
577
+ type: "add";
578
+ item: {
579
+ step: string;
580
+ status?: "pending" | "in_progress" | "completed";
581
+ };
582
+ } | {
583
+ type: "update";
584
+ index: number;
585
+ updates: Partial<{
586
+ step: string;
587
+ status: "pending" | "in_progress" | "completed";
588
+ }>;
589
+ } | {
590
+ type: "remove";
591
+ index: number;
592
+ } | {
593
+ type: "reorder";
594
+ newOrder: number[];
595
+ }>): void;
596
+ /**
597
+ * Add a new todo item to the agent's plan.
598
+ *
599
+ * @param step The todo step description
600
+ * @param status The initial status (defaults to "pending")
601
+ */
602
+ addTodo(step: string, status?: "pending" | "in_progress" | "completed"): void;
603
+ /**
604
+ * Update an existing todo item.
605
+ *
606
+ * @param index The index of the todo item to update
607
+ * @param updates The updates to apply
608
+ */
609
+ updateTodo(index: number, updates: Partial<{
610
+ step: string;
611
+ status: "pending" | "in_progress" | "completed";
612
+ }>): void;
613
+ /**
614
+ * Remove a todo item from the plan.
615
+ *
616
+ * @param index The index of the todo item to remove
617
+ */
618
+ removeTodo(index: number): void;
619
+ /**
620
+ * Reorder the todo items in the plan.
621
+ *
622
+ * @param newOrder Array of indices representing the new order
623
+ */
624
+ reorderTodos(newOrder: number[]): void;
625
+ /** Compacts the conversation history for this thread using Codex's builtin compaction. */
626
+ compact(): Promise<void>;
627
+ /**
628
+ * Fork this thread at the specified user message, returning a new thread that starts
629
+ * from the conversation history prior to that message.
630
+ *
631
+ * @param options Fork configuration including which user message to branch before and optional thread overrides.
632
+ */
633
+ fork(options: ForkOptions): Promise<Thread>;
634
+ /** Provides the input to the agent and streams events as they are produced during the turn. */
635
+ runStreamed(input: Input, turnOptions?: TurnOptions): Promise<StreamedTurn>;
636
+ private runStreamedInternal;
637
+ /** Provides the input to the agent and returns the completed turn. */
638
+ run(input: Input, turnOptions?: TurnOptions): Promise<Turn>;
639
+ private buildTuiRequest;
640
+ /**
641
+ * Launches the interactive Codex TUI (Terminal User Interface) for this thread and returns a session handle.
642
+ *
643
+ * The handle allows advanced workflows where the TUI can be started and stopped programmatically,
644
+ * while preserving the underlying conversation state.
645
+ */
646
+ launchTui(overrides?: Partial<NativeTuiRequest>): TuiSession;
647
+ /**
648
+ * Launches the interactive Codex TUI (Terminal User Interface) for this thread.
649
+ *
650
+ * This method enables seamless transition from programmatic agent interaction to
651
+ * interactive terminal chat within the same session. The TUI takes over the terminal
652
+ * and allows you to continue the conversation interactively.
653
+ *
654
+ * @param overrides - Optional configuration to override thread defaults. Supports all TUI options
655
+ * including prompt, sandbox mode, approval mode, and resume options.
656
+ * @param options - Optional run options including an AbortSignal to request shutdown.
657
+ * @returns A Promise that resolves to TUI exit information including:
658
+ * - tokenUsage: Token consumption statistics
659
+ * - conversationId: Session ID for resuming later
660
+ * - updateAction: Optional suggested update command
661
+ * @throws {Error} If not in a trusted git repository (unless skipGitRepoCheck is set)
662
+ * @throws {Error} If the terminal is not interactive (TTY required)
663
+ */
664
+ tui(overrides?: Partial<NativeTuiRequest>, options?: RunTuiOptions): Promise<NativeTuiExitInfo>;
665
+ private wrapTuiSession;
666
+ private attachDefaultLspBridge;
667
+ private registerSkillsFromConfig;
668
+ private buildNativeInputItems;
176
669
  }
177
670
 
178
- export declare function forkThread(req: ForkRequest): Promise<ForkResult>
179
-
180
- export declare function isTokioRuntimeAvailable(): boolean
181
-
182
- export interface JsApprovalRequest {
183
- type: string
184
- details?: JsonValue
671
+ type NativeToolDefinition = NativeToolInfo & {
672
+ handler: (call: NativeToolInvocation) => Promise<NativeToolResult> | NativeToolResult;
673
+ };
674
+ type CodexOptions = {
675
+ codexPathOverride?: string;
676
+ baseUrl?: string;
677
+ apiKey?: string;
678
+ /** Optional model provider override to use instead of the default */
679
+ modelProvider?: string;
680
+ /** Default model to use when a thread omits an explicit choice */
681
+ defaultModel?: string;
682
+ tools?: NativeToolDefinition[];
683
+ /**
684
+ * When true, constructor will not clear already-registered tools on the native binding.
685
+ * Useful when other code (CLI, plugins) pre-register tools before instantiating Codex.
686
+ */
687
+ preserveRegisteredTools?: boolean;
688
+ /**
689
+ * Programmatically registered skills (no SKILL.md files required).
690
+ *
691
+ * Mention a skill by name in prompts using `$<name>` (default) or `@<name>` if enabled.
692
+ */
693
+ skills?: SkillDefinition[] | Record<string, string | Omit<SkillDefinition, "name">>;
694
+ /**
695
+ * Prefixes that activate skills when present immediately before the skill name.
696
+ *
697
+ * Defaults to `["$"]` to match Codex CLI/TUI behavior.
698
+ */
699
+ skillMentionTriggers?: SkillMentionTrigger[];
700
+ };
701
+
702
+ type CurrentChangesReview = {
703
+ type: "current_changes";
704
+ };
705
+ type BranchReview = {
706
+ type: "branch";
707
+ baseBranch: string;
708
+ };
709
+ type CommitReview = {
710
+ type: "commit";
711
+ sha: string;
712
+ subject?: string;
713
+ };
714
+ type CustomReview = {
715
+ type: "custom";
716
+ prompt: string;
717
+ hint?: string;
718
+ };
719
+ type ReviewTarget = CurrentChangesReview | BranchReview | CommitReview | CustomReview;
720
+ type ReviewInvocationOptions = {
721
+ target: ReviewTarget;
722
+ threadOptions?: ThreadOptions;
723
+ turnOptions?: TurnOptions;
724
+ };
725
+
726
+ type NativeToolInterceptorContext = {
727
+ invocation: NativeToolInvocation;
728
+ callBuiltin: (invocation?: NativeToolInvocation) => Promise<NativeToolResult>;
729
+ };
730
+ type ConversationSummary = NativeConversationSummary;
731
+ type ConversationListPage = NativeConversationListPage;
732
+ type ConversationListOptions = ThreadOptions & {
733
+ pageSize?: number;
734
+ cursor?: string;
735
+ modelProviders?: string[];
736
+ };
737
+
738
+ /**
739
+ * Codex is the main class for interacting with the Codex agent.
740
+ *
741
+ * This is the native NAPI-based implementation that uses Rust bindings directly.
742
+ *
743
+ * Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread.
744
+ */
745
+ declare class Codex {
746
+ private exec;
747
+ private options;
748
+ private readonly nativeBinding;
749
+ private readonly lspForTools;
750
+ private readonly skills;
751
+ private readonly skillMentionTriggers;
752
+ constructor(options?: CodexOptions);
753
+ registerSkill(skill: SkillDefinition): void;
754
+ registerSkills(skills: SkillDefinition[]): void;
755
+ listSkills(): SkillDefinition[];
756
+ clearSkills(): void;
757
+ /**
758
+ * Inspect currently registered native tools (for debugging/testing).
759
+ */
760
+ listRegisteredTools(): NativeToolInfo[];
761
+ private registerSkillsFromConfig;
762
+ /**
763
+ * Register a tool for Codex. When `tool.name` matches a built-in Codex tool,
764
+ * the native implementation is replaced for this Codex instance.
765
+ */
766
+ registerTool(tool: NativeToolDefinition): void;
767
+ /**
768
+ * Register a tool interceptor for Codex. Interceptors can modify tool invocations
769
+ * and results, and can call the built-in implementation.
770
+ */
771
+ registerToolInterceptor(toolName: string, handler: (context: NativeToolInterceptorContext) => Promise<NativeToolResult> | NativeToolResult): void;
772
+ /**
773
+ * Clear all registered tools, restoring built-in defaults.
774
+ */
775
+ clearTools(): void;
776
+ private buildConversationConfig;
777
+ private createLspManagerForTools;
778
+ private registerDefaultReadFileInterceptor;
779
+ /**
780
+ * Register a programmatic approval callback that Codex will call before executing
781
+ * sensitive operations (e.g., shell commands, file writes).
782
+ */
783
+ setApprovalCallback(handler: (request: ApprovalRequest) => boolean | Promise<boolean>): void;
784
+ /**
785
+ * Starts a new conversation with an agent.
786
+ * @returns A new thread instance.
787
+ */
788
+ startThread(options?: ThreadOptions): Thread;
789
+ /**
790
+ * Resumes a conversation with an agent based on the thread id.
791
+ * Threads are persisted in ~/.codex/sessions.
792
+ *
793
+ * @param id The id of the thread to resume.
794
+ * @returns A new thread instance.
795
+ */
796
+ resumeThread(id: string, options?: ThreadOptions): Thread;
797
+ listConversations(options?: ConversationListOptions): Promise<ConversationListPage>;
798
+ deleteConversation(id: string, options?: ThreadOptions): Promise<boolean>;
799
+ resumeConversationFromRollout(rolloutPath: string, options?: ThreadOptions): Promise<Thread>;
800
+ /**
801
+ * Starts a review task using the built-in Codex review flow.
802
+ */
803
+ review(options: ReviewInvocationOptions): Promise<Turn>;
804
+ /**
805
+ * Starts a review task and returns the event stream.
806
+ */
807
+ reviewStreamed(options: ReviewInvocationOptions): Promise<StreamedTurn>;
808
+ private reviewStreamedInternal;
185
809
  }
186
810
 
187
- export interface JsEmitBackgroundEventRequest {
188
- threadId: string
189
- message: string
811
+ type LspDiagnosticSeverity = "error" | "warning" | "info" | "hint";
812
+ type NormalizedDiagnostic = {
813
+ message: string;
814
+ severity: LspDiagnosticSeverity;
815
+ source?: string;
816
+ code?: string | number;
817
+ range: Diagnostic["range"];
818
+ };
819
+ type FileDiagnostics = {
820
+ path: string;
821
+ diagnostics: NormalizedDiagnostic[];
822
+ };
823
+ type WorkspaceLocator = {
824
+ type: "markers";
825
+ include: string[];
826
+ exclude?: string[];
827
+ } | {
828
+ type: "fixed";
829
+ path: string;
830
+ };
831
+ type LspServerConfig = {
832
+ id: string;
833
+ displayName: string;
834
+ command: string[];
835
+ extensions: string[];
836
+ env?: NodeJS.ProcessEnv;
837
+ initializationOptions?: Record<string, unknown>;
838
+ workspace?: WorkspaceLocator;
839
+ };
840
+ type LspManagerOptions = {
841
+ workingDirectory: string;
842
+ waitForDiagnostics?: boolean;
843
+ };
844
+
845
+ declare class LspDiagnosticsBridge {
846
+ private readonly options;
847
+ private readonly manager;
848
+ private readonly attached;
849
+ constructor(options: LspManagerOptions);
850
+ attach(thread: Thread): () => void;
851
+ dispose(): Promise<void>;
852
+ private processDiagnostics;
190
853
  }
191
854
 
192
- export interface JsEmitPlanUpdateRequest {
193
- threadId: string
194
- explanation?: string
195
- plan: Array<JsPlanItem>
855
+ /**
856
+ * Attaches the LSP diagnostics bridge to a thread.
857
+ * Returns a cleanup function that detaches the bridge and disposes shared resources.
858
+ */
859
+ declare function attachLspDiagnostics(thread: Thread, options: LspManagerOptions): () => void;
860
+
861
+ declare class LspManager {
862
+ private readonly options;
863
+ private clients;
864
+ constructor(options: LspManagerOptions);
865
+ collectDiagnostics(files: string[]): Promise<FileDiagnostics[]>;
866
+ dispose(): Promise<void>;
867
+ private getClient;
868
+ private createClient;
196
869
  }
197
870
 
198
- export interface JsModifyPlanRequest {
199
- threadId: string
200
- operations: Array<JsPlanOperation>
871
+ declare const DEFAULT_SERVERS: LspServerConfig[];
872
+ declare function findServerForFile(filePath: string): LspServerConfig | undefined;
873
+ declare function resolveWorkspaceRoot(filePath: string, locator: WorkspaceLocator | undefined, fallbackDir: string): string;
874
+
875
+ type DiagnosticSeverity = "error" | "warning" | "info" | "hint";
876
+ declare function formatDiagnosticsForTool(diagnostics: FileDiagnostics[]): string;
877
+ declare function formatDiagnosticsForBackgroundEvent(diagnostics: FileDiagnostics[], cwd: string): string;
878
+ /**
879
+ * Filter diagnostics by minimum severity level
880
+ */
881
+ declare function filterBySeverity(diagnostics: FileDiagnostics[], minSeverity?: DiagnosticSeverity): FileDiagnostics[];
882
+ /**
883
+ * Generate summary statistics for diagnostics
884
+ */
885
+ declare function summarizeDiagnostics(diagnostics: FileDiagnostics[]): {
886
+ fileCount: number;
887
+ errorCount: number;
888
+ warningCount: number;
889
+ infoCount: number;
890
+ hintCount: number;
891
+ totalCount: number;
892
+ };
893
+ /**
894
+ * Format diagnostics with summary (concise format for post-merge validation)
895
+ */
896
+ declare function formatDiagnosticsWithSummary(diagnostics: FileDiagnostics[], cwd: string, options?: {
897
+ minSeverity?: DiagnosticSeverity;
898
+ maxPerFile?: number;
899
+ }): string;
900
+
901
+ /**
902
+ * Options for creating a CodexProvider
903
+ */
904
+ interface CodexProviderOptions extends CodexOptions {
905
+ /**
906
+ * Default model to use when none is specified
907
+ */
908
+ defaultModel?: string;
909
+ /**
910
+ * Approval policy forwarded to threads created by this provider.
911
+ */
912
+ approvalMode?: ThreadOptions["approvalMode"];
913
+ /**
914
+ * Use local OSS provider via Ollama (pulls models as needed)
915
+ */
916
+ oss?: boolean;
917
+ /**
918
+ * Working directory for Codex operations
919
+ * @default process.cwd()
920
+ */
921
+ workingDirectory?: string;
922
+ /**
923
+ * Skip git repository check
924
+ * @default false
925
+ */
926
+ skipGitRepoCheck?: boolean;
927
+ /**
928
+ * Sandbox policy to use when executing shell commands
929
+ * @default "danger-full-access"
930
+ */
931
+ sandboxMode?: ThreadOptions["sandboxMode"];
932
+ /**
933
+ * Reasoning effort level for reasoning-capable models
934
+ * @default "medium"
935
+ */
936
+ reasoningEffort?: ThreadOptions["reasoningEffort"];
937
+ /**
938
+ * Reasoning summary preference for reasoning-capable models
939
+ * @default "auto"
940
+ */
941
+ reasoningSummary?: ThreadOptions["reasoningSummary"];
942
+ /**
943
+ * Enable LSP diagnostics for threads created by this provider
944
+ * @default true
945
+ */
946
+ enableLsp?: boolean;
201
947
  }
202
-
203
- export interface JsPlanItem {
204
- step: string
205
- status?: string
948
+ /**
949
+ * Provider implementation that uses Codex as the backend for OpenAI Agents
950
+ *
951
+ * @example
952
+ * ```typescript
953
+ * import { CodexProvider } from '@codex-native/sdk/agents';
954
+ * import { Agent, Runner } from '@openai/agents';
955
+ *
956
+ * const provider = new CodexProvider({
957
+ * defaultModel: 'gpt-5.2-codex'
958
+ * });
959
+ *
960
+ * const agent = new Agent({
961
+ * name: 'CodeAssistant',
962
+ * instructions: 'You are a helpful coding assistant'
963
+ * });
964
+ *
965
+ * const runner = new Runner({ modelProvider: provider });
966
+ * const result = await runner.run(agent, 'Fix the failing tests');
967
+ * ```
968
+ */
969
+ declare class CodexProvider implements ModelProvider {
970
+ private codex;
971
+ private options;
972
+ constructor(options?: CodexProviderOptions);
973
+ /**
974
+ * Lazy initialization of Codex instance
975
+ */
976
+ private getCodex;
977
+ getModel(modelName?: string): Model;
978
+ /**
979
+ * Register a programmatic approval callback on the underlying Codex instance.
980
+ */
981
+ setApprovalCallback(callback: (request: ApprovalRequest) => boolean | Promise<boolean>): void;
206
982
  }
207
983
 
208
- export interface JsPlanOperation {
209
- type: string
210
- item?: JsPlanItem
211
- index?: number
212
- updates?: JsPlanUpdate
213
- newOrder?: Array<number>
984
+ type BaseToolOptions = Parameters<typeof tool>[0];
985
+ type AgentTool = ReturnType<typeof tool>;
986
+ type CodexToolOptions = BaseToolOptions & {
987
+ codexExecute?: (input: unknown) => Promise<unknown> | unknown;
988
+ };
989
+ declare function codexTool(options: CodexToolOptions): AgentTool;
990
+
991
+ type ToolCallEvent = {
992
+ name?: string;
993
+ input?: unknown;
994
+ output?: unknown;
995
+ status?: "started" | "completed";
996
+ };
997
+ type FormattedStream = {
998
+ text: string;
999
+ reasoning: string;
1000
+ toolCalls: ToolCallEvent[];
1001
+ usage?: {
1002
+ requests?: number;
1003
+ inputTokens: number;
1004
+ outputTokens: number;
1005
+ totalTokens: number;
1006
+ inputTokensDetails?: Record<string, number>;
1007
+ outputTokensDetails?: Record<string, number>;
1008
+ };
1009
+ /**
1010
+ * Convenience field when providers report cached tokens (e.g. via inputTokensDetails.cachedTokens)
1011
+ */
1012
+ cachedTokens?: number;
1013
+ responseId?: string;
1014
+ /**
1015
+ * Raw provider-specific data (e.g., costs, cache hit ratios, rate limit info)
1016
+ */
1017
+ providerData?: Record<string, unknown>;
1018
+ errors: {
1019
+ message: string;
1020
+ }[];
1021
+ };
1022
+ type FormatStreamOptions = {
1023
+ onUpdate?: (partial: Partial<FormattedStream>) => void;
1024
+ };
1025
+ /**
1026
+ * Consume a stream of StreamEvent and aggregate into a coherent object:
1027
+ * - Concatenates output_text deltas into `text`
1028
+ * - Concatenates reasoning deltas into `reasoning`
1029
+ * - Captures usage and responseId on response_done
1030
+ * - Prepares space for tool call events (future-friendly; empty for now)
1031
+ *
1032
+ * Optionally invokes `onUpdate` with partial snapshots as data arrives.
1033
+ */
1034
+ declare function formatStream(stream: AsyncIterable<StreamEvent>, options?: FormatStreamOptions): Promise<FormattedStream>;
1035
+
1036
+ type PermissionDecision = boolean | "once" | "always" | "reject" | {
1037
+ response: "once" | "always" | "reject";
1038
+ };
1039
+ interface PermissionRequest {
1040
+ id: string;
1041
+ type: string;
1042
+ title: string;
1043
+ sessionId: string;
1044
+ metadata: Record<string, unknown>;
1045
+ pattern?: string | string[];
214
1046
  }
215
-
216
- export interface JsPlanUpdate {
217
- step?: string
218
- status?: string
1047
+ interface OpenCodeAgentOptions {
1048
+ /** Fully qualified base URL for an existing opencode server. When omitted the agent will start its own server. */
1049
+ baseUrl?: string;
1050
+ /** Hostname passed to `createOpencode` when auto-starting the server. */
1051
+ hostname?: string;
1052
+ /** Port passed to `createOpencode` when auto-starting the server. */
1053
+ port?: number;
1054
+ /** Additional configuration forwarded to `createOpencode`. */
1055
+ config?: Record<string, unknown>;
1056
+ /** Preferred model string in the form `provider/model`. */
1057
+ model?: string;
1058
+ /** Directory the OpenCode session should operate within. Defaults to the current working directory. */
1059
+ workingDirectory?: string;
1060
+ /** Optional user-friendly session title. */
1061
+ title?: string;
1062
+ /** Callback invoked whenever opencode asks for a permission decision. */
1063
+ onApprovalRequest?: (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
1064
+ /** Override for tests – returns a hydrated opencode client. */
1065
+ clientFactory?: () => Promise<{
1066
+ client: OpencodeClient;
1067
+ close?: () => void;
1068
+ }>;
219
1069
  }
220
-
221
- export interface JsToolInterceptorContext {
222
- invocation: JsToolInvocation
223
- token: string
1070
+ interface DelegationResult {
1071
+ sessionId: string;
1072
+ /** Deprecated alias retained for backwards compatibility. */
1073
+ threadId?: string;
1074
+ output: string;
1075
+ success: boolean;
1076
+ error?: string;
1077
+ usage?: Usage | null;
224
1078
  }
225
-
226
- export interface JsToolInvocation {
227
- callId: string
228
- toolName: string
229
- arguments?: string
230
- input?: string
1079
+ declare class OpenCodeAgent {
1080
+ private readonly options;
1081
+ private readonly approvalHandler?;
1082
+ private clientPromise?;
1083
+ private closeCallback?;
1084
+ constructor(options?: OpenCodeAgentOptions);
1085
+ /**
1086
+ * Cleanup method to shut down the OpenCode server if one was started.
1087
+ * Should be called when done using the agent to prevent zombie processes.
1088
+ */
1089
+ close(): Promise<void>;
1090
+ delegate(task: string): Promise<DelegationResult>;
1091
+ delegateStreaming(task: string, onEvent?: (event: Event) => void, sessionId?: string): Promise<DelegationResult>;
1092
+ resume(sessionId: string, task: string): Promise<DelegationResult>;
1093
+ workflow(steps: string[]): Promise<DelegationResult[]>;
1094
+ private executeTask;
1095
+ private ensureClient;
1096
+ private ensureSession;
1097
+ private createSessionTitle;
1098
+ private parseModel;
1099
+ private collectText;
1100
+ private toUsage;
1101
+ private extractData;
1102
+ private describeError;
1103
+ private watchEvents;
1104
+ private extractSessionId;
1105
+ private respondToPermission;
1106
+ private normalizeDecision;
1107
+ private getWorkingDirectory;
231
1108
  }
232
1109
 
233
- export declare const enum LayoutType {
234
- Split = 0,
235
- Tabs = 1,
236
- Grid = 2,
237
- Stack = 3
1110
+ type CloudTaskStatus = "pending" | "ready" | "applied" | "error";
1111
+ type DiffSummary = {
1112
+ files_changed: number;
1113
+ lines_added: number;
1114
+ lines_removed: number;
1115
+ };
1116
+ type CloudTaskSummary = {
1117
+ id: string;
1118
+ title: string;
1119
+ status: CloudTaskStatus;
1120
+ updated_at: string;
1121
+ environment_id?: string | null;
1122
+ environment_label?: string | null;
1123
+ summary: DiffSummary;
1124
+ is_review?: boolean;
1125
+ attempt_total?: number | null;
1126
+ };
1127
+ type CloudApplyStatus = "success" | "partial" | "error";
1128
+ type CloudApplyOutcome = {
1129
+ applied: boolean;
1130
+ status: CloudApplyStatus;
1131
+ message: string;
1132
+ skipped_paths: string[];
1133
+ conflict_paths: string[];
1134
+ };
1135
+ type CloudTaskCreateResult = {
1136
+ id: string;
1137
+ };
1138
+ type CloudTasksOptions = {
1139
+ baseUrl?: string;
1140
+ apiKey?: string;
1141
+ };
1142
+ declare class CloudTasks {
1143
+ private readonly options;
1144
+ constructor(options?: CloudTasksOptions);
1145
+ private binding;
1146
+ list(env?: string): Promise<CloudTaskSummary[]>;
1147
+ getDiff(taskId: string): Promise<string | null>;
1148
+ applyPreflight(taskId: string, diffOverride?: string): Promise<CloudApplyOutcome>;
1149
+ apply(taskId: string, diffOverride?: string): Promise<CloudApplyOutcome>;
1150
+ create(envId: string, prompt: string, opts?: {
1151
+ gitRef?: string;
1152
+ qaMode?: boolean;
1153
+ bestOfN?: number;
1154
+ }): Promise<CloudTaskCreateResult>;
238
1155
  }
239
1156
 
240
- export declare function listConversations(req: ListConversationsRequest): Promise<ConversationListPage>
241
-
242
- export interface ListConversationsRequest {
243
- config?: ConversationConfigRequest
244
- pageSize?: number
245
- cursor?: string
246
- modelProviders?: Array<string>
1157
+ /**
1158
+ * Log level enumeration
1159
+ */
1160
+ declare enum LogLevel {
1161
+ DEBUG = 0,
1162
+ INFO = 1,
1163
+ WARN = 2,
1164
+ ERROR = 3,
1165
+ SILENT = 4
247
1166
  }
248
-
249
- export declare function modifyPlan(req: JsModifyPlanRequest): void
250
-
251
- export interface NativeToolInfo {
252
- name: string
253
- description?: string
254
- parameters?: JsonValue
255
- strict?: boolean
256
- supportsParallel?: boolean
1167
+ /**
1168
+ * Log scopes for different subsystems
1169
+ */
1170
+ type LogScope = "thread" | "merge" | "git" | "coordinator" | "worker" | "supervisor" | "reviewer" | "validation" | "lsp" | "agent" | "provider" | "ci" | "test" | "system";
1171
+ /**
1172
+ * Configuration for logger instances
1173
+ */
1174
+ interface LoggerConfig {
1175
+ /** Minimum log level to output */
1176
+ level?: LogLevel;
1177
+ /** Enable colored output (default: true for TTY) */
1178
+ colors?: boolean;
1179
+ /** Include timestamps in output (default: false) */
1180
+ timestamps?: boolean;
1181
+ /** Prefix for all log messages */
1182
+ prefix?: string;
1183
+ /** Enable structured JSON output instead of formatted text */
1184
+ json?: boolean;
1185
+ /** Custom output stream (default: console) */
1186
+ output?: LogOutput;
257
1187
  }
258
-
259
- export interface NativeToolResponse {
260
- output?: string
261
- success?: boolean
262
- error?: string
1188
+ /**
1189
+ * Output interface for log messages
1190
+ */
1191
+ interface LogOutput {
1192
+ debug(message: string): void;
1193
+ info(message: string): void;
1194
+ warn(message: string): void;
1195
+ error(message: string): void;
263
1196
  }
264
-
265
- export declare function registerApprovalCallback(handler: (request: JsApprovalRequest) => boolean | Promise<boolean>): void
266
-
267
- export declare function registerTool(info: NativeToolInfo, handler: (call: JsToolInvocation) => NativeToolResponse | Promise<NativeToolResponse>): void
268
-
269
- export declare function registerToolInterceptor(toolName: string, handler: (context: JsToolInterceptorContext) => NativeToolResponse | Promise<NativeToolResponse>): void
270
-
271
- export interface RepoDiffFileChange {
272
- path: string
273
- status: string
274
- diff: string
275
- truncated: boolean
276
- previousPath?: string
1197
+ /**
1198
+ * Thread logging sink interface
1199
+ */
1200
+ interface ThreadLoggingSink {
1201
+ info(message: string): void;
1202
+ warn(message: string): void;
1203
+ recordUsage?(usage: Usage): void;
277
1204
  }
278
-
279
- export interface RepoDiffOptions {
280
- maxFiles?: number
281
- diffContextLines?: number
282
- diffCharLimit?: number
1205
+ /**
1206
+ * Structured log entry for JSON output
1207
+ */
1208
+ interface LogEntry {
1209
+ timestamp: string;
1210
+ level: string;
1211
+ scope?: string;
1212
+ subject?: string;
1213
+ message: string;
1214
+ data?: Record<string, unknown>;
283
1215
  }
284
1216
 
285
- export interface RepoDiffSummary {
286
- repoPath: string
287
- branch: string
288
- baseBranch: string
289
- upstreamRef?: string
290
- mergeBase: string
291
- statusSummary: string
292
- diffStat: string
293
- recentCommits: string
294
- changedFiles: Array<RepoDiffFileChange>
295
- totalChangedFiles: number
1217
+ /**
1218
+ * Centralized logger with support for scopes, levels, and structured output
1219
+ */
1220
+ declare class Logger {
1221
+ private level;
1222
+ private colors;
1223
+ private timestamps;
1224
+ private prefix;
1225
+ private json;
1226
+ private output;
1227
+ constructor(config?: LoggerConfig);
1228
+ /**
1229
+ * Create a new logger with modified configuration
1230
+ */
1231
+ configure(config: Partial<LoggerConfig>): Logger;
1232
+ /**
1233
+ * Create a scoped logger
1234
+ */
1235
+ scope(scope: LogScope, subject?: string): ScopedLogger;
1236
+ /**
1237
+ * Log a debug message
1238
+ */
1239
+ debug(message: string, data?: Record<string, unknown>): void;
1240
+ /**
1241
+ * Log an info message
1242
+ */
1243
+ info(message: string, data?: Record<string, unknown>): void;
1244
+ /**
1245
+ * Log a warning message
1246
+ */
1247
+ warn(message: string, data?: Record<string, unknown>): void;
1248
+ /**
1249
+ * Log an error message
1250
+ */
1251
+ error(message: string, data?: Record<string, unknown>): void;
1252
+ /**
1253
+ * Internal log method
1254
+ */
1255
+ private log;
1256
+ /**
1257
+ * Log in JSON format
1258
+ */
1259
+ private logJson;
1260
+ /**
1261
+ * Log in formatted text
1262
+ */
1263
+ private logFormatted;
1264
+ /**
1265
+ * Internal scoped log method (used by ScopedLogger)
1266
+ */
1267
+ logScoped(level: LogLevel, message: string, scope: LogScope, subject?: string, data?: Record<string, unknown>): void;
296
1268
  }
297
-
298
- export declare function resumeConversationFromRollout(req: ResumeFromRolloutRequest): Promise<ForkResult>
299
-
300
- export interface ResumeFromRolloutRequest {
301
- rolloutPath: string
302
- config?: ConversationConfigRequest
1269
+ /**
1270
+ * Scoped logger for a specific subsystem
1271
+ */
1272
+ declare class ScopedLogger {
1273
+ private logger;
1274
+ private scope;
1275
+ private subject?;
1276
+ constructor(logger: Logger, scope: LogScope, subject?: string | undefined);
1277
+ /**
1278
+ * Log a debug message
1279
+ */
1280
+ debug(message: string, data?: Record<string, unknown>): void;
1281
+ /**
1282
+ * Log an info message
1283
+ */
1284
+ info(message: string, data?: Record<string, unknown>): void;
1285
+ /**
1286
+ * Log a warning message
1287
+ */
1288
+ warn(message: string, data?: Record<string, unknown>): void;
1289
+ /**
1290
+ * Log an error message
1291
+ */
1292
+ error(message: string, data?: Record<string, unknown>): void;
1293
+ /**
1294
+ * Create a ThreadLoggingSink adapter
1295
+ */
1296
+ asThreadSink(): ThreadLoggingSink;
303
1297
  }
304
-
305
- export interface ReverieConversation {
306
- id: string
307
- path: string
308
- createdAt?: string
309
- updatedAt?: string
310
- headRecords: Array<string>
311
- tailRecords: Array<string>
312
- headRecordsToon: Array<string>
313
- tailRecordsToon: Array<string>
1298
+ /**
1299
+ * Global default logger instance
1300
+ */
1301
+ declare const logger: Logger;
1302
+
1303
+ /**
1304
+ * Create a thread logging sink from a scoped logger
1305
+ */
1306
+ declare function createThreadLogger(scopedLogger: ScopedLogger, onUsage?: (usage: Usage) => void): ThreadLoggingSink;
1307
+ /**
1308
+ * Run a thread turn with automatic event logging
1309
+ */
1310
+ declare function runThreadTurnWithLogs(thread: Thread, sink: ThreadLoggingSink, prompt: string, turnOptions?: TurnOptions): Promise<Turn>;
1311
+
1312
+ /**
1313
+ * Reverie System Constants
1314
+ *
1315
+ * Configuration constants for reverie search, filtering, and grading.
1316
+ * These values are tuned for optimal balance between result quality and performance.
1317
+ */
1318
+ /**
1319
+ * Default number of final reverie insights to return.
1320
+ * After all filtering and grading, this is the target result count.
1321
+ */
1322
+ declare const DEFAULT_REVERIE_LIMIT = 6;
1323
+ /**
1324
+ * Maximum number of candidate insights to fetch initially.
1325
+ * We fetch many candidates upfront and then filter aggressively.
1326
+ */
1327
+ declare const DEFAULT_REVERIE_MAX_CANDIDATES = 80;
1328
+ /**
1329
+ * Embedding model for semantic search.
1330
+ * Large model provides better semantic understanding at cost of memory/speed.
1331
+ */
1332
+ declare const REVERIE_EMBED_MODEL = "BAAI/bge-large-en-v1.5";
1333
+ /**
1334
+ * Reranker model for improving search precision.
1335
+ * Applied after initial embedding search to rerank top candidates.
1336
+ */
1337
+ declare const REVERIE_RERANKER_MODEL = "rozgo/bge-reranker-v2-m3";
1338
+ /**
1339
+ * Candidate multiplier for aggressive filtering.
1340
+ * Fetch 3x candidates since we'll filter heavily for quality.
1341
+ */
1342
+ declare const REVERIE_CANDIDATE_MULTIPLIER = 3;
1343
+ /**
1344
+ * Minimum relevance score threshold for LLM grading.
1345
+ * Only insights scoring >= 0.7 are sent for expensive LLM evaluation.
1346
+ * This optimizes API costs by skipping obvious low-quality candidates.
1347
+ */
1348
+ declare const REVERIE_LLM_GRADE_THRESHOLD = 0.7;
1349
+ /**
1350
+ * Default reranker top-k value.
1351
+ * Number of results to rerank after initial retrieval.
1352
+ */
1353
+ declare const DEFAULT_RERANKER_TOP_K = 20;
1354
+ /**
1355
+ * Default reranker batch size.
1356
+ * Number of candidates to process per reranker batch.
1357
+ */
1358
+ declare const DEFAULT_RERANKER_BATCH_SIZE = 8;
1359
+
1360
+ /**
1361
+ * Reverie Type Definitions
1362
+ *
1363
+ * Core types used throughout the reverie system.
1364
+ */
1365
+ /**
1366
+ * Represents a single reverie insight from past conversations.
1367
+ */
1368
+ interface ReverieInsight$1 {
1369
+ /** Unique identifier for the conversation */
1370
+ conversationId: string;
1371
+ /** ISO timestamp of when the conversation occurred */
1372
+ timestamp: string;
1373
+ /** Relevance score from semantic search (0-1) */
1374
+ relevance: number;
1375
+ /** Text excerpt from the conversation */
1376
+ excerpt: string;
1377
+ /** Extracted insights or key points from the excerpt */
1378
+ insights: string[];
314
1379
  }
315
-
316
- export declare function reverieGetConversationInsights(conversationPath: string, query?: string | undefined | null): Promise<Array<string>>
317
-
318
- export declare function reverieIndexSemantic(codexHomePath: string, options?: ReverieSemanticSearchOptions | undefined | null): Promise<ReverieSemanticIndexStats>
319
-
320
- export declare function reverieListConversations(codexHomePath: string, limit?: number | undefined | null, offset?: number | undefined | null): Promise<Array<ReverieConversation>>
321
-
322
- /** Search using blocks from the current ongoing conversation to find similar past sessions */
323
- export declare function reverieSearchByConversation(codexHomePath: string, conversationMessages: Array<string>, options?: ReverieSemanticSearchOptions | undefined | null): Promise<Array<ReverieSearchResult>>
324
-
325
- export declare function reverieSearchConversations(codexHomePath: string, query: string, limit?: number | undefined | null): Promise<Array<ReverieSearchResult>>
326
-
327
- export interface ReverieSearchResult {
328
- conversation: ReverieConversation
329
- relevanceScore: number
330
- matchingExcerpts: Array<string>
331
- insights: Array<string>
332
- rerankerScore?: number
1380
+ interface ReverieEpisodeSummary {
1381
+ conversationId: string;
1382
+ episodeId: string;
1383
+ timestamp: string;
1384
+ summary: string;
1385
+ keyDecisions?: string[];
1386
+ importance?: number;
333
1387
  }
334
-
335
- export declare function reverieSearchSemantic(codexHomePath: string, contextText: string, options?: ReverieSemanticSearchOptions | undefined | null): Promise<Array<ReverieSearchResult>>
336
-
337
- export interface ReverieSemanticIndexStats {
338
- conversationsIndexed: number
339
- documentsEmbedded: number
340
- batches: number
1388
+ /**
1389
+ * Options for reverie semantic search.
1390
+ */
1391
+ interface ReverieSearchOptions {
1392
+ /** Maximum number of final results to return (after all filtering) */
1393
+ limit?: number;
1394
+ /** Maximum number of candidates to fetch initially */
1395
+ maxCandidates?: number;
1396
+ /** Whether to use reranker for improving precision */
1397
+ useReranker?: boolean;
1398
+ /** Reranker model identifier */
1399
+ rerankerModel?: string;
1400
+ /** Number of results to rerank */
1401
+ rerankerTopK?: number;
1402
+ /** Batch size for reranking operations */
1403
+ rerankerBatchSize?: number;
1404
+ /** Multiplier for candidate fetching (fetch N × limit candidates) */
1405
+ candidateMultiplier?: number;
341
1406
  }
342
-
343
- export interface ReverieSemanticSearchOptions {
344
- limit?: number
345
- maxCandidates?: number
346
- projectRoot?: string
347
- batchSize?: number
348
- normalize?: boolean
349
- cache?: boolean
350
- rerankerModel?: string
351
- rerankerCacheDir?: string
352
- rerankerMaxLength?: number
353
- rerankerShowProgress?: boolean
354
- rerankerBatchSize?: number
355
- rerankerTopK?: number
1407
+ /**
1408
+ * Options for LLM-based relevance grading.
1409
+ */
1410
+ interface GradingOptions {
1411
+ /** Minimum relevance score to trigger LLM grading (default: 0.7) */
1412
+ minRelevanceForGrading?: number;
1413
+ /** Whether to grade insights in parallel (default: true) */
1414
+ parallel?: boolean;
356
1415
  }
357
-
358
- export declare function runApplyPatch(patch: string): void
359
-
360
- export interface RunRequest {
361
- prompt: string
362
- inputItems?: JsonValue
363
- threadId?: string
364
- images?: Array<string>
365
- model?: string
366
- modelProvider?: string
367
- oss?: boolean
368
- sandboxMode?: string
369
- approvalMode?: string
370
- workspaceWriteOptions?: WorkspaceWriteOptions
371
- reviewMode?: boolean
372
- reviewHint?: string
373
- workingDirectory?: string
374
- skipGitRepoCheck?: boolean
375
- outputSchema?: JsonValue
376
- baseUrl?: string
377
- apiKey?: string
378
- linuxSandboxPath?: string
379
- reasoningEffort?: string
380
- reasoningSummary?: string
381
- fullAuto?: boolean
1416
+ /**
1417
+ * Statistics from reverie filtering pipeline.
1418
+ */
1419
+ interface ReverieFilterStats {
1420
+ /** Total raw results from search */
1421
+ total: number;
1422
+ /** Results after basic quality filtering */
1423
+ afterQuality: number;
1424
+ /** Results after embedding-based boilerplate filtering */
1425
+ afterBoilerplate?: number;
1426
+ /** Results after relevance score threshold */
1427
+ afterScore: number;
1428
+ /** Results after deduplication */
1429
+ afterDedup: number;
1430
+ /** Results after LLM grading */
1431
+ afterLLMGrade?: number;
1432
+ /** Final result count */
1433
+ final: number;
382
1434
  }
383
-
384
- export declare function runThread(req: RunRequest): Promise<unknown>
385
-
386
- export declare function runThreadStream(req: RunRequest, onEvent: (err: unknown, eventJson?: string) => void): Promise<unknown>
387
-
388
- export declare function runTui(req: TuiRequest): Promise<TuiExitInfo>
389
-
390
- export declare function sse(events: Array<string>): string
391
-
392
- export declare function startTui(req: TuiRequest): TuiSession
393
-
394
- export interface TokenizerBaseOptions {
395
- model?: string
396
- encoding?: "o200k_base" | "cl100k_base"
1435
+ /**
1436
+ * Complete pipeline options combining search, filtering, and grading.
1437
+ */
1438
+ interface ReveriePipelineOptions extends ReverieSearchOptions, GradingOptions {
1439
+ /** Whether to skip LLM grading entirely (default: false) */
1440
+ skipLLMGrading?: boolean;
397
1441
  }
398
-
399
- export declare function tokenizerCount(text: string, options?: TokenizerBaseOptions | undefined | null): number
400
-
401
- export declare function tokenizerDecode(tokens: Array<number>, options?: TokenizerBaseOptions | undefined | null): string
402
-
403
- export declare function tokenizerEncode(text: string, options?: TokenizerEncodeOptions | undefined | null): Array<number>
404
-
405
- export interface TokenizerEncodeOptions {
406
- model?: string
407
- encoding?: "o200k_base" | "cl100k_base"
408
- withSpecialTokens?: boolean
1442
+ /**
1443
+ * Reverie search level types for multi-level search hierarchy.
1444
+ */
1445
+ type ReverieSearchLevel = 'project' | 'branch' | 'file';
1446
+ /**
1447
+ * Project-level search context for repository-wide patterns.
1448
+ */
1449
+ interface ProjectLevelContext {
1450
+ /** Search level identifier */
1451
+ level: 'project';
1452
+ /** Repository root path */
1453
+ repoPath: string;
1454
+ /** Search query describing what to find */
1455
+ query: string;
1456
+ /** Optional file patterns to filter search scope (e.g., ["*.ts", "src/**"]) */
1457
+ filePatterns?: string[];
409
1458
  }
410
-
411
- export interface TokenUsageSummary {
412
- inputTokens: number
413
- cachedInputTokens: number
414
- outputTokens: number
415
- reasoningOutputTokens: number
416
- totalTokens: number
1459
+ /**
1460
+ * Branch-level search context for feature/branch-specific work.
1461
+ */
1462
+ interface BranchLevelContext {
1463
+ /** Search level identifier */
1464
+ level: 'branch';
1465
+ /** Repository root path */
1466
+ repoPath: string;
1467
+ /** Current branch name */
1468
+ branch: string;
1469
+ /** Base branch for comparison (e.g., "main") */
1470
+ baseBranch?: string;
1471
+ /** List of changed file paths in this branch */
1472
+ changedFiles: string[];
1473
+ /** Recent commit messages or summaries */
1474
+ recentCommits?: string;
417
1475
  }
418
-
419
- export declare function toonEncode(value: JsonValue): string
420
-
421
- export interface TuiExitInfo {
422
- tokenUsage: TokenUsageSummary
423
- conversationId?: string
424
- updateAction?: UpdateActionInfo
425
- }
426
-
427
- export interface TuiRequest {
428
- prompt?: string
429
- images?: Array<string>
430
- model?: string
431
- oss?: boolean
432
- sandboxMode?: string
433
- approvalMode?: string
434
- resumeSessionId?: string
435
- resumeLast?: boolean
436
- resumePicker?: boolean
437
- fullAuto?: boolean
438
- dangerouslyBypassApprovalsAndSandbox?: boolean
439
- workingDirectory?: string
440
- configProfile?: string
441
- configOverrides?: Array<string>
442
- addDir?: Array<string>
443
- webSearch?: boolean
444
- linuxSandboxPath?: string
445
- baseUrl?: string
446
- apiKey?: string
447
- reasoningEffort?: string
448
- reasoningSummary?: string
449
- }
450
-
451
- export interface TuiTestRequest {
452
- width: number
453
- height: number
454
- viewport: TuiTestViewport
455
- lines: Array<string>
1476
+ /**
1477
+ * File-level search context for individual file changes.
1478
+ */
1479
+ interface FileLevelContext {
1480
+ /** Search level identifier */
1481
+ level: 'file';
1482
+ /** Repository root path */
1483
+ repoPath: string;
1484
+ /** Path to the file being analyzed */
1485
+ filePath: string;
1486
+ /** Git diff or change content */
1487
+ diff?: string;
1488
+ /** Extracted symbols from the file (functions, classes, etc.) */
1489
+ symbols?: string[];
456
1490
  }
457
-
458
- export declare function tuiTestRun(req: TuiTestRequest): Array<string>
459
-
460
- export interface TuiTestViewport {
461
- x: number
462
- y: number
463
- width: number
464
- height: number
1491
+ /**
1492
+ * Union type representing any level of search context.
1493
+ */
1494
+ type ReverieContext = ProjectLevelContext | BranchLevelContext | FileLevelContext;
1495
+
1496
+ /**
1497
+ * Reverie Quality Utilities
1498
+ *
1499
+ * Provides filtering, deduplication, and quality assessment for reverie search results.
1500
+ * Ensures that only meaningful conversation excerpts are surfaced to agents and users.
1501
+ */
1502
+ /**
1503
+ * Represents a single reverie insight from past conversations.
1504
+ * This is a generic interface that can be extended with additional metadata.
1505
+ */
1506
+ interface ReverieInsight {
1507
+ /** Unique identifier for the conversation */
1508
+ conversationId: string;
1509
+ /** ISO timestamp of when the conversation occurred */
1510
+ timestamp: string;
1511
+ /** Relevance score from semantic search (0-1) */
1512
+ relevance: number;
1513
+ /** Text excerpt from the conversation */
1514
+ excerpt: string;
1515
+ /** Extracted insights or key points from the excerpt */
1516
+ insights: string[];
465
1517
  }
466
-
467
- export interface UpdateActionInfo {
468
- kind: string
469
- command: string
1518
+ /**
1519
+ * Type alias for reverie results (used for logging compatibility).
1520
+ */
1521
+ type ReverieResult = ReverieInsight;
1522
+ /**
1523
+ * Statistics from the quality filtering pipeline.
1524
+ */
1525
+ interface QualityFilterStats {
1526
+ /** Number of insights before filtering */
1527
+ initial: number;
1528
+ /** Number after validity filtering */
1529
+ afterValidityFilter: number;
1530
+ /** Number after deduplication */
1531
+ afterDeduplication: number;
1532
+ /** Final number of insights */
1533
+ final: number;
470
1534
  }
471
-
472
- export declare const enum WidgetType {
473
- Text = 0,
474
- Chat = 1,
475
- Terminal = 2,
476
- ProgressBar = 3,
477
- StatusLine = 4,
478
- Table = 5,
479
- FileTree = 6,
480
- Markdown = 7
1535
+ /**
1536
+ * Validates whether a reverie excerpt contains meaningful content worth indexing.
1537
+ *
1538
+ * Filters out:
1539
+ * - Very short excerpts (< 20 chars)
1540
+ * - System prompts and boilerplate text
1541
+ * - Tool outputs and structured data
1542
+ * - Excerpts with excessive XML/HTML tags
1543
+ * - JSON objects and configuration snippets
1544
+ *
1545
+ * @param excerpt - The text excerpt to validate
1546
+ * @returns true if the excerpt contains meaningful content, false otherwise
1547
+ *
1548
+ * @example
1549
+ * ```typescript
1550
+ * const excerpt = "Let's refactor the auth module to use async/await";
1551
+ * isValidReverieExcerpt(excerpt); // true
1552
+ *
1553
+ * const systemPrompt = "<INSTRUCTIONS>You are a coding assistant</INSTRUCTIONS>";
1554
+ * isValidReverieExcerpt(systemPrompt); // false
1555
+ * ```
1556
+ */
1557
+ declare function isValidReverieExcerpt(excerpt: string): boolean;
1558
+ /**
1559
+ * Removes duplicate or highly similar reverie insights based on content fingerprinting.
1560
+ *
1561
+ * CRITICAL FIX: Groups by fingerprint and keeps the insight with the HIGHEST relevance score.
1562
+ * Previous implementations incorrectly kept the first occurrence, which could discard
1563
+ * higher-quality duplicates found later in the list.
1564
+ *
1565
+ * Uses the first 100 characters of each excerpt (normalized) as a fingerprint
1566
+ * to identify duplicates. This prevents redundant insights from being shown
1567
+ * to the user while preserving the most relevant unique insights.
1568
+ *
1569
+ * @param insights - Array of reverie insights to deduplicate
1570
+ * @returns Deduplicated array of reverie insights, sorted by relevance (highest first)
1571
+ *
1572
+ * @example
1573
+ * ```typescript
1574
+ * const insights = [
1575
+ * { excerpt: "We refactored the auth module...", relevance: 0.7, ... },
1576
+ * { excerpt: "We refactored the auth module to use async/await", relevance: 0.9, ... },
1577
+ * { excerpt: "Updated the database schema", relevance: 0.8, ... }
1578
+ * ];
1579
+ *
1580
+ * const deduplicated = deduplicateReverieInsights(insights);
1581
+ * // Returns 2 insights: the higher-scoring auth one (0.9) and the database one (0.8)
1582
+ * ```
1583
+ */
1584
+ declare function deduplicateReverieInsights<T extends ReverieInsight>(insights: T[]): T[];
1585
+ /**
1586
+ * Applies the complete quality pipeline to reverie insights.
1587
+ *
1588
+ * Pipeline steps:
1589
+ * 1. Filter out invalid excerpts (system prompts, boilerplate, etc.)
1590
+ * 2. Deduplicate similar insights, keeping highest relevance
1591
+ * 3. Sort by relevance score (highest first)
1592
+ * 4. Limit to top N results
1593
+ *
1594
+ * @param insights - Raw reverie insights from search
1595
+ * @param limit - Maximum number of insights to return (default: 10)
1596
+ * @returns Filtered, deduplicated, and sorted insights with statistics
1597
+ *
1598
+ * @example
1599
+ * ```typescript
1600
+ * const rawInsights = await reverieSearchSemantic(codexHome, query, options);
1601
+ * const { insights, stats } = applyQualityPipeline(rawInsights, 5);
1602
+ *
1603
+ * console.log(`Filtered ${stats.initial} → ${stats.final} insights`);
1604
+ * insights.forEach(insight => {
1605
+ * console.log(`[${insight.relevance.toFixed(2)}] ${insight.excerpt.slice(0, 100)}`);
1606
+ * });
1607
+ * ```
1608
+ */
1609
+ declare function applyQualityPipeline<T extends ReverieInsight>(insights: T[], limit?: number): {
1610
+ insights: T[];
1611
+ stats: QualityFilterStats;
1612
+ };
1613
+
1614
+ /**
1615
+ * LLM-Based Relevance Grading for Reverie Insights
1616
+ *
1617
+ * Uses an LLM to evaluate whether reverie excerpts contain specific technical details
1618
+ * relevant to the current work context. This provides a more sophisticated filter than
1619
+ * simple keyword matching or relevance scores.
1620
+ *
1621
+ * Key optimizations:
1622
+ * - Only grades high-scoring candidates (relevance >= 0.7) to minimize API costs
1623
+ * - Parallel grading for performance
1624
+ * - Strict filtering to reject boilerplate and generic content
1625
+ */
1626
+
1627
+ /**
1628
+ * Minimal interface for an agent runner that can execute prompts.
1629
+ * Compatible with @openai/agents Runner and similar implementations.
1630
+ */
1631
+ interface AgentRunner {
1632
+ run(agent: {
1633
+ name: string;
1634
+ instructions: string | ((...args: any[]) => any);
1635
+ outputType?: unknown;
1636
+ getEnabledHandoffs?: (...args: any[]) => Promise<unknown> | unknown;
1637
+ getAllTools?: (...args: any[]) => Promise<unknown> | unknown;
1638
+ }, prompt: string): Promise<{
1639
+ finalOutput?: unknown;
1640
+ }>;
481
1641
  }
482
-
483
- export interface WorkspaceWriteOptions {
484
- networkAccess?: boolean
485
- writableRoots?: Array<string>
486
- excludeTmpdirEnvVar?: boolean
487
- excludeSlashTmp?: boolean
1642
+ /**
1643
+ * Uses LLM to evaluate if a reverie excerpt contains specific technical details
1644
+ * relevant to the search context.
1645
+ *
1646
+ * The grader is extremely strict and only approves excerpts with:
1647
+ * - Specific code/file references
1648
+ * - Technical decisions and rationale
1649
+ * - Error messages and debugging details
1650
+ * - Implementation specifics
1651
+ *
1652
+ * It rejects:
1653
+ * - Greetings and pleasantries
1654
+ * - Thinking markers (**, ##)
1655
+ * - JSON objects and structured data
1656
+ * - Generic phrases ("Context from past work")
1657
+ * - Metadata and system information
1658
+ *
1659
+ * @param runner - Agent runner capable of executing LLM prompts
1660
+ * @param searchContext - Context describing what we're searching for
1661
+ * @param insight - Reverie insight to evaluate
1662
+ * @returns true if the excerpt contains valuable technical details, false otherwise
1663
+ *
1664
+ * @example
1665
+ * ```typescript
1666
+ * const context = "Implementing authentication with JWT tokens";
1667
+ * const insight = {
1668
+ * excerpt: "We decided to use RS256 for JWT signing because...",
1669
+ * relevance: 0.85,
1670
+ * // ...
1671
+ * };
1672
+ *
1673
+ * const isRelevant = await gradeReverieRelevance(runner, context, insight);
1674
+ * // Returns: true (contains specific technical decision)
1675
+ * ```
1676
+ */
1677
+ declare function gradeReverieRelevance(runner: AgentRunner, searchContext: string, insight: ReverieInsight$1): Promise<boolean>;
1678
+ /**
1679
+ * Grades multiple reverie insights in parallel using LLM evaluation.
1680
+ *
1681
+ * Pipeline:
1682
+ * 1. Filter insights by minimum relevance threshold (default: 0.7)
1683
+ * 2. Send high-scoring insights to LLM grader in parallel
1684
+ * 3. Return only insights that pass LLM evaluation
1685
+ *
1686
+ * This approach optimizes API costs by:
1687
+ * - Skipping low-scoring candidates entirely
1688
+ * - Running high-scoring evaluations in parallel for speed
1689
+ * - Using strict filtering to minimize false positives
1690
+ *
1691
+ * @param runner - Agent runner capable of executing LLM prompts
1692
+ * @param context - Search context describing what we're looking for
1693
+ * @param insights - Array of insights to grade
1694
+ * @param options - Grading configuration options
1695
+ * @returns Filtered array containing only LLM-approved insights
1696
+ *
1697
+ * @example
1698
+ * ```typescript
1699
+ * const allInsights = await searchReveries("authentication bug", repo);
1700
+ * const approved = await gradeReveriesInParallel(
1701
+ * runner,
1702
+ * "Fix authentication token validation",
1703
+ * allInsights,
1704
+ * { minRelevanceForGrading: 0.75, parallel: true }
1705
+ * );
1706
+ *
1707
+ * console.log(`${approved.length}/${allInsights.length} insights approved`);
1708
+ * ```
1709
+ */
1710
+ declare function gradeReveriesInParallel(runner: AgentRunner, context: string, insights: ReverieInsight$1[], options?: GradingOptions): Promise<ReverieInsight$1[]>;
1711
+
1712
+ /**
1713
+ * Complete Reverie Pipeline
1714
+ *
1715
+ * Orchestrates the full reverie search and filtering process:
1716
+ * 1. Search with 3x candidates for aggressive filtering headroom
1717
+ * 2. Basic quality filter (remove boilerplate and system prompts)
1718
+ * 3. Split by relevance threshold (high vs low scoring)
1719
+ * 4. LLM grade high-scoring candidates only (cost optimization)
1720
+ * 5. Deduplicate results (keep highest relevance)
1721
+ * 6. Log statistics at every stage (transparent operation)
1722
+ *
1723
+ * This pipeline matches diff-agent's sophistication while being fully generic
1724
+ * and reusable across different contexts.
1725
+ */
1726
+
1727
+ /**
1728
+ * Result from the complete reverie pipeline.
1729
+ */
1730
+ interface ReveriePipelineResult {
1731
+ /** Final filtered and graded insights */
1732
+ insights: ReverieInsight$1[];
1733
+ /** Statistics from each pipeline stage */
1734
+ stats: ReverieFilterStats;
488
1735
  }
1736
+ /**
1737
+ * Applies the complete reverie pipeline with all sophisticated features from diff-agent.
1738
+ *
1739
+ * Pipeline stages:
1740
+ * 1. **Search** - Fetch 3x candidates with optional reranking
1741
+ * 2. **Quality Filter** - Remove system prompts, boilerplate, JSON objects
1742
+ * 3. **Score Split** - Separate high-scoring (≥0.7) from low-scoring candidates
1743
+ * 4. **LLM Grading** - Grade only high-scoring candidates (cost optimization)
1744
+ * 5. **Deduplication** - Remove similar excerpts, keeping highest relevance
1745
+ * 6. **Logging** - Transparent statistics at each stage
1746
+ *
1747
+ * Key optimizations:
1748
+ * - 3x candidate multiplier provides headroom for aggressive filtering
1749
+ * - LLM grading only applied to high-scoring candidates (≥0.7)
1750
+ * - Parallel grading for performance
1751
+ * - Deduplication preserves highest-relevance duplicates
1752
+ * - Comprehensive logging for debugging and monitoring
1753
+ *
1754
+ * @param codexHome - Path to .codex directory containing conversation data
1755
+ * @param searchText - Search query describing what to look for
1756
+ * @param repo - Repository root path for filtering conversations
1757
+ * @param runner - Agent runner for LLM-based relevance grading (required unless skipLLMGrading is true)
1758
+ * @param options - Pipeline configuration options
1759
+ * @returns Pipeline result with filtered insights and statistics
1760
+ *
1761
+ * @example
1762
+ * ```typescript
1763
+ * // Full pipeline with LLM grading
1764
+ * const result = await applyReveriePipeline(
1765
+ * "/Users/me/.codex",
1766
+ * "authentication bug with JWT tokens",
1767
+ * "/Users/me/my-project",
1768
+ * runner,
1769
+ * {
1770
+ * limit: 6,
1771
+ * useReranker: true,
1772
+ * minRelevanceForGrading: 0.7
1773
+ * }
1774
+ * );
1775
+ *
1776
+ * console.log(`Found ${result.insights.length} relevant insights`);
1777
+ * console.log(`Filtered: ${result.stats.total} → ${result.stats.final}`);
1778
+ *
1779
+ * // Without LLM grading (faster, lower quality)
1780
+ * const fastResult = await applyReveriePipeline(
1781
+ * codexHome,
1782
+ * query,
1783
+ * repo,
1784
+ * null,
1785
+ * { skipLLMGrading: true }
1786
+ * );
1787
+ * ```
1788
+ */
1789
+ declare function applyReveriePipeline(codexHome: string, searchText: string, repo: string, runner: AgentRunner | null, options?: ReveriePipelineOptions): Promise<ReveriePipelineResult>;
1790
+ /**
1791
+ * Simplified pipeline for file-specific searches.
1792
+ *
1793
+ * Similar to main pipeline but optimized for individual file contexts:
1794
+ * - Uses fewer candidates (maxCandidates / 2)
1795
+ * - Same filtering and grading logic
1796
+ * - Transparent logging
1797
+ *
1798
+ * @param codexHome - Path to .codex directory
1799
+ * @param filePath - File path being analyzed
1800
+ * @param fileContext - Contextual information about the file (symbols, changes, etc.)
1801
+ * @param repo - Repository root path
1802
+ * @param runner - Agent runner for LLM grading
1803
+ * @param options - Pipeline options
1804
+ * @returns Pipeline result with file-specific insights
1805
+ *
1806
+ * @example
1807
+ * ```typescript
1808
+ * const fileInsights = await applyFileReveriePipeline(
1809
+ * codexHome,
1810
+ * "src/auth/jwt.ts",
1811
+ * "File: src/auth/jwt.ts\nImplementing: validateToken, generateToken",
1812
+ * repo,
1813
+ * runner,
1814
+ * { limit: 3 }
1815
+ * );
1816
+ * ```
1817
+ */
1818
+ declare function applyFileReveriePipeline(codexHome: string, filePath: string, fileContext: string, repo: string, runner: AgentRunner | null, options?: ReveriePipelineOptions): Promise<ReveriePipelineResult>;
1819
+ /**
1820
+ * Multi-level reverie search pipeline.
1821
+ *
1822
+ * Executes searches at multiple levels (project, branch, file) and returns
1823
+ * results organized by level. This enables comprehensive context gathering
1824
+ * from different scopes in a single operation.
1825
+ *
1826
+ * @param codexHome - Path to .codex directory
1827
+ * @param contexts - Array of search contexts at different levels
1828
+ * @param runner - Agent runner for LLM grading (optional if skipLLMGrading is true)
1829
+ * @param options - Pipeline options
1830
+ * @returns Map of search level to pipeline results
1831
+ *
1832
+ * @example
1833
+ * ```typescript
1834
+ * import { buildProjectContext, buildBranchContext, buildFileContext } from './context.js';
1835
+ *
1836
+ * const contexts = [
1837
+ * buildProjectContext("Testing conventions in this codebase"),
1838
+ * buildBranchContext("feat/auth", ["src/auth.ts", "src/login.ts"]),
1839
+ * buildFileContext("src/auth.ts", { extractSymbols: true })
1840
+ * ];
1841
+ *
1842
+ * const results = await searchMultiLevel(codexHome, contexts, runner, {
1843
+ * limit: 5,
1844
+ * useReranker: true
1845
+ * });
1846
+ *
1847
+ * // Access results by level
1848
+ * const projectInsights = results.get('project')?.insights || [];
1849
+ * const branchInsights = results.get('branch')?.insights || [];
1850
+ * const fileInsights = results.get('file')?.insights || [];
1851
+ * ```
1852
+ */
1853
+ declare function searchMultiLevel(codexHome: string, contexts: ReverieContext[], runner: AgentRunner | null, options?: ReveriePipelineOptions): Promise<Map<ReverieSearchLevel, ReveriePipelineResult>>;
1854
+ /**
1855
+ * Search at project level for repository-wide patterns.
1856
+ *
1857
+ * Optimized for broad searches across the entire codebase to find
1858
+ * architectural decisions, common practices, and project conventions.
1859
+ *
1860
+ * @param codexHome - Path to .codex directory
1861
+ * @param context - Project-level search context
1862
+ * @param runner - Agent runner for LLM grading
1863
+ * @param options - Pipeline options
1864
+ * @returns Pipeline result with project-wide insights
1865
+ *
1866
+ * @example
1867
+ * ```typescript
1868
+ * const context = buildProjectContext(
1869
+ * "How we handle database migrations",
1870
+ * { repoPath: "/Users/me/my-project" }
1871
+ * );
1872
+ *
1873
+ * const result = await searchProjectLevel(codexHome, context, runner, {
1874
+ * limit: 8,
1875
+ * useReranker: true
1876
+ * });
1877
+ *
1878
+ * console.log(`Found ${result.insights.length} project-wide insights`);
1879
+ * ```
1880
+ */
1881
+ declare function searchProjectLevel(codexHome: string, context: ProjectLevelContext, runner: AgentRunner | null, options?: ReveriePipelineOptions): Promise<ReveriePipelineResult>;
1882
+ /**
1883
+ * Search at branch level for feature-specific context.
1884
+ *
1885
+ * Optimized for understanding work done in a specific branch,
1886
+ * including intent, changed files, and commit history.
1887
+ *
1888
+ * @param codexHome - Path to .codex directory
1889
+ * @param context - Branch-level search context
1890
+ * @param runner - Agent runner for LLM grading
1891
+ * @param options - Pipeline options
1892
+ * @returns Pipeline result with branch-specific insights
1893
+ *
1894
+ * @example
1895
+ * ```typescript
1896
+ * const context = buildBranchContext(
1897
+ * "feat/oauth2",
1898
+ * ["src/auth.ts", "src/login.ts"],
1899
+ * {
1900
+ * baseBranch: "main",
1901
+ * recentCommits: "Add OAuth2 support\nImplement token refresh"
1902
+ * }
1903
+ * );
1904
+ *
1905
+ * const result = await searchBranchLevel(codexHome, context, runner, {
1906
+ * limit: 6
1907
+ * });
1908
+ *
1909
+ * console.log(`Found ${result.insights.length} branch insights`);
1910
+ * ```
1911
+ */
1912
+ declare function searchBranchLevel(codexHome: string, context: BranchLevelContext, runner: AgentRunner | null, options?: ReveriePipelineOptions): Promise<ReveriePipelineResult>;
1913
+ /**
1914
+ * Search at file level for specific file changes.
1915
+ *
1916
+ * Optimized for focused searches on individual file modifications,
1917
+ * using extracted symbols for better targeting.
1918
+ *
1919
+ * @param codexHome - Path to .codex directory
1920
+ * @param context - File-level search context
1921
+ * @param runner - Agent runner for LLM grading
1922
+ * @param options - Pipeline options
1923
+ * @returns Pipeline result with file-specific insights
1924
+ *
1925
+ * @example
1926
+ * ```typescript
1927
+ * const context = buildFileContext(
1928
+ * "src/auth/jwt.ts",
1929
+ * {
1930
+ * diff: "+function validateToken(...)\n+function refreshToken(...)",
1931
+ * extractSymbols: true
1932
+ * }
1933
+ * );
1934
+ *
1935
+ * const result = await searchFileLevel(codexHome, context, runner, {
1936
+ * limit: 3
1937
+ * });
1938
+ *
1939
+ * console.log(`Found ${result.insights.length} file-specific insights`);
1940
+ * ```
1941
+ */
1942
+ declare function searchFileLevel(codexHome: string, context: FileLevelContext, runner: AgentRunner | null, options?: ReveriePipelineOptions): Promise<ReveriePipelineResult>;
1943
+
1944
+ /**
1945
+ * Reverie logging utilities.
1946
+ * Provides transparent logging for reverie search and filtering operations.
1947
+ */
1948
+
1949
+ /**
1950
+ * Logs reverie search operation details.
1951
+ *
1952
+ * @param query - The search query
1953
+ * @param context - Optional context about the search
1954
+ */
1955
+ declare function logReverieSearch(query: string, context?: string): void;
1956
+ /**
1957
+ * Logs reverie filtering pipeline statistics.
1958
+ *
1959
+ * @param stats - Filtering statistics
1960
+ */
1961
+ declare function logReverieFiltering(stats: {
1962
+ total: number;
1963
+ afterQuality: number;
1964
+ afterBoilerplate?: number;
1965
+ afterScore: number;
1966
+ afterDedup: number;
1967
+ minScore?: number;
1968
+ }): void;
1969
+ /**
1970
+ * Logs top reverie insights for debugging.
1971
+ *
1972
+ * @param insights - Filtered reverie insights
1973
+ * @param limit - Maximum number of insights to log (default: 3)
1974
+ */
1975
+ declare function logReverieInsights(insights: ReverieResult[], limit?: number): void;
1976
+ /**
1977
+ * Logs quality filtering statistics for hint collection.
1978
+ *
1979
+ * @param stats - Hint collection statistics
1980
+ */
1981
+ declare function logReverieHintQuality(stats: {
1982
+ totalRaw: number;
1983
+ afterQuality: number;
1984
+ afterDedup: number;
1985
+ }): void;
1986
+ /**
1987
+ * Logs LLM grading statistics showing approved vs rejected counts.
1988
+ *
1989
+ * @param stats - LLM grading statistics
1990
+ */
1991
+ declare function logLLMGrading(stats: {
1992
+ total: number;
1993
+ approved: number;
1994
+ rejected: number;
1995
+ minScore?: number;
1996
+ }): void;
1997
+ /**
1998
+ * Logs approved reverie excerpts with relevance scores (verbose mode).
1999
+ *
2000
+ * @param insights - Approved reverie insights to log
2001
+ * @param maxToShow - Maximum number of insights to display (default: 5)
2002
+ */
2003
+ declare function logApprovedReveries(insights: ReverieResult[], maxToShow?: number): void;
2004
+ /**
2005
+ * Truncates a string to a maximum length, adding ellipsis if needed.
2006
+ */
2007
+ declare function truncate(text: string, maxLength: number): string;
2008
+
2009
+ /**
2010
+ * Logs multi-level search initiation.
2011
+ *
2012
+ * @param levels - Array of search levels being executed
2013
+ *
2014
+ * @example
2015
+ * ```typescript
2016
+ * logMultiLevelSearch(['project', 'branch', 'file']);
2017
+ * // Output: "🔍 Multi-level reverie search: project → branch → file"
2018
+ * ```
2019
+ */
2020
+ declare function logMultiLevelSearch(levels: ReverieSearchLevel[]): void;
2021
+ /**
2022
+ * Logs results for a specific search level.
2023
+ *
2024
+ * @param level - The search level
2025
+ * @param result - Pipeline result for this level
2026
+ *
2027
+ * @example
2028
+ * ```typescript
2029
+ * logLevelResults('project', {
2030
+ * insights: [...],
2031
+ * stats: { total: 50, final: 8, ... }
2032
+ * });
2033
+ * // Output: " 🌐 Project level: 8 insights (50 → 8, 84% filtered)"
2034
+ * ```
2035
+ */
2036
+ declare function logLevelResults(level: ReverieSearchLevel, result: ReveriePipelineResult): void;
2037
+ /**
2038
+ * Logs a summary of multi-level search results.
2039
+ *
2040
+ * @param results - Map of level to pipeline results
2041
+ *
2042
+ * @example
2043
+ * ```typescript
2044
+ * const results = new Map([
2045
+ * ['project', { insights: [...], stats: {...} }],
2046
+ * ['branch', { insights: [...], stats: {...} }],
2047
+ * ['file', { insights: [...], stats: {...} }]
2048
+ * ]);
2049
+ *
2050
+ * logMultiLevelSummary(results);
2051
+ * // Output summary of all levels with total counts
2052
+ * ```
2053
+ */
2054
+ declare function logMultiLevelSummary(results: Map<ReverieSearchLevel, ReveriePipelineResult>): void;
2055
+
2056
+ /**
2057
+ * Symbol Extraction for Reverie Search
2058
+ *
2059
+ * Extracts key code symbols from diffs to create more focused search queries.
2060
+ * This improves search precision by targeting specific functions, classes, and variables.
2061
+ */
2062
+ /**
2063
+ * Extracts key symbols and terms from a diff to make search queries more targeted.
2064
+ *
2065
+ * Focuses on:
2066
+ * - Function and class definitions
2067
+ * - Variable declarations (const, let, var)
2068
+ * - Exported symbols
2069
+ * - Interface and type definitions
2070
+ *
2071
+ * Avoids:
2072
+ * - Language keywords (true, false, null, etc.)
2073
+ * - Very short symbols (< 3 chars)
2074
+ * - Boilerplate patterns
2075
+ *
2076
+ * @param diff - Git diff content to extract symbols from
2077
+ * @returns Comma-separated string of top 5 symbols, or "code changes" if none found
2078
+ *
2079
+ * @example
2080
+ * ```typescript
2081
+ * const diff = `
2082
+ * +function processUser(user: User) {
2083
+ * + const userName = user.name;
2084
+ * + return userName;
2085
+ * +}
2086
+ * `;
2087
+ *
2088
+ * extractKeySymbols(diff); // "processUser, userName"
2089
+ * ```
2090
+ */
2091
+ declare function extractKeySymbols(diff: string): string;
2092
+
2093
+ /**
2094
+ * Advanced Reverie Search
2095
+ *
2096
+ * Provides semantic search over past conversation history with sophisticated filtering:
2097
+ * - 3x candidate multiplier for aggressive filtering
2098
+ * - Reranker support for improved precision
2099
+ * - Multi-stage filtering with transparent logging
2100
+ * - Quality and deduplication pipelines
2101
+ */
2102
+
2103
+ /**
2104
+ * Performs advanced semantic search over reverie conversation history.
2105
+ *
2106
+ * Search pipeline:
2107
+ * 1. Fetch 3x candidates (candidateMultiplier × limit)
2108
+ * 2. Apply quality filtering (remove boilerplate, system prompts)
2109
+ * 3. Deduplicate similar excerpts (keep highest relevance)
2110
+ * 4. Apply reranker if enabled (improve precision)
2111
+ * 5. Return top N results
2112
+ *
2113
+ * Key features:
2114
+ * - Aggressive candidate fetching for better filtering headroom
2115
+ * - Optional reranker support for precision improvement
2116
+ * - Quality filtering removes system prompts and boilerplate
2117
+ * - Deduplication preserves highest-relevance duplicates
2118
+ * - Transparent logging at each stage
2119
+ *
2120
+ * @param codexHome - Path to .codex directory containing conversation data
2121
+ * @param text - Search query text
2122
+ * @param repo - Repository root path for filtering conversations
2123
+ * @param options - Search configuration options
2124
+ * @returns Array of relevant reverie insights, sorted by relevance
2125
+ *
2126
+ * @example
2127
+ * ```typescript
2128
+ * const insights = await searchReveries(
2129
+ * "/Users/me/.codex",
2130
+ * "authentication bug with JWT tokens",
2131
+ * "/Users/me/my-project",
2132
+ * {
2133
+ * limit: 6,
2134
+ * useReranker: true,
2135
+ * candidateMultiplier: 3
2136
+ * }
2137
+ * );
2138
+ *
2139
+ * console.log(`Found ${insights.length} relevant insights`);
2140
+ * insights.forEach(insight => {
2141
+ * console.log(`[${insight.relevance.toFixed(2)}] ${insight.excerpt.slice(0, 100)}`);
2142
+ * });
2143
+ * ```
2144
+ */
2145
+ declare function searchReveries(codexHome: string, text: string, repo: string, options?: ReverieSearchOptions): Promise<ReverieInsight$1[]>;
2146
+
2147
+ /**
2148
+ * Reverie Context Builders
2149
+ *
2150
+ * Utilities for building search contexts at different levels:
2151
+ * - Project level: Repository-wide patterns and architecture
2152
+ * - Branch level: Feature/branch-specific work and intent
2153
+ * - File level: Individual file changes and symbols
2154
+ */
2155
+
2156
+ /**
2157
+ * Builds project-level search context for repository-wide patterns.
2158
+ *
2159
+ * Use this for searching architectural decisions, common practices,
2160
+ * and project-wide patterns across the entire codebase.
2161
+ *
2162
+ * @param query - Natural language query describing what to find
2163
+ * @param options - Optional configuration
2164
+ * @returns Project-level context ready for search
2165
+ *
2166
+ * @example
2167
+ * ```typescript
2168
+ * const context = buildProjectContext(
2169
+ * "How we handle database migrations in this repository",
2170
+ * { repoPath: "/Users/me/my-project" }
2171
+ * );
2172
+ *
2173
+ * const results = await searchProjectLevel(codexHome, context, runner);
2174
+ * ```
2175
+ */
2176
+ declare function buildProjectContext(query: string, options?: {
2177
+ repoPath?: string;
2178
+ filePatterns?: string[];
2179
+ }): ProjectLevelContext;
2180
+ /**
2181
+ * Builds branch-level search context for feature/branch-specific work.
2182
+ *
2183
+ * Use this for understanding branch intent, feature context, and changes
2184
+ * made across multiple files in a feature branch.
2185
+ *
2186
+ * @param branch - Current branch name
2187
+ * @param changedFiles - List of files modified in this branch
2188
+ * @param options - Optional configuration
2189
+ * @returns Branch-level context ready for search
2190
+ *
2191
+ * @example
2192
+ * ```typescript
2193
+ * const context = buildBranchContext(
2194
+ * "feat/oauth2",
2195
+ * ["src/auth.ts", "src/login.ts", "test/auth.test.ts"],
2196
+ * {
2197
+ * baseBranch: "main",
2198
+ * recentCommits: "Add OAuth2 support\nImplement token refresh",
2199
+ * repoPath: "/Users/me/my-project"
2200
+ * }
2201
+ * );
2202
+ *
2203
+ * const results = await searchBranchLevel(codexHome, context, runner);
2204
+ * ```
2205
+ */
2206
+ declare function buildBranchContext(branch: string, changedFiles: string[], options?: {
2207
+ baseBranch?: string;
2208
+ recentCommits?: string;
2209
+ repoPath?: string;
2210
+ }): BranchLevelContext;
2211
+ /**
2212
+ * Builds file-level search context for individual file changes.
2213
+ *
2214
+ * Use this for focused searches on specific file modifications,
2215
+ * with optional symbol extraction for better targeting.
2216
+ *
2217
+ * @param filePath - Path to the file being analyzed
2218
+ * @param options - Optional configuration
2219
+ * @returns File-level context ready for search
2220
+ *
2221
+ * @example
2222
+ * ```typescript
2223
+ * // Without symbol extraction
2224
+ * const context = buildFileContext(
2225
+ * "src/auth/jwt.ts",
2226
+ * {
2227
+ * diff: "... git diff content ...",
2228
+ * repoPath: "/Users/me/my-project"
2229
+ * }
2230
+ * );
2231
+ *
2232
+ * // With automatic symbol extraction
2233
+ * const context = buildFileContext(
2234
+ * "src/auth/jwt.ts",
2235
+ * {
2236
+ * diff: "+function validateToken(...)\n+function refreshToken(...)",
2237
+ * extractSymbols: true,
2238
+ * repoPath: "/Users/me/my-project"
2239
+ * }
2240
+ * );
2241
+ * // context.symbols will be: ["validateToken", "refreshToken"]
2242
+ *
2243
+ * const results = await searchFileLevel(codexHome, context, runner);
2244
+ * ```
2245
+ */
2246
+ declare function buildFileContext(filePath: string, options?: {
2247
+ diff?: string;
2248
+ extractSymbols?: boolean;
2249
+ repoPath?: string;
2250
+ }): FileLevelContext;
2251
+ /**
2252
+ * Converts a ReverieContext to a search query string.
2253
+ *
2254
+ * Transforms structured context objects into natural language queries
2255
+ * suitable for semantic search.
2256
+ *
2257
+ * @param context - Any level of reverie context
2258
+ * @returns Formatted search query string
2259
+ *
2260
+ * @example
2261
+ * ```typescript
2262
+ * const projectCtx = buildProjectContext("Authentication patterns");
2263
+ * const query = contextToQuery(projectCtx);
2264
+ * // Returns: "Project-wide: Authentication patterns"
2265
+ *
2266
+ * const branchCtx = buildBranchContext("feat/auth", ["auth.ts", "login.ts"]);
2267
+ * const query = contextToQuery(branchCtx);
2268
+ * // Returns: "Branch: feat/auth\nFiles: auth.ts, login.ts"
2269
+ *
2270
+ * const fileCtx = buildFileContext("auth.ts", {
2271
+ * symbols: ["validateToken", "refreshToken"]
2272
+ * });
2273
+ * const query = contextToQuery(fileCtx);
2274
+ * // Returns: "File: auth.ts\nSymbols: validateToken, refreshToken"
2275
+ * ```
2276
+ */
2277
+ declare function contextToQuery(context: ReverieContext): string;
2278
+ /**
2279
+ * Helper to format file paths for display in contexts.
2280
+ *
2281
+ * @param files - Array of file paths
2282
+ * @param maxFiles - Maximum number of files to show before truncating
2283
+ * @returns Formatted file list string
2284
+ */
2285
+ declare function formatFileList(files: string[], maxFiles?: number): string;
2286
+
2287
+ declare function evCompleted(id: string): string;
2288
+ declare function evResponseCreated(id: string): string;
2289
+ declare function evAssistantMessage(id: string, text: string): string;
2290
+ declare function evFunctionCall(callId: string, name: string, args: string): string;
2291
+ declare function sse(events: string[]): string;
2292
+
2293
+ export { type AgentMessageItem, type AgentRunner, type ApprovalMode, type ApprovalRequest, type BranchLevelContext, type BranchReview, type CloudApplyOutcome, type CloudApplyStatus, type DiffSummary as CloudDiffSummary, type CloudTaskStatus, type CloudTaskSummary, CloudTasks, type CloudTasksOptions, Codex, type CodexOptions, CodexProvider, type CodexProviderOptions, type CodexToolOptions, type CommandExecutionItem, type CommandExecutionStatus, type CommitReview, type ConversationListOptions, type ConversationListPage, type ConversationSummary, type CurrentChangesReview, type CustomReview, DEFAULT_RERANKER_BATCH_SIZE, DEFAULT_RERANKER_TOP_K, DEFAULT_REVERIE_LIMIT, DEFAULT_REVERIE_MAX_CANDIDATES, DEFAULT_SERVERS, type DelegationResult, type DiagnosticSeverity, type ErrorItem, type FastEmbedEmbedRequest, type FastEmbedInitOptions, type FastEmbedRerankerModelCode, type FileChangeItem, type FileDiagnostics, type FileLevelContext, type FileUpdateChange, type ForkOptions, type FormatStreamOptions, type FormattedStream, type GradingOptions, type Input, type ItemCompletedEvent, type ItemStartedEvent, type ItemUpdatedEvent, type LogEntry, LogLevel, type LogOutput, type LogScope, Logger, type LoggerConfig, type LspDiagnosticSeverity, LspDiagnosticsBridge, LspManager, type LspManagerOptions, type LspServerConfig, type McpToolCallItem, type McpToolCallStatus, type NativeForkResult, type NativeTokenUsage, type NativeToolDefinition, type NativeToolInterceptorContext, type NativeToolInvocation, type NativeToolResult, type NativeTuiExitInfo, type NativeTuiRequest, type NativeUpdateActionInfo, type NativeUpdateActionKind, type NormalizedDiagnostic, OpenCodeAgent, type OpenCodeAgentOptions, type PatchApplyStatus, type PatchChangeKind, type PermissionDecision, type PermissionRequest, type ProjectLevelContext, type QualityFilterStats, REVERIE_CANDIDATE_MULTIPLIER, REVERIE_EMBED_MODEL, REVERIE_LLM_GRADE_THRESHOLD, REVERIE_RERANKER_MODEL, type ReasoningItem, type RepoDiffFileChange, type RepoDiffSummary, type RepoDiffSummaryOptions, type ReverieContext, type ReverieEpisodeSummary, type ReverieFilterStats, type ReverieInsight$1 as ReverieInsight, type ReveriePipelineOptions, type ReveriePipelineResult, type ReverieResult, type ReverieSearchLevel, type ReverieSearchOptions, type ReverieSemanticIndexStats, type ReverieSemanticSearchOptions, type ReviewInvocationOptions, type ReviewTarget, type RunResult, type RunStreamedResult, type RunTuiOptions, type SandboxMode, ScopedLogger, type SkillDefinition, type SkillMentionTrigger, Thread, type ThreadError, type ThreadErrorEvent, type ThreadEvent, type ThreadItem, type ThreadLoggingSink, type ThreadOptions, type ThreadStartedEvent, type TodoItem, type TodoListItem, type TokenizerEncodeOptions, type TokenizerOptions, type ToolCallEvent, type TuiSession, type TurnCompletedEvent, type TurnFailedEvent, type TurnOptions, type TurnStartedEvent, type Usage, type UserInput, type WebSearchItem, type WorkspaceLocator, applyFileReveriePipeline, applyQualityPipeline, applyReveriePipeline, attachLspDiagnostics, buildBranchContext, buildFileContext, buildProjectContext, codexTool, collectRepoDiffSummary, contextToQuery, createThreadLogger, deduplicateReverieInsights, encodeToToon, evAssistantMessage, evCompleted, evFunctionCall, evResponseCreated, extractKeySymbols, fastEmbedEmbed, fastEmbedInit, filterBySeverity, findServerForFile, formatDiagnosticsForBackgroundEvent, formatDiagnosticsForTool, formatDiagnosticsWithSummary, formatFileList, formatStream, gradeReverieRelevance, gradeReveriesInParallel, isValidReverieExcerpt, logApprovedReveries, logLLMGrading, logLevelResults, logMultiLevelSearch, logMultiLevelSummary, logReverieFiltering, logReverieHintQuality, logReverieInsights, logReverieSearch, logger, resolveWorkspaceRoot, reverieGetConversationInsights, reverieIndexSemantic, reverieListConversations, reverieSearchConversations, reverieSearchSemantic, runThreadTurnWithLogs, runTui, searchBranchLevel, searchFileLevel, searchMultiLevel, searchProjectLevel, searchReveries, sse, startTui, summarizeDiagnostics, tokenizerCount, tokenizerDecode, tokenizerEncode, truncate as truncateText };