@deepagents/context 0.10.2 → 0.12.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.
Files changed (50) hide show
  1. package/README.md +114 -119
  2. package/dist/example-error-recovery.d.ts +2 -0
  3. package/dist/example-error-recovery.d.ts.map +1 -0
  4. package/dist/index.d.ts +18 -388
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +2765 -1091
  7. package/dist/index.js.map +4 -4
  8. package/dist/lib/agent.d.ts +87 -12
  9. package/dist/lib/agent.d.ts.map +1 -1
  10. package/dist/lib/engine.d.ts +325 -0
  11. package/dist/lib/engine.d.ts.map +1 -0
  12. package/dist/lib/estimate.d.ts +1 -1
  13. package/dist/lib/estimate.d.ts.map +1 -1
  14. package/dist/lib/fragments/domain.d.ts +537 -0
  15. package/dist/lib/fragments/domain.d.ts.map +1 -0
  16. package/dist/lib/fragments/user.d.ts +122 -0
  17. package/dist/lib/fragments/user.d.ts.map +1 -0
  18. package/dist/lib/fragments.d.ts +103 -0
  19. package/dist/lib/fragments.d.ts.map +1 -0
  20. package/dist/lib/guardrail.d.ts +138 -0
  21. package/dist/lib/guardrail.d.ts.map +1 -0
  22. package/dist/lib/guardrails/error-recovery.guardrail.d.ts +3 -0
  23. package/dist/lib/guardrails/error-recovery.guardrail.d.ts.map +1 -0
  24. package/dist/lib/render.d.ts +21 -0
  25. package/dist/lib/render.d.ts.map +1 -0
  26. package/dist/lib/renderers/abstract.renderer.d.ts +11 -3
  27. package/dist/lib/renderers/abstract.renderer.d.ts.map +1 -1
  28. package/dist/lib/sandbox/binary-bridges.d.ts +31 -0
  29. package/dist/lib/sandbox/binary-bridges.d.ts.map +1 -0
  30. package/dist/lib/sandbox/container-tool.d.ts +134 -0
  31. package/dist/lib/sandbox/container-tool.d.ts.map +1 -0
  32. package/dist/lib/sandbox/docker-sandbox.d.ts +471 -0
  33. package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -0
  34. package/dist/lib/sandbox/index.d.ts +4 -0
  35. package/dist/lib/sandbox/index.d.ts.map +1 -0
  36. package/dist/lib/skills/fragments.d.ts +24 -0
  37. package/dist/lib/skills/fragments.d.ts.map +1 -0
  38. package/dist/lib/skills/index.d.ts +31 -0
  39. package/dist/lib/skills/index.d.ts.map +1 -0
  40. package/dist/lib/skills/loader.d.ts +28 -0
  41. package/dist/lib/skills/loader.d.ts.map +1 -0
  42. package/dist/lib/skills/types.d.ts +40 -0
  43. package/dist/lib/skills/types.d.ts.map +1 -0
  44. package/dist/lib/store/sqlite.store.d.ts +4 -2
  45. package/dist/lib/store/sqlite.store.d.ts.map +1 -1
  46. package/dist/lib/store/store.d.ts +36 -2
  47. package/dist/lib/store/store.d.ts.map +1 -1
  48. package/package.json +8 -4
  49. package/dist/lib/context.d.ts +0 -56
  50. package/dist/lib/context.d.ts.map +0 -1
@@ -1,28 +1,103 @@
1
- import { type StreamTextTransform, type ToolChoice, type ToolSet, generateText } from 'ai';
1
+ import { type GenerateTextResult, Output, type StreamTextResult, type StreamTextTransform, type ToolChoice, type ToolSet, generateText } from 'ai';
2
2
  import z from 'zod';
3
3
  import { type AgentModel } from '@deepagents/agent';
4
4
  import { type ContextEngine } from '../index.ts';
