@framers/agentos 0.1.98 → 0.1.99

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 (53) hide show
  1. package/README.md +58 -13
  2. package/dist/api/agency.d.ts +51 -0
  3. package/dist/api/agency.d.ts.map +1 -0
  4. package/dist/api/agency.js +645 -0
  5. package/dist/api/agency.js.map +1 -0
  6. package/dist/api/agent.d.ts +15 -54
  7. package/dist/api/agent.d.ts.map +1 -1
  8. package/dist/api/agent.js +14 -7
  9. package/dist/api/agent.js.map +1 -1
  10. package/dist/api/generateText.d.ts +16 -0
  11. package/dist/api/generateText.d.ts.map +1 -1
  12. package/dist/api/generateText.js.map +1 -1
  13. package/dist/api/hitl.d.ts +139 -0
  14. package/dist/api/hitl.d.ts.map +1 -0
  15. package/dist/api/hitl.js +211 -0
  16. package/dist/api/hitl.js.map +1 -0
  17. package/dist/api/strategies/debate.d.ts +16 -0
  18. package/dist/api/strategies/debate.d.ts.map +1 -0
  19. package/dist/api/strategies/debate.js +118 -0
  20. package/dist/api/strategies/debate.js.map +1 -0
  21. package/dist/api/strategies/hierarchical.d.ts +20 -0
  22. package/dist/api/strategies/hierarchical.d.ts.map +1 -0
  23. package/dist/api/strategies/hierarchical.js +140 -0
  24. package/dist/api/strategies/hierarchical.js.map +1 -0
  25. package/dist/api/strategies/index.d.ts +41 -0
  26. package/dist/api/strategies/index.d.ts.map +1 -0
  27. package/dist/api/strategies/index.js +95 -0
  28. package/dist/api/strategies/index.js.map +1 -0
  29. package/dist/api/strategies/parallel.d.ts +17 -0
  30. package/dist/api/strategies/parallel.d.ts.map +1 -0
  31. package/dist/api/strategies/parallel.js +122 -0
  32. package/dist/api/strategies/parallel.js.map +1 -0
  33. package/dist/api/strategies/review-loop.d.ts +18 -0
  34. package/dist/api/strategies/review-loop.d.ts.map +1 -0
  35. package/dist/api/strategies/review-loop.js +153 -0
  36. package/dist/api/strategies/review-loop.js.map +1 -0
  37. package/dist/api/strategies/sequential.d.ts +15 -0
  38. package/dist/api/strategies/sequential.d.ts.map +1 -0
  39. package/dist/api/strategies/sequential.js +94 -0
  40. package/dist/api/strategies/sequential.js.map +1 -0
  41. package/dist/api/strategies/shared.d.ts +36 -0
  42. package/dist/api/strategies/shared.d.ts.map +1 -0
  43. package/dist/api/strategies/shared.js +82 -0
  44. package/dist/api/strategies/shared.js.map +1 -0
  45. package/dist/api/types.d.ts +806 -0
  46. package/dist/api/types.d.ts.map +1 -0
  47. package/dist/api/types.js +25 -0
  48. package/dist/api/types.js.map +1 -0
  49. package/dist/index.d.ts +5 -0
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +3 -0
  52. package/dist/index.js.map +1 -1
  53. package/package.json +1 -1
@@ -0,0 +1,806 @@
1
+ /**
2
+ * @file types.ts
3
+ * Shared configuration types for the AgentOS high-level Agency API.
4
+ *
5
+ * Defines `BaseAgentConfig` — the unified configuration shape accepted by both
6
+ * `agent()` and `agency()` — together with all supporting sub-config interfaces,
7
+ * event types, callback maps, and the discriminated `AgencyStreamPart` union.
8
+ */
9
+ import type { ToolDefinitionMap } from './toolAdapter.js';
10
+ /**
11
+ * Named security tier controlling which tools and capabilities an agent is
12
+ * permitted to invoke. Ordered from least-restrictive to most-restrictive.
13
+ *
14
+ * - `"dangerous"` — no restrictions; only for trusted internal contexts.
15
+ * - `"permissive"` — most capabilities enabled; network + filesystem allowed.
16
+ * - `"balanced"` — sensible defaults; destructive actions require approval.
17
+ * - `"strict"` — read-only filesystem, no shell spawn, narrow tool allow-list.
18
+ * - `"paranoid"` — minimal surface; all side-effecting tools blocked.
19
+ */
20
+ export type SecurityTier = 'dangerous' | 'permissive' | 'balanced' | 'strict' | 'paranoid';
21
+ /**
22
+ * Memory subsystem classification that controls where and how facts are stored.
23
+ *
24
+ * - `"episodic"` — time-ordered conversation events (what happened when).
25
+ * - `"semantic"` — factual knowledge and entity attributes.
26
+ * - `"procedural"` — learned skills and step-by-step procedures.
27
+ * - `"prospective"` — future intentions and pending reminders.
28
+ */
29
+ export type MemoryType = 'episodic' | 'semantic' | 'procedural' | 'prospective';
30
+ /**
31
+ * High-level orchestration strategy for multi-agent runs.
32
+ *
33
+ * - `"sequential"` — agents are called one after another; output of each feeds the next.
34
+ * - `"parallel"` — all agents are invoked concurrently; results are merged.
35
+ * - `"debate"` — agents iteratively argue and refine a shared answer.
36
+ * - `"review-loop"` — one agent produces output, another reviews and requests revisions.
37
+ * - `"hierarchical"` — a coordinator agent dispatches sub-tasks to specialist agents.
38
+ */
39
+ export type AgencyStrategy = 'sequential' | 'parallel' | 'debate' | 'review-loop' | 'hierarchical';
40
+ /**
41
+ * Fine-grained memory configuration. Pass `true` to `BaseAgentConfig.memory` to
42
+ * enable defaults, or supply this object for explicit control.
43
+ */
44
+ export interface MemoryConfig {
45
+ /** When `true` in a multi-agent context, all agents share the same memory store. */
46
+ shared?: boolean;
47
+ /** Which memory subsystems to activate. */
48
+ types?: MemoryType[];
49
+ /** Configuration for the short-lived working-memory buffer. */
50
+ working?: {
51
+ /** Whether the working-memory buffer is active. */
52
+ enabled: boolean;
53
+ /** Maximum tokens held in the working-memory window. */
54
+ maxTokens?: number;
55
+ /** Eviction / summarisation strategy identifier. */
56
+ strategy?: string;
57
+ };
58
+ /** Configuration for periodic background consolidation of episodic → semantic memory. */
59
+ consolidation?: {
60
+ /** Whether automatic consolidation is enabled. */
61
+ enabled: boolean;
62
+ /** Cron-style or ISO-duration interval between consolidation passes (e.g. `"PT1H"`). */
63
+ interval?: string;
64
+ };
65
+ }
66
+ /**
67
+ * Retrieval-Augmented Generation configuration.
68
+ * Attaches a vector store and optional document loaders to the agent.
69
+ */
70
+ export interface RagConfig {
71
+ /** Vector store provider and embedding model selection. */
72
+ vectorStore?: {
73
+ /** Provider identifier (e.g. `"pinecone"`, `"weaviate"`, `"in-memory"`). */
74
+ provider: string;
75
+ /** Embedding model used to encode documents and queries. */
76
+ embeddingModel?: string;
77
+ };
78
+ /** Document sources to index on startup. */
79
+ documents?: Array<{
80
+ /** Absolute or relative path to a local file. */
81
+ path?: string;
82
+ /** Remote URL to fetch and index. */
83
+ url?: string;
84
+ /** Loader identifier (e.g. `"pdf"`, `"markdown"`, `"html"`). */
85
+ loader?: string;
86
+ }>;
87
+ /** Graph-based RAG extension (e.g. Microsoft GraphRAG). */
88
+ graphRag?: {
89
+ /** Whether graph-enhanced retrieval is active. */
90
+ enabled: boolean;
91
+ /** Graph store provider identifier. */
92
+ provider?: string;
93
+ };
94
+ /** Enable multimodal document indexing alongside text. */
95
+ multimodal?: {
96
+ /** Index and retrieve image content. */
97
+ images?: boolean;
98
+ /** Index and retrieve audio transcripts. */
99
+ audio?: boolean;
100
+ };
101
+ /** Default number of chunks to retrieve per query. */
102
+ topK?: number;
103
+ /** Minimum cosine-similarity score to include a chunk (0–1). */
104
+ minScore?: number;
105
+ /** Per-agent retrieval overrides in multi-agent contexts. */
106
+ agentAccess?: Record<string, {
107
+ /** Override `topK` for this specific agent. */
108
+ topK?: number;
109
+ /** Restrict this agent to a subset of named collections. */
110
+ collections?: string[];
111
+ }>;
112
+ }
113
+ /**
114
+ * Capability discovery configuration.
115
+ * Controls whether and how the agent self-discovers tools and extensions at
116
+ * runtime via the `CapabilityDiscoveryEngine`.
117
+ */
118
+ export interface DiscoveryConfig {
119
+ /** Whether runtime capability discovery is enabled. */
120
+ enabled: boolean;
121
+ /**
122
+ * Filter by capability kind.
123
+ * @example `['tool', 'skill', 'extension']`
124
+ */
125
+ kinds?: string[];
126
+ /**
127
+ * Discovery aggressiveness profile.
128
+ * - `"aggressive"` — maximise recall; may surface lower-relevance capabilities.
129
+ * - `"balanced"` — default trade-off between precision and recall.
130
+ * - `"precision"` — only surface high-confidence matches.
131
+ */
132
+ profile?: 'aggressive' | 'balanced' | 'precision';
133
+ }
134
+ /**
135
+ * Structured guardrail configuration.
136
+ * Allows separate input and output guardrail sets, plus an optional security tier
137
+ * override. Pass a plain `string[]` to `BaseAgentConfig.guardrails` as a shorthand.
138
+ */
139
+ export interface GuardrailsConfig {
140
+ /** Guardrail identifiers applied to every incoming user message. */
141
+ input?: string[];
142
+ /** Guardrail identifiers applied to every outgoing assistant response. */
143
+ output?: string[];
144
+ /** Security tier applied when evaluating guardrail policies. */
145
+ tier?: SecurityTier;
146
+ }
147
+ /**
148
+ * Tool and resource permission overrides for the agent.
149
+ */
150
+ export interface PermissionsConfig {
151
+ /**
152
+ * Which tools the agent is allowed to call.
153
+ * - `"all"` — unrestricted (subject to the active security tier).
154
+ * - `string[]` — explicit allow-list of tool names.
155
+ */
156
+ tools?: 'all' | string[];
157
+ /** Whether the agent may make outbound network requests. */
158
+ network?: boolean;
159
+ /** Whether the agent may read or write files. */
160
+ filesystem?: boolean;
161
+ /** Whether the agent may spawn subprocesses. */
162
+ spawn?: boolean;
163
+ /** Tool names that require a human-in-the-loop approval before execution. */
164
+ requireApproval?: string[];
165
+ }
166
+ /**
167
+ * Human-in-the-loop (HITL) configuration.
168
+ * Gates specific lifecycle events behind an async approval handler before
169
+ * the agent proceeds.
170
+ */
171
+ export interface HitlConfig {
172
+ /**
173
+ * Declarative approval triggers. All are opt-in; omitting a field means
174
+ * no pause at that lifecycle point.
175
+ */
176
+ approvals?: {
177
+ /** Tool names whose invocations require approval before execution. */
178
+ beforeTool?: string[];
179
+ /** Agent names whose invocations require approval before execution. */
180
+ beforeAgent?: string[];
181
+ /** Whether emergent agent creation requires approval. */
182
+ beforeEmergent?: boolean;
183
+ /** Whether returning the final answer requires approval. */
184
+ beforeReturn?: boolean;
185
+ /** Whether a runtime strategy override requires approval. */
186
+ beforeStrategyOverride?: boolean;
187
+ };
188
+ /**
189
+ * Custom async handler invoked for every approval request.
190
+ * Must resolve to an `ApprovalDecision` within `timeoutMs` or the
191
+ * `onTimeout` policy is applied.
192
+ */
193
+ handler?: (request: ApprovalRequest) => Promise<ApprovalDecision>;
194
+ /** Maximum milliseconds to wait for the handler to resolve. Defaults to `30_000`. */
195
+ timeoutMs?: number;
196
+ /**
197
+ * Policy applied when the handler does not respond within `timeoutMs`.
198
+ * - `"reject"` — treat as denied; the action is blocked.
199
+ * - `"approve"` — treat as approved; the action proceeds automatically.
200
+ * - `"error"` — throw an error and halt the run.
201
+ */
202
+ onTimeout?: 'reject' | 'approve' | 'error';
203
+ }
204
+ /**
205
+ * Emergent agent configuration.
206
+ * Controls whether the orchestrator may synthesise new specialist agents
207
+ * at runtime to handle tasks not covered by the statically defined roster.
208
+ */
209
+ export interface EmergentConfig {
210
+ /** Whether runtime agent synthesis is enabled. */
211
+ enabled: boolean;
212
+ /**
213
+ * Scope in which synthesised agents are visible.
214
+ * - `"session"` — ephemeral; discarded when the run ends.
215
+ * - `"agent"` — persisted for the lifetime of the parent agent instance.
216
+ * - `"shared"` — persisted globally across all agent instances.
217
+ */
218
+ tier?: 'session' | 'agent' | 'shared';
219
+ /** When `true`, a separate judge agent evaluates emergent agents before use. */
220
+ judge?: boolean;
221
+ }
222
+ /**
223
+ * Voice interface configuration.
224
+ * Activates real-time audio I/O via a streaming or telephony transport.
225
+ */
226
+ export interface VoiceConfig {
227
+ /** Whether voice mode is active. */
228
+ enabled: boolean;
229
+ /**
230
+ * Underlying transport mechanism.
231
+ * - `"streaming"` — WebSocket / WebRTC real-time audio.
232
+ * - `"telephony"` — PSTN / SIP integration via a telephony provider.
233
+ */
234
+ transport?: 'streaming' | 'telephony';
235
+ /** Speech-to-text provider identifier (e.g. `"deepgram"`, `"whisper"`). */
236
+ stt?: string;
237
+ /** Text-to-speech provider identifier (e.g. `"elevenlabs"`, `"openai-tts"`). */
238
+ tts?: string;
239
+ /** Voice ID or name to use for TTS synthesis. */
240
+ ttsVoice?: string;
241
+ /** Endpointing strategy identifier for turn detection. */
242
+ endpointing?: string;
243
+ /** Barge-in (interruption) strategy identifier. */
244
+ bargeIn?: string;
245
+ /** Whether multi-speaker diarization is enabled. */
246
+ diarization?: boolean;
247
+ /** BCP-47 language tag for STT and TTS (e.g. `"en-US"`). */
248
+ language?: string;
249
+ /** Provider-specific telephony options passed through opaquely. */
250
+ telephony?: Record<string, unknown>;
251
+ }
252
+ /**
253
+ * Provenance and audit-trail configuration.
254
+ * Records a cryptographic chain of custody for every agent action.
255
+ */
256
+ export interface ProvenanceConfig {
257
+ /** Whether provenance recording is active. */
258
+ enabled: boolean;
259
+ /** Append each record to a hash chain for tamper detection. */
260
+ hashChain?: boolean;
261
+ /** Flags controlling which events are included in the provenance log. */
262
+ record?: Record<string, boolean>;
263
+ /**
264
+ * Export format for the provenance ledger.
265
+ * - `"jsonl"` — newline-delimited JSON written to a local file.
266
+ * - `"otlp"` — OpenTelemetry Protocol export to a collector.
267
+ * - `"solana"` — on-chain anchor commitment via the Wunderland SOL integration.
268
+ */
269
+ export?: 'jsonl' | 'otlp' | 'solana';
270
+ }
271
+ /**
272
+ * Observability and telemetry configuration.
273
+ */
274
+ export interface ObservabilityConfig {
275
+ /** Minimum log severity to emit. */
276
+ logLevel?: 'silent' | 'error' | 'info' | 'debug';
277
+ /** Whether to emit structured trace events for every agent lifecycle step. */
278
+ traceEvents?: boolean;
279
+ /** Durable usage ledger options (provider-defined; pass-through). */
280
+ usageLedger?: unknown;
281
+ /** OpenTelemetry integration. */
282
+ otel?: {
283
+ /** Whether OTEL span export is enabled. */
284
+ enabled: boolean;
285
+ };
286
+ }
287
+ /**
288
+ * Resource limits applied to the entire agency run.
289
+ * The `onLimitReached` policy determines whether a breach is fatal.
290
+ */
291
+ export interface ResourceControls {
292
+ /** Maximum total tokens (prompt + completion) across all agents and steps. */
293
+ maxTotalTokens?: number;
294
+ /** Maximum USD cost cap across the entire run. */
295
+ maxCostUSD?: number;
296
+ /** Wall-clock time budget for the run in milliseconds. */
297
+ maxDurationMs?: number;
298
+ /** Maximum number of agent invocations (across all agents). */
299
+ maxAgentCalls?: number;
300
+ /** Maximum steps per individual agent invocation. */
301
+ maxStepsPerAgent?: number;
302
+ /** Maximum number of emergent agents the orchestrator may synthesise. */
303
+ maxEmergentAgents?: number;
304
+ /**
305
+ * Action taken when any resource limit is breached.
306
+ * - `"stop"` — gracefully stop and return partial results.
307
+ * - `"warn"` — emit a `limitReached` event and continue.
308
+ * - `"error"` — throw an error and halt immediately.
309
+ */
310
+ onLimitReached?: 'stop' | 'warn' | 'error';
311
+ }
312
+ /**
313
+ * A pending approval request raised by the HITL subsystem.
314
+ * Passed to `HitlConfig.handler` and emitted on the `approvalRequested` callback.
315
+ */
316
+ export interface ApprovalRequest {
317
+ /** Unique identifier for this approval request. */
318
+ id: string;
319
+ /**
320
+ * What kind of action is awaiting approval.
321
+ *
322
+ * - `"tool"` — a tool invocation.
323
+ * - `"agent"` — an agent invocation.
324
+ * - `"emergent"` — synthesis of a new runtime agent.
325
+ * - `"output"` — the final answer before returning to the caller.
326
+ * - `"strategy-override"` — the orchestrator wants to change the execution strategy.
327
+ */
328
+ type: 'tool' | 'agent' | 'emergent' | 'output' | 'strategy-override';
329
+ /** Name of the agent that triggered the approval request. */
330
+ agent: string;
331
+ /** Short action label (e.g. tool or agent name). */
332
+ action: string;
333
+ /** Human-readable description of what is being approved. */
334
+ description: string;
335
+ /** Structured details about the pending action (tool args, agent config, etc.). */
336
+ details: Record<string, unknown>;
337
+ /** Snapshot of run context at the time the request was raised. */
338
+ context: {
339
+ /** All agent call records completed so far in this run. */
340
+ agentCalls: AgentCallRecord[];
341
+ /** Cumulative token count up to this point. */
342
+ totalTokens: number;
343
+ /** Cumulative cost in USD up to this point. */
344
+ totalCostUSD: number;
345
+ /** Wall-clock milliseconds elapsed since the run started. */
346
+ elapsedMs: number;
347
+ };
348
+ }
349
+ /**
350
+ * The resolved decision returned by `HitlConfig.handler`.
351
+ */
352
+ export interface ApprovalDecision {
353
+ /** Whether the action was approved. */
354
+ approved: boolean;
355
+ /** Optional human-provided rationale for the decision. */
356
+ reason?: string;
357
+ /**
358
+ * Optional in-line modifications the approver wishes to apply.
359
+ * The orchestrator merges these on top of the original action before
360
+ * proceeding (only when `approved` is `true`).
361
+ */
362
+ modifications?: {
363
+ /** Overridden tool arguments. */
364
+ toolArgs?: unknown;
365
+ /** Overridden output text. */
366
+ output?: string;
367
+ /** Additional instructions injected into the agent's system prompt. */
368
+ instructions?: string;
369
+ };
370
+ }
371
+ /**
372
+ * A complete record of a single agent invocation within an agency run.
373
+ * Appended to `GenerateTextResult.agentCalls` and surfaced in `ApprovalRequest.context`.
374
+ */
375
+ export interface AgentCallRecord {
376
+ /** Name of the agent that was invoked. */
377
+ agent: string;
378
+ /** Input prompt or message sent to the agent. */
379
+ input: string;
380
+ /** Final text output produced by the agent. */
381
+ output: string;
382
+ /** Ordered list of tool invocations made during this call. */
383
+ toolCalls: Array<{
384
+ /** Tool name. */
385
+ name: string;
386
+ /** Arguments supplied by the model. */
387
+ args: unknown;
388
+ /** Return value from the tool (present on success). */
389
+ result?: unknown;
390
+ /** Error message if the tool failed. */
391
+ error?: string;
392
+ }>;
393
+ /** Guardrail evaluation results for this agent call. */
394
+ guardrailResults?: Array<{
395
+ /** Guardrail identifier. */
396
+ id: string;
397
+ /** Whether the guardrail check passed. */
398
+ passed: boolean;
399
+ /** Action taken by the guardrail (e.g. `"allow"`, `"block"`, `"redact"`). */
400
+ action: string;
401
+ }>;
402
+ /** Token usage for this individual agent call. */
403
+ usage: {
404
+ promptTokens: number;
405
+ completionTokens: number;
406
+ totalTokens: number;
407
+ /** Cost in USD for this call, when available. */
408
+ costUSD?: number;
409
+ };
410
+ /** Wall-clock milliseconds for this agent call. */
411
+ durationMs: number;
412
+ /** Whether this agent was synthesised at runtime by the emergent subsystem. */
413
+ emergent?: boolean;
414
+ }
415
+ /** Emitted immediately before an agent begins processing its input. */
416
+ export interface AgentStartEvent {
417
+ /** Agent name. */
418
+ agent: string;
419
+ /** Input text provided to the agent. */
420
+ input: string;
421
+ /** Unix timestamp in milliseconds. */
422
+ timestamp: number;
423
+ }
424
+ /** Emitted after an agent has produced its final output. */
425
+ export interface AgentEndEvent {
426
+ /** Agent name. */
427
+ agent: string;
428
+ /** Final text output. */
429
+ output: string;
430
+ /** Wall-clock duration of the agent call. */
431
+ durationMs: number;
432
+ /** Unix timestamp in milliseconds. */
433
+ timestamp: number;
434
+ }
435
+ /** Emitted when the orchestrator routes control from one agent to another. */
436
+ export interface HandoffEvent {
437
+ /** Name of the agent relinquishing control. */
438
+ fromAgent: string;
439
+ /** Name of the agent receiving control. */
440
+ toAgent: string;
441
+ /** Human-readable explanation of why the handoff occurred. */
442
+ reason: string;
443
+ /** Unix timestamp in milliseconds. */
444
+ timestamp: number;
445
+ }
446
+ /** Emitted each time an agent invokes a tool. */
447
+ export interface ToolCallEvent {
448
+ /** Agent name that issued the tool call. */
449
+ agent: string;
450
+ /** Tool name. */
451
+ toolName: string;
452
+ /** Arguments passed to the tool. */
453
+ args: unknown;
454
+ /** Unix timestamp in milliseconds. */
455
+ timestamp: number;
456
+ }
457
+ /** Emitted when the emergent agent subsystem synthesises or attempts to synthesise a new agent. */
458
+ export interface ForgeEvent {
459
+ /** Name assigned to the newly synthesised agent. */
460
+ agentName: string;
461
+ /** System instructions generated for the emergent agent. */
462
+ instructions: string;
463
+ /** Whether the forge was approved (relevant when `HitlConfig.approvals.beforeEmergent` is set). */
464
+ approved: boolean;
465
+ /** Unix timestamp in milliseconds. */
466
+ timestamp: number;
467
+ }
468
+ /** Emitted after a guardrail has evaluated an input or output. */
469
+ export interface GuardrailEvent {
470
+ /** Agent name whose content was evaluated. */
471
+ agent: string;
472
+ /** Guardrail identifier. */
473
+ guardrailId: string;
474
+ /** Whether the guardrail check passed. */
475
+ passed: boolean;
476
+ /** Action taken by the guardrail (e.g. `"allow"`, `"block"`, `"redact"`). */
477
+ action: string;
478
+ /** Unix timestamp in milliseconds. */
479
+ timestamp: number;
480
+ }
481
+ /** Emitted when a `ResourceControls` limit is reached. */
482
+ export interface LimitEvent {
483
+ /** Name of the metric that was breached (e.g. `"maxTotalTokens"`). */
484
+ metric: string;
485
+ /** Observed value at the time of the breach. */
486
+ value: number;
487
+ /** Configured limit that was exceeded. */
488
+ limit: number;
489
+ /** Unix timestamp in milliseconds. */
490
+ timestamp: number;
491
+ }
492
+ /**
493
+ * Discriminated union of all structured trace events emitted by the agency run.
494
+ * Collected in `GenerateTextResult.trace` and emitted via `AgencyCallbacks`.
495
+ */
496
+ export type AgencyTraceEvent = AgentStartEvent | AgentEndEvent | HandoffEvent | ToolCallEvent | ForgeEvent | GuardrailEvent | LimitEvent;
497
+ /**
498
+ * Event callbacks registered on `BaseAgentConfig.on`.
499
+ * All handlers are fire-and-forget (return `void`); errors thrown inside them
500
+ * are swallowed to prevent disrupting the main run.
501
+ */
502
+ export interface AgencyCallbacks {
503
+ /** Called immediately before an agent starts. */
504
+ agentStart?: (e: AgentStartEvent) => void;
505
+ /** Called after an agent produces its final output. */
506
+ agentEnd?: (e: AgentEndEvent) => void;
507
+ /** Called when control is handed off between agents. */
508
+ handoff?: (e: HandoffEvent) => void;
509
+ /** Called when an agent invokes a tool. */
510
+ toolCall?: (e: ToolCallEvent) => void;
511
+ /** Called when an unhandled error occurs inside an agent. */
512
+ error?: (e: {
513
+ agent: string;
514
+ error: Error;
515
+ timestamp: number;
516
+ }) => void;
517
+ /** Called when the emergent subsystem forges a new agent. */
518
+ emergentForge?: (e: ForgeEvent) => void;
519
+ /** Called after a guardrail evaluates an input or output. */
520
+ guardrailResult?: (e: GuardrailEvent) => void;
521
+ /** Called when a resource limit is reached. */
522
+ limitReached?: (e: LimitEvent) => void;
523
+ /** Called when an approval request is raised. */
524
+ approvalRequested?: (e: ApprovalRequest) => void;
525
+ /** Called after an approval decision is resolved. */
526
+ approvalDecided?: (e: ApprovalDecision) => void;
527
+ }
528
+ /**
529
+ * Discriminated union of all streaming events emitted by an `agency()` stream.
530
+ * A superset of the base `StreamPart` type — includes all text/tool events
531
+ * plus agency-level lifecycle events.
532
+ */
533
+ export type AgencyStreamPart = {
534
+ type: 'text';
535
+ text: string;
536
+ agent?: string;
537
+ } | {
538
+ type: 'tool-call';
539
+ toolName: string;
540
+ args: unknown;
541
+ agent?: string;
542
+ } | {
543
+ type: 'tool-result';
544
+ toolName: string;
545
+ result: unknown;
546
+ agent?: string;
547
+ } | {
548
+ type: 'error';
549
+ error: Error;
550
+ agent?: string;
551
+ } | {
552
+ type: 'agent-start';
553
+ agent: string;
554
+ input: string;
555
+ } | {
556
+ type: 'agent-end';
557
+ agent: string;
558
+ output: string;
559
+ durationMs: number;
560
+ } | {
561
+ type: 'agent-handoff';
562
+ fromAgent: string;
563
+ toAgent: string;
564
+ reason: string;
565
+ } | {
566
+ type: 'strategy-override';
567
+ original: string;
568
+ chosen: string;
569
+ reason: string;
570
+ } | {
571
+ type: 'emergent-forge';
572
+ agentName: string;
573
+ instructions: string;
574
+ approved: boolean;
575
+ } | {
576
+ type: 'guardrail-result';
577
+ agent: string;
578
+ guardrailId: string;
579
+ passed: boolean;
580
+ action: string;
581
+ } | {
582
+ type: 'approval-requested';
583
+ request: ApprovalRequest;
584
+ } | {
585
+ type: 'approval-decided';
586
+ requestId: string;
587
+ approved: boolean;
588
+ } | {
589
+ type: 'permission-denied';
590
+ agent: string;
591
+ action: string;
592
+ reason: string;
593
+ };
594
+ /**
595
+ * A stateful agent instance. Returned by both `agent()` and `agency()`.
596
+ * The `agency()` variant additionally coordinates multiple underlying agents.
597
+ */
598
+ export interface Agent {
599
+ /**
600
+ * Generates a single reply (non-streaming).
601
+ *
602
+ * @param prompt - User prompt text.
603
+ * @param opts - Optional per-call overrides.
604
+ * @returns The complete generation result including text, usage, and tool calls.
605
+ */
606
+ generate(prompt: string, opts?: Record<string, unknown>): Promise<unknown>;
607
+ /**
608
+ * Streams a reply, returning a `StreamTextResult`-compatible object.
609
+ *
610
+ * @param prompt - User prompt text.
611
+ * @param opts - Optional per-call overrides.
612
+ * @returns An object with `textStream`, `fullStream`, and awaitable `text`/`usage` promises.
613
+ */
614
+ stream(prompt: string, opts?: Record<string, unknown>): unknown;
615
+ /**
616
+ * Returns (or creates) a named conversation session.
617
+ *
618
+ * @param id - Optional session identifier; auto-generated when omitted.
619
+ * @returns The session object for this ID.
620
+ */
621
+ session(id?: string): unknown;
622
+ /**
623
+ * Returns cumulative usage totals for the agent or a specific session.
624
+ *
625
+ * @param sessionId - Optional session filter.
626
+ */
627
+ usage(sessionId?: string): Promise<unknown>;
628
+ /** Releases all in-memory state held by this agent. */
629
+ close(): Promise<void>;
630
+ /**
631
+ * Starts an HTTP server exposing the agent over a REST / SSE interface.
632
+ * Present on agency instances only.
633
+ *
634
+ * @param opts - Server options including optional port.
635
+ * @returns Resolves to the bound port, URL, and a `close()` teardown function.
636
+ */
637
+ listen?(opts?: {
638
+ port?: number;
639
+ }): Promise<{
640
+ port: number;
641
+ url: string;
642
+ close: () => Promise<void>;
643
+ }>;
644
+ /**
645
+ * Connects the agent to configured channel adapters (e.g. Discord, Slack).
646
+ * Present on agency instances only.
647
+ */
648
+ connect?(): Promise<void>;
649
+ }
650
+ /**
651
+ * An `Agency` is structurally identical to an `Agent` but is returned by
652
+ * `agency()` and coordinates multiple underlying sub-agents.
653
+ */
654
+ export type Agency = Agent;
655
+ /**
656
+ * Full shared configuration accepted by both `agent()` and `agency()`.
657
+ *
658
+ * Each field is optional; sensible defaults are applied at runtime. For the
659
+ * lightweight `agent()` helper, only `model`/`provider`, `instructions`, and
660
+ * `tools` are typically needed. The richer fields (`rag`, `discovery`, `hitl`,
661
+ * `emergent`, `voice`, etc.) are consumed by the full AgentOS orchestrator and
662
+ * the `agency()` factory.
663
+ */
664
+ export interface BaseAgentConfig {
665
+ /**
666
+ * Model identifier. Accepted in two formats:
667
+ * - `"provider:model"` — e.g. `"openai:gpt-4o"`.
668
+ * - Plain model name when `provider` is also set.
669
+ */
670
+ model?: string;
671
+ /**
672
+ * Provider name (e.g. `"openai"`, `"anthropic"`, `"ollama"`).
673
+ * Auto-detected from environment API keys when omitted.
674
+ */
675
+ provider?: string;
676
+ /** Free-form system instructions prepended to the system prompt. */
677
+ instructions?: string;
678
+ /** Display name for the agent, injected into the system prompt. */
679
+ name?: string;
680
+ /** Override the provider API key instead of reading from environment variables. */
681
+ apiKey?: string;
682
+ /** Override the provider base URL (useful for local proxies or Ollama). */
683
+ baseUrl?: string;
684
+ /**
685
+ * HEXACO-inspired personality trait overrides (0–1 scale).
686
+ * Encoded as a human-readable trait string appended to the system prompt.
687
+ */
688
+ personality?: Partial<{
689
+ honesty: number;
690
+ emotionality: number;
691
+ extraversion: number;
692
+ agreeableness: number;
693
+ conscientiousness: number;
694
+ openness: number;
695
+ }>;
696
+ /** Named tools available to the agent on every call. */
697
+ tools?: ToolDefinitionMap;
698
+ /** Maximum number of agentic steps (LLM calls) per invocation. Defaults to `5`. */
699
+ maxSteps?: number;
700
+ /**
701
+ * Memory configuration.
702
+ * - `true` — enable in-memory conversation history with default settings.
703
+ * - `false` — disable memory; every call is stateless.
704
+ * - `MemoryConfig` — full control over memory subsystems.
705
+ */
706
+ memory?: boolean | MemoryConfig;
707
+ /** Retrieval-Augmented Generation configuration. */
708
+ rag?: RagConfig;
709
+ /** Runtime capability discovery configuration. */
710
+ discovery?: DiscoveryConfig;
711
+ /**
712
+ * Guardrail policy identifiers or structured config.
713
+ * - `string[]` — shorthand; applies to both input and output.
714
+ * - `GuardrailsConfig` — full control with separate input/output lists.
715
+ */
716
+ guardrails?: string[] | GuardrailsConfig;
717
+ /** Security tier controlling permitted tools and capabilities. */
718
+ security?: {
719
+ tier: SecurityTier;
720
+ };
721
+ /** Fine-grained tool and resource permission overrides. */
722
+ permissions?: PermissionsConfig;
723
+ /** Human-in-the-loop approval configuration. */
724
+ hitl?: HitlConfig;
725
+ /** Emergent agent synthesis configuration. */
726
+ emergent?: EmergentConfig;
727
+ /** Voice interface configuration. */
728
+ voice?: VoiceConfig;
729
+ /**
730
+ * Channel adapter configurations keyed by channel name.
731
+ * Values are channel-specific option objects passed through opaquely.
732
+ */
733
+ channels?: Record<string, Record<string, unknown>>;
734
+ /**
735
+ * Output schema for structured generation.
736
+ * Accepts a Zod schema at runtime; typed as `unknown` here to avoid a
737
+ * hard dependency on the `zod` package in the types layer.
738
+ */
739
+ output?: unknown;
740
+ /** Provenance and audit-trail configuration. */
741
+ provenance?: ProvenanceConfig;
742
+ /** Observability and telemetry configuration. */
743
+ observability?: ObservabilityConfig;
744
+ /** Event callbacks fired at various lifecycle points during the run. */
745
+ on?: AgencyCallbacks;
746
+ /** Resource limits (tokens, cost, time) applied to the entire run. */
747
+ controls?: ResourceControls;
748
+ }
749
+ /**
750
+ * Configuration for the `agency()` factory function.
751
+ * Extends `BaseAgentConfig` with a required `agents` roster and optional
752
+ * multi-agent orchestration settings.
753
+ */
754
+ export interface AgencyOptions extends BaseAgentConfig {
755
+ /**
756
+ * Named roster of sub-agents. Each value is either a `BaseAgentConfig`
757
+ * object (the agency will instantiate it) or a pre-built `Agent` instance.
758
+ */
759
+ agents: Record<string, BaseAgentConfig | Agent>;
760
+ /**
761
+ * Orchestration strategy for coordinating sub-agents.
762
+ * Defaults to `"sequential"` when omitted.
763
+ */
764
+ strategy?: AgencyStrategy;
765
+ /**
766
+ * Whether the orchestrator may override `strategy` at runtime based on
767
+ * task complexity signals.
768
+ */
769
+ adaptive?: boolean;
770
+ /**
771
+ * Maximum number of orchestration rounds before the run is terminated.
772
+ * Applies to iterative strategies like `"debate"` and `"review-loop"`.
773
+ */
774
+ maxRounds?: number;
775
+ }
776
+ /**
777
+ * Compiled strategy interface used internally by the agency orchestrator.
778
+ * @internal
779
+ */
780
+ export interface CompiledStrategy {
781
+ /**
782
+ * Execute the compiled strategy and return the aggregated result.
783
+ *
784
+ * @param prompt - User prompt.
785
+ * @param opts - Optional per-call overrides.
786
+ */
787
+ execute(prompt: string, opts?: Record<string, unknown>): Promise<unknown>;
788
+ /**
789
+ * Stream the compiled strategy execution.
790
+ *
791
+ * @param prompt - User prompt.
792
+ * @param opts - Optional per-call overrides.
793
+ */
794
+ stream(prompt: string, opts?: Record<string, unknown>): unknown;
795
+ }
796
+ /**
797
+ * Thrown when an `agency()` configuration is invalid (e.g. no agents defined,
798
+ * unknown strategy, conflicting options).
799
+ */
800
+ export declare class AgencyConfigError extends Error {
801
+ /**
802
+ * @param message - Human-readable description of the configuration problem.
803
+ */
804
+ constructor(message: string);
805
+ }
806
+ //# sourceMappingURL=types.d.ts.map