@reactive-agents/runtime 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tyler Buell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # @reactive-agents/runtime
2
+
3
+ The execution runtime for [Reactive Agents](https://tylerjrbuell.github.io/reactive-agents-ts/).
4
+
5
+ Contains the 10-phase `ExecutionEngine`, the `ReactiveAgentBuilder` fluent API, and `createRuntime()` — the function that wires all optional layers together.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ bun add @reactive-agents/runtime effect
11
+ ```
12
+
13
+ Or install everything at once (recommended for new projects):
14
+
15
+ ```bash
16
+ bun add reactive-agents effect
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### Builder API (recommended)
22
+
23
+ ```typescript
24
+ import { ReactiveAgents } from "@reactive-agents/runtime";
25
+
26
+ const agent = await ReactiveAgents.create()
27
+ .withName("my-agent")
28
+ .withProvider("anthropic")
29
+ .withModel("claude-sonnet-4-20250514")
30
+ .withMemory("1")
31
+ .withReasoning()
32
+ .withGuardrails()
33
+ .withCostTracking()
34
+ .build();
35
+
36
+ const result = await agent.run("Explain the CAP theorem");
37
+ console.log(result.output);
38
+ console.log(result.metadata); // { duration, cost, tokensUsed, stepsCount }
39
+ ```
40
+
41
+ ### Effect API
42
+
43
+ ```typescript
44
+ import { Effect } from "effect";
45
+ import { ReactiveAgents } from "@reactive-agents/runtime";
46
+
47
+ const program = Effect.gen(function* () {
48
+ const agent = yield* ReactiveAgents.create()
49
+ .withName("my-agent")
50
+ .withProvider("anthropic")
51
+ .buildEffect();
52
+
53
+ return yield* agent.runEffect("What is the meaning of life?");
54
+ });
55
+
56
+ const result = await Effect.runPromise(program);
57
+ ```
58
+
59
+ ### Low-level `createRuntime()`
60
+
61
+ ```typescript
62
+ import { createRuntime } from "@reactive-agents/runtime";
63
+ import { Effect } from "effect";
64
+
65
+ const runtime = createRuntime({
66
+ agentId: "my-agent",
67
+ provider: "anthropic",
68
+ enableReasoning: true,
69
+ enableGuardrails: true,
70
+ enableCostTracking: true,
71
+ });
72
+ ```
73
+
74
+ ## The 10-Phase Execution Engine
75
+
76
+ Every task flows through:
77
+
78
+ 1. **Bootstrap** — load memory context
79
+ 2. **Guardrail** — safety checks on input
80
+ 3. **Cost Route** — select optimal model
81
+ 4. **Strategy Select** — choose reasoning strategy
82
+ 5. **Think** — LLM completion
83
+ 6. **Act** — tool execution
84
+ 7. **Observe** — append results
85
+ 8. **Verify** — fact-check output
86
+ 9. **Memory Flush** — persist session
87
+ 10. **Complete** — return result
88
+
89
+ Each phase supports `before`, `after`, and `on-error` lifecycle hooks.
90
+
91
+ ## Documentation
92
+
93
+ Full documentation at [tylerjrbuell.github.io/reactive-agents-ts](https://tylerjrbuell.github.io/reactive-agents-ts/)
@@ -0,0 +1,241 @@
1
+ import * as effect from 'effect';
2
+ import { Schema, Context, Effect, Layer } from 'effect';
3
+ import * as effect_Cause from 'effect/Cause';
4
+ import * as effect_Types from 'effect/Types';
5
+ import * as _reactive_agents_core from '@reactive-agents/core';
6
+ import { Task, TaskResult, TaskError } from '@reactive-agents/core';
7
+ import * as _reactive_agents_memory from '@reactive-agents/memory';
8
+ import * as _reactive_agents_llm_provider from '@reactive-agents/llm-provider';
9
+
10
+ declare const ExecutionError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
11
+ readonly _tag: "ExecutionError";
12
+ } & Readonly<A>;
13
+ declare class ExecutionError extends ExecutionError_base<{
14
+ readonly message: string;
15
+ readonly taskId: string;
16
+ readonly phase: string;
17
+ readonly cause?: unknown;
18
+ }> {
19
+ }
20
+ declare const HookError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
21
+ readonly _tag: "HookError";
22
+ } & Readonly<A>;
23
+ declare class HookError extends HookError_base<{
24
+ readonly message: string;
25
+ readonly phase: string;
26
+ readonly timing: string;
27
+ readonly cause?: unknown;
28
+ }> {
29
+ }
30
+ declare const MaxIterationsError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
31
+ readonly _tag: "MaxIterationsError";
32
+ } & Readonly<A>;
33
+ declare class MaxIterationsError extends MaxIterationsError_base<{
34
+ readonly message: string;
35
+ readonly taskId: string;
36
+ readonly iterations: number;
37
+ readonly maxIterations: number;
38
+ }> {
39
+ }
40
+ declare const GuardrailViolationError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
41
+ readonly _tag: "GuardrailViolationError";
42
+ } & Readonly<A>;
43
+ declare class GuardrailViolationError extends GuardrailViolationError_base<{
44
+ readonly message: string;
45
+ readonly taskId: string;
46
+ readonly violation: string;
47
+ }> {
48
+ }
49
+ type RuntimeErrors = ExecutionError | HookError | MaxIterationsError | GuardrailViolationError;
50
+
51
+ declare const LifecyclePhase: Schema.Literal<["bootstrap", "guardrail", "cost-route", "strategy-select", "think", "act", "observe", "verify", "memory-flush", "cost-track", "audit", "complete"]>;
52
+ type LifecyclePhase = typeof LifecyclePhase.Type;
53
+ declare const HookTiming: Schema.Literal<["before", "after", "on-error"]>;
54
+ type HookTiming = typeof HookTiming.Type;
55
+ declare const AgentState: Schema.Literal<["idle", "bootstrapping", "running", "paused", "verifying", "flushing", "completed", "failed"]>;
56
+ type AgentState = typeof AgentState.Type;
57
+ declare const ExecutionContextSchema: Schema.Struct<{
58
+ taskId: typeof Schema.String;
59
+ agentId: typeof Schema.String;
60
+ sessionId: typeof Schema.String;
61
+ phase: Schema.Literal<["bootstrap", "guardrail", "cost-route", "strategy-select", "think", "act", "observe", "verify", "memory-flush", "cost-track", "audit", "complete"]>;
62
+ agentState: Schema.Literal<["idle", "bootstrapping", "running", "paused", "verifying", "flushing", "completed", "failed"]>;
63
+ iteration: typeof Schema.Number;
64
+ maxIterations: typeof Schema.Number;
65
+ messages: Schema.Array$<typeof Schema.Unknown>;
66
+ memoryContext: Schema.optional<typeof Schema.Unknown>;
67
+ selectedStrategy: Schema.optional<typeof Schema.String>;
68
+ selectedModel: Schema.optional<typeof Schema.Unknown>;
69
+ toolResults: Schema.Array$<typeof Schema.Unknown>;
70
+ cost: typeof Schema.Number;
71
+ startedAt: typeof Schema.DateFromSelf;
72
+ metadata: Schema.Record$<typeof Schema.String, typeof Schema.Unknown>;
73
+ }>;
74
+ type ExecutionContext = typeof ExecutionContextSchema.Type;
75
+ declare const ToolResultSchema: Schema.Struct<{
76
+ toolCallId: typeof Schema.String;
77
+ toolName: typeof Schema.String;
78
+ result: typeof Schema.Unknown;
79
+ error: Schema.optional<typeof Schema.String>;
80
+ durationMs: typeof Schema.Number;
81
+ }>;
82
+ type ToolResult = typeof ToolResultSchema.Type;
83
+ interface LifecycleHook {
84
+ readonly phase: LifecyclePhase;
85
+ readonly timing: HookTiming;
86
+ readonly handler: (ctx: ExecutionContext) => effect.Effect.Effect<ExecutionContext, ExecutionError>;
87
+ }
88
+ declare const ReactiveAgentsConfigSchema: Schema.Struct<{
89
+ maxIterations: typeof Schema.Number;
90
+ defaultModel: Schema.optional<typeof Schema.Unknown>;
91
+ memoryTier: Schema.Literal<["1", "2"]>;
92
+ enableGuardrails: typeof Schema.Boolean;
93
+ enableVerification: typeof Schema.Boolean;
94
+ enableCostTracking: typeof Schema.Boolean;
95
+ enableAudit: typeof Schema.Boolean;
96
+ agentId: typeof Schema.String;
97
+ }>;
98
+ type ReactiveAgentsConfig = typeof ReactiveAgentsConfigSchema.Type;
99
+ declare const defaultReactiveAgentsConfig: (agentId: string) => ReactiveAgentsConfig;
100
+
101
+ declare const LifecycleHookRegistry_base: Context.TagClass<LifecycleHookRegistry, "LifecycleHookRegistry", {
102
+ /** Register a lifecycle hook. Returns unregister function. */
103
+ readonly register: (hook: LifecycleHook) => Effect.Effect<() => void, never>;
104
+ /** Run all hooks for a phase/timing. Returns updated context. */
105
+ readonly run: (phase: LifecyclePhase, timing: HookTiming, ctx: ExecutionContext) => Effect.Effect<ExecutionContext, HookError>;
106
+ /** Get all registered hooks. */
107
+ readonly list: () => Effect.Effect<readonly LifecycleHook[], never>;
108
+ }>;
109
+ declare class LifecycleHookRegistry extends LifecycleHookRegistry_base {
110
+ }
111
+ declare const LifecycleHookRegistryLive: Layer.Layer<LifecycleHookRegistry, never, never>;
112
+
113
+ declare const ExecutionEngine_base: Context.TagClass<ExecutionEngine, "ExecutionEngine", {
114
+ readonly execute: (task: Task) => Effect.Effect<TaskResult, RuntimeErrors | TaskError>;
115
+ readonly registerHook: (hook: LifecycleHook) => Effect.Effect<void, never>;
116
+ readonly getContext: (taskId: string) => Effect.Effect<ExecutionContext | null, never>;
117
+ readonly cancel: (taskId: string) => Effect.Effect<void, ExecutionError>;
118
+ }>;
119
+ declare class ExecutionEngine extends ExecutionEngine_base {
120
+ }
121
+ declare const ExecutionEngineLive: (config: ReactiveAgentsConfig) => Layer.Layer<ExecutionEngine, never, LifecycleHookRegistry>;
122
+
123
+ interface RuntimeOptions {
124
+ agentId: string;
125
+ provider?: "anthropic" | "openai" | "ollama" | "gemini" | "test";
126
+ memoryTier?: "1" | "2";
127
+ maxIterations?: number;
128
+ testResponses?: Record<string, string>;
129
+ extraLayers?: Layer.Layer<any, any>;
130
+ enableGuardrails?: boolean;
131
+ enableVerification?: boolean;
132
+ enableCostTracking?: boolean;
133
+ enableReasoning?: boolean;
134
+ enableTools?: boolean;
135
+ enableIdentity?: boolean;
136
+ enableObservability?: boolean;
137
+ enableInteraction?: boolean;
138
+ enablePrompts?: boolean;
139
+ enableOrchestration?: boolean;
140
+ enableAudit?: boolean;
141
+ }
142
+ /**
143
+ * Create the full reactive-agents runtime layer.
144
+ *
145
+ * Composes Core + LLM + Memory + ExecutionEngine as the base,
146
+ * then merges optional layers based on the enabled flags.
147
+ *
148
+ * Usage:
149
+ * const Runtime = createRuntime({
150
+ * agentId: "my-agent",
151
+ * provider: "anthropic",
152
+ * enableReasoning: true,
153
+ * enableGuardrails: true,
154
+ * });
155
+ */
156
+ declare const createRuntime: (options: RuntimeOptions) => Layer.Layer<LifecycleHookRegistry | ExecutionEngine | _reactive_agents_core.AgentService | _reactive_agents_core.TaskService | _reactive_agents_core.ContextWindowManager | _reactive_agents_core.EventBus | _reactive_agents_llm_provider.LLMService | _reactive_agents_llm_provider.PromptManager | _reactive_agents_memory.MemoryDatabase | _reactive_agents_memory.MemorySearchService | _reactive_agents_memory.WorkingMemoryService | _reactive_agents_memory.SemanticMemoryService | _reactive_agents_memory.EpisodicMemoryService | _reactive_agents_memory.ProceduralMemoryService | _reactive_agents_memory.MemoryFileSystem | _reactive_agents_memory.ZettelkastenService | _reactive_agents_memory.MemoryService, _reactive_agents_memory.DatabaseError, never>;
157
+
158
+ interface AgentResultMetadata {
159
+ readonly duration: number;
160
+ readonly cost: number;
161
+ readonly tokensUsed: number;
162
+ readonly strategyUsed?: string;
163
+ readonly stepsCount: number;
164
+ }
165
+ interface AgentResult {
166
+ readonly output: string;
167
+ readonly success: boolean;
168
+ readonly taskId: string;
169
+ readonly agentId: string;
170
+ readonly metadata: AgentResultMetadata;
171
+ }
172
+ declare const ReactiveAgents: {
173
+ /** Create a new builder. All configuration is optional except `.withModel()`. */
174
+ create: () => ReactiveAgentBuilder;
175
+ };
176
+ declare class ReactiveAgentBuilder {
177
+ private _name;
178
+ private _provider;
179
+ private _model?;
180
+ private _memoryTier;
181
+ private _hooks;
182
+ private _maxIterations;
183
+ private _enableGuardrails;
184
+ private _enableVerification;
185
+ private _enableCostTracking;
186
+ private _enableAudit;
187
+ private _enableReasoning;
188
+ private _enableTools;
189
+ private _enableIdentity;
190
+ private _enableObservability;
191
+ private _enableInteraction;
192
+ private _enablePrompts;
193
+ private _enableOrchestration;
194
+ private _testResponses?;
195
+ private _extraLayers?;
196
+ withName(name: string): this;
197
+ withModel(model: string): this;
198
+ withProvider(provider: "anthropic" | "openai" | "ollama" | "gemini" | "test"): this;
199
+ withMemory(tier: "1" | "2"): this;
200
+ withMaxIterations(n: number): this;
201
+ withHook(hook: LifecycleHook): this;
202
+ withGuardrails(): this;
203
+ withVerification(): this;
204
+ withCostTracking(): this;
205
+ withAudit(): this;
206
+ withReasoning(): this;
207
+ withTools(): this;
208
+ withIdentity(): this;
209
+ withObservability(): this;
210
+ withInteraction(): this;
211
+ withPrompts(): this;
212
+ withOrchestration(): this;
213
+ withTestResponses(responses: Record<string, string>): this;
214
+ withLayers(layers: Layer.Layer<any, any>): this;
215
+ build(): Promise<ReactiveAgent>;
216
+ buildEffect(): Effect.Effect<ReactiveAgent, Error>;
217
+ }
218
+ declare class ReactiveAgent {
219
+ private readonly engine;
220
+ readonly agentId: string;
221
+ private readonly runtime;
222
+ constructor(engine: {
223
+ execute: (task: any) => Effect.Effect<any, any>;
224
+ cancel: (taskId: string) => Effect.Effect<void, any>;
225
+ getContext: (taskId: string) => Effect.Effect<any, never>;
226
+ }, agentId: string, runtime: Layer.Layer<any, any>);
227
+ /**
228
+ * Run a task and return the result (Simple API).
229
+ */
230
+ run(input: string): Promise<AgentResult>;
231
+ /**
232
+ * Run a task and return the result (Advanced API — Effect).
233
+ */
234
+ runEffect(input: string): Effect.Effect<AgentResult, Error>;
235
+ /** Cancel a running task by ID. */
236
+ cancel(taskId: string): Promise<void>;
237
+ /** Inspect context of a running task (null if not running). */
238
+ getContext(taskId: string): Promise<unknown>;
239
+ }
240
+
241
+ export { type AgentResult, type AgentResultMetadata, AgentState, AgentState as AgentStateSchema, type ExecutionContext, ExecutionContextSchema, ExecutionEngine, ExecutionEngineLive, ExecutionError, GuardrailViolationError, HookError, HookTiming, HookTiming as HookTimingSchema, type LifecycleHook, LifecycleHookRegistry, LifecycleHookRegistryLive, LifecyclePhase, LifecyclePhase as LifecyclePhaseSchema, MaxIterationsError, ReactiveAgent, ReactiveAgentBuilder, ReactiveAgents, type ReactiveAgentsConfig, ReactiveAgentsConfigSchema, type RuntimeErrors, type ToolResult, ToolResultSchema, createRuntime, defaultReactiveAgentsConfig };
package/dist/index.js ADDED
@@ -0,0 +1,757 @@
1
+ // src/types.ts
2
+ import { Schema } from "effect";
3
+ var LifecyclePhase = Schema.Literal(
4
+ "bootstrap",
5
+ "guardrail",
6
+ "cost-route",
7
+ "strategy-select",
8
+ "think",
9
+ "act",
10
+ "observe",
11
+ "verify",
12
+ "memory-flush",
13
+ "cost-track",
14
+ "audit",
15
+ "complete"
16
+ );
17
+ var HookTiming = Schema.Literal("before", "after", "on-error");
18
+ var AgentState = Schema.Literal(
19
+ "idle",
20
+ "bootstrapping",
21
+ "running",
22
+ "paused",
23
+ "verifying",
24
+ "flushing",
25
+ "completed",
26
+ "failed"
27
+ );
28
+ var ExecutionContextSchema = Schema.Struct({
29
+ taskId: Schema.String,
30
+ agentId: Schema.String,
31
+ sessionId: Schema.String,
32
+ phase: LifecyclePhase,
33
+ agentState: AgentState,
34
+ iteration: Schema.Number,
35
+ maxIterations: Schema.Number,
36
+ messages: Schema.Array(Schema.Unknown),
37
+ memoryContext: Schema.optional(Schema.Unknown),
38
+ selectedStrategy: Schema.optional(Schema.String),
39
+ selectedModel: Schema.optional(Schema.Unknown),
40
+ toolResults: Schema.Array(Schema.Unknown),
41
+ cost: Schema.Number,
42
+ startedAt: Schema.DateFromSelf,
43
+ metadata: Schema.Record({ key: Schema.String, value: Schema.Unknown })
44
+ });
45
+ var ToolResultSchema = Schema.Struct({
46
+ toolCallId: Schema.String,
47
+ toolName: Schema.String,
48
+ result: Schema.Unknown,
49
+ error: Schema.optional(Schema.String),
50
+ durationMs: Schema.Number
51
+ });
52
+ var ReactiveAgentsConfigSchema = Schema.Struct({
53
+ maxIterations: Schema.Number,
54
+ defaultModel: Schema.optional(Schema.Unknown),
55
+ memoryTier: Schema.Literal("1", "2"),
56
+ enableGuardrails: Schema.Boolean,
57
+ enableVerification: Schema.Boolean,
58
+ enableCostTracking: Schema.Boolean,
59
+ enableAudit: Schema.Boolean,
60
+ agentId: Schema.String
61
+ });
62
+ var defaultReactiveAgentsConfig = (agentId) => ({
63
+ maxIterations: 10,
64
+ memoryTier: "1",
65
+ enableGuardrails: false,
66
+ enableVerification: false,
67
+ enableCostTracking: false,
68
+ enableAudit: false,
69
+ agentId
70
+ });
71
+
72
+ // src/errors.ts
73
+ import { Data } from "effect";
74
+ var ExecutionError = class extends Data.TaggedError("ExecutionError") {
75
+ };
76
+ var HookError = class extends Data.TaggedError("HookError") {
77
+ };
78
+ var MaxIterationsError = class extends Data.TaggedError("MaxIterationsError") {
79
+ };
80
+ var GuardrailViolationError = class extends Data.TaggedError(
81
+ "GuardrailViolationError"
82
+ ) {
83
+ };
84
+
85
+ // src/hooks.ts
86
+ import { Effect, Context, Layer, Ref } from "effect";
87
+ var LifecycleHookRegistry = class extends Context.Tag("LifecycleHookRegistry")() {
88
+ };
89
+ var LifecycleHookRegistryLive = Layer.effect(
90
+ LifecycleHookRegistry,
91
+ Effect.gen(function* () {
92
+ const hooks = yield* Ref.make([]);
93
+ return {
94
+ register: (hook) => Effect.gen(function* () {
95
+ yield* Ref.update(hooks, (hs) => [...hs, hook]);
96
+ return () => {
97
+ Effect.runSync(
98
+ Ref.update(hooks, (hs) => hs.filter((h) => h !== hook))
99
+ );
100
+ };
101
+ }),
102
+ run: (phase, timing, ctx) => Effect.gen(function* () {
103
+ const allHooks = yield* Ref.get(hooks);
104
+ const matching = allHooks.filter(
105
+ (h) => h.phase === phase && h.timing === timing
106
+ );
107
+ let current = ctx;
108
+ for (const hook of matching) {
109
+ current = yield* hook.handler(current).pipe(
110
+ Effect.mapError(
111
+ (cause) => new HookError({
112
+ message: `Hook failed for ${phase}/${timing}: ${cause}`,
113
+ phase,
114
+ timing,
115
+ cause
116
+ })
117
+ )
118
+ );
119
+ }
120
+ return current;
121
+ }),
122
+ list: () => Ref.get(hooks)
123
+ };
124
+ })
125
+ );
126
+
127
+ // src/execution-engine.ts
128
+ import { Effect as Effect2, Context as Context2, Layer as Layer2, Ref as Ref2 } from "effect";
129
+ var ExecutionEngine = class extends Context2.Tag("ExecutionEngine")() {
130
+ };
131
+ var ExecutionEngineLive = (config) => Layer2.effect(
132
+ ExecutionEngine,
133
+ Effect2.gen(function* () {
134
+ const hookRegistry = yield* LifecycleHookRegistry;
135
+ const runningContexts = yield* Ref2.make(
136
+ /* @__PURE__ */ new Map()
137
+ );
138
+ const cancelledTasks = yield* Ref2.make(/* @__PURE__ */ new Set());
139
+ const runPhase = (ctx, phase, body) => Effect2.gen(function* () {
140
+ const ctxBefore = { ...ctx, phase };
141
+ const ctxAfterBefore = yield* hookRegistry.run(phase, "before", ctxBefore).pipe(Effect2.catchAll(() => Effect2.succeed(ctxBefore)));
142
+ const cancelled = yield* Ref2.get(cancelledTasks);
143
+ if (cancelled.has(ctx.taskId)) {
144
+ return yield* Effect2.fail(
145
+ new ExecutionError({
146
+ message: `Task ${ctx.taskId} was cancelled`,
147
+ taskId: ctx.taskId,
148
+ phase
149
+ })
150
+ );
151
+ }
152
+ const ctxAfterBody = yield* body(ctxAfterBefore).pipe(
153
+ Effect2.tapError(
154
+ (e) => hookRegistry.run(phase, "on-error", {
155
+ ...ctxAfterBefore,
156
+ metadata: { ...ctxAfterBefore.metadata, error: e }
157
+ }).pipe(Effect2.catchAll(() => Effect2.void))
158
+ )
159
+ );
160
+ const ctxFinal = yield* hookRegistry.run(phase, "after", ctxAfterBody).pipe(Effect2.catchAll(() => Effect2.succeed(ctxAfterBody)));
161
+ return ctxFinal;
162
+ });
163
+ const execute = (task) => Effect2.gen(function* () {
164
+ const now = /* @__PURE__ */ new Date();
165
+ const sessionId = `session-${Date.now()}`;
166
+ let ctx = {
167
+ taskId: task.id,
168
+ agentId: task.agentId,
169
+ sessionId,
170
+ phase: "bootstrap",
171
+ agentState: "bootstrapping",
172
+ iteration: 0,
173
+ maxIterations: config.maxIterations,
174
+ messages: [],
175
+ toolResults: [],
176
+ cost: 0,
177
+ startedAt: now,
178
+ metadata: {}
179
+ };
180
+ yield* Ref2.update(
181
+ runningContexts,
182
+ (m) => new Map(m).set(task.id, ctx)
183
+ );
184
+ ctx = yield* runPhase(
185
+ ctx,
186
+ "bootstrap",
187
+ (c) => Effect2.gen(function* () {
188
+ const memoryContext = yield* Effect2.serviceOption(
189
+ Context2.GenericTag("MemoryService")
190
+ ).pipe(
191
+ Effect2.flatMap(
192
+ (opt) => opt._tag === "Some" ? opt.value.bootstrap(c.agentId).pipe(Effect2.map((mc) => mc)) : Effect2.succeed(void 0)
193
+ ),
194
+ Effect2.catchAll(() => Effect2.succeed(void 0))
195
+ );
196
+ return {
197
+ ...c,
198
+ agentState: "running",
199
+ memoryContext
200
+ };
201
+ })
202
+ );
203
+ if (config.enableGuardrails) {
204
+ ctx = yield* runPhase(
205
+ ctx,
206
+ "guardrail",
207
+ (c) => Effect2.succeed(c)
208
+ );
209
+ }
210
+ if (config.enableCostTracking) {
211
+ ctx = yield* runPhase(
212
+ ctx,
213
+ "cost-route",
214
+ (c) => Effect2.succeed({ ...c, selectedModel: config.defaultModel })
215
+ );
216
+ }
217
+ ctx = yield* runPhase(
218
+ ctx,
219
+ "strategy-select",
220
+ (c) => Effect2.gen(function* () {
221
+ const selectorOpt = yield* Effect2.serviceOption(
222
+ Context2.GenericTag("StrategySelector")
223
+ );
224
+ const strategy = selectorOpt._tag === "Some" ? yield* selectorOpt.value.select(
225
+ {
226
+ taskDescription: JSON.stringify(task.input),
227
+ taskType: task.type,
228
+ complexity: 0.5,
229
+ urgency: 0.5
230
+ },
231
+ c.memoryContext
232
+ ).pipe(Effect2.catchAll(() => Effect2.succeed("reactive"))) : "reactive";
233
+ return { ...c, selectedStrategy: strategy };
234
+ })
235
+ );
236
+ const reasoningOpt = yield* Effect2.serviceOption(
237
+ Context2.GenericTag("ReasoningService")
238
+ );
239
+ if (reasoningOpt._tag === "Some") {
240
+ ctx = yield* runPhase(
241
+ ctx,
242
+ "think",
243
+ (c) => Effect2.gen(function* () {
244
+ const result2 = yield* reasoningOpt.value.execute({
245
+ taskDescription: JSON.stringify(task.input),
246
+ taskType: task.type,
247
+ memoryContext: String(
248
+ c.memoryContext?.semanticContext ?? ""
249
+ ),
250
+ availableTools: [],
251
+ strategy: c.selectedStrategy ?? "reactive"
252
+ });
253
+ return {
254
+ ...c,
255
+ cost: c.cost + (result2.metadata.cost ?? 0),
256
+ metadata: {
257
+ ...c.metadata,
258
+ lastResponse: String(result2.output ?? ""),
259
+ isComplete: result2.status === "completed",
260
+ reasoningResult: result2,
261
+ stepsCount: result2.metadata.stepsCount
262
+ }
263
+ };
264
+ })
265
+ );
266
+ } else {
267
+ let isComplete = false;
268
+ while (!isComplete && ctx.iteration < ctx.maxIterations) {
269
+ ctx = yield* runPhase(
270
+ ctx,
271
+ "think",
272
+ (c) => Effect2.gen(function* () {
273
+ const llm = yield* Context2.GenericTag("LLMService");
274
+ const systemPrompt = c.memoryContext ? `${String(c.memoryContext.semanticContext ?? "")}
275
+
276
+ Complete the task: ${JSON.stringify(task.input)}` : `Complete the task: ${JSON.stringify(task.input)}`;
277
+ const response = yield* llm.complete({
278
+ messages: c.messages,
279
+ systemPrompt,
280
+ model: c.selectedModel
281
+ });
282
+ const updatedMessages = [
283
+ ...c.messages,
284
+ { role: "assistant", content: response.content }
285
+ ];
286
+ const done = response.stopReason === "end_turn" && !response.toolCalls?.length;
287
+ return {
288
+ ...c,
289
+ messages: updatedMessages,
290
+ metadata: {
291
+ ...c.metadata,
292
+ lastResponse: response.content,
293
+ pendingToolCalls: response.toolCalls ?? [],
294
+ isComplete: done
295
+ }
296
+ };
297
+ })
298
+ );
299
+ const pendingCalls = ctx.metadata.pendingToolCalls ?? [];
300
+ if (pendingCalls.length > 0) {
301
+ ctx = yield* runPhase(
302
+ ctx,
303
+ "act",
304
+ (c) => Effect2.gen(function* () {
305
+ const toolResults = pendingCalls.map(
306
+ (call) => ({
307
+ toolCallId: call.id ?? "unknown",
308
+ toolName: call.name ?? "unknown",
309
+ result: `[Tool ${call.name} executed]`,
310
+ durationMs: 0
311
+ })
312
+ );
313
+ return {
314
+ ...c,
315
+ toolResults: [...c.toolResults, ...toolResults]
316
+ };
317
+ })
318
+ );
319
+ ctx = yield* runPhase(
320
+ ctx,
321
+ "observe",
322
+ (c) => Effect2.succeed({
323
+ ...c,
324
+ messages: [
325
+ ...c.messages,
326
+ {
327
+ role: "user",
328
+ content: c.toolResults.slice(-pendingCalls.length).map(
329
+ (r) => `Tool result: ${JSON.stringify(r.result)}`
330
+ ).join("\n")
331
+ }
332
+ ],
333
+ iteration: c.iteration + 1
334
+ })
335
+ );
336
+ } else {
337
+ isComplete = Boolean(ctx.metadata.isComplete);
338
+ ctx = { ...ctx, iteration: ctx.iteration + 1 };
339
+ }
340
+ }
341
+ if (!isComplete && ctx.iteration >= ctx.maxIterations) {
342
+ return yield* Effect2.fail(
343
+ new MaxIterationsError({
344
+ message: `Task ${task.id} exceeded max iterations (${ctx.maxIterations})`,
345
+ taskId: task.id,
346
+ iterations: ctx.iteration,
347
+ maxIterations: ctx.maxIterations
348
+ })
349
+ );
350
+ }
351
+ }
352
+ if (config.enableVerification) {
353
+ ctx = yield* runPhase(ctx, "verify", (c) => Effect2.succeed(c));
354
+ }
355
+ ctx = yield* runPhase(
356
+ ctx,
357
+ "memory-flush",
358
+ (c) => Effect2.gen(function* () {
359
+ yield* Effect2.serviceOption(
360
+ Context2.GenericTag("MemoryService")
361
+ ).pipe(
362
+ Effect2.flatMap(
363
+ (opt) => opt._tag === "Some" ? opt.value.snapshot({
364
+ id: c.sessionId,
365
+ agentId: c.agentId,
366
+ messages: c.messages,
367
+ summary: String(c.metadata.lastResponse ?? ""),
368
+ keyDecisions: [],
369
+ taskIds: [c.taskId],
370
+ startedAt: c.startedAt,
371
+ endedAt: /* @__PURE__ */ new Date(),
372
+ totalCost: c.cost,
373
+ totalTokens: 0
374
+ }) : Effect2.void
375
+ ),
376
+ Effect2.catchAll(() => Effect2.void)
377
+ );
378
+ return { ...c, agentState: "flushing" };
379
+ })
380
+ );
381
+ if (config.enableCostTracking) {
382
+ ctx = yield* runPhase(
383
+ ctx,
384
+ "cost-track",
385
+ (c) => Effect2.succeed(c)
386
+ );
387
+ }
388
+ if (config.enableAudit) {
389
+ ctx = yield* runPhase(ctx, "audit", (c) => Effect2.succeed(c));
390
+ }
391
+ ctx = yield* runPhase(
392
+ ctx,
393
+ "complete",
394
+ (c) => Effect2.succeed({ ...c, agentState: "completed" })
395
+ );
396
+ const result = {
397
+ taskId: task.id,
398
+ agentId: task.agentId,
399
+ output: ctx.metadata.lastResponse ?? null,
400
+ success: true,
401
+ metadata: {
402
+ duration: Date.now() - ctx.startedAt.getTime(),
403
+ cost: ctx.cost,
404
+ tokensUsed: 0,
405
+ strategyUsed: ctx.selectedStrategy,
406
+ stepsCount: ctx.iteration
407
+ },
408
+ completedAt: /* @__PURE__ */ new Date()
409
+ };
410
+ return result;
411
+ }).pipe(
412
+ // Always clean up running context
413
+ Effect2.ensuring(
414
+ Ref2.update(runningContexts, (m) => {
415
+ const next = new Map(m);
416
+ next.delete(task.id);
417
+ return next;
418
+ })
419
+ )
420
+ );
421
+ return {
422
+ execute,
423
+ registerHook: (hook) => hookRegistry.register(hook).pipe(Effect2.asVoid),
424
+ getContext: (taskId) => Ref2.get(runningContexts).pipe(
425
+ Effect2.map((m) => m.get(taskId) ?? null)
426
+ ),
427
+ cancel: (taskId) => Effect2.gen(function* () {
428
+ const running = yield* Ref2.get(runningContexts);
429
+ if (!running.has(taskId)) {
430
+ return yield* Effect2.fail(
431
+ new ExecutionError({
432
+ message: `Task ${taskId} is not running`,
433
+ taskId,
434
+ phase: "complete"
435
+ })
436
+ );
437
+ }
438
+ yield* Ref2.update(cancelledTasks, (s) => new Set(s).add(taskId));
439
+ })
440
+ };
441
+ })
442
+ );
443
+
444
+ // src/runtime.ts
445
+ import { Layer as Layer3 } from "effect";
446
+ import { CoreServicesLive, EventBusLive } from "@reactive-agents/core";
447
+ import { createLLMProviderLayer } from "@reactive-agents/llm-provider";
448
+ import { createMemoryLayer } from "@reactive-agents/memory";
449
+ import { createGuardrailsLayer } from "@reactive-agents/guardrails";
450
+ import { createVerificationLayer } from "@reactive-agents/verification";
451
+ import { createCostLayer } from "@reactive-agents/cost";
452
+ import { createReasoningLayer } from "@reactive-agents/reasoning";
453
+ import { createToolsLayer } from "@reactive-agents/tools";
454
+ import { createIdentityLayer } from "@reactive-agents/identity";
455
+ import { createObservabilityLayer } from "@reactive-agents/observability";
456
+ import { createInteractionLayer } from "@reactive-agents/interaction";
457
+ import { createPromptLayer } from "@reactive-agents/prompts";
458
+ import { createOrchestrationLayer } from "@reactive-agents/orchestration";
459
+ var createRuntime = (options) => {
460
+ const config = {
461
+ ...defaultReactiveAgentsConfig(options.agentId),
462
+ memoryTier: options.memoryTier ?? "1",
463
+ maxIterations: options.maxIterations ?? 10,
464
+ enableGuardrails: options.enableGuardrails ?? false,
465
+ enableVerification: options.enableVerification ?? false,
466
+ enableCostTracking: options.enableCostTracking ?? false,
467
+ enableAudit: options.enableAudit ?? false
468
+ };
469
+ const eventBusLayer = EventBusLive;
470
+ const coreLayer = CoreServicesLive;
471
+ const llmLayer = createLLMProviderLayer(
472
+ options.provider ?? "test",
473
+ options.testResponses
474
+ );
475
+ const memoryLayer = createMemoryLayer(config.memoryTier, {
476
+ agentId: options.agentId
477
+ });
478
+ const hookLayer = LifecycleHookRegistryLive;
479
+ const engineLayer = ExecutionEngineLive(config).pipe(Layer3.provide(hookLayer));
480
+ let runtime = Layer3.mergeAll(
481
+ coreLayer,
482
+ eventBusLayer,
483
+ llmLayer,
484
+ memoryLayer,
485
+ hookLayer,
486
+ engineLayer
487
+ );
488
+ if (options.enableGuardrails) {
489
+ runtime = Layer3.merge(runtime, createGuardrailsLayer());
490
+ }
491
+ if (options.enableVerification) {
492
+ runtime = Layer3.merge(runtime, createVerificationLayer());
493
+ }
494
+ if (options.enableCostTracking) {
495
+ runtime = Layer3.merge(runtime, createCostLayer());
496
+ }
497
+ if (options.enableReasoning) {
498
+ const reasoningLayer = createReasoningLayer().pipe(Layer3.provide(llmLayer));
499
+ runtime = Layer3.merge(runtime, reasoningLayer);
500
+ }
501
+ if (options.enableTools) {
502
+ const toolsLayer = createToolsLayer().pipe(Layer3.provide(eventBusLayer));
503
+ runtime = Layer3.merge(runtime, toolsLayer);
504
+ }
505
+ if (options.enableIdentity) {
506
+ runtime = Layer3.merge(runtime, createIdentityLayer());
507
+ }
508
+ if (options.enableObservability) {
509
+ runtime = Layer3.merge(runtime, createObservabilityLayer());
510
+ }
511
+ if (options.enableInteraction) {
512
+ const interactionLayer = createInteractionLayer().pipe(
513
+ Layer3.provide(eventBusLayer)
514
+ );
515
+ runtime = Layer3.merge(runtime, interactionLayer);
516
+ }
517
+ if (options.enablePrompts) {
518
+ runtime = Layer3.merge(runtime, createPromptLayer());
519
+ }
520
+ if (options.enableOrchestration) {
521
+ runtime = Layer3.merge(runtime, createOrchestrationLayer());
522
+ }
523
+ if (options.extraLayers) {
524
+ runtime = Layer3.merge(runtime, options.extraLayers);
525
+ }
526
+ return runtime;
527
+ };
528
+
529
+ // src/builder.ts
530
+ import { Effect as Effect3 } from "effect";
531
+ var ReactiveAgents = {
532
+ /** Create a new builder. All configuration is optional except `.withModel()`. */
533
+ create: () => new ReactiveAgentBuilder()
534
+ };
535
+ var ReactiveAgentBuilder = class {
536
+ _name = "agent";
537
+ _provider = "test";
538
+ _model;
539
+ _memoryTier = "1";
540
+ _hooks = [];
541
+ _maxIterations = 10;
542
+ _enableGuardrails = false;
543
+ _enableVerification = false;
544
+ _enableCostTracking = false;
545
+ _enableAudit = false;
546
+ _enableReasoning = false;
547
+ _enableTools = false;
548
+ _enableIdentity = false;
549
+ _enableObservability = false;
550
+ _enableInteraction = false;
551
+ _enablePrompts = false;
552
+ _enableOrchestration = false;
553
+ _testResponses;
554
+ _extraLayers;
555
+ // ─── Identity ───
556
+ withName(name) {
557
+ this._name = name;
558
+ return this;
559
+ }
560
+ // ─── Model & Provider ───
561
+ withModel(model) {
562
+ this._model = model;
563
+ return this;
564
+ }
565
+ withProvider(provider) {
566
+ this._provider = provider;
567
+ return this;
568
+ }
569
+ // ─── Memory ───
570
+ withMemory(tier) {
571
+ this._memoryTier = tier;
572
+ return this;
573
+ }
574
+ // ─── Execution ───
575
+ withMaxIterations(n) {
576
+ this._maxIterations = n;
577
+ return this;
578
+ }
579
+ // ─── Lifecycle Hooks ───
580
+ withHook(hook) {
581
+ this._hooks.push(hook);
582
+ return this;
583
+ }
584
+ // ─── Optional Features ───
585
+ withGuardrails() {
586
+ this._enableGuardrails = true;
587
+ return this;
588
+ }
589
+ withVerification() {
590
+ this._enableVerification = true;
591
+ return this;
592
+ }
593
+ withCostTracking() {
594
+ this._enableCostTracking = true;
595
+ return this;
596
+ }
597
+ withAudit() {
598
+ this._enableAudit = true;
599
+ return this;
600
+ }
601
+ withReasoning() {
602
+ this._enableReasoning = true;
603
+ return this;
604
+ }
605
+ withTools() {
606
+ this._enableTools = true;
607
+ return this;
608
+ }
609
+ withIdentity() {
610
+ this._enableIdentity = true;
611
+ return this;
612
+ }
613
+ withObservability() {
614
+ this._enableObservability = true;
615
+ return this;
616
+ }
617
+ withInteraction() {
618
+ this._enableInteraction = true;
619
+ return this;
620
+ }
621
+ withPrompts() {
622
+ this._enablePrompts = true;
623
+ return this;
624
+ }
625
+ withOrchestration() {
626
+ this._enableOrchestration = true;
627
+ return this;
628
+ }
629
+ // ─── Testing ───
630
+ withTestResponses(responses) {
631
+ this._testResponses = responses;
632
+ return this;
633
+ }
634
+ // ─── Extra Layers ───
635
+ withLayers(layers) {
636
+ this._extraLayers = layers;
637
+ return this;
638
+ }
639
+ // ─── Build ───
640
+ async build() {
641
+ return Effect3.runPromise(this.buildEffect());
642
+ }
643
+ buildEffect() {
644
+ const agentId = `${this._name}-${Date.now()}`;
645
+ const runtime = createRuntime({
646
+ agentId,
647
+ provider: this._provider,
648
+ memoryTier: this._memoryTier,
649
+ maxIterations: this._maxIterations,
650
+ enableGuardrails: this._enableGuardrails,
651
+ enableVerification: this._enableVerification,
652
+ enableCostTracking: this._enableCostTracking,
653
+ enableAudit: this._enableAudit,
654
+ enableReasoning: this._enableReasoning,
655
+ enableTools: this._enableTools,
656
+ enableIdentity: this._enableIdentity,
657
+ enableObservability: this._enableObservability,
658
+ enableInteraction: this._enableInteraction,
659
+ enablePrompts: this._enablePrompts,
660
+ enableOrchestration: this._enableOrchestration,
661
+ testResponses: this._testResponses,
662
+ extraLayers: this._extraLayers
663
+ });
664
+ const hooks = [...this._hooks];
665
+ return Effect3.gen(function* () {
666
+ const engine = yield* ExecutionEngine.pipe(Effect3.provide(runtime));
667
+ for (const hook of hooks) {
668
+ yield* engine.registerHook(hook);
669
+ }
670
+ return new ReactiveAgent(engine, agentId, runtime);
671
+ });
672
+ }
673
+ };
674
+ var ReactiveAgent = class {
675
+ constructor(engine, agentId, runtime) {
676
+ this.engine = engine;
677
+ this.agentId = agentId;
678
+ this.runtime = runtime;
679
+ }
680
+ /**
681
+ * Run a task and return the result (Simple API).
682
+ */
683
+ async run(input) {
684
+ return Effect3.runPromise(this.runEffect(input));
685
+ }
686
+ /**
687
+ * Run a task and return the result (Advanced API — Effect).
688
+ */
689
+ runEffect(input) {
690
+ const taskId = `task-${Date.now()}`;
691
+ const agentId = this.agentId;
692
+ const engine = this.engine;
693
+ const runtime = this.runtime;
694
+ const task = {
695
+ id: taskId,
696
+ agentId,
697
+ type: "query",
698
+ input: { question: input },
699
+ priority: "medium",
700
+ status: "pending",
701
+ metadata: { tags: [] },
702
+ createdAt: /* @__PURE__ */ new Date()
703
+ };
704
+ return engine.execute(task).pipe(
705
+ Effect3.map((result) => ({
706
+ output: String(result.output ?? ""),
707
+ success: Boolean(result.success),
708
+ taskId: String(result.taskId),
709
+ agentId: String(result.agentId),
710
+ metadata: result.metadata
711
+ })),
712
+ Effect3.mapError(
713
+ (e) => new Error(e.message ?? String(e))
714
+ ),
715
+ Effect3.provide(runtime)
716
+ );
717
+ }
718
+ /** Cancel a running task by ID. */
719
+ async cancel(taskId) {
720
+ return Effect3.runPromise(
721
+ this.engine.cancel(taskId).pipe(
722
+ Effect3.mapError((e) => new Error(e.message ?? String(e))),
723
+ Effect3.provide(this.runtime)
724
+ )
725
+ );
726
+ }
727
+ /** Inspect context of a running task (null if not running). */
728
+ async getContext(taskId) {
729
+ return Effect3.runPromise(
730
+ this.engine.getContext(taskId).pipe(
731
+ Effect3.provide(this.runtime)
732
+ )
733
+ );
734
+ }
735
+ };
736
+ export {
737
+ AgentState as AgentStateSchema,
738
+ ExecutionContextSchema,
739
+ ExecutionEngine,
740
+ ExecutionEngineLive,
741
+ ExecutionError,
742
+ GuardrailViolationError,
743
+ HookError,
744
+ HookTiming as HookTimingSchema,
745
+ LifecycleHookRegistry,
746
+ LifecycleHookRegistryLive,
747
+ LifecyclePhase as LifecyclePhaseSchema,
748
+ MaxIterationsError,
749
+ ReactiveAgent,
750
+ ReactiveAgentBuilder,
751
+ ReactiveAgents,
752
+ ReactiveAgentsConfigSchema,
753
+ ToolResultSchema,
754
+ createRuntime,
755
+ defaultReactiveAgentsConfig
756
+ };
757
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/errors.ts","../src/hooks.ts","../src/execution-engine.ts","../src/runtime.ts","../src/builder.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\n// ─── Lifecycle Phase ───\n\nexport const LifecyclePhase = Schema.Literal(\n \"bootstrap\",\n \"guardrail\",\n \"cost-route\",\n \"strategy-select\",\n \"think\",\n \"act\",\n \"observe\",\n \"verify\",\n \"memory-flush\",\n \"cost-track\",\n \"audit\",\n \"complete\",\n);\nexport type LifecyclePhase = typeof LifecyclePhase.Type;\n\n// ─── Hook Timing ───\n\nexport const HookTiming = Schema.Literal(\"before\", \"after\", \"on-error\");\nexport type HookTiming = typeof HookTiming.Type;\n\n// ─── Agent State Machine ───\n\nexport const AgentState = Schema.Literal(\n \"idle\",\n \"bootstrapping\",\n \"running\",\n \"paused\",\n \"verifying\",\n \"flushing\",\n \"completed\",\n \"failed\",\n);\nexport type AgentState = typeof AgentState.Type;\n\n// ─── Execution Context (passed between phases) ───\n\nexport const ExecutionContextSchema = Schema.Struct({\n taskId: Schema.String,\n agentId: Schema.String,\n sessionId: Schema.String,\n phase: LifecyclePhase,\n agentState: AgentState,\n iteration: Schema.Number,\n maxIterations: Schema.Number,\n messages: Schema.Array(Schema.Unknown),\n memoryContext: Schema.optional(Schema.Unknown),\n selectedStrategy: Schema.optional(Schema.String),\n selectedModel: Schema.optional(Schema.Unknown),\n toolResults: Schema.Array(Schema.Unknown),\n cost: Schema.Number,\n startedAt: Schema.DateFromSelf,\n metadata: Schema.Record({ key: Schema.String, value: Schema.Unknown }),\n});\nexport type ExecutionContext = typeof ExecutionContextSchema.Type;\n\n// ─── Tool Result ───\n\nexport const ToolResultSchema = Schema.Struct({\n toolCallId: Schema.String,\n toolName: Schema.String,\n result: Schema.Unknown,\n error: Schema.optional(Schema.String),\n durationMs: Schema.Number,\n});\nexport type ToolResult = typeof ToolResultSchema.Type;\n\n// ─── Lifecycle Hook ───\n\nexport interface LifecycleHook {\n readonly phase: LifecyclePhase;\n readonly timing: HookTiming;\n readonly handler: (\n ctx: ExecutionContext,\n ) => import(\"effect\").Effect.Effect<\n ExecutionContext,\n import(\"./errors.js\").ExecutionError\n >;\n}\n\n// ─── Reactive Agents Config ───\n\nexport const ReactiveAgentsConfigSchema = Schema.Struct({\n maxIterations: Schema.Number,\n defaultModel: Schema.optional(Schema.Unknown),\n memoryTier: Schema.Literal(\"1\", \"2\"),\n enableGuardrails: Schema.Boolean,\n enableVerification: Schema.Boolean,\n enableCostTracking: Schema.Boolean,\n enableAudit: Schema.Boolean,\n agentId: Schema.String,\n});\nexport type ReactiveAgentsConfig = typeof ReactiveAgentsConfigSchema.Type;\n\nexport const defaultReactiveAgentsConfig = (\n agentId: string,\n): ReactiveAgentsConfig => ({\n maxIterations: 10,\n memoryTier: \"1\",\n enableGuardrails: false,\n enableVerification: false,\n enableCostTracking: false,\n enableAudit: false,\n agentId,\n});\n","import { Data } from \"effect\";\n\nexport class ExecutionError extends Data.TaggedError(\"ExecutionError\")<{\n readonly message: string;\n readonly taskId: string;\n readonly phase: string;\n readonly cause?: unknown;\n}> {}\n\nexport class HookError extends Data.TaggedError(\"HookError\")<{\n readonly message: string;\n readonly phase: string;\n readonly timing: string;\n readonly cause?: unknown;\n}> {}\n\nexport class MaxIterationsError extends Data.TaggedError(\"MaxIterationsError\")<{\n readonly message: string;\n readonly taskId: string;\n readonly iterations: number;\n readonly maxIterations: number;\n}> {}\n\nexport class GuardrailViolationError extends Data.TaggedError(\n \"GuardrailViolationError\",\n)<{\n readonly message: string;\n readonly taskId: string;\n readonly violation: string;\n}> {}\n\nexport type RuntimeErrors =\n | ExecutionError\n | HookError\n | MaxIterationsError\n | GuardrailViolationError;\n","import { Effect, Context, Layer, Ref } from \"effect\";\nimport type {\n LifecycleHook,\n LifecyclePhase,\n HookTiming,\n ExecutionContext,\n} from \"./types.js\";\nimport { HookError } from \"./errors.js\";\n\n// ─── Service Tag ───\n\nexport class LifecycleHookRegistry extends Context.Tag(\"LifecycleHookRegistry\")<\n LifecycleHookRegistry,\n {\n /** Register a lifecycle hook. Returns unregister function. */\n readonly register: (\n hook: LifecycleHook,\n ) => Effect.Effect<() => void, never>;\n\n /** Run all hooks for a phase/timing. Returns updated context. */\n readonly run: (\n phase: LifecyclePhase,\n timing: HookTiming,\n ctx: ExecutionContext,\n ) => Effect.Effect<ExecutionContext, HookError>;\n\n /** Get all registered hooks. */\n readonly list: () => Effect.Effect<readonly LifecycleHook[], never>;\n }\n>() {}\n\n// ─── Live Implementation ───\n\nexport const LifecycleHookRegistryLive = Layer.effect(\n LifecycleHookRegistry,\n Effect.gen(function* () {\n const hooks = yield* Ref.make<LifecycleHook[]>([]);\n\n return {\n register: (hook) =>\n Effect.gen(function* () {\n yield* Ref.update(hooks, (hs) => [...hs, hook]);\n return () => {\n Effect.runSync(\n Ref.update(hooks, (hs) => hs.filter((h) => h !== hook)),\n );\n };\n }),\n\n run: (phase, timing, ctx) =>\n Effect.gen(function* () {\n const allHooks = yield* Ref.get(hooks);\n const matching = allHooks.filter(\n (h) => h.phase === phase && h.timing === timing,\n );\n\n let current = ctx;\n for (const hook of matching) {\n current = yield* hook.handler(current).pipe(\n Effect.mapError(\n (cause) =>\n new HookError({\n message: `Hook failed for ${phase}/${timing}: ${cause}`,\n phase,\n timing,\n cause,\n }),\n ),\n );\n }\n return current;\n }),\n\n list: () => Ref.get(hooks),\n };\n }),\n);\n","import { Effect, Context, Layer, Ref } from \"effect\";\nimport type { ExecutionContext, ReactiveAgentsConfig } from \"./types.js\";\nimport {\n ExecutionError,\n MaxIterationsError,\n type RuntimeErrors,\n} from \"./errors.js\";\nimport { LifecycleHookRegistry } from \"./hooks.js\";\nimport type { LifecycleHook } from \"./types.js\";\n\n// Import from other packages (type-only to avoid circular deps at runtime)\nimport type { Task, TaskResult } from \"@reactive-agents/core\";\nimport type { TaskError } from \"@reactive-agents/core\";\n\n// ─── Service Tag ───\n\nexport class ExecutionEngine extends Context.Tag(\"ExecutionEngine\")<\n ExecutionEngine,\n {\n readonly execute: (\n task: Task,\n ) => Effect.Effect<TaskResult, RuntimeErrors | TaskError>;\n\n readonly registerHook: (hook: LifecycleHook) => Effect.Effect<void, never>;\n\n readonly getContext: (\n taskId: string,\n ) => Effect.Effect<ExecutionContext | null, never>;\n\n readonly cancel: (taskId: string) => Effect.Effect<void, ExecutionError>;\n }\n>() {}\n\n// ─── Live Implementation ───\n\nexport const ExecutionEngineLive = (config: ReactiveAgentsConfig) =>\n Layer.effect(\n ExecutionEngine,\n Effect.gen(function* () {\n const hookRegistry = yield* LifecycleHookRegistry;\n\n // Track running contexts (taskId -> ExecutionContext)\n const runningContexts = yield* Ref.make<Map<string, ExecutionContext>>(\n new Map(),\n );\n\n // Track cancelled task IDs\n const cancelledTasks = yield* Ref.make<Set<string>>(new Set());\n\n /**\n * Run a phase: fire before hooks, execute phase body, fire after hooks.\n * On error: fire on-error hooks, then propagate.\n */\n const runPhase = <E>(\n ctx: ExecutionContext,\n phase: ExecutionContext[\"phase\"],\n body: (ctx: ExecutionContext) => Effect.Effect<ExecutionContext, E>,\n ): Effect.Effect<ExecutionContext, E | RuntimeErrors> =>\n Effect.gen(function* () {\n const ctxBefore = { ...ctx, phase };\n\n // Before hooks\n const ctxAfterBefore = yield* hookRegistry\n .run(phase, \"before\", ctxBefore)\n .pipe(Effect.catchAll(() => Effect.succeed(ctxBefore)));\n\n // Check cancellation\n const cancelled = yield* Ref.get(cancelledTasks);\n if (cancelled.has(ctx.taskId)) {\n return yield* Effect.fail(\n new ExecutionError({\n message: `Task ${ctx.taskId} was cancelled`,\n taskId: ctx.taskId,\n phase,\n }),\n );\n }\n\n // Phase body\n const ctxAfterBody = yield* body(ctxAfterBefore).pipe(\n Effect.tapError((e) =>\n hookRegistry\n .run(phase, \"on-error\", {\n ...ctxAfterBefore,\n metadata: { ...ctxAfterBefore.metadata, error: e },\n })\n .pipe(Effect.catchAll(() => Effect.void)),\n ),\n );\n\n // After hooks\n const ctxFinal = yield* hookRegistry\n .run(phase, \"after\", ctxAfterBody)\n .pipe(Effect.catchAll(() => Effect.succeed(ctxAfterBody)));\n\n return ctxFinal;\n });\n\n const execute = (task: Task): Effect.Effect<TaskResult, RuntimeErrors> =>\n (Effect.gen(function* () {\n const now = new Date();\n const sessionId = `session-${Date.now()}`;\n\n // Initialize context\n let ctx: ExecutionContext = {\n taskId: task.id,\n agentId: task.agentId,\n sessionId,\n phase: \"bootstrap\",\n agentState: \"bootstrapping\",\n iteration: 0,\n maxIterations: config.maxIterations,\n messages: [],\n toolResults: [],\n cost: 0,\n startedAt: now,\n metadata: {},\n };\n\n // Register context as running\n yield* Ref.update(runningContexts, (m) =>\n new Map(m).set(task.id, ctx),\n );\n\n // ── Phase 1: BOOTSTRAP ──\n ctx = yield* runPhase(ctx, \"bootstrap\", (c) =>\n Effect.gen(function* () {\n // MemoryService is optional — skip if not provided\n const memoryContext = yield* Effect.serviceOption(\n Context.GenericTag<{\n bootstrap: (id: string) => Effect.Effect<unknown>;\n }>(\"MemoryService\"),\n ).pipe(\n Effect.flatMap((opt) =>\n opt._tag === \"Some\"\n ? opt.value\n .bootstrap(c.agentId)\n .pipe(Effect.map((mc) => mc))\n : Effect.succeed(undefined),\n ),\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n\n return {\n ...c,\n agentState: \"running\" as const,\n memoryContext,\n };\n }),\n );\n\n // ── Phase 2: GUARDRAIL (optional) ──\n if (config.enableGuardrails) {\n ctx = yield* runPhase(ctx, \"guardrail\", (c) =>\n Effect.succeed(c),\n );\n }\n\n // ── Phase 3: COST_ROUTE (optional) ──\n if (config.enableCostTracking) {\n ctx = yield* runPhase(ctx, \"cost-route\", (c) =>\n Effect.succeed({ ...c, selectedModel: config.defaultModel }),\n );\n }\n\n // ── Phase 4: STRATEGY_SELECT ──\n ctx = yield* runPhase(ctx, \"strategy-select\", (c) =>\n Effect.gen(function* () {\n const selectorOpt = yield* Effect.serviceOption(\n Context.GenericTag<{\n select: (\n selCtx: unknown,\n memCtx: unknown,\n ) => Effect.Effect<string>;\n }>(\"StrategySelector\"),\n );\n const strategy =\n selectorOpt._tag === \"Some\"\n ? yield* selectorOpt.value\n .select(\n {\n taskDescription: JSON.stringify(task.input),\n taskType: task.type,\n complexity: 0.5,\n urgency: 0.5,\n },\n c.memoryContext,\n )\n .pipe(Effect.catchAll(() => Effect.succeed(\"reactive\")))\n : \"reactive\";\n return { ...c, selectedStrategy: strategy };\n }),\n );\n\n // ── Phase 5: AGENT_LOOP ──\n const reasoningOpt = yield* Effect.serviceOption(\n Context.GenericTag<{\n execute: (params: {\n taskDescription: string;\n taskType: string;\n memoryContext: string;\n availableTools: readonly string[];\n strategy?: string;\n }) => Effect.Effect<{\n output: unknown;\n status: string;\n metadata: {\n cost: number;\n tokensUsed: number;\n stepsCount: number;\n };\n }>;\n }>(\"ReasoningService\"),\n );\n\n if (reasoningOpt._tag === \"Some\") {\n // ── Full reasoning path ──\n ctx = yield* runPhase(ctx, \"think\", (c) =>\n Effect.gen(function* () {\n const result = yield* reasoningOpt.value.execute({\n taskDescription: JSON.stringify(task.input),\n taskType: task.type,\n memoryContext: String(\n (c.memoryContext as any)?.semanticContext ?? \"\",\n ),\n availableTools: [],\n strategy: c.selectedStrategy ?? \"reactive\",\n });\n return {\n ...c,\n cost: c.cost + (result.metadata.cost ?? 0),\n metadata: {\n ...c.metadata,\n lastResponse: String(result.output ?? \"\"),\n isComplete: result.status === \"completed\",\n reasoningResult: result,\n stepsCount: result.metadata.stepsCount,\n },\n };\n }),\n );\n } else {\n // ── Minimal direct-LLM loop ──\n let isComplete = false;\n\n while (!isComplete && ctx.iteration < ctx.maxIterations) {\n // 5a. THINK\n ctx = yield* runPhase(ctx, \"think\", (c) =>\n (Effect.gen(function* () {\n const llm = yield* Context.GenericTag<{\n complete: (\n req: unknown,\n ) => Effect.Effect<{\n content: string;\n toolCalls?: unknown[];\n stopReason: string;\n }>;\n }>(\"LLMService\");\n\n const systemPrompt = c.memoryContext\n ? `${String((c.memoryContext as any).semanticContext ?? \"\")}\\n\\nComplete the task: ${JSON.stringify(task.input)}`\n : `Complete the task: ${JSON.stringify(task.input)}`;\n\n const response = yield* llm.complete({\n messages: c.messages,\n systemPrompt,\n model: c.selectedModel,\n });\n\n const updatedMessages = [\n ...c.messages,\n { role: \"assistant\", content: response.content },\n ];\n\n const done =\n response.stopReason === \"end_turn\" &&\n !response.toolCalls?.length;\n\n return {\n ...c,\n messages: updatedMessages,\n metadata: {\n ...c.metadata,\n lastResponse: response.content,\n pendingToolCalls: response.toolCalls ?? [],\n isComplete: done,\n },\n };\n }) as unknown as Effect.Effect<ExecutionContext, never>),\n );\n\n // 5b. ACT (if tool calls present)\n const pendingCalls =\n (ctx.metadata.pendingToolCalls as unknown[]) ?? [];\n if (pendingCalls.length > 0) {\n ctx = yield* runPhase(ctx, \"act\", (c) =>\n Effect.gen(function* () {\n const toolResults: unknown[] = pendingCalls.map(\n (call: any) => ({\n toolCallId: call.id ?? \"unknown\",\n toolName: call.name ?? \"unknown\",\n result: `[Tool ${call.name} executed]`,\n durationMs: 0,\n }),\n );\n\n return {\n ...c,\n toolResults: [...c.toolResults, ...toolResults],\n };\n }),\n );\n\n // 5c. OBSERVE\n ctx = yield* runPhase(ctx, \"observe\", (c) =>\n Effect.succeed({\n ...c,\n messages: [\n ...c.messages,\n {\n role: \"user\",\n content: c.toolResults\n .slice(-pendingCalls.length)\n .map(\n (r: any) =>\n `Tool result: ${JSON.stringify(r.result)}`,\n )\n .join(\"\\n\"),\n },\n ],\n iteration: c.iteration + 1,\n }),\n );\n } else {\n // 5d. LOOP_CHECK\n isComplete = Boolean(ctx.metadata.isComplete);\n ctx = { ...ctx, iteration: ctx.iteration + 1 };\n }\n }\n\n // Max iterations reached without completion\n if (!isComplete && ctx.iteration >= ctx.maxIterations) {\n return yield* Effect.fail(\n new MaxIterationsError({\n message: `Task ${task.id} exceeded max iterations (${ctx.maxIterations})`,\n taskId: task.id,\n iterations: ctx.iteration,\n maxIterations: ctx.maxIterations,\n }),\n );\n }\n }\n\n // ── Phase 6: VERIFY (optional) ──\n if (config.enableVerification) {\n ctx = yield* runPhase(ctx, \"verify\", (c) => Effect.succeed(c));\n }\n\n // ── Phase 7: MEMORY_FLUSH ──\n ctx = yield* runPhase(ctx, \"memory-flush\", (c) =>\n Effect.gen(function* () {\n yield* Effect.serviceOption(\n Context.GenericTag<{\n snapshot: (s: unknown) => Effect.Effect<void>;\n }>(\"MemoryService\"),\n ).pipe(\n Effect.flatMap((opt) =>\n opt._tag === \"Some\"\n ? opt.value.snapshot({\n id: c.sessionId,\n agentId: c.agentId,\n messages: c.messages,\n summary: String(c.metadata.lastResponse ?? \"\"),\n keyDecisions: [],\n taskIds: [c.taskId],\n startedAt: c.startedAt,\n endedAt: new Date(),\n totalCost: c.cost,\n totalTokens: 0,\n })\n : Effect.void,\n ),\n Effect.catchAll(() => Effect.void),\n );\n\n return { ...c, agentState: \"flushing\" as const };\n }),\n );\n\n // ── Phase 8: COST_TRACK (optional) ──\n if (config.enableCostTracking) {\n ctx = yield* runPhase(ctx, \"cost-track\", (c) =>\n Effect.succeed(c),\n );\n }\n\n // ── Phase 9: AUDIT (optional) ──\n if (config.enableAudit) {\n ctx = yield* runPhase(ctx, \"audit\", (c) => Effect.succeed(c));\n }\n\n // ── Phase 10: COMPLETE ──\n ctx = yield* runPhase(ctx, \"complete\", (c) =>\n Effect.succeed({ ...c, agentState: \"completed\" as const }),\n );\n\n // Build TaskResult\n const result: TaskResult = {\n taskId: task.id as any,\n agentId: task.agentId,\n output: ctx.metadata.lastResponse ?? null,\n success: true,\n metadata: {\n duration: Date.now() - ctx.startedAt.getTime(),\n cost: ctx.cost,\n tokensUsed: 0,\n strategyUsed: ctx.selectedStrategy,\n stepsCount: ctx.iteration,\n },\n completedAt: new Date(),\n };\n\n return result;\n }) as Effect.Effect<TaskResult, RuntimeErrors, any>).pipe(\n // Always clean up running context\n Effect.ensuring(\n Ref.update(runningContexts, (m) => {\n const next = new Map(m);\n next.delete(task.id);\n return next;\n }),\n ),\n ) as Effect.Effect<TaskResult, RuntimeErrors>;\n\n return {\n execute,\n\n registerHook: (hook) => hookRegistry.register(hook).pipe(Effect.asVoid),\n\n getContext: (taskId) =>\n Ref.get(runningContexts).pipe(\n Effect.map((m) => m.get(taskId) ?? null),\n ),\n\n cancel: (taskId) =>\n Effect.gen(function* () {\n const running = yield* Ref.get(runningContexts);\n if (!running.has(taskId)) {\n return yield* Effect.fail(\n new ExecutionError({\n message: `Task ${taskId} is not running`,\n taskId,\n phase: \"complete\",\n }),\n );\n }\n yield* Ref.update(cancelledTasks, (s) => new Set(s).add(taskId));\n }),\n };\n }),\n );\n","import { Layer } from \"effect\";\nimport { LifecycleHookRegistryLive } from \"./hooks.js\";\nimport { ExecutionEngineLive } from \"./execution-engine.js\";\nimport type { ReactiveAgentsConfig } from \"./types.js\";\nimport { defaultReactiveAgentsConfig } from \"./types.js\";\nimport { CoreServicesLive, EventBusLive } from \"@reactive-agents/core\";\nimport { createLLMProviderLayer } from \"@reactive-agents/llm-provider\";\nimport { createMemoryLayer } from \"@reactive-agents/memory\";\n\n// Optional package imports\nimport { createGuardrailsLayer } from \"@reactive-agents/guardrails\";\nimport { createVerificationLayer } from \"@reactive-agents/verification\";\nimport { createCostLayer } from \"@reactive-agents/cost\";\nimport { createReasoningLayer } from \"@reactive-agents/reasoning\";\nimport { createToolsLayer } from \"@reactive-agents/tools\";\nimport { createIdentityLayer } from \"@reactive-agents/identity\";\nimport { createObservabilityLayer } from \"@reactive-agents/observability\";\nimport { createInteractionLayer } from \"@reactive-agents/interaction\";\nimport { createPromptLayer } from \"@reactive-agents/prompts\";\nimport { createOrchestrationLayer } from \"@reactive-agents/orchestration\";\n\n// ─── Runtime Options ───\n\nexport interface RuntimeOptions {\n agentId: string;\n provider?: \"anthropic\" | \"openai\" | \"ollama\" | \"gemini\" | \"test\";\n memoryTier?: \"1\" | \"2\";\n maxIterations?: number;\n testResponses?: Record<string, string>;\n extraLayers?: Layer.Layer<any, any>;\n\n // Optional features\n enableGuardrails?: boolean;\n enableVerification?: boolean;\n enableCostTracking?: boolean;\n enableReasoning?: boolean;\n enableTools?: boolean;\n enableIdentity?: boolean;\n enableObservability?: boolean;\n enableInteraction?: boolean;\n enablePrompts?: boolean;\n enableOrchestration?: boolean;\n enableAudit?: boolean;\n}\n\n/**\n * Create the full reactive-agents runtime layer.\n *\n * Composes Core + LLM + Memory + ExecutionEngine as the base,\n * then merges optional layers based on the enabled flags.\n *\n * Usage:\n * const Runtime = createRuntime({\n * agentId: \"my-agent\",\n * provider: \"anthropic\",\n * enableReasoning: true,\n * enableGuardrails: true,\n * });\n */\nexport const createRuntime = (options: RuntimeOptions) => {\n const config: ReactiveAgentsConfig = {\n ...defaultReactiveAgentsConfig(options.agentId),\n memoryTier: options.memoryTier ?? \"1\",\n maxIterations: options.maxIterations ?? 10,\n enableGuardrails: options.enableGuardrails ?? false,\n enableVerification: options.enableVerification ?? false,\n enableCostTracking: options.enableCostTracking ?? false,\n enableAudit: options.enableAudit ?? false,\n };\n\n // ── Required layers ──\n // EventBusLive is exposed separately so optional layers that need it can be provided\n const eventBusLayer = EventBusLive;\n const coreLayer = CoreServicesLive;\n const llmLayer = createLLMProviderLayer(\n options.provider ?? \"test\",\n options.testResponses,\n );\n const memoryLayer = createMemoryLayer(config.memoryTier, {\n agentId: options.agentId,\n });\n const hookLayer = LifecycleHookRegistryLive;\n const engineLayer = ExecutionEngineLive(config).pipe(Layer.provide(hookLayer));\n\n let runtime = Layer.mergeAll(\n coreLayer,\n eventBusLayer,\n llmLayer,\n memoryLayer,\n hookLayer,\n engineLayer,\n );\n\n // ── Optional layers ──\n\n if (options.enableGuardrails) {\n runtime = Layer.merge(runtime, createGuardrailsLayer()) as any;\n }\n\n if (options.enableVerification) {\n runtime = Layer.merge(runtime, createVerificationLayer()) as any;\n }\n\n if (options.enableCostTracking) {\n runtime = Layer.merge(runtime, createCostLayer()) as any;\n }\n\n if (options.enableReasoning) {\n // ReasoningService requires LLMService\n const reasoningLayer = createReasoningLayer().pipe(Layer.provide(llmLayer));\n runtime = Layer.merge(runtime, reasoningLayer) as any;\n }\n\n if (options.enableTools) {\n // ToolService requires EventBus\n const toolsLayer = createToolsLayer().pipe(Layer.provide(eventBusLayer));\n runtime = Layer.merge(runtime, toolsLayer) as any;\n }\n\n if (options.enableIdentity) {\n runtime = Layer.merge(runtime, createIdentityLayer()) as any;\n }\n\n if (options.enableObservability) {\n runtime = Layer.merge(runtime, createObservabilityLayer()) as any;\n }\n\n if (options.enableInteraction) {\n // InteractionManager requires EventBus\n const interactionLayer = createInteractionLayer().pipe(\n Layer.provide(eventBusLayer),\n );\n runtime = Layer.merge(runtime, interactionLayer) as any;\n }\n\n if (options.enablePrompts) {\n runtime = Layer.merge(runtime, createPromptLayer()) as any;\n }\n\n if (options.enableOrchestration) {\n runtime = Layer.merge(runtime, createOrchestrationLayer()) as any;\n }\n\n if (options.extraLayers) {\n runtime = Layer.merge(runtime, options.extraLayers) as any;\n }\n\n return runtime;\n};\n","import { Effect, Layer } from \"effect\";\nimport { createRuntime } from \"./runtime.js\";\nimport { ExecutionEngine } from \"./execution-engine.js\";\nimport type { LifecycleHook } from \"./types.js\";\n\n// ─── Result Types ────────────────────────────────────────────────────────────\n\nexport interface AgentResultMetadata {\n readonly duration: number;\n readonly cost: number;\n readonly tokensUsed: number;\n readonly strategyUsed?: string;\n readonly stepsCount: number;\n}\n\nexport interface AgentResult {\n readonly output: string;\n readonly success: boolean;\n readonly taskId: string;\n readonly agentId: string;\n readonly metadata: AgentResultMetadata;\n}\n\n// ─── ReactiveAgents Namespace ────────────────────────────────────────────────\n\nexport const ReactiveAgents = {\n /** Create a new builder. All configuration is optional except `.withModel()`. */\n create: (): ReactiveAgentBuilder => new ReactiveAgentBuilder(),\n};\n\n// ─── ReactiveAgentBuilder ────────────────────────────────────────────────────\n\nexport class ReactiveAgentBuilder {\n private _name: string = \"agent\";\n private _provider: \"anthropic\" | \"openai\" | \"ollama\" | \"gemini\" | \"test\" = \"test\";\n private _model?: string;\n private _memoryTier: \"1\" | \"2\" = \"1\";\n private _hooks: LifecycleHook[] = [];\n private _maxIterations: number = 10;\n private _enableGuardrails: boolean = false;\n private _enableVerification: boolean = false;\n private _enableCostTracking: boolean = false;\n private _enableAudit: boolean = false;\n private _enableReasoning: boolean = false;\n private _enableTools: boolean = false;\n private _enableIdentity: boolean = false;\n private _enableObservability: boolean = false;\n private _enableInteraction: boolean = false;\n private _enablePrompts: boolean = false;\n private _enableOrchestration: boolean = false;\n private _testResponses?: Record<string, string>;\n private _extraLayers?: Layer.Layer<any, any>;\n\n // ─── Identity ───\n\n withName(name: string): this {\n this._name = name;\n return this;\n }\n\n // ─── Model & Provider ───\n\n withModel(model: string): this {\n this._model = model;\n return this;\n }\n\n withProvider(\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"gemini\" | \"test\",\n ): this {\n this._provider = provider;\n return this;\n }\n\n // ─── Memory ───\n\n withMemory(tier: \"1\" | \"2\"): this {\n this._memoryTier = tier;\n return this;\n }\n\n // ─── Execution ───\n\n withMaxIterations(n: number): this {\n this._maxIterations = n;\n return this;\n }\n\n // ─── Lifecycle Hooks ───\n\n withHook(hook: LifecycleHook): this {\n this._hooks.push(hook);\n return this;\n }\n\n // ─── Optional Features ───\n\n withGuardrails(): this {\n this._enableGuardrails = true;\n return this;\n }\n\n withVerification(): this {\n this._enableVerification = true;\n return this;\n }\n\n withCostTracking(): this {\n this._enableCostTracking = true;\n return this;\n }\n\n withAudit(): this {\n this._enableAudit = true;\n return this;\n }\n\n withReasoning(): this {\n this._enableReasoning = true;\n return this;\n }\n\n withTools(): this {\n this._enableTools = true;\n return this;\n }\n\n withIdentity(): this {\n this._enableIdentity = true;\n return this;\n }\n\n withObservability(): this {\n this._enableObservability = true;\n return this;\n }\n\n withInteraction(): this {\n this._enableInteraction = true;\n return this;\n }\n\n withPrompts(): this {\n this._enablePrompts = true;\n return this;\n }\n\n withOrchestration(): this {\n this._enableOrchestration = true;\n return this;\n }\n\n // ─── Testing ───\n\n withTestResponses(responses: Record<string, string>): this {\n this._testResponses = responses;\n return this;\n }\n\n // ─── Extra Layers ───\n\n withLayers(layers: Layer.Layer<any, any>): this {\n this._extraLayers = layers;\n return this;\n }\n\n // ─── Build ───\n\n async build(): Promise<ReactiveAgent> {\n return Effect.runPromise(this.buildEffect());\n }\n\n buildEffect(): Effect.Effect<ReactiveAgent, Error> {\n const agentId = `${this._name}-${Date.now()}`;\n\n const runtime = createRuntime({\n agentId,\n provider: this._provider,\n memoryTier: this._memoryTier,\n maxIterations: this._maxIterations,\n enableGuardrails: this._enableGuardrails,\n enableVerification: this._enableVerification,\n enableCostTracking: this._enableCostTracking,\n enableAudit: this._enableAudit,\n enableReasoning: this._enableReasoning,\n enableTools: this._enableTools,\n enableIdentity: this._enableIdentity,\n enableObservability: this._enableObservability,\n enableInteraction: this._enableInteraction,\n enablePrompts: this._enablePrompts,\n enableOrchestration: this._enableOrchestration,\n testResponses: this._testResponses,\n extraLayers: this._extraLayers,\n });\n\n const hooks = [...this._hooks];\n\n return Effect.gen(function* () {\n const engine = yield* ExecutionEngine.pipe(Effect.provide(runtime));\n\n for (const hook of hooks) {\n yield* engine.registerHook(hook);\n }\n\n return new ReactiveAgent(engine, agentId, runtime);\n });\n }\n}\n\n// ─── ReactiveAgent Facade ────────────────────────────────────────────────────\n\nexport class ReactiveAgent {\n constructor(\n private readonly engine: {\n execute: (task: any) => Effect.Effect<any, any>;\n cancel: (taskId: string) => Effect.Effect<void, any>;\n getContext: (taskId: string) => Effect.Effect<any, never>;\n },\n readonly agentId: string,\n private readonly runtime: Layer.Layer<any, any>,\n ) {}\n\n /**\n * Run a task and return the result (Simple API).\n */\n async run(input: string): Promise<AgentResult> {\n return Effect.runPromise(this.runEffect(input));\n }\n\n /**\n * Run a task and return the result (Advanced API — Effect).\n */\n runEffect(input: string): Effect.Effect<AgentResult, Error> {\n const taskId = `task-${Date.now()}`;\n const agentId = this.agentId;\n const engine = this.engine;\n const runtime = this.runtime;\n\n const task = {\n id: taskId,\n agentId,\n type: \"query\" as const,\n input: { question: input },\n priority: \"medium\" as const,\n status: \"pending\" as const,\n metadata: { tags: [] },\n createdAt: new Date(),\n };\n\n return engine.execute(task).pipe(\n Effect.map((result: any) => ({\n output: String(result.output ?? \"\"),\n success: Boolean(result.success),\n taskId: String(result.taskId),\n agentId: String(result.agentId),\n metadata: result.metadata as AgentResultMetadata,\n })),\n Effect.mapError(\n (e: any) => new Error(e.message ?? String(e)),\n ),\n Effect.provide(runtime as unknown as Layer.Layer<never>),\n ) as Effect.Effect<AgentResult, Error>;\n }\n\n /** Cancel a running task by ID. */\n async cancel(taskId: string): Promise<void> {\n return Effect.runPromise(\n this.engine.cancel(taskId).pipe(\n Effect.mapError((e: any) => new Error(e.message ?? String(e))),\n Effect.provide(this.runtime as unknown as Layer.Layer<never>),\n ) as Effect.Effect<void>,\n );\n }\n\n /** Inspect context of a running task (null if not running). */\n async getContext(taskId: string): Promise<unknown> {\n return Effect.runPromise(\n this.engine.getContext(taskId).pipe(\n Effect.provide(this.runtime as unknown as Layer.Layer<never>),\n ) as Effect.Effect<unknown>,\n );\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AAIhB,IAAM,iBAAiB,OAAO;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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QACzBA,QAAO,SAAS,CAAC,MAAW,IAAI,MAAM,EAAE,WAAW,OAAO,CAAC,CAAC,CAAC;AAAA,QAC7DA,QAAO,QAAQ,KAAK,OAAwC;AAAA,MAC9D;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAAW,QAAkC;AACjD,WAAOA,QAAO;AAAA,MACZ,KAAK,OAAO,WAAW,MAAM,EAAE;AAAA,QAC7BA,QAAO,QAAQ,KAAK,OAAwC;AAAA,MAC9D;AAAA,IACF;AAAA,EACF;AACF;","names":["Effect","Context","Layer","Ref","Context","Layer","Effect","Ref","result","Layer","Layer","Effect","Effect"]}
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@reactive-agents/runtime",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsup --config ../../tsup.config.base.ts",
9
+ "typecheck": "tsc --noEmit",
10
+ "test": "bun test",
11
+ "test:watch": "bun test --watch"
12
+ },
13
+ "dependencies": {
14
+ "effect": "^3.10.0",
15
+ "@reactive-agents/core": "0.1.0",
16
+ "@reactive-agents/llm-provider": "0.1.0",
17
+ "@reactive-agents/memory": "0.1.0",
18
+ "@reactive-agents/guardrails": "0.1.0",
19
+ "@reactive-agents/verification": "0.1.0",
20
+ "@reactive-agents/cost": "0.1.0",
21
+ "@reactive-agents/reasoning": "0.1.0",
22
+ "@reactive-agents/tools": "0.1.0",
23
+ "@reactive-agents/identity": "0.1.0",
24
+ "@reactive-agents/observability": "0.1.0",
25
+ "@reactive-agents/interaction": "0.1.0",
26
+ "@reactive-agents/prompts": "0.1.0",
27
+ "@reactive-agents/orchestration": "0.1.0"
28
+ },
29
+ "devDependencies": {
30
+ "typescript": "^5.7.0",
31
+ "bun-types": "latest"
32
+ },
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/tylerjrbuell/reactive-agents-ts.git",
37
+ "directory": "packages/runtime"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "exports": {
48
+ ".": {
49
+ "types": "./dist/index.d.ts",
50
+ "import": "./dist/index.js",
51
+ "default": "./dist/index.js"
52
+ }
53
+ },
54
+ "description": "Runtime for Reactive Agents — ExecutionEngine, ReactiveAgentBuilder, and createRuntime",
55
+ "homepage": "https://tylerjrbuell.github.io/reactive-agents-ts/",
56
+ "bugs": {
57
+ "url": "https://github.com/tylerjrbuell/reactive-agents-ts/issues"
58
+ }
59
+ }