@kalphq/core 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/engine/execution-log.ts","../src/engine/primitives/ai.ts","../src/engine/primitives/storage.ts","../src/engine/primitives/actions.ts","../src/engine/primitives/mcp.ts","../src/engine/primitives/date.ts","../src/engine/primitives/math.ts","../src/engine/primitives/agent-meta.ts","../src/engine/context-builder.ts","../src/engine/reactor.ts"],"sourcesContent":["/**\n * Structured execution log for the Kalp v2 Orchestration Reactor.\n *\n * The execution log is the system's source of truth. Every runtime operation\n * emits a structured event that is persisted via the {@link PersistenceAdapter}.\n * This enables replay, time-travel debugging, billing, and observability.\n *\n * Rule: **If it doesn't emit an event, it doesn't exist.**\n *\n * @module\n */\n\nimport type { EventStore } from \"@/adapters/interfaces\";\nimport type { ExecutionEvent } from \"@/engine/types\";\n\n/**\n * Append-only structured event log backed by an {@link EventStore}.\n *\n * All reactor operations flow through this class. It provides a unified\n * interface for emitting and loading events regardless of the underlying\n * storage mechanism.\n */\nexport class ExecutionLog {\n /** In-memory buffer of events emitted during the current processing cycle. */\n private buffer: ExecutionEvent[] = [];\n\n /**\n * Creates a new execution log backed by the given event store.\n *\n * @param eventStore - The store used to persist and load events.\n */\n constructor(private eventStore: EventStore) {}\n\n /**\n * Emits a structured execution event.\n *\n * The event is immediately persisted via the adapter and buffered in memory\n * for the current processing cycle.\n *\n * @param event - The execution event to emit.\n */\n async emit(event: ExecutionEvent): Promise<void> {\n this.buffer.push(event);\n await this.eventStore.append(event);\n }\n\n /**\n * Loads all previously persisted events from the adapter.\n *\n * Used for replay, rehydration, and debugging.\n *\n * @returns An ordered array of all persisted execution events.\n */\n async load(): Promise<ExecutionEvent[]> {\n return this.eventStore.loadAll();\n }\n\n /**\n * Returns events emitted during the current processing cycle (in-memory only).\n *\n * @returns The in-memory event buffer.\n */\n getBuffer(): ReadonlyArray<ExecutionEvent> {\n return this.buffer;\n }\n\n /**\n * Clears the in-memory buffer. Called between processing cycles.\n */\n clearBuffer(): void {\n this.buffer = [];\n }\n}\n","/**\n * AI primitive — intercepted LLM calls with event emission.\n *\n * Every generate/stream/classify call is logged to the execution log.\n * The actual LLM provider call is delegated to the injected implementation.\n *\n * @module\n */\n\nimport type { KalpAI } from \"@kalphq/sdk\";\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/**\n * A concrete AI provider implementation that performs the actual LLM calls.\n * This is injected by the host adapter (e.g. Cloudflare AI, OpenAI fetch, etc.).\n */\nexport type AIProvider = KalpAI;\n\n/**\n * Creates an intercepted AI primitive that wraps every call with event emission.\n *\n * The returned object matches the SDK's {@link KalpAI} interface exactly.\n * Internally, each method:\n * 1. Emits a `primitive.invoked` event before calling the provider.\n * 2. Calls the actual provider implementation.\n * 3. Emits a `primitive.invoked` event with the result.\n *\n * @param provider - The concrete AI provider implementation.\n * @param log - The execution log for event emission.\n * @param execCtx - Optional execution context for event identity.\n * @returns An intercepted {@link KalpAI} matching the SDK interface.\n */\nexport function createAIPrimitive(\n provider: AIProvider,\n log: ExecutionLog,\n execCtx?: ExecutionContext,\n): KalpAI {\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n return {\n async generate(params) {\n const result = await provider.generate(params);\n await log.emit({\n type: \"primitive.invoked\",\n name: \"ai.generate\",\n params: { model: params.model, prompt: params.prompt },\n result,\n ...ids,\n timestamp: Date.now(),\n });\n return result;\n },\n\n stream(params) {\n // Stream is special — we log the invocation but return the iterable.\n // Individual chunks are NOT logged (too noisy). The caller consumes them.\n void log.emit({\n type: \"primitive.invoked\",\n name: \"ai.stream\",\n params: { model: params.model, prompt: params.prompt },\n result: \"[stream]\",\n ...ids,\n timestamp: Date.now(),\n });\n return provider.stream(params);\n },\n\n async classify(params) {\n const result = await provider.classify(params);\n await log.emit({\n type: \"primitive.invoked\",\n name: \"ai.classify\",\n params: { input: params.input, labels: params.labels },\n result,\n ...ids,\n timestamp: Date.now(),\n });\n return result;\n },\n };\n}\n","/**\n * Storage primitive — intercepted key-value state with event emission.\n *\n * Every read/write is logged to the execution log. The actual storage\n * is delegated to the {@link StateStore}.\n *\n * @module\n */\n\nimport type { StoragePrimitive } from \"@kalphq/sdk\";\nimport type { StateStore } from \"@/adapters/interfaces\";\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/**\n * Creates an intercepted storage primitive that emits events for every operation.\n *\n * @param stateStore - The state sub-store for KV operations.\n * @param log - The execution log for event emission.\n * @param execCtx - The current execution context (identity for events).\n * @returns A {@link StoragePrimitive} matching the SDK's storage API.\n */\nexport function createStoragePrimitive(\n stateStore: StateStore,\n log: ExecutionLog,\n execCtx?: ExecutionContext,\n): StoragePrimitive {\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n return {\n async get<T = unknown>(key: string): Promise<T | null> {\n const value = (await stateStore.get(key)) as T | null;\n await log.emit({\n type: \"state.read\",\n key,\n value,\n ...ids,\n timestamp: Date.now(),\n });\n return value;\n },\n\n async put(key: string, value: unknown): Promise<void> {\n await stateStore.set(key, value);\n await log.emit({\n type: \"state.write\",\n key,\n value,\n ...ids,\n timestamp: Date.now(),\n });\n },\n\n async delete(key: string): Promise<void> {\n await stateStore.delete(key);\n await log.emit({\n type: \"state.write\",\n key,\n value: undefined,\n ...ids,\n timestamp: Date.now(),\n });\n },\n\n async increment(key: string, amount: number = 1): Promise<number> {\n const newValue = await stateStore.increment(key, amount);\n await log.emit({\n type: \"state.write\",\n key,\n value: newValue,\n ...ids,\n timestamp: Date.now(),\n });\n return newValue;\n },\n\n async transaction<T>(\n callback: (tx: any) => Promise<T>,\n _options?: any,\n ): Promise<T> {\n // Basic transaction wrapping (without full interceptor for tx context yet)\n return stateStore.transaction(async (tx) => {\n return callback(tx as any);\n });\n },\n };\n}\n","/**\n * Actions primitive — intercepted orchestration intents with event emission.\n *\n * This is the core of the event-sourced runtime model. Every action is an\n * **intent**, not a direct execution. The handler emits the intent, and the\n * reactor resolves it.\n *\n * - `actions.run(step, input)` → emits `action.run`, suspends, reactor enqueues handler, resolves with result\n * - `actions.wait(duration)` → emits `action.wait`, schedules alarm, terminates execution\n * - `actions.loop(body)` → emits `action.loop.start`, reactor drives iterations\n * - `actions.fetch(url, init)` → emits `action.fetch`, delegates to http primitive\n *\n * @module\n */\n\nimport type {\n KalpActions,\n ExecutableNode,\n InputOf,\n OutputOf,\n WakeReason,\n AskOptions,\n EmitOptions,\n AgentContract,\n} from \"@kalphq/sdk\";\nimport { z } from \"@kalphq/sdk\";\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { SchedulerAdapter } from \"@/adapters/interfaces\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/** Callback to dispatch a handler task into the reactor queue. */\nexport type DispatchAction = (\n moduleRef: string,\n input: unknown,\n) => Promise<unknown>;\n\n/**\n * Parses a human-readable duration string (e.g. \"5m\", \"1h\", \"30s\") to milliseconds.\n *\n * @param duration - A string like \"5m\", \"1h\", \"30s\", \"2d\", or a raw number of ms.\n * @returns Duration in milliseconds.\n */\nfunction parseDuration(duration: string | number): number {\n if (typeof duration === \"number\") return duration;\n\n const match = duration.match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/i);\n if (!match) {\n throw new Error(\n `Invalid duration format: \"${duration}\". Expected e.g. \"5m\", \"30s\", \"1h\".`,\n );\n }\n\n const value = parseFloat(match[1]!);\n const unit = match[2]!.toLowerCase();\n\n const multipliers: Record<string, number> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n };\n\n return value * (multipliers[unit] ?? 1);\n}\n\n/**\n * Creates the intercepted actions primitive for handler context.\n *\n * Each method emits structured events and interacts with the reactor\n * via the `dispatch` callback (for run) and the `scheduler` adapter\n * (for wait).\n *\n * @param log - The execution log for event emission.\n * @param scheduler - The scheduler adapter for deferred execution.\n * @param dispatch - Callback to enqueue a handler task in the reactor.\n * @param execCtx - Optional execution context for event identity.\n * @returns A {@link KalpActions} matching the SDK interface exactly.\n */\nexport function createActionsPrimitive(\n log: ExecutionLog,\n scheduler: SchedulerAdapter,\n dispatch: DispatchAction,\n execCtx?: ExecutionContext,\n): KalpActions {\n let loopCounter = 0;\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n return {\n /**\n * Emits an `action.run` intent and suspends until the reactor resolves it.\n * The handler receives a Promise that resolves with the step/tool result.\n */\n async run<T extends ExecutableNode>(\n node: T,\n ...args: InputOf<T> extends never ? [] : [input: InputOf<T>]\n ): Promise<OutputOf<T>> {\n const target = `${node.kind}s.${node.id}`;\n const input = args[0];\n\n await log.emit({\n type: \"action.run\",\n target,\n input,\n ...ids,\n timestamp: Date.now(),\n });\n\n const result = await dispatch(target, input);\n\n await log.emit({\n type: \"action.run.completed\",\n target,\n result,\n ...ids,\n timestamp: Date.now(),\n });\n\n return result as OutputOf<T>;\n },\n\n /**\n * Emits an `action.wait` event, schedules an alarm, and returns.\n * The host adapter is responsible for re-entering the reactor when the alarm fires.\n */\n async wait(duration: string | number): Promise<WakeReason> {\n const ms = parseDuration(duration);\n\n await log.emit({\n type: \"action.wait\",\n duration,\n ...ids,\n timestamp: Date.now(),\n });\n\n await scheduler.schedule(Date.now() + ms);\n\n // In the event-sourced model, wait terminates the current execution.\n // The alarm fires and re-enters the reactor via handleEvent(\"onTick\").\n // The WakeReason is resolved by the reactor on rehydration.\n return { type: \"timeout\" };\n },\n\n /**\n * Runtime-driven loop. Each iteration is a separate event, enabling\n * persistence, rehydration, cut, pause, and per-iteration billing.\n */\n loop(body: () => Promise<void>): void {\n const loopId = `loop_${++loopCounter}_${Date.now()}`;\n\n // Fire-and-forget — the reactor drives the loop asynchronously.\n // The handler does NOT await the loop; it registers the intent.\n void (async () => {\n await log.emit({\n type: \"action.loop.start\",\n loopId,\n ...ids,\n timestamp: Date.now(),\n });\n\n let iteration = 0;\n\n while (true) {\n await log.emit({\n type: \"action.loop.iteration\",\n loopId,\n iteration,\n ...ids,\n timestamp: Date.now(),\n });\n\n try {\n await body();\n } catch (err) {\n await log.emit({\n type: \"action.loop.end\",\n loopId,\n reason: err instanceof Error ? err.message : \"error\",\n ...ids,\n timestamp: Date.now(),\n });\n break;\n }\n\n iteration++;\n }\n })();\n },\n\n /**\n * Intercepted fetch — logs the request and delegates to globalThis.fetch.\n */\n async fetch(\n input: string | URL | Request,\n init?: RequestInit,\n ): Promise<Response> {\n const url =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n const method =\n init?.method ?? (input instanceof Request ? input.method : \"GET\");\n\n const start = Date.now();\n const response = await globalThis.fetch(input, init);\n const durationMs = Date.now() - start;\n\n await log.emit({\n type: \"action.fetch\",\n url,\n method,\n status: response.status,\n durationMs,\n ...ids,\n timestamp: Date.now(),\n });\n\n return response;\n },\n\n async ask<T extends z.ZodTypeAny>(\n _prompt: string,\n _schema: T,\n _options?: AskOptions,\n ): Promise<z.infer<T>> {\n await log.emit({\n type: \"action.ask\",\n ...ids,\n timestamp: Date.now(),\n });\n return { text: \"stub response\" } as z.infer<T>;\n },\n\n async requestApproval(\n _reason: string,\n _options?: AskOptions,\n ): Promise<boolean> {\n await log.emit({\n type: \"action.approval\",\n ...ids,\n timestamp: Date.now(),\n });\n return true;\n },\n\n emit(eventName: string, payload: unknown, _options?: EmitOptions): void {\n void log.emit({\n type: \"action.emit\",\n event: eventName,\n payload,\n ...ids,\n timestamp: Date.now(),\n });\n },\n\n async callAgent<TContract extends AgentContract<any, any>>(\n contract: TContract,\n input: z.infer<TContract[\"inputSchema\"]>,\n ): Promise<z.infer<TContract[\"outputSchema\"]>> {\n await log.emit({\n type: \"action.call\",\n contract: contract.agentId,\n input,\n ...ids,\n timestamp: Date.now(),\n });\n return {} as z.infer<TContract[\"outputSchema\"]>;\n },\n\n /**\n * Pauses the agent until an external event occurs.\n * Emits an action.wait event with duration and schedules a timeout alarm if specified.\n */\n async waitForEvent(\n eventName: string,\n timeout?: string | number,\n ): Promise<WakeReason> {\n const duration = timeout ? parseDuration(timeout) : 0;\n\n await log.emit({\n type: \"action.wait\",\n duration,\n ...ids,\n timestamp: Date.now(),\n });\n\n if (timeout) {\n await scheduler.schedule(Date.now() + duration);\n }\n\n // The reactor will resolve this when the event arrives or timeout fires\n return { type: \"event\", eventName, payload: undefined };\n },\n\n /**\n * Pauses the agent until a specific date/time.\n * Emits an action.wait event with the duration and schedules an alarm for the target time.\n */\n async waitUntil(date: Date | string | number): Promise<WakeReason> {\n const targetTime =\n typeof date === \"number\"\n ? date\n : typeof date === \"string\"\n ? new Date(date).getTime()\n : date.getTime();\n\n const now = Date.now();\n const duration = Math.max(0, targetTime - now);\n\n await log.emit({\n type: \"action.wait\",\n duration,\n ...ids,\n timestamp: Date.now(),\n });\n\n await scheduler.schedule(targetTime);\n\n return {\n type: \"scheduled_time_reached\",\n scheduledAt: new Date(targetTime).toISOString(),\n };\n },\n\n /**\n * Schedules a node for future non-blocking execution.\n * Emits an action.schedule event and schedules the execution via the scheduler.\n */\n async schedule<T extends ExecutableNode>(\n node: T,\n date: Date | string | number,\n ...args: InputOf<T> extends never ? [] : [input: InputOf<T>]\n ): Promise<{ scheduleId: string }> {\n const targetTime =\n typeof date === \"number\"\n ? date\n : typeof date === \"string\"\n ? new Date(date).getTime()\n : date.getTime();\n\n const target = `${node.kind}s.${node.id}`;\n const input = args[0];\n const scheduleId = `schedule_${target}_${targetTime}`;\n\n await log.emit({\n type: \"action.schedule\",\n at: targetTime,\n payload: { scheduleId, target, input },\n ...ids,\n timestamp: Date.now(),\n });\n\n await scheduler.schedule(targetTime);\n\n return { scheduleId };\n },\n };\n}\n","/**\n * Model Context Protocol (MCP) primitive.\n *\n * Provides access to MCP servers configured in the project.\n *\n * @module\n */\n\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { KalpMcp } from \"@kalphq/sdk\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/**\n * Creates an MCP primitive that emits events to the execution log.\n *\n * @param log - The execution log for event emission.\n * @param execCtx - Optional execution context for event identity.\n * @returns A {@link KalpMcp} instance.\n */\nexport function createMcpPrimitive(\n log: ExecutionLog,\n execCtx?: ExecutionContext,\n): KalpMcp {\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n // Return a Proxy that dynamically handles MCP server calls\n return new Proxy({} as KalpMcp, {\n get(_target, serverName: string) {\n // Return a Proxy for the server's tools\n return new Proxy(\n {},\n {\n get(_target, toolName: string) {\n // Return the tool function\n return async (input: unknown): Promise<unknown> => {\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"mcp.\" + serverName + \".\" + toolName,\n params: input,\n result: undefined,\n ...ids,\n timestamp,\n });\n\n // TODO: Implement actual MCP server connection\n // For now, return a stub response\n return { error: \"MCP not implemented in core yet\" };\n };\n },\n },\n );\n },\n });\n}\n","/**\n * Deterministic date/time primitive.\n *\n * Provides deterministic time operations using the event timestamp.\n *\n * @module\n */\n\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { KalpDate, TimezoneFormatter } from \"@kalphq/sdk\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/**\n * Creates a date primitive that emits events to the execution log.\n *\n * @param log - The execution log for event emission.\n * @param execCtx - Optional execution context for event identity.\n * @returns A {@link KalpDate} instance.\n */\nexport function createDatePrimitive(\n log: ExecutionLog,\n execCtx?: ExecutionContext,\n): KalpDate {\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n // Use current time as base (in production, use event timestamp)\n const baseTime = Date.now();\n\n return {\n /**\n * Get the current time (event timestamp).\n */\n now(): number {\n return baseTime;\n },\n\n /**\n * Format the current time as ISO string.\n */\n toISOString(): string {\n return new Date(baseTime).toISOString();\n },\n\n /**\n * Check if the original event occurred after the given date.\n *\n * @param isoString - ISO 8601 date string to compare against.\n */\n isAfter(isoString: string): boolean {\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"date.isAfter\",\n params: isoString,\n result: undefined,\n ...ids,\n timestamp,\n });\n return baseTime > new Date(isoString).getTime();\n },\n\n /**\n * Add a duration to the current time.\n *\n * @param duration - Duration string (e.g., \"1h\", \"30m\", \"24h\") or milliseconds.\n */\n add(duration: string | number): number {\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"date.add\",\n params: duration,\n result: undefined,\n ...ids,\n timestamp,\n });\n\n // If duration is a number, treat as milliseconds\n if (typeof duration === \"number\") {\n return baseTime + duration;\n }\n\n // Parse duration string\n const match = duration.match(/^(\\d+)([smhd])$/);\n if (!match) {\n throw new Error(`Invalid duration format: ${duration}`);\n }\n\n const value = parseInt(match[1]!, 10);\n const unit = match[2]!;\n if (!unit) {\n throw new Error(`Invalid duration format: ${duration}`);\n }\n\n const multipliers: Record<string, number> = {\n s: 1000,\n m: 60000,\n h: 3600000,\n d: 86400000,\n };\n\n const multiplier = multipliers[unit];\n if (!multiplier) {\n throw new Error(`Invalid duration unit: ${unit}`);\n }\n\n return baseTime + value * multiplier;\n },\n\n /**\n * Convert the event timestamp to a specific timezone.\n *\n * @param tz - IANA timezone identifier.\n * @returns TimezoneFormatter for the converted time.\n */\n timezone(tz: string): TimezoneFormatter {\n const formatter: TimezoneFormatter = {\n format(format: string): string {\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"date.timezone.format\",\n params: { tz, format },\n result: undefined,\n ...ids,\n timestamp,\n });\n\n // Simple formatting - in production use a proper date library\n const date = new Date(baseTime);\n return date.toISOString().replace(\"T\", \" \").slice(0, 19);\n },\n toISOString(): string {\n return new Date(baseTime).toISOString();\n },\n };\n return formatter;\n },\n };\n}\n","/**\n * Deterministic math primitive.\n *\n * Provides deterministic random number generation and standard math operations.\n *\n * @module\n */\n\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { KalpMath } from \"@kalphq/sdk\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/**\n * Creates a math primitive that emits events to the execution log.\n *\n * @param log - The execution log for event emission.\n * @param execCtx - Optional execution context for event identity.\n * @returns A {@link KalpMath} instance.\n */\nexport function createMathPrimitive(\n log: ExecutionLog,\n execCtx?: ExecutionContext,\n): KalpMath {\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n // Simple seeded random for deterministic behavior\n let seed = execCtx?.executionId.split(\"\").reduce((a, c) => a + c.charCodeAt(0), 0) ?? Date.now();\n\n return {\n /**\n * Deterministic pseudo-random number generator.\n * Seeded by the execution runId (ULID) for replay consistency.\n */\n random(): number {\n const timestamp = Date.now();\n seed = (seed * 9301 + 49297) % 233280;\n const result = seed / 233280;\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.random\",\n params: undefined,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Round down to nearest integer. */\n floor(x: number): number {\n const result = Math.floor(x);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.floor\",\n params: x,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Round up to nearest integer. */\n ceil(x: number): number {\n const result = Math.ceil(x);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.ceil\",\n params: x,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Round to nearest integer. */\n round(x: number): number {\n const result = Math.round(x);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.round\",\n params: x,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Return smallest of provided values. */\n min(...values: number[]): number {\n const result = Math.min(...values);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.min\",\n params: values,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Return largest of provided values. */\n max(...values: number[]): number {\n const result = Math.max(...values);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.max\",\n params: values,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Return absolute value. */\n abs(x: number): number {\n const result = Math.abs(x);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.abs\",\n params: x,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Return base to the power of exponent. */\n pow(base: number, exponent: number): number {\n const result = Math.pow(base, exponent);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.pow\",\n params: { base, exponent },\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n\n /** Return square root. */\n sqrt(x: number): number {\n const result = Math.sqrt(x);\n const timestamp = Date.now();\n void log.emit({\n type: \"primitive.invoked\",\n name: \"math.sqrt\",\n params: x,\n result,\n ...ids,\n timestamp,\n });\n return result;\n },\n };\n}\n","/**\n * Agent introspection primitive.\n *\n * Provides read-only metadata about the current agent execution.\n *\n * @module\n */\n\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { AgentIntrospection } from \"@kalphq/sdk\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/**\n * Creates an agent introspection primitive.\n *\n * @param log - The execution log for event emission.\n * @param execCtx - Optional execution context for event identity.\n * @param agentConfig - Agent configuration metadata.\n * @returns An {@link AgentIntrospection} instance.\n */\nexport function createAgentMetaPrimitive(\n log: ExecutionLog,\n execCtx?: ExecutionContext,\n agentConfig?: {\n name: string;\n systemPrompt: string;\n metadata?: Record<string, unknown>;\n },\n): AgentIntrospection {\n return {\n agentId: execCtx?.executionId ?? \"unknown\",\n runId: execCtx?.traceId ?? \"unknown\",\n name: agentConfig?.name ?? \"unknown\",\n systemPrompt: agentConfig?.systemPrompt ?? \"\",\n metadata: agentConfig?.metadata,\n };\n}\n","/**\n * Handler context builder for the Kalp v2 Orchestration Reactor.\n *\n * Assembles the {@link HandlerContext} that is passed to every handler function.\n * Each primitive in the context is intercepted — all operations emit structured\n * events to the execution log.\n *\n * The context shape matches the SDK's `HandlerContext` interface exactly,\n * preserving DX:\n *\n * ```ts\n * const { fetch, loop, run, wait } = actions;\n * const { delete: deleteKey, get, put } = storage;\n * const { classify, generate, stream } = ai;\n * ```\n *\n * @module\n */\n\nimport type {\n HandlerContext,\n KalpAuth,\n KalpMemory,\n KalpVault,\n} from \"@kalphq/sdk\";\nimport type { StateStore, SchedulerAdapter } from \"@/adapters/interfaces\";\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { AIProvider } from \"@/engine/primitives/ai\";\nimport type { DispatchAction } from \"@/engine/primitives/actions\";\nimport { createAIPrimitive } from \"@/engine/primitives/ai\";\nimport { createStoragePrimitive } from \"@/engine/primitives/storage\";\nimport { createActionsPrimitive } from \"@/engine/primitives/actions\";\nimport { createMcpPrimitive } from \"@/engine/primitives/mcp\";\nimport { createDatePrimitive } from \"@/engine/primitives/date\";\nimport { createMathPrimitive } from \"@/engine/primitives/math\";\nimport { createAgentMetaPrimitive } from \"@/engine/primitives/agent-meta\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n// ────────────────────────────────────────────────────────────────────────────\n// External providers injected by the host adapter\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * External provider implementations injected by the host adapter.\n * These are NOT part of the reactor core — they come from infrastructure.\n */\nexport interface RuntimeProviders {\n /** AI provider implementation (e.g. OpenAI, Anthropic, Cloudflare AI). */\n ai: AIProvider;\n /** Authentication context for the current request. */\n auth: KalpAuth;\n /** Memory (conversation history) provider. */\n memory: KalpMemory;\n /** Secrets vault provider. */\n vault: KalpVault;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Context builder\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Builds a {@link HandlerContext} with fully intercepted primitives.\n *\n * Every operation on the returned context (ai.generate, storage.put,\n * actions.run, etc.) is intercepted to emit structured events to the\n * execution log. The handler never touches infrastructure directly.\n *\n * @param log - The execution log for event emission.\n * @param stateStore - The state sub-store for KV operations.\n * @param scheduler - The scheduler adapter for deferred execution.\n * @param dispatch - Callback to enqueue handler tasks in the reactor.\n * @param providers - External providers (ai, auth, memory, vault).\n * @param execCtx - Optional execution context for event identity.\n * @param agentConfig - Optional agent configuration for metadata.\n * @returns A complete {@link HandlerContext} matching the SDK interface.\n */\nexport function buildHandlerContext(\n log: ExecutionLog,\n stateStore: StateStore,\n scheduler: SchedulerAdapter,\n dispatch: DispatchAction,\n providers: RuntimeProviders,\n execCtx?: ExecutionContext,\n agentConfig?: {\n name: string;\n systemPrompt: string;\n metadata?: Record<string, unknown>;\n },\n): HandlerContext {\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n return {\n ai: createAIPrimitive(providers.ai, log),\n storage: createStoragePrimitive(stateStore, log, execCtx),\n actions: createActionsPrimitive(log, scheduler, dispatch, execCtx),\n auth: providers.auth,\n memory: providers.memory,\n vault: providers.vault,\n mcp: createMcpPrimitive(log, execCtx),\n agent: createAgentMetaPrimitive(log, execCtx, agentConfig),\n date: createDatePrimitive(log, execCtx),\n math: createMathPrimitive(log, execCtx),\n log: {\n debug: (msg, data) =>\n void log.emit({\n type: \"log\",\n level: \"debug\",\n msg,\n data,\n ...ids,\n timestamp: Date.now(),\n }),\n info: (msg, data) =>\n void log.emit({\n type: \"log\",\n level: \"info\",\n msg,\n data,\n ...ids,\n timestamp: Date.now(),\n }),\n warn: (msg, data) =>\n void log.emit({\n type: \"log\",\n level: \"warn\",\n msg,\n data,\n ...ids,\n timestamp: Date.now(),\n }),\n error: (err, data) => {\n const msg = err instanceof Error ? err.message : String(err);\n const errorData =\n err instanceof Error ? { ...data, stack: err.stack } : data;\n void log.emit({\n type: \"log\",\n level: \"error\",\n msg,\n data: errorData,\n ...ids,\n timestamp: Date.now(),\n });\n },\n },\n };\n}\n","/**\n * Orchestration Reactor — the Kalp v2 event-sourced execution engine.\n *\n * The reactor is **infrastructure-agnostic**. It receives events, processes\n * tasks from an internal queue, and delegates all IO to adapter interfaces.\n * When the queue is empty, control returns to the host adapter (Durable Object,\n * Node process, test harness, etc.) which waits for the next external event.\n *\n * Key invariants:\n * - The reactor never imports Cloudflare, Node, or any platform API.\n * - Every operation emits structured events to the {@link ExecutionLog}.\n * - Handler execution is sandboxed via intercepted primitives.\n * - `actions.run` is an intent + suspend, not a direct call.\n *\n * @module\n */\n\nimport type { IRGraph, IRNodeId } from \"@kalphq/sdk\";\nimport type {\n PersistenceAdapter,\n SchedulerAdapter,\n} from \"@/adapters/interfaces\";\nimport type {\n ExecutionTask,\n RuntimeEvent,\n HandlerModule,\n} from \"@/engine/types\";\nimport type { RuntimeProviders } from \"@/engine/context-builder\";\nimport { ExecutionLog } from \"@/engine/execution-log\";\nimport { buildHandlerContext } from \"@/engine/context-builder\";\n\n/**\n * The Kalp v2 Orchestration Reactor.\n *\n * Processes external events by looking up the corresponding IR entry,\n * executing the handler chain, and emitting structured events for every\n * operation. The reactor is portable — it works in Durable Objects, Node,\n * or any environment that provides the adapter interfaces.\n */\nexport class OrchestrationReactor {\n /** The execution log (single source of truth). */\n public readonly log: ExecutionLog;\n /** The IR graph (structural index only). */\n public readonly ir: IRGraph;\n\n /** Internal task queue. */\n private queue: ExecutionTask[] = [];\n /** Bundled handler modules keyed by moduleRef. */\n private bundles: Map<string, HandlerModule>;\n /** Composite persistence adapter (state, events, idempotency, threads). */\n private persistence: PersistenceAdapter;\n /** Scheduler adapter (alarms). */\n private scheduler: SchedulerAdapter;\n /** External providers (ai, auth, memory, vault). */\n private providers: RuntimeProviders;\n /** Result of the last completed handler. */\n private lastResult: unknown = undefined;\n /** Opaque thread identifier (set by adapter via RuntimeEvent.threadId). */\n private threadId: string = \"\";\n\n /**\n * Creates a new reactor instance.\n *\n * @param ir - The compiled IR graph.\n * @param bundles - Map from moduleRef to bundled handler module.\n * @param persistence - Persistence adapter for state and event log.\n * @param scheduler - Scheduler adapter for deferred wake-ups.\n * @param providers - External providers for ai, auth, memory, vault.\n */\n constructor(\n ir: IRGraph,\n bundles: Map<string, HandlerModule>,\n persistence: PersistenceAdapter,\n scheduler: SchedulerAdapter,\n providers: RuntimeProviders,\n ) {\n this.ir = ir;\n this.bundles = bundles;\n this.persistence = persistence;\n this.scheduler = scheduler;\n this.providers = providers;\n this.log = new ExecutionLog(persistence.events);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Public API (called by host adapter)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Handles an external event by resolving the IR entry and processing\n * the handler chain until the queue is empty.\n *\n * @param event - The external runtime event.\n * @returns The result of the last completed handler.\n * @throws If no entry exists for the event type.\n */\n async handleEvent(event: RuntimeEvent): Promise<unknown> {\n const entryId = this.ir.entries[event.type];\n if (!entryId) {\n throw new Error(`No entry for event: ${event.type}`);\n }\n\n // Set thread identity from adapter (opaque — Core never parses it)\n if (event.threadId) {\n this.threadId = event.threadId;\n }\n\n const traceId = crypto.randomUUID();\n\n await this.log.emit({\n type: \"node.started\",\n nodeId: entryId,\n executionId: \"\",\n traceId,\n threadId: this.threadId,\n timestamp: Date.now(),\n });\n\n this.queue.push({ nodeId: entryId, context: event.payload });\n await this.processUntilIdle();\n\n return this.lastResult;\n }\n\n /**\n * Drains the task queue. Called internally after handleEvent and recursively\n * after actions.run dispatches. When the queue is empty, control returns to\n * the host adapter.\n */\n async processUntilIdle(): Promise<void> {\n while (this.queue.length > 0) {\n const task = this.queue.shift()!;\n await this.processTask(task);\n }\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal task processing\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Processes a single task from the queue.\n *\n * - **Entry nodes**: traverse sequential edges to find the handler.\n * - **Handler nodes**: build context, execute handler, emit events.\n */\n private async processTask(task: ExecutionTask): Promise<void> {\n const node = this.ir.nodes[task.nodeId];\n if (!node) {\n await this.log.emit({\n type: \"error\",\n nodeId: task.nodeId,\n error: `Node \"${task.nodeId}\" not found in IR.`,\n executionId: \"\",\n traceId: \"\",\n threadId: this.threadId,\n timestamp: Date.now(),\n });\n return;\n }\n\n switch (node.kind) {\n case \"entry\": {\n // Entry nodes are pass-through — enqueue successors\n this.enqueueSuccessors(task.nodeId, task.context);\n break;\n }\n\n case \"handler\": {\n const executionId = crypto.randomUUID();\n\n await this.log.emit({\n type: \"node.started\",\n nodeId: node.id,\n executionId,\n traceId: \"\",\n threadId: this.threadId,\n timestamp: Date.now(),\n });\n\n const handlerModule = this.bundles.get(node.moduleRef);\n if (!handlerModule) {\n await this.log.emit({\n type: \"error\",\n nodeId: node.id,\n error: `Handler module \"${node.moduleRef}\" not found in bundles.`,\n executionId,\n traceId: \"\",\n threadId: this.threadId,\n timestamp: Date.now(),\n });\n return;\n }\n\n // Build intercepted context with dispatch callback\n const dispatch = this.createDispatch();\n const ctx = buildHandlerContext(\n this.log,\n this.persistence.state,\n this.scheduler,\n dispatch,\n this.providers,\n { \n executionId, \n traceId: \"\", \n threadId: this.threadId,\n untrackedIOCount: 0,\n untrackedIOByType: { network: 0, timer: 0, fs: 0, unknown: 0 },\n hasUntrustedPlugins: false\n },\n );\n\n // Execute handler in sandboxed context\n try {\n const result = await handlerModule.default(ctx, task.context);\n\n await this.log.emit({\n type: \"node.completed\",\n nodeId: node.id,\n result,\n executionId,\n traceId: \"\",\n threadId: this.threadId,\n timestamp: Date.now(),\n });\n\n this.lastResult = result;\n\n // If this task was dispatched by actions.run, resolve the caller's promise\n if (task.resolve) {\n task.resolve(result);\n }\n\n // Continue to sequential successors\n this.enqueueSuccessors(task.nodeId, {\n ...(task.context as object),\n result,\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n await this.log.emit({\n type: \"error\",\n nodeId: node.id,\n error: message,\n executionId,\n traceId: \"\",\n threadId: this.threadId,\n timestamp: Date.now(),\n });\n\n // Re-throw to let the host adapter handle it\n throw err;\n }\n break;\n }\n }\n }\n\n /**\n * Enqueues all successor nodes connected by outgoing edges from the given node.\n *\n * @param nodeId - The source node ID.\n * @param context - The context to pass to successor tasks.\n */\n private enqueueSuccessors(nodeId: IRNodeId, context: unknown): void {\n const outEdges = this.ir.edges.filter((e) => e.from === nodeId);\n for (const edge of outEdges) {\n this.queue.push({ nodeId: edge.to, context });\n }\n }\n\n /**\n * Creates a dispatch function for actions.run.\n *\n * When a handler calls `actions.run(step, input)`, this function:\n * 1. Looks up the handler node by moduleRef in the IR.\n * 2. Creates a task with a resolve callback.\n * 3. Returns a Promise that resolves when the task completes.\n */\n private createDispatch(): (\n moduleRef: string,\n input: unknown,\n ) => Promise<unknown> {\n return (moduleRef: string, input: unknown): Promise<unknown> => {\n // O(1) lookup via handlerIndex (built by compiler)\n const handlerNodeId = this.ir.handlerIndex[moduleRef] as\n | IRNodeId\n | undefined;\n\n if (!handlerNodeId) {\n return Promise.reject(\n new Error(\n `Cannot dispatch: handler \"${moduleRef}\" not found in IR. ` +\n `Ensure it is statically imported at the top level.`,\n ),\n );\n }\n\n return new Promise<unknown>((resolve) => {\n this.queue.push({\n nodeId: handlerNodeId,\n context: input,\n resolve,\n });\n });\n };\n }\n}\n"],"mappings":";AAsBO,IAAM,eAAN,MAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASxB,YAAoB,YAAwB;AAAxB;AAAA,EAAyB;AAAA;AAAA,EAPrC,SAA2B,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBpC,MAAM,KAAK,OAAsC;AAC/C,SAAK,OAAO,KAAK,KAAK;AACtB,UAAM,KAA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e,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,gBAAM,KAAK,IAAI,KAAK;AAAA,YAClB,MAAM;AAAA,YACN,QAAQ,KAAK;AAAA,YACb,OAAO;AAAA,YACP;AAAA,YACA,SAAS;AAAA,YACT,UAAU,KAAK;AAAA,YACf,WAAW,KAAK,IAAI;AAAA,UACtB,CAAC;AAGD,gBAAM;AAAA,QACR;AACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,kBAAkB,QAAkB,SAAwB;AAClE,UAAM,WAAW,KAAK,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM;AAC9D,eAAW,QAAQ,UAAU;AAC3B,WAAK,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,QAAQ,CAAC;AAAA,IAC9C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,iBAGc;AACpB,WAAO,CAAC,WAAmB,UAAqC;AAE9D,YAAM,gBAAgB,KAAK,GAAG,aAAa,SAAS;AAIpD,UAAI,CAAC,eAAe;AAClB,eAAO,QAAQ;AAAA,UACb,IAAI;AAAA,YACF,6BAA6B,SAAS;AAAA,UAExC;AAAA,QACF;AAAA,MACF;AAEA,aAAO,IAAI,QAAiB,CAAC,YAAY;AACvC,aAAK,MAAM,KAAK;AAAA,UACd,QAAQ;AAAA,UACR,SAAS;AAAA,UACT;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["_target"]}
@@ -0,0 +1,59 @@
1
+ import { IRGraph } from '@kalphq/sdk';
2
+ import { H as HandlerModule, P as PersistenceAdapter, S as SchedulerAdapter, R as RuntimeProviders, O as OrchestrationReactor } from './reactor-Brv_eUBE.js';
3
+
4
+ /**
5
+ * Engine factory — the ONLY way to create a reactor instance.
6
+ *
7
+ * This file is deliberately separate from the barrel (index.ts) to prevent
8
+ * coupling between type consumers and runtime consumers.
9
+ *
10
+ * Import path: `@kalphq/core/factory`
11
+ *
12
+ * This is NOT a composition root. It does NOT create adapters.
13
+ * Platform packages (cloudflare, node, bun) create adapters in their own
14
+ * wiring files and pass them here.
15
+ *
16
+ * @module
17
+ */
18
+
19
+ /**
20
+ * Configuration for creating a new reactor instance.
21
+ *
22
+ * All fields are required. Platform wiring files are responsible for
23
+ * creating the adapter instances and passing them here.
24
+ */
25
+ interface ReactorConfig {
26
+ /** The compiled IR graph for the agent. */
27
+ ir: IRGraph;
28
+ /** Map from moduleRef to bundled handler module. */
29
+ bundles: Map<string, HandlerModule>;
30
+ /** Composite persistence adapter (state, events, idempotency, threads). */
31
+ persistence: PersistenceAdapter;
32
+ /** Scheduler adapter for deferred wake-ups. */
33
+ scheduler: SchedulerAdapter;
34
+ /** External providers for ai, auth, memory, vault. */
35
+ providers: RuntimeProviders;
36
+ }
37
+ /**
38
+ * Creates a new {@link OrchestrationReactor} instance.
39
+ *
40
+ * This is the standard entrypoint for all platform adapters.
41
+ * The factory performs no validation — callers are responsible for
42
+ * ensuring the config is complete and correct.
43
+ *
44
+ * @param config - The reactor configuration.
45
+ * @returns A fully initialized reactor ready to handle events.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * import { createReactor } from "@kalphq/core/factory";
50
+ *
51
+ * const reactor = createReactor({
52
+ * ir, bundles, persistence, scheduler, providers,
53
+ * });
54
+ * await reactor.handleEvent(event);
55
+ * ```
56
+ */
57
+ declare function createReactor(config: ReactorConfig): OrchestrationReactor;
58
+
59
+ export { type ReactorConfig, createReactor };
@@ -0,0 +1,18 @@
1
+ import {
2
+ OrchestrationReactor
3
+ } from "./chunk-G4LOF3MT.js";
4
+
5
+ // src/factory.ts
6
+ function createReactor(config) {
7
+ return new OrchestrationReactor(
8
+ config.ir,
9
+ config.bundles,
10
+ config.persistence,
11
+ config.scheduler,
12
+ config.providers
13
+ );
14
+ }
15
+ export {
16
+ createReactor
17
+ };
18
+ //# sourceMappingURL=factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/factory.ts"],"sourcesContent":["/**\n * Engine factory — the ONLY way to create a reactor instance.\n *\n * This file is deliberately separate from the barrel (index.ts) to prevent\n * coupling between type consumers and runtime consumers.\n *\n * Import path: `@kalphq/core/factory`\n *\n * This is NOT a composition root. It does NOT create adapters.\n * Platform packages (cloudflare, node, bun) create adapters in their own\n * wiring files and pass them here.\n *\n * @module\n */\n\nimport type { IRGraph } from \"@kalphq/sdk\";\nimport { OrchestrationReactor } from \"@/engine/reactor\";\nimport type { HandlerModule } from \"@/engine/types\";\nimport type { PersistenceAdapter, SchedulerAdapter } from \"@/adapters/interfaces\";\nimport type { RuntimeProviders } from \"@/engine/context-builder\";\n\n/**\n * Configuration for creating a new reactor instance.\n *\n * All fields are required. Platform wiring files are responsible for\n * creating the adapter instances and passing them here.\n */\nexport interface ReactorConfig {\n /** The compiled IR graph for the agent. */\n ir: IRGraph;\n /** Map from moduleRef to bundled handler module. */\n bundles: Map<string, HandlerModule>;\n /** Composite persistence adapter (state, events, idempotency, threads). */\n persistence: PersistenceAdapter;\n /** Scheduler adapter for deferred wake-ups. */\n scheduler: SchedulerAdapter;\n /** External providers for ai, auth, memory, vault. */\n providers: RuntimeProviders;\n}\n\n/**\n * Creates a new {@link OrchestrationReactor} instance.\n *\n * This is the standard entrypoint for all platform adapters.\n * The factory performs no validation — callers are responsible for\n * ensuring the config is complete and correct.\n *\n * @param config - The reactor configuration.\n * @returns A fully initialized reactor ready to handle events.\n *\n * @example\n * ```ts\n * import { createReactor } from \"@kalphq/core/factory\";\n *\n * const reactor = createReactor({\n * ir, bundles, persistence, scheduler, providers,\n * });\n * await reactor.handleEvent(event);\n * ```\n */\nexport function createReactor(config: ReactorConfig): OrchestrationReactor {\n return new OrchestrationReactor(\n config.ir,\n config.bundles,\n config.persistence,\n config.scheduler,\n config.providers,\n );\n}\n"],"mappings":";;;;;AA4DO,SAAS,cAAc,QAA6C;AACzE,SAAO,IAAI;AAAA,IACT,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,42 @@
1
+ import { a as StateStore, E as ExecutionLog, b as ExecutionContext } from './reactor-Brv_eUBE.js';
2
+ export { A as AIProvider, C as CrossThreadAdapter, D as DispatchAction, c as EventStore, d as ExecutionEvent, e as ExecutionTask, H as HandlerModule, I as IdempotencyStore, O as OrchestrationReactor, P as PersistenceAdapter, f as RuntimeEvent, R as RuntimeProviders, S as SchedulerAdapter, T as ThreadStore, g as TransportAdapter, U as UntrackedIOSource, h as buildHandlerContext, i as createAIPrimitive, j as createActionsPrimitive } from './reactor-Brv_eUBE.js';
3
+ import { StoragePrimitive } from '@kalphq/sdk';
4
+
5
+ /**
6
+ * Storage primitive — intercepted key-value state with event emission.
7
+ *
8
+ * Every read/write is logged to the execution log. The actual storage
9
+ * is delegated to the {@link StateStore}.
10
+ *
11
+ * @module
12
+ */
13
+
14
+ /**
15
+ * Creates an intercepted storage primitive that emits events for every operation.
16
+ *
17
+ * @param stateStore - The state sub-store for KV operations.
18
+ * @param log - The execution log for event emission.
19
+ * @param execCtx - The current execution context (identity for events).
20
+ * @returns A {@link StoragePrimitive} matching the SDK's storage API.
21
+ */
22
+ declare function createStoragePrimitive(stateStore: StateStore, log: ExecutionLog, execCtx?: ExecutionContext): StoragePrimitive;
23
+
24
+ /**
25
+ * HTTP primitive — intercepted fetch with event emission.
26
+ *
27
+ * Every outbound HTTP request is logged to the execution log.
28
+ * The actual fetch is delegated to the runtime's fetch implementation.
29
+ *
30
+ * @module
31
+ */
32
+
33
+ /**
34
+ * Creates an intercepted fetch function that emits events for every call.
35
+ *
36
+ * @param log - The execution log for event emission.
37
+ * @param execCtx - Optional execution context for event identity.
38
+ * @returns A fetch function matching the standard `fetch` signature.
39
+ */
40
+ declare function createHttpPrimitive(log: ExecutionLog, execCtx?: ExecutionContext): (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
41
+
42
+ export { ExecutionContext, ExecutionLog, StateStore, createHttpPrimitive, createStoragePrimitive };
package/dist/index.js ADDED
@@ -0,0 +1,41 @@
1
+ import {
2
+ ExecutionLog,
3
+ OrchestrationReactor,
4
+ buildHandlerContext,
5
+ createAIPrimitive,
6
+ createActionsPrimitive,
7
+ createStoragePrimitive
8
+ } from "./chunk-G4LOF3MT.js";
9
+
10
+ // src/engine/primitives/http.ts
11
+ function createHttpPrimitive(log, execCtx) {
12
+ const ids = {
13
+ executionId: execCtx?.executionId ?? "",
14
+ traceId: execCtx?.traceId ?? "",
15
+ threadId: execCtx?.threadId ?? ""
16
+ };
17
+ return async (input, init) => {
18
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
19
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
20
+ const response = await globalThis.fetch(input, init);
21
+ await log.emit({
22
+ type: "primitive.invoked",
23
+ name: "http.fetch",
24
+ params: { url, method },
25
+ result: { status: response.status, statusText: response.statusText },
26
+ ...ids,
27
+ timestamp: Date.now()
28
+ });
29
+ return response;
30
+ };
31
+ }
32
+ export {
33
+ ExecutionLog,
34
+ OrchestrationReactor,
35
+ buildHandlerContext,
36
+ createAIPrimitive,
37
+ createActionsPrimitive,
38
+ createHttpPrimitive,
39
+ createStoragePrimitive
40
+ };
41
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/engine/primitives/http.ts"],"sourcesContent":["/**\n * HTTP primitive — intercepted fetch with event emission.\n *\n * Every outbound HTTP request is logged to the execution log.\n * The actual fetch is delegated to the runtime's fetch implementation.\n *\n * @module\n */\n\nimport type { ExecutionLog } from \"@/engine/execution-log\";\nimport type { ExecutionContext } from \"@/engine/types\";\n\n/**\n * Creates an intercepted fetch function that emits events for every call.\n *\n * @param log - The execution log for event emission.\n * @param execCtx - Optional execution context for event identity.\n * @returns A fetch function matching the standard `fetch` signature.\n */\nexport function createHttpPrimitive(\n log: ExecutionLog,\n execCtx?: ExecutionContext,\n): (input: string | URL | Request, init?: RequestInit) => Promise<Response> {\n const ids = {\n executionId: execCtx?.executionId ?? \"\",\n traceId: execCtx?.traceId ?? \"\",\n threadId: execCtx?.threadId ?? \"\",\n };\n\n return async (\n input: string | URL | Request,\n init?: RequestInit,\n ): Promise<Response> => {\n const url =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n const method =\n init?.method ?? (input instanceof Request ? input.method : \"GET\");\n\n const response = await globalThis.fetch(input, init);\n\n await log.emit({\n type: \"primitive.invoked\",\n name: \"http.fetch\",\n params: { url, method },\n result: { status: response.status, statusText: response.statusText },\n ...ids,\n timestamp: Date.now(),\n });\n\n return response;\n };\n}\n"],"mappings":";;;;;;;;;;AAmBO,SAAS,oBACd,KACA,SAC0E;AAC1E,QAAM,MAAM;AAAA,IACV,aAAa,SAAS,eAAe;AAAA,IACrC,SAAS,SAAS,WAAW;AAAA,IAC7B,UAAU,SAAS,YAAY;AAAA,EACjC;AAEA,SAAO,OACL,OACA,SACsB;AACtB,UAAM,MACJ,OAAO,UAAU,WACb,QACA,iBAAiB,MACf,MAAM,OACN,MAAM;AACd,UAAM,SACJ,MAAM,WAAW,iBAAiB,UAAU,MAAM,SAAS;AAE7D,UAAM,WAAW,MAAM,WAAW,MAAM,OAAO,IAAI;AAEnD,UAAM,IAAI,KAAK;AAAA,MACb,MAAM;AAAA,MACN,MAAM;AAAA,MACN,QAAQ,EAAE,KAAK,OAAO;AAAA,MACtB,QAAQ,EAAE,QAAQ,SAAS,QAAQ,YAAY,SAAS,WAAW;AAAA,MACnE,GAAG;AAAA,MACH,WAAW,KAAK,IAAI;AAAA,IACtB,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":[]}