@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
@@ -0,0 +1,537 @@
1
+ import type { ContextFragment, FragmentData } from '../fragments.ts';
2
+ /**
3
+ * Domain knowledge fragment builders.
4
+ *
5
+ * These fragments capture domain-specific knowledge that can be injected
6
+ * into AI prompts. Use with renderers (XML, Markdown, TOML, TOON) to format.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { term, hint, guardrail } from '@deepagents/context';
11
+ *
12
+ * context.set(
13
+ * term('NPL', 'non-performing loan'),
14
+ * hint('Always filter by status'),
15
+ * guardrail({ rule: 'Never expose PII' }),
16
+ * );
17
+ * ```
18
+ */
19
+ /**
20
+ * Define domain-specific vocabulary and business terminology.
21
+ *
22
+ * Use this to define simple, direct mappings between business terms and their meanings.
23
+ * The system will understand these terms when users mention them in queries.
24
+ *
25
+ * @param name - The business term or acronym to define
26
+ * @param definition - What the term means in your domain
27
+ *
28
+ * @example
29
+ * // Logistics/Transportation dataset
30
+ * term("deadhead miles", "distance driven with empty truck between deliveries")
31
+ * term("dwell time", "total time a truck spends at a loading dock or warehouse")
32
+ * term("LTL", "less than truckload - shipment that doesn't fill entire truck")
33
+ *
34
+ * @example
35
+ * // Education/University dataset
36
+ * term("matriculation", "students who completed enrollment and started classes")
37
+ * term("DFW rate", "percentage of students receiving D, F, or Withdrawal in a course")
38
+ * term("cohort", "group of students who entered the same semester or academic year")
39
+ *
40
+ * @example
41
+ * // Finance/Banking dataset
42
+ * term("NPL", "non-performing loan - loan past due 90+ days")
43
+ * term("basis points", "one hundredth of a percentage point (1% = 100 bps)")
44
+ * term("AUM", "assets under management - total market value of client investments")
45
+ */
46
+ export declare function term(name: string, definition: string): ContextFragment;
47
+ /**
48
+ * Define behavioral rules and constraints that should always apply.
49
+ *
50
+ * Use this for business logic, data quality rules, or query preferences that should
51
+ * be automatically applied to all relevant queries.
52
+ *
53
+ * @param text - The rule or constraint to follow (use imperative language)
54
+ *
55
+ * @example
56
+ * // Manufacturing/Supply Chain dataset
57
+ * hint("Always exclude work orders with status = 'simulation' from production metrics")
58
+ * hint("When calculating OEE (overall equipment effectiveness), only count scheduled production time")
59
+ * hint("Defect rates should be calculated per batch, not per individual unit, for consistency")
60
+ *
61
+ * @example
62
+ * // Real Estate/Property dataset
63
+ * hint("Never include properties with listing_status = 'draft' in market analysis")
64
+ * hint("Always filter out duplicate MLS listings - use the earliest listing_date for each property_id")
65
+ * hint("Square footage comparisons must specify if including or excluding basement/garage")
66
+ *
67
+ * @example
68
+ * // Social Media/Content Platform dataset
69
+ * hint("Engagement metrics should exclude bot accounts identified by is_verified_human = false")
70
+ * hint("View counts reset daily - always use cumulative_views for historical analysis")
71
+ * hint("Default content filters to published_status = 'public' unless analyzing drafts")
72
+ */
73
+ export declare function hint(text: string): ContextFragment;
74
+ /**
75
+ * Define hard guardrails, safety rules, and compliance boundaries.
76
+ *
77
+ * Use this for "never do" rules, sensitive data handling, and required behaviors when
78
+ * certain conditions occur. Guardrails should be explicit and action-oriented.
79
+ *
80
+ * @param input.rule - The guardrail or restriction to enforce
81
+ * @param input.reason - Why this guardrail exists (compliance, security, performance)
82
+ * @param input.action - What to do when this guardrail is triggered
83
+ *
84
+ * @example
85
+ * // Healthcare dataset
86
+ * guardrail({
87
+ * rule: "Never return PHI like SSN, MRN, or full address in query results",
88
+ * reason: "HIPAA compliance",
89
+ * action: "If asked, state that identifiable patient data cannot be shared; offer de-identified aggregates instead"
90
+ * })
91
+ *
92
+ * @example
93
+ * // Finance dataset
94
+ * guardrail({
95
+ * rule: "Block any query exposing employee-level compensation by name",
96
+ * reason: "Confidential payroll data",
97
+ * action: "Provide ranges grouped by department or level instead of individual salaries"
98
+ * })
99
+ *
100
+ * @example
101
+ * // E-commerce dataset
102
+ * guardrail({
103
+ * rule: "Warn when a query would scan more than 10 million rows; require a narrower date range",
104
+ * reason: "Performance and cost control",
105
+ * action: "Ask the user to add filters (recent timeframe, specific categories) before proceeding"
106
+ * })
107
+ */
108
+ export declare function guardrail(input: {
109
+ rule: string;
110
+ reason?: string;
111
+ action?: string;
112
+ }): ContextFragment;
113
+ /**
114
+ * Define a rich understanding of a single concept using metaphors and explanations.
115
+ *
116
+ * Use this when a simple term definition isn't enough - when you need to convey deeper
117
+ * understanding about how to think about and calculate a metric or concept.
118
+ *
119
+ * @param input.concept - The concept being explained
120
+ * @param input.explanation - A metaphor or detailed explanation
121
+ * @param input.therefore - Optional actionable instruction based on this understanding
122
+ *
123
+ * @example
124
+ * // Gaming/Entertainment dataset
125
+ * explain({
126
+ * concept: "daily active users to monthly active users ratio",
127
+ * explanation: "like measuring how many club members visit daily vs just once a month - shows stickiness",
128
+ * therefore: "Calculate as DAU / MAU, where higher ratio (closer to 1) means more engaged user base"
129
+ * })
130
+ *
131
+ * @example
132
+ * // HR/Employee Management dataset
133
+ * explain({
134
+ * concept: "time to fill",
135
+ * explanation: "like measuring how long a house sits on the market - from posting job to accepting offer",
136
+ * therefore: "Calculate as days between job_posted_date and offer_accepted_date, exclude cancelled requisitions"
137
+ * })
138
+ *
139
+ * @example
140
+ * // Telecommunications dataset
141
+ * explain({
142
+ * concept: "network congestion ratio",
143
+ * explanation: "like rush hour traffic density - measures actual usage vs total capacity at peak times",
144
+ * therefore: "Calculate as (peak_hour_bandwidth_used / total_bandwidth_capacity) during busiest hour of day"
145
+ * })
146
+ */
147
+ export declare function explain(input: {
148
+ concept: string;
149
+ explanation: string;
150
+ therefore?: string;
151
+ }): ContextFragment;
152
+ /**
153
+ * Define concrete examples of question → answer pairs.
154
+ *
155
+ * Use this for few-shot learning - show the system exactly how to translate
156
+ * specific types of questions. Great for establishing patterns.
157
+ *
158
+ * @param input.question - The natural language question or request
159
+ * @param input.answer - The correct answer that responds to the question
160
+ * @param input.note - Optional note or explanation about the example
161
+ *
162
+ * @example
163
+ * // Energy/Utilities dataset
164
+ * example({
165
+ * question: "show me peak demand hours for the last week",
166
+ * answer: "SELECT DATE_TRUNC('hour', reading_timestamp) as hour, MAX(consumption_kwh) as peak_demand FROM meter_readings WHERE reading_timestamp >= CURRENT_DATE - INTERVAL '7 days' GROUP BY hour ORDER BY peak_demand DESC LIMIT 10"
167
+ * })
168
+ *
169
+ * @example
170
+ * // Agriculture/Farm Management dataset
171
+ * example({
172
+ * question: "what is the average yield per acre by crop type this season",
173
+ * answer: "SELECT crop_type, AVG(harvest_quantity / field_acres) as yield_per_acre FROM harvests WHERE harvest_date >= '2024-01-01' GROUP BY crop_type ORDER BY yield_per_acre DESC"
174
+ * })
175
+ *
176
+ * @example
177
+ * // Travel/Hospitality dataset
178
+ * example({
179
+ * question: "show me hotel occupancy rate for this month",
180
+ * answer: "SELECT hotel_name, (SUM(occupied_rooms) / SUM(total_rooms)) * 100 as occupancy_rate FROM daily_occupancy WHERE date >= DATE_TRUNC('month', CURRENT_DATE) GROUP BY hotel_id, hotel_name ORDER BY occupancy_rate DESC",
181
+ * note: "Occupancy rate is a percentage - multiply by 100 for readable output"
182
+ * })
183
+ */
184
+ export declare function example(input: {
185
+ question: string;
186
+ answer: string;
187
+ note?: string;
188
+ }): ContextFragment;
189
+ /**
190
+ * Define when and what to ask for clarification.
191
+ *
192
+ * Use this to handle ambiguous terms or situations where the system should
193
+ * proactively ask the user for more information.
194
+ *
195
+ * @param input.when - The condition or trigger that should prompt clarification
196
+ * @param input.ask - The question to ask the user
197
+ * @param input.reason - Why this clarification is necessary
198
+ *
199
+ * @example
200
+ * // Marketing/Advertising dataset
201
+ * clarification({
202
+ * when: "user asks for 'conversion rate'",
203
+ * ask: "Which conversion: click-to-lead, lead-to-opportunity, or opportunity-to-customer?",
204
+ * reason: "Conversion rate means different things at each funnel stage - need to specify which metric"
205
+ * })
206
+ *
207
+ * @example
208
+ * // Food Delivery dataset
209
+ * clarification({
210
+ * when: "user asks about 'delivery time'",
211
+ * ask: "Do you mean estimated time at order, actual delivery time, or time from kitchen to door?",
212
+ * reason: "Multiple time metrics exist - estimated vs actual impacts customer satisfaction differently"
213
+ * })
214
+ *
215
+ * @example
216
+ * // Fitness/Gym Management dataset
217
+ * clarification({
218
+ * when: "user mentions 'active members'",
219
+ * ask: "Do you mean paid memberships or members who actually visited in last 30 days?",
220
+ * reason: "Many paid members don't use facilities - different metrics for revenue vs utilization"
221
+ * })
222
+ */
223
+ export declare function clarification(input: {
224
+ when: string;
225
+ ask: string;
226
+ reason: string;
227
+ }): ContextFragment;
228
+ /**
229
+ * Define multi-step analytical processes that require sequential logic.
230
+ *
231
+ * Use this for complex analytical tasks that require multiple steps or specific
232
+ * methodologies. Workflows teach the system HOW to approach a type of analysis.
233
+ *
234
+ * @param input.task - Name of the analytical task
235
+ * @param input.steps - Sequential steps to execute
236
+ * @param input.triggers - Optional phrases that should activate this workflow
237
+ * @param input.notes - Optional additional context, warnings, or guidance
238
+ *
239
+ * @example
240
+ * // Insurance dataset
241
+ * workflow({
242
+ * task: "Claims Loss Ratio Analysis",
243
+ * triggers: ["loss ratio", "claims ratio", "underwriting performance"],
244
+ * steps: [
245
+ * "Calculate total claims paid for each policy period",
246
+ * "Calculate total premiums earned for same period",
247
+ * "Compute loss ratio as (claims_paid / premiums_earned) * 100",
248
+ * "Segment by policy type, geography, and underwriter",
249
+ * "Identify policies with loss ratio > 100% (losing money)",
250
+ * "Calculate trend over time using rolling 12-month windows"
251
+ * ],
252
+ * notes: "Use incurred date for claims, not paid date. Exclude reinsurance recoveries from claims total."
253
+ * })
254
+ *
255
+ * @example
256
+ * // Media/Publishing dataset
257
+ * workflow({
258
+ * task: "Content Performance Funnel",
259
+ * triggers: ["content funnel", "engagement funnel", "content performance"],
260
+ * steps: [
261
+ * "Count total impressions (articles shown) per content piece",
262
+ * "Count click-throughs (articles opened)",
263
+ * "Count scroll depth > 50% (meaningful engagement)",
264
+ * "Count shares, comments, or saves (viral actions)",
265
+ * "Calculate conversion rate at each funnel stage",
266
+ * "Identify top-performing content by final conversion rate"
267
+ * ],
268
+ * notes: "Requires multiple event types. Join events table multiple times or use conditional aggregation."
269
+ * })
270
+ *
271
+ * @example
272
+ * // Sports Analytics dataset
273
+ * workflow({
274
+ * task: "Player Performance Rating Calculation",
275
+ * triggers: ["player rating", "performance score", "player analytics"],
276
+ * steps: [
277
+ * "Aggregate per-game stats: points, assists, rebounds, turnovers",
278
+ * "Calculate efficiency metrics: shooting percentage, plus/minus",
279
+ * "Normalize each metric using z-scores vs league average",
280
+ * "Apply position-specific weights to each metric",
281
+ * "Combine weighted scores into overall performance rating (0-100)",
282
+ * "Rank players within position group and overall"
283
+ * ],
284
+ * notes: "Requires league-wide statistics for normalization. Update weights each season based on game trends."
285
+ * })
286
+ */
287
+ export declare function workflow(input: {
288
+ task: string;
289
+ steps: string[];
290
+ triggers?: string[];
291
+ notes?: string;
292
+ }): ContextFragment;
293
+ /**
294
+ * Define data quirks, edge cases, or database-specific issues and their workarounds.
295
+ *
296
+ * Use this to document weird data patterns, database limitations, or special handling
297
+ * required for specific scenarios.
298
+ *
299
+ * @param input.issue - Description of the quirk, edge case, or problem
300
+ * @param input.workaround - How to handle or work around this issue
301
+ *
302
+ * @example
303
+ * // Government/Public Services dataset
304
+ * quirk({
305
+ * issue: "Citizen IDs contain leading zeros but are stored as integers, losing the zeros",
306
+ * workaround: "Always cast to VARCHAR and use LPAD(citizen_id::VARCHAR, 10, '0') to restore leading zeros"
307
+ * })
308
+ *
309
+ * @example
310
+ * // Aviation dataset
311
+ * quirk({
312
+ * issue: "Flight times crossing midnight show as negative duration (landing before takeoff)",
313
+ * workaround: "Add 24 hours when calculated duration < 0: CASE WHEN duration < 0 THEN duration + INTERVAL '24 hours' ELSE duration END"
314
+ * })
315
+ *
316
+ * @example
317
+ * // Automotive/Dealership dataset
318
+ * quirk({
319
+ * issue: "VIN numbers with letter 'O' were incorrectly entered as zero '0' in legacy data",
320
+ * workaround: "When searching by VIN, use REPLACE(vin, '0', 'O') or fuzzy matching to handle both cases"
321
+ * })
322
+ */
323
+ export declare function quirk(input: {
324
+ issue: string;
325
+ workaround: string;
326
+ }): ContextFragment;
327
+ /**
328
+ * Define style preferences and coding standards.
329
+ *
330
+ * Use this to enforce consistent formatting, naming conventions, and best practices
331
+ * specific to your team or organization.
332
+ *
333
+ * @param input.prefer - Preferred style or pattern
334
+ * @param input.never - Optional anti-pattern to avoid
335
+ * @param input.always - Optional rule that must always be followed
336
+ *
337
+ * @example
338
+ * // Non-profit/Charity dataset
339
+ * styleGuide({
340
+ * prefer: "Use donor-centric language in column aliases: 'donor_name' not 'customer_name'",
341
+ * never: "Never expose internal donor IDs in external reports - use public gift IDs",
342
+ * always: "Always include fiscal year in date-based aggregations (FY starts July 1)"
343
+ * })
344
+ *
345
+ * @example
346
+ * // Legal/Law Firm dataset
347
+ * styleGuide({
348
+ * prefer: "Use billable_hours with 2 decimal precision for accurate client billing",
349
+ * never: "Never include attorney_rate in queries visible to paralegals - confidential data",
350
+ * always: "Always filter by matter_status = 'open' unless specifically analyzing closed cases"
351
+ * })
352
+ *
353
+ * @example
354
+ * // Inventory/Warehouse dataset
355
+ * styleGuide({
356
+ * prefer: "Use location_id in joins rather than location_name (duplicates exist across warehouses)",
357
+ * never: "Never aggregate inventory without grouping by warehouse_id first",
358
+ * always: "Always use inventory_on_hand - inventory_reserved for available stock calculations"
359
+ * })
360
+ */
361
+ export declare function styleGuide(input: {
362
+ prefer: string;
363
+ never?: string;
364
+ always?: string;
365
+ }): ContextFragment;
366
+ /**
367
+ * Define comparisons between related concepts through real-world analogies.
368
+ *
369
+ * Use this to teach relational understanding between concepts by drawing comparisons
370
+ * to familiar real-world scenarios.
371
+ *
372
+ * @param input.concepts - Array of related concepts to compare
373
+ * @param input.relationship - The comparison/analogy using real-world examples
374
+ * @param input.insight - Optional key insight the analogy reveals
375
+ * @param input.therefore - Optional actionable instruction
376
+ * @param input.pitfall - Optional common mistake to avoid
377
+ *
378
+ * @example
379
+ * // E-commerce dataset
380
+ * analogy({
381
+ * concepts: ["cart abandonment", "browse abandonment"],
382
+ * relationship: "Cart abandonment is like leaving items at a checkout counter, browse abandonment is like window shopping without picking anything up",
383
+ * insight: "Cart abandonment shows purchase intent (added to cart), browse abandonment shows only interest",
384
+ * therefore: "Prioritize cart abandonment recovery campaigns - higher conversion potential than browse",
385
+ * pitfall: "Don't combine both into generic 'abandonment rate' - they need different marketing strategies"
386
+ * })
387
+ *
388
+ * @example
389
+ * // SaaS dataset
390
+ * analogy({
391
+ * concepts: ["logo churn", "revenue churn"],
392
+ * relationship: "Logo churn is like counting how many customers left the store, revenue churn is how much money walked out",
393
+ * insight: "Losing 10 small customers (high logo churn) might hurt less than losing 1 enterprise customer (high revenue churn)",
394
+ * therefore: "Always report both metrics - logo churn for customer satisfaction, revenue churn for financial health",
395
+ * pitfall: "Don't use logo churn to predict revenue impact - customer size distribution matters"
396
+ * })
397
+ *
398
+ * @example
399
+ * // Healthcare dataset
400
+ * analogy({
401
+ * concepts: ["incidence", "prevalence"],
402
+ * relationship: "Incidence is like new house sales this month, prevalence is total houses currently occupied",
403
+ * insight: "Incidence measures new cases over time, prevalence measures all existing cases at a point in time",
404
+ * therefore: "For tracking disease outbreaks use incidence rate, for resource planning use prevalence",
405
+ * pitfall: "Don't sum incidence rates across time periods - it's a rate not a count"
406
+ * })
407
+ */
408
+ export declare function analogy(input: {
409
+ concepts: string[];
410
+ relationship: string;
411
+ insight?: string;
412
+ therefore?: string;
413
+ pitfall?: string;
414
+ }): ContextFragment;
415
+ /**
416
+ * Map business terms directly to expressions or fragments.
417
+ *
418
+ * Use this to teach the system how to CALCULATE or QUERY specific business concepts.
419
+ * The system will substitute these patterns when users mention the term.
420
+ *
421
+ * **Glossary vs Alias:**
422
+ * - `alias` = user vocabulary → table/column name ("the big table" → "orders table")
423
+ * - `glossary` = business term → SQL expression ("revenue" → "SUM(orders.total_amount)")
424
+ *
425
+ * In short: alias renames, glossary computes.
426
+ *
427
+ * @param entries - Record mapping business terms to their expressions
428
+ *
429
+ * @example
430
+ * glossary({
431
+ * "revenue": "SUM(orders.total_amount)",
432
+ * "average order value": "AVG(orders.total_amount)",
433
+ * "active user": "last_login > NOW() - INTERVAL '30 days'",
434
+ * "churned": "status = 'churned'",
435
+ * "power user": "order_count > 10",
436
+ * "net revenue": "SUM(orders.total_amount) - SUM(refunds.amount)",
437
+ * })
438
+ */
439
+ export declare function glossary(entries: Record<string, string>): ContextFragment;
440
+ /**
441
+ * Create a role fragment for system prompt instructions.
442
+ */
443
+ export declare function role(content: string): ContextFragment;
444
+ /**
445
+ * Define a guiding principle that shapes agent behavior.
446
+ *
447
+ * Use this to establish high-level rules for decision-making, reasoning, or domain behavior.
448
+ * Principles can contain policies (specific rules that implement the principle).
449
+ *
450
+ * @param input.title - Name/title of the principle
451
+ * @param input.description - What this principle means and why it matters
452
+ * @param input.policies - Optional specific rules that implement this principle
453
+ *
454
+ * @example
455
+ * // Logical dependencies principle
456
+ * principle({
457
+ * title: "Logical dependencies and constraints",
458
+ * description: "Analyze intended actions against factors in order of importance",
459
+ * policies: [
460
+ * "Policy-based rules, mandatory prerequisites, and constraints",
461
+ * "Order of operations: Ensure actions don't prevent subsequent necessary actions",
462
+ * "Other prerequisites (information and/or actions needed)",
463
+ * "Explicit user constraints or preferences"
464
+ * ]
465
+ * })
466
+ *
467
+ * @example
468
+ * // Risk assessment principle
469
+ * principle({
470
+ * title: "Risk assessment",
471
+ * description: "Evaluate consequences before taking action",
472
+ * policies: [
473
+ * "For exploratory tasks, missing optional parameters is LOW risk",
474
+ * "Prefer calling tools with available information over asking the user"
475
+ * ]
476
+ * })
477
+ *
478
+ * @example
479
+ * // Design principle
480
+ * principle({
481
+ * title: "Separation of concerns",
482
+ * description: "Each module should have a single, well-defined responsibility",
483
+ * policies: [
484
+ * "Data access logic stays in repository layer",
485
+ * "Business rules stay in service layer",
486
+ * "Presentation logic stays in controller/view layer"
487
+ * ]
488
+ * })
489
+ */
490
+ export declare function principle(input: {
491
+ title: string;
492
+ description: string;
493
+ policies?: FragmentData[];
494
+ }): ContextFragment;
495
+ /**
496
+ * Define a policy rule, optionally with prerequisites or nested sub-policies.
497
+ *
498
+ * Policies can be used in two ways:
499
+ * 1. Prerequisite rules: "must do X before Y" using the `before` parameter
500
+ * 2. Sub-policies: nested rules within a principle using the `policies` parameter
501
+ *
502
+ * Policies differ from guardrails: policies are prerequisites (do this first),
503
+ * guardrails are prohibitions (never do this).
504
+ *
505
+ * @param input.rule - The policy rule to enforce
506
+ * @param input.before - What action this is a prerequisite for (optional for sub-policies)
507
+ * @param input.reason - Why this rule matters
508
+ * @param input.policies - Nested sub-policies for hierarchical structure
509
+ *
510
+ * @example
511
+ * // Prerequisite rule with "before"
512
+ * policy({
513
+ * rule: "Validate SQL syntax",
514
+ * before: "executing any query against the database",
515
+ * reason: "Catches errors early and allows correction before execution"
516
+ * })
517
+ *
518
+ * @example
519
+ * // Sub-policy within a principle (no "before" needed)
520
+ * policy({ rule: "Policy-based rules, mandatory prerequisites, and constraints." })
521
+ *
522
+ * @example
523
+ * // Nested sub-policies (hierarchical structure like 1.2 → 1.2.1)
524
+ * policy({
525
+ * rule: "Order of operations: Ensure taking an action does not prevent a subsequent necessary action.",
526
+ * policies: [
527
+ * "The user may request actions in a random order, but you may need to reorder operations.",
528
+ * ],
529
+ * })
530
+ */
531
+ export declare function policy(input: {
532
+ rule: string;
533
+ before?: string;
534
+ reason?: string;
535
+ policies?: FragmentData[];
536
+ }): ContextFragment;
537
+ //# sourceMappingURL=domain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"domain.d.ts","sourceRoot":"","sources":["../../../src/lib/fragments/domain.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,122 @@
1
+ import type { ContextFragment } from '../fragments.ts';
2
+ /**
3
+ * User-specific fragment builders.
4
+ *
5
+ * These fragments capture user context, preferences, and personalization data
6
+ * that can be injected into AI prompts to tailor responses.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { identity, persona, preference } from '@deepagents/context';
11
+ *
12
+ * context.set(
13
+ * identity({ name: 'John', role: 'VP of Sales' }),
14
+ * persona({ name: 'Freya', role: 'Data Assistant', tone: 'professional' }),
15
+ * preference('date format', 'YYYY-MM-DD'),
16
+ * );
17
+ * ```
18
+ */
19
+ /**
20
+ * Define the user's identity including name and/or role.
21
+ *
22
+ * Use this to capture who the user is and what lens they view data through.
23
+ * Helps tailor explanations, terminology, and focus areas.
24
+ *
25
+ * @param input.name - The user's name (optional)
26
+ * @param input.role - The user's role or position (optional)
27
+ *
28
+ * @example
29
+ * identity({ name: "John", role: "VP of Sales" })
30
+ * identity({ role: "Data analyst in the marketing team" })
31
+ * identity({ name: "Sarah" })
32
+ * identity({ role: "Finance manager focused on cost optimization" })
33
+ */
34
+ export declare function identity(input: {
35
+ name?: string;
36
+ role?: string;
37
+ }): ContextFragment;
38
+ /**
39
+ * Define an AI persona with a name, role, objective, and communication tone.
40
+ *
41
+ * Use this to customize the assistant's identity and what it should accomplish.
42
+ *
43
+ * @param input.name - The persona's name
44
+ * @param input.role - The persona's expertise/identity (what they are)
45
+ * @param input.objective - What the persona should accomplish (the goal)
46
+ * @param input.tone - The communication style (e.g., friendly, professional, concise)
47
+ *
48
+ * @example
49
+ * persona({ name: "DataBot", role: "SQL Expert", objective: "Generate accurate SQL queries from natural language" })
50
+ * persona({ name: "QueryMaster", role: "Database Analyst", objective: "Help users explore database schemas" })
51
+ */
52
+ export declare function persona(input: {
53
+ name: string;
54
+ role?: string;
55
+ objective?: string;
56
+ tone?: string;
57
+ }): ContextFragment;
58
+ /**
59
+ * Define user-specific term meanings and vocabulary.
60
+ *
61
+ * Use this when the user has their own definitions for terms that might
62
+ * differ from standard or domain definitions. Like `term()` but personal.
63
+ *
64
+ * @param term - The term the user uses
65
+ * @param meaning - What the user means by this term
66
+ *
67
+ * @example
68
+ * alias("revenue", "gross revenue before deductions, not net")
69
+ * alias("active users", "users who logged in within the last 30 days")
70
+ * alias("the big table", "the orders table")
71
+ * alias("Q4", "October through December, not fiscal Q4")
72
+ */
73
+ export declare function alias(term: string, meaning: string): ContextFragment;
74
+ /**
75
+ * Define how the user prefers results presented.
76
+ *
77
+ * Use this to capture output formatting, style, and behavioral preferences
78
+ * that should apply to all interactions with this user.
79
+ *
80
+ * @param aspect - What aspect of output this preference applies to
81
+ * @param value - The user's preference
82
+ *
83
+ * @example
84
+ * preference("date format", "YYYY-MM-DD")
85
+ * preference("output style", "tables over charts unless trend data")
86
+ * preference("detail level", "always show the SQL query in responses")
87
+ * preference("row limit", "default to 50 rows unless I ask for more")
88
+ * preference("explanation style", "brief and to the point")
89
+ */
90
+ export declare function preference(aspect: string, value: string): ContextFragment;
91
+ /**
92
+ * Define the user's current working focus or project.
93
+ *
94
+ * Use this to capture temporary context that helps inform defaults,
95
+ * assumptions, and suggestions. Should be updated as focus changes.
96
+ *
97
+ * @param description - What the user is currently working on
98
+ *
99
+ * @example
100
+ * userContext("Preparing Q4 board presentation")
101
+ * userContext("Investigating drop in signups last week")
102
+ * userContext("Working on EMEA regional analysis for strategy meeting")
103
+ * userContext("Debugging discrepancy in revenue numbers")
104
+ */
105
+ export declare function userContext(description: string): ContextFragment;
106
+ /**
107
+ * Record a correction the user made to previous understanding.
108
+ *
109
+ * Use this when the user corrects a misunderstanding about data, columns,
110
+ * or business logic. Prevents repeating the same mistake.
111
+ *
112
+ * @param subject - What was misunderstood
113
+ * @param clarification - The correct understanding
114
+ *
115
+ * @example
116
+ * correction("status column", "1 = active, 0 = inactive, not boolean true/false")
117
+ * correction("orders table", "Use orders_v2, not the deprecated legacy_orders table")
118
+ * correction("date field", "order_date is when order was placed, ship_date is when shipped")
119
+ * correction("revenue calculation", "Must exclude refunds and chargebacks")
120
+ */
121
+ export declare function correction(subject: string, clarification: string): ContextFragment;
122
+ //# sourceMappingURL=user.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user.d.ts","sourceRoot":"","sources":["../../../src/lib/fragments/user.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvD;;;;;;;;;;;;;;;;GAgBG;AAEH;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,eAAe,CAQlB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,eAAe,CAUlB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,eAAe,CAKpE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,eAAe,CAKzE;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,eAAe,CAKhE;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,MAAM,GACpB,eAAe,CAKjB"}