5
- export interface CreateAgent<COut, CIn = COut, Output = never> {
5
+ import { type Guardrail } from './guardrail.ts';
6
+ export interface CreateAgent<CIn, COut = CIn> {
6
7
  name: string;
7
- context: ContextEngine;
8
+ context?: ContextEngine;
8
9
  tools?: ToolSet;
9
- model: AgentModel;
10
+ model?: AgentModel;
10
11
  toolChoice?: ToolChoice<Record<string, COut>>;
11
- output?: z.Schema<Output>;
12
12
  providerOptions?: Parameters<typeof generateText>[0]['providerOptions'];
13
13
  logging?: boolean;
14
+ /**
15
+ * Guardrails to apply during streaming.
16
+ * Each guardrail inspects text chunks and can trigger self-correction retries.
17
+ */
18
+ guardrails?: Guardrail[];
19
+ /**
20
+ * Maximum number of retry attempts when guardrails fail (default: 3).
21
+ */
22
+ maxGuardrailRetries?: number;
14
23
  }
15
- declare class Agent<COut, CIn = COut, Output = never> {
24
+ declare class Agent<CIn, COut = CIn> {
16
25
  #private;
17
- constructor(options: CreateAgent<COut, CIn, Output>);
18
- generate<COut, CIn = COut, Output = never>(contextVariables: CIn, config?: {
26
+ readonly tools: ToolSet;
27
+ constructor(options: CreateAgent<CIn, COut>);
28
+ generate<COut, CIn = COut>(contextVariables: CIn, config?: {
19
29
  abortSignal?: AbortSignal;
20
- }): Promise<import("ai").GenerateTextResult<ToolSet, Output_1>>;
21
- stream<COut, CIn = COut, Output = never>(contextVariables: CIn, config?: {
30
+ }): Promise<GenerateTextResult<ToolSet, Output.Output<string, string, any>>>;
31
+ /**
32
+ * Stream a response from the agent.
33
+ *
34
+ * When guardrails are configured, `toUIMessageStream()` is wrapped to provide
35
+ * self-correction behavior. Direct access to fullStream/textStream bypasses guardrails.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const stream = await agent.stream({});
40
+ *
41
+ * // With guardrails - use toUIMessageStream for protection
42
+ * await printer.readableStream(stream.toUIMessageStream());
43
+ *
44
+ * // Or use printer.stdout which uses toUIMessageStream internally
45
+ * await printer.stdout(stream);
46
+ * ```
47
+ */
48
+ stream<COut, CIn = COut>(contextVariables: CIn, config?: {
22
49
  abortSignal?: AbortSignal;
23
50
  transform?: StreamTextTransform<ToolSet> | StreamTextTransform<ToolSet>[];
24
- }): Promise<import("ai").StreamTextResult<ToolSet, import("ai").DeepPartial<Output_1>>>;
51
+ maxRetries?: number;
52
+ }): Promise<StreamTextResult<ToolSet, never>>;
53
+ clone(overrides?: Partial<CreateAgent<CIn, COut>>): Agent<CIn, COut>;
25
54
  }
26
- export declare function agent<Output, CIn, COut = CIn>(options: CreateAgent<COut, CIn, Output>): Agent<COut, CIn, Output>;
55
+ export declare function agent<CIn, COut = CIn>(options: CreateAgent<CIn, COut>): Agent<CIn, COut>;
56
+ /**
57
+ * Options for creating a structured output handler.
58
+ */
59
+ export interface StructuredOutputOptions<TSchema extends z.ZodType> {
60
+ context?: ContextEngine;
61
+ model?: AgentModel;
62
+ schema: TSchema;
63
+ providerOptions?: Parameters<typeof generateText>[0]['providerOptions'];
64
+ tools?: ToolSet;
65
+ }
66
+ /**
67
+ * Create a structured output handler that provides simplified access to structured output.
68
+ *
69
+ * @param options - Configuration options including schema
70
+ * @returns Object with generate() and stream() methods
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * const output = structuredOutput({
75
+ * name: 'extractor',
76
+ * model: groq('...'),
77
+ * context,
78
+ * schema: z.object({
79
+ * name: z.string(),
80
+ * age: z.number(),
81
+ * }),
82
+ * });
83
+ *
84
+ * // Generate - returns only the structured output
85
+ * const result = await output.generate({});
86
+ * // result: { name: string, age: number }
87
+ *
88
+ * // Stream - returns the full stream
89
+ * const stream = await output.stream({});
90
+ * ```
91
+ */
92
+ export interface StructuredOutputResult<TSchema extends z.ZodType> {
93
+ generate<CIn>(contextVariables?: CIn, config?: {
94
+ abortSignal?: AbortSignal;
95
+ }): Promise<z.infer<TSchema>>;
96
+ stream<CIn>(contextVariables?: CIn, config?: {
97
+ abortSignal?: AbortSignal;
98
+ transform?: StreamTextTransform<ToolSet> | StreamTextTransform<ToolSet>[];
99
+ }): Promise<StreamTextResult<ToolSet, any>>;
100
+ }
101
+ export declare function structuredOutput<TSchema extends z.ZodType>(options: StructuredOutputOptions<TSchema>): StructuredOutputResult<TSchema>;
27
102
  export {};
28
103
  //# sourceMappingURL=agent.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/lib/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,UAAU,EACf,KAAK,OAAO,EAGZ,YAAY,EAIb,MAAM,IAAI,CAAC;AAEZ,OAAO,CAAC,MAAM,KAAK,CAAC;AAEpB,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,EAAE,KAAK,aAAa,EAA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;;;;;;;GAyBG;AACH,MAAM,WAAW,sBAAsB,CAAC,OAAO,SAAS,CAAC,CAAC,OAAO;IAC/D,QAAQ,CAAC,GAAG,EACV,gBAAgB,CAAC,EAAE,GAAG,EACtB,MAAM,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,WAAW,CAAA;KAAE,GACrC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7B,MAAM,CAAC,GAAG,EACR,gBAAgB,CAAC,EAAE,GAAG,EACtB,MAAM,CAAC,EAAE;QACP,WAAW,CAAC,EAAE,WAAW,CAAC;QAC1B,SAAS,CAAC,EAAE,mBAAmB,CAAC,OAAO,CAAC,GAAG,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;KAC3E,GACA,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;CAC5C;AAED,wBAAgB,gBAAgB,CAAC,OAAO,SAAS,CAAC,CAAC,OAAO,EACxD,OAAO,EAAE,uBAAuB,CAAC,OAAO,CAAC,GACxC,sBAAsB,CAAC,OAAO,CAAC,CAoEjC"}
@@ -0,0 +1,325 @@
1
+ import { type EstimateResult } from './estimate.ts';
2
+ import type { ContextFragment } from './fragments.ts';
3
+ import type { Models } from './models.generated.ts';
4
+ import { type ContextRenderer } from './renderers/abstract.renderer.ts';
5
+ import { type BranchInfo, type CheckpointInfo, ContextStore, type GraphData, type MessageData } from './store/store.ts';
6
+ /**
7
+ * Result of resolving context - ready for AI SDK consumption.
8
+ */
9
+ export interface ResolveResult {
10
+ /** Rendered non-message fragments for system prompt */
11
+ systemPrompt: string;
12
+ /** Message fragments decoded to AI SDK format */
13
+ messages: unknown[];
14
+ }
15
+ /**
16
+ * Options for resolve().
17
+ */
18
+ export interface ResolveOptions {
19
+ /** Renderer to use for system prompt (defaults to XmlRenderer) */
20
+ renderer: ContextRenderer;
21
+ }
22
+ /**
23
+ * Options for creating a ContextEngine.
24
+ */
25
+ export interface ContextEngineOptions {
26
+ /** Store for persisting fragments (required) */
27
+ store: ContextStore;
28
+ /** Unique identifier for this chat (required) */
29
+ chatId: string;
30
+ /** User who owns this chat (required) */
31
+ userId: string;
32
+ }
33
+ /**
34
+ * Metadata about a chat.
35
+ */
36
+ export interface ChatMeta {
37
+ /** Unique chat identifier */
38
+ id: string;
39
+ /** User who owns this chat */
40
+ userId: string;
41
+ /** When the chat was created */
42
+ createdAt: number;
43
+ /** When the chat was last updated */
44
+ updatedAt: number;
45
+ /** Optional user-provided title */
46
+ title?: string;
47
+ /** Optional custom metadata */
48
+ metadata?: Record<string, unknown>;
49
+ }
50
+ /**
51
+ * Options for context inspection.
52
+ */
53
+ export interface InspectOptions {
54
+ /** Model ID for cost estimation (required) */
55
+ modelId: Models;
56
+ /** Renderer for estimation (required) */
57
+ renderer: ContextRenderer;
58
+ }
59
+ /**
60
+ * Result of inspecting context state.
61
+ * JSON-serializable snapshot for debugging.
62
+ */
63
+ export interface InspectResult {
64
+ /** Token usage and cost estimation */
65
+ estimate: EstimateResult;
66
+ /** Rendered output using the provided renderer */
67
+ rendered: string;
68
+ /** Fragment structure breakdown */
69
+ fragments: {
70
+ /** Non-message fragments (role, hints, etc.) */
71
+ context: ContextFragment[];
72
+ /** Pending messages not yet saved to store */
73
+ pending: ContextFragment[];
74
+ /** Persisted messages from the store */
75
+ persisted: MessageData[];
76
+ };
77
+ /** Conversation graph with branches and checkpoints */
78
+ graph: GraphData;
79
+ /** Inspection metadata */
80
+ meta: {
81
+ chatId: string;
82
+ branch: string;
83
+ timestamp: number;
84
+ };
85
+ }
86
+ /**
87
+ * Context engine for managing AI conversation context with graph-based storage.
88
+ *
89
+ * The engine uses a DAG (Directed Acyclic Graph) model for messages:
90
+ * - Messages are immutable nodes with parentId forming the graph
91
+ * - Branches are pointers to head (tip) messages
92
+ * - Checkpoints are pointers to specific messages
93
+ * - History is preserved through branching (rewind creates new branch)
94
+ */
95
+ export declare class ContextEngine {
96
+ #private;
97
+ constructor(options: ContextEngineOptions);
98
+ /**
99
+ * Get the current chat ID.
100
+ */
101
+ get chatId(): string;
102
+ /**
103
+ * Get the current branch name.
104
+ */
105
+ get branch(): string;
106
+ /**
107
+ * Get metadata for the current chat.
108
+ * Returns null if the chat hasn't been initialized yet.
109
+ */
110
+ get chat(): ChatMeta | null;
111
+ /**
112
+ * Add fragments to the context.
113
+ *
114
+ * - Message fragments (user/assistant) are queued for persistence
115
+ * - Non-message fragments (role/hint) are kept in memory for system prompt
116
+ */
117
+ set(...fragments: ContextFragment[]): this;
118
+ unset(fragmentId: string): void;
119
+ /**
120
+ * Render all fragments using the provided renderer.
121
+ * @internal Use resolve() instead for public API.
122
+ */
123
+ render(renderer: ContextRenderer): string;
124
+ /**
125
+ * Resolve context into AI SDK-ready format.
126
+ *
127
+ * - Initializes chat and branch if needed
128
+ * - Loads message history from the graph (walking parent chain)
129
+ * - Separates context fragments for system prompt
130
+ * - Combines with pending messages
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * const context = new ContextEngine({ store, chatId: 'chat-1', userId: 'user-1' })
135
+ * .set(role('You are helpful'), user('Hello'));
136
+ *
137
+ * const { systemPrompt, messages } = await context.resolve();
138
+ * await generateText({ system: systemPrompt, messages });
139
+ * ```
140
+ */
141
+ resolve(options: ResolveOptions): Promise<ResolveResult>;
142
+ /**
143
+ * Save pending messages to the graph.
144
+ *
145
+ * Each message is added as a node with parentId pointing to the previous message.
146
+ * The branch head is updated to point to the last message.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * context.set(user('Hello'));
151
+ * // AI responds...
152
+ * context.set(assistant('Hi there!'));
153
+ * await context.save(); // Persist to graph
154
+ * ```
155
+ */
156
+ save(): Promise<void>;
157
+ /**
158
+ * Estimate token count and cost for the full context.
159
+ *
160
+ * Includes:
161
+ * - System prompt fragments (role, hints, etc.)
162
+ * - Persisted chat messages (from store)
163
+ * - Pending messages (not yet saved)
164
+ *
165
+ * @param modelId - Model ID (e.g., "openai:gpt-4o", "anthropic:claude-3-5-sonnet")
166
+ * @param options - Optional settings
167
+ * @returns Estimate result with token counts, costs, and per-fragment breakdown
168
+ */
169
+ estimate(modelId: Models, options?: {
170
+ renderer?: ContextRenderer;
171
+ }): Promise<EstimateResult>;
172
+ /**
173
+ * Rewind to a specific message by ID.
174
+ *
175
+ * Creates a new branch from that message, preserving the original branch.
176
+ * The new branch becomes active.
177
+ *
178
+ * @param messageId - The message ID to rewind to
179
+ * @returns The new branch info
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * context.set(user('What is 2 + 2?', { id: 'q1' }));
184
+ * context.set(assistant('The answer is 5.', { id: 'wrong' })); // Oops!
185
+ * await context.save();
186
+ *
187
+ * // Rewind to the question, creates new branch
188
+ * const newBranch = await context.rewind('q1');
189
+ *
190
+ * // Now add correct answer on new branch
191
+ * context.set(assistant('The answer is 4.'));
192
+ * await context.save();
193
+ * ```
194
+ */
195
+ rewind(messageId: string): Promise<BranchInfo>;
196
+ /**
197
+ * Create a checkpoint at the current position.
198
+ *
199
+ * A checkpoint is a named pointer to the current branch head.
200
+ * Use restore() to return to this point later.
201
+ *
202
+ * @param name - Name for the checkpoint
203
+ * @returns The checkpoint info
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * context.set(user('I want to learn a new skill.'));
208
+ * context.set(assistant('Would you like coding or cooking?'));
209
+ * await context.save();
210
+ *
211
+ * // Save checkpoint before user's choice
212
+ * const cp = await context.checkpoint('before-choice');
213
+ * ```
214
+ */
215
+ checkpoint(name: string): Promise<CheckpointInfo>;
216
+ /**
217
+ * Restore to a checkpoint by creating a new branch from that point.
218
+ *
219
+ * @param name - Name of the checkpoint to restore
220
+ * @returns The new branch info
221
+ *
222
+ * @example
223
+ * ```ts
224
+ * // User chose cooking, but wants to try coding path
225
+ * await context.restore('before-choice');
226
+ *
227
+ * context.set(user('I want to learn coding.'));
228
+ * context.set(assistant('Python is a great starting language!'));
229
+ * await context.save();
230
+ * ```
231
+ */
232
+ restore(name: string): Promise<BranchInfo>;
233
+ /**
234
+ * Switch to a different branch by name.
235
+ *
236
+ * @param name - Branch name to switch to
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * // List branches (via store)
241
+ * const branches = await store.listBranches(context.chatId);
242
+ * console.log(branches); // [{name: 'main', ...}, {name: 'main-v2', ...}]
243
+ *
244
+ * // Switch to original branch
245
+ * await context.switchBranch('main');
246
+ * ```
247
+ */
248
+ switchBranch(name: string): Promise<void>;
249
+ /**
250
+ * Create a parallel branch from the current position ("by the way").
251
+ *
252
+ * Use this when you want to fork the conversation without leaving
253
+ * the current branch. Common use case: user wants to ask another
254
+ * question while waiting for the model to respond.
255
+ *
256
+ * Unlike rewind(), this method:
257
+ * - Uses the current HEAD (no messageId needed)
258
+ * - Does NOT switch to the new branch
259
+ * - Keeps pending messages intact
260
+ *
261
+ * @returns The new branch info (does not switch to it)
262
+ * @throws Error if no messages exist in the conversation
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * // User asked a question, model is generating...
267
+ * context.set(user('What is the weather?'));
268
+ * await context.save();
269
+ *
270
+ * // User wants to ask something else without waiting
271
+ * const newBranch = await context.btw();
272
+ * // newBranch = { name: 'main-v2', ... }
273
+ *
274
+ * // Later, switch to the new branch and add the question
275
+ * await context.switchBranch(newBranch.name);
276
+ * context.set(user('Also, what time is it?'));
277
+ * await context.save();
278
+ * ```
279
+ */
280
+ btw(): Promise<BranchInfo>;
281
+ /**
282
+ * Update metadata for the current chat.
283
+ *
284
+ * @param updates - Partial metadata to merge (title, metadata)
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * await context.updateChat({
289
+ * title: 'Coding Help Session',
290
+ * metadata: { tags: ['python', 'debugging'] }
291
+ * });
292
+ * ```
293
+ */
294
+ updateChat(updates: Partial<Pick<ChatMeta, 'title' | 'metadata'>>): Promise<void>;
295
+ /**
296
+ * Consolidate context fragments (no-op for now).
297
+ *
298
+ * This is a placeholder for future functionality that merges context fragments
299
+ * using specific rules. Currently, it does nothing.
300
+ *
301
+ * @experimental
302
+ */
303
+ consolidate(): void;
304
+ /**
305
+ * Inspect the full context state for debugging.
306
+ * Returns a JSON-serializable object with context information.
307
+ *
308
+ * @param options - Inspection options (modelId and renderer required)
309
+ * @returns Complete inspection data including estimates, rendered output, fragments, and graph
310
+ *
311
+ * @example
312
+ * ```ts
313
+ * const inspection = await context.inspect({
314
+ * modelId: 'openai:gpt-4o',
315
+ * renderer: new XmlRenderer(),
316
+ * });
317
+ * console.log(JSON.stringify(inspection, null, 2));
318
+ *
319
+ * // Or write to file for analysis
320
+ * await fs.writeFile('context-debug.json', JSON.stringify(inspection, null, 2));
321
+ * ```
322
+ */
323
+ inspect(options: InspectOptions): Promise<InspectResult>;
324
+ }
325
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/lib/engine.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,cAAc,EAGpB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EACL,KAAK,eAAe,EAErB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAEL,KAAK,UAAU,EAGf,KAAK,cAAc,EACnB,YAAY,EACZ,KAAK,SAAS,EACd,KAAK,WAAW,EAEjB,MAAM,kBAAkB,CAAC;AAE1B;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,uDAAuD;IACvD,YAAY,EAAE,MAAM,CAAC;IACrB,iDAAiD;IACjD,QAAQ,EAAE,OAAO,EAAE,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,kEAAkE;IAClE,QAAQ,EAAE,eAAe,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,gDAAgD;IAChD,KAAK,EAAE,YAAY,CAAC;IACpB,iDAAiD;IACjD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;;;;;;;;;;;;;;;OAkBG;IACU,OAAO,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;CAuCtE"}
@@ -1,4 +1,4 @@
1
- import type { ContextFragment } from './context.ts';
1
+ import type { ContextFragment } from './fragments.ts';
2
2
  import type { Models } from './models.generated.ts';
3
3
  import type { ContextRenderer } from './renderers/abstract.renderer.ts';
4
4
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"estimate.d.ts","sourceRoot":"","sources":["../../src/lib/estimate.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAExE;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE;QACL,OAAO,EAAE,MAAM,CAAC;QAChB,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;IACF,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,QA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