@framers/agentos 0.1.1 → 0.1.3

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 (27) hide show
  1. package/README.md +273 -223
  2. package/dist/cognitive_substrate/personas/definitions/atlas_systems_architect.json +2 -2
  3. package/dist/core/guardrails/ICrossAgentGuardrailService.d.ts +180 -0
  4. package/dist/core/guardrails/ICrossAgentGuardrailService.d.ts.map +1 -0
  5. package/dist/core/guardrails/ICrossAgentGuardrailService.js +26 -0
  6. package/dist/core/guardrails/ICrossAgentGuardrailService.js.map +1 -0
  7. package/dist/core/guardrails/IGuardrailService.d.ts +233 -42
  8. package/dist/core/guardrails/IGuardrailService.d.ts.map +1 -1
  9. package/dist/core/guardrails/IGuardrailService.js +34 -4
  10. package/dist/core/guardrails/IGuardrailService.js.map +1 -1
  11. package/dist/core/guardrails/crossAgentGuardrailDispatcher.d.ts +119 -0
  12. package/dist/core/guardrails/crossAgentGuardrailDispatcher.d.ts.map +1 -0
  13. package/dist/core/guardrails/crossAgentGuardrailDispatcher.js +221 -0
  14. package/dist/core/guardrails/crossAgentGuardrailDispatcher.js.map +1 -0
  15. package/dist/core/guardrails/guardrailDispatcher.d.ts +97 -9
  16. package/dist/core/guardrails/guardrailDispatcher.d.ts.map +1 -1
  17. package/dist/core/guardrails/guardrailDispatcher.js +119 -9
  18. package/dist/core/guardrails/guardrailDispatcher.js.map +1 -1
  19. package/dist/core/guardrails/index.d.ts +52 -0
  20. package/dist/core/guardrails/index.d.ts.map +1 -0
  21. package/dist/core/guardrails/index.js +56 -0
  22. package/dist/core/guardrails/index.js.map +1 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -0
  26. package/dist/index.js.map +1 -1
  27. package/package.json +84 -84
package/README.md CHANGED
@@ -276,241 +276,291 @@ for await (const chunk of agent.processRequest({
276
276
 
277
277
  ## Documentation
278
278
 
279
+ ### Core Concepts
280
+
279
281
  | Guide | Description |
280
282
  |-------|-------------|
281
283
  | [Architecture](./docs/ARCHITECTURE.md) | System design and component overview |
284
+ | [Guardrails](./docs/GUARDRAILS_USAGE.md) | Safety controls and mid-stream intervention |
285
+ | [Extensions](./docs/RFC_EXTENSION_STANDARDS.md) | Extension system and standards |
286
+ | [Ecosystem](./docs/ECOSYSTEM.md) | Related repos and packages |
287
+
288
+ ### Agent Features
289
+
290
+ | Guide | Description |
291
+ |-------|-------------|
282
292
  | [Planning Engine](./docs/PLANNING_ENGINE.md) | Multi-step task planning and execution |
283
293
  | [Human-in-the-Loop](./docs/HUMAN_IN_THE_LOOP.md) | Approval workflows and oversight |
284
294
  | [Agent Communication](./docs/AGENT_COMMUNICATION.md) | Inter-agent messaging patterns |
285
- | [RAG Configuration](./docs/RAG_MEMORY_CONFIGURATION.md) | Memory and retrieval setup |
295
+ | [Self-Building Agents](./docs/RECURSIVE_SELF_BUILDING_AGENTS.md) | Recursive agent construction |
286
296
  | [Structured Output](./docs/STRUCTURED_OUTPUT.md) | JSON schema validation |
287
297
  | [Evaluation Framework](./docs/EVALUATION_FRAMEWORK.md) | Testing and quality assurance |
298
+
299
+ ### Storage & Memory
300
+
301
+ | Guide | Description |
302
+ |-------|-------------|
303
+ | [RAG Configuration](./docs/RAG_MEMORY_CONFIGURATION.md) | Memory and retrieval setup |
304
+ | [SQL Storage](./docs/SQL_STORAGE_QUICKSTART.md) | SQLite/PostgreSQL setup |
305
+ | [Client-Side Storage](./docs/CLIENT_SIDE_STORAGE.md) | Browser storage options |
306
+
307
+ ### Operations
308
+
309
+ | Guide | Description |
310
+ |-------|-------------|
311
+ | [Cost Optimization](./docs/COST_OPTIMIZATION.md) | Token usage and cost management |
312
+ | [Platform Support](./docs/PLATFORM_SUPPORT.md) | Supported platforms and environments |
313
+ | [Releasing](./docs/RELEASING.md) | How to publish new versions |
288
314
  | [API Reference](./docs/api/index.html) | TypeDoc-generated API docs |
315
+ ---
316
+
317
+ ## Examples
318
+
319
+ ### Structured Data Extraction
320
+
321
+ ```typescript
322
+ import { AgentOS, StructuredOutputManager } from '@framers/agentos';
323
+
324
+ const agent = new AgentOS();
325
+ await agent.initialize({
326
+ llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' }
327
+ });
328
+
329
+ // Extract typed data from unstructured text
330
+ const structured = new StructuredOutputManager({ llmProviderManager: agent.llmProviderManager });
331
+ const contact = await structured.generate({
332
+ prompt: 'Extract: "Meeting with Sarah Chen (sarah@startup.io) on Jan 15 re: Series A"',
333
+ schema: {
334
+ type: 'object',
335
+ properties: {
336
+ name: { type: 'string' },
337
+ email: { type: 'string', format: 'email' },
338
+ date: { type: 'string' },
339
+ topic: { type: 'string' }
340
+ },
341
+ required: ['name', 'email']
342
+ },
343
+ schemaName: 'ContactInfo'
344
+ });
345
+ // → { name: 'Sarah Chen', email: 'sarah@startup.io', date: 'Jan 15', topic: 'Series A' }
346
+ ```
347
+
348
+ ### Human-in-the-Loop Approvals
349
+
350
+ ```typescript
351
+ import { HumanInteractionManager } from '@framers/agentos';
352
+
353
+ const hitl = new HumanInteractionManager({ defaultTimeoutMs: 300000 });
354
+
355
+ // Gate high-risk operations with human approval
356
+ const decision = await hitl.requestApproval({
357
+ action: {
358
+ type: 'database_mutation',
359
+ description: 'Archive 50K inactive accounts older than 2 years',
360
+ severity: 'high',
361
+ metadata: { affectedRows: 50000, table: 'users' }
362
+ },
363
+ alternatives: [
364
+ { action: 'soft_delete', description: 'Mark as inactive instead of archiving' },
365
+ { action: 'export_first', description: 'Export to CSV before archiving' }
366
+ ]
367
+ });
368
+
369
+ if (decision.approved) {
370
+ await executeArchive();
371
+ } else if (decision.selectedAlternative) {
372
+ await executeAlternative(decision.selectedAlternative);
373
+ }
374
+ ```
375
+
376
+ ### Autonomous Task Planning
377
+
378
+ ```typescript
379
+ import { AgentOS, PlanningEngine } from '@framers/agentos';
380
+
381
+ const agent = new AgentOS();
382
+ await agent.initialize({
383
+ llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' }
384
+ });
385
+
386
+ const planner = new PlanningEngine({ llmProvider: agent.llmProviderManager, strategy: 'react' });
387
+
388
+ // Decompose complex goals into executable steps with ReAct reasoning
389
+ const plan = await planner.generatePlan({
390
+ goal: 'Migrate authentication from sessions to JWT',
391
+ constraints: ['Zero downtime', 'Backwards compatible for 30 days', 'Audit logging required'],
392
+ context: { currentStack: 'Express + Redis sessions', userCount: '50K' }
393
+ });
394
+
395
+ for await (const step of planner.executePlan(plan.id)) {
396
+ console.log(`[${step.status}] ${step.action}`);
397
+ if (step.requiresHumanApproval) {
398
+ const approved = await promptUser(step.description);
399
+ if (!approved) break;
400
+ }
401
+ }
402
+ ```
403
+
404
+ ### Multi-Agent Collaboration
405
+
406
+ ```typescript
407
+ import { AgentOS, AgencyRegistry, AgentCommunicationBus } from '@framers/agentos';
408
+
409
+ // Create specialized agents
410
+ const researcher = new AgentOS();
411
+ await researcher.initialize({ llmProvider: llmConfig, persona: 'Research analyst' });
412
+
413
+ const writer = new AgentOS();
414
+ await writer.initialize({ llmProvider: llmConfig, persona: 'Technical writer' });
415
+
416
+ // Register in agency with shared communication
417
+ const agency = new AgencyRegistry();
418
+ const bus = new AgentCommunicationBus();
419
+ agency.register('researcher', researcher, { bus });
420
+ agency.register('writer', writer, { bus });
421
+
422
+ // Agents coordinate via message passing
423
+ bus.on('research:complete', async ({ findings }) => {
424
+ await writer.processRequest({
425
+ message: `Write documentation based on: ${JSON.stringify(findings)}`
426
+ });
427
+ });
428
+
429
+ await researcher.processRequest({ message: 'Analyze the authentication module' });
430
+ ```
431
+
432
+ ### Guardrails: Mid-Stream Decision Override
433
+
434
+ ```typescript
435
+ import { AgentOS } from '@framers/agentos';
436
+ import { CostCeilingGuardrail } from './guardrails/CostCeilingGuardrail';
437
+
438
+ const costGuard = new CostCeilingGuardrail({
439
+ maxCostUsd: 0.05, // 5 cents per request
440
+ inputTokenPricePer1k: 0.0001,
441
+ outputTokenPricePer1k: 0.0002,
442
+ budgetExceededText: 'Response exceeded cost ceiling. Please refine your request.'
443
+ });
444
+
445
+ const agent = new AgentOS();
446
+ await agent.initialize({
447
+ llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY },
448
+ guardrailService: costGuard
449
+ });
450
+
451
+ // Agent generates expensive response → guardrail intercepts → substitutes budget message
452
+ // Agents can "change their mind" before delivery based on cost, content policy, or quality checks
453
+ ```
454
+
455
+ See [Guardrails Usage Guide](./docs/GUARDRAILS_USAGE.md) for complete documentation.
456
+
457
+ ### Non-Streaming Response
458
+
459
+ ```typescript
460
+ import { AgentOS } from '@framers/agentos';
461
+
462
+ const agent = new AgentOS();
463
+ await agent.initialize({
464
+ llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' }
465
+ });
466
+
467
+ // Collect full response without streaming
468
+ const chunks = [];
469
+ for await (const chunk of agent.processRequest({ message: 'Explain OAuth 2.0 briefly' })) {
470
+ if (chunk.type === 'content') {
471
+ chunks.push(chunk.content);
472
+ }
473
+ }
474
+ const fullResponse = chunks.join('');
475
+ ```
476
+
477
+ ### Mood-Adaptive Responses
478
+
479
+ ```typescript
480
+ import { AgentOS, GMIMood } from '@framers/agentos';
481
+
482
+ const agent = new AgentOS();
483
+ await agent.initialize({
484
+ llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' },
485
+ persona: {
486
+ name: 'Support Agent',
487
+ moodAdaptation: {
488
+ enabled: true,
489
+ defaultMood: GMIMood.EMPATHETIC,
490
+ allowedMoods: [GMIMood.EMPATHETIC, GMIMood.FOCUSED, GMIMood.ANALYTICAL],
491
+ sensitivityFactor: 0.7,
492
+ // Mood-specific prompt modifiers
493
+ moodPrompts: {
494
+ [GMIMood.EMPATHETIC]: 'Prioritize understanding and emotional support.',
495
+ [GMIMood.FRUSTRATED]: 'Acknowledge difficulty, offer step-by-step guidance.',
496
+ [GMIMood.ANALYTICAL]: 'Provide detailed technical explanations with examples.'
497
+ }
498
+ }
499
+ }
500
+ });
501
+
502
+ // Agent automatically adapts tone based on conversation context
503
+ for await (const chunk of agent.processRequest({
504
+ message: 'This is so frustrating, nothing works!'
505
+ })) {
506
+ // Response adapts with empathetic tone, mood shifts to EMPATHETIC
507
+ }
508
+ ```
509
+
510
+ ### Contextual Prompt Adaptation
511
+
512
+ ```typescript
513
+ import { AgentOS } from '@framers/agentos';
514
+
515
+ const agent = new AgentOS();
516
+ await agent.initialize({
517
+ llmProvider: llmConfig,
518
+ persona: {
519
+ name: 'Adaptive Tutor',
520
+ // Dynamic prompt elements injected based on runtime context
521
+ contextualPromptElements: [
522
+ {
523
+ id: 'beginner-guidance',
524
+ type: 'SYSTEM_INSTRUCTION_ADDON',
525
+ content: 'Explain concepts simply, avoid jargon, use analogies.',
526
+ criteria: { userSkillLevel: ['novice', 'beginner'] },
527
+ priority: 10
528
+ },
529
+ {
530
+ id: 'expert-mode',
531
+ type: 'SYSTEM_INSTRUCTION_ADDON',
532
+ content: 'Assume deep technical knowledge, be concise, skip basics.',
533
+ criteria: { userSkillLevel: ['expert', 'advanced'] },
534
+ priority: 10
535
+ },
536
+ {
537
+ id: 'debugging-context',
538
+ type: 'FEW_SHOT_EXAMPLE',
539
+ content: { role: 'assistant', content: 'Let\'s trace through step by step...' },
540
+ criteria: { taskHint: ['debugging', 'troubleshooting'] }
541
+ }
542
+ ],
543
+ // Meta-prompts for self-reflection and planning
544
+ metaPrompts: [
545
+ {
546
+ id: 'mid-conversation-check',
547
+ trigger: 'every_n_turns',
548
+ triggerConfig: { n: 5 },
549
+ prompt: 'Assess: Is the user making progress? Should I adjust my approach?'
550
+ }
551
+ ]
552
+ }
553
+ });
554
+
555
+ // Prompts automatically adapt based on user context and task
556
+ await agent.updateUserContext({ skillLevel: 'expert' });
557
+ for await (const chunk of agent.processRequest({ message: 'Explain monads' })) {
558
+ // Uses expert-mode prompt element, skips beginner explanations
559
+ }
560
+ ```
289
561
 
290
562
  ---
291
563
 
292
- ## Examples
293
-
294
- ### Structured Data Extraction
295
-
296
- ```typescript
297
- import { AgentOS, StructuredOutputManager } from '@framers/agentos';
298
-
299
- const agent = new AgentOS();
300
- await agent.initialize({
301
- llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' }
302
- });
303
-
304
- // Extract typed data from unstructured text
305
- const structured = new StructuredOutputManager({ llmProviderManager: agent.llmProviderManager });
306
- const contact = await structured.generate({
307
- prompt: 'Extract: "Meeting with Sarah Chen (sarah@startup.io) on Jan 15 re: Series A"',
308
- schema: {
309
- type: 'object',
310
- properties: {
311
- name: { type: 'string' },
312
- email: { type: 'string', format: 'email' },
313
- date: { type: 'string' },
314
- topic: { type: 'string' }
315
- },
316
- required: ['name', 'email']
317
- },
318
- schemaName: 'ContactInfo'
319
- });
320
- // → { name: 'Sarah Chen', email: 'sarah@startup.io', date: 'Jan 15', topic: 'Series A' }
321
- ```
322
-
323
- ### Human-in-the-Loop Approvals
324
-
325
- ```typescript
326
- import { HumanInteractionManager } from '@framers/agentos';
327
-
328
- const hitl = new HumanInteractionManager({ defaultTimeoutMs: 300000 });
329
-
330
- // Gate high-risk operations with human approval
331
- const decision = await hitl.requestApproval({
332
- action: {
333
- type: 'database_mutation',
334
- description: 'Archive 50K inactive accounts older than 2 years',
335
- severity: 'high',
336
- metadata: { affectedRows: 50000, table: 'users' }
337
- },
338
- alternatives: [
339
- { action: 'soft_delete', description: 'Mark as inactive instead of archiving' },
340
- { action: 'export_first', description: 'Export to CSV before archiving' }
341
- ]
342
- });
343
-
344
- if (decision.approved) {
345
- await executeArchive();
346
- } else if (decision.selectedAlternative) {
347
- await executeAlternative(decision.selectedAlternative);
348
- }
349
- ```
350
-
351
- ### Autonomous Task Planning
352
-
353
- ```typescript
354
- import { AgentOS, PlanningEngine } from '@framers/agentos';
355
-
356
- const agent = new AgentOS();
357
- await agent.initialize({
358
- llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' }
359
- });
360
-
361
- const planner = new PlanningEngine({ llmProvider: agent.llmProviderManager, strategy: 'react' });
362
-
363
- // Decompose complex goals into executable steps with ReAct reasoning
364
- const plan = await planner.generatePlan({
365
- goal: 'Migrate authentication from sessions to JWT',
366
- constraints: ['Zero downtime', 'Backwards compatible for 30 days', 'Audit logging required'],
367
- context: { currentStack: 'Express + Redis sessions', userCount: '50K' }
368
- });
369
-
370
- for await (const step of planner.executePlan(plan.id)) {
371
- console.log(`[${step.status}] ${step.action}`);
372
- if (step.requiresHumanApproval) {
373
- const approved = await promptUser(step.description);
374
- if (!approved) break;
375
- }
376
- }
377
- ```
378
-
379
- ### Multi-Agent Collaboration
380
-
381
- ```typescript
382
- import { AgentOS, AgencyRegistry, AgentCommunicationBus } from '@framers/agentos';
383
-
384
- // Create specialized agents
385
- const researcher = new AgentOS();
386
- await researcher.initialize({ llmProvider: llmConfig, persona: 'Research analyst' });
387
-
388
- const writer = new AgentOS();
389
- await writer.initialize({ llmProvider: llmConfig, persona: 'Technical writer' });
390
-
391
- // Register in agency with shared communication
392
- const agency = new AgencyRegistry();
393
- const bus = new AgentCommunicationBus();
394
- agency.register('researcher', researcher, { bus });
395
- agency.register('writer', writer, { bus });
396
-
397
- // Agents coordinate via message passing
398
- bus.on('research:complete', async ({ findings }) => {
399
- await writer.processRequest({
400
- message: `Write documentation based on: ${JSON.stringify(findings)}`
401
- });
402
- });
403
-
404
- await researcher.processRequest({ message: 'Analyze the authentication module' });
405
- ```
406
-
407
- ### Non-Streaming Response
408
-
409
- ```typescript
410
- import { AgentOS } from '@framers/agentos';
411
-
412
- const agent = new AgentOS();
413
- await agent.initialize({
414
- llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' }
415
- });
416
-
417
- // Collect full response without streaming
418
- const chunks = [];
419
- for await (const chunk of agent.processRequest({ message: 'Explain OAuth 2.0 briefly' })) {
420
- if (chunk.type === 'content') {
421
- chunks.push(chunk.content);
422
- }
423
- }
424
- const fullResponse = chunks.join('');
425
- ```
426
-
427
- ### Mood-Adaptive Responses
428
-
429
- ```typescript
430
- import { AgentOS, GMIMood } from '@framers/agentos';
431
-
432
- const agent = new AgentOS();
433
- await agent.initialize({
434
- llmProvider: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' },
435
- persona: {
436
- name: 'Support Agent',
437
- moodAdaptation: {
438
- enabled: true,
439
- defaultMood: GMIMood.EMPATHETIC,
440
- allowedMoods: [GMIMood.EMPATHETIC, GMIMood.FOCUSED, GMIMood.ANALYTICAL],
441
- sensitivityFactor: 0.7,
442
- // Mood-specific prompt modifiers
443
- moodPrompts: {
444
- [GMIMood.EMPATHETIC]: 'Prioritize understanding and emotional support.',
445
- [GMIMood.FRUSTRATED]: 'Acknowledge difficulty, offer step-by-step guidance.',
446
- [GMIMood.ANALYTICAL]: 'Provide detailed technical explanations with examples.'
447
- }
448
- }
449
- }
450
- });
451
-
452
- // Agent automatically adapts tone based on conversation context
453
- for await (const chunk of agent.processRequest({
454
- message: 'This is so frustrating, nothing works!'
455
- })) {
456
- // Response adapts with empathetic tone, mood shifts to EMPATHETIC
457
- }
458
- ```
459
-
460
- ### Contextual Prompt Adaptation
461
-
462
- ```typescript
463
- import { AgentOS } from '@framers/agentos';
464
-
465
- const agent = new AgentOS();
466
- await agent.initialize({
467
- llmProvider: llmConfig,
468
- persona: {
469
- name: 'Adaptive Tutor',
470
- // Dynamic prompt elements injected based on runtime context
471
- contextualPromptElements: [
472
- {
473
- id: 'beginner-guidance',
474
- type: 'SYSTEM_INSTRUCTION_ADDON',
475
- content: 'Explain concepts simply, avoid jargon, use analogies.',
476
- criteria: { userSkillLevel: ['novice', 'beginner'] },
477
- priority: 10
478
- },
479
- {
480
- id: 'expert-mode',
481
- type: 'SYSTEM_INSTRUCTION_ADDON',
482
- content: 'Assume deep technical knowledge, be concise, skip basics.',
483
- criteria: { userSkillLevel: ['expert', 'advanced'] },
484
- priority: 10
485
- },
486
- {
487
- id: 'debugging-context',
488
- type: 'FEW_SHOT_EXAMPLE',
489
- content: { role: 'assistant', content: 'Let\'s trace through step by step...' },
490
- criteria: { taskHint: ['debugging', 'troubleshooting'] }
491
- }
492
- ],
493
- // Meta-prompts for self-reflection and planning
494
- metaPrompts: [
495
- {
496
- id: 'mid-conversation-check',
497
- trigger: 'every_n_turns',
498
- triggerConfig: { n: 5 },
499
- prompt: 'Assess: Is the user making progress? Should I adjust my approach?'
500
- }
501
- ]
502
- }
503
- });
504
-
505
- // Prompts automatically adapt based on user context and task
506
- await agent.updateUserContext({ skillLevel: 'expert' });
507
- for await (const chunk of agent.processRequest({ message: 'Explain monads' })) {
508
- // Uses expert-mode prompt element, skips beginner explanations
509
- }
510
- ```
511
-
512
- ---
513
-
514
564
  ## Roadmap
515
565
 
516
566
  | Version | Status | Features |
@@ -2,8 +2,8 @@
2
2
  "id": "atlas-systems-architect",
3
3
  "version": "1.0.0",
4
4
  "name": "Atlas - Systems Architect",
5
- "role": "system",
6
- "systemPrompt": "You are Atlas, an expert systems architect and technical consultant. You excel at designing scalable, maintainable software architectures. You help users understand system design patterns, make architectural decisions, and plan technical implementations.\n\nYour approach:\n- Break down complex systems into understandable components\n- Consider scalability, reliability, and maintainability\n- Recommend industry best practices and proven patterns\n- Explain trade-offs clearly\n- Provide actionable implementation guidance\n\nYou communicate technical concepts clearly and help users navigate architectural decisions with confidence.",
5
+ "description": "Expert systems architect for technical design and architecture decisions",
6
+ "baseSystemPrompt": "You are Atlas, an expert systems architect and technical consultant. You excel at designing scalable, maintainable software architectures. You help users understand system design patterns, make architectural decisions, and plan technical implementations.\n\nYour approach:\n- Break down complex systems into understandable components\n- Consider scalability, reliability, and maintainability\n- Recommend industry best practices and proven patterns\n- Explain trade-offs clearly\n- Provide actionable implementation guidance\n\nYou communicate technical concepts clearly and help users navigate architectural decisions with confidence.",
7
7
  "modelPreference": {
8
8
  "primary": "openai/gpt-4o",
9
9
  "fallback": "openai/gpt-4o-mini"
@@ -0,0 +1,180 @@
1
+ /**
2
+ * @module ICrossAgentGuardrailService
3
+ *
4
+ * Cross-agent guardrail interface for multi-agent supervision.
5
+ *
6
+ * Extends {@link IGuardrailService} to enable guardrails that observe
7
+ * and intervene in other agents' output streams. This enables patterns like:
8
+ * - Supervisor agents monitoring worker agents
9
+ * - Quality gates across an agency
10
+ * - Cross-agent policy enforcement
11
+ *
12
+ * @example Supervisor guardrail
13
+ * ```typescript
14
+ * class SupervisorGuardrail implements ICrossAgentGuardrailService {
15
+ * observeAgentIds = ['worker-1', 'worker-2'];
16
+ * canInterruptOthers = true;
17
+ * config = { evaluateStreamingChunks: true };
18
+ *
19
+ * async evaluateCrossAgentOutput({ sourceAgentId, chunk }) {
20
+ * if (chunk.textDelta?.includes('CONFIDENTIAL')) {
21
+ * return {
22
+ * action: GuardrailAction.BLOCK,
23
+ * reason: `Agent ${sourceAgentId} attempted to leak confidential info`
24
+ * };
25
+ * }
26
+ * return null;
27
+ * }
28
+ * }
29
+ * ```
30
+ */
31
+ import type { AgentOSResponse } from '../../api/types/AgentOSResponse';
32
+ import type { GuardrailContext, GuardrailEvaluationResult, IGuardrailService } from './IGuardrailService';
33
+ /**
34
+ * Payload for cross-agent output evaluation.
35
+ *
36
+ * Provides information about both the source agent (producing output)
37
+ * and the observer agent (running the guardrail).
38
+ */
39
+ export interface CrossAgentOutputPayload {
40
+ /**
41
+ * The agent that produced this output chunk.
42
+ * Use this to apply agent-specific policies.
43
+ */
44
+ sourceAgentId: string;
45
+ /**
46
+ * The agent running this guardrail (the observer/supervisor).
47
+ */
48
+ observerAgentId: string;
49
+ /**
50
+ * Agency ID if both agents belong to the same agency.
51
+ * Useful for agency-level policy enforcement.
52
+ */
53
+ agencyId?: string;
54
+ /**
55
+ * The output chunk from the source agent.
56
+ */
57
+ chunk: AgentOSResponse;
58
+ /**
59
+ * Guardrail context for policy decisions.
60
+ */
61
+ context: GuardrailContext;
62
+ }
63
+ /**
64
+ * Cross-agent guardrail service for multi-agent supervision.
65
+ *
66
+ * Extends {@link IGuardrailService} to enable observation and intervention
67
+ * in other agents' output streams. Use this for:
68
+ *
69
+ * - **Supervisor patterns**: A supervisor agent monitors worker agents
70
+ * - **Quality gates**: Enforce quality standards across an agency
71
+ * - **Policy enforcement**: Apply organization-wide rules to all agents
72
+ * - **Safety monitoring**: Detect and prevent harmful outputs from any agent
73
+ *
74
+ * @example Quality gate guardrail
75
+ * ```typescript
76
+ * class QualityGateGuardrail implements ICrossAgentGuardrailService {
77
+ * // Observe all agents in the agency
78
+ * observeAgentIds = [];
79
+ * canInterruptOthers = true;
80
+ *
81
+ * async evaluateCrossAgentOutput({ sourceAgentId, chunk, context }) {
82
+ * if (chunk.type === 'FINAL_RESPONSE') {
83
+ * const quality = await assessQuality(chunk.finalResponseText);
84
+ * if (quality.score < 0.5) {
85
+ * return {
86
+ * action: GuardrailAction.BLOCK,
87
+ * reason: 'Response did not meet quality standards',
88
+ * metadata: { qualityScore: quality.score, agent: sourceAgentId }
89
+ * };
90
+ * }
91
+ * }
92
+ * return null;
93
+ * }
94
+ * }
95
+ * ```
96
+ *
97
+ * @example Selective agent monitoring
98
+ * ```typescript
99
+ * class SensitiveDataGuardrail implements ICrossAgentGuardrailService {
100
+ * // Only observe agents handling sensitive data
101
+ * observeAgentIds = ['data-analyst', 'report-generator'];
102
+ * canInterruptOthers = true;
103
+ * config = { evaluateStreamingChunks: true };
104
+ *
105
+ * async evaluateCrossAgentOutput({ chunk }) {
106
+ * if (chunk.textDelta && containsPII(chunk.textDelta)) {
107
+ * return {
108
+ * action: GuardrailAction.SANITIZE,
109
+ * modifiedText: redactPII(chunk.textDelta)
110
+ * };
111
+ * }
112
+ * return null;
113
+ * }
114
+ * }
115
+ * ```
116
+ */
117
+ export interface ICrossAgentGuardrailService extends IGuardrailService {
118
+ /**
119
+ * Agent IDs this guardrail observes.
120
+ *
121
+ * - Empty array `[]` or undefined: Observe all agents in the agency
122
+ * - Specific IDs: Only observe listed agents
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * // Observe specific workers
127
+ * observeAgentIds = ['worker-1', 'worker-2'];
128
+ *
129
+ * // Observe all agents
130
+ * observeAgentIds = [];
131
+ * ```
132
+ */
133
+ observeAgentIds?: string[];
134
+ /**
135
+ * Whether this guardrail can interrupt other agents' streams.
136
+ *
137
+ * When `true`:
138
+ * - {@link GuardrailAction.BLOCK} terminates the observed agent's stream
139
+ * - {@link GuardrailAction.SANITIZE} modifies the observed agent's output
140
+ *
141
+ * When `false` (default):
142
+ * - Guardrail can only observe and log (FLAG action)
143
+ * - BLOCK/SANITIZE actions are downgraded to FLAG
144
+ *
145
+ * @default false
146
+ */
147
+ canInterruptOthers?: boolean;
148
+ /**
149
+ * Evaluate output from an observed agent.
150
+ *
151
+ * Called when an observed agent (per {@link observeAgentIds}) emits a chunk.
152
+ * The evaluation timing depends on {@link IGuardrailService.config}:
153
+ * - `evaluateStreamingChunks: true`: Called for each TEXT_DELTA
154
+ * - `evaluateStreamingChunks: false`: Called only for FINAL_RESPONSE
155
+ *
156
+ * @param payload - Cross-agent context and chunk to evaluate
157
+ * @returns Evaluation result, or `null` to allow without action
158
+ *
159
+ * @remarks
160
+ * - Only effective when {@link canInterruptOthers} is `true`
161
+ * - Falls back to this guardrail's own stream for logging/metadata
162
+ */
163
+ evaluateCrossAgentOutput?(payload: CrossAgentOutputPayload): Promise<GuardrailEvaluationResult | null>;
164
+ }
165
+ /**
166
+ * Type guard to check if a guardrail service is a cross-agent guardrail.
167
+ *
168
+ * @param service - Guardrail service to check
169
+ * @returns `true` if the service implements cross-agent evaluation
170
+ */
171
+ export declare function isCrossAgentGuardrail(service: IGuardrailService): service is ICrossAgentGuardrailService;
172
+ /**
173
+ * Check if a cross-agent guardrail should observe a specific agent.
174
+ *
175
+ * @param guardrail - The cross-agent guardrail
176
+ * @param agentId - The agent ID to check
177
+ * @returns `true` if the guardrail should observe this agent
178
+ */
179
+ export declare function shouldObserveAgent(guardrail: ICrossAgentGuardrailService, agentId: string): boolean;
180
+ //# sourceMappingURL=ICrossAgentGuardrailService.d.ts.map