@kodax-ai/kodax 0.7.41 → 0.7.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -1
- package/README.md +129 -232
- package/README_CN.md +128 -253
- package/dist/chunks/chunk-3RKBXWZS.js +2 -0
- package/dist/chunks/chunk-7JLYVWAF.js +1033 -0
- package/dist/chunks/chunk-CD3R5YBH.js +16 -0
- package/dist/chunks/chunk-DKXUY5F2.js +209 -0
- package/dist/chunks/chunk-HMYEQJGT.js +31 -0
- package/dist/chunks/{chunk-6OB4AJOM.js → chunk-IYJ5EPRV.js} +1 -1
- package/dist/chunks/chunk-KUX5LRPP.js +2 -0
- package/dist/chunks/{chunk-EQ5DGS2W.js → chunk-OWSKU55I.js} +5 -6
- package/dist/chunks/chunk-ZZ4KRK2B.js +465 -0
- package/dist/chunks/compaction-config-FIFFP4FT.js +2 -0
- package/dist/chunks/{construction-bootstrap-HBCWJFHC.js → construction-bootstrap-J2WOCYEK.js} +1 -1
- package/dist/chunks/dist-2ZHWDXMQ.js +2 -0
- package/dist/chunks/dist-W4CJWLIH.js +2 -0
- package/dist/chunks/utils-A5MWDTWZ.js +2 -0
- package/dist/index.d.ts +15 -10
- package/dist/index.js +5 -5
- package/dist/kodax_cli.js +841 -833
- package/dist/sdk-agent.d.ts +9 -93
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +315 -250
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-llm.d.ts +6 -5
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.d.ts +17 -0
- package/dist/sdk-mcp.js +2 -0
- package/dist/sdk-repl.d.ts +342 -10
- package/dist/sdk-repl.js +2 -1
- package/dist/sdk-session.d.ts +164 -0
- package/dist/sdk-session.js +2 -0
- package/dist/sdk-skills.d.ts +72 -4
- package/dist/sdk-skills.js +1 -1
- package/dist/types-chunks/{bash-prefix-extractor.d-B2iliwdi.d.ts → bash-prefix-extractor.d-CkhaqKkg.d.ts} +237 -98
- package/dist/types-chunks/capability.d-3C62G8Eq.d.ts +39 -0
- package/dist/types-chunks/config.d-BfJUXxC0.d.ts +41 -0
- package/dist/types-chunks/{cost-tracker.d-C4dMlQuV.d.ts → cost-tracker.d-B6vMoLLF.d.ts} +20 -2
- package/dist/types-chunks/{history-cleanup.d-q1vAvCss.d.ts → history-cleanup.d-DznrzEiU.d.ts} +221 -12
- package/dist/types-chunks/{instance-discovery.d-DZhp77vb.d.ts → instance-discovery.d-BsKnIwpg.d.ts} +31 -258
- package/dist/types-chunks/{resolver.d-BwD6TKz7.d.ts → resolver.d-DX9au4NJ.d.ts} +4 -3
- package/dist/types-chunks/session-storage.d-Cci897iM.d.ts +68 -0
- package/dist/types-chunks/{storage.d-Bv9T99Qu.d.ts → storage.d-Bc5DoAwp.d.ts} +17 -69
- package/dist/types-chunks/transport.d-DuyjG30t.d.ts +180 -0
- package/dist/types-chunks/{capability.d-BxNgd1-c.d.ts → types.d-B1uGoVTE.d.ts} +72 -40
- package/dist/types-chunks/types.d-mM8vqvhT.d.ts +254 -0
- package/package.json +9 -1
- package/dist/chunks/chunk-5TFLMGER.js +0 -2
- package/dist/chunks/chunk-6QO6HWGU.js +0 -30
- package/dist/chunks/chunk-HYWVRTFA.js +0 -1233
- package/dist/chunks/chunk-SX2IS5JP.js +0 -16
- package/dist/chunks/chunk-ZPJPNLBK.js +0 -462
- package/dist/chunks/compaction-config-LT5PEXPT.js +0 -2
- package/dist/chunks/dist-M57GIWR4.js +0 -2
- package/dist/chunks/dist-V3BS2NKB.js +0 -2
- package/dist/chunks/utils-FAFUQJ2A.js +0 -2
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { m as KodaXMessage } from './types.d-B1uGoVTE.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @kodax-ai/agent Types
|
|
5
|
+
*
|
|
6
|
+
* 通用 Agent 类型定义
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
type KodaXJsonPrimitive = string | number | boolean | null;
|
|
10
|
+
type KodaXJsonValue = KodaXJsonPrimitive | KodaXJsonValue[] | {
|
|
11
|
+
[key: string]: KodaXJsonValue;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Session error metadata - 会话错误元数据
|
|
15
|
+
* Used for error recovery and session cleanup - 用于错误恢复和会话清理
|
|
16
|
+
*/
|
|
17
|
+
interface SessionErrorMetadata {
|
|
18
|
+
/** Last error message - 最后的错误消息 */
|
|
19
|
+
lastError?: string;
|
|
20
|
+
/** Last error timestamp - 最后错误时间戳 */
|
|
21
|
+
lastErrorTime?: number;
|
|
22
|
+
/** Consecutive error count - 连续错误计数 */
|
|
23
|
+
consecutiveErrors: number;
|
|
24
|
+
}
|
|
25
|
+
interface KodaXExtensionSessionRecord {
|
|
26
|
+
id: string;
|
|
27
|
+
extensionId: string;
|
|
28
|
+
type: string;
|
|
29
|
+
ts: number;
|
|
30
|
+
data?: KodaXJsonValue;
|
|
31
|
+
dedupeKey?: string;
|
|
32
|
+
}
|
|
33
|
+
type KodaXExtensionSessionState = Record<string, Record<string, KodaXJsonValue>>;
|
|
34
|
+
interface KodaXSessionEntryBase {
|
|
35
|
+
id: string;
|
|
36
|
+
parentId: string | null;
|
|
37
|
+
timestamp: string;
|
|
38
|
+
}
|
|
39
|
+
interface KodaXSessionMessageEntry extends KodaXSessionEntryBase {
|
|
40
|
+
type: 'message';
|
|
41
|
+
message: KodaXMessage;
|
|
42
|
+
}
|
|
43
|
+
interface KodaXSessionCompactionEntry extends KodaXSessionEntryBase {
|
|
44
|
+
type: 'compaction';
|
|
45
|
+
summary: string;
|
|
46
|
+
firstKeptEntryId?: string;
|
|
47
|
+
tokensBefore?: number;
|
|
48
|
+
tokensAfter?: number;
|
|
49
|
+
artifactLedgerId?: string;
|
|
50
|
+
reason?: string;
|
|
51
|
+
details?: KodaXJsonValue;
|
|
52
|
+
memorySeed?: KodaXCompactMemorySeed;
|
|
53
|
+
/**
|
|
54
|
+
* FEATURE_072: post-compact ledger summary + file-content messages that
|
|
55
|
+
* are inlined after the compaction summary at slicer time
|
|
56
|
+
* (`getSessionMessagesFromLineage`). Stored here so they leave the active
|
|
57
|
+
* path automatically when a new compaction entry is appended.
|
|
58
|
+
*
|
|
59
|
+
* NOTE: attachments are emitted by the slicer, NOT by `getContextMessagesForEntry`
|
|
60
|
+
* — preserving the latter's 1-to-1 contract that `entryMatchesContextMessage`
|
|
61
|
+
* and FEATURE_073's future slicing both depend on.
|
|
62
|
+
*/
|
|
63
|
+
postCompactAttachments?: readonly KodaXMessage[];
|
|
64
|
+
}
|
|
65
|
+
interface KodaXSessionBranchSummaryEntry extends KodaXSessionEntryBase {
|
|
66
|
+
type: 'branch_summary';
|
|
67
|
+
summary: string;
|
|
68
|
+
fromId?: string;
|
|
69
|
+
details?: KodaXJsonValue;
|
|
70
|
+
}
|
|
71
|
+
interface KodaXSessionLabelEntry extends KodaXSessionEntryBase {
|
|
72
|
+
type: 'label';
|
|
73
|
+
targetId: string;
|
|
74
|
+
label?: string;
|
|
75
|
+
}
|
|
76
|
+
interface KodaXSessionArchiveMarkerEntry extends KodaXSessionEntryBase {
|
|
77
|
+
type: 'archive_marker';
|
|
78
|
+
/** Links to the corresponding batch in the .archive.jsonl sidecar file */
|
|
79
|
+
archiveBatchId: string;
|
|
80
|
+
/** Number of entries that were archived in this batch */
|
|
81
|
+
archivedEntryCount: number;
|
|
82
|
+
/** Brief summary of the archived content */
|
|
83
|
+
summary: string;
|
|
84
|
+
}
|
|
85
|
+
type KodaXSessionEntry = KodaXSessionMessageEntry | KodaXSessionCompactionEntry | KodaXSessionBranchSummaryEntry | KodaXSessionLabelEntry | KodaXSessionArchiveMarkerEntry;
|
|
86
|
+
interface KodaXSessionArtifactLedgerEntry {
|
|
87
|
+
id: string;
|
|
88
|
+
kind: 'file_read' | 'file_modified' | 'file_created' | 'file_deleted' | 'path_scope' | 'search_scope' | 'command_scope' | 'check_result' | 'decision' | 'image_input' | 'tombstone';
|
|
89
|
+
sourceTool?: string;
|
|
90
|
+
action?: string;
|
|
91
|
+
target: string;
|
|
92
|
+
displayTarget?: string;
|
|
93
|
+
summary?: string;
|
|
94
|
+
sessionEntryId?: string;
|
|
95
|
+
timestamp: string;
|
|
96
|
+
metadata?: Record<string, KodaXJsonValue>;
|
|
97
|
+
}
|
|
98
|
+
interface KodaXCompactMemoryProgress {
|
|
99
|
+
completed: string[];
|
|
100
|
+
inProgress: string[];
|
|
101
|
+
blockers: string[];
|
|
102
|
+
}
|
|
103
|
+
interface KodaXCompactMemorySeed {
|
|
104
|
+
objective?: string;
|
|
105
|
+
constraints: string[];
|
|
106
|
+
progress: KodaXCompactMemoryProgress;
|
|
107
|
+
keyDecisions: string[];
|
|
108
|
+
nextSteps: string[];
|
|
109
|
+
keyContext: string[];
|
|
110
|
+
importantTargets: string[];
|
|
111
|
+
tombstones: string[];
|
|
112
|
+
}
|
|
113
|
+
interface KodaXSessionLineage {
|
|
114
|
+
version: 2;
|
|
115
|
+
activeEntryId: string | null;
|
|
116
|
+
entries: KodaXSessionEntry[];
|
|
117
|
+
}
|
|
118
|
+
interface KodaXSessionNavigationOptions {
|
|
119
|
+
summarizeCurrentBranch?: boolean;
|
|
120
|
+
}
|
|
121
|
+
interface KodaXSessionTreeNode {
|
|
122
|
+
entry: Exclude<KodaXSessionEntry, KodaXSessionLabelEntry>;
|
|
123
|
+
children: KodaXSessionTreeNode[];
|
|
124
|
+
label?: string;
|
|
125
|
+
active: boolean;
|
|
126
|
+
}
|
|
127
|
+
type KodaXSessionScope = 'user' | 'managed-task-worker';
|
|
128
|
+
type KodaXSessionUiHistoryItemType = 'user' | 'assistant' | 'system' | 'thinking' | 'error' | 'event' | 'info' | 'hint';
|
|
129
|
+
interface KodaXSessionUiHistoryItem {
|
|
130
|
+
type: KodaXSessionUiHistoryItemType;
|
|
131
|
+
text: string;
|
|
132
|
+
icon?: string;
|
|
133
|
+
compactText?: string;
|
|
134
|
+
}
|
|
135
|
+
type KodaXSessionWorkspaceKind = 'detected' | 'managed';
|
|
136
|
+
interface KodaXSessionRuntimeInfo {
|
|
137
|
+
canonicalRepoRoot?: string;
|
|
138
|
+
workspaceRoot?: string;
|
|
139
|
+
executionCwd?: string;
|
|
140
|
+
branch?: string;
|
|
141
|
+
workspaceKind?: KodaXSessionWorkspaceKind;
|
|
142
|
+
}
|
|
143
|
+
interface KodaXSessionData {
|
|
144
|
+
messages: KodaXMessage[];
|
|
145
|
+
title: string;
|
|
146
|
+
gitRoot: string;
|
|
147
|
+
runtimeInfo?: KodaXSessionRuntimeInfo;
|
|
148
|
+
scope?: KodaXSessionScope;
|
|
149
|
+
uiHistory?: KodaXSessionUiHistoryItem[];
|
|
150
|
+
errorMetadata?: SessionErrorMetadata;
|
|
151
|
+
extensionState?: KodaXExtensionSessionState;
|
|
152
|
+
extensionRecords?: KodaXExtensionSessionRecord[];
|
|
153
|
+
lineage?: KodaXSessionLineage;
|
|
154
|
+
artifactLedger?: KodaXSessionArtifactLedgerEntry[];
|
|
155
|
+
}
|
|
156
|
+
interface KodaXSessionMeta {
|
|
157
|
+
_type: 'meta';
|
|
158
|
+
title: string;
|
|
159
|
+
id: string;
|
|
160
|
+
gitRoot: string;
|
|
161
|
+
runtimeInfo?: KodaXSessionRuntimeInfo;
|
|
162
|
+
createdAt: string;
|
|
163
|
+
scope?: KodaXSessionScope;
|
|
164
|
+
uiHistory?: KodaXSessionUiHistoryItem[];
|
|
165
|
+
extensionState?: KodaXExtensionSessionState;
|
|
166
|
+
extensionRecordCount?: number;
|
|
167
|
+
artifactLedgerCount?: number;
|
|
168
|
+
lineageVersion?: 2;
|
|
169
|
+
activeEntryId?: string | null;
|
|
170
|
+
lineageEntryCount?: number;
|
|
171
|
+
activeMessageCount?: number;
|
|
172
|
+
/** Error metadata for recovery - 错误元数据用于恢复 */
|
|
173
|
+
errorMetadata?: SessionErrorMetadata;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Extension-scoped persistence entry.
|
|
177
|
+
*
|
|
178
|
+
* Each entry belongs to a namespace (extensionId) and carries
|
|
179
|
+
* a string key, a JSON-safe value, and an opaque version tag
|
|
180
|
+
* used for optimistic concurrency control.
|
|
181
|
+
*/
|
|
182
|
+
interface KodaXExtensionStoreEntry {
|
|
183
|
+
key: string;
|
|
184
|
+
value: KodaXJsonValue;
|
|
185
|
+
version: string;
|
|
186
|
+
updatedAt: number;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Extension persistence store interface (FEATURE_034 manual persistence).
|
|
190
|
+
*
|
|
191
|
+
* Implementations provide a durable key-value store scoped to a single
|
|
192
|
+
* extension identity. The store is independent of session lifecycle —
|
|
193
|
+
* data survives across sessions and restarts.
|
|
194
|
+
*/
|
|
195
|
+
interface KodaXExtensionStore {
|
|
196
|
+
/**
|
|
197
|
+
* Read a single key.
|
|
198
|
+
* Returns `undefined` when the key does not exist.
|
|
199
|
+
*/
|
|
200
|
+
get(key: string): Promise<KodaXExtensionStoreEntry | undefined>;
|
|
201
|
+
/**
|
|
202
|
+
* Write a key-value pair.
|
|
203
|
+
*
|
|
204
|
+
* When `expectedVersion` is provided the write only succeeds when the
|
|
205
|
+
* stored entry's version still matches (optimistic concurrency).
|
|
206
|
+
* Returns the new entry on success, or `false` on version mismatch.
|
|
207
|
+
*/
|
|
208
|
+
put(key: string, value: KodaXJsonValue, options?: {
|
|
209
|
+
expectedVersion?: string;
|
|
210
|
+
}): Promise<KodaXExtensionStoreEntry | false>;
|
|
211
|
+
/**
|
|
212
|
+
* Remove a key.
|
|
213
|
+
* Returns `true` when the key existed and was removed.
|
|
214
|
+
*/
|
|
215
|
+
delete(key: string): Promise<boolean>;
|
|
216
|
+
/**
|
|
217
|
+
* List all keys (optionally filtered by prefix).
|
|
218
|
+
*/
|
|
219
|
+
list(options?: {
|
|
220
|
+
prefix?: string;
|
|
221
|
+
}): Promise<string[]>;
|
|
222
|
+
/**
|
|
223
|
+
* Clear all keys (optionally filtered by prefix).
|
|
224
|
+
* Returns the number of entries removed.
|
|
225
|
+
*/
|
|
226
|
+
clear(options?: {
|
|
227
|
+
prefix?: string;
|
|
228
|
+
}): Promise<number>;
|
|
229
|
+
}
|
|
230
|
+
interface KodaXSessionStorage {
|
|
231
|
+
save(id: string, data: KodaXSessionData): Promise<void>;
|
|
232
|
+
load(id: string): Promise<KodaXSessionData | null>;
|
|
233
|
+
getLineage?(id: string): Promise<KodaXSessionLineage | null>;
|
|
234
|
+
setActiveEntry?(id: string, selector: string, options?: KodaXSessionNavigationOptions): Promise<KodaXSessionData | null>;
|
|
235
|
+
setLabel?(id: string, selector: string, label?: string): Promise<KodaXSessionData | null>;
|
|
236
|
+
rewind?(id: string, selector?: string): Promise<KodaXSessionData | null>;
|
|
237
|
+
fork?(id: string, selector?: string, options?: {
|
|
238
|
+
sessionId?: string;
|
|
239
|
+
title?: string;
|
|
240
|
+
}): Promise<{
|
|
241
|
+
sessionId: string;
|
|
242
|
+
data: KodaXSessionData;
|
|
243
|
+
} | null>;
|
|
244
|
+
list?(gitRoot?: string): Promise<Array<{
|
|
245
|
+
id: string;
|
|
246
|
+
title: string;
|
|
247
|
+
msgCount: number;
|
|
248
|
+
runtimeInfo?: KodaXSessionRuntimeInfo;
|
|
249
|
+
}>>;
|
|
250
|
+
delete?(id: string): Promise<void>;
|
|
251
|
+
deleteAll?(gitRoot?: string): Promise<void>;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export type { KodaXCompactMemoryProgress as K, SessionErrorMetadata as S, KodaXCompactMemorySeed as a, KodaXExtensionSessionRecord as b, KodaXExtensionSessionState as c, KodaXExtensionStore as d, KodaXExtensionStoreEntry as e, KodaXJsonValue as f, KodaXSessionArchiveMarkerEntry as g, KodaXSessionArtifactLedgerEntry as h, KodaXSessionBranchSummaryEntry as i, KodaXSessionCompactionEntry as j, KodaXSessionData as k, KodaXSessionEntry as l, KodaXSessionEntryBase as m, KodaXSessionLabelEntry as n, KodaXSessionLineage as o, KodaXSessionMessageEntry as p, KodaXSessionMeta as q, KodaXSessionNavigationOptions as r, KodaXSessionRuntimeInfo as s, KodaXSessionScope as t, KodaXSessionStorage as u, KodaXSessionTreeNode as v, KodaXSessionUiHistoryItem as w, KodaXSessionUiHistoryItemType as x, KodaXSessionWorkspaceKind as y };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kodax-ai/kodax",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.42",
|
|
4
4
|
"description": "极致轻量化 Coding Agent - TypeScript 实现,支持 12 个 LLM 提供商,可发布为免 Node 单文件二进制",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"workspaces": [
|
|
@@ -36,6 +36,14 @@
|
|
|
36
36
|
"types": "./dist/sdk-skills.d.ts",
|
|
37
37
|
"import": "./dist/sdk-skills.js"
|
|
38
38
|
},
|
|
39
|
+
"./mcp": {
|
|
40
|
+
"types": "./dist/sdk-mcp.d.ts",
|
|
41
|
+
"import": "./dist/sdk-mcp.js"
|
|
42
|
+
},
|
|
43
|
+
"./session": {
|
|
44
|
+
"types": "./dist/sdk-session.d.ts",
|
|
45
|
+
"import": "./dist/sdk-session.js"
|
|
46
|
+
},
|
|
39
47
|
"./package.json": "./package.json"
|
|
40
48
|
},
|
|
41
49
|
"scripts": {
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{pc as A,rc as M}from"./chunk-HYWVRTFA.js";import{ia as O}from"./chunk-SX2IS5JP.js";import{$ as m,S as w,T as S,U as x,V as I,W as L,X as h,_ as k,ca as b,ja as R}from"./chunk-6QO6HWGU.js";import{a as i}from"./chunk-V4WSBIXB.js";import a from"fs";import c from"path";import{exec as F,spawnSync as G}from"child_process";import{promisify as V}from"util";import{fileURLToPath as q}from"url";var E="en";function U(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}i(U,"detectSystemLocale");function N(e){if(!e||e==="auto"){E=U();return}E=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}i(N,"setLocale");var T={en:{"dialog.confirm":"[Confirm]","dialog.select":"[Select]","dialog.input":"[Input]","confirm.instruction.basic":"Press (y) yes, (n) no","confirm.instruction.always":"Press (y) yes, (a) always yes for this tool, (n) no","confirm.instruction.protected":"Press (y) to confirm, (n) to cancel (protected path)","confirm.result.approved":"Approved","confirm.result.approved_always":"Approved (always)","confirm.result.denied":"Denied","tool.bash.title":"Execute bash command?","tool.shell.title":"Execute shell command?","tool.write.title":"Write to file?","tool.edit.title":"Edit file?","tool.generic.title":"Execute {tool}?","field.reason":"Reason","field.intent":"Intent","field.target":"Target","field.scope":"Scope","field.risk":"Risk","field.summary":"Summary","intent.read":"Read project files","intent.delete":"Delete files","intent.deps":"Modify dependencies or environment","intent.modify":"Modify files","intent.execute":"Execute command","intent.write_file":"Write file","intent.edit_file":"Edit file","intent.use_tool":"Use {tool}","risk.destructive":"Destructive change","risk.deps":"May change dependencies or local tools","risk.modify":"May modify files","risk.unknown":"Command effects depend on its arguments","risk.network":"May access network","scope.outside":"Outside project","scope.protected":"Protected path","waiting.confirm":"Waiting: approval required","waiting.select":"Waiting: choose an option","waiting.input":"Waiting: answer the prompt","placeholder.confirm":"Respond to the approval prompt above...","placeholder.select":"Choose an option above...","placeholder.input":"Answer the prompt above...","placeholder.busy":"Agent is busy...","placeholder.queue":"Queue a follow-up for the next round...","placeholder.idle":"Type a message...","select.choice":"Choice:","select.type_number":"(type a number)","select.more":"{count} more choices...","select.more_above":"\u2191 {count} more above","select.more_below":"\u2193 {count} more below","select.confirm_hint":"Press Enter to confirm, Esc to cancel","select.navigate_hint":"Use \u2191\u2193 to navigate, Enter to confirm, Esc to cancel","select.multiselect_hint":"Use \u2191\u2193 to navigate, Space to toggle, Enter to confirm, Esc to cancel","select.multiselect_empty":"Select at least one option with Space before confirming.","select.back_prev":"\u2190 Back to previous question","input.default":"Default:","input.value":"Value:","input.type_response":"(type your response)","managed.completed":"Task completed","managed.completed.blocked":"Task blocked","managed.completed.continuation":"Task needs continuation",cancelled:"[Cancelled] Operation cancelled by user"},zh:{"dialog.confirm":"[\u786E\u8BA4]","dialog.select":"[\u9009\u62E9]","dialog.input":"[\u8F93\u5165]","confirm.instruction.basic":"\u6309 (y) \u786E\u8BA4, (n) \u62D2\u7EDD","confirm.instruction.always":"\u6309 (y) \u786E\u8BA4, (a) \u59CB\u7EC8\u5141\u8BB8\u6B64\u5DE5\u5177, (n) \u62D2\u7EDD","confirm.instruction.protected":"\u6309 (y) \u786E\u8BA4, (n) \u53D6\u6D88 (\u53D7\u4FDD\u62A4\u8DEF\u5F84)","confirm.result.approved":"\u5DF2\u6279\u51C6","confirm.result.approved_always":"\u5DF2\u6279\u51C6 (\u59CB\u7EC8\u5141\u8BB8)","confirm.result.denied":"\u5DF2\u62D2\u7EDD","tool.bash.title":"\u6267\u884C bash \u547D\u4EE4\uFF1F","tool.shell.title":"\u6267\u884C shell \u547D\u4EE4\uFF1F","tool.write.title":"\u5199\u5165\u6587\u4EF6\uFF1F","tool.edit.title":"\u7F16\u8F91\u6587\u4EF6\uFF1F","tool.generic.title":"\u6267\u884C {tool}\uFF1F","field.reason":"\u539F\u56E0","field.intent":"\u610F\u56FE","field.target":"\u76EE\u6807","field.scope":"\u8303\u56F4","field.risk":"\u98CE\u9669","field.summary":"\u6458\u8981","intent.read":"\u8BFB\u53D6\u9879\u76EE\u6587\u4EF6","intent.delete":"\u5220\u9664\u6587\u4EF6","intent.deps":"\u4FEE\u6539\u4F9D\u8D56\u6216\u73AF\u5883","intent.modify":"\u4FEE\u6539\u6587\u4EF6","intent.execute":"\u6267\u884C\u547D\u4EE4","intent.write_file":"\u5199\u5165\u6587\u4EF6","intent.edit_file":"\u7F16\u8F91\u6587\u4EF6","intent.use_tool":"\u4F7F\u7528 {tool}","risk.destructive":"\u7834\u574F\u6027\u53D8\u66F4","risk.deps":"\u53EF\u80FD\u4FEE\u6539\u4F9D\u8D56\u6216\u672C\u5730\u5DE5\u5177","risk.modify":"\u53EF\u80FD\u4FEE\u6539\u6587\u4EF6","risk.unknown":"\u547D\u4EE4\u6548\u679C\u53D6\u51B3\u4E8E\u53C2\u6570","risk.network":"\u53EF\u80FD\u8BBF\u95EE\u7F51\u7EDC","scope.outside":"\u9879\u76EE\u5916\u90E8","scope.protected":"\u53D7\u4FDD\u62A4\u8DEF\u5F84","waiting.confirm":"\u7B49\u5F85\u4E2D\uFF1A\u9700\u8981\u5BA1\u6279","waiting.select":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u9009\u62E9","waiting.input":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u56DE\u7B54","placeholder.confirm":"\u8BF7\u56DE\u5E94\u4E0A\u65B9\u7684\u5BA1\u6279\u63D0\u793A...","placeholder.select":"\u8BF7\u5728\u4E0A\u65B9\u9009\u62E9\u4E00\u4E2A\u9009\u9879...","placeholder.input":"\u8BF7\u56DE\u7B54\u4E0A\u65B9\u7684\u63D0\u793A...","placeholder.busy":"\u4EE3\u7406\u6B63\u5728\u5DE5\u4F5C\u4E2D...","placeholder.queue":"\u6392\u961F\u7B49\u5F85\u4E0B\u4E00\u8F6E\u8DDF\u8FDB...","placeholder.idle":"\u8F93\u5165\u6D88\u606F...","select.choice":"\u9009\u9879\uFF1A","select.type_number":"(\u8F93\u5165\u7F16\u53F7)","select.more":"\u8FD8\u6709 {count} \u4E2A\u9009\u9879...","select.more_above":"\u2191 \u4E0A\u65B9\u8FD8\u6709 {count} \u4E2A","select.more_below":"\u2193 \u4E0B\u65B9\u8FD8\u6709 {count} \u4E2A","select.confirm_hint":"\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.navigate_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0C\u7A7A\u683C \u5207\u6362\u9009\u4E2D\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_empty":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u9009\u9879\u3002","select.back_prev":"\u2190 \u8FD4\u56DE\u4E0A\u4E00\u9898","input.default":"\u9ED8\u8BA4\u503C\uFF1A","input.value":"\u503C\uFF1A","input.type_response":"(\u8F93\u5165\u4F60\u7684\u56DE\u7B54)","managed.completed":"\u4EFB\u52A1\u5B8C\u6210","managed.completed.blocked":"\u4EFB\u52A1\u53D7\u963B","managed.completed.continuation":"\u4EFB\u52A1\u9700\u8981\u7EE7\u7EED",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88"}};function pe(e,t){let o=T[E][e]??T.en[e]??e;if(t)for(let[r,l]of Object.entries(t))o=o.replace(`{${r}}`,String(l));return o}i(pe,"t");var W=V(F),X=O(),Ce=c.join(X,"sessions"),d=c.join(X,"config.json"),we=60,s=null,_=!1,J="dumb";function Q(e){let t=c.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",o=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",o],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",o]:["-lc",o],sentinel:n}}i(Q,"buildShellEnvCommand");function Y(e,t){let n=`${t}\0`,o=e.lastIndexOf(n);if(o===-1)return{};let r=e.slice(o+n.length),l={};for(let u of r.split("\0")){if(!u)continue;let p=u.indexOf("=");p<=0||(l[u.slice(0,p)]=u.slice(p+1))}return l}i(Y,"parseNullDelimitedShellEnv");function Z(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let o=e.shell??t.SHELL;if(!o||!c.isAbsolute(o))return!1;let{args:r,sentinel:l}=Q(o),u=e.run??G,p={...t,TERM:J},f=u(o,r,{encoding:"utf8",env:p,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(f.status!==0||!f.stdout)return!1;let H=typeof f.stdout=="string"?f.stdout:f.stdout.toString("utf8"),j=Y(H,l),C=!1;for(let[v,z]of Object.entries(j))v!=="TERM"&&t[v]===void 0&&(t[v]=z,C=!0);return C}i(Z,"hydrateProcessEnvFromShell");function ee(){if(!_){_=!0;try{Z()}catch{}}}i(ee,"ensureShellEnvironmentHydrated");function Se(){_=!1}i(Se,"resetShellEnvironmentHydrationForTesting");function te(e){k(e.customProviders??[])}i(te,"registerConfiguredCustomProviders");function $(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:[]}i($,"normalizeConfiguredExtensions");function ne(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{a.mkdirSync(c.dirname(d),{recursive:!0}),a.writeFileSync(d,JSON.stringify(t,null,2))}catch{}return t}i(ne,"migrateLegacyPermissionModeInConfig");function oe(){if(s)return s;let e="0.7.41";if(e)return s=e,s;let t=c.join(c.dirname(q(import.meta.url)),"../../package.json");if(a.existsSync(t))try{return s=JSON.parse(a.readFileSync(t,"utf-8")).version??"0.0.0",s??"0.0.0"}catch{}return s="0.0.0",s}i(oe,"getVersion");var xe=oe();function Ie(e){return S(e)}i(Ie,"getProviderModel");function P(e,t){let n=new Set(e.map(r=>r.toLowerCase())),o=[...e];for(let r of t)n.has(r.toLowerCase())||o.push(r);return o}i(P,"mergeModels");function ie(e,t){t||(t=y().providerModels);let n=t?.[e];if(n&&n.length>0){try{let o=h(e);if(o.length>0)return P(n,o)}catch{}try{let o=m(e);if(o)return P(n,o.getAvailableModels())}catch{}return n}try{let o=h(e);if(o.length>0)return o}catch{}try{let o=m(e);if(o)return o.getAvailableModels()}catch{}return[]}i(ie,"getProviderAvailableModels");function re(e,t){let n=x(e,t);if(n!=="unknown")return n;try{let o=m(e);if(o)return o.getReasoningCapability(t)}catch{}return"unknown"}i(re,"getProviderReasoningCapability");function se(e){let t=I(e);if(t)return t;try{return b().find(o=>o.name===e)?.capabilityProfile??null}catch{return null}}i(se,"getProviderCapabilityProfile");function B(e,t){let n=se(e),o=re(e,t);if(n)return{capabilityProfile:n,reasoningCapability:o};try{let r=R(e);return{capabilityProfile:r.getCapabilityProfile(),reasoningCapability:r.getReasoningCapability(t)}}catch{return null}}i(B,"getProviderCapabilityMetadata");function Le(e,t){let n=B(e,t);return n?A({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}i(Le,"getProviderCapabilitySnapshot");function ae(e,t,n,o){let r=B(e,t);return r?M({providerName:e,model:t,capabilityProfile:r.capabilityProfile,reasoningCapability:r.reasoningCapability==="unknown"?void 0:r.reasoningCapability,reasoningMode:n,hints:o}):null}i(ae,"getProviderPolicyDecision");function ke(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"forwards only the latest user message":"preserves full conversation history",o=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${o}`}i(ke,"describeProviderCapabilitySummary");function Re(e){switch(e){case"native-budget":return"B";case"native-effort":return"E";case"native-toggle":return"T";default:return"-"}}i(Re,"formatReasoningCapabilityShort");function ce(e){switch(e){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";default:return"none"}}i(ce,"describeReasoningCapabilityControl");function Oe(e,t){if(e==="off")return"Reasoning disabled";switch(t){case"native-budget":return"Uses native thinking budget control";case"native-effort":return"Uses native reasoning effort control";case"native-toggle":return"Uses provider-native thinking toggle only";case"none":return"Runs without native reasoning parameters";case"prompt-only":return"Uses prompt overlays only; no native reasoning parameter";default:return"Runs without native reasoning parameters"}}i(Oe,"describeReasoningExecution");function Ae(e){let t=[];e||(e=y().providerModels);for(let n of L())t.push({name:n.name,model:n.model,models:ie(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=b().map(o=>({...o,models:(()=>{let r=e?.[o.name];return r&&r.length>0?P(r,o.models):o.models})()}));t.push(...n)}catch{}return t}i(Ae,"getProviderList");function Me(e){if(w(e))return!0;try{return m(e)?.isConfigured()??!1}catch{return!1}}i(Me,"isProviderConfigured");function y(){try{if(a.existsSync(d)){let e=JSON.parse(a.readFileSync(d,"utf-8")),t=e.reasoningCeiling??e.reasoningMode;return ne({...e,reasoningMode:t,extensions:$(e.extensions)})}}catch{}return{}}i(y,"loadConfig");function le(e){e.streamIdleTimeoutMs&&!process.env.KODAX_STREAM_IDLE_TIMEOUT_MS&&(process.env.KODAX_STREAM_IDLE_TIMEOUT_MS=String(e.streamIdleTimeoutMs))}i(le,"applyResilienceRuntimeEnv");function ue(e){e.repoIntelligenceMode&&!process.env.KODAX_REPO_INTELLIGENCE_MODE&&(process.env.KODAX_REPO_INTELLIGENCE_MODE=e.repoIntelligenceMode),e.repointelEndpoint&&!process.env.KODAX_REPOINTEL_ENDPOINT&&(process.env.KODAX_REPOINTEL_ENDPOINT=e.repointelEndpoint),e.repointelBin&&!process.env.KODAX_REPOINTEL_BIN&&(process.env.KODAX_REPOINTEL_BIN=e.repointelBin),e.repoIntelligenceTrace===!0&&!process.env.KODAX_REPO_INTELLIGENCE_TRACE&&(process.env.KODAX_REPO_INTELLIGENCE_TRACE="1")}i(ue,"applyRepoIntelligenceRuntimeEnv");function Te(){ee();let e=y();return le(e),ue(e),te(e),N(e.locale),e}i(Te,"prepareRuntimeConfig");function Ne(e){let n={...y(),...e},o=$(n.extensions);o!==void 0&&(n.extensions=o);for(let r of Object.keys(e))e[r]===void 0&&delete n[r];a.mkdirSync(c.dirname(d),{recursive:!0}),a.writeFileSync(d,JSON.stringify(n,null,2))}i(Ne,"saveConfig");async function De(){try{let{stdout:e}=await W("git rev-parse --show-toplevel");return e.trim()}catch{return null}}i(De,"getGitRoot");function de(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}i(de,"formatProviderSourceKind");function Ke(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"latest-user-message only":"full conversation history";return[`Source: ${de(e.sourceKind)}`,`Transport: ${t}`,`Conversation semantics: ${n}`,`Context fidelity: ${e.contextFidelity}`,`Tool calling: ${e.toolCallingFidelity}`,`Session behavior: ${e.sessionSupport}`,`Long-running support: ${e.longRunningSupport}`,`Evidence-heavy flows: ${e.evidenceSupport}`,`Multimodal support: ${e.multimodalSupport}`,`MCP support: ${e.mcpSupport}`,`Reasoning control: ${ce(e.reasoningCapability)}`]}i(Ke,"formatProviderCapabilityDetailLines");function Xe(e,t,n){return[{label:"General coding",hints:{}},{label:"Evidence-heavy review",hints:{evidenceHeavy:!0}},{label:"Long-running task",hints:{longRunning:!0}}].map(r=>({label:r.label,decision:ae(e,t,n,r.hints)})).filter(r=>r.decision!==null)}i(Xe,"getProviderCommonPolicyScenarios");var D=.5,K=0,g={locked:!1,queue:[]};async function $e(e){for(;g.locked;)await new Promise(t=>g.queue.push(t));g.locked=!0;try{let t=(Date.now()-K)/1e3;t<D&&await new Promise(o=>setTimeout(o,(D-t)*1e3));let n=await e();return K=Date.now(),n}finally{g.locked=!1;let t=g.queue.shift();t&&t()}}i($e,"rateLimitedCall");export{pe as a,X as b,Ce as c,d,we as e,Z as f,Se as g,te as h,oe as i,xe as j,Ie as k,ie as l,re as m,se as n,Le as o,ae as p,ke as q,Re as r,ce as s,Oe as t,Ae as u,Me as v,y as w,Te as x,Ne as y,De as z,de as A,Ke as B,Xe as C,$e as D};
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{a as i}from"./chunk-V4WSBIXB.js";var H=class extends Error{static{i(this,"KodaXError")}code;constructor(e,n="KODAX_ERROR"){super(e),this.code=n,this.name="KodaXError"}},R=class extends H{static{i(this,"KodaXProviderError")}provider;constructor(e,n){super(e,"PROVIDER_ERROR"),this.provider=n,this.name="KodaXProviderError"}},de=class extends H{static{i(this,"KodaXRateLimitError")}retryAfter;constructor(e,n){super(e,"RATE_LIMIT_ERROR"),this.retryAfter=n,this.name="KodaXRateLimitError"}},Fe=class extends H{static{i(this,"KodaXNetworkError")}isTimeout;constructor(e,n=!1){super(e,"NETWORK_ERROR"),this.isTimeout=n,this.name="KodaXNetworkError"}},Ue=class extends H{static{i(this,"KodaXToolCallIdError")}constructor(e){super(e,"TOOL_CALL_ID_ERROR"),this.name="KodaXToolCallIdError"}};var Xe=32768,J=32e3,We=64e3,un=.5;var pn=["off","auto","quick","balanced","deep"],Rt={low:6e3,medium:1e4,high:2e4},At=4096;function $e(t){return t.reasoningCapability?t.reasoningCapability:t.supportsThinking?"native-toggle":"prompt-only"}i($e,"getReasoningCapability");function Q(t){return ke(t).enabled}i(Q,"isReasoningEnabled");function ke(t){if(typeof t=="boolean")return{enabled:t,mode:t?"auto":"off",depth:t?"medium":"off",taskType:"unknown",executionMode:"implementation"};let e=t?.mode??"off",n=t?.depth??St(e),o=t?.enabled??(e!=="off"&&n!=="off");return{enabled:o&&e!=="off"&&n!=="off",mode:e,depth:o?n:"off",taskType:t?.taskType??"unknown",executionMode:t?.executionMode??"implementation"}}i(ke,"normalizeReasoningRequest");function St(t){switch(t){case"quick":return"low";case"balanced":case"auto":return"medium";case"deep":return"high";default:return"off"}}i(St,"getDefaultThinkingDepthForMode");function q(t,e,n="unknown"){if(e==="off")return 0;let o={...Rt,...t.defaultThinkingBudgets??{}},s=t.taskBudgetOverrides?.[n]?.[e]??o[e];return t.thinkingBudgetCap?Math.min(s,t.thinkingBudgetCap):s}i(q,"resolveThinkingBudget");function Z(t,e,n=At){let o=Math.max(1024,e-n);return Math.max(1024,Math.min(t,o))}i(Z,"clampThinkingBudget");function je(t){switch(t){case"low":return"low";case"medium":return"medium";case"high":return"high";default:return}}i(je,"mapDepthToOpenAIReasoningEffort");import xe from"fs";import dn from"os";import He from"path";var Ge=null;function mn(t){return t==="budget"||t==="effort"||t==="toggle"||t==="none"}i(mn,"isReasoningOverride");function fn(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.providerReasoningOverrides;return e===void 0?!0:!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(mn)}i(fn,"isStoredConfig");function gn(){return process.env.KODAX_HOME??He.join(dn.homedir(),".kodax")}i(gn,"getKodaxDir");function Ot(){return process.env.KODAX_CONFIG_FILE??He.join(gn(),"config.json")}i(Ot,"getConfigFilePath");function ze(t,e){return Ge={filePath:t,config:e},e}i(ze,"updateStoredConfigCache");function hn(t){let e=JSON.parse(xe.readFileSync(t,"utf-8"));return fn(e)?e:{}}i(hn,"readStoredConfigFromDisk");function Ve(t){switch(t){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"none":return"none";default:return}}i(Ve,"reasoningCapabilityToOverride");function Ye(t){switch(t){case"budget":return"native-budget";case"effort":return"native-effort";case"toggle":return"native-toggle";default:return"none"}}i(Ye,"reasoningOverrideToCapability");function ee(t,e,n){return[t,e.baseUrl??"",n??e.model].join("|")}i(ee,"buildReasoningOverrideKey");function Je(){let t=Ot();if(Ge?.filePath===t)return Ge.config;try{if(xe.existsSync(t))return ze(t,hn(t))}catch{}return ze(t,{})}i(Je,"loadStoredConfig");function It(t){let e=Ot();try{xe.mkdirSync(He.dirname(e),{recursive:!0}),xe.writeFileSync(e,JSON.stringify(t,null,2)),ze(e,t)}catch(n){process.env.KODAX_DEBUG_OVERRIDES&&console.error("[ReasoningOverride] Failed to save config:",n)}}i(It,"saveStoredConfig");function be(t,e,n){let o=Je(),r=ee(t,e,n);return o.providerReasoningOverrides?.[r]}i(be,"loadReasoningOverride");function Qe(t,e,n,o){let r=Je(),s=ee(t,e,o);r.providerReasoningOverrides={...r.providerReasoningOverrides??{},[s]:n},It(r)}i(Qe,"saveReasoningOverride");function yn(t,e,n){let o=Je(),r=ee(t,e,n);if(!o.providerReasoningOverrides?.[r])return;let s={...o.providerReasoningOverrides};delete s[r],o.providerReasoningOverrides=Object.keys(s).length>0?s:void 0,It(o)}i(yn,"clearReasoningOverride");function Dt(t,e){if(!t)return;if(typeof t.get=="function")return t.get(e)??void 0;let n=t,o=e.toLowerCase(),r=n[e]??n[o]??n[o.replace(/\b\w/g,s=>s.toUpperCase())];if(r!==void 0)return Array.isArray(r)?r[0]:r}i(Dt,"readHeader");function Kt(t){if(!t)return;let e=t.trim();if(e.length===0)return;let n=Number(e);if(!(!Number.isFinite(n)||n<=0))return n}i(Kt,"parsePositiveNumber");function _n(t,e){if(!t)return;let n=t.trim();if(n.length===0)return;let o=Date.parse(n);if(!Number.isFinite(o))return;let r=o-e;return r>0?r:void 0}i(_n,"parseHttpDate");function ve(t,e){let n=e.baseBackoffMs??1e3,o=e.maxBackoffMs??3e4,r=e.maxHeaderWaitMs??12e4,s=e.now?e.now():Date.now(),a=Kt(Dt(t,"retry-after-ms"));if(a!==void 0){let _=Math.min(a,r);return{type:"header",waitMs:Math.round(_),source:"retry-after-ms",cappedFromHeader:_!==a}}let l=Dt(t,"retry-after");if(l!==void 0&&l.trim().length>0){let _=Kt(l);if(_!==void 0){let x=_*1e3,u=Math.min(x,r);return{type:"header",waitMs:Math.round(u),source:"retry-after-seconds",cappedFromHeader:u!==x}}let M=_n(l,s);if(M!==void 0){let x=Math.min(M,r);return{type:"header",waitMs:Math.round(x),source:"retry-after-date",cappedFromHeader:x!==M}}}let c=n*Math.pow(2,Math.max(0,e.attempt)),m=Math.min(c,o),f=e.withJitter!==!1?Math.random()*.25*m:0;return{type:"backoff",waitMs:Math.round(m+f),source:"exponential-backoff",attempt:e.attempt}}i(ve,"parseRetryAfter");function Me(t){if(!t||typeof t!="object")return;let e=t;return e.headers??e.response?.headers??e.cause?.headers??e.cause?.response?.headers}i(Me,"extractHeadersFromError");var me={transport:"native-api",conversationSemantics:"full-history",mcpSupport:"none",contextFidelity:"full",toolCallingFidelity:"full",sessionSupport:"full",longRunningSupport:"full",multimodalSupport:"none",evidenceSupport:"full"},L={...me,multimodalSupport:"image-input"},fe={transport:"cli-bridge",conversationSemantics:"last-user-message",mcpSupport:"none",contextFidelity:"lossy",toolCallingFidelity:"limited",sessionSupport:"stateless",longRunningSupport:"limited",multimodalSupport:"none",evidenceSupport:"limited"},Lt={...fe,multimodalSupport:"image-input"};function Ce(t){return{transport:t.transport,conversationSemantics:t.conversationSemantics,mcpSupport:t.mcpSupport,contextFidelity:t.contextFidelity??"full",toolCallingFidelity:t.toolCallingFidelity??"full",sessionSupport:t.sessionSupport??"full",longRunningSupport:t.longRunningSupport??"full",multimodalSupport:t.multimodalSupport??"none",evidenceSupport:t.evidenceSupport??"full"}}i(Ce,"normalizeCapabilityProfile");function F(t){return{...Ce(t)}}i(F,"cloneCapabilityProfile");function kn(t){if(!t)return;let e=parseInt(t,10);return Number.isFinite(e)&&e>0?e:void 0}i(kn,"parseEnvInt");var G=class{static{i(this,"KodaXBaseProvider")}maxOutputTokensOverride;setMaxOutputTokensOverride(e){this.maxOutputTokensOverride=e}getEffectiveMaxOutputTokens(e){if(this.maxOutputTokensOverride!==void 0)return this.maxOutputTokensOverride;let n=kn(process.env.KODAX_MAX_OUTPUT_TOKENS);if(n!==void 0)return n;let o=this.getModelDescriptor(e)?.maxOutputTokens;return o!==void 0?o:this.config.maxOutputTokens??32768}getStreamMaxDurationMs(){return this.config.streamMaxDurationMs}supportsNonStreamingFallback(){return!1}async complete(e,n,o,r,s,a){throw new R(`${this.name} does not support non-streaming fallback`)}isConfigured(){return!!process.env[this.config.apiKeyEnv]}getModel(){return this.config.model}getAvailableModels(){return this.config.models?.length?[...new Set([this.config.model,...this.config.models.map(e=>e.id)])]:[this.config.model]}getModelDescriptor(e){return!e||e===this.config.model?{id:this.config.model}:this.config.models?.find(n=>n.id===e)}getBaseUrl(){return this.config.baseUrl}getApiKeyEnv(){return this.config.apiKeyEnv}getCapabilityProfile(){return F(this.config.capabilityProfile??me)}getConfiguredReasoningCapability(e){let n=this.getModelDescriptor(e);return n?.reasoningCapability?n.reasoningCapability:$e(this.config)}getReasoningCapability(e){let n=be(this.name,this.config,e);return n?Ye(n):this.getConfiguredReasoningCapability(e)}getReasoningOverride(e){return be(this.name,this.config,e)}getReasoningOverrideKey(e){return ee(this.name,this.config,e)}persistReasoningCapabilityOverride(e,n){let o=Ve(e);o&&Qe(this.name,this.config,o,n)}shouldFallbackForReasoningError(e,...n){let o=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),s=n.map(l=>l.toLowerCase()).some(l=>o.includes(l)),a=o.includes("parameter")||s;return o.includes("unknown parameter")||o.includes("invalid parameter")||o.includes("unsupported")&&a}shouldFallbackForSpecificReasoningError(e,...n){let o=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return n.map(a=>a.toLowerCase()).some(a=>o.includes(a))?o.includes("unknown parameter")||o.includes("invalid parameter")||o.includes("unsupported"):!1}getReasoningFallbackChain(e){switch(e){case"native-budget":return["native-budget","native-toggle","none"];case"native-effort":return["native-effort","none"];case"native-toggle":return["native-toggle","none"];default:return["none"]}}getContextWindow(){return this.getEffectiveContextWindow()}getEffectiveContextWindow(e){let n=this.getModelDescriptor(e)?.contextWindow;return n!==void 0?n:this.config.contextWindow??2e5}getApiKey(){let e=process.env[this.config.apiKeyEnv];if(!e)throw new Error(`${this.config.apiKeyEnv} not set`);return e}shouldLogStreamDiagnostics(){return!!process.env.KODAX_DEBUG_STREAM}logStreamDiagnostic(...e){this.shouldLogStreamDiagnostics()&&console.error(...e)}normalizeReasoning(e){return ke(e)}onStaleConnection(){}isRateLimitError(e){if(!(e instanceof Error))return!1;let n=e.message.toLowerCase();return["rate","limit","\u901F\u7387","\u9891\u7387","1302","429","too many","overload","overwhelmed","503","529","busy"].some(o=>n.includes(o))}classifyRateLimitReason(e){let n=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return n.includes("overload")||n.includes("overwhelmed")||n.includes("503")||n.includes("529")||n.includes("busy")?"overloaded":"rate-limit"}extractRetryAfterMs(e){let n=Me(e);if(!n)return;let o=ve(n,{attempt:0,withJitter:!1});return o.type==="header"?o.waitMs:void 0}parseContextOverflow(e){let n=String(e?.message??""),o=[/(\d[\d,]*)\s*tokens?.*?(\d[\d,]*)\s*(?:maximum|limit|context)/i,/maximum.*?(\d[\d,]*)\s*tokens?.*?requested.*?(\d[\d,]*)/i,/exceeds?\s+.*?(\d[\d,]*)\s*.*?(?:limit|max|上限).*?(\d[\d,]*)/i];for(let r of o){let s=n.match(r);if(s){let a=Number(s[1].replace(/,/g,"")),l=Number(s[2].replace(/,/g,"")),c=Math.min(a,l),m=Math.max(a,l);return Math.max(3e3,m-c-1e3)}}}isContextOverflowError(e){let n=String(e?.message??"").toLowerCase();return n.includes("prompt is too long")||n.includes("prompt too long")||n.includes("context length")||n.includes("context_length_exceeded")||n.includes("context window")||n.includes("\u4E0A\u4E0B\u6587\u957F\u5EA6")}async withRateLimit(e,n,o=3,r,s){for(let a=0;a<o;a++)try{let l=await e();return this.maxOutputTokensOverride=void 0,l}catch(l){if(this.isContextOverflowError(l)&&!this.maxOutputTokensOverride){let c=this.parseContextOverflow(l);if(c){this.maxOutputTokensOverride=c,r?.(a+1,o,0);continue}}if(this.isRateLimitError(l)){if(a===o-1)throw new de(`API rate limit exceeded after ${o} retries. Please wait and try again later.`,6e4);let c=Me(l)??{},m=ve(c,{attempt:a,baseBackoffMs:500,maxBackoffMs:32e3,withJitter:!0}),v=m.waitMs,f=this.classifyRateLimitReason(l);if(s?.({provider:this.name,waitMs:v,reason:f,source:m.source,attempt:a+1,maxAttempts:o}),r?r(a+1,o,v):s||console.log(`[Rate Limit] Retrying in ${v/1e3}s (${a+1}/${o})...`),n?.aborted)throw new DOMException("Request aborted","AbortError");if(await new Promise(_=>setTimeout(_,v)),n?.aborted)throw new DOMException("Request aborted","AbortError");continue}if(l instanceof Error){if((l.name==="AbortError"||l.name==="APIUserAbortError")&&n?.aborted)throw l.name==="AbortError"?l:new DOMException(l.message||"Request aborted","AbortError");let c=l?.cause?.code??l?.code??"";throw(c==="ECONNRESET"||c==="EPIPE")&&this.onStaleConnection(),new R(`${this.name} API error: ${l.message}`,this.name)}throw l}throw new H("Unexpected end of withRateLimit")}};import Cn from"@anthropic-ai/sdk";import{parse as xn}from"partial-json";function te(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{}try{let e=xn(t);return process.env.KODAX_DEBUG_TOOL_STREAM&&console.warn("[Tool Block Salvaged] partial JSON recovered, rawLength=",t.length),e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}i(te,"parseToolInputWithSalvage");function qe(t,e){let n=t[t.length-1];if(n&&ne(n)&&n.hint===e)return t;let o=e?{type:"cache-boundary",hint:e}:{type:"cache-boundary"};return[...t,o]}i(qe,"insertCacheBoundary");function ne(t){if(typeof t!="object"||t===null||t.type!=="cache-boundary")return!1;let e=Object.keys(t);return e.length<=2&&e.every(n=>n==="type"||n==="hint")}i(ne,"isCacheBoundary");function Ze(t,e){let n=[];for(let o of t){if(ne(o)){if(e==="attach"&&n.length>0){let r=n[n.length-1];n[n.length-1]={...r,cache_control:{type:"ephemeral"}}}continue}n.push(o)}return n}i(Ze,"lowerCacheBoundaries");function ge(t){return t.filter(e=>!ne(e))}i(ge,"stripCacheBoundaries");import{readFile as bn}from"node:fs/promises";import vn from"node:path";var Mn={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"};function et(t,e){return e??Mn[vn.extname(t).toLowerCase()]??"image/png"}i(et,"resolveImageMediaType");async function tt(t){return(await bn(t)).toString("base64")}i(tt,"readImageFileAsBase64");async function Nt(t,e){let n=et(t,e),o=await tt(t);return`data:${n};base64,${o}`}i(Nt,"buildImageDataUrl");var Tn="KodaX";function En(t){return t.userAgentMode==="sdk"?void 0:{"User-Agent":Tn}}i(En,"getAnthropicCompatDefaultHeaders");function nt(t,e){if(!t)return e;let n=t.input_tokens!==void 0&&t.input_tokens!==null||t.cache_creation_input_tokens!==void 0&&t.cache_creation_input_tokens!==null||t.cache_read_input_tokens!==void 0&&t.cache_read_input_tokens!==null,o=typeof t.input_tokens=="number"?t.input_tokens:n?0:e?.inputTokens??0,r=typeof t.cache_creation_input_tokens=="number"?t.cache_creation_input_tokens:n?0:e?.cachedWriteTokens??0,s=typeof t.cache_read_input_tokens=="number"?t.cache_read_input_tokens:n?0:e?.cachedReadTokens??0,a=typeof t.output_tokens=="number"?t.output_tokens:e?.outputTokens??0,l=n?o+r+s:e?.inputTokens??0;if(![l,a].some(c=>!Number.isFinite(c)||c<0))return{inputTokens:l,outputTokens:a,totalTokens:l+a,cachedReadTokens:s||void 0,cachedWriteTokens:r||void 0}}i(nt,"normalizeAnthropicUsage");var K=class extends G{static{i(this,"KodaXAnthropicCompatProvider")}supportsThinking=!0;client;initClient(){let e=En(this.config);this.client=new Cn({apiKey:this.getApiKey(),baseURL:this.config.baseUrl,...e?{defaultHeaders:e}:{}})}onStaleConnection(){this.initClient()}applyCacheControlToSystem(e){if(!e.trim()||process.env.KODAX_DISABLE_PROMPT_CACHE==="1")return e;let n=qe([{type:"text",text:e}],"system");return Ze(n,"attach")}applyCacheControlToTools(e){if(e.length===0||process.env.KODAX_DISABLE_PROMPT_CACHE==="1")return e;let n=e.slice(),o=n[n.length-1];return n[n.length-1]={...o,cache_control:{type:"ephemeral"}},n}async stream(e,n,o,r,s,a){return this.withRateLimit(async()=>{let l=this.normalizeReasoning(r),c=s?.modelOverride??this.config.model,m=this.getEffectiveMaxOutputTokens(c),v=await this.convertMessages(e),f=l.enabled?this.getReasoningCapability(c):"none",_=l.enabled?this.getReasoningFallbackChain(f).filter(k=>k==="native-budget"||k==="native-toggle"||k==="none"):["none"],M=i(k=>{let P={model:c,max_tokens:m,system:this.applyCacheControlToSystem(this.buildSystemPrompt(o,e)),messages:v,tools:this.applyCacheControlToTools(n),stream:!0};if(k==="native-budget"){let S=q(this.config,l.depth,l.taskType);P.thinking={type:"enabled",budget_tokens:Z(S,m)}}else k==="native-toggle"&&(P.thinking={type:"enabled"});return P},"buildRequest");if(a?.aborted)throw new DOMException("Request aborted","AbortError");let x=[],u=[],y=[],g,b=null,p="",d="",T="",w="",W="",O="",$="",E=!1,j,A=Date.now(),_e=Date.now(),le,ue;for(let k of _)try{le=await this.client.messages.create(M(k),a?{signal:a}:{}),k!==f&&this.persistReasoningCapabilityOverride(k,c);break}catch(P){ue=P;let S=k==="native-budget"?["budget_tokens","thinking"]:k==="native-toggle"?["thinking"]:[];if(!this.shouldFallbackForReasoningError(P,...S))throw P}if(!le)throw ue??new R("All reasoning capability attempts failed without a captured error",this.name);let pe=Date.now(),C=0,I=0,D=3e4;for await(let k of le){if(a?.aborted)throw new DOMException("Request aborted","AbortError");let P=Date.now(),S=P-pe;if(S>D&&(C++,I+=S,this.logStreamDiagnostic(`[Stream] stall detected: ${Math.round(S/1e3)}s gap before ${k.type}`,{stallCount:C,totalStallMs:I,eventType:k.type})),pe=P,k.type==="content_block_start"||k.type==="content_block_stop"?s?.onHeartbeat?.(!0):s?.onHeartbeat?.(),k.type==="content_block_start"){A=Date.now();let h=k.content_block;b=h.type,process.env.KODAX_DEBUG_TOOL_STREAM&&h.type==="tool_use"&&console.error("[ToolStream] content_block_start:",{type:h.type,id:h.id,name:h.name}),h.type==="thinking"?(d="",T=h.signature??""):h.type==="redacted_thinking"?(b="redacted_thinking",w=h.data??""):h.type==="text"?p="":h.type==="tool_use"&&(W=h.id,O=h.name,$="")}else if(k.type==="content_block_delta"){A=Date.now();let h=k.delta;h.type==="thinking_delta"?(d+=h.thinking??"",s?.onThinkingDelta?.(h.thinking??"")):h.type==="text_delta"?(p+=h.text??"",s?.onTextDelta?.(h.text??"")):h.type==="input_json_delta"&&($+=h.partial_json??"",s?.onToolInputDelta?.(O,h.partial_json??"",W?{toolId:W}:void 0))}else if(k.type==="content_block_stop")A=Date.now(),b==="thinking"?d&&(y.push({type:"thinking",thinking:d,signature:T}),s?.onThinkingEnd?.(d)):b==="redacted_thinking"?(w&&y.push({type:"redacted_thinking",data:w}),w=""):b==="text"?p&&x.push({type:"text",text:p}):b==="tool_use"&&(!W||!O?console.error("[Tool Block Invalid] Missing tool id or name:",{id:JSON.stringify(W),name:JSON.stringify(O),input:$.slice(0,100)}):u.push({type:"tool_use",id:W,name:O,input:te($)})),b=null;else if(k.type==="message_stop"){if(E=!0,A=Date.now(),process.env.KODAX_DEBUG_STREAM){let h=Date.now()-_e;this.logStreamDiagnostic(`[Stream] message_stop received after ${h}ms`)}}else if(k.type==="message_delta"){A=Date.now(),g=nt(k.usage,g);let h=k.delta;h?.stop_reason&&(j=h.stop_reason,process.env.KODAX_DEBUG_STREAM&&this.logStreamDiagnostic(`[Stream] message_delta with stop_reason: ${j}`))}else k.type==="message_start"&&(A=Date.now(),g=nt(k.message?.usage,g),process.env.KODAX_DEBUG_STREAM&&this.logStreamDiagnostic("[Stream] message_start received"))}if(!E){let k=Date.now()-_e,P=Date.now()-A;if(a?.aborted){let h=a.reason instanceof Error?a.reason.message:typeof a.reason=="string"?a.reason:"Request aborted";throw this.logStreamDiagnostic("[Stream] Stream ended after abort before message_stop:",{duration:k,lastEventAge:P,reason:h,textBlocks:x.length,toolBlocks:u.length,thinkingBlocks:y.length}),new DOMException(h,"AbortError")}let S=new Error(`Stream incomplete: message_stop event not received. Duration: ${k}ms, Last event: ${P}ms ago. This may indicate a network disconnection or API timeout.`);throw S.name="StreamIncompleteError",this.logStreamDiagnostic("[Stream] Incomplete stream detected:",{duration:k,lastEventAge:P,textBlocks:x.length,toolBlocks:u.length,thinkingBlocks:y.length}),S}return{textBlocks:x,toolBlocks:u,thinkingBlocks:y,usage:g,stopReason:j}},a,3,s?.onRateLimit,s?.onRetryAfter)}supportsNonStreamingFallback(){return!0}async complete(e,n,o,r,s,a){return this.withRateLimit(async()=>{let l=this.normalizeReasoning(r),c=s?.modelOverride??this.config.model,m=this.getEffectiveMaxOutputTokens(c),v=await this.convertMessages(e),f=l.enabled?this.getReasoningCapability(c):"none",_=l.enabled?this.getReasoningFallbackChain(f).filter(p=>p==="native-budget"||p==="native-toggle"||p==="none"):["none"],M=i(p=>{let d={model:c,max_tokens:m,system:this.applyCacheControlToSystem(this.buildSystemPrompt(o,e)),messages:v,tools:this.applyCacheControlToTools(n)};if(p==="native-budget"){let T=q(this.config,l.depth,l.taskType);d.thinking={type:"enabled",budget_tokens:Z(T,m)}}else p==="native-toggle"&&(d.thinking={type:"enabled"});return d},"buildRequest"),x,u;for(let p of _)try{x=await this.client.messages.create(M(p),a?{signal:a}:{}),p!==f&&this.persistReasoningCapabilityOverride(p,c);break}catch(d){u=d;let T=p==="native-budget"?["budget_tokens","thinking"]:p==="native-toggle"?["thinking"]:[];if(!this.shouldFallbackForReasoningError(d,...T))throw d}if(!x)throw u??new R("All reasoning capability attempts failed without a captured error",this.name);let y=[],g=[],b=[];for(let p of x.content)p.type==="text"?(y.push({type:"text",text:p.text}),s?.onTextDelta?.(p.text)):p.type==="thinking"?(b.push({type:"thinking",thinking:p.thinking,signature:p.signature??""}),s?.onThinkingDelta?.(p.thinking),s?.onThinkingEnd?.(p.thinking)):p.type==="redacted_thinking"?b.push({type:"redacted_thinking",data:p.data}):p.type==="tool_use"&&g.push({type:"tool_use",id:p.id,name:p.name,input:typeof p.input=="object"&&p.input!==null?p.input:{}});return{textBlocks:y,toolBlocks:g,thinkingBlocks:b,usage:nt(x.usage),stopReason:x.stop_reason??void 0}},a,3,s?.onRateLimit,s?.onRetryAfter)}serializeSystemMessageContent(e){if(typeof e=="string")return e.trim();for(let n of e)if(ne(n))throw new R("cache-boundary marker reached system message serialization unlowered. Provider base class lowering must run before any wire-level serialization.",this.name);return e.filter(n=>n.type==="text").map(n=>n.text.trim()).filter(Boolean).join(`
|
|
3
|
-
`)}buildSystemPrompt(e,n){let o=n.filter(r=>r.role==="system").map(r=>this.serializeSystemMessageContent(r.content)).filter(Boolean);return[e,...o].filter(r=>typeof r=="string"&&r.trim().length>0).join(`
|
|
4
|
-
|
|
5
|
-
`)}async convertMessages(e){let n=[];for(let o of e.filter(r=>r.role!=="system")){let r=o.role==="user"?"user":"assistant";if(typeof o.content=="string"){n.push({role:r,content:o.content});continue}let s=[],a=[];for(let c of o.content)c.type==="thinking"?!this.config.strictThinkingSignature||typeof c.signature=="string"&&c.signature.length>0?s.push({type:"thinking",thinking:c.thinking,signature:c.signature??""}):c.thinking&&a.push(c.thinking):c.type==="redacted_thinking"&&(this.config.strictThinkingSignature||s.push({type:"redacted_thinking",data:c.data}));a.length>0&&o.role==="assistant"&&s.push({type:"text",text:`<prior_reasoning>
|
|
6
|
-
${a.join(`
|
|
7
|
-
|
|
8
|
-
`)}
|
|
9
|
-
</prior_reasoning>`});for(let c of o.content)c.type==="tool_result"&&o.role==="user"&&s.push({type:"tool_result",tool_use_id:c.tool_use_id,content:c.content,...c.is_error===!0?{is_error:!0}:{}});for(let c of o.content)c.type==="tool_use"&&o.role==="assistant"&&s.push({type:"tool_use",id:c.id,name:c.name,input:c.input});for(let c of o.content)c.type==="text"?s.push({type:"text",text:c.text}):c.type==="image"&&o.role==="user"&&s.push({type:"image",source:{type:"base64",media_type:et(c.path,c.mediaType),data:await tt(c.path)}});if(r==="assistant"&&this.config.supportsThinking&&!this.config.strictThinkingSignature){let c=s.some(v=>v.type==="tool_use"),m=s.some(v=>v.type==="thinking"||v.type==="redacted_thinking");c&&!m&&s.unshift({type:"thinking",thinking:"...",signature:""})}let l=s.length===0||r==="assistant"&&s.every(c=>{let m=c;return m.type==="thinking"&&!m.thinking||m.type==="text"&&!m.text});n.push({role:o.role,content:l?[{type:"text",text:"..."}]:s})}return n}};import Pn from"openai";var wn="KodaX";function Rn(t){return t.userAgentMode==="sdk"?void 0:{"User-Agent":wn}}i(Rn,"getOpenAICompatDefaultHeaders");function Bt(t){if(!t)return;let e=typeof t.prompt_tokens=="number"?t.prompt_tokens:0,n=typeof t.completion_tokens=="number"?t.completion_tokens:0,o=typeof t.total_tokens=="number"?t.total_tokens:e+n;if([e,n,o].some(s=>!Number.isFinite(s)||s<0)||o<e||o<n)return;let r=typeof t.prompt_tokens_details?.cached_tokens=="number"&&t.prompt_tokens_details.cached_tokens>=0?t.prompt_tokens_details.cached_tokens:typeof t.prompt_cache_hit_tokens=="number"&&t.prompt_cache_hit_tokens>=0?t.prompt_cache_hit_tokens:void 0;return{inputTokens:e,outputTokens:n,totalTokens:o,...r!==void 0?{cachedReadTokens:r}:{}}}i(Bt,"normalizeOpenAIUsage");function An(t){return t?t.type==="function"&&"function"in t:!1}i(An,"isOpenAIFunctionToolCall");function Sn(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return"";let n=Reflect.get(e,"text");if(typeof n=="string")return n;if(n&&typeof n=="object"){let o=Reflect.get(n,"value");return typeof o=="string"?o:""}return""}).filter(Boolean).join(""):""}i(Sn,"extractOpenAIMessageText");function On(t){if(!t||typeof t!="object")return"";let e=Reflect.get(t,"reasoning_content");return typeof e=="string"?e:Array.isArray(e)?e.map(n=>typeof n=="string"?n:n&&typeof n=="object"&&"text"in n&&typeof n.text=="string"?n.text:"").join(""):""}i(On,"extractOpenAIMessageReasoning");var N=class extends G{static{i(this,"KodaXOpenAICompatProvider")}supportsThinking=!0;client;initClient(){let e=Rn(this.config);this.client=new Pn({apiKey:this.getApiKey(),baseURL:this.config.baseUrl,...e?{defaultHeaders:e}:{}})}onStaleConnection(){this.initClient()}stripCacheBoundariesFromMessages(e){return e.map(n=>{if(typeof n.content=="string")return n;let o=ge(n.content);return o.length===n.content.length?n:{...n,content:o}})}normalizeSystemForWire(e,n){let o=[];e&&e.trim().length>0&&o.push(e);let r=[];for(let s of n){if(s.role!=="system"){r.push(s);continue}let a=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.filter(l=>typeof l=="object"&&l!==null&&l.type==="text"&&typeof l.text=="string").map(l=>l.text).join(`
|
|
10
|
-
`):"";a.trim().length>0&&o.push(a)}return{system:o.join(`
|
|
11
|
-
|
|
12
|
-
`),rest:r}}appendExtraBody(e,n){let o=typeof e.extra_body=="object"&&e.extra_body!==null?e.extra_body:{};e.extra_body={...o,...n}}resetReasoningCapabilityParams(e){delete e.reasoning_effort,delete e.thinking;let n=typeof e.extra_body=="object"&&e.extra_body!==null?{...e.extra_body}:void 0;if(n){if(delete n.enable_thinking,delete n.thinking_budget,delete n.thinking,Object.keys(n).length===0){delete e.extra_body;return}e.extra_body=n}}applyReasoningCapability(e,n,o){let r=e,s=this.getEffectiveMaxOutputTokens(e.model),a=Z(q(this.config,o.depth,o.taskType),s);switch(n){case"native-effort":{let l=je(o.depth);l&&(r.reasoning_effort=l);break}case"native-budget":{this.name==="qwen"?this.appendExtraBody(r,{enable_thinking:!0,thinking_budget:a}):this.name==="zhipu"&&(r.thinking={type:"enabled",budget_tokens:a});break}case"native-toggle":{this.name==="qwen"?this.appendExtraBody(r,{enable_thinking:!0}):this.name==="zhipu"&&(r.thinking={type:"enabled"});break}default:break}}getFallbackTerms(e){switch(e){case"native-budget":return["thinking_budget","budget_tokens","thinking"];case"native-effort":return["reasoning_effort"];case"native-toggle":return["enable_thinking","thinking"];default:return[]}}async stream(e,n,o,r,s,a){return this.withRateLimit(async()=>{let l=this.stripCacheBoundariesFromMessages(e),{system:c,rest:m}=this.normalizeSystemForWire(o,l),v=[{role:"system",content:c},...await this.convertMessages(m)],f=n.map(C=>({type:"function",function:{name:C.name,description:C.description,parameters:C.input_schema}}));if(a?.aborted)throw new DOMException("Request aborted","AbortError");let _=new Map,M="",x="",u,y=!0,g=null,b=Date.now(),p=this.normalizeReasoning(r),d=s?.modelOverride??this.config.model,T=Q(p)?this.getReasoningCapability(d):"none",w=Q(p)?this.getReasoningFallbackChain(T).filter(C=>C==="native-budget"||C==="native-effort"||C==="native-toggle"||C==="none"):["none"],W={model:d,messages:v,tools:f,max_completion_tokens:this.getEffectiveMaxOutputTokens(d),stream:!0},O,$;for(let C of w){for(;!O;){let I={...W};y&&(I.stream_options={include_usage:!0}),this.resetReasoningCapabilityParams(I),this.applyReasoningCapability(I,C,p);try{O=await this.client.chat.completions.create(I,a?{signal:a}:{}),C!==T&&this.persistReasoningCapabilityOverride(C,d)}catch(D){if($=D,y&&this.shouldFallbackForSpecificReasoningError(D,"stream_options","include_usage")){y=!1;continue}if(!this.shouldFallbackForReasoningError(D,...this.getFallbackTerms(C)))throw D;break}}if(O)break}if(!O)throw $??new R("All reasoning capability attempts failed without a captured error",this.name);let E=Date.now(),j=0,A=0,_e=3e4;for await(let C of O){if(a?.aborted)throw new DOMException("Request aborted","AbortError");let I=Date.now(),D=I-E;D>_e&&(j++,A+=D,this.logStreamDiagnostic(`[Stream] stall detected: ${Math.round(D/1e3)}s gap`,{stallCount:j,totalStallMs:A})),E=I,s?.onHeartbeat?.(),u=Bt(C.usage)??u;let k=C.choices[0],P=k?.delta;if(k?.finish_reason&&(g=k.finish_reason,process.env.KODAX_DEBUG_STREAM)){let h=Date.now()-b;this.logStreamDiagnostic(`[Stream] finish_reason: ${g} after ${h}ms`)}P?.content&&(M+=P.content,s?.onTextDelta?.(P.content));let S=this.extractReasoningDelta(P);if(S&&(x+=S,s?.onThinkingDelta?.(S)),P?.tool_calls)for(let h of P.tool_calls){let Y=_.get(h.index)??{id:"",name:"",arguments:""};h.id&&(Y.id=h.id),h.function?.name&&(Y.name=h.function.name),h.function?.arguments&&(Y.arguments+=h.function.arguments,s?.onToolInputDelta?.(Y.name,h.function.arguments,Y.id?{toolId:Y.id}:void 0)),_.set(h.index,Y)}}if(!g){let C=Date.now()-b;if(a?.aborted){let D=a.reason instanceof Error?a.reason.message:typeof a.reason=="string"?a.reason:"Request aborted";throw this.logStreamDiagnostic("[Stream] Stream ended after abort before finish_reason:",{duration:C,reason:D,textContentLength:M.length,toolCallsCount:_.size}),new DOMException(D,"AbortError")}let I=new Error(`Stream incomplete: finish_reason not received. Duration: ${C}ms. This may indicate a network disconnection or API timeout.`);throw I.name="StreamIncompleteError",this.logStreamDiagnostic("[Stream] Incomplete stream detected:",{duration:C,textContentLength:M.length,toolCallsCount:_.size}),I}let le=M?[{type:"text",text:M}]:[],ue=[],pe=[];x&&(pe.push({type:"thinking",thinking:x}),s?.onThinkingEnd?.(x));for(let[,C]of _)C.id&&C.name&&ue.push({type:"tool_use",id:C.id,name:C.name,input:te(C.arguments)});return{textBlocks:le,toolBlocks:ue,thinkingBlocks:pe,usage:u,stopReason:g??void 0}},a,3,s?.onRateLimit,s?.onRetryAfter)}supportsNonStreamingFallback(){return!0}async complete(e,n,o,r,s,a){return this.withRateLimit(async()=>{let l=this.stripCacheBoundariesFromMessages(e),{system:c,rest:m}=this.normalizeSystemForWire(o,l),v=[{role:"system",content:c},...await this.convertMessages(m)],f=n.map(E=>({type:"function",function:{name:E.name,description:E.description,parameters:E.input_schema}})),_=this.normalizeReasoning(r),M=s?.modelOverride??this.config.model,x=Q(_)?this.getReasoningCapability(M):"none",u=Q(_)?this.getReasoningFallbackChain(x).filter(E=>E==="native-budget"||E==="native-effort"||E==="native-toggle"||E==="none"):["none"],y={model:M,messages:v,tools:f,max_completion_tokens:this.getEffectiveMaxOutputTokens(M)},g,b;for(let E of u){let j={...y};this.resetReasoningCapabilityParams(j),this.applyReasoningCapability(j,E,_);try{g=await this.client.chat.completions.create(j,a?{signal:a}:{}),E!==x&&this.persistReasoningCapabilityOverride(E,M);break}catch(A){if(b=A,!this.shouldFallbackForReasoningError(A,...this.getFallbackTerms(E)))throw A}}if(!g)throw b??new R("All reasoning capability attempts failed without a captured error",this.name);let p=g.choices[0],d=p?.message,T=Sn(d?.content),w=On(d),W=(d?.tool_calls??[]).filter(An).map(E=>({type:"tool_use",id:E.id,name:E.function.name,input:te(E.function.arguments)}));T&&s?.onTextDelta?.(T);let O=T?[{type:"text",text:T}]:[],$=[];return w&&($.push({type:"thinking",thinking:w}),s?.onThinkingDelta?.(w),s?.onThinkingEnd?.(w)),{textBlocks:O,toolBlocks:W,thinkingBlocks:$,usage:Bt(g.usage),stopReason:p?.finish_reason??void 0}},a,3,s?.onRateLimit,s?.onRetryAfter)}extractReasoningDelta(e){let n=e?.reasoning_content;return typeof n=="string"?n:Array.isArray(n)?n.map(o=>typeof o=="string"?o:typeof o=="object"&&o!==null&&"text"in o&&typeof o.text=="string"?o.text:"").join(""):""}serializeAssistantMessage(e){let n=e.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
13
|
-
`),o=e.filter(c=>c.type==="tool_use").map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:JSON.stringify(c.input??{})}})),r=e.filter(c=>c.type==="thinking"||c.type==="redacted_thinking").map(c=>c.type==="thinking"?c.thinking:"").filter(Boolean).join(`
|
|
14
|
-
|
|
15
|
-
`),s=e.some(c=>c.type==="thinking"||c.type==="redacted_thinking");if(!n&&o.length===0&&!s)return[];let a;n?a=n:o.length>0?a=null:a="...";let l={role:"assistant",content:a};return o.length>0&&(l.tool_calls=o),this.config.replayReasoningContent&&(l.reasoning_content=r||""),[l]}async serializeUserMessage(e){let n=[],o=e.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
16
|
-
`),r=e.filter(a=>a.type==="image");for(let a of e)a.type==="tool_result"&&n.push({role:"tool",tool_call_id:a.tool_use_id,content:a.content});if(r.length===0)return o&&n.push({role:"user",content:o}),n;let s=[];o&&s.push({type:"text",text:o});for(let a of r)s.push({type:"image_url",image_url:{url:await Nt(a.path,a.mediaType)}});return n.push({role:"user",content:s}),n}serializeSystemMessage(e){if(typeof e=="string")return[{role:"system",content:e}];let n=e.filter(o=>o.type==="text").map(o=>o.text).join(`
|
|
17
|
-
`);return n?[{role:"system",content:n}]:[]}async convertMessages(e){let n=[];for(let o of e){if(o.role==="system"){n.push(...this.serializeSystemMessage(o.content));continue}if(typeof o.content=="string"){n.push({role:o.role,content:o.content});continue}if(o.role==="assistant"){n.push(...this.serializeAssistantMessage(o.content));continue}n.push(...await this.serializeUserMessage(o.content))}return n}};import{spawn as In}from"node:child_process";import{Readable as Dn,Writable as Kn}from"node:stream";import ot from"node:process";import{ClientSideConnection as Ln,PROTOCOL_VERSION as Nn,ndJsonStream as Bn}from"@agentclientprotocol/sdk";var Te=class{static{i(this,"AcpClient")}client=null;agentProcess=null;options;constructor(e){this.options=e}async connect(){let e,n;if(this.options.inputStream&&this.options.outputStream)e=this.options.inputStream,n=this.options.outputStream;else if(this.options.command){let s=ot.platform==="win32"&&!this.options.command.endsWith(".cmd")?`${this.options.command}.cmd`:this.options.command;if(this.agentProcess=In(s,this.options.args??[],{cwd:this.options.cwd??ot.cwd(),stdio:["pipe","pipe","inherit"]}),!this.agentProcess.stdin||!this.agentProcess.stdout)throw new Error("Failed to create ACP stdio pipes");n=Kn.toWeb(this.agentProcess.stdin),e=Dn.toWeb(this.agentProcess.stdout)}else throw new Error("AcpClient requires either a command or I/O streams");let o=Bn(n,e);this.client=new Ln(()=>({sessionUpdate:i(async r=>{this.options.onSessionUpdate?.(r)},"sessionUpdate"),requestPermission:i(async r=>{let s=r.options??[],a=s.find(l=>l.kind==="allow_once"||l.kind==="allow_always")??s[0];return a?{outcome:{outcome:"selected",optionId:a.optionId}}:{outcome:{outcome:"cancelled"}}},"requestPermission")}),o),await this.client.initialize({protocolVersion:Nn,clientCapabilities:{},clientInfo:{name:"kodax-ai-acp-client",version:"1.0.0"}})}async createNewSession(){if(!this.client)throw new Error("Client not connected");return(await this.client.newSession({cwd:this.options.cwd??ot.cwd(),mcpServers:[]})).sessionId}async prompt(e,n,o,r){if(!this.client)throw new Error("Client not connected");let s={sessionId:n,prompt:[{type:"text",text:e}]};r?.model&&(s.model=r.model);let a=this.client.prompt(s);if(o){let l=i(()=>{this.client?.cancel({sessionId:n}).catch(()=>{})},"onAbort");o.addEventListener("abort",l),a=a.finally(()=>{o.removeEventListener("abort",l)})}return await a}disconnect(){this.agentProcess?.kill(),this.options.abort?.();try{this.client?.close?.()}catch{}this.client=null}};function Fn(t){if(!t||typeof t!="object")return;let e=t,n=typeof e.inputTokens=="number"?e.inputTokens:0,o=typeof e.outputTokens=="number"?e.outputTokens:0,r=typeof e.totalTokens=="number"?e.totalTokens:n+o;if(![n,o,r].some(s=>!Number.isFinite(s)||s<0)&&!(r<n||r<o))return{inputTokens:n,outputTokens:o,totalTokens:r,cachedReadTokens:typeof e.cachedReadTokens=="number"?e.cachedReadTokens:void 0,cachedWriteTokens:typeof e.cachedWriteTokens=="number"?e.cachedWriteTokens:void 0,thoughtTokens:typeof e.thoughtTokens=="number"?e.thoughtTokens:void 0}}i(Fn,"normalizeAcpUsage");var oe=class extends G{static{i(this,"KodaXAcpProvider")}_client=null;_sessionMap=new Map;_activeStreams=new Map;isConfigured(){return!0}getCapabilityProfile(){return F(fe)}serializeImageBlockToPromptToken(e){return null}stripCacheBoundariesFromMessages(e){return e.map(n=>{if(typeof n.content=="string")return n;let o=ge(n.content);return o.length===n.content.length?n:{...n,content:o}})}async stream(e,n,o,r,s,a){if(e=this.stripCacheBoundariesFromMessages(e),this.acpClientOptions.executor&&typeof this.acpClientOptions.executor.isInstalled=="function"&&!await this.acpClientOptions.executor.isInstalled())throw new Error(`${this.name} requires a local CLI environment, but the CLI was not found or is not configured correctly.`);let l=[],c=[],m=e[e.length-1],v="";if(m&&typeof m.content=="string")v=m.content;else if(m&&Array.isArray(m.content)){let y=[];for(let g of m.content)if(g.type==="text")y.push(g.text);else if(g.type==="image"){let b=this.serializeImageBlockToPromptToken(g);b&&y.push(b)}v=y.join(`
|
|
18
|
-
`)}let f={...this.acpClientOptions,onSessionUpdate:i(y=>{let g=y.update,b=y.sessionId;if(!("sessionUpdate"in g))return;let p=b?this._activeStreams.get(b):void 0;if(p)switch(g.sessionUpdate){case"agent_message_chunk":if(g.content?.type==="text"){let d=g.content.text;p.output.text+=d,p.streamOptions?.onTextDelta?.(d)}break;case"tool_call":{let d="{}",T=g.arguments??g.parameters;T&&(d=typeof T=="string"?T:JSON.stringify(T)),p.streamOptions?.onToolInputDelta?.(g.title,d);let w=`
|
|
19
|
-
> [Tool Use] ${g.title}: ${d}
|
|
20
|
-
`;p.output.text+=w,p.streamOptions?.onTextDelta?.(w);break}case"tool_call_update":if(g.status){let d=`> [Tool Result] ${g.status}
|
|
21
|
-
|
|
22
|
-
`;p.output.text+=d,p.streamOptions?.onTextDelta?.(d)}break}},"onSessionUpdate")},_=s?.sessionId??"default";this._client||(this._client=new Te(f),await this._client.connect());let M=this._sessionMap.get(_);M||(M=await this._client.createNewSession(),this._sessionMap.set(_,M));let x={text:""};this._activeStreams.set(M,{streamOptions:s,output:x});let u;try{u=await this._client.prompt(v,M,a,{model:s?.modelOverride})}catch(y){if(!(y instanceof Error&&y.name==="AbortError"))throw y}finally{this._activeStreams.delete(M)}return x.text&&l.push({type:"text",text:x.text}),{textBlocks:l,toolBlocks:c,thinkingBlocks:[],usage:Fn(u?.usage)}}disconnect(){this._client&&(this._client.disconnect(),this._client=null),this._activeStreams.clear(),this._sessionMap.clear()}};import{spawn as Un}from"node:child_process";import it from"node:process";var ie=class{static{i(this,"CLIExecutor")}config;_installedCache=null;constructor(e){this.config=e}async isInstalled(){return this._installedCache!==null?this._installedCache:(this._installedCache=await this.checkInstalled(),this._installedCache)}async*execute(e){let n=this.buildArgs(e),o={...it.env,...this.config.env},s=it.platform==="win32"&&!this.config.command.endsWith(".cmd")?`${this.config.command}.cmd`:this.config.command,a=Un(s,n,{cwd:this.config.cwd??it.cwd(),env:o,stdio:["ignore","pipe","pipe"]}),l="";a.stderr?.on("data",v=>{l+=v.toString()});let c=!1,m=i(()=>{c||a.kill("SIGTERM")},"abortHandler");e.signal?.addEventListener("abort",m),a.on("exit",()=>{c=!0});try{yield*this.parseOutputStream(a.stdout,e.signal),l.trim()&&console.error(`[CLIExecutor] stderr: ${l.trim()}`)}finally{e.signal?.removeEventListener("abort",m),c||a.kill()}}async*parseOutputStream(e,n){let o="";for await(let r of e){if(n?.aborted)break;o+=r.toString();let s=o.split(`
|
|
23
|
-
`);o=s.pop()??"";for(let a of s){if(!a.trim())continue;let l=this.parseLine(a.trim());l&&(yield l)}}if(o.trim()&&!n?.aborted){let r=this.parseLine(o.trim());r&&(yield r)}}};import{spawn as Xn}from"node:child_process";import Wn from"node:process";async function Ee(t){try{let e=Wn.platform==="win32",n=Xn(e?`${t}.cmd`:t,["--version"]);return await new Promise(o=>{n.on("close",r=>o(r===0)),n.on("error",()=>o(!1))})}catch{return!1}}i(Ee,"checkCliCommandInstalled");var Pe=class extends ie{static{i(this,"GeminiCLIExecutor")}model;constructor(e){super({command:"gemini",baseArgs:["--output-format","stream-json","--approval-mode","yolo"],timeout:3e5,...e}),this.model=e?.model??"gemini-2.5-pro"}async checkInstalled(){return Ee("gemini")}buildArgs(e){let n=["-m",e.model??this.model];return e.sessionId?(n.push("-r",e.sessionId),n.push(e.prompt)):n.push("-p",e.prompt),[...n,...this.config.baseArgs]}parseLine(e){if(!e.startsWith("{"))return null;try{let n=JSON.parse(e);return this.convertEvent(n)}catch{return null}}convertEvent(e){let n=e.timestamp?Date.parse(e.timestamp):Date.now();switch(e.type){case"init":return{type:"session_start",timestamp:n,sessionId:e.session_id??"",model:e.model??this.model,raw:e};case"message":return{type:"message",timestamp:n,role:e.role,content:e.content??"",delta:e.delta,raw:e};case"tool_use":return{type:"tool_use",timestamp:n,toolId:e.tool_id??"",toolName:e.tool_name??"",parameters:e.parameters??{},raw:e};case"tool_result":return{type:"tool_result",timestamp:n,toolId:e.tool_id??"",status:e.status==="success"?"success":"error",output:e.output??"",raw:e};case"error":return{type:"error",timestamp:n,errorType:"error",message:e.message??"Unknown error",raw:e};case"result":return{type:"complete",timestamp:n,status:e.status==="success"?"success":"failed",usage:e.stats?{inputTokens:e.stats.input_tokens??0,outputTokens:e.stats.output_tokens??0,totalTokens:e.stats.total_tokens??0}:void 0,raw:e};default:return null}}};import{TransformStream as Ft}from"node:stream/web";import{randomUUID as rt}from"node:crypto";function we(t){let e=new Ft,n=new Ft,o=e.readable.getReader(),r=n.writable.getWriter(),s=new TextDecoder,a=new TextEncoder,l="",c=rt(),m=new AbortController,v=new Map;(async()=>{try{for(;;){let{done:u,value:y}=await o.read();if(u)break;l+=s.decode(y,{stream:!0});let g=l.split(`
|
|
24
|
-
`);l=g.pop()??"";for(let b of g)if(b.trim())try{let p=JSON.parse(b);_(p).catch(d=>{console.error("[PseudoAcpServer] Failed to handle request:",d)})}catch{console.error("[PseudoAcpServer] Failed to parse message:",b)}}}catch(u){console.error("[PseudoAcpServer] Stream read error:",u)}})();let f=i(async u=>{let y=JSON.stringify(u)+`
|
|
25
|
-
`;await r.write(a.encode(y))},"sendMsg");async function _(u){if(u.method==="initialize")await f({jsonrpc:"2.0",id:u.id,result:{protocolVersion:u.params.protocolVersion,serverInfo:{name:"pseudo-acp-server",version:"1.0.0"},serverCapabilities:{}}});else if(u.method==="session/new"||u.method==="sessions/new")c=u.params?.sessionId??rt(),await f({jsonrpc:"2.0",id:u.id,result:{sessionId:c}});else if(u.method==="session/prompt"||u.method==="chat/prompt"){let y=new AbortController,g=u.params.sessionId;v.set(g,y);let b=i(()=>y.abort(),"onGlobalAbort");m.signal.addEventListener("abort",b);let d=await M(g,u.params.prompt,typeof u.params.model=="string"?u.params.model:void 0,y.signal).finally(()=>{v.delete(g),m.signal.removeEventListener("abort",b)});await f({jsonrpc:"2.0",id:u.id,result:d.usage?{stopReason:d.stopReason,usage:d.usage}:{stopReason:d.stopReason}})}else if(u.method==="session/cancel"||u.method==="chat/cancel"){let y=v.get(u.params.sessionId);y&&y.abort(),u.id!==void 0&&await f({jsonrpc:"2.0",id:u.id,result:{}})}else u.id!==void 0&&await f({jsonrpc:"2.0",id:u.id,result:{}})}i(_,"handleRequest");let M=i(async(u,y,g,b)=>{let p=y.find(d=>d.type==="text")?.text??"";try{let d=t.execute({prompt:p,model:g,sessionId:u==="default"?void 0:u,signal:b});for await(let T of d){let w=x(T);if(w&&await f({jsonrpc:"2.0",method:"session/update",params:{sessionId:u,update:w}}),T.type==="complete")return{stopReason:b.aborted?"cancelled":"end_turn",usage:T.usage}}return{stopReason:b.aborted?"cancelled":"end_turn"}}catch(d){return b.aborted||d instanceof Error&&d.name==="AbortError"?{stopReason:"cancelled"}:(console.error("[PseudoAcpServer] Error executing prompt:",d),await f({jsonrpc:"2.0",method:"session/update",params:{sessionId:u,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
26
|
-
[Fatal Error: ${d}]
|
|
27
|
-
`}}}}),{stopReason:"end_turn"})}},"executePrompt"),x=i(u=>{switch(u.type){case"message":if(u.role==="assistant"&&u.content)return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.content}};break;case"tool_use":return{sessionUpdate:"tool_call",title:u.toolName,arguments:u.parameters,status:"running",toolCallId:u.toolId||rt()};case"tool_result":return{sessionUpdate:"tool_call_update",toolCallId:u.toolId,status:u.status};case"error":return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
28
|
-
[Error: ${u.message}]
|
|
29
|
-
`}};case"complete":break}return null},"mapToAcpNotification");return{inputStream:n.readable,outputStream:e.writable,abort:i(()=>{m.abort(),e.readable.cancel().catch(()=>{}),n.writable.abort().catch(()=>{})},"abort"),executor:t}}i(we,"createPseudoAcpServer");import Ut from"node:fs";import Xt from"node:os";import Wt from"node:path";var $n="gpt-5.4",jn="auto-gemini-3",Gn=["gpt-5.4","gpt-5.3-codex","gpt-5.3-codex-spark"],zn=["auto-gemini-3","gemini-3.1-pro-preview","gemini-3-flash-preview","gemini-2.5-pro","gemini-2.5-flash"];function $t(t){let e=new Set,n=[];for(let o of t){let r=o.trim();if(!r)continue;let s=r.toLowerCase();e.has(s)||(e.add(s),n.push(r))}return n}i($t,"dedupePreserveOrder");function Hn(){let t=Wt.join(Xt.homedir(),".codex","config.toml");try{return Ut.readFileSync(t,"utf8").match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1]?.trim()||null}catch{return null}}i(Hn,"readCodexConfiguredModel");function Vn(){let t=Wt.join(Xt.homedir(),".gemini","settings.json");try{let e=JSON.parse(Ut.readFileSync(t,"utf8")),n=typeof e.model=="string"?e.model.trim():"";return n||(typeof e.general?.model=="string"?e.general.model.trim():"")||null}catch{return null}}i(Vn,"readGeminiConfiguredModel");function re(){return Hn()||$n}i(re,"getCodexCliDefaultModel");function se(){return Vn()||jn}i(se,"getGeminiCliDefaultModel");function he(){return $t([re(),...Gn])}i(he,"getCodexCliKnownModels");function ye(){return $t([se(),...zn])}i(ye,"getGeminiCliKnownModels");var st=se(),Yn=ye(),Jn={transport:"cli-bridge",conversationSemantics:"last-user-message",mcpSupport:"none",contextFidelity:"lossy",toolCallingFidelity:"limited",sessionSupport:"stateless",longRunningSupport:"limited",multimodalSupport:"image-input",evidenceSupport:"limited"},Re=class extends oe{static{i(this,"KodaXGeminiCliProvider")}name="gemini-cli";supportsThinking=!1;config={apiKeyEnv:"GEMINI_CLI_API_KEY",model:st,models:Yn.filter(e=>e!==st).map(e=>({id:e,displayName:e})),supportsThinking:!1,reasoningCapability:"prompt-only",contextWindow:1048576};acpClientOptions;constructor(){super();let e=new Pe({model:st});this.acpClientOptions=we(e)}getCapabilityProfile(){return F(Jn)}serializeImageBlockToPromptToken(e){return/\s/.test(e.path)?(console.warn(`[gemini-cli] Image path contains whitespace and cannot be safely passed via @<path> syntax \u2014 dropping image block. Path: ${JSON.stringify(e.path)}`),null):`@${e.path}`}};var Ae=class extends ie{static{i(this,"CodexCLIExecutor")}model;constructor(e){super({command:"codex",baseArgs:["exec","--json","--full-auto"],timeout:3e5,...e}),this.model=e?.model??"gpt-5.4"}async checkInstalled(){return Ee("codex")}buildArgs(e){this.model=e.model??this.model;let n=e.model?["-m",e.model]:[];return e.sessionId?["exec","resume",e.sessionId,...n,e.prompt,...this.config.baseArgs.filter(o=>o!=="exec")]:[...this.config.baseArgs,...n,e.prompt]}parseLine(e){if(!e.startsWith("{"))return null;try{let n=JSON.parse(e);return this.convertEvent(n)}catch{return null}}convertEvent(e){let n=Date.now();switch(e.type){case"thread.started":return{type:"session_start",timestamp:n,sessionId:e.thread_id??"",model:this.model,raw:e};case"item.completed":return e.item?.type==="agent_message"?{type:"message",timestamp:n,role:"assistant",content:e.item.text??"",raw:e}:e.item?.type==="command_execution"?{type:"tool_use",timestamp:n,toolId:e.item.id,toolName:"Bash",parameters:{command:e.item.command},raw:e}:null;case"turn.completed":return{type:"complete",timestamp:n,status:"success",usage:e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens}:void 0,raw:e};case"error":case"turn.failed":return{type:"error",timestamp:n,errorType:e.type,message:e.message??"Unknown error",raw:e};default:return null}}};var at=re(),Qn=he(),Se=class extends oe{static{i(this,"KodaXCodexCliProvider")}name="codex-cli";supportsThinking=!1;config={apiKeyEnv:"CODEX_CLI_API_KEY",model:at,models:Qn.filter(e=>e!==at).map(e=>({id:e,displayName:e})),supportsThinking:!1,reasoningCapability:"prompt-only",contextWindow:128e3};acpClientOptions;constructor(){super();let e=new Ae({model:at});this.acpClientOptions=we(e)}};import qn from"@anthropic-ai/sdk";var jt=se(),Zn=ye(),Gt=re(),eo=he(),z={anthropic:{apiKeyEnv:"ANTHROPIC_API_KEY",model:"claude-sonnet-4-6",models:["claude-opus-4-6","claude-haiku-4-5"],reasoningCapability:"native-budget",capabilityProfile:L},openai:{apiKeyEnv:"OPENAI_API_KEY",model:"gpt-5.3-codex",models:["gpt-5.4","gpt-5.3-codex-spark"],reasoningCapability:"native-effort",capabilityProfile:L},deepseek:{apiKeyEnv:"DEEPSEEK_API_KEY",model:"deepseek-v4-flash",models:["deepseek-v4-pro"],reasoningCapability:"native-effort",capabilityProfile:L},kimi:{apiKeyEnv:"KIMI_API_KEY",model:"kimi-k2.6",models:["k2.5"],reasoningCapability:"native-effort",capabilityProfile:L},"kimi-code":{apiKeyEnv:"KIMI_API_KEY",model:"kimi-for-coding",reasoningCapability:"native-budget",capabilityProfile:L},qwen:{apiKeyEnv:"QWEN_API_KEY",model:"qwen3.5-plus",reasoningCapability:"native-budget",capabilityProfile:L},zhipu:{apiKeyEnv:"ZHIPU_API_KEY",model:"glm-5",models:["glm-5.1","glm-5-turbo"],reasoningCapability:"native-budget",capabilityProfile:L},"zhipu-coding":{apiKeyEnv:"ZHIPU_API_KEY",model:"glm-5",models:["glm-5.1","glm-5-turbo"],reasoningCapability:"native-budget",capabilityProfile:L},"minimax-coding":{apiKeyEnv:"MINIMAX_API_KEY",model:"MiniMax-M2.7",models:["MiniMax-M2.7-highspeed","MiniMax-M2.5","MiniMax-M2.5-highspeed","MiniMax-M2.1","MiniMax-M2.1-highspeed","MiniMax-M2"],reasoningCapability:"native-budget",capabilityProfile:L},"mimo-coding":{apiKeyEnv:"MIMO_API_KEY",model:"mimo-v2.5-pro",models:["mimo-v2.5"],reasoningCapability:"native-budget",capabilityProfile:L},"ark-coding":{apiKeyEnv:"ARK_API_KEY",model:"glm-5.1",models:["glm-4.7","kimi-k2.6","kimi-k2.5","minimax-latest","deepseek-v3.2","doubao-seed-2.0-code","doubao-seed-2.0-pro","doubao-seed-2.0-lite"],reasoningCapability:"native-budget",capabilityProfile:L},"gemini-cli":{apiKeyEnv:"GEMINI_API_KEY",model:jt,models:Zn.filter(t=>t!==jt),reasoningCapability:"prompt-only",capabilityProfile:Lt},"codex-cli":{apiKeyEnv:"OPENAI_API_KEY",model:Gt,models:eo.filter(t=>t!==Gt),reasoningCapability:"prompt-only",capabilityProfile:fe}};function X(t,e){let n=z[t];return{apiKeyEnv:n.apiKeyEnv,model:n.model,reasoningCapability:n.reasoningCapability,...e}}i(X,"buildProviderConfig");var ct=class extends K{static{i(this,"AnthropicProvider")}name="anthropic";config=X("anthropic",{models:[{id:"claude-opus-4-6",displayName:"Opus 4.6",thinkingBudgetCap:28e3},{id:"claude-haiku-4-5",displayName:"Haiku 4.5",thinkingBudgetCap:1e4}],supportsThinking:!0,contextWindow:2e5,maxOutputTokens:64e3,thinkingBudgetCap:28e3,strictThinkingSignature:!0});constructor(){super(),this.client=new qn({apiKey:this.getApiKey()})}},lt=class extends K{static{i(this,"ZhipuCodingProvider")}name="zhipu-coding";config=X("zhipu-coding",{baseUrl:"https://open.bigmodel.cn/api/anthropic",models:[{id:"glm-5.1",displayName:"GLM-5.1"},{id:"glm-5-turbo",displayName:"GLM-5 Turbo",contextWindow:128e3}],supportsThinking:!0,contextWindow:2e5,maxOutputTokens:16e3,thinkingBudgetCap:16e3,streamMaxDurationMs:3e5});constructor(){super(),this.initClient()}},ut=class extends K{static{i(this,"KimiCodeProvider")}name="kimi-code";config=X("kimi-code",{baseUrl:"https://api.kimi.com/coding/",supportsThinking:!0,contextWindow:256e3,maxOutputTokens:32e3});constructor(){super(),this.initClient()}},pt=class extends K{static{i(this,"MiniMaxCodingProvider")}name="minimax-coding";config=X("minimax-coding",{baseUrl:"https://api.minimaxi.com/anthropic",models:[{id:"MiniMax-M2.7",displayName:"MiniMax M2.7"},{id:"MiniMax-M2.7-highspeed",displayName:"MiniMax M2.7 Highspeed (higher-tier plan)"},{id:"MiniMax-M2.5",displayName:"MiniMax M2.5"},{id:"MiniMax-M2.5-highspeed",displayName:"MiniMax M2.5 Highspeed (higher-tier plan)"},{id:"MiniMax-M2.1",displayName:"MiniMax M2.1"},{id:"MiniMax-M2.1-highspeed",displayName:"MiniMax M2.1 Highspeed (higher-tier plan)"},{id:"MiniMax-M2",displayName:"MiniMax M2"}],supportsThinking:!0,contextWindow:204800,maxOutputTokens:32e3});constructor(){super(),this.initClient()}},dt=class extends K{static{i(this,"MimoCodingProvider")}name="mimo-coding";config=X("mimo-coding",{baseUrl:"https://token-plan-cn.xiaomimimo.com/anthropic",models:[{id:"mimo-v2.5",displayName:"MiMo V2.5"}],supportsThinking:!0,contextWindow:1e6,maxOutputTokens:32e3,thinkingBudgetCap:16e3});constructor(){super(),this.initClient()}},mt=class extends K{static{i(this,"ArkCodingProvider")}name="ark-coding";config=X("ark-coding",{baseUrl:"https://ark.cn-beijing.volces.com/api/coding",models:[{id:"glm-4.7",displayName:"GLM-4.7"},{id:"kimi-k2.6",displayName:"Kimi K2.6",contextWindow:256e3},{id:"kimi-k2.5",displayName:"Kimi K2.5",contextWindow:256e3},{id:"minimax-latest",displayName:"MiniMax Latest",contextWindow:204800},{id:"deepseek-v3.2",displayName:"DeepSeek V3.2",contextWindow:128e3},{id:"doubao-seed-2.0-code",displayName:"Doubao Seed 2.0 Code",contextWindow:256e3},{id:"doubao-seed-2.0-pro",displayName:"Doubao Seed 2.0 Pro",contextWindow:256e3},{id:"doubao-seed-2.0-lite",displayName:"Doubao Seed 2.0 Lite",contextWindow:256e3}],supportsThinking:!0,contextWindow:2e5,maxOutputTokens:32e3});constructor(){super(),this.initClient()}},ft=class extends N{static{i(this,"OpenAIProvider")}name="openai";config=X("openai",{models:[{id:"gpt-5.4",displayName:"GPT-5.4"},{id:"gpt-5.3-codex-spark",displayName:"GPT-5.3 Codex Spark"}],supportsThinking:!0,contextWindow:4e5,maxOutputTokens:32768});constructor(){super(),this.initClient()}},gt=class extends N{static{i(this,"DeepSeekProvider")}name="deepseek";config=X("deepseek",{baseUrl:"https://api.deepseek.com",models:[{id:"deepseek-v4-pro",displayName:"DeepSeek V4 Pro"}],supportsThinking:!0,contextWindow:1e6,maxOutputTokens:64e3,replayReasoningContent:!0});constructor(){super(),this.initClient()}},ht=class extends N{static{i(this,"KimiProvider")}name="kimi";config=X("kimi",{baseUrl:"https://api.moonshot.cn/v1",models:[{id:"k2.5",displayName:"K2.5"}],supportsThinking:!0,contextWindow:256e3,maxOutputTokens:32768,replayReasoningContent:!0});constructor(){super(),this.initClient()}},yt=class extends N{static{i(this,"QwenProvider")}name="qwen";config=X("qwen",{baseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",supportsThinking:!0,contextWindow:256e3,maxOutputTokens:32768,replayReasoningContent:!0});constructor(){super(),this.initClient()}},_t=class extends N{static{i(this,"ZhipuProvider")}name="zhipu";config=X("zhipu",{baseUrl:"https://open.bigmodel.cn/api/paas/v4",models:[{id:"glm-5.1",displayName:"GLM-5.1"},{id:"glm-5-turbo",displayName:"GLM-5 Turbo",contextWindow:128e3}],supportsThinking:!0,contextWindow:2e5,maxOutputTokens:32768,replayReasoningContent:!0});constructor(){super(),this.initClient()}},U={anthropic:i(()=>new ct,"anthropic"),openai:i(()=>new ft,"openai"),deepseek:i(()=>new gt,"deepseek"),kimi:i(()=>new ht,"kimi"),"kimi-code":i(()=>new ut,"kimi-code"),qwen:i(()=>new yt,"qwen"),zhipu:i(()=>new _t,"zhipu"),"zhipu-coding":i(()=>new lt,"zhipu-coding"),"minimax-coding":i(()=>new pt,"minimax-coding"),"mimo-coding":i(()=>new dt,"mimo-coding"),"ark-coding":i(()=>new mt,"ark-coding"),"gemini-cli":i(()=>new Re,"gemini-cli"),"codex-cli":i(()=>new Se,"codex-cli")},kt=process.env.KODAX_PROVIDER??"zhipu-coding",zt=new Map;function to(t){if(B(t))return z[t].apiKeyEnv}i(to,"resolveApiKeyEnvForProvider");function Ht(t){let e=t??kt,n=U[e];if(!n)throw new R(`Unknown provider: ${e}. Available: ${Object.keys(U).join(", ")}`,e);let o=to(e),r=o?process.env[o]:void 0,s=zt.get(e);if(s&&s.apiKey===r)return s.instance;let a=n();return zt.set(e,{apiKey:r,instance:a}),a}i(Ht,"getProvider");function Vt(t){return B(t)?!!process.env[z[t].apiKeyEnv]:!1}i(Vt,"isProviderConfigured");function Yt(t){return B(t)?z[t].model:null}i(Yt,"getProviderModel");function Jt(t,e){if(!B(t))return"unknown";let n=z[t],o=e??n.model;return n.modelReasoningCapabilities?.[o]??n.reasoningCapability}i(Jt,"getProviderConfiguredReasoningCapability");function Qt(t){return B(t)?F(z[t].capabilityProfile):null}i(Qt,"getProviderConfiguredCapabilityProfile");function qt(){let t=[];for(let e of Object.keys(U)){let n=z[e];t.push({name:e,model:n.model,models:n.models?[n.model,...n.models]:[n.model],configured:!!process.env[n.apiKeyEnv],reasoningCapability:n.reasoningCapability,capabilityProfile:F(n.capabilityProfile)})}return t}i(qt,"getProviderList");function Zt(t){let e=z[t];return e?e.models?[e.model,...e.models]:[e.model]:[]}i(Zt,"getProviderModels");function B(t){return t in U}i(B,"isProviderName");var no=new Set(["compat","sdk"]);function vt(t){if(!t.name||!t.baseUrl||!t.apiKeyEnv||!t.model)throw new Error(`Custom provider requires name, baseUrl, apiKeyEnv, and model. Got: ${JSON.stringify({name:t.name,baseUrl:t.baseUrl,apiKeyEnv:t.apiKeyEnv,model:t.model})}`);if(t.protocol!=="anthropic"&&t.protocol!=="openai")throw new Error(`Unknown protocol "${t.protocol}" for custom provider "${t.name}". Must be "anthropic" or "openai".`);if(t.userAgentMode!==void 0&&!no.has(t.userAgentMode))throw new Error(`Unknown userAgentMode "${t.userAgentMode}" for custom provider "${t.name}". Must be "compat" or "sdk".`)}i(vt,"validateCustomProviderConfig");function oo(t){let e=t.models?.length?t.models.map(n=>typeof n=="string"?{id:n}:n):void 0;return{apiKeyEnv:t.apiKeyEnv,model:t.model,baseUrl:t.baseUrl,models:e,userAgentMode:t.userAgentMode,supportsThinking:t.supportsThinking??!1,reasoningCapability:t.reasoningCapability??"none",capabilityProfile:t.capabilityProfile,contextWindow:t.contextWindow,maxOutputTokens:t.maxOutputTokens,thinkingBudgetCap:t.thinkingBudgetCap}}i(oo,"buildProviderConfig");function Oe(t){vt(t);let e=oo(t);return t.protocol==="anthropic"?new xt(t.name,e):new bt(t.name,e)}i(Oe,"createCustomProvider");var xt=class extends K{static{i(this,"DynamicAnthropicProvider")}name;config;constructor(e,n){super(),this.name=e,this.config=n,this.initClient()}},bt=class extends N{static{i(this,"DynamicOpenAIProvider")}name;config;constructor(e,n){super(),this.name=e,this.config=n,this.initClient()}};var ae=new Map,Mt=new Map;function en(t){let e=new Set,n=new Map,o=new Map;for(let r of t){if(vt(r),e.has(r.name))throw new Error(`Duplicate custom provider name: "${r.name}". Each custom provider must have a unique name.`);r.name in U&&console.warn(`[kodax] Custom provider "${r.name}" shadows a built-in provider. The built-in provider will be used. Choose a different name to use your custom provider.`),e.add(r.name),n.set(r.name,r),o.set(r.name,()=>Oe(r))}ae.clear(),Mt.clear();for(let[r,s]of n)ae.set(r,s);for(let[r,s]of o)Mt.set(r,s)}i(en,"registerCustomProviders");function Ie(t){let e=Mt.get(t);return e?e():void 0}i(Ie,"getCustomProvider");function ce(t){return ae.has(t)}i(ce,"isCustomProviderName");function De(){return[...ae.keys()]}i(De,"getCustomProviderNames");function tn(){let t=[];for(let[e,n]of ae){let o=!!process.env[n.apiKeyEnv],r=(n.models??[]).map(a=>typeof a=="string"?a:a.id),s=n.model&&r.length?[...new Set([n.model,...r])]:[n.model];t.push({name:e,model:n.model,models:s,configured:o,reasoningCapability:n.reasoningCapability??"none",capabilityProfile:F(n.capabilityProfile??me),custom:!0})}return t}i(tn,"getCustomProviderList");function nn(t){let e=ae.get(t);if(!e)return;let n=(e.models??[]).map(o=>typeof o=="string"?o:o.id);return e.model&&n.length?[...new Set([e.model,...n])]:[e.model]}i(nn,"getCustomProviderModels");var V=new Map,io=0;function Ct(t){let e=V.get(t);if(!(!e||e.length===0))return e[e.length-1]}i(Ct,"getActiveRuntimeProviderRegistration");function ro(t){for(let[e,n]of V){let o=n.filter(r=>r.id!==t);if(o.length!==n.length){o.length===0?V.delete(e):V.set(e,o);return}}}i(ro,"removeRuntimeProviderRegistration");function on(t,e){let n=t.trim();if(!n)throw new Error("Model provider name cannot be empty.");if(B(n))throw new Error(`Runtime model provider "${n}" conflicts with a built-in provider.`);if(ce(n))throw new Error(`Runtime model provider "${n}" conflicts with an existing config-defined custom provider.`);let o={id:`runtime-provider:${++io}`,name:n,factory:e},r=V.get(n)??[];return V.set(n,[...r,o]),()=>{ro(o.id)}}i(on,"registerModelProvider");function Ke(t){let e=Ct(t);return e?e.factory():void 0}i(Ke,"getRuntimeModelProvider");function Le(t){return Ct(t)!==void 0}i(Le,"isRuntimeModelProviderName");function Ne(){return Array.from(V.keys()).filter(t=>Ct(t)!==void 0)}i(Ne,"getRuntimeModelProviderNames");function rn(){V.clear()}i(rn,"clearRuntimeModelProviders");function sn(t){if(B(t))return U[t]();let e=Ke(t);if(e)return e;let n=Ie(t);if(n)return n;let o=Tt();throw new Error(`Unknown provider: ${t}. Available: ${o.join(", ")}`)}i(sn,"resolveProvider");function an(t){return B(t)||Le(t)||ce(t)}i(an,"isKnownProvider");function Tt(){let t=Object.keys(U),e=Ne(),n=De();return[...new Set([...t,...e,...n])]}i(Tt,"getAvailableProviderNames");var cn={anthropic:{"claude-opus-4-6":{inputPer1M:15,outputPer1M:75,cachePer1M:1.875},"claude-sonnet-4-6":{inputPer1M:3,outputPer1M:15,cachePer1M:.375},"claude-haiku-4-5":{inputPer1M:.8,outputPer1M:4,cachePer1M:.08}},openai:{"gpt-5.4":{inputPer1M:30,outputPer1M:120},"gpt-5.3-codex-spark":{inputPer1M:10,outputPer1M:40}},deepseek:{"deepseek-v4-flash":{inputPer1M:.14,outputPer1M:.28,cachePer1M:.028},"deepseek-v4-pro":{inputPer1M:1.68,outputPer1M:3.36,cachePer1M:.14}},kimi:{"k2.5":{inputPer1M:.005,outputPer1M:.015},"kimi-k2.6":{inputPer1M:.005,outputPer1M:.015}},"kimi-code":{"kimi-for-coding":{inputPer1M:.005,outputPer1M:.015}},qwen:{"qwen3.5-plus":{inputPer1M:.003,outputPer1M:.006}},zhipu:{"glm-5":{inputPer1M:.05,outputPer1M:.1},"glm-5.1":{inputPer1M:.05,outputPer1M:.1},"glm-5-turbo":{inputPer1M:.01,outputPer1M:.03}},"zhipu-coding":{"glm-5":{inputPer1M:.05,outputPer1M:.1},"glm-5.1":{inputPer1M:.05,outputPer1M:.1},"glm-5-turbo":{inputPer1M:.01,outputPer1M:.03}},"minimax-coding":{"MiniMax-M2.7":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2.7-highspeed":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2.5":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2.5-highspeed":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2.1":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2.1-highspeed":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2":{inputPer1M:.01,outputPer1M:.03}},"mimo-coding":{"mimo-v2.5-pro":{inputPer1M:.01,outputPer1M:.03},"mimo-v2.5":{inputPer1M:.01,outputPer1M:.03}},"ark-coding":{"glm-5.1":{inputPer1M:.005,outputPer1M:.015},"glm-4.7":{inputPer1M:.005,outputPer1M:.015},"kimi-k2.6":{inputPer1M:.005,outputPer1M:.015},"kimi-k2.5":{inputPer1M:.005,outputPer1M:.015},"minimax-latest":{inputPer1M:.005,outputPer1M:.015},"deepseek-v3.2":{inputPer1M:.005,outputPer1M:.015},"doubao-seed-2.0-code":{inputPer1M:.005,outputPer1M:.015},"doubao-seed-2.0-pro":{inputPer1M:.005,outputPer1M:.015},"doubao-seed-2.0-lite":{inputPer1M:.005,outputPer1M:.015}},"gemini-cli":{},"codex-cli":{}};function Et(t,e,n){let o=n?.[t]?.[e];return o||cn[t]?.[e]}i(Et,"getCostRate");function Pt(t,e,n,o=0){let r=e/1e6*t.inputPer1M,s=n/1e6*t.outputPer1M,a=t.cachePer1M?o/1e6*t.cachePer1M:0;return r+s+a}i(Pt,"calculateCost");function so(){return{records:[],retries:[]}}i(so,"createCostTracker");function ao(t,e){let n={timestamp:Date.now(),provider:e.provider,waitMs:e.waitMs,reason:e.reason,source:e.source};return{records:t.records,retries:[...t.retries,n]}}i(ao,"recordRetry");function wt(t,e,n){let o=Et(e.provider,e.model,n),r=(e.cacheReadTokens??0)+(e.cacheWriteTokens??0),s=o?Pt(o,e.inputTokens,e.outputTokens,r):0,a={timestamp:Date.now(),provider:e.provider,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens??0,cacheWriteTokens:e.cacheWriteTokens??0,cost:s,role:e.role};return{records:[...t.records,a],retries:t.retries}}i(wt,"recordUsage");function co(t){let e=0,n=0,o=0,r=0,s=0,a=0,l={},c={};for(let f of t.records){e+=f.cost,n+=f.inputTokens,o+=f.outputTokens,r+=f.cacheReadTokens+f.cacheWriteTokens,s+=f.cacheReadTokens,a+=f.cacheWriteTokens;let _=l[f.provider];l[f.provider]={cost:(_?.cost??0)+f.cost,calls:(_?.calls??0)+1,inputTokens:(_?.inputTokens??0)+f.inputTokens,outputTokens:(_?.outputTokens??0)+f.outputTokens};let M=f.role??"default",x=c[M];c[M]={cost:(x?.cost??0)+f.cost,calls:(x?.calls??0)+1,inputTokens:(x?.inputTokens??0)+f.inputTokens,outputTokens:(x?.outputTokens??0)+f.outputTokens}}let m=0;for(let f of t.retries)m+=f.waitMs;let v=r>0?s/r:0;return{totalCost:e,totalInputTokens:n,totalOutputTokens:o,totalCacheTokens:r,totalCacheReadTokens:s,totalCacheWriteTokens:a,cacheHitRate:v,callCount:t.records.length,retryCount:t.retries.length,retryWaitMs:m,byProvider:l,byRole:c}}i(co,"getSummary");function Be(t){return t<.01?`$${t.toFixed(4)}`:t<1?`$${t.toFixed(3)}`:`$${t.toFixed(2)}`}i(Be,"formatCost");function lo(t){let e=[];if(e.push(`Session Cost: ${Be(t.totalCost)} (${t.callCount} calls)`),e.push(`Tokens: ${t.totalInputTokens.toLocaleString()} in / ${t.totalOutputTokens.toLocaleString()} out`),t.totalCacheTokens>0){let r=(t.cacheHitRate*100).toFixed(0);e.push(`Cache: ${t.totalCacheTokens.toLocaleString()} tokens (${t.totalCacheReadTokens.toLocaleString()} read / ${t.totalCacheWriteTokens.toLocaleString()} write, ${r}% hit rate)`)}if(t.retryCount>0){let r=(t.retryWaitMs/1e3).toFixed(1);e.push(`Retries: ${t.retryCount} (${r}s total wait)`)}e.push("");let n=Object.entries(t.byProvider).sort((r,s)=>s[1].cost-r[1].cost);if(n.length>0){e.push("By Provider:");for(let[r,s]of n)e.push(` ${r}: ${Be(s.cost)} (${s.calls} calls, ${s.inputTokens.toLocaleString()} in / ${s.outputTokens.toLocaleString()} out)`);e.push("")}let o=Object.entries(t.byRole).sort((r,s)=>s[1].cost-r[1].cost);if(o.length>1){e.push("By Role:");for(let[r,s]of o)e.push(` ${r}: ${Be(s.cost)} (${s.calls} calls)`)}return e.join(`
|
|
30
|
-
`)}i(lo,"formatCostReport");var ln={inputTokens:0,outputTokens:0,totalTokens:0},uo=3e4;async function po(t){let e=new AbortController,n=t.timeoutMs??uo,o,r=i(l=>{o||(o=l),e.abort()},"recordAbort"),s=setTimeout(()=>r("timeout"),n),a=i(()=>r("parent"),"onParentAbort");t.abortSignal&&(t.abortSignal.aborted?r("parent"):t.abortSignal.addEventListener("abort",a,{once:!0}));try{let l=await t.provider.stream([...t.messages],[],t.system,t.reasoning??{mode:"off"},{modelOverride:t.model},e.signal),c=l.usage??ln,m=l.textBlocks??[],v=l.toolBlocks??[],f=m.map(M=>M.text).join("");if(v.length>0)return{text:f,usage:c,costTracker:t.costTracker,stopReason:"error",error:new Error(`sideQuery: provider returned ${v.length} tool_use block(s); sideQuery expects text-only output`)};let _=t.costTracker;return _&&(_=wt(_,{provider:t.provider.name,model:t.model,inputTokens:c.inputTokens,outputTokens:c.outputTokens,cacheReadTokens:c.cachedReadTokens,cacheWriteTokens:c.cachedWriteTokens,role:t.querySource})),{text:f,usage:c,costTracker:_,stopReason:mo(l.stopReason)}}catch(l){let c=l instanceof Error?l:new Error(String(l)),m="error";return e.signal.aborted&&(m=o==="timeout"?"timeout":"aborted"),{text:"",usage:ln,costTracker:t.costTracker,stopReason:m,error:c}}finally{clearTimeout(s),t.abortSignal&&t.abortSignal.removeEventListener("abort",a)}}i(po,"sideQuery");function mo(t){return t==="max_tokens"?"max_tokens":"end_turn"}i(mo,"mapStopReason");export{H as a,R as b,de as c,Fe as d,Ue as e,Xe as f,J as g,We as h,un as i,pn as j,Rt as k,At as l,$e as m,Q as n,ke as o,St as p,q,Z as r,je as s,Ve as t,Ye as u,ee as v,be as w,Qe as x,yn as y,ve as z,Me as A,Ce as B,G as C,te as D,qe as E,ne as F,Ze as G,ge as H,K as I,N as J,re as K,se as L,he as M,ye as N,z as O,U as P,kt as Q,Ht as R,Vt as S,Yt as T,Jt as U,Qt as V,qt as W,Zt as X,B as Y,Oe as Z,en as _,Ie as $,ce as aa,De as ba,tn as ca,nn as da,on as ea,Ke as fa,Le as ga,Ne as ha,rn as ia,sn as ja,an as ka,Tt as la,cn as ma,Et as na,Pt as oa,so as pa,ao as qa,wt as ra,co as sa,Be as ta,lo as ua,po as va};
|