zidane 5.0.6 → 5.1.1
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/README.md +37 -1
- package/dist/{agent-JhicgLOV.d.ts → agent-B0vrSTQ9.d.ts} +162 -4
- package/dist/agent-B0vrSTQ9.d.ts.map +1 -0
- package/dist/chat.d.ts +526 -81
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +2 -2
- package/dist/contexts/docker.d.ts +7 -0
- package/dist/contexts/docker.d.ts.map +1 -0
- package/dist/{contexts-3Arvn7yR.js → contexts/docker.js} +2 -128
- package/dist/contexts/docker.js.map +1 -0
- package/dist/contexts-BwiHIr2w.js +129 -0
- package/dist/contexts-BwiHIr2w.js.map +1 -0
- package/dist/contexts.d.ts +3 -2
- package/dist/contexts.js +2 -2
- package/dist/index-CFxhms_B.d.ts +1303 -0
- package/dist/index-CFxhms_B.d.ts.map +1 -0
- package/dist/index-DYcymRtr.d.ts +26 -0
- package/dist/index-DYcymRtr.d.ts.map +1 -0
- package/dist/{index-t_W9i7Ql.d.ts → index-X6Q9PN_A.d.ts} +3 -3
- package/dist/{index-t_W9i7Ql.d.ts.map → index-X6Q9PN_A.d.ts.map} +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +10 -9
- package/dist/index.js.map +1 -1
- package/dist/login-B7b7NNJQ.js +1277 -0
- package/dist/login-B7b7NNJQ.js.map +1 -0
- package/dist/{mcp-Dw-fRPVk.js → mcp-BgwK6ySj.js} +184 -9
- package/dist/mcp-BgwK6ySj.js.map +1 -0
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +1 -1
- package/dist/{messages-xaYMMFlb.js → messages-BAFLvH_z.js} +1 -1
- package/dist/{messages-xaYMMFlb.js.map → messages-BAFLvH_z.js.map} +1 -1
- package/dist/{presets-BRFH2qsQ.js → presets-CI8_fyvX.js} +2 -2
- package/dist/{presets-BRFH2qsQ.js.map → presets-CI8_fyvX.js.map} +1 -1
- package/dist/presets.d.ts +2 -2
- package/dist/presets.js +1 -1
- package/dist/{providers-BCbdv99U.js → providers-C6-vhaVu.js} +2 -2
- package/dist/{providers-BCbdv99U.js.map → providers-C6-vhaVu.js.map} +1 -1
- package/dist/providers.d.ts +1 -1
- package/dist/providers.js +2 -2
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/{session-791hhrFa.js → session-pS4Vt4dl.js} +1 -1
- package/dist/{session-791hhrFa.js.map → session-pS4Vt4dl.js.map} +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/session.js +2 -2
- package/dist/skills.d.ts +2 -2
- package/dist/{stats-DZIsGqzu.js → stats-DvCtBRwK.js} +1 -1
- package/dist/{stats-DZIsGqzu.js.map → stats-DvCtBRwK.js.map} +1 -1
- package/dist/{theme-C3JHZ5y9.d.ts → tool-formatters-D7cN3T_W.d.ts} +932 -31
- package/dist/tool-formatters-D7cN3T_W.d.ts.map +1 -0
- package/dist/{tools-CLazLRb4.js → tools-d1yeA6xK.js} +399 -13
- package/dist/tools-d1yeA6xK.js.map +1 -0
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +1 -1
- package/dist/tui.d.ts +426 -68
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +3966 -878
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-BfEh-GER.js → turn-operations-lsUMITng.js} +2550 -206
- package/dist/turn-operations-lsUMITng.js.map +1 -0
- package/dist/types-Bx_F8jet.js.map +1 -1
- package/dist/{index-CXVvqTQj.d.ts → types-OtrV6LJT.d.ts} +2 -27
- package/dist/types-OtrV6LJT.d.ts.map +1 -0
- package/dist/types.d.ts +4 -3
- package/dist/types.js +1 -1
- package/package.json +5 -1
- package/dist/agent-JhicgLOV.d.ts.map +0 -1
- package/dist/contexts-3Arvn7yR.js.map +0 -1
- package/dist/index-2yLUyTbc.d.ts +0 -430
- package/dist/index-2yLUyTbc.d.ts.map +0 -1
- package/dist/index-CXVvqTQj.d.ts.map +0 -1
- package/dist/mcp-Dw-fRPVk.js.map +0 -1
- package/dist/theme-C3JHZ5y9.d.ts.map +0 -1
- package/dist/tools-CLazLRb4.js.map +0 -1
- package/dist/turn-operations-BfEh-GER.js.map +0 -1
|
@@ -0,0 +1,1303 @@
|
|
|
1
|
+
import { a as ExecutionHandle, i as ExecutionContext } from "./types-OtrV6LJT.js";
|
|
2
|
+
import { D as Session, Ot as SessionTurn, Pt as ToolResultContent, Rt as TurnUsage, W as Provider, gt as McpServerConfig, ht as ChildRunStats, i as AgentOptions, jt as ThinkingLevel, l as SkillActivationState, mt as AgentStats, r as AgentHooks, s as ActiveSkill, v as ToolContext, x as SkillConfig, y as ToolDef } from "./agent-B0vrSTQ9.js";
|
|
3
|
+
import { Hookable } from "hookable";
|
|
4
|
+
import { OAuthClientProvider, OAuthDiscoveryState } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
5
|
+
import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
6
|
+
|
|
7
|
+
//#region src/compact/messages.d.ts
|
|
8
|
+
/**
|
|
9
|
+
* What to summarize and what to preserve verbatim.
|
|
10
|
+
*
|
|
11
|
+
* - `'full'` — summarize everything, no preserved tail.
|
|
12
|
+
* - `'tail'` — summarize everything before the last `keepTurns` turns.
|
|
13
|
+
* - `{ kind: 'from', turnId }` — summarize from the anchor turn onward.
|
|
14
|
+
* - `{ kind: 'up_to', turnId }` — summarize up to (and including) the anchor.
|
|
15
|
+
*/
|
|
16
|
+
type CompactScope = 'full' | 'tail' | {
|
|
17
|
+
kind: 'from';
|
|
18
|
+
turnId: string;
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'up_to';
|
|
21
|
+
turnId: string;
|
|
22
|
+
};
|
|
23
|
+
interface CompactionSlice {
|
|
24
|
+
/** The portion of the conversation that will be summarized. */
|
|
25
|
+
toSummarize: readonly SessionTurn[];
|
|
26
|
+
/** The portion that stays verbatim in the post-compact history. */
|
|
27
|
+
preserved: readonly SessionTurn[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Partition `turns` into `(toSummarize, preserved)` according to `scope`.
|
|
31
|
+
*
|
|
32
|
+
* Throws {@link CompactInvalidInputError} on degenerate inputs so the
|
|
33
|
+
* caller doesn't pay for a doomed provider call:
|
|
34
|
+
* - empty `turns`
|
|
35
|
+
* - `scope: 'tail'` with `keepTurns >= turns.length` (nothing to summarize)
|
|
36
|
+
* - `scope: { from | up_to }` with an anchor id that isn't in `turns`
|
|
37
|
+
* - the resulting `toSummarize` slice contains no text-bearing content
|
|
38
|
+
* (only system turns or empty content)
|
|
39
|
+
*
|
|
40
|
+
* Pure. Returns references to the original `SessionTurn` objects — the
|
|
41
|
+
* caller can compare by identity (=== Object.is) to confirm.
|
|
42
|
+
*/
|
|
43
|
+
declare function sliceForCompaction(turns: readonly SessionTurn[], scope: CompactScope, keepTurns: number): CompactionSlice;
|
|
44
|
+
/**
|
|
45
|
+
* Replace every image block in `turns` with a `[image]` text marker.
|
|
46
|
+
*
|
|
47
|
+
* Covers two shapes:
|
|
48
|
+
* - Top-level `{ type: 'image', ... }` content blocks on user turns.
|
|
49
|
+
* - Image entries inside `tool_result.output` array form (multimodal
|
|
50
|
+
* tool results — e.g. an MCP browser screenshot).
|
|
51
|
+
*
|
|
52
|
+
* Unconditional by design: even on vision-capable models, the summary
|
|
53
|
+
* call doesn't benefit from raw image bytes (the model can't refer to
|
|
54
|
+
* them after the summary lands), and stripping uniformly avoids
|
|
55
|
+
* `prompt_too_long` on image-heavy sessions.
|
|
56
|
+
*
|
|
57
|
+
* Returns a fresh array; input turns / blocks are never mutated.
|
|
58
|
+
*/
|
|
59
|
+
declare function stripImagesFromTurns(turns: readonly SessionTurn[]): SessionTurn[];
|
|
60
|
+
/**
|
|
61
|
+
* Drop the oldest "round" from `turns` and return a fresh array. Used by
|
|
62
|
+
* the PTL retry path to shrink the prompt one round at a time.
|
|
63
|
+
*
|
|
64
|
+
* A round is a contiguous `[user, assistant?, tool_results?]` group. The
|
|
65
|
+
* function walks forward from index 0, advances through the user turn
|
|
66
|
+
* and any trailing assistant + tool-result turns belonging to the same
|
|
67
|
+
* exchange, and returns the remainder.
|
|
68
|
+
*
|
|
69
|
+
* Adjacency-safe: when the oldest user turn carries `tool_result` blocks
|
|
70
|
+
* answering an assistant turn ahead of it (rare — happens during
|
|
71
|
+
* resume), the function keeps walking until the next clean boundary so
|
|
72
|
+
* the resulting array still respects every provider's `tool_use ↔
|
|
73
|
+
* tool_result` adjacency rule.
|
|
74
|
+
*
|
|
75
|
+
* Returns `turns` unchanged when only one round (or less) remains — the
|
|
76
|
+
* caller is expected to interpret that as "cannot shrink further" and
|
|
77
|
+
* give up the retry loop.
|
|
78
|
+
*/
|
|
79
|
+
declare function truncateHeadForPtlRetry(turns: readonly SessionTurn[]): SessionTurn[];
|
|
80
|
+
/**
|
|
81
|
+
* Maximum length of an anchor turn's textual preview, in characters. Long
|
|
82
|
+
* enough to give the model recognizable context (the first paragraph of
|
|
83
|
+
* a typical user message), short enough that it doesn't blow the
|
|
84
|
+
* cache-stability invariant for the prompt prefix.
|
|
85
|
+
*/
|
|
86
|
+
declare const ANCHOR_PREVIEW_MAX_CHARS = 200;
|
|
87
|
+
/**
|
|
88
|
+
* Extract the first ~200 chars of text-bearing content from a turn — the
|
|
89
|
+
* preview surfaced in `from` / `up_to` direction prompts so the model
|
|
90
|
+
* knows where the slice begins.
|
|
91
|
+
*/
|
|
92
|
+
declare function anchorPreviewFor(turn: SessionTurn): string;
|
|
93
|
+
/**
|
|
94
|
+
* Input shape for {@link summaryToTurn}. Designed to align with the
|
|
95
|
+
* fields of `CompactResult` so a caller can spread the runner's output
|
|
96
|
+
* with a single `replacesTurnIds` rename — no field-by-field unpacking
|
|
97
|
+
* required.
|
|
98
|
+
*
|
|
99
|
+
* Primitive shape (no `CompactResult` import) keeps this module free of
|
|
100
|
+
* dependencies on the runner — `compact.ts` imports from here, not the
|
|
101
|
+
* other way around.
|
|
102
|
+
*/
|
|
103
|
+
interface SummaryToTurnInput {
|
|
104
|
+
/** Summary text — typically `CompactResult.summary`. */
|
|
105
|
+
summary: string;
|
|
106
|
+
/** Turn ids being replaced — typically `CompactResult.summarizedTurnIds`. */
|
|
107
|
+
replacesTurnIds: readonly string[];
|
|
108
|
+
/** Model id that produced the summary. */
|
|
109
|
+
model: string;
|
|
110
|
+
/** Token usage from the summary call. */
|
|
111
|
+
usage: TurnUsage;
|
|
112
|
+
/** Defaults to `Date.now()` when omitted. */
|
|
113
|
+
compactedAt?: number;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Build a synthetic `SessionTurn` carrying a single `compact-summary`
|
|
117
|
+
* block, ready to append to a session.
|
|
118
|
+
*
|
|
119
|
+
* The turn's role is `'user'` so it sits at a conversational boundary
|
|
120
|
+
* the way the model expects. The caller is responsible for
|
|
121
|
+
* `session.appendTurns([turn])`. The id is freshly generated via
|
|
122
|
+
* `crypto.randomUUID()` so collisions are statistically impossible.
|
|
123
|
+
*
|
|
124
|
+
* Typical use after running `compactConversation`:
|
|
125
|
+
*
|
|
126
|
+
* ```ts
|
|
127
|
+
* const result = await compactConversation({ provider, turns })
|
|
128
|
+
* const turn = summaryToTurn({
|
|
129
|
+
* summary: result.summary,
|
|
130
|
+
* replacesTurnIds: result.summarizedTurnIds,
|
|
131
|
+
* model: result.model,
|
|
132
|
+
* usage: result.usage,
|
|
133
|
+
* })
|
|
134
|
+
* await session.appendTurns([turn])
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
declare function summaryToTurn(input: SummaryToTurnInput): SessionTurn;
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/compact/prompt.d.ts
|
|
140
|
+
/**
|
|
141
|
+
* Pure prompt builders for conversation compaction.
|
|
142
|
+
*
|
|
143
|
+
* The builders produce the **system prompt** for a no-tools summary call.
|
|
144
|
+
* They are total functions of `(direction, anchorPreview?)` and produce
|
|
145
|
+
* byte-stable output for the same inputs — that's load-bearing for the
|
|
146
|
+
* provider's prompt cache: repeated compactions in the same host process
|
|
147
|
+
* share the same prefix and read cache instead of writing it.
|
|
148
|
+
*
|
|
149
|
+
* Inspired by Claude Code's `services/compact/prompt.ts` — same 9-section
|
|
150
|
+
* scaffold, same `<analysis> + <summary>` envelope, same no-tools
|
|
151
|
+
* preamble. Adapted to zidane-specific wording (no "Claude" references)
|
|
152
|
+
* and trimmed of the bits that don't apply (no `marble_origami`-style
|
|
153
|
+
* query sources, no compaction-fingerprint header).
|
|
154
|
+
*/
|
|
155
|
+
/** Identifier for the section of the conversation being summarized. */
|
|
156
|
+
type CompactDirection = 'full' | 'tail' | 'from' | 'up_to';
|
|
157
|
+
interface CompactPromptOptions {
|
|
158
|
+
direction: CompactDirection;
|
|
159
|
+
/**
|
|
160
|
+
* Short preview of the anchor turn's text — only used by `'from'` and
|
|
161
|
+
* `'up_to'`. Pass the last ~200 chars of the anchor turn so the model
|
|
162
|
+
* has a recognizable handle on where the slice begins / ends. Empty /
|
|
163
|
+
* undefined for `'full'` and `'tail'`.
|
|
164
|
+
*/
|
|
165
|
+
anchorPreview?: string;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Function shape for callers that want to swap in a domain-specific
|
|
169
|
+
* summary prompt (security review handoff, support-ticket continuation,
|
|
170
|
+
* etc.) without touching the runner. Default: {@link buildCompactPrompt}.
|
|
171
|
+
*/
|
|
172
|
+
type CompactPromptBuilder = (opts: CompactPromptOptions) => string;
|
|
173
|
+
/**
|
|
174
|
+
* No-tools guard. The runner sends `tools: []` to the provider already,
|
|
175
|
+
* but some models still hallucinate tool-call intent on a long
|
|
176
|
+
* conversation. The prose guard is cheap insurance.
|
|
177
|
+
*/
|
|
178
|
+
declare const NO_TOOLS_PREAMBLE = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n- Do NOT use Read, Bash, Grep, Glob, Edit, Write, or ANY other tool.\n- You already have all the context you need in the conversation above.\n- Tool calls will be REJECTED and will waste your only turn \u2014 you will fail the task.\n- Your entire response must be plain text: an <analysis> block followed by a <summary> block.";
|
|
179
|
+
/**
|
|
180
|
+
* Body shared by every direction. Lays out the 9-section scaffold,
|
|
181
|
+
* mirrors Claude Code's `BASE_COMPACT_PROMPT` so a model already trained
|
|
182
|
+
* on the layout produces the same shape.
|
|
183
|
+
*/
|
|
184
|
+
declare const BASE_INSTRUCTIONS = "Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\n\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like file names, full code snippets, function signatures, file edits\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n2. Double-check for technical accuracy and completeness.\n\nYour summary, wrapped in <summary> tags, must include the following sections:\n\n1. Primary Request and Intent\n2. Key Technical Concepts\n3. Files and Code Sections (with paths; include code snippets only when load-bearing)\n4. Errors and fixes\n5. Problem Solving\n6. All user messages (list ALL non-tool user messages, verbatim)\n7. Pending Tasks\n8. Current Work\n9. Optional Next Step (include direct quotes from the most recent conversation when relevant)";
|
|
185
|
+
/** Trailer prompting the model to begin. Same on every direction. */
|
|
186
|
+
declare const TRAILER = "Provide your <analysis> and <summary> now.";
|
|
187
|
+
declare function buildFullCompactPrompt(): string;
|
|
188
|
+
declare function buildTailCompactPrompt(): string;
|
|
189
|
+
declare function buildFromCompactPrompt(anchorPreview: string): string;
|
|
190
|
+
declare function buildUpToCompactPrompt(anchorPreview: string): string;
|
|
191
|
+
/**
|
|
192
|
+
* Default public builder. Dispatches by direction to the four named
|
|
193
|
+
* builders. Throws when `from` / `up_to` are passed without an
|
|
194
|
+
* `anchorPreview` — those scopes only make sense with an anchor and a
|
|
195
|
+
* silent fallback would produce a prompt that doesn't tell the model
|
|
196
|
+
* where the slice begins.
|
|
197
|
+
*/
|
|
198
|
+
declare const buildCompactPrompt: CompactPromptBuilder;
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/compact/errors.d.ts
|
|
201
|
+
/**
|
|
202
|
+
* Typed errors thrown by the compaction helper.
|
|
203
|
+
*
|
|
204
|
+
* Lives in its own file so both the runner and the pure messages module
|
|
205
|
+
* can import without circular dependencies.
|
|
206
|
+
*/
|
|
207
|
+
/**
|
|
208
|
+
* Raised when the caller's inputs make compaction meaningless before any
|
|
209
|
+
* API call is attempted. Common cases:
|
|
210
|
+
* - empty `turns`
|
|
211
|
+
* - `keepTurns >= turns.length` (no older content to summarize)
|
|
212
|
+
* - `'from'` / `'up_to'` anchor id not found in `turns`
|
|
213
|
+
* - the resolved `toSummarize` slice has no text-bearing content
|
|
214
|
+
*
|
|
215
|
+
* Synchronous — thrown from `compactConversation()` before the provider
|
|
216
|
+
* call so the caller can recover without a network round-trip.
|
|
217
|
+
*/
|
|
218
|
+
declare class CompactInvalidInputError extends Error {
|
|
219
|
+
constructor(message: string);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Raised when the provider rejects the compaction request with
|
|
223
|
+
* `prompt_too_long` (or an equivalent) and the head-truncation retry
|
|
224
|
+
* budget has been exhausted. Callers can inspect `ptlRetries` to log
|
|
225
|
+
* how far the retry loop got before giving up.
|
|
226
|
+
*/
|
|
227
|
+
declare class CompactPromptTooLongError extends Error {
|
|
228
|
+
readonly ptlRetries: number;
|
|
229
|
+
constructor(message: string, ptlRetries: number);
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
//#region src/compact/compact.d.ts
|
|
233
|
+
interface CompactOptions {
|
|
234
|
+
/** Provider used for the summary call. Called with empty tools list. */
|
|
235
|
+
provider: Provider;
|
|
236
|
+
/** Conversation to compact, in chronological order. */
|
|
237
|
+
turns: readonly SessionTurn[];
|
|
238
|
+
/**
|
|
239
|
+
* What to summarize. Default: `'tail'` — summarize everything before
|
|
240
|
+
* the last `keepTurns` turns. See {@link CompactScope}.
|
|
241
|
+
*/
|
|
242
|
+
scope?: CompactScope;
|
|
243
|
+
/**
|
|
244
|
+
* Trailing turns left untouched when `scope: 'tail'`. Default: 4.
|
|
245
|
+
* Matches `AgentBehavior.compactKeepTurns` so a host that uses both
|
|
246
|
+
* mechanisms shares one knob.
|
|
247
|
+
*/
|
|
248
|
+
keepTurns?: number;
|
|
249
|
+
/** Model id used for the summary call. Default: `provider.meta.defaultModel`. */
|
|
250
|
+
model?: string;
|
|
251
|
+
/**
|
|
252
|
+
* Maximum tokens the summary itself can occupy. Default: 20_000 — the
|
|
253
|
+
* p99.99 of summary output size in Claude Code's `COMPACT_MAX_OUTPUT`.
|
|
254
|
+
* Reasonable for any model with a 200k+ window.
|
|
255
|
+
*/
|
|
256
|
+
maxOutputTokens?: number;
|
|
257
|
+
/** Optional reasoning level. Default: `'off'` — summarization rarely benefits from thinking. */
|
|
258
|
+
thinking?: ThinkingLevel;
|
|
259
|
+
/** Optional cancellation signal forwarded to `provider.stream()`. */
|
|
260
|
+
signal?: AbortSignal;
|
|
261
|
+
/**
|
|
262
|
+
* Retries with head-truncation when the provider reports
|
|
263
|
+
* `prompt_too_long`. Each retry drops the oldest conversational round
|
|
264
|
+
* before re-issuing the call. Default: 3. Set 0 to fail-fast.
|
|
265
|
+
*/
|
|
266
|
+
maxPtlRetries?: number;
|
|
267
|
+
/**
|
|
268
|
+
* Optional builder override. The default builder dispatches by
|
|
269
|
+
* direction to the named builders in `./prompt.ts`; pass a custom
|
|
270
|
+
* function to swap in a domain-specific summary prompt.
|
|
271
|
+
*/
|
|
272
|
+
prompt?: CompactPromptBuilder;
|
|
273
|
+
/**
|
|
274
|
+
* Lifecycle hook for observability. Fires once per provider call,
|
|
275
|
+
* including retries. The `kind` field tells you whether the call is
|
|
276
|
+
* the initial attempt, a head-truncated retry, or a transient-error
|
|
277
|
+
* retry — useful for surfacing progress in a UI spinner.
|
|
278
|
+
*/
|
|
279
|
+
onAttempt?: (event: {
|
|
280
|
+
attempt: number;
|
|
281
|
+
kind: 'initial' | 'ptl-retry' | 'transient-retry';
|
|
282
|
+
}) => void;
|
|
283
|
+
}
|
|
284
|
+
interface CompactResult {
|
|
285
|
+
/** The summary text, with any `<analysis>` block stripped. */
|
|
286
|
+
summary: string;
|
|
287
|
+
/** Token usage from the (last successful) summary call. */
|
|
288
|
+
usage: TurnUsage;
|
|
289
|
+
/** Model id used to produce the summary. */
|
|
290
|
+
model: string;
|
|
291
|
+
/** Number of `prompt_too_long` retries that fired before success. 0 on first-try success. */
|
|
292
|
+
ptlRetries: number;
|
|
293
|
+
/**
|
|
294
|
+
* Turn ids actually covered by the summary — i.e., the ids of turns
|
|
295
|
+
* that made it to the provider. **PTL-retry safe**: when head-truncation
|
|
296
|
+
* shrank the scope, only the surviving (post-truncation) turn ids
|
|
297
|
+
* appear here. Drives `summaryToTurn`'s `replacesTurnIds`; the wire-
|
|
298
|
+
* level cutoff in `applyCompactSummaryCutoff` reads the same field
|
|
299
|
+
* from the persisted marker.
|
|
300
|
+
*/
|
|
301
|
+
summarizedTurnIds: readonly string[];
|
|
302
|
+
/**
|
|
303
|
+
* Turn ids dropped by PTL head-truncation before reaching the
|
|
304
|
+
* provider. **Empty on first-try success.** These turns are NOT
|
|
305
|
+
* covered by the summary — callers should either leave them in the
|
|
306
|
+
* conversation history (they stay visible to the model verbatim,
|
|
307
|
+
* since the id-based cutoff only elides ids the marker explicitly
|
|
308
|
+
* claims) or surface a "compaction lost N turns of context" warning.
|
|
309
|
+
*
|
|
310
|
+
* The harness keeps these in the wire-level conversation by default;
|
|
311
|
+
* the safety contract is "the summary describes exactly what's in
|
|
312
|
+
* `summarizedTurnIds` — nothing more, nothing less".
|
|
313
|
+
*/
|
|
314
|
+
droppedDueToPtl: readonly string[];
|
|
315
|
+
/** Turns left untouched (the preserved tail / verbatim slice). */
|
|
316
|
+
preservedTurns: readonly SessionTurn[];
|
|
317
|
+
/** Byte length of turns actually summarized (post-PTL-truncation). */
|
|
318
|
+
beforeBytes: number;
|
|
319
|
+
/** UTF-8 byte length of the summary text (rough "after" measure). */
|
|
320
|
+
afterBytes: number;
|
|
321
|
+
}
|
|
322
|
+
declare function compactConversation(opts: CompactOptions): Promise<CompactResult>;
|
|
323
|
+
//#endregion
|
|
324
|
+
//#region src/compact/restore.d.ts
|
|
325
|
+
/** One file selected for restoration, with its last-read timestamp for ranking. */
|
|
326
|
+
interface RecentFile {
|
|
327
|
+
/** Path relative to the execution context's `handle.cwd`. */
|
|
328
|
+
path: string;
|
|
329
|
+
/** Wall-clock when the file was last read, in ms. Drives recency ranking. */
|
|
330
|
+
mtimeMs: number;
|
|
331
|
+
}
|
|
332
|
+
interface PostCompactRestoreOptions {
|
|
333
|
+
/**
|
|
334
|
+
* Files to consider for restoration, ranked by recency. Typically derived
|
|
335
|
+
* via {@link selectFilesFromReadState} from `getReadState(session)`.
|
|
336
|
+
* The helper takes the top {@link PostCompactRestoreOptions.maxFilesToRestore}
|
|
337
|
+
* by `mtimeMs` descending, fetches their current content, and synthesizes
|
|
338
|
+
* `read_file` tool_call/tool_result pairs.
|
|
339
|
+
*/
|
|
340
|
+
recentFiles?: readonly RecentFile[];
|
|
341
|
+
/**
|
|
342
|
+
* Active skills to re-inject. Typically `agent.activeSkills`. Each entry
|
|
343
|
+
* yields a synthetic `skills_use` tool_call/tool_result pair carrying the
|
|
344
|
+
* skill's instructions (possibly truncated to the per-skill budget).
|
|
345
|
+
*/
|
|
346
|
+
activeSkills?: readonly ActiveSkill[];
|
|
347
|
+
/**
|
|
348
|
+
* Execution context used to fetch file content. **Required for file
|
|
349
|
+
* restoration.** Skills come pre-loaded (instructions live on the
|
|
350
|
+
* `SkillConfig`), so they don't need the context.
|
|
351
|
+
*/
|
|
352
|
+
execution?: ExecutionContext;
|
|
353
|
+
handle?: ExecutionHandle;
|
|
354
|
+
/**
|
|
355
|
+
* Canonical name of the file-read tool. Defaults to `read_file`. Aliases
|
|
356
|
+
* (e.g. `Read`) are NOT specified here — the agent loop's
|
|
357
|
+
* `rewriteMessagesToWire` handles wire conversion automatically.
|
|
358
|
+
*
|
|
359
|
+
* Override only when a host registered file-read under a different
|
|
360
|
+
* canonical name (not just an alias).
|
|
361
|
+
*/
|
|
362
|
+
readFileToolName?: string;
|
|
363
|
+
/**
|
|
364
|
+
* Canonical name of the skill-activation tool. Defaults to `skills_use`.
|
|
365
|
+
* Same aliasing semantics as `readFileToolName`.
|
|
366
|
+
*/
|
|
367
|
+
skillsUseToolName?: string;
|
|
368
|
+
/** Total token budget for file restoration. Default: 50_000. */
|
|
369
|
+
fileTokenBudget?: number;
|
|
370
|
+
/** Per-file token cap. Default: 5_000. */
|
|
371
|
+
fileTokenPerFileCap?: number;
|
|
372
|
+
/** Maximum file count. Default: 5. */
|
|
373
|
+
maxFilesToRestore?: number;
|
|
374
|
+
/** Total token budget for skill restoration. Default: 25_000. */
|
|
375
|
+
skillTokenBudget?: number;
|
|
376
|
+
/** Per-skill token cap. Default: 5_000. */
|
|
377
|
+
skillTokenPerSkillCap?: number;
|
|
378
|
+
/**
|
|
379
|
+
* Paths to skip — typically the file paths already covered by the
|
|
380
|
+
* compaction result's `preservedTurns`. Avoids double-injection when the
|
|
381
|
+
* recent reads sit in the preserved tail.
|
|
382
|
+
*/
|
|
383
|
+
excludePaths?: readonly string[];
|
|
384
|
+
/**
|
|
385
|
+
* Optional `runId` to tag the synthetic turns with — useful for hosts
|
|
386
|
+
* that want the restoration turns to roll up under the same run as the
|
|
387
|
+
* compaction marker. Defaults to undefined (orphan turns).
|
|
388
|
+
*/
|
|
389
|
+
runId?: string;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Envelope returned by {@link buildPostCompactAttachments}. The caller
|
|
393
|
+
* spreads `turns` into `session.appendTurns([summaryTurn, ...turns])`.
|
|
394
|
+
* Count fields drive UI banners ("restored 5 files + 2 skills").
|
|
395
|
+
*/
|
|
396
|
+
interface PostCompactAttachments {
|
|
397
|
+
/**
|
|
398
|
+
* Two synthetic turns when at least one item was restored, otherwise
|
|
399
|
+
* an empty array. The pair is `[assistant_with_tool_calls,
|
|
400
|
+
* user_with_tool_results]` — adjacent and well-formed for every
|
|
401
|
+
* provider's `tool_use ↔ tool_result` invariant.
|
|
402
|
+
*/
|
|
403
|
+
turns: readonly SessionTurn[];
|
|
404
|
+
/** Count of files actually restored (post-budget). */
|
|
405
|
+
restoredFiles: number;
|
|
406
|
+
/** Count of skills actually restored (post-budget). */
|
|
407
|
+
restoredSkills: number;
|
|
408
|
+
/** Rough total token cost of the restoration payload (sum of all content). */
|
|
409
|
+
estimatedTokens: number;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Convert a raw read-state map into a deduped, path-ranked list ready for
|
|
413
|
+
* restoration. Multiple entries for the same path (different
|
|
414
|
+
* `(offset, limit, maxBytes)` slices) collapse to one — keeping the most
|
|
415
|
+
* recent `mtimeMs`.
|
|
416
|
+
*
|
|
417
|
+
* Filters out entries whose key doesn't share the given `cwd` prefix:
|
|
418
|
+
* those came from a different execution context and can't be read back
|
|
419
|
+
* through this agent's handle.
|
|
420
|
+
*
|
|
421
|
+
* Pure. Most callers want {@link selectFilesFromSession}, which wraps
|
|
422
|
+
* `getReadState(session)` + this function in one call so the host
|
|
423
|
+
* doesn't have to reach into the tools layer.
|
|
424
|
+
*/
|
|
425
|
+
declare function selectFilesFromReadState(readState: ReadonlyMap<string, {
|
|
426
|
+
mtimeMs: number;
|
|
427
|
+
}>, cwd: string): RecentFile[];
|
|
428
|
+
/**
|
|
429
|
+
* Session-aware convenience: extract recently-read files directly from
|
|
430
|
+
* a {@link Session} via its per-session read-state map.
|
|
431
|
+
*
|
|
432
|
+
* Hosts (TUI / SDK consumers) typically have a `Session` and a `cwd`
|
|
433
|
+
* (the active agent's `handle.cwd`) on hand — this wrapper saves them
|
|
434
|
+
* from reaching into `src/tools/read-state.ts` directly. Returns an
|
|
435
|
+
* empty list when no read state has been recorded yet (fresh session,
|
|
436
|
+
* or `behavior.dedupReads === false`).
|
|
437
|
+
*
|
|
438
|
+
* Equivalent to:
|
|
439
|
+
*
|
|
440
|
+
* ```ts
|
|
441
|
+
* const state = getReadState(session)
|
|
442
|
+
* return state ? selectFilesFromReadState(state, cwd) : []
|
|
443
|
+
* ```
|
|
444
|
+
*/
|
|
445
|
+
declare function selectFilesFromSession(session: Session, cwd: string): RecentFile[];
|
|
446
|
+
/**
|
|
447
|
+
* Pick the top `maxFiles` from `files` (descending by `mtimeMs`),
|
|
448
|
+
* dropping any whose path appears in `excludePaths`.
|
|
449
|
+
*
|
|
450
|
+
* Stable for equal mtimes — files with the same timestamp retain their
|
|
451
|
+
* input order. Pure.
|
|
452
|
+
*/
|
|
453
|
+
declare function selectRecentFiles(files: readonly RecentFile[], opts: {
|
|
454
|
+
maxFiles: number;
|
|
455
|
+
excludePaths?: readonly string[];
|
|
456
|
+
}): RecentFile[];
|
|
457
|
+
/** UTF-8 byte length, matching `Buffer.byteLength(text, 'utf-8')`. */
|
|
458
|
+
/**
|
|
459
|
+
* Build the synthetic turns to append after a `compact-summary` marker.
|
|
460
|
+
*
|
|
461
|
+
* Returns a `PostCompactAttachments` envelope; the caller is responsible
|
|
462
|
+
* for `session.appendTurns([summaryTurn, ...result.turns])`. The two
|
|
463
|
+
* synthetic turns are always emitted together (or both omitted when
|
|
464
|
+
* nothing was restored) so the `tool_use ↔ tool_result` adjacency
|
|
465
|
+
* invariant holds regardless of caller code path.
|
|
466
|
+
*
|
|
467
|
+
* Failure isolation: a single file's read failure never blocks the rest
|
|
468
|
+
* of restoration — that file is skipped silently and processing
|
|
469
|
+
* continues. The returned `restoredFiles` count reflects what actually
|
|
470
|
+
* landed in the synthesized turns.
|
|
471
|
+
*/
|
|
472
|
+
declare function buildPostCompactAttachments(opts: PostCompactRestoreOptions): Promise<PostCompactAttachments>;
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region src/compact/utils.d.ts
|
|
475
|
+
/**
|
|
476
|
+
* Shared utilities for the compact module — extracted so the runner
|
|
477
|
+
* (`compact.ts`) and the restoration helper (`restore.ts`) don't carry
|
|
478
|
+
* redundant copies of the same low-level math.
|
|
479
|
+
*
|
|
480
|
+
* Kept zero-dependency by design: no Node/Bun imports, no zidane types
|
|
481
|
+
* either. Both `utf8ByteLength` and `estimateTokens` are total
|
|
482
|
+
* functions of a single `string` argument, so they're trivially
|
|
483
|
+
* portable to a worker/browser context if the compact module ever
|
|
484
|
+
* needs to render outside Node.
|
|
485
|
+
*/
|
|
486
|
+
/**
|
|
487
|
+
* UTF-8 byte length, matching `Buffer.byteLength(text, 'utf-8')` but
|
|
488
|
+
* without pulling `node:buffer` for a one-liner. Stable for surrogate
|
|
489
|
+
* pairs — a high+low surrogate pair counts as a single 4-byte sequence
|
|
490
|
+
* (not 2 × 3-byte). Cheap to call in hot loops.
|
|
491
|
+
*
|
|
492
|
+
* Pure. Identical bytes for identical input across every JS runtime.
|
|
493
|
+
*/
|
|
494
|
+
declare function utf8ByteLength(text: string): number;
|
|
495
|
+
/** Same constant Claude Code's `CONTEXT_MANAGEMENT.md` documents. */
|
|
496
|
+
declare const BYTES_PER_TOKEN = 4;
|
|
497
|
+
/**
|
|
498
|
+
* Approximate token count for `text`. Mirrors Claude Code's
|
|
499
|
+
* `BYTES_PER_TOKEN = 4` heuristic — acceptable for budget arithmetic
|
|
500
|
+
* (sizing summarization scopes, enforcing per-file caps in restoration).
|
|
501
|
+
*
|
|
502
|
+
* Accurate to ~10% on English + code. Use a real tokenizer when exact
|
|
503
|
+
* counts matter (cost reporting, hard caps); this is for budget gates
|
|
504
|
+
* where being off by 10% is fine.
|
|
505
|
+
*
|
|
506
|
+
* Pure. Exported so callers (TUI, SDK consumers) can do their own
|
|
507
|
+
* pre-budgeting against the same heuristic the harness uses internally.
|
|
508
|
+
*/
|
|
509
|
+
declare function estimateTokens(text: string): number;
|
|
510
|
+
//#endregion
|
|
511
|
+
//#region src/loop-persistence.d.ts
|
|
512
|
+
/**
|
|
513
|
+
* Bytes of head content included in the inline preview block. 2 KiB matches
|
|
514
|
+
* Claude Code's `PREVIEW_SIZE_BYTES` — enough for the model to identify the
|
|
515
|
+
* content class (error output / structured data / log shape) and decide
|
|
516
|
+
* whether to call `read_file` on the persisted path for the full payload.
|
|
517
|
+
*
|
|
518
|
+
* Tail-priority preview (matching `shell`'s truncation strategy) was
|
|
519
|
+
* considered but rejected: most "what is this?" decisions get made from
|
|
520
|
+
* the head, and the path is in the stub for the rare case where the tail
|
|
521
|
+
* matters.
|
|
522
|
+
*/
|
|
523
|
+
declare const PERSISTENCE_PREVIEW_BYTES: number;
|
|
524
|
+
/**
|
|
525
|
+
* Byte-stable prefix every {@link buildPersistedStub} output starts with.
|
|
526
|
+
* Exported so wire-level passes (tail compaction, future stale-output
|
|
527
|
+
* elision) can recognize a persisted stub and preserve its path attribute
|
|
528
|
+
* rather than replacing the stub with their own — losing the pointer to
|
|
529
|
+
* the on-disk blob.
|
|
530
|
+
*
|
|
531
|
+
* Bound to the literal opening of the XML tag; changing the stub format
|
|
532
|
+
* requires updating this constant in lockstep (and shipping a migration
|
|
533
|
+
* for in-flight sessions).
|
|
534
|
+
*/
|
|
535
|
+
declare const PERSISTED_STUB_PREFIX = "<persisted-output tool=\"";
|
|
536
|
+
/**
|
|
537
|
+
* Resolve the per-session persistence directory under `<userDir>/tool-results/<sessionId>/`.
|
|
538
|
+
*
|
|
539
|
+
* The chat layer calls this at session activation and forwards the result
|
|
540
|
+
* via `behavior.persistDir`. Exposed as a public helper so SDK consumers
|
|
541
|
+
* pick the same layout — single source of truth for "where do blobs live".
|
|
542
|
+
*/
|
|
543
|
+
declare function resolvePersistDir(opts: {
|
|
544
|
+
userDir: string;
|
|
545
|
+
sessionId: string;
|
|
546
|
+
}): string;
|
|
547
|
+
/**
|
|
548
|
+
* Inputs to {@link maybePersistToolResult}. Kept as a struct so the loop's
|
|
549
|
+
* call site stays readable and additional optional knobs (compression,
|
|
550
|
+
* mime detection, …) land without re-threading every call site.
|
|
551
|
+
*/
|
|
552
|
+
interface PersistInput {
|
|
553
|
+
/** Canonical tool name — checked against `excludeTools`. */
|
|
554
|
+
toolName: string;
|
|
555
|
+
/** `tool_use` id from the assistant turn. Used as the filename. */
|
|
556
|
+
callId: string;
|
|
557
|
+
/** Result returned by the tool (post-`tool:transform`). */
|
|
558
|
+
output: string | ToolResultContent[];
|
|
559
|
+
/** Byte threshold; outputs at or below stay inline. */
|
|
560
|
+
threshold: number;
|
|
561
|
+
/** Canonical tool names that bypass persistence. */
|
|
562
|
+
excludeTools?: readonly string[];
|
|
563
|
+
/** Persistence root directory. Created on first write. */
|
|
564
|
+
persistDir: string;
|
|
565
|
+
}
|
|
566
|
+
type PersistOutcome = {
|
|
567
|
+
kind: 'skip';
|
|
568
|
+
reason: 'disabled' | 'excluded' | 'under-threshold' | 'unsupported-shape' | 'unsafe-call-id' | 'invalid-persist-dir';
|
|
569
|
+
} | {
|
|
570
|
+
kind: 'persisted';
|
|
571
|
+
output: string;
|
|
572
|
+
originalBytes: number;
|
|
573
|
+
persistedPath: string;
|
|
574
|
+
} | {
|
|
575
|
+
kind: 'error';
|
|
576
|
+
reason: 'write-failed';
|
|
577
|
+
error: Error;
|
|
578
|
+
};
|
|
579
|
+
/**
|
|
580
|
+
* Decide-and-persist for a single tool result. Pure decision + filesystem
|
|
581
|
+
* side-effect; returns the new wire-level `output` string when substitution
|
|
582
|
+
* happened, otherwise tells the caller to leave the result alone.
|
|
583
|
+
*
|
|
584
|
+
* Atomicity: writes go through `<path>.tmp` + `rename` so a concurrent
|
|
585
|
+
* read (or a crash mid-write) never sees a half-written blob.
|
|
586
|
+
*
|
|
587
|
+
* `ToolResultContent[]` results (images, structured blocks) currently bypass
|
|
588
|
+
* persistence — the inline image bytes are the point of the call, and a
|
|
589
|
+
* mixed text/image array isn't representable as a single `.txt` file. We
|
|
590
|
+
* may revisit if a tool starts returning very large text-only arrays.
|
|
591
|
+
*/
|
|
592
|
+
declare function maybePersistToolResult(input: PersistInput): Promise<PersistOutcome>;
|
|
593
|
+
interface BuildStubInput {
|
|
594
|
+
toolName: string;
|
|
595
|
+
originalBytes: number;
|
|
596
|
+
persistedPath: string;
|
|
597
|
+
output: string;
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Render the byte-stable `<persisted-output>` stub the model sees in place
|
|
601
|
+
* of the original `tool_result`.
|
|
602
|
+
*
|
|
603
|
+
* Format choices:
|
|
604
|
+
* - XML wrapper because models reliably parse it as structural.
|
|
605
|
+
* - Byte count + path in attributes so the model can decide whether to
|
|
606
|
+
* `read_file` the persisted blob without scanning the preview.
|
|
607
|
+
* - Preview always shows the head — `shell`'s tail-priority truncation is
|
|
608
|
+
* irrelevant here because the model has the full path if it needs the
|
|
609
|
+
* tail.
|
|
610
|
+
* - No timestamps, no random UUIDs inside the stub: every byte must be
|
|
611
|
+
* reproducible from the inputs, otherwise re-emission on subsequent
|
|
612
|
+
* turns would bust the prompt cache.
|
|
613
|
+
*
|
|
614
|
+
* Exported for tests (asserting the byte-stable contract) and for SDK
|
|
615
|
+
* consumers wiring their own persistence middleware against the same
|
|
616
|
+
* surface.
|
|
617
|
+
*/
|
|
618
|
+
declare function buildPersistedStub(input: BuildStubInput): string;
|
|
619
|
+
/**
|
|
620
|
+
* Remove every persisted blob belonging to a session. Called by the chat
|
|
621
|
+
* layer from its session-delete path so closing a session frees the disk
|
|
622
|
+
* footprint alongside the SQLite row.
|
|
623
|
+
*
|
|
624
|
+
* Idempotent — missing directory (session never persisted anything) is a
|
|
625
|
+
* no-op, not an error. Wraps the `rm -rf` so a permissions blip on one
|
|
626
|
+
* blob doesn't propagate to the caller; the chat layer can't usefully
|
|
627
|
+
* recover from "couldn't unlink a result file" mid-delete.
|
|
628
|
+
*/
|
|
629
|
+
declare function cleanupPersistedSession(persistRoot: string): Promise<void>;
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region src/mcp/oauth-provider.d.ts
|
|
632
|
+
/**
|
|
633
|
+
* Per-server persisted state. Subfields are optional so a partial save
|
|
634
|
+
* (e.g. `saveCodeVerifier` arriving before `saveTokens`) doesn't blow away
|
|
635
|
+
* earlier subfields — the provider always patches, never replaces.
|
|
636
|
+
*/
|
|
637
|
+
interface McpCredentialEntry {
|
|
638
|
+
tokens?: OAuthTokens;
|
|
639
|
+
clientInformation?: OAuthClientInformationMixed;
|
|
640
|
+
discoveryState?: OAuthDiscoveryState;
|
|
641
|
+
}
|
|
642
|
+
interface McpCredentialStore {
|
|
643
|
+
load: (name: string) => McpCredentialEntry | undefined;
|
|
644
|
+
save: (name: string, entry: McpCredentialEntry) => void;
|
|
645
|
+
delete: (name: string) => void;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* In-memory store — primarily for tests, but valid as a no-persistence option
|
|
649
|
+
* (tokens evaporate on process exit, the user re-auths every cold start).
|
|
650
|
+
*/
|
|
651
|
+
declare function createMemoryMcpCredentialStore(seed?: Record<string, McpCredentialEntry>): McpCredentialStore;
|
|
652
|
+
interface McpOAuthProviderOptions {
|
|
653
|
+
/** Server name — used as the storage key. */
|
|
654
|
+
name: string;
|
|
655
|
+
/** Persistence backend. */
|
|
656
|
+
store: McpCredentialStore;
|
|
657
|
+
/**
|
|
658
|
+
* Loopback callback URI. Pass `undefined` for bootstrap (non-interactive
|
|
659
|
+
* mode — stored tokens + refresh only, never opens a browser).
|
|
660
|
+
*/
|
|
661
|
+
redirectUri?: string;
|
|
662
|
+
/**
|
|
663
|
+
* Invoked when the SDK wants the user agent to navigate to the authorization
|
|
664
|
+
* URL. Typically the host opens the browser AND emits a hook so the TUI can
|
|
665
|
+
* render the URL in a status row. No-op in non-interactive mode (the SDK
|
|
666
|
+
* still calls this before throwing `UnauthorizedError` from connect).
|
|
667
|
+
*/
|
|
668
|
+
onAuthorizationUrl?: (url: URL) => void | Promise<void>;
|
|
669
|
+
/**
|
|
670
|
+
* `client_name` used in dynamic client registration. Defaults to `'zidane'`.
|
|
671
|
+
* Some servers display this string to the user on the consent screen.
|
|
672
|
+
*/
|
|
673
|
+
clientName?: string;
|
|
674
|
+
/**
|
|
675
|
+
* Override the requested OAuth scope. Default: unset (the SDK negotiates
|
|
676
|
+
* via the server's metadata).
|
|
677
|
+
*/
|
|
678
|
+
scope?: string;
|
|
679
|
+
}
|
|
680
|
+
declare class McpOAuthProvider implements OAuthClientProvider {
|
|
681
|
+
private readonly name;
|
|
682
|
+
private readonly store;
|
|
683
|
+
private readonly _redirectUri?;
|
|
684
|
+
private readonly onAuthorizationUrl?;
|
|
685
|
+
private readonly clientName;
|
|
686
|
+
private readonly _scope?;
|
|
687
|
+
private codeVerifierValue;
|
|
688
|
+
constructor(opts: McpOAuthProviderOptions);
|
|
689
|
+
get redirectUrl(): string | URL | undefined;
|
|
690
|
+
get clientMetadata(): OAuthClientMetadata;
|
|
691
|
+
tokens(): OAuthTokens | undefined;
|
|
692
|
+
saveTokens(tokens: OAuthTokens): void;
|
|
693
|
+
clientInformation(): OAuthClientInformationMixed | undefined;
|
|
694
|
+
saveClientInformation(info: OAuthClientInformationMixed): void;
|
|
695
|
+
discoveryState(): OAuthDiscoveryState | undefined;
|
|
696
|
+
saveDiscoveryState(state: OAuthDiscoveryState): void;
|
|
697
|
+
saveCodeVerifier(verifier: string): void;
|
|
698
|
+
codeVerifier(): string;
|
|
699
|
+
redirectToAuthorization(url: URL): Promise<void>;
|
|
700
|
+
/**
|
|
701
|
+
* Wipe stored credentials when the server reports the cached state is no
|
|
702
|
+
* longer valid. The SDK calls this with a scope hint:
|
|
703
|
+
* - `'tokens'` → access/refresh revoked, keep client registration
|
|
704
|
+
* - `'client'` → client registration invalidated, reset everything
|
|
705
|
+
* - `'verifier'`→ PKCE state stale (e.g. mismatched state param)
|
|
706
|
+
* - `'discovery'` → discovery metadata stale (servers re-keyed)
|
|
707
|
+
* - `'all'` → full reset
|
|
708
|
+
*/
|
|
709
|
+
invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): Promise<void>;
|
|
710
|
+
private patch;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* True when an HTTP transport's auth headers already include an explicit
|
|
714
|
+
* Authorization. Used by the bootstrap escape-hatch: a user who provided
|
|
715
|
+
* their own bearer token shouldn't be auto-promoted to OAuth on a 401.
|
|
716
|
+
*
|
|
717
|
+
* Case-insensitive — Node normalizes outgoing headers to lowercase but
|
|
718
|
+
* users hand-write `Authorization` in configs.
|
|
719
|
+
*/
|
|
720
|
+
declare function hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean;
|
|
721
|
+
//#endregion
|
|
722
|
+
//#region src/mcp/login.d.ts
|
|
723
|
+
interface LoginMcpServerOptions {
|
|
724
|
+
/** Persistence — same store the bootstrap path reads from. */
|
|
725
|
+
store: McpCredentialStore;
|
|
726
|
+
/**
|
|
727
|
+
* Invoked with the authorization URL once it's ready. Hosts typically
|
|
728
|
+
* (a) emit `mcp:auth:url` for the TUI, and (b) call `tryOpenBrowser`.
|
|
729
|
+
* The URL is identical to the one passed to the `mcp:auth:url` hook
|
|
730
|
+
* fired automatically — this callback is a synchronous hook for callers
|
|
731
|
+
* that don't want to wire the agent hook machinery.
|
|
732
|
+
*/
|
|
733
|
+
onAuthorizationUrl?: (url: URL) => void | Promise<void>;
|
|
734
|
+
/** Cancels the flow (esc / close modal / SIGINT). */
|
|
735
|
+
signal?: AbortSignal;
|
|
736
|
+
/** Agent hooks. The flow emits `mcp:auth:url`/`success`/`error` when wired. */
|
|
737
|
+
hooks?: Hookable<AgentHooks>;
|
|
738
|
+
/** Override `client_name` shown on consent screens. Default: 'zidane'. */
|
|
739
|
+
clientName?: string;
|
|
740
|
+
/** Override the requested OAuth scope. */
|
|
741
|
+
scope?: string;
|
|
742
|
+
/**
|
|
743
|
+
* Override the loopback callback path. Default: `/callback`. Useful only
|
|
744
|
+
* for servers that pinned a different path during registration.
|
|
745
|
+
*/
|
|
746
|
+
callbackPath?: string;
|
|
747
|
+
/**
|
|
748
|
+
* Maximum time to wait for the user to complete the browser flow, in ms.
|
|
749
|
+
* The user can also cancel via `signal`. Default: 5 minutes.
|
|
750
|
+
*/
|
|
751
|
+
timeoutMs?: number;
|
|
752
|
+
}
|
|
753
|
+
interface LoginMcpServerResult {
|
|
754
|
+
/** Stored OAuth tokens after a successful exchange. */
|
|
755
|
+
tokens: NonNullable<ReturnType<McpOAuthProvider['tokens']>>;
|
|
756
|
+
/**
|
|
757
|
+
* Upstream tool descriptors discovered after re-connecting with the new
|
|
758
|
+
* tokens. Already filtered by the server's `enabledTools` / `disabledTools`
|
|
759
|
+
* is NOT applied here — that's a bootstrap concern. Hosts that want filtering
|
|
760
|
+
* should pass the result through `connectMcpServers` rebuild on the next
|
|
761
|
+
* session activation rather than reusing this list verbatim.
|
|
762
|
+
*/
|
|
763
|
+
tools: Array<{
|
|
764
|
+
name: string;
|
|
765
|
+
description?: string | null;
|
|
766
|
+
inputSchema?: unknown;
|
|
767
|
+
}>;
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Run the full interactive OAuth flow for `config`. Only supports `sse` and
|
|
771
|
+
* `streamable-http` transports — `stdio` MCP servers don't speak OAuth.
|
|
772
|
+
*
|
|
773
|
+
* Throws on:
|
|
774
|
+
* - Wrong transport.
|
|
775
|
+
* - Abort signal.
|
|
776
|
+
* - Browser-side error (user denied, server rejected, etc.).
|
|
777
|
+
* - Code exchange failure.
|
|
778
|
+
* - Post-exchange connect failure.
|
|
779
|
+
*
|
|
780
|
+
* Always closes the loopback callback server before returning, success or
|
|
781
|
+
* failure.
|
|
782
|
+
*/
|
|
783
|
+
declare function loginMcpServer(config: McpServerConfig, options: LoginMcpServerOptions): Promise<LoginMcpServerResult>;
|
|
784
|
+
//#endregion
|
|
785
|
+
//#region src/mcp/oauth-callback.d.ts
|
|
786
|
+
/**
|
|
787
|
+
* Local loopback HTTP callback for OAuth 2.0 authorization code flows.
|
|
788
|
+
*
|
|
789
|
+
* Stands up a one-shot server on `127.0.0.1:<random>` that captures the
|
|
790
|
+
* `?code=...` redirect from a browser-driven OAuth flow and resolves a
|
|
791
|
+
* promise with the code. Used as the `redirectUrl` half of the MCP SDK's
|
|
792
|
+
* `OAuthClientProvider` (the persistence half lives separately).
|
|
793
|
+
*
|
|
794
|
+
* Design:
|
|
795
|
+
* - Loopback-only (`127.0.0.1`) — the OAuth spec treats `http://127.0.0.1:<port>`
|
|
796
|
+
* as a public-client redirect URI per RFC 8252 §7.3. Browsers do NOT block it,
|
|
797
|
+
* and Anthropic / OpenAI / Linear / GitHub all accept it.
|
|
798
|
+
* - Random port (`port = 0`) — the OS picks an unused one. We read the actual
|
|
799
|
+
* port back from `server.address()` after `listen()`.
|
|
800
|
+
* - Single-shot — the first GET to `path` with a `code` (or `error`) wins;
|
|
801
|
+
* subsequent requests get 404. The server keeps listening (in case the user
|
|
802
|
+
* hits "back" and re-authorizes), so callers must `close()` once they have
|
|
803
|
+
* the code or have given up.
|
|
804
|
+
* - Abort-aware — wiring an external `AbortSignal` rejects the promise and
|
|
805
|
+
* closes the server immediately. Required for the TUI's "esc cancels login"
|
|
806
|
+
* UX.
|
|
807
|
+
* - No HTML framework — a single inline `<html>` string keeps this isolated
|
|
808
|
+
* from any UI dependency.
|
|
809
|
+
*/
|
|
810
|
+
/**
|
|
811
|
+
* Result of a successful callback. `state` is forwarded verbatim from the
|
|
812
|
+
* query string — callers verify it against their pre-flight value to defend
|
|
813
|
+
* against CSRF (the MCP SDK does this internally when it controls `state`).
|
|
814
|
+
*/
|
|
815
|
+
interface OAuthCallbackResult {
|
|
816
|
+
code: string;
|
|
817
|
+
state?: string;
|
|
818
|
+
}
|
|
819
|
+
interface OAuthCallbackHandle {
|
|
820
|
+
/**
|
|
821
|
+
* Full URI to register with the authorization server, e.g.
|
|
822
|
+
* `http://127.0.0.1:51823/callback`. Stable for the lifetime of the
|
|
823
|
+
* handle.
|
|
824
|
+
*/
|
|
825
|
+
redirectUri: string;
|
|
826
|
+
/**
|
|
827
|
+
* Resolves with `{ code, state }` on a successful callback. Rejects with:
|
|
828
|
+
* - The OAuth-spec `error` field (`access_denied`, `server_error`, ...)
|
|
829
|
+
* when the authorization server redirects with `?error=...`.
|
|
830
|
+
* - `'OAuth callback aborted'` when the external `AbortSignal` fires.
|
|
831
|
+
* - `'OAuth callback server closed'` when `close()` is called before any
|
|
832
|
+
* callback arrives.
|
|
833
|
+
*
|
|
834
|
+
* Single-shot — only the first matching request resolves the promise.
|
|
835
|
+
*/
|
|
836
|
+
promise: Promise<OAuthCallbackResult>;
|
|
837
|
+
/**
|
|
838
|
+
* Idempotent shutdown. Safe to call from a `finally` block whether the
|
|
839
|
+
* flow succeeded, failed, or was aborted. Resolves once the server stops
|
|
840
|
+
* accepting connections.
|
|
841
|
+
*/
|
|
842
|
+
close: () => Promise<void>;
|
|
843
|
+
}
|
|
844
|
+
interface OAuthCallbackOptions {
|
|
845
|
+
/** Cancels the flow — rejects `promise` and closes the server. */
|
|
846
|
+
signal?: AbortSignal;
|
|
847
|
+
/**
|
|
848
|
+
* Path component the authorization server should redirect to. Defaults
|
|
849
|
+
* to `/callback`. Useful when matching a pre-registered URI that uses a
|
|
850
|
+
* different path.
|
|
851
|
+
*/
|
|
852
|
+
path?: string;
|
|
853
|
+
/**
|
|
854
|
+
* Override the loopback host. Defaults to `127.0.0.1`. Don't bind to
|
|
855
|
+
* `0.0.0.0` here — the OAuth code is a one-time secret and the server
|
|
856
|
+
* would otherwise accept it from any host on the LAN.
|
|
857
|
+
*/
|
|
858
|
+
host?: string;
|
|
859
|
+
/**
|
|
860
|
+
* Override the port. Defaults to `0` (OS-assigned). Pin to a fixed port
|
|
861
|
+
* only when the authorization server requires a pre-registered redirect
|
|
862
|
+
* URI; the random-port path is preferred so concurrent flows don't clash.
|
|
863
|
+
*/
|
|
864
|
+
port?: number;
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* Start a one-shot OAuth callback server. The returned handle's `redirectUri`
|
|
868
|
+
* should be passed to the authorization server as the `redirect_uri` query
|
|
869
|
+
* parameter; `promise` resolves once the user finishes the browser flow.
|
|
870
|
+
*
|
|
871
|
+
* Always `await handle.close()` in a `finally` block — even on success, the
|
|
872
|
+
* server stays open until told to shut down (so it can serve the
|
|
873
|
+
* "you can close this tab" page).
|
|
874
|
+
*/
|
|
875
|
+
declare function startOAuthCallback(opts?: OAuthCallbackOptions): Promise<OAuthCallbackHandle>;
|
|
876
|
+
//#endregion
|
|
877
|
+
//#region src/stats.d.ts
|
|
878
|
+
/**
|
|
879
|
+
* Per-model usage rollup produced by {@link statsByModel}.
|
|
880
|
+
*
|
|
881
|
+
* `turns` counts the number of `TurnUsage` entries attributed to the model
|
|
882
|
+
* across the whole tree (parent loop + every recursively-spawned child).
|
|
883
|
+
* Cache and cost numbers are summed from the same set of turns.
|
|
884
|
+
*/
|
|
885
|
+
interface ModelUsage {
|
|
886
|
+
input: number;
|
|
887
|
+
output: number;
|
|
888
|
+
cost: number;
|
|
889
|
+
cacheRead: number;
|
|
890
|
+
cacheCreation: number;
|
|
891
|
+
turns: number;
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Depth-first walk over the stats tree, returning every `TurnUsage` entry
|
|
895
|
+
* — parent loop first, then each child subtree in completion order.
|
|
896
|
+
*
|
|
897
|
+
* Closes the cache-token aggregation gap: `TurnUsage.cacheRead` /
|
|
898
|
+
* `cacheCreation` live only on per-turn entries, and the top-level
|
|
899
|
+
* `AgentStats` deliberately doesn't carry cumulative forms (one source of
|
|
900
|
+
* truth, no risk of drift). Anything that needs a tree-wide sum walks
|
|
901
|
+
* through this.
|
|
902
|
+
*/
|
|
903
|
+
declare function flattenTurns(stats: AgentStats): TurnUsage[];
|
|
904
|
+
/**
|
|
905
|
+
* Group cumulative usage by `TurnUsage.modelId`. Each entry sums the input,
|
|
906
|
+
* output, cache, cost, and turn-count across every turn the tree attributed
|
|
907
|
+
* to that model — naturally handling cross-model runs (vision-fallback,
|
|
908
|
+
* model-shifted subagents, mixed-provider workflows).
|
|
909
|
+
*
|
|
910
|
+
* Turns missing `modelId` (mock providers, providers that don't echo a model
|
|
911
|
+
* id) are bucketed under the literal string `'(unknown)'`.
|
|
912
|
+
*/
|
|
913
|
+
declare function statsByModel(stats: AgentStats): Map<string, ModelUsage>;
|
|
914
|
+
//#endregion
|
|
915
|
+
//#region src/tools/edit.d.ts
|
|
916
|
+
/**
|
|
917
|
+
* Surgical edit — replace `old_string` with `new_string` in a single file.
|
|
918
|
+
*
|
|
919
|
+
* Mirrors Claude Code's `Edit` semantics so models post-trained on Anthropic's
|
|
920
|
+
* tool surface need no relearning. Fails clearly when `old_string` isn't unique
|
|
921
|
+
* (unless `replace_all: true`) and when not found, with a nearest-match preview
|
|
922
|
+
* so the model can recover without a separate `read_file` round-trip.
|
|
923
|
+
*/
|
|
924
|
+
declare const edit: ToolDef;
|
|
925
|
+
//#endregion
|
|
926
|
+
//#region src/tools/glob.d.ts
|
|
927
|
+
declare const glob: ToolDef;
|
|
928
|
+
//#endregion
|
|
929
|
+
//#region src/tools/grep.d.ts
|
|
930
|
+
declare const grep: ToolDef;
|
|
931
|
+
//#endregion
|
|
932
|
+
//#region src/tools/interaction.d.ts
|
|
933
|
+
interface InteractionToolOptions {
|
|
934
|
+
/** JSON Schema for the request payload the model sends */
|
|
935
|
+
schema: Record<string, unknown>;
|
|
936
|
+
/** Tool name (default: 'interaction') */
|
|
937
|
+
name?: string;
|
|
938
|
+
/** Tool description shown to the model */
|
|
939
|
+
description?: string;
|
|
940
|
+
/** Called when the model invokes this tool. Receives the validated payload and tool context, returns data for the model. */
|
|
941
|
+
onRequest: (payload: Record<string, unknown>, ctx: ToolContext) => Promise<Record<string, unknown> | string>;
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Create an interaction tool that lets the agent request structured input.
|
|
945
|
+
*
|
|
946
|
+
* The model calls this tool with a payload matching the schema.
|
|
947
|
+
* `onRequest` is called with the payload and should return the response
|
|
948
|
+
* (string or object) that gets sent back to the model as the tool result.
|
|
949
|
+
*/
|
|
950
|
+
declare function createInteractionTool(options: InteractionToolOptions): ToolDef;
|
|
951
|
+
//#endregion
|
|
952
|
+
//#region src/tools/list-files.d.ts
|
|
953
|
+
declare const listFiles: ToolDef;
|
|
954
|
+
//#endregion
|
|
955
|
+
//#region src/tools/multi-edit.d.ts
|
|
956
|
+
declare const multiEdit: ToolDef;
|
|
957
|
+
//#endregion
|
|
958
|
+
//#region src/tools/read-file.d.ts
|
|
959
|
+
declare const readFile: ToolDef;
|
|
960
|
+
//#endregion
|
|
961
|
+
//#region src/tools/shell.d.ts
|
|
962
|
+
declare const shell: ToolDef;
|
|
963
|
+
//#endregion
|
|
964
|
+
//#region src/tools/skills-read.d.ts
|
|
965
|
+
interface SkillsReadToolOptions {
|
|
966
|
+
catalog: readonly SkillConfig[];
|
|
967
|
+
state: SkillActivationState;
|
|
968
|
+
}
|
|
969
|
+
declare function createSkillsReadTool(options: SkillsReadToolOptions): ToolDef;
|
|
970
|
+
//#endregion
|
|
971
|
+
//#region src/tools/skills-run-script.d.ts
|
|
972
|
+
interface SkillsRunScriptToolOptions {
|
|
973
|
+
catalog: readonly SkillConfig[];
|
|
974
|
+
state: SkillActivationState;
|
|
975
|
+
/** Script timeout in milliseconds. Default 60000. */
|
|
976
|
+
scriptTimeoutMs?: number;
|
|
977
|
+
}
|
|
978
|
+
declare function createSkillsRunScriptTool(options: SkillsRunScriptToolOptions): ToolDef;
|
|
979
|
+
//#endregion
|
|
980
|
+
//#region src/tools/skills-use.d.ts
|
|
981
|
+
interface SkillsUseToolOptions {
|
|
982
|
+
/** Resolved skills catalog for this run. */
|
|
983
|
+
catalog: readonly SkillConfig[];
|
|
984
|
+
/** Per-agent activation state the tool mutates. */
|
|
985
|
+
state: SkillActivationState;
|
|
986
|
+
/** Agent hooks — used to fire `skills:activate` on first activation. */
|
|
987
|
+
hooks: Hookable<AgentHooks>;
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Factory for `skills_use`. Auto-injected into the agent's tool set by the
|
|
991
|
+
* agent runtime when a non-empty skills catalog is available (unless
|
|
992
|
+
* `SkillsConfig.tool === false`).
|
|
993
|
+
*
|
|
994
|
+
* The tool schema's `name` property is `enum`-constrained to the resolved
|
|
995
|
+
* catalog so the LLM cannot hallucinate a skill that doesn't exist.
|
|
996
|
+
*/
|
|
997
|
+
declare function createSkillsUseTool(options: SkillsUseToolOptions): ToolDef;
|
|
998
|
+
//#endregion
|
|
999
|
+
//#region src/tools/spawn.d.ts
|
|
1000
|
+
interface ChildAgent {
|
|
1001
|
+
id: string;
|
|
1002
|
+
task: string;
|
|
1003
|
+
startedAt: number;
|
|
1004
|
+
/** Subagent depth — 1 for a direct child of a top-level agent. */
|
|
1005
|
+
depth: number;
|
|
1006
|
+
}
|
|
1007
|
+
interface SpawnToolState {
|
|
1008
|
+
/** Currently running children. */
|
|
1009
|
+
readonly children: ReadonlyMap<string, ChildAgent>;
|
|
1010
|
+
/**
|
|
1011
|
+
* Cumulative stats across every completed direct child of this spawn-tool
|
|
1012
|
+
* instance (returns a copy). Each child's contribution is the cumulative
|
|
1013
|
+
* `AgentStats` returned by its `agent.run()` — so
|
|
1014
|
+
* `totalIn`/`totalOut`/`totalCacheRead`/`totalCacheCreation` cover the
|
|
1015
|
+
* entire subtree (children + grandchildren + …), while `turns` and
|
|
1016
|
+
* `elapsed` stay parent-loop-only per child and are summed across direct
|
|
1017
|
+
* children. `elapsed` over-counts when children ran in parallel.
|
|
1018
|
+
*
|
|
1019
|
+
* Lives across multiple parent runs that share this instance.
|
|
1020
|
+
*/
|
|
1021
|
+
readonly totalChildStats: Readonly<AgentStats>;
|
|
1022
|
+
}
|
|
1023
|
+
interface SpawnToolOptions {
|
|
1024
|
+
/** Maximum concurrent sub-agents (default: 3). */
|
|
1025
|
+
maxConcurrent?: number;
|
|
1026
|
+
/**
|
|
1027
|
+
* Maximum subagent depth. 0 disables spawning entirely; 1 allows top-level
|
|
1028
|
+
* spawns but forbids grandchildren; 3 (default) allows three levels of
|
|
1029
|
+
* recursion — enough for most orchestration patterns, a sharp ceiling
|
|
1030
|
+
* against runaway loops.
|
|
1031
|
+
*/
|
|
1032
|
+
maxDepth?: number;
|
|
1033
|
+
/** Child model override. */
|
|
1034
|
+
model?: string;
|
|
1035
|
+
/** Child system prompt override. Per-spawn `input.system` takes precedence. */
|
|
1036
|
+
system?: string;
|
|
1037
|
+
/** Child thinking level. */
|
|
1038
|
+
thinking?: 'off' | 'minimal' | 'low' | 'medium' | 'high';
|
|
1039
|
+
/** Preset override for children. Shallow-merged over the parent's preset (parent fields still win for anything left unset). */
|
|
1040
|
+
preset?: Preset;
|
|
1041
|
+
/**
|
|
1042
|
+
* Per-child timeout, in milliseconds. When the child exceeds it the spawn
|
|
1043
|
+
* tool returns a timeout marker, fires `spawn:error`, and destroys the
|
|
1044
|
+
* child agent. Default: none.
|
|
1045
|
+
*/
|
|
1046
|
+
timeoutMs?: number;
|
|
1047
|
+
/**
|
|
1048
|
+
* When `true` and the parent has a session, the child reuses the parent's
|
|
1049
|
+
* session — child turns are appended with the child's own `runId`, and the
|
|
1050
|
+
* resulting `SessionRun` carries `parentRunId` so the tree is
|
|
1051
|
+
* reconstructible. Default: `false` (child is in-memory only).
|
|
1052
|
+
*/
|
|
1053
|
+
persist?: boolean;
|
|
1054
|
+
/**
|
|
1055
|
+
* Forward a curated subset of child hook events (`stream:*`, `tool:*`,
|
|
1056
|
+
* `turn:after`) onto the parent's hook bus as `child:*` events. Default:
|
|
1057
|
+
* `true`. Grandchildren bubble through their child transparently.
|
|
1058
|
+
*/
|
|
1059
|
+
forwardHooks?: boolean;
|
|
1060
|
+
/** Called when a child agent starts. */
|
|
1061
|
+
onSpawn?: (child: ChildAgent) => void;
|
|
1062
|
+
/** Called when a child agent completes (success, abort, timeout, or error). */
|
|
1063
|
+
onComplete?: (child: ChildAgent, stats: AgentStats, status: NonNullable<ChildRunStats['status']>) => void;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Create a configured spawn tool.
|
|
1067
|
+
*
|
|
1068
|
+
* State (`children`, `totalChildStats`, counters, active count) is scoped to
|
|
1069
|
+
* the returned instance. Multiple parent agents using the same instance will
|
|
1070
|
+
* share counters + stats + concurrency slots — call `createSpawnTool()` per
|
|
1071
|
+
* agent (or use the stateless default `spawn`) to keep them isolated.
|
|
1072
|
+
*/
|
|
1073
|
+
declare function createSpawnTool(options?: SpawnToolOptions): ToolDef & SpawnToolState;
|
|
1074
|
+
//#endregion
|
|
1075
|
+
//#region src/tools/tool-search.d.ts
|
|
1076
|
+
interface LazyToolEntry {
|
|
1077
|
+
/**
|
|
1078
|
+
* Wire name (after `toolAliases` rewrite). What the model sees in the
|
|
1079
|
+
* catalog, what `tool_search` matches against, and what the provider's
|
|
1080
|
+
* tool list will carry once the entry is unlocked.
|
|
1081
|
+
*/
|
|
1082
|
+
name: string;
|
|
1083
|
+
/**
|
|
1084
|
+
* Canonical (registry-key) name used for unlock-set membership and for the
|
|
1085
|
+
* loop's `ctx.tools[name]` dispatch lookup. Equal to `name` when no alias
|
|
1086
|
+
* is configured for this tool.
|
|
1087
|
+
*/
|
|
1088
|
+
canonicalName: string;
|
|
1089
|
+
description: string;
|
|
1090
|
+
inputSchema: Record<string, unknown>;
|
|
1091
|
+
/** Source MCP server, when applicable. Used for `server`-bulk unlock. */
|
|
1092
|
+
server?: string;
|
|
1093
|
+
}
|
|
1094
|
+
interface ToolSearchToolOptions {
|
|
1095
|
+
/**
|
|
1096
|
+
* Snapshot of every lazy tool the model can discover. Built once per run by
|
|
1097
|
+
* the agent — the tool closes over this array and never mutates it.
|
|
1098
|
+
*/
|
|
1099
|
+
catalog: readonly LazyToolEntry[];
|
|
1100
|
+
/**
|
|
1101
|
+
* Mutable per-run set of unlocked **canonical** tool names. The tool adds
|
|
1102
|
+
* matches in place; the loop reads the set when rebuilding the wire-level
|
|
1103
|
+
* tool list. Keyed by canonical (not wire) so dispatch lookups stay
|
|
1104
|
+
* alias-stable.
|
|
1105
|
+
*/
|
|
1106
|
+
unlocked: Set<string>;
|
|
1107
|
+
/** Default cap on returned matches when the model omits `limit`. */
|
|
1108
|
+
defaultLimit?: number;
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Factory for `tool_search`. Auto-injected by the agent when
|
|
1112
|
+
* `behavior.toolDisclosure === 'lazy'` and at least one MCP tool is in the
|
|
1113
|
+
* registry. Opt out via `behavior.toolSearch.tool === false`.
|
|
1114
|
+
*/
|
|
1115
|
+
declare function createToolSearchTool(options: ToolSearchToolOptions): ToolDef;
|
|
1116
|
+
//#endregion
|
|
1117
|
+
//#region src/tools/validation.d.ts
|
|
1118
|
+
/**
|
|
1119
|
+
* Tool argument validation against JSON Schema-style inputSchema.
|
|
1120
|
+
*
|
|
1121
|
+
* Two passes:
|
|
1122
|
+
* 1. Required-field presence. Missing or null/undefined required fields fail.
|
|
1123
|
+
* 2. Top-level type checks with **best-effort coercion**. Small/OSS models
|
|
1124
|
+
* routinely send `"true"` for a `boolean` field or `"42"` for a `number`,
|
|
1125
|
+
* and rejecting outright forces a confusing retry. Instead, we auto-heal
|
|
1126
|
+
* coerce when the conversion is unambiguous, fail only when the value
|
|
1127
|
+
* cannot be reasonably normalized to any of the declared types.
|
|
1128
|
+
*
|
|
1129
|
+
* Nested validation is intentionally out of scope — keep it cheap and let the
|
|
1130
|
+
* tool's `execute` body assert deeper invariants.
|
|
1131
|
+
*/
|
|
1132
|
+
interface ValidationResult {
|
|
1133
|
+
valid: boolean;
|
|
1134
|
+
/** Human-readable reason. Present on failure only. */
|
|
1135
|
+
error?: string;
|
|
1136
|
+
/**
|
|
1137
|
+
* Possibly-coerced input. Present iff `valid: true`. Tools should call
|
|
1138
|
+
* `execute(coercedInput, ctx)` so auto-healed values reach the tool body.
|
|
1139
|
+
* When no coercion was applied, this is reference-equal to the input.
|
|
1140
|
+
*/
|
|
1141
|
+
coercedInput?: Record<string, unknown>;
|
|
1142
|
+
/**
|
|
1143
|
+
* Names of fields whose values were coerced. Empty when nothing changed.
|
|
1144
|
+
* Useful for telemetry (`validation:reject` on failure already carries the
|
|
1145
|
+
* reason; this is the success-path equivalent).
|
|
1146
|
+
*/
|
|
1147
|
+
coercions?: readonly string[];
|
|
1148
|
+
}
|
|
1149
|
+
declare function validateToolArgs(input: Record<string, unknown>, schema: Record<string, unknown>): ValidationResult;
|
|
1150
|
+
//#endregion
|
|
1151
|
+
//#region src/tools/write-file.d.ts
|
|
1152
|
+
/**
|
|
1153
|
+
* Write a file, with an idempotency signal when the content is unchanged.
|
|
1154
|
+
*
|
|
1155
|
+
* Three return shapes — chosen so the model can recognize a no-op without a
|
|
1156
|
+
* separate read:
|
|
1157
|
+
* - `Created path (N bytes)` — file did not exist
|
|
1158
|
+
* - `Updated path (N bytes)` — content differed from on-disk
|
|
1159
|
+
* - `No change needed: path already at target state (N bytes)` — equal
|
|
1160
|
+
*
|
|
1161
|
+
* Race window: in non-process execution contexts (docker, sandbox) shared by
|
|
1162
|
+
* multiple agents, another writer can mutate the file between our read and
|
|
1163
|
+
* our write. Local process context is single-writer per agent so the race is
|
|
1164
|
+
* a non-issue there. Documented rather than locked because the cost of
|
|
1165
|
+
* cross-context locking outweighs the cost of a stale "No change" message.
|
|
1166
|
+
*/
|
|
1167
|
+
declare const writeFile: ToolDef;
|
|
1168
|
+
//#endregion
|
|
1169
|
+
//#region src/tracing.d.ts
|
|
1170
|
+
/** Minimal span shape — any tracer that provides these two methods is compatible. */
|
|
1171
|
+
interface Span {
|
|
1172
|
+
/** Close the span. Called exactly once per span. */
|
|
1173
|
+
end: () => void;
|
|
1174
|
+
/** Optional: attach additional attributes after the span is started (ignored if unsupported). */
|
|
1175
|
+
setAttributes?: (attrs: Record<string, unknown>) => void;
|
|
1176
|
+
}
|
|
1177
|
+
/** Function that opens a span. Caller-provided so we stay tracer-agnostic. */
|
|
1178
|
+
type StartSpan = (name: string, attrs?: Record<string, unknown>) => Span;
|
|
1179
|
+
interface TracingHooksOptions {
|
|
1180
|
+
/** Tracer seam. Receives a span name + attributes; must return a `Span`. */
|
|
1181
|
+
startSpan: StartSpan;
|
|
1182
|
+
/**
|
|
1183
|
+
* Optional attribute namespace. Prepended to every span name (e.g. `"agent"` →
|
|
1184
|
+
* span names like `agent/turn:0`, `agent/tool:Bash`).
|
|
1185
|
+
*/
|
|
1186
|
+
namespace?: string;
|
|
1187
|
+
}
|
|
1188
|
+
/** Value returned by {@link createTracingHooks} — install entrypoint. */
|
|
1189
|
+
interface TracingHookSet {
|
|
1190
|
+
/**
|
|
1191
|
+
* Attach every hook handler to the given agent hooks instance.
|
|
1192
|
+
*
|
|
1193
|
+
* @returns an `uninstall` function that detaches every handler and closes any
|
|
1194
|
+
* still-open spans. Safe to call multiple times.
|
|
1195
|
+
*/
|
|
1196
|
+
install: (hooks: Hookable<AgentHooks>) => () => void;
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Build a set of tracing hook handlers that can be installed on an agent.
|
|
1200
|
+
*
|
|
1201
|
+
* @example Sentry
|
|
1202
|
+
* ```ts
|
|
1203
|
+
* const tracing = createTracingHooks({
|
|
1204
|
+
* startSpan: (name, attrs) => Sentry.startInactiveSpan({ name, attributes: attrs }),
|
|
1205
|
+
* })
|
|
1206
|
+
* const uninstall = tracing.install(agent.hooks)
|
|
1207
|
+
* try { await agent.run({ prompt }) }
|
|
1208
|
+
* finally { uninstall() }
|
|
1209
|
+
* ```
|
|
1210
|
+
*/
|
|
1211
|
+
declare function createTracingHooks(options: TracingHooksOptions): TracingHookSet;
|
|
1212
|
+
//#endregion
|
|
1213
|
+
//#region src/zod.d.ts
|
|
1214
|
+
/**
|
|
1215
|
+
* Zod v4 integration helper.
|
|
1216
|
+
*
|
|
1217
|
+
* Normalizes the output of z.toJsonSchema() for use as ToolSpec.inputSchema.
|
|
1218
|
+
* Zod is an optional peer dependency — consumers call z.toJsonSchema() themselves.
|
|
1219
|
+
*
|
|
1220
|
+
* Usage:
|
|
1221
|
+
* import { z } from 'zod'
|
|
1222
|
+
* import { zodToJsonSchema } from 'zidane'
|
|
1223
|
+
* const schema = zodToJsonSchema(z.toJsonSchema(z.object({ name: z.string() })))
|
|
1224
|
+
*/
|
|
1225
|
+
/**
|
|
1226
|
+
* Normalize a JSON Schema (e.g. from zod v4's z.toJsonSchema()) for use
|
|
1227
|
+
* as a ToolSpec.inputSchema.
|
|
1228
|
+
*
|
|
1229
|
+
* Strips the $schema key that some providers reject.
|
|
1230
|
+
*/
|
|
1231
|
+
declare function zodToJsonSchema(jsonSchema: Record<string, unknown>): Record<string, unknown>;
|
|
1232
|
+
//#endregion
|
|
1233
|
+
//#region src/presets/basic.d.ts
|
|
1234
|
+
/**
|
|
1235
|
+
* Core tools available in every basic preset (without spawn).
|
|
1236
|
+
*
|
|
1237
|
+
* `edit` and `multi_edit` ship in the basic set because surgical edits are the
|
|
1238
|
+
* default modality for production agents — `write_file` is for full overwrites.
|
|
1239
|
+
* `glob` and `grep` are exported but opt-in: not every agent needs codebase
|
|
1240
|
+
* search, and shipping them by default would force `tool:gate` work onto
|
|
1241
|
+
* consumers that prefer the model to use `shell` + classic Unix tools.
|
|
1242
|
+
*/
|
|
1243
|
+
declare const basicTools: {
|
|
1244
|
+
shell: ToolDef;
|
|
1245
|
+
readFile: ToolDef;
|
|
1246
|
+
writeFile: ToolDef;
|
|
1247
|
+
listFiles: ToolDef;
|
|
1248
|
+
edit: ToolDef;
|
|
1249
|
+
multiEdit: ToolDef;
|
|
1250
|
+
};
|
|
1251
|
+
declare const _default: Preset;
|
|
1252
|
+
//#endregion
|
|
1253
|
+
//#region src/presets/index.d.ts
|
|
1254
|
+
/**
|
|
1255
|
+
* A preset is a reusable slice of `AgentOptions` — spread it into `createAgent()`
|
|
1256
|
+
* to configure tools, a default system prompt, aliases, behavior defaults, and
|
|
1257
|
+
* agent-lifetime hooks.
|
|
1258
|
+
*
|
|
1259
|
+
* `provider`, `execution`, `session`, and internal fields are excluded so presets
|
|
1260
|
+
* remain shareable and composable.
|
|
1261
|
+
*
|
|
1262
|
+
* ```ts
|
|
1263
|
+
* import { basic } from 'zidane/presets'
|
|
1264
|
+
* createAgent({ ...basic, provider })
|
|
1265
|
+
* ```
|
|
1266
|
+
*
|
|
1267
|
+
* ### Composing multiple presets
|
|
1268
|
+
*
|
|
1269
|
+
* Bare `...spread` is shallow — `{ ...a, ...b }` overwrites every key `b`
|
|
1270
|
+
* defines, including `hooks`. Use {@link composePresets} when you want
|
|
1271
|
+
* field-aware merging (per-event hook concat, tools shallow-merge, etc.):
|
|
1272
|
+
*
|
|
1273
|
+
* ```ts
|
|
1274
|
+
* createAgent({ ...composePresets(basic, telemetry, mine), provider })
|
|
1275
|
+
* ```
|
|
1276
|
+
*/
|
|
1277
|
+
type Preset = Omit<Partial<AgentOptions>, 'provider' | 'execution' | 'session' | 'mcpConnector'>;
|
|
1278
|
+
/**
|
|
1279
|
+
* Identity helper for type inference when defining a preset.
|
|
1280
|
+
*/
|
|
1281
|
+
declare function definePreset(config: Preset): Preset;
|
|
1282
|
+
/**
|
|
1283
|
+
* Field-aware composition of presets. Right-most preset wins for scalar fields;
|
|
1284
|
+
* objects shallow-merge; arrays and hook handler lists concatenate. Designed so
|
|
1285
|
+
* stacking presets does the obvious thing without the spread-collision footgun:
|
|
1286
|
+
*
|
|
1287
|
+
* - `name`, `system`, `eager`, `skills` → last-defined wins
|
|
1288
|
+
* - `tools`, `toolAliases`, `behavior` → shallow-merge (later keys override)
|
|
1289
|
+
* - `mcpServers` → concat with last-wins on `name` collision
|
|
1290
|
+
* - `hooks` → per-event concat; every handler fires
|
|
1291
|
+
*
|
|
1292
|
+
* `hooks` always emerges as `event → handler[]` so downstream registration
|
|
1293
|
+
* (in `createAgent`) sees a uniform shape. Order of handlers within an event
|
|
1294
|
+
* follows preset order: earlier presets register first.
|
|
1295
|
+
*
|
|
1296
|
+
* `mcpServers` is deduped by `name` because shipping two servers with the same
|
|
1297
|
+
* name would trip the connector at runtime — a later preset overriding an
|
|
1298
|
+
* earlier preset's `github` server is the practical intent.
|
|
1299
|
+
*/
|
|
1300
|
+
declare function composePresets(...presets: Preset[]): Preset;
|
|
1301
|
+
//#endregion
|
|
1302
|
+
export { PERSISTENCE_PREVIEW_BYTES as $, listFiles as A, buildTailCompactPrompt as At, OAuthCallbackOptions as B, truncateHeadForPtlRetry as Bt, SkillsRunScriptToolOptions as C, CompactPromptBuilder as Ct, shell as D, buildCompactPrompt as Dt, createSkillsReadTool as E, TRAILER as Et, edit as F, SummaryToTurnInput as Ft, loginMcpServer as G, startOAuthCallback as H, ModelUsage as I, anchorPreviewFor as It, McpOAuthProvider as J, McpCredentialEntry as K, flattenTurns as L, sliceForCompaction as Lt, createInteractionTool as M, ANCHOR_PREVIEW_MAX_CHARS as Mt, grep as N, CompactScope as Nt, readFile as O, buildFromCompactPrompt as Ot, glob as P, CompactionSlice as Pt, PERSISTED_STUB_PREFIX as Q, statsByModel as R, stripImagesFromTurns as Rt, createSkillsUseTool as S, CompactDirection as St, SkillsReadToolOptions as T, NO_TOOLS_PREAMBLE as Tt, LoginMcpServerOptions as U, OAuthCallbackResult as V, LoginMcpServerResult as W, createMemoryMcpCredentialStore as X, McpOAuthProviderOptions as Y, hasAuthorizationHeader as Z, ChildAgent as _, CompactResult as _t, basicTools as a, resolvePersistDir as at, createSpawnTool as b, CompactPromptTooLongError as bt, TracingHookSet as c, utf8ByteLength as ct, writeFile as d, RecentFile as dt, PersistInput as et, ValidationResult as f, buildPostCompactAttachments as ft, createToolSearchTool as g, CompactOptions as gt, ToolSearchToolOptions as h, selectRecentFiles as ht, _default as i, maybePersistToolResult as it, InteractionToolOptions as j, buildUpToCompactPrompt as jt, multiEdit as k, buildFullCompactPrompt as kt, TracingHooksOptions as l, PostCompactAttachments as lt, LazyToolEntry as m, selectFilesFromSession as mt, composePresets as n, buildPersistedStub as nt, zodToJsonSchema as o, BYTES_PER_TOKEN as ot, validateToolArgs as p, selectFilesFromReadState as pt, McpCredentialStore as q, definePreset as r, cleanupPersistedSession as rt, Span as s, estimateTokens as st, Preset as t, PersistOutcome as tt, createTracingHooks as u, PostCompactRestoreOptions as ut, SpawnToolOptions as v, compactConversation as vt, createSkillsRunScriptTool as w, CompactPromptOptions as wt, SkillsUseToolOptions as x, BASE_INSTRUCTIONS as xt, SpawnToolState as y, CompactInvalidInputError as yt, OAuthCallbackHandle as z, summaryToTurn as zt };
|
|
1303
|
+
//# sourceMappingURL=index-CFxhms_B.d.ts.map
|