framework-agents 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,2842 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Content blocks — standard, provider-neutral message payload
5
+ * Standard message payload: text, reasoning, multimodal and tool-call blocks.
6
+ * `content` stays `string | ContentBlock[]`: strings for simple cases,
7
+ * blocks for multimodal / reasoning / tool-call payloads.
8
+ */
9
+ declare const TextBlockSchema: z.ZodObject<{
10
+ type: z.ZodLiteral<"text">;
11
+ text: z.ZodString;
12
+ }, "strip", z.ZodTypeAny, {
13
+ type: "text";
14
+ text: string;
15
+ }, {
16
+ type: "text";
17
+ text: string;
18
+ }>;
19
+ declare const ReasoningBlockSchema: z.ZodObject<{
20
+ type: z.ZodLiteral<"reasoning">;
21
+ reasoning: z.ZodString;
22
+ }, "strip", z.ZodTypeAny, {
23
+ type: "reasoning";
24
+ reasoning: string;
25
+ }, {
26
+ type: "reasoning";
27
+ reasoning: string;
28
+ }>;
29
+ declare const ImageBlockSchema: z.ZodObject<{
30
+ type: z.ZodLiteral<"image">;
31
+ url: z.ZodOptional<z.ZodString>;
32
+ data: z.ZodOptional<z.ZodString>;
33
+ mimeType: z.ZodOptional<z.ZodString>;
34
+ fileId: z.ZodOptional<z.ZodString>;
35
+ }, "strip", z.ZodTypeAny, {
36
+ type: "image";
37
+ url?: string | undefined;
38
+ data?: string | undefined;
39
+ mimeType?: string | undefined;
40
+ fileId?: string | undefined;
41
+ }, {
42
+ type: "image";
43
+ url?: string | undefined;
44
+ data?: string | undefined;
45
+ mimeType?: string | undefined;
46
+ fileId?: string | undefined;
47
+ }>;
48
+ declare const AudioBlockSchema: z.ZodObject<{
49
+ type: z.ZodLiteral<"audio">;
50
+ url: z.ZodOptional<z.ZodString>;
51
+ data: z.ZodOptional<z.ZodString>;
52
+ mimeType: z.ZodOptional<z.ZodString>;
53
+ fileId: z.ZodOptional<z.ZodString>;
54
+ }, "strip", z.ZodTypeAny, {
55
+ type: "audio";
56
+ url?: string | undefined;
57
+ data?: string | undefined;
58
+ mimeType?: string | undefined;
59
+ fileId?: string | undefined;
60
+ }, {
61
+ type: "audio";
62
+ url?: string | undefined;
63
+ data?: string | undefined;
64
+ mimeType?: string | undefined;
65
+ fileId?: string | undefined;
66
+ }>;
67
+ declare const FileBlockSchema: z.ZodObject<{
68
+ type: z.ZodLiteral<"file">;
69
+ url: z.ZodOptional<z.ZodString>;
70
+ data: z.ZodOptional<z.ZodString>;
71
+ mimeType: z.ZodOptional<z.ZodString>;
72
+ fileId: z.ZodOptional<z.ZodString>;
73
+ }, "strip", z.ZodTypeAny, {
74
+ type: "file";
75
+ url?: string | undefined;
76
+ data?: string | undefined;
77
+ mimeType?: string | undefined;
78
+ fileId?: string | undefined;
79
+ }, {
80
+ type: "file";
81
+ url?: string | undefined;
82
+ data?: string | undefined;
83
+ mimeType?: string | undefined;
84
+ fileId?: string | undefined;
85
+ }>;
86
+ declare const ToolCallBlockSchema: z.ZodObject<{
87
+ type: z.ZodLiteral<"tool_call">;
88
+ id: z.ZodString;
89
+ name: z.ZodString;
90
+ args: z.ZodUnknown;
91
+ }, "strip", z.ZodTypeAny, {
92
+ type: "tool_call";
93
+ id: string;
94
+ name: string;
95
+ args?: unknown;
96
+ }, {
97
+ type: "tool_call";
98
+ id: string;
99
+ name: string;
100
+ args?: unknown;
101
+ }>;
102
+ declare const NonStandardBlockSchema: z.ZodObject<{
103
+ type: z.ZodLiteral<"non_standard">;
104
+ value: z.ZodUnknown;
105
+ }, "strip", z.ZodTypeAny, {
106
+ type: "non_standard";
107
+ value?: unknown;
108
+ }, {
109
+ type: "non_standard";
110
+ value?: unknown;
111
+ }>;
112
+ declare const ContentBlockSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
113
+ type: z.ZodLiteral<"text">;
114
+ text: z.ZodString;
115
+ }, "strip", z.ZodTypeAny, {
116
+ type: "text";
117
+ text: string;
118
+ }, {
119
+ type: "text";
120
+ text: string;
121
+ }>, z.ZodObject<{
122
+ type: z.ZodLiteral<"reasoning">;
123
+ reasoning: z.ZodString;
124
+ }, "strip", z.ZodTypeAny, {
125
+ type: "reasoning";
126
+ reasoning: string;
127
+ }, {
128
+ type: "reasoning";
129
+ reasoning: string;
130
+ }>, z.ZodObject<{
131
+ type: z.ZodLiteral<"image">;
132
+ url: z.ZodOptional<z.ZodString>;
133
+ data: z.ZodOptional<z.ZodString>;
134
+ mimeType: z.ZodOptional<z.ZodString>;
135
+ fileId: z.ZodOptional<z.ZodString>;
136
+ }, "strip", z.ZodTypeAny, {
137
+ type: "image";
138
+ url?: string | undefined;
139
+ data?: string | undefined;
140
+ mimeType?: string | undefined;
141
+ fileId?: string | undefined;
142
+ }, {
143
+ type: "image";
144
+ url?: string | undefined;
145
+ data?: string | undefined;
146
+ mimeType?: string | undefined;
147
+ fileId?: string | undefined;
148
+ }>, z.ZodObject<{
149
+ type: z.ZodLiteral<"audio">;
150
+ url: z.ZodOptional<z.ZodString>;
151
+ data: z.ZodOptional<z.ZodString>;
152
+ mimeType: z.ZodOptional<z.ZodString>;
153
+ fileId: z.ZodOptional<z.ZodString>;
154
+ }, "strip", z.ZodTypeAny, {
155
+ type: "audio";
156
+ url?: string | undefined;
157
+ data?: string | undefined;
158
+ mimeType?: string | undefined;
159
+ fileId?: string | undefined;
160
+ }, {
161
+ type: "audio";
162
+ url?: string | undefined;
163
+ data?: string | undefined;
164
+ mimeType?: string | undefined;
165
+ fileId?: string | undefined;
166
+ }>, z.ZodObject<{
167
+ type: z.ZodLiteral<"file">;
168
+ url: z.ZodOptional<z.ZodString>;
169
+ data: z.ZodOptional<z.ZodString>;
170
+ mimeType: z.ZodOptional<z.ZodString>;
171
+ fileId: z.ZodOptional<z.ZodString>;
172
+ }, "strip", z.ZodTypeAny, {
173
+ type: "file";
174
+ url?: string | undefined;
175
+ data?: string | undefined;
176
+ mimeType?: string | undefined;
177
+ fileId?: string | undefined;
178
+ }, {
179
+ type: "file";
180
+ url?: string | undefined;
181
+ data?: string | undefined;
182
+ mimeType?: string | undefined;
183
+ fileId?: string | undefined;
184
+ }>, z.ZodObject<{
185
+ type: z.ZodLiteral<"tool_call">;
186
+ id: z.ZodString;
187
+ name: z.ZodString;
188
+ args: z.ZodUnknown;
189
+ }, "strip", z.ZodTypeAny, {
190
+ type: "tool_call";
191
+ id: string;
192
+ name: string;
193
+ args?: unknown;
194
+ }, {
195
+ type: "tool_call";
196
+ id: string;
197
+ name: string;
198
+ args?: unknown;
199
+ }>, z.ZodObject<{
200
+ type: z.ZodLiteral<"non_standard">;
201
+ value: z.ZodUnknown;
202
+ }, "strip", z.ZodTypeAny, {
203
+ type: "non_standard";
204
+ value?: unknown;
205
+ }, {
206
+ type: "non_standard";
207
+ value?: unknown;
208
+ }>]>;
209
+ type ContentBlock = z.infer<typeof ContentBlockSchema>;
210
+ type TextBlock = z.infer<typeof TextBlockSchema>;
211
+ type ReasoningBlock = z.infer<typeof ReasoningBlockSchema>;
212
+ type ImageBlock = z.infer<typeof ImageBlockSchema>;
213
+ /** Plain-text view of any content shape — what the model "reads". */
214
+ declare function textOf(content: string | ContentBlock[]): string;
215
+ /**
216
+ * Text for re-sending history to a provider: reasoning blocks are dropped —
217
+ * a model's own past thinking must not come back as ordinary assistant text
218
+ * (duplicated context, and Anthropic rejects thinking-as-text turns).
219
+ */
220
+ declare function wireTextOf(content: string | ContentBlock[]): string;
221
+ declare function hasImages(content: string | ContentBlock[]): boolean;
222
+ /** Images in wire-ready form (url or base64 data). */
223
+ declare function imagesOf(content: string | ContentBlock[]): {
224
+ url?: string;
225
+ data?: string;
226
+ mimeType?: string;
227
+ }[];
228
+
229
+ type Brand<T, B extends string> = T & {
230
+ readonly __brand: B;
231
+ };
232
+ type AgentId = Brand<string, "AgentId">;
233
+ type RunId = Brand<string, "RunId">;
234
+ type ToolName = Brand<string, "ToolName">;
235
+ declare const ChatMessageSchema: z.ZodObject<{
236
+ id: z.ZodOptional<z.ZodString>;
237
+ role: z.ZodEnum<["system", "user", "assistant", "tool"]>;
238
+ content: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
239
+ type: z.ZodLiteral<"text">;
240
+ text: z.ZodString;
241
+ }, "strip", z.ZodTypeAny, {
242
+ type: "text";
243
+ text: string;
244
+ }, {
245
+ type: "text";
246
+ text: string;
247
+ }>, z.ZodObject<{
248
+ type: z.ZodLiteral<"reasoning">;
249
+ reasoning: z.ZodString;
250
+ }, "strip", z.ZodTypeAny, {
251
+ type: "reasoning";
252
+ reasoning: string;
253
+ }, {
254
+ type: "reasoning";
255
+ reasoning: string;
256
+ }>, z.ZodObject<{
257
+ type: z.ZodLiteral<"image">;
258
+ url: z.ZodOptional<z.ZodString>;
259
+ data: z.ZodOptional<z.ZodString>;
260
+ mimeType: z.ZodOptional<z.ZodString>;
261
+ fileId: z.ZodOptional<z.ZodString>;
262
+ }, "strip", z.ZodTypeAny, {
263
+ type: "image";
264
+ url?: string | undefined;
265
+ data?: string | undefined;
266
+ mimeType?: string | undefined;
267
+ fileId?: string | undefined;
268
+ }, {
269
+ type: "image";
270
+ url?: string | undefined;
271
+ data?: string | undefined;
272
+ mimeType?: string | undefined;
273
+ fileId?: string | undefined;
274
+ }>, z.ZodObject<{
275
+ type: z.ZodLiteral<"audio">;
276
+ url: z.ZodOptional<z.ZodString>;
277
+ data: z.ZodOptional<z.ZodString>;
278
+ mimeType: z.ZodOptional<z.ZodString>;
279
+ fileId: z.ZodOptional<z.ZodString>;
280
+ }, "strip", z.ZodTypeAny, {
281
+ type: "audio";
282
+ url?: string | undefined;
283
+ data?: string | undefined;
284
+ mimeType?: string | undefined;
285
+ fileId?: string | undefined;
286
+ }, {
287
+ type: "audio";
288
+ url?: string | undefined;
289
+ data?: string | undefined;
290
+ mimeType?: string | undefined;
291
+ fileId?: string | undefined;
292
+ }>, z.ZodObject<{
293
+ type: z.ZodLiteral<"file">;
294
+ url: z.ZodOptional<z.ZodString>;
295
+ data: z.ZodOptional<z.ZodString>;
296
+ mimeType: z.ZodOptional<z.ZodString>;
297
+ fileId: z.ZodOptional<z.ZodString>;
298
+ }, "strip", z.ZodTypeAny, {
299
+ type: "file";
300
+ url?: string | undefined;
301
+ data?: string | undefined;
302
+ mimeType?: string | undefined;
303
+ fileId?: string | undefined;
304
+ }, {
305
+ type: "file";
306
+ url?: string | undefined;
307
+ data?: string | undefined;
308
+ mimeType?: string | undefined;
309
+ fileId?: string | undefined;
310
+ }>, z.ZodObject<{
311
+ type: z.ZodLiteral<"tool_call">;
312
+ id: z.ZodString;
313
+ name: z.ZodString;
314
+ args: z.ZodUnknown;
315
+ }, "strip", z.ZodTypeAny, {
316
+ type: "tool_call";
317
+ id: string;
318
+ name: string;
319
+ args?: unknown;
320
+ }, {
321
+ type: "tool_call";
322
+ id: string;
323
+ name: string;
324
+ args?: unknown;
325
+ }>, z.ZodObject<{
326
+ type: z.ZodLiteral<"non_standard">;
327
+ value: z.ZodUnknown;
328
+ }, "strip", z.ZodTypeAny, {
329
+ type: "non_standard";
330
+ value?: unknown;
331
+ }, {
332
+ type: "non_standard";
333
+ value?: unknown;
334
+ }>]>, "many">]>;
335
+ /** Provider user-identification; behavior varies, optional. */
336
+ name: z.ZodOptional<z.ZodString>;
337
+ toolCallId: z.ZodOptional<z.ZodString>;
338
+ toolName: z.ZodOptional<z.ZodString>;
339
+ /** Pinned messages survive conversation-manager trimming. */
340
+ pinned: z.ZodOptional<z.ZodBoolean>;
341
+ }, "strip", z.ZodTypeAny, {
342
+ role: "system" | "user" | "assistant" | "tool";
343
+ content: string | ({
344
+ type: "text";
345
+ text: string;
346
+ } | {
347
+ type: "reasoning";
348
+ reasoning: string;
349
+ } | {
350
+ type: "image";
351
+ url?: string | undefined;
352
+ data?: string | undefined;
353
+ mimeType?: string | undefined;
354
+ fileId?: string | undefined;
355
+ } | {
356
+ type: "audio";
357
+ url?: string | undefined;
358
+ data?: string | undefined;
359
+ mimeType?: string | undefined;
360
+ fileId?: string | undefined;
361
+ } | {
362
+ type: "file";
363
+ url?: string | undefined;
364
+ data?: string | undefined;
365
+ mimeType?: string | undefined;
366
+ fileId?: string | undefined;
367
+ } | {
368
+ type: "tool_call";
369
+ id: string;
370
+ name: string;
371
+ args?: unknown;
372
+ } | {
373
+ type: "non_standard";
374
+ value?: unknown;
375
+ })[];
376
+ id?: string | undefined;
377
+ name?: string | undefined;
378
+ toolCallId?: string | undefined;
379
+ toolName?: string | undefined;
380
+ pinned?: boolean | undefined;
381
+ }, {
382
+ role: "system" | "user" | "assistant" | "tool";
383
+ content: string | ({
384
+ type: "text";
385
+ text: string;
386
+ } | {
387
+ type: "reasoning";
388
+ reasoning: string;
389
+ } | {
390
+ type: "image";
391
+ url?: string | undefined;
392
+ data?: string | undefined;
393
+ mimeType?: string | undefined;
394
+ fileId?: string | undefined;
395
+ } | {
396
+ type: "audio";
397
+ url?: string | undefined;
398
+ data?: string | undefined;
399
+ mimeType?: string | undefined;
400
+ fileId?: string | undefined;
401
+ } | {
402
+ type: "file";
403
+ url?: string | undefined;
404
+ data?: string | undefined;
405
+ mimeType?: string | undefined;
406
+ fileId?: string | undefined;
407
+ } | {
408
+ type: "tool_call";
409
+ id: string;
410
+ name: string;
411
+ args?: unknown;
412
+ } | {
413
+ type: "non_standard";
414
+ value?: unknown;
415
+ })[];
416
+ id?: string | undefined;
417
+ name?: string | undefined;
418
+ toolCallId?: string | undefined;
419
+ toolName?: string | undefined;
420
+ pinned?: boolean | undefined;
421
+ }>;
422
+ interface ChatMessage {
423
+ id?: string;
424
+ role: "system" | "user" | "assistant" | "tool";
425
+ content: string | ContentBlock[];
426
+ name?: string;
427
+ toolCallId?: string;
428
+ toolName?: string;
429
+ pinned?: boolean;
430
+ }
431
+ interface AgentResult {
432
+ text: string;
433
+ messages: ChatMessage[];
434
+ toolCalls: ExecutedToolCall[];
435
+ usage: TokenUsage;
436
+ /** Typed answer when the agent ran with `responseFormat`. */
437
+ structuredResponse?: unknown;
438
+ /** The invocation state object (same reference mutated during the run). */
439
+ invocationState?: Record<string, unknown>;
440
+ }
441
+ interface ExecutedToolCall {
442
+ id: string;
443
+ name: string;
444
+ args: unknown;
445
+ output: unknown;
446
+ /** Downstream-only data (never sent to the model). See Tool.toResult. */
447
+ artifact?: unknown;
448
+ }
449
+ interface TokenUsage {
450
+ inputTokens: number;
451
+ outputTokens: number;
452
+ /**
453
+ * Reasoning/thinking tokens, when the provider reports them. A SUBSET of
454
+ * `outputTokens` on every supported provider — count for reporting, never
455
+ * add on top for budgets or cost.
456
+ */
457
+ reasoningTokens?: number;
458
+ /** USD cost, when a price is known (see models/pricing). Never guessed. */
459
+ costUsd?: number;
460
+ }
461
+ type Result<T, E = AgentError> = {
462
+ ok: true;
463
+ value: T;
464
+ } | {
465
+ ok: false;
466
+ error: E;
467
+ };
468
+ declare class AgentError extends Error {
469
+ readonly code: string;
470
+ readonly retryable: boolean;
471
+ constructor(code: string, message: string, retryable?: boolean);
472
+ }
473
+ /** Factory helpers — stable ids, no class hierarchy. */
474
+ declare function system(content: string | ContentBlock[]): ChatMessage;
475
+ declare function user(content: string | ContentBlock[], opts?: {
476
+ id?: string;
477
+ name?: string;
478
+ }): ChatMessage;
479
+ declare function assistant(content: string | ContentBlock[]): ChatMessage;
480
+ declare function toolResult(toolCallId: string, toolName: string, content: string | ContentBlock[]): ChatMessage;
481
+ /** Serialize history for persistence (plain JSON-safe objects). */
482
+ declare function serializeMessages(messages: ChatMessage[]): unknown[];
483
+ /** Deserialize + validate history (e.g. resume from disk). Throws on bad shape. */
484
+ declare function deserializeMessages(raw: unknown[]): ChatMessage[];
485
+
486
+ declare const ConfigSchema: z.ZodObject<{
487
+ TOGETHER_API_KEY: z.ZodDefault<z.ZodString>;
488
+ TOGETHER_BASE_URL: z.ZodDefault<z.ZodString>;
489
+ /** Small chat default — one model, no tiers. */
490
+ TOGETHER_MODEL: z.ZodDefault<z.ZodString>;
491
+ OPENAI_BASE_URL: z.ZodDefault<z.ZodString>;
492
+ OPENAI_API_KEY: z.ZodDefault<z.ZodString>;
493
+ OPENAI_MODEL: z.ZodDefault<z.ZodString>;
494
+ ANTHROPIC_API_KEY: z.ZodDefault<z.ZodString>;
495
+ ANTHROPIC_BASE_URL: z.ZodDefault<z.ZodString>;
496
+ ANTHROPIC_MODEL: z.ZodDefault<z.ZodString>;
497
+ OLLAMA_BASE_URL: z.ZodDefault<z.ZodString>;
498
+ OLLAMA_MODEL: z.ZodDefault<z.ZodString>;
499
+ E2E_MODEL: z.ZodDefault<z.ZodString>;
500
+ }, "strip", z.ZodTypeAny, {
501
+ TOGETHER_API_KEY: string;
502
+ TOGETHER_BASE_URL: string;
503
+ TOGETHER_MODEL: string;
504
+ OPENAI_BASE_URL: string;
505
+ OPENAI_API_KEY: string;
506
+ OPENAI_MODEL: string;
507
+ ANTHROPIC_API_KEY: string;
508
+ ANTHROPIC_BASE_URL: string;
509
+ ANTHROPIC_MODEL: string;
510
+ OLLAMA_BASE_URL: string;
511
+ OLLAMA_MODEL: string;
512
+ E2E_MODEL: string;
513
+ }, {
514
+ TOGETHER_API_KEY?: string | undefined;
515
+ TOGETHER_BASE_URL?: string | undefined;
516
+ TOGETHER_MODEL?: string | undefined;
517
+ OPENAI_BASE_URL?: string | undefined;
518
+ OPENAI_API_KEY?: string | undefined;
519
+ OPENAI_MODEL?: string | undefined;
520
+ ANTHROPIC_API_KEY?: string | undefined;
521
+ ANTHROPIC_BASE_URL?: string | undefined;
522
+ ANTHROPIC_MODEL?: string | undefined;
523
+ OLLAMA_BASE_URL?: string | undefined;
524
+ OLLAMA_MODEL?: string | undefined;
525
+ E2E_MODEL?: string | undefined;
526
+ }>;
527
+ type FrameworkConfig = z.infer<typeof ConfigSchema> & {
528
+ /** Resolved provider settings: TogetherAI wins when its key is set. */
529
+ active: {
530
+ baseUrl: string;
531
+ apiKey: string;
532
+ model: string;
533
+ source: "together" | "openai";
534
+ };
535
+ };
536
+ declare function loadConfig(env?: NodeJS.ProcessEnv): FrameworkConfig;
537
+ /** Test-only: clear cache so tests can pass custom env objects. */
538
+ declare function __resetConfig(): void;
539
+
540
+ /**
541
+ * Typed run events with independent projections.
542
+ * Consume via `for await (const e of agent.stream(input))`.
543
+ */
544
+ type StreamEvent = {
545
+ type: "step";
546
+ step: number;
547
+ } | {
548
+ type: "token";
549
+ delta: string;
550
+ } | {
551
+ type: "thinking";
552
+ delta: string;
553
+ } | {
554
+ type: "tool_call";
555
+ name: string;
556
+ args: unknown;
557
+ } | {
558
+ type: "tool_result";
559
+ name: string;
560
+ output: unknown;
561
+ } | {
562
+ type: "done";
563
+ text: string;
564
+ };
565
+ /** Collect a stream into buckets — handy for tests and simple UIs. */
566
+ declare function collectStream(stream: AsyncGenerator<StreamEvent, AgentResult>): Promise<{
567
+ events: StreamEvent[];
568
+ result: AgentResult;
569
+ }>;
570
+
571
+ /**
572
+ * State in three lifetimes:
573
+ * - Conversation history: messages (model-visible), via Memory.
574
+ * - Agent state: validated JSON key-value store, NEVER sent to the model.
575
+ * - Invocation state: per-run data + request handle, shared by reference
576
+ * across hooks and tools within one run, returned on the result.
577
+ */
578
+ type InvocationState = Record<string, unknown>;
579
+ /** Key-value store outside the model context. Tools + app logic read/write freely. */
580
+ declare class AgentState {
581
+ private data;
582
+ constructor(initial?: Record<string, unknown>);
583
+ get<T = unknown>(key?: string): T | Record<string, unknown> | undefined;
584
+ set(key: string, value: unknown): void;
585
+ delete(key: string): void;
586
+ /** Plain-object copy for snapshots/persistence. */
587
+ toJSON(): Record<string, unknown>;
588
+ static fromJSON(raw: Record<string, unknown>): AgentState;
589
+ }
590
+ /** What tools receive: agent identity + state + per-run invocation state. */
591
+ interface ToolContext {
592
+ agentName: string;
593
+ state: AgentState;
594
+ invocationState: InvocationState;
595
+ }
596
+
597
+ interface OpenAICompatibleOptions {
598
+ baseUrl: string;
599
+ apiKey: string;
600
+ model: string;
601
+ temperature?: number;
602
+ maxTokens?: number;
603
+ /** Stream responses (SSE) so text + thinking tokens flow via callbacks. Default false. */
604
+ stream?: boolean;
605
+ /** fetch-compatible; injectable for tests. Defaults to global fetch. */
606
+ fetchFn?: typeof fetch;
607
+ }
608
+ /**
609
+ * Minimal OpenAI-compatible chat provider (OpenAI, TogetherAI, vLLM, etc.).
610
+ * POST {baseUrl}/chat/completions with tools; no SDK dependency.
611
+ * - Images: fail fast with MODEL_CAPABILITY when the model can't see.
612
+ * - Thinking: reasoning_content streams through onThinking (SSE when stream: true).
613
+ */
614
+ declare class OpenAICompatibleProvider implements ModelProvider {
615
+ readonly id: string;
616
+ readonly capabilities: {
617
+ structuredOutput: boolean;
618
+ streaming: boolean;
619
+ };
620
+ private opts;
621
+ constructor(opts: OpenAICompatibleOptions);
622
+ complete(options: CompleteOptions): Promise<ModelCompletion>;
623
+ private readJson;
624
+ /** SSE: `data: {...}` lines; delta.content -> onToken, delta.reasoning_content -> onThinking. */
625
+ private readStream;
626
+ }
627
+ /** Build a provider from env config (TogetherAI preferred when key present). */
628
+ declare function providerFromEnv(active: {
629
+ baseUrl: string;
630
+ apiKey: string;
631
+ model: string;
632
+ }, extra?: Partial<OpenAICompatibleOptions>): OpenAICompatibleProvider;
633
+
634
+ /**
635
+ * Model capability registry — researched defaults live here so users never
636
+ * pick tiers. Full per-model research (vision, tools, reasoning, context
637
+ * limits) lands later; until then: explicit allowlist + fail-fast error.
638
+ */
639
+ type ModelCapability = "vision" | "tools" | "reasoning-stream";
640
+ declare function supportsVision(modelId: string): boolean;
641
+ /** Throw AgentError(MODEL_CAPABILITY) when input needs vision the model lacks. */
642
+ declare function assertCanHandle(modelId: string, needsVision: boolean): void;
643
+
644
+ /**
645
+ * Resolve `provider:model` strings to a configured provider.
646
+ * - `together:<id>` / bare `<id>` → TogetherAI (TOGETHER_API_KEY)
647
+ * - `openai:<id>` → OpenAI (OPENAI_API_KEY)
648
+ * - `anthropic:<id>` → Anthropic native API (ANTHROPIC_API_KEY)
649
+ * - `ollama:<id>` → local Ollama (no key; OLLAMA_BASE_URL or localhost:11434)
650
+ * - `custom:<id>` + baseUrl/apiKey → any OpenAI-compatible endpoint
651
+ */
652
+ declare function initChatModel(spec: string, opts?: {
653
+ apiKey?: string;
654
+ baseUrl?: string;
655
+ temperature?: number;
656
+ maxTokens?: number;
657
+ stream?: boolean;
658
+ thinkingBudget?: number;
659
+ }): ModelProvider;
660
+
661
+ interface AnthropicOptions {
662
+ apiKey: string;
663
+ model: string;
664
+ baseUrl?: string;
665
+ maxTokens?: number;
666
+ temperature?: number;
667
+ /** Extended thinking budget (tokens). Enables thinking blocks. */
668
+ thinkingBudget?: number;
669
+ stream?: boolean;
670
+ fetchFn?: typeof fetch;
671
+ }
672
+ /**
673
+ * Native Anthropic Messages API (fetch-based, no SDK).
674
+ * - tools become `tools` with input_schema; tool results become tool_result blocks
675
+ * - thinking blocks stream/return via onThinking
676
+ * - no native json_schema mode: capabilities.structuredOutput is false,
677
+ * so `auto` responseFormat correctly falls back to the tool strategy
678
+ */
679
+ declare class AnthropicProvider implements ModelProvider {
680
+ readonly id: string;
681
+ readonly capabilities: {
682
+ structuredOutput: boolean;
683
+ streaming: boolean;
684
+ };
685
+ private opts;
686
+ constructor(opts: AnthropicOptions);
687
+ complete(options: CompleteOptions): Promise<ModelCompletion>;
688
+ private toCompletion;
689
+ private readJson;
690
+ private readStream;
691
+ }
692
+
693
+ interface OllamaOptions {
694
+ model: string;
695
+ /** Defaults to local Ollama. No key needed. */
696
+ baseUrl?: string;
697
+ temperature?: number;
698
+ maxTokens?: number;
699
+ stream?: boolean;
700
+ fetchFn?: typeof fetch;
701
+ }
702
+ /**
703
+ * Local-first Ollama provider via its OpenAI-compatible endpoint.
704
+ * No API key, no account, no network beyond localhost. Tool support
705
+ * depends on the model (qwen2.5, llama3.1+ work well).
706
+ * structuredOutput stays false → `auto` format uses the tool strategy.
707
+ */
708
+ declare class OllamaProvider extends OpenAICompatibleProvider {
709
+ readonly id: string;
710
+ readonly capabilities: {
711
+ structuredOutput: boolean;
712
+ streaming: boolean;
713
+ };
714
+ constructor(opts: OllamaOptions);
715
+ }
716
+ declare function ollama(opts: OllamaOptions): OllamaProvider;
717
+
718
+ /**
719
+ * Per-model prices (USD per 1M tokens). Researched defaults — verify against
720
+ * your provider bill: cloud prices change, and dedicated/self-hosted
721
+ * endpoints (Ollama, vLLM) cost $0 in API terms.
722
+ *
723
+ * Why a table: TogetherAI/OpenAI-compatible and Anthropic usage payloads
724
+ * carry token counts ONLY (no cost field). Cost is always computed
725
+ * client-side as usage × price. (OpenRouter is the exception — it returns
726
+ * cost directly; nothing to do there.)
727
+ */
728
+ interface ModelPrice {
729
+ inputPerMillion: number;
730
+ outputPerMillion: number;
731
+ }
732
+ /** Look up a price by bare model id (provider prefixes like `openai:`/`ollama:` are stripped). */
733
+ declare function priceFor(modelId: string): ModelPrice | undefined;
734
+ /**
735
+ * USD cost for usage; unknown models return undefined (never a misleading zero).
736
+ * `outputTokens` already includes reasoning tokens on every supported provider
737
+ * (OpenAI: reasoning_tokens ⊂ completion_tokens; Anthropic: thinking ⊂ output_tokens),
738
+ * so they are billed at the output rate with no extra addition.
739
+ */
740
+ declare function usageCost(usage: TokenUsage, modelId: string, override?: ModelPrice): number | undefined;
741
+
742
+ interface ToolCallRequest {
743
+ /** Provider tool-call id; generated when the provider omits it. */
744
+ id: string;
745
+ name: string;
746
+ args: unknown;
747
+ }
748
+ interface ModelCompletion {
749
+ text: string;
750
+ /** Thinking/reasoning trace, when the provider exposes it. */
751
+ thinking?: string;
752
+ toolCalls: ToolCallRequest[];
753
+ usage: TokenUsage;
754
+ /**
755
+ * Provider stop reason when reported ("stop", "length"/"max_tokens",
756
+ * "tool_calls", ...). Consumers can detect truncation; a TOTAL truncation
757
+ * (no content at all) throws MODEL_ERROR at the provider instead.
758
+ */
759
+ finishReason?: string;
760
+ }
761
+ interface ResponseFormatWire {
762
+ name: string;
763
+ schema: Record<string, unknown>;
764
+ strict?: boolean;
765
+ }
766
+ interface CompleteOptions {
767
+ messages: ChatMessage[];
768
+ /** Tool metadata; `parametersSchema` (JSON Schema) lets models call with real args — omit only for zero-arg tools. */
769
+ tools: {
770
+ name: string;
771
+ description: string;
772
+ parametersSchema?: Record<string, unknown>;
773
+ }[];
774
+ /** Native structured output (OpenAI `response_format`). Honored when the provider supports it. */
775
+ responseFormat?: ResponseFormatWire;
776
+ /** Streamed text deltas (non-thinking). */
777
+ onToken?: (delta: string) => void;
778
+ /** Streamed thinking/reasoning deltas (reasoning_content). */
779
+ onThinking?: (delta: string) => void;
780
+ /** Aborts the in-flight provider request (fetch). */
781
+ signal?: AbortSignal;
782
+ }
783
+ /** Provider abstraction — implement OpenAI/Anthropic/etc. behind this. */
784
+ interface ModelProvider {
785
+ readonly id: string;
786
+ readonly capabilities?: {
787
+ structuredOutput?: boolean;
788
+ vision?: boolean;
789
+ streaming?: boolean;
790
+ };
791
+ complete(options: CompleteOptions): Promise<ModelCompletion>;
792
+ }
793
+ /** Deterministic mock for tests/examples — no network. */
794
+ declare class MockModelProvider implements ModelProvider {
795
+ readonly id = "mock";
796
+ readonly capabilities: {
797
+ structuredOutput: boolean;
798
+ streaming: boolean;
799
+ };
800
+ private calls;
801
+ complete(_options: CompleteOptions): Promise<ModelCompletion>;
802
+ }
803
+
804
+ interface ToolResult {
805
+ /** Model-visible content (string or blocks). */
806
+ content: string | ContentBlock[];
807
+ /** Downstream-only data — stored on the call record, never sent to the model. */
808
+ artifact?: unknown;
809
+ }
810
+ interface Tool<TArgs = any, TOutput = any> {
811
+ name: string;
812
+ description: string;
813
+ schema: z.ZodType<TArgs>;
814
+ /** Optional second arg receives ToolContext (state + invocationState). */
815
+ execute: (args: TArgs, ctx?: ToolContext) => Promise<TOutput>;
816
+ /**
817
+ * Split raw output into model-visible content + downstream artifact.
818
+ * Default: JSON/string content, no artifact. Override to keep raw payloads
819
+ * (retrieval metadata, debug blobs) out of the model's context.
820
+ */
821
+ toResult?: (output: any) => ToolResult;
822
+ }
823
+ declare function defaultToResult(output: unknown): ToolResult;
824
+ declare function defineTool<TArgs, TOutput>(tool: Tool<TArgs, TOutput>): Tool<TArgs, TOutput>;
825
+ /** Validating registry — single place tools are looked up + arg-checked. */
826
+ declare class ToolRegistry {
827
+ private tools;
828
+ register(tool: Tool): this;
829
+ get(name: string): Tool | undefined;
830
+ list(): Tool[];
831
+ call<T>(name: string, rawArgs: unknown): Promise<T>;
832
+ }
833
+
834
+ /**
835
+ * Middleware — control the agent loop without forking it.
836
+ *
837
+ * Execution order:
838
+ * - beforeModel / beforeTool: registration order
839
+ * - afterModel / afterTool: REVERSE order
840
+ * - wrapModel / aroundTool: nested, first registered = outermost
841
+ */
842
+ interface HookContext {
843
+ step: number;
844
+ /** Per-run data, shared by reference (never sent to the model). */
845
+ invocationState?: InvocationState;
846
+ }
847
+ interface ModelRequest {
848
+ messages: ChatMessage[];
849
+ tools: {
850
+ name: string;
851
+ description: string;
852
+ parametersSchema?: Record<string, unknown>;
853
+ }[];
854
+ responseFormat?: ResponseFormatWire;
855
+ }
856
+ interface ToolCallRef {
857
+ name: string;
858
+ args: unknown;
859
+ }
860
+ interface AgentMiddleware {
861
+ name: string;
862
+ /** Tools contributed by this middleware (merged into the agent's tool list). */
863
+ tools?: Tool[];
864
+ beforeModel?: (req: ModelRequest, ctx: HookContext) => Promise<ModelRequest | undefined> | ModelRequest | undefined;
865
+ wrapModel?: (req: ModelRequest, next: (req: ModelRequest) => Promise<ModelCompletion>, ctx: HookContext) => Promise<ModelCompletion>;
866
+ afterModel?: (res: ModelCompletion, req: ModelRequest, ctx: HookContext) => Promise<ModelCompletion | undefined> | ModelCompletion | undefined;
867
+ beforeTool?: (call: ToolCallRef, ctx: HookContext) => Promise<ToolCallRef | undefined> | ToolCallRef | undefined;
868
+ aroundTool?: (call: ToolCallRef, next: () => Promise<unknown>, ctx: HookContext) => Promise<unknown>;
869
+ afterTool?: (call: ToolCallRef, output: unknown, ctx: HookContext) => Promise<unknown> | unknown;
870
+ }
871
+ /** Identity factory — documents intent and locks the type. */
872
+ declare function createMiddleware(m: AgentMiddleware): AgentMiddleware;
873
+ /** Thrown (usually by approval middleware) to skip execution with feedback for the model. */
874
+ declare class ToolRejection extends Error {
875
+ readonly feedback: string;
876
+ constructor(feedback: string);
877
+ }
878
+ /** Mark an error retryable (true) or fatal (false). Shape and type are untouched. */
879
+ declare function stampRetryable<T extends Error>(err: T, retryable: boolean): T;
880
+ /** Read a verdict: true/false, or undefined when never marked. AgentError maps to its flag. */
881
+ declare function getRetryable(err: unknown): boolean | undefined;
882
+ interface BackoffOptions {
883
+ maxRetries?: number;
884
+ initialDelayMs?: number;
885
+ backoffFactor?: number;
886
+ maxDelayMs?: number;
887
+ jitter?: boolean;
888
+ }
889
+ declare function backoffDelayMs(attempt: number, opts: Required<Omit<BackoffOptions, "maxRetries">>): number;
890
+ type RetryFilter = ((error: Error) => boolean) | (new (...args: never[]) => Error)[];
891
+ /** Cap model calls per run; exceeded -> AgentError(BUDGET_EXCEEDED). Stateless (uses step). */
892
+ declare function modelCallLimit(maxCalls: number): AgentMiddleware;
893
+ /** Retry failing tool executions with exponential backoff. AgentErrors pass through untouched. */
894
+ declare function toolRetry(opts?: {
895
+ attempts?: number;
896
+ backoffMs?: number;
897
+ }): AgentMiddleware;
898
+ interface RetryMiddlewareOptions extends BackoffOptions {
899
+ retryOn?: RetryFilter;
900
+ onFailure?: "error" | "continue" | ((error: Error) => string);
901
+ /** Limit retries to these tool names (tool retry only). */
902
+ tools?: string[];
903
+ }
904
+ /**
905
+ * Full tool retry: exponential backoff + jitter, error-class filtering,
906
+ * per-tool scoping, and exhausted-failure behavior (continue as tool
907
+ * message vs rethrow). Honors stampRetryable verdicts.
908
+ */
909
+ declare function toolRetryMiddleware(opts?: RetryMiddlewareOptions): AgentMiddleware;
910
+ /**
911
+ * Model retry with the same backoff/filter/onFailure semantics.
912
+ * onFailure "continue" synthesizes an empty-text completion so the loop ends gracefully.
913
+ */
914
+ declare function modelRetryMiddleware(opts?: RetryMiddlewareOptions): AgentMiddleware;
915
+ /** Fall back across providers when the primary model fails (first success wins). */
916
+ declare function modelFallbackMiddleware(...fallbacks: ModelProvider[]): AgentMiddleware;
917
+ /** Per-run tool-call budgets (global + per-tool). Exceeded calls are blocked with feedback or throw. */
918
+ declare function toolCallLimitMiddleware(opts: {
919
+ toolName?: string;
920
+ runLimit?: number;
921
+ exitBehavior?: "continue" | "error";
922
+ }): AgentMiddleware;
923
+ type HitlDecision = "approve" | {
924
+ edit: unknown;
925
+ } | {
926
+ reject: string;
927
+ } | {
928
+ suspend: true;
929
+ };
930
+ /** Thrown to suspend a run for human review. Persisted by checkpoint when checkpointer+threadId are set. */
931
+ declare class HitlInterrupt extends Error {
932
+ readonly interruptId: string;
933
+ readonly tool: string;
934
+ readonly args: unknown;
935
+ constructor(interruptId: string, tool: string, args: unknown);
936
+ }
937
+ /** Stable key binding a decision to one tool call (used across suspend/resume). */
938
+ declare function hitlKey(tool: string, args: unknown): string;
939
+ interface HitlDecideRequest {
940
+ name: string;
941
+ args: unknown;
942
+ allowed: ("approve" | "edit" | "reject")[];
943
+ interruptId: string;
944
+ }
945
+ /**
946
+ * Human-in-the-loop: pause tool execution for approval/edit/reject.
947
+ * Single-process version — `decide` is called inline (CLI prompt, API
948
+ * handler, test stub). Checkpointed resume lands with durable runtime (P3).
949
+ */
950
+ declare function humanInTheLoopMiddleware(opts: {
951
+ interruptOn: Record<string, boolean | {
952
+ allowedDecisions?: ("approve" | "edit" | "reject")[];
953
+ }>;
954
+ /** Inline decider. May return { suspend: true } to checkpoint + throw HitlInterrupt. Omit to always suspend. */
955
+ decide?: (req: HitlDecideRequest) => Promise<HitlDecision> | HitlDecision;
956
+ }): AgentMiddleware;
957
+ interface PIIMatch {
958
+ text: string;
959
+ start: number;
960
+ end: number;
961
+ }
962
+ type PIIDetector = RegExp | string | ((content: string) => PIIMatch[]);
963
+ type PIIStrategy = "block" | "redact" | "mask" | "hash";
964
+ /** PII detection with redact/mask/hash/block strategies across input, output, and tool results. */
965
+ declare function piiMiddleware(piiType: string, opts?: {
966
+ strategy?: PIIStrategy;
967
+ detector?: PIIDetector;
968
+ applyToInput?: boolean;
969
+ applyToOutput?: boolean;
970
+ applyToToolResults?: boolean;
971
+ }): AgentMiddleware;
972
+ /**
973
+ * Auto-summarize history when estimated tokens pass `triggerTokens`,
974
+ * keeping the newest `keepMessages`. Text-oriented: summarized-away
975
+ * multimodal blocks survive only as prose (store media externally and
976
+ * pass URLs if images must persist).
977
+ */
978
+ declare function summarizationMiddleware(opts: {
979
+ model: ModelProvider;
980
+ triggerTokens: number;
981
+ keepMessages?: number;
982
+ summaryPrefix?: string;
983
+ summarize?: (messages: ChatMessage[]) => Promise<string>;
984
+ }): AgentMiddleware;
985
+ interface ClearToolUsesOptions {
986
+ triggerTokens?: number;
987
+ keep?: number;
988
+ clearToolInputs?: boolean;
989
+ excludeTools?: string[];
990
+ placeholder?: string;
991
+ }
992
+ /** Clear older tool outputs past a token budget; newest `keep` results survive. */
993
+ declare class ClearToolUsesEdit {
994
+ private opts;
995
+ constructor(opts?: ClearToolUsesOptions);
996
+ apply(messages: ChatMessage[]): ChatMessage[];
997
+ clearInputs(messages: ChatMessage[]): ChatMessage[];
998
+ }
999
+ declare function contextEditingMiddleware(opts: {
1000
+ edits?: ClearToolUsesEdit[];
1001
+ }): AgentMiddleware;
1002
+ interface TodoItem {
1003
+ content: string;
1004
+ status: "pending" | "active" | "completed";
1005
+ }
1006
+ /** Task planning: contributes a `write_todos` tool and tracks state per run. */
1007
+ declare function todoListMiddleware(): AgentMiddleware & {
1008
+ listTodos(): TodoItem[];
1009
+ };
1010
+ /** Narrow 10+ tools to the relevant few before the main model call. */
1011
+ declare function llmToolSelectorMiddleware(opts: {
1012
+ model: ModelProvider;
1013
+ maxTools?: number;
1014
+ alwaysInclude?: string[];
1015
+ systemPrompt?: string;
1016
+ }): AgentMiddleware;
1017
+ /** Emulate tool execution with an LLM — testing/prototyping without side effects. */
1018
+ declare function toolEmulatorMiddleware(opts?: {
1019
+ tools?: string[];
1020
+ model?: ModelProvider;
1021
+ }): AgentMiddleware;
1022
+ /** ls/read_file/write_file/edit_file scoped to `root` (escapes rejected). */
1023
+ declare function filesystemTools(root: string): Tool[];
1024
+ declare function filesystemMiddleware(opts: {
1025
+ root: string;
1026
+ }): AgentMiddleware;
1027
+ /**
1028
+ * Spawn named subagents via a `task` tool — isolates context so the
1029
+ * supervisor stays clean while the subagent goes deep.
1030
+ */
1031
+ declare function createSubAgentMiddleware(opts: {
1032
+ model: ModelProvider;
1033
+ subagents: {
1034
+ name: string;
1035
+ description: string;
1036
+ systemPrompt?: string;
1037
+ tools?: Tool[];
1038
+ }[];
1039
+ }): AgentMiddleware;
1040
+
1041
+ /**
1042
+ * Conversation managers keep history within context limits.
1043
+ * - apply(): after-run management (before memory.save).
1044
+ * - beforeModel(): per-turn management inside the loop (sliding window).
1045
+ * - reduce(): explicit shrink (overflow recovery / proactive triggers).
1046
+ * Pinned messages are never removed. Tool/assistant-tool_call pairs are
1047
+ * never orphaned: trimming drops leading dangling messages.
1048
+ */
1049
+ interface ConversationManager {
1050
+ readonly name: string;
1051
+ /** Messages removed so far (lets session loading skip efficiently). */
1052
+ removedCount: number;
1053
+ apply(messages: ChatMessage[]): ChatMessage[] | Promise<ChatMessage[]>;
1054
+ reduce(messages: ChatMessage[]): ChatMessage[] | Promise<ChatMessage[]>;
1055
+ beforeModel?(messages: ChatMessage[], step: number): ChatMessage[] | Promise<ChatMessage[]>;
1056
+ }
1057
+ /** Drop leading messages that lost their pair (tool head, call-only assistant head). */
1058
+ declare function trimDangling(messages: ChatMessage[]): ChatMessage[];
1059
+ declare function messageTokens(m: ChatMessage): number;
1060
+ declare function historyTokens(messages: ChatMessage[]): number;
1061
+ /** Keeps full history. Pass explicitly to disable the default sliding window. */
1062
+ declare class NullConversationManager implements ConversationManager {
1063
+ readonly name = "null";
1064
+ removedCount: number;
1065
+ apply(messages: ChatMessage[]): ChatMessage[];
1066
+ reduce(messages: ChatMessage[]): ChatMessage[];
1067
+ }
1068
+ interface SlidingWindowOptions {
1069
+ /** Max messages kept (excluding pinned). Default 40. */
1070
+ windowSize?: number;
1071
+ /** Permanently protect the first N messages. Default 0. */
1072
+ pinFirst?: number;
1073
+ /** Manage before every model call (true) or every N calls. Default false (after-run only). */
1074
+ perTurn?: boolean | number;
1075
+ }
1076
+ declare class SlidingWindowConversationManager implements ConversationManager {
1077
+ readonly name = "sliding-window";
1078
+ removedCount: number;
1079
+ private windowSize;
1080
+ private pinFirst;
1081
+ private perTurn;
1082
+ constructor(opts?: SlidingWindowOptions);
1083
+ private pin;
1084
+ private trim;
1085
+ apply(messages: ChatMessage[]): ChatMessage[];
1086
+ reduce(messages: ChatMessage[]): ChatMessage[];
1087
+ beforeModel(messages: ChatMessage[], step: number): ChatMessage[];
1088
+ }
1089
+ interface SummarizingOptions {
1090
+ /** Fraction of oldest messages to summarize away (0.1–0.8). Default 0.3. */
1091
+ summaryRatio?: number;
1092
+ /** Newest messages always kept. Default 10. */
1093
+ preserveRecent?: number;
1094
+ pinFirst?: number;
1095
+ summarizer?: (messages: ChatMessage[]) => Promise<string>;
1096
+ /** Model used for summaries when no `summarizer` fn is given. */
1097
+ model?: ModelProvider;
1098
+ summaryPrefix?: string;
1099
+ }
1100
+ declare class SummarizingConversationManager implements ConversationManager {
1101
+ readonly name = "summarizing";
1102
+ removedCount: number;
1103
+ private ratio;
1104
+ private preserveRecent;
1105
+ private pinFirst;
1106
+ private summarizer?;
1107
+ private model?;
1108
+ private summaryPrefix;
1109
+ /** Set when the last apply() summarized (tests/UI can assert on it). */
1110
+ lastSummary?: string;
1111
+ constructor(opts?: SummarizingOptions);
1112
+ private summarizable;
1113
+ private summarize;
1114
+ apply(messages: ChatMessage[]): Promise<ChatMessage[]>;
1115
+ reduce(messages: ChatMessage[]): ChatMessage[];
1116
+ }
1117
+
1118
+ /**
1119
+ * Local-first durability: file checkpointer + file locks. No services,
1120
+ * no third-party deps. Checkpointed HITL resume works fully offline.
1121
+ */
1122
+ interface ThreadCheckpoint {
1123
+ threadId: string;
1124
+ savedAt: string;
1125
+ messages: ChatMessage[];
1126
+ state: Record<string, unknown>;
1127
+ pending: {
1128
+ interruptId: string;
1129
+ tool: string;
1130
+ args: unknown;
1131
+ }[];
1132
+ }
1133
+ interface Checkpointer {
1134
+ save(threadId: string, checkpoint: Omit<ThreadCheckpoint, "threadId" | "savedAt">): Promise<void>;
1135
+ load(threadId: string): Promise<ThreadCheckpoint | undefined>;
1136
+ delete(threadId: string): Promise<void>;
1137
+ }
1138
+ /**
1139
+ * Exclusive local lock via O_EXCL file creation. Stale locks (older than
1140
+ * staleMs) are reclaimed. Single-machine correctness; distributed locking
1141
+ * is explicitly out of scope (see roadmap P3).
1142
+ */
1143
+ declare function withFileLock<T>(lockPath: string, fn: () => Promise<T>, opts?: {
1144
+ staleMs?: number;
1145
+ }): Promise<T>;
1146
+ /** JSON-file checkpointer: <root>/threads/<threadId>/checkpoint.json, lock-guarded. */
1147
+ declare class FileCheckpointer implements Checkpointer {
1148
+ private root;
1149
+ constructor(root: string);
1150
+ /** threadId lands in a filesystem path — keep it a single safe directory name. */
1151
+ private threadDir;
1152
+ private file;
1153
+ private lock;
1154
+ save(threadId: string, checkpoint: Omit<ThreadCheckpoint, "threadId" | "savedAt">): Promise<void>;
1155
+ load(threadId: string): Promise<ThreadCheckpoint | undefined>;
1156
+ delete(threadId: string): Promise<void>;
1157
+ }
1158
+
1159
+ /**
1160
+ * Sessions: persist agent state + history across restarts.
1161
+ * - Storage: byte-moving backends (memory / local files).
1162
+ * - SessionManager: latest snapshot + immutable checkpoints (UUID ids).
1163
+ * - Agent snapshots: manual take/load with field selection + appData.
1164
+ */
1165
+ interface Storage {
1166
+ read(key: string): Promise<string | undefined>;
1167
+ write(key: string, value: string): Promise<void>;
1168
+ deletePrefix(prefix: string): Promise<void>;
1169
+ list(prefix: string): Promise<string[]>;
1170
+ }
1171
+ declare class InMemoryStorage implements Storage {
1172
+ private data;
1173
+ read(key: string): Promise<string | undefined>;
1174
+ write(key: string, value: string): Promise<void>;
1175
+ deletePrefix(prefix: string): Promise<void>;
1176
+ list(prefix: string): Promise<string[]>;
1177
+ }
1178
+ declare class LocalFileStorage implements Storage {
1179
+ private root;
1180
+ constructor(root: string);
1181
+ private path;
1182
+ read(key: string): Promise<string | undefined>;
1183
+ write(key: string, value: string): Promise<void>;
1184
+ deletePrefix(prefix: string): Promise<void>;
1185
+ list(prefix: string): Promise<string[]>;
1186
+ }
1187
+ interface SnapshotData {
1188
+ messages?: ChatMessage[];
1189
+ state?: Record<string, unknown>;
1190
+ systemPrompt?: string;
1191
+ }
1192
+ interface Snapshot {
1193
+ id: string;
1194
+ createdAt: string;
1195
+ data: SnapshotData;
1196
+ appData?: Record<string, unknown>;
1197
+ }
1198
+ type SnapshotField = "messages" | "state" | "systemPrompt";
1199
+ interface TakeSnapshotOptions {
1200
+ /** Preset bundle. Currently only "session" (messages + state). */
1201
+ preset?: "session";
1202
+ include?: SnapshotField[];
1203
+ exclude?: SnapshotField[];
1204
+ appData?: Record<string, unknown>;
1205
+ }
1206
+ declare function selectSnapshotFields(full: Required<Pick<SnapshotData, "messages" | "state">> & Pick<SnapshotData, "systemPrompt">, opts?: TakeSnapshotOptions): SnapshotData;
1207
+ interface SessionManagerOptions {
1208
+ sessionId?: string;
1209
+ storage: Storage;
1210
+ agentId?: string;
1211
+ }
1212
+ declare class SessionManager {
1213
+ readonly sessionId: string;
1214
+ readonly agentId: string;
1215
+ private storage;
1216
+ constructor(opts: SessionManagerOptions);
1217
+ private scope;
1218
+ saveLatest(data: SnapshotData): Promise<void>;
1219
+ loadLatest(): Promise<SnapshotData | undefined>;
1220
+ /** Immutable checkpoint; returns its id. */
1221
+ saveSnapshot(data: SnapshotData, appData?: Record<string, unknown>): Promise<string>;
1222
+ listSnapshotIds(): Promise<string[]>;
1223
+ restoreSnapshot(id: string): Promise<Snapshot | undefined>;
1224
+ deleteSession(): Promise<void>;
1225
+ }
1226
+
1227
+ /**
1228
+ * Structured output — typed agent results instead of parsed prose.
1229
+ * Two strategies:
1230
+ * - provider: native `response_format` (OpenAI-compatible APIs). Most reliable.
1231
+ * - tool: synthetic `__structured_response` tool; validation errors return as
1232
+ * tool messages so the model self-repairs within maxSteps.
1233
+ */
1234
+ type ResponseStrategy = "auto" | "provider" | "tool";
1235
+ interface ResponseFormat<T = unknown> {
1236
+ schema: z.ZodType<T>;
1237
+ /** Function/tool name. Default: "structured_response". */
1238
+ name?: string;
1239
+ strategy?: ResponseStrategy;
1240
+ /** Tool message content on success (tool strategy). */
1241
+ toolMessageContent?: string;
1242
+ /** Validation retries before STRUCTURED_NO_MATCH (tool strategy). Default 2. */
1243
+ maxAttempts?: number;
1244
+ }
1245
+ declare function toolStrategy<T>(schema: z.ZodType<T>, opts?: Omit<ResponseFormat<T>, "schema" | "strategy">): ResponseFormat<T>;
1246
+ declare function providerStrategy<T>(schema: z.ZodType<T>, opts?: Omit<ResponseFormat<T>, "schema" | "strategy">): ResponseFormat<T>;
1247
+ declare function responseFormatName<T>(format: ResponseFormat<T>): string;
1248
+ declare function responseFormatJsonSchema<T>(format: ResponseFormat<T>): Record<string, unknown>;
1249
+ /** Validate raw model output; throws AgentError STRUCTURED_INVALID (retryable) on mismatch. */
1250
+ declare function parseStructured<T>(format: ResponseFormat<T>, raw: unknown): T;
1251
+
1252
+ interface Memory {
1253
+ load(): Promise<ChatMessage[]>;
1254
+ save(messages: ChatMessage[]): Promise<void>;
1255
+ clear(): Promise<void>;
1256
+ }
1257
+ declare class InMemoryMemory implements Memory {
1258
+ private messages;
1259
+ private maxMessages;
1260
+ constructor(maxMessages?: number);
1261
+ load(): Promise<ChatMessage[]>;
1262
+ save(messages: ChatMessage[]): Promise<void>;
1263
+ clear(): Promise<void>;
1264
+ }
1265
+ /**
1266
+ * File-backed JSON memory: same windowing as in-memory, persisted per
1267
+ * write to `<dir>/memory.json`. Crash-safe enough for local-first use
1268
+ * (write-then-rename atomicity, validated reload).
1269
+ */
1270
+ declare class FileMemory implements Memory {
1271
+ private cache?;
1272
+ private file;
1273
+ private maxMessages;
1274
+ constructor(dir: string, maxMessages?: number);
1275
+ private readAll;
1276
+ private flush;
1277
+ load(): Promise<ChatMessage[]>;
1278
+ save(messages: ChatMessage[]): Promise<void>;
1279
+ clear(): Promise<void>;
1280
+ }
1281
+
1282
+ interface StepEvent {
1283
+ step: number;
1284
+ messages: ChatMessage[];
1285
+ }
1286
+ interface ToolCallEvent {
1287
+ tool: string;
1288
+ args: unknown;
1289
+ }
1290
+ interface ToolResultEvent {
1291
+ tool: string;
1292
+ output: unknown;
1293
+ }
1294
+ interface DoneEvent {
1295
+ text: string;
1296
+ toolCalls: AgentResult["toolCalls"];
1297
+ }
1298
+ /** Observability hooks — plug logger/tracer here, keep core dependency-free. */
1299
+ interface AgentEvents {
1300
+ onStep?: (e: StepEvent) => void;
1301
+ onToolCall?: (e: ToolCallEvent) => void;
1302
+ onToolResult?: (e: ToolResultEvent) => void;
1303
+ onDone?: (e: DoneEvent) => void;
1304
+ /** Streamed text deltas. */
1305
+ onToken?: (delta: string) => void;
1306
+ /** Streamed thinking/reasoning deltas. */
1307
+ onThinking?: (delta: string) => void;
1308
+ }
1309
+ /** Minimal ANSI colors, dependency-free. Honors NO_COLOR and non-TTY. */
1310
+ declare function supportsColor(): boolean;
1311
+ interface ConsoleEventsOptions {
1312
+ prefix?: string;
1313
+ /** Force colors on/off. Default: auto (TTY without NO_COLOR). */
1314
+ colors?: boolean;
1315
+ }
1316
+ declare function consoleEvents(prefix?: string, opts?: ConsoleEventsOptions): AgentEvents;
1317
+ declare function consoleEvents(opts: ConsoleEventsOptions): AgentEvents;
1318
+ /** Red error line for failures (pairs with consoleEvents). */
1319
+ declare function logError(prefix: string, err: unknown, colors?: boolean): void;
1320
+
1321
+ type OutputVersion = "v0" | "v1";
1322
+ interface AgentOptions {
1323
+ name?: string;
1324
+ /** One-line specialty, used by the router menu. */
1325
+ description?: string;
1326
+ systemPrompt?: string;
1327
+ model: ModelProvider;
1328
+ tools?: Tool[];
1329
+ memory?: Memory;
1330
+ maxSteps?: number;
1331
+ /** Max tool executions per run; exceeded -> AgentError(BUDGET_EXCEEDED). Default: unlimited. */
1332
+ maxToolCalls?: number;
1333
+ /** Token/cost/deadline budgets enforced after every model call. */
1334
+ budgets?: TokenBudgets;
1335
+ /**
1336
+ * Output version. v0: assistant messages carry plain text (thinking streams
1337
+ * via events only). v1: thinking is also stored as `reasoning` blocks.
1338
+ */
1339
+ outputVersion?: OutputVersion;
1340
+ /** Typed final answer (tool or provider strategy). Sets `structuredResponse` on the result. */
1341
+ responseFormat?: ResponseFormat;
1342
+ /** Middleware hooks (before/after model + tool). Run in order. */
1343
+ middleware?: AgentMiddleware[];
1344
+ /** Conversation history: seed prior messages to continue a conversation. */
1345
+ initialMessages?: ChatMessage[];
1346
+ /** Agent key-value state (never sent to the model). */
1347
+ state?: Record<string, unknown> | AgentState;
1348
+ /** History management. Default: NullConversationManager (keep everything; memory still windows). */
1349
+ conversationManager?: ConversationManager;
1350
+ /** Persist state + history across restarts. Restored on first run, saved after each run. */
1351
+ sessionManager?: SessionManager;
1352
+ events?: AgentEvents;
1353
+ }
1354
+ interface TimelineEntry {
1355
+ rev: number;
1356
+ kind: "run" | "edit" | "branch" | "resume" | "snapshot";
1357
+ label?: string;
1358
+ at: string;
1359
+ }
1360
+ interface TokenBudgets {
1361
+ /** Total (input + output + reasoning) tokens per run. */
1362
+ maxTokens?: number;
1363
+ /** USD cap per run. Needs a known price (table lookup or `prices`) — never guessed. */
1364
+ maxCostUsd?: number;
1365
+ /** Price override when the model is missing from the pricing table. */
1366
+ prices?: ModelPrice;
1367
+ /** Wall-clock deadline per run. */
1368
+ deadlineMs?: number;
1369
+ }
1370
+ interface RunOptions {
1371
+ signal?: AbortSignal;
1372
+ /** Per-run data: shared by reference across hooks/tools, returned on the result, never sent to the model. */
1373
+ invocationState?: InvocationState;
1374
+ /** Checkpointed HITL: persist + resume human approvals locally. */
1375
+ checkpointer?: Checkpointer;
1376
+ threadId?: string;
1377
+ }
1378
+ /**
1379
+ * Minimal ReAct-style loop:
1380
+ * 1. load memory -> messages
1381
+ * 2. loop: model.complete -> tool calls -> execute -> append
1382
+ * 3. save memory, return AgentResult
1383
+ *
1384
+ * `run()` drains `stream()`; both fire `events` hooks identically.
1385
+ */
1386
+ declare class Agent {
1387
+ private options;
1388
+ private seeded;
1389
+ private restored;
1390
+ private lastMessages;
1391
+ private revisions;
1392
+ readonly agentState: AgentState;
1393
+ private instanceSessionId?;
1394
+ constructor(options: AgentOptions);
1395
+ /** Public identity for orchestration menus and logs. */
1396
+ get name(): string;
1397
+ get description(): string;
1398
+ get model(): ModelProvider;
1399
+ /** Member tools (copy) — introspection for orchestration/menus. */
1400
+ get tools(): Tool[];
1401
+ /**
1402
+ * Clone with extra tools. Memory, session, and state are NOT carried over
1403
+ * (fresh per clone); model, tools, middleware, and formats are shared.
1404
+ * Used by coordinators (swarm handoffs) that inject control tools.
1405
+ */
1406
+ withTools(...extra: Tool[]): Agent;
1407
+ /** Key-value state (never sent to the model). */
1408
+ get state(): AgentState;
1409
+ /** Session handle: the manager's id, or a generated per-instance id. */
1410
+ get sessionId(): string;
1411
+ /** Full conversation history from the last run (system + memory + new turns). */
1412
+ get messages(): ChatMessage[];
1413
+ /** Version timeline: runs, edits, branches, resumes (append-only). */
1414
+ get timeline(): TimelineEntry[];
1415
+ private record;
1416
+ /**
1417
+ * Edit a message in the current history (by id or index) and keep the
1418
+ * version in the timeline. History + memory stay in sync.
1419
+ */
1420
+ editMessage(idOrIndex: string | number, content: string | ContentBlock[]): Promise<ChatMessage>;
1421
+ /**
1422
+ * Branch the current history into an independent agent. Model, tools,
1423
+ * middleware, and formats are shared; state is copied; memory is fresh
1424
+ * (seeded with this history); sessions are NOT carried over (to avoid
1425
+ * double-persist collisions). Both timelines record the branch.
1426
+ */
1427
+ branch(label: string, overrides?: Partial<AgentOptions>): Promise<Agent>;
1428
+ /**
1429
+ * Pause mid-conversation: persist history + state under threadId without
1430
+ * needing an interrupt. Pair with resume() (empty decisions continue).
1431
+ */
1432
+ pause(threadId: string, opts: {
1433
+ checkpointer: Checkpointer;
1434
+ }): Promise<{
1435
+ threadId: string;
1436
+ messages: number;
1437
+ }>;
1438
+ /** Manual checkpoint: messages + state (+ system prompt on request) + appData. */
1439
+ takeSnapshot(opts?: TakeSnapshotOptions): Snapshot;
1440
+ /** Restore fields present in the snapshot; absent fields keep current values. */
1441
+ loadSnapshot(snapshot: Snapshot): Promise<void>;
1442
+ /**
1443
+ * Resume a suspended run: restores the checkpoint, seeds human decisions,
1444
+ * and continues the loop without new input. Decisions are keyed by
1445
+ * `hitlKey(tool, args)` for an exact match, or by bare tool name to cover
1446
+ * every re-issued call of that tool (models re-issue with regenerated arg
1447
+ * text, so exact keys alone would never converge).
1448
+ */
1449
+ resume(threadId: string, decisions: Record<string, HitlDecision> | undefined, opts: {
1450
+ checkpointer: Checkpointer;
1451
+ } & RunOptions): Promise<AgentResult>;
1452
+ private buildRuntime;
1453
+ /** Continue the loop from restored history (no new user message). */
1454
+ private iterateContinuation;
1455
+ run(input: string | ContentBlock[], signal?: AbortSignal): Promise<AgentResult>;
1456
+ run(input: string | ContentBlock[], opts?: RunOptions): Promise<AgentResult>;
1457
+ stream(input: string | ContentBlock[], signal?: AbortSignal, invocationState?: InvocationState): AsyncGenerator<StreamEvent, AgentResult>;
1458
+ stream(input: string | ContentBlock[], opts?: RunOptions): AsyncGenerator<StreamEvent, AgentResult>;
1459
+ private iterate;
1460
+ private runLoop;
1461
+ }
1462
+
1463
+ /**
1464
+ * Swarm: autonomous handoffs across specialists, no fixed path.
1465
+ * Each member gets a `handoff_to_agent` tool; shared context (task,
1466
+ * history, contributed knowledge, roster) is rebuilt for every turn.
1467
+ * Safety: max handoffs / iterations / timeouts + ping-pong detection.
1468
+ */
1469
+ interface SwarmOptions {
1470
+ agents: Agent[];
1471
+ /** First agent to run. Default: agents[0]. Accepts instance or name. */
1472
+ entryPoint?: Agent | string;
1473
+ maxHandoffs?: number;
1474
+ maxIterations?: number;
1475
+ executionTimeoutMs?: number;
1476
+ nodeTimeoutMs?: number;
1477
+ /** Ping-pong detection: window size + min unique agents (0 = disabled). */
1478
+ loopDetectionWindow?: number;
1479
+ minUniqueAgents?: number;
1480
+ }
1481
+ interface HandoffSignal {
1482
+ to: string;
1483
+ message: string;
1484
+ context?: Record<string, unknown>;
1485
+ }
1486
+ type SwarmStatus = "COMPLETED" | "FAILED";
1487
+ interface SwarmResult {
1488
+ status: SwarmStatus;
1489
+ text: string;
1490
+ nodeHistory: string[];
1491
+ results: Record<string, AgentResult>;
1492
+ iterations: number;
1493
+ handoffs: number;
1494
+ usage: TokenUsage;
1495
+ sharedContext: Record<string, Record<string, unknown>>;
1496
+ error?: string;
1497
+ }
1498
+ type SwarmStreamEvent = {
1499
+ type: "node_start";
1500
+ agent: string;
1501
+ } | {
1502
+ type: "node_done";
1503
+ agent: string;
1504
+ } | {
1505
+ type: "handoff";
1506
+ from: string;
1507
+ to: string;
1508
+ } | {
1509
+ type: "agent_event";
1510
+ agent: string;
1511
+ event: StreamEvent;
1512
+ } | {
1513
+ type: "result";
1514
+ result: SwarmResult;
1515
+ };
1516
+ declare function readHandoffSignal(err: unknown): HandoffSignal | undefined;
1517
+ declare class Swarm {
1518
+ private agents;
1519
+ private entryPoint;
1520
+ private maxHandoffs;
1521
+ private maxIterations;
1522
+ private executionTimeoutMs?;
1523
+ private nodeTimeoutMs?;
1524
+ private loopWindow;
1525
+ private minUniqueAgents;
1526
+ constructor(opts: SwarmOptions);
1527
+ private roster;
1528
+ private buildInput;
1529
+ private memberWithHandoff;
1530
+ run(task: string | ContentBlock[], opts?: RunOptions & {
1531
+ sharedState?: InvocationState;
1532
+ }): Promise<SwarmResult>;
1533
+ stream(task: string | ContentBlock[], opts?: RunOptions & {
1534
+ sharedState?: InvocationState;
1535
+ }): AsyncGenerator<SwarmStreamEvent, SwarmResult>;
1536
+ private detectLoop;
1537
+ private finish;
1538
+ }
1539
+
1540
+ /**
1541
+ * Agent-to-Agent (A2A) interop — The Framework agents calling agents on
1542
+ * other platforms, and vice versa. Minimal core of the open protocol:
1543
+ * agent-card discovery + JSON-RPC message/send over HTTP, with per-context
1544
+ * isolation on the server side.
1545
+ */
1546
+ interface AgentCard {
1547
+ name: string;
1548
+ description?: string;
1549
+ version?: string;
1550
+ skills?: {
1551
+ name: string;
1552
+ description?: string;
1553
+ }[];
1554
+ }
1555
+ interface A2AClientOptions {
1556
+ fetchFn?: typeof fetch;
1557
+ timeoutMs?: number;
1558
+ }
1559
+ /** Consume a remote A2A agent like a local one. */
1560
+ declare class A2AClient {
1561
+ readonly endpoint: string;
1562
+ private fetchFn;
1563
+ private timeoutMs;
1564
+ constructor(endpoint: string, opts?: A2AClientOptions);
1565
+ getCard(): Promise<AgentCard>;
1566
+ send(text: string, contextId?: string): Promise<{
1567
+ text: string;
1568
+ contextId?: string;
1569
+ }>;
1570
+ }
1571
+ /** Wrap a remote agent as a framework Tool for orchestrators. */
1572
+ declare function a2aAsTool(client: A2AClient, opts?: {
1573
+ name?: string;
1574
+ description?: string;
1575
+ }): Tool;
1576
+ interface A2AServerOptions {
1577
+ card: AgentCard;
1578
+ /**
1579
+ * Fresh agent per contextId (isolation). Retained up to maxContexts (LRU).
1580
+ * Return the SAME agent for a contextId to keep state in memory across
1581
+ * turns of one conversation, but never share one instance across contexts —
1582
+ * shared history leaks conversations between users.
1583
+ */
1584
+ agentFactory: (contextId: string) => Agent | Promise<Agent>;
1585
+ maxContexts?: number;
1586
+ port?: number;
1587
+ host?: string;
1588
+ /** Durable HITL threads: runs execute with { checkpointer, threadId: contextId }. */
1589
+ checkpointer?: Checkpointer;
1590
+ /** Browser frontends: reflected as Access-Control-Allow-Origin (+ OPTIONS handling). */
1591
+ corsOrigins?: string[];
1592
+ /** Max JSON-RPC request body bytes. Default 10 MiB. */
1593
+ maxBodyBytes?: number;
1594
+ }
1595
+ /** Serve a Framework agent over A2A (card + message/send). */
1596
+ declare class A2AServer {
1597
+ private opts;
1598
+ private server?;
1599
+ private contexts;
1600
+ private maxContexts;
1601
+ constructor(opts: A2AServerOptions);
1602
+ private corsHeaders;
1603
+ private runOpts;
1604
+ private agentFor;
1605
+ /** Read a request body with a hard cap; JSON.parse errors to the caller. */
1606
+ private readBody;
1607
+ private handle;
1608
+ start(port?: number, host?: string): Promise<number>;
1609
+ stop(): Promise<void>;
1610
+ }
1611
+
1612
+ /**
1613
+ * Frontend/server-component client for Framework agents.
1614
+ * Framework-agnostic (fetch + async iterators): use directly in TanStack
1615
+ * Query loaders, Next.js route handlers/components, Svelte, or plain DOM.
1616
+ * React bindings live in @fabisch/react (thin layer over this client).
1617
+ */
1618
+ interface AgentClientOptions {
1619
+ fetchFn?: typeof fetch;
1620
+ timeoutMs?: number;
1621
+ }
1622
+ declare class AgentClient {
1623
+ private a2a;
1624
+ private fetchFn;
1625
+ readonly endpoint: string;
1626
+ constructor(endpoint: string, opts?: AgentClientOptions);
1627
+ card(): Promise<AgentCard>;
1628
+ send(text: string, contextId?: string): Promise<{
1629
+ text: string;
1630
+ contextId?: string;
1631
+ }>;
1632
+ /** Live StreamEvents over SSE (`POST /stream`). Throws AgentError on server errors. */
1633
+ stream(text: string, contextId?: string, signal?: AbortSignal, opts?: {
1634
+ onContext?: (contextId: string) => void;
1635
+ }): AsyncGenerator<StreamEvent>;
1636
+ }
1637
+ /**
1638
+ * Next.js / TanStack Start route handler bridge: POST { text, contextId? }
1639
+ * → SSE stream of agent events. `AgentClient.stream` posts to
1640
+ * `${endpoint}/stream`, so mount this at `app/api/agent/stream/route.ts` and
1641
+ * point `useAgent({ endpoint: "/api/agent" })` (or AgentClient) at the parent:
1642
+ *
1643
+ * import { AgentClient, handleAgentRoute } from "@fabisch/agents";
1644
+ * const client = new AgentClient(process.env.AGENT_URL!);
1645
+ * export const POST = (req: Request) => handleAgentRoute(req, client);
1646
+ *
1647
+ * The browser disconnect (req.signal) stops the upstream agent run.
1648
+ */
1649
+ declare function handleAgentRoute(req: Request, client: AgentClient): Promise<Response>;
1650
+
1651
+ /**
1652
+ * framework.json — declare agents, launch them as A2A servers.
1653
+ * Relative paths resolve against the config file's directory.
1654
+ */
1655
+ declare const AgentDefSchema: z.ZodObject<{
1656
+ name: z.ZodString;
1657
+ description: z.ZodDefault<z.ZodString>;
1658
+ systemPrompt: z.ZodDefault<z.ZodString>;
1659
+ model: z.ZodString;
1660
+ port: z.ZodOptional<z.ZodNumber>;
1661
+ skills: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
1662
+ filesystem: z.ZodOptional<z.ZodString>;
1663
+ todos: z.ZodDefault<z.ZodBoolean>;
1664
+ maxSteps: z.ZodDefault<z.ZodNumber>;
1665
+ sessionDir: z.ZodOptional<z.ZodString>;
1666
+ /** Extra env file for this agent (keys override framework-level). */
1667
+ envFile: z.ZodOptional<z.ZodString>;
1668
+ }, "strip", z.ZodTypeAny, {
1669
+ name: string;
1670
+ model: string;
1671
+ todos: boolean;
1672
+ systemPrompt: string;
1673
+ description: string;
1674
+ maxSteps: number;
1675
+ skills: string[];
1676
+ filesystem?: string | undefined;
1677
+ port?: number | undefined;
1678
+ sessionDir?: string | undefined;
1679
+ envFile?: string | undefined;
1680
+ }, {
1681
+ name: string;
1682
+ model: string;
1683
+ todos?: boolean | undefined;
1684
+ filesystem?: string | undefined;
1685
+ systemPrompt?: string | undefined;
1686
+ description?: string | undefined;
1687
+ maxSteps?: number | undefined;
1688
+ port?: number | undefined;
1689
+ skills?: string[] | undefined;
1690
+ sessionDir?: string | undefined;
1691
+ envFile?: string | undefined;
1692
+ }>;
1693
+ declare const FrameworkFileSchema: z.ZodObject<{
1694
+ server: z.ZodDefault<z.ZodObject<{
1695
+ host: z.ZodDefault<z.ZodString>;
1696
+ basePort: z.ZodDefault<z.ZodNumber>;
1697
+ }, "strip", z.ZodTypeAny, {
1698
+ host: string;
1699
+ basePort: number;
1700
+ }, {
1701
+ host?: string | undefined;
1702
+ basePort?: number | undefined;
1703
+ }>>;
1704
+ /** Framework-level env file(s), loaded before agents resolve models. */
1705
+ envFile: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
1706
+ /** Inline env mapping (applied after env files, overrides them). */
1707
+ env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
1708
+ /** Local checkpoint dir for served agents (durable HITL threads). */
1709
+ checkpointer: z.ZodOptional<z.ZodObject<{
1710
+ dir: z.ZodString;
1711
+ }, "strip", z.ZodTypeAny, {
1712
+ dir: string;
1713
+ }, {
1714
+ dir: string;
1715
+ }>>;
1716
+ http: z.ZodDefault<z.ZodObject<{
1717
+ corsOrigins: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
1718
+ }, "strip", z.ZodTypeAny, {
1719
+ corsOrigins: string[];
1720
+ }, {
1721
+ corsOrigins?: string[] | undefined;
1722
+ }>>;
1723
+ agents: z.ZodArray<z.ZodUnion<[z.ZodObject<{
1724
+ name: z.ZodString;
1725
+ description: z.ZodDefault<z.ZodString>;
1726
+ systemPrompt: z.ZodDefault<z.ZodString>;
1727
+ model: z.ZodString;
1728
+ port: z.ZodOptional<z.ZodNumber>;
1729
+ skills: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
1730
+ filesystem: z.ZodOptional<z.ZodString>;
1731
+ todos: z.ZodDefault<z.ZodBoolean>;
1732
+ maxSteps: z.ZodDefault<z.ZodNumber>;
1733
+ sessionDir: z.ZodOptional<z.ZodString>;
1734
+ /** Extra env file for this agent (keys override framework-level). */
1735
+ envFile: z.ZodOptional<z.ZodString>;
1736
+ }, "strip", z.ZodTypeAny, {
1737
+ name: string;
1738
+ model: string;
1739
+ todos: boolean;
1740
+ systemPrompt: string;
1741
+ description: string;
1742
+ maxSteps: number;
1743
+ skills: string[];
1744
+ filesystem?: string | undefined;
1745
+ port?: number | undefined;
1746
+ sessionDir?: string | undefined;
1747
+ envFile?: string | undefined;
1748
+ }, {
1749
+ name: string;
1750
+ model: string;
1751
+ todos?: boolean | undefined;
1752
+ filesystem?: string | undefined;
1753
+ systemPrompt?: string | undefined;
1754
+ description?: string | undefined;
1755
+ maxSteps?: number | undefined;
1756
+ port?: number | undefined;
1757
+ skills?: string[] | undefined;
1758
+ sessionDir?: string | undefined;
1759
+ envFile?: string | undefined;
1760
+ }>, z.ZodObject<{
1761
+ file: z.ZodString;
1762
+ }, "strip", z.ZodUnknown, z.objectOutputType<{
1763
+ file: z.ZodString;
1764
+ }, z.ZodUnknown, "strip">, z.objectInputType<{
1765
+ file: z.ZodString;
1766
+ }, z.ZodUnknown, "strip">>]>, "many">;
1767
+ }, "strip", z.ZodTypeAny, {
1768
+ server: {
1769
+ host: string;
1770
+ basePort: number;
1771
+ };
1772
+ http: {
1773
+ corsOrigins: string[];
1774
+ };
1775
+ agents: ({
1776
+ name: string;
1777
+ model: string;
1778
+ todos: boolean;
1779
+ systemPrompt: string;
1780
+ description: string;
1781
+ maxSteps: number;
1782
+ skills: string[];
1783
+ filesystem?: string | undefined;
1784
+ port?: number | undefined;
1785
+ sessionDir?: string | undefined;
1786
+ envFile?: string | undefined;
1787
+ } | z.objectOutputType<{
1788
+ file: z.ZodString;
1789
+ }, z.ZodUnknown, "strip">)[];
1790
+ checkpointer?: {
1791
+ dir: string;
1792
+ } | undefined;
1793
+ envFile?: string | string[] | undefined;
1794
+ env?: Record<string, string> | undefined;
1795
+ }, {
1796
+ agents: ({
1797
+ name: string;
1798
+ model: string;
1799
+ todos?: boolean | undefined;
1800
+ filesystem?: string | undefined;
1801
+ systemPrompt?: string | undefined;
1802
+ description?: string | undefined;
1803
+ maxSteps?: number | undefined;
1804
+ port?: number | undefined;
1805
+ skills?: string[] | undefined;
1806
+ sessionDir?: string | undefined;
1807
+ envFile?: string | undefined;
1808
+ } | z.objectInputType<{
1809
+ file: z.ZodString;
1810
+ }, z.ZodUnknown, "strip">)[];
1811
+ checkpointer?: {
1812
+ dir: string;
1813
+ } | undefined;
1814
+ envFile?: string | string[] | undefined;
1815
+ server?: {
1816
+ host?: string | undefined;
1817
+ basePort?: number | undefined;
1818
+ } | undefined;
1819
+ env?: Record<string, string> | undefined;
1820
+ http?: {
1821
+ corsOrigins?: string[] | undefined;
1822
+ } | undefined;
1823
+ }>;
1824
+
1825
+ type FrameworkFile = z.infer<typeof FrameworkFileSchema>;
1826
+ type ServedAgent = {
1827
+ name: string;
1828
+ url: string;
1829
+ cardUrl: string;
1830
+ server: A2AServer;
1831
+ };
1832
+ type ResolvedAgentDef = z.infer<typeof AgentDefSchema>;
1833
+ /** loadFrameworkConfig output: every entry resolved to a concrete agent def. */
1834
+ interface LoadedFrameworkFile {
1835
+ server: {
1836
+ host: string;
1837
+ basePort: number;
1838
+ };
1839
+ envFile?: string | string[];
1840
+ env?: Record<string, string>;
1841
+ checkpointer?: {
1842
+ dir: string;
1843
+ };
1844
+ http: {
1845
+ corsOrigins: string[];
1846
+ };
1847
+ agents: ResolvedAgentDef[];
1848
+ }
1849
+ /**
1850
+ * Load an env file if present (silent when missing). `override: false` fills
1851
+ * gaps like plain dotenv (the process environment wins); `override: true`
1852
+ * lets later files beat earlier ones — used for agent-level files, which the
1853
+ * config schema documents as overriding framework-level keys.
1854
+ */
1855
+ declare function loadEnvFile(path: string, override?: boolean): void;
1856
+ declare function loadFrameworkConfig(path: string): LoadedFrameworkFile;
1857
+ declare function buildServedAgent(def: ResolvedAgentDef, opts?: {
1858
+ sessionId?: string;
1859
+ }): Promise<{
1860
+ agent: Agent;
1861
+ card: {
1862
+ name: string;
1863
+ description?: string;
1864
+ };
1865
+ }>;
1866
+ declare function serveFramework(file: LoadedFrameworkFile): Promise<{
1867
+ agents: ServedAgent[];
1868
+ stop: () => Promise<void>;
1869
+ }>;
1870
+
1871
+ /**
1872
+ * Retrieval interface — no bundled vector DB (local-first).
1873
+ * Adapters: InMemoryRetriever (TF-IDF, dependency-free), SparqlRetriever
1874
+ * over any GraphStore. retrievalTool() exposes them to agents.
1875
+ */
1876
+ interface ScoredDoc {
1877
+ id: string;
1878
+ text: string;
1879
+ score: number;
1880
+ meta?: Record<string, unknown>;
1881
+ }
1882
+ interface Retriever {
1883
+ readonly id: string;
1884
+ search(query: string, k?: number): Promise<ScoredDoc[]>;
1885
+ }
1886
+ /** Dependency-free TF-IDF retriever over static documents. */
1887
+ declare class InMemoryRetriever implements Retriever {
1888
+ readonly id = "tfidf";
1889
+ private docs;
1890
+ private df;
1891
+ constructor(docs: {
1892
+ id: string;
1893
+ text: string;
1894
+ meta?: Record<string, unknown>;
1895
+ }[]);
1896
+ private idf;
1897
+ search(query: string, k?: number): Promise<ScoredDoc[]>;
1898
+ }
1899
+ declare function retrievalTool(retriever: Retriever, opts?: {
1900
+ k?: number;
1901
+ name?: string;
1902
+ }): Tool<{
1903
+ query: string;
1904
+ k?: number | undefined;
1905
+ }, ScoredDoc[]>;
1906
+ /** SPARQL-backed retriever: keyword match over the closure, rendered as text. */
1907
+ declare function sparqlRetriever(store: {
1908
+ match: (s: string | null, p: string | null, o: string | null) => Promise<{
1909
+ subject: string;
1910
+ predicate: string;
1911
+ object: string;
1912
+ }[]>;
1913
+ }, opts?: {
1914
+ id?: string;
1915
+ }): Retriever;
1916
+
1917
+ /**
1918
+ * Sandboxed JavaScript execution (node:vm, fresh context per call).
1919
+ * Code runs as a program (completion value returned — wrap object literals
1920
+ * in parens). No require/fetch/process by default; timeout enforced; output
1921
+ * must be JSON-serializable (returned) or a string. For untrusted code
1922
+ * prefer an external container — this is a speed bump, not a security boundary.
1923
+ */
1924
+ declare function runJavascriptTool(opts?: {
1925
+ timeoutMs?: number;
1926
+ maxOutputChars?: number;
1927
+ }): Tool<{
1928
+ code: string;
1929
+ }, {} | null>;
1930
+ /**
1931
+ * Sandbox backend (local-first): one rooted workspace with shell `execute`
1932
+ * plus file tools, matching the Deep Agents backend shape (ls, read_file,
1933
+ * write_file, edit_file, glob, grep + execute).
1934
+ *
1935
+ * Isolation, honestly scoped: fresh cwd jail per call, scrubbed env (no
1936
+ * secrets/proxies inherited), timeouts, output caps with spill-to-file.
1937
+ * This is NOT a container boundary: never put secrets in the sandbox env,
1938
+ * gate `execute` with human-in-the-loop for sensitive work, and treat all
1939
+ * outputs as untrusted input.
1940
+ */
1941
+ interface SandboxOptions {
1942
+ /** Workspace root. Defaults to cwd. */
1943
+ root?: string;
1944
+ timeoutMs?: number;
1945
+ maxOutputChars?: number;
1946
+ /** Extra env vars for shell commands (merged over the scrubbed base). */
1947
+ env?: Record<string, string>;
1948
+ }
1949
+ interface SandboxBackend {
1950
+ readonly root: string;
1951
+ tools(): Tool[];
1952
+ }
1953
+ /** Minimal glob (*, ?, and double-star for crossing directories) over paths relative to root. */
1954
+ declare function matchGlob(pattern: string, path: string): boolean;
1955
+ declare function createSandboxBackend(opts?: SandboxOptions): SandboxBackend;
1956
+
1957
+ /**
1958
+ * Evals: JSONL datasets + scoring + pass-rate reporter.
1959
+ * Offline by default (stub models); set EVAL_LIVE=1 to run cases
1960
+ * against the configured provider instead.
1961
+ */
1962
+ interface EvalExpect {
1963
+ contains?: string[];
1964
+ toolUsed?: string[];
1965
+ noStructuredError?: boolean;
1966
+ }
1967
+ interface EvalCase {
1968
+ id: string;
1969
+ input: string;
1970
+ expect?: EvalExpect;
1971
+ }
1972
+ interface EvalScore {
1973
+ id: string;
1974
+ pass: boolean;
1975
+ detail: string;
1976
+ usage: TokenUsage;
1977
+ }
1978
+ declare function loadJsonl(path: string): EvalCase[];
1979
+ declare function runEval(cases: EvalCase[], makeAgent: (c: EvalCase) => Agent): Promise<{
1980
+ scores: EvalScore[];
1981
+ passRate: number;
1982
+ }>;
1983
+ declare function printReport(scores: EvalScore[], passRate: number): void;
1984
+
1985
+ /**
1986
+ * Tracing exporter: OTel-shaped spans (trace/span ids, timestamps,
1987
+ * attributes) from AgentEvents, sunk to console or JSONL. No OTel SDK —
1988
+ * the shape is compatible, the transport is local-first. Adapters to
1989
+ * Langfuse/LangSmith-style HTTP endpoints can POST these spans unchanged.
1990
+ */
1991
+ interface Span {
1992
+ traceId: string;
1993
+ spanId: string;
1994
+ parentId?: string;
1995
+ name: string;
1996
+ startedAt: string;
1997
+ endedAt?: string;
1998
+ attributes: Record<string, unknown>;
1999
+ }
2000
+ interface SpanSink {
2001
+ emit(span: Span): void;
2002
+ }
2003
+ declare class ConsoleSpanSink implements SpanSink {
2004
+ emit(span: Span): void;
2005
+ }
2006
+ declare class JsonlSpanSink implements SpanSink {
2007
+ private path;
2008
+ constructor(path: string);
2009
+ emit(span: Span): void;
2010
+ }
2011
+ declare class MemorySpanSink implements SpanSink {
2012
+ spans: Span[];
2013
+ emit(span: Span): void;
2014
+ }
2015
+ /** Build AgentEvents that project run/step/tool lifecycle into spans. */
2016
+ declare function tracingEvents(sink: SpanSink, opts?: {
2017
+ traceId?: string;
2018
+ }): AgentEvents;
2019
+ /**
2020
+ * Policy filter: allow/deny tool calls by name pattern before execution.
2021
+ * Denied calls become ToolRejection feedback (model continues) or throw
2022
+ * POLICY_DENY with exitBehavior "error".
2023
+ */
2024
+ declare function policyFilterMiddleware(opts: {
2025
+ allow?: (string | RegExp)[];
2026
+ deny?: (string | RegExp)[];
2027
+ exitBehavior?: "continue" | "error";
2028
+ }): AgentMiddleware;
2029
+
2030
+ /**
2031
+ * Compaction: keep long runs inside the context window without losing meaning.
2032
+ * Strategy (P1): oldest messages -> model/pluggable summarizer -> single
2033
+ * boundary message. Semantic variant keeps extracted triples, drops prose.
2034
+ */
2035
+ interface CompactionOptions {
2036
+ /** Compact when messages exceed this count. Default 40. */
2037
+ maxMessages?: number;
2038
+ /** Summarizer: (messages to compress) -> summary text. Default: extractive stub. */
2039
+ summarize?: (messages: ChatMessage[]) => Promise<string>;
2040
+ }
2041
+ declare function defaultSummarize(messages: ChatMessage[]): Promise<string>;
2042
+ /** Wrap any Memory with auto-compaction. */
2043
+ declare class CompactedMemory implements Memory {
2044
+ private inner;
2045
+ private opts;
2046
+ constructor(inner: Memory, opts?: CompactionOptions);
2047
+ load(): Promise<ChatMessage[]>;
2048
+ save(messages: ChatMessage[]): Promise<void>;
2049
+ clear(): Promise<void>;
2050
+ }
2051
+
2052
+ interface Budget {
2053
+ signal?: AbortSignal;
2054
+ timeoutMs?: number;
2055
+ }
2056
+ /** Runtime guard: abort + timeout. Token/cost budgets land here in P1. */
2057
+ declare function runWithBudget<T>(fn: () => Promise<T>, budget?: Budget): Promise<T>;
2058
+
2059
+ type OrchestrationStrategy = "sequential" | "parallel" | "router";
2060
+ interface OrchestrationPlan {
2061
+ strategy: OrchestrationStrategy;
2062
+ agents: Agent[];
2063
+ /** Max concurrent agents for parallel. Default: all at once. */
2064
+ concurrency?: number;
2065
+ /** Model that picks the agent for router. Defaults to the first agent's model. */
2066
+ routerModel?: ModelProvider;
2067
+ events?: AgentEvents;
2068
+ }
2069
+ interface OrchestratedResult {
2070
+ strategy: OrchestrationStrategy;
2071
+ results: AgentResult[];
2072
+ /** Combined text: last result (sequential/router), joined (parallel). */
2073
+ text: string;
2074
+ /** Router only: index of the chosen agent. */
2075
+ routedTo?: number;
2076
+ }
2077
+ declare function runOrchestrated(plan: OrchestrationPlan, input: string, signal?: AbortSignal): Promise<OrchestratedResult>;
2078
+ declare function runOrchestrated(plan: OrchestrationPlan, input: string, opts?: RunOptions): Promise<OrchestratedResult>;
2079
+
2080
+ /** DAG workflow node. `ctx` maps completed node ids to their results. */
2081
+ interface WorkflowNode {
2082
+ id: string;
2083
+ run: (ctx: Record<string, unknown>, invocationState?: InvocationState) => Promise<unknown>;
2084
+ dependsOn?: string[];
2085
+ /** Retry policy. Default: no retry (attempts: 1). Abort always rethrows. */
2086
+ retry?: {
2087
+ attempts?: number;
2088
+ backoffMs?: number;
2089
+ };
2090
+ }
2091
+ interface WorkflowOptions {
2092
+ signal?: AbortSignal;
2093
+ /** Shared per-run data passed to every node (never sent to models by itself). */
2094
+ invocationState?: InvocationState;
2095
+ }
2096
+ /**
2097
+ * Execute a DAG: topological levels run in order, nodes within a level
2098
+ * run concurrently. Returns id -> result. Throws structured WORKFLOW_* errors.
2099
+ */
2100
+ declare function runWorkflow(nodes: WorkflowNode[], opts?: WorkflowOptions): Promise<Record<string, unknown>>;
2101
+
2102
+ /**
2103
+ * Skills: portable capability packs (SKILL.md + optional tools/resources).
2104
+ * Spec: a skill is a directory with SKILL.md frontmatter
2105
+ * (name, description, version) + markdown body. Loader discovers,
2106
+ * validates, and exposes skills as Tools or prompt injections.
2107
+ */
2108
+ interface Skill {
2109
+ name: string;
2110
+ description: string;
2111
+ version: string;
2112
+ path: string;
2113
+ body: string;
2114
+ tools?: Tool[];
2115
+ }
2116
+ interface SkillLoaderOptions {
2117
+ /** Directories to scan for SKILL.md files. */
2118
+ dirs: string[];
2119
+ /** If true, throw on invalid skill; else skip with warning. Default false. */
2120
+ strict?: boolean;
2121
+ }
2122
+ /** Parse SKILL.md content -> { meta, body }. Pure, testable, no FS. */
2123
+ declare function parseSkillFile(content: string, path?: string): Omit<Skill, "tools">;
2124
+ /** Registry of loaded skills — activation is explicit, never magic. */
2125
+ declare class SkillRegistry {
2126
+ private skills;
2127
+ register(skill: Skill): this;
2128
+ get(name: string): Skill | undefined;
2129
+ list(): Skill[];
2130
+ /** Expose each skill's tools (if any) for Agent consumption. */
2131
+ asTools(): Tool[];
2132
+ }
2133
+ /**
2134
+ * Scan directories for SKILL.md files (one level, plus direct files).
2135
+ * Invalid skills are skipped (or throw when `strict`). Never throws for
2136
+ * missing directories — returns what it finds.
2137
+ */
2138
+ declare function discoverSkills(dirs: string[], opts?: {
2139
+ strict?: boolean;
2140
+ }): Promise<Skill[]>;
2141
+ /** Load + register every discoverable skill. Duplicate names throw. */
2142
+ declare function loadSkillsInto(registry: SkillRegistry, dirs: string[], opts?: {
2143
+ strict?: boolean;
2144
+ }): Promise<Skill[]>;
2145
+ /**
2146
+ * Local skill routing — dependency-free TF-IDF cosine over skill
2147
+ * name+description. Explicit `$name` mentions always win. No embedding
2148
+ * APIs, no network. A pluggable embedder can replace `scoreSkills`
2149
+ * later without changing `matchSkills`.
2150
+ */
2151
+ declare function tokenize(text: string): string[];
2152
+ declare function scoreSkills(registry: SkillRegistry, input: string): {
2153
+ skill: Skill;
2154
+ score: number;
2155
+ }[];
2156
+ declare function matchSkills(registry: SkillRegistry, input: string, threshold?: number): Skill[];
2157
+
2158
+ /**
2159
+ * MCP (Model Context Protocol) client.
2160
+ * - Streamable HTTP transport (POST JSON-RPC; JSON or SSE responses).
2161
+ * - stdio transport (spawned server, line-delimited JSON-RPC).
2162
+ * - `mcpToolsToFramework` bridges MCP tool defs to framework Tools,
2163
+ * converting JSON Schema input schemas to zod.
2164
+ */
2165
+ interface McpToolDef {
2166
+ name: string;
2167
+ description?: string;
2168
+ inputSchema: Record<string, unknown>;
2169
+ }
2170
+ interface McpClientOptions {
2171
+ fetchFn?: typeof fetch;
2172
+ headers?: Record<string, string>;
2173
+ clientName?: string;
2174
+ }
2175
+ /** Minimal JSON Schema -> zod (objects, string/number/integer/boolean/array/enum/null; else unknown). */
2176
+ declare function jsonSchemaToZod(schema: Record<string, unknown>): z.ZodType<unknown>;
2177
+ /** MCP client over Streamable HTTP. */
2178
+ declare class McpHttpClient {
2179
+ readonly serverId: string;
2180
+ private url;
2181
+ private headers;
2182
+ private fetchFn;
2183
+ private clientName;
2184
+ private sessionId?;
2185
+ private connected;
2186
+ constructor(url: string, opts?: McpClientOptions & {
2187
+ serverId?: string;
2188
+ });
2189
+ private rpc;
2190
+ /** JSON-RPC notification — no id, no response expected. */
2191
+ private notify;
2192
+ private rpcInner;
2193
+ connect(): Promise<{
2194
+ name: string;
2195
+ version?: string;
2196
+ }>;
2197
+ private requireConnected;
2198
+ listTools(): Promise<McpToolDef[]>;
2199
+ callTool(name: string, args: unknown): Promise<unknown>;
2200
+ close(): Promise<void>;
2201
+ }
2202
+ /** MCP client over stdio (spawns `command args`, speaks line-delimited JSON-RPC). */
2203
+ declare class McpStdioClient {
2204
+ private command;
2205
+ private args;
2206
+ readonly serverId: string;
2207
+ private child?;
2208
+ private buffer;
2209
+ private pending;
2210
+ private clientName;
2211
+ constructor(command: string, args?: string[], opts?: {
2212
+ serverId?: string;
2213
+ clientName?: string;
2214
+ });
2215
+ connect(): Promise<void>;
2216
+ private request;
2217
+ listTools(): Promise<McpToolDef[]>;
2218
+ callTool(name: string, args: unknown): Promise<unknown>;
2219
+ close(): Promise<void>;
2220
+ }
2221
+ type AnyMcpClient = Pick<McpHttpClient, "serverId" | "listTools" | "callTool" | "close">;
2222
+ interface McpClient {
2223
+ readonly serverId: string;
2224
+ listTools(): Promise<McpToolDef[]>;
2225
+ callTool(name: string, args: unknown): Promise<unknown>;
2226
+ close(): Promise<void>;
2227
+ }
2228
+ /** Turn MCP tool defs into framework Tools (namespaced `server.tool` on collision). */
2229
+ declare function mcpToolsToFramework(client: McpClient, defs?: McpToolDef[]): Promise<Tool[]>;
2230
+ declare function connectMcpHttp(url: string, opts?: McpClientOptions): Promise<McpHttpClient>;
2231
+ declare function connectMcpStdio(command: string, args?: string[]): Promise<McpStdioClient>;
2232
+
2233
+ interface PromptTemplate {
2234
+ name: string;
2235
+ version: string;
2236
+ template: string;
2237
+ render(vars: Record<string, string | number>): string;
2238
+ }
2239
+ declare function definePrompt(name: string, template: string, version?: string): PromptTemplate;
2240
+ /** Load `--- name, version ---` frontmatter + markdown body from disk. */
2241
+ declare function loadPromptFile(path: string): PromptTemplate;
2242
+ /** A/B variants: pick by traffic split (weighted random) or explicit variant. */
2243
+ declare function abPrompts(variants: {
2244
+ name: string;
2245
+ template: string;
2246
+ version?: string;
2247
+ weight?: number;
2248
+ }[], pick?: string): PromptTemplate;
2249
+
2250
+ /**
2251
+ * Remote SPARQL adapter (roadmap P2-sem): talk to real SPARQL endpoints —
2252
+ * Wikidata Query Service, Fuseki, GraphDB, Virtuoso — with auth and pinned
2253
+ * prefixes. The local GraphStore stays the read path for closures; this is
2254
+ * for data that lives OUTSIDE the agent's own graph.
2255
+ *
2256
+ * Protocol: SPARQL 1.1 — SELECT via POST `application/sparql-query`,
2257
+ * UPDATE via POST `application/sparql-update`; SELECT responses must be
2258
+ * `application/sparql-results+json` (we ask for it in Accept).
2259
+ */
2260
+ type SparqlAuth = {
2261
+ type: "basic";
2262
+ user: string;
2263
+ password: string;
2264
+ } | {
2265
+ type: "bearer";
2266
+ token: string;
2267
+ } | {
2268
+ type: "header";
2269
+ name: string;
2270
+ value: string;
2271
+ };
2272
+ interface RemoteSparqlOptions {
2273
+ /** Query endpoint URL (e.g. https://query.wikidata.org/sparql). */
2274
+ endpoint: string;
2275
+ /** Update endpoint; defaults to `endpoint`. */
2276
+ updateEndpoint?: string;
2277
+ auth?: SparqlAuth;
2278
+ /** Pinned prefixes, prepended to every query as PREFIX declarations. */
2279
+ prefixes?: Record<string, string>;
2280
+ /** Extra request headers (merged over the defaults below). */
2281
+ headers?: Record<string, string>;
2282
+ fetchFn?: typeof fetch;
2283
+ /** Per-request timeout. Default 30s. */
2284
+ timeoutMs?: number;
2285
+ /**
2286
+ * Built-in retries for transient endpoints (429/5xx/network). Rate limits
2287
+ * are common on public SPARQL endpoints; the middleware retry is a separate
2288
+ * layer for MODEL calls only. Default 2. Honors Retry-After when present.
2289
+ */
2290
+ maxRetries?: number;
2291
+ }
2292
+ /** One SELECT result row: variable name -> plain string term. */
2293
+ type SparqlRow = Record<string, string>;
2294
+ declare class RemoteSparqlAdapter {
2295
+ readonly endpoint: string;
2296
+ private readonly updateEndpoint;
2297
+ private readonly prefixes;
2298
+ private readonly extraHeaders;
2299
+ private readonly fetchFn;
2300
+ private readonly timeoutMs;
2301
+ private readonly maxRetries;
2302
+ private readonly auth?;
2303
+ constructor(opts: RemoteSparqlOptions);
2304
+ /** Prepend pinned PREFIX declarations so caller queries stay short. */
2305
+ withPrefixes(query: string): string;
2306
+ private headers;
2307
+ private post;
2308
+ /**
2309
+ * SELECT over the remote endpoint. Returns rows of plain-string terms
2310
+ * (same shape as the local `executeSelect`) so both path kinds compose.
2311
+ */
2312
+ select(query: string): Promise<SparqlRow[]>;
2313
+ /**
2314
+ * SPARQL 1.1 UPDATE (INSERT/DELETE DATA, DELETE WHERE...) against the
2315
+ * update endpoint. Opt-in — never wire this into a read-only agent.
2316
+ */
2317
+ update(query: string): Promise<void>;
2318
+ }
2319
+ /** Agent-facing tool. SELECT always; UPDATE only when `allowUpdate`. */
2320
+ declare function remoteSparqlTool(adapter: RemoteSparqlAdapter, opts?: {
2321
+ allowUpdate?: boolean;
2322
+ }): Tool;
2323
+
2324
+ /**
2325
+ * Entity linking (roadmap P2-sem): turn free-text mentions into graph IRIs.
2326
+ * Case-insensitive label index (rdfs:label / skos:prefLabel / skos:altLabel)
2327
+ * over the store closure, canonicalized through owl:sameAs groups — a
2328
+ * mention linked through any alias resolves to ONE representative IRI.
2329
+ *
2330
+ * docs/07 rule 2, autonomy-first: the model calls `propose_mapping` and the
2331
+ * mapping commits on proposal (default) as a provenance-carrying
2332
+ * skos:altLabel the linker sees from then on — matching the autonomous write
2333
+ * path everywhere else (graph_add). Human review is the opt-out:
2334
+ * `new MappingProposals({ autonomy: false })` queues proposals for decide(),
2335
+ * or gate the tool with humanInTheLoopMiddleware. Provenance is mandatory
2336
+ * either way.
2337
+ */
2338
+ declare const LABEL_PREDICATES: Set<string>;
2339
+ /** Prefixes used to expand/compact IRIs for JSON-LD I/O (nullable values pass through). */
2340
+ declare const JSONLD_PREFIXES: Record<string, string>;
2341
+ interface LinkedEntity {
2342
+ /** Canonical (sameAs-group representative) IRI, in the store's term form. */
2343
+ iri: string;
2344
+ label?: string;
2345
+ score: number;
2346
+ /** Other IRIs the same entity is known as (the sameAs group). */
2347
+ sameAsGroup: string[];
2348
+ }
2349
+ declare class EntityLinker {
2350
+ private store;
2351
+ constructor(store: GraphStore);
2352
+ /** Union-find over owl:sameAs pairs: every alias cluster -> one representative. */
2353
+ private sameAsGroups;
2354
+ /** Mention -> candidate entities, best first, canonicalized via sameAs. */
2355
+ link(mention: string, k?: number): Promise<LinkedEntity[]>;
2356
+ }
2357
+ /** link_entity agent tool: mention -> canonical IRIs with scores. */
2358
+ declare function linkEntityTool(linker: EntityLinker): Tool<{
2359
+ mention: string;
2360
+ k?: number | undefined;
2361
+ }, LinkedEntity[]>;
2362
+ interface MappingProposal {
2363
+ id: string;
2364
+ /** The source-side term: usually a raw column header / mention string. */
2365
+ from: string;
2366
+ /** The proposed target: a canonical ontology IRI. */
2367
+ to: string;
2368
+ /** Provenance for the eventual commit (required by GraphStore.validate). */
2369
+ source: string;
2370
+ status: "pending" | "approved" | "rejected";
2371
+ /** True when autonomy committed it on proposal (no human turn). */
2372
+ committedByAutonomy?: boolean;
2373
+ proposedAt: string;
2374
+ }
2375
+ type MappingDecision = "approved" | "rejected";
2376
+ interface MappingProposalsOptions {
2377
+ /**
2378
+ * Autonomy: proposals commit IMMEDIATELY on proposal. DEFAULT ON — the
2379
+ * agent's whole write path is autonomous (graph_add), so mapping should
2380
+ * not be the one gate keeping a human in the loop. Set `autonomy: false`
2381
+ * to queue proposals for human decide() instead, or gate the tool with
2382
+ * humanInTheLoopMiddleware.
2383
+ */
2384
+ autonomy?: boolean;
2385
+ /** Store to commit against. Without one there is nowhere to commit — proposals queue as pending. */
2386
+ store?: GraphStore;
2387
+ }
2388
+ declare class MappingProposals {
2389
+ private opts;
2390
+ private seq;
2391
+ private items;
2392
+ constructor(opts?: MappingProposalsOptions);
2393
+ /** True when proposals commit themselves (autonomy on AND a store bound). */
2394
+ get autonomy(): boolean;
2395
+ private commit;
2396
+ /**
2397
+ * Record an LLM-proposed mapping. With autonomy (default) + a bound store
2398
+ * it commits right away, provenance required; with `autonomy: false` (or
2399
+ * no store bound) it queues as pending until decide().
2400
+ */
2401
+ propose(from: string, to: string, source: string): Promise<MappingProposal>;
2402
+ list(status?: MappingProposal["status"]): MappingProposal[];
2403
+ /** Human decision. `approved` also commits the alias into the graph. */
2404
+ decide(store: GraphStore, id: string, decision: MappingDecision): Promise<MappingProposal | undefined>;
2405
+ }
2406
+ declare function proposeMappingTool(proposals: MappingProposals): Tool<{
2407
+ to: string;
2408
+ from: string;
2409
+ source: string;
2410
+ }, string | {
2411
+ id: string;
2412
+ status: string;
2413
+ committed: boolean;
2414
+ note?: undefined;
2415
+ } | {
2416
+ id: string;
2417
+ status: string;
2418
+ note: string;
2419
+ committed?: undefined;
2420
+ }>;
2421
+ /**
2422
+ * Quads -> expanded JSON-LD. Named graphs round-trip: quads carrying a
2423
+ * `graph` become JSON-LD named-graph entries ({"@id": graph, "@graph": ...}),
2424
+ * graph-less quads land in the default graph. Provenance fields
2425
+ * (source/rule) do not round-trip — JSON-LD carries the statements, the
2426
+ * store keeps the evidence.
2427
+ */
2428
+ declare function quadsToJsonLd(quads: Quad[], prefixes?: Record<string, string>): Record<string, unknown>;
2429
+ /** Expanded JSON-LD -> quads (named graphs preserved; prefixed terms restored where the map covers them). */
2430
+ declare function jsonldToQuads(doc: {
2431
+ "@graph"?: unknown[];
2432
+ } & Record<string, unknown>, prefixes?: Record<string, string>): {
2433
+ subject: string;
2434
+ predicate: string;
2435
+ object: string;
2436
+ graph?: string;
2437
+ }[];
2438
+
2439
+ /**
2440
+ * Ontology evolution (roadmap P2-sem, docs/07 lifecycle stage "evolve"):
2441
+ * TBox v3 -> v4 with a migration that is checked before AND after by a
2442
+ * conformance battery, and that never destroys the old store.
2443
+ *
2444
+ * The store has no delete by design; migration therefore REBUILDS: explicit
2445
+ * facts are exported from the old store, transformed (axiom add/remove,
2446
+ * term renames, deprecations), re-validated and re-entailed into a fresh
2447
+ * v4 store. The v3 store survives untouched — rollback is "don't adopt".
2448
+ */
2449
+ interface ConformanceCheck {
2450
+ id: string;
2451
+ /**
2452
+ * SPARQL-subset SELECT (see executeSelect). Passes when the row count is
2453
+ * within [minRows, maxRows]. Default: at least one row (ask-style);
2454
+ * `minRows: 0, maxRows: 0` asserts absence.
2455
+ */
2456
+ ask?: string;
2457
+ minRows?: number;
2458
+ maxRows?: number;
2459
+ /** An extra SHACL shape the closure must satisfy. */
2460
+ shape?: NodeShape;
2461
+ /** Why this check matters — surfaces in failure reports. */
2462
+ reason?: string;
2463
+ }
2464
+ interface ConformanceResult {
2465
+ id: string;
2466
+ passed: boolean;
2467
+ detail: string;
2468
+ }
2469
+ interface ConformanceReport {
2470
+ passed: boolean;
2471
+ results: ConformanceResult[];
2472
+ }
2473
+ /** Run a battery of checks against a store's closure. */
2474
+ declare function runConformance(store: InMemoryGraphStore, battery: ConformanceCheck[]): Promise<ConformanceReport>;
2475
+ interface TBoxMigrationSpec {
2476
+ from: string;
2477
+ to: string;
2478
+ /** New TBox axioms to add (provenance required by the store). */
2479
+ added?: Quad[];
2480
+ /** Exact axioms to retract (matched on subject|predicate|object). */
2481
+ removed?: {
2482
+ subject: string;
2483
+ predicate: string;
2484
+ object: string;
2485
+ }[];
2486
+ /**
2487
+ * Term renames applied to BOTH the TBox and ABox in all three positions
2488
+ * (subject/predicate/object): class splits, predicate renames, IRI moves.
2489
+ */
2490
+ renames?: {
2491
+ from: string;
2492
+ to: string;
2493
+ }[];
2494
+ /** Terms deprecated in this version; with `replacement`, uses are rewritten. */
2495
+ deprecations?: {
2496
+ term: string;
2497
+ replacement?: string;
2498
+ reason: string;
2499
+ }[];
2500
+ /** Shapes/rules carried by the NEW store (defaults to the old store's). */
2501
+ shapes?: NodeShape[];
2502
+ rules?: StoreOptions["rules"];
2503
+ }
2504
+ interface MigrationReport {
2505
+ from: string;
2506
+ to: string;
2507
+ status: "migrated" | "aborted" | "failed";
2508
+ addedQuads: number;
2509
+ removedQuads: number;
2510
+ rewrittenQuads: number;
2511
+ /** Named graph the v4 TBox axioms were written to (match(.., ..., tboxGraph)). */
2512
+ tboxGraph?: string;
2513
+ deprecatedWarnings: string[];
2514
+ errors: string[];
2515
+ preBattery?: ConformanceReport;
2516
+ postBattery?: ConformanceReport;
2517
+ }
2518
+ interface MigrationResult {
2519
+ report: MigrationReport;
2520
+ /** Present on success — the new-version store with a fresh closure. The v3 store is untouched. */
2521
+ store?: InMemoryGraphStore;
2522
+ }
2523
+ /** Ontology-defining predicates: shared with the review auditor. */
2524
+ declare const TBOX_PREDICATES: Set<string>;
2525
+ /** rdf:type objects that mark a TERM declaration, not an instance fact. */
2526
+ declare const OWL_VOCAB: Set<string>;
2527
+ /**
2528
+ * Migrate a TBox. Order: pre-battery (abort on failure) -> rebuild ->
2529
+ * post-battery (report failure; caller decides whether to adopt).
2530
+ */
2531
+ declare function migrateTBox(oldStore: InMemoryGraphStore, spec: TBoxMigrationSpec, opts?: {
2532
+ battery?: ConformanceCheck[];
2533
+ factory?: (opts: StoreOptions) => InMemoryGraphStore;
2534
+ tboxGraph?: string | false;
2535
+ }): Promise<MigrationResult>;
2536
+
2537
+ interface TermStat {
2538
+ term: string;
2539
+ kind: "class" | "property";
2540
+ /** Explicit ABox uses: instance-of counts for classes, fact counts for properties. */
2541
+ uses: number;
2542
+ /** TBox axioms mentioning the term (declarations, subClassOf, domain/range, ...). */
2543
+ axiomCount: number;
2544
+ label?: string;
2545
+ }
2546
+ interface OntologyReview {
2547
+ classes: TermStat[];
2548
+ properties: TermStat[];
2549
+ /** Used in data with zero TBox declarations — the "what to add" list. */
2550
+ undeclared: TermStat[];
2551
+ /** Declared but never used in any explicit fact. */
2552
+ unused: string[];
2553
+ /** Terms without rdfs:label / skos:prefLabel / altLabel. */
2554
+ unlabeled: string[];
2555
+ /** Properties missing rdfs:domain / rdfs:range axioms. */
2556
+ missingDomain: string[];
2557
+ missingRange: string[];
2558
+ /** Explicit quads vs closure size — how much the ontology explains. */
2559
+ explicitQuads: number;
2560
+ closureQuads: number;
2561
+ }
2562
+ /** Audit the store: inventory + gap list. Pure read — never mutates. */
2563
+ declare function reviewOntology(store: InMemoryGraphStore): Promise<OntologyReview>;
2564
+ interface ShapeInductionOptions {
2565
+ /** Classes with fewer instances produce no shape. Default 2. */
2566
+ minInstances?: number;
2567
+ /** Only emit a property shape when >= this fraction of instances have it. Default 0.5. */
2568
+ coverage?: number;
2569
+ }
2570
+ /**
2571
+ * Propose NodeShapes by observing explicit instance data: for each class,
2572
+ * per-property coverage, cardinality, datatypes, node kinds across its
2573
+ * instances. PROPOSAL ONLY per docs/07 (shapes are builder-owned).
2574
+ */
2575
+ declare function proposeShapes(store: InMemoryGraphStore, opts?: ShapeInductionOptions): Promise<NodeShape[]>;
2576
+ /**
2577
+ * Adopt proposed shapes: each shape is validated against the CURRENT closure
2578
+ * in isolation — a shape the existing data already violates is rejected with
2579
+ * its violations (1:1 mapping, no guesswork), the clean ones are registered.
2580
+ * Versioned adoption: migrateTBox({ shapes }) instead.
2581
+ */
2582
+ declare function adoptShapes(store: InMemoryGraphStore, shapes: NodeShape[]): Promise<{
2583
+ adopted: NodeShape[];
2584
+ rejected: {
2585
+ shape: NodeShape;
2586
+ violations: string[];
2587
+ }[];
2588
+ }>;
2589
+ /** review_ontology agent tool: inventory + gaps, straight from the store. */
2590
+ declare function reviewOntologyTool(store: InMemoryGraphStore): Tool<{}, OntologyReview>;
2591
+ /** propose_shapes agent tool: SHACL candidates induced from instance data. */
2592
+ declare function proposeShapesTool(store: InMemoryGraphStore, opts?: ShapeInductionOptions): Tool<{}, NodeShape[]>;
2593
+
2594
+ /**
2595
+ * Semantic layer. See docs/07-semantics-governance.md.
2596
+ * In-memory store: RDFS-subset + OWL property axioms entailment with proofs,
2597
+ * SHACL-subset validation, versioned CONSTRUCT-style rules, SPARQL-subset
2598
+ * read tools, and GraphMemory. Remote SPARQL, entity linking + JSON-LD I/O,
2599
+ * and TBox evolution live in sibling modules, re-exported here.
2600
+ */
2601
+ interface Quad {
2602
+ subject: string;
2603
+ predicate: string;
2604
+ object: string;
2605
+ graph?: string;
2606
+ /** Provenance: who vouched, source URI, valid-until. Required on agent writes. */
2607
+ source?: string;
2608
+ derivedFrom?: string;
2609
+ rule?: string;
2610
+ }
2611
+ interface ShapeReport {
2612
+ valid: boolean;
2613
+ violations: {
2614
+ message: string;
2615
+ node?: string;
2616
+ path?: string;
2617
+ }[];
2618
+ }
2619
+ /** Minimal triple-store contract — N3 in-memory first, remote SPARQL later. */
2620
+ interface GraphStore {
2621
+ add(quads: Quad[]): Promise<void>;
2622
+ /**
2623
+ * Match by pattern; null/undefined = wildcard (including the graph slot).
2624
+ * Queries the entailment closure. A `graph` value selects ONE named
2625
+ * graph — the same s/p/o CAN live in several graphs; identity includes it.
2626
+ */
2627
+ match(s?: string | null, p?: string | null, o?: string | null, g?: string | null): Promise<Quad[]>;
2628
+ validate(quads: Quad[]): Promise<ShapeReport>;
2629
+ /** Proof chain for an entailed fact: premises + rule id. Null for explicit facts. */
2630
+ why(quad: Quad): Promise<{
2631
+ premises: Quad[];
2632
+ rule: string;
2633
+ } | null>;
2634
+ }
2635
+ /** SHACL-subset shape: class-scoped property constraints. */
2636
+ interface PropertyShape {
2637
+ path: string;
2638
+ minCount?: number;
2639
+ maxCount?: number;
2640
+ datatype?: string;
2641
+ nodeKind?: "iri" | "literal";
2642
+ hasValue?: string;
2643
+ }
2644
+ interface NodeShape {
2645
+ targetClass: string;
2646
+ properties: PropertyShape[];
2647
+ }
2648
+ /** Versioned CONSTRUCT-style rule over triple patterns (?vars). */
2649
+ interface TriplePattern {
2650
+ subject: string;
2651
+ predicate: string;
2652
+ object: string;
2653
+ }
2654
+ interface GraphRule {
2655
+ id: string;
2656
+ version?: string;
2657
+ where: TriplePattern[];
2658
+ construct: TriplePattern[];
2659
+ }
2660
+ interface StoreOptions {
2661
+ shapes?: NodeShape[];
2662
+ rules?: GraphRule[];
2663
+ }
2664
+ declare class InMemoryGraphStore implements GraphStore {
2665
+ private quads;
2666
+ private derivations;
2667
+ private shapes;
2668
+ private rules;
2669
+ constructor(opts?: StoreOptions);
2670
+ addShapes(...shapes: NodeShape[]): this;
2671
+ addRules(...rules: GraphRule[]): this;
2672
+ /** Registered SHACL shapes (carried to new stores by TBox migrations). */
2673
+ ontologyShapes(): NodeShape[];
2674
+ /** Registered CONSTRUCT rules (versioned with the ontology they encode). */
2675
+ ontologyRules(): GraphRule[];
2676
+ /** Identity includes the named graph: the same s/p/o in two graphs are two quads. */
2677
+ private key;
2678
+ add(quads: Quad[]): Promise<void>;
2679
+ match(s?: string | null, p?: string | null, o?: string | null, g?: string | null): Promise<Quad[]>;
2680
+ /** Structural + provenance check. Full SHACL engine lands in P1-sem. */
2681
+ validate(quads: Quad[]): Promise<ShapeReport>;
2682
+ why(quad: Quad): Promise<{
2683
+ premises: Quad[];
2684
+ rule: string;
2685
+ } | null>;
2686
+ /** Functional properties must have at most one value per subject (conflict, not a second fact). */
2687
+ private checkFunctional;
2688
+ /** SHACL-subset validation over a quad set. */
2689
+ checkShapes(quads: Quad[]): ShapeReport;
2690
+ private insert;
2691
+ /**
2692
+ * RDFS subset + OWL property axioms + versioned rules, to fixpoint:
2693
+ * - RDFS-SUB-TRANS / RDFS-TYPE / RDFS-SUBPROP-TRANS / RDFS-SUBPROP / RDFS-DOMAIN / RDFS-RANGE
2694
+ * - OWL-TRANSITIVE / OWL-SYMMETRIC / OWL-INVERSE (inverseOf both directions)
2695
+ * - <ruleId>@<version> for each applied GraphRule (premises tracked for why())
2696
+ */
2697
+ private entailToFixpoint;
2698
+ private applyOwl;
2699
+ private applyRules;
2700
+ }
2701
+ interface PatternBinding {
2702
+ vars: Map<string, string>;
2703
+ quads: Quad[];
2704
+ }
2705
+ /** Conjunctive matching of patterns against quads (nested-loop join). */
2706
+ declare function matchPatterns(patterns: TriplePattern[], quads: Quad[]): PatternBinding[];
2707
+ declare function instantiate(term: string, vars: Map<string, string>): string;
2708
+ interface SparqlSelect {
2709
+ variables: string[];
2710
+ patterns: TriplePattern[];
2711
+ }
2712
+ /**
2713
+ * Minimal SELECT parser: `SELECT ?a ?b WHERE { s p o . ... }`.
2714
+ * Terms: ?vars, <iris>, prefixed names, "literals" (^^datatype/@lang ok).
2715
+ * Anything else throws — this is a documented subset, not full SPARQL.
2716
+ */
2717
+ declare function parseSelect(query: string): SparqlSelect;
2718
+ /** Execute a SELECT against the store closure. Returns variable bindings. */
2719
+ declare function executeSelect(store: GraphStore, query: string): Promise<Record<string, string>[]>;
2720
+
2721
+ /** Read-only SPARQL SELECT over the entailment closure. */
2722
+ declare function sparqlSelectTool(store: GraphStore): Tool<{
2723
+ query: string;
2724
+ }, Record<string, string>[]>;
2725
+ /** Ontology lookup: find classes/properties/labels matching a term. */
2726
+ declare function ontologyLookupTool(store: GraphStore): Tool<{
2727
+ term: string;
2728
+ limit?: number | undefined;
2729
+ }, {
2730
+ subject: string;
2731
+ predicate: string;
2732
+ object: string;
2733
+ }[]>;
2734
+ declare const TurtleQuadSchema: z.ZodObject<{
2735
+ subject: z.ZodString;
2736
+ predicate: z.ZodString;
2737
+ object: z.ZodString;
2738
+ source: z.ZodString;
2739
+ }, "strip", z.ZodTypeAny, {
2740
+ object: string;
2741
+ source: string;
2742
+ subject: string;
2743
+ predicate: string;
2744
+ }, {
2745
+ object: string;
2746
+ source: string;
2747
+ subject: string;
2748
+ predicate: string;
2749
+ }>;
2750
+ /**
2751
+ * Autonomous validated write: SHACL + provenance + functional checks run
2752
+ * inside the store. Violations return as tool results (not throws) so the
2753
+ * model repairs and retries on its own — autonomy without anarchy.
2754
+ */
2755
+ declare function graphAddTool(store: GraphStore): Tool<{
2756
+ quads: {
2757
+ object: string;
2758
+ source: string;
2759
+ subject: string;
2760
+ predicate: string;
2761
+ }[];
2762
+ }, string | {
2763
+ committed: number;
2764
+ inferred: number;
2765
+ }>;
2766
+ type ClaimVerdict = "grounded" | "unknown" | "contradicted";
2767
+ /**
2768
+ * Anti-hallucination primitive: is this triple in the closure (grounded),
2769
+ * absent (unknown — do not assert), or clashing with a functional value
2770
+ * (contradicted)? Ask before answering from memory.
2771
+ */
2772
+ declare function claimCheckTool(store: GraphStore): Tool<{
2773
+ object: string;
2774
+ subject: string;
2775
+ predicate: string;
2776
+ }, {
2777
+ verdict: ClaimVerdict;
2778
+ proof: {
2779
+ premises: Quad[];
2780
+ rule: string;
2781
+ } | null;
2782
+ } | {
2783
+ verdict: ClaimVerdict;
2784
+ proof: {
2785
+ existing: string[];
2786
+ related?: undefined;
2787
+ };
2788
+ } | {
2789
+ verdict: ClaimVerdict;
2790
+ proof: {
2791
+ related: string[];
2792
+ existing?: undefined;
2793
+ } | null;
2794
+ }>;
2795
+
2796
+ /**
2797
+ * Session memory + long-term store in one:
2798
+ * - load(): recent messages + top-k closure facts relevant to the latest
2799
+ * user turn (keyword overlap), rendered as a knowledge message.
2800
+ * - save(): delegates to inner memory (extraction of triples from prose
2801
+ * stays model-driven via graph_add — never silent parsing).
2802
+ * - exportState()/importState(): quads JSON for SessionManager snapshots (LTS).
2803
+ */
2804
+ declare class GraphMemory implements Memory {
2805
+ private store;
2806
+ private inner;
2807
+ private opts;
2808
+ constructor(store: GraphStore, inner: Memory, opts?: {
2809
+ facts?: number;
2810
+ });
2811
+ load(): Promise<ChatMessage[]>;
2812
+ save(messages: ChatMessage[]): Promise<void>;
2813
+ clear(): Promise<void>;
2814
+ /** Serialize the closure for snapshots / long-term persistence. */
2815
+ exportState(): Promise<{
2816
+ quads: Quad[];
2817
+ }>;
2818
+ /** Restore a previously exported closure (facts become explicit again). */
2819
+ importState(state: {
2820
+ quads: Quad[];
2821
+ }): Promise<void>;
2822
+ }
2823
+
2824
+ declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
2825
+ /**
2826
+ * Local token estimate — dependency-free approximation, not a BPE.
2827
+ * Counts word-ish runs, numbers, CJK characters, and punctuation clusters
2828
+ * separately (close to subword behavior on prose; ±30% on code).
2829
+ * Calibrated so `estimateTokens("abcd") === 1`. Prefer provider usage
2830
+ * metadata when available; use this for budgets and triggers only.
2831
+ */
2832
+ declare function estimateTokens(text: string): number;
2833
+ /** Rough USD cost for usage against a per-1M-token price table. */
2834
+ declare function estimateCostUsd(usage: {
2835
+ inputTokens: number;
2836
+ outputTokens: number;
2837
+ }, price: {
2838
+ inputPerMillion: number;
2839
+ outputPerMillion: number;
2840
+ }): number;
2841
+
2842
+ export { A2AClient, type A2AClientOptions, A2AServer, type A2AServerOptions, Agent, type AgentCard, AgentClient, type AgentClientOptions, AgentError, type AgentEvents, type AgentId, type AgentMiddleware, type AgentOptions, type AgentResult, AgentState, type AnthropicOptions, AnthropicProvider, type AnyMcpClient, AudioBlockSchema, type BackoffOptions, type Brand, type Budget, type ChatMessage, ChatMessageSchema, type Checkpointer, type ClaimVerdict, ClearToolUsesEdit, type ClearToolUsesOptions, CompactedMemory, type CompactionOptions, type CompleteOptions, type ConformanceCheck, type ConformanceReport, type ConformanceResult, type ConsoleEventsOptions, ConsoleSpanSink, type ContentBlock, ContentBlockSchema, type ConversationManager, type DoneEvent, EntityLinker, type EvalCase, type EvalExpect, type EvalScore, type ExecutedToolCall, FileBlockSchema, FileCheckpointer, FileMemory, type FrameworkConfig, type FrameworkFile, FrameworkFileSchema, GraphMemory, type GraphRule, type GraphStore, type HandoffSignal, type HitlDecideRequest, type HitlDecision, HitlInterrupt, type HookContext, type ImageBlock, ImageBlockSchema, InMemoryGraphStore, InMemoryMemory, InMemoryRetriever, InMemoryStorage, type InvocationState, JSONLD_PREFIXES, JsonlSpanSink, LABEL_PREDICATES, type LinkedEntity, type LoadedFrameworkFile, LocalFileStorage, type MappingDecision, type MappingProposal, MappingProposals, type MappingProposalsOptions, type McpClient, type McpClientOptions, McpHttpClient, McpStdioClient, type McpToolDef, type Memory, MemorySpanSink, type MigrationReport, type MigrationResult, MockModelProvider, type ModelCapability, type ModelCompletion, type ModelPrice, type ModelProvider, type ModelRequest, type NodeShape, NonStandardBlockSchema, NullConversationManager, OWL_VOCAB, type OllamaOptions, OllamaProvider, type OntologyReview, type OpenAICompatibleOptions, OpenAICompatibleProvider, type OrchestratedResult, type OrchestrationPlan, type OrchestrationStrategy, type OutputVersion, type PIIDetector, type PIIMatch, type PIIStrategy, type PatternBinding, type PromptTemplate, type PropertyShape, type Quad, type ReasoningBlock, ReasoningBlockSchema, RemoteSparqlAdapter, type RemoteSparqlOptions, type ResolvedAgentDef, type ResponseFormat, type ResponseFormatWire, type ResponseStrategy, type Result, type Retriever, type RetryFilter, type RetryMiddlewareOptions, type RunId, type RunOptions, type SandboxBackend, type SandboxOptions, type ScoredDoc, type ServedAgent, SessionManager, type SessionManagerOptions, type ShapeInductionOptions, type ShapeReport, type Skill, type SkillLoaderOptions, SkillRegistry, SlidingWindowConversationManager, type SlidingWindowOptions, type Snapshot, type SnapshotData, type SnapshotField, type Span, type SpanSink, type SparqlAuth, type SparqlRow, type SparqlSelect, type StepEvent, type Storage, type StoreOptions, type StreamEvent, SummarizingConversationManager, type SummarizingOptions, Swarm, type SwarmOptions, type SwarmResult, type SwarmStatus, type SwarmStreamEvent, TBOX_PREDICATES, type TBoxMigrationSpec, type TakeSnapshotOptions, type TermStat, type TextBlock, TextBlockSchema, type ThreadCheckpoint, type TimelineEntry, type TodoItem, type TokenBudgets, type TokenUsage, type Tool, ToolCallBlockSchema, type ToolCallEvent, type ToolCallRef, type ToolCallRequest, type ToolContext, type ToolName, ToolRegistry, ToolRejection, type ToolResult, type ToolResultEvent, type TriplePattern, TurtleQuadSchema, type WorkflowNode, type WorkflowOptions, __resetConfig, a2aAsTool, abPrompts, adoptShapes, assertCanHandle, assistant, backoffDelayMs, buildServedAgent, claimCheckTool, collectStream, connectMcpHttp, connectMcpStdio, consoleEvents, contextEditingMiddleware, createMiddleware, createSandboxBackend, createSubAgentMiddleware, defaultSummarize, defaultToResult, definePrompt, defineTool, deserializeMessages, discoverSkills, estimateCostUsd, estimateTokens, executeSelect, filesystemMiddleware, filesystemTools, getRetryable, graphAddTool, handleAgentRoute, hasImages, historyTokens, hitlKey, humanInTheLoopMiddleware, imagesOf, initChatModel, instantiate, jsonSchemaToZod, jsonldToQuads, linkEntityTool, llmToolSelectorMiddleware, loadConfig, loadEnvFile, loadFrameworkConfig, loadJsonl, loadPromptFile, loadSkillsInto, logError, matchGlob, matchPatterns, matchSkills, mcpToolsToFramework, messageTokens, migrateTBox, modelCallLimit, modelFallbackMiddleware, modelRetryMiddleware, ollama, ontologyLookupTool, parseSelect, parseSkillFile, parseStructured, piiMiddleware, policyFilterMiddleware, priceFor, printReport, proposeMappingTool, proposeShapes, proposeShapesTool, providerFromEnv, providerStrategy, quadsToJsonLd, readHandoffSignal, remoteSparqlTool, responseFormatJsonSchema, responseFormatName, retrievalTool, reviewOntology, reviewOntologyTool, runConformance, runEval, runJavascriptTool, runOrchestrated, runWithBudget, runWorkflow, scoreSkills, selectSnapshotFields, serializeMessages, serveFramework, sleep, sparqlRetriever, sparqlSelectTool, stampRetryable, summarizationMiddleware, supportsColor, supportsVision, system, textOf, todoListMiddleware, tokenize, toolCallLimitMiddleware, toolEmulatorMiddleware, toolResult, toolRetry, toolRetryMiddleware, toolStrategy, tracingEvents, trimDangling, usageCost, user, wireTextOf, withFileLock